lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
I 'm currently dealing with 2 systems that expose interop via their own RESTful JSON APIs . One is in C # with JSON.NET and one is Java Spring Boot Starter ( Jackson JSON ) . I have full control over both systems.Both systems need to transfer JSON data with reference handling . Whilst both JSON serialization frameworks...
{ `` Resources '' : [ { `` Id '' : 0 , `` Name '' : `` Resource 0 '' } , { `` Id '' : 1 , `` Name '' : `` Resource 1 '' } ] , `` Tasks '' : [ { `` Id '' : 0 , `` Name '' : `` Task 0 '' , `` Resource '' : 0 } , { `` Id '' : 1 , `` Name '' : `` Task 1 '' , `` Resource '' : 1 } , { `` Id '' : 2 , `` Name '' : `` Task 2 ''...
Dealing with JSON interop between Java and C # REST APIs
Java
I developed a breakout alike game with a friend using HTML5 WebSockets and java as backend and recently deployed my game on a Glassfish server that 's running on the 20 $ Digitalocean droplet ( 3GB ram , 2cpu 's ) .When developing the game I worked with IntelliJ and a co-worker with Netbeans , when deploying our WAR fi...
@ ServerEndpoint ( `` /singleplayer '' ) public class SingleplayerSocket { private static final Set < Session > PLAYERS = Collections.synchronizedSet ( new HashSet < Session > ( ) ) ; private Session session ; private Gson gson ; private Game game ; private void sendMessage ( String message ) { try { for ( Session play...
Deploying game to server results in strange behaviour
Java
So I wrote some code and Netbeans suggests convert to try-with-resources on the same line I instantiate sc . This suggestion pops up the moment I put the sc.close ( ) after the while-loop . I do n't quite understand why this close-operation is badly placed .
public static void main ( String [ ] args ) { try { Scanner sc = new Scanner ( new File ( args [ 0 ] ) ) ; while ( sc.hasNext ( ) ) { System.out.println ( sc.nextLine ( ) ) ; } sc.close ( ) ; } catch ( FileNotFoundException e ) { System.out.println ( `` Het bestand kon niet gevonden worden . `` ) ; } catch ( Exception ...
What is wrong with opening and closing a stream like this ?
Java
I have the following ( kotlin ) code : and then of coursebut for the life of me I ca n't figure out how to create a trivial entry in this section : The basic cards appear in the Google Assistant section ( obviously ) .What am I missing in order to create default simple default responses ? If you are thinking `` oh that...
import com.google.cloud.dialogflow.v2beta1 . *val project = `` my-super-agent '' val trainingPhraseBuilder = Intent.TrainingPhrase.Part.newBuilder ( ) trainingPhraseBuilder.text = `` Tell me about the product . `` val trainingPhrasePart = trainingPhraseBuilder.build ( ) println ( trainingPhrasePart ) var i = with ( Int...
How to create a default response using dialogflow.v2beta1
Java
As we already know that the URL and FORM scope variables can be modified using external proxy tools.For example if someone makes a request like this - http : \\website\index.cfm ? a=1 & b=2This way one can add values to URL scope of a .cfm page.Similarly is there any way to add/alter value to request scope in ColdFusio...
< cfset request.uploadFileDir = application.fileDir & `` \upload '' / > < cffile action= '' upload '' accept= '' application/pdf '' destination= '' # REQUEST.uploadFileDir # '' filefield= '' brochure '' nameconflict= '' makeunique '' / >
Can the Request scope variables be tampered/modified using external proxy tools ?
Java
Lets assume i want to iterate over a collection of objects.How does the second example ( without lambdas ) work ? A new object ( Predicate and Consumer ) created every time i call the code , how much can java jit compiler optimalize a lambda expression ? For a better performace should i declare all lambdas as a variabl...
List < String > strmap = ... //Without lambdasstrmap.stream ( ) .filter ( new Predicate < String > ( ) { public boolean test ( String string ) { return string.length == 10 ; } } .forEach ( new Consumer < String > ( ) { public void accept ( String string ) { System.out.println ( `` string `` + string + `` contains exact...
Implementation differences/optimizations between Lambda Expressions and Anonymous Classes
Java
The foo method in following example gives us a warning , while bar not ?
public class X { static class Y { } static class Z extends Y { } Y y = new Y ( ) ; < T extends Y > T foo ( ) { return ( T ) y ; // warning - Unchecked cast from X.Y to T } Z bar ( ) { return ( Z ) y ; // compiles fine } }
Java generics inheritance warning
Java
How can I use Java8 Supplier interface to rewrite this factory method to provide the proper typed instance ? I 've a simple interface that extends Map : Then I have a ThingyFactory class , which contains a list of all of the implementation classnames of Thingy : I 'm pretty sure that I can do this elegantly and w/o the...
public interface Thingy < K , V > extends Map < K , V > { } public final class ThingyFactory { Map < String , Class < Thingy < ? , ? > > > thingyclasses = new ConcurrentHashMap < > ( ) ; ... .. @ SuppressWarnings ( `` unchecked '' ) public < K , V > Thingy < K , V > getInstance ( String classname ) throws ThingyExcepti...
Java8 Supplier interface to provide the proper typed instance
Java
I would like to upload large files in a POST request using Volley . I tried to use a VolleyMultiPartRequest library , but I get java.lang.OutOfMemoryError : All of the libraries like VolleyPlus MultiPartRequest overrides the function public byte [ ] getBody ( ) . This seems to be the problem , because if a large file i...
2020-11-13 19:14:06.636 18802-18802/com.example.myproject E/MainActivity : Tried to start foreground service from background2020-11-13 19:14:09.730 18802-19082/com.example.myproject E/AndroidRuntime : FATAL EXCEPTION : Thread-15 Process : com.example.myproject , PID : 18802 java.lang.OutOfMemoryError : Failed to alloca...
How is it possible to upload large files with Volley ? ( Android )
Java
Basically I need jacoco only instrument the tests part , but is instrumententing the entire pom.xml , and the report came with everything ( Data from “ oracle.jdbc.driver ” , “ com.mysql.jdbc ” … etc . ) I 've been trying for a couple of days with almost everything . But I have not succeeded so farNotice here how jacoc...
[ INFO ] -- - jacoco-maven-plugin:0.8.4 : instrument ( default-instrument ) @ myApp -- - ... [ DEBUG ] ( f ) project = MavenProject : com.firstPackage.tdz : myApp : X.1.0 @ C : \rootFolder\my_app\server\MyApp\pom.xml [ INFO ] -- - maven-compiler-plugin:3.5.1 : testCompile ( default-testCompile ) @ myApp -- - [ DEBUG ] ...
JaCoCo ( Offline Instrumentation ) in < goal > instrument < /goal > analyzes the entire pom.xml . But I need only the tests part
Java
How is it possible for the following line to compile : Provided getInteger ( ) is typed as following
public class POJO < T > { private List < Integer > integer = new ArrayList < Integer > ( ) ; public POJO ( ) { integer.add ( 1 ) ; integer.add ( 2 ) ; } public List < Integer > getInteger ( ) { return integer ; } public static void main ( String [ ] args ) { POJO pojo = new POJO ( ) ; List < String > integer = pojo.get...
Java compiler ignores type safety
Java
I have a list of EmployeeI want to get Map < Employee , List < Employee > > where map key is for each Department 's max salary employee and value is all employee of that department.I am trying to groupingBy but it gives all employee with Department map . How to get all max salary employee as map key ?
public class Employee { private String name ; private Integer age ; private Double salary ; private Department department ; } List < Employee > employeeList = Arrays.asList ( new Employee ( `` Tom Jones '' , 45 , 12000.00 , Department.MARKETING ) , new Employee ( `` Harry Major '' , 26 , 20000.00 , Department.LEGAL ) ,...
Java stream groupingBy key as max salary employee and value as all employee of department
Java
I 'm new in java , spring and kafkaI have the next code for sending messageMy configuration for producer : I want to send message with my consumer group ( example `` MyConsumerGroup '' ) , but I do n't know how I can to do itthanks for help
kafkaTemplate.send ( topic , message ) ; props.put ( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG , bootstrapServers ) ; props.put ( ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG , IntegerSerializer.class ) ; props.put ( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG , StringSerializer.class ) ; // value to block , after which i...
How to add consumer group to message in java ?
Java
There is a old Java code ( without lambda expressions ) : I 'm trying to rewrite this code to Java 8 Stream API style : PROBLEM : The function isCheckerBlocked ( ) ( which uses in last filter ( ) operation ) takes variable of VectorDirection type ( variable d ) . But after calling map ( ) function I lose access to this...
public List < CheckerPosition > getAttackedCheckersForPoint ( CheckerPosition from , boolean isSecondPlayerOwner , boolean isQueen , VectorDirection ignoredDirection ) { List < VectorDirection > allDirections = VectorDirection.generateAllDirections ( ) ; List < CheckerPosition > result = new ArrayList < CheckerPosition...
How I can rewrite this classic Java-code to Java Stream API code ?
Java
In the past I have seen people using the following 2 idioms to inject dependencies from the same @ Configuration : Is there any practical difference between them ? Does Spring process the whole instantiation method in each call for IDIOM 1 ? ( relevant if method has any side-effect , might be not idempotent ) ? Does ot...
@ Configurationpublic class MyConfiguration { @ Bean public MyBeanDependencyA myBeanDependencyA ( ) { return new MyBeanDependencyA ( ) ; } @ Bean . //IDIOM 1 public MyBeanDependencyB1 myBeanDependencyB1 ( ) { return new MyBeanDependencyB1 ( myBeanDependencyA ( ) ) ; } @ Bean //IDIOM 2 public MyBeanDependencyB2 myBeanDe...
Injecting @ Beans from within a very same @ Configuration class idioms
Java
I ca n't figure out the smallest upper barriers for those twoi thought about log3 ( n ) for the first oneand O ( n ! ) for the second , but i 'm not sure about that , because i have not really understood the subject
public int ex1 ( int n ) { int r = 0 ; for ( int i = 1 ; i < n ; i++ ) { r += n ; n = n / 3 ; } return r ; } public static int ex5 ( int n ) { int r = 1 ; for ( int i = 0 ; i < n ; i ++ ) { r += ex5 ( n - 1 ) ; } return r ; }
What is the big o notation of following
Java
I think example of volatile in Java specification is a little wrong.In 8.3.1.4. volatile Fields , it says ... then method two could occasionally print a value for j that is greater than the value of i , because the example includes no synchronization and , under the rules explained in§17.4 , the shared values of i and ...
class Test { static int i = 0 , j = 0 ; static void one ( ) { i++ ; j++ ; } static void two ( ) { System.out.println ( `` i= '' + i + `` j= '' + j ) ; } } read iread j read ii++j++read j
how to understand volatile example in Java Language Specification ?
Java
I 've come across something I find odd in Java and have n't been able to find much information on it . Consider the following code : The compiler shows an error on the getMap ( ) method : But the same error is not present for the getList ( ) method , yet I would expect either both to work or both to fail . In both case...
public class TestClass { private static abstract class AbstractClass { abstract List < ? extends Object > getList ( ) ; abstract Map < Long , List < ? extends Object > > getMap ( ) ; } private static final class ConcreteClass extends AbstractClass { @ Override List < String > getList ( ) { return null ; } @ Override Ma...
Generics and Abstract Methods
Java
Is this good OO Design assuming you want every inheriting class to be a infinite Thread ? Any better/more elegant way of doing similar thing ?
public abstract class Base implements Runnable { protected abstract void doSomething ( ) ; public void run ( ) { while ( true ) { Thread.sleep ( 1000 ) ; doSomething ( ) ; } } }
Is this acceptable OO Design
Java
Obtaining an intersection of two streams , or finding whether their intersection is empty or not is generally not possible in Java , since streams can only be used once , and the generic solution has a complexity.If we do n't know anything about the nature of the underlying supplier , we can get away with at most one s...
< T > boolean intersects ( final Stream < T > c1 , final Collection < T > c2 ) { return c1.filter ( c2 : :contains ) .findAny ( ) .isPresent ( ) ; }
Finding whether stream intersection is non-empty
Java
I have a class that I want to test . It looks similar to this : Class Dependency1 is complex and I would like to mock it out when writing a unit test for methodUnderTest ( ) .How do I do that ?
public class ClassUnderTest { private Dependency1 dep1 ; private Dependency1 getDependency1 ( ) { if ( dep1 == null ) dep1 = new Dependency1 ( ) ; return dep1 ; } public void methodUnderTest ( ) { ... . do something getDependency1 ( ) .InvokeSomething ( .. ) ; } }
How to mock private getters ?
Java
I have a java interface like thisplease note the < V extends T > type parameter of the method.Then I have a class MyFoo implements MyInterfaceSo when I now have a class like this : Then I want to take MyFoo to set Other in a Bar instance : This works perfectly . Type can be determined by java generics . No additional c...
public interface MyInterface < T > { public < V extends T > V get ( String key , Bundle bundle ) ; } class MyFoo implements MyInterface < Object > { // Object because can be any type @ Override public < V > V get ( String key , Bundle bundle ) { return new Other ( ) ; } } class Bar { public Other other ; public Other s...
Bounded Type Parameters casting issue
Java
I want to know if the below code is violating open closed principle . Animal is a parent class of Dog , however Animal has jackson annotations that help ObjectMapper ( de ) serialize the classes . Anyone who extends Animal will have to edit only annotations present on Animal to make sure ( de ) serialization works as i...
@ JsonTypeInfo ( use = JsonTypeInfo.Id.NAME , include = JsonTypeInfo.As.PROPERTY , property = `` type '' ) @ JsonSubTypes ( { // all subclasses @ Type ( value = Dog.class , name = `` dog '' ) } ) public abstract class Animal { // fields , constructors , getters and setters } public class Dog extends Animal { }
Does this code violate open-closed principle ?
Java
I know this question is basic but I am looking for a less-clumsy approach to the following if statement : I should also note that sOne.Contains ( ) refers to the following code ... It should also be noted that those five chars will never be changed .
if ( ( sOne.Contains ( '* ' ) ) || ( sOne.Contains ( '/ ' ) ) || ( sOne.Contains ( '- ' ) ) || ( sOne.Contains ( '+ ' ) ) || ( sOne.Contains ( ' % ' ) ) ) { public boolean Contains ( char key ) { // Checks stack for key boolean retval = arrs.contains ( key ) ; return retval ; }
In Java , is there a cleaner approach to an if statement with a slew of || 's
Java
BackgroundI am exposing the following interface as part of an API : The client passes me models of `` pastures '' as objects implementing this interface . Each object represents one pasture.On my side of the API , I keep track of `` visits '' to these objects at various times , then invoke pasture.yield ( time , lastVi...
public interface Pasture { /** * @ param t The time of the visit ( as measured from optimization starting point ) . * @ param tLast The time of the preceding visit ( as measured from optimization starting point ) . * @ return The expected reward that will be reaped by visiting under the given conditions . */ double yie...
Can an interface somehow prevent lambda expression implementations ?
Java
I have a resource called Pricing which i want to retrieve . An Offer can have pricing and a Promo can have Pricing resource and there is another entity Customer with which Pricing can be mapped . I want to retrieve Pricing based on either one of OfferId/PromoId/CustomerId.To design the URLs for this , i 'm running into...
/pricing ? OfferId=234 & PromoId=345 & CustomerId=543234 /pricing/offer ? id=234/pricing/promo ? id=345/pricing/customer ? id=543234
url design for RESTful services
Java
I am a noob to regex.I have string like : -andi have to extract all patterns matched with this type $ { ... . } Like : - for given str result should be further if it finds any duplicates then gives only one . for ex : -result should be : - onlythis is my answer : -but this one not giving the correct result.it gives onl...
String str = `` sbs 01.00 sip $ { dreamworks.values } print $ { fwVer } to used $ { lang } en given $ { model } in $ { region } '' ; $ { dreamworks.values } $ { fwVer } $ { lang } $ { model } $ { region } String feed = `` sip $ { dreamworks.values } print $ { fwVer } to $ { fwVer } used $ { lang } en $ { lang } given $...
Regex in java to find pattern like $ { ... } from given string
Java
In my project I need to process objects in different threads . To manipulate stream 's behaviour I create new observables to change their observeOn ( ) this way : But I think in RxJava there is much more beautiful and efficient way to process one response in different threads . I tried to google it , but I did n't find...
apiService.getObjects ( token ) // Retrofit .compose ( bindToLifecycle ( ) ) .subscribeOn ( Schedulers.io ( ) ) .observeOn ( AndroidSchedulers.mainThread ( ) ) .doOnNext ( o - > { // process in Main Thread } ) .map ( Observable : :just ) // create new one , to change thread for it .observeOn ( Schedulers.io ( ) ) .subs...
Efficient way to manipulate threads RxJava
Java
How to get all elements of a list by instance ? I have a list that can have any class implementation of an interface Foo : I want to use the java8 stream api to provide a utility method for extracting all elements of a specific class type : using : Result : It works , but I have to add @ SuppressWarnings due to the unc...
interface Foo ; class Bar implements Foo ; public static < T extends Foo > List < T > getFromList ( List < Foo > list , Class < T > type ) { return ( List < T > ) list.stream ( ) .filter ( entry - > type.isInstance ( entry ) ) .collect ( Collectors.toList ( ) ) ; } List < Foo > list ; List < Bar > bars = Util.getFromLi...
How to get all elements of a list by instance ?
Java
I want to understand why the following code throws Null pointer exception .
import java.util.List ; public class Test { public static void main ( String [ ] args ) { List < String > names = null ; System.out.println ( `` Result is : `` + names == null ? null : names.size ( ) ) ; } }
Operator precedence - Arithmetic and Conditional operators
Java
I 'm trying to get as much performance as possible from some internal method.The Java code is : In my profiler I saw there is 1 % CPU spend in java.util.Objects.requireNonNull , but I do n't even call that . When inspecting the bytecode , I saw this : So the compiler generates this ( useless ? ) check . I work on primi...
List < DirectoryTaxonomyWriter > writers = Lists.newArrayList ( ) ; private final int taxos = 4 ; [ ... ] @ Overridepublic int getParent ( final int globalOrdinal ) throws IOException { final int bin = globalOrdinal % this.taxos ; final int ordinalInBin = globalOrdinal / this.taxos ; return this.writers.get ( bin ) .ge...
Remainder operator on int causes java.util.Objects.requireNonNull ?
Java
I was looking through code in Guava https : //github.com/google/guava and I see a lot of cool optimizations.I was wondering if using & over & & is an optimization and if it is , why is it ? Could it be a style choice ? We are squaring an int b in the IntMath.checkedPow function . We want to check that b * b does not ov...
checkNoOverflow ( -FLOOR_SQRT_MAX_INT < = b & b < = FLOOR_SQRT_MAX_INT ) ; b *= b ; public static boolean and ( boolean a , boolean b ) { return a & & b ; } public static boolean andBit ( boolean a , boolean b ) { return a & b ; } // access flags 0x9 public static and ( ZZ ) Z L0 LINENUMBER 8 L0 ILOAD 0 IFEQ L1 ILOAD 1...
Why was & used over & & in java when comparing two bools ?
Java
My understanding is that you can not reference a variable before it has been declared , and that all code ( including instance initializers ) that is within the body of a class , but outside of any method , is executed in order before constructor when the object is created ( the exception being static variables and ini...
public class WhyIsThisOk { { a = 5 ; } // why is this ok ? ? ? int a = 10 ; public WhyIsThisOk ( ) { } public static void main ( String [ ] args ) { WhyIsThisOk why = new WhyIsThisOk ( ) ; System.out.println ( why.a ) ; // 10 } }
Why can my instance initializer block reference a field before it is declared ?
Java
I am using Java 8 , after following documentation : How to Use Tables - Using an Editor to Validate User-Entered TextI 'd like to setup a specialized formatter when editing a column in my JTable . This column contains java.time.LocalTime instances.Where LocalTimeEditor is defined by ( tentatively ) : But this leads to ...
JTable table ; ... table.setDefaultEditor ( LocalTime.class , new LocalTimeEditor ( ) ) ; public class LocalTimeEditor extends DefaultCellEditor { JFormattedTextField ftf ; public LocalTimeEditor ( ) { super ( new JFormattedTextField ( ) ) ; ftf = ( JFormattedTextField ) getComponent ( ) ; // Set up the editor for the ...
JTable define an editor for LocalTime type
Java
I am working out with Java Puzzlers second puzzle.You will think the answer is 0.9 . But it is not . If you workout this you will get 0.8999999 . The solution given isNow it will print 0.9 . I understood why it prints 0.89999 . But whileI am curiously debugging BigDecimal class , I found there are many constant values ...
public class Change { public static void main ( String args [ ] ) { System.out.println ( 2.00 - 1.10 ) ; } } System.out.println ( new BigDecimal ( `` 2.00 '' ) .subtract ( new BigDecimal ( `` 1.10 '' ) ) ) ; while ( len > 10 & & Character.digit ( c , 10 ) == 0 ) { offset++ ; c = in [ offset ] ; len -- ; } public static...
BigDecimal Class in Java - Reason behind Constant values
Java
I have two functions . One works fine , while the other does n't compile . Not able to spot the cause . Can you please help me here ? This works fine This one does n't compile
static byte method1 ( ) { final short sh1 = 2 ; return sh1 ; } static byte method2 ( final short sh2 ) { return sh2 ; }
Return values in a static function - Java
Java
I am unable to grasp the idea of either addition operator or short data-type.It 's said that ; which will not compile because addition operator always cast short , chart , byte data-types to int and I understand this . But this ; works totally fine . So , if addition operator auto converts short to int and then apply t...
short a = 1 ; short b = 2 ; short c = a + b ; short c = 1 + 2 ;
Java + Operator
Java
I want to change the value of a field in a Stream . I am trying to change it in a .map but I got a compilation error Syntax error on token ( s ) , misplaced construct ( s ) the stream :
user.getMenuAlertNotifications ( ) .parallelStream ( ) .filter ( not - > not.getUser ( ) .getId ( ) ==userId & & notificationList.getIds ( ) .contains ( not.getId ( ) ) ) .map ( not - > not.setRead ( Boolean.TRUE ) - > not ) .forEach ( not - > menuService.save ( not ) ) ;
Changing the value of a field in a map function of Stream
Java
I 'm trying to obtain the lowest level of byte counting possible with URLConnection . I already went to count the data passing by the two streams , with CountingInputStream and CountingOutputStream from the Apache Commons IO but the byte counting I get there is equal to the body size I 'm sending + response body size I...
public static long getCurrentRx ( Context context ) { int uid = context.getApplicationInfo ( ) .uid ; return TrafficStats.getUidRxBytes ( uid ) ; } public static long getCurrentTx ( Context context ) { int uid = context.getApplicationInfo ( ) .uid ; return TrafficStats.getUidTxBytes ( uid ) ; } public static long getCu...
URLConnection low level byte counting
Java
ProblemWhen I am starting the PetUI main class from the actionPerformed function in my StartGUI class , the PetUI dialog does not start with anything on the screen but it seems to be running in the background . For debugging purposes , the pet will die within a few seconds . Once the pet dies , the screen updates and y...
package vps.main.gui ; import vps.main.Pet ; import vps.util.io ; import javax.swing . * ; import java.awt . * ; import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; /** * Created by XXXX on 3/23/2016 . */public class PetUI extends JFrame implements ActionListener { public static Pet mainPet = new...
GUI not loading but seems to be running
Java
If I understand signal right this is an asynchronous message between two or more objects . For example in UML we have a signal classifier : Then we can write this signal in Java as following : However , in Java we have a CLASS , but in UML we have a SIGNAL classifier , but not a CLASS classifier ( Update : I mean in th...
-- -- -- -- -- -- -- -- -| < < signal > > || SomeEvent | -- -- -- -- -- -- -- -- -|id : Int ||text : String | -- -- -- -- -- -- -- -- -|getId ( ) ||getText ( ) | -- -- -- -- -- -- -- -- - class SomeEvent { private final int id ; private final String text ; //+constructor + getters }
UML : signal classifier vs class classifier
Java
Let 's say I have the following code : And let 's also say shouldDoSomething ( ) is a method I do n't have source code for . Is there any way I can force the code into the if block even if shouldDoSomething ( ) returns false ? And vice versa ? I know in C++ in Visual Studio I could just change the value in the EAX regi...
if ( shouldDoSomething ( ) ) { // amazing code here }
Is it possible to modify the response of a function in Eclipse while debugging ?
Java
I am configuring Coveralls using a GitHub Action.I searched but I can not find how I should be able to generate the ./coverage/lcov.info file.When the action runs , since I do n't have such file , I get : I tried running test with Coverage via IntelliJ but the only export I can produce is in HTML format.How can I gener...
Using lcov file : ./coverage/lcov.info Error : Lcov file not found . # For most projects , this workflow file will not need changing ; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed , # or to provide custom queries or build logic.name : `...
Coveralls GitHub Action - Error : Lcov file not found
Java
I 'm currently studying Java and , as a part of my learning , I attempted to intentionally induce a stack overflow to see what it would do.I did some boundary testing and , interestingly , I discovered that if I execute the following code it will only sporadically cause an error . Sometimes it will run without any prob...
public class SO { public static void main ( String [ ] args ) { ohno ( 0 ) ; } public static void ohno ( int a ) { System.out.println ( a ) ; if ( a ! = 11413 ) ohno ( a+1 ) ; } }
Why does n't a stack overflow always occur ?
Java
I know that the System.in of the System class is an instance of a concrete subclass of InputStream because the read ( ) method of InputStream is abstract and System.in must override this method.According to the document about the read ( ) method of InputStream : public abstract int read ( ) throws IOException Reads the...
import java.io . * ; class SystemInTest { public static void main ( String [ ] args ) throws IOException { InputStream in = System.in ; //InputStream in = new FileInputStream ( `` h.txt '' ) ; int ch = 0 ; while ( ( ch = in.read ( ) ) ! = -1 ) { System.out.println ( ch ) ; } } } 97989910
confusion about the behavior of the read ( ) method of System.in in Java
Java
I am working on a Java web project using Jackson for Json serialization and deserializtion.I am using Jetty as a web serverI am trying to deserialize a generated class at build time : I am using AbstractSamplePayload to add propeties to the generated class , AbstractSamplePayload : So with the @ JsonAnySetter and handl...
/** *Generated class at compile time**/ @ JsonInclude ( NON_NULL ) public class SamplePayloadContent extends AbstractSamplePayload { @ NotNull @ JsonProperty ( value = `` sampleProperty '' , required = true ) private String sampleProperty ; ... } public abstract class AbstractSamplePayload implements Serializable { pro...
Unstable behavior with Jackson Json and @ JsonAnySetter
Java
I am upgrading java version from 6 to 7 for my project . It used to compile fine with java 6.This is snapshot from a de-compiled class . Types were not erased by compiler and code compiles fine.But after java upgrade to version 7 , this code has started giving compilation error error : name clash : provideVptchProv ( N...
@ ProvidesVptchProvIntf provideVptchProv ( NeVersion neVersion , Provider < ClVptchProv > classicProvider , Provider < RsVptchProv > rsProvider ) { return ( VptchProvIntf ) provideForPlatform ( neVersion , classicProvider , rsProvider ) ; } @ ProvidesStsnVcnProvIntf provideVptchProv ( NeVersion neVersion , Provider < C...
Google Guice - have the same erasure - compilation error after java upgrade from v6 to v7
Java
I have a situation where I have have a lot of model classes ( ~1000 ) which implement any number of 5 interfaces . So I have classes which implement one and others which implement four or five.This means I can have any permutation of those five interfaces . In the classical model , I would have to implement 32-5 = 27 `...
public void addChild ( T parent , T child ) { T newRev = parent.createNewRevision ( ) ; newRev.addChild ( foo ) ; ... possibly more method calls to other interfaces ... } public < T extends IRevisionable & ITree > void addChild ( T parent , T child ) { ... }
What is the best way to work with many interfaces ?
Java
I was digging through some of the Java Math functions native C source code . Especially tanh ( ) , as I was curious to see how they implemented that one.However , what I found surprised me : As the comment indicates , the taylor series of tanh ( x ) around 0 , starts with : Then why does it look like they implemented i...
double tanh ( double x ) { ... if ( ix < 0x40360000 ) { /* |x| < 22 */ if ( ix < 0x3c800000 ) /* |x| < 2**-55 */ return x* ( one+x ) ; /* tanh ( small ) = small */ ... } tanh ( x ) = x - x^3/3 + ... tanh ( x ) = x * ( 1 + x ) = x + x^2
Java/C : OpenJDK native tanh ( ) implementation wrong ?
Java
Given the following setup : Why wo n't the compiler accept the list as parameter to accept ( ) ? List extends Iterable via Collection so that is n't the problem.On the other hand , the compiler tells me thatincompatible types : java.util.List < enums.Constants > can not be converted to java.lang.Iterable < enums.MyInte...
public class TestType { public static void main ( String [ ] args ) { List < Constants > list = new ArrayList < > ( ) ; accept ( list ) ; //Does not compile } static void accept ( Iterable < MyInterface > values ) { for ( MyInterface value : values ) { value.doStuff ( ) ; } } } interface MyInterface < T > { T doStuff (...
Java generics Enum subtyping Interface
Java
When I calculated this problem on paper I found A=200 B=20 , but when I write it down to eclipse it shows A=100 B=20Can you explain the solution like solving on the paper ? I tried to solve in Eclipse and by myself.How do we solve it ?
public static void main ( String [ ] args ) { int A=5 ; int B=2 ; A *= B*= A *= B ; System.out.println ( A ) ; System.out.println ( B ) ; }
How is A *= B *= A *= B evaluated ?
Java
I have the following 2 classes : And when I run Cat , I got the following results : I can understand 1,2,3 and 5 , but why # 4 is not : `` Cat : static -- 4 `` ? My understanding would be like this : myAnimal=myCat means `` myAnimal '' is now exactly the same as `` myCat '' , so anywhere `` myAnimal '' apears , you can...
class Animal { public static void staticMethod ( int i ) { System.out.println ( `` Animal : static -- `` + i ) ; } public void instanceMethod ( int i ) { System.out.println ( `` Animal : instance -- `` + i ) ; } } class Cat extends Animal { public static void staticMethod ( int i ) { System.out.println ( `` Cat : stati...
What does Java object assignment mean ?
Java
I 'm trying to replace the common switch for arithmetical operations by BinaryOperator functional interface . The base method is : As I understand it 's nesessary to write something like : But I do n't understand how to avoid switch in computeExpression that would be the same as computeOne .
private static int computeOne ( int res , String operand , String operation ) { int number = Integer.parseInt ( operand ) ; switch ( operation ) { case `` + '' : res += number ; break ; case `` - '' : res -= number ; break ; case `` * '' : res *= number ; break ; case `` / '' : res = ( number ! = 0 ? res / number : Int...
Replacing switch by BinaryOperator
Java
I have an app running on Google App Engine which is the backend for an Android app . It 's basically a bridge between the Android app and a MySQL database running on my own server.The log for the App Engine app is filled with this warning about an exception caught while disconnecting . The exception message is java.net...
10:41:05.477 [ s~appname/1.389899266979631246 ] . < stderr > : Mon Jan 11 18:41:05 UTC 2016 WARN : Caught while disconnecting ... EXCEPTION STACK TRACE : ** BEGIN NESTED EXCEPTION ** java.net.SocketExceptionMESSAGE : Invalid request : Invalid how.STACKTRACE : java.net.SocketException : Invalid request : Invalid how . a...
java.net.SocketException : Invalid request : Invalid how
Java
I am developing a plugin for an RCP application.Within the plugin.xml , I need to register certain classes at a given extension point.One of these classes is an anonymous ( ? ) class defined like this : } Is there any way to reference AnotherClass < ClassOne > within the plugin.xml ? I already tried something like de.m...
package de.me.mypackage ; import org.something.AnotherClass ; public class ClassOne { ... public static AnotherClass < ClassOne > getThat ( ) { return new AnotherClass < ClassOne > ( ) { ... } ; }
Reference an anonymous class ?
Java
Java 's inner classes can be static or non-static . Non-static inner classes are tied to an instance of the enclosing class.Annotations are a type of Java interface , and like any other class , they can be defined inside a class . Similarly , they can be declared static or non-static . What is the difference between th...
public class AnnotationContainer { public static @ interface StaticAnnotation { } public @ interface NonstaticAnnotation { } }
What 's is the difference between a static and non-static annotation ?
Java
I have the following code : where factor.getAttributes ( ) returns List < Attribute > . Apparently , there is only one initial call to factor.getAttributes ( ) and then the traversal starts . However , I do n't understand why there is only one call . If I were to include a function call in the header of a regular for (...
for ( Attribute thisAttribute : factor.getAttributes ( ) ) { // blabla }
Java advanced loop : what is ( not ) evaluated in the loop 's header ?
Java
I have a list of data in a txt file like thismy assignment is to sort these data by each criterion ex ) sort by date , latitude and longtitudei tried bubble sort like this this works but takes too much timetheres 40000 data in the txt fileis there any alternative way to sort these data ?
Date , Lat , Lon , Depth , Mag20000101,34.6920 , -116.3550,12.30,1.2120000101,34.4420 , -116.2280,7.32,1.0120000101,37.4172 , -121.7667,5.88,1.1420000101 , -41.1300,174.7600,27.00,1.9020000101,37.6392 , -119.0482,2.40,1.0320000101,32.1790 , -115.0730,6.00,2.4420000101,59.7753 , -152.2192,86.34,1.4820000101,34.5230 , -1...
Sort Java String array by multiple numbers
Java
Sample 1 : Output is : Sample 2 : Output : I just do n't understand why making saySomething non-static causes the second call to saySomething invoke the Cow version instead of the Animal version . My understanding was that Gurrr ! Moo ! Moo ! would be the output in either case .
class Animal { public static void saySomething ( ) { System.out.print ( `` Gurrr ! `` ) ; } } class Cow extends Animal { public static void saySomething ( ) { System.out.print ( `` Moo ! `` ) ; } public static void main ( String [ ] args ) { Animal [ ] animals = { new Animal ( ) , new Cow ( ) } ; for ( Animal a : anima...
Why do these two code samples produce different outputs ?
Java
I want to get 4 parts of this string The 4 parts I need are `` 10 trillion '' `` 896 billion '' `` 45 million '' and `` 56873 '' .What I did was to remove all spaces and then substring it , but I get confused about the indexes.I saw many questions but could not understand my problem.I could n't run because I did n't kn...
String string = `` 10 trillion 896 billion 45 million 56873 '' ; Sorry I do n't have any code
How to substring this String
Java
My project is finally complete , but my only problem is that my teacher does not accept `` breaks '' in our code . Can someone help me resolve this issue , I have been working on it for days and I just ca n't seem to get the program to work without using them . The breaks are located in my DropYellowDisk and DropRedDis...
private static void DropYellowDisk ( String [ ] [ ] grid ) { int number = 0 ; Scanner keyboard = new Scanner ( System.in ) ; System.out.println ( `` Drop a yellow disk at column ( 1–7 ) : `` ) ; int c = 2*keyboard.nextInt ( ) +1 ; for ( int i=6 ; i > =0 ; i -- ) { if ( grid [ i ] [ c ] == `` `` ) { grid [ i ] [ c ] = `...
Breaking out of a nested for loop without using break
Java
I just started using jshell in intellij idea community version . When I write the below code in jshell , it works.However the same code does n't work in intellij . It says `` Expression expected '' . It executes fine but shows that there is error with List < String > . The problem is `` auto-complete '' does n't work ....
List < String > list = List.of ( `` a '' , `` b '' , `` c '' ) ; System.out.println ( list ) ;
Jshell in intellij does n't allow generic types
Java
I have a mathematical formula in my program that takes in two values , both between 0 and 1 , and does a lot of work to find an answer . I also want to be able to do the inverse , i.e . I want to know what input values will produce a certain output . I can not do this analytically , as the same answer can be produced f...
for ( double i = 0 ; i < = 1 ; i += 0.0001 ) for ( double j = 0 ; j < = 1 ; j+= 0.0001 ) answer = formula ( i , j ) ; //do the math if ( Math.abs ( answer - answerWanted ) < 0.001 ) //close match found
Pre-computing large table of values
Java
Recently , I observed an unexpected behavior of accessing priavte fields in Java . Consider the following example , which illustrates the behavior : Why I am allowed to access the private field of another object of class A within the foo method ( 2nd case ) ?
public class A { private int i ; < -- private field ! public A ( int i ) { this.i = i ; } public void foo ( A a ) { System.out.println ( this.i ) ; // 1 . Accessing the own private field : good System.out.println ( a.i ) ; // 2 . Accessing private field of another object ! } public static void main ( String [ ] args ) ...
Why is it allowed to access a private field of another object ?
Java
We tried just for fun to create a for loop like below . We assumed that the number we get would be very high but we got 0 . Why is it 0 and not something big ? We even tried it with a long because we thought it might be bigger than a int.Thanks in advance .
private static void calculate ( ) { int currentSolution = 1 ; for ( int i = 1 ; i < 100 ; i++ ) { currentSolution *= i ; } System.out.println ( currentSolution ) ; }
How does index*int in a for loop end up with zero as result ?
Java
Suppose I have this code : Running the code : would yield 2 for getAddressMethodCount variable ; why is this so ?
public interface Address { public int getNo ( ) ; } public interface User < T extends Address > { public String getUsername ( ) ; public T getAddress ( ) ; } public class AddressImpl implements Address { private int no ; public int getNo ( ) { return no ; } public void setNo ( int no ) { this.no = no ; } } public class...
Why does reflection return two methods , when there is only one implementation ?
Java
I can compile above method . Is there any explanation about the allowed multiple `` + '' operator ?
public static void main ( String [ ] args ) { int x = 1 + + + + + + + + + 2 ; System.out.println ( x ) ; }
Explanation about a Java statement
Java
I was wondering why the following bit of code does not work : If the type is < ? super String > it can contain anything which is super of String ( String included ) not ?
Collection < ? super String > col = new ArrayList < String > ( ) ; col.add ( new Object ( ) ) ; // does not compilecol.add ( `` yo ! `` ) ; // compiles indeed ;
Generics < ? super > wildcard
Java
I am a beginner in java and Apache POI . So right now what i wan na to achieve is I want to loop the array days row by row ( vertical ) under the Days column : Public Holidays Days Date ClassThe error that I am getting is that : The method setCellValue ( double ) in the type Cell is not applicable for the arguments ( S...
public static void main ( String [ ] args ) { XSSFWorkbook workbook = new XSSFWorkbook ( ) ; XSSFSheet sheet = workbook.createSheet ( ) ; String [ ] days = { `` SU '' , `` MO '' , `` TU '' , `` WED '' , `` TH '' , `` FR '' , `` SA '' } ; Row row = sheet.createRow ( 0 ) ; row.createCell ( 0 ) .setCellValue ( `` Public H...
loop array data using apache poi
Java
Function abstraction : max method implementationAnd usage ( how it should look like ) But I get this error and do n't understand why it requires ObjectI have read big amount of similar QA but did n't get how to fix this.Thanks .
public abstract class Function < X , Y > { abstract Y apply ( X x ) ; } public static < V extends Comparable < V > > Function < List < V > , V > max ( ) { return new Function < List < V > , V > ( ) { @ Override public V apply ( List < V > list ) { return Collections.max ( list ) ; } } ; } Date result = max ( ) .apply (...
Java generics : Functional-like max ( )
Java
In other words I want to know if changing variable before interrupt is always visible when interrupt is detected inside interrupted thread . E.g.I tried to find answer in Java language specification and in Summary page of the java.util.concurrent package mentioned in Java tutorial but interrupt was not mentioned.I know...
private int sharedVariable ; public static void interruptTest ( ) { Thread someThread = new Thread ( ( ) - > { try { Thread.sleep ( 5000 ) ; } catch ( InterruptedException e ) { // Is it here guaranteed that changes before interrupt are always visible here ? System.out.println ( sharedVariable ) ; } } ) ; someThread.st...
Does calling interrupt ( ) on a thread create happens-before relation with the interrupted thread
Java
I 'm using Hibernate version 4.3.5.Final . The problem here is that Hibernate finds entities of the type Foo where the case of the property address has different a case ( e.g . `` BLAFOO '' ) . However , in my example , ex.ignoreCase ( ) is not called.I only want to find entities which match the exact case . What am i ...
Foo myBean = new Foo ( ) ; myBean.setAddress ( `` blaFoo '' ) ; Example ex = Example.create ( myBean ) ; ex.excludeZeroes ( ) ; //ex.ignoreCase ( ) ; DetachedCriteria crit = DetachedCriteria.forClass ( Foo.class ) .add ( ex ) ; List < MonitoredApp > apps = dao.findByDetachedCriteria ( crit ) ;
Hibernate Example ignores case without calling Example.ignoreCase ( )
Java
I have a nested list of Long . for example : Is there a way using streams to create a new list of items that are present in all the lists :
List < List < Long > > ids = [ [ 1,2,3 ] , [ 1,2,3,4 ] , [ 2,3 ] ] ; List < Long > result = [ 2,3 ] ;
Intersection between nested lists java 8 streams
Java
What would be a good pattern to use here ? I don´t want to return nulls , that just does not feel right.Another thing is , what if I want to return the reason that causes it to null ? If caller knows why it is null , it can do some extra things so I want caller knows it and acts that way
Public CustomerDetails getCustomerDetails ( ) { if ( noCustomer ) { ..log..etc.. return null ; } if ( some other bad weird condition ) { ..log..etc.. return null ; } CustomerDetails details= getCustomerDetailsFromSomewhere ( ) ; if ( details ! =null ) { return details ; } else { ..log..etc.. return null ; } }
A suitable pattern instead of returning nulls
Java
I am making program to campare sorting algorithms.I am using big amount of numbers . I have a performance problem in creating array full of random numbers.Is there any way to make it faster ? Currently I am using : where
int [ ] temp = new int [ length ] ; for ( int i = 0 ; i < temp.length ; i++ ) { temp [ i ] = generator.nextInt ( temp.length * 10 ) ; } generator = new Random ( ) ;
Better performance when generating random array int [ ]
Java
I am currently porting an open source library to be JDK9+ compliant , and it depends on some of the Java EE Modules that have been deprecated in Java 9 and removed in Java 11 : specifically , JAXB , JAX-WS and javax.annotation.I added explicit dependencies to the third party implementations as suggested here : However ...
< dependency > < groupId > com.sun.xml.ws < /groupId > < artifactId > jaxws-ri < /artifactId > < version > 2.3.0.1 < /version > < /dependency > < dependency > < groupId > com.sun.xml.bind < /groupId > < artifactId > jaxb-ri < /artifactId > < version > 2.3.0.1 < /version > < /dependency > < dependency > < groupId > com....
Selectively using third-party implementation for deprecated JavaEE modules
Java
Recently I was refactoring a generic method when I got into generic casting issues I can not explain . Finally I realized I could do without the T type altogether ( just inline it myself ) , but I 'm still curious as to why the convert fail . I created this minimal example to illustrate the issue.Can someone explain me...
public < K , T extends List < K > > void castLists ( List < T > list , K kForBinging ) { Map < Integer , List < T > > map = mapSizeToList ( list ) ; // Type mismatch : can not convert from Map < Integer , List < T > > to Map < Integer , List < List < K > > > // Map < Integer , List < List < K > > > expandedMap = map ; ...
Can not convert generic to expanded nested type
Java
Example : When I execute the program , some times I have the output like below : Sometimes I have output like below : In some other occasions I have output where t1 starts first , and t2 starts before t1 completes all output.I thought output1 makes more sense as “ Threads with higher priority are executed in preference...
class MyThread extends Thread { public MyThread ( String name ) { super ( name ) ; } public void run ( ) { for ( int i=0 ; i < 5 ; i++ ) { System.out.println ( Thread.currentThread ( ) .getName ( ) + '' ( `` +Thread.currentThread ( ) .getPriority ( ) + `` ) '' + '' , loop `` +i ) ; } } } ; public class Demo { public st...
Java Multithreading priority : Why in this example , sometimes t1 occurs before t2 is completed , even if t2 has higher priority ?
Java
Let 's say I have a method like this : The actual specifics of the method is n't really important . However , to call this method we use : My question is , is it possible to write such a method without conventional parameters . Without overloading , and ultimately without Boxing.Ideally invoked by :
static class Example { public static < N extends Number > Number getOddBits ( N type ) { if ( type instanceof Byte ) return ( byte ) 0xAA ; else if ( type instanceof Short ) return ( short ) 0xAAAA ; else if ( type instanceof Integer ) return 0xAAAAAAAA ; else if ( type instanceof Float ) return Float.intBitsToFloat ( ...
Method Generics Without Arguments
Java
Related to this question https : //stackoverflow.com/questions I want to achieve the same in Java with rxJava2 as in haskell How can I implement generalized `` zipn '' and `` unzipn '' in Haskell ? : In haskell I can achieve this with applicative functors : being f : : Int - > Int - > Int - > Int - > Int - > Int - > In...
f < $ > a1 < * > a2 < * > a3 < * > a4 < * > a5 < * > a6 < * > a7 < * > a8 < * > a9 < * > a10 < * > a11 import io.reactivex.annotations.NonNull ; public interface Function11 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , R > { @ NonNull R apply ( @ NonNull T1 var1 , @ NonNull T2 var2 , @ NonNull T3 var3 , @ ...
How can I generalize the arity of rxjava2 Zip function ( from Single/Observable ) to n Optional arguments without lose its types ?
Java
Im currently developing an application that implements apigee , however , i 've come across an issue when trying to update entities . Below is the method i 'm currently using . However I 'm getting the following error : '' Error PUT to 'https : //api.usergrid.com/ORGNAME/APPNAME/user/USERID '' followed by : `` No authe...
Map < String , Object > updatedEntity = new HashMap < String , Object > ( ) ; ArrayList < Map < String , Object > > subPropertyArray = new ArrayList < Map < String , Object > > ( ) ; Map < String , Object > subProperty = new HashMap < String , Object > ( ) ; subProperty.put ( `` age '' , `` '' ) ; subProperty.put ( `` ...
Error when updating APIGEE Entities
Java
If you declare an instance of a generic class as a raw type in Java , does the compiler assume a parametrized type of Object for all class member methods ? Does this extend even to those methods which return some form ( e.g . a Collection ) of a concrete parametrized type ? I erroneously declared an instance of a gener...
import java.util . * ; public class Main { public static void main ( String [ ] args ) { final Test < String > t1 = new Test < String > ( ) ; final Test t2 = new Test < String > ( ) ; for ( final Integer i : t1.getInts ( ) ) { System.out.println ( i ) ; } for ( final Integer i : t2.getInts ( ) ) { // < -- compile-time ...
Java - Behavior of Class Members of Generic Classes
Java
I know , it 's a very basic topic , so if it is a duplicate question , please provide a reference.Say , there is a following code : It outputs : 42,42But if we change the order of the appearance of the variables : It outputs : 42,0I understand that in the second case the situation can be described as something like : `...
public class Point { int x = 42 ; int y = getX ( ) ; int getX ( ) { return x ; } public static void main ( String s [ ] ) { Point p = new Point ( ) ; System.out.println ( p.x + `` , '' + p.y ) ; } } public class Point { int y = getX ( ) ; int x = 42 ; int getX ( ) { return x ; } public static void main ( String s [ ] )...
Order of the initialization in Java
Java
Another example from the Oracle Java SE tutorials . It works fine , but I 'm not sure if/why 'this ' is necessary when creating an instance of the inner class . The result seems to be same regardless of whether I take it out or not . To be clear , I am referring to : InnerEvenIterator iterator = this.new InnerEvenItera...
public class DataStructure { // create an array private final static int SIZE = 15 ; private int [ ] arrayOfInts = new int [ SIZE ] ; public DataStructure ( ) { // fill the array with ascending integer values for ( int i = 0 ; i < SIZE ; i++ ) { arrayOfInts [ i ] = i ; } } public void printEven ( ) { // prints out the ...
Is the keyword 'this ' needed when instantiating a new inner class ?
Java
Consider the following self-contained sample : The code above compiles just fine under the following : javac from the command line.IntelliJ IDEA configured to use the javac compiler.But it fails to compile with the following : EclipseIntelliJ IDEA configured to use the Eclipse compiler.Eclipse fails to compile the line...
package bloopers ; import java.lang.annotation.Annotation ; public final class Blooper5 { interface Converter < T , F > { T convert ( F from ) ; } interface Identifier < T > { } static class ConvertingIdentifier < F , T > implements Identifier < F > { ConvertingIdentifier ( Converter < T , F > converter ) { } } static ...
Eclipse fails where javac and IDEA succeed
Java
Can someone please explain the difference between the following cases and where would we use each one ? Thanks allEdit : Hello all thank for the answers . I maybe I was not clear enough . I am aware that classes B and C can not be declared static unless they are inner classes . I so in your answers please assume that t...
class A { static public void methodA ( ) } static class B { static public void methodB ( ) } static class C { public void methodC ( ) }
when to use these variations of `` static '' in java
Java
We have a mobile app which presents feed to users . The feed REST API is implemented on tomcat , which parallel makes calls to different data sources such as Couchbase , MYSQL to present the content . The simple code is given below : Right now we have around 4-5 parallel tasks per request . But it is expected to grow t...
Future < List < CardDTO > > pnrFuture = null ; Future < List < CardDTO > > newsFuture = null ; ExecutionContext ec = ExecutionContexts.fromExecutorService ( executor ) ; final List < CardDTO > combinedDTOs = new ArrayList < CardDTO > ( ) ; // Array list of futures List < Future < List < CardDTO > > > futures = new Arra...
How to optimize Tomcat for Feed pull
Java
While researching another question , I was surprised to discover that the following Java code compiles without errors : In my JDK6 , var gets initialized to 1.Does the above code have well-defined semantics , or is its behaviour undefined ? If you say it 's well-defined , please quote the relevant parts of the JLS .
public class Clazz { int var = this.var + 1 ; }
Using this.var during var 's initialization
Java
I have a very basic JavaFX application that works flawlessly if the Application class is not the Main class : However , when I merge the two together ( which is the recommended way in most tutorials , including OpenJFX 's official documentation ) , the module system throws an IllegalAccessError ( at least on OpenJDK 11...
import javafx.application.Application ; import javafx.fxml.FXMLLoader ; import javafx.stage.Stage ; public class Main { public static void main ( String [ ] args ) { Application.launch ( App.class , args ) ; } } public class App extends Application { @ Override public void start ( Stage primaryStage ) { FXMLLoader load...
Understanding how the main class affects JPMS
Java
I 'm trying to load images to an array and ca n't figure out the syntax . I 'm used to something like this in C # : That does n't work here . Can anyone help me with this syntax , and any applicable imports I need to make . This is what I have : The library that allows me to use the ImageIO wo n't load .
picture.Image = Image.FromFile ( fileLocation ) ; public class Beards extends ActionBarActivity { Image [ ] beard = new Image [ 20 ] ; String [ ] beardLocation = new String [ 20 ] ; public void fillArrays ( ) { for ( int i = 0 ; i < 20 ; i++ ) { beardLocation [ i ] = `` C : /Users/geoffoverfield01/AndroidStudioProjects...
Android importing images to array
Java
This will not compile : This will compile and work : First and second example are very similar . First uses varargs , second not . Why one works , second not . 7 is primitive , so second method should be called in both cases . Is it normal behaviour ? I found it : Bug reportStack overflow
public class Methods { public static void method ( Integer ... i ) { System.out.print ( `` A '' ) ; } public static void method ( int ... i ) { System.out.print ( `` B '' ) ; } public static void main ( String args [ ] ) { method ( 7 ) ; } } public class Methods { public static void method ( Integer i ) { System.out.pr...
Overloading function using varargs
Java
I want to limit maven to use only private/not public maven repository , do these two settings have the same effect ? 1.Setting mirror in settings.xml2.Setting repository in pom.xmlAgain the requirement is that maven never goes out to public repositories even if some dependencies are not there on the internal repository...
< mirrors > < mirror > < id > my-internal-site < /id > < mirrorOf > * < /mirrorOf > < name > our maven repository < /name > < url > http : //myserver/repository < /url > < /mirror > < /mirrors > < repositories > < repository > < id > my-internal-site < /id > < name > our maven repository < /name > < url > http : //myse...
Are these two settings same in maven ?
Java
I 'm creating a ListPopupWindow like this : I tried to do simple mathto center it horizontally . It worked on my phone but not on others , so I suspect something is wrong about my asumptions . But I also suspect there 's a better way of solving this.How do I simply center something horizontally programatically ? PS : t...
final ListPopupWindow insidelistPopupWindow = new ListPopupWindow ( view.getContext ( ) ) ; insidelistPopupWindow.setContentWidth ( getResources ( ) .getDimensionPixelSize ( R.dimen.popupNewWidth ) ) ; insidelistPopupWindow.setHeight ( getResources ( ) .getDimensionPixelSize ( R.dimen.size300dp ) ) ; insidelistPopupWin...
How to center a ListPopupWindow/Other views on Android horizontally ?
Java
In my Java program , I have the following code : Strangely enough , calling Arrays.sort ( ) from java.util.Arrays causes many items to be removed from the list . When I run the code above , this is the output : I am very , very confused as to what 's going on here . Why are only 11 items printed out ? Is Arrays.sort ( ...
String [ ] states = readFile ( `` States.txt '' ) ; System.out.println ( String.join ( `` `` , states ) ) ; System.out.println ( states.length ) ; Arrays.sort ( states ) ; System.out.println ( String.join ( `` `` , states ) ) ; System.out.println ( states.length ) ; FL GA SC NC VA MD NY NJ DE PA CT RI MA VT NH ME AL TN...
Arrays.sort ( ) removes many items from my array
Java
I have defined list from 0-9 ( Integer ) as below : When I try to remove elements using below code : It should throw ConcurrentModificationException but interestingly it works for some of the elements and gives below output ( threw exception at the end and removed some of the elements ) : But if I have added sorted ( )...
List < Integer > list = IntStream.range ( 0 , 10 ) .boxed ( ) .collect ( Collectors.toCollection ( ArrayList : :new ) ) ; list.stream ( ) .peek ( list : :remove ) .forEach ( System.out : :println ) ; 02468nullnullnullnullnullException in thread `` main '' java.util.ConcurrentModificationException list.stream ( ) .sorte...
Bizarre behavior of list
Java
Question1 : Does it make sense to specifiy the size of the ArrayList . I know how many elements is going to carry in my List , is it good to specify the size before hand or it does not even matter . Question2 : The java.util.ConcurrentModificationException occurs when you manipulate ( add , remove ) a collection while ...
List < String > list = new ArrayList < String > ( 1 ) ; list.add ( `` Hello '' ) ; List < String > newList = new ArrayList < String > ( ) ; newList.add ( `` Hello '' ) ;
Couple of questions on ArrayList
Java
I have the following two classes : I am trying to find out the max pair from a map where objects of these classes are key and value pairs respectively . I also have an com.google.common.collect.Ordering < ValueClass > which uses multiple comparators . I can easily find out the max of values using this ordering , but wh...
class KeyClass { private prop1 ; private prop2 ; hashcode ( ) { //implemented properly } equals ( ) { //implemented properly } } class ValueClass { private prop1 ; private prop2 ; hashcode ( ) { //implemented properly } equals ( ) { //implemented properly } }
Ordering for key value pairs
Java
I am writing software that detects an images outline , thins it to a `` single pixel '' thick , then performs operations on the resulting outline . My hope is to eventually get the following : I have written software that detects the RGBA colors , converts it to HSB , asks for a limit that sets whether a pixel is an ou...
public void thinOutline ( ) { thinned = new boolean [ outline.length ] [ outline [ 0 ] .length ] ; for ( int x = 0 ; x < thinned.length ; x++ ) for ( int y = 0 ; y < thinned [ 0 ] .length ; y++ ) { if ( x > 0 & & x < thinned.length - 1 & & y > 0 & & y < thinned [ 0 ] .length - 1 ) if ( ! thinned [ x + 1 ] [ y ] & & ! t...
Thinning a line
Java
In Java , int a = 10 , b = 10 ; But , in SQL , Why is that ?
if ( a == 10 || b==10 ) { // first condition ( a==10 ) is true , so it wont check further } select * from my table where a = 10 or b = 10 ; -- As per my understanding , It should return data only based on a. -- But it returns both entries .
Why or condition is working differently compare with Java and SQL
Java
I have the following Java generics questionI have the following generic class thay may be sketched as : where ... represents code that is not relevant to the case.For the class MyClass < T > is not as important which exact type T is ( as of now ) but for both : AnotherClass < T > OtherClass < T > is absolutely crucial ...
public class MyClass < T > { AnotherClass < T > another ; OtherClass < T > other ; ... } public interface BaseT { ... } public class T_1 implements BaseT { ... } public class T_2 implements BaseT { ... } public class MyClass < T extends BaseT >
Generic class with two class hierarchies