Groovy: Multi threaded producer consumer program

import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue

BlockingQueue queue = new LinkedBlockingQueue();

Thread.start('Producer') {
    10.times {
        println(Thread.currentThread().name + " adding $it")
        queue << it
        sleep(100)
    }
}

Thread.start('Consumer') {
    for(i in 0..9){
        sleep(200)
        print(Thread.currentThread().name)
        println("consuming ${queue.take()}")
    }
}
Advertisements

Groovy: Closure Composition

Closure composition corresponds to the concept of function composition, that is to say creating a new function by composing two or more functions (chaining calls), as illustrated in this example:

def plus2  = { it + 2 }
def times3 = { it * 3 }

def times3plus2 = plus2 << times3
assert times3plus2(3) == 11
assert times3plus2(4) == plus2(times3(4))

def plus2times3 = times3 << plus2
assert plus2times3(3) == 15
assert plus2times3(5) == times3(plus2(5))

// reverse composition
assert times3plus2(3) == (times3 >> plus2)(3)

 

SDK MAN – Software Development Kit Manager

I use sdk man to maintain multiple versions of Groovy, Java, Scala. It makes switching very easy.

SDKMAN! is a tool for managing parallel versions of multiple Software Development Kits on most Unix based systems. It provides a convenient Command Line Interface (CLI) and API for installing, switching, removing and listing Candidates. Formerly known as GVM the Groovy enVironment Manager, it was inspired by the very useful RVM and rbenv tools, used at large by the Ruby community.

Installing SDKMAN! on UNIX-like platforms is as easy as ever. SDKMAN! installs smoothly on Mac OSX, Linux, Cygwin, Solaris and FreeBSD. We also support Bash and ZSH shells.
Simply open a new terminal and enter:

$ curl -s "https://get.sdkman.io" | bash

Follow the instructions on-screen to complete installation.
Next, open a new terminal or enter:

$ source "$HOME/.sdkman/bin/sdkman-init.sh"

Lastly, run the following code snippet to ensure that installation succeeded:

$ sdk version

If all went well, the version should be displayed. Something like:

  sdkman 5.0.0+51

Cron : Repeat execution at regular interval

 

crontab -e

will open up all cron list in edit mode, you need provide time interval for the job to repeat.

0 0 * * * yourcommand >/tmp/stdout.log 2>/tmp/stderr.log

By default logs are not captured, you can check logs on this file – /tmp/stdout.log 2 in you specifically redirect the logs.

To see a list of your active crontab jobs, use the following command:

crontab -l

The following graph shows what it consists of:

* * * * * *
| | | | | | 
| | | | | +-- Year              (range: 1900-3000)
| | | | +---- Day of the Week   (range: 1-7, 1 standing for Monday)
| | | +------ Month of the Year (range: 1-12)
| | +-------- Day of the Month  (range: 1-31)
| +---------- Hour              (range: 0-23)
+------------ Minute            (range: 0-59)

 

This site will help you to get cron expression for interval you are looking for

https://crontab.guru/

Nonstandard predefined scheduling definitions

Some cron implementations support the following non-standard macros:

Entry Description Equivalent to
@yearly (or @annually) Run once a year at midnight of 1 January 0 0 1 1 *
@monthly Run once a month at midnight of the first day of the month 0 0 1 * *
@weekly Run once a week at midnight on Sunday morning 0 0 * * 0
@daily Run once a day at midnight 0 0 * * *
@hourly Run once an hour at the beginning of the hour 0 * * * *
@reboot Run at startup N/A

@reboot configures a job to run once when the daemon is started. Since cron is typically never restarted, this typically corresponds to the machine being booted. This behavior is enforced in some variations of cron, such as that provided in so that simply restarting the daemon does not re-run @reboot jobs.

 

Python: Suppressing Exceptions

# In Python 3.4+ you can use
# contextlib.suppress() to selectively
# ignore specific exceptions:

import contextlib
import os
with contextlib.suppress(FileNotFoundError):
    os.remove('somefile.tmp')

# This is equivalent to:

try:
    os.remove('somefile.tmp')
except FileNotFoundError:
    pass

# contextlib.suppress docstring: 
#
# "Return a context manager that suppresses any 
#  of the specified exceptions if they occur in the body
#  of a with statement and then resumes execution with 
#  the first statement following the end of 
#  the with statement."

Scala: Traits

A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Unlike class inheritance, in which each class must inherit from just one superclass, a class can mix in any number of traits.

Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters.

A trait definition looks just like a class definition except that it uses the keyword trait. The following is the basic example syntax of trait.

Syntax

trait Equal {
   def isEqual(x: Any): Boolean
   def isNotEqual(x: Any): Boolean = !isEqual(x)
}

This trait consists of two methods isEqual and isNotEqual. Here, we have not given any implementation for isEqual where as another method has its implementation. Child classes extending a trait can give implementation for the un-implemented methods. So a trait is very similar to what we have abstract classes in Java.

Scala : Closure program

closure is a function, whose return value depends on the value of one or more variables declared outside this function.

The following piece of code with anonymous function.

val multiplier = (i:Int) => i * 10

Here the only variable used in the function body, i * 10 , is i, which is defined as a parameter to the function. Try the following code −

val multiplier = (i:Int) => i * factor

There are two free variables in multiplier: i and factor. One of them, i, is a formal parameter to the function. Hence, it is bound to a new value each time multiplier is called. However, factor is not a formal parameter, then what is this? Let us add one more line of code.

var factor = 3
val multiplier = (i:Int) => i * factor

Now factor has a reference to a variable outside the function but in the enclosing scope. The function references factor and reads its current value each time. If a function has no external references, then it is trivially closed over itself. No external context is required.

Try the following example program.

Example

object Closure {
   def main(args: Array[String]) {
      println( "multiplier(1) value = " +  multiplier(1) )
      println( "multiplier(2) value = " +  multiplier(2) )
   }
   var factor = 3
   val multiplier = (i:Int) => i * factor
}