I playing around with Reactor's flux api. I'm already familiar with RxJava so I wanted to test Reactor's Flux.
I don't understand why I always receives 0's in the following code:
Flux.create(e -> {
long current = 1;
while (!e.isCancelled()) {
e.next(current);
current *= 2;
}
})
.subscribe(l -> System.out.println("Got " + l + " on " + Thread.currentThread().getName()), e -> System.out.println(e.getMessage() + "!!!!"), () -> System.out.println("finished"));
When I ran the code I get infinite lines showing
"Got 0 on main"
You have got Long overflow. Change your while block to
while (!e.isCancelled()) {
if (current < 0) {
e.complete();
} else {
e.next(current);
current *= 2;
}
}
Related
We have a HashMap Integer/String and in Java we would iterate over the HashMap and display 3 key value pairs at a time with the click of a button. Java Code Below
hm.put(1, "1");
hm.put(2, "Dwight");
hm.put(3, "Lakeside");
hm.put(4, "2");
hm.put(5, "Billy");
hm.put(6, "Georgia");
hm.put(7, "3");
hm.put(8, "Sam");
hm.put(9, "Canton");
hm.put(10, "4");
hm.put(11, "Linda");
hm.put(12, "North Canton");
hm.put(13, "5");
hm.put(14, "Lisa");
hm.put(15, "Phoenix");
onNEXT(null);
public void onNEXT(View view){
etCity.setText("");
etName.setText("");
etID.setText("");
X = X + 3;
for(int L = 1; L <= X; L++ ){
String id = hm.get(L);
String name = hm.get(L = L + 1);
String city = hm.get(L = L + 1);
etID.setText(id);
etName.setText(name);
etCity.setText(city);
}
if(X == hm.size()){
X = 0;
}
}
We decoded to let Android Studio convert the above Java Code to Kotlin
The converter decide to change the for(int L = 1; L <= X; L++) loop to a while loop which seemed OK at first then we realized the while loop was running for 3 loops with each button click. Also Kotlin complained a lot about these line of code String name = hm.get(L = L + 1); String city = hm.get(L = L + 1);
We will post the Kotlin Code below and ask the question
fun onNEXT(view: View?) {
etCity.setText("")
etName.setText("")
etID.setText("")
X = X + 3
var L = 0
while (L <= X) {
val id = hm[L - 2]
val name = hm.get(L - 1)
val city = hm.get(L)
etID.setText(id)
etName.setText(name)
etCity.setText(city)
L++
}
if (X == hm.size) {
X = 0
}
}
We tried to write a For Next Loop like this for (L in 15 downTo 0 step 1)
it seems you can not count upTo so we thought we would use the hm:size for the value 15 and just use downTo
So the questions are
How do we use the Kotlin For Next Loop syntax and include the hm:size in the construct?
We have L declared as a integer but Kotlin will not let us use
L = L + 1 in the While loop nor the For Next Loop WHY ?
HERE is the strange part notice we can increment X by using X = X + 3
YES X was declared above as internal var X = 0 as was L the same way
Okay, I'll bite.
The following code will print your triples:
val hm = HashMap<Int, String>()
hm[1] = "1"
hm[2] = "Dwight"
hm[3] = "Lakeside"
hm[4] = "2"
hm[5] = "Billy"
hm[6] = "Georgia"
hm[7] = "3"
hm[8] = "Sam"
hm[9] = "Canton"
hm[10] = "4"
hm[11] = "Linda"
hm[12] = "North Canton"
hm[13] = "5"
hm[14] = "Lisa"
hm[15] = "Phoenix"
for (i in 1..hm.size step 3) {
println(Triple(hm[i], hm[i + 1], hm[i + 2]))
}
Now let's convert the same idea into a function:
var count = 0
fun nextTriplet(hm: HashMap<Int, String>): Triple<String?, String?, String?> {
val result = mutableListOf<String?>()
for (i in 1..3) {
result += hm[(count++ % hm.size) + 1]
}
return Triple(result[0], result[1], result[2])
}
We used a far from elegant set of code to accomplish an answer to the question.
We used a CharArray since Grendel seemed OK with that concept of and Array
internal var YY = 0
val CharArray = arrayOf(1, "Dwight", "Lakeside",2,"Billy","Georgia",3,"Sam","Canton")
In the onCreate method we loaded the first set of data with a call to onCO(null)
Here is the working code to iterate over the CharArray that was used
fun onCO(view: View?){
etCity.setText("")
etName.setText("")
etID.setText("")
if(CharArray.size > YY){
val id = CharArray[YY]
val name = CharArray[YY + 1]
val city = CharArray[YY + 2]
etID.setText(id.toString())
etName.setText(name.toString())
etCity.setText(city.toString())
YY = YY + 3
}else{
YY = 0
val id = CharArray[YY]
val name = CharArray[YY + 1]
val city = CharArray[YY + 2]
etID.setText(id.toString())
etName.setText(name.toString())
etCity.setText(city.toString())
YY = YY + 3
}
Simple but not elegant. Seems the code is a better example of a counter than iteration.
Controlling the For Next Look may involve less lines of code. Control of the look seemed like the wrong direction. We might try to use the KEY WORD "when" to apply logic to this question busy at the moment
After some further research here is a partial answer to our question
This code only show how to traverse a hash map indexing this traverse every 3 records needs to be added to make the code complete. This answer is for anyone who stumbles upon the question. The code and a link to the resource is provide below
fun main(args: Array<String>) {
val map = hashMapOf<String, Int>()
map.put("one", 1)
map.put("two", 2)
for ((key, value) in map) {
println("key = $key, value = $value")
}
}
The link will let you try Kotlin code examples in your browser
LINK
We only did moderate research before asking this question. Our Appoligies. If anyone is starting anew with Kotlin this second link may be of greater value. We seldom find understandable answers in the Android Developers pages. The Kotlin and Android pages are beginner friendlier and not as technical in scope. Enjoy the link
Kotlin and Android
I have a for loop in Obj-C that looks similar to this:
for (int i = r1o.index - 1; i < r1o.index -1 + (32*r1h); i+=32) {
// code goes here
}
I am busy converting my code to Swift 3 and I am not sure how to represent the above loop in Swift 3. if the auto increment were i++ (instead of i += 32) I could do the following:
for i in r1o.index - 1 ..< r1o.index -1 + (32*r1h) {
// code goes here
}
But it is how to handle the i += 32 that is throwing me. Do I need to convert this to a while loop like the following or is there a Swift 3 for loop that can handle this.
var i = r1o.index - 1
while i < r1o.index -1 + (32*r1h) {
// code goes here
i += 32
}
In Swift 3 you can use stride(from:to:by:) for that.
for i in stride(from: r1o.index - 1, to: (r1o.index -1 + (32*r1h)), by: 32){
print(i)
//your code
}
Is it possible to change some fundamental codes inside UnityEngine?
For example, I want to know if I can change how acceleration behaves in reaction to the force the object is applied with
-> changing from F = m*a to F = m*a^2.
I tried doing this way:
void Update () {
if (enableKinematic == true) {
accelerationVector = forceVector / mass;
velocityVector += accelerationVector * Time.deltaTime;
positionVector += velocityVector * Time.deltaTime;
// Debug.Log ("a:" + accelerationVector + " v:" + velocityVector + " d:" + positionVector);
// Apply position
transform.position += positionVector;
}
}
But I realized that collision detection gets pretty complicated this way.
I'm trying to move learn Swift 2 coming from a background of Python. Started making a really simple function that counts the G's and C's. I'm getting Use of unresolved identifier 'SEQ' on the line var length: Float = Float(SEQ.characters.count)
What am I doing wrong? It's definitely defined in the beginning of the function?
Tried the following posts:
Swift Use of unresolved identifier 'UIApplicationStateInactive'
Swift - Use of unresolved identifier
func GC(input_seq: String) -> Float {
let SEQ = input_seq.uppercaseString
var counter = 0.0
for nt in SEQ.characters {
if (nt == "G") {
var counter = counter + 1
}
if (nt == "C") {
var counter = counter + 1
}
}
}
var length: Float = Float(SEQ.characters.count)
return counter/length
}
let query_seq = "ATGGGGCTTTTGA"
GC(query_seq)
Couple of things you do wrong.
You are creating a Double counter (not a Float as you probably intended): var counter = 0.0
You really need it as an integer since it's a counter. You can convert it to a Float later. var counter = 0 will create an Int variable
you are creating a second and a third local variables in the if blocks:
if (nt == "G") {
var counter = counter + 1
}
I don't think you understand the basics and might be beneficial for you to start reading the Swift book from the beginning.
This is really an improvement - you can use a shorthands:
counter = counter + 1 to counter += 1 or even counter++
Here is a working version of your code:
func GC(input_seq: String) -> Float {
let SEQ = input_seq.uppercaseString
var counter = 0
for nt in SEQ.characters {
if (nt == "G") {
counter++
}
if (nt == "C") {
counter++
}
}
return Float(counter)/Float(SEQ.characters.count)
}
let query_seq = "ATGGGGCTTTTGA"
GC(query_seq)
Hope this helps.
In Java8, processing pairs of items in two parallel streams as below:
final List<Item> items = getItemList();
final int l = items.size();
List<String> results = Collections.synchronizedList(new ArrayList<String>());
IntStream.range(0, l - 1).parallel().forEach(
i -> {
Item item1 = items.get(i);
int x1 = item1.x;
IntStream.range(i + 1, l).parallel()
.forEach(j -> {
Item item2 = items.get(j);
int x2 = item2.x;
if (x1 + x2 < 200) return;
// code that writes to ConcurrentHashMap defined near results
if (x1 + x2 > 500) results.add(i + " " + j);
});
}
);
Each stream pair writes to ConcurrentHashMap, and depending on certain conditions it may terminate the stream execution by calling return; or it may write to a synchronized list.
I want to make streams return the results like return i + " " + j and collect those results into a list strings outside. It should be partial as returning nothing must be supported (in case when x1 + x2 < 200).
What would be the most time-efficient (fastest code) way to achieve that?
In this answer, I will not address the time efficiency, because there are correctness problems that should be handled beforehand.
As I said in the comments, it is not possible to stop the stream execution after a certain condition if we parallelize the stream. Otherwise, there might be some pairs (i,j) that are already being executed that are numerically after a pair that triggered the stop condition x1 + x2 < 200.
Another issue is the return; inside the lambda, all it will do is skip the second if for the j for which x1 + x2 < 200 holds, but the stream will continue with j+1.
There is no straightforward way to stop a stream in Java, but we can achieve that with allMatch, as we can expect that as soon as it finds a false value, it will short-circuit and return false right way.
So, this would be a correct version of your code:
IntStream.range(0, l - 1).allMatch(i -> {
int x1 = items.get(i).x;
return IntStream.range(i + 1, l).allMatch(j -> {
int x2 = items.get(j).x;
if (x1 + x2 < 200) {
return false;
} else {
if (x1 + x2 > 500) results2.add(i + " " + j);
return true;
}
});
});
For the following example, with the constructor Item(int x, int y):
final List<Item> items = Arrays.asList(
new Item(200, 0),
new Item(100, 0),
new Item(500, 0),
new Item(400, 0),
new Item(1, 0));
The contents of results in my version is:
[0 2, 0 3, 1 2]
With your code (order and elements vary in each execution):
[2 4, 2 3, 1 2, 0 3, 0 2]
I think this will be more efficient (haven't done any micro benchmarking though):
IntStream.range(0,l-1).forEach(
i -> IntStream.range(i+1,l)
.filter(j -> items.get(i).x + items.get(j).x > 500)
.forEach(j -> results.add(i + " " + j)));
However, if I was really worried about the time taken to do this, I'd pay more attention to what kind of a List implementation is used for items. Perhaps even convert the list to a HashMap<Integer, Item> before getting into the lambda. For example, if items is a LinkedList, any improvement to the lambda may be inconsequential because items.get() will eat up all the time.