- S / Sleep. If I turn in before midnight and manage to sleep through the night without longer periods of being awake, then I put an 'S' in my calendar.
- T / Quality Time. If I have good time or even brief moments that I value, then I record a 'T'. It can really be anything on the range from a day-long solo hike down to a passionate kiss from the woman I love.
- I / Intermittent Fasting. IF is a great routine but sometimes challenging to follow. Every time I manage to stick to my IF schedule, I record an 'I'.
- L / Learning. Every time I spend time learning something, for instance practicing a bunny hop or doing a chess lesson, I record an 'L'.
- E / Exercise. Whenever I do a workout or have any other sport activity, I record an 'E'.
Oracle SOA, Java and Software Development Reflections
Thursday, October 3, 2024
Hacking Your Life with STILE
Saturday, December 17, 2022
Final Thoughts or How I Stopped
- Things that bring me forward
- Things that bring me down
Things that bring you forward
Dreams and Goals
It's great to have dreams and goals. They are like guiding lights giving you direction and sense in what otherwise seems to be a completely frantic rat race. It's even better to write your dreams and goals down. It's a bold thing to do since chances are, you will not be able to fulfill all your goals. Writing them down makes the failure to reach a goal visible. Don't be afraid of that to happen! A person I highly respect told me recently: "DuΕ‘an, you wouldn't believe how often successful people fail". So do not take a failed goal as a loss. Take it as an opportunity - to re-evaluate your goals, to understand why it did not work out for that particular goal and most importantly - never stop dreaming.Love
Define love. I don't think I can. Love can have so many forms and so many flavors. All I can say is this: Love is another thing that gives us reason. It's love what gives you shelter when your dreams collapse and hope appears to be lost.Sex
A plethora of good things happen in your body when you have sex. It's like exercise, only better. That's one reason I put sex here on this list. The other reason is that sex is still tabooized for no good reason. Nobody but celebrities appear to be talking about sex. That needs to change.Good Habits
This is not my idea. Credits to James Clear and his Atomic Habits book. In a quintescence, a secret to sticking to a good habit is to make the habit desirable and easy to execute. In another words, remove all obstacles standing between you and your good habit. For instance, do you need to drive first to make that bike ride but your bike carrying car is always blocked by your other car? Rearrange your cars so that you can go straight away!Things that bring you down
Bad Habits
Again not my idea, still borrowing from James Clear. The secret to breaking a bad habit is, guess what - make it hard to fall into a bad habit. For example, if you want to spend less time checking your phone, just put it out of your direct reach. Know your enemy - be aware what your bad habits are and try to avoid them as much as possible.Not Challenging Yourself
Nothing is as constant as change. Responding to change is challenging. But instead of trying to avoid the challenge I think it's better to embrace it. Take the next bold step and see what happens.On that note, I am closing my blog. Wishing all my readers a wonderful and sexy year 2023 and beyond!
Tuesday, December 24, 2019
Add Dark Mode Support to Your Web Page
The good news is: there is a solution for this. Designers can style their web page based on the user's selected color scheme. Support for this has been added pretty recently so it may take some time before we'll see web pages adopting it.
Impatient as I am, I decided to give it a try immediately and I applied it to my personal navigation web page. It is for sure not the world's first color-scheme-aware web page - nor the prettiest one - but hey! It is optimized for the dark mode! π
Try it out: open my web page on your device and try switching between the light and the dark mode. Or just sit back and watch this video:
So how does this work? The key is the CSS media feature prefers-color-scheme
:
As you can see in the page source I set more colors in the actual CSS but it is that simple to make your web page aware of the user's color scheme! I expect web sites to adopt this rather sooner than later. When is your web page going to support the dark mode?
Tuesday, October 15, 2019
5 JavaScript Features That I Miss in Java
I also used to do a lot of backend server programming where Java was predominant back then. Still I was amazed at how often I'd hear my fellow technologists say things like:
- "JavaScript is a flawed language"
- "it is a language for script-kiddies"
- "there is much hype about JavaScript"
For every feature I give an example in JavaScript, and an equivalent code in Java, to my best effort. Please share in comments if you can do better. For some of the examples I used TypeScript because the JavaScript code with no types would have appeared to be shorter and more concise, and I wanted to keep the comparison as fair as possible.
I only added explanation where I felt it was necessary.
1. Template String Literals
2. Destructuring Assignment
JavaScript | Java |
---|---|
3. Spread Operator
Student
and Customer
. How can you copy all overlapping properties from the customer object to the student object?
TypeScript | Java |
---|---|
4. Default Parameters
Write a function that returns a logarithm of a given number to a given base, with the base defaulting to 10 if not provided.TypeScript | Java |
---|---|
5. JavaScript Object Initializer
JavaScript | Java |
---|---|
Conclusion
What are your favorite JavaScript features? Do you have another opinion about Java or JavaScript? Let me know in the comments below!
Saturday, July 15, 2017
Learning Functional Style in Java by Example
Learn Java Functional Style in Style
There's plenty of articles on the functional features in Java 8 around the net. In this blog post I offer you a different learning path: by example.I'll show you a problem and solve it step by step using the Java 8 functional features naturally. I'll point out the interesting aspects of the solution so that you have some anchor points for your further research. That's learning Java functional style programming in style!
The Problem
So here's the problem to solve: calculate the number π to a precision of 20 decimal digits. I'll do the coding work so that you can focus on another things: understanding how the solution works and figuring out for yourself if you embrace this style in your daily Java coding.Nilakantha Sequence
First we need a method how to calculate π. For the sake of simplicity I've chosen to use the Nilakantha sequence, the Indian mathematician's discovery dating back to the 15th century:First Bite: Infinite Alternating Sequence
You're probably familiar with the notorious advice:"How do you eat an elephant? One bite at a time."Our first bite when eating the elephant (umm I mean producing the Nilakantha sequence) will be creating a Stream of BigDecimal's containing elements of this alternating sequence:
2, -4, 6, -8, 10, -12, 14, -16, ...This turns out to be a bit more difficult than it seems, since the sequence generation needs to address two aspects of the above sequence:
- the iteration through all even numbers
- the alternation of the sign of the elements
Note that the above code very neatly separates all concerns of the sequence generation:
- on line 2 an infinite stream of positive members of the sequence is generated using Stream#iterate
- on line 3 a negative counterpart for each positive member of the sequence is added using Stream#of and Stream#flatMap
- on line 4 the stream of integers is converted to a stream of BigDecimal's using Stream#map (we need BigDecimal's because otherwise the double arithmetics would fail to provide the fractional elements of the sequence with the necessary precision)
Let's visualize this scenario using the following alternative way to produce the root sequence:
The comments on the right hand side show what the stream looks like after each intermediate step. The flatMap invocation takes an identity function as parameter, which effectively means that the flatMap call only flattens the stream - the resulting stream contains the same numbers but in a flat structure.
Key Takeaways
- Infinite streams can be created with iterate
- map vs flatMap:
- Use map to replace each element with some other element
- Use flatMap to replace each element with an arbitrary number of other elements
- When using map the number of elements in the stream will never change. With flatMap the resulting stream can have different number of elements than the original stream.
Second Bite: Infinite Nilakantha Sequence
Our second bite will be creating all fractional elements of the Nilakantha sequence:This can be solved by transforming the elements using the map method we already encountered in the previous bite:
This code replaces each of the root sequence elements (2, -4, 6, ...) with the corresponding fraction - which is specified in the lambda expression passed to the map method. The fraction expression also contains the specification of the rounding mode (without it a runtime exception occurs since the JVM cannot calculate the fraction precisely).
Third Bite: Calculating the Sum
The third bite is the calculation of the sum of the Nilakantha sequence elements. But hey, the sequence is infinite so how are we going to calculate the sum after all? Of course, the more elements we take for the calculation, the closer we get to the exact value of π. So the question actually is - how many elements do we need to take to get the number π with the precision of 20 digits? The answer lies within the code:Let's have a look at the new stuff here:
- on line 3 the infinite stream is turned into a finite one by telling the stream to stop generating more elements after 6,578,000 elements have been generated
- in case you wonder how the limit call affects the sequence generation, which occurs as the first method in the code, the answer is laziness: Java 8 streams are lazy so no operations are actually triggered before a terminal operation is applied on the stream. Limit itself is not a terminal operation but the very next operation on the stream - reduce - is a terminal one, and when it runs, the stream is already marked to contain a limited number of elements.
- on line 4 the sum of all elements in the sequence is calculated by starting with 3 and then adding each elements of the sequence
- on line 5 the required precision is set
Key Takeaways
- Infinite streams can be truncated to contain a finite number of elements with Stream#limit.
- Streams are lazy:
- any intermediate operation is only performed when a terminal operation is initiated
- stream elements are generated only when they are needed
- Combine all elements in the stream with a specified binary operation to produce a single result using Stream#reduce.
The Dessert: Parallelizing the Calculation
We did manage to eat the elephant in three bites, but I've got a bonus - since there's no piece of elephant left I'll call it a dessert: let's make the calculation more efficient by employing parallelism. It is very straightforward to make a Java 8 stream process in parallel - you only need to invoke parallel on the stream.I chose to make the stream parallel after the initialization, before the fractions and their sum are calculated - see line 3 in the following Gist:
Unfortunately this first try does not yield the expected result - the test is now broken!
~/ws/java-8-way $ mvn -Dtest=LifeOfPiTest testWTF? (note: this is not bad language but a valid measurement of code quality) The fractional part is correct but the part before the decimal point is wrong. To solve this little mystery we have to reiterate how the elements of the sequence are added: with reduce(THREE, BigDecimal::add). So here is what happens: since the computation is now parallel, the reduce operation is also done on multiple threads and hence the initial value, THREE, is added way too many times. On your computer, you may get a different result before the decimal point, but it is guaranteed to be a multiple of three!
...
Failed tests:
LifeOfPiTest.calculate:33 expected:<[3].1415926535897932384...> but was:<[249].1415926535897932384...>
Once the problem is identified it is easy to fix:
The above code adds three as the final step - all reduce operations add the sequence elements starting with the initial sum of zero. Now the test is fixed but unfortunately the execution times don't seem to be much different between the sequential (first line) and the parallel (second line) version:
Time elapsed: 4.98 sec - in de.blogspot...LifeOfPiTestThe reason why parallelism gave us no gain (yet) is that the stream is ordered - which defies any benefits that the parallel processing might yield. Since the sum of the sequence elements does not depend on their order, we can specify that the stream should be unordered declaratively:
Time elapsed: 5.064 sec - in de.blogspot...LifeOfPiTest
With this modification, finally, we get some benefit from parallelism:
Time elapsed: 2.559 sec - in de.blogspot...LifeOfPiTest
Key Takeaways
- Parallel streams can be tricky - so make sure you understand what you're doing. If you don't need to optimize then don't bother to introduce parallelism.
- Using unordered streams may significantly improve parallel processing performance, but you can only use them if the semantics of your problem does not depend on the ordering.
- Not every problem is embarrassingly parallel. The virtual machine I ran this example in has four CPU cores yet the parallel version runs barely twice as fast as the sequential version.
Conclusion
I hope you enjoyed learning Java 8 features on the example of π calculation. If you did enjoy the math I can assure you that you are in a good company: also Isaac Newton used infinite series to compute π to 15 digits, later writing "I am ashamed to tell you to how many figures I carried these computations".Don't be ashamed yourself to carry some more computations! Feel free to further experiment with the code: LifeOfPi.java
Of course, you can download, clone or fork the entire project from GitHub. Have fun!
Wednesday, February 24, 2016
Funtastic Birthday with Haskell
I was curious though as to what is the next number that satisfies the above condition. So I decided to write a program in Haskell - my favorite functional language - to generate the sequence:
I won't dissect it too much - after all I promised this would be fun - so let me just point out one little fact about Haskell that I always find fascinating: it lets you define and use infinite sequences like the birthday numbers above. In fact, if you try to evaluate this sequence your machine will start producing the numbers but it would never stop - that is if it had unlimited amount of memory.
The beautiful trick is that once you have an infinite sequence, you can extract portions of it to get answers to finite questions, like my tiny age puzzle - which can be answered by taking the first element of the sequence:
*Fun> takeWhile (<=122) birthdayNumbersAs you can see, the answer is 'very optimistic' :-)
[44,110]
If you just simply want to see the first 10 numbers of the sequence you can do:
*Fun> take 10 birthdayNumbersYou may also be wondering, why not make the program even shorter by dropping the isqrt function and instead checking the divisors up to k-1? The reason is obvious: performance. I leave it to the inquiring reader to see the difference for themselves. This is how you can turn on the built-in profiling in the Haskell interpreter and calculate the gap between the consecutive birthday numbers:
[44,110,132,198,242,264,308,374,440,462]
*Fun> :set +sOne final thought: there are actually two ways to solve the puzzle I've given to the curious inquirers:
*Fun> take 10 (zipWith (-) (tail birthdayNumbers) birthdayNumbers)
[66,22,66,44,22,44,66,66,22,110]
(0.02 secs, 3042172 bytes)
- exact: verify the predecessor primality for all multiples of 11 until you find the solution
- heuristic: since I was giving the puzzle in a face-to-face talk it was much easier to estimate my age then compare it with the nearest multiples of 11 and rule out 33 and 55 as being too low / too high respectively.
Sunday, February 8, 2015
Color Bash Prompt for Git on Linux/Mac
- the current working directory
- the name of the git branch (if the current directory is a git working copy)
- whether or not there are uncommitted changes
The above prompt is produced with this one-liner:
Prompt Contents
Let's first dissect the parts of the prompt that define what it actually shows:- \w - this is the bash shortcut for current working directory. Simple.
- $(git status -s 2>/dev/null | head -1 | sed 's/.*/ */') - this will print an asterisk if the current working directory is a git working copy and if it has uncommitted changes (this can be also achiewed with __git_ps1 and
GIT_PS1_SHOWDIRTYSTATE but I prefer to highlight the asterisk with different color) - $(git rev-parse --abbrev-ref HEAD 2>/dev/null | sed 's/.*/ &/') - this will print the branch name with a space in front of it
Prompt Colors
The prompt uses ANSI escape sequences to change the colors. I decided to use tput to generate the sequence instead of putting it in directly. It is simply more readable with explicit capability names. Here setaf sets the foreground color and sgr0 resets all attributes. You can check the man page terminfo(5) if you need for more details.Finally, it is necessary to mark the ANSI escape sequences as non-printable in order for bash to correctly figure out the actual length of the prompt. This is done by adding \[ and \] around the control characters.