Multiple thenApply in a completableFuture - completable-future

I have a situation where I want to execute some methods in different threads but want to pass the result of one thread to another. I have following methods in my class.
public static int addition(int a, int b){
System.out.println((a+b));
return (a+b);
}
public static int subtract(int a, int b){
System.out.println((a-b));
return (a-b);
}
public static int multiply(int a, int b){
System.out.println((a*b));
return (a*b);
}
public static String convert(Integer a){
System.out.println((a));
return a.toString();
}
here is main method:
public static void main(String[] args) {
int a = 10;
int b = 5;
CompletableFuture<String> cf = new CompletableFuture<>();
cf.supplyAsync(() -> addition(a, b))
.thenApply(r ->subtract(20,r)
.thenApply(r1 ->multiply(r1, 10))
.thenApply(r2 ->convert(r2))
.thenApply(finalResult ->{
System.out.println(cf.complete(finalResult));
}));
System.out.println(cf.complete("Done"));
}
I am trying to pass result of addition to subtraction to multiplication to printing result. But I am getting compilation error. Looks like we can't do nested thenApply(). Is there any way we can do this? Searched it over google and found one helpful link- http://kennethjorgensen.com/blog/2016/introduction-to-completablefutures But didn't find much help.

A couple of things are wrong with your snippet:
Parenthesis: you have to start the next thenApply after the end of the one before, not after the substract method.
supplyAsync() is a static method. Use it as such.
If you just want to print out the result in the last operation, use thenAccept instead of thenApply
You do not need to complete the CF in thenAccept (neither you would have to do it in thenApply before.
This piece of code compiles, and it may be close to what you want to achieve:
CompletableFuture<Void> cf = CompletableFuture
.supplyAsync(() -> addition(a, b))
.thenApply(r -> subtract(20, r))
.thenApply(r1 -> multiply(r1, 10))
.thenApply(r2 -> convert(r2))
.thenAccept(finalResult -> {
System.out.println("this is the final result: " + finalResult);
});
//just to wait until the cf is completed - do not use it on your program
cf.join();

Related

Sage: Iterate over increasing sequences

I have a problem that I am unwilling to believe hasn't been solved before in Sage.
Given a pair of integers (d,n) as input, I'd like to receive a list (or set, or whatever) of all nondecreasing sequences of length d all of whose entries are no greater than n.
Similarly, I'd like another function which returns all strictly increasing sequences of length d whose entries are no greater than n.
For example, for d = 2 n=3, I'd receive the output:
[[1,2], [1,3], [2,3]]
or
[[1,1], [1,2], [1,3], [2,2], [2,3], [3,3]]
depending on whether I'm using increasing or nondecreasing.
Does anyone know of such a function?
Edit Of course, if there is such a method for nonincreasing or decreasing sequences, I can modify that to fit my purposes. Just something to iterate over sequences
I needed this algorithm too and I finally managed to write one today. I will share the code here, but I only started to learn coding last week, so it is not pretty.
Idea Input=(r,d). Step 1) Create a class "ListAndPosition" that has a list L of arrays Integer[r+1]'s, and an integer q between 0 and r. Step 2) Create a method that receives a ListAndPosition (L,q) and screens sequentially the arrays in L checking if the integer at position q is less than the one at position q+1, if so, it adds a new array at the bottom of the list with that entry ++. When done, the Method calls itself again with the new list and q-1 as input.
The code for Step 1)
import java.util.ArrayList;
public class ListAndPosition {
public static Integer r=5;
public final ArrayList<Integer[]> L;
public int q;
public ListAndPosition(ArrayList<Integer[]> L, int q) {
this.L = L;
this.q = q;
}
public ArrayList<Integer[]> getList(){
return L;
}
public int getPosition() {
return q;
}
public void decreasePosition() {
q--;
}
public void showList() {
for(int i=0;i<L.size();i++){
for(int j=0; j<r+1 ; j++){
System.out.print(""+L.get(i)[j]);
}
System.out.println("");
}
}
}
The code for Step 2)
import java.util.ArrayList;
public class NonDecreasingSeqs {
public static Integer r=5;
public static Integer d=3;
public static void main(String[] args) {
//Creating the first array
Integer[] firstArray;
firstArray = new Integer[r+1];
for(int i=0;i<r;i++){
firstArray[i] = 0;
}
firstArray[r] = d;
//Creating the starting listAndDim
ArrayList<Integer[]> L = new ArrayList<Integer[]>();
L.add(firstArray);
ListAndPosition Lq = new ListAndPosition(L,r-1);
System.out.println(""+nonDecSeqs(Lq).size());
}
public static ArrayList<Integer[]> nonDecSeqs(ListAndPosition Lq){
int iterations = r-1-Lq.getPosition();
System.out.println("How many arrays in the list after "+iterations+" iterations? "+Lq.getList().size());
System.out.print("Should we stop the iteration?");
if(0<Lq.getPosition()){
System.out.println(" No, position = "+Lq.getPosition());
for(int i=0;i<Lq.getList().size();i++){
//Showing particular array
System.out.println("Array of L #"+i+":");
for(int j=0;j<r+1;j++){
System.out.print(""+Lq.getList().get(i)[j]);
}
System.out.print("\nCan it be modified at position "+Lq.getPosition()+"?");
if(Lq.getList().get(i)[Lq.getPosition()]<Lq.getList().get(i)[Lq.getPosition()+1]){
System.out.println(" Yes, "+Lq.getList().get(i)[Lq.getPosition()]+"<"+Lq.getList().get(i)[Lq.getPosition()+1]);
{
Integer[] tempArray = new Integer[r+1];
for(int j=0;j<r+1;j++){
if(j==Lq.getPosition()){
tempArray[j] = new Integer(Lq.getList().get(i)[j])+1;
}
else{
tempArray[j] = new Integer(Lq.getList().get(i)[j]);
}
}
Lq.getList().add(tempArray);
}
System.out.println("New list");Lq.showList();
}
else{
System.out.println(" No, "+Lq.getList().get(i)[Lq.getPosition()]+"="+Lq.getList().get(i)[Lq.getPosition()+1]);
}
}
System.out.print("Old position = "+Lq.getPosition());
Lq.decreasePosition();
System.out.println(", new position = "+Lq.getPosition());
nonDecSeqs(Lq);
}
else{
System.out.println(" Yes, position = "+Lq.getPosition());
}
return Lq.getList();
}
}
Remark: I needed my sequences to start at 0 and end at d.
This is probably not a very good answer to your question. But you could, in principle, use Partitions and the max_slope=-1 argument. Messing around with filtering lists of IntegerVectors sounds equally inefficient and depressing for other reasons.
If this has a canonical name, it might be in the list of sage-combinat functionality, and there is even a base class you could perhaps use for integer lists, which is basically what you are asking about. Maybe you could actually get what you want using IntegerListsLex? Hope this proves helpful.
This question can be solved by using the class "UnorderedTuples" described here:
http://doc.sagemath.org/html/en/reference/combinat/sage/combinat/tuple.html
To return all all nondecreasing sequences with entries between 0 and n-1 of length d, you may type:
UnorderedTuples(range(n),d)
This returns the nondecreasing sequence as a list. I needed an immutable object (because the sequences would become keys of a dictionary). So I used the "tuple" method to turn the lists into tuples:
immutables = []
for s in UnorderedTuples(range(n),d):
immutables.append(tuple(s))
return immutables
And I also wrote a method which picks out only the increasing sequences:
def isIncreasing(list):
for i in range(len(list) - 1):
if list[i] >= list[i+1]:
return false
return true
The method that returns only strictly increasing sequences would look like
immutables = []
for s in UnorderedTuples(range(n),d):
if isIncreasing(s):
immutables.append(tuple(s))
return immutables

return of a local variable by ref works

Take a look at this C++ code:
#include <iostream>
using namespace std;
class B{
public:
int& f() {
int local_n = 447;
return local_n ;
} // local_n gets out of scope here
};
int main()
{
B b;
int n = b.f(); // and now n = 447
}
I don't understand why n = 447 at the end of main, because I tried to return a reference to a local_n, when it should be NULL;
Returning a reference to a local variable invokes undefined behavior - meaning you might get lucky and it might work... sometimes... or it might format your hard drive or summon nasal demons. In this case, the compiler generated code that managed to copy the old value off the stack before it got overwritten with something else. Oh, and references do not have a corresponding NULL value...
Edit - here's an example where returning a reference is a bad thing. In your example above, since you copy the value out of the reference immediately before calling anything else, it's quite possible (but far from guaranteed) that it might work most of the time. However, if you bind another reference to the returned reference, things won't look so good:
extern void call_some_other_functions();
extern void lucky();
extern void oops();
int& foo()
{ int bar = 0;
return bar;
}
main()
{ int& x = foo();
x = 5;
call_some_other_functions();
if (x == 5)
lucky();
else
oops();
}

Static Parameter Function Specialization in D

I've read somewhere that D supports specialization of functions to calls where arguments are compile-time constants. Typical use of this is in matrix power functions (if exponent is 2 x*x is often faster than the general case).
I want this in my member function
bool opIndexAssign(bool b, size_t i) #trusted pure nothrow in {
assert(i < len); // TODO: Add static assert(i < len) when i is constant
} body {
b ? bts(ptr, i) : btr(ptr, i);
return b;
}
of a statically sized BitSet struct I'm writing. This in order to, when possible, get compile-time bounds checking on the index variable i. I thought
bool opIndexAssign(bool b, const size_t i) #trusted pure nothrow in {
static assert(i < len);
} body {
b ? bts(ptr, i) : btr(ptr, i);
return b;
}
would suffice but then DMD complains as follows
dmd -debug -gc -gs -unittest -D -Dd/home/per/.emacs.d/auto-builds/dmd/Debug-Boundscheck-Unittest/home/per/Work/justd/ -w -main ~/Work/justd/bitset.d /home/per/Work/justd/assert_ex.d -of/home/per/.emacs.d/auto-builds/dmd/Debug-Boundscheck-Unittest/home/per/Work/justd/bitset
/home/per/Work/justd/bitset.d(58): Error: bitset.BitSet!2.BitSet.opIndexAssign called with argument types (bool, int) matches both:
/home/per/Work/justd/bitset.d(49): opIndexAssign(bool b, ulong i)
and:
/home/per/Work/justd/bitset.d(65): opIndexAssign(bool b, const(ulong) i)
/home/per/Work/justd/bitset.d(66): Error: variable i cannot be read at compile time
/home/per/Work/justd/bitset.d(66): while evaluating: static assert(i < 2LU)
/home/per/Work/justd/bitset.d(58): Error: bitset.BitSet!2.BitSet.opIndexAssign called with argument types (bool, int) matches both:
/home/per/Work/justd/bitset.d(49): opIndexAssign(bool b, ulong i)
Do I have to make parameter i a template parameter, say using type U, and then use static if someTypeTrait!U. I tried this but isMutable!Index always evaluates to true.
import std.traits: isIntegral;
bool opIndexAssign(Index)(bool b, Index i) #trusted pure nothrow if (isIntegral!Index) in {
import std.traits: isMutable;
// See also: http://stackoverflow.com/questions/19906516/static-parameter-function-specialization-in-d
static if (isMutable!Index) {
assert(i < len);
} else {
import std.conv: to;
static assert(i < len,
"Index " ~ to!string(i) ~ " must be smaller than BitSet length " ~ to!string(len));
}
} body {
b ? bts(ptr, i) : btr(ptr, i);
return b;
}
What you're trying to do doesn't really work. You can do a template value parameter:
void foo(int i)() { /* use i at compile time */ }
but then you can't pass a runtime value to it, and it has different call syntax: foo!2 vs foo(2).
The closest you can get is is CTFE:
int foo(int i) { return i; }
enum something = foo(2); // works, evaluated at compile time
int s = foo(2); // also works, but runs at runtime.
Inside the function, there is a magic if(__ctfe) { running at compile time } else { at runtime}, but again, this isn't if there's a literal, it is if the function is run in a CT context, e.g., assigning the result to an enum constant.
But, otherwise, an int literal is still a mutable int as far as the function is concerned. So what you're specifically trying to do won't work in D as it is right now. (There's been some talk about wanting a way to tell if it is a literal, but as far as I know, there's no plan to actually do it.)

How to use the value of a return statement in a different method?

I recently started codeing java, so this question might be a little, well, stupid, but i created a small program that averages 5 numbers. I know the program is very over complicated, i have just been trying out some of the new things i've learned.My problem is i would like to get the variable "Answer" up in my main program. I dont want to change around the program if i dont have to.I have returned the value in the average method, and set this answer to the variable Answer, but how can i use System.out.print(Answer) or print the return. Heres the code! Sorry if its not in a code block, i indented 4 spaces, but it doesnt say anything.
package Tests;
import java.util.*;
public class average_Test {
static double Total=0;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int temp;
int count[]={5,1,2,3,4};
for(int x:count){
System.out.print("Please enter 5 numbers: ");
temp=scan.nextInt();
average(temp);
}
}
public static double average(int n){
for(int c=0;c<1;c++){
Total+=n;
}
double average=Total/5;
System.out.println(average);
double Answer = Total/5;
return Total/5;
}
}
You can use variable binding, or print result of function:
double a = average(temp);
System.out.println(a);
or:
System.out.println(average(temp));
At the end it will look like this:
double result = 0;
System.out.print("Please enter 5 numbers: ");
for (int x : count) {
temp = scan.nextInt();
result = average(temp);
}
System.out.println(result);
P.S. code looks weird, consider implementing double average(int[] numbers)

runge kutta 4th order to solve system of differential equation

dT/dt=(1.344-1.025T)/h (1)
dh/dt=0.025-(3.5*10^-4)*sqrt(h) (2)
h(0)=1
T(0)=1
I have to solve this system of equations in fortran. I solved the problem in matlab but I dont know fortran programming so guys if somebody can help me or somebody have the fortran code for this help me please please please
thanks a lot
Try it with Euler integration. Do something simple first. You have one advantage: you've solved this once, so you know what the answer looks like when you get it.
Since the moderators are insisting this is a low quality answer because of the short length, I'll provide a working one in Java that should spark some thoughts for you. I used the Apache Commons math library; it has several different ODE integration schemes, including Euler and Runge Kutta.
I ran this on a Windows 7 machine using JDK 8. You can switch between Euler and Runge-Kutta using the command line:
package math.ode;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.MaxCountExceededException;
import org.apache.commons.math3.ode.FirstOrderDifferentialEquations;
import org.apache.commons.math3.ode.FirstOrderIntegrator;
import org.apache.commons.math3.ode.nonstiff.ClassicalRungeKuttaIntegrator;
import org.apache.commons.math3.ode.nonstiff.EulerIntegrator;
/**
* IntegrationExample solves coupled ODEs using Euler and Runge Kutta
* Created by Michael
* Creation date 12/20/2015.
* #link https://stackoverflow.com/questions/20065521/dependencies-for-jama-in-maven
*/
public class IntegrationExample {
public static final double DEFAULT_STEP_SIZE = 0.001;
private static final double DEFAULT_MAX_TIME = 2.0;
public static void main(String[] args) {
// Problem set up
double step = (args.length > 0) ? Double.valueOf(args[0]) : DEFAULT_STEP_SIZE;
double maxTime = (args.length > 1) ? Double.valueOf(args[1]) : DEFAULT_MAX_TIME;
String integratorName = (args.length > 2) ? args[2] : "euler";
// Choose different integration schemes here.
FirstOrderIntegrator firstOrderIntegrator = getFirstOrderIntegrator(step, integratorName);
// Equations to solve here; see class below
FirstOrderDifferentialEquations odes = new CoupledOdes();
double [] y = ((CoupledOdes) odes).getInitialConditions();
double t = 0.0;
int i = 0;
while (t <= maxTime) {
System.out.println(String.format("%5d %10.6f %10.6f %10.6f", i, t, y[0], y[1]));
firstOrderIntegrator.integrate(odes, t, y, t+step, y);
t += step;
++i;
}
}
private static FirstOrderIntegrator getFirstOrderIntegrator(double step, String integratorName) {
FirstOrderIntegrator firstOrderIntegrator;
if ("runge-kutta".equalsIgnoreCase(integratorName)) {
firstOrderIntegrator = new ClassicalRungeKuttaIntegrator(step);
} else {
firstOrderIntegrator = new EulerIntegrator(step);
}
return firstOrderIntegrator;
}
}
class CoupledOdes implements FirstOrderDifferentialEquations {
public double [] getInitialConditions() {
return new double [] { 1.0, 1.0 };
}
#Override
public int getDimension() {
return 2;
}
#Override
public void computeDerivatives(double t, double[] y, double[] yDot) throws MaxCountExceededException, DimensionMismatchException {
yDot[0] = (1.344-1.025*y[0])/y[1];
yDot[1] = 0.025-3.5e-4*Math.sqrt(y[1]);
}
}
You didn't say how far out you needed to integrate in time, so I assumed 2.0 as the max time. You can change this on the command line, too.
Here's the plot of results versus time from Excel. As you can see, the responses are smooth and well behaved. Euler has no problem with systems of equations like this.